
Solidity Reentrancy Guards: Preventing Reentrant Execution in State-Changing Functions
What reentrancy is and why it matters
A function is reentrant when it can be entered again before the previous invocation completes. In Solidity, this often happens through external calls such as:
calltransferin older codebases- token callbacks
- hooks in ERC-777 or similar standards
- arbitrary external contract calls
The danger is not the call itself, but the fact that the callee may call back into your contract while your internal state is still inconsistent.
A classic failure mode
Consider a vault that lets users withdraw ETH:
function withdraw() external {
uint256 amount = balances[msg.sender];
require(amount > 0, "Nothing to withdraw");
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "Transfer failed");
balances[msg.sender] = 0;
}
At first glance, this looks reasonable. But the external call happens before the balance is cleared. If msg.sender is a malicious contract, it can call withdraw() again during the transfer and receive the same funds multiple times.
The core issue is that the contract exposes a temporary inconsistent state to external code.
The checks-effects-interactions pattern
Before discussing explicit guards, it is worth understanding the foundational pattern that prevents many reentrancy bugs.
The rule
- Checks: validate inputs and permissions.
- Effects: update internal state.
- Interactions: call external contracts last.
Applied to the previous example:
function withdraw() external {
uint256 amount = balances[msg.sender];
require(amount > 0, "Nothing to withdraw");
balances[msg.sender] = 0;
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "Transfer failed");
}
Now, if the external call re-enters withdraw(), the stored balance is already zero. The second call fails.
Why this is necessary but not always sufficient
Checks-effects-interactions is a strong baseline, but it does not eliminate every reentrancy risk:
- A function may call multiple external contracts.
- A callback may re-enter a different function that shares state.
- Cross-function or cross-contract reentrancy can still occur.
- Complex accounting may require more than one state update before interaction.
That is where reentrancy guards become useful.
Reentrancy guards: the mutex approach
A reentrancy guard is a simple lock that prevents a function from being entered while it is already executing. This is often implemented as a state variable that tracks whether the contract is “entered.”
Minimal custom implementation
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Vault {
mapping(address => uint256) private balances;
bool private locked;
modifier nonReentrant() {
require(!locked, "Reentrant call");
locked = true;
_;
locked = false;
}
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw() external nonReentrant {
uint256 amount = balances[msg.sender];
require(amount > 0, "Nothing to withdraw");
balances[msg.sender] = 0;
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "Transfer failed");
}
}
This pattern blocks nested execution of any function protected by nonReentrant.
How it works
- The first call sets
locked = true. - Any nested call to a guarded function fails immediately.
- Execution completes and resets the lock.
This is a practical defense when you cannot fully eliminate external calls or when multiple functions share sensitive state.
When to use a reentrancy guard
A guard is most useful when a function:
- transfers ETH or tokens to an external address
- calls unknown or user-supplied contracts
- performs multiple state updates that must remain atomic
- exposes shared accounting that could be manipulated by callbacks
It is especially important in:
- vaults and escrow contracts
- staking and reward distribution systems
- AMM-like contracts
- NFT minting or redemption flows with callbacks
- protocols integrating arbitrary third-party contracts
When a guard may be unnecessary
If a function:
- only reads state
- does not call external code
- uses a fully internal accounting flow with no callbacks
then a guard may add unnecessary complexity. Security controls should be targeted, not blanket applied everywhere.
Guard placement strategy
A common mistake is protecting only one function while leaving related entry points open. Reentrancy often crosses function boundaries.
Example: shared state across functions
Suppose withdraw() is guarded, but claimReward() uses the same balance pool and is not guarded. A malicious callback may re-enter through claimReward() and still exploit the shared state.
To avoid this:
- protect all state-mutating functions that can be reached during an external call
- treat the lock as contract-wide, not just function-local
- review internal functions that are called by multiple public entry points
Practical rule
If a function can be reached from an external call path and it mutates shared state, assume it needs protection unless you can prove otherwise.
Comparing common defense techniques
| Technique | What it does | Strengths | Limitations |
|---|---|---|---|
| Checks-effects-interactions | Updates state before external calls | Simple, low overhead, widely applicable | Does not stop all cross-function or cross-contract reentrancy |
| Reentrancy guard | Blocks nested entry into protected functions | Strong, easy to reason about | Must be applied consistently; adds a storage write |
| Pull-based withdrawals | Users claim funds in a separate transaction | Reduces external call risk in core logic | More UX friction; still needs safe claim logic |
| Internal accounting only | Avoids external calls in sensitive paths | Very safe when feasible | Not always possible for real integrations |
In practice, robust contracts often combine checks-effects-interactions with a guard on the most sensitive functions.
A more realistic example: reward distribution
Imagine a staking contract that lets users claim accumulated rewards. The contract must compute the claimable amount, update accounting, and send ETH.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract StakingRewards {
mapping(address => uint256) public rewards;
mapping(address => uint256) public claimed;
bool private locked;
modifier nonReentrant() {
require(!locked, "Reentrant call");
locked = true;
_;
locked = false;
}
function accrue(address user, uint256 amount) external {
rewards[user] += amount;
}
function claim() external nonReentrant {
uint256 total = rewards[msg.sender];
uint256 alreadyClaimed = claimed[msg.sender];
uint256 claimable = total - alreadyClaimed;
require(claimable > 0, "Nothing to claim");
claimed[msg.sender] = total;
(bool ok, ) = msg.sender.call{value: claimable}("");
require(ok, "Payment failed");
}
receive() external payable {}
}
Why this is safer
- The claimable amount is derived from stored state.
- The contract records the claim before transferring ETH.
- The guard prevents nested claims during the transfer.
This is a good example of layered defense: state update first, then guarded interaction.
Common mistakes to avoid
1. Resetting the lock too early
The lock must remain active for the entire duration of the sensitive operation. If you unlock before the external call returns, the protection is ineffective.
2. Protecting only one entry point
If withdraw() is guarded but emergencyWithdraw() is not, an attacker may use the unguarded path during reentry.
3. Forgetting internal call paths
A public function may call an internal helper that performs an external interaction. The helper itself does not need a modifier, but the public entry point does.
4. Assuming transfer() is always safe
Older code relied on transfer() because it forwarded limited gas. That assumption is no longer a reliable security strategy. Modern Solidity code should not depend on gas stipend behavior as a primary defense.
5. Mixing external calls with complex accounting
If a function performs multiple calculations, updates several mappings, and then calls out, the state transition should be carefully ordered. If possible, split the logic into:
- compute
- commit state
- interact
Design guidelines for production contracts
Prefer simple state transitions
The fewer mutable variables involved in a sensitive function, the easier it is to reason about reentrancy safety. Avoid spreading accounting across many mappings unless necessary.
Minimize external calls inside core logic
If an external call is not essential, move it out of the critical path. For example, record a payout and let the user withdraw later.
Use explicit invariants
Ask what must always be true before and after the function runs. For example:
- a balance can only be withdrawn once
- total claimed rewards cannot exceed total accrued rewards
- a user cannot receive the same entitlement twice
If a reentrant call could violate an invariant mid-execution, protect the function.
Consider cross-contract interactions
If your contract calls another protocol, that protocol may call back into you indirectly. Reentrancy is not limited to direct ETH transfers.
Test with malicious receivers
A good test suite should include a contract that:
- receives ETH
- re-enters your target function
- attempts to exploit shared state
This kind of adversarial test often reveals issues that ordinary unit tests miss.
Gas and usability trade-offs
A reentrancy guard adds a storage read and write, so it is not free. However, the cost is usually small compared with the damage of a vulnerability.
| Approach | Gas overhead | Security benefit | Best use case |
|---|---|---|---|
| No guard | Lowest | None against reentrancy | Purely internal, no external calls |
| Checks-effects-interactions only | Low | Good baseline | Simple withdrawal or accounting flows |
| Reentrancy guard | Moderate | Strong protection | Sensitive state-changing functions |
| Pull payment architecture | Varies | Very strong structural safety | Payout-heavy systems |
The right choice depends on the contract’s risk profile, not just gas cost.
Practical checklist
Before deploying a contract that transfers value or calls external code, verify the following:
- State is updated before external interaction where possible
- Sensitive functions are protected by a reentrancy guard
- All related entry points are reviewed, not just one function
- External calls are minimized and isolated
- Tests include malicious callback behavior
- Accounting invariants remain valid under nested execution
If any item is uncertain, treat the function as reentrancy-sensitive.
Conclusion
Reentrancy is a structural risk in smart contract development, not just a bug in one function. The safest contracts reduce external interactions, update state before calling out, and use reentrancy guards when nested execution cannot be ruled out.
In practice, the best defense is layered: design for safe control flow, then enforce it with a guard where needed. That combination is simple, effective, and widely used in production Solidity systems.