2

How does one call an entrypoint of an existing contract using SmartPy?

For example, I'd like to be able to write a contract that calls the getBalance method of the existing ETHtz FA1.2 contract and stores the return value in local state.

In other words, I'd like to complete this code:

import smartpy as sp

class MyETHtzBalanceContract(sp.Contract):
    def __init__(self):
        self.init(num_ethtz = 0)

    @sp.entry_point
    def set_balance(self, ethtz_holder_address):
        # The address of the ETHtz FA1.2 contract.
        ethtz = sp.address("KT19at7rQUvyjxnZ2fBv7D9zc8rkyG7gAoU8")
        # How do I get this value for account `ethtz_holder_address`?
        # Note the ethtz contract defines a `getBalance` entrypoint of type
        # `(pair %getBalance (address :owner) (contract nat))`.
        self.data.num_ethtz = ...

BTW, I'm using the SmartPy web IDE.

Thanks!

1 Answer 1

2

The getBalance entrypoint is a view entrypoint that requires a parameter of type pair address (contract nat). ETHtz was written back when on-chain read functions were not available on Tezos, so a callback was required to retrieve values from another contract.

class ETHtzBalance(sp.Contract):
    def __init__(self):
        self.init(
            ethtz_bal = sp.nat(0),
            ethtz_address = sp.address("KT19at7rQUvyjxnZ2fBv7D9zc8rkyG7gAoU8")
        )
    
    @sp.entry_point
    def set_balance_callback(self, balance):
        sp.set_type(balance, sp.TNat)

        sp.verify(sp.sender == self.data.ethtz_address, "Not authorised")

        self.data.ethtz_bal = balance
    
    @sp.entry_point
    def set_balance(self, ethtz_holder_address):
        c = sp.contract(
            sp.TPair(sp.TAddress, sp.TContract(sp.TNat)), 
            self.data.ethtz_address, 
            "getBalance"
        ).open_some()
        sp.transfer(
            sp.pair(ethtz_holder_address, sp.self_entry_point("set_balance_callback")), 
            sp.tez(0), 
            c
        )    

Be careful about the SENDER check in the callback whenever you use a view function.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.