What is a Reentrancy Attack?
A reentrancy attack happens when a smart contract lets an attacker call the same function again and again before the contract finishes updating its data. This means the attacker can steal ETH, tokens, or change how the contract works.
Why Does It Happen?
State updates after external calls: If you transfer ETH or call another contract first and then update your balance, it leaves room for repeated attacks
Trusting User-Controlled Parameters: Relying on inputs from external users or contracts without proper checks
How Contracts Receive ETH?
Smart contracts can receive ETH in three ways:
Payable Functions: Functions marked payable allow ETH to be sent directly.
Fallback Functions: Triggered when no function matches or when data is sent with ETH.
Receive Functions: Special functions for receiving ETH without data (msg.data is empty).
These methods can be exploited if state updates happen after sending ETH, enabling reentrancy attacks.
What You SHOULD Do
- Use the “Checks-Effects-Interactions” Pattern
Check: Validate conditions (e.g., “Does the user have enough balance?”).
Effect: Update the contract’s state (e.g., “Deduct the balance”).
Interact: Only then, send ETH or call another contract.
2.Use a Lock (Reentrancy Guard)
- Add a “locked” variable to stop reentering the same function.
3.Or use OpenZeppelin’s ReentrancyGuard library to make this easier.
Hence,
Avoid: Updating contract state after external calls.
Do: Validate, update, and then interact.
Extra Layer: Use a reentrancy guard for critical functions.
A small change in how you write functions can save your contract from huge losses. Let’s build secure and reliable smart contracts! 💪
Top comments (0)