Crypto Training
Reentrancy Beyond the Basics: Cross-Function, Cross-Contract, and Read-Only
Reentrancy covers every case where outside code runs while one of your invariants is temporarily false. This post sorts the variants by what that code can reach (the same function, a sibling, another contract, a view), with the incident, the code shape and the defense for each.
Reentrancy is usually taught as one bug, in which a contract sends ETH and updates the balance afterwards. The incidents of the last few years fit a wider definition better, and one question captures it:
Did we cross a trust boundary while an invariant was temporarily false?
When the answer is yes, what remains is to work out which functions the outside code can reach during that window and what it finds there. The four variants below are the four possible answers. Where the outside code gets its turn (token hooks, safe transfers, registered callbacks, callbacks you expose) is the subject of the companion post, Reentrancy in 2026: callback surfaces you still miss.
The reentrancy matrix#
| Variant | What the outside code reaches | What breaks | Incident |
|---|---|---|---|
| Classic | the function that is already running | a value read before the call and written after it | Uniswap V1 imBTC pool, April 2020 |
| Cross-function | another function of the same contract | state the two functions share | Lendf.Me, April 2020 |
| Cross-contract | a function of another contract in the same system | an invariant that spans contracts | Cream, August 2021, and Rari Fuse, April 2022 |
| Read-only | a view function, read by a third protocol | whatever that protocol computes from the view | dForce, Sentiment and Conic, 2023 |
A nonReentrant modifier on the function under review settles the first row and, when it is applied to every function that shares the state, the second. It does nothing for the last two, which is why they keep appearing in audited code.
The invariant lens#
A function that reads state, computes something from it, calls out and then continues is assuming that what it read is still true when it continues. Reentrancy is the act of breaking that assumption from inside the call. The dangerous region of a function is therefore the stretch between its first read and its last write of a related set of variables, and any external call inside that stretch opens the window.
The diagram shows why "can the attacker call the same function again" is too narrow a test. The second call enters through emergencyExit(), a different entry point that touches the same shares and assets while they disagree.
Classic reentry into the running function#
// VULNERABLE: the classic shape that still works under Solidity 0.8.
function withdrawAll() external {
uint256 amount = balances[msg.sender]; // read
(bool ok,) = msg.sender.call{value: amount}(""); // interaction
require(ok, "send failed");
balances[msg.sender] = 0; // effect, too late
}
A contract that receives the ETH calls withdrawAll() again from its receive(), finds its balance unchanged and is paid a second time, and can repeat this until the contract is empty.
Checked arithmetic removed part of this class. If the function ended with balances[msg.sender] -= amount, the nested calls would underflow as they unwound and the whole transaction would revert. The versions that survive in 0.8 code assign a constant or a value computed before the call, so the stale write succeeds.
The stale value does not have to be a user balance. Uniswap V1 priced a token sale from the pool's token balance, paid out ETH and pulled the tokens last, and with an ERC-777 token the seller re-entered the same swap function while the reserve still showed the old balance. In that case the value that was read early and corrected late was a price.
Cross-function reentry through a sibling#
function withdraw(uint256 shares) external nonReentrant {
_withdraw(msg.sender, shares);
}
function emergencyExit() external { // no lock
_withdraw(msg.sender, balanceOf[msg.sender]);
}
Adding the modifier to withdraw() closes the function that was reported and leaves a second route to the same internal transition. Lendf.Me had this shape across supply() and withdraw(): the attacker re-entered withdraw() from a token hook fired inside supply(), and when supply() resumed it wrote a balance it had computed before the withdrawal.
The lock therefore has to cover every external function that reads or writes the state the running function depends on, including transfers of receipt tokens, delegation and admin setters. The companion post has a complete example of this variant with a Foundry test.
Cross-contract reentry around a misplaced lock#
A lock is a storage variable, so it protects the contract that owns it. When the invariant spans several contracts, a per-contract lock leaves the other contracts open.
Cream's markets each had their own nonReentrant flag. The attacker's AMP borrow was in flight in one market when a token hook let it borrow from another market, whose flag was clear and whose liquidity check could not yet see the first debt.
Rari's Fuse fork of Compound had taken that lesson. Every market function acquired a pool-wide lock in the Comptroller, and the comment on _beforeNonReentrant cites "AMP on Cream" as the case it prevents. The Comptroller's own exitMarket did not consult that lock. In April 2022 an attacker borrowed ETH, which that fork sent with a plain call before recording the debt, and used the callback to exit the collateral market while the account still appeared to owe nothing. Reported losses were about $80M.
Both cases point at the same design rule, which is that the lock belongs where the invariant lives. A system-wide lock has to be consulted by every entry point of every contract that can change the inputs of the shared check, and the entry points on the contract that holds the lock are the easiest ones to forget.
Read-only reentrancy#
Read-only reentrancy needs no write at all. The attacker calls a view function during the window and lets a different protocol act on the answer, so the contract with the inconsistent state loses nothing and a lender that trusted its view takes the loss.
// VULNERABLE: pricePerShare() can be read while the pool is half-updated.
contract EthPool is ReentrancyGuard {
mapping(address => uint256) public shares;
uint256 public totalShares;
uint256 public reserve; // ETH the pool accounts for
// addLiquidity() omitted: it mints shares pro rata and adds msg.value to reserve.
function removeLiquidity(uint256 burned) external nonReentrant {
uint256 amount = burned * reserve / totalShares;
shares[msg.sender] -= burned;
totalShares -= burned; // supply is already lower
(bool ok,) = msg.sender.call{value: amount}(""); // the recipient runs here
require(ok, "send failed");
reserve -= amount; // reserve catches up only now
}
function pricePerShare() external view returns (uint256) {
return reserve * 1e18 / totalShares; // no lock check
}
}
Every state-changing function is locked and the pool itself cannot be drained. During the callback, however, the supply has dropped and the reserve has not, so a pool where someone burns 90% of the shares reports ten times the true price until removeLiquidity returns. A lender that values these shares with pricePerShare() will lend against the inflated number if the attacker borrows from inside its receive().
This is the shape of the Curve issue that ChainSecurity reported in April 2022 and published in October 2022, once the affected teams had patched. In pools holding native ETH, remove_liquidity burned the LP tokens and sent the ETH with a raw call before the balances were fully updated, and get_virtual_price() had no lock. The write-up lists MakerDAO, Enzyme, Abracadabra, TribeDAO and Opyn among the protocols whose price feeds read it, with more than $100M at risk on the stETH pool alone.
The same window was then used against protocols that integrated later. Midas on Polygon in January 2023, dForce on Arbitrum in February 2023 (about $3.65M) and Conic in July 2023 (about $3.25M) each priced Curve LP collateral from pool state read during remove_liquidity. Balancer v2 has a matching window, described in its forum post of February 2023: during a join or exit the Vault can return unused ETH to the caller before pool supply and Vault balances agree. Sentiment (April 2023, about $1M) and Sturdy (June 2023, about $800K) valued Balancer LP tokens inside it.
The producer of the view can close the window in two ways. It can finish its writes before the external call, which is checks-effects-interactions applied to the variables the view reads. It can also make the view refuse to answer while the lock is held, and OpenZeppelin Contracts 5.5 added a nonReentrantView modifier for that purpose.
The consumer cannot fix the producer, so it has to detect the window. For Curve, the mitigation in ChainSecurity's write-up is to call the pool's withdraw_admin_fees before reading, since that function takes the lock and reverts when the pool is in the middle of an operation. For Balancer v2 the equivalent is VaultReentrancyLib.ensureNotInVaultContext. Where a source offers no such call, treat its view as something an attacker can move within a transaction and bound it against an independent reference, as the oracles post describes.
Defenses and what they cost#
The strongest fix is to remove the window. Committing every effect before the interaction does that for the variables written early, and it is the first thing to try. It becomes hard when the amount is only known after the call, for example when a deposit is measured as a balance delta or a swap result feeds the accounting.
Where ordering cannot remove the window, moving the external call out of the transition does. With pull payments or a request and claim pair, the state change completes in one call and the transfer happens in another, when no invariant is open. This also takes care of recipients that revert, which the gas griefing post covers.
Hooks offered to integrators, such as an afterDeposit callback, need a decision about failure. If a reverting hook reverts the deposit, the hook owner holds a veto over deposits. If it does not, the call needs a gas limit and bounded return data, and the accounting must be complete before the hook runs.
| Defense | What it gives you | Cost or failure mode |
|---|---|---|
nonReentrant on every function sharing the state | blocks classic and cross-function reentry | one missed function reopens it; views stay readable |
| System-wide lock in a shared contract | covers cross-contract reentry | every entry point must consult it, as the Fuse case shows |
| Effects before interactions | no window for the variables written early | awkward when amounts are known only after the call |
| Pull payments, request and claim | the external call happens with no invariant open | an extra transaction and more state |
| Lock-aware views | consumers cannot read a half-updated value | integrators that read during a legitimate callback now revert |
Our preference in reviews is ordering first and pull payments second, with locks as a backstop on every function that shares state, because the first two fix the invariant and a lock only blocks the paths someone remembered.
External calls inside pricing#
A pricing function that calls out (to an oracle, a fee module or a hook) and is used inside a state transition combines three risks in one line, since the callee can re-enter, revert or consume the gas. Modular designs produce this shape often, in fee modules, hook-based exchanges and vault strategies. The remedy is to read the external values once before the transition starts and pass them in, so that the code between the first read and the last write makes no external calls.
Finding it in a review#
Searching for nonReentrant first tends to anchor a review on the functions that already have it. This order has worked better for us:
- List every external call, including token transfers and mints.
- For each call, mark which invariants are open around it, meaning which related variables have been read or partly written.
- List every function reachable during that window, in every contract of the system, including views that other protocols consume.
- Try to build a cycle in the call graph that passes through the window.
A cycle through an open invariant is a candidate. It becomes a finding once a test shows the invariant broken afterwards.
Testing#
Each candidate deserves a small reproduction: an attacker contract that implements the callback, calls a second entry point or a view from inside it, and an assertion on the invariant. For read-only cases the assertion is that the view either reverts inside the callback or returns the same value as before the operation.
// In the attacker contract: runs when removeLiquidity sends the ETH.
receive() external payable {
observed = pool.pricePerShare();
}
// In the test: the pool starts with 1 ETH from an honest provider.
function test_viewIsConsistentDuringCallback() public {
uint256 priceBefore = pool.pricePerShare();
reader.addThenRemove(9 ether); // adds 9 ETH, then removes it
assertEq(reader.observed(), priceBefore); // fails on EthPool: 10e18 against 1e18
}
Two exercises build the habit quickly. Write the EthPool above with a lender that reads its price, and take a loan from inside the callback. Then reorder the pool's writes until the loan stops working, and note which line had to move.
Checklist#
- Is there an external call between the first read and the last write of any related set of variables?
- Which other functions, in this contract and in the rest of the system, read or write those variables, and do they all take the same lock?
- Are token transfers, mints and safe transfers counted as external calls?
- Which view functions do other protocols read as prices or rates, and what do they return in the middle of each state-changing function?
- Which external views does this protocol read, and what proves they are not being read during the source's own state change?
Sources#
- ChainSecurity, Curve LP oracle manipulation post-mortem, for the
get_virtual_pricewindow, the affected feeds and thewithdraw_admin_feesmitigation. - Balancer forum, Reentrancy vulnerability scope expanded, for the Vault join and exit window and the affected pool types.
- Balancer VaultReentrancyLib, the consumer-side check for Balancer v2.
- Rari-Capital/compound-protocol, Comptroller.sol at e339026, for the pool-wide lock and
exitMarket. - OpenZeppelin Contracts changelog, for
nonReentrantViewin 5.5.0. - Solidity documentation, security considerations, for the checks-effects-interactions pattern.