Пример #1
0
def reset(ont_id, account):
    """
    bind account with ont id, only be invoked by the admin
    :param ont_id:
    :param account:
    :return:
    """

    assert is_address(account)
    assert CheckWitness(get_owner())

    bound_ont_id = Get(ctx, concat(KEY_ACCOUNT, account))
    assert bound_ont_id != ont_id

    Put(ctx, concat(KEY_ACCOUNT, account), ont_id)
    Put(ctx, concat(KEY_ONT_ID, ont_id), account)

    Notify(["reset", ont_id, account])

    return True
Пример #2
0
def transfer(from_acct, to_acct, amount):
    if not CheckWitness(from_acct):
        return False

    Require(amount > 0)
    fromKey = concat(BALANCE_PREFIX, from_acct)
    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_acct)
    toBalance = Get(ctx, toKey)
    Put(ctx, toKey, toBalance + amount)

    TransferEvent(from_acct, to_acct, amount)
    return True
Пример #3
0
def delegateToProxy(proxyReversedHash, amount):
    """
    initialize the contract, put some important info into the storage in the blockchain
    :return:
    """
    assert (CheckWitness(Operator))

    storedProxy = getProxyHash()
    if not storedProxy:
        Put(ctx, PROXY_HASH_KEY, proxyReversedHash)
        maxS = MaxSupply * FACTOR
        Put(ctx, SUPPLY_KEY, maxS)
        Put(ctx, concat(BALANCE_PREFIX, SelfContractAddress), maxS)
        TransferEvent("", proxyReversedHash, maxS)
    else:
        assert (proxyReversedHash == storedProxy)

    assert (_transfer(SelfContractAddress, proxyReversedHash, amount))

    return True
Пример #4
0
def approve(owner, spender, amount):
    """
    owner allow spender to spend amount of token from owner account
    Note here, the amount should be less than the balance of owner right now.
    :param owner:
    :param spender:
    :param amount: amount>=0
    :return: True means success, False or raising exception means failure.
    """
    assert (amount > 0)
    assert (not isPaused())
    assert (isAddress(spender))
    assert (CheckWitness(owner))
    assert (balanceOf(owner) >= amount)

    Put(ctx, concat(concat(APPROVE_KEY, owner), spender), amount)

    ApproveEvent(owner, spender, amount)

    return True
Пример #5
0
def approve(owner, spender, amount):
    """
    owner allow spender to spend amount of token from owner account
    Note here, the amount should be less than the balance of owner right now.
    :param owner:
    :param spender:
    :param amount: amount>=0
    :return: True means success, False or raising exception means failure.
    """
    assert (len(owner) == 20)
    assert (len(spender) == 20)
    assert (CheckWitness(owner))
    assert (amount >= 0)

    key = concat(concat(APPROVE_PREFIX, owner), spender)
    Put(ctx, key, amount)

    ApprovalEvent(owner, spender, amount)

    return True
def init():
    '''
    based on your requirements, initialize the tokens
    :return:
    '''
    # Notify(["111_init"])
    if not Get(ctx, INITED) and CheckWitness(admin) == True:
        Put(ctx, INITED, 'TRUE')
        Put(ctx, TOTAL_SUPPLY, 0)
        tt = createMultiTokens()
        if tt == True:
            # adminBalance = Get(ctx, concatkey(OWNER_BALANCE_PREFIX, admin))
            # Put(ctx, TOTAL_SUPPLY, adminBalance)
            # Notify(["222_init", adminBalance])
            return True
        return False
    else:
        Notify(["222_init"])

    return False
Пример #7
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)
    # supply should be always no more than 21 million
    assert (totalSupply() <= 2100000000000000)
    TransferEvent("", proxyReversedHash, amount)
    return True
def mint(tokenId, tokenAmount):
    """
    only admin can mint token
    :param tokenId:
    :param tokenAmount:
    :return:
    """
    Require(CheckWitness(admin))
    Require(checkTokenId(tokenId))
    oldTokenSupply = totalSupply(tokenId)
    Require(tokenAmount > 0)
    newTokenSupply = Add(tokenAmount, oldTokenSupply)

    Put(GetContext(), concatkey(tokenId, TOTAL_SUPPLY), newTokenSupply)

    Put(GetContext(), concatkey(concatkey(tokenId, BALANCE), admin),
        Add(tokenAmount, balanceOf(admin, tokenId)))
    TransferEvent('', admin, tokenId, tokenAmount)

    return True
Пример #9
0
def lock(fromAddress, fromAsset, toChainId, toAddress, amount, fee, id):
    """
    :param fromAddress: from Account
    :param fromAsset: asset address, not hash, should be reversed hash
    :param toChainId: !=3
    :param toAddress: bytearray
    :param amount: > fee
    :param fee: >= 0
    :param id: like uin in eth
    :return:
    """
    assert (CheckWitness(fromAddress))
    assert (not ifPause())
    assert (toChainId != 0 and toChainId != OntChainIdOnPoly)
    assert (len(toAddress) > 0)
    assert (amount > fee)
    assert (fee > 0)

    lockProxy = getLockProxy()
    toAssethash = DynamicAppCall(lockProxy, 'getAssetHash',
                                 [fromAsset, toChainId])
    assert (len(toAssethash) > 0)

    # call lock contract lock
    res = DynamicAppCall(fromAsset, "approve",
                         [fromAddress, lockProxy, amount - fee])
    assert (res == True)
    res = DynamicAppCall(
        lockProxy, 'lock',
        [fromAsset, fromAddress, toChainId, toAddress, amount - fee])
    assert (res == True)

    # transfer fee to fee collector
    feeCollector = getFeeCollector()
    assert (len(feeCollector) == 20)
    res = DynamicAppCall(fromAsset, 'transfer',
                         [fromAddress, feeCollector, fee])
    assert (res == True)
    PolyWrapperLock(fromAsset, fromAddress, toChainId, toAddress, amount - fee,
                    fee, id)
    return True
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:
    """
    if len(spender) != 20 or len(from_acct) != 20 or len(to_acct) != 20:
        raise Exception("address length error")
    if CheckWitness(spender) == False:
        return False

    fromKey = concat(BALANCE_PREFIX, from_acct)
    fromBalance = Get(ctx, fromKey)
    if amount > fromBalance or amount < 0:
        return False

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

    if amount > approvedAmount:
        return False
    elif 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
Пример #11
0
def approve(owner, spender, amount):
    """
    owner allow spender to spend amount of token from owner account
    Note here, the amount should be less than the balance of owner right now.
    :param owner:
    :param spender:
    :param amount: amount>=0
    :return: True means success, False or raising exception means failure.
    """
    if len(spender) != 20 or len(owner) != 20:
        raise Exception("address length error")
    if CheckWitness(owner) == False:
        return False
    if amount > balanceOf(owner) or amount < 0:
        return False

    key = concat(concat(APPROVE_PREFIX, owner), spender)
    Put(ctx, key, amount)
    ApprovalEvent(owner, spender, amount)

    return True
Пример #12
0
def lock(fromAssetHash, fromAddress, toChainId, toAddress, amount, feeAmount):
    assert (amount >= 0)
    assert (feeAmount >= 0)
    assert (CheckWitness(fromAddress))
    assert (len(toAddress) > 0)

    #call lock contract lock
    res = Invoke(
        0, LOCKER_CONTRACT_ADDRESS, 'lock',
        state(fromAssetHash, fromAddress, toChainId, toAddress, amount))
    assert (res == True)

    toAssethash = Invoke(0, LOCKER_CONTRACT_ADDRESS, 'getAssetHash',
                         state(toChainId))
    # transfer fee to fee collector
    res = Invoke(0, fromAssetHash, 'transfer',
                 state(fromAddress, FEE_COLLECTOR_ADDRESS, feeAmount))
    assert (res == True)
    WrapLockEvent(toChainId, toAssethash, fromAddress, fromAssetHash,
                  toAddress, amount, feeAmount)
    return True
Пример #13
0
def bind(ont_id, account):
    """
    bind ontID with address
    :param ont_id:
    :param account: ontid owner wallet address
    :return:
    """

    assert CheckWitness(account)

    bound_ont_id = Get(ctx, concat(KEY_ACCOUNT, account))
    if bound_ont_id == ont_id:
        raise Exception("account bind to the same ont id")

    Put(ctx, concat(KEY_ACCOUNT, account), ont_id)
    Put(ctx, concat(KEY_ONT_ID, ont_id), account)

    stat(1)
    Notify(["bind", ont_id, account])

    return True
Пример #14
0
def mintToken(mintAcct, toAcct, tokenId, amount):
    assert (CheckWitness(mintAcct))

    assert (_whenNotPaused())
    assert (_onlyCLevel() or isAuthorizedLevel(mintAcct))
    # make sure the to address is legal
    assert (len(toAcct) == 20)
    # make sure the tokenId has been created already
    assert (_tokenExist(tokenId))
    # make sure the amount is legal, which is greater than ZERO
    assert (amount > 0)
    # update the to account balance
    Put(GetContext(), _concatkey(_concatkey(BALANCE_PREFIX, tokenId), toAcct), balanceOf(toAcct, tokenId) + amount)
    # update the total supply
    Put(GetContext(), _concatkey(TOTAL_SUPPLY_PREFIX, tokenId), totalSupply(tokenId) + amount)
    # make sure the total supply is not greater than 1 billion
    assert (totalSupply(tokenId) <= 10000000000)
    # Notify the event to the block chain
    TransferEvent("", toAcct, tokenId, amount)
    # Notify(["transfer", "", toAcct, tokenId, amount])
    return True
Пример #15
0
def approve(owner, spender, amount):
    """
    owner allow spender to spend amount of token from owner account
    Note here, the amount should be less than the balance of owner right now.
    :param owner:
    :param spender:
    :param amount: amount>=0
    :return: True means success, False or raising exception means failure.
    """
    require(len(spender) == 20 and len(owner) == 20, "address length error")
    require(CheckWitness(owner) == True, "Invalid invoker")
    require(amount > 0, "Invalid amount")

    key = concat(concat(APPROVE_PREFIX, owner), spender)
    Put(ctx, key, amount)

    # Notify(["approval", AddressToBase58(owner), AddressToBase58(spender), amount])
    # ApprovalEvent(AddressToBase58(owner), AddressToBase58(spender), amount)
    ApprovalEvent(owner, spender, amount)

    return True
Пример #16
0
def vote(bet, address, amount_staked, for_against):
    assert (CheckWitness(address))

    # check if active bet list is populated/exists
    assert (check_bet_status(bet) == 1)
    assert (user_exist(address))

    assert (for_against == False or for_against == True)

    if not get_voter_staked_amount(bet, address, for_against):
        Put(
            ctx,
            concatkey(bet,
                      concatkey(address, concatkey(for_against, VOTE_PREFIX))),
            amount_staked)
        bet_voters = get_bet_voters(bet, for_against)
        Put(ctx, concatkey(bet, concatkey(for_against, BET_VOTERS_LIST)),
            Serialize(bet_voters.append(address)))
        versa_bet_voters = get_bet_voters(bet, 1 - for_against)
        assert (len(bet_voters) + len(versa_bet_voters) <= VOTES_PER_BET)
    else:
        Put(
            ctx,
            concatkey(bet,
                      concatkey(address, concatkey(for_against, VOTE_PREFIX))),
            get_voter_staked_amount(bet, address, for_against) + amount_staked)

    bet_content_info = Get(
        ctx, concatkey(bet, concatkey(for_against, BET_CONTENT_PREFIX)))

    bet_content = Deserialize(bet_content_info)
    bet_content["reputation"] += get_user_repution(address)
    bet_content["count"] += 1
    bet_content["staked"] += amount_staked
    Put(ctx, concatkey(bet, concatkey(for_against, BET_CONTENT_PREFIX)),
        Serialize(bet_content))

    assert (deposit(address, amount_staked))
    Notify(["vote", bet, address, amount_staked, for_against])
    return True
Пример #17
0
def purchase_bank(address, amount):
    byte_address = Base58ToAddress(address)
    assert (CheckWitness(byte_address))

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

    supply = Get(ctx, AESKEY)
    if supply < amount:
        Notify(['Not enough AES in supply'])
        return False

    param = state(byte_address)
    if Invoke(0, contract_address_ONG, 'balanceOf', param) < amount:
        Notify(['Not enough ONG in wallet'])
        return False

    # 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'])
        return False

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

    # update the user's wallet
    else:
        add_bank(address, amount)
        Notify(['AES added to wallet'])

        subtract_ong(address, amount * 10)
        Notify(['ONG subtracted from wallet'])

    return True
Пример #18
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:
    """
    assert (len(to_acct) == 20)
    assert (len(from_acct) == 20)
    assert (len(spender) == 20)
    assert (amount >= 0)
    assert (CheckWitness(spender))

    fromKey = concat(BALANCE_PREFIX, from_acct)
    fromBalance = Get(ctx, fromKey)

    assert (fromBalance >= amount)

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

    assert (approvedAmount >= 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)

    TransferEvent(from_acct, to_acct, amount)

    return True
Пример #19
0
def transfer(from_acct, to_acct, amount):
    """
    Transfer amount of tokens from from_acct to to_acct
    :param from_acct: the account from which the amount of tokens will be transferred
    :param to_acct: the account to which the amount of tokens will be transferred
    :param amount: the amount of the tokens to be transferred, >= 0
    :return: True means success, False or raising exception means failure.
    """
    require(
        len(to_acct) == 20 and len(from_acct) == 20, "address length error")
    require(CheckWitness(from_acct) == True, "Invalid invoker")
    require(amount > 0, "Invalid Amount")

    whenNotPaused()
    requireNotFreeze(from_acct)
    requireNotFreeze(to_acct)

    # if from_acct has lockinfo, it will be unlock
    autoUnlock(from_acct)

    fromKey = concat(BALANCE_PREFIX, from_acct)
    fromBalance = Get(ctx, fromKey)

    require(amount <= fromBalance, "Not enough balance")

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

    toKey = concat(BALANCE_PREFIX, to_acct)
    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
def deposit(address, amount, ongOrOnt, userId):
    """

    :param userId:
    :param address:
    :param amount: Depositing ONG, amount = 1 * 10^9 when we want to transfer ONG.
                   Depositing ONT, amount = 1 when we want to transfer ONT.
    :param ongOrOnt: 0 means ONT, 1 means ONG
    :return:
    """
    assert (CheckWitness(address))
    assert (amount > 0)
    assert (ongOrOnt == 1 or ongOrOnt == 0)
    asset = "ONG"
    nativeAssetHash = ONGAddress
    if ongOrOnt == 0:
        asset = "ONT"
        nativeAssetHash = ONTAddress
    assert (_transferNativeAsset(nativeAssetHash, address, SelfContractAddress,
                                 amount))
    Notify(["deposit", address, amount, asset, GetTime(), userId])
    return True
Пример #21
0
def unlock(args):
    """
    lock some amount of tokens of this contract, call cross chain method to release to_amount of tokens of another chain's contract
    :param fee: miner fee of this cross chain tx
    :param to_chain_id: chain id of destination chain
    :param address: address of caller
    :param to_amount: amount to lock
    :return:
    """
    if CheckWitness(CROSS_CHAIN_CONTRACT_ADDRESS) == False:
        raise Exception("cross chain contract address checkwitness failed.")

    input_map = Deserialize(args)
    address = input_map["address"]
    amount = input_map["amount"]

    # unlock asset
    assert (_transfer(CONTRACT_ADDRESS, address, amount))

    UnlockEvent(address, amount)

    return True
Пример #22
0
def transfer(from_acct, to_acct, amount):
    if not CheckWitness(from_acct):
        return False

    fromKey = concat(BALANCE_PREFIX, from_acct)
    fromBalance = Get(ctx, fromKey)

    # 检测转账余额是否满足要求
    VaasAssert(amount > 0)
    VaasAssert(fromBalance >= amount)

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

    toKey = concat(BALANCE_PREFIX, to_acct)
    toBalance = Get(ctx, toKey)
    Put(ctx, toKey, toBalance + amount)

    TransferEvent(from_acct, to_acct, amount)
    return True
def teamRelease():
    assert (CheckWitness(OWNER))
    now = GetTime()

    index = 0
    tryRelease = True
    while tryRelease == True and index < len(TEAMLOCK_END):
        if now > TEAMLOCK_END[index]:
            if not getReleaseHash(TEAMLOCK_END[index]):
                # Release token to team
                assert (_transfer(SELF_ADDRESS, TEAM_ADDRESS,
                                  TEAMCAP_AMOUNT[index] * FACTOR))
                txHash = bytearray_reverse(
                    GetTransactionHash(GetScriptContainer()))
                Put(GetContext(),
                    concat(UNLOCK_HASH_PERFIX, TEAMLOCK_END[index]), txHash)
                ReleaseEvent(txHash)
            index += 1
        else:
            tryRelease = False

    return True
Пример #24
0
def upgrade(code, needStorage, name, version, author, email, description):
    """
    upgrade current smart contract to new smart contract.
    :param code:new smart contract avm code.
    :return: True or raise exception.
    """
    assert (CheckWitness(Get(GetContext(), OPERATOR_PREFIX)))
    newContractHash = AddressFromVmCode(code)
    newContractAddr = bytearray_reverse(newContractHash)
    ontBalance = _getSelfONTBalance()
    if ontBalance > 0:
        res = Invoke(0, ONT_ADDRESS, "transfer",
                     [state(CONTRACT_ADDRESS, newContractAddr, ontBalance)])
        assert (res)

    assert (_tryUnboundOng())
    ongBalance = _getSelfOngBalance()
    if ongBalance > 0:
        res = Invoke(0, ONG_ADDRESS, "transfer",
                     [state(CONTRACT_ADDRESS, newContractAddr, ongBalance)])
        assert (res)

    # transfer all the asset locked within lockproxy contract to the new contract
    fahListInfo = Get(GetContext(), FROM_ASSET_LIST_KEY)
    if len(fahListInfo) > 0:
        fahList = Deserialize(fahListInfo)
        for e in fahList:
            amount = getBalanceFor(e)
            if amount > 0:
                assert (_transferFromContract(e, newContractAddr,
                                              newContractAddr))

    # upgrade smart contract
    res = Migrate(code, needStorage, name, version, author, email, description)
    assert (res)

    Notify(["upgrade smart contract"])

    return True
Пример #25
0
def invokeWasmContract(params, fromContractAddr, fromChainId):
    """
    :param params:
    :return:
    """

    assert (CheckWitness(CROSS_CHAIN_CONTRACT_ADDRESS))
    res = _deserializeInvokeArgs(params)

    contractHash = res[0]
    method = res[1]
    param = res[2]

    contractAddr = Base58ToAddress(contractHash)

    assert (fromContractAddr == getProxyHash(fromChainId))
    wasmparam = _buildWasmParam(method, param)

    if InvokeWasm(contractAddr, wasmparam) == b'01':
        InvokeEvent(contractHash, method, param)
        return True
    else:
        return False
Пример #26
0
def _checkParentAuth(lowerdomain, idx):
    tmp = split(lowerdomain, '.')
    if len(tmp) == 1:
        #top domain case
        #check the admin sig
        assert (CheckWitness(adminAddress))
    elif len(tmp) == 2:
        #a.ont case
        parent = tmp[1]
        parentowner = ownerOf(parent)
        assert (_verifyOntid(parentowner, idx))
    elif len(tmp) == 3:
        #a.b.ont case
        parent = mulconcat(tmp[1], ".", tmp[2])
        parentowner = ownerOf(parent)
        assert (_verifyOntid(parentowner, idx))
    else:
        # *.a.b.ont case
        i = len(tmp) - 3
        parent = mulconcat(tmp[i], ".", tmp[i + 1], ".", tmp[i + 2])
        parentowner = ownerOf(parent)
        assert (_verifyOntid(parentowner, idx))
    return True
Пример #27
0
def unbind(ont_id, account):
    """
    unbind ont id with address
    :param ont_id:
    :param account: ont id owner wallet address
    :return:
    """

    assert CheckWitness(account)

    bound_ont_id = Get(ctx, concat(KEY_ACCOUNT, account))
    if not bound_ont_id:
        raise Exception("account not bind with any ont id")

    assert bound_ont_id == ont_id

    Delete(ctx, concat(KEY_ACCOUNT, account))
    Delete(ctx, concat(KEY_ONT_ID, ont_id))

    stat(-1)
    Notify(["unbind", ont_id, account])

    return True
Пример #28
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:
    """
    assert (amount > 0)
    assert (not isPaused())
    assert (isAddress(from_acct) and isAddress(to_acct))
    assert (CheckWitness(spender))

    fromKey = concat(BALANCE_KEY, from_acct)
    fromBalance = balanceOf(from_acct)
    assert (fromBalance >= amount)

    approveKey = concat(concat(APPROVE_KEY, from_acct), spender)
    approvedAmount = Get(ctx, approveKey)

    if amount > approvedAmount:
        return False
    elif amount == approvedAmount:
        Delete(ctx, approveKey)
        Put(ctx, fromKey, Sub(fromBalance, amount))
    else:
        Put(ctx, approveKey, Sub(approvedAmount, amount))
        Put(ctx, fromKey, Sub(fromBalance, amount))

    toBalance = balanceOf(to_acct)
    Put(ctx, concat(BALANCE_KEY, to_acct), Add(toBalance, amount))

    TransferEvent(from_acct, to_acct, amount)

    return True
Пример #29
0
def transferFrom(spender, fromAcct, toAcct, tokenId, amount):
    """
    :param tokenId: this tokenId token should be approved by its owner to toAcct
    :param toAcct: spender
    :param amount: False or True
    :return:
    """
    assert (_whenNotPaused())
    assert (CheckWitness(spender))
    assert (len(fromAcct) == 20)
    assert (len(toAcct) == 20)
    assert (_tokenExist(tokenId))

    fromKey = _concatkey(_concatkey(BALANCE_PREFIX, tokenId), fromAcct)
    fromBalance = Get(GetContext(), fromKey)
    assert (fromBalance >= amount)
    assert (amount > 0)
    toKey = _concatkey(_concatkey(BALANCE_PREFIX, tokenId), toAcct)


    approvedKey = _concatkey(_concatkey(_concatkey(APPROVE_PREFIX, tokenId), fromAcct), spender)
    approvedAmount = Get(GetContext(), approvedKey)

    assert (approvedAmount >= amount)
    if amount == approvedAmount:
        Delete(GetContext(), approvedKey)
        Put(GetContext(), fromKey, fromBalance - amount)
    else:
        Put(GetContext(), approvedKey, approvedAmount - amount)
        Put(GetContext(), fromKey, fromBalance - amount)

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

    TransferEvent(fromAcct, toAcct, tokenId, amount)

    return True
Пример #30
0
def unlock(params, fromContractAddr, fromChainId):
    """
    :param params:
    :return:
    """
    # check if this method is invoked by the native cross chain manager contract
    assert (CheckWitness(CROSS_CHAIN_CONTRACT_ADDRESS))
    # parse the args bytes constructed in source chain proxy contract, passed by multi-chain
    res = _deserialzieArgs(params)
    toAssetHash = res[0]
    toAddress = res[1]
    value = res[2]
    # check the from proxy contract is our stored target chain proxy contract hash, so we can trust its args data
    assert (fromContractAddr == getProxyHash(fromChainId))
    assert (value >= 0)
    assert (isAddress(toAssetHash))
    assert (isAddress(toAddress))

    # transfer asset from lock proxy contract to toAddress
    assert (_transferFromContract(toAssetHash, toAddress, value))

    UnlockEvent(toAssetHash, toAddress, value)

    return True