Reentrancy Attacks Explained: How They Work and How to Prevent Them
How reentrancy attacks work in Solidity, the cross-function, cross-contract and read-only variants, and which defences and tests cover each one.
In this guide
A reentrancy attack happens when a contract makes an external call before it has finished updating its own state, and the code it called uses that moment to call back in. The second call acts on balances, supplies or flags that are no longer true. The classic case drains a vault through one function, but the same flaw appears across functions, across contracts, in view functions that other protocols read, and in token transfers that notify the receiver.
Why reentrancy is possible
Calls between contracts are synchronous. When your function calls another contract, your code stops until the callee returns, and in the meantime the callee can do anything a normal caller can, including calling your contract again. The Solidity documentation says so without qualification: any interaction with another contract, and any transfer of Ether, hands control to that contract, which can call back before the interaction has completed.
Two conditions must hold at the same time:
- An external call reaches code the attacker controls: an ETH transfer, a token transfer with a receiver hook, or a call to an address a user supplied.
- Some state is not final at that moment: a balance paid out but not yet reduced, a supply that changed before the reserves did, a claim flag that is still false.
Every defence below removes one of the two.
ethereum.org's security guide gives the 2016 DAO hack as its example of a contract drained through reentrancy. Our smart contract security basics summarise the fork that followed.
Single-function and cross-function reentrancy
The textbook version re-enters the function that made the call.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
contract Vault {
mapping(address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
// Vulnerable: the balance is cleared after the external call
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;
}
}
An attacker contract deposits 1 ETH and calls withdraw. The vault sends 1 ETH, which runs the attacker's receive function, which calls withdraw again. The mapping still says 1 ETH, so the vault pays again, and the loop continues until the vault is empty.
Two fixes look sufficient and are not. The first is to send ETH with transfer or send, which forward only a small amount of gas. Slither's documentation notes that they do not protect from reentrancy if gas prices change, and they do nothing for calls to tokens or other contracts. The second is to put a guard on withdraw and stop there.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ReentrancyGuardTransient} from
"@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
contract Bank is ReentrancyGuardTransient {
mapping(address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
// Guarded, but still pays before clearing the balance
function withdraw() external nonReentrant {
uint256 amount = balances[msg.sender];
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "transfer failed");
balances[msg.sender] = 0;
}
// Not guarded, and it reads the same mapping
function transfer(address to, uint256 amount) external {
balances[msg.sender] -= amount;
balances[to] += amount;
}
}
Here the attacker's receive function calls transfer instead and moves its still-recorded balance to a second address. The guard never fires, because withdraw was not re-entered. When withdraw resumes it zeroes a balance that is already zero, and the second address withdraws the same ETH again. Every function that reads or writes the unfinished state is an entry point, not only the one that made the call.
Cross-contract reentrancy
Guarding every function closes the cross-function hole, but not when the unfinished state lives in a different contract.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ReentrancyGuardTransient} from
"@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
interface IDepositToken {
function balanceOf(address account) external view returns (uint256);
function mint(address to, uint256 amount) external;
function burnAll(address account) external;
}
contract TokenVault is ReentrancyGuardTransient {
IDepositToken public immutable token;
constructor(IDepositToken token_) {
token = token_;
}
function deposit() external payable nonReentrant {
token.mint(msg.sender, msg.value);
}
// Guarded, but the balances live in a contract with its own state
function withdrawAll() external nonReentrant {
uint256 amount = token.balanceOf(msg.sender);
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "transfer failed");
token.burnAll(msg.sender);
}
}
The vault issues one deposit token per wei and both of its functions are guarded. During the ETH transfer, the attacker calls the token contract directly and transfers its deposit tokens to a second address. The token cannot know that a withdrawal is in progress, because the lock is a variable inside the vault. burnAll then burns nothing, and the second address redeems the same tokens for ETH.
The Solidity documentation warns that you have to take multi-contract situations into account, because a called contract can modify the state of another contract you depend on. The fix is ordering: burn first, pay last, and treat all contracts that share accounting as one unit.
Read-only reentrancy
In the last variant nothing is re-entered for writing. The attacker needs a view function to return a wrong value at the right moment, and a third contract that trusts it.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ReentrancyGuardTransient} from
"@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
contract Pool is ReentrancyGuardTransient {
uint256 public totalAssets;
uint256 public totalShares;
mapping(address => uint256) public sharesOf;
// deposit() mints shares pro rata and is omitted here
function withdraw(uint256 shares) external nonReentrant {
uint256 payout = shares * totalAssets / totalShares;
sharesOf[msg.sender] -= shares;
totalShares -= shares; // supply is already reduced
(bool ok, ) = msg.sender.call{value: payout}("");
require(ok, "transfer failed");
totalAssets -= payout; // assets are reduced too late
}
// Other protocols read this as the value of one share
function sharePrice() external view returns (uint256) {
return totalAssets * 1e18 / totalShares;
}
}
While the ETH transfer in withdraw is in progress, totalShares has already dropped and totalAssets has not, so sharePrice reports more than a share is worth. In our test of this pool, with 10 ETH from another depositor, an attacker that deposited 10 ETH and withdrew half of its shares read 1.33 ETH per share inside the callback, against 1 ETH before and after.
The pool loses nothing. The victim is whoever reads the price: a lending market that values share collateral with sharePrice lends too much if the attacker borrows from inside the callback. The nonReentrant modifier on withdraw changes nothing, because the view function is not locked.
ChainSecurity described this pattern in October 2022 under the name read-only reentrancy. In the Curve pools it examined, get_virtual_price could be called while remove_liquidity was sending ETH, after the LP token supply had been reduced and before the pool balances were fully updated, and several protocols used that function as a price feed. If your contract reads a price from another protocol, treat this as one of the oracle risks described in common audit findings.
Token hooks that hand control to the receiver
None of this requires ETH. Several token standards call code on the sender or the receiver during a transfer, and each hook is an external call made from the middle of your function.
- ERC-777. A holder can register a
tokensToSendhook and a recipient atokensReceivedhook through the ERC-1820 registry. The first must be called before the token's state is updated, the second after. Registered hooks also run on the token's ERC-20transferandtransferFromfunctions, so a contract written for plain ERC-20 can be called back by a token it accepts. - ERC-721.
safeTransferFromchecks whether the recipient is a contract and, if so, callsonERC721Receivedon it.transferFromleaves that check to the caller. - ERC-1155. The interface has only safe transfer functions, and a transfer or mint to a contract calls
onERC1155ReceivedoronERC1155BatchReceived. Balances must be updated before the hook runs, which protects the token, not the contract that started the transfer.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
contract Giveaway {
IERC721 public immutable nft;
uint256 public nextId;
mapping(address => bool) public claimed;
constructor(IERC721 nft_) {
nft = nft_;
}
// Vulnerable: the receiver hook runs before claimed is set
function claim() external {
require(!claimed[msg.sender], "already claimed");
nft.safeTransferFrom(address(this), msg.sender, nextId++);
claimed[msg.sender] = true;
}
}
A contract whose onERC721Received calls claim again passes the check every time, because the flag is set only after the transfer returns. Setting claimed before the transfer removes the bug.
Defences and what each one covers
Checks-effects-interactions. Validate first, write every state change second, make external calls last. It is the only defence that addresses all four variants, because a callback that finds final state has nothing to exploit. It depends on discipline: every state change includes other contracts in your system and every value a view function exposes, and a later edit can silently break the order.
A reentrancy guard. OpenZeppelin's nonReentrant modifier sets a lock on entry and reverts if a guarded function is entered while the lock is held. There is one lock per contract, so it stops single-function reentrancy and, if every function that touches the shared state carries it, cross-function reentrancy. It does not see other contracts and does not lock view functions. For those, nonReentrantView makes a view revert while the lock is held.
At the time of writing, the Contracts 5.x documentation marks the storage-based ReentrancyGuard as deprecated and due to be replaced in v6.0 by ReentrancyGuardTransient, available since version 5.1. The transient variant keeps the lock in transient storage (EIP-1153), which is discarded at the end of every transaction and makes the lock cheaper. It only works on networks where EIP-1153 is available. On Ethereum the opcodes arrived with the Cancun upgrade, and Solidity has supported them since 0.8.24. Before deploying to a layer 2 or another EVM chain, confirm that it supports them.
Applied to the pool above:
// Pool, corrected: every effect precedes the call and the view is locked
function withdraw(uint256 shares) external nonReentrant {
uint256 payout = shares * totalAssets / totalShares;
sharesOf[msg.sender] -= shares;
totalShares -= shares;
totalAssets -= payout;
(bool ok, ) = msg.sender.call{value: payout}("");
require(ok, "transfer failed");
}
function sharePrice() external view nonReentrantView returns (uint256) {
return totalAssets * 1e18 / totalShares;
}
Pull payments. Instead of sending funds inside a function that does other work, record what each address is owed and let it withdraw in a separate call. The external call leaves the complicated function, but the withdrawal function must still zero the amount before it pays, hence "partly" in the table.
| Defence | Single-function | Cross-function | Cross-contract | Read-only |
|---|---|---|---|---|
| Checks-effects-interactions | Yes | Yes | Yes, if effects in every contract come first | Yes, if every value a view exposes is final |
nonReentrant on the calling function only |
Yes | No | No | No |
nonReentrant on every function that shares the state |
Yes | Yes | No, the lock is per contract | No |
nonReentrantView on view functions |
No | No | Only reads through the guarded view | Yes, the read reverts |
| Pull payments | Partly | Partly | Partly | Partly |
How to test for reentrancy
A test that calls the contract from a plain address never triggers a callback, so it cannot find this bug. Write an attacker contract whose callback calls back in, and assert what must stay true afterwards.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Test} from "forge-std/Test.sol";
import {Vault} from "../src/Vault.sol";
contract Attacker {
Vault private immutable vault;
constructor(Vault vault_) {
vault = vault_;
}
function attack() external payable {
vault.deposit{value: msg.value}();
vault.withdraw();
}
receive() external payable {
if (address(vault).balance >= msg.value) {
try vault.withdraw() {} catch {}
}
}
}
contract VaultReentrancyTest is Test {
Vault vault;
Attacker attacker;
address alice = makeAddr("alice");
function setUp() public {
vault = new Vault();
attacker = new Attacker(vault);
vm.deal(alice, 10 ether);
vm.prank(alice);
vault.deposit{value: 10 ether}();
}
function test_ReentrancyCannotDrainOtherDeposits() public {
attacker.attack{value: 1 ether}();
assertEq(address(attacker).balance, 1 ether);
assertEq(address(vault).balance, 10 ether);
}
}
With Vault.sol from the first example in src/, forge test reports a failure: the attacker ends the call holding 11 ETH instead of 1. The test passes once the balance is cleared before the transfer, or when withdraw is given a guard. The try/catch in receive lets the outer withdrawal finish when the re-entry is refused, so the assertions decide the result.
For the other variants:
- In the callback, try every external function, not only the one that made the call.
- Use the callback your code really triggers:
receivefor ETH, the receiver hook for tokens. - For read-only reentrancy, record the view function's value inside the callback and compare it with the value before and after.
- State the property as an invariant, for example that the vault's ETH balance covers the sum of recorded balances. Our comparison of smart contract testing tools covers invariant testing.
Static analysis is the cheap first pass. At the time of writing, Slither's detector documentation lists six reentrancy checks:
| Detector | Severity | What it reports |
|---|---|---|
reentrancy-eth |
High | Reentrancy that involves Ether |
reentrancy-balance |
High | A balance saved before an external call and checked again after it |
reentrancy-no-eth |
Medium | Reentrancy that does not involve Ether |
reentrancy-benign |
Low | Reentrancy that acts as a double call |
reentrancy-events |
Low | Reentrancy that can change the order or value of events |
reentrancy-unlimited-gas |
Informational | Reentrancy based on transfer or send |
None of the six is described as a check for read-only reentrancy, and a tool that analyses one codebase cannot know which protocols read your view functions.
FAQ
Does a reentrancy guard on every function make a contract safe?
It stops re-entry into that contract's guarded functions. It does not protect state held in another contract or stop other protocols from reading an unguarded view function during the call. Correct ordering covers those cases.
Can reentrancy happen without sending ETH?
Yes. Any call to another contract hands over control. Token transfers with hooks, such as ERC-777 transfers, ERC-721 safeTransferFrom and ERC-1155 transfers to contracts, are common entry points.
Is using transfer instead of call a fix?
No. It relies on the receiver having too little gas to do harm, which depends on gas costs that can change, and it does not cover calls to tokens or other contracts.
Sources
- Solidity documentation: Security Considerations
- Solidity blog: Transient Storage Opcodes in Solidity 0.8.24
- Ethereum Improvement Proposals: EIP-1153: Transient storage opcodes
- OpenZeppelin Contracts 5.x: Utilities API (ReentrancyGuard, ReentrancyGuardTransient)
- Ethereum Improvement Proposals: ERC-777: Token Standard
- Ethereum Improvement Proposals: ERC-721: Non-Fungible Token Standard
- Ethereum Improvement Proposals: ERC-1155: Multi Token Standard
- Slither (GitHub): Detector Documentation
- ChainSecurity: Curve LP Oracle Manipulation: Post Mortem
- ethereum.org: Smart contract security