i am trying to code a smart contract which takes the tokens of the player who enters.

function enterToken(address token, uint amount) public {
        uint _amount = amount * 10 ** 18;
        IERC20 token_ = IERC20(token);
        require(token_.approve(address(this), _amount), 'Approve failed.');
        require(token_.transferFrom(msg.sender, address(this), _amount), 'Transfer failed.');

I have literelly no clue why it is not working, maybe someone can help me out.

Thank you!

  • It does not work like that, when u are calling token_.approve then the contract is the one who call approve and not the sender. So what u are doing is „like“ approving your self to transfer your token :)
    – Majd TL
    Jun 20, 2021 at 18:14

1 Answer 1


Your problem is that you can't do approve and transferFrom in the same transaction.

The approve has to be performed by the token owner. So basically the token owner calls the token contract's approve function directly to allow your contract to withdraw the tokens. Let's call your contract contractA.

After that, anyone (typically the user) initiates a transaction with contractA where the transferFrom is used. Because the user had approved for contractA to withdraw some amount of his tokens, contractA can transfer those with the transferFrom function.

If your example code worked, it means the contract could withdraw the user's tokens without his explicit approval. So basically any malicious contract the user calls could take his tokens. So, for security reasons, the user first has to explicitly add allowance for a specific contract to withdraw his tokens.

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.