Source profileQuality 89/100

nirholas/three.ws/data/skills/security/smart-contract-auditing/SKILL.md

smart-contract-auditing

Complete mastery guide for smart contract security auditing — from first principles of EVM bytecode to advanced exploit patterns. Covers manual code review methodology, automated tooling (Slither, Mythril, Foundry fuzz), common vulnerability taxonomy (reentrancy, flash-loan attacks, oracle manipulation, access control, integer math), audit report writing, severity classification (Critical/High/Medium/Low/Informational), gas optimization reviews, upgrade safety, and DeFi-specific audit checklists

Source repository stars
91
Declared platforms
0
Static risk flags
0
Last source update
2026-08-05
Source checked
2026-08-05

Decision brief

What it does—and where it fits

This skill teaches you to think like a top-tier smart contract auditor. You'll learn to find vulnerabilities that automated tools miss, write clear findings, and reason about protocol-level risks in DeFi systems.

Best for

    Not for

    • Tasks that require unconfirmed production actions or broad system permissions.
    • Environments where the pinned source and install steps cannot be inspected.

    Compatibility matrix

    Platform support, with evidence labels

    PlatformStatusEvidenceWhat to check
    CodexNot declaredNo explicit evidencePortability before use
    Claude CodeNot declaredNo explicit evidencePortability before use
    CursorNot declaredNo explicit evidencePortability before use
    Gemini CLINot declaredNo explicit evidencePortability before use
    Open the compatibility checker

    Installation

    Inspect first. Install second.

    The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.

    Source-detected install commandSource
    npx skills add https://github.com/nirholas/three.ws --skill "data/skills/security/smart-contract-auditing"
    Safe inspection promptEditorial

    Inspect the Agent Skill "smart-contract-auditing" from https://github.com/nirholas/three.ws/blob/87e97e04e6c97f570a34dc2e5906bd6911db9312/data/skills/security/smart-contract-auditing/SKILL.md at commit 87e97e04e6c97f570a34dc2e5906bd6911db9312. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.

    Workflow

    What the source asks the agent to do

    1. 01

      The Audit Process

      Draw the contract dependency graph:

      User → Router: Input validation, slippage checksRouter → Vault: Authorization, reentrancy guardsVault → Strategy: Withdrawal limits, accounting
    2. 02

      Phase 1: Scoping (Day 1)

      Review the “Phase 1: Scoping (Day 1)” section in the pinned source before continuing.

      Review and apply the “Phase 1: Scoping (Day 1)” source section.
    3. 03

      Phase 2: Architecture Review (Day 1-2)

      Draw the contract dependency graph:

      User → Router: Input validation, slippage checksRouter → Vault: Authorization, reentrancy guardsVault → Strategy: Withdrawal limits, accounting
    4. 04

      Phase 3: Line-by-Line Review (Day 2-5)

      Review the “Phase 3: Line-by-Line Review (Day 2-5)” section in the pinned source before continuing.

      Review and apply the “Phase 3: Line-by-Line Review (Day 2-5)” source section.
    5. 05

      Phase 4: Attack Simulation (Day 3-5)

      Write proof-of-concept exploits in Foundry:

      Write proof-of-concept exploits in Foundry:

    Permission review

    Static risk signals and limitations

    No configured static risk pattern was detected

    This is not proof of safety. Runtime behavior, indirect dependencies, and hidden external systems are outside the static scan.

    Evidence record

    Why each signal appears

    EvidenceSourceComputedTestedEditorial
    SignalValueEvidence typeMeaning
    Quality score89/100ComputedDocumentation, specificity, maintenance, and trust rules
    Repository stars91SourceRepository attention, not individual Skill quality
    Compatibility0 platformsSourceDeclared in the catalog source record
    Usage guideautomated source guideEditorialGenerated or reviewed according to the visible evidence level

    Pinned source

    Provenance and original SKILL.md

    Repository
    nirholas/three.ws
    Skill path
    data/skills/security/smart-contract-auditing/SKILL.md
    Commit
    87e97e04e6c97f570a34dc2e5906bd6911db9312
    License
    NOASSERTION
    Collected
    2026-08-05
    Default branch
    main
    View the original SKILL.md

    Smart Contract Auditing — From Zero to Expert

    This skill teaches you to think like a top-tier smart contract auditor. You'll learn to find vulnerabilities that automated tools miss, write clear findings, and reason about protocol-level risks in DeFi systems.

    The Auditor's Mindset

    "Your job is not to confirm the code works. It's to prove it can break."

    An auditor must think adversarially. Every function is a potential attack surface. Every external call is a trust boundary. Every assumption is a vulnerability waiting to happen.

    ┌─────────────────────────────────────────────────┐
    │              AUDITOR'S MENTAL MODEL              │
    ├─────────────────────────────────────────────────┤
    │                                                  │
    │   1. UNDERSTAND the protocol's invariants        │
    │   2. ENUMERATE every state-changing path         │
    │   3. CHALLENGE every assumption                  │
    │   4. SIMULATE adversarial scenarios              │
    │   5. VERIFY mitigations are complete             │
    │                                                  │
    │   "What must ALWAYS be true?" ← start here       │
    │   "How can I make it false?" ← then ask this     │
    │                                                  │
    └─────────────────────────────────────────────────┘
    

    Vulnerability Taxonomy

    Tier 1 — Critical (Funds at Risk)

    VulnerabilityWhat BreaksClassic Example
    ReentrancyState updated after external callThe DAO hack ($60M)
    Flash Loan AttackPrice oracle manipulation in single txbZx ($8M), Cream ($130M)
    Access ControlMissing onlyOwner / role checksParity wallet freeze ($280M)
    Unchecked Return ValuesSilent failure on transferToken transfers returning false
    Storage CollisionProxy upgrades overwriting slotsAudius governance ($6M)

    Tier 2 — High (Protocol Malfunction)

    VulnerabilityWhat BreaksHow to Spot
    Oracle ManipulationPrice feeds return stale/wrong dataCheck updatedAt staleness
    Integer Overflow/UnderflowMath wraps around (pre-0.8.0)Solidity < 0.8 without SafeMath
    Front-runningMEV bots sandwich user txsUnprotected swaps, auctions
    Denial of ServiceUnbounded loops, gas griefingArrays that grow without limit
    Signature ReplaySame sig reused across chains/contractsMissing nonce or chainId

    Tier 3 — Medium (Edge Cases)

    VulnerabilityWhat BreaksHow to Spot
    Rounding ErrorsDust accumulation, unfair distributionsDivision before multiplication
    Timestamp DependenceMiners manipulate block.timestamp±15 second tolerance
    Centralization RiskAdmin can rug (even if "trusted")Unrevoked roles, no timelock
    Missing EventsOff-chain trackers lose syncState changes without emit
    Gas OptimizationTx reverts on large setsStorage reads in loops

    The Audit Process

    Phase 1: Scoping (Day 1)

    Questions to answer before reading ANY code:
    ─────────────────────────────────────────────
    □ What does this protocol DO? (lending, DEX, vault, stablecoin?)
    □ What are the protocol invariants?
       - "Total deposits ≥ total borrows"
       - "LP token supply × price ≥ pool reserves"
       - "Collateral ratio always > liquidation threshold"
    □ What's the attack surface?
       - External entry points (public/external functions)
       - Admin/privileged functions
       - Oracle dependencies
       - Cross-contract interactions
    □ What token standards are involved? (ERC-20, ERC-721, ERC-4626, rebasing?)
    □ Is it upgradeable? (proxy pattern? UUPS? Transparent?)
    □ What chains is it deployed on? (different precompiles, EIPs)
    

    Phase 2: Architecture Review (Day 1-2)

    Draw the contract dependency graph:

    ┌──────────────┐     ┌──────────────┐     ┌──────────────┐
    │   Router     │────▶│    Vault      │────▶│   Strategy   │
    │ (user entry) │     │ (holds funds) │     │ (deploys $)  │
    └──────────────┘     └──────┬───────┘     └──────────────┘
                                │
                         ┌──────▼───────┐
                         │  PriceOracle  │
                         │ (Chainlink)   │
                         └──────────────┘
    

    Identify trust boundaries:

    • User → Router: Input validation, slippage checks
    • Router → Vault: Authorization, reentrancy guards
    • Vault → Strategy: Withdrawal limits, accounting
    • Vault → Oracle: Staleness checks, deviation bounds

    Phase 3: Line-by-Line Review (Day 2-5)

    Checklist Per Function

    // For EVERY external/public function, verify:
    
    // 1. ACCESS CONTROL
    // ✓ Who can call this? Is that correct?
    // ✓ Are modifiers applied? (onlyOwner, onlyRole, whenNotPaused)
    
    // 2. INPUT VALIDATION
    // ✓ Are all parameters validated? (address != 0, amount > 0)
    // ✓ Are array lengths bounded?
    // ✓ Can attacker pass malicious calldata?
    
    // 3. STATE CHANGES
    // ✓ Is state updated BEFORE external calls? (CEI pattern)
    // ✓ Are all related state variables updated atomically?
    // ✓ Can this function be called recursively? (reentrancy)
    
    // 4. EXTERNAL CALLS
    // ✓ Is the target trusted? What if it's a malicious contract?
    // ✓ Are return values checked?
    // ✓ Is the call wrapped in try/catch where needed?
    
    // 5. MATH
    // ✓ Division before multiplication? (precision loss)
    // ✓ Can values overflow? (unlikely in 0.8+ but check casts)
    // ✓ Zero denominators? (division by zero)
    // ✓ Rounding direction — who benefits? (always round against user)
    
    // 6. TOKEN HANDLING
    // ✓ Fee-on-transfer tokens? (actual received != amount sent)
    // ✓ Rebasing tokens? (balance changes between snapshots)
    // ✓ ERC-777 hooks? (potential reentrancy via tokensReceived)
    // ✓ Return value check? (some tokens don't return bool)
    
    // 7. EVENTS
    // ✓ Is every state change emitted?
    // ✓ Are indexed fields correct for off-chain filtering?
    

    Phase 4: Attack Simulation (Day 3-5)

    Write proof-of-concept exploits in Foundry:

    // test/audit/ReentrancyPoC.t.sol
    contract ReentrancyAttack is Test {
        Vault vault;
        AttackerContract attacker;
    
        function setUp() public {
            vault = new Vault();
            attacker = new AttackerContract(address(vault));
            // Fund vault with 100 ETH
            deal(address(vault), 100 ether);
            // Attacker deposits 1 ETH
            deal(address(attacker), 1 ether);
            attacker.deposit{value: 1 ether}();
        }
    
        function testReentrancyDrain() public {
            uint256 vaultBefore = address(vault).balance;
            attacker.attack();
            uint256 vaultAfter = address(vault).balance;
            // If vault is drained, reentrancy exists
            assertLt(vaultAfter, vaultBefore / 2, "Vault should be drained");
        }
    }
    

    Fuzz Testing for Edge Cases

    function testFuzz_withdrawNeverExceedsBalance(
        uint256 depositAmount,
        uint256 withdrawAmount
    ) public {
        depositAmount = bound(depositAmount, 1, 1e30);
        withdrawAmount = bound(withdrawAmount, 0, depositAmount);
    
        vault.deposit(depositAmount);
        vault.withdraw(withdrawAmount);
    
        assertGe(
            vault.balanceOf(address(this)),
            depositAmount - withdrawAmount,
            "Balance invariant violated"
        );
    }
    

    Automated Tooling

    Use tools to AUGMENT manual review, never replace it.

    ToolBest ForCatchesMisses
    SlitherStatic analysisCommon patterns, reentrancy, uninitialized varsBusiness logic
    MythrilSymbolic executionInteger overflow, assert violationsComplex DeFi logic
    EchidnaProperty-based fuzzingInvariant violationsRequires good properties
    Foundry FuzzTargeted fuzzingEdge cases in mathRequires test writing
    4naly3erGas + info findingsOptimization, best practicesNo security findings
    AderynRust-based static analysisFast pattern matchingLimited rule set

    Running an Automated Pass

    # Static analysis
    slither . --print human-summary
    slither . --detect reentrancy-eth,reentrancy-no-eth,unchecked-transfer
    
    # Symbolic execution
    myth analyze contracts/Vault.sol --solv 0.8.20 --execution-timeout 300
    
    # Property-based fuzzing
    echidna . --contract VaultTest --test-mode assertion --test-limit 50000
    

    DeFi-Specific Audit Checklists

    Lending Protocol Checklist

    □ Liquidation math is correct (health factor, close factor)
    □ Bad debt is handled (socializing losses or insurance fund)
    □ Interest rate model handles extreme utilization (100%)
    □ Oracle manipulation can't create instant liquidatable positions
    □ Flash loans can't manipulate collateral prices within one tx
    □ Supply/borrow caps prevent single-asset concentration
    □ Pause mechanism covers all entry points
    □ Collateral factors account for token volatility
    

    AMM / DEX Checklist

    □ Constant product invariant maintained (x * y = k)
    □ Swap cannot drain pool to zero on either side
    □ Slippage protection cannot be bypassed
    □ LP share calculation is rounding-safe
    □ Fee accounting doesn't leak value
    □ Flash swaps repay within same tx (or revert)
    □ Pool creation can't be front-run with bad initial ratio
    □ Remove liquidity handles single-sided correctly
    

    Vault / Yield Checklist (ERC-4626)

    □ Deposit/withdraw exchange rate can't be manipulated
    □ "Donation attack" prevented (first depositor gets fair shares)
    □ Strategy can't lose more than deposited (bounded loss)
    □ Emergency withdrawal bypasses strategy locks
    □ Harvest/compound doesn't benefit front-runners
    □ Share price increases monotonically (no loss of precision)
    □ Fee calculation rounds in protocol's favor
    

    Stablecoin Checklist (e.g., Sperax USDs)

    □ Peg mechanism handles de-peg scenarios
    □ Collateral ratio maintained above safety threshold
    □ Rebasing doesn't break integrating contracts
    □ Mint/redeem can't be sandwich attacked
    □ Oracle failure triggers protective pause
    □ Collateral diversification limits enforced
    □ Emergency redemption path exists
    □ Yield distribution is fair across all holders
    

    Writing Audit Reports

    Finding Format

    ## [H-01] Reentrancy in Vault.withdraw() allows complete fund drainage
    
    **Severity**: High
    **Status**: Open
    **Location**: Vault.sol#L142-L158
    
    ### Description
    The `withdraw()` function sends ETH to the caller before updating
    the `balances` mapping, allowing a malicious contract to re-enter
    and withdraw repeatedly.
    
    ### Impact
    An attacker can drain the entire vault balance in a single transaction.
    
    ### Proof of Concept
    [Link to PoC test]
    
    ### Recommendation
    Apply the Checks-Effects-Interactions pattern:
    

    Severity Classification

    SeverityCriteriaExample
    CriticalDirect loss of funds, no user interaction neededReentrancy drain, access control bypass
    HighLoss of funds with some conditionsOracle manipulation + flash loan
    MediumFunds not at immediate risk, protocol malfunctionDoS, griefing, incorrect accounting
    LowBest practice violations, minor issuesMissing events, suboptimal patterns
    InformationalSuggestions, gas optimizationsUse immutable, cache storage reads

    Common Patterns — What Good Code Looks Like

    Checks-Effects-Interactions (CEI)

    // ✅ CORRECT — state updated before external call
    function withdraw(uint256 amount) external {
        require(balances[msg.sender] >= amount);  // Check
        balances[msg.sender] -= amount;            // Effect
        (bool ok,) = msg.sender.call{value: amount}(""); // Interaction
        require(ok);
    }
    

    Pull Over Push

    // ✅ CORRECT — users withdraw, contract doesn't push
    mapping(address => uint256) public pendingWithdrawals;
    
    function claimReward() external {
        uint256 amount = pendingWithdrawals[msg.sender];
        pendingWithdrawals[msg.sender] = 0;
        token.safeTransfer(msg.sender, amount);
    }
    

    Access Control with Timelock

    // ✅ CORRECT — admin actions have delay
    function queueAction(bytes32 actionHash) external onlyAdmin {
        timelockExpiry[actionHash] = block.timestamp + 48 hours;
        emit ActionQueued(actionHash);
    }
    
    function executeAction(bytes32 actionHash) external onlyAdmin {
        require(block.timestamp >= timelockExpiry[actionHash], "Too early");
        delete timelockExpiry[actionHash];
        _execute(actionHash);
    }
    

    Sperax Ecosystem Audit Considerations

    When auditing protocols that integrate with Sperax:

    • USDs Rebasing: USDs balances change every rebase. Contracts holding USDs must handle balanceOf() returning different values between blocks without any transfer occurring
    • SPA Staking: veSPA lock periods create time-weighted voting power; verify governance contracts weight correctly
    • ERC-8004 Agents: On-chain agent identity NFTs — verify agent metadata is immutable post-registration and reputation scores can't be manipulated
    • Farms Rewards: Sperax Farms distribute rewards per-block; verify rewardPerToken() accumulator handles zero-supply edge case

    Resources for Continued Learning

    ResourceTypeLevel
    Damn Vulnerable DeFiCTF challengesIntermediate
    EthernautCTF challengesBeginner
    Solidity by Example — HacksCode examplesBeginner
    Immunefi Bug BountyReal bountiesAdvanced
    Trail of Bits blogResearch articlesAdvanced
    Spearbit reportsReal audit reportsAdvanced

    Alternatives

    Compare before choosing