All writing

3 min

The Guard That Protects You Is Also the Guard You're Paying For

A reentrancy guard costs gas on every guarded call, and that cost is worth paying. The gas you can actually save lives somewhere else: in what a contract writes to storage and how many transactions a user has to send.

Contents

A technique note, not a case study: the costs below are the EVM's published prices, not measurements from a project of mine.

TL;DR

  • A reentrancy guard adds a small, fixed gas cost to every guarded call. Keep it — and don't treat it as the only defense, because checks-effects-interactions is what still holds when someone forgets the modifier.
  • The expensive line items on Ethereum are storage writes and per-transaction overhead, not computation. Storing a hash instead of content, and batching actions into one transaction, attack exactly those.
  • The optimization order is inverted from most backends: assume storage is the cost until proven otherwise.

You are writing a contract that moves value, and gas prices are high enough that users notice every extra write. The tempting place to look for savings is the safety code, because it is the code that does nothing on the happy path. That is the wrong place to look.

The safety half: ordering first, modifier second

Reentrancy happens when a contract calls an external address — a token, a user's fallback function — before updating its own state. The callee calls back in, sees a balance that has not been decremented yet, and withdraws again.

solidity
// Vulnerable: interaction before effect
function withdraw(uint256 amount) external {
    require(balances[msg.sender] >= amount);
    (bool ok, ) = msg.sender.call{value: amount}("");
    require(ok);
    balances[msg.sender] -= amount;
}

// Checks, effects, then interactions
function withdraw(uint256 amount) external nonReentrant {
    require(balances[msg.sender] >= amount);   // check
    balances[msg.sender] -= amount;            // effect
    (bool ok, ) = msg.sender.call{value: amount}("");  // interaction
    require(ok);
}

OpenZeppelin's nonReentrant blocks the re-entry itself. Checks-effects-interactions makes re-entry harmless even where the modifier is missing, because the state is already correct before any external call. Use both.

The guard's cost is deliberately small. ReentrancyGuard stores its status as 1 and 2 rather than false and true, so the lock never writes a zero slot to non-zero — the most expensive kind of storage write. On chains with EIP-1153, ReentrancyGuardTransient keeps the lock in transient storage, which is cheaper still. Either way, this is a constant you pay for correctness, not a place to hunt for savings.

The gas half: storage is the expensive resource

The EVM's price list explains where the savings are:

OperationGas
Base cost of any transaction21,000
SSTORE, zero → non-zero slot20,000 (plus a cold-access surcharge the first time a transaction touches the slot)
Calldata, per non-zero byte16
TSTORE / TLOAD (transient storage)100

Two techniques follow directly from that table.

Store a fixed-size digest, not the content. A string written to storage costs a slot per 32 bytes. Putting the content on IPFS and storing only its hash costs one slot, regardless of how large the content is. The contract can still verify content against the hash; it just stops paying to hold it.

Batch actions into one transaction. Every transaction pays the 21,000 base cost before its logic runs. If a user needs five actions, five transactions pay it five times. A batch function pays it once, so the saving grows with every action folded in.

One more thing users pay for: a transaction that reverts still costs the gas it used up to the point of failure. Estimates from eth_estimateGas simulate against current state, which can change before the transaction lands, so re-estimating right before signing and showing a range rather than a single number protects users from paying for a failed attempt.

The transferable part

Pay for safety, hunt in storage. The guard is a fixed cost that buys correctness; storage writes and transaction count are the variable costs that grow with usage. Optimize the variable ones.

Know which way your platform's cost model points. On most backends, storage is cheap and compute is what you tune. On Ethereum the order flips, and the habits that serve you everywhere else will point you at the wrong code.

Share this note

Comments

— responses

0/2000

Loading comments…