Difference Between transfer() and transferFrom() in ERC20 Token contract

Difference Between transfer() and transferFrom() in ERC20 Token contract

In this article, you will learn about the difference between the transfer method and transferFrom() method in the ERC20 Token contract.

transfer method:

function transfer(address _to, uint256 _value) public returns (bool success)

transfer(address _to, uint256 _value) transfers _value tokens from the senders account to the _to address and fire a Transfer event.

If the sender address does not have _to tokens, then a revert message is thrown. If 0 tokens are transferred, then it MUST be treated as normal transfer and fire the Transfer event.

If you want to transfer tokens by yourself. then use transfer()

Example:

A: 10 tokens, B: 0 tokens, A wants to send 2 tokens to B.

transfer method invoked by A → transfer(B_address*, 2)

A: 8 tokens, B: 2 tokens

transferFrom method:

function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)

transferFrom(address _from, address _to, uint256 _value) transfers _value tokens from the _from address to the _to address. transferFrom() is used for Withdraw flow, allowing contracts to transfer tokens on your behalf. In order to use this, you need to approve the spender contract to withdraw tokens from your address. This can be done using approve() method.

approve method:

function approve(address _spender, uint256 _value) public returns (bool success) approve(address spender, uint256 value) allows the spender address to transfer tokens multiple times until the value limit is reached.

Example :

A: 10 tokens, B: 0 tokens, A wants to send 2 tokens to B.

Approve method invoked by A → approve(contract_C_address, 2)

transferFrom method invoked by Contract C → transferFrom(A_address, B_address, 2)

If you want to see an example of withdrawal flow, you can have a look at this article.