Skill 3.1.1

Identify and prevent reentrancy

Key Concepts

Reentrancy happens when a contract makes an external call before it has finished updating its own state. The called contract, or the receiver of ether through its receive function, can call back into the original contract while its state still shows the old values. In the classic example, a vault sends a user's balance with call and only then sets the balance to zero; an attacking contract's receive function calls withdraw again and again, draining the vault.

Variants include cross-function reentrancy, where the callback enters a different function that shares the same state, and read-only reentrancy, where another protocol reads a view function during the callback and sees inconsistent values. Token standards with hooks, such as ERC-721 safeTransferFrom and ERC-777, also hand control to external code.

Prevention: follow checks-effects-interactions (update state before the external call), use a reentrancy guard such as OpenZeppelin's nonReentrant, and prefer pull payments.