示例#1
0
def checkHash():
    Notify(["111_checkHash"])
    # to prevent hack from other contract
    callerHash = GetCallingScriptHash()
    entryHash = GetEntryScriptHash()
    Notify([callerHash, entryHash, ContractAddress])
    return True
示例#2
0
def invokeB(param):
    Notify(["111_invokeB", param])
    # to prevent hack from other contract
    callerHash = GetCallingScriptHash()
    entryHash = GetEntryScriptHash()
    Notify([callerHash, entryHash, ContractAddress])
    return True
示例#3
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():
        if CheckWitness(OWNER):
            return True

        return False

    elif trigger == Application():

        if operation == 'currentKing':
            return Get(ctx, KOTH_KEY)

        if operation == 'currentBounty':
            myhash = GetExecutingScriptHash()
            currentBalance = TUT_Contract('balanceOf', [myhash])
            current_bounty = currentBalance + INCREMENT
            return current_bounty

        chash = GetCallingScriptHash()
        if chash != TUT_Scripthash:
            print('Token type not accepted by this contract')
            return False

        elif operation == 'onTokenTransfer':
            print('onTokenTransfer() called')

            return handle_token_received(ctx, args)

    return False
示例#4
0
def avoidToBeInvokedByContract():
    callerHash = GetCallingScriptHash()
    entryHash = GetEntryScriptHash()
    if callerHash != entryHash:
        Notify(["You are not allowed to invoke this method through contract"])
        return False
    else:
        Notify(["You can implement what you need to do here!"])
        return True
示例#5
0
def Main(operation, args):
    """
    This is the main entry point for the Smart Contract

    :param operation: the operation to be performed ( eg `balanceOf`, `transfer`, etc)
    :type operation: str
    :param args: a list of arguments ( which may be empty, but not absent )
    :type args: list
    :return: indicating the successful execution of the smart contract
    :rtype: bool
    """

    # The trigger determines whether this smart contract is being
    # run in 'verification' mode or 'application'

    trigger = GetTrigger()

    # 'Verification' mode is used when trying to spend assets ( eg NEO, Gas)
    # on behalf of this contract's address
    if trigger == Verification():

        # if the script that sent this is the owner
        # we allow the spend
        assert CheckWitness(OWNER), 'unauthorized'
        return True

    # 'Application' mode is the main body of the smart contract
    elif trigger == Application():

        if operation == 'name':
            return TOKEN_NAME

        elif operation == 'decimals':
            return TOKEN_DECIMALS

        elif operation == 'symbol':
            return TOKEN_SYMBOL

        elif operation == 'totalSupply':
            return TOKEN_TOTAL_SUPPLY

        elif operation == 'balanceOf':
            assert len(args) == 1, 'incorrect arg length'
            account = args[0]
            return do_balance_of(ctx, account)

        elif operation == 'transfer':
            assert len(args) == 3, 'incorrect arg length'
            t_from = args[0]
            t_to = args[1]
            t_amount = args[2]
            return do_transfer(ctx, t_from, t_to, t_amount,
                               GetCallingScriptHash())

        AssertionError('unknown operation')
示例#6
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():
        if CheckWitness(OWNER):
            return True

        return False

    elif trigger == Application():

        if operation == 'hello':
            print('hello world!')
            totalcalls = Get('totalCalls')
            totalcalls = totalcalls + 1
            print(totalcalls)
            if Put('totalCalls', totalcalls):
                return True
            print('staked storage call failed')
            return False

            return True

        if operation == 'ownerWithdraw':
            if not CheckWitness(OWNER):
                print(
                    'only the contract owner can withdraw MCT from the contract'
                )
                return False

            if len(args) != 1:
                print('withdraw amount not specified')
                return False

            t_amount = args[0]
            myhash = GetExecutingScriptHash()

            return MCTContract('transfer', [myhash, OWNER, t_amount])

        # end of normal invocations, reject any non-MCT invocations

        caller = GetCallingScriptHash()

        if caller != MCT_SCRIPTHASH:
            print('token type not accepted by this contract')
            return False

        if operation == 'onTokenTransfer':
            print('onTokenTransfer() called')
            return handle_token_received(caller, args)

    return False
def avoidContractCallAttack(guessNumber):

    randomNumber = getRandomNumber()

    callerHash = GetCallingScriptHash()
    entryHash = GetEntryScriptHash()
    Notify(["randomNumber:", randomNumber, "guessNumber:", guessNumber])
    if callerHash != entryHash:
        Notify(["You are not allowed to invoke this method through contract!"])
        return False
    else:
        Notify(["You can implement what you need to do here!"])
        if guessNumber == randomNumber:
            Notify(["You have won the big prize!"])
        return True
示例#8
0
def Main(op, args):
    context = GetContext()

    if op == 'registerProvider':
        if len(args) == 2:
            return register_provider(context, args)
        else:
            Notify(ARG_ERROR)
            return False
    elif op == 'delegateVerify':
        if len(args) == 1:
            wallet = GetCallingScriptHash()
            return delegate_verify(context, wallet, args)
        else:
            Notify(ARG_ERROR)
            return False
    else:
        Notify(INVALID_OPERATION)
        return False
示例#9
0
def bet(account, ongAmount, number):
    """
    :param account:
    :param ongAmount:
    :param number:
    :return:
    """
    # RequireWitness(account)
    if CheckWitness(account) == False:
        # bet: Check witness failed!
        Notify(["Error", 601])
        return False

    currentRound = getCurrentRound()

    # to prevent hack from other contract
    callerHash = GetCallingScriptHash()
    entryHash = GetEntryScriptHash()
    # Require(callerHash == entryHash)
    if callerHash != entryHash:
        # bet: Don't support bet method being invoked by another contract to prevent hacking
        Notify(["Error", 602])
        return False

    if getRoundGameStatus(currentRound) != STATUS_ON:
        # bet: Current round game ended, please wait for the starting of the next round game and try later
        Notify(["Error", 603])
        return False

    # make sure the contract has enough ong to pay to accont if account wins
    tryPayOutToWin = _calculatePayOutToWin(ongAmount, number)
    totalOngAmount = getTotalONG()
    realTimeRunVault = getRealTimeRunningVault(currentRound)

    # # Require(realTimeRunVault > tryPayOutToWin)
    if realTimeRunVault < Sub(tryPayOutToWin, ongAmount):
        # bet: Running pot/vault does not have enough asset to pay to the player, please try smaller bet
        Notify(["Error", 604])
        return False

    # Require(_transferONG(account, ContractAddress, ongAmount))
    res = _transferONG(account, ContractAddress, ongAmount)
    if res == False:
        # bet: Transfer ONG failed, please try later or again
        Notify(["Error", 605])
        return False

    # Require(number < 97)
    if number >= 97:
        # bet: Please try to bet with a number less than 97
        Notify(["Error", 606])
        return False
    # Require(number > 1)
    if number <= 1:
        # bet: Please try to bet with a number greater than 1
        Notify(["Error", 607])
        return False

    theNumber = _rollANumber()
    payOutToWin = 0
    if theNumber < number:
        payOutToWin = tryPayOutToWin
        Require(_transferONGFromContact(account, payOutToWin))

        # update total ongAmount
        ongAmountToBeSub = Sub(payOutToWin, ongAmount)
        Put(GetContext(), TOTAL_ONG_KEY, Sub(totalOngAmount, ongAmountToBeSub))
        # update real time running vault
        realTimeRunVaultKey = concatKey(concatKey(ROUND_PREFIX, currentRound),
                                        REAL_TIME_RUNNING_VAULT)
        Put(GetContext(), realTimeRunVaultKey,
            Sub(realTimeRunVault, ongAmountToBeSub))
        realTimeRunVault = getRealTimeRunningVault(currentRound)
        # mark the game as end if real time running vault is less than 1/10 of running vault
        if realTimeRunVault <= Div(getIncreasingRunnVault(currentRound), 10):
            # mark this round of game end
            Put(GetContext(),
                concatKey(concatKey(ROUND_PREFIX, currentRound), ROUND_STATUS),
                STATUS_OFF)
            # update profit per investment for bankers
            runVaultLeft = getRunningVault(currentRound)
            if runVaultLeft > 0:
                profitPerRuningVaultShareToBeAdd = Div(
                    Mul(realTimeRunVault, MagnitudeForProfitPerSth),
                    runVaultLeft)
                Put(
                    GetContext(),
                    concatKey(concatKey(ROUND_PREFIX, currentRound),
                              PROFIT_PER_RUNNING_VAULT_SHARE_KEY),
                    Add(profitPerRuningVaultShareToBeAdd,
                        getProfitPerRunningVaultShare(currentRound)))
            # update real time running vault
            Delete(GetContext(), realTimeRunVaultKey)
            Notify(["endCurrentRound", currentRound])
            return True
    else:
        # update total ong amount
        Put(GetContext(), TOTAL_ONG_KEY, Add(totalOngAmount, ongAmount))

        # update profit per investment for bankers
        runVaultLeft = getRunningVault(currentRound)
        if runVaultLeft > 0:
            profitPerRunNingVaultShareToBeAdd = Div(
                Mul(ongAmount, MagnitudeForProfitPerSth), runVaultLeft)
            Put(
                GetContext(),
                concatKey(concatKey(ROUND_PREFIX, currentRound),
                          PROFIT_PER_RUNNING_VAULT_SHARE_KEY),
                Add(profitPerRunNingVaultShareToBeAdd,
                    getProfitPerRunningVaultShare(currentRound)))

    Notify([
        "bet", currentRound, account, number, theNumber, ongAmount, payOutToWin
    ])
    return True
示例#10
0
def Main(operation, args):
    """Entry point to the program

    :param str operation: The name of the operation to perform
    :param list args: A list of arguments along with the operation
    :return: The result of the operation
    :rtype: bytearray

    Token operations:
    - name(): returns name of token
    - symbol(): returns token symbol
    - claims(): returns a holders claim

    TOKEN_CONTRACT_OWNER operations:
        - mintToken(owner, claims): create a new NFT token with the specified properties
        and URI and send it to the specified owner
    """
    # The trigger determines whether this smart contract is being run
    # in 'verification' mode or 'application'
    trigger = GetTrigger()

    # 'Verification' mode is used when trying to spend assets
    # (eg NEO, Gas) on behalf of this contract's address
    if trigger == Verification():

        # if the script that sent this is the owner, we allow the spend
        if CheckWitness(TOKEN_CONTRACT_OWNER):
            return True

    elif trigger == Application():

        ctx = GetContext()

        if operation == 'name':
            return TOKEN_NAME

        elif operation == 'symbol':
            return TOKEN_SYMBOL

        elif operation == 'claims':
            t_owner = GetCallingScriptHash()
            token = Get(ctx, t_owner)

            if len(token) == b'\x00':
                token = b'\x01'  # token id's cannot go below 1

            claims = Get(ctx, concat('claims/', token))
            if claims:
                return claims

            Notify(TOKEN_DNE_ERROR)
            return False

        # Administrative operations
        if operation == 'mintToken':
            if CheckWitness(TOKEN_CONTRACT_OWNER):
                if len(args) == 2:
                    return do_mint_token(ctx, args)

                Notify(ARG_ERROR)
                return False
            else:
                Notify(PERMISSION_ERROR)
                return False

        Notify('unknown operation')

    return False
示例#11
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():
        # This should never be necessary but just in case someone
        # accidentally sends non-MCT assets to the contract they
        # can be recovered instead of being burned forever

        if CheckWitness(PARTY1):
            return True

        return False

    elif trigger == Application():

        # setNewPayee(newPayee) - if the current payee wants to assign
        # the tokens to another party, the contract payee can be changed
        # but only if both the depositor and current payee agree

        if operation == 'setNewPayee':
            if len(args) != 1:
                print('New payee scripthash not specified')
                return False

            new_payee = args[0]

            if len(new_payee) != 20:
                print('Incorrect new payee scripthash length')
                return False

            current_payee = Get('payee')

            if len(current_payee) != 20:
                current_payee = PARTY2

            if CheckWitness(PARTY1):  # depositor approval
                party2_payee = Get('Party2_Payee_Change_Approval')
                if new_payee == party2_payee:
                    Put('payee', new_payee)
                    Delete('Party1_Payee_Change_Approval')
                    Delete('Party2_Payee_Change_Approval')
                else:
                    Put('Party1_Payee_Change_Approval', new_payee)
                return True

            if CheckWitness(current_payee):  # current payee approval
                party1_payee = Get('Party1_Payee_Change_Approval')
                if new_payee == party1_payee:
                    Put('payee', new_payee)
                    Delete('Party1_Payee_Change_Approval')
                    Delete('Party2_Payee_Change_Approval')
                else:
                    Put('Party1_Payee_Change_Approval', new_payee)
                return True

            print('Not authorized to approve payee change')
            return False

        # getCurrentPayee() - return currently set payee value

        if operation == 'getCurrentPayee':
            current_payee = Get('payee')

            if len(current_payee) != 20:
                current_payee = PARTY2

            return current_payee

        # getUnlockTime() - return hard-coded unlock timestamp

        if operation == 'getUnlockTime':
            return unlockTime

        # withdraw() - if this operation is called after the unlock
        # period, the entire contract balance will be automatically
        # transferred to the current payee

        if operation == 'withdraw':
            header = GetHeader(GetHeight())
            if header.Timestamp < unlockTime:
                print('unlock period has not yet expired')
                return False

            # This contract's script hash, owner of the locked MCT tokens
            myhash = GetExecutingScriptHash()

            # Payout to current payee address
            payee = Get('payee')

            if len(payee) != 20:
                payee = PARTY2

            t_amount = MCTContract('balanceOf', [myhash])

            if t_amount > 0:
                print('Transferring all funds in contract to payee')
                return MCTContract('transfer', [myhash, payee, t_amount])
            else:
                print('No funds in contract')
            return False

        # end of normal invocations, reject any non-MCT invocations

        caller = GetCallingScriptHash()

        if caller != MCT_SCRIPTHASH:
            print('token type not accepted by this contract')
            return False

        if operation == 'onTokenTransfer':
            if CheckWitness(PARTY1):
                return True  # this is how party 1 deposits stake+locked tokens

            print('onTokenTransfer() called from address other than party 1')

    return False
示例#12
0
def invokeA(operation, params):
    callerHash = GetCallingScriptHash()
    entryHash = GetEntryScriptHash()
    Notify(["111_invokeA",callerHash, entryHash, ContractAddress])
    return ContractB(operation, params)
示例#13
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():
        return False  # no withdrawals allowed, even by contract owner

    elif trigger == Application():

        arglen = len(args)

        if operation == 'onTokenTransfer':
            return handle_token_received(GetCallingScriptHash(), args)

        if operation == 'confirmShipment':  # seller-only
            assert arglen == 1, 'incorrect argument length'
            sale_id = args[0]
            
            sale = loadSale(sale_id)
            assert sale['state'] == 'awaiting shipment', 'sale state incorrect'
            assert CheckWitness(sale['seller']), 'must be seller to confirm shipment'

            sale['state'] = 'shipment confirmed'
            r = Put(concat('sales/', sale_id), Serialize(sale))
        
            return True

        elif operation == 'confirmReceived':  # buyer-only
            assert arglen == 1, 'incorrect argument length'
            sale_id = args[0]
            
            sale = loadSale(sale_id)
            assert sale['state'] == 'shipment confirmed', 'sale state incorrect'
            seller = sale['seller']
            buyer = sale['buyer']
            price = sale['price']

            myhash = GetExecutingScriptHash()
            assert CheckWitness(buyer), 'must be buyer to complete the sale'

            # return the buyer deposit minus the item price
            r = MCTContract('transfer', [myhash, buyer, price])

            # return the seller deposit plus the item price
            r = MCTContract('transfer', [myhash, seller, price * 3])

            # delete the sale
            r = Delete(concat('sales/', sale_id))
            return True

        elif operation == 'deleteSale':  # seller-only, if buyer has not already made deposit
            assert arglen == 1, 'incorrect argument length'
            sale_id = args[0]
            sale = loadSale(sale_id)
            assert sale['state'] == 'new', 'cannot cancel sale post-buyer-deposit'
            seller = sale['seller']
            price = sale['price']

            myhash = GetExecutingScriptHash()
            assert CheckWitness(seller), 'must be seller to cancel the sale'

            # return the seller deposit to them
            return MCTContract('transfer', [myhash, seller, price * 2])

            # delete the sale
            r = Delete(concat('sales/', sale_id))
            return True

        elif operation == 'sale':  # get sale details
            assert arglen == 1, 'incorrect argument length'
            sale_id = args[0]
            return Get(concat('sales/', sale_id))

    AssertionError('unknown operation - code: XxXxXxXx')
示例#14
0
def Main(operation, args):
  caller = GetCallingScriptHash()
  print('caller_main')
  print(caller)
  printTest()
示例#15
0
def fillPaper(account, guessNumberList):
    """
    :param account:
    :param guessNumberList: can be a list of numbers
    :return:
    """
    RequireWitness(account)

    currentRound = getCurrentRound()

    Require(getGameStatus(currentRound) == STATUS_ON)

    # to prevent hack from other contract
    callerHash = GetCallingScriptHash()
    entryHash = GetEntryScriptHash()
    Require(callerHash == entryHash)
    # Require(entryHash == ContractAddress)

    guessNumberLen = len(guessNumberList)

    Require(guessNumberLen >= 1)

    currentPaperBalance = getPaperBalance(account)

    # make sure his balance is greater or equal to guessNumberList length
    Require(currentPaperBalance >= guessNumberLen)

    numberListKey = concatKey(concatKey(ROUND_PREFIX, currentRound), FILLED_NUMBER_LIST_KEY)
    numberListInfo = Get(GetContext(), numberListKey)
    numberList = []
    if numberListInfo:
        numberList = Deserialize(numberListInfo)

    for guessNumber in guessNumberList:

        # Require is need to raise exception
        Require(guessNumber < 100)
        Require(guessNumber >= 0)

        numberPlayersListKey = concatKey(concatKey(ROUND_PREFIX, currentRound), concatKey(FILLED_NUMBER_KEY, guessNumber))
        numberPlayersListInfo = Get(GetContext(), numberPlayersListKey)

        numberPlayersList = []
        if numberPlayersListInfo:
            numberPlayersList = Deserialize(numberPlayersListInfo)

            # make sure account has NOT filled the number before in this round
            for player in numberPlayersList:
                Require(player != account)
        else:
            numberList.append(guessNumber)

        # add account to the players list that filled the number in this round
        numberPlayersList.append(account)

        # Store the numberPlayers List
        numberPlayersListInfo = Serialize(numberPlayersList)
        Put(GetContext(), numberPlayersListKey, numberPlayersListInfo)
    # Store the numberList
    numberListInfo = Serialize(numberList)
    Put(GetContext(), numberListKey, numberListInfo)

    # update dividend
    updateDividendBalance(account)

    # update the paper balance of account  -- destroy the filled papers
    Put(GetContext(), concatKey(PAPER_BALANCE_PREFIX, account), Sub(currentPaperBalance, guessNumberLen))

    # update total paper amount
    Put(GetContext(), TOTAL_PAPER_KEY, Sub(getTotalPaper(), guessNumberLen))

    # update the filled paper balance of account in current round
    key1 = concatKey(ROUND_PREFIX, currentRound)
    key2 = concatKey(FILLED_PAPER_BALANCE_PREFIX, account)
    key = concatKey(key1, key2)
    Put(GetContext(), key, Add(guessNumberLen, getFilledPaperBalance(account, currentRound)))

    # update the filled paper amount in current round
    key = concatKey(concatKey(ROUND_PREFIX, currentRound), FILLED_PAPER_AMOUNT)
    Put(GetContext(), key, Add(guessNumberLen, getFilledPaperAmount(currentRound)))

    Notify(["fillPaper", account, guessNumberList, GetTime()])

    return True
示例#16
0
def Main(operation, args):
    """Entry point to the program

    :param str operation: The name of the operation to perform
    :param list args: A list of arguments along with the operation
    :return: The result of the operation
    :rtype: bytearray

    Token operations:
    - allowance(token_id): returns approved third-party spender of a
        token
    - approve(token_receiver, token_id, revoke): approve third party
        to spend a token
    - balanceOf(owner): returns owner's current total tokens owned
    - name(): returns name of token
    - decimals(): returns token decimal precision
    - ownerOf(token_id): returns the owner of the specified token.
    - properties(token_id): returns a token's read-only data
    - rwProperties(token_id): returns a token's read/write data
    - supportedStandards(): returns a list of supported standards
        {"NEP-10"}
    - symbol(): returns token symbol
    - token(token_id): returns a dictionary where token, property,
        and uri keys map to the corresponding data for the given
        `token_id`
    - tokensOfOwner(owner, starting_index): returns a dictionary that
        contains less than or equal to ten of the tokens owned by
        the specified address starting at the `starting_index`.
    - totalSupply(): Returns the total token supply deployed in the
        system.
    - transfer(to, token_id, extra_arg): transfers a token
    - transferFrom(spender, from, to, token_id): allows a third party
        to execute a pre-approved transfer
    - uri(token_id): Returns a distinct Uniform Resource Identifier
        (URI) for a given asset.
        The URI data of a token supplies a reference to get more
        information about a specific token or its data.

    TOKEN_CONTRACT_OWNER operations:
        - mintToken(owner, properties, URI, extra_arg): create a new
            NFT token with the specified properties and URI and send it
            to the specified owner
        - modifyURI(token_id, token_data): modify specified token's
            URI data

        setters:
        - setName(name): sets the name of the token
        - setSymbol(symbol): sets the token's symbol
        - setSupportedStandards(supported_standards): sets the
            supported standards, 'NEP-10' is always the first element
            in the array
    """
    # The trigger determines whether this smart contract is being run
    # in 'verification' mode or 'application'
    trigger = GetTrigger()

    # 'Verification' mode is used when trying to spend assets
    # (eg NEO, Gas) on behalf of this contract's address
    if trigger == Verification():

        # if the script that sent this is the owner, we allow the spend
        if CheckWitness(TOKEN_CONTRACT_OWNER):
            return True

    elif trigger == Application():

        # Need to get this at the top level
        caller = GetCallingScriptHash()
        ctx = GetContext()

        if operation == 'name':
            name = Get(ctx, 'name')
            if name:
                return name
            else:
                return TOKEN_NAME

        elif operation == 'symbol':
            symbol = Get(ctx, 'symbol')
            if symbol:
                return symbol
            else:
                return TOKEN_SYMBOL

        elif operation == 'supportedStandards':
            supported_standards = Get(ctx, 'supportedStandards')
            if supported_standards:
                return supported_standards
            else:
                return Serialize(['NEP-10'])

        elif operation == 'totalSupply':
            return Get(ctx, TOKEN_CIRC_KEY)

        elif operation == 'allowance':
            assert len(args) == 1, ARG_ERROR
            ownership = safe_deserialize(
                Get(ctx, concat('ownership/', args[0])))
            assert ownership, TOKEN_DNE_ERROR
            # don't fault here in case a calling contract is just checking allowance value
            if not has_key(ownership, 'approved'): return False
            if len(ownership['approved']) != 40: return False
            return ownership['approved']

        elif operation == 'balanceOf':
            assert len(args) == 1, ARG_ERROR
            assert len(args[0]) == 20, INVALID_ADDRESS_ERROR
            token_iter = Find(ctx, args[0])
            count = 0
            while token_iter.next():
                count += 1
            return count

        elif operation == 'ownerOf':
            assert len(args) == 1, ARG_ERROR
            ownership = safe_deserialize(
                Get(ctx, concat('ownership/', args[0])))
            assert ownership, TOKEN_DNE_ERROR
            assert has_key(ownership, 'owner'), TOKEN_DNE_ERROR
            assert len(ownership['owner']) == 20, TOKEN_DNE_ERROR
            return ownership['owner']

        elif operation == 'properties':
            assert len(args) == 1, ARG_ERROR
            return get_properties(ctx, args[0])

        elif operation == 'rwProperties':
            assert len(args) == 1, ARG_ERROR
            return get_rw_properties(ctx, args[0])

        elif operation == 'token':
            assert len(args) == 1, ARG_ERROR
            token = Get(ctx, concat('token/', args[0]))
            assert token, TOKEN_DNE_ERROR
            return token

        elif operation == 'tokensOfOwner':
            assert len(args) == 2, ARG_ERROR
            tokens_of_owner = do_tokens_of_owner(ctx, args[0], args[1])
            assert tokens_of_owner, 'address has no tokens'
            return Serialize(tokens_of_owner)

        elif operation == 'uri':
            assert len(args) == 1, ARG_ERROR
            token = safe_deserialize(Get(ctx, concat('token/', args[0])))
            assert token, TOKEN_DNE_ERROR
            assert has_key(token, 'uri'), TOKEN_DNE_ERROR
            return token['uri']

        elif operation == 'decimals':
            return TOKEN_DECIMALS

        #
        # User RW operations
        #

        if operation == 'approve':
            # args: from, spender, id, revoke
            # (NFT needs a fourth argument to revoke approval)
            assert len(args) > 2, ARG_ERROR
            assert args[2], TOKEN_DNE_ERROR
            return do_approve(ctx, caller, args)

        elif operation == 'transfer':
            assert len(args) > 1, ARG_ERROR
            return do_transfer(ctx, caller, args)

        elif operation == 'transferFrom':

            assert len(args) > 2, ARG_ERROR
            if len(args) == 3:
                # Nash-style (from, to, amount/id) transferFrom that can
                # be invoked only by whitelisted DEX to initiate a
                # pre-approved transfer

                return nash_do_transfer_from(ctx, caller, args)
            else:
                # Moonlight-style (spender, from, to, amount/id)
                # transfer where an authenticated spender/originator is
                # the only one who can initiate a transfer but can send
                # to an arbitrary third party (or themselves)

                return do_transfer_from(ctx, caller, args)

        #
        # dApp operations
        #
        if operation == 'setRWProperties':
            # args: token id, rwdata
            assert CheckWitness(DAPP_ADMIN), PERMISSION_ERROR
            assert len(args) == 2, ARG_ERROR
            return set_rw_properties(ctx, args[0], args[1])

        # Administrative operations
        if CheckWitness(TOKEN_CONTRACT_OWNER):
            if operation == 'mintToken':
                assert len(args) > 3, ARG_ERROR
                return do_mint_token(ctx, args)

            elif operation == 'modifyURI':
                assert len(args) == 2, ARG_ERROR
                return do_modify_uri(ctx, args)

            elif operation == 'setName':
                assert len(args) == 1, ARG_ERROR
                return do_set_config(ctx, 'name', args[0])

            elif operation == 'setSymbol':
                assert len(args) == 1, ARG_ERROR
                return do_set_config(ctx, 'symbol', args[0])

            elif operation == 'setSupportedStandards':
                assert len(args) >= 1, ARG_ERROR
                supported_standards = ['NEP-10']
                for arg in args:
                    supported_standards.append(arg)
                return do_set_config(ctx, 'supportedStandards',
                                     Serialize(supported_standards))

        AssertionError('unknown operation')
    return False
def FixGamblingResult(tx_hash):
    caller_adress = GetCallingScriptHash()
    if caller_adress != CHINCIRO_DICE_CONTRACT:
        Nofity([FixGamblingResult, "Falsy Execution"])
        return True
示例#18
0
def printTest():
    caller = GetCallingScriptHash()
    print('caller_printCaller')
    print(caller)
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():
        if CheckWitness(OWNER):
            return True

        return False

    elif trigger == Application():
        if operation == 'setExchangeRate':
            if not CheckWitness(OWNER):
                return False

            if len(args) != 3:
                return False

            fromtoken = args[0]
            totoken = args[1]
            rate = args[2]
            
            tokenkey = concat(fromtoken, totoken)

            if len(tokenkey) != 40:
                return False

            return Put(tokenkey, rate)
 
        if operation == 'exchangeRate':
            if len(args) != 2:
                return False

            fromtoken = args[0]
            totoken = args[1]

            tokenkey = concat(fromtoken, totoken)

            if len(tokenkey) != 40:
                return False

            return Get(tokenkey)

        if operation == 'migrateStorage':
            if not CheckWitness(OWNER):
                return False

            if len(args) != 1:
                return False
         
            return Migrate(args[0])

        if operation == 'ownerWithdraw':
            if not CheckWitness(OWNER):
                return False

            if len(args) != 2:
                return False
         
            t_scripthash = args[0]
            t_amount = args[1]

            myhash = GetExecutingScriptHash()

            if t_scripthash == TOKEN1: 
                return Token1Contract('transfer', [myhash, OWNER, t_amount])
            elif t_scripthash == TOKEN2: 
                return Token2Contract('transfer', [myhash, OWNER, t_amount])

        chash = GetCallingScriptHash()

        if chash != TOKEN1:
            if chash != TOKEN2:  # for some reason comparing these with "and"
                                 # returns an extra value on evaluation stack
                print('Token type not accepted by this contract')
                return False

        if operation == 'onTokenTransfer':
            print('onTokenTransfer() called')
            return handle_token_received(chash, args)

    return False
示例#20
0
def Main(operation, args):
    """Entry point to the program

    :param str operation: The name of the operation to perform
    :param list args: A list of arguments along with the operation
    :return: The result of the operation
    :rtype: bytearray


    Token operations:

    - name(): returns name of token
    - symbol(): returns token symbol
    - totalSupply(): Returns the total token supply deployed in the
      system.
    - decimals(): Return decimalS
    - tokens(): Return enumerator with all tokens FEHLT
    - transfer(to, token_id, extra_arg): transfers a token
    - ownerOf(token_id): returns the owner of the specified token.
    - tokenURI(token_id): Returns a distinct Uniform Resource Identifier
        (URI) for a given asset.
        The URI data of a token supplies a reference to get more
        information about a specific token or its data.
    - balanceOf(owner): returns owner's current total tokens owned
    - tokensOfOwner(owner, starting_index): returns a dictionary that
        contains less than or equal to ten of the tokens owned by
        the specified address starting at the `starting_index`.

    - allowance(token_id): returns approved third-party spender of a
        token
    - approve(token_receiver, token_id, revoke): approve third party
        to spend a token
    - properties(token_id): returns a token's read-only data
    - supportedStandards(): returns a list of supported standards
        {"NEP-10"}
    - tokenData(token_id): returns a dictionary where token, property,
        and uri keys map to the corresponding data for the given
        `token_id`
    - tokensDataOfOwner(owner, starting_index): returns a dictionary
        that contains less than or equal to five of the tokens (where
        token, properties, and uri keys map to their corresponding data
        for each token id) owned by the specified address starting at
        the `starting_index`.
    - transferFrom(from, to, token_id, extra_arg): allows a third party
        to execute an approved transfer


    TOKEN_CONTRACT_OWNER operations:
        - mintToken(owner, properties, URI, extra_arg): create a new
            NFT token with the specified properties and URI and send it
            to the specified owner
        - modifyURI(token_id, token_data): modify specified token's
            URI data

        setters:
        - setName(name): sets the name of the token
        - setSymbol(symbol): sets the token's symbol
        - setSupportedStandards(supported_standards): sets the
            supported standards, 'NEP-10' is always the first element
            in the array
    """
    # The trigger determines whether this smart contract is being run
    # in 'verification' mode or 'application'
    trigger = GetTrigger()

    # 'Verification' mode is used when trying to spend assets
    # (eg NEO, Gas) on behalf of this contract's address
    if trigger == Verification():

        # if the script that sent this is the owner, we allow the spend
        if CheckWitness(TOKEN_CONTRACT_OWNER):
            return True

    elif trigger == Application():

        ctx = GetContext()

        if operation == 'name':
            name = Get(ctx, 'name')
            if name:
                return name
            else:
                return TOKEN_NAME

        elif operation == 'symbol':
            symbol = Get(ctx, 'symbol')
            if symbol:
                return symbol
            else:
                return TOKEN_SYMBOL

        elif operation == 'decimals':
            return TOKEN_DECIMALS

        elif operation == 'totalSupply':
            return Get(ctx, TOKEN_CIRC_KEY)

        if operation == 'allowance':
            if len(args) == 1:
                return Get(ctx, concat('approved/', args[0]))

            Notify(ARG_ERROR)
            return False

        elif operation == 'approve':
            if len(args) == 3:
                # GetCallingScriptHash() can't be done within the
                # function because the calling script hash changes
                # depending on where the function is called
                return do_approve(ctx, GetCallingScriptHash(), args[0],
                                  args[1], args[2])

            Notify(ARG_ERROR)
            return False

        elif operation == 'balanceOf':
            if len(args) == 1:
                if len(args[0]) == 20:
                    return Get(ctx, args[0])

                Notify(INVALID_ADDRESS_ERROR)
                return False

            Notify(ARG_ERROR)
            return False

        elif operation == 'ownerOf':
            if len(args) == 1:
                t_owner = Get(ctx, args[0])
                if len(t_owner) == 20:
                    return t_owner

                Notify(TOKEN_DNE_ERROR)
                return False

            Notify(ARG_ERROR)
            return False

        elif operation == 'properties':
            if len(args) == 1:
                token_properties = Get(ctx, concat('properties/', args[0]))
                if token_properties:
                    return token_properties

                Notify(TOKEN_DNE_ERROR)
                return False

            Notify(ARG_ERROR)
            return False

        elif operation == 'tokenData':
            if len(args) == 1:
                # check to make sure the token exists
                if len(Get(ctx, args[0])) == 20:
                    return Serialize(do_token_data(ctx, args[0]))

                Notify(TOKEN_DNE_ERROR)
                return False

            Notify(ARG_ERROR)
            return False

        elif operation == 'tokensDataOfOwner':
            if len(args) == 2:
                tokens_data_of_owner = do_tokens_data_of_owner(
                    ctx, args[0], args[1])
                if tokens_data_of_owner:
                    return Serialize(tokens_data_of_owner)

                return False

            Notify(ARG_ERROR)
            return False

        elif operation == 'tokensOfOwner':
            if len(args) == 2:
                tokens_of_owner = do_tokens_of_owner(ctx, args[0], args[1])
                if tokens_of_owner:
                    return Serialize(tokens_of_owner)

                return False

            Notify(ARG_ERROR)
            return False

        elif operation == 'transfer':
            if len(args) >= 2:
                # GetCallingScriptHash() can't be done within the
                # function because the calling script hash changes
                # depending on where the function is called
                return do_transfer(ctx, GetCallingScriptHash(), args)

            Notify(ARG_ERROR)
            return False

        elif operation == 'transferFrom':
            if len(args) >= 3:
                return do_transfer_from(ctx, args)

            Notify(ARG_ERROR)
            return False

        elif operation == 'uri':
            if len(args) == 1:
                token_uri = Get(ctx, concat('uri/', args[0]))
                if token_uri:
                    return token_uri

                Notify(TOKEN_DNE_ERROR)
                return False

            Notify(ARG_ERROR)
            return False

        # Administrative operations
        if CheckWitness(TOKEN_CONTRACT_OWNER):
            if operation == 'mintToken':
                if len(args) >= 3:
                    return do_mint_token(ctx, args)

                Notify(ARG_ERROR)
                return False

            elif operation == 'modifyURI':
                if len(args) == 2:
                    return do_modify_uri(ctx, args[0], args[1])

                Notify(ARG_ERROR)
                return False

            elif operation == 'setName':
                if len(args) == 1:
                    return do_set_config(ctx, 'name', args[0])

                Notify(ARG_ERROR)
                return False

            elif operation == 'setSymbol':
                if len(args) == 1:
                    return do_set_config(ctx, 'symbol', args[0])

                Notify(ARG_ERROR)
                return False

            elif operation == 'setSupportedStandards':
                if len(args) >= 1:
                    supported_standards = ['NEP-10']
                    for arg in args:
                        supported_standards.append(arg)

                    return do_set_config(ctx, 'supportedStandards',
                                         Serialize(supported_standards))

                Notify(ARG_ERROR)
                return False

        else:
            Notify(PERMISSION_ERROR)
            return False

        Notify('unknown operation')

    return False
示例#21
0
def IsFromContract():
    callerHash = GetCallingScriptHash()
    entryHash = GetEntryScriptHash()
    if callerHash != entryHash:
        return True
    return False