Repository navigation
feat(contracts): add PaymentChannel USDC settlement gateway (#452) - #716
Merged
Merged
Conversation
ADR 003 PaymentChannel: USDC-denominated off-chain payment channels with EIP-712 vouchers (SignatureChecker for EOA + ERC-1271), 48h dispute window, operator early-withdraw-while-open, and same-tx settlement routing through FeeRouter.routeSettlement. openChannel gates on CapacityBond.isActive; the forced-inclusion deadline extension sits behind an overridable L2 seam. Adds focused consumer interfaces IFeeRouterSettlement + ICapacityBondActivity (mirroring the existing ICapacityBondReporter/Ejector split). First of four stacked PRs closing the remaining #452 contract surface. Co-Authored-By: Claude <[email protected]>
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
Gas snapshotGas changes vs baseRun: 26668559609 |
Contracts coverageLine coverage: 85.40% (1369/1603 lines) |
There was a problem hiding this comment.
Pull request overview
Adds the ADR 003 PaymentChannel Solidity surface for USDC-denominated off-chain settlement, routing provider payouts through FeeRouter and gating channel opens on active CapacityBond operators.
Changes:
- Introduces
PaymentChannelwith EIP-712 voucher verification, withdraw/close/dispute/settle/reclaim lifecycle, pause/governance controls, and FeeRouter settlement routing. - Adds focused consumer interfaces for
FeeRouter.routeSettlementandCapacityBond.isActive. - Adds Foundry coverage for channel lifecycle, router delta accounting, governance setters, forced-inclusion extension seam, and settlement conservation fuzzing.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
contracts/src/PaymentChannel.sol |
Implements the PaymentChannel contract and lifecycle logic. |
contracts/src/interfaces/IFeeRouterSettlement.sol |
Adds the narrow FeeRouter interface consumed by PaymentChannel. |
contracts/src/interfaces/ICapacityBondActivity.sol |
Adds the narrow CapacityBond activity interface consumed by PaymentChannel. |
contracts/test/PaymentChannel.t.sol |
Adds unit and fuzz tests for PaymentChannel behavior. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
This was referenced May 29, 2026
alpergundogdu
commented
May 29, 2026
alpergundogdu
commented
May 29, 2026
…tChannel Address review on #716: - closeChannel now goes through _requireOpenAndUnexpired (like topUp/ withdraw) so it reverts ChannelExpired after expiresAt. Previously a provider could close + settle an expired channel and route an un-withdrawn claim, bypassing the reclaimExpired forfeiture path that refunds deposit - withdrawnAmount to the client (ADR 003 close-before-expiry obligation). - setFeeRouter re-applies the constructor's code-size invariant (FeeRouterHasNoCode), so governance can't point settlement at an EOA where _route advances channel state while routeSettlement no-ops. Adds test_close_revertsAfterExpiry and test_setFeeRouter_revertsOnEoaRouter. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… tests From the multi-agent PR review on #716: Contract (PaymentChannel.sol): - Reject byte-only watermark advances at closeChannel/disputeChannel (new _requireBytesTrackPayment + ByteAdvanceWithoutPayment error). settleChannel forwards bytes only alongside a positive amount delta, so a voucher advancing claimedBytes without claimedAmount would otherwise silently drop served-byte accounting (ADR 036 vote weight). - status uint8 constants -> enum Status { Open, Closing, Closed }, matching CapacityBond/SlashAppeal. - Pack the Channel struct: uint64 timestamps + grouped status/extended share one slot (cuts ~27k gas on withdraw and across the lifecycle). - Extract _advanceClaimWatermark(strictNonce) — single enforcement site for the monotonicity invariant previously hand-copied across withdraw/close/ dispute (drift risk). Tests (PaymentChannel.t.sol): +20 (34 -> 54). Cover zero-remainder settle, close-at-watermark nonce, deposit boundary + over-deposit reverts, dispute amount/bytes regression, withdraw zero-delta/bytes-regression, byte-only advance rejection, ERC-1271 voucher path, cross-channel replay, constructor reverts, paused-exits-callable, and forced-inclusion negative branches. ADR 003: setFeeRouter Validation now documents the code-size check; corrected the stale 3-arg constructor description to the real 8-arg surface; added settlement-path invariant 5 (byte-only advance rejection). Full suite: 355 pass, 0 fail. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thiras
added a commit
that referenced
this pull request
Jun 1, 2026
…rename (#327) (#743) * feat(node): on-chain PaymentChannel seller settlement + CapacityBond rename (#327) Implements the on-chain PaymentChannel client (seller/provider settlement path) for issue #327. The CapacityBond registry read-path was already done as ChainStakerSet; PaymentChannel.sol landed in #716, so this wires the Rust side that drives close/withdraw/settle. - incentive: PaymentChannel sol! bindings (reads + writes + lifecycle events), validated field-for-field against the compiled ABI. - voucher: fix EIP-712 domain name "StablePaymentChannel" -> "PaymentChannel" to match the contract's EIP712("PaymentChannel","1") ctor — without this every closeChannel/withdraw reverts with InvalidVoucherSignature despite off-chain verification passing. Pinned with a regression test. - store: schema v2 persists the latest voucher signature (additive trailing postcard segment; v1 records hydrate with an empty signature and are unredeemable until re-recorded). Adds a `get` point-lookup to the trait. - node: PaymentChannelService watches ChannelOpened (provider==self) -> persist so the voucher handler accepts it, ChannelSettled -> forget, ChannelCloseInitiated -> observe-only (dispute monitor deferred, #324). Redeems via threshold `withdraw` (redeem hint from the voucher-accept path) and best-effort `closeChannel` on graceful shutdown, with on-chain v-byte normalization (0/1 -> 27/28). - runtime: wallet-filled provider from the eth signer, usdc() startup self-check, redeem_threshold_micro_usdc config (default 1 USDC), shutdown close hook. BREAKING CHANGE: renames StakingRegistry -> CapacityBond. The config TOML key `blockchain.staking_registry_address` is now `blockchain.capacity_bond_address`, the CLI flag `--staking-registry-address` is now `--capacity-bond-address`, and the env var DECDN_STAKING_REGISTRY_ADDRESS is now DECDN_CAPACITY_BOND_ADDRESS. Out of scope (deferred): buyer-side openChannel for node-to-node pulls, the in-process dispute monitor (#324), and the live anvil e2e (no existing harness). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(node): address PR review — RPC-cache, parallel shutdown close, topUp + expiry handling (#327) External review (gemini-code-assist, Copilot) on PR #743: - redeemer: cache last-known on-chain `withdrawnAmount` per channel and skip the `getChannel` RPC when the accrued claim is provably below threshold — avoids per-voucher RPC spam under active streaming. The cache is always `<=` the true value (only our own `withdraw` advances it), so a redemption is never wrongly skipped. - shutdown close: submit `closeChannel` sequentially (nonce order) but await receipts concurrently via `join_all` so more channels close within the bounded shutdown deadline. `submit_close` refactored into a free `send_close` returning a receipt future (`use<P>` precise capture). - topUp (Copilot): subscribe to `ChannelToppedUp` and raise the tracked `ChannelState.deposit` so `apply_voucher` stops rejecting otherwise-valid vouchers a client signs after topping up. - expiry (Copilot): persist the channel's on-chain `expiresAt` (schema-v2 second trailing segment), add a periodic pre-expiry close sweep so the provider redeems before `reclaimExpired` can refund the client, and gate the voucher handler to refuse delivery once a channel is expired (defense in depth). Closing earns the claim; the sweep then retires (forgets) the channel so the node stops serving it. Verification: clippy --workspace --all-targets -D warnings, fmt, 1264 tests, rustdoc -D warnings — all green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(node): address comprehensive PR review — reverted-tx guard, validation, dead-field + doc fixes, tests (#327) Multi-agent review of PR #743 (code/tests/errors/types/comments): Critical: - try_redeem / send_close now check `receipt.status()`. `get_receipt()` resolves Ok even for a reverted tx; previously a reverted `withdraw` poisoned the withdrawn-amount cache (channel silently never redeemed again until restart) and a reverted `closeChannel` made the expiry sweep forget an un-redeemed channel right before reclaimExpired. Both now leave state intact and retry. Important: - reject `blockchain.redeem_threshold_micro_usdc = 0` at config resolution (0 withdraws on every voucher and reverts on zero-delta) — mirrors the rpc_watchdog floor pattern. Test added. - correct the `as_bytes()` v-byte docs: alloy already emits 27/28, so `normalize_voucher_signature` is a defensive no-op today (not the active 0/1->27/28 bridge the doc claimed). - fix module docs: add `ChannelToppedUp` to the watcher's handled-events list; correct the "registered at startup" claim (startup is store hydration in ClientHandler::new, not register_open_channel); document the opened-during-downtime backfill gap. - drop dead `redeem_threshold` / `self_address` fields from PaymentChannelService (read only in Debug; the live values are the copies moved into the tasks). Tests (pure-logic gaps the review flagged): - extract `is_expired` / `within_close_window` predicates (shared by the sweep and the handler expiry gate) + boundary table tests. - register_open_channel idempotency preserves the voucher watermark (the #527 replay-window guard) — was untested. - update_channel_deposit raises / no-ops on non-increasing / no-ops on untracked. - normalize empty signature. Not changed (with rationale): kept the schema-v2 trailing-segment encoding — the suggested "struct fields + version bump" breaks reading existing on-disk v1 records (a v2 reader would read past end-of-input). Deferred to follow-ups: observability metrics, an independent redeemer tick, shutdown-quiesce of the redeemer, ChannelState type-strengthening, and the downtime log-backfill. Verification: clippy --workspace --all-targets -D warnings, fmt, 1270 tests, rustdoc -D warnings — all green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(node): auto-settle closed PaymentChannels after the dispute window (#327) closeChannel only opens the dispute window; the provider's un-withdrawn remainder (claimedAmount - withdrawnAmount) is routed only when settleChannel runs after disputeDeadline. The node never called settleChannel and the expiry sweep forgot the channel, so when the client had no incentive to settle (clientRefund == 0) the remainder stranded (PR #743 review by @alpergundogdu). - Add durable PendingSettleStore (incentive trait + MemoryPendingSettleStore; redb-backed via a second `pending_settle_v1` table on the existing channel store, sharing one open file + fsync discipline). - Record a pending-settle entry after every close (shutdown + pre-expiry sweep, both via send_close), keyed by channel with the on-chain disputeDeadline gate. - Add a settle sweep (settle_pass/try_settle) that calls settleChannel once the window elapses, gated on the stored deadline to avoid guaranteed-revert gas; re-stamps the deadline if a dispute extended it, and drops the entry once a ChannelSettled event (from any party) confirms finalization. - Failed-to-record paths log at error! with the manual settleChannel remedy. No contract change (settleChannel already exists). Tests cover the store round-trip/overwrite/forget/persistence, table independence, and the gate boundary. clippy -D warnings, fmt, docs, and nextest all clean. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
First of 4 stacked PRs closing the remaining #452 contract surface (PaymentChannel → SlashJudge → OriginAssignment → DeployProtocol+E2E). Implements the ADR 003
PaymentChannel:channelId = keccak256(client, provider, channelNonce).SignatureChecker(EOA + ERC-1271/4337).openChannel/topUp/withdraw(early withdraw-while-open) /closeChannel(incl. zero-voucher close) /disputeChannel/settleChannel/reclaimExpired.FeeRouter.routeSettlement; withdrawal-watermark invariants guarantee each byte/USDC unit is counted exactly once.openChannelgates onCapacityBond.isActive(provider).IFeeRouterSettlement+ICapacityBondActivity(mirrors existingICapacityBondReporter/Ejectorsplit).Reconciliation decisions (please confirm — ADRs disagree)
ADR 016 (canonical surface, newer) conflicts with ADR 003 in three places; I resolved each toward the canonical/consistent option and flag them here:
AccessControl, notOwnable. ADR 016 §Contract Inventory + §OZ-usage table sayOwnable, but ADR 016 §Access-Control Matrix listsDEFAULT_ADMIN_ROLEon all contracts +EMERGENCY_ROLEpause, ADR 003setFeeRoutersaysGOVERNANCE_ROLE, and the existingBaseProtocolDeployhandoff is uniformgrantRole/revokeRole. ChoseAccessControlso the deploy handoff (PR4) stays uniform. Suggest updating ADR 016's inventory/OZ-table toAccessControl.isActivegate. Followed ADR 016 §step-8 constructor(usdc, capacityBond, feeRouter, disputeWindow, maxChannelDuration, rateBounds, admin)and the call-tableopenChannel → isActive(provider), over ADR 003's 3-arg constructor.minDeposit(1 USDC) +maxVoucherIntervalMb(1) default internally.settleChannelalways routes. (Node-to-node is Rust-integration scope, Implement on-chain CapacityBond and PaymentChannel contract integration #327.)Also: the forced-inclusion deadline extension (ADR 003 §L2 sequencer censorship) is implemented but its detection sits behind an overridable internal seam (
_arrivedViaForcedInclusion, default off) since "exact detection is finalized at L2 selection." Theextendedflag, reset-on-close, and extension arithmetic are fully implemented + tested via a harness.Verification
forge fmt --checkclean;FOUNDRY_PROFILE=ci forge build --deny warningsclean; pre-commit hooks pass.forge test— 32 new tests pass (incl. 2 fuzz suites @256 runs); full suite 333 pass, 0 fail (no regressions).reentrancy-no-eth/reentrancy-state-changedirectives the repo already uses for the external-call-before-state-write pattern (seeSlashAppeal).Test plan
🤖 Generated with Claude Code