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);
}
me
address which is the contract address. But do you know that when it will call the function then themsg.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.