DEV Community

Mahima Thacker
Mahima Thacker

Posted on

Reentrancy Attacks - The Hidden Threat in Smart Contracts 😵‍💫

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?

  1. 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

  2. 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:

  1. Payable Functions: Functions marked payable allow ETH to be sent directly.

  2. Fallback Functions: Triggered when no function matches or when data is sent with ETH.

  3. 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

  1. 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.

Image description

2.Use a Lock (Reentrancy Guard)

  • Add a “locked” variable to stop reentering the same function.

Image description

3.Or use OpenZeppelin’s ReentrancyGuard library to make this easier.

Image description

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! 💪

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs