Esempio n. 1
0
def purchase_bank(address, amount):
    byte_address = Base58ToAddress(address)
    if len(byte_address) != 20:
        Notify(['Invalid address'])
        return False

    else:
        # check if user has been created. if not, create the user
        user_info = Get(ctx, USERKEY)
        all_users = Deserialize(user_info)

        if address not in all_users:
            create_user(address)

        # if the user has been created, that means the bank map exists. update the user's bank and wallet
        else:
            bank_info = Get(ctx, BANKEY)
            bank_map = Deserialize(bank_info)
            bank_map[address] += amount
            bank_info = Serialize(bank_map)
            Put(ctx, BANKEY, bank_info)

            add_bank(address, amount)

        return True
Esempio n. 2
0
def bindAssetHash(fromAssetHash, toChainId, toAssetHash):
    assert (CheckWitness(Get(GetContext(), OPERATOR_PREFIX)))
    assert (_addFromAssetHash(fromAssetHash))
    Put(GetContext(), concat(ASSET_HASH, concat(fromAssetHash, toChainId)), toAssetHash)
    curBalance = getBalanceFor(fromAssetHash)
    Notify(["bindAssetHash", fromAssetHash, toChainId, toAssetHash, curBalance])
    return True
def approve(owner, spender, tokenId, amount):
    """
    approve amount of the tokenId token to toAcct address, it can overwrite older approved amount
    :param owner:
    :param spender:
    :param tokenId:
    :param amount:
    :return:
    """
    res = int(owner)
    RequireWitness(owner)
    RequireScriptHash(owner)
    RequireScriptHash(spender)
    Require(checkTokenId(tokenId))

    ownerBalance = balanceOf(owner, tokenId)
    # you can use "if" to notify the corresponding message, or use Require to raise exception
    Require(ownerBalance >= amount)
    Require(amount > 0)
    key = concatkey(concatkey(concatkey(tokenId, APPROVE), owner), spender)
    Put(GetContext(), key, amount)

    ApprovalEvent(owner, spender, tokenId, amount)

    return True
Esempio n. 4
0
def fulfill(requestId, price):
    assert (ChainlinkClientCall(
        'recordChainlinkFulfillment',
        [bytearray_reverse(GetCallingScriptHash()), requestId]))
    # Notify(['test'])
    Put(GetContext(), CURRENT_PRICE, price)
    return True
Esempio n. 5
0
def transferOwnership(newOwner):
    oldOwner = getOwner()
    assert (CheckWitness(oldOwner))
    assert (len(newOwner) == 20 and newOwner != ZERO_ADDRESS)
    Put(GetContext(), OWNER_KEY, newOwner)
    TransferOwnershipEvent(oldOwner, newOwner)
    return True
Esempio n. 6
0
def unbind(ont_id, bucket):
    """
    unbind ont id with address
    :param ont_id:
    :param bucket: bucket id or url
    :return:
    """

    assert CheckWitness(ADMIN)

    bound_bucket = Get(ctx, concat(KEY_ONT, ont_id))
    if not bound_bucket:
        raise Exception("ont id bind with nothing")

    assert bound_bucket == bucket

    bind_data = Get(ctx, concat(KEY_BUCKET, bucket))
    bind_map = Deserialize(bind_data)
    bind_map.remove(ont_id)

    Put(ctx, concat(KEY_BUCKET, bucket), Serialize(bind_map))
    Delete(ctx, concat(KEY_ONT, ont_id))

    Notify(["unbind", ont_id, bucket])

    return True
def TestStorage():
    Put(ctx, "key", 100)
    v = Get(ctx, "key")
    Notify(v)

    Delete(ctx, "key")
    Notify(Get(ctx, "key"))
def approve(owner, spender, tokenId, amount):
    """
    approve amount of the tokenId token to toAcct address, it can overwrite older approved amount
    :param owner:
    :param spender:
    :param tokenId:
    :param amount:
    :return:
    """
    assert (_whenNotPaused())
    # make sure the invoker is the owner address
    assert (CheckWitness(owner))
    # make sure the address is legal
    assert (len(spender) == 20)
    assert (_tokenExist(tokenId))

    ownerBalance = balanceOf(owner, tokenId)
    # you can use "if" to notify the corresponding message, or use assert to raise exception
    assert (ownerBalance >= amount)
    assert (amount > 0)
    key = _concatkey(_concatkey(_concatkey(APPROVE_PREFIX, tokenId), owner),
                     spender)
    Put(GetContext(), key, amount)

    ApprovalEvent(owner, spender, tokenId, amount)

    return True
Esempio n. 9
0
def purchase_bank(address, amount):
    byte_address = Base58ToAddress(address)
    assert (CheckWitness(byte_address))

    if len(byte_address) != 20:
        Notify(['Invalid address'])
        return False

    else:
        # check if user has been created. if not, create the user
        user_info = Get(ctx, USERKEY)
        if user_info:
            all_users = Deserialize(user_info)
        else:
            Notify(['No existing users'])
            create_user(address)

        if address not in all_users:
            Notify(['not a registered user'])
            create_user(address)

        # if the user has been created, that means the bank map exists. update the user's bank and wallet
        else:
            bank_info = Get(ctx, BANKEY)
            bank_map = Deserialize(bank_info)
            bank_map[address] += amount
            bank_info = Serialize(bank_map)
            Put(ctx, BANKEY, bank_info)
            Notify(['bank_map updated'])

            add_bank(address, amount)
            Notify(['user wallet updated'])

        return True
Esempio n. 10
0
def add_bank(address, amount):
    byte_address = Base58ToAddress(address)
    if len(byte_address) != 20:
        Notify(['Invalid address'])
        return False

    if token_supply() < amount:
        Notify(['Not enough tokens'])
        return False

    else:
        from_acct = contract_address
        to_acct = byte_address

        supply = Get(ctx, SUPPKEY)
        if supply < amount:
            Notify(['Not enough tokens in supply'])
            return False
        else:
            supply -= amount
            Put(ctx, SUPPKEY, supply)
            Notify(['Supply decreased by', amount])

            params = [from_acct, to_acct, amount]
            return RepContract('transfer', params)
Esempio n. 11
0
def transferFrom(spender, from_acct, to_acct, amount):
    """
    spender spends amount of tokens on the behalf of from_acct, spender makes a transaction of amount of tokens
    from from_acct to to_acct
    :param spender:
    :param from_acct:
    :param to_acct:
    :param amount:
    :return:
    """
    require(
        len(spender) == 20 and len(from_acct) == 20 and len(to_acct) == 20,
        "address length error")
    require(CheckWitness(spender) == True, "Invalid invoker")

    whenNotPaused()
    requireNotFreeze(spender)
    requireNotFreeze(from_acct)
    requireNotFreeze(to_acct)

    autoUnlock(from_acct)

    fromKey = concat(BALANCE_PREFIX, from_acct)
    fromBalance = Get(ctx, fromKey)
    require(amount <= fromBalance and amount > 0, "Invalid amount")

    approveKey = concat(concat(APPROVE_PREFIX, from_acct), spender)
    approvedAmount = Get(ctx, approveKey)
    toKey = concat(BALANCE_PREFIX, to_acct)

    require(amount <= approvedAmount, "Invalid amount")

    if amount == approvedAmount:
        Delete(ctx, approveKey)
        Put(ctx, fromKey, fromBalance - amount)
    else:
        Put(ctx, approveKey, approvedAmount - amount)
        Put(ctx, fromKey, fromBalance - amount)

    toBalance = Get(ctx, toKey)
    Put(ctx, toKey, toBalance + amount)

    # Notify(["transfer", AddressToBase58(from_acct), AddressToBase58(to_acct), amount])
    # TransferEvent(AddressToBase58(from_acct), AddressToBase58(to_acct), amount)
    TransferEvent(from_acct, to_acct, amount)

    return True
Esempio n. 12
0
def createProperty(Account, createList):
    """
    only contract owner or admin can create property
    cannot create more than 1000 property once
    :param createList: [Account, [[account1, DNA1],[account2, DNA2]]]
    :return: bool
    """
    Require(Get(context, concatKey(ADMIN_ADDRESS_KEY, Account)) == 1)
    RequireWitness(Account)
    DNAlist = Get(context, concatKey(PLAYER_ADDRESS_PRE_KEY, createList[0][0]))
    if not DNAlist:
        DNAlist = []
    else:
        DNAlist = Deserialize(DNAlist)
    Require(len(createList) <= 1000)
    for createE in createList:
        account = createE[0]
        DNA = createE[1]
        accountCheck = Get(context, concatKey(DNA_PRE_KEY, DNA))

        Require(len(account) == 20)
        # check len
        Require(DNA >= 100000000000000)
        Require(DNA < 10000000000000000)
        # check kind
        Require(Div(DNA, 100000000000000) % 100 > 0)
        Require(Div(DNA, 100000000000000) % 100 < 100)
        # check grade
        Require(Div(DNA, 1000000000000) % 100 > 0)
        Require(Div(DNA, 1000000000000) % 100 < 100)
        # check name
        Require(Div(DNA, 1000000000) % 1000 > 0)
        Require(Div(DNA, 1000000000) % 1000 < 1000)
        # check number
        Require(Div(DNA, 1000) % 1000000 > 0)
        Require(Div(DNA, 1000) % 1000000 < 1000000)
        # check random
        Require(DNA % 1000 >= 0)
        Require(DNA % 1000 < 1000)
        # check DNA
        Require(not accountCheck)

        DNAlist.append(DNA)
        Put(context, concatKey(DNA_PRE_KEY, DNA), account)
        Put(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account), Serialize(DNAlist))
    Notify(["Create property successfully."])
    return True
Esempio n. 13
0
def fulfill(requestId, price):
    chainlinkClient = Get(GetContext(), CHAINLINK_CLIENT)
    assert (DynamicCallFunction(
        bytearray_reverse(chainlinkClient), 'recordChainlinkFulfillment',
        [bytearray_reverse(GetCallingScriptHash()), requestId]))

    Put(GetContext(), CURRENT_PRICE, price)
    return True
def burn(amount):
    """
    Burns the amount of Minglechain token from the owner's address.
    :param _amount: MC amount to burn.
    """
    # only owner can burn the token
    assert (CheckWitness(OWNER))
    ownerBalance = balanceOf(OWNER)
    total = totalSupply()
    assert (total >= amount and ownerBalance >= amount and amount >= 0)
    newTotal = total - amount
    # update total supply
    Put(GetContext(), SUPPLY_KEY, newTotal)
    # update the owner's balance
    Put(GetContext(), concat(BALANCE_PREFIX, OWNER), ownerBalance - amount)
    TransferEvent(OWNER, "", amount)
    return True
Esempio n. 15
0
def setFeeCollector(feeCollector):
    """
    :param feeCollector: address
    :return:
    """
    assert (CheckWitness(getOwner()))
    Put(GetContext(), FEE_COLLECTOR_KEY, feeCollector)
    return True
Esempio n. 16
0
def setLockProxy(lockProxy):
    """
    :param lockProxy: ont lock proxy
    :return:
    """
    assert (CheckWitness(getOwner()))
    Put(GetContext(), LOCK_PROXY_KEY, bytearray_reverse(lockProxy))
    return True
Esempio n. 17
0
def init():
    # init list
    list1 = [1,2,3]
    list1Info = Serialize(list1)
    Put(GetContext(), LISTKEY, list1Info)
    # init map
    map1 = {
        "key1":1,
        "key2":2
    }
    map1Info = Serialize(map1)
    Put(GetContext(), MAPKEY, map1Info)

    Notify(["init list is ",list1])
    Notify(["init map is ", map1["key1"], map1["key2"]])

    return True
def approve(owner, spender, amount):
    if not CheckWitness(owner):
        return False
    key = concat(concat(APPROVE_PREFIX, owner), spender)
    Put(ctx, key, amount)

    ApprovalEvent(owner, spender, amount)
    return True
def checkIn(address, userId):
    assert (CheckWitness(address))
    checkInDays = canCheckIn(address)
    assert (checkInDays > 0)
    Put(GetContext(), concat(PLAYER_LAST_CHECK_IN_DAY, address), checkInDays)

    Notify(["checkIn", address, userId, GetTime()])
    return True
Esempio n. 20
0
def delegateToProxy(proxyReversedHash, amount):
    """
    initialize the contract, put some important info into the storage in the blockchain
    :return:
    """
    assert (CheckWitness(getOwner()))

    storedProxy = getProxyHash()
    if not storedProxy:
        Put(ctx, PROXY_HASH_KEY, proxyReversedHash)
    else:
        assert (proxyReversedHash == storedProxy)

    Put(ctx, concat(BALANCE_PREFIX, proxyReversedHash), balanceOf(proxyReversedHash) + amount)
    Put(ctx, SUPPLY_KEY, totalSupply() + amount)
    TransferEvent("", proxyReversedHash, amount)
    return True
Esempio n. 21
0
def init():
    """
    Initializes the contract
    """

    RequireIsAddress(OWNER)
    RequireWitness(OWNER)
    Require(totalSupply() == 0)

    total = TOTAL_AMOUNT * DECIMAL_MULTIPLIER
    Put(ctx, SUPPLY_KEY, total)

    key = getBalanceKey(OWNER)
    Put(ctx, key, total)

    TransferEvent(None, OWNER, total)
    return True
Esempio n. 22
0
def init(addr):
    if len(Get(GetContext(), KeyOwnerAddress)) == 0:
        Put(GetContext(), KeyOwnerAddress, addr)
        Notify(["init True"])
        return True
    else:
        Notify(["init False"])
        return False
Esempio n. 23
0
def lock(toChainId, fromAddress, toAddress, amount):
    """
    decrease the btcx balance of 'fromAddress' in this contract, decrease the total supply.
    request cross chain transaction from Ontology network to the 'toChainId' blockchain by sending serialized parameter to
    Ontology Native contract method of 'createCrossChainTx'.
    :param toChainId: indicates which blockchain 'fromAddress' wants to do cross chain transaction, in integer format.
    :param fromAddress: indicates the requester of this crosschain transaction invocation, in Ontology address format
    :param toAddress: indicates the address that will receive btcx asset in the 'toChainId' blockchain, in hex format,
                    if 'toAddress' belongs to Ethereum, we take the ethereum address and remove the '0x' then pass it as bytearray to contract
                    if 'toAddress' belongs to BitCoin, we take the btc address and force formating it to bytes and take the hex of bytes then pass it as bytearray to contract
    :param amount: indicates how many btcx 'fromAddress' want to do cross chain transaction from Ontology to another chain, in integer format, should be >= minimum limit
    :return:
    """
    btcRedeemScriptBytes = getBtcRedeemScript()
    assert(len(btcRedeemScriptBytes) != 0)
    # When cross back to btc blockchain, make sure the amount is no less than zero, the minimum cross chain limit, if no setMinBackBTCLimit, by default is 0
    if toChainId == BTC_ChainId:
        assert (amount >= getMinBackBTCLimit())
        argsList = [toAddress, amount, btcRedeemScriptBytes]
    else:
        assert (amount >=0 and toChainId != ONT_ChainId)
        argsList = [toAddress, amount]
    # check signature of from account
    assert (CheckWitness(fromAddress))
    # make sure the toAddress is not empty, since toChainId can be BTC_chainId, ETH_chainId, NEO_chainId
    # it is hard for us to check if the toAddress is legal, so here just check if it's empty
    assert (len(toAddress) != 0)
    # update the btcx balance of the from account
    Put(ctx, concat(BALANCE_KEY, fromAddress), Sub(balanceOf(fromAddress), amount))
    # decrease the total supply of Btcx
    Put(ctx, TOTAL_SUPPLY_KEY, Sub(totalSupply(), amount))

    # serialize the to account, amount, and redeem script together


    inputArgs = _serialzieArgs(argsList)

    # construct the parameters and pass them to the native cross chain manager contract to request for cross chain transaction
    toAssetHash = getContractAddrWithChainId(toChainId)
    assert(len(toAssetHash) != 0)
    param = state(toChainId, toAssetHash, "unlock", inputArgs)
    assert (Invoke(0, CROSS_CHAIN_CONTRACT_ADDRESS, "createCrossChainTx", param))
    # emit the event
    LockEvent(CONTRACT_ADDRESS, fromAddress, toChainId, toAssetHash, toAddress, amount)
    return True
Esempio n. 24
0
def unpause():
    """
    Resume the smart contract to normal state, all the function can be invoked.
    :return:True or raise exception.
    """
    assert (CheckWitness(getOwner()))

    Put(ctx, PAUSED, False)
    return True
Esempio n. 25
0
def unlock(params, fromContractAddr, fromChainId):
    """
    :param params:
    :return:
    """
    assert (CheckWitness(CROSS_CHAIN_CONTRACT_ADDRESS))
    res = _deserialzieArgs(params)
    toAddress = res[0]
    value = res[1]
    assert(fromContractAddr == getAssetHash(fromChainId))

    assert (value >= 0)
    assert (isAddress(toAddress))

    Put(ctx, concat(BALANCE_KEY, toAddress), Add(balanceOf(toAddress), value))
    Put(ctx, TOTAL_SUPPLY_KEY, Add(totalSupply(), value))
    UnlockEvent(toAddress, value)
    return True
Esempio n. 26
0
def checkIn(account):
    assert (CheckWitness(account))
    checkInDays = canCheckIn(account)
    if (checkInDays > 0):
        _transferTokenTo(account, 100 * OEP4TokenMagnitude)
        _chargeONG(account, Fee)
        Put(GetContext(), concatKey(PLAYER_LAST_CHECK_IN_DAY, account), checkInDays)
        Notify(["checkIn", account])
    return True
Esempio n. 27
0
def add_user_list(bet, element, prefix):
    list_info = Get(ctx, concatkey(bet, prefix))
    lists = Deserialize(list_info)

    lists.append(element)
    list_info = Serialize(lists)
    Put(ctx, concatkey(bet, prefix), list_info)
    Notify(['add_user_list', element, prefix])
    return True
def _transfer(_from, _to, _amount):
    fromKey = concat(BALANCE_PREFIX, _from)
    fromBalance = Get(ctx, fromKey)
    if _amount > fromBalance:
        return False
    if _amount == fromBalance:
        Delete(ctx, fromKey)
    else:
        Put(ctx, fromKey, fromBalance - _amount)
    toKey = concat(BALANCE_PREFIX, _to)
    toBalance = Get(ctx, toKey)
    Put(ctx, toKey, toBalance + _amount)

    # Notify(["transfer", AddressToBase58(from_acct), AddressToBase58(to_acct), amount])
    # TransferEvent(AddressToBase58(from_acct), AddressToBase58(to_acct), amount)
    TransferEvent(_from, _to, _amount)

    return True
Esempio n. 29
0
def setBreadInfo(childAddress, value):
    res = CheckWitness(Provider)
    if res:
        state = "inProgress"
        Put(GetContext(), childAddress, value)
        Notify(["setBreadInfo", childAddress, value, state])
    else:
        Notify(["Identity wrong"])
    return True
Esempio n. 30
0
def remove_list(element):
    ab_info = Get(ctx, ABKEY)
    ab = Deserialize(ab_info)

    ab1 = ab.remove(element)
    ab1_info = Serialize(ab1)
    Put(ctx, ABKEY, ab1_info)

    return True