2

I would like to understand why, approving an ERC20 token inside a contract function doesn't work.

Suppose that I create a function in my contract, that calls an approve for an ERC20 token for the users in this way:

contract MyContract {
  function approveToken(address token) external {
    IERC20(token).approve(address(this), 1000);
  }
}

Is it right to say that:

  • the msg.sender of the transaction is the user who will be prompted to approve the transaction

  • the msg.sender of the approve function of the ERC20 token will not be that user, but the contract address

  • the effect of the approve will be to approve that ERC20 token on the following parameter: both spender and approver will the be contract address of my contract. So it's like we are telling the ERC20 token to have this:

    allowances[CONTRACT_ADDRESS][CONTRACT_ADDRESS] = 1000.

Thus, to approve my contract to spend token for some tokens' holder, the msg.sender in the approve function of ERC20 should be the token holder, hence the token holder should call the function directly on the client side without passing through a contract because the contract can't impersonate that user.

Is my understanding correct?

2 Answers 2

4

Thus, to approve my contract to spend token for some tokens' holder, the msg.sender in the approve function of ERC20 should be the token holder, hence the token holder should call the function directly on the client side without passing through a contract because the contract can't impersonate that user.

You are correct on every point !

The ERC-20, ERC-721 will only allow a holder to directly approve a spender for obvious logic and security reasons.

0

Correct!. A contract cannot run an approved function within itself. Since the msg.sender now becomes the smart contract's address instead of the account's address. You're understanding is correct.

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.