0

The approve function code in my ERC20 contract is below:

function approve(address _spender, uint256 _amount) public returns (bool success) {
    allowed[msg.sender][_spender] = _amount;
    Approval(msg.sender, _spender, _amount);
    return true;
  }

I tested approval gas cost estimation for multiple times in Rinkeby testnet, found that the estimation results will change like bellow:

Test configuration:

  1. Account1 approve account2 to spend erc20 token, account2 never spend the allowance after any approval;
  2. Before first time approval,account1 never approve account2 to be able to spend token from its balance;
  3. Before first time approval,account2 has no any balance of that token type.

First time: Account1 approves account2 to spend 1000 tokens

gas estimation:44895

Second time: Account1 approves account2 to spend 1000 tokens

gas estimation:25695

Third time: Account1 approves account2 to spend 1000 tokens

gas estimation:25695

Fourth time: Account1 approves account2 to spend 5000 tokens

gas estimation:29907

Fifth time: Account1 approves account2 to spend 1000 tokens

gas estimation:29895

Get confused by these results, how to understand and explain it? Thanks.

  • 1
    Changing zero to non-zero is the most expensive, changing non-zero to non-zero is less expensive, and changing non-zero to zero actually gives you some gas back. – goodvibration Jan 20 at 8:18
1

Gas cost of writing to the storage depends on what current and new values are. The most expensive (20000 gas) is to write a non-zero value into a slot, whose current value is zero (your first case). Changing non-zero value to another non-zero value costs less (5000 gas), as in your fourth and fifth cases. Leaving slot value unchanged is virtually free (second and third cases).

The above should explain most of the difference. Small deviations could be explained by the fact that zero bytes in transaction data cost less (4 gas) than non-zero bytes (68 gas).

See Appendix G of Ethereum Yellow Paper for details.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.