# Sc Audit

> Deep security audit of a smart-contract repo OR a live on-chain contract by address - detect Solidity, model the protocol invariants and trust boundaries first, run Slither (best-effort) plus a bounded agentic pass that hunts for a path breaking each invariant, triage, adversarially verify, prove with a fuzzer, and drive each finding through the shared responsible-disclosure routing. The dedicated contract arm split out of vuln-scanner.

- Skill: `aaronjmars/sc-audit` (Agent Skill, multi-file: 6 files)
- Install (CLI): `npx get-skill add aaronjmars/sc-audit`
- Raw SKILL.md: https://api.skillmd.com/api/skills/aaronjmars/sc-audit/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: aaronjmars (https://skillmd.com/u/aaronjmars)
- Updated: 2026-11-12
- Page: https://skillmd.com/skills/aaronjmars/sc-audit

---


> **${var}** - Target selector. Four forms:
> - `` (empty) -> auto-select the day's fresh feed target, audit **only if it contains Solidity**, else exit clean. See §S1 for the selection order (an optional `sc-targets.json` ledger, else the `github-trending` feed).
> - `owner/repo` -> audit that GitHub repo (e.g. `Uniswap/v4-core`, `aave/aave-v3-origin`).
> - `<chain>:0x<address>` -> **on-chain mode**: audit a **live deployed contract by address**. It fetches the verified source from the block explorer (Etherscan V2) or Sourcify, materializes it as a Foundry project, and runs the same pipeline - plus on-chain context (proxy/implementation, owner/admin, funds at risk). `chain` in `eth`/`base`/`arbitrum`/`optimism`/`polygon`/`bsc`/... (bare `0x<address>` defaults to `eth`). Examples: `base:0x4200000000000000000000000000000000000006`, `eth:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2`. On-chain findings are **operator-gated** - never auto-filed/auto-emailed (see §S7). See §S1/§S2.
> - `fixture:<name>` -> **local regression mode**: audit the bundled fixture at `skills/sc-audit/fixtures/<name>/` (e.g. `fixture:vault`). No fork, no dedup, no disclosure - a self-contained way to exercise the whole pipeline including the fuzz arm, with no external repo. See §S1/§S2.

Today is ${today}. Read `memory/MEMORY.md` and the last 30 days of `memory/logs/` before starting.

## Why this skill exists

Smart-contract bugs are logic and economics, not syntax. Slither matches known static patterns; it is weak on **access control, protocol invariants, oracle/price manipulation, rounding/precision, upgradeability storage collisions, and cross-contract reentrancy** - the classes that actually drain funds, and where exploitation on-chain is immediate and irreversible. That whole class is what an agentic reviewer catches by reading the source and reasoning about who can call what and which invariant breaks.

This skill is the **contract arm split out of `vuln-scanner`**. vuln-scanner detects Solidity and hands the repo here rather than running Slither inline; this skill owns the deep audit and then routes findings through vuln-scanner's shared disclosure machinery. It does **not** duplicate the disclosure/PVR/email logic - see §S7.

It audits two kinds of target: a **GitHub repo** (source in a repo you fork), and a **live contract deployed on-chain by address** (`<chain>:0x<addr>`) - the latter fetches the verified source from the block explorer/Sourcify and adds on-chain context (proxy/implementation, owner, funds at risk). A live deployed contract is where a bug is *already exploitable with real money at stake*, so on-chain findings are treated as the highest-stakes disclosure and are **operator-gated** - staged for a human, never auto-filed (§S7).

The agentic source pass is the **reliable core**. Slither is best-effort: a headless run has `slither` allow-listed but **not** `solc` / `forge` / `solc-select`, so contracts that need a compiler to build may not compile in-run. The source pass needs no compiler, so a clean audit never depends on Slither succeeding.

## S1. Detect Solidity and select the target

**Shell shape.** Each Bash call is one allowed command (pipes are fine). The run refuses a call that sets a variable (`REPO=...`, `WORKDIR="$(git rev-parse ...)"`, `SOL_FILES=$(find ...)`), starts with `export`, uses `if` / `case` / `[ ... ]` tests, or joins commands with `;`, `&&` or `||`, and each refusal costs a model turn. `find`, `cp`, `rm`, `tr`, `printf` and `command -v` are not allowed commands either. So this skill makes its decisions in prose from what each call printed, writes every value it already knows (`<REPO>`, `<WORKDIR>`, `<SCRATCH>`, `<CHAIN>`, `<CID>`, `<ADDR>`, `<PROJ>`, ...) into later commands literally in place of the placeholder, and writes or appends `sources.txt` lines with Write/Edit. Shell variables never carried over between Bash calls anyway (each call is a fresh shell; only the working directory carries over).

Parse the selector in your head, not in a shell script. `REPO` = `${var}`, one of: owner/repo | empty (auto) | fixture:<name> | <chain>:0x<addr> | 0x<addr>.

- Starts with `fixture:` -> `MODE=fixture`, `FIXTURE` = the text after `fixture:`.
- Matches `^([a-zA-Z0-9-]+:)?0x[0-9a-fA-F]{40}$` -> `MODE=onchain` (deployed-contract selector).
- Anything else -> `MODE=repo` (owner/repo, or empty -> auto-select).

- **`MODE=fixture`** -> audit the bundled fixture `skills/sc-audit/fixtures/<FIXTURE>/` (see §S2). **Skip the dedup ledger and skip disclosure entirely** (§S7/§S8) - fixtures are deliberately-vulnerable regression targets meant to be re-run on demand, never disclosed. If the fixture dir is missing, log `no-fixture: <FIXTURE>` and exit clean.
- **`MODE=repo`, `REPO` set** -> that is the target. Confirm it holds Solidity before forking, one call with REPO written in literally: `gh api "search/code?q=repo:<REPO>+extension:sol" --jq '.total_count'` (or just proceed and detect after clone in S2). If the repo has **no** `*.sol`, log `no-solidity: <REPO>` and exit clean - this is the wrong skill for it.
- **`MODE=repo`, `REPO` empty** -> auto-select a repo target, best-first:

  1. **Optional ledger first.** If an `sc-source`-style ledger exists at `memory/sc-targets.json` (schema `{updated, repos:[{repo, stars, tier, desc, first_seen}]}`, best-first, already Solidity-scoped and deduped), read it and take `repos[0].repo`. If that repo was scanned within 30 days per `memory/vuln-scanned.json`, or turns out to hold no real Solidity after clone (S2), walk down `repos[]`. This ledger is optional; the skill stands alone without it.
  2. **Trending feed fallback.** If no ledger is present or it is exhausted, read the `github-trending` feed at `output/.chains/github-trending.md` (most recent by ISO header date) and walk its repos for one that contains Solidity.
  3. If **none** contain Solidity, log `no-solidity-target` and exit clean.

  On-chain candidates never enter auto-mode - the empty-`REPO` path is repo-only. Audit a live contract by passing an explicit `<chain>:0x<addr>` selector.
- **`MODE=onchain`** -> resolve the chain to an Etherscan V2 chain id and normalize the address, then fetch verified source in §S2. Work these out yourself from the selector:

  - `ADDR` = the text after the last `:` (or the whole string if there is none). `CHAIN` = the text before the `:`, or `eth` when there is no `:`.
  - Lowercase both (explorer/Sourcify are checksum-insensitive).
  - `CID` from `CHAIN`:

    | CHAIN | CID | CHAIN | CID |
    |---|---|---|---|
    | `eth`, `ethereum`, `mainnet` | 1 | `base` | 8453 |
    | `arbitrum`, `arb` | 42161 | `optimism`, `op` | 10 |
    | `polygon`, `matic` | 137 | `bsc`, `bnb` | 56 |
    | `avalanche`, `avax` | 43114 | `gnosis`, `xdai` | 100 |
    | `scroll` | 534352 | `linea` | 59144 |
    | `zksync` | 324 | `blast` | 81457 |
    | `sepolia` | 11155111 | `base-sepolia` | 84532 |

  - Any other CHAIN: log `unknown-chain: <CHAIN> (add its Etherscan V2 chainid to S1 to support it)` and exit clean.
  - Record `onchain target: chain=<CHAIN> cid=<CID> addr=<ADDR>` in the run output.

  For a Blockscout-only chain not on Etherscan V2, add its `BLOCKSCOUT` host in §S2b and the Etherscan calls no-op cleanly (verified source comes from the Sourcify/Blockscout fallback).

  On-chain findings are **operator-gated** - a live contract holding funds is the highest-stakes disclosure, so this mode NEVER auto-files a PVR, auto-sends an email, or opens any public channel; it stages an operator-gated draft and notifies (see §S7).

**Dedup (mandatory in `MODE=repo` and `MODE=onchain`, same ledger as vuln-scanner).** Before auditing, skip a target already covered in the last 30 days: read `memory/vuln-scanned.json` and skip any row inside the window - keyed on `<REPO>` for a repo, on `onchain:<CHAIN>:<ADDR>` for an address. For a repo, also check `gh api "repos/<REPO>/security-advisories"` - a repo with a published/credited advisory for the same finding class is already handled; skip and log. This is the identical dedup contract described in vuln-scanner §A1 / §A6. **`MODE=fixture` bypasses dedup** (re-runnable).

## S2. Get the code (fork a repo, copy a fixture, or fetch on-chain source)

Capture `WORKDIR` first so every write lands in the real repo, not the throwaway target. Every mode works inside gitignored `.scan/`, so the build artifacts (`out/`, `cache/`, `crytic-export/`, fuzz `corpus/`) never touch the tracked tree. Each command below is its own Bash call.

1. **WORKDIR** - the aeon repo root, where memory/ and state live:
   ```bash
   git rev-parse --show-toplevel
   ```
   It prints WORKDIR. Then:
   ```bash
   mkdir -p <WORKDIR>/.scan
   ```
2. **Scratch dir** for this run's intermediate files (scan JSON, sources.txt, fuzz harness). Prefer /tmp:
   ```bash
   mkdir -p /tmp/sc-audit
   ```
   If that fails or /tmp is not writable in this sandbox, fall back to a gitignored dir under `.scan/` instead:
   ```bash
   mkdir -p <WORKDIR>/.scan/_sc-audit
   ```
   `SCRATCH` = whichever of `/tmp/sc-audit` or `<WORKDIR>/.scan/_sc-audit` you are using. Write that path literally into every later command (S2b, S4, S6.5). It comes before the target step because §S2b needs it; there is nothing to re-resolve per call.
3. **Get the target into `.scan/`, by mode:**
   - **`MODE=fixture`** - local regression: copy the bundled fixture into gitignored `.scan/` and audit the COPY (never the tracked fixture) so forge's out/cache stay out of the working tree. No fork. Check `<WORKDIR>/skills/sc-audit/fixtures/<FIXTURE>/` with Glob; if it is missing, log `no-fixture: <FIXTURE>` and exit clean. Otherwise replace any old copy with a fresh one in one `python3` call (`rm` and `cp` are not allowed commands):
     ```bash
     python3 - '<WORKDIR>/skills/sc-audit/fixtures/<FIXTURE>' '<WORKDIR>/.scan/<FIXTURE>' <<'PY'
     import shutil, sys
     src, dst = sys.argv[1], sys.argv[2]
     shutil.rmtree(dst, ignore_errors=True)
     shutil.copytree(src, dst)
     print(f"copied {src} -> {dst}")
     PY
     ```
     ```bash
     cd <WORKDIR>/.scan/<FIXTURE>
     ```
   - **`MODE=onchain`** - live contract by address: fetch the VERIFIED source from the explorer/Sourcify and materialize it as a Foundry project under `.scan/`. `PROJ` = `<WORKDIR>/.scan/onchain-<CHAIN>-<ADDR>`. Run §S2b now (fetch + materialize + on-chain context); after it you are in `<PROJ>` with `src/` + `foundry.toml` written. If no verified source exists, §S2b exits clean (bytecode-only audit is out of scope).
   - **`MODE=repo`** - fork and clone, then step into the clone (NAME = the repo part of REPO, after the `/`):
     ```bash
     cd <WORKDIR>/.scan
     ```
     ```bash
     gh repo fork "<REPO>" --clone --default-branch-only -- --depth 50 --quiet
     ```
     ```bash
     cd <NAME>
     ```
     The working directory is now `<WORKDIR>/.scan/<NAME>`.
4. **Confirm Solidity is actually present** (auto-select already filtered, but a direct `REPO` may not have): Glob `**/*.sol` in the target dir, ignoring `node_modules/`. If there is none, record `no-solidity after clone: <REPO>`, log a clean no-op row in S8 and exit.

## S2b. On-chain source fetch, materialize, and context (`MODE=onchain` only)

Run this only when `MODE=onchain`. It fetches the contract's **verified** source, writes it as a Foundry project under `<PROJ>`, and records on-chain context that drives severity. **If no verified source exists, log it and exit clean - a bytecode-only audit is out of scope** (decompilation is unreliable and would produce unfalsifiable findings; the honest output is "source not verified, cannot audit").

**1. Fetch the verified source.** Prefer Etherscan V2 (one key, ~60 chains, best coverage); fall back to Sourcify (keyless), then to Blockscout's keyless REST for Blockscout-explorer chains that are on neither. The Etherscan key goes through `./secretcurl` as a `{ETHERSCAN_API_KEY}` placeholder (it ends `_KEY`, so it substitutes) - never put the raw key on the command line. Check whether `ETHERSCAN_API_KEY` and `BLOCKSCOUT_API_KEY` are set: read the "Keys set for this run" line in your run notes, never a shell test (those are refused and cost a turn). A key on that line is set; a key not on it is unset. Each command below is its own Bash call (SCRATCH from §S2 step 2, CID and ADDR from §S1, all written in literally).

- **BLOCKSCOUT** = the Blockscout base URL for chains NOT on Etherscan V2 (keyless REST), one line per chain. No chain has one yet, so BLOCKSCOUT is empty for every chain until a host is added here.
- Start with `VERIFIED=no`.

**(a) Etherscan V2 getsourcecode** - only if `ETHERSCAN_API_KEY` is set:
```bash
./secretcurl -s -w 'http=%{http_code}\n' -o <SCRATCH>/etherscan.json \
  "https://api.etherscan.io/v2/api?chainid=<CID>&module=contract&action=getsourcecode&address=<ADDR>&apikey={ETHERSCAN_API_KEY}"
```
Verified iff `result[0].ABI` is real source (NOT the literal "Contract source code not verified"). Check with one call; exit code 0 means verified (`VERIFIED=etherscan`), exit code 1 means not:
```bash
python3 - <SCRATCH>/etherscan.json <<'PY'
import json,sys
try: r=json.load(open(sys.argv[1]))["result"][0]
except Exception: sys.exit(1)
sys.exit(0 if r.get("ABI","").strip() and r["ABI"]!="Contract source code not verified" and r.get("SourceCode","").strip() else 1)
PY
```

**(b) Sourcify keyless fallback** (no key, or Etherscan had no verified source) - only while `VERIFIED=no`. Use API **v2**. The old v1 route (`/server/files/any/<CID>/<ADDR>`) is deprecated; do not fall back to it. v2 returns ONE object (not a file list) whose `sources` maps path -> {content}, so it needs its own parse branch below. If the fetch fails, continue (it just stays unverified):
```bash
curl -s -o <SCRATCH>/sourcify.json \
  "https://sourcify.dev/server/v2/contract/<CID>/<ADDR>?fields=sources,compilation,proxyResolution,deployment"
```
```bash
grep -c '"sources"' <SCRATCH>/sourcify.json
```
A count above `0` -> `VERIFIED=sourcify`.

**(c) Blockscout v2 fallback** - only while `VERIFIED=no` and BLOCKSCOUT is set: Blockscout-explorer chains that are on NEITHER Etherscan V2 nor Sourcify. Keyless GET `/api/v2/smart-contracts/<addr>` returns ONE object: source_code + file_path + additional_sources[{file_path,source_code}] + proxy_type + implementations + compiler_version/evm_version. Parsed by its own branch in step 2. If the fetch fails, continue:
```bash
curl -s -o <SCRATCH>/blockscout.json "<BLOCKSCOUT>/api/v2/smart-contracts/<ADDR>"
```
Exit code 0 from this check -> `VERIFIED=blockscout`:
```bash
python3 - <SCRATCH>/blockscout.json <<'PY'
import json,sys
try: d=json.load(open(sys.argv[1]))
except Exception: sys.exit(1)
sys.exit(0 if d.get("is_verified") and (d.get("source_code") or "").strip() else 1)
PY
```

Record `verified-source: <VERIFIED>`. If it is still `no`: record `onchain: source NOT verified for <CHAIN>:<ADDR> - cannot audit (bytecode-only out of scope).`, write a clean dedup row (channel: skipped) + coverage note in S8, notify nothing, exit.

**2. Materialize the Foundry project** at `<PROJ>` (`src/` + a synthesized `foundry.toml`). Etherscan's `SourceCode` field has three shapes - a plain flattened string, a single-brace `{ "File.sol": {"content": ...} }` map, or a double-brace `{{ ...standard-json... }}` object - so parse with Python, not jq. This snippet handles all three plus the Sourcify file list, and pins `solc`/`evm_version` from the compiler metadata. One call, with SCRATCH, PROJ and VERIFIED written in literally:

```bash
python3 - '<SCRATCH>' '<PROJ>' '<VERIFIED>' <<'PY'
import json, os, re, sys
scratch, proj, src_from = sys.argv[1], sys.argv[2], sys.argv[3]
os.makedirs(os.path.join(proj, "src"), exist_ok=True)
def write(relpath, content):
    p = os.path.join(proj, "src", relpath.lstrip("/"))
    os.makedirs(os.path.dirname(p) or os.path.join(proj, "src"), exist_ok=True)
    open(p, "w").write(content)
solc = evm = name = ""; proxy = "0"; impl = ""
if src_from == "etherscan":
    r = json.load(open(os.path.join(scratch, "etherscan.json")))["result"][0]
    name = r.get("ContractName") or "Contract"; proxy = str(r.get("Proxy", "0")); impl = r.get("Implementation", "")
    m = re.search(r"v?(\d+\.\d+\.\d+)", r.get("CompilerVersion", "")); solc = m.group(1) if m else ""
    ev = (r.get("EVMVersion") or "").strip().lower(); evm = "" if ev in ("", "default") else ev
    s = (r.get("SourceCode") or "").strip()
    if s.startswith("{{") and s.endswith("}}"):
        for path, v in json.loads(s[1:-1]).get("sources", {}).items(): write(path, v.get("content", ""))
    elif s.startswith("{"):
        obj = json.loads(s)
        srcs = obj.get("sources", obj)
        for path, v in srcs.items():
            if isinstance(v, dict) and "content" in v: write(path, v["content"])
    else:
        write(f"{name}.sol", s)
elif src_from == "sourcify":  # sourcify API v2 - ONE object: sources{path:{content}} + compilation + proxyResolution
    d = json.load(open(os.path.join(scratch, "sourcify.json")))
    for path, v in (d.get("sources") or {}).items():
        write(path, v.get("content", "") if isinstance(v, dict) else v)
    comp = d.get("compilation") or {}
    name = comp.get("name") or "Contract"
    m = re.search(r"(\d+\.\d+\.\d+)", comp.get("compilerVersion", "")); solc = m.group(1) if m else solc
    ev = ((comp.get("compilerSettings") or {}).get("evmVersion") or "").strip().lower()
    evm = "" if ev in ("", "default") else ev
    pres = d.get("proxyResolution") or {}
    if pres.get("isProxy"):
        proxy = "1"
        impls = pres.get("implementations") or []
        # v2 implementation entries are dicts ({"address": ...}) or bare strings
        if impls: impl = impls[0].get("address", "") if isinstance(impls[0], dict) else impls[0]
else:  # blockscout v2 - /api/v2/smart-contracts: source_code + file_path + additional_sources[]
    d = json.load(open(os.path.join(scratch, "blockscout.json")))
    if d.get("file_path"): write(d["file_path"], d.get("source_code") or "")
    else: write(f'{d.get("name") or "Contract"}.sol', d.get("source_code") or "")
    for a in (d.get("additional_sources") or []):
        if a.get("file_path"): write(a["file_path"], a.get("source_code") or "")
    name = d.get("name") or "Contract"
    m = re.search(r"(\d+\.\d+\.\d+)", d.get("compiler_version", "")); solc = m.group(1) if m else solc
    ev = (d.get("evm_version") or "").strip().lower(); evm = "" if ev in ("", "default") else ev
    pt = d.get("proxy_type")
    if pt and str(pt).lower() not in ("none", "unverified"):
        proxy = "1"
        impls = d.get("implementations") or []
        if impls: impl = impls[0].get("address", "") if isinstance(impls[0], dict) else impls[0]
ft = ['[profile.default]', 'src = "src"', 'out = "out"', 'libs = ["lib"]']
if solc: ft.append(f'solc = "{solc}"')
if evm and evm != "default": ft.append(f'evm_version = "{evm}"')
open(os.path.join(proj, "foundry.toml"), "w").write("\n".join(ft) + "\n")
json.dump({"name": name, "solc": solc, "evm": evm, "proxy": proxy, "implementation": impl},
          open(os.path.join(scratch, "materialized.json"), "w"))
print(f"materialized: name={name} solc={solc} evm={evm} proxy={proxy} impl={impl}")
PY
```
Then step into the project, its own call:
```bash
cd <PROJ>
```

**3. If it's a proxy, also materialize the implementation** - the proxy shell holds almost no logic; the bug is in the implementation it `delegatecall`s. When `materialized.json` has `proxy=1` and a non-empty `implementation`, re-run steps 1-2 for that implementation address (fetch `impl` on the same `<CID>`, write it under `src/impl/`) so S4/S5 audit the real logic. Note the proxy->impl relationship prominently in the report. If the explorer didn't flag a proxy, still probe the EIP-1967 implementation slot before concluding it's non-upgradeable (step 4).

**4. Record on-chain context** (drives severity - a live contract holding funds turns a "possible" into "exploitable now"). Best-effort via the Etherscan V2 `proxy`/`account` modules (same key), Blockscout's keyless Etherscan-compatible `/api` for Blockscout chains, or a public RPC; each is optional, never fatal. Write `<SCRATCH>/onchain-context.json`. Pick the branch in prose, one call per command:

- **BLOCKSCOUT set** (Blockscout chains): Etherscan V2 does not cover `<CID>`, so read the native balance from Blockscout's keyless Etherscan-compatible `/api`. Its result is a wei string in the SAME `{"status","message","result"}` shape as Etherscan V2's balance response, so it parses identically into `native_balance_wei`. Proxy/impl already came from the materialize step. An optional `BLOCKSCOUT_API_KEY` is passed via secretcurl's `{BLOCKSCOUT_API_KEY}` placeholder - the legacy `/api` honors `?apikey=` on key-enforcing instances; instances that don't enforce keyed tiers ignore it. Keyless otherwise. The v2 source endpoint above ignores the key.
  - `BLOCKSCOUT_API_KEY` set:
    ```bash
    ./secretcurl -s -o <SCRATCH>/balance.json \
      "<BLOCKSCOUT>/api?module=account&action=balance&address=<ADDR>&tag=latest&apikey={BLOCKSCOUT_API_KEY}"
    ```
  - Not set (if it fails, continue):
    ```bash
    curl -s -o <SCRATCH>/balance.json \
      "<BLOCKSCOUT>/api?module=account&action=balance&address=<ADDR>&tag=latest"
    ```
- **Else, `ETHERSCAN_API_KEY` set:** native balance at the address = funds directly at risk (wei):
  ```bash
  ./secretcurl -s -o <SCRATCH>/balance.json \
    "https://api.etherscan.io/v2/api?chainid=<CID>&module=account&action=balance&address=<ADDR>&tag=latest&apikey={ETHERSCAN_API_KEY}"
  ```
  Then the EIP-1967 implementation slot (proxy detection independent of the explorer flag):
  ```bash
  ./secretcurl -s -o <SCRATCH>/eip1967.json \
    "https://api.etherscan.io/v2/api?chainid=<CID>&module=proxy&action=eth_getStorageAt&address=<ADDR>&position=0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc&tag=latest&apikey={ETHERSCAN_API_KEY}"
  ```

Capture into `<SCRATCH>/onchain-context.json`: `{chain, cid, address, name, solc, evm_version, is_proxy, implementation, native_balance_wei, admin_or_owner (best-effort), notes}`. Also note the ERC20/TVL exposure qualitatively if it's obvious from the contract type (a router/vault/bridge holding user funds is high-exposure). This context is **non-sensitive** (it does not aid exploitation) and rides into the S9 report and the staged disclosure so the operator sees the blast radius. From here, S3-S6.5 run **unchanged** against `<PROJ>` - the materialized source is just another Foundry project in `.scan/`.

## S3. Stage the toolchain and harden the build

`slither`, `solc`, `solc-select`, `forge`, `crytic-compile`, `echidna`, `medusa` are the contract toolchain. Every step checks for its tool first (a bare `<tool> --version` call; "command not found" means absent), so any tool that is not present is skipped, never fatal - the source pass (S5) is the reliable core and needs none of them. Staging splits two ways:

- **In-run (pip-installable):** `slither-analyzer`, `solc-select` (downloads `solc`), and `crytic-compile` install via the allow-listed `python3 -m pip`. This covers Slither on **hardhat** (via `npx`) and **bare-solc** layouts.
- **Workflow-staged (binaries):** `forge`, `echidna`, `medusa` ship as tarballs/binaries whose installers need shell tooling that may not be allow-listed in-run, so they are only available when the instance provides a pre-`claude -p` staging step that installs them and appends their dir to `$GITHUB_PATH`. When no such step ran or a tool failed to stage: a **foundry** repo may not build (Slither degrades to `compile-fail`, source pass S5 still runs), and the fuzz arm (S6.5) is **skipped** cleanly.

**Harden first - you are about to compile and (in S6.5) fuzz UNTRUSTED contract code.** Compiling and running a foundry test executes the target repo's build and test code in this runner. Disable foundry FFI so a malicious `foundry.toml`/test can't shell out to the host, and only ever work inside the throwaway `.scan/<repo>` clone.

- **Pin FFI off in the config.** `export FOUNDRY_FFI=false` is refused in this run, and an exported variable would not reach the next Bash call anyway (each call is a fresh shell). So block forge tests from shelling out to the host through the clone's own config: Glob for `foundry.toml` at the target root; if it is there, Read it and, with Edit, make every `[profile.*]` section say `ffi = false` (change `ffi = true`, add the line where it is missing). The clone is throwaway, so editing its config is fine; never touch the target's source. A synthesized on-chain `foundry.toml` (§S2b) has no `ffi` line, so FFI stays at its default, off.
- **PATH.** Do not `export PATH`: the workflow steps that stage the tools already put `/tmp/bin` and the Foundry bin dir on PATH for every call (`$GITHUB_PATH`), so the bare names resolve.
- **In-run pip tools** (crytic-compile drives the build for slither/echidna/medusa). For each tool, one call to check it, and only if that fails ("command not found") one call to install it; if the install fails too, continue without it:
  ```bash
  slither --version
  ```
  ```bash
  python3 -m pip install --quiet --disable-pip-version-check slither-analyzer
  ```
  ```bash
  solc-select versions
  ```
  ```bash
  python3 -m pip install --quiet --disable-pip-version-check solc-select
  ```
  ```bash
  crytic-compile --version
  ```
  ```bash
  python3 -m pip install --quiet --disable-pip-version-check crytic-compile
  ```
- **forge/echidna/medusa:** use them only if a workflow step already staged them (check each with its own `--version` call before use).

Pick the contract's solc version when a compile fails on version mismatch: read the `pragma solidity` line, then `solc-select install <ver>` and `solc-select use <ver>` as two calls (solc-select downloads the binary via Python - this works in-run). crytic-compile auto-detects hardhat (`npx hardhat`), foundry (`forge`, if staged), and bare-solc layouts.

**Cap the compile - the S5 source pass needs NO compiler, so NEVER chase a clean build.** Slither and the fuzz arm are best-effort *extras*; the audit's reliable core (S5) reads source and needs nothing to build. So make **at most ONE** best-effort compile attempt (plus **one** optional `solc-select` switch to match the `pragma`), and time-box it to a few minutes. If it still fails, set `SLITHER=compile-fail`, skip Slither and the fuzz arm, and go straight to S5. **Do NOT** `npm install`/`forge install` missing deps, hand-write `remappings.txt`, add `lib/` submodules, or loop the compile trying to satisfy imports - that rabbit hole is the #1 cause of a run hitting the job timeout and losing the whole scan. This bites **on-chain / `MODE=onchain` targets** hardest: materialized explorer/Sourcify source routinely imports `@openzeppelin`, `@layerzerolabs`, etc. with no remappings or `lib/`, so it will not build out of the box - that is **expected**, record `compile-fail` and audit the source directly. A self-contained contract (e.g. WETH) compiles instantly; a dep-heavy one won't - do not spend the run's budget forcing it.

## S4. Slither scan - best-effort, degrade cleanly

If S3 found slither, run it from the target dir (SCRATCH written in literally). Its output goes to `<SCRATCH>/slither.err` through a `node` writer, because a `2>` redirect into a file is refused when SCRATCH is the in-repo fallback; a nonzero exit is fine, continue:
```bash
slither . --json <SCRATCH>/slither.json --exclude-informational --exclude-low 2>&1 | node -e 'require("fs").writeFileSync(process.argv[1], require("fs").readFileSync(0))' <SCRATCH>/slither.err
```
Then size the JSON, its own call:
```bash
wc -c <SCRATCH>/slither.json
```
Status: `ok` = wrote JSON with results (a size above 0); `compile-fail` = ran but crytic-compile could not build (wrong solc version, missing deps, non-standard layout) - try `solc-select install/use <pragma version>` once, then re-run; `skipped` = binary absent (S3's check failed). compile-fail is NOT a network/sandbox block. Write the status as the first line of `<SCRATCH>/sources.txt` with the Write tool (a new file, replacing any old one):
```
slither=<SLITHER>
```

On `compile-fail`, the source pass (S5) still carries the audit - it needs no compiler. Never report `slither=fail` with a "sandbox / network" reason; the real reason is a build problem in the target (record the shortest decisive line from `slither.err`).

## S5.0. Threat model - derive the invariants FIRST (before you hunt)

**Build the spec of what must be true before you go looking for what's wrong.** A freeform read finds the bugs you happen to trip over; a threat model finds the bugs that matter because you decided what "broken" means up front. This is the same "threat-model before analysis" discipline used by professional audit workflows - it focuses the attack surface, and the invariant list it produces is reused twice: it targets the S5 hunt and it *becomes* the S6.5 fuzz properties. **This is fully automated - you (the agent) derive it from the source; there is no human step.**

Read the production contracts and the on-chain context (for `MODE=onchain`, the §S2b proxy/owner/funds data), then write `<SCRATCH>/threat-model.json`:

1. **Actors & trust boundaries** - who can call what (anyone / owner / a role / another contract / a keeper/relayer), what each is trusted to do, and every point where value or authority crosses a boundary.
2. **Protocol invariants** - the properties that must hold on **every** reachable path. Derive them from the contract's *purpose* and its state variables, not a fixed list: accounting conservation (`sum(balanceOf) <= totalDeposited`), solvency (`assets >= liabilities`), share/asset ratio monotonicity, supply caps, access (`only owner can pause`), one-time init, no-free-value. Give each a stable `id`.
3. **Assets at risk** - what an attacker is trying to achieve (drain funds, mint from nothing, seize ownership, brick a core function, grief) and the max value exposed (for on-chain, the native balance from §S2b).

```json
{
  "actors": [{"who":"anyone","trusted_to":"deposit/withdraw own funds"},
             {"who":"owner","trusted_to":"pause, set fees"}],
  "invariants": [{"id":"INV1","statement":"sum(balanceOf[*]) <= totalDeposited","why":"insolvency = theft"},
                 {"id":"INV2","statement":"only owner can pause","why":"griefing / fund lock"}],
  "assets_at_risk": ["user deposits (native balance)", "protocol ownership"]
}
```

Keep it tight - a handful of load-bearing invariants beats an exhaustive list. This model is the audit's plan; S5 hunts for a path that breaks any listed invariant, and S6.5 fuzzes each one.

## S5. Agentic contract audit (the core) - BOUNDED

You are the agentic scanner. Read the Solidity source and, **guided by the S5.0 threat model**, reason about **who can call what, what state moves, and which invariant breaks** - the source->sink work Slither can't do. This pass produces *candidates*, not verdicts; everything goes through S6 triage.

**Bound it.** Size the contract surface, then deep-review the top-N highest-exposure contracts only; record the rest as `reviewed: false` (they still count in the S8 coverage denominator).

Count the production `.sol` files with one call from the target dir (`find` is not an allowed command; `grep -rc ''` prints one line per file it searched, so `wc -l` counts them):
```bash
grep -rc --include='*.sol' --exclude-dir=node_modules --exclude-dir=lib --exclude-dir=test --exclude-dir=tests --exclude-dir='mock*' '' . | wc -l
```
It prints SOL_FILES. Set N yourself: SOL_FILES <= 15 -> N = SOL_FILES (small - review all production contracts); <= 60 -> N = 12; else N = 8. Then record the budget line:
```bash
echo "sc-budget: SOL_FILES=<SOL_FILES> N=<N>"
```

**1. Inventory the attack surface.** Enumerate every `external`/`public` state-changing function and every value-handling path. Rank by exposure: unauthenticated + reachable + moves funds/critical state first. Ignore `test/`, `mock/`, `script/`, `lib/` (dependencies), and `*.t.sol`.

**2. Deep-review the top N - hunt for a path that breaks a listed invariant.** For each entrypoint, trace attacker control -> state change -> **which S5.0 invariant it could violate** (targeted, not freeform). Also run this Solidity-specific checklist (the classes Slither is weak on) - a hit here often reveals an invariant break you didn't list, so add it to the threat model:

- **Access control** - missing/incorrect modifiers, unprotected `initialize`, `tx.origin` auth, owner-only funcs left external, role-grant paths, upgrade authorization.
- **Reentrancy** - single-function, cross-function, **cross-contract**, and **read-only reentrancy**; verify checks-effects-interactions and external-call ordering, not just a `nonReentrant` presence.
- **Oracle / price manipulation** - spot price read from AMM reserves, missing TWAP, single-source or stale oracle (no `updatedAt`/round check), flash-loan-manipulable pricing.
- **Arithmetic / precision** - rounding direction favoring the user, division-before-multiplication, `unchecked` blocks, decimals mismatch, **ERC4626 first-depositor / share-inflation**.
- **Upgradeability / delegatecall** - storage-layout collision, uninitialized proxy, unguarded initializer, `selfdestruct`/`delegatecall` in an implementation, selector clashes.
- **External-call assumptions** - unchecked return values, non-standard ERC20 (no return value, **fee-on-transfer**, rebasing), `DoS` via revert-in-loop, gas griefing.
- **Signatures / replay** - missing nonce, no `chainId` in the EIP-712 domain, malleable `ecrecover`, missing deadline, `permit` misuse.
- **Economic / MEV** - sandwichable actions with no slippage bound, front-runnable init, unprotected liquidation, donation/`balanceOf`-accounting attacks.
- **Uniswap v4 hooks (full checklist)** - if the target implements ANY `IHooks` callback (`before`/`after` Initialize/Swap/AddLiquidity/RemoveLiquidity/Donate) or inherits a hook base (`BaseHook`, `SafeCallback`, `IHooks`, a custom fee base), it is a v4 hook regardless of origin (any repo, any deployed address, any file - this is target-agnostic). Audit it against the FULL 11-class checklist in `skills/sc-audit/references/hook-checklist.md`: access control (Cork $12M missing `onlyPoolManager`), hookData/PoolKey validation (Cork, Doppler), flash-accounting deltas (settle/sync/take/clear + `BeforeSwapDelta` sign, CELO double-settle), rounding/precision (Bunni $8.4M), reentrancy (Bunni), permission-bit vs address-flag encoding (Angstrom), dynamic fees, JIT liquidity (OZ LiquidityPenalty), tick-crossing/price manipulation (Angstrom, Flayer), gate unit-confusion, and DoS/economic. Derive the hook's permission flags from the address (low 14 bits, mask `0x3FFF`) or `getHookPermissions()` and cross-check they match the implemented callbacks. Two source-reasoning gate cases worth stating inline: a `beforeSwap`/`afterSwap` gate that compares raw `amountSpecified` to a token-denominated constant is unit-confused: the caller chooses the specified currency via exact-in vs exact-out AND swap direction, so one constant silently governs BOTH tokens of the pool, and on a sub-18-decimal specified token the cap fails OPEN (never binds). A `balance` / `skew` / `heavier-side` gate on the two virtual reserves is a raw-price-vs-`1.0` gate in disguise: `StateLibrary` gives `amount0 = L*2^96/sqrtP` and `amount1 = L*sqrtP/2^96`, so `amount0/amount1 = 1/price` and the liquidity `L` cancels, leaving the pool's raw price (`token1/token0` in smallest units) compared to an implicit `1.0`. Such a gate is permanently one-directional on any pair that is not a same-decimals pool near parity (one whole leg reverts forever) unless it anchors to the pool's OWN reference - its `sqrtPriceX96` at `afterInitialize` (adds flag bit `0x1000`), or an explicit target ratio. Confirm by reasoning at a price away from 1:1, BOTH legs: a gate that only looks correct at parity is a false pass.
- **Protocol invariants** - derive the invariants the contract must hold (e.g. `sum(shares) == totalSupply`, `collateral >= debt`, accounting conservation) and reason whether any reachable path breaks one.
- **Vendored-dependency provenance (do this FIRST on `MODE=onchain`)** - explorer/Sourcify verification proves **source == bytecode**, it proves **nothing** about source == genuine upstream. Most verified contracts are 90%+ vendored `@openzeppelin` / `@layerzerolabs` / `solmate` files, so one altered line inside a vendored file is invisible both to the explorer and to a reviewer who assumes "that's just OpenZeppelin" - the highest-yield backdoor there is, and the cheapest to rule out. Identify the upstream versions, pull the genuine releases (`curl -sL https://registry.npmjs.org/<pkg>` for the tarball URL - URL-encode the whole scoped name, both the `@` scope and the `/` separator (`@openzeppelin/contracts` becomes `%40openzeppelin%2Fcontracts`) - then extract with Python's `tarfile`; the `tar` binary may not be allow-listed), and diff **every** vendored file by SHA-256. Report a per-file `IDENTICAL / DIFFERENT / UNVERIFIED` verdict and never mark a file clean you could not actually compare. A near-miss on the version is normal: sweep the adjacent releases before calling a diff "tampering". Pair it with a **bytecode match** - compile locally and compare against `eth_getCode`, masking immutables and the trailing CBOR metadata - which upgrades "this source is verified" into "this source is provably the live code".

**3. Emit candidates.** Write one JSON array (may be `[]`) to `<SCRATCH>/agentic.json` with the **Write** tool, then record the source status:

```json
[
  {"file":"src/Vault.sol","line":142,"severity":"critical","category":"access-control",
   "claim":"initialize() has no initializer guard - anyone can re-init and set themselves owner",
   "invariant":"only deployer is owner after setup","invariant_id":"INV2"}
]
```

append this line to `<SCRATCH>/sources.txt` with Edit (a shell `>>` append is refused). 0 candidates on a reviewed surface is still `ok`; write `agentic=skipped` only if source is unreadable (bytecode-only):
```
agentic=ok
```

Tag each candidate with the `invariant` it breaks and the `invariant_id` from the S5.0 model (or a new id if the checklist surfaced one not yet listed). A candidate whose `category` in `{invariant, arithmetic/precision, economic, access-control}` is a fuzz-arm target (S6.5): S6.5 turns its stated invariant into a property test.

## S6. Triage - read every finding before trusting it

Merge `<SCRATCH>/slither.json` and `<SCRATCH>/agentic.json` and triage every candidate by the **same bar as vuln-scanner §A4**:

1. Open the file at the reported line; read the surrounding context and the functions it calls.
2. Write one sentence: what an attacker controls and what they gain (funds drained, ownership seized, protocol bricked). If you can't, discard it.
3. Confirm reachability from an external caller in **production** contracts - not tests, mocks, scripts, or dependency `lib/`.
4. Severity: **critical** (fund theft, ownership takeover, invariant break that drains value), **high** (griefing/DoS of core function, price manipulation with bounded profit, precision loss with real impact), **medium** (missing event/slippage guard, recoverable rounding).
5. Drop it if it sits in test/mock/example, needs privileges >= what it yields, or you'd be embarrassed to defend it to the maintainer.

If 0 findings survive -> log "clean audit - N candidates reviewed, 0 confirmed" and go to S8/S9.

**Then adversarially verify every survivor before S7 - apply vuln-scanner §A4.5.** Switch sides and try to *refute* each finding: re-read the contract at HEAD (confirm the vulnerable code is still present and unguarded on the default branch / at the audited commit), build the complet

…(truncated)
