1

I'm calling a function of one of my contracts with the same parameters twice in a row (locally). The gas spent by the first transaction is 178,310, while the gas spent by the second transaction is only 156,710.

let result = await instance.myFunction(amount,list,rates,tokens,{from:accounts[1],value:web3.utils.toWei("20","ether")})

The difference is exactly 21,600 gas, I'm wondering if it has anything to do with the gas cost of a value transfer?

Thanks

1 Answer 1

2

The number just happens to be similar to the minimum transaction cost of 21000, it's not related to that.

There are various things that may make a second call have different gas cost. The most typical one is storage of data: changing a value of a previously non-set variable to non-zero costs more than setting it again from non-zero to non-zero. Here's some more information about that: Why does zero to non-zero in storage take higher gas?

Otherwise, there may be a bunch of reasons: for example different code paths based on whether some data is already stored or not, or even calls to external contracts.

2
  • Thanks Lauri. As an indication, my code doesn't modify any storage and always follow the same flow (since I call it immediately after the first call with the same parameters, and no storage is modified). I'm wondering, could it be because the first call is the first call EVER to any function on the contract and solidity does some kind of set up, maybe related to initializing the constructor (my contract does initialize a couple storage variables in the constructor) or something like that? Thanks again
    – Hiperfly
    Jun 28, 2021 at 6:58
  • 1
    The constructor is only called when the contract is deployed, so it's not related to that. But impossible to say what the reason is without seeing the code. Jun 28, 2021 at 8:00

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.