Solidity – Resolving Transaction Failure After Contract Self-Transfer in ERC-20

erc-20msg.sendersoliditytransfer

I have this line in some function in an ERC721 contract:

IERC20 instance = IERC20(token_address);
instance.transfer(address(this),1);

And when deploying the contract I make sure the caller of the function gets at least one of those ERC20 tokens:

ERC20Token[-1].mint(account2,1,{"from":account1})

Before deploying the ERC721 contract and calling this specific function with account2.

The error I get is:

"Gas estimation failed: 'execution reverted: ERC20: transfer amount exceeds balance'. This transaction will likely revert. If you wish to broadcast, you must set the gas limit manually."

After approving the ERC721 contract to spend some ERC20 from account2 it works.

When approving inside this specific question it doesn't work..

(instance.approve(address(this),1))

the msg.sender is account2.. What is going on?

Thanks!

Best Answer

The transfer function in ERC20 is for transferring tokens from the current contract address to some other account, so your line of code is trying to transfer 1 unit of the token from the contract to itself.

What you are most likely looking for is transferFrom(sender, recipient, amount) which is a more general form of transfer, allowing your contract to send tokens from accounts that have approved your contract to do so.

In your example, it would be:

IERC20 instance = IERC20(token_address);
instance.transferFrom(msg.sender, address(this), 1);

You will not be able to call approve on behalf of other users from your contract, though - this will always be something the user has to do before interacting with your contract.