Repository navigation
refactor(contracts): remove SafetyReserve; escrow-on-slash + 5% bucket to burn - #708
Conversation
…t to burn Removes the SafetyReserve contract and its standing USDC insurance pool. Slash restitution is now handled by escrow-on-slash in CapacityBond, and the slash-appeal state machine lives in a new standalone SlashAppeal contract. Contracts: - Delete SafetyReserve.sol / ISafetyReserve.sol (+ test + mock). - FeeRouter: drop the 4th "safety" bucket; fold its 5% into buyback (25%->30%). Split is now 60/30/10, uint256[4]->uint256[3]. - CapacityBond: escrow-on-slash. slash() escrows the slashed TOKEN (escrowedTotal) instead of distributing it; add permissionless finalizeUnappealedSlash (50/50 challenger/burn after the 30-day window) and the SLASH_APPEAL_ROLE settle hooks markAppealOpen / settleAppealUpheld / settleAppealGranted (refund operator + internal _clearSlashedAtEpoch). Remove the 30% safety redirect, recordSlashInflow try/catch, and the SafetyReserveNotWired guard. - New SlashAppeal.sol + ISlashAppeal.sol + ICapacityBondSlashEscrow.sol: open/fastTrack/reject/grant/uphold/cleanup; TOKEN appeal bonds only, no USDC/pool/swap/queue. grant/uphold replace the old ratify/reverse. - CapacityBond drops to 23,167 B (was 23,912) despite gaining escrow logic. Verification: forge build --sizes --deny warnings (all <24KB), forge fmt, 257/257 tests pass (new SlashAppeal + escrow-lifecycle coverage), aderyn 0 high, slither no medium+, gas snapshot regenerated. ADRs (single source of truth): - Retire 032 + 033 to _history/. - Rewrite 026 (split 60/30/10, escrow-on-slash 50/50, recourse-gap note) and 028 (escrow-refund-in-TOKEN, SlashAppeal surface). - Structural updates to 016 + 009; cross-ref fixes in 003/008/014/018/031/ 036/architecture/glossary/appendices; update decdn/CLAUDE.md ADR note. Accepted scope reduction: downtime / bad-data user recourse is no longer a protocol contract surface (DAO Treasury governance only); reputation (ADR 008) is the standing deterrent. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Contracts coverageLine coverage: 83.62% (980/1172 lines) |
Gas snapshotGas changes vs baseRun: 26651225936 |
There was a problem hiding this comment.
Code Review
This pull request retires the SafetyReserve contract and introduces a standalone SlashAppeal contract alongside an escrow-on-slash model in CapacityBond. It also updates the tokenomics to a three-bucket split (60% operator, 30% buyback, 10% treasury). The review feedback highlights several improvement opportunities: restricting rejectAppeal in SlashAppeal to open appeals to preserve the two-stage governance process, adding explicit validation checks for invalid slash IDs in CapacityBond's escrow hooks, and specifying exact error selectors in Foundry tests instead of using empty vm.expectRevert() calls.
There was a problem hiding this comment.
Pull request overview
This PR removes the SafetyReserve contract surface and replaces slash restitution with CapacityBond escrow-on-slash plus a standalone SlashAppeal state machine. It also updates fee routing from 60/25/10/5 to 60/30/10 and refreshes tests, gas snapshots, and ADR documentation around the new contract model.
Changes:
- Removed
SafetyReservecontracts/tests/mocks/interfaces and introducedSlashAppeal+ICapacityBondSlashEscrow. - Refactored
CapacityBondslashing to escrow slashed TOKEN until finality or appeal resolution. - Updated FeeRouter bucket accounting, governance lifecycle tests, and ADR references for the 60/30/10 split.
Reviewed changes
Copilot reviewed 36 out of 36 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
contracts/src/CapacityBond.sol |
Adds slash escrow records, finality distribution, and appeal settle hooks. |
contracts/src/SlashAppeal.sol |
New slash appeal state machine and appeal bond handling. |
contracts/src/FeeRouter.sol |
Converts routing from four buckets to three buckets. |
contracts/src/ContentBlacklist.sol |
Updates comments to reference SlashAppeal. |
contracts/src/interfaces/ICapacityBond.sol |
Removes external slash-clearer from the read interface. |
contracts/src/interfaces/ICapacityBondSlashEscrow.sol |
Adds escrow hook interface for SlashAppeal. |
contracts/src/interfaces/ISlashAppeal.sol |
Adds SlashAppeal public interface. |
contracts/src/interfaces/ISafetyReserve.sol |
Removes retired SafetyReserve interface. |
contracts/src/SafetyReserve.sol |
Removes retired SafetyReserve contract. |
contracts/test/CapacityBond.t.sol |
Updates slashing tests for escrow lifecycle. |
contracts/test/SlashAppeal.t.sol |
Adds end-to-end SlashAppeal flow tests. |
contracts/test/FeeRouter.t.sol |
Updates FeeRouter tests for three-bucket routing. |
contracts/test/GovernanceLifecycle.t.sol |
Replaces SafetyReserve lifecycle coverage with SlashAppeal coverage. |
contracts/test/SafetyReserve.t.sol |
Removes retired SafetyReserve tests. |
contracts/test/mocks/MockSafetyReserve.sol |
Removes retired SafetyReserve mock. |
contracts/test/mocks/MockCapacityBond.sol |
Updates mock comments/interface compatibility. |
contracts/.gas-snapshot |
Refreshes Foundry gas snapshots. |
CLAUDE.md |
Updates repository/ADR notes for SafetyReserve retirement. |
adr/003-payments.md |
Updates payment-routing docs to 60/30/10. |
adr/008-reputation.md |
Updates non-base skim description. |
adr/009-governance.md |
Updates governance model for SlashAppeal and three FeeRouter shares. |
adr/014-on-chain-verification.md |
Updates slashing verification docs for escrow-on-slash. |
adr/018-liquidity-strategy.md |
Updates buyback inflow references to 30%. |
adr/026-tokenomics.md |
Rewrites tokenomics around escrow-on-slash and no SafetyReserve. |
adr/031-content-blacklist-appeals-contract.md |
Updates analogy/reference from SafetyReserve to SlashAppeal. |
adr/036-served-bytes-voting-weight.md |
Updates slash-zero-out appeal recovery path. |
adr/appendix-l2-deployment.md |
Updates settlement overhead and buyback share docs. |
adr/appendix-observability.md |
Replaces SafetyReserve metrics with slash escrow/appeal metrics. |
adr/appendix-operator-key-rotation.md |
Updates compromised-key recourse guidance. |
adr/appendix-poc-production-seams.md |
Updates contract-client seam list. |
adr/architecture.md |
Updates architecture index for SafetyReserve retirement. |
adr/glossary.md |
Updates FeeRouter and SlashAppeal glossary entries. |
adr/_history/032-safety-reserve-appeals-contract.md |
Marks ADR 032 retired. |
adr/_history/033-safety-insurance-reserve.md |
Marks ADR 033 retired. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
…nSlash guards Code-review feedback from gemini-code-assist + Copilot on #708: - SlashAppeal.rejectAppeal: restrict to AppealStatus.Open only. A FastTracked appeal must be resolved by the Governor (grantAppeal/upholdAppeal), so the multisig can no longer overturn its own interim relief and burn the full bond — preserves the two-stage governance process and the 50/50 bond split on the fast-tracked-failure path. (matches ADR 028 "rejects at intake") - CapacityBond: add explicit `slashId >= slashCounter -> UnknownSlash` guards to finalizeUnappealedSlash / markAppealOpen / settleAppealUpheld / settleAppealGranted, matching getSlashRecord's clearer error reporting. - Tests: replace bare vm.expectRevert() with specific selectors in SlashAppeal.t.sol (access-control) and FeeRouter.t.sol (SharesDoNotSum / NonZeroShareNeedsDestination). ADR consistency (stale-reference cleanups the reviewers flagged): - 018: remaining 25% buyback/inflow refs -> 30% (liquidity-cap + risk sections). - glossary: BuybackBurner 25%->30%; Slashing entry -> escrow-on-slash 50/50; slashedAtEpoch cleared via settleAppealGranted (not clearSlashedAtEpoch). - 009: "four FeeRouter shares" -> three; drop "safety" from the 0%-floor prose. - 026 + 028: correct the credit-slash scope to match the contract — the full at-risk pool (originalGrant - claimed, incl. vested-but-unclaimed) is slashable (closes the delay-to-shield loophole); claimed credit is slashed via the stake path. (Pre-existing ADR/contract mismatch.) Verification: build --deny warnings (all <24KB), fmt, 257/257 tests, aderyn 0 high, slither no medium+, gas snapshot regenerated. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alpergundogdu
left a comment
There was a problem hiding this comment.
Max-effort review of the escrow-on-slash rewrite. Core mechanism is sound — escrow token-backing stays balanced, no double-settle (status guards are one-shot), CEI + nonReentrant throughout, splits round safely, and cleanupExpiredAppeal is a permissionless backstop so escrow can't lock forever. 7 findings inline.
Decisions folded into the comments below:
- Pause (#4/#5): pause should apply to the whole settlement path, and the appeal windows should be extended by the paused duration so a pause never silently consumes a deadline.
- #6 and #7 are must-fix in this PR, not deferred.
#1 is a blocker — it's a cheap, profitable griefing attack that nullifies the appeal protection this PR's ADR exists to provide.
…+ 6 more 7 findings from the max-effort escrow-on-slash review on #708. #1 (blocker) — appeal-slot griefing. `openSlashAppeal` was permissionless; the one-shot-per-slashId guard let anyone (notably the recorded challenger, who earns 50% of an upheld slash) front-run a junk appeal and permanently burn the operator's only recourse. Now operator-only: `msg.sender` must equal the operator recorded in the slash. New `CallerNotOperator` error + tests. #6 (must-fix) — clip the credit-slash leg. `_slashPendingCreditAtTier` now caps `slashed` at `atRisk` (symmetric with `_reduceStakeAtTier`'s C2 clip), so `escrowedTotal` can never book more than the tokens removed if a tier constant is ever set >100%. Invariant comment added. #7 (must-fix) — granted appeal restores credit vesting, not liquid TOKEN. `SlashRecord` gains `creditPortion` (set in `_mintSlashRecord`). On `settleAppealGranted` the credit portion is added back to `_pendingCredit.originalGrant` (grantedAt untouched → vest resumes) and only the stake portion is refunded liquid — exactly whole, no accelerated-credit windfall. New credit-restore test. #2 — conditional `slashedAtEpoch` clear. `settleAppealGranted` clears the per-operator stamp only when it belongs to the reversed slash; a later still-standing slash keeps its zero-out. Two-slash regression test. (Closes the deferral in #709.) #3 — `upholdAppeal` graceful degrade. Drops the `ChallengerPoolNotWired` revert; burns 100% of the bond when the pool is unset (matching `rejectAppeal`) so a misconfig can't block an uphold and let cleanup flip it to an operator-favorable grant. Pool-unset test. #4 — pause covers the whole settlement path. `whenNotPaused` added to the CapacityBond settle hooks and all SlashAppeal resolution functions. #5 — appeal windows extended by paused duration. Each contract tracks `pausedTotal` (override `_pause`/`_unpause`); filing/review/ratification deadline checks add the offset so a pause never silently consumes a window. Pause-spans-window test. ADR 028 updated for operator-only filing. Verification: build --deny warnings (both contracts <24,576), fmt, 262/262 tests, aderyn 0 high, slither no medium+, gas snapshot regenerated. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two comment-only corrections surfaced by PR review after the #708 rebase: - GovernanceLifecycle.t.sol: buyback share in the fixture is 3000 bps, not the 2500 left over from the old 4-bucket split. - DeployProtocolScript.t.sol: the base-deploy pipeline is 6 phases (the _assertNoBackDoors guard at phase 6 is covered in DeployProtocol.t.sol), not "phases 1-5". Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
* feat(contracts): production DeployProtocol script (closes #694) Add `script/DeployProtocol.s.sol` + abstract `BaseProtocolDeploy.s.sol` that deploys the v3 contract surface in ADR 016 § Deployment Order, wires cross-contract roles, and atomically hands off GOVERNANCE_ROLE + DEFAULT_ADMIN_ROLE from the deployer EOA to a fresh TimelockController. Post-deploy `_assertNoBackDoors` reverts the run if any step left the deployer holding a privileged role. The shared base is also consumed by `GovernanceLifecycleTest`, removing ~150 lines of duplicated deploy helpers; all 57 lifecycle tests pass unchanged. Design choices (confirmed up-front): - BuybackBurner is abstract; ship with bucket dormant (buybackBurner_=address(0), shares[1]=0). Governance activates later via setSharesAndDestinations once a concrete subclass lands. - ED25519_VERIFIER_ADDRESS is operator-supplied via env var (no production verifier in repo yet). 13 new tests across DeployProtocol.t.sol + DeployProtocolScript.t.sol: role-matrix invariants, 7 ZeroAddress fail-fast cases, manifest write/overwrite/contents, env-var defaults, run-guard against forge's default sender. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(contracts): mark defaults test view to satisfy --deny warnings solc W2018 (state mutability can be restricted to view) is fatal under FOUNDRY_PROFILE=ci --deny warnings. test_readConfig_appliesDefaultsForOptionalVars only calls the external-view wrapper and pure assertions, so solc flags it. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(contracts): Timelock-custody FeeRouter treasury per ADR 016 Address PR #700 review: - Deploy TimelockController before FeeRouter (new phase 1) and wire it as the treasury bucket destination, matching ADR 016 § Deployment Order step 7 (treasury is Timelock-custodied, disbursed only by governance proposal). Previously FeeRouter took an operator-supplied TREASURY_ADDRESS deployed before the timelock existed — so "treasury == the Timelock" was unreachable in a single run. Drop the TREASURY_ADDRESS env var and the treasury config field; the bucket is now always address(timelock). _deployGovernance splits into _deployTimelock (phase 1) + _deployGovernor (phase 3). Note: FeeRouter.treasury is a mutable GOVERNANCE_ROLE-gated setter, not immutable as the review stated, so a misconfig was always correctable via a 48h proposal — but Timelock-custody is the canonical ADR 016 model regardless. - gitignore deployments/3133769*.json so a failed/interrupted DeployProtocolScript test run can't leave a stray test manifest that gets accidentally committed. Real-chain manifests use other ids and remain committable with `git add -f`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(contracts): address DeployProtocol review findings Multi-agent review of PR #700 surfaced several gaps; all verified findings fixed: - Manifest writability is now checked in run() BEFORE vm.startBroadcast, not after. Previously a stale manifest with no FORCE_OVERWRITE_MANIFEST let the whole deploy + governance handoff broadcast on-chain, then reverted at the write — leaving deployed contracts with no recorded addresses. New _assertManifestWritable/_manifestPath helpers; _writeManifest keeps the guard so direct callers/tests still get it. - Grant GENESIS_GRANTOR_ROLE to the Timelock in phase 4 (ADR 016 § Post-Deploy Init step 7). The 30-day genesis window starts ticking at CapacityBond construction; without this, enabling credits needed a ~10-day proposal, burning a third of the window. - Drop FEE_ROUTER_EPOCH_LENGTH env var — it can only ever be 7 days (FeeRouter reverts EpochLengthMismatch otherwise), so it advertised false tunability and carried a silent uint256->uint64 truncation. Now a fixed uint64 constant; FEE_ROUTER_WINDOW_EPOCHS gets an explicit overflow guard. - Enforce a MIN_TIMELOCK_DELAY floor — TIMELOCK_DELAY=0 was silently accepted, constructing a zero-delay Timelock that defeats the governance-delay model. - Make _assertNoBackDoors symmetric: assert the Timelock HOLDS both roles on every target and self-administers, not just that the deployer is out. A handoff that revoked the deployer but skipped a Timelock grant would otherwise pass while leaving a contract ungoverned. New GovernanceNotHandedOff error; extract _governedTargets(d) as the single source of truth for the handoff loop and the guard. - Fix stale comments: "five-phase"->"six-phase", "§ Role Matrix"->"§ Access Control Matrix", "phases 1-5"->"phases 1-6", imprecise ADR step-7 custody citations, and the overstated "sorted alphabetically" manifest claim. Tests: add run() pre-broadcast manifest-guard test, GovernanceNotHandedOff negative test, genesis-grantor wiring test, and manifest deployer/deployBlock assertions. 297 pass; forge fmt, aderyn (0 high), slither (clean). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(contracts): fix stale review comments in deploy tests Two comment-only corrections surfaced by PR review after the #708 rebase: - GovernanceLifecycle.t.sol: buyback share in the fixture is 3000 bps, not the 2500 left over from the old 4-bucket split. - DeployProtocolScript.t.sol: the base-deploy pipeline is 6 phases (the _assertNoBackDoors guard at phase 6 is covered in DeployProtocol.t.sol), not "phases 1-5". Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Removes the
SafetyReservecontract and its standing USDC insurance pool. Its only load-bearing job — slash restitution — is replaced by escrow-on-slash inCapacityBond(the slashed TOKEN is escrowed and refunded to the operator on a successful appeal, so no pool is needed), and the slash-appeal state machine moves to a new standaloneSlashAppealcontract. The freed 5% FeeRouter bucket folds into buyback-and-burn (25%→30%).This is the Option C + A decision: route the 5% safety bucket to burn, and adopt escrow-on-slash with delayed (finality-time) distribution.
Contract changes
SafetyReserve.sol/ISafetyReserve.sol(+ test + mock) — 645 LOC of contract removed.FeeRouter→ three buckets[60/30/10](operator / buyback / treasury). Dropped the safety bucket,safetyReserve/setSafetyReserve,ShareDestinations.safetyReserve;uint256[4]→uint256[3].CapacityBond→ escrow-on-slash:slash()escrows the slashed TOKEN into a per-slashIdrecord (escrowedTotal) — nothing is transferred or burned at slash time.finalizeUnappealedSlash(slashId)— permissionless; after the 30-day filing window distributes 50% challenger / 50% burn.SLASH_APPEAL_ROLEsettle hooksmarkAppealOpen/settleAppealUpheld/settleAppealGranted(granted refunds the operator's escrowed TOKEN + internal_clearSlashedAtEpoch).recordSlashInflowtry/catch, and theSafetyReserveNotWiredguard.SlashAppeal.sol(+ISlashAppeal.sol,ICapacityBondSlashEscrow.sol): the slimmed appeal state machine (open/fastTrack/reject/grant/uphold/cleanup), TOKEN appeal bonds only — no USDC, pool, swap, or pending-claim queue.grant/upholdreplace the confusingratify/reversenaming.CapacityBonddrops to 23,167 B (was 23,912) despite gaining escrow logic — the separate-contract choice keeps it comfortably under the 24 KB EIP-170 limit.Verification
FOUNDRY_PROFILE=ci forge build --sizes --deny warnings— exit 0, all contracts < 24,576 Bforge fmt --check— cleanforge test— 257/257 pass (13 newSlashAppealflow tests + new CapacityBond escrow-lifecycle tests)aderyn— 0 high;slither— no medium+ (only the pre-existing lowblock-timestampinformational)ADR changes (single source of truth)
adr/_history/with superseded-by headers.SlashAppealcontract surface).decdn/CLAUDE.mdADR note.Accepted scope reduction
Downtime / bad-data user recourse is no longer a protocol contract surface. It is handled, if ever needed, via the existing DAO Treasury through normal governance (no emergency-multisig fast-track); reputation (ADR 008) is the standing deterrent. ADR 026 documents this as an accepted, testnet-appropriate reduction that can be revisited before mainnet carries real customer SLAs.
Follow-up (separate repo, not in this PR)
finance/notebooks/_shared/params.pystill carriesfee_safety=0.05/ 25% burn and should be updated to the 60/30/10 split per the workspace single-source-of-truth rule, then affected notebooks re-run.🤖 Generated with Claude Code