ERC20 transfer not working

When i tried to use the transfer() i get the error revert ERC20: transfer amount exceeds balance but when i use transferFrom() with little changes, i don’t get the error. What could be the issue, please?

Attached is a screenshot to show both implementations.

Using TransferFrom

Using normal transfer

Please, help!

1 Like

Hi @sirphemmiey,

When an ERC20 token holder interacts with another contract using the token, two transactions are required:

  1. The token holder calls approve to set an allowance of tokens that the contract can use. (assuming an OpenZeppelin ERC20 implementation can use increaseAllowance)
  2. The token holder calls the contract to perform an action and the contract can transferFrom an amount of tokens within the set allowance.

This is why the transferFrom case works.

transfer moves tokens from the caller’s account.

This is why this fails as your contract token balance is less than what you are trying to transfer, as the caller’s account is your contract and not the token holder (end user account initiating the transaction).
Moves amount tokens from the caller’s account to recipient.

@abcoathup Aha, i see my silly mistake.
Thanks for the detailed explanation.

One more thing:
Now that both operations are working, is/are there any edge(s) that transferFrom has over transfer and vice versa looking at it from a security perspective or in any other perspective you might think?

1 Like

Hi @sirphemmiey,

When using ERC20 tokens with a contract to “do stuff”, you need to use the approve and then transferFrom pattern, requiring two transactions.

If the ERC20 token is an OpenZeppelin implementation then you should use increaseAllowance

Alternatively you could look at creating ERC777 tokens (no need to do approve and transferFrom in two separate transactions). See the documentation for details:

As far as security, smart contracts should be appropriately tested and audited. For testing, see the following guide: Test smart contracts like a rockstar

Nice one.

Thank you.

1 Like