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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more