Understanding the refund logic in ReentrancyGuard

If we used 0/1 values, setting the _status variable from 0 to 1 would cost 20k gas, and resetting it to 0 at the end of the transaction will cost 100 gas with a 19.9k refund. If the full refund is realized this would amount to only 200 gas. However, refunds are capped at 1/5th of total transaction cost (EIP-3529), so a transaction that uses this version of ReentrancyGuard has to cost around 100k gas in order to actually realize the optimal cost, and this is assuming there are no other refunds in that transaction. Note that if the transaction costs less than 100k gas, the full refund is not realized and the cost of using the reentrancy guard may be closer to 20k gas than to 200.

For a general purpose utility like ReentrancyGuard, we can't assume that a transaction costs more than 100k gas. If instead we use 1/2 values, setting the flag costs 2.9k gas, resetting it costs 100 gas with 2.8k refund. The final amount if the full refund is realized is still 200 gas, but the refund is a lot smaller now so the total transaction cost doesn't need to be as high to realize it.

(This is obviously an EVM inefficiency, but it will be fixed with transient stoage!)

1 Like