Skip to content

perf(payments): cut per-lane redemption gas 79% to bound dust-lane settlement - #1701

Merged
alpergundogdu merged 4 commits into
mainfrom
claude/redeem-many-batch-transfer-e0e9d8
Aug 15, 2026
Merged

alpergundogdu merged 4 commits into
mainfrom
claude/redeem-many-batch-transfer-e0e9d8

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

A lane is free to open while a pool is not. An adversary funds one pool — which costs real gas, so it is sybil-resistant — then spreads dust across many free lanes, sizing each just under whatever balance the node finds worth redeeming. The node either redeems at a loss or serves for free.

A genuine publisher with millions of client lanes has exactly the same shape, so no per-lane minimum can separate the two: any floor taxes the honest publisher just as hard. The only lever that doesn't discriminate is the per-lane cost of a batch, which sets the floor on the smallest balance a node can afford to collect. This PR drives it down.

Tally

Marginal gas per extra lane in a batch: 106,079 → 22,517 (−78.8%). The minimum economically-redeemable lane balance drops ~4.7×.

optimisation what it removes marginal gas/lane
baseline — 106,079
Settle once per call N−1 router round-trips: forceApprove pair, transferFrom, 3 payout legs, Settled log, reentrancy + role checks 34,308
Pack Authorization/Lane/Pool to uint64 3 cold slots + 2 SSTOREs per lane; 2 cold slots per pool; 20k per first-time signer 27,231
Nest redeemMany by pool per-lane poolId in calldata; per-lane status read and totalRedeemed write 26,426
Compact voucher signature (EIP-2098) 128 calldata bytes + a cold EXTCODESIZE per lane 23,696
One PoolRedeemed per pool group per-lane log base + 4 topics, and the never-read paid word 22,517

Measured end to end, one transaction per measurement so the access list starts cold:

shape before after calldata after
1 lane 182,191 173,192 420 B
8 lanes, one pool 924,747 330,572 1,540 B
32 lanes, one pool ~3.47M¹ 871,349 5,380 B
8 pools × 1 lane 986,347 414,672 2,884 B
cold: register + redeem 8 new signers — 645,106 3,844 B

¹ extrapolated from the measured 106,079 baseline marginal; every other cell is measured.

Calldata matters more than the gas column suggests — gasleft() does not see it, and on Arbitrum the L1 data fee is the larger term. A lane went 352 B → 160 B.

What changed

Settle once per call. _applyVoucher only advances state and returns what it drew; redeemMany sums and makes a single _route(msg.sender, totalBytes, totalPaid). Sound because every voucher in a call is redeemed for the caller. This also strengthens checks-effects-interactions: every lane, spent and totalRedeemed advance now lands before the one external call.

Pack storage to uint64. Authorization 3 slots → 1, Lane 2 → 1, Pool 4 → 2 (dropping the write-only openedAt and the token field that duplicated the immutable usdc). uint64 is ~$18.4T at USDC's six decimals — ~400× the token's entire supply — and 18.4 EB for a byte count. Every value is bounded by construction: spent ≤ cap, totalRedeemed ≤ deposit, and both watermarks only advance toward a presented uint64 cumulative. The EIP-712 typehashes still declare uint256, which is the same 32-byte word, so no client signing code changes.

Nest by pool. redeemMany(PoolBatch[]), each group {poolId, capabilities[], vouchers[]}. The pool is named once, its status gate read once, and totalRedeemed advanced in one write. The group's remaining is read once and drawn down in a local, so each voucher is bounded by what earlier vouchers in the same group already took.

Drop provider from the voucher. It is always msg.sender, which the contract substitutes when rebuilding the EIP-712 hash — so a voucher signed for another node now surfaces as InvalidVoucherSignature rather than a separate NotProvider.

Compact voucher signatures (EIP-2098). bytes32 r, vs makes LaneVoucher a static struct: no element offset, no length word, no padding. Recovery is ECDSA.tryRecover(digest, r, vs), which also skips the cold EXTCODESIZE an ERC-1271 check does. High-s signatures are refused — the same malleability bound the contract enforced anyway.

One PoolRedeemed per pool group carrying LaneSettled[] {signer, newPaidCumulative, bytesPaid}. The never-read paid delta is gone; the node writes the cumulative, which is what makes the stream idempotent under replay and gaps.

Delete redeem. redeemMany is the sole entry point; a single lane is a one-pool batch of one. NothingToRedeem and NotProvider go with it.

Breaking changes

Pre-launch, so no compatibility shims — every side moves in this PR.

  • ABI: redeem removed; redeemMany reshaped; openPool/topUp take uint64; getPool/getAuthorization/getWatermark return packed structs; PoolRedeemed reshaped.
  • A voucher signer must be an EOA. ERC-1271 smart accounts can no longer sign vouchers. A pool owner is unaffected — the capability path keeps SignatureChecker, so a Safe can own a pool and delegate to EOA signers. This matches the direction ADR 024 already took on remote/Safe voucher signing.
  • Per-lane byte attribution now lives only in PoolRedeemed.lanes[].bytesPaid, since FeeRouter.Settled is a per-batch aggregate. Nothing normative reads it — ADR 036 sources vote weight from FeeRouter.bytesPerEpoch.
  • Off-chain wire is untouched. The node compacts its stored 65-byte signature at redemption time; the protocol messages and the client's signing path are unchanged.

Evaluated and rejected

  • ReentrancyGuardTransient — 4.7k gross per call, but slither 0.11.6 cannot generate IR for a contract inheriting it: 3 false-positive high-severity uninitialized-state findings and degraded analysis of the whole contract. Not worth ~2k net on the contract holding all the money.
  • Inlining the redemption helpers — measurably slower (+842 gas/lane) under the repo's legacy codegen. The call is a jump; the flattened frame is stack pressure.
  • A per-lane minimum redeemable cumulative — cannot distinguish a dust attacker from a genuine high-lane-count publisher.

Not closed by this

Gas reduction narrows the dust window; it does not close it. At ~22.5k/lane a 30M-gas block still holds only ~1,300 lanes, so an attacker can open lanes faster than a node sweeps them. Worth its own issue.

Also spotted: the settlement watcher filters on topic0 only and re-checks provider client-side after decoding, even though provider is an indexed topic. This is deliberate, not an oversight, and it is not the easy win it looks like: one eth_getLogs filter ANDs across topic positions, and the four watched events disagree on what topic2 is — PoolRedeemed puts provider there, PoolCloseInitiated/PoolReclaimed put owner, and PoolToppedUp has no topic2 at all. Pinning topic2 would silently drop three of the four. Making it load-bearing needs the watcher split in two, with a second CheckpointKey, cursor and resync path — a change to durable checkpoint machinery that belongs on its own, not appended here.

Verification

814/814 Foundry · 2761/2761 Rust · clippy 0 findings · anvil-e2e compiles · forge fmt + cargo fmt clean · gas snapshot regenerated · aderyn highs unchanged (6, all pre-existing, none in PaymentPool) · slither 52 vs the 50 baseline, the two extras being Low timestamp and informational assembly, both under CI's medium gate.

New tests worth noting:

  • test_redeemMany_secondVoucherOnAPoolSeesTheFirstsDraw pins the per-group solvency threading. Mutation-tested: without the - poolPaid term the batch tries to move 1.6e9 against a 1e9 pool and only the ERC-20 balance check stops it.
  • test_redeemMany_spansPoolsAndStillSettlesOnce, test_redeemMany_aClosedPoolRevertsEveryGroup, test_redeemMany_settlesOnceForTheWholeBatch, test_redeemMany_allEmptyBatchNeverCallsRouter.
  • test_redeem_rejectsErc1271VoucherSigner pins the EOA-only rule with its reasoning.
  • Both PoolRedeemed ABI pin tests rewritten for the new topic/data split.

ADR 003 gains § Voucher signatures are compact, and their signers are EOAs, and its redemption, event and struct sections are updated to present-tense canon. ADR 016's PaymentPool rows follow.

🤖 Generated with Claude Code

…ttlement

A lane is free to open while a pool is not, so an adversary funds one pool and
spreads dust across many lanes. A genuine publisher with millions of client
lanes has the same shape, so no per-lane minimum can separate them — only a
cheaper lane helps both. The per-lane cost of a batch is what sets the floor on
the balance a node can afford to collect, so this drives it down.

Marginal gas per extra lane in a batch: 106,079 -> 22,517.

- Settle once per call, not once per voucher. `_applyVoucher` only advances
  state and returns what it drew; `redeemMany` sums and makes a single
  `_route(msg.sender, totalBytes, totalPaid)`. Safe because every voucher is
  redeemed for the caller.
- Pack storage to `uint64`. `Authorization` 3 slots -> 1, `Lane` 2 -> 1, `Pool`
  4 -> 2 (dropping the write-only `openedAt` and the `token` that duplicated the
  immutable `usdc`). uint64 is ~$18.4T at USDC's six decimals and 18.4 EB for a
  byte count; every value is bounded by construction. The EIP-712 typehashes
  still declare `uint256`, which is the same 32-byte word, so no client signing
  changes.
- Nest `redeemMany` by pool. `redeemMany(PoolBatch[])` names each pool once for
  its group, so the status gate is read once and `totalRedeemed` advances in one
  write. The group's `remaining` is read once and drawn down in a local, so a
  batch cannot overdraw the pool.
- Drop `provider` from the voucher. It is always `msg.sender`, which the
  contract substitutes when rebuilding the EIP-712 hash, so a voucher signed for
  another node now fails as `InvalidVoucherSignature`.
- Compact voucher signatures (EIP-2098). `bytes32 r, vs` makes `LaneVoucher` a
  static struct: no element offset, no length word, no padding, so a lane costs
  160 calldata bytes instead of 288, and recovery skips a cold EXTCODESIZE. A
  voucher signer must now be an EOA; a pool owner may still be a Safe, since the
  capability path keeps `SignatureChecker`.
- Emit one `PoolRedeemed` per pool group carrying `LaneSettled[]`, instead of
  one per lane. Drops the never-read `paid` field and pays the log base and its
  topics once per group.
- Delete `redeem`. `redeemMany` is the sole entry point; a single lane is a
  one-pool batch of one. `NothingToRedeem` and `NotProvider` go with it.

Rust: `to_pool_u64` narrows at the contract boundary only, leaving the ERC-20
and TOKEN paths on `U256`; the sweep buckets lanes by pool; the settlement
watcher walks the event's `lanes` array. The self-owned capability cap moves
from `U256::MAX` to `u64::MAX`, which the narrower field can carry and the
EIP-712 hash can reconstruct.

Evaluated and rejected: `ReentrancyGuardTransient` (4.7k gross, but slither
0.11.6 cannot generate IR for a contract inheriting it, degrading analysis of
the whole contract); inlining the redemption helpers (measurably slower under
the repo's legacy codegen).

Co-Authored-By: Claude Opus 5 <[email protected]>
Copilot AI lite review requested due to automatic review settings August 15, 2026 11:57
@github-actions

github-actions Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 89.66% (2540/2833 lines)
▲ +0.04pp vs base (89.61% → 89.66%)
Run: 31885490582

@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

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 optimizes the PaymentPool redemption path to drastically reduce per-lane gas and calldata costs, specifically to make dust-lane settlement economically viable for nodes while preserving the same cumulative-voucher payment model across the Rust node/client stack and Solidity contracts.

Changes:

  • Reworks PaymentPool redemption to a single entry point redeemMany(PoolBatch[]) that groups lanes by pool, settles once per call via FeeRouter, and emits one PoolRedeemed per pool group carrying per-lane outcomes.
  • Packs on-chain counters/struct fields to uint64 and updates Rust bindings + call sites (node settlement, client pool open/top-up, e2e tests) to narrow values at the contract boundary.
  • Switches voucher signatures to EIP-2098 (r, vs) in calldata (EOA-only voucher signers) and updates node-side signature handling plus contract-side verification.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
crates/node/src/payment_settlement.rs Updates settlement watcher + redemption planner/sweeper for new ABI (pool-grouped batches, EIP-2098 signatures, uint64 fields).
crates/incentive/src/payment_pool.rs Updates Alloy sol! bindings for packed structs/new redeemMany ABI and adds to_pool_u64 helper.
crates/e2e/tests/g_node_07_rotate_key.rs Adapts assertions to uint64 lane fields.
crates/e2e/tests/g_gov_02_rate_bounds.rs Adapts watermark helpers/assertions to uint64 and updates implied-rate computation.
crates/e2e/tests/cli_fetch_delegated.rs Updates delegated capability + settlement log checks for new packed structs and PoolRedeemed lanes array.
crates/e2e/tests/anvil_pool_redeem.rs Updates pool redemption E2E test expectations for uint64 caps and new behavior (skip-empty vs revert).
crates/e2e/src/bindings.rs Updates comment/docs for removed redeem and retained redeemMany.
crates/client-pull/src/buyer_pool.rs Narrows open/top-up amounts to uint64 and updates “self capability cap” to a uint64-representable EIP-712 word.
contracts/src/PaymentPool.sol Implements the optimized redemption design (pool batches, single settlement, packed structs, EIP-2098 voucher sigs, new events, removes redeem).
contracts/test/PaymentPool.t.sol Updates and expands Foundry coverage for new ABI/behavior (pool grouping, settle-once, EOA-only voucher signers, skip-empty semantics, new events).
contracts/test/InterfaceFreeze.t.sol Updates ABI freeze assertions for openPool(uint64), topUp(uint64), and new redeemMany signature.
contracts/test/E2EProtocol.t.sol Updates protocol E2E test to call new redeemMany and validate new PoolRedeemed format.
contracts/.gas-snapshot Refreshes gas snapshot reflecting the new redemption implementation.
adr/016-contract-interactions.md Updates contract interaction documentation to match settle-once batch redemption.
adr/003-payments.md Updates the payment model ADR to the new redemption entry point, packed widths, EIP-2098 vouchers, and event semantics.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/node/src/payment_settlement.rs Resolved
alpergundogdu and others added 2 commits August 15, 2026 13:15
…ttlement

`getPool` decoded into a binding still carrying the pre-packing seven-field
`Pool` (`openedAt`, `token`, `uint256` amounts). The `sol!` block is a
hand-written restatement of the ABI, not something derived from the Solidity
source, so the drift compiled cleanly and failed only against a real chain: the
node read a garbage owner, could not verify a presented capability, never
registered the lane, and refused every request as an unknown lane.

Pin the layouts so this cannot recur silently. `read_surface_struct_layouts_
match_contract` and `redeem_call_struct_layouts_match_contract` assert the field
list of every struct the read and calldata surfaces decode into — the existing
event pins covered only topic/data placement, which is why this got through.

Also fixes the consumers the corrected binding surfaced: `Pool.token` is gone
(the token is the contract's immutable `usdc()`, which the CLI now reads on the
top-up and delegate paths, matching the open path), `pool_view` widens the
packed deposits, and the `anvil-e2e`-gated tests compare against `uint64`.

The node's own gated tests (`crates/node/tests/anvil_settlement_e2e.rs`) sit
outside `cargo test -p decdn-e2e --features anvil-e2e`; only
`cargo clippy --workspace --all-targets --all-features` reaches them, which is
what CI runs and what caught this. That test also issued a self-capability at
`U256::MAX`, which the narrowed field can no longer carry — it now uses the
exported `SELF_CAPABILITY_CAP`, so the production path and the test share one
definition.

Co-Authored-By: Claude Opus 5 <[email protected]>
Compaction checked only that the top bit of `s` was free for the recovery bit.
That is necessary but not sufficient: `secp256k1n / 2` sits below `2^255`, so
roughly `2^128` values of `s` carry a clear top bit and are still high-`s`.
Such a signature compacted cleanly and then reverted in the contract's
`ECDSA.tryRecover` — reverting the whole `redeemMany`, so one hostile lane would
sink every honest lane batched with it. That is the same griefing shape this
batch path exists to bound, arriving through the signature instead of the
balance.

Use the crate's existing `sig_canon::is_high_s` rather than a hand-rolled bound,
so the redeem path and the voucher-accept path share one definition of
canonical; the helper is now `pub` for that. Parsing through
`Signature::from_raw` also replaces the manual `r‖s‖v` splitting.

`compaction_rejects_high_s_whose_top_bit_is_clear` pins the band directly, at
`n / 2 + 1` — the smallest high-`s` value, whose top bit is 0.

Reported by Copilot review on #1701.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions

github-actions Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.63% (was 80.62%, ▲ +0.01%) — 58782/72904 lines

File Coverage Lines Δ
crates/cli/src/commands/fetch.rs 30.88% 323/1046 ▼ 0.18%
crates/cli/src/commands/pool.rs 57.17% 303/530 ▲ +0.11%
crates/client-pull/src/buyer_pool.rs 53.12% 153/288 ▼ 0.56%
crates/incentive/src/payment_pool.rs 98.70% 76/77 ▼ 1.30%
crates/incentive/src/sig_canon.rs 100.00% 37/37 ● 0.00%
crates/node/src/payment_settlement.rs 25.65% 188/733 ▲ +1.96%
crates/node/src/pool_view.rs 0.00% 0/30 ● 0.00%
History
Commit Total Δ vs base
c7fb5f8 80.62% ● 0.00%
fabfdcb (HEAD) 80.63% ▲ +0.01%

`to_pool_u64` is the single point every USDC amount crosses on its way into the
contract, and it had no test — the coverage report on #1701 surfaced it as the
one genuinely uncovered line in the new code.

Pin both sides of the ceiling: `u64::MAX` is a legal deposit (~$18.4 trillion at
six decimals) and must pass, one base unit more is not expressible on-chain and
must be refused rather than truncated. A silent wrap here would understate a
pool's deposit.

Co-Authored-By: Claude Opus 5 <[email protected]>
@alpergundogdu
alpergundogdu merged commit 1ec9cf2 into main Aug 15, 2026
26 checks passed
@alpergundogdu
alpergundogdu deleted the claude/redeem-many-batch-transfer-e0e9d8 branch August 17, 2026 17:47
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