5

I noticed that the same transfer() calls for a certain ERC20 token cost different gas-used:

Gas Used By Txn: 52595

https://etherscan.io/tx/0xa7c1639040725e92d3905cc6b8a4d4a3b21a3e23800c75950da682ce2043c274

Gas Used By Txn: 37595

https://etherscan.io/tx/0x34728b3f03d859eb701e0bfaf253033cf26d2e9b6be5562d7ab7f2d7518a84cb

I think the executions of transfer() should take extract same gas because only the parameters are different.

6

A low level explanation follows. If you transfer to a contract (an account with code), the code of the contract will be executed. The code is at a low level a sequence of EVM (Ethereum Virtual Machine) instructions. And every instruction has an associated gas cost. To troubleshoot the gas usage, you can refer to the detailed transaction traces:

These traces display each instruction executed by the EVM during the transaction. You can spot the difference at step 328. This is an SSTORE instruction, which costs 20000 gas for the first transaction, but only 5000 gas for the second transaction. Other then this, the two transactions execute the same instructions using the same gas value. And yes, the first transaction uses 15000 more gas, then the second:

52595 - 37595 = 15000

The question now is that why does the first SSTORE cost 20000 gas, but the second only 5000? You can refer to the Ethereum Yellowpaper, where the gas costs are defined: https://ethereum.github.io/yellowpaper/paper.pdf

20000: Paid for an SSTORE operation when the storage value is set to non-zero from zero.
5000: Paid for an SSTORE operation when the storage value’s zeroness remains unchanged or is set to zero.

So it seems, that the first transaction increases the size of storage (a zero value is set to non-zero), and the second transaction uses the same storage item (it does not increase the size of storage). Note, that a storage item with zero value is not stored, it does not increase the size of the state. That's why the first zero to non-zero change costs more gas, than a non-zero to non-zero or zero change.

If you want to check the logic which caused the difference, you can refer to the Solidity source code of the contract at etherscan and debug the transactions using Remix.

0

There are many possible reasons why transaction gas amount (or gasUsed) is not the same when calling the same function. At least:

1) The function modifies an array and the array has different amount of items in it than previously. Or other similar modifications.

2) The parameters cause different logic inside the function - maybe even calling different functions internally

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.