Gas refunds are provided when clearing storage or calling SELFDESTRUCT
on contracts.
The Yellow Paper mentions that refunds are "being capped up to a maximum of half…". What exactly is this "half" and the other components that sum up to a refund? Preferred answer will explain with a specific example (since the Yellow Paper has the definitions).
What are the limits? What attacks would have been possible if refunds were not limited?
Best Answer
The following opcodes trigger a refund
SELFDESTRUCT
SSTORE[x] = 0
(i.e. deletion)SELFDESTRUCT
refunds24.000
andSSTORE
clear refunds15.000
gas. The accumulated refund can not exceed half the gas used for the current context (i.e. the initial call).Let's take the following example:
Current state of the contract's storage
And the following execution
This would result in the following gas sum
21000 + 3 + 3 + 5000
(tx_gas + push_gas + push_gas + sstore_clear_gas
). The total amount of which may be refunded is thereforgas_sum / 2
(13.003
). The amount refunded is15.000
but since this clearly exceeds the maximum of13.003
we cap it to that amount.And the reason why we cap this is so that the miner does not end up paying for the actual execution of the contract :-)
EDIT:
If the refunds weren't capped we would run in to 2 issues:
It would be disincentive to run these type of transactions if they weren't capped because at the end of the execution the refund is reduced from the amount that which a miner gets (i.e.
gasUsed * tx.price
). Capping at say thegasUsed
would render the execution useless to the miner (it doesn't get rewarded for running the contract). This brings us to the second point; having a higher refund than the gas used would therefor end up in a negative gas usage and would therefor have to be reduced from the miner's balance. No miner in their right mind is going to pay you for execution your call.