ERC20 Approve function

Ashish Babar
2 min readJun 19, 2020

What is this approve and transferFrom ? So I wanted to share my understanding regarding usage of these functions in ERC20 standards based Token for Ethereum Platform.

We’ll be covering

  1. Approve Function.
  2. TransferFrom and BurnFrom Function
  3. ApproveAndCall Function.
  4. Additional Information.

Approve Function:

This feature is used for approving tokens to be used by spender. It allows spender to either transfer the tokens or burn those tokens from Approver. The amount is added in allowance against approver and spender:

Eg. Alice calls approve(bob,200) will result in _allowance[alice][bob]=200.

Alice is able to approve tokens from his balance to Bob.

TransferFrom and BurnFrom function

Spender can now use allowed tokens from approvers balance using below two functions:

  1. transferFrom function
  2. burnFrom function

1. transferFrom function:

In the below example we can see, Bob can use transferFrom function to transfer approved tokens from alice’s balance.

Eg. Bob (with 0 balance) calls transferFrom(alice,bob,100) will result in

  1. _allowance[alice][bob]=100.
  2. balanceOf[bob]=balanceOf[bob]+100.

2. burnFrom:

In the below example we can see, Bob can also burn approved tokens from alice’s balance.

Eg. Bob calls burnFrom(alice,100) will result in

  1. _allowance[alice][bob]=100.
  2. totalSupply=totalSupply-100.

Bob can either transfer those tokens or can burn those tokens.

Note: burnFrom is an additional feature which is not mandatory in ERC20 standards.

ApproveAndCall function

ApproveAndCall function is specifically used for notifying third party service contracts about approved tokens. Approver can approve required tokens against service contract and Service contract can then call tranferFrom function (Ideally) to get approved tokens from approver.

Service contract can retrieve approved tokens after receiving receivedApproval from token contract.

Note: appoveAndCall is an additional feature which is not mandatory in ERC20 standards.

Additional Information:

Service contract needs to implement receivedApporval Function to get notified by approveAndCall. Below is code snippet for the same in which service contract can call transferFrom function of ERC20 token contract to get tokens and then it updates Payers balance.

Code Snippet

function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public {    Token t = Token(_token);    require(t.transferFrom(_from,  this, _value));    payers[_from] += _value;    ReceivedTokens(_from, _value, _token, _extraData);}

Note: Service contract implementation is an additional feature which is not mandatory in ERC20 standards.

--

--

Ashish Babar
0 Followers

Software Developer, Passionate about blockchain