Using approve to allow transfer of ERC20 tokens in a contract

:1234: Code to reproduce

pragma solidity ^0.6.0;
 import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
 import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol";
contract Trust { 
   
  using SafeMath for uint256;
  uint256 y=10;
  IERC20 public token;
  function q (IERC20 _token)public{
      _token.approve(msg.sender,y);
      _token.transferFrom(msg.sender,address(this),y);
  }
}

transact to Trust.q errored: VM error: revert. revert The transaction has been reverted to the initial state. Reason provided by the contract: “ERC20: transfer amount exceeds allowance”. Debug the transaction to get more information.

1 Like

Hi @1118,

Welcome to the community :wave:

The reason why the transaction is reverting is because in the approve you are setting an allowance for the msg.sender to spend but then you are attempting to transferFrom the msg.sender to the contract and unless the msg.sender has set a high enough allowance, then this will fail.

For a contract to transfer tokens, first the holder of the tokens would need to approve an allowance for the contract for the amount you want to spend.

I recommend looking at the following: Example on how to use ERC20 token in another contract

1 Like

Hi @1118,

Just checking that you were able to resolve the issue?

1 Like

To solve thanks !

1 Like