DEV Community

Cover image for How Do You Prevent Reentrancy Attacks in Solidity?
Neville Adam
Neville Adam

Posted on

How Do You Prevent Reentrancy Attacks in Solidity?

Problem Faced:
A reentrancy attack occurs when an attacker re-enters a smart contract function before the previous execution completes, leading to unexpected behavior like multiple withdrawals.
**
Solution:**
Use the Checks-Effects-Interactions pattern and Solidity’s reentrancy guard modifier.

  • Check: Validate the caller and amount.
  • Effects: Update the contract’s state.
  • Interactions: Transfer ETH last.

Fix Using ReentrancyGuard:
solidity

pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract SecureContract is ReentrancyGuard {
    mapping(address => uint256) balances;

    function withdraw() external nonReentrant {
        uint256 amount = balances[msg.sender];
        require(amount > 0, "Insufficient balance");

        balances[msg.sender] = 0; // State update before transfer
        payable(msg.sender).transfer(amount);
    }
}

Enter fullscreen mode Exit fullscreen mode

Build secure, scalable, and customized blockchain solutions tailored to your business needs. From smart contract development to decentralized applications, get end-to-end services for your blockchain projects. Our blockchain development ensures seamless integration, high security, and innovative solutions for Web3, DeFi, and enterprise blockchain applications. Let’s shape the future of decentralized technology together!

DevCycle image

OpenFeature Multi-Provider: Enabling New Feature Flagging Use-Cases

DevCycle is the first feature management platform with OpenFeature built in. We pair the reliability, scalability, and security of a managed service with freedom from vendor lock-in, helping developers ship faster with true OpenFeature-native feature flagging.

Watch Full Video 🎥

Top comments (0)

Dev Diairies image

User Feedback & The Pivot That Saved The Project ↪️

We’re following the journey of a dev team building on the Stellar Network as they go from hackathon idea to funded startup, testing their product in the real world and adapting as they go.

Watch full video 🎥

👋 Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creators—let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay