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

Smart Contract Security

Blockchain DevelopmentđŸŸĸ Free Lesson

Smart Contract Security

Overview

Smart contract security is paramount due to the immutable nature of blockchain. A single vulnerability can result in irreversible loss of funds.

âš ī¸

Smart contracts handle real money. Always conduct thorough security audits, use established patterns, and test extensively before deployment.

Security Landscape

Smart Contract Threat LandscapeSmartContractReentrancyOverflow/UnderflowAccess ControlFront-runningOracle ManipulationFlash LoanPrice ManipulationLogic ErrorsOver $3B lost to vulnerabilities since 2016Source: Rekt News, DeFi Llama

Reentrancy Attacks

The Classic Vulnerability

// VULNERABLE CONTRACT - DO NOT USE
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");
        
        // VULNERABLE: External call before state update
        (bool success, ) = msg.sender.call{value: balance}("");
        require(success, "Transfer failed");
        
        balances[msg.sender] = 0;  // Too late!
    }
}

Attack Flow

Reentrancy Attack FlowAttackerContractVictimVaultAttackerEOA1. Withdraw()2. External call to attacker fallback3. Attacker calls withdraw() again (recursive)4. Drain all funds before balance update

Prevention: Checks-Effects-Interactions

// SECURE CONTRACT
contract SecureVault {
    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");
        
        // CHECKS: Validate conditions
        require(balance <= address(this).balance, "Insufficient contract balance");
        
        // EFFECTS: Update state BEFORE external call
        balances[msg.sender] = 0;
        
        // INTERACTIONS: External call
        (bool success, ) = msg.sender.call{value: balance}("");
        require(success, "Transfer failed");
    }
}

Reentrancy Guard

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

abstract contract ReentrancyGuard {
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;
    
    uint256 private _status;
    
    error ReentrantCall();
    
    constructor() {
        _status = _NOT_ENTERED;
    }
    
    modifier nonReentrant() {
        if (_status == _ENTERED) revert ReentrantCall();
        _status = _ENTERED;
        _;
        _status = _NOT_ENTERED;
    }
    
    function _getReentrancyStatus() internal view returns (uint256) {
        return _status;
    }
}

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

Integer Overflow/Underflow

Pre-0.8.x Vulnerability

// VULNERABLE (Solidity < 0.8.0)
contract OverflowVulnerable {
    mapping(address => uint8) public balances;
    
    function transfer(address to, uint8 amount) public {
        // Overflow possible!
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }
}

Protection Patterns

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

contract OverflowProtected {
    mapping(address => uint256) public balances;
    
    // Solidity 0.8.x has built-in overflow checks
    function safeTransfer(address to, uint256 amount) public {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        
        // Automatic overflow protection
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }
    
    // Unchecked for gas optimization (when overflow impossible)
    function optimizedTransfer(address to, uint256 amount) public {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        
        unchecked {
            // Safe because we checked above
            balances[msg.sender] -= amount;
            balances[to] += amount;
        }
    }
}

Access Control

Vulnerable Access Control

// VULNERABLE
contract VulnerableAccess {
    address public owner;
    
    constructor() {
        owner = msg.sender;
    }
    
    // Missing access control!
    function changeOwner(address newOwner) public {
        owner = newOwner;
    }
}

Secure Access Control Patterns

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

contract AccessControl {
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    
    mapping(address => mapping(bytes32 => bool)) private _roles;
    
    event RoleGranted(bytes32 indexed role, address indexed account);
    event RoleRevoked(bytes32 indexed role, address indexed account);
    
    constructor() {
        _roles[msg.sender][ADMIN_ROLE] = true;
    }
    
    modifier onlyRole(bytes32 role) {
        require(hasRole(role, msg.sender), "Unauthorized");
        _;
    }
    
    function hasRole(bytes32 role, address account) public view returns (bool) {
        return _roles[account][role];
    }
    
    function grantRole(bytes32 role, address account) public onlyRole(ADMIN_ROLE) {
        _roles[account][role] = true;
        emit RoleGranted(role, account);
    }
    
    function revokeRole(bytes32 role, address account) public onlyRole(ADMIN_ROLE) {
        _roles[account][role] = false;
        emit RoleRevoked(role, account);
    }
    
    // Time-locked admin
    mapping(address => uint256) public pendingAdmins;
    uint256 public constant TIMELOCK_DELAY = 48 hours;
    
    function proposeAdmin(address newAdmin) public onlyRole(ADMIN_ROLE) {
        pendingAdmins[newAdmin] = block.timestamp + TIMELOCK_DELAY;
    }
    
    function acceptAdmin(address newAdmin) public {
        require(pendingAdmins[newAdmin] != 0, "Not proposed");
        require(block.timestamp >= pendingAdmins[newAdmin], "Too early");
        
        _roles[newAdmin][ADMIN_ROLE] = true;
        delete pendingAdmins[newAdmin];
    }
}

Front-Running Attacks

Attack Vector

Front-Running AttackUser TXBroadcastAttacker TXHigher GasAttacker TXExecutedUser TXExecutedTime →Legitimate UserAttackerMiner/Validator

Mitigation: Commit-Reveal

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

contract CommitReveal {
    mapping(bytes32 => bool) public commitments;
    mapping(address => uint256) public nonces;
    
    event CommitmentMade(bytes32 indexed commitment);
    event Revealed(address indexed sender, uint256 value);
    
    function commit(bytes32 commitment) external {
        require(!commitments[commitment], "Commitment exists");
        
        commitments[commitment] = true;
        emit CommitmentMade(commitment);
    }
    
    function reveal(uint256 value, bytes32 salt) external {
        bytes32 commitment = keccak256(abi.encodePacked(msg.sender, value, salt));
        require(commitments[commitment], "Invalid commitment");
        
        delete commitments[commitment];
        
        emit Revealed(msg.sender, value);
    }
}

Mitigation: Slippage Protection

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

contract SlippageProtection {
    function swap(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,  // Slippage tolerance
        uint256 deadline       // Time limit
    ) external {
        require(block.timestamp <= deadline, "Expired");
        
        uint256 amountOut = _getAmountOut(tokenIn, tokenOut, amountIn);
        require(amountOut >= minAmountOut, "Slippage exceeded");
        
        // Execute swap
    }
    
    function _getAmountOut(address tokenIn, address tokenOut, uint256 amountIn) 
        internal pure returns (uint256) 
    {
        // AMM calculation
        return amountIn; // Placeholder
    }
}

Oracle Manipulation

Attack Vector

// VULNERABLE: Using spot price
contract VulnerableOracle {
    IUniswapV2Pair public pair;
    
    function getPrice() public view returns (uint256) {
        // VULNERABLE: Single block price can be manipulated
        (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();
        return (uint256(reserve1) * 1e18) / uint256(reserve0);
    }
}

Mitigation: TWAP Oracle

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

contract TWAPOracle {
    struct Observation {
        uint256 timestamp;
        uint256 priceCumulative;
    }
    
    Observation public lastObservation;
    uint256 public constant PERIOD = 1 hours;
    
    function update(uint256 price) external {
        uint256 timeElapsed = block.timestamp - lastObservation.timestamp;
        
        if (timeElapsed >= PERIOD) {
            lastObservation = Observation({
                timestamp: block.timestamp,
                priceCumulative: lastObservation.priceCumulative + (price * timeElapsed)
            });
        }
    }
    
    function getPrice() public view returns (uint256) {
        require(block.timestamp >= lastObservation.timestamp + PERIOD, "Period not elapsed");
        
        return (lastObservation.priceCumulative) / PERIOD;
    }
}

Oracle Security Comparison

MethodSecurityLatencyCost
Spot PriceLowInstantLow
TWAPHigh1 hour+Medium
ChainlinkHigh5-10 minMedium
Multi-oracleVery HighVariableHigh

Flash Loan Attacks

Attack Mechanism

// Simplified flash loan attack
contract FlashLoanAttack {
    IERC20 public token;
    IUniswapV2Router public router;
    
    function executeAttack() external {
        // 1. Borrow flash loan
        uint256 borrowedAmount = 1000 ether;
        token.approve(address(this), borrowedAmount);
        
        // 2. Manipulate price oracle
        _manipulatePrice();
        
        // 3. Exploit vulnerable protocol
        _exploitVulnerableProtocol();
        
        // 4. Repay flash loan + fee
        uint256 repayAmount = borrowedAmount * 10001 / 10000; // 0.1% fee
        token.transfer(address(router), repayAmount);
    }
    
    function _manipulatePrice() internal {
        // Dump tokens to crash price
        token.transfer(address(router), 100 ether);
    }
    
    function _exploitVulnerableProtocol() internal {
        // Buy at manipulated low price
    }
}

Mitigation: Oracle Delay

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

contract FlashLoanResistant {
    uint256 public lastBlock;
    uint256 public constant DELAY = 1;
    
    modifier noFlashLoan() {
        require(block.number > lastBlock + DELAY, "Flash loan detected");
        lastBlock = block.number;
        _;
    }
    
    function criticalOperation() public noFlashLoan {
        // Safe from flash loan attacks
    }
}

Auditing Tools

Static Analysis

ToolTypeStrengths
SlitherStatic analysisFast, comprehensive
MythrilSymbolic executionDeep analysis
EchidnaFuzzingProperty testing
Securify2Static analysisPattern matching
OyenteStatic analysisEarly detection

Example: Slither Usage

# Install Slither
pip install slither-analyzer

# Run analysis
slither contract.sol

# Detectors
slither --detect reentrancy-eth,unchecked-transfer contract.sol

# Print contract summary
slither --print contract-summary contract.sol

Formal Verification

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

contract FormalVerification {
    uint256 public totalSupply;
    mapping(address => uint256) public balances;
    
    // Formal verification with Certora
    // specification: totalSupply == sum(balances)
    
    function transfer(address to, uint256 amount) public {
        require(balances[msg.sender] >= amount, "Insufficient");
        
        balances[msg.sender] -= amount;
        balances[to] += amount;
        
        // Invariant preserved: total supply unchanged
    }
    
    function mint(address to, uint256 amount) public {
        totalSupply += amount;
        balances[to] += amount;
        
        // Invariant preserved: totalSupply == sum(balances)
    }
}

Real-World Attacks

The DAO Hack (2016)

MetricValue
Loss$60M (3.6M ETH)
VulnerabilityReentrancy
ImpactEthereum hard fork
LessonChecks-Effects-Interactions

Poly Network (2021)

MetricValue
Loss$611M (later returned)
VulnerabilityAccess control
ImpactCross-chain bridge
LessonMulti-sig requirements

Wormhole (2022)

MetricValue
Loss$320M
VulnerabilitySignature verification
ImpactCross-chain bridge
LessonCryptographic verification

Security Checklist

## Smart Contract Security Checklist

### Access Control
- [ ] Owner functions protected
- [ ] Role-based access implemented
- [ ] Time locks for critical operations
- [ ] Multi-sig for high-value functions

### Reentrancy
- [ ] Checks-Effects-Interactions pattern
- [ ] Reentrancy guards on state-changing functions
- [ ] External call reentrancy considered

### Integer Safety
- [ ] Solidity 0.8.x or SafeMath
- [ ] Overflow/underflow checks
- [ ] Unchecked blocks justified

### Oracle Security
- [ ] TWAP or delayed oracle used
- [ ] Multi-oracle consensus
- [ ] Price bounds validated

### Front-Running
- [ ] Commit-reveal for sensitive data
- [ ] Slippage protection
- [ ] Deadline parameters

### Testing
- [ ] Unit tests (100% coverage)
- [ ] Integration tests
- [ ] Fuzz testing
- [ ] Formal verification

Trade-offs

Security MeasureGas CostDevelopment TimeProtection Level
Reentrancy Guard+2,600LowHigh
Access Control+5,000MediumHigh
Oracle Delay+10,000MediumHigh
Multi-sig+20,000HighVery High

Interview Questions

  1. Explain the Checks-Effects-Interactions pattern and why it prevents reentrancy attacks.

    The pattern separates validation (checks), state changes (effects), and external calls (interactions). By updating state before external calls, reentrant calls see updated state and cannot exploit the vulnerability. This is the primary defense against reentrancy.

  2. How do flash loan attacks work and what defenses exist?

    Flash loans allow borrowing large amounts within one transaction. Attackers use them to manipulate prices or exploit vulnerabilities. Defenses include: TWAP oracles, block delays, oracle updates before operations, and circuit breakers.

  3. Compare static analysis and formal verification for smart contract security.

    Static analysis (Slither, Mythril) finds common patterns quickly but may miss complex issues. Formal verification mathematically proves contract correctness but requires more effort. Use both: static analysis for quick checks, formal verification for critical invariants.

Quiz Questions

  1. What is the primary cause of the DAO hack?

    • A) Integer overflow
    • B) Reentrancy
    • C) Access control
    • D) Front-running

    Answer: B - The DAO hack was caused by a reentrancy vulnerability that allowed repeated withdrawals.

  2. Which pattern prevents reentrancy attacks?

    • A) Pull over Push
    • B) Checks-Effects-Interactions
    • C) Rate Limiting
    • D) Time Locks

    Answer: B - Checks-Effects-Interactions ensures state is updated before external calls.

  3. What is TWAP and why is it used?

    • A) Time-Weighted Average Price, for oracle security
    • B) Token Wrapped Average Price, for token wrapping
    • C) Total Weighted Average Price, for total calculation
    • D) Time-Weighted Average Pool, for pool pricing

    Answer: A - TWAP (Time-Weighted Average Price) prevents price manipulation by averaging prices over time.

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