Reentrancy attacks in Solidity: how they work and how to prevent them

A reentrancy attack is when a contract makes an external call before its state is final, and the code it calls comes back in to act on that stale state. Sending ETH is the classic case, but token hooks and calls to other protocols open the same door. Update state before the call, guard every function that shares that state, and test the guard by actually re-entering.

Last updated . 5 minute read. By the QuillShield team.

How does a reentrancy attack work?

Any external call hands control to code you didn't write. Sending ETH to a contract runs its receive function. ERC-777 transfers call hooks on the sender and the recipient, and the safe transfers of ERC-721 and ERC-1155 call a receiver function on the recipient. A call into another protocol can call back into yours.

If the calling function has not finished updating its balances, the callback sees the old numbers. It can withdraw the same balance again, or enter a different function that trusts the same stale state. The variants you meet in reviews:

  • Single-function. The callback re-enters the function that made the call.
  • Cross-function. The callback enters another function that reads the same balance.
  • Cross-contract. The callback enters another contract of the protocol that shares the state.
  • Read-only. A view function returns a value from the middle of an update, and another protocol uses it as a price.

What does vulnerable code look like?

This bank sends ETH before it clears the balance.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Bank {
    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");
        // The call runs the caller's code while its balance is still set.
        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "send failed");
        balances[msg.sender] = 0;
    }
}

An attacker contract deposits 1 ETH and calls withdraw. Its receive function calls withdraw again, and because the balance still reads 1 ETH, the bank pays again, until the bank is empty or the gas runs out.

How do you fix it?

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract SafeBank {
    mapping(address => uint256) public balances;
    uint256 private locked = 1;

    modifier nonReentrant() {
        require(locked == 1, "reentrant call");
        locked = 2;
        _;
        locked = 1;
    }

    function deposit() external payable nonReentrant {
        balances[msg.sender] += msg.value;
    }

    function withdraw() external nonReentrant {
        uint256 amount = balances[msg.sender];
        require(amount > 0, "nothing to withdraw");
        balances[msg.sender] = 0; // effects first
        (bool ok, ) = msg.sender.call{value: amount}(""); // interaction last
        require(ok, "send failed");
    }
}
  • Checks, effects, interactions. Clear or reduce the balance before the external call, so a callback sees the final state.
  • A reentrancy guard. The nonReentrant modifier makes any second entry revert, and OpenZeppelin's ReentrancyGuard works the same way. Put it on every function that touches the shared state, not only the one that sends.
  • Pull over push. Let users withdraw what they are owed, rather than sending to them in the middle of a larger operation.
  • Treat tokens as callers. If your protocol accepts arbitrary tokens, assume a transfer can call back.

How has it been exploited?

On 30 July 2023, between 13:10 and 22:00 UTC, attackers drained several Curve pools, among them pETH/ETH, msETH/ETH, alETH/ETH and CRV/ETH. Curve's post-mortem traces each loss to "a malfunctioning reentrancy lock" in Vyper versions 0.2.15, 0.2.16 and 0.3.0. The pools declared the lock in their source, but the compiled code did not enforce it. Vyper 0.3.1 had already fixed the bug without anyone knowing it was a bug. The pETH/ETH pool alone lost 6,106.65 WETH, about $11M at the time.

The lesson holds in any language: a declared guard is not proof of a working one. A test that tries to re-enter each guarded function checks the compiled code, not the annotation.

An older case shows the token route. In April 2020 an attacker used imBTC, an ERC-777 token whose transfers call hooks on the sender and the recipient, to re-enter Lendf.Me in the middle of a deposit, and took about $25M.

What should a reviewer check?

  • List every external call: ETH sends, token transfers, NFT safe transfers and calls into other protocols.
  • Is every piece of state the call could depend on updated before the call?
  • Does the guard cover every function that reads or writes the same state, including functions in other contracts of the protocol?
  • Can a view function return a half-updated value during a call, and does anything use it as a price?
  • Which tokens can the contract receive? ERC-777 and other tokens with hooks behave differently from plain ERC-20s.
  • Is there a test for each guarded function that re-enters it and expects a revert?

How does QuillShield check for it?

Reentrancy often crosses contract boundaries, which a review of one file at a time can miss. A QuillShield full audit covers the whole Foundry codebase in scope, and a separate reviewer agent tries to disprove each finding before you see it. On a full audit a finding can carry a proof of concept, with its status shown as passed or failed, so you know whether the callback path works against your code.

New external calls tend to arrive in small pull requests after launch. QuillShield checks each pull request against the audit's security graph, and on GitHub, with branch protection or rulesets, a required QuillShield check blocks the merge while the pull request has a High or Critical finding.

Full audits start at $49 and are priced from the lines of Solidity in scope, as the pricing page shows. The guide to running your first audit walks through getting a quote for your own code. Sign up free and you see the exact price before anything is charged.

Common questions

Does Solidity 0.8 prevent reentrancy?

No. Version 0.8 added checked arithmetic, which stops overflow and underflow. Nothing in the compiler stops a contract from being called again during an external call.

Are transfer() and send() a fix?

They forward only 2,300 gas, which blocks most callbacks, but gas costs have changed before and the limit breaks payments to smart contract wallets. Order your updates and use a guard instead.

What is read-only reentrancy?

A view function returns a value from the middle of an update, such as a pool's price before its balances settle, and another protocol reads it. The reader has to check that the pool is not mid-update, or the pool has to guard its views.

Does nonReentrant on one function protect the others?

No, only the functions that carry it. A callback can enter any unguarded function that reads the same balance, so guard all of them or make each one safe on its own.

Sources

QuillShield is building the security layer between AI and money, so you can keep shipping between audits.

Sign-up is free, and new accounts get $50 in credit, good for up to half of an order.

  1. 1Sign up and import a repo
  2. 2See the exact price before anything is charged
  3. 3Approve it, and the audit starts