Approve ERC20 token inside a contract function

erc-20erc-20-approve

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?

Best Answer

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.

Related Topic