0

I have a couple of different smart contracts (Beacon Proxy etc) that can receive ERC20 tokens and performs various calls (for implementation and admin) and then moves all the ERC20 balance to a provided destination.

I've been trying to find a way to save on the gas required to perform the functions (and struggling) but one thing I've noticed is that the same function call is cheaper after it's been called.

I've been trying to investigate (and google search) for answers but I'm unable to piece it together.

Just wondering if someone would be able provide some reasons as to why the gas cost is reduced?

Is it to do with sload?

Example of the gas cost on a Local Hardhat forked from Mainnet using USDC.

First call
┌──────────┬─────────┐
│ (index)  │ Values  │
├──────────┼─────────┤
│ moveGas1 │ '83979' │
└──────────┴─────────┘
Second call
┌──────────┬─────────┐
│ (index)  │ Values  │
├──────────┼─────────┤
│ moveGas2 │ '66879' │
└──────────┴─────────┘
1
  • The question has been answered here
    – Gbolahan
    Commented Oct 21, 2022 at 12:23

2 Answers 2

1

Welcome to ES! :) the SSTORE (write data to storage) opcode costs 20000 gas when assigning a non-zero value to a previously zeroed out slot, and 5000 in every other cases. I can't say for sure without looking at your code, but that's very probably why your second call is less expensive :)

2
  • Looking at the output of debug_traceTransaction there are 2 SSTORE. One ` "gasCost": 20000` and "gasCost": 2900. And tyhe second is 2 SSTORE of "gasCost": 2900. I think that might be it!! Thanks
    – Kitch205
    Commented Oct 21, 2022 at 13:25
  • 2900 means that the slot has already been accessed in the transaction. Look up hackmd.io/@fvictorio/gas-costs-after-berlin for more info (:
    – Foxxxey
    Commented Oct 21, 2022 at 13:46
1

Reusing previously used storage slots can indeed save gas.

For example, reading a previously read value from storage costs 100 gas instead of 2100. Also, a previously touched storage location uses less gas when written to. There are additional gas refunds when a previously filled storage location is emptied.

You should be able to use the evm opcodes calculator to find out how you ended up with the gas costs in your particular example.

1
  • Thanks for that, definitely put me on the right path. And thanks for the evm resource!
    – Kitch205
    Commented Oct 21, 2022 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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