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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up