feat(core): DelayedFlowRouter — amount-sensitive rate-limit + timelock ISM#8671
Draft
feat(core): DelayedFlowRouter — amount-sensitive rate-limit + timelock ISM#8671
Conversation
Add `DelayedFlowRouter`, a hook + ISM that pairs with a warp route and slows cross-chain withdrawals proportionally when net flow exceeds a configurable fraction of the paired pool. Capacity is read live from `warpRouter.balance` / `balanceOf` / `totalSupply`; deposits credit the bucket 1:1 so balanced two-way flow preserves instant UX for rebalancers. Compose with `PausableIsm` via `StaticAggregationIsm` (pausable first) to let watchers kill delivery during the delay window. Refactor `TimelockRouter` for extension: `postDispatch` and `_handle` are now overridable end-to-end via leaf helpers `_TimelockRouter_dispatchPreverify` and `_TimelockRouter_commitReadyAt`. Make `RateLimited.maxCapacity()` virtual so subclasses may back it dynamically (with refill rate derived automatically), and add `_credit` / `_consume` primitives. Token-bucket math uses `Math.mulDiv` for precision.
Rename `nextDispatchNonce` → `lastCreditedNonce` with strict `>` check — semantics are now "the highest Mailbox nonce we've credited." Add fuzz tests for wait invariants (zero iff amount ≤ level, clamped at maxDelay) and round-trip net-flow (deposit after withdrawal returns the bucket to its prior level, modulo cap clamping). Add a regression test for the layered-defense behavior: a message with a fresh nonce but no matching Mailbox dispatch is rejected by `_isLatestDispatched`.
…ario Add `testFuzz_sequence_invariants` exercising 8 alternating withdrawal/deposit ops with bucket bounds and per-message wait clamp checks. Add `test_rebalancing_restoresInstantUX` showing that a rebalancer-deposit after a drain restores instant UX for the next same-sized withdrawal. Add `test_postDispatch_revertsIfNotLatestDispatched` to cover the layered-defense path where a fresh nonce doesn't bypass `_isLatestDispatched`. Extract `_simulateWithdrawal` / `_deposit` helpers and reuse them across tests.
`calculateCurrentLevel` no longer reverts on zero capacity — it returns 0 so dynamic-capacity subclasses can use it as a pass-through. `testRateLimited_revertsIfMaxNotSet` and `testCalculateCurrentLevel_revertsWhenCapacityIsZero` are renamed to `returnsZero…` and assert the new behavior.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #8671 +/- ##
==========================================
+ Coverage 79.33% 79.56% +0.22%
==========================================
Files 143 144 +1
Lines 4278 4330 +52
Branches 436 444 +8
==========================================
+ Hits 3394 3445 +51
+ Misses 855 854 -1
- Partials 29 31 +2
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
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
Adds
DelayedFlowRouter, a hook + ISM that pairs with a warp route on both chains and slows cross-chain withdrawals proportionally when net flow exceeds a configurable fraction of the paired pool — without rejecting them. Designed to bound the blast radius of a bridge / ISM compromise (e.g. LayerZero rsETH) while leaving normal small-amount flow instant.maxCapacity() = pool × thresholdBps / BPSreads the paired warp router'sbalance(native) /balanceOf(collateral) /totalSupply(synthetic) at call time. No snapshot.maxCapacity(); the refill rate follows automatically._handleconsumes the bucket and writes an immutablereadyAt[id].verifyis a pure read — no re-evaluation at verify time (would only ever lengthen delays and complicate the state machine).PausableIsmviaStaticAggregationIsm(pausable first) so watchers can kill delivery during the delay window with a cleanPausable: pausedrevert.Lifecycle
sequenceDiagram autonumber actor U as User participant SR as Synthetic Router<br/>(origin) participant OD as origin<br/>DelayedFlowRouter participant OM as Origin Mailbox participant DM as Dest Mailbox participant DD as destination<br/>DelayedFlowRouter participant CR as Collateral Router<br/>(destination) Note over U,CR: maxCapacity() = pool × thresholdBps / BPS (read live) U->>SR: transferRemote(dest, to, amount) SR->>SR: burn synthetic (totalSupply ↓) SR->>OM: dispatch(warp) OM-->>OD: postDispatch(warp) Note over OD: sender == warpRouter<br/>nonce >= nextDispatchNonce<br/>_credit(amount) OD->>OM: dispatch(preverify = id, amount) Note over OM,DM: cross-chain delivery — preverify & warp<br/>arrive independently DM-->>DD: handle(preverify) Note over DD: maxCapacity() read NOW<br/>(pre-withdrawal pool)<br/>_consume → deficit<br/>wait = min(deficit, maxDelay) Note over DD: commit readyAt[id] DM->>CR: process(warp) CR->>DD: verify(warp) alt block.timestamp < readyAt[id] DD-->>CR: revert MessageNotReadyUntil else ready DD-->>CR: true CR->>U: release(amount) endSee
docs/delayed-flow-router.mdfor the full design.Refactors
TimelockRouter:postDispatch/_handleare now overridable end-to-end, with leaf helpers_TimelockRouter_dispatchPreverify(id, destination, payload)and_TimelockRouter_commitReadyAt(id, wait)exposed for subclasses. No more virtual-callback weaving (_encodePreverify,_waitremoved).RateLimited:maxCapacity()made virtual; refill rate derived from it automatically;_creditand_consumeprimitives added; token-bucket math switched toMath.mulDivfor precision; single-maxCapacity()-read-per-path factoring via a private_levelAt(cap)helper.Security notes
postDispatchrequiresmessage.sender == warpRouterso a third party can't grief our bucket by dispatching arbitrary messages through the Mailbox.verifyrequiresmessage.recipient == warpRouterso we don't attest to messages not destined for our paired route.nextDispatchNonce(uint32, monotonic) +_isLatestDispatchedprevent same-message double-credit / re-preverify.maxCapacity()are STATICCALL-only (IERC20.balanceOf/totalSupplyare view) and can't reenter.Test plan
forge test --match-contract DelayedFlowRouter(13 tests): capacity source derivation (HypNative / HypERC20 / HypERC20Collateral), under-threshold passes immediately, over-threshold scales proportionally, oversize clips atmaxDelay, deposit credits bucket, preverify replay rejected, sender/recipient binding, PausableIsm composition.forge test --match-contract TimelockRouter|RateLimited(26 tests): existing suites still pass after refactor.pnpm -C solidity gas).maxDelay1 day.Follow-ups (out of scope for v1)
DelayedFlowRouterFactorythat deploys both legs, cross-enrolls, and wraps inStaticAggregationIsm([Pausable, Delayed]).thresholdBps,maxDelay).HypXERC20variants (different capacity notion).