What is a reentrancy guard in smart contracts?
A reentrancy guard is a lock that a contract sets when a guarded function starts and clears when it ends, so any call that tries to enter a guarded function in between reverts. It is usually written as a nonReentrant modifier, and it stops a callback made during an external call from coming back into the functions that carry it.
How does a reentrancy guard work?
The guard is one variable with two states. On entry the modifier checks it reads 'not entered', sets it to 'entered', runs the function and resets it. Because every guarded function shares the variable, OpenZeppelin notes that functions marked nonReentrant can't call one another (OpenZeppelin).
A nonReentrant modifier on a transient lock (illustrative, not audited code) GuardedBank.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
contract GuardedBank {
mapping(address => uint256) public balances;
bool private transient locked; // cleared at the end of every transaction
modifier nonReentrant() {
require(!locked, "reentrant call");
locked = true;
_;
locked = false;
}
function deposit() external payable nonReentrant {
balances[msg.sender] += msg.value;
}
function withdraw(uint256 amount) external nonReentrant {
balances[msg.sender] -= amount;
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "send failed");
}
}
Solidity 0.8.28 fully supports transient state variables of value types (Solidity), which live in EIP-1153 transient storage, discarded after every transaction and named in the EIP as a fit for reentrancy locks. OpenZeppelin ships ReentrancyGuardTransient since v5.1 and marks its storage-based ReentrancyGuard for replacement by it in v6.0 (OpenZeppelin).
What should you check when a contract uses one?
- Every function that reads or writes the shared state carries the guard, including those that never send funds.
- A callback can't reach another contract of the protocol that trusts the half-updated state of this one.
- Views that other protocols read revert while
_reentrancyGuardEntered()is true, or the state is final before any call. - The chain supports EIP-1153 if the lock is transient.
- A test re-enters each guarded function and expects a revert.
Pair the guard with checks-effects-interactions: finish the state update before the external call, and lock the functions that share that state.
FAQ
Does nonReentrant stop read-only reentrancy?
No, because read-only reentrancy goes through a view function, which a guard on state-changing functions doesn't cover. Make views revert while the guard is entered, or finish every update before an external call.
Sources
- Utilities API: ReentrancyGuard and ReentrancyGuardTransient, OpenZeppelin checked 3 December 2026
- Solidity 0.8.28 release announcement, Solidity team checked 3 December 2026
- EIP-1153: Transient storage opcodes, Ethereum Improvement Proposals checked 3 December 2026