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); } Commented 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. Commented Nov 6, 2022 at 10:34
  • How can i do that? Commented Nov 6, 2022 at 11:44
  • can u provide me with some sample code Commented Nov 6, 2022 at 11:44
  • or can u edit in the provided code and comment it? Commented 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);
    }
1
  • You can't do that. It will revert because of "insufficient allowance". Has to be done in a separate transaction.
    – Chev_603
    Commented Mar 25, 2023 at 23:19

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