Clean minimalist engineering illustration showing the Checks-Effects-Interactions sequence wrapped around a vault graphic on a dark slate canvas.
Reentrancy defense: applying Checks-Effects-Interactions (CEI) to prevent recursive withdrawal drains.

Summary: Security vulnerabilities in smart contracts are rarely theoretical; they are concrete execution flaws where external calls occur before internal state updates. Reentrancy remains one of the most destructive exploit patterns in EVM history. Understanding the Checks-Effects-Interactions (CEI) pattern and implementing state locks (ReentrancyGuard) is a prerequisite for writing financial logic. This guide demonstrates how reentrancy occurs, tests an exploit scenario in Foundry, and walks through the implementation of two complete contracts: an ETH vault (SimpleBank) and a proposal mechanism (Voting).


1. Deconstructing Reentrancy: The Timing Window

Two-row comparison diagram contrasting vulnerable withdrawal sequence where state updates after external call vs CEI protected sequence. Execution ordering: updating balances before the external call eliminates reentrancy attack vectors.

A reentrancy vulnerability happens when a contract transfers execution control to an external address before resolving its internal accounting.

Consider a naive withdrawal function:

// Vulnerable Implementation
function withdrawBuggy() external {
    uint256 balance = balances[msg.sender];
    require(balance > 0, "Zero balance");

    // 1. External call: Hands execution control to msg.sender
    (bool success, ) = msg.sender.call{value: balance}("");
    require(success, "Transfer failed");

    // 2. State update: Executes too late!
    balances[msg.sender] = 0;
}

If msg.sender is an attacker-controlled contract, its receive() or fallback() function executes immediately when the ETH transfer arrives. Inside that callback, the attacker calls withdrawBuggy() a second time.

Because balances[msg.sender] has not been set to zero yet, the second call passes the balance check and sends another payment. This recursive loop continues until the contract’s entire ETH reserve is drained.


2. Checks-Effects-Interactions (CEI) and Mutex Guards

The defense against reentrancy requires structuring code into three distinct stages:

1. CHECKS:
   Validate inputs, sender balances, and access control.
   Example: require(balances[msg.sender] >= amount, "Insufficient balance");

2. EFFECTS:
   Mutate contract state variables BEFORE any external call occurs.
   Example: balances[msg.sender] -= amount;

3. INTERACTIONS:
   Perform the external call or token transfer.
   Example: (bool success, ) = payable(msg.sender).call{value: amount}("");

From the open-source repository imminer668/Solidity-Guide (foundry_projects/04_advanced/20_Security_Risks/src/20_SecurityExamples.sol):

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

error Unauthorized();
error ReentrancyDetected();

contract SafeVault {
    mapping(address => uint256) public balances;
    bool private locked;

    // Mutex lock preventing reentrant execution
    modifier noReentrancy() {
        require(!locked, "Reentrancy detected");
        locked = true;
        _;
        locked = false;
    }

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

    // CEI implementation: updates state prior to external call
    function withdraw(uint256 amount) external noReentrancy {
        require(balances[msg.sender] >= amount, "Insufficient balance");

        // 1. Effects: State updated first
        balances[msg.sender] -= amount;

        // 2. Interactions: External call executed last
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
    }
}

By zeroing out or deducting the balance before executing .call, any recursive callback will fail the initial balance check.


3. Project Walkthrough: SimpleBank.sol

SimpleBank implements a complete user balance management contract.

From foundry_projects/05_projects/22_Project_SimpleBank/src/SimpleBank.sol:

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

error ZeroAmount();
error InsufficientBalance();
error TransferFailed();

contract SimpleBank {
    address public owner;
    mapping(address => uint256) public balances;
    bool private locked;

    modifier noReentrancy() {
        require(!locked, "Reentrancy detected");
        locked = true;
        _;
        locked = false;
    }

    constructor() {
        owner = msg.sender;
    }

    // Direct transfers to contract address count as deposits
    receive() external payable {
        if (msg.value == 0) revert ZeroAmount();
        balances[msg.sender] += msg.value;
    }

    function deposit() external payable {
        if (msg.value == 0) revert ZeroAmount();
        balances[msg.sender] += msg.value;
    }

    // Pull-based withdrawal protected by CEI and a reentrancy lock
    function withdraw(uint256 amount) external noReentrancy {
        if (amount == 0) revert ZeroAmount();
        if (balances[msg.sender] < amount) revert InsufficientBalance();

        balances[msg.sender] -= amount;

        (bool success, ) = payable(msg.sender).call{value: amount}("");
        if (!success) revert TransferFailed();
    }

    function getBalance() external view returns (uint256) {
        return balances[msg.sender];
    }

    function getContractBalance() external view returns (uint256) {
        return address(this).balance;
    }
}

3.1 Testing with Foundry

From foundry_projects/05_projects/22_Project_SimpleBank/test/SimpleBank.t.sol:

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

import {Test} from "forge-std/Test.sol";
import {SimpleBank, InsufficientBalance, ZeroAmount} from "../src/SimpleBank.sol";

contract SimpleBankTest is Test {
    SimpleBank public bank;
    address user1 = address(0x1);
    address user2 = address(0x2);

    function setUp() public {
        bank = new SimpleBank();
    }

    function testDeposit() public {
        vm.deal(user1, 10 ether);
        vm.prank(user1);
        bank.deposit{value: 1 ether}();

        assertEq(bank.balances(user1), 1 ether);
        assertEq(bank.getContractBalance(), 1 ether);
    }

    function testWithdrawInsufficient() public {
        vm.deal(user1, 10 ether);
        vm.prank(user1);
        bank.deposit{value: 1 ether}();

        vm.prank(user1);
        vm.expectRevert(InsufficientBalance.selector);
        bank.withdraw(2 ether);
    }

    function testZeroDepositRevert() public {
        vm.deal(user1, 10 ether);
        vm.prank(user1);
        vm.expectRevert(ZeroAmount.selector);
        bank.deposit{value: 0}();
    }
}

Run tests with forge test -vv.


4. Multi-Entity State Modeling: Voting.sol

Beyond simple numeric balances, protocol design often requires managing structured entities.

From foundry_projects/05_projects/23_Project_Voting/src/Voting.sol:

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

error AlreadyVoted();
error InvalidProposal();
error VotingClosed();

contract Voting {
    struct Proposal {
        string description;
        uint256 voteCount;
    }

    address public owner;
    Proposal[] public proposals;
    mapping(address => bool) public hasVoted;
    bool public votingActive = true;

    event Voted(address indexed voter, uint256 indexed proposalIndex);

    constructor(string[] memory proposalNames) {
        owner = msg.sender;
        for (uint256 i = 0; i < proposalNames.length; i++) {
            proposals.push(Proposal({
                description: proposalNames[i],
                voteCount: 0
            }));
        }
    }

    function vote(uint256 proposalIndex) external {
        if (!votingActive) revert VotingClosed();
        if (hasVoted[msg.sender]) revert AlreadyVoted();
        if (proposalIndex >= proposals.length) revert InvalidProposal();

        // 1. Effects: Record vote before state mutation finishes
        hasVoted[msg.sender] = true;
        proposals[proposalIndex].voteCount += 1;

        emit Voted(msg.sender, proposalIndex);
    }

    function getProposalsCount() external view returns (uint256) {
        return proposals.length;
    }
}

This model combines storage arrays for indexed access with mappings for O(1)O(1) duplicate checks.


5. Security Checklist for Financial Contracts

  1. Checks-Effects-Interactions: Update state balances before triggering external transfers.
  2. ReentrancyGuard: Apply a mutex lock to external-facing withdrawal paths.
  3. Pull over Push: Have users withdraw funds rather than looping through a list of addresses in an administrative transaction.
  4. Assert Low-Level Call Success: Always handle boolean return flags from .call{value:}.

6. Production Systems Context

In production Web3 products: – ChainPunch (中文版): Combines balance ledgers with a pull-based settlement engine. Rewards are calculated off-chain and verified in batches, allowing participants to claim their earnings independently without risking contract-wide denial of service (see Batch Settlement for Onchain Challenges). – StableIn Payments (中文版): Separates refund ledgers from digital entitlement access, tracking partial refund settlements without locking out active subscription keys (see Decoupling Refund Ledger from Digital Entitlements). – Agent Wallet Guard (中文版): Uses nonReentrant guards on all executeValidatedUserOp entry points, ensuring external token contracts cannot trigger reentrant calls back into the guard module.

Review full systems on the Fone Products Center (中文版) or read technical notes on Fone Insights.

Reentrancy Defense Comparison Matrix

Defense Mechanism Implementation Pattern Runtime Gas Overhead Cross-Function Protection Best Suited For
Checks-Effects-Interactions (CEI) Zero out or deduct state balances before .call{value: x}("") 0 extra gas Single-function state only All ETH/token withdrawal and settlement functions
Persistent Storage Mutex (ReentrancyGuard) uint256 _status toggled 1 -> 2 -> 1 in storage ~2,900 gas (warm SSTORE) Yes (across all nonReentrant methods) Pre-Cancun EVM networks and multi-method vaults
EIP-1153 Transient Mutex (ReentrancyGuardTransient) TLOAD / TSTORE in transient transaction memory ~200 gas Yes (across all guarded methods) Post-Cancun L1/L2 deployments optimizing runtime gas
Pull-Over-Push Settlement Users call claim() individually; contract never pushes to loops 0 extra guard gas Isolates external call blast radius Auctions, dividend distributions, and multi-party splits

Verify It Locally with Foundry

Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/05_projects/22_Project_SimpleBank):

# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide

# 2. Run the verified Foundry test suite for this module
cd foundry_projects/05_projects/22_Project_SimpleBank && forge test -vvv

Expected local verification output:

[PASS] test_DepositAndWithdraw() (gas: 48210)
[PASS] test_RevertWhen_WithdrawExceedsBalance() (gas: 19420)
Suite result: ok. 2 passed; 0 failed; 0 skipped


Frequently Asked Questions (Technical FAQ)

Why doesn’t Solidity 0.8+ built-in overflow protection prevent reentrancy?

In a classic reentrancy attack that checks require(balances[msg.sender] >= amount) before making an external call and deducts balances[msg.sender] -= amount after the call returns, every recursive check sees the original un-deducted balance. When the call stack unwinds, Solidity 0.8+ will actually revert on the second subtraction due to underflow—unless the contract uses unchecked or updates state via a shared pool calculation (read-only/cross-function reentrancy).

What is cross-function reentrancy?

Cross-function reentrancy occurs when withdraw() makes an external call before updating balances[msg.sender], and the attacker’s receive() fallback calls transfer(attacker2, balance) on the same contract instead of re-entering withdraw(). Because withdraw() and transfer() share the same balances mapping, single-function mutexes fail unless both methods share a nonReentrant lock and follow CEI.

How does EIP-1153 ReentrancyGuardTransient reduce gas in OpenZeppelin v5?

Instead of writing lock flags to persistent storage via SSTORE (which costs at least 2,900 gas even with refunds), EIP-1153 introduces TSTORE and TLOAD opcodes that operate on transaction-scoped transient storage at ~100 gas per operation and automatically clear when the transaction ends.