0xharbs/agent-setup

solidity-audit

Smart contract security audit workflow using Slither, Aderyn, and 104 vulnerability patterns.

Ver código-fonte
Documento original do Skill

Renderizado do repositório de origem, preservando títulos, exemplos, código, tabelas, links e imagens.

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:

FlagBehavior
(none)Audit changed .sol files (git diff vs main)
--contract <path>Target a specific contract file
--deepSpawn parallel domain-expert sub-agents for thorough analysis
--quickSlither + regex patterns only, skip manual review
--reentrancyFocused reentrancy audit (ETH-001–005, ETH-044, ETH-081–083)
--access-controlFocused access control audit (ETH-006–012, ETH-086–093)
--report <json>Generate report from existing scan results JSON
--verifyGenerate Foundry PoC exploit tests for findings
--fuzzGenerate invariant and property-based fuzz tests
--coverageRun 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
  1. Check tool availability:
bash
   slither --version 2>/dev/null
   aderyn --version 2>/dev/null
   forge --version 2>/dev/null
  1. Read at least 2 existing test files to understand project conventions.
  2. 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 <path>`: 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 <target> --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 DetectorETH ID
reentrancy-eth, reentrancy-no-eth, reentrancy-benignETH-001
tx-originETH-007
suicidalETH-008
unprotected-upgradeETH-052
divide-before-multiplyETH-014
unchecked-lowlevel, unchecked-send, unused-returnETH-018
controlled-delegatecall, delegatecall-loopETH-019
low-level-callsETH-020
arbitrary-send-eth, arbitrary-send-erc20ETH-006
incorrect-equalityETH-034
weak-prngETH-037
timestampETH-036
unchecked-transferETH-022
erc20-interfaceETH-041
locked-etherETH-032
uninitialized-state, uninitialized-storage, uninitialized-localETH-029
shadowing-state, shadowing-localETH-031
calls-loop, costly-loopETH-066
pragmaETH-071
solc-versionETH-072
encode-packed-collisionETH-073
missing-zero-checkETH-045

3b. Run Aderyn

bash
aderyn <target> --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 DetectorETH ID
reentrancyETH-001
tx-originETH-007
selfdestructETH-008
delegatecallETH-019
unchecked-returnETH-018
floating-pragmaETH-071
unsafe-erc20ETH-041
missing-zero-addressETH-045
unbounded-loopETH-066
weak-randomnessETH-037

3c. Run Pattern Scanner

Run the Python scanner script:

bash
python3 ~/.claude/skills/solidity-audit/scripts/scan.py <target> --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%
  1. 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.
  1. 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)
ScoreRisk Level
90-100Minimal Risk
70-89Low Risk
50-69Medium Risk
25-49High Risk
0-24Critical 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 "<ProjectName>"

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:      <ProjectName>
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

SeverityCriteriaExamples
CRITICALDirect fund loss, single transaction, no preconditionsReentrancy drain, unprotected withdraw, oracle manipulation
HIGHSignificant loss with specific conditions, or contract brickingMissing access control, flash loan attack, storage collision
MEDIUMLimited loss, DoS, or requires unlikely conditionsTimestamp dependence, rounding errors, centralization risk
LOWMinor issues, best practices, code qualityFloating pragma, missing events, infinite approval
INFORMATIONALSuggestions, style, gas optimizationUnused variables, naming conventions

Confidence Scoring

RangeMeaningAction
0.90–1.00Definite — tool-confirmed or PoC-verifiedReport with full evidence
0.70–0.89High likelihood — strong pattern match + contextReport with evidence
0.50–0.69Possible — pattern match but needs reviewReport as "needs review"
< 0.50Low — weak signal, likely false positiveDo 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.