Skip to main content

Reentrancy Guard Pattern

Implement a reentrancy guard to prevent one of the most common smart contract attacks. Implement a reentrancy guard to prevent one of the most common smart contract attacks.

Explanation

Reentrancy is the most famous smart contract vulnerability (the DAO hack, 2016). A malicious contract re-enters a function before state is updated, draining funds. How this guard works:
  • A _locked boolean is set true at function entry.
  • If the external call triggers a re-entry, nonReentrant reverts.
  • The boolean resets after the function completes.
OpenZeppelin provides ReentrancyGuard — prefer it in production. Always combine with checks-effects-interactions.

Code


Canonical knowledge ID: code-example:reentrancy-guard-pattern