0

I've found a few old posts that ask a similar question to this (see e.g. Requiring a specific type of token in smart contract) however i'm a bit confused how this relates to some other posts i've seen about how best to transfer tokens.

What i want to do is have a function in a smart contract that expects to recieve some amount of a specific token and will change some state or perform some other action if it is present, i.e. something like :

function do_a_thing(int amount_of_token) public {
        //check if token is the right type
        state = new_state;
        // do something else
    }

When reading online i have seen posts about how one should use the 'call' function to transfer, rather than transfer/receive, i've also seen things about 're-entry attacks'.. sufficed to say I am somewhat confused about the right way to go about this!

Any help would be appreciated, as would any suggestions for up to date guides on how to do interesting things with smart contracts.

Many Thanks

1 Answer 1

1

Since tokens themselves are contracts, you cant really send tokens at the same time as making a contract call, since the call to transfer tokens is also a contract call. You essentially have 2 options because of this:

  1. Check if your contract is holding more tokens than it remembers holding, and assume that the new tokens are from the user, who would need to transfer the tokens ahead of time. This should only be done if the caller is another smart contract and can immediately execute the function to "register" the tokens. This is how uniswap lp tokens work, essentially skimming the top of the pool to see if there are any new tokens and doing actions based on that. I do not recommend trying to do this.

  2. The most common way to handle this, the user first approves your contract to spend tokens on their behalf using the approval function of tokens. Your contract then transfers the users tokens from the user to itself, using the transferFrom function of the token. Your contract spends the users tokens on their behalf by transferring them from the user to itself, and the user must give permission for this ahead of time by approving your contract.

1
  • Thanks, i've seen that the ERC777 standard allows for the approve/transferfrom to essentially happen in one go by using a receive hook which essentially calls a function when it receives the required token. I've not been able to find any parse-able examples of a simple 'hello world' style smart contract that implements this (i.e. upon receipt of payment it just calls a hello world function saying how much was sent). Is this something you are familiar with? Commented May 20, 2022 at 20:48

Your Answer

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

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