2 Maret 20269 min read

Web3 Security Fundamentals & Battle-Tested Solidity Design Patterns

Preventing reentrancy attacks, integer overflow, flash loan exploits, and implementing upgradeable smart contracts with OpenZeppelin.

Web3SolidityEthereumBlockchainSecurity

Smart contract development is unforgiving: once deployed to the Ethereum Virtual Machine (EVM), immutable code holds financial value. A single reentrancy vulnerability can result in catastrophic exploits.


1. Checks-Effects-Interactions (CEI) Pattern

The gold standard for preventing reentrancy attacks is strictly adhering to the CEI pattern:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

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

    event Withdrawn(address indexed user, uint256 amount);

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

        // 2. EFFECTS (Update state BEFORE external call)
        balances[msg.sender] -= amount;

        // 3. INTERACTIONS (External transfer)
        (bool success, ) = payable(msg.sender).call{value: amount}("");
        require(success, "Transfer failed");

        emit Withdrawn(msg.sender, amount);
    }
}

2. Safe Oracle Pricing Against Flash Loan Attacks

Never rely on spot prices from Uniswap AMM pools without a Time-Weighted Average Price (TWAP) or Chainlink Decentralized Oracle:

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumer {
    AggregatorV3Interface internal priceFeed;

    constructor(address oracleAddress) {
        priceFeed = AggregatorV3Interface(oracleAddress);
    }

    function getLatestPrice() public view returns (int256) {
        (
            /* uint80 roundID */,
            int256 price,
            /* uint startedAt */,
            uint256 timeStamp,
            /* uint80 answeredInRound */
        ) = priceFeed.latestRoundData();
        
        require(timeStamp > 0, "Round not complete");
        require(block.timestamp - timeStamp < 3600, "Stale price feed");
        return price;
    }
}

Thorough testing with Foundry and continuous automated auditing ensure mission-critical smart contract safety.

Bagikan

Artikel lainnya