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);
}
}
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!
Top comments (0)