Repository navigation
feat(contracts): implement ADR 026/028/030/031/033/036 deltas - #684
Conversation
Refit the Solidity contract suite to the recent ADR revisions: vote weight
moves from ve-balance to served-bytes (036), tokenomics adopts the work-
token v2.2 no-emission model with Genesis Bond Credits and capacity-curve
naming (026), and slash/blacklist appeals get their own state machines
(028, 031, 032, 033).
Contract surface:
- NEW FeeRouter — 4-bucket distributor (60/25/10/5 by default, bounded
governance-tunable), per-epoch served-bytes accounting, bytesInWindow
helpers consumed by DecdnGovernor per ADR 036.
- NEW SafetyReserve — payout/incidents ledger, pending-claim FIFO queue,
slash-inflow accounting, full six-entrypoint ADR 028 appeal state
machine (open/fastTrack/reject/ratify/reverse/cleanup). reverseAppeal
clears CapacityBond.slashedAtEpoch via APPEAL_REVERSAL_ROLE.
- NEW BuybackBurner — USDC→TOKEN swap-then-burn scaffold; reverts with
SwapNotImplemented until a subclass binds the live Balancer V3 ABI.
- NEW ContentBlacklist — hash (global+regional) + operator + origin
blacklist with ADR 031 appeal entrypoints; cross-contract ejectNode
wire to CapacityBond.
- RENAMED StakingRegistry → CapacityBond. Additions: firstBondedAt +
slashedAtEpoch + clearSlashedAtEpoch (ADR 036); regionPrev/Last +
updateRegion (ADR 030); PendingCredit + Genesis Bond Credit
grant/vest/claim (ADR 026); declaredMbps; slashId + slashRecords +
Treasury forfeit path on unbond.
- REWIRED DecdnGovernor — vote source moved from VotingEscrow to
FeeRouter.bytesInWindow × age_ramp with CapacityBond.slashedAtEpoch
zero-out per ADR 036. voteCapBps + ageRampMonths checkpointed via OZ
Trace208 so setter changes don't shift in-flight proposal weights.
- DELETED VotingEscrow + IVotingEscrow + test + mock.
Review-driven fixes applied in this commit (from /code-review run):
- C1 slashed Genesis Bond Credit now routes through 50/30/20 alongside
the stake-slash amount, not 100% burn.
- C2 defensive cap on _reduceStakeAtTier prevents future tier-bps
changes above 50% from silently underflowing the unbonding subtraction.
- C3 unbond forfeits unvested credit to a governance-set treasury
(burns if treasury unset).
- C4 PendingCredit refactored to {originalGrant, claimed, grantedAt} so
the linear curve no longer skews after a partial claim.
- I1 BuybackBurner.executeBuyback + SafetyReserve.swapAccumulatedTokens
revert with SwapNotImplemented instead of emit-and-no-op.
- I2 CapacityBond.slash mints slashId + persists SlashRecord; SafetyReserve
reads operator from CapacityBond.slashRecords instead of caller assertion.
- I3 recordSlashInflow wrapped in try/catch — faulty SafetyReserve cannot
brick slashing.
- I4 voteCapBps + ageRampMonths use Checkpoints.Trace208; in-flight
proposals snapshot the prior value.
- I5 claimVestedCredit gated on activeStake>0, !ejected, !slashed.
- SF-C1 payout returns (incidentId, queued, claimId) tuple; no more
type(uint256).max sentinel collision.
- SF-M1 openBlacklistAppeal reverts on region == bytes32(0).
Tests: 138/138 pass (+29 new across CapacityBond, FeeRouter, SafetyReserve,
ContentBlacklist, DecdnGovernor). Rust workspace builds clean (sol! bindings
unchanged — function selectors preserved). All contracts under EIP-170;
CapacityBond is tightest at 21.6KB / 2.9KB margin.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Gas snapshotGas changes vs baseRun: 26574856822 |
Contracts coverageLine coverage: 67.81% (853/1258 lines) |
There was a problem hiding this comment.
Code Review
This pull request introduces a major architectural shift, replacing the StakingRegistry with CapacityBond and transitioning DecdnGovernor from a VotingEscrow model to a served-bytes-weighted voting model (ADR 036). It also adds BuybackBurner, ContentBlacklist, FeeRouter, and SafetyReserve to support the updated tokenomics, slashing splits, and appeal lifecycles. The review feedback highlights several critical issues: a potential revert in FeeRouter due to rounding dust being sent to an unset safety reserve, retroactive voting weight zero-out in DecdnGovernor, state override bugs in ContentBlacklist during concurrent appeals, duplicate appeal vulnerabilities in SafetyReserve, and permanent credit claim lockouts in CapacityBond after any historical slash.
There was a problem hiding this comment.
Pull request overview
Refactors the Solidity contract suite to align with updated ADRs (notably ADR 036 served-bytes voting, ADR 026 tokenomics changes, and ADR 028/031 appeals), replacing the legacy VotingEscrow/StakingRegistry model with the new FeeRouter + CapacityBond + SafetyReserve + ContentBlacklist architecture and corresponding tests/mocks.
Changes:
- Replaced ve-style governance weight with ADR 036 served-bytes vote weight via
FeeRouteraccounting +CapacityBondtenure/slash gating inDecdnGovernor. - Introduced/updated core protocol contracts:
FeeRouter,SafetyReserve(payout + slash appeals),ContentBlacklist(blacklist + appeals), andBuybackBurnerscaffold. - Replaced legacy tests/mocks with new smoke tests covering the updated contract surfaces and removed obsolete
VotingEscrow/StakingRegistryartifacts.
Reviewed changes
Copilot reviewed 27 out of 27 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| contracts/testnet/TestnetFaucet.sol | Updates doc reference from StakingRegistry to CapacityBond. |
| contracts/test/VotingEscrow.t.sol | Removes obsolete VotingEscrow tests. |
| contracts/test/StakingRegistry.t.sol | Removes obsolete StakingRegistry tests. |
| contracts/test/SafetyReserve.t.sol | Adds smoke tests for payout queue + slash-appeal state machine. |
| contracts/test/FeeRouter.t.sol | Adds tests for four-bucket settlement routing + epoch byte accounting. |
| contracts/test/DecdnGovernor.t.sol | Replaces VE-based governor tests with ADR 036 served-bytes vote-weight tests. |
| contracts/test/ContentBlacklist.t.sol | Adds smoke tests for blacklist + appeal lifecycle + eject wiring. |
| contracts/test/CapacityBond.t.sol | Adds smoke tests for bonding timestamps, slash epoch, genesis credit flow, and slash records. |
| contracts/test/mocks/MockVotingEscrow.sol | Removes obsolete VE vote-source mock. |
| contracts/test/mocks/MockSafetyReserve.sol | Expands mock to revert loudly on unimplemented paths; keeps recordSlashInflow for slash-redirect assertions. |
| contracts/test/mocks/MockFeeRouter.sol | Adds mock FeeRouter to inject served-bytes totals for governor math tests. |
| contracts/test/mocks/MockEd25519Verifier.sol | Updates doc comment to reference CapacityBond call sites. |
| contracts/test/mocks/MockCapacityBond.sol | Adds mock CapacityBond exposing firstBondedAt, slashedAtEpoch, and slashRecords. |
| contracts/src/VotingEscrow.sol | Removes legacy VE contract. |
| contracts/src/StakingRegistry.sol | Removes legacy staking/registry contract superseded by CapacityBond. |
| contracts/src/SafetyReserve.sol | Adds SafetyReserve implementation (payouts, queue, slash inflow accounting, slash appeals). |
| contracts/src/FeeRouter.sol | Adds FeeRouter implementation (four-bucket settlement + per-epoch served-bytes accounting). |
| contracts/src/DecdnGovernor.sol | Rewires governor vote weight/quorum/threshold to ADR 036 formula and checkpoints cap/ramp params. |
| contracts/src/ContentBlacklist.sol | Adds blacklist + appeals contract and CapacityBond.ejectNode wiring. |
| contracts/src/BuybackBurner.sol | Adds buyback/burn scaffold that intentionally reverts until swap ABI is implemented. |
| contracts/src/Token.sol | Updates docs to reflect new governance weight source and staking entrypoint. |
| contracts/src/interfaces/IVotingEscrow.sol | Removes obsolete VE interface. |
| contracts/src/interfaces/ISafetyReserve.sol | Expands interface to full SafetyReserve external surface. |
| contracts/src/interfaces/IFeeRouter.sol | Adds FeeRouter external interface used by governor/tests. |
| contracts/src/interfaces/ICapacityBond.sol | Adds CapacityBond cross-contract interface for governor + SafetyReserve. |
| contracts/src/interfaces/IEd25519Verifier.sol | Updates docs to reflect CapacityBond onboarding paths. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
CI on the initial PR failed on three jobs: - `solidity build+test` (`forge build --sizes --deny warnings`) tripped on an "unreachable code" warning in OZ ReentrancyGuard, caused by stub-swap functions that always reverted while carrying `nonReentrant`. - `solidity aderyn` flagged H-1 (state change after external view call in `openSlashAppeal`) and H-2 (storage→memory copy into helper params). - `solidity slither` flagged `reentrancy-no-eth` in `requestUnstake`, `unused-return` on `Trace208.push`, and `incorrect-equality` on internally-computed amount guards. Fixes: - BuybackBurner: marked `abstract`; `_performSwap` is now an abstract hook (no body). Solc treats the virtual call as opaque, so the unreachable- code propagation from a return-0 base body is gone. Deployment PRs subclass and supply the real Balancer V3 swap. - SafetyReserve.swapAccumulatedTokens: dropped `nonReentrant` (function always reverts in this revision, so `_nonReentrantAfter` was unreachable). Added a `SwapAttempted` emit before the revert so solc classifies the function as state-mutating (otherwise it would warn "Function state mutability can be restricted to view" — also fatal under `--deny-warnings`). Documented that subclasses with a real swap MUST re-add `nonReentrant`. - SafetyReserve.openSlashAppeal: state writes now happen BEFORE the external `safeTransferFrom` (strict CEI per aderyn H-1). Added an aderyn-ignore-next-line for the prior `capacityBond.slashRecords` view call — the analyzer flags any external call before a later state write regardless of mutability; the call site is a view on a trusted immutable contract. - CapacityBond.requestUnstake: state mutation (activeStake, unbondingOf) now precedes the `_forfeitUnvestedCredit` call that does `token.burn` / `safeTransfer` — slither reentrancy-no-eth fix. - CapacityBond: refactored `_curveVestedFromMem(PendingCredit memory)` → `_curveVested(address)` reading storage directly. ContentBlacklist refactored `_isLive(HashEntry memory)` → `_isLive(bytes32 region, bytes32 hash)` for the same reason — both close aderyn H-2. - DecdnGovernor: added `// slither-disable-next-line unused-return` on the three `Trace208.push` call sites that intentionally discard the return tuple. - CapacityBond: added `// slither-disable-next-line incorrect-equality` directives on the four internal-amount guards (`unvested == 0`, `slashed == 0`, `claimable == 0`) — these are derived amounts, not token-balance reads, so the dangerous-strict-equality detector is a false positive here. Tests: 138/138 still pass. Aderyn: 0 highs (was 2). Slither: exit 0 under `fail_on: medium` (was failing on reentrancy-no-eth + unused-return + incorrect-equality). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI on the second run still failed on two jobs:
- `solidity build+test`: forge-lint flagged 57 `unsafe-typecast` warnings
(every `bytes32("literal")` event-key cast and every
`uint64(block.timestamp / EPOCH_LENGTH)` epoch derivation) plus 6
`erc20-unchecked-transfer` warnings in test files. All warnings are
safe (short string literals; long-lifetime timestamps; tests against
the project's own OZ ERC20 which always returns true). `--deny
warnings` made them fatal.
- `solidity slither`: one `unused-return` slipped through because the
`slither-disable-next-line` directive was followed by an
`aderyn-ignore-next-line` comment on the next line — slither's
"next-line" matched the aderyn comment, not the actual call.
Fixes:
- foundry.toml: added `[lint]` section with `exclude_lints =
["unsafe-typecast", "erc20-unchecked-transfer"]`. Documented why both
are safe to suppress globally.
- SafetyReserve.openSlashAppeal: reordered the suppression comments so
`slither-disable-next-line unused-return` is the LAST comment before
the destructuring call site.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI run on 05f9e26 had `solidity build+test` and `solidity slither` green but `solidity aderyn` regressed (back to 1 high). Root cause: my prior ordering of suppression comments put the slither directive on the line immediately before the call and the aderyn directive one line above the slither directive — so aderyn's `next-line` matched the slither comment instead of the actual call. Slither attributes `unused-return` to the enclosing function, not the call site, so the directive belongs at the function declaration. Moving `// slither-disable-next-line unused-return` directly above `function openSlashAppeal(...)` clears slither without requiring any intermediate comment between the aderyn directive and the call site. The aderyn directive is now the immediate predecessor of the call line (no slither comment in between). Both analyzers see their suppression in scope. Verified locally: aderyn `| High | 0 |`, slither `exit=0`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
PR #684 received inline review from gemini-code-assist (1 critical, 3 high, 1 medium) and Copilot (1 low + 1 dup of critical). All findings verified against the code and addressed: - **G-1 (critical) / Copilot-1 — FeeRouter rounding dust → address(0)** `safetyShare` was the rounding remainder. When `shares[BUCKET_SAFETY] == 0` but `safetyReserve == address(0)` (allowed for inactive bucket), dust triggered `safeTransfer(address(0), 1 wei)` and bricked settlements. Swap the remainder to the operator leg — operator share is always ≥ `OPERATOR_BPS_FLOOR` (4000 bps) and its destination is always non-zero (per-call argument). - **G-2 (high) — DecdnGovernor retroactive slash zero-out** `_slashedInWindow` returned true for any slash whose epoch ≥ windowStart of a HISTORICAL timepoint, retroactively zeroing votes on past proposals. Bound the check at `slashed <= endEpoch` so only slashes that had already happened by the proposal snapshot can zero its weight. - **G-3 (high) — ContentBlacklist concurrent appeal override** Multiple appeals could be opened + fast-tracked for the same `(region, hash)`. When one terminated (reject/lapse/reverse), it cleared `_hashEntries[region][hash].suspended` — un-suspending the entry under any still-live appeals. Added `hasActiveAppeal[region][hash]` boolean guard: `openBlacklistAppeal` reverts with `AppealAlreadyActive` if a live appeal already exists for that pair; every terminal transition (reject / ratify / reverse / cleanup-lapse) clears the flag. - **G-4 (high) — SafetyReserve duplicate appeals on same slashId** Without a guard, multiple appeals could be opened on a single slashId and each ratified up to `maxAppealRestitution`, draining the reserve. Added `slashAppealed[slashId]` one-shot guard; subsequent `openSlashAppeal` calls revert with `SlashAlreadyAppealed`. Set on successful open, never cleared (the slashId is one event; a rejected appeal is final). - **G-5 (medium) — CapacityBond `SlashedInWindowForClaim` locked claims forever** The gate was `if (_slashedAtEpoch[op] != 0) revert` — a slash from a year ago still blocks the claim because `_slashedAtEpoch` is only cleared by `reverseAppeal`. Added `CLAIM_SLASH_GATE_EPOCHS = 13` (matches the default `FeeRouter.windowEpochs`) and gate on `currentEpoch < slashEpoch + 13`. Added a new test `test_claimVestedCredit_succeedsAfterSlashGateExpires`. - **Copilot-2 (low) — FeeRouter unused error** Removed `NonZeroDestinationNeedsShare` — declared but never thrown. Verification: - 139/139 Foundry tests pass (added 1 new for the slash-gate expiry). - `FOUNDRY_PROFILE=ci forge build --sizes --deny warnings` clean. - `aderyn` reports `| High | 0 |`. - `slither --config-file slither.config.json` exits 0 under `fail_on: medium`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…-1..T-4) After the 2nd internal multi-agent review on the post-`dcf44a9` state, applies remaining findings. **F-1 — Swap stubs not overridable.** SafetyReserve `swapAccumulatedTokens` is now `virtual` and calls a `_doSwap` internal virtual hook; the outer function keeps `nonReentrant` because solc cannot propagate the base hook's revert through the virtual call. Subclasses override `_doSwap`, not the external entrypoint. BuybackBurner `executeBuyback` is now `virtual` for symmetry. **S-6 — BuybackBurner burn invariant.** `executeBuyback` reads the TOKEN balance before/after `_performSwap`, asserts the delta matches the subclass-reported `tokenOut`, reverts with `SwapReportMismatch` on under/over-report. Burns the actual delta. Closes the trust boundary. **S-1 — `claimSlashGateEpochs` governance-tunable storage.** Promoted from `internal constant` to `uint64 public`, default 13, bounded `[4, 26]` to match FeeRouter. New `setClaimSlashGateEpochs` setter lets governance keep this in lock-step with `FeeRouter.windowEpochs`. **S-5 — Slash-inflow failure event surfaces reason + slashId.** `catch (bytes memory reason)` captures the revert reason from `recordSlashInflow`. Event is now `SlashInflowReportFailed(slashId, operator, amount, reason)`. `slashId` threads `slash() → _distributeAndStamp → _routeSlashShares`. **S-2/S-3 — Docstring fixes on the claim gate.** Updated NatSpec. **S-4 — Dropped reviewer-bot attribution.** Replaced 5 "gemini-code-assist" mentions with descriptive bug-class phrasing. **T-1 — FeeRouter dust-to-opShare regression test.** **T-2 — SafetyReserve duplicate-appeal revert test.** **T-3 — ContentBlacklist `AppealAlreadyActive` + 3× clear-on-terminal tests.** **T-4 — DecdnGovernor retroactive-slash bound test.** Verification: - 146/146 Foundry tests pass (was 139; +7 new). - `forge build --sizes --deny warnings` clean. - `aderyn` reports `| High | 0 |`. - `slither` exit 0 under `fail_on: medium`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…5740) The F-1 fix in 98ed731 added `nonReentrant` back to `swapAccumulatedTokens` via the `_doSwap` virtual hook on the assumption that solc would treat the virtual call as opaque for reachability analysis. CI's clean rebuild proved otherwise — solc inlines/sees the concrete base `_doSwap` body and propagates its revert, making `_nonReentrantAfter` unreachable and tripping warning 5740 under `--deny-warnings`. Reverting to the pre-F-1 state for `nonReentrant`: - `swapAccumulatedTokens` keeps `virtual` so subclasses can override. - `nonReentrant` is dropped on the base; documented as a checklist item for production subclasses with a real swap. - `_doSwap` keeps the `emit SwapAttempted` so solc still classifies the function as state-mutating (avoids the "can be view" warning). `BuybackBurner.executeBuyback` is unaffected — `_performSwap` is truly abstract there (no body), so solc can't propagate. 146/146 tests still pass; CI build clean post-revert. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…chas - Refresh the stale contract list (Token, VotingEscrow, StakingRegistry, PublisherRegistry, DecdnGovernor) → matches the actual surface on this branch (Token, CapacityBond, FeeRouter, SafetyReserve, BuybackBurner, ContentBlacklist, PublisherRegistry, DecdnGovernor). - Update the contracts test command to mirror CI exactly: FOUNDRY_PROFILE=ci forge build --sizes --deny warnings, plus aderyn and slither at their respective fail thresholds. - New "Solidity CI gotchas" subsection capturing the traps hit during this PR: solc W5740 (unreachable _nonReentrantAfter) when nonReentrant meets an always-reverting body; virtual hooks with concrete bodies don't fool solc's reachability analysis; forge-lint suppressions in foundry.toml [lint] exclude_lints; slither/aderyn directive placement rules; slither unused-return attributes to function; forge-fmt vs solhint 120-char tie-breaker (positional args); emit-before-revert dodges "can be view"; pre-commit re-stage workflow. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ochs, epoch invariant) Source fixes the prior multi-agent review flagged as in-scope: - `_forfeitUnvestedCredit` retroactive clawback: stamps `FULLY_VESTED_SENTINEL` on `pc.grantedAt` so the truncated principal is immediately fully vested on the next curve read. Pre-fix, an operator who claimed partway through vesting and then unbonded lost the vested-but-unclaimed portion because the curve re-stretched the smaller principal over the original timeline. - `FeeRouter.windowEpochs` checkpointing: replaces the live storage read with an OZ `Trace208` history (mirrors the I4 pattern on `voteCapBps`), exposes `windowEpochsAt(timepoint)`, and rewires `DecdnGovernor`'s `quorum` / `proposalThreshold` / `_slashedInWindow` / `_cappedServed` to the snapshot read. Closes the silent mid-vote weight-drift seam. - `FeeRouter` constructor asserts `epochLength_` equals `CapacityBond.epochLength()`. New `EpochLengthMismatch` error + new `epochLength()` accessor on `CapacityBond` (and the local `ICapacityBondReporter` interface) close the silent epoch-mis-anchor footgun where `DecdnGovernor._slashedInWindow` would mix incompatible epoch indices. - Spec deviations documented inline: `UNBONDING_PERIOD_*` bounds vs ADR 009 (`CapacityBond`), `APPEAL_BOND_*` bounds vs ADR 011 (`ContentBlacklist`). - `ICapacityBond.firstBondedAt` NatSpec corrected to match the impl (set from `stake()` / `claimVestedCredit()`, not from `register*`). Test additions covering the headline invariants the suite did not previously exercise: - I3 try/catch: `MockSafetyReserve` gains a `setRevertOnRecordSlashInflow` toggle; `test_slash_succeedsEvenWhenInflowCallbackReverts` proves the slash advances `slashCounter` and skips the inflow row when the callback reverts. - I4 Trace208 snapshot: `TestableDecdnGovernor` subclass exposes a privileged `pushVoteCapBpsForTest`; `test_voteCapBpsAt_preservesPriorReadAfterLaterPush` proves `voteCapBpsAt(historicalTp)` and `getVotes(operator, historicalTp)` stay anchored to the prior cap after a later push. - ADR 030 `updateRegion` cooldown: `test_updateRegion_cooldownAndPrevSnapshot` drives the full `stake -> registerNode -> updateRegion x2` flow with a key-derived operator + EIP-712 binding signature, asserting the first call has no cooldown, the second inside the window reverts, and `regionPrev` snapshots the prior region. - `FeeRouter.routeSettlement` role gate: `test_routeSettlement_revertsWithoutRouterRole` locks the access- control invariant that prevents any account from inflating its own per-epoch served-bytes (= governance voting weight). - Regression: `test_forfeitUnvestedCredit_doesNotClawBackVestedUnclaimed` pins the sentinel fix. `MockFeeRouter` gains a `windowEpochsAt` impl. Mock `MockBondReporter` in the FeeRouter test gains an `epochLength()` impl to satisfy the new constructor check. `.gas-snapshot` regenerated via `FOUNDRY_PROFILE=ci forge snapshot`. Verified: `forge fmt --check` clean, `FOUNDRY_PROFILE=ci forge build --deny warnings` clean, `forge test` -> 151/151 pass (was 138). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request refactors the protocol's core contracts, replacing the StakingRegistry with CapacityBond and transitioning from a ve-token voting model to a served-bytes-weighted voting mechanism in DecdnGovernor integrated with FeeRouter. It also introduces ContentBlacklist, SafetyReserve, and BuybackBurner to support content takedowns, slashing appeals, and buyback-and-burn operations. The review feedback identifies several critical issues: vested-but-unclaimed Genesis Bond Credits currently escape slashing; the returned slash amount in _reduceStakeAtTier is not updated when the unbonding cap is triggered, causing token distribution mismatches; regional bodies can unauthorizedly remove global blacklist entries; epoch 0 slashes are ignored due to sentinel collision; new payouts bypass the SafetyReserve queue violating FIFO ordering; honest appellants are unfairly penalized when fast-tracked appeals lapse; and addHashRegional reverts with an incorrect error.
… 0, FIFO, refund-on-lapse, regional-body scope) Real bugs flagged by gemini-code-assist + Copilot after c02623c: - Slash basis broadened: `_slashPendingCreditAtTier` now slashes the full `originalGrant - claimed` pool (both unvested AND vested-but-unclaimed) instead of just the unvested portion. Closes the loophole where an operator could shield earned credit by simply delaying `claimVestedCredit`. Already-claimed credit lives in `activeStake` and is slashed by `_reduceStakeAtTier`, so the two functions partition the at-risk pool with no double-counting. New regression `test_slashHitsVestedAndUnvestedTogether`. - `_reduceStakeAtTier` now updates `slashAmount` to the actually-subtracted total when the C2 defensive `min(remainder, req.amount)` cap clips — previously the caller's distribution math used the un-clipped value and would over-transfer / over-burn against future tier-bps schedules > 50%. - `removeHashRegional` rejects `region == bytes32(0)` and `region == GLOBAL_REGION` (security-high: REGIONAL_BODY_ROLE could previously delete GLOBAL entries, bypassing governance). Mirrors the guard already on `addHashRegional`. - `_slashedAtEpoch` is now stored as `actualEpoch + 1` so an epoch-0 slash (first `EPOCH_LENGTH` after deploy) is not confused with the unslashed sentinel. Decoded in `CapacityBond.claimVestedCredit` and `DecdnGovernor._slashedInWindow`. Interface NatSpec + tests updated. - `SafetyReserve.payout` queues when the pending queue is non-empty, not only when liquidity is short — preserves insertion-FIFO so a fresh payout cannot jump ahead of an older queued claim. - `cleanupExpiredAppeal` FastTracked branch now REFUNDS the bond instead of burning it. The emergency multisig already validated the appeal at fast-track; a lapse at the ratification stage is governance inactivity and shouldn't penalize honest filers. - `addHashRegional` reverts with `MissingRegion()` (not `ZeroHash()`) when the region argument is invalid — both bots flagged the error misnaming. Cosmetic / safety guards in the same pass: - New `AppealFilingWindowClosed(region, hash)` error so off-chain callers can distinguish "never blacklisted" from "too late to appeal". - `swapAccumulatedTokens` rejects `amountIn == 0` for symmetry with `BuybackBurner.executeBuyback`. - Misleading comments in `test_forfeitUnvestedCredit_doesNotClawBackVestedUnclaimed` rewritten (the prior version referenced a "30k claim" and a "direct test-write" that the test never actually performs). Five additional gemini/Copilot findings on c02623c were verified as false positives (already fixed in earlier passes): FeeRouter dust to operator (T-1), DecdnGovernor `_slashedInWindow` upper bound (T-4), ContentBlacklist concurrent appeals (`hasActiveAppeal` guard), SafetyReserve duplicate slashId (`slashAppealed`), Copilot's `NonZeroDestinationNeedsShare` flag (wrong error name; only `NonZeroShareNeedsDestination` exists). Verified: `forge fmt --check` clean, `FOUNDRY_PROFILE=ci forge build --deny warnings` clean, `forge test` -> 153/153 pass (was 151). `.gas-snapshot` regenerated. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* chore(contracts): triage slither + aderyn findings (closes #690) PR #684's test plan deferred the slither + aderyn static-analysis pass to a follow-up. Both CI gates were already green on main (slither 31 findings, all sub-medium; aderyn 0 High, 80 Low), so this commit handles the explicit triage: fix root causes where cheap, suppress with inline directives where intent is documented, leave sub-threshold noise alone. Slither (31 → 21): - Hoist `ICapacityBondEjector` (was inline in ContentBlacklist) and `ICapacityBondReporter` (was inline in FeeRouter) into dedicated files under `src/interfaces/`. Declare them on `CapacityBond`, mark `ejectNode`, `recordSettlement`, `epochLength` `override`. Clears 2x `missing-inheritance`. - Suppress `missing-zero-check` at the 5 sites where zero address is documented-intentional: `BuybackBurner.setPool`/`setVault` ("not wired" state — `executeBuyback` reverts with `PoolNotWired`), `CapacityBond. setTreasury` (forfeit burns as fallback), and the two `FeeRouter` constructor params for `safetyReserve_` / `buybackBurner_` (allowed iff matching share is zero; cross-validated in `_setShares`). - Suppress `unimplemented-functions` on the `abstract BuybackBurner` — the `_performSwap` virtual-without-body is the documented seam for the Balancer V3 deployment-PR subclass. Aderyn (L-3: 6 → 3, L-5: 1 → 0): - Real zero-checks added to `SafetyReserve.setBalancerPool`, `SafetyReserve.setChallengerIncentivePool`, and `CapacityBond.setSafetyReserve` — none had a documented intent for zero, and writing zero would brick the slash-routing flow. - Remove the unused `error NoPendingCredit()` from CapacityBond. Remaining sub-threshold findings (~21 slither timestamp lows on time-gated state machines + aderyn centralization-risk / unchecked-return / large-numeric lows) are accepted by design — suppressing each would add ~30 directives of noise without clearing any gate. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore(contracts): drop redundant inline comment on FeeRouter constructor Bot reviewers flagged the `// See NatSpec on lines 161-164` reference as both wrong (the @PARAM NatSpec is above the constructor signature) and brittle (hard-coded line numbers drift). The @PARAM NatSpec already documents the zero-allowed semantics — the inline comment was redundant. Keep the two `slither-disable-next-line missing-zero-check` directives. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore(contracts): apply review feedback — override consistency + interface NatSpec - Add `override` to the four pre-existing `ICapacityBond` implementations on `CapacityBond` (`clearSlashedAtEpoch`, `firstBondedAt`, `slashedAtEpoch`, `slashRecords`) so the file no longer mixes styles with the three new `override` markers added for the hoisted `ICapacityBondEjector` / `ICapacityBondReporter` interfaces. - Document on `ICapacityBondReporter.epochLength` why the interface is declared `view` rather than `pure` despite the production implementor being `pure` — test mocks need to return a constructor-stored value per instance, which `pure` (which can't read state or immutables) would block. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Refit the Solidity contract suite to the recent ADR revisions.
DecdnGovernorrewired — vote source moved fromVotingEscrowtoFeeRouter.bytesInWindow × age_rampwithCapacityBond.slashedAtEpochzero-out.VotingEscrowdeleted.StakingRegistry→CapacityBondwith capacity-curve naming, Genesis Bond Credit grant/vest/claim flow, declared-Mbps storage.SafetyReservewith full six-entrypoint appeal state machine, payout queue, slash-inflow accounting.regionPrev/regionLastChanged/updateRegiononCapacityBond.ContentBlacklistwith appeal lifecycle + cross-contractejectNodewire.FeeRouterfour-bucket distributor (governance-tunable shares within ADR 026 bounds) with the per-epoch served-bytes ledger ADR 036 reads.BuybackBurnerscaffold (revertsSwapNotImplementeduntil a subclass binds the live Balancer V3 ABI per ADR 018).Review-driven fixes
This branch went through a multi-agent
/code-reviewafter the initial implementation; the following issues surfaced and were fixed in the same commit before pushing:_reduceStakeAtTierprevents future tier-bps changes above 50% from silently underflowing.treasury(or burns if unset).PendingCreditrefactored to{originalGrant, claimed, grantedAt}; linear curve no longer skews on partial claims.BuybackBurner.executeBuyback+SafetyReserve.swapAccumulatedTokensrevert withSwapNotImplementedinstead of emit-and-no-op.CapacityBond.slashmintsslashId+ persistsSlashRecord;SafetyReserve.openSlashAppealreads operator fromCapacityBond.slashRecords(no caller-asserted operator).recordSlashInflowcallback wrapped intry/catch— faultySafetyReservecannot brick slashing.voteCapBps+ageRampMonthscheckpointed via OZTrace208; in-flight proposals snapshot the prior value.claimVestedCreditgated onactiveStake > 0 && !ejected && !slashed.payoutreturns(incidentId, queued, claimId)tuple; no moretype(uint256).maxsentinel collision.openBlacklistAppealreverts onregion == bytes32(0); caller must passGLOBAL_REGIONexplicitly.StakingRegistry/VotingEscrowreferences and wrong ADR section anchors cleared across multiple files.Out of scope (follow-ups)
PaymentChannel,SlashJudge,OriginAssignmentimplementations (not changed by the latest ADR deltas).BuybackBurner._performSwapandSafetyReserve.swapAccumulatedTokens(deferred per ADR 018 deployment PR).MAX_APPEAL_RESTITUTION(governance-set USDC ceiling for now; documented inSafetyReserveheader).ContentBlacklistheader).updateRegionintegration test (smoke test covers cooldown; full e2e requires the EIP-712 + ed25519registerNodesigning harness).Test plan
(cd contracts && forge fmt --check)— clean(cd contracts && forge build --sizes)— all contracts under EIP-170 (CapacityBond 21.6KB / 2.9KB margin tightest)(cd contracts && forge test)— 138/138 pass across 8 test suitescargo build --workspace && cargo clippy --workspace— clean (alloysol!bindings still match — selectors preserved onCapacityBond)cargo nextest run— 1102/1103 pass;probe_rate_limit_returns_rate_limited_close_codeflakes under nextest, passes undercargo test, unrelated to contract changesgh pr checks— pending CI🤖 Generated with Claude Code