🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Ethereum Security Audit Guide

Blockchain DevelopmentđŸŸĸ Free Lesson

Ethereum Security Audit Guide

Overview

Smart contract security is paramount due to the immutable nature of blockchain. This guide covers vulnerabilities, prevention techniques, and audit methodologies.

Security Audit FrameworkCriticalâ€ĸ Reentrancyâ€ĸ Integer Overflowâ€ĸ Access Controlâ€ĸ Flash Loansâ€ĸ Oracle Manipulationâ€ĸ Front-RunningHighâ€ĸ Delegatecallâ€ĸ Selfdestructâ€ĸ Denial of Serviceâ€ĸ Price Manipulationâ€ĸ Governance Attacksâ€ĸ Logic ErrorsMediumâ€ĸ Timestamp Dependenceâ€ĸ Gas Limit Issuesâ€ĸ Rounding Errorsâ€ĸ Unchecked Returnâ€ĸ MEV Extractionâ€ĸ Privacy LeaksLowâ€ĸ Styleâ€ĸ Namingâ€ĸ Commentsâ€ĸ Gas HintsAudit ProcessReconnaissance → Static Analysis → Manual Review → Dynamic Testing → ReportStatic AnalysisSlither, MythrilDynamic AnalysisEchidna, MedusaFormal VerificationCertora, Halmos

Common Vulnerabilities

Reentrancy Attack

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

// ❌ VULNERABLE: Reentrancy attack
contract VulnerableVault {
    mapping(address => uint256) public balances;
    
    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }
    
    function withdraw() public {
        uint256 balance = balances[msg.sender];
        require(balance > 0, "No balance");
        
        // ❌ External call before state update
        (bool success, ) = msg.sender.call{value: balance}("");
        require(success, "Transfer failed");
        
        balances[msg.sender] = 0; // State updated after external call
    }
}

// Attacker contract
contract Attacker {
    VulnerableVault public vault;
    
    constructor(address _vault) {
        vault = VulnerableVault(_vault);
    }
    
    function attack() external payable {
        vault.deposit{value: 1 ether}();
        vault.withdraw();
    }
    
    receive() external payable {
        if (address(vault).balance >= 1 ether) {
            vault.withdraw(); // Re-enter before balance is set to 0
        }
    }
}

// ✅ SECURE: ReentrancyGuard
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract SecureVault is ReentrancyGuard {
    mapping(address => uint256) public balances;
    
    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }
    
    function withdraw() public nonReentrant {
        uint256 balance = balances[msg.sender];
        require(balance > 0, "No balance");
        
        // ✅ State update before external call
        balances[msg.sender] = 0;
        
        (bool success, ) = msg.sender.call{value: balance}("");
        require(success, "Transfer failed");
    }
}

// ✅ SECURE: Checks-Effects-Interactions pattern
contract SecureVault2 {
    mapping(address => uint256) public balances;
    
    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }
    
    function withdraw() public {
        uint256 balance = balances[msg.sender];
        
        // Checks
        require(balance > 0, "No balance");
        
        // Effects
        balances[msg.sender] = 0;
        
        // Interactions
        (bool success, ) = msg.sender.call{value: balance}("");
        require(success, "Transfer failed");
    }
}

Access Control Vulnerability

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

// ❌ VULNERABLE: Missing access control
contract VulnerableToken {
    address public owner;
    mapping(address => uint256) public balances;
    
    constructor() {
        owner = msg.sender;
    }
    
    // ❌ Anyone can mint tokens
    function mint(address to, uint256 amount) public {
        balances[to] += amount;
    }
    
    // ❌ Anyone can transfer ownership
    function transferOwnership(address newOwner) public {
        owner = newOwner;
    }
}

// ✅ SECURE: Role-based access control
import "@openzeppelin/contracts/access/AccessControl.sol";

contract SecureToken is AccessControl {
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    
    mapping(address => uint256) public balances;
    
    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(ADMIN_ROLE, msg.sender);
        _grantRole(MINTER_ROLE, msg.sender);
    }
    
    function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
        balances[to] += amount;
    }
    
    function transferOwnership(address newOwner) public onlyRole(ADMIN_ROLE) {
        _grantRole(DEFAULT_ADMIN_ROLE, newOwner);
        _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }
}

// ✅ SECURE: Ownable pattern
import "@openzeppelin/contracts/access/Ownable.sol";

contract SecureToken2 is Ownable {
    mapping(address => uint256) public balances;
    
    function mint(address to, uint256 amount) public onlyOwner {
        balances[to] += amount;
    }
}

Flash Loan Attack Prevention

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

// ❌ VULNERABLE: Flash loan manipulation
contract VulnerableDEX {
    mapping(address => mapping(address => uint256)) reserves;
    
    function swap(
        address tokenIn,
        address tokenOut,
        uint256 amountIn
    ) external returns (uint256) {
        uint256 reserveIn = reserves[tokenIn][tokenOut];
        uint256 reserveOut = reserves[tokenOut][tokenIn];
        
        // ❌ No protection against flash loans
        uint256 amountOut = (amountIn * reserveOut) / (reserveIn + amountIn);
        
        reserves[tokenIn][tokenOut] += amountIn;
        reserves[tokenOut][tokenIn] -= amountOut;
        
        return amountOut;
    }
}

// ✅ SECURE: TWAP (Time-Weighted Average Price)
contract SecureDEX {
    mapping(address => mapping(address => uint256)) reserves;
    mapping(address => mapping(address => uint256)) priceCumulative;
    mapping(address => mapping(address => uint256)) lastTimestamp;
    
    function update() public {
        for (uint256 i = 0; i < tokenPairs.length; i++) {
            (address tokenA, address tokenB) = tokenPairs[i];
            
            uint256 timeElapsed = block.timestamp - lastTimestamp[tokenA][tokenB];
            
            priceCumulative[tokenA][tokenB] += reserves[tokenB][tokenA] * timeElapsed;
            priceCumulative[tokenB][tokenA] += reserves[tokenA][tokenB] * timeElapsed;
            
            lastTimestamp[tokenA][tokenB] = block.timestamp;
        }
    }
    
    function getTWAP(
        address tokenA,
        address tokenB,
        uint256 period
    ) public view returns (uint256) {
        uint256 priceCumulativeEnd = priceCumulative[tokenA][tokenB];
        uint256 timeElapsed = block.timestamp - lastTimestamp[tokenA][tokenB];
        
        require(timeElapsed >= period, "Period not elapsed");
        
        return priceCumulativeEnd / timeElapsed;
    }
    
    function swap(
        address tokenIn,
        address tokenOut,
        uint256 amountIn
    ) external returns (uint256) {
        uint256 twap = getTWAP(tokenIn, tokenOut, 1800); // 30 min TWAP
        
        uint256 amountOut = (amountIn * twap) / 1e18;
        
        // Execute swap with TWAP protection
        return amountOut;
    }
}

Oracle Manipulation Prevention

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

// ❌ VULNERABLE: Single oracle
contract VulnerableLending {
    IPriceOracle public oracle;
    
    function getPrice(address token) public view returns (uint256) {
        return oracle.getPrice(token); // ❌ Single point of failure
    }
    
    function borrow(uint256 amount, address collateral) public {
        uint256 price = getPrice(collateral);
        uint256 collateralValue = (amount * price) / 1e18;
        require(collateralValue >= amount * 150 / 100, "Insufficient collateral");
    }
}

// ✅ SECURE: Multi-oracle with circuit breaker
contract SecureLending {
    IPriceOracle[] public oracles;
    uint256 public constant MAX_DEVIATION = 10; // 10% max deviation
    uint256 public lastValidPrice;
    uint256 public lastPriceUpdate;
    
    constructor(address[] memory _oracles) {
        for (uint256 i = 0; i < _oracles.length; i++) {
            oracles.push(IPriceOracle(_oracles[i]));
        }
    }
    
    function getMedianPrice(address token) public view returns (uint256) {
        uint256[] memory prices = new uint256[](oracles.length);
        
        for (uint256 i = 0; i < oracles.length; i++) {
            prices[i] = oracles[i].getPrice(token);
        }
        
        // Sort prices
        for (uint256 i = 0; i < prices.length - 1; i++) {
            for (uint256 j = 0; j < prices.length - i - 1; j++) {
                if (prices[j] > prices[j + 1]) {
                    (prices[j], prices[j + 1]) = (prices[j + 1], prices[j]);
                }
            }
        }
        
        // Return median
        return prices[prices.length / 2];
    }
    
    function getPriceWithDeviationCheck(address token) public returns (uint256) {
        uint256 medianPrice = getMedianPrice(token);
        
        // Check deviation from last valid price
        if (lastValidPrice > 0) {
            uint256 deviation = (medianPrice > lastValidPrice)
                ? ((medianPrice - lastValidPrice) * 100) / lastValidPrice
                : ((lastValidPrice - medianPrice) * 100) / lastValidPrice;
            
            require(deviation <= MAX_DEVIATION, "Price deviation too high");
        }
        
        lastValidPrice = medianPrice;
        lastPriceUpdate = block.timestamp;
        
        return medianPrice;
    }
    
    function borrow(uint256 amount, address collateral) public {
        uint256 price = getPriceWithDeviationCheck(collateral);
        uint256 collateralValue = (amount * price) / 1e18;
        require(collateralValue >= amount * 150 / 100, "Insufficient collateral");
    }
}

interface IPriceOracle {
    function getPrice(address token) external view returns (uint256);
}

Audit Checklist

CategoryCheck ItemSeverity
Access ControlOwner/admin functions protectedCritical
Role-based access implementedHigh
No hardcoded addressesMedium
ReentrancyChecks-Effects-InteractionsCritical
ReentrancyGuard usedHigh
No external calls in loopsHigh
Integer SafetySolidity 0.8+ usedCritical
SafeMath for older versionsCritical
No unchecked arithmetic in critical pathsHigh
OracleMulti-oracle implementationHigh
TWAP for price feedsHigh
Circuit breakersHigh
Flash LoansTime-weighted pricesHigh
Delay mechanismsMedium
Multi-block confirmationMedium
UpgradeabilityProxy pattern secureHigh
Storage layout preservedCritical
Initialization functionsHigh
GasNo unbounded loopsMedium
Storage packing optimizedLow
Batch operationsLow

Formal Verification Tools

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

// Certora specification (in .spec file)
// contract MyToken {
//     function transfer(address to, uint256 amount) external returns (bool);
// }

// Rule: Total supply should remain constant after transfer
// rule totalSupplyConstant {
//     uint256 supplyBefore = totalSupply();
//     
//     env e;
//     address to; uint256 amount;
//     transfer(e, to, amount);
//     
//     uint256 supplyAfter = totalSupply();
//     assert supplyBefore == supplyAfter;
// }

// Rule: Balance conservation
// rule balanceConservation {
//     env e;
//     address from; address to; uint256 amount;
//     
//     uint256 fromBefore = balanceOf(e, from);
//     uint256 toBefore = balanceOf(e, to);
//     
//     transfer(e, to, amount);
//     
//     uint256 fromAfter = balanceOf(e, from);
//     uint256 toAfter = balanceOf(e, to);
//     
//     assert fromBefore - amount == fromAfter;
//     assert toBefore + amount == toAfter;
// }

// Halmos symbolic testing
contract TokenProperties {
    MyToken public token;
    
    function setUp() public {
        token = new MyToken("Test", "TST");
    }
    
    function testTransferPreservesTotalSupply(
        address from,
        address to,
        uint256 amount
    ) public {
        vm.assume(from != address(0) && to != address(0));
        vm.assume(from != to);
        
        token.mint(from, amount);
        
        uint256 supplyBefore = token.totalSupply();
        
        vm.prank(from);
        token.transfer(to, amount);
        
        uint256 supplyAfter = token.totalSupply();
        
        assert(supplyBefore == supplyAfter);
    }
}

Bug Bounty Programs

ProtocolPlatformMax PayoutScope
UniswapImmunefi$3,000,000Core contracts
AaveImmunefi$250,000All contracts
CompoundImmunefi$150,000All contracts
MakerDAOHackerOne$10,000Governance
LidoImmunefi$250,000Staking
// Bug bounty submission template
/*
1. Vulnerability Title: [Title]
2. Severity: Critical/High/Medium/Low
3. Vulnerability Type: [e.g., Reentrancy]
4. Affected Contract: [Contract address]
5. Vulnerability Description: [Detailed description]
6. Impact: [What can an attacker do?]
7. Proof of Concept: [Code or steps to reproduce]
8. Recommended Fix: [Suggested solution]
*/

Real-World Attack Examples

AttackDateLossVulnerability
DAO Hack2016$60MReentrancy
Parity Wallet2017$150MAccess Control
Cream Finance2021$130MFlash Loan
Mango Markets2022$114MOracle Manipulation
Euler Finance2023$197MFlash Loan

Gas Cost of Security

Security MeasureGas CostImplementation
ReentrancyGuard+2,600OpenZeppelin
Access Control+1,500OpenZeppelin
Pause Mechanism+2,500OpenZeppelin
Multi-sig+5,000Custom
Time Lock+5,000Custom
Circuit Breaker+3,000Custom

Interview Questions

  1. Explain the reentrancy vulnerability and how to prevent it.

    • Answer: Reentrancy occurs when a contract makes an external call before updating state, allowing the called contract to re-enter the first function. Prevention includes: using the Checks-Effects-Interactions pattern (validate, update state, then interact), using ReentrancyGuard from OpenZeppelin, and avoiding external calls in loops. The DAO hack in 2016 was a famous reentrancy attack.
  2. What is the difference between a flash loan attack and front-running?

    • Answer: Flash loan attacks use borrowed funds (must be repaid in same transaction) to manipulate prices or exploit vulnerabilities. Front-running involves observing pending transactions and submitting your own first to profit. Flash loans require technical sophistication but can be atomic; front-running requires monitoring the mempool and quick execution.
  3. How would you design a secure oracle system?

    • Answer: Use multiple independent oracle sources, implement TWAP (Time-Weighted Average Price) to prevent manipulation, add circuit breakers that halt operations if price deviates too much, use median rather than average to reduce outlier impact, and implement delay mechanisms for large price changes. Chainlink is a common decentralized oracle solution.

Quiz Questions

  1. Which OpenZeppelin contract prevents reentrancy attacks?

    • A) Ownable
    • B) Pausable
    • C) ReentrancyGuard
    • D) AccessControl
  2. What is the recommended pattern to prevent reentrancy?

    • A) Checks-Interactions-Effects
    • B) Effects-Checks-Interactions
    • C) Checks-Effects-Interactions
    • D) Interactions-Effects-Checks
  3. Which oracle manipulation prevention technique uses average prices over time?

    • A) Single oracle
    • B) TWAP (Time-Weighted Average Price)
    • C) Median price
    • D) Circuit breaker
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement