--- name: solidity-audit version: 1.0.0 description: | Smart contract security audit workflow using Slither, Aderyn, and 104 vulnerability patterns. Generates professional audit reports with severity classification, confidence scoring, and remediation guidance. Use /solidity-audit to audit changed contracts. Use /solidity-audit --contract to target a specific contract. Use /solidity-audit --deep to run parallel domain-expert sub-agents. Use /solidity-audit --quick for fast Slither + regex scan only. Use /solidity-audit --report to generate report from existing findings. Use /solidity-audit --verify to generate Foundry PoC exploit tests. Use /solidity-audit --fuzz to generate invariant and property-based fuzz tests. Use /solidity-audit --reentrancy for focused reentrancy audit. Use /solidity-audit --access-control for focused access control audit. allowed-tools: - Read - Edit - Write - Bash - Grep - Glob - Agent - AskUserQuestion --- # Solidity Audit Skill Comprehensive smart contract security audit using automated tools (Slither, Aderyn), 104 vulnerability pattern detection, and LLM-guided semantic analysis. Produces professional audit reports. ## Arguments Parse `$ARGUMENTS` for these flags: | Flag | Behavior | |---|---| | *(none)* | Audit changed `.sol` files (git diff vs main) | | `--contract ` | Target a specific contract file | | `--deep` | Spawn parallel domain-expert sub-agents for thorough analysis | | `--quick` | Slither + regex patterns only, skip manual review | | `--reentrancy` | Focused reentrancy audit (ETH-001–005, ETH-044, ETH-081–083) | | `--access-control` | Focused access control audit (ETH-006–012, ETH-086–093) | | `--report ` | Generate report from existing scan results JSON | | `--verify` | Generate Foundry PoC exploit tests for findings | | `--fuzz` | Generate invariant and property-based fuzz tests | | `--coverage` | Run `forge coverage` after audit and report gaps | --- ## Step 1: Detect Project Structure 1. Check `foundry.toml` exists. If not, check for `hardhat.config.js/ts`. If neither, stop and inform the user. 2. Read `foundry.toml` to determine: - Source directory (`src/` or `contracts/`) - Test directory (default `test/`) - Solidity version / pragma - Remappings (for import resolution) - Fuzz run count 3. Check tool availability: ```bash slither --version 2>/dev/null aderyn --version 2>/dev/null forge --version 2>/dev/null ``` 4. Read at least 2 existing test files to understand project conventions. 5. Check for existing audit reports or security documentation. --- ## Step 2: Identify Target Contracts - **Default:** `git diff main --name-only` filtered to source `.sol` files. Exclude: test files, scripts, interfaces, libraries, mocks. - **`--contract `:** Use specified file directly. - **`--reentrancy` / `--access-control`:** Still identify targets but narrow the analysis scope. For each target contract: 1. Read the source file fully. 2. Read all imported files and inherited contracts. 3. Build a map of: external/public functions, internal/private functions, state variables, events, custom errors, modifiers, external dependencies. --- ## Step 3: Run Automated Scanners ### 3a. Run Slither (always, unless `--quick` skips it) ```bash slither --json /tmp/slither_output.json 2>/dev/null ``` Parse the JSON output: - Extract each detector result: check name, severity (High/Medium/Low/Informational), confidence, file, line, description. - Map Slither detector names to ETH-xxx IDs using this table: | Slither Detector | ETH ID | |---|---| | reentrancy-eth, reentrancy-no-eth, reentrancy-benign | ETH-001 | | tx-origin | ETH-007 | | suicidal | ETH-008 | | unprotected-upgrade | ETH-052 | | divide-before-multiply | ETH-014 | | unchecked-lowlevel, unchecked-send, unused-return | ETH-018 | | controlled-delegatecall, delegatecall-loop | ETH-019 | | low-level-calls | ETH-020 | | arbitrary-send-eth, arbitrary-send-erc20 | ETH-006 | | incorrect-equality | ETH-034 | | weak-prng | ETH-037 | | timestamp | ETH-036 | | unchecked-transfer | ETH-022 | | erc20-interface | ETH-041 | | locked-ether | ETH-032 | | uninitialized-state, uninitialized-storage, uninitialized-local | ETH-029 | | shadowing-state, shadowing-local | ETH-031 | | calls-loop, costly-loop | ETH-066 | | pragma | ETH-071 | | solc-version | ETH-072 | | encode-packed-collision | ETH-073 | | missing-zero-check | ETH-045 | ### 3b. Run Aderyn ```bash aderyn --output /tmp/aderyn_output.json 2>/dev/null ``` If JSON output is available, parse individual findings. If only markdown output, parse sections for High/Medium/Low findings with file:line references. Map Aderyn detectors to ETH-xxx IDs: | Aderyn Detector | ETH ID | |---|---| | reentrancy | ETH-001 | | tx-origin | ETH-007 | | selfdestruct | ETH-008 | | delegatecall | ETH-019 | | unchecked-return | ETH-018 | | floating-pragma | ETH-071 | | unsafe-erc20 | ETH-041 | | missing-zero-address | ETH-045 | | unbounded-loop | ETH-066 | | weak-randomness | ETH-037 | ### 3c. Run Pattern Scanner Run the Python scanner script: ```bash python3 ~/.claude/skills/solidity-audit/scripts/scan.py --output json -f /tmp/scan_results.json ``` If Python is not available or the script fails, perform manual pattern detection using the vulnerability database at `~/.claude/skills/solidity-audit/patterns/vulnerability-db.md`. For each target contract, search for patterns using grep/read. --- ## Step 4: Manual Semantic Analysis Skip this step if `--quick` flag is set. For each target contract, perform deeper analysis that regex/static tools cannot catch: ### 4a. Reentrancy Analysis (ETH-001–005, ETH-044, ETH-081–083) For every external call (`.call`, `.transfer`, `.send`, `delegatecall`, token transfers): 1. Check if state updates happen AFTER the call (CEI violation). 2. Check for `nonReentrant` modifier on the function. 3. Check for cross-function reentrancy: does another function read state that this function updates after the call? 4. Check for read-only reentrancy: do view functions return values that depend on state updated after calls? 5. For TSTORE-based locks: verify slot is namespaced (keccak256), not a small integer. ### 4b. Access Control Analysis (ETH-006–012, ETH-086–093) 1. Map all state-changing functions and their access control modifiers. 2. Identify privilege hierarchy: owner → admin → operator → user. 3. Check for single points of failure (no timelock, no multisig). 4. Check proxy initialization: `_disableInitializers()` in constructor. 5. Check EIP-7702: `tx.origin == msg.sender` no longer guarantees EOA. 6. Check `extcodesize`/`isContract` assumptions. ### 4c. DeFi Analysis (ETH-024–028, ETH-055–065, ETH-094–096) 1. Identify protocol type (AMM, lending, vault, governance, bridge). 2. Check oracle sources: spot price vs TWAP, Chainlink staleness checks. 3. Check flash loan resistance: same-block protections, snapshot-based voting. 4. Check vault share calculations: first depositor attack, donation attack. 5. Check slippage/deadline parameters. 6. Check Uniswap V4 hooks: `msg.sender == poolManager` validation. ### 4d. Storage Analysis (ETH-029–033, ETH-050, ETH-081–084) 1. For proxy contracts: verify storage layout compatibility between versions. 2. Check for storage gaps (`__gap`) in upgradeable contracts. 3. Check for ERC-7201 namespaced storage. 4. Check transient storage usage: slot collisions, cleanup, delegatecall exposure. --- ## Step 5: Merge and Deduplicate Findings Run the merger script: ```bash python3 ~/.claude/skills/solidity-audit/scripts/merge.py /tmp/slither_output.json /tmp/scan_results.json -o /tmp/merged_findings.json ``` Or perform manually: 1. **Group findings** by (file, line ± 3 lines, ETH-ID or category). 2. **Boost confidence** when multiple tools agree: - 2 tools agree → +10% confidence - 3+ tools agree → cap at 95% 3. **Apply false positive filters:** - Remove reentrancy findings where `nonReentrant` modifier IS present in function scope. - Remove overflow findings in Solidity >= 0.8.0 outside `unchecked` blocks. - Remove missing access control where `onlyOwner`/`onlyRole`/`onlyAdmin` exists. - Remove unsafe ERC20 where `safeTransfer`/`safeTransferFrom` IS used. 4. **Filter low confidence:** Remove findings below 0.70 confidence threshold. --- ## Step 6: Deep Analysis (--deep mode only) When `--deep` flag is set, spawn parallel sub-agents for thorough analysis: ``` Agent 1: Reentrancy Expert - Analyze all external call paths - Check CEI compliance for every function - Map cross-function and cross-contract reentrancy paths - Check TSTORE-based lock implementations Agent 2: Access Control Expert - Map complete privilege hierarchy - Check all state-changing functions for modifiers - Check proxy initialization and upgrade paths - Check EIP-7702 and ERC-4337 patterns Agent 3: DeFi/Oracle Expert - Identify protocol type and economic model - Check oracle manipulation resistance - Check flash loan attack vectors - Check vault share inflation - Check MEV/sandwich resistance Agent 4: Adversary Reviewer - Review ALL findings from Agents 1-3 - Attempt to disprove each finding - Classify as: TRUE POSITIVE, FALSE POSITIVE, DOWNGRADE, UPGRADE - Only findings confirmed by adversary are included ``` Each agent reads the target contracts and the vulnerability patterns database. After all agents complete, merge their findings with the automated scan results. Confidence adjustments in deep mode: - Single agent finding: base 60-85% - Two agents agree: +10% - Three+ agents agree: cap 95% - Adversary confirms: +5% - Adversary disproves: rejected --- ## Step 7: Generate Report ### Security Score ``` Score = 100 - (Critical × 15) - (High × 8) - (Medium × 3) - (Low × 1) ``` | Score | Risk Level | |---|---| | 90-100 | Minimal Risk | | 70-89 | Low Risk | | 50-69 | Medium Risk | | 25-49 | High Risk | | 0-24 | Critical Risk | ### Report Structure Generate a professional audit report following the template at `~/.claude/skills/solidity-audit/templates/report.md`. The report includes: 1. **Executive Summary** — Security score, risk level, key findings, recommendation. 2. **Scope & Methodology** — Contracts audited, tools used, analysis techniques. 3. **Findings Overview** — Table grouped by severity with counts. 4. **Detailed Findings** — Each finding with: ID, title, severity, confidence, file:line, description, impact, code snippet, recommendation. 5. **Recommendations** — Immediate (CRITICAL/HIGH), short-term (MEDIUM), long-term (LOW/INFO). 6. **Appendix** — Score formula, tool versions, vulnerability pattern references. Run the report generator: ```bash python3 ~/.claude/skills/solidity-audit/scripts/report.py /tmp/merged_findings.json -o audit-report.md --project "" ``` Or generate manually following the template. --- ## Step 8: Generate Exploit PoCs (--verify mode) For each CRITICAL and HIGH finding, generate a Foundry PoC test: 1. **Reentrancy (ETH-001–004):** Attacker contract with `receive()` that re-enters the vulnerable function. 2. **Access Control (ETH-006, 009, 010):** Call privileged function from non-owner address. 3. **Oracle Manipulation (ETH-024, 025):** Flash loan → manipulate price → profit. 4. **Vault Inflation (ETH-057, 058):** First depositor front-runs second depositor. 5. **Signature Replay (ETH-038, 039):** Replay valid signature on different chain/nonce. Place PoC tests in `test/exploits/` directory. Run them: ```bash forge test --match-path "test/exploits/" -vvvv ``` Report status: VERIFIED (test passes = vuln confirmed), DISPROVED (test fails = false positive), ERROR (compilation/runtime error). --- ## Step 9: Generate Fuzz Tests (--fuzz mode) Generate Foundry invariant tests and optionally Echidna property tests: 1. **Reentrancy invariants:** Balance consistency after any call sequence. 2. **Access control fuzz:** Random caller rejection from admin functions. 3. **Arithmetic fuzz:** No overflow/underflow with extreme inputs. 4. **Oracle fuzz:** Protocol handles extreme prices gracefully. 5. **Vault invariants:** Share price stability, first depositor fairness. 6. **DoS fuzz:** Operations complete within gas bounds for large inputs. Place fuzz tests in `test/invariants/` directory. Run them: ```bash forge test --match-test "invariant" -vvv --fuzz-runs 1000 ``` --- ## Step 10: Final Report Output a summary: ``` Solidity Audit Results ──────────────────────────────────── Project: Contracts: N analyzed Tools: Slither, Aderyn, Pattern Scanner Mode: Standard | Deep | Quick Findings: Critical: N High: N Medium: N Low: N Info: N Total: N Security Score: XX/100 (Risk Level) Top Findings: 1. [CRITICAL] ETH-001: Reentrancy in Vault.withdraw() — src/Vault.sol:42 2. [HIGH] ETH-006: Missing access control on setFee() — src/Pool.sol:128 3. ... Report: audit-report.md PoC Tests: test/exploits/ (N verified, M disproved) Fuzz Tests: test/invariants/ (N invariants) ──────────────────────────────────── ``` --- ## Severity Classification | Severity | Criteria | Examples | |---|---|---| | **CRITICAL** | Direct fund loss, single transaction, no preconditions | Reentrancy drain, unprotected withdraw, oracle manipulation | | **HIGH** | Significant loss with specific conditions, or contract bricking | Missing access control, flash loan attack, storage collision | | **MEDIUM** | Limited loss, DoS, or requires unlikely conditions | Timestamp dependence, rounding errors, centralization risk | | **LOW** | Minor issues, best practices, code quality | Floating pragma, missing events, infinite approval | | **INFORMATIONAL** | Suggestions, style, gas optimization | Unused variables, naming conventions | --- ## Confidence Scoring | Range | Meaning | Action | |---|---|---| | 0.90–1.00 | Definite — tool-confirmed or PoC-verified | Report with full evidence | | 0.70–0.89 | High likelihood — strong pattern match + context | Report with evidence | | 0.50–0.69 | Possible — pattern match but needs review | Report as "needs review" | | < 0.50 | Low — weak signal, likely false positive | Do not report | --- ## Critical Rules 1. **Never modify source contracts.** Only create/edit test files, report files, and tree files. 2. **Every finding needs evidence.** Include file:line, code snippet, and explanation. No speculation. 3. **False positive reduction is mandatory.** Check compensating controls before reporting. 4. **Match project conventions.** Read existing tests/code style before generating anything. 5. **Solitary PoC tests.** Each exploit test targets one finding with mocked dependencies. 6. **Report all CRITICAL findings even at lower confidence.** Better to flag and let humans verify. 7. **Do not inflate severity.** A floating pragma is LOW, not MEDIUM. Missing events are LOW, not HIGH. 8. **Check inheritance chains.** A modifier on a parent function protects the child. Don't flag the child. 9. **Cross-reference findings.** If Slither and the pattern scanner both find the same issue, boost confidence. 10. **Run forge build before reporting.** Ensure the project compiles. Compilation errors may cause false negatives.