Skip to content

Add a solc-based scanner for unreachable and unused Solidity code - #1890

Open
KillariDev wants to merge 15 commits into
mainfrom
t3/solidity-unreachable-code-scanner
Open

KillariDev wants to merge 15 commits into
mainfrom
t3/solidity-unreachable-code-scanner

Conversation

@KillariDev

@KillariDev KillariDev commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

What

Adds bun run check:solidity-unreachable (tooling/contracts/find-unreachable-solidity.mts), a scanner that analyzes solidity/contracts with solc (analysis only, no code generation) and reports code that can never execute or whose result is never used. It only points out issues; fixing them is left to the implementer. A follow-up PR fixes the current findings.

Why

Dead branches, signatures nothing implements, never-emitted events and similar leftovers accumulate as the protocol changes, and nothing in the compiler or existing checks reports them.

How it works

References are resolved through solc's referencedDeclaration ids rather than names, so overloads, overrides, inheritance and library calls are matched exactly. Concrete contracts in deployable files are the roots. A live contract keeps its entry points and base contracts live, live code keeps what it references live, and overrides of live virtual functions in live contracts are live. Code reached only from dead code is dead.

Kind Reports
after-terminator statements after return, revert, break, continue, an infinite loop, a call that never returns, or a terminating assembly statement (Solidity and Yul)
constant-condition branches and operands decided by constants: literals, named constants, arithmetic on them, and parameters every caller passes the same constant for
tautological-comparison comparisons the operand type decides, such as uint >= 0
redundant-condition conditions an earlier check on the same path, or every caller, already decides, including integer ranges (x < 10 then x > 20), checks on state repeated before anything could change it, checks a modifier already made before _, bounds a checked operation proves (a - b proves a >= b; a / b proves b > 0), operands of &&/`
state-value-condition comparisons of a state variable, mapping element, or struct field with a constant that every value it is ever assigned decides, such as status == Status.Settled when nothing assigns Settled
unreachable-state writes to an enum or integer state variable whose guards need a value the variable can never reach from its start, treating its guarded writes as a state machine; comparisons then use the reachable values
fixed-loop for loops whose constant bounds run the body never or at most once
could-be-immutable production state variables only assigned in the declaring contract's constructor (or only by a constant initializer); delegate-shared storage is skipped
constant-return internal functions that always return the same constant; calls to any function that does fold, including calls through an interface whose every implementation is production code in this repository
unused-function / unused-modifier non-external functions and modifiers no live code uses, interface/abstract signatures nothing calls or implements, and ...Delegate functions no caller routes a delegatecall to
unused-event / unused-error events never emitted (a canonical signature string hashed for a raw log topic counts) and errors never raised
unused-type / unused-contract structs, enums, value types, interfaces, libraries and abstract contracts no live code uses
unused-variable / write-only-variable non-public state variables and file constants never used, or assigned but never read
unused-struct-field / unused-enum-value fields never read and enum values nothing can produce, for types that do not cross the ABI
unused-import / unused-assembly-function imports providing nothing the file (or a whole-file importer) uses, and Yul functions nothing calls
dead-store values assigned to locals or parameters that are overwritten, discarded by a return, or go out of scope before being read, and value-typed state variable writes a later statement overwrites before anything could read them
unused-parameter / unassigned-return parameters a function body never reads, and named return values never assigned
modifier-skips-body modifiers with a path that ends without reaching _, silently skipping the function
uncalled-entry-point external/public functions no Solidity refers to (by reference or selector) and no production TypeScript names; in test harnesses, only functions no TypeScript names at all
undeployed-contract / unconsumed-event concrete contracts nothing deploys (no Solidity new/creation code and no TypeScript names them), and emitted events no production TypeScript reads
never-executed with --coverage, statements in live functions an LCOV report shows the test suite never runs, or that a function is never called at all when every line was missed
never-assigned-variable / constant-struct-field state variables (public ones and mappings included) and struct fields only ever set to their default; reads of them fold to the default, as do locals that keep their initializer
uncalled-restricted-function functions only a fixed contract may call (require(msg.sender == pool), directly or through a modifier) that no live Solidity calls; roles that may be accounts are skipped
ignored-return-value return values (or tuple slots) of internal functions that every caller discards
identical-branches if/else branches or conditional operands that are the same
one-way-branch with --coverage, if conditions the tests only saw go one way and require/assert checks that never failed
constant-test-read never-assigned public state that TypeScript tests still read, so assertions on it cannot fail

Options: --json, --changed (only files changed since the merge base with main), --baseline=file / --write-baseline=file, --sarif=file, --coverage[=lcov path] (defaults to the bun run coverage:contracts:bytecode output), --production (contracts in test directories stop counting as users), and paths inside solidity/contracts to narrow reporting. Vendored code, OpenOracle, Multicall3 and WETH9 are never reported but still count as users. A full scan takes about 20 to 30 seconds, most of it solc analysis with the WASM compiler (ZOLTAR_SOLC_NATIVE_PATH speeds it up).

solidity/ts/compile.ts gains loadMainCompiler() so the scanner reuses the compile pipeline's source loading, import aliasing and compiler selection.

CI: check:solidity-unreachable runs with the committed baseline tooling/contracts/unreachable-solidity-baseline.json and is part of check:repository:current, so CI fails on any finding the baseline does not accept. Under GitHub Actions the failures are also annotated on their lines. Baseline entries match file, kind, and message with numbers ignored, so edits elsewhere in a file do not invalidate them; entries that no longer occur are only reported, so a PR that fixes a baselined finding cannot break another. On current main the baseline holds five findings: a test mock's never-assigned questionForker, three test-harness functions nothing calls (setRejectETH, setConsumeAllGas, creditForkFees), and TwoWayConstantProductFactory.predictPair, which only an integration test calls.

Compiler: solc 0.8.36+ gives built-ins such as require and revert negative declaration ids instead of ids near 2^32, so the scanner now recognises both numbering schemes; without that, the 0.8.39 upgrade on main made it miss every require and revert.

Branch coverage: bytecode coverage now records which way each JUMPI went, under the source range it maps to, as LCOV BRDA records (with BRF/BRH, and branchHits in the summary, merged across shards). The jump bookkeeping lives in solidity/ts/testSupport/coverage/jumpOutcomes.ts, which also takes the trace parsers, so traceToSource.ts shrinks and its size allowance ratchets down to 826. With the full suite's report, the scanner finds 81 one-way branches, almost all require checks whose revert no test triggers.

Motivating case: scanning the pre-#1895 SecurityPoolServices reports its never-filled pendingBurnCash queue and the dead tail of flushBurn, which only coverage had pointed at before.

Validation

  • bun ./tooling/testing/bun-test.mts tooling/contracts/find-unreachable-solidity.test.ts: 72 tests pass (plus 3 for baseline, SARIF, and annotation output). They compile real Solidity snippets with solc and cover each kind plus the false-positive cases found in review.
  • bun run tsc, bun run format:check, bun run check:changed, bun run knip and git diff --check all pass.
  • bun run coverage:contracts:bytecode (all tests pass in both shards), then the scanner with --coverage; test-discovery.test.ts also asserts a real coverage worker records jump outcomes with consistent BRF/BRH totals.
  • bun run check (which now includes the scanner) and the coverage tests that use the touched modules.

Adds bun run check:solidity-unreachable, which analyzes solidity/contracts
with solc and reports code that can never execute or is never used:
statements after terminators, constant and type-decided conditions,
conditions an earlier check already decides, declarations unreachable from
deployable contracts, write-only state variables, unread struct fields,
unproducible enum values, unused imports, and dead assembly code.

References resolve through solc's declaration ids, so liveness follows
overloads, overrides, and inheritance exactly. The scanner only reports;
fixing findings is left to the implementer.
…onstant ranges, and off-chain and coverage evidence

Adds dataflow checks (dead stores, unused parameters, unassigned named returns, modifiers that skip the function body),
integer range facts and named-constant folding for conditions, constant-argument parameters, delegate routing,
and opt-in evidence checks: contracts nothing deploys, emitted events no production TypeScript reads, and,
with --coverage, live statements the test suite never executes.
…nches, and gate CI on a baseline

Adds never-assigned state variables and struct fields (whose reads fold to the default, as do locals that keep
their initializer), functions only a fixed contract may call that no Solidity calls, ranges every caller keeps an
argument within, ignored return values, identical branches, and tests that read never-assigned getters.
Bytecode coverage now records which way each conditional jump went as LCOV BRDA records, and the scanner reports
if conditions and checks the tests only saw go one way. --baseline, --write-baseline, --changed, --sarif, and
GitHub annotations let CI run the scanner: check:repository:current now fails on findings the committed baseline
does not accept.
…etic-implied checks, and overwritten storage
…e checks, operand contradictions, fixed loops, and could-be-immutable state

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant