If a smart contract puts a zero in a storage box, then later puts a zero in the same box again, how much gas money does it get back for these two actions?
The amount of gas money a smart contract gets back depends on the initial state of the storage box before the first action. Gas is a unit of computational effort required to execute operations on the Ethereum blockchain, paid by the transaction sender. Gas refunds are mechanisms that return a portion of gas spent when certain operations reduce the blockchain's state size, primarily by clearing storage slots. These refunds are collected during the transaction and applied at the end, with a total refund cap of 50% of the transaction's total gas consumption.
A storage box, also known as a storage slot, is a 32-byte permanent data location within a smart contract's state. Writing to a storage slot uses the `SSTORE` operation, which has varying gas costs and potential refunds based on the current and new values of the slot, and whether the slot has been accessed previously in the current transaction (a 'warm' access).
Let's analyze the two actions:
Scenario 1: The storage box initially contained a non-zero value (e.g., 100).
1. First action: The smart contract 'puts a zero in a storage box'.
Since the box changes from a non-zero value to zero, this `SSTORE` operation costs 5000 gas.
Crucially, this action generates a gas refund of 15000 gas. This refund is given because clearing a storage slot (setting a non-zero value to zero) reduces the overall state size of the blockchain. This 15000 gas is queued to be returned at the end of the transaction.
2. Second action: The smart contract 'later puts a zero in the same box again'.
At this point, the storage box already contains zero due to the first action.
Writing a zero to a storage slot that already contains zero is considered a 'warm' access where the value does not change. This specific `SSTORE` operation costs 100 gas.
This action generates 0 gas refund because it does not change the state of the storage box or reduce the blockchain's state size further.
In this scenario, for these two actions, the total gas money the smart contract gets back is 15000 gas (from the first action), assuming the overall transaction's gas usage allows for the refund to be fully applied within the 50% cap.
Scenario 2: The storage box initially contained zero.
1. First action: The smart contract 'puts a zero in a storage box'.
Since the box already contains zero and remains zero, this 'warm' `SSTORE` operation costs 100 gas.
This action generates 0 gas refund, as no state change occurs that reduces storage size.
2. Second action: The smart contract 'later puts a zero in the same box again'.
The box still contains zero.
This 'warm' `SSTORE` operation costs 100 gas.
This action also generates 0 gas refund.
In this scenario, for these two actions, the smart contract gets back 0 gas, as neither operation generated a refund.