Lesson 2 of 5 Smart Contract Vulnerabilities

Reentrancy

Reentrancy is the most famous smart contract vulnerability. This lesson explains how a reentrancy attack works step by step, describes its variants and shows the code patterns that prevent it.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how a reentrancy attack works.
  • Distinguish the variants of reentrancy.
  • Explain how checks-effects-interactions and reentrancy guards prevent it.

How the attack works

The following vault looks reasonable but contains the classic reentrancy flaw: it sends ether before updating the balance.

// VULNERABLE: external call before the state update
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 exploits it with a contract, in the following sequence.

  1. Deposit

    The attacker's contract deposits 1 ETH, so its recorded balance is 1 ETH.

  2. Withdraw

    It calls withdraw(). The vault reads 1 ETH and sends it with call.

  3. Re-enter

    Receiving ether triggers the attacker's receive(), which calls withdraw() again.

  4. Repeat

    The balance is still 1 ETH, because line 7 has not run yet, so the vault sends another 1 ETH, and so on.

  5. Unwind

    When the vault is empty or gas runs low, the calls return and the balance is finally set to zero, too late.

The following diagram shows the calls between the attacker and the vault.

The classic reentrancy attack. The attacker's contract deposits 1 ETH and calls withdraw(). The vulnerable vault reads the balance and sends the ether with call before setting the balance to zero. Receiving ether runs the attacker's receive(), which calls withdraw() again; the balance is still 1 ETH, so the vault pays again, and so on. When the vault is empty, the calls unwind and the balance is finally set to zero, too late.
The external call happens before the state update.
Put in order

Anatomy of a reentrancy attack

Exam skills 3.1.1

Arrange the steps of a reentrancy attack on a vault that sends ether before updating balances.

Log in to try this activity Interactive activities are free with an account.

Variants

Reentrancy is not limited to one function re-entering itself. The following terms describe the main variants.

Single-function reentrancy
The callback re-enters the same function, as in the vault above.
Cross-function reentrancy
The callback enters a different function that uses the same state, such as transfer() of the balance that withdraw() has not yet cleared.
Cross-contract reentrancy
Several contracts share state, and the callback enters another contract that trusts the half-updated state.
Read-only reentrancy
During the callback, another protocol calls a view function and reads an inconsistent value, such as a price, and acts on it.

Any external call can hand control to an attacker: sending ether, calling an unknown token, and token hooks such as ERC-721 onERC721Received, ERC-1155 receiver hooks and ERC-777 hooks.

Scenario questions

Reentrancy variants

Exam skills 3.1.1

Recognise reentrancy that does not re-enter the same function.

Log in to try this activity Interactive activities are free with an account.

Preventing reentrancy

The following version applies the two standard defences.

import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

contract Vault is ReentrancyGuard {
    mapping(address => uint256) public balances;

    function withdraw() external nonReentrant {
        uint256 amount = balances[msg.sender];          // checks
        if (amount == 0) revert NothingToWithdraw();
        balances[msg.sender] = 0;                       // effects
        (bool ok, ) = msg.sender.call{value: amount}(""); // interactions
        if (!ok) revert TransferFailed();
    }
}

Checks-effects-interactions sets the balance to zero before the call, so a re-entering call finds nothing to withdraw. The nonReentrant modifier sets a lock that makes any second entry revert, and it also protects other functions marked nonReentrant against cross-function reentrancy. Using both is common practice; the ordering is the essential fix.

True or false

Reentrancy defences

Exam skills 3.1.1 · 3.2.1

Check how checks-effects-interactions and reentrancy guards protect a contract.

Log in to try this activity Interactive activities are free with an account.
Worked example

Spot the flaw

A contract's claimReward() first calls rewardToken.transfer(msg.sender, reward) and then sets claimed[msg.sender] = true. The reward token is a standard OpenZeppelin ERC-20. Is this vulnerable to reentrancy?

A standard ERC-20 transfer does not call the recipient, so this exact token cannot be used to re-enter. The code is still poorly ordered: if the token is ever changed to one with transfer hooks, or is upgradeable, the flaw becomes exploitable. Setting claimed before the transfer costs nothing and removes the risk; reviewers flag the pattern regardless of today's token.

Worked example

Is transfer() enough?

A team argues that using payable(msg.sender).transfer(amount) instead of call prevents reentrancy because only 2,300 gas is forwarded. Should they rely on it?

No. The stipend is too small for a re-entering call today, but gas costs have changed in past upgrades and may change again, and transfer breaks payments to smart contract wallets. The robust defence is checks-effects-interactions plus a reentrancy guard, with call for sending.

Check yourself

What ordering mistake makes a withdrawal function vulnerable to reentrancy?

Show answer

Making the external call, such as sending ether, before updating the caller's balance. The callee can re-enter while the balance still shows the old amount.

Exam Tips

Remember for the exam

  • Reentrancy: an external call lets the callee re-enter before state is updated.
  • Variants include cross-function, cross-contract and read-only reentrancy.
  • Fix with checks-effects-interactions; add nonReentrant as a second layer.
  • Sending ether and token hooks are external calls too.