0

I am using the following code to transfer some erc20 tokens with token address = token and amount being amount but every time I deploy it and try to transfer an erc20 token it is showing me the following error

Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? execution reverted: ERC20: insufficient allowance { "originalError": { "code": 3, "data": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001d45524332303a20696e73756666696369656e7420616c6c6f77616e6365000000", "message": "execution reverted: ERC20: insufficient allowance" } }

CODE:

function depositERC20tokens(address token, uint amount) public{
 

       IERC20 _token = IERC20(token);
        address me = address(this);
        uint256 allowance = _token.allowance(msg.sender,me);
        _token.approve(me,amount);
        _token.transferFrom(msg.sender, me, amount);
    }
7
  • function depositERC20tokens(address token, uint amount) public{ IERC20 _token = IERC20(token); address me = address(this); uint256 allowance = _token.allowance(msg.sender,me); _token.approve(me, _token.totalSupply()); _token.transferFrom(msg.sender, me, amount); } Nov 6, 2022 at 10:18
  • 1
    Heyy, You are approving the me address which is the contract address. But do you know that when it will call the function then the msg.sender is the contract from which you are calling so basically you are approving the contract to spend tokens of the contract itself. You need to approve the contract from the wallet address first, because it is the sender. Nov 6, 2022 at 10:34
  • How can i do that? Nov 6, 2022 at 11:44
  • can u provide me with some sample code Nov 6, 2022 at 11:44
  • or can u edit in the provided code and comment it? Nov 6, 2022 at 11:44

1 Answer 1

1

your _token.approve(me,amount) is wrong, it will set allowance of your contract to spend token, while you need to set allowance of msg.sender to spend token.

function depositERC20tokens(address token, uint amount) public{
        IERC20 _token = IERC20(token);
        address me = address(this);
        address receiver = msg.sender;
        // uint256 allowance = _token.allowance(msg.sender,me);
        // _token.approve(me,amount);
        _token.approve(receiver, amount);
        _token.transferFrom(receiver, me, amount);
    }

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