按源仓库内容呈现,保留标题、案例、代码、表格、链接以及原文引用的演示图片。
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 <path> | 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 <json> | 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
- Check
foundry.tomlexists. If not, check forhardhat.config.js/ts. If neither, stop and inform the user. - Read
foundry.tomlto determine:
- Source directory (
src/orcontracts/) - Test directory (default
test/) - Solidity version / pragma
- Remappings (for import resolution)
- Fuzz run count
- Check tool availability:
slither --version 2>/dev/null
aderyn --version 2>/dev/null
forge --version 2>/dev/null- Read at least 2 existing test files to understand project conventions.
- Check for existing audit reports or security documentation.
Step 2: Identify Target Contracts
- Default:
git diff main --name-onlyfiltered to source.solfiles. 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:
- Read the source file fully.
- Read all imported files and inherited contracts.
- 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)
slither <target> --json /tmp/slither_output.json 2>/dev/nullParse 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
aderyn <target> --output /tmp/aderyn_output.json 2>/dev/nullIf 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:
python3 ~/.claude/skills/solidity-audit/scripts/scan.py <target> --output json -f /tmp/scan_results.jsonIf 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):
- Check if state updates happen AFTER the call (CEI violation).
- Check for
nonReentrantmodifier on the function. - Check for cross-function reentrancy: does another function read state that this function updates after the call?
- Check for read-only reentrancy: do view functions return values that depend on state updated after calls?
- For TSTORE-based locks: verify slot is namespaced (keccak256), not a small integer.
4b. Access Control Analysis (ETH-006–012, ETH-086–093)
- Map all state-changing functions and their access control modifiers.
- Identify privilege hierarchy: owner → admin → operator → user.
- Check for single points of failure (no timelock, no multisig).
- Check proxy initialization:
_disableInitializers()in constructor. - Check EIP-7702:
tx.origin == msg.senderno longer guarantees EOA. - Check
extcodesize/isContractassumptions.
4c. DeFi Analysis (ETH-024–028, ETH-055–065, ETH-094–096)
- Identify protocol type (AMM, lending, vault, governance, bridge).
- Check oracle sources: spot price vs TWAP, Chainlink staleness checks.
- Check flash loan resistance: same-block protections, snapshot-based voting.
- Check vault share calculations: first depositor attack, donation attack.
- Check slippage/deadline parameters.
- Check Uniswap V4 hooks:
msg.sender == poolManagervalidation.
4d. Storage Analysis (ETH-029–033, ETH-050, ETH-081–084)
- For proxy contracts: verify storage layout compatibility between versions.
- Check for storage gaps (
__gap) in upgradeable contracts. - Check for ERC-7201 namespaced storage.
- Check transient storage usage: slot collisions, cleanup, delegatecall exposure.
Step 5: Merge and Deduplicate Findings
Run the merger script:
python3 ~/.claude/skills/solidity-audit/scripts/merge.py /tmp/slither_output.json /tmp/scan_results.json -o /tmp/merged_findings.jsonOr perform manually:
- Group findings by (file, line ± 3 lines, ETH-ID or category).
- Boost confidence when multiple tools agree:
- 2 tools agree → +10% confidence
- 3+ tools agree → cap at 95%
- Apply false positive filters:
- Remove reentrancy findings where
nonReentrantmodifier IS present in function scope. - Remove overflow findings in Solidity >= 0.8.0 outside
uncheckedblocks. - Remove missing access control where
onlyOwner/onlyRole/onlyAdminexists. - Remove unsafe ERC20 where
safeTransfer/safeTransferFromIS used.
- 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 includedEach 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:
- Executive Summary — Security score, risk level, key findings, recommendation.
- Scope & Methodology — Contracts audited, tools used, analysis techniques.
- Findings Overview — Table grouped by severity with counts.
- Detailed Findings — Each finding with: ID, title, severity, confidence, file:line, description, impact, code snippet, recommendation.
- Recommendations — Immediate (CRITICAL/HIGH), short-term (MEDIUM), long-term (LOW/INFO).
- Appendix — Score formula, tool versions, vulnerability pattern references.
Run the report generator:
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:
- Reentrancy (ETH-001–004): Attacker contract with
receive()that re-enters the vulnerable function. - Access Control (ETH-006, 009, 010): Call privileged function from non-owner address.
- Oracle Manipulation (ETH-024, 025): Flash loan → manipulate price → profit.
- Vault Inflation (ETH-057, 058): First depositor front-runs second depositor.
- Signature Replay (ETH-038, 039): Replay valid signature on different chain/nonce.
Place PoC tests in test/exploits/ directory.
Run them:
forge test --match-path "test/exploits/" -vvvvReport 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:
- Reentrancy invariants: Balance consistency after any call sequence.
- Access control fuzz: Random caller rejection from admin functions.
- Arithmetic fuzz: No overflow/underflow with extreme inputs.
- Oracle fuzz: Protocol handles extreme prices gracefully.
- Vault invariants: Share price stability, first depositor fairness.
- DoS fuzz: Operations complete within gas bounds for large inputs.
Place fuzz tests in test/invariants/ directory.
Run them:
forge test --match-test "invariant" -vvv --fuzz-runs 1000Step 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
| 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
- Never modify source contracts. Only create/edit test files, report files, and tree files.
- Every finding needs evidence. Include file:line, code snippet, and explanation. No speculation.
- False positive reduction is mandatory. Check compensating controls before reporting.
- Match project conventions. Read existing tests/code style before generating anything.
- Solitary PoC tests. Each exploit test targets one finding with mocked dependencies.
- Report all CRITICAL findings even at lower confidence. Better to flag and let humans verify.
- Do not inflate severity. A floating pragma is LOW, not MEDIUM. Missing events are LOW, not HIGH.
- Check inheritance chains. A modifier on a parent function protects the child. Don't flag the child.
- Cross-reference findings. If Slither and the pattern scanner both find the same issue, boost confidence.
- Run forge build before reporting. Ensure the project compiles. Compilation errors may cause false negatives.
