Skip to content

ci(contracts): add static analysis, security scans, coverage, gas snapshots - #644

Merged
thiras merged 20 commits into
mainfrom
worktree-contracts-ci-hardening
May 21, 2026
Merged

thiras merged 20 commits into
mainfrom
worktree-contracts-ci-hardening

Conversation

@thiras

@thiras thiras commented May 21, 2026

Copy link
Copy Markdown
Contributor

Summary

Hardens contract CI from the existing fmt/build/test trio to a full security-grade pipeline. Splits the single solidity job into seven focused jobs that mirror the Rust split, adds Slither + Aderyn (SAST → SARIF → GitHub code-scanning), Solhint (lint), Codecov (coverage), and sticky-comment gas-snapshot diffs. Foundry pinned to v1.7.1 (was tracking the moving stable channel); all actions used by new/replaced jobs pinned to concrete vX.Y.Z tags.

Local pre-commit hooks (forge-fmt, solhint on commit; forge-build, forge-test on push; slither, aderyn manual) mirror the cargo hook layout.

The plan and rationale for each judgment call live in /home/thiras/.claude/plans/build-ci-for-our-enumerated-planet.md.

New jobs (all gated on needs.changes.outputs.solidity)

  • solidity-fmt — forge fmt --check
  • solidity-build-test — forge build --deny-warnings + forge test (CI profile)
  • solidity-coverage — forge coverage --report lcov → Codecov (contracts flag)
  • solidity-solhint — npm run lint (solhint pinned to 6.2.1)
  • solidity-slither — crytic/[email protected], fail-on: medium, SARIF uploaded
  • solidity-aderyn — aderyn v0.6.8 via official curl installer, SARIF uploaded
  • solidity-gas-snapshot — PR-only; forge snapshot --diff .gas-snapshot; sticky PR comment

Notable judgment calls

  • Lint scope is contracts/src/ only — Foundry's test_xxx_yyy test convention conflicts with func-name-mixedcase and tests aren't security-relevant for lint.
  • Tuned .solhint.json to disable use-natspec/gas-* rules — high false-positive volume, no security signal (ADRs are the canonical docs).
  • Slither flagged divide-before-multiply in slash() — confirmed false positive. The burnShare = slashAmount - challengerShare - safetyShare residual captures all rounding dust, proven by testFuzz_slash_threeLegsSumToSlashAmount. Suppressed inline with justification (no global exclusion).

Test plan

  • solidity-fmt green
  • solidity-build-test green (sizes + 46/46 tests passing under CI profile)
  • solidity-coverage green; Codecov comment appears with contracts flag
  • solidity-solhint green
  • solidity-slither green; SARIF visible in Security → Code scanning under slither category
  • solidity-aderyn green; SARIF visible under aderyn category
  • solidity-gas-snapshot green; sticky comment posts "No gas changes vs base"
  • CI success green (gates on all seven via needs:)
  • Open a separate docs-only PR; confirm all solidity-* jobs report skipped and CI success still goes green via allowed-skips

Post-merge

  • Confirm branch protection still targets only CI success (no UI change needed — added jobs are transitively gated)

🤖 Generated with Claude Code

thiras added 9 commits May 21, 2026 19:49
Adds solhint (v6.2.1) for Solidity style linting on contracts/src/.
Configured for the project's stack:

- compiler-version pinned to ^0.8.28 (matches foundry.toml)
- max-line-length 120 (matches forge fmt config)
- gas-custom-errors enforced (codebase already uses custom errors)
- Disabled noisy/opinion rules (use-natspec, gas-* observations,
  function-max-lines, private-vars-leading-underscore) that produce
  high false-positive volume without security signal — ADRs are the
  authoritative documentation surface.
- Disabled import-path-check (solhint doesn't honor foundry remappings).
- Disabled immutable-vars-naming (codebase deliberately uses lowercase
  for the singleton TOKEN reference; already suppressed at forge-lint
  level).
- Lint scope is src/ only; test/ uses Foundry's test_xxx_yyy convention
  which conflicts with func-name-mixedcase and is functionally
  irrelevant for security lint.

contracts/.gitignore ignores node_modules/, package-lock.json (single
pinned dep makes lock-file noise larger than its determinism benefit),
and SARIF/report outputs from upcoming static-analysis CI.

Verification: cd contracts && npm install && npm run lint exits 0
with zero findings.
Adds slither.config.json with:
- fail_on: medium (block CI on medium-and-above findings)
- filter_paths excludes lib/, test/, script/
- detectors_to_exclude: naming-convention (handled by solhint),
  solc-version/pragma (already pinned in foundry.toml), assembly
  (no inline asm yet — drop exclusion when adding asm)
- solc_remaps mirroring remappings.txt so slither finds OZ + forge-std

The slash math in StakingRegistry triggers slither's
divide-before-multiply detector at lines computing challengerShare
and safetyShare. This is a confirmed false positive: the burnShare
= slashAmount - challengerShare - safetyShare subtraction captures
all rounding dust, so the three legs sum exactly to slashAmount.
The invariant is exercised by testFuzz_slash_threeLegsSumToSlashAmount.
Suppressed inline with justification rather than globally excluding
the detector.

Remaining slither findings (reentrancy-benign, timestamp) are low
severity, expected by design (ReentrancyGuard handles the post-call
state write; unbonding period is timestamp-based per ADR), and do
not fail CI under the medium threshold. They remain visible in
GitHub code-scanning.
Adds aderyn.toml so Aderyn (Cyfrin static analyzer) scans contracts/src
only, with the same OZ + forge-std remappings as foundry.toml.
Excludes lib/, test/, script/, broadcast/, node_modules/, out/, cache/.

Local verification is optional (aderyn install requires cyfrinup or
the curl installer); the CI job exercises this config on every PR.
Generated via FOUNDRY_PROFILE=ci forge snapshot --snap .gas-snapshot.
Covers all 46 tests across Token.t.sol (10 tests) and
StakingRegistry.t.sol (36 tests, including testFuzz_slash with 1024
runs at gas mean 267851).

The upcoming solidity-gas-snapshot CI job runs forge snapshot --diff
against this baseline on PRs and posts the diff as a sticky comment.
Regenerate in the same PR that legitimately moves gas; never commit
a baseline that was not generated under FOUNDRY_PROFILE=ci.
Posts/updates a single sticky PR comment with the output of
forge snapshot --diff .gas-snapshot. Marker-pinned so the
solidity-gas-snapshot CI job (added in a follow-up commit) can
update in place across pushes rather than spawning duplicates.

Mirrors the coverage-comment sticky pattern in ci.yml.
Mirrors the cargo hook layout for Rust, graduated by speed:

commit stage (every commit, fast):
- forge-fmt  — forge fmt --check on staged contracts/*.sol
- solhint    — solhint on contracts/src/ (uses pre-commit's node
               sandbox so contracts/node_modules need not exist)

pre-push stage (only on `git push`):
- forge-build — forge build --deny-warnings
- forge-test  — forge test

manual stage (`pre-commit run --hook-stage manual <id>`):
- slither — needs `pip install slither-analyzer` locally
- aderyn  — needs `aderyn` on PATH (cyfrinup or curl installer)

Slither/aderyn are manual-only because they require external
toolchains; CI is the authoritative gate for both.

solhint is pinned to 6.2.1 to match contracts/package.json so the
hook and the npm install agree.
…rage, gas snapshot

Replaces the single solidity job with seven focused jobs mirroring the
Rust job split (one concern per job):

- solidity-fmt          — forge fmt --check (fast smoke gate)
- solidity-build-test   — forge build --deny-warnings + forge test
                          (CI profile: 1024 fuzz, 256/50-depth invariants;
                          --deny-warnings is new, catches Solidity warnings)
- solidity-coverage     — forge coverage --report lcov → Codecov
                          (contracts flag; coverage profile disables
                          optimizer + via_ir for accurate source mapping)
- solidity-solhint      — npm-installed solhint on contracts/src/
- solidity-slither      — crytic/slither-action with fail-on: medium;
                          SARIF uploaded to GitHub code-scanning
- solidity-aderyn       — Cyfrin/aderyn installed via official curl
                          installer (no SARIF-capable Cyfrin action
                          exists yet); SARIF uploaded to code-scanning
- solidity-gas-snapshot — PR-only; forge snapshot --diff vs the
                          committed baseline; posts sticky PR comment.
                          Skipped on fork PRs (read-only token).

Foundry version pinned to v1.7.1 (was: stable). All actions used by
new/replaced jobs pinned to concrete vX.Y.Z tags
(actions/[email protected], [email protected], [email protected],
[email protected], codeql-action [email protected],
[email protected]).

The `changes` filter gains .github/scripts/post-gas-snapshot-comment.sh
so edits to that script trigger the contracts pipeline (config files
under contracts/ are already covered by 'contracts/**').

ci-success.needs and allowed-skips updated for the new job set; branch
protection rules need no UI change since they target the single
'CI success' check.
Adds a "Solidity development" section to CONTRIBUTING.md covering:
- foundry commands and profiles (default/ci/fuzz/coverage)
- local static analysis (solhint, slither, aderyn) with install hints
- pre-commit hook layout (commit/pre-push/manual stages)
- gas snapshot baseline maintenance workflow
- how to interpret slither/aderyn findings (inline suppress only;
  never expand global exclusions) and where coverage lands

Positioned after the existing "Build and Test" section to keep the
Rust-vs-Solidity distinction visible.
Adds a one-line contracts command to the Common Commands block in
CLAUDE.md and a single sentence pointing at the new Solidity
development section in CONTRIBUTING.md. Full workflow stays in
CONTRIBUTING.md.
Copilot AI review requested due to automatic review settings May 21, 2026 17:02
@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown

Gas snapshot

Gas changes vs base
Compiling 57 files with Solc 0.8.28
Solc 0.8.28 finished in 1.60s
Compiler run successful!

Ran 10 tests for test/Token.t.sol:TokenTest
[PASS] testFuzz_burn_reducesSupplyByExactAmount(uint256) (runs: 1024, μ: 27700, ~: 27700)
[PASS] test_burnFrom_consumesAllowance() (gas: 38534)
[PASS] test_burn_reducesTotalSupplyAndBalance() (gas: 26044)
[PASS] test_constructor_metadata() (gas: 17896)
[PASS] test_constructor_mintsFullSupplyToHolder() (gas: 12954)
[PASS] test_constructor_revertsOnZeroInitialHolder() (gas: 83264)
[PASS] test_constructor_totalSupplyConstantMatches() (gas: 9364)
[PASS] test_noMintFunctionExposed() (gas: 10765)
[PASS] test_noVotesSurfaceExposed() (gas: 11991)
[PASS] test_permit_setsAllowance() (gas: 67380)
Suite result: ok. 10 passed; 0 failed; 0 skipped; finished in 84.01ms (83.50ms CPU time)

Ran 36 tests for test/StakingRegistry.t.sol:StakingRegistryTest
[PASS] testFuzz_slash_threeLegsSumToSlashAmount(uint256) (runs: 1024, μ: 267892, ~: 267939)
[PASS] test_constructor_revertsOnOutOfBoundsMinStake() (gas: 125485)
[PASS] test_constructor_revertsOnOutOfBoundsUnbondingPeriod() (gas: 125607)
[PASS] test_constructor_revertsOnZeroAdmin() (gas: 64369)
[PASS] test_constructor_revertsOnZeroToken() (gas: 64326)
[PASS] test_constructor_setsImmutableAndState() (gas: 23869)
[PASS] test_ejectNode_revertsWithoutBlacklistRole() (gas: 13066)
[PASS] test_ejectNode_setsFlagWithoutMovingTokens() (gas: 114331)
[PASS] test_isActive_requiresMinStakeAndNotEjected() (gas: 137540)
[PASS] test_recordSettlement_revertsWithoutReporterRole() (gas: 13022)
[PASS] test_recordSettlement_updatesTimestamp() (gas: 39711)
[PASS] test_requestUnstake_movesAmountToUnbonding() (gas: 137196)
[PASS] test_requestUnstake_revertsOnInflightRequest() (gas: 139841)
[PASS] test_requestUnstake_revertsOnInsufficientStake() (gas: 89060)
[PASS] test_setMinStake_revertsOutOfBounds() (gas: 17645)
[PASS] test_setMinStake_withinBoundsSucceeds() (gas: 20254)
[PASS] test_setUnbondingPeriod_revertsOutOfBounds() (gas: 17701)
[PASS] test_slash_appliesToActivePlusUnbonding() (gas: 307745)
[PASS] test_slash_autoEjectsWhenStakeFallsBelowHalfMinimum() (gas: 414072)
[PASS] test_slash_distributes50_30_20() (gas: 267038)
[PASS] test_slash_drawsFromUnbondingWhenActiveInsufficient() (gas: 310205)
[PASS] test_slash_notifiesSafetyReserve() (gas: 262215)
[PASS] test_slash_revertsOnZeroChallenger() (gas: 93093)
[PASS] test_slash_revertsWhenSafetyReserveNotWired() (gas: 102762)
[PASS] test_slash_revertsWithoutSlashRole() (gas: 92603)
[PASS] test_slash_tier1_is5Percent() (gas: 259294)
[PASS] test_slash_tier2_is15Percent() (gas: 325018)
[PASS] test_slash_tier3Stays50PercentBeyondThird() (gas: 522527)
[PASS] test_slash_tier3_is50Percent() (gas: 390852)
[PASS] test_stake_addsToActiveStake() (gas: 86918)
[PASS] test_stake_clearsEjectedFlagWhenRestakedToMinimum() (gas: 135568)
[PASS] test_stake_revertsOnZeroAmount() (gas: 18200)
[PASS] test_stake_revertsWhenPaused() (gas: 45265)
[PASS] test_unstake_returnsTokensAfterUnbonding() (gas: 135641)
[PASS] test_unstake_revertsBeforeUnbondingComplete() (gas: 128276)
[PASS] test_unstake_revertsWithNoRequest() (gas: 22449)
Suite result: ok. 36 passed; 0 failed; 0 skipped; finished in 191.65ms (194.00ms CPU time)

Ran 2 test suites in 198.82ms (275.66ms CPU time): 46 tests passed, 0 failed, 0 skipped (46 total tests)
━ StakingRegistryTest::testFuzz_slash_threeLegsSumToSlashAmount(uint256) (gas: 267939 → 267939 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnOutOfBoundsMinStake() (gas: 125485 → 125485 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnOutOfBoundsUnbondingPeriod() (gas: 125607 → 125607 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnZeroAdmin() (gas: 64369 → 64369 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnZeroToken() (gas: 64326 → 64326 | 0 0.000%)
━ StakingRegistryTest::test_constructor_setsImmutableAndState() (gas: 23869 → 23869 | 0 0.000%)
━ StakingRegistryTest::test_ejectNode_revertsWithoutBlacklistRole() (gas: 13066 → 13066 | 0 0.000%)
━ StakingRegistryTest::test_ejectNode_setsFlagWithoutMovingTokens() (gas: 114331 → 114331 | 0 0.000%)
━ StakingRegistryTest::test_isActive_requiresMinStakeAndNotEjected() (gas: 137540 → 137540 | 0 0.000%)
━ StakingRegistryTest::test_recordSettlement_revertsWithoutReporterRole() (gas: 13022 → 13022 | 0 0.000%)
━ StakingRegistryTest::test_recordSettlement_updatesTimestamp() (gas: 39711 → 39711 | 0 0.000%)
━ StakingRegistryTest::test_requestUnstake_movesAmountToUnbonding() (gas: 137196 → 137196 | 0 0.000%)
━ StakingRegistryTest::test_requestUnstake_revertsOnInflightRequest() (gas: 139841 → 139841 | 0 0.000%)
━ StakingRegistryTest::test_requestUnstake_revertsOnInsufficientStake() (gas: 89060 → 89060 | 0 0.000%)
━ StakingRegistryTest::test_setMinStake_revertsOutOfBounds() (gas: 17645 → 17645 | 0 0.000%)
━ StakingRegistryTest::test_setMinStake_withinBoundsSucceeds() (gas: 20254 → 20254 | 0 0.000%)
━ StakingRegistryTest::test_setUnbondingPeriod_revertsOutOfBounds() (gas: 17701 → 17701 | 0 0.000%)
━ StakingRegistryTest::test_slash_appliesToActivePlusUnbonding() (gas: 307745 → 307745 | 0 0.000%)
━ StakingRegistryTest::test_slash_autoEjectsWhenStakeFallsBelowHalfMinimum() (gas: 414072 → 414072 | 0 0.000%)
━ StakingRegistryTest::test_slash_distributes50_30_20() (gas: 267038 → 267038 | 0 0.000%)
━ StakingRegistryTest::test_slash_drawsFromUnbondingWhenActiveInsufficient() (gas: 310205 → 310205 | 0 0.000%)
━ StakingRegistryTest::test_slash_notifiesSafetyReserve() (gas: 262215 → 262215 | 0 0.000%)
━ StakingRegistryTest::test_slash_revertsOnZeroChallenger() (gas: 93093 → 93093 | 0 0.000%)
━ StakingRegistryTest::test_slash_revertsWhenSafetyReserveNotWired() (gas: 102762 → 102762 | 0 0.000%)
━ StakingRegistryTest::test_slash_revertsWithoutSlashRole() (gas: 92603 → 92603 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier1_is5Percent() (gas: 259294 → 259294 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier2_is15Percent() (gas: 325018 → 325018 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier3Stays50PercentBeyondThird() (gas: 522527 → 522527 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier3_is50Percent() (gas: 390852 → 390852 | 0 0.000%)
━ StakingRegistryTest::test_stake_addsToActiveStake() (gas: 86918 → 86918 | 0 0.000%)
━ StakingRegistryTest::test_stake_clearsEjectedFlagWhenRestakedToMinimum() (gas: 135568 → 135568 | 0 0.000%)
━ StakingRegistryTest::test_stake_revertsOnZeroAmount() (gas: 18200 → 18200 | 0 0.000%)
━ StakingRegistryTest::test_stake_revertsWhenPaused() (gas: 45265 → 45265 | 0 0.000%)
━ StakingRegistryTest::test_unstake_returnsTokensAfterUnbonding() (gas: 135641 → 135641 | 0 0.000%)
━ StakingRegistryTest::test_unstake_revertsBeforeUnbondingComplete() (gas: 128276 → 128276 | 0 0.000%)
━ StakingRegistryTest::test_unstake_revertsWithNoRequest() (gas: 22449 → 22449 | 0 0.000%)
━ TokenTest::testFuzz_burn_reducesSupplyByExactAmount(uint256) (gas: 27700 → 27700 | 0 0.000%)
━ TokenTest::test_burnFrom_consumesAllowance() (gas: 38534 → 38534 | 0 0.000%)
━ TokenTest::test_burn_reducesTotalSupplyAndBalance() (gas: 26044 → 26044 | 0 0.000%)
━ TokenTest::test_constructor_metadata() (gas: 17896 → 17896 | 0 0.000%)
━ TokenTest::test_constructor_mintsFullSupplyToHolder() (gas: 12954 → 12954 | 0 0.000%)
━ TokenTest::test_constructor_revertsOnZeroInitialHolder() (gas: 83264 → 83264 | 0 0.000%)
━ TokenTest::test_constructor_totalSupplyConstantMatches() (gas: 9364 → 9364 | 0 0.000%)
━ TokenTest::test_noMintFunctionExposed() (gas: 10765 → 10765 | 0 0.000%)
━ TokenTest::test_noVotesSurfaceExposed() (gas: 11991 → 11991 | 0 0.000%)
━ TokenTest::test_permit_setsAllowance() (gas: 67380 → 67380 | 0 0.000%)

--------------------------------------------------------------------------------
Total tests: 46, ↑ 0, ↓ 0, ━ 46
Overall gas change: 0 (0.000%)

Run: 26244793265

@codecov

codecov Bot commented May 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request establishes a robust Solidity development environment and CI pipeline, introducing tools for linting (Solhint), static analysis (Slither, Aderyn), and gas benchmarking. It includes a new script for posting gas snapshot diffs as PR comments and updates the project documentation to guide contributors on the new Solidity workflow. A review comment identifies that the Slither configuration globally excludes security-critical detectors like assembly, which contradicts the project's stated policy of using inline suppressions.

Comment thread contracts/slither.config.json Resolved
@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 89.97% (was 89.98%, ▼ 0.01%) — 16800/18672 lines

No Rust files changed in this PR.

History
Commit Total Δ vs base
8d7f94b 89.97% ▼ 0.01%
c8bacb1 89.97% ▼ 0.01%
87a508e 89.97% ▼ 0.01%
d59668d 89.97% ▼ 0.01%
bb7dc08 89.97% ▼ 0.01%
2ad38e6 89.96% ▼ 0.02%
2702ebb (HEAD) 89.97% ▼ 0.01%

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens the Solidity contracts CI pipeline by splitting the prior single solidity job into multiple focused jobs and adding security/static-analysis, linting, coverage reporting, and gas snapshot reporting. It also mirrors these checks locally via pre-commit hooks and documents the workflow for contributors.

Changes:

  • Expands Solidity CI into separate fmt, build+test, coverage (Codecov), solhint lint, Slither + Aderyn SARIF code-scanning, and gas snapshot sticky-comment jobs.
  • Adds Solidity tooling/config files for Slither, Aderyn, Solhint, and a committed Foundry gas snapshot baseline.
  • Updates contributor docs and pre-commit hooks to match the CI contract workflow.

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
CONTRIBUTING.md Documents Solidity dev workflow, CI expectations, and how to interpret findings.
CLAUDE.md Adds a quick contracts command bundle and links to the CONTRIBUTING Solidity section.
.pre-commit-config.yaml Adds Solidity hooks (forge fmt, solhint, forge build/test, slither, aderyn) with staged execution.
.github/workflows/ci.yml Replaces the monolithic Solidity job with a multi-job pipeline including SAST, coverage, and gas snapshots.
.github/scripts/post-gas-snapshot-comment.sh Adds a sticky-comment helper script for gas snapshot diffs.
contracts/src/StakingRegistry.sol Adds inline Slither suppression + rationale for a known false positive in slash() share splitting.
contracts/slither.config.json Adds Slither configuration (paths, fail threshold, remaps, excluded detectors).
contracts/aderyn.toml Adds Aderyn configuration (src/excludes/remappings).
contracts/package.json Adds a local solhint install + lint script for contracts.
contracts/.solhint.json Adds Solhint rules tuned for this repo’s Solidity code style.
contracts/.solhintignore Excludes build artifacts and vendored deps from linting.
contracts/.gitignore Ignores node_modules and SARIF/report outputs for contract tooling.
contracts/.gas-snapshot Adds a committed baseline for Foundry gas snapshot diffs.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread .github/workflows/ci.yml Resolved
Comment thread CONTRIBUTING.md Resolved
Comment thread contracts/.gitignore Resolved
thiras added 2 commits May 21, 2026 20:17
CI failures (3):
- aderyn.toml: aderyn-v0.6.8 expects `version = 1`, `src` as String
  (not array), and no `remappings` field (auto-discovered from
  foundry.toml). Regenerated against the actual schema in
  Cyfrin/aderyn aderyn_driver::config::AderynConfig.
- foundry.toml: forge v1.7.1 introduced forge-lint with the
  block-timestamp rule, which fires on StakingRegistry.unstake's
  unbonding check (block.timestamp < req.unlockAt). With CI now
  running `forge build --deny warnings`, the lint warning failed
  the build. Suppressed at the project level via [lint] exclude_lints
  rather than inline so older forge versions (which don't recognize
  the unknown lint id) don't themselves warn — keeping local dev
  portable across forge releases. Validator manipulation of
  block.timestamp is bounded by consensus drift (seconds), dwarfed
  by the unbonding period (days, ADR 003) — the comparison is the
  explicit design.
- ci.yml: codeql-action/upload-sarif calls the workflow_runs API to
  enrich SARIF metadata; without `actions: read` the call 403s after
  SARIF validation already passed. Added to solidity-slither and
  solidity-aderyn jobs.

Review feedback addressed:

gemini-code-assist on slither.config.json:
- Dropped `assembly` from detectors_to_exclude. The original
  rationale ("we have no assembly") doesn't justify pre-emptive
  global exclusion of a security-critical detector. If no assembly
  is used, the detector never fires; if assembly is added later,
  slither catches it. Verified: zero new findings on current code.

Copilot on ci.yml gas snapshot step:
- The previous `forge snapshot --diff … > /tmp/gas-diff.txt || true`
  redirected stdout BEFORE the `|| true`, so a forge failure
  (compile/test/missing-baseline) produced an empty diff file that
  later posted as "No gas changes vs base", masking real errors.
  Now uses `set -o pipefail` and no `|| true` — the step fails
  loudly on forge errors. Empty diff from a successful run remains
  valid and still reports "No gas changes".

Copilot on CONTRIBUTING.md aderyn install:
- Replaced the `releases/latest` installer URL with the pinned
  `releases/download/aderyn-v0.6.8/aderyn-installer.sh` URL, matching
  the CI pin. Added an inspect-before-piping note.

Copilot on contracts/.gitignore + npm install:
- Committed contracts/package-lock.json (97 transitive packages) and
  removed the .gitignore exclusion. Switched CI from `npm install`
  to `npm ci` so the full transitive dependency graph is pinned, not
  just solhint itself. Added setup-node cache config keyed on the
  lock file. Updated CONTRIBUTING.md to recommend `npm ci` locally.

Also modernized `--deny-warnings` (deprecated in v1.7) to
`--deny warnings` in the CI invocation.
Drops the codecov/codecov-action upload in favor of a sticky PR
comment with line coverage and delta vs main, mirroring the Rust
side's coverage-diff.py pattern (parallel script, distinct marker
to avoid sticky-comment collision).

solidity-coverage job changes:
- Permissions: contents: read, pull-requests: write (was: only the
  default contents: read, which the upstream codecov-action handled).
- On push to main: actions/upload-artifact@v7 publishes lcov.info as
  the `contracts-coverage-lcov` baseline (90-day retention, matches
  Rust).
- On PR: dawidd6/action-download-artifact@v21 fetches the latest
  successful main baseline. `if_no_artifact_found: warn` so first-ever
  PRs / expired baselines degrade gracefully to "head-only" coverage
  display.
- New step posts a sticky comment via .github/scripts/contracts-
  coverage-comment.sh; continue-on-error keeps coverage tooling
  non-blocking even though the job itself is required.

contracts-coverage-comment.sh:
- LCOV parsing via awk over LF:/LH: aggregates; gives total line
  coverage % plus head-vs-base delta in percentage points.
- Sticky comment via gh REST API; marker
  <!-- decdn-contracts-coverage-comment --> is distinct from the
  Rust marker so the two reports don't collide.
- Local dry-run mode: omit GH_PR_NUMBER and the script prints the
  body to stdout instead of posting.

Other:
- contracts/.gitignore ignores lcov.info + baseline/ so local
  forge coverage runs don't dirty git status.
- CONTRIBUTING.md "Interpreting CI findings" updated to describe
  the sticky-comment flow instead of codecov.
- changes filter picks up the new script path.
@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 93.58% (102/109 lines)
No baseline available (first PR on this stack, or baseline artifact expired).
Run: 26244793265

thiras added 9 commits May 21, 2026 20:31
Both slither and aderyn jobs were failing on the SARIF upload step with
"Advanced Security must be enabled for this repository to use code
scanning". GHAS is required for code-scanning on private repos (free on
public repos), and decdn/decdn is private without GHAS today. The SARIF
file was being validated and uploaded successfully — the platform just
refused to ingest it.

Slither:
- Keep the run and the `fail-on: medium` config-level gate (that's the
  authoritative CI signal — findings still fail the step).
- Add `continue-on-error: true` to the SARIF upload step so its failure
  doesn't fail the job. The upload is left in place so it activates
  automatically if GHAS is enabled later or the repo goes public.

Aderyn:
- Swap the manual installer + invoke for the official Cyfrin/aderyn-ci
  action (v0.0.10) with `fail-on: high`. The action runs aderyn, posts
  a job-summary view of findings, and gates CI via its own exit code —
  no SARIF needed. This also drops the security-events: write + actions:
  read permissions from the aderyn job.

CONTRIBUTING.md "Interpreting CI findings" updated: slither/aderyn
output lives in the job log; the Security tab only renders if GHAS is
enabled.
Now that GitHub Advanced Security is enabled and aderyn is gated via
Cyfrin/[email protected] (fail-on: high), aderyn flagged the same
pattern slither marks as reentrancy-benign: the external calls in
slash() (safetyReserve.recordSlashInflow, token.burn) precede the
`ejected[operator] = true` state write at line 403. Aderyn rates this
HIGH; slither rates it LOW.

Adds inline `aderyn-fp-next-line(reentrancy-state-change)` directives
on the two flagged lines, paired with the equivalent
`slither-disable-next-line reentrancy-benign` (slither doesn't fail on
this one today since it's Low + the config gate is `fail_on: medium`,
but pairing the directives keeps the two analyzers aligned).

Why this is a false positive:
- slash() carries `nonReentrant` (line 331), so a reentrant call is
  impossible.
- `ejected` is informational; nothing in slash() reads it to decide on
  external calls.
- Both external-call targets (TOKEN, SafetyReserve) are admin-
  configured trusted contracts (set via constructor + setSafetyReserve).

A CEI-clean refactor that moves the state write earlier was attempted
and reverted — it required one extra local variable (`bool autoEject`)
which pushed slash() past Solidity's 16-slot stack limit (would have
needed via_ir, a project-wide compile-strategy change out of scope for
this PR).
Removes the slither reentrancy-benign / aderyn reentrancy-state-change
inline suppressions in slash() by actually following checks-effects-
interactions: compute `bool autoEject` from post-slash state, write
`ejected[operator] = true` BEFORE the external transfers, defer the
AutoEjected emit so log order in indexers still reads "transfers, then
eject".

The earlier refactor attempt (commit-history) hit Solidity's 16-slot
stack limit because `req`, `totalAtRisk`, and `remainder` stayed live
through the share computation + new autoEject bool. Wrapping them in a
block scope frees their slots before the share locals are declared, so
the function compiles without via_ir. Verified locally on forge v1.7.1:
build clean, 46/46 tests pass, aderyn 0 HIGH findings, slither down
from 2 results to 1 (only `timestamp` LOW remains in unstake()).

Drops the corresponding 14-line justification block — the code is now
the documentation. The divide-before-multiply suppression on the share
computations stays, since that pattern (truncate slashAmount once,
split into three legs with burn-as-residual) is not addressable
without semantic change.

foundry.toml change: replaces the project-wide
`[lint] exclude_lints = ["block-timestamp"]` with an inline
`// forge-lint: disable-next-line(block-timestamp)` directive at the
single site (unstake's unbonding check). Reasoning: future timestamp
misuse (oracle freshness, VRF seed) should not be silently skipped by
a blanket project-level exclusion. Now requires forge >= 1.7
locally; CONTRIBUTING.md already pins to v1.7.1.
…pin)

solidity-coverage:
- Add `actions: read` permission. dawidd6/action-download-artifact
  calls the workflow_runs API; without this, the call 403s on a
  private repo and (because the step is `continue-on-error: true`)
  every PR silently renders "no baseline available". Same root-cause
  as the slither/aderyn permission fix.
- After downloading, write contracts/baseline/.absent-reason so the
  comment script can distinguish "first PR / artifact expired"
  (not-found) from "artifact API failed" (download-failed). The
  previous code treated both identically, hiding real outages.

solidity-slither:
- Drop the SARIF-upload `continue-on-error: true`. It was added when
  GitHub Advanced Security was unavailable; GHAS is now enabled, so a
  failed upload is a real signal (token-scope drift, schema rejection,
  billing lapse) that should fail the job.
- Rewrite the inline comment to reflect that GHAS is enabled, removing
  the stale "private repo" framing.

solidity-gas-snapshot:
- `forge snapshot --diff` exits 0 (and writes a full snapshot to
  stdout) when the baseline file is missing, which previously posted
  a giant fake "gas changes" comment. Add an explicit
  `[ -f .gas-snapshot ]` guard with a clear error message.
- Drop the misleading `set -o pipefail` invocation and comment. The
  step has a redirect, not a pipeline, so pipefail does nothing here;
  GH Actions bash already defaults to `set -eo pipefail`.

Third-party actions SHA-pinned (supply-chain hardening for the new
security pipeline):
- dawidd6/action-download-artifact@v21 → b6e2e70617bc...
- crytic/[email protected]         → b52cc1cbfee9...
- Cyfrin/[email protected]             → 6c7e31332665...

Aderyn `working-directory` input still used despite the action's
deprecation warning — the workflow comment notes the warning is
benign and the input still works in v0.0.10.
post-gas-snapshot-comment.sh:
- All GH_/GITHUB_ env vars guarded with `:?` defaults so a local
  dry-run fails with a useful message rather than a cryptic
  `unbound variable` from set -u (only DIFF_FILE/GH_PR_NUMBER were
  previously guarded).
- Read the diff body via `$(<"$DIFF_FILE")` instead of `$(cat …)` so a
  failure between the `[ -s … ]` size check and the read (the file
  gets deleted by another step, permissions race, etc.) propagates
  via set -e instead of producing an empty BODY masked as "no diff".
- Diff body wrapped in `~~~` fence instead of triple-backtick, so a
  test name containing ``` (e.g. crafted via a fork PR test) can't
  break out of the code fence and inject markdown.
- gh api response body captured to a tempfile + trap on non-zero
  exit; previously `> /dev/null` swallowed 4xx response bodies that
  would diagnose rate-limit / token-scope / validation failures.
- Heredoc-based body assembly (read -r -d '' BODY <<EOF) is portable
  across bash versions and reads better than the prior $'\n' string
  concatenation chain.

contracts-coverage-comment.sh:
- LCOV totals: awk regex anchored to `^LF:[0-9]+$` / `^LH:[0-9]+$`.
  The previous `/^LF:/` would have matched any line beginning with
  `LF:`, including pathological cases where another LCOV field
  contained that token.
- New parse_totals helper detects awk-empty-output (read succeeds
  with empty values) and surfaces it as `::error::` rather than
  silently rendering "0/0 lines" as a "real" 0% measurement.
- New optional 3rd argument `<absent-reason-file>` distinguishes
  baseline-download outcomes:
    - "not-found"        → first PR / artifact expired (informational)
    - "download-failed"  → artifact API outage (:warning: surfaced)
  Previously both rendered the same "no baseline available" message,
  so a persistent artifact-API regression would look identical to
  legitimate first PRs.
- Same gh api response-body capture trap as the gas-snapshot script.

ci.yml: pass `baseline/.absent-reason` to the coverage comment
invocation as the 3rd argument (the workflow step writes it; see
Group A commit b487291).
- Drop `fail_on: medium` from JSON. The crytic/slither-action input
  `fail-on: medium` in ci.yml is the authoritative gate; the action
  overrides any config-level value, so having both invited drift if
  someone tightened one and not the other.
- Add `_comment_fail_on` and `_comment_excludes` sibling keys
  (slither ignores unknown keys) documenting (a) where the severity
  gate actually lives and (b) why naming-convention / solc-version /
  pragma are excluded (overlap with solhint + explicit solc pin).
  Greppable rationale beats a config that drifts away from its docs.
CI uses the new `--deny warnings` syntax (forge v1.7.1 deprecated the
old `--deny-warnings` form). Pre-commit hook and CONTRIBUTING.md
still referenced the deprecated form; aligned to the new form so a
future forge bump that finally removes the deprecation doesn't leave
local dev + docs broken while CI passes.
- Regenerate contracts/.gas-snapshot baseline. The CEI refactor in
  39aa9a9 (introducing the `autoEject` bool + block-scoping `req`/
  `totalAtRisk`/`remainder`) shifted gas costs by an average of +775
  units (~0.014%) across 14 tests; baseline regenerated under
  FOUNDRY_PROFILE=ci so the gas-snapshot CI job reports clean diffs
  going forward.
- Restore `fail_on: medium` in slither.config.json. The agent review
  flagged it as redundant because the action passes `fail-on: medium`
  via its input, but removing it broke the local CLI invocation (and
  the manual pre-commit hook) — slither 0.11.5's CLI default is
  `--fail-pedantic`, which fails on LOW findings unless the config
  field is honored. With `fail_on` back in the config, both surfaces
  (action + local CLI) agree on the gate. Removed the `_comment_*`
  sibling keys in favor of documenting the rationale in
  CONTRIBUTING.md (slither logs INFO warnings for unknown JSON keys,
  which added log noise without value).
- CONTRIBUTING.md "Interpreting CI findings" now spells out the
  globally excluded detectors and why, plus the post-GHAS SARIF
  behavior (upload no longer continue-on-error).
decdn/decdn is private without GitHub Advanced Security, so the
code-scanning SARIF upload errors with "Advanced Security must be
enabled". Comments out the Upload SARIF step in solidity-slither and
removes the now-unused `security-events: write` + `actions: read`
permissions from the job; the slither step still produces
results.sarif on disk, only the upload-to-code-scanning is gated.

The slither-action's `fail-on: medium` input remains the authoritative
CI gate — medium-and-above findings fail the job and surface in the
run log. Re-enabling the upload requires uncommenting the step and
restoring the two permissions (instructions inline next to the
commented-out block).

CONTRIBUTING.md "Interpreting CI findings" updated to reflect the
disabled state.

aderyn still runs via Cyfrin/[email protected] with fail-on: high,
which produces its own job-summary output rather than SARIF — so the
aderyn job is unaffected.
@thiras
thiras merged commit 1504ecb into main May 21, 2026
18 checks passed
@thiras
thiras deleted the worktree-contracts-ci-hardening branch May 21, 2026 18:23
alpergundogdu added a commit that referenced this pull request May 22, 2026
Extends StakingRegistry with the iroh-NodeId binding + multiaddrs
registry from ADR 003 § Node Registry. Stake mechanics and slash math
are unchanged; this layers identity + active-set pagination on top of
the merged stake-and-slash core.

OZ v5 additions: EIP712 (BindNodeId typed-data domain) + SignatureChecker
(EOA + ERC-1271 + ERC-4337 binding signatures, ADR 024).

New surface:
  - registerNode / deregisterNode / updateMultiaddrs
  - getNode / getNodeByAddress / isActiveNode / getActiveNodeCount /
    getActiveNodes (pagination) / getFirstRegisteredAt / nodeIdOf
  - refined isActive(addr): registered + active + stake>=min + !ejected
  - IEd25519Verifier abstraction (real impl is its own audit boundary;
    tests use MockEd25519Verifier)
  - governable multiaddrUpdateCooldown [0,1d] + maxMultiaddrSize [64,1024]

Auto-eject (slash + blacklist) propagates to NodeInfo.active +
registrationNonce bump + active-set removal (gemini security review:
every active-set exit invalidates stale ed25519 registration sigs).

Rebased onto main's contract CI overhaul (#644). Integrated #644's
slash() hardening into the node-registry version: block-scoped
stake-reduction locals, slither-disable divide-before-multiply on the
bps share calcs, checks-effects-interactions (all eject effects commit
before external transfers; emits defer to after), forge-lint
block-timestamp disable on the updateMultiaddrs cooldown comparison.
.gas-snapshot baseline regenerated for the new surface.

Local verification (forge v1.7.1, matching CI pin): forge fmt --check,
forge build --deny warnings, forge test (111/111), npm run lint
(solhint 0 errors), gas snapshot regenerated.

Out of scope (follow-up): bindNodeId (rebinding), reclaimNodeId
(squat recovery), real IEd25519Verifier implementation.

Refs: #452

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request May 22, 2026
Extends StakingRegistry with the iroh-NodeId binding + multiaddrs
registry from ADR 003 § Node Registry. Stake mechanics and slash math
are unchanged; this layers identity + active-set pagination on top of
the merged stake-and-slash core.

OZ v5 additions: EIP712 (BindNodeId typed-data domain) + SignatureChecker
(EOA + ERC-1271 + ERC-4337 binding signatures, ADR 024).

New surface:
  - registerNode / deregisterNode / updateMultiaddrs
  - getNode / getNodeByAddress / isActiveNode / getActiveNodeCount /
    getActiveNodes (pagination) / getFirstRegisteredAt / nodeIdOf
  - refined isActive(addr): registered + active + stake>=min + !ejected
  - IEd25519Verifier abstraction (real impl is its own audit boundary;
    tests use MockEd25519Verifier)
  - governable multiaddrUpdateCooldown [0,1d] + maxMultiaddrSize [64,1024]

Auto-eject (slash + blacklist) propagates to NodeInfo.active +
registrationNonce bump + active-set removal (gemini security review:
every active-set exit invalidates stale ed25519 registration sigs).

Rebased onto main's contract CI overhaul (#644). Integrated #644's
slash() hardening into the node-registry version: block-scoped
stake-reduction locals, slither-disable divide-before-multiply on the
bps share calcs, checks-effects-interactions (all eject effects commit
before external transfers; emits defer to after), forge-lint
block-timestamp disable on the updateMultiaddrs cooldown comparison.
.gas-snapshot baseline regenerated for the new surface.

Local verification (forge v1.7.1, matching CI pin): forge fmt --check,
forge build --deny warnings, forge test (111/111), npm run lint
(solhint 0 errors), gas snapshot regenerated.

Out of scope (follow-up): bindNodeId (rebinding), reclaimNodeId
(squat recovery), real IEd25519Verifier implementation.

Refs: #452

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request May 22, 2026
* feat(contracts): add node-registry surface to StakingRegistry

Extends StakingRegistry with the iroh-NodeId binding + multiaddrs
registry from ADR 003 § Node Registry. Stake mechanics and slash math
are unchanged; this layers identity + active-set pagination on top of
the merged stake-and-slash core.

OZ v5 additions: EIP712 (BindNodeId typed-data domain) + SignatureChecker
(EOA + ERC-1271 + ERC-4337 binding signatures, ADR 024).

New surface:
  - registerNode / deregisterNode / updateMultiaddrs
  - getNode / getNodeByAddress / isActiveNode / getActiveNodeCount /
    getActiveNodes (pagination) / getFirstRegisteredAt / nodeIdOf
  - refined isActive(addr): registered + active + stake>=min + !ejected
  - IEd25519Verifier abstraction (real impl is its own audit boundary;
    tests use MockEd25519Verifier)
  - governable multiaddrUpdateCooldown [0,1d] + maxMultiaddrSize [64,1024]

Auto-eject (slash + blacklist) propagates to NodeInfo.active +
registrationNonce bump + active-set removal (gemini security review:
every active-set exit invalidates stale ed25519 registration sigs).

Rebased onto main's contract CI overhaul (#644). Integrated #644's
slash() hardening into the node-registry version: block-scoped
stake-reduction locals, slither-disable divide-before-multiply on the
bps share calcs, checks-effects-interactions (all eject effects commit
before external transfers; emits defer to after), forge-lint
block-timestamp disable on the updateMultiaddrs cooldown comparison.
.gas-snapshot baseline regenerated for the new surface.

Local verification (forge v1.7.1, matching CI pin): forge fmt --check,
forge build --deny warnings, forge test (111/111), npm run lint
(solhint 0 errors), gas snapshot regenerated.

Out of scope (follow-up): bindNodeId (rebinding), reclaimNodeId
(squat recovery), real IEd25519Verifier implementation.

Refs: #452

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(contracts): address Copilot review on node-registry PR

Four findings from Copilot, all applied:

1. isActive now requires no in-flight unbonding (unbondingOf.amount
   == 0) — ADR 003 line 785 lists "stake fully or partially in
   unbonding" as inactive, even when remaining activeStake >= minStake.

2. registerNode rejects ejected callers (new OperatorEjected error).
   Prevents a blacklist/auto-ejected operator that still holds
   stake >= minStake from re-entering _registeredAddrs / getActiveNodes
   while ejected == true. Reinstatement (re-stake to >= minStake) is
   required first.

3. regionHint is length-bounded (MAX_REGION_HINT_BYTES = 16, new
   RegionHintTooLong error) — anti-state-bloat bound; ADR 003 specifies
   a 2-byte ISO 3166-1 alpha-2 code (self-reported/unverified).

4. deregisterNode vs ADR 003 reconciled. Implementation flips the
   active flag without auto-unbonding (deactivation and stake exit are
   separate; stake stays bonded + slashable; re-register needs no
   re-funding). ADR 003 line 678 updated to match — the slash-then-run
   protection keys off requestUnstake, not deregistration, so it holds.

Tests +3, 114/114 passing under FOUNDRY_PROFILE=ci. Gas snapshot
regenerated.

Refs: #452

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(contracts): slither-disable the isActive unbonding presence check

The Copilot-requested `unbondingOf[operator].amount == 0` clause in
isActive tripped slither's incorrect-equality (Medium) detector — same
false-positive class as the firstRegisteredAt == 0 write-once sentinel.
It's a presence check (no in-flight unbonding request), not a
manipulable balance equality. Scoped slither-disable with rationale.

Refs: #452

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

2 participants