# BlazePhoenix-Dex Whitepaper v2.4.0 — part 4 of 9: Part III — Routing and execution > One part of the whitepaper in llms.txt form; every part and every section is listed in > https://blazephoenix.xyz/whitepaper/llms.txt. The parts are the full text, unabridged: the bodies of parts > 1-9, joined in order, are https://blazephoenix.xyz/whitepaper.md byte for byte (sha256 a47389f947e4aa6656f693004e43fbe3e0101dccaf133e49c303767811f223cc). > Cite as https://doi.org/10.5281/zenodo.24517342; numbering (§, E, INV-) as in the paper. ----- verbatim text of whitepaper.md follows ----- ## Part III — Routing and execution ## §10 Routing and the Split Allocator A constant-product pool prices by one rule: its two reserves, multiplied, may never shrink. Pour $\Delta$ in with fee retention $\gamma$ (a 0.30 % venue fee means $\gamma = 0.997$) and you receive $y\,\gamma\Delta / (x + \gamma\Delta)$, with your own input in the denominator: the more you push through one pool, the worse each further token pays. Slippage is arithmetic, and so is its cure: splitting the same order across pools of the same pair moves each pool less. **Worked example 2 — a split across two pools.** One order of 100 against two pools of the same pair, both at 0.30 %: pool A holds 1,000 a side, pool B holds 4,000 a side. | Route | Arithmetic | You receive | |---|---|---| | All 100 into A | $1{,}000 \times 99.7 / 1{,}099.7$ | 90.661 | | All 100 into B | $4{,}000 \times 99.7 / 4{,}099.7$ | 97.275 | | 20 into A, 80 into B | $1{,}000 \times 19.94 / 1{,}019.94 \;+\; 4{,}000 \times 79.76 / 4{,}079.76$ | $19.550 + 78.201 = 97.751$ | The 20 / 80 split is the allocator's own choice, not a guess: weights are proportional to measured depth against the deepest candidate — A weighs $1{,}000/4{,}000 = 2{,}500$ of 10,000, B weighs 10,000 — so A takes $2{,}500 / 12{,}500 = 20$ % of the order. The split beats the best single pool by 0.476 tokens, 48.9 bps of it. The split gate then asks whether that gain earns its second leg: the threshold is $97.275 \times (1 + 25 / 10^{6}) = 97.278$, and 97.751 clears it, so the split stands. Every row is checkable with a calculator, and it compounds: price impact is each pool's response to *its own* slice, so every admissible leg added to a route moves every pool less. ![FIG-6 — Output against the share sent to the deep pool](https://blazephoenix.xyz/whitepaper/figs/v2.4/fig-6.svg) *FIG-6 — Output against the share sent to the deep pool for the two-pool example: a concave curve with its maximum near 80 %, the allocator's depth-proportional point marked.* ### §10.1 Route shapes and budgets The Solver builds four topologies and returns the maximiser (`findBestRoutePlan`, with the runner-up as a fallback): a *direct* route in one hop and, for each configured bridge, a *bridge* route through that one intermediate (`tIn → bridge → tOut`). Two hops is the deepest shape the Solver builds and the most the Router accepts (`MAX_HOPS = 2`; a longer route is refused with `RouterE(3)` at every door). The topologies are judged in order and a tie keeps the earlier one, but the bridge topologies only add candidates to the judgement: a direct route still wins whenever it delivers more, because the comparison is by the output built and not by the depth of the topology. Bridges come from an operator-configured set of at most three tokens in the Hub (`BRIDGE_SLOTS = 3`, the Hub's `MAX_BRIDGES`), so `TOPOLOGIES = 1 + BRIDGE_SLOTS = 4`; the Solver expands every configured bridge and lets the measured `totalOut` decide, per trade. Every hop splits across parallel legs under one budget with one producer: `MAX_LEGS_PER_HOP = 5` in Core is the Router's ceiling (`RouterE(3)` refuses a wider hop), the Quoter's test for whether a plan is executable, and the Solver's leg budget for every stage of every topology, so the Solver never proposes a hop the Router refuses and never stops a leg short of one the Router takes. A route therefore holds at most `MAX_HOPS × MAX_LEGS_PER_HOP = 10` legs, and that bound is the product of those two constants and nothing else: no code needs a route-wide count, so no third constant can drift from it. A route whose measured impact exceeds `MAX_ROUTE_IMPACT_BPS = 9,000` is not returned at all, and a pair with no admissible route refuses with `SolverE(5)` rather than fabricating one. ### §10.2 The funnel For each pair the Solver gathers the registered pools and, unless the registry is fresh (§9.4), the discovered ones; removes any pool whose hook alters deltas (the projector Ξ, applied here so that the planned door can never assemble a route the Router would refuse); and orders the union by Ψ. No count cuts the funnel: Ψ fixes only which venue is probed first and settles exact ties (an exact tie breaks toward the lower fee, so on a cold registry the order is a function of price rather than of history), so a deep pool listed behind several thin venues is seen, weighted and can displace them instead of being starved by list order, and the quotes make every real decision. The cut to `MAX_LEGS_PER_HOP` = 5 legs in a hop comes after the probe and the weighting, and the candidates that pass the believability band reach the split gate, not only those the cut keeps (§3). What leaves the list is dust, and dust is measured against the pair rather than counted out. Each row is weighed by its mass on this hop, the output token it can pay (`hopMass18`), and row $j$ is dropped if and only if $d_j \cdot 10^6 < \mathrm{MIN\_SPLIT\_IMPROVEMENT\_PPM} \cdot (D - d_j)$, with $D$ the sum of the masses. The rule has no threshold of its own and no price: it is the split gate's improvement bar (§10.4) read as a share of the pair's measured depth. For pools at one price and one fee, the most a leg on $j$ can add to what the others pay, relative to it, is $d_j/(D-d_j)$ at every size (the derivation is in the `_dropDust` documentation of the Solver), so a dropped row cannot lift an order by the improvement a split must show to be kept. A row alone on its pair or holding all of it is never dust, nor is the deepest row, and a Gate wrapper, whose mass is not read here, stays: absent is not zero. A singleton book (V4) is measured twice: its declared side is its current tick alone, not a bound, so before a book that declares mass is dropped every book is walked over its tick and the next stretch (`FUNNEL_STRETCHES = 2`): its own $d_j$ is the larger of the side it declares and what it holds over that walk, and what it adds to the other rows' $D$ is what it holds over it. The limit is stated where it is decided: at two prices inside the band a dust row priced better can win an order small enough for it, and dropping it costs at most the price gap. Each candidate is then probed once, at a hundredth of the order (`amountIn / 100`, or the whole order when that floors to zero), capturing its marginal rate and its depth in the same call. Marginal rates cleanly separate two signals that full-size rates conflate: a stale-priced pool has a wrong marginal rate regardless of size, while a small but healthy pool has a correct marginal rate and merely a poor full-size output. For pair-shaped kinds the declared depth is capped by what the pool physically holds of the output token, so a synthetic pair declaring $3 \times 10^{30}$ while holding one token of each side is weighed at what it holds. ### §10.3 The believability band Before allocation, candidates must be believed, and belief must be anchored on a quantity that costs something to forge. The band's centre is the **depth-weighted median of the survivors' prices** (`_depthWeightedMedian`): prices are sorted with their depths travelling alongside, and the median is the price at which half the *depth mass* has been passed. Its breakdown point is 50 % of the mass — to move it, an attacker must out-depth half the pair's real liquidity — and the depths it weighs are `getReserves` for reserve pools, active liquidity for concentrated pools and measured liquidity for V4: quantities a plain donation to a pool does not move. That last property is why the anchor is not the largest real balance: a transfer to a pool inflates `balanceOf` without moving the reserve or the price and is recoverable by the donor, so it is not capital at risk. The band reads **prices, not rates**. A probe measures the rate after the venue's fee, so a band on rates reads a fee as a price: a venue charging 10 % at the honest price sits 10 % under an honest 0.3 % venue. A probe's price is $p_i = r_i \cdot 10^6 / (10^6 - f_i)$, with $f_i$ the fee the probe itself charged, in pips. **The width is no-arbitrage, not a number of basis points.** Two honest venues at rest leave no round trip to take, so their spots satisfy $(1-f_i)(1-f_*) \le s_i/s_* \le 1/((1-f_i)(1-f_*))$, with $*$ the base; a measured price sits within its probe's error bound $e$ of its spot, $s(1-e) \le p \le s/(1-e)$. With $k_i = (1-f_i)(1-f_*)(1-e_i)(1-e_*)$, every honest venue at rest has $k_i \le p_i/p_* \le 1/k_i$. The band keeps row $i$ if and only if - below: $p_i \ge p_* \, k_i$, with $e_*$ read at the hop's size; - above: $p_i \, k_i \, (1-f_*) \le p_*$, the base's fee counted twice. Both hold for every honest venue at rest, so the band never drops one. The base's fee counts twice above because $k_i$ alone lets a base holding half the mass park itself on the no-arbitrage edge, where it leaves a round trip of only about $e_h + e_*$ open — too little to pay an arbitrageur's gas — drops the honest venue $h$ over the top and charges the user $1-(1-f_*)^2$ against $h$ (19 % at $f_* = 10$ %). Counted twice, dropping $h$ needs a round trip $G$ between $h$ and the base with $1+G > 1/(1-f_*)$; then the user's loss against $h$, $1-(1-f_*)^2/(1+G)$, stays under $1-(1+G)^{-3} \le 3G$ (the first step from $1-f_* > 1/(1+G)$, the second is Bernoulli's inequality): hurting the user by $L$ leaves at least $L/3$ open to whoever closes it. Below, $k_i$ alone loses nothing: a row dropped there has a measured rate under the base's own. A fee nobody knows (a Gate wrapper reports none) is handled without inventing one: its price is read as its rate, a floor of the truth; above it is judged with $f_i = 0$; below it is never judged; its mass does not vote while a row with a stated fee does; and a base whose fee is unknown states no width, so every live row is kept. A candidate set of one is not filtered at all, and a set in which no live row carries a vote (every live depth zero, or every vote muted) falls back to the plain median's row, which is live, so an otherwise routable hop is not killed for want of a vote. The width has a price, and it is stated where it is decided. The band is as narrow as the fees: where the venues charge 0.05 %, an honest venue that lags the base by more than the round trip is dropped until an arbitrageur closes the gap. A venue at a fair price behind a large fee is now inside the band, and the split weighs by depth, so the split carries a rule for it (§10.4, *every leg pays for its place*). A fee near 100 % leaves $k_i$ near zero and passes both edges, but such a venue's rate is near zero and the gate weighs rates. What the band does not bound is the arbitrageur's gas and the quote shapes the probe lists as its limits. The metamorphic lane of §15.7 measures the band from outside, with one pool priced $10^{10}$ away from its sibling : before the price band existed, the header of that test file records that the plan paid 35 % less than the outlier alone (MR-R1); the relations now run inside the band's domain, so that figure is history, not a property asserted at 6387350. The source of this subsection is the documentation of `BlazePhoenixMath` («THE BAND») at 6387350. ### §10.4 The allocator and its four guards Weights are proportional to measured depth, normalised against the largest depth in the set (`_weights`) — one normalisation, no modes, because every family's depth is token-denominated (§4.2) and therefore comparable. Proportional allocation is the robust choice for an adversarial environment: it needs no iteration and no per-venue curvature model, and it avoids the catastrophic failure a uniform split produces — in a measured WETH/USDC case, splitting 50 / 50 across a 790-WETH pool and a 0.34-WETH dust pool returned 1,302 USDC where concentrating in the deep pool returned 1,638; the depth-weighted allocation returned 1,638. When the funnel holds more survivors than the hop's budget, the top-budget survivors *by weight* are kept, so a deep late-listed pool displaces thin early-listed ones. Four guards then stand between the allocation and the route it becomes. - **The capacity clamp.** The single-tick concentrated-liquidity formula models the current tick's liquidity as if it spanned every price, so on a thin pool it can promise more than the pool has ever held — 117× more in one observed case. A concentrated leg on a pool-shaped venue (kinds 1 and 6) is therefore clamped to `MAX_CONC_DRAIN_BPS = 3,000` — 30 % — of the pool's *measured* real output-token balance. The clamp does not reach V4 legs: the singleton holds every pool's tokens in one balance, so the Solver skips the read for kinds 4 and 8 and a V4 promise carries no physical bound beyond the floor of §11.3 — the floor is its bound. The clamp is two-tier: when the quote exceeds the pool's entire holdings the promise is physically impossible, and the clamp caps the promise and, on the first hop, cuts the leg's *committed input* in the same ratio (a later hop keeps its input, which the Router rescales to what the stage before produced), cascading the freed input to the remaining legs and leaving anything unroutable to be swept back to the caller; when the fill is aggressive but possible, the capital stays, because cutting it there was measured to force partial fills on pools that execute fine: every topology ranks the leg at the cap, and on the winning topology's own build it is promised what the pool's book pays for that input, walked read-only and held between the cap and the quote (a book that cannot be read keeps the cap). Reserve-bounded formulas cannot over-promise and are untouched. This clamp reads `balanceOf` deliberately where the band does not: the band asks a *relative* question a donation can skew, the clamp asks a *physical* one — can this pool pay this? — and a donation raises what the pool can really pay. - **The split gate.** Each extra leg costs real gas, and the allocator deliberately contains no gas-price term, because comparing gas in the native token against output in the trade's token would need exactly the price oracle the protocol refuses to have. The oracle-free proxy is a threshold: a split is kept only if $\mathrm{out}_{\mathrm{split}} \ge \mathrm{out}_{\mathrm{single}} \cdot (1 + 25/10^{6})$ — `MIN_SPLIT_IMPROVEMENT_PPM = 25` — otherwise the allocation collapses to one leg. The threshold is a measured number: the true break-even between a leg's gas and its improvement measured 3 ppm on Base (320 bytes of calldata per extra leg at 105.5 gas per byte), and the gate sits at about eight times that, denominated in parts per million because a quarter of a basis point does not exist in basis points; its history — 20 bps, then 5, then 0.25 — is a record of three values that had never been calibrated against a measurement. When the gate collapses a route, it measures every survivor of the band alone at full size, not two representatives: the deepest pool and the best marginal rate are both heuristics for the best single leg, and with three or more survivors that leg can be neither (`test/SplitGateSeesEverySurvivor.t.sol`); the best fill wins. - **Every leg pays for its place.** The weights are depths, and a split by depth is the best split only where every leg pays one price. Because the band judges prices (§10.3), a venue at a fair price behind a high fee sits inside it and takes its depth's share of the order: in the test that pins this rule, beside two honest venues at 0.3 %, a venue at 10 % holding 0.3× their depth took 23.1 % of an order a tenth of each, and the route paid 1.10 % less than without it (`test/SplitLegPaysForItsPlace.t.sol`; figures measured at 3975a50 and recorded in its header). The gate above asks whether the whole split beats its best leg alone; this guard asks it of each leg. A leg of a split of three or more stays only while the split with it pays at least `MIN_SPLIT_IMPROVEMENT_PPM` more than the same split without it, and a split of two is not tried, since without one of its legs it is the other alone, which the gate measures at full size. No threshold of its own decides *which* leg is tried: an optimal split leaves leg $j$ out if and only if its rate at zero is at most the common marginal rate $m$ of the legs it keeps; some kept leg $i$ receives at least its present share $a_i$ there, and on a concave book $m \le \mathrm{marginal}_i(a_i) \le \mathrm{average}_i(a_i)$; a probe pays its own impact, so $j$'s probe rate is at most its rate at zero. So $j$ can be left out only if its probe rate is at most what another leg pays on average now, and only then is a leg tried, the one whose probe paid least first; the trials stop at the first leg that pays. The leg left out frees its weight to the others and stays in the band, so the gate still quotes it alone. The cost is one more quote of the legs that remain per trial. - **Insurance by measurement, not by margin.** An earlier design shaved every leg of longer routes by 5 bps at planning time as insurance against inter-leg drift. The drift was then measured on nine Base pairs in the same block: worst case −2 bps, an order of magnitude below the insurance, which every honest multi-leg route paid on every trade — 27× its measured hazard. The shave was retired; the floors, enforced on realised output, carry that risk at zero planning cost. The measurement was taken in a calm window and the counter-argument is on the record in the source: if conservatism is ever restored, the right place is the floor, which is checked, and not the estimate, which only ranks. The assembled route carries what the Router will re-derive: each leg's committed input and expected output, the route's share-weighted impact, and the floor Φ the Solver attests from the same arithmetic the Router enforces (§11). The Solver also prices each leg's execution by kind from the `THETA_GAS` ladder and publishes the total as `estGas`, an advisory figure the route carries and nothing on-chain reads. The reader's rule of thumb survives all of this machinery unchanged: compare the improvement the router claims against the gas your wallet shows, before you confirm. ## §11 The execution layer and the Iron-Law floor Φ The Solver proposes; the Router disposes — atomically, or not at all. The Router is the only contract that moves funds, holds none between transactions, and is built on one principle: one mechanism per concern, applied universally. It assumes nothing it can measure. ### §11.1 Four doors, one executor | Door | Signature (abridged) | Authorisation | Route | |---|---|---|---| | `swapExactIn` | `(route, amountIn, userMinOut, recipient, deadline)` | classic `approve` + `transferFrom` | from calldata | | `swapExactInWithPermit2` | `(route, amountIn, userMinOut, recipient, deadline, permit, signature)` | one-step Permit2 signature transfer through the canonical Permit2 contract; no standing allowance to the Router | from calldata | | `swapExactInNative` | `(route, userMinOut, recipient, deadline)` payable | native value, wrapped once at the door; fail-closed until `weth` is wired (`RouterE(3)`) | from calldata | | `swapBestExactIn` | `(tokenIn, tokenOut, amountIn, userMinOut, recipient, deadline)` | classic | solved in-frame by the Solver (`findBestRoutePlan`, under the `SOLVE_GAS` budget of 14,700,000), then executed through a self-call with the payer threaded explicitly | Only `swapBestExactIn` invokes the Solver in the transaction; the other three take the route the caller computed off-chain, for free, through the Quoter (§12). All four converge on one private executor (`_execute`), so every check below runs on every door. If the in-frame Solver reverts without data, the door refuses with `RouterE(17)` rather than guessing. An EIP-7702 delegated account calls the Router as a contract would; no separate entry exists for it, and the executor itself refuses to run inside a delegated frame, where every balance it measures would be the account's (`RouterE(18)`). Two refusals run before anything moves. A zero minimum is refused at every door — `RouterE(10)`, no exceptions, no compatibility flag — because the minimum is the one bound the contract cannot compute on the user's behalf, and a guard that may be absent is not a guard. And a route with more than two hops (`MAX_HOPS = 2`), more than five legs in a hop (`MAX_LEGS_PER_HOP = 5`), a hop whose two tokens are the same, or a hop whose input token is not the previous hop's output is refused with `RouterE(3)`: hop continuity is what makes the pre-swap "foreign" balance of every intermediate token known, so a crafted route cannot name a stranded token as its input and scale the Router's whole balance of it into the swap. The product of the two ceilings, 2 × 5 = 10 legs, is the most a route can hold; the Solver's own budget is set to the same shape (§10.1). ### §11.2 Measurement, from the first instruction Whichever door is used, the first thing the Router does is measure what arrived: it reads its own balance delta after the pull rather than trusting the nominal amount, so a token that delivers short on transfer enters the route at its true size. Baselines are born once: the input token's pre-swap balance (`baseIn`) and the output token's (`toutStart`) are taken at entry, and every later measurement is a delta against them, so tokens already sitting in the contract — dust, donations, strandings from unrelated history — are excluded from what a swap can pay out. A route that manages to spend below its own baseline fails on checked arithmetic — the safe outcome, since those funds were never this swap's to spend. A multi-hop route is a plan, and plans meet reality at every hop boundary. The Router rescales each hop's legs against the balance that *actually* arrived — hop 0 against the measured post-pull input, capped by what the route committed (so the Router never force-feeds a pre-cut order into a thin pool); the second hop against the measured bridge balance above its foreign baseline — each leg executing $\mathrm{amt} = \mathrm{amountIn}_{\mathrm{leg}} \cdot \mathrm{real}/\mathrm{planned}$ (`_hopScaleImpactAndQuote`). A leg scaled to zero is skipped; unspent input and bridge residuals are swept back to the payer, never to the Router. The same pass reads each leg's pool state once and produces, from that single read, the leg's scaled amount, its measured impact and its in-frame quote — the three quantities the floors consume — so the reserve and concentrated families pay no extra `staticcall` for their measurement. ### §11.3 Four refusals under every leg **The per-leg floor.** Each leg's measured contribution to the Router's output balance must reach `LEG_FLOOR_BPS = 8,000` — 80 % — of its bound, or the whole swap reverts with `RouterE(5)` (`_execScaled`), so a single sandwiched or manipulated pool fails the transaction immediately instead of hiding its loss inside an otherwise healthy total. The bound is the caller's attested quote, pro-rata to the amount actually spent, joined by the quote measured in-frame as the second element of a maximum: $\mathrm{bound} = \max(\mathrm{attested},\ \lfloor q \cdot 5{,}000/10^{4} \rfloor)$, where $q$ is the in-frame quote and `MIN_QUOTE_COVERAGE_BPS = 5,000` (Router:1789-1842 at 6387350). That is a maximum, not a minimum, on purpose: on a floor, `min(claimed, measured)` with a deflated claim returns the deflated one and relaxes, which is the attack the gate closes. And it is monotone in the attestation — attesting more never lowers the floor — because the lift goes to the threshold itself and not to the whole measurement. The guard runs whenever there is any floor basis — the caller's attestation or the in-frame quote — so writing zero into a route does not switch the caller's own floor off. A venue with no measurable quote and no attestation is bounded by the aggregate floors and the user minimum. **The aggregate floor per hop.** The per-leg floor is local while composition is global: an attacker holding one leg of $L$ could extract about $20\,\% \cdot (L-1)/L$ of a hop without failing any single floor. So each hop may lose at most what one *average* attested leg could legitimately lose: $\sum \mathrm{got} + \lfloor (\mathrm{BPS} - \mathrm{LEG\_FLOOR\_BPS}) \cdot \lfloor \sum \mathrm{attested} / n \rfloor / \mathrm{BPS} \rfloor \ \ge\ \sum \mathrm{attested}$ — the slack is 20 % of the average attested leg, else `RouterE(5)`. The mean and not the maximum, because under a maximum the attacker inflates their own leg to inflate the shared budget. Only legs that have a bound enter the sum, on both sides, so a leg without one cannot mask another's shortfall. For one leg the rule collapses exactly onto the per-leg floor — zero new rigidity, by construction. **The declaration cap.** A leg's measured output delta may not exceed what the venue declares it paid (`RouterE(20)`, Router:1787 at 6387350); less is fine, which is how a fee-on-transfer output token passes. The window of a leg also spans the venue's own code, and tokens landing on the Router inside it must not be counted as the leg's output. **The gated door.** A leg of an external kind executes only if the wrapper it names is the one the Hub's Gate derives from the hop's own tokens and fee (`RouterE(19)`); the kind in calldata is a claim, not an identity (§14.4). **The route floor Φ** is §11.5. ### §11.4 One callback, one unlock Every V3-shaped venue — Uniswap V3, Algebra, the concentrated Solidly forks, Pancake V3, Sushi V3 — uses the same flash-accounting pattern under a different callback name: the pool calls back mid-swap with a delta for token0, a delta for token1 and arbitrary data, demanding payment. Rather than one named callback per fork, the Router exposes a single `fallback` that answers them all — the **One-Callback Doctrine**: it reads the two deltas, identifies which token it owes from their signs, and pays exactly that amount, taking the in-flight leg context from transient storage (`TSLOT_POOL`, `TSLOT_TOKEN`, `TSLOT_AMT`). Because a fallback is reachable by anyone, it is guarded on three fronts: it pays only the pool committed for the current leg, it refuses to act when no leg is in flight (the transient context is zero between swaps), and it never releases more than the leg's recorded budget — a second demand within one leg is refused with `RouterE(6)`. A newly launched V3 fork with a novel callback name is supported the day it deploys. The V4 singleton is wrapped behind the same hop interface: `unlock`, then swap, `sync → settle → take`, re-lock, with the currencies carried in transient storage and the native seam of §5.3. Before any V4 leg executes, the Router derives the pool id from the leg's own fields and refuses a leg whose id or direction does not match (`RouterE(11)`), then reads the hook address and refuses the leg if its bits declare delta-altering permissions (`RouterE(9)`); the sieved hook is the executed hook, because the canonical PoolManager echoes the unlock data verbatim (`test/V4SievedHookIsTheExecutedHook.t.sol`). The route-shape rule is canonical order, route-wide: once a hooked leg has executed, no hookless leg executes after it in this or any later hop (`sawHooked`, `RouterE(3)`), so a hook cannot observe a later hookless leg of the same route before it settles; a hooked leg may sit in an earlier hop only if every leg after it is hooked too. It is an encoding rule, like token ordering: every route can be written in the canonical order, so nothing is rejected that could not be re-expressed. **Fee-on-transfer, on the legs that can afford it.** Some tokens deliver short on every transfer. On constant-product legs the Router handles this by the canonical pattern — transfer first, then read the pool's reserves and its balance in the same post-transfer state, and price the output on the difference the pool actually sees — a quantity correct by construction, because it is exactly the quantity the pool's own invariant will check. The branch engages only when a token measures short (`TSLOT_FOT`, which holds the compounded measured net ratio in WAD), and what engaging it costs is stated with it: the quote-derived route floor was computed blind to the tax and is dropped for that swap; the protocol floor is re-scaled by the measured net ratio (rounded up, the conservative direction); each per-leg bound on a constant-product leg is re-priced by that leg's own measured ratio (what the pool received over what was sent to it, rounded up); and the user's minimum becomes the binding constraint. Concentrated legs do not support fee-on-transfer by design — flash accounting must pay exactly what is owed — so a taxed token on a V3-only route is refused up front with `RouterE(13)` rather than reverting inside a pool. ### §11.5 The Iron-Law floor Φ, in full Not every route that can execute should — a route returning 60 % of fair value is worse than no trade — so under everything above sits a floor the protocol derives for itself. It is a retention fraction in basis points (Core `ironFloorBpsShv`, `legShaveBps`): $$ \mathtt{floorBps} \;=\; \max\!\left(\;9{,}600 - \mathtt{legShv} - \min(\delta,\, 10^{4}) - \sigma_{\ln}/10^{14},\;\; 8{,}000\;\right) $$ ^e15 $$ \mathtt{legShv} \;=\; \sum_{\mathrm{hops}} \left\lfloor 200 \cdot \frac{(\sum_{i} a_{i})^{2} - \sum_{i} a_{i}^{2}}{\sum_{i} a_{i}^{2}} \right\rfloor \;=\; \sum_{\mathrm{hops}} \left\lfloor 200\,(n_{\mathrm{eff}} - 1) \right\rfloor $$ ^e23 Three constants decide it: `FLOOR_BASE_BPS = 9,600`, `FLOOR_PER_LEG_BPS = 200`, `FLOOR_HARD_MAX_LOSS_BPS = 2,000` (Core:400-402; the floor itself is Core:3345-3357, the leg shave Core:3338). The floor starts at 96 % for a clean single-leg swap, loosens one basis point per basis point of measured impact $\delta$ and 200 bps per *effective* extra leg, and is clamped so it never falls below 8,000 bps: the protocol will never knowingly admit a route retaining less than 80 % of its reference, whatever the inputs. The leg shave is computed from the *concentration* of the trade across legs — $(\sum a)^{2}/\sum a^{2}$, the effective number of legs, exactly $N$ for $N$ equal shares and exactly 1 for one dominant leg — so a split earns loosening in proportion to how genuinely it is split, and a leg carrying a vanishing share earns a vanishing amount whether it declares zero or one wei. By Cauchy–Schwarz the numerator never underflows. The impact term is the share-weighted mean of the legs' measured impacts over the route. Two properties are printed as part of the definition: the volatility term $\sigma_{\ln}$ exists in the signature and is passed as literal zero at every call site — a hook for a future estimator, currently inert — and the reserve-family impact is fee-exclusive while the concentrated-family impact is fee-inclusive, each in the form its family's specification gives it. What makes Φ an enforcement rather than a heuristic is where it runs and on what. The route handed to the Router carries advisory fields — a quoted total, an attested floor — and the Router trusts neither: inside the executing frame it measures each leg's real impact, computes the leg shave from the amounts it is handed, recomputes `floorBps`, and applies it to the **final hop's in-frame quote at the amount that actually arrived there** — a reference denominated in the output token, derived from pool state read during this execution, unforgeable by calldata. The choice of reference is what lets the guard fire at all: a fraction of the *realised* output can never exceed the realised output. When the final hop cannot be quoted in-frame — a liquidity gap at the current tick, a fee sentinel — the reference falls back to the hop's attested quote, which the coverage gate has already lifted and the fee-on-transfer measurement re-priced, so a just-in-time (JIT) liquidity gap on a thin pool cannot disarm the floor; the floor's anchor is always a hop that moved value and produces the route's output. The check runs on the gross output, before any output-side fee. The effective minimum is a three-way maximum, $$ \mathtt{effMin} \;=\; \max\!\left(\mathtt{userMinOut},\;\; \mathtt{route.singleOutFloor},\;\; \left\lceil \mathtt{finalHopQuote} \cdot \mathtt{floorBps}/10^{4} \right\rceil\right) $$ ^e16 and its asymmetry is the point: caller-supplied fields can tighten protection and can never loosen it. The Solver attests `singleOutFloor` from the same `legShaveBps` and `ironFloorBpsShv` on the same amounts, so for a Solver-built route the attested floor and the enforced floor agree by construction (`test/FloorParitySolverRouter.t.sol`), and the regime harness of §15 pins the two frames on every generated row: with the fee off the input, the enforced floor sits in $[\mathrm{attested},\ \mathrm{attested}/(1 - \mathrm{fee})]$, the attested floor read back on the gross output (one factor per charging hop); with the fee off the output, it equals the attested floor. ![FIG-7 — The Iron-Law floor](https://blazephoenix.xyz/whitepaper/figs/v2.4/fig-7.svg) *FIG-7 — The Iron-Law floor: retention against measured impact for a single leg, two equal legs and four equal legs; the 80 % hard clamp; the point of Worked example 3 marked.* **Worked example 3 — the floor on a two-hop route.** A route A → WETH → B: hop 0 splits 600 A into pool P and 400 A into pool Q; hop 1 sends the WETH produced through one pool R. Measured in the frame: hop 0's legs show impacts of 100 and 60 bps, hop 1's leg 72 bps, and the share-weighted mean over the route is 80 bps. Hop 1's in-frame quote at the WETH amount that actually arrived is 1,000.000 B. 1. Hop 0 concentration: $(600 + 400)^{2} = 1{,}000{,}000$; $600^{2} + 400^{2} = 520{,}000$; $n_{\mathrm{eff}} = 1.923$; shave $= \lfloor 200 \times 480{,}000 / 520{,}000 \rfloor = \lfloor 184.6 \rfloor = 184$ bps. 2. Hop 1 has one leg: $(\sum a)^{2} - \sum a^{2} = 0$; shave 0. Total `legShv` = 184. 3. $\mathtt{floorBps} = \max(9{,}600 - 184 - 80 - 0,\ 8{,}000) = 9{,}336$: the route must retain 93.36 % of its reference. 4. $\mathtt{protocolFloorOut} = \lceil 1{,}000.000 \times 9{,}336 / 10{,}000 \rceil = 933.600$ B. 5. With `userMinOut` = 990 B set by the trader and `singleOutFloor` = 933.6 B attested by the Solver, `effMin` = 990 B — the user's own bound is the binding one, as it should be on an honest route. A delivery of 998.4 B settles; a delivery of 985 B is refused with `RouterE(5)`, and the whole transaction, every pool's swap included, never happened. Had the trader set `userMinOut` = 900 B, the protocol floor would bind at 933.6 B: a fill at 930 B, 7 % below the in-frame reference, is refused even though it clears the user's number. ### §11.6 Settlement, and how to read one Settlement closes the frame the way it opened: by measurement. The Router takes its output-token delta against the entry baseline as the gross output (`RouterE(8)` if it is zero), runs the floor check above, charges the fee where the regime puts it (§13), transfers the net to the recipient and measures the *recipient's* balance delta, enforces `userMinOut` on that delivered amount — so a fee-on-transfer output token cannot slip the user below their bound (`RouterE(5)`) — and reads the fee ledger once: a settlement that paid the protocol nothing is refused (`RouterE(15)`), and on an anchored route a second payment is refused (`RouterE(16)`). Then, and only on the success path, it calls the Hub's `recordSwap` once per executed leg (`_recordHits`) with the amounts the hop was able to spend — the measured-over-declared ratio applied to each leg — which is the single external write a swap performs; nothing is written when the floor rejects. Every settlement emits `Swap(payer, tokenIn, tokenOut, amountIn, delivered, declaredLegs)`, with `amountIn` the gross amount the user handed over, and `ExecutionProof(user, tokenOut, quoted, realized, floorUsed, blockNumber)`: the reference quote produced in the same frame as the execution, published as an on-chain series that anyone can re-derive by an `eth_call` to `findBestRoutePlan` at that block. Its fields, without over-claiming: `user` is the payer, never `msg.sender`; `quoted` is the final hop's quote — it proves the last hop, not the route; `realized` is what was delivered, measured at the recipient; `floorUsed` is the protocol floor that had to be beaten, published net of any transfer tax the output token levied, on the transfer into the Router and on the final transfer (scaled by received over the venues' declared gross and by delivered over sent; the identity on an untaxed token), so a taxed output never shows a floor as met that the tax already took. Each `Fee(token, amount, toT1, toT2)` event names the token and the split. **Worked example 6 — reading a settlement.** The route of Example 3 settles and emits `ExecutionProof(0xUSER, B, 1,000.000, 998.400, 933.600, N)` and one `Fee(WETH, 0.014, 0.0042, 0.0098)`. | Quantity | Value | Reading | |---|---|---| | `quoted` | 1,000.000 B | the final hop's in-frame quote at the WETH that actually arrived | | `realized` | 998.400 B | delivered to the recipient, measured there; 9,984 bps of the quote | | `floorUsed` | 933.600 B | `floorBps` 9,336 applied to the quote; the fill sat 64.8 B above it | | `Fee` | 0.014 WETH in one event | the anchored regime: 28 bps of the 5.000 WETH that hop 0 produced, paid at hop 1's input, 30 % to the first treasury; nothing was taken from B | | distance to `userMinOut` | 8.4 B | the user's 990 B bound left 0.84 % of slack | Delivered minus quoted is the market's answer, not the protocol's: the fee left earlier, in WETH, and no output-side cut exists on this route. A `Fee` event denominated in the output token appears only on a direct route into a bridge coin (§13). ### §11.7 The Router's refusals | Code | Meaning | Where | |---|---|---| | `RouterE(1)` | unauthorised caller — a control call, a treasury move by a non-treasury, a fee claim with nothing owed, the self-call door called from outside | `onlyControl`, `moveTreasury`, `claimFee`, `selfExecutePrePulled` | | `RouterE(2)` | paused, or renunciation attempted while paused | `whenLive`, `renounceControl` | | `RouterE(3)` | bad input — zero address, unwired native door, hop count (over 2), legs per hop (over 5), hop discontinuity, a hookless leg after a hooked one | entry points, `_execute` | | `RouterE(4)` | deadline passed | entry points | | `RouterE(5)` | output below a floor — per-leg, per-hop aggregate, route floor or `userMinOut` | `_execScaled`, `_execute` | | `RouterE(6)` | callback not authorised — wrong pool, no leg in flight, second demand | `fallback` | | `RouterE(7)` | re-entrancy | `nrEntrant` (transient lock) | | `RouterE(8)` | swap failed — zero output, unknown kind, fee at or above the amount | `_execute`, `_execScaled`, `_chargeHopFee` | | `RouterE(9)` | V4 hook alters deltas, or a hook that runs in the swap is paused in the Hub | V4 leg pre-commitment | | `RouterE(10)` | `userMinOut == 0` with `amountIn > 0` | every door | | `RouterE(11)` | V4 leg whose pool id or direction does not derive from its own fields | V4 leg pre-commitment | | `RouterE(13)` | fee-on-transfer input on a V3 leg — the pool measurably received less than it demanded | `_v3Callback` | | `RouterE(14)` | rescue not queued or inside its 48-hour delay | `executeRescue` | | `RouterE(15)` | settled without paying the protocol fee | fee ledger, end of `_execute` | | `RouterE(16)` | fee paid twice on an anchored route | fee ledger, end of `_execute` | | `RouterE(17)` | the in-frame Solver reverted without data | `swapBestExactIn` | | `RouterE(18)` | executor entered inside an EIP-7702 delegated frame | `_execute` | | `RouterE(19)` | external-kind leg whose Gate wrapper does not derive from the hop's tokens and fee | `_execScaled` | | `RouterE(20)` | a leg's measured output exceeds what its venue declares it paid | `_execScaled` | Code 12 is not assigned. A revert surface as enumerable as the API is what lets the regime arrays of §15 judge every row by one rule — settle, or refuse with a selector of ours — and call anything else a third way. ### §11.8 Fee-on-transfer on the way out §11.4 treated the input side: a token that taxes its own transfers enters the route at its measured size. The output side has two transfers, and the Router measures each. The first is the venue paying the Router. The Router's balance delta over its entry baseline is the gross output of §11.6, and the venue's own declaration of what it paid bounds that delta from above (`RouterE(20)`, §11.3). The second is the Router paying the recipient: the recipient's balance delta is the delivered amount, and `userMinOut` is enforced on it (`RouterE(5)`). Both are balance deltas; neither trusts a nominal amount. What was left to settle is which of the two the *protocol* floors read. Up to 969bcc6 the route floors of §11.5, the protocol floor and the caller's `singleOutFloor`, were compared with the measured delta, which is net of any tax on the first transfer, while both floors are priced on gross output. At 6387350 (PR #132) they are read instead against `outCap` (Router:1594-1600): the gross the venues declared paying in the output token, net of what the route took back out (Router:1337-1338 accumulates it, and it also caps the measured delta, Router:1490). The user's bound does not move: `userMinOut` stays on the recipient's delta. The per-leg floor and the hop budget keep reading the measured delta, with their base taken from the attestation. Three consequences follow from the definitions, not from a measurement, and are stated as such. First, on an untaxed token the venue's declaration equals the measured delta (§11.3, declaration cap), so `outCap` and the measured amount are the same number and an untaxed swap settles as before. Second, whatever the token does, the user receives at least `userMinOut` or the swap is refused: the check is a refusal on the recipient's measured delta, so $\mathrm{delivered} \ge \mathtt{userMinOut}$ on every settlement. The protocol floors are conditions on the route's pricing and are tested before the second transfer (§11.5); this change does not make them depend on what the second transfer does. Third, a tax large enough to take a leg below its 80 % bound or a hop past its budget is still refused (`RouterE(5)`), because those two guards still read the measured delta. What the change removes is one false refusal: a route that the venues priced correctly, rejected by a floor because the output token taxed the venue's payment. ## §12 Quote surfaces, and how a quote ages There are two places a number called "your quote" can come from, and they are different code paths: the **Quoter**, a preview contract an interface calls before you sign, and the **in-frame path**, where the Solver and Router compute quotes inside the executing transaction. §4.4 gave the per-kind truth; this section gives the surfaces and measures the gap between them. ### §12.1 The Quoter's surfaces | Function | Returns | Notes | |---|---|---| | `previewPlan(tIn, tOut, amountIn)` | a `Preview`, the fallback route and a flag | the Solver's plan, packed with the fee and the safety buffer (`BlazePhoenixQuoter.sol:231`); a `view` | | `previewPlanWithMinOut(…, userMinOut)` | the same | `canExecute` judged against the caller's minimum, which can only tighten the floor (`:243`); a `view` | | `previewRoute(route, userMinOut)` | a `Preview` | a route built earlier or off-chain, packed without re-running the Solver (`:316`); a `view` | | `batchQuote(entries[])` | up to `MAX_BATCH = 32` previews | a pair that cannot be planned leaves a zero-initialised entry; more than 32 entries revert `QuoterE(4)` (`:173`, `:323-327`); a `view` | | `previewAndEncode(…)` / `previewAndEncodeWithMinOut(…)` | a `Preview` and the calldata for `swapExactIn` | the way an integrator takes a quote; the §12.2 study uses exactly this. Not a `view`: call it by `eth_call` (`:264`, `:274`) | | `previewPlanExact(tIn, tOut, amountIn)` | the route and an exact net output | the Exact Pass: every concentrated leg dry-run against the pool's own swap; by `eth_call` (`:811`) | | `previewRouteExact(route, amountIn)` | the same, for a route built off-chain | the only way to quote a Gate leg (kind 9), which the Solver never plans; by `eth_call` (`:847`) | **What a preview is.** The `Preview` struct (`:204`) is advisory by design: the binding checks are the ones the Router re-derives in-frame. Its fields: `grossOut` echoes the plan's total; `protocolFee` is the effect of the 28 bps fee on the output (`Core:426`), modelled per regime exactly as the Router charges it (§13) (once on an anchored route, once per hop on an exhausted one) and rounded up as the Router rounds (`:346-470`); `safetyBuffer` is the inter-leg buffer $$ s \;=\; \min\!\left(\max(0,\, n-2) + 5a,\;\; 10\right)\ \text{bps} $$ ^e21 where $n$ is the leg count and $a$ the number of constant-product legs priced on an *assumed* fee (a declared fee the Core replaced under its ceiling). The terms are `BASE_SAFETY_BPS = 0`, `PER_LEG_SAFETY = 1`, `ASSUMED_FEE_SAFETY = 5` and the shared cap `SAFETY_CAP_BPS = 10` (`:146-148`, `:172`): zero at two legs or fewer, one basis point per leg above two, five per assumed-fee leg, under one cap of ten, because a buffer without a ceiling stops being a buffer and becomes a floor. The code's own reason for 5: only one direction hurts. A pool that charges less than the assumed 30 bps under-quotes harmlessly; one that charges more over-quotes and execution then delivers under the floor. The wired V2 venues publish 25 to 30 bps, so five covers the realistic spread, and the buffer deliberately does not cover the worst case the V2 fee ceiling admits, because a buffer sized for that case is a floor, and the floor already exists (`:150-172`). `netOut` is $\mathrm{grossOut} - \mathrm{protocolFee} - s$; `ironFloor` echoes the attested floor; `topology` (0 direct, 1 through one bridge) and `bridgeUsed` are derived from the hop count and from the fee anchor the Router will use, asked of the same producer (`BPC.feeCalendar`, reached through `feeCalendarOf`, `:346-470`), so the preview and the executor cannot name different bridges. `canExecute` carries the Router's shape and hook refusals (`_hookRefusedIn`, `:499`): an empty route, more than `MAX_HOPS` hops, a hop with no leg or more than `MAX_LEGS_PER_HOP`, a leg off its hop's pair, a hook that alters deltas or runs in the swap while the Hub holds it paused. The integrator rule fits in one sentence and is the most load-bearing advice in this paper: derive your minimum from your own price expectation, never from a preview field. **The encode doors ask the Router's own questions.** `previewAndEncode` returns the calldata with `effectiveMinOut = max(userMinOut, ironFloor)` already inside, and returns it empty when the route cannot settle: a caller cannot submit a transaction the function already knows will be refused. Three refusals are asked before the bytes are built (`_encode`, `:298-312`). The deadline is behind the block (`RouterE(4)`). The route, funded as the Router funds it, delivers under the floor the bytes carry, a figure taken from the venues' dry-run on every fee calendar, together with each leg's floor, the hop budget and the Router's route protocol floor (the last hop's gross output against `BPC.routeFloorBps` of that hop's base) (`_settles`, `:988`). And a concentrated leg is paid in a token its pool receives short of (`RouterE(13)`), measured by the input probe (`_inputTaxed`, `:684`): the pool is run backwards on the leg's output so that it pays this frame the input token before it calls back, and the callback pays it back and measures. The view doors cannot make this last measurement, since a view frame holds no token; the dry-run doors can, which is why the doors that return bytes are not views. **One item's gas does not starve the next.** In `batchQuote` each entry's solve is given its share of what is left, `gasleft() / (n - i)` for entry $i$ of $n$ (`:331-337`): a solve that runs out hands back one sixty-fourth of its gas (EIP-150), and the entries after it would otherwise read zero for a book that is not theirs. The share is taken over the entries still to run, so it never shrinks down the batch and the last entry is given everything. **The Exact Pass.** For a pool-exact preview of a concentrated venue, the Quoter calls the pool's real swap entry with a price limit at the extreme; the pool calls back demanding payment; the Quoter's callback, instead of paying, reverts, carrying the computed deltas in a tagged payload (`QuoteDeltas`, so a venue's own revert data can never be read as a quote, whatever its length) (`_simConc`, `:660-675`). The revert unwinds all state, nothing is paid, and the decoded output is the venue's own swap over live state, run and rolled back. V4 is handled identically through an unlock whose callback reverts with the packed delta (`unlockCallback`, `:724-742`; `_simV4`, `:747`). The scalar the call returns is **net**, and is taken where the Router takes the fee: on the anchor hop's input on a multi-hop route (inside the walk, so the next pool rounds on the reduced amount), on the output only where the fee calendar puts it there, and rounded up, so a minimum derived from it is honoured by the floor (`_exact`, `:853-950`; `test/QuoterExactNetOut.t.sol`). The scalar is also the smaller of the walk and the figure the Router funds, so the two producers cannot drift apart. It answers zero, and says nothing more, in the cases where the Router will not fill: a leg the Router refuses (a delta-altering or paused hook `RouterE(9)`, a key that does not derive `RouterE(11)`, a native side with no canonical WETH `RouterE(8)`), a taxed input into a concentrated leg (`RouterE(13)`), and a pool named twice in one hop. The last case: the Router runs the legs in turn and the second meets the pool the first moved, so a split priced side by side over-promises. The Solver merges a pool's legs and never plans it; a route built off-chain can. The route keeps its pool-math attestation, so what the Router compares against is unchanged (`:933-950`, `:955`). A pool that refuses the dry run keeps the plan's own claim, scaled and never raised. Write the venue's output as a function $f$ of its input with $f(0)=0$ and the plan's one known point $(b, f(b))$ with $b$ the leg's planned input (`_priceLeg`, `:1174-1185`). For a constant-product pool with reserves $x, y$ and retention $\gamma$, $$ f(a) \;=\; \frac{y\gamma a}{x + \gamma a}, \qquad f'(a) = \frac{y\gamma x}{(x+\gamma a)^2}, \qquad f''(a) = -\frac{2\,y\gamma^2 x}{(x+\gamma a)^3} < 0 . $$ A concentrated pool is one such curve on shifted reserves inside a tick range, and at a range boundary the marginal rate $\gamma$ times the price is continuous and only falls as the price moves against the trade, so $f$ is concave there too (derived; the code's comment states the same). For a concave $f$ with $f(0)=0$, $f(\lambda b) \ge \lambda f(b)$ for $0 \le \lambda \le 1$ (the curve lies above its chord), and $f(t)/t$ is non-increasing, so for $t > b$ the same rescale $t f(b)/b$ is an upper bound that overstates. The code therefore rescales linearly below $b$, where the result is the chord and understates, and caps the ratio at one above it (`mulDiv(expectedOut, min(legIn, base), base)`), so a refused leg may keep the plan's claim and never exceed it. Hop 0 is funded at what the committed legs sum to, so a capacity-clamped route is not dry-run at a size the Router will never spend. This is the Quoter's preview-side instrument; the surface that binds is the in-frame re-derivation. ### §12.2 How a quote ages A quote is a promise about a future block. The study takes it the way an integrator does (`previewAndEncode` returns the preview and the calldata), lets the world move (zero to three trades by someone else through the route's first pool, the shallow one, each up to 3 % of the shallow reserve, all in the user's direction so every one of them hurts), lets zero to ten seconds pass, and executes the calldata unchanged. 240 samples on a three-token universe of constant-product mocks (A, B = bridge coin, C; direct into the bridge, two hops through it, two hops the other way), every outcome classified (`test/QuoteDelayStatistics.t.sol`, `N = 240`). A sample for which the encode door returns no bytes is counted as "no quote", and the test requires fewer than a tenth of the samples to be so. The tables below were measured in CI at 969bcc6: of the 240 samples, none was without a quote. | Drift between quote and execution | Samples | Settled | Refused by the floor (`RouterE(5)`) | Delivered / predicted, mean | min | |---|---|---|---|---|---| | none | 64 | 64 | 0 | 10,000 bps | 10,000 | | 1 – 100 bps | 43 | 43 | 0 | 9,952 bps | 9,803 | | over 100 bps (up to 900) | 133 | 102 | 31 | 9,966 bps | 9,653 | | Delay between quote and execution | Samples | Settled | Refused (`RouterE(5)`) | Delivered / predicted, mean | min | |---|---|---|---|---|---| | 0 s | 17 | 15 | 2 | 9,989 bps | 9,857 | | 1 – 5 s | 99 | 89 | 10 | 9,959 bps | 9,653 | | 6 – 10 s | 124 | 105 | 19 | 9,983 bps | 9,659 | ![FIG-8 — How a quote ages](https://blazephoenix.xyz/whitepaper/figs/v2.4/fig-8.svg) *FIG-8 — How a quote ages: settled and refused samples by drift bucket, with the mean delivered/predicted ratio of each bucket's settled samples; the same 240 samples bucketed by delay show no trend.* Time does not move a quote; drift does. Asserted on every sample: a drift-free quote settles at every delay and delivers at least its own net prediction (64 of 64); a settlement never delivers below the floor the preview attested; there is no third outcome. After the deadline (`deadline = now + 5`, executed at `+10`) 20 of 20 are refused with the deadline's own code, `RouterE(4)`, and none settles (`test_QuoteExecutedAfterItsDeadline_IsRefusedWithCode4`). Under up to 1 % of adverse drift every quote still fills, within 2 % of its prediction; above 1 % (up to three trades of 3 % each) the floor refuses about one in four (31 of 133) rather than fill it below the attested output, and the fills land within 3.5 % of the prediction: the sandwich curve of §14 seen from the quote's side. (Percentages are the table's own ratios, read from its minima: the lowest fill, 9,653 bps, is 3.47 % under its prediction.) **Live Base** (`test/fork/QuoteDelayFork.t.sol`, 1,000 USDC → WETH, real pools, the protocol deployed on a fork at the current block): executed 0, 3, 6 and 10 s later with nothing else moving, the quote delivered exactly its prediction all four times. With 10,000 · 50,000 · 200,000 · 1,000,000 · 5,000,000 USDC traded ahead of it through the same route and the stale calldata executed 10 s later, all five settled inside the floor at 9,999 · 9,998 · 9,994 · 9,974 · 10,000 bps of the prediction: a million dollars ahead of a thousand costs the thousand a quarter of a percent, and the five-million trade routed through pools the thousand-dollar route does not touch. The distributions above are over mocks; live Base gives reach on one pair at one block, not a distribution. These fork figures were measured at 8949a9d on 2026-09-05 (Version 2.3 measurement). ### §12.3 What a quote costs through the ABI Gas measured around the external call, forty sizes each on the three-token universe (`test/QuoterGasStatistics.t.sol`). Measured in CI at 969bcc6; the live-Base figures of the 2.3 are not carried over. | World | `previewPlan` mean | min | max | σ | `previewAndEncode` mean | σ | |---|---|---|---|---|---|---| | mocks, discovery: the pair known to the factory only, one pool found | 148,772 | 140,519 | 151,081 | 1,871 | 196,957 | 2,022 | | mocks, fresh registry: three seeded pools priced | 362,856 | 350,680 | 365,600 | 2,952 | 412,921 | 3,353 | `batchQuote` of ten entries on mocks: 3,299,195 gas, 329,919 per entry. The fresh-registry mock costs more than discovery because it prices three pools where discovery found one; a quote is an `eth_call` an integrator never pays for on chain. ### §12.4 The in-frame budgets The Router's automatic door runs the same search under a fixed budget, so the plan is a function of the state and never of the gas the caller brought. `SOLVE_GAS = 14,700,000` (`Core:2521`) is $2^{24}$ (the per-transaction cap of EIP-7825, 16,777,216) less about 2.08 M kept for the pull, the execution and the self-call [derived from the code's comment, `Core:2511-2521`]. The Solver's capacity walk runs on what the search leaves, never more than `WALK_CAP = 8,000,000` (`Core:2531`): $$ W \;=\; \min\!\Big(\tfrac{63}{64}\,(S - s - 20{,}000),\;\; \mathrm{WALK\_CAP}\Big), \qquad S = \mathrm{SOLVE\_GAS} - 1{,}200, $$ with $s$ the gas the search itself spent and 20,000 kept for the splice (`Solver:309-341`). A walk's cost is the venue's choice (each read is capped at `GAS_CAP = 100,000`, `Core:215`), so without a ceiling a pair's held books could burn all of `SOLVE_GAS` and leave the automatic door too little to settle. The code records the two bounds that put the cap where it is: 4,850,000 is the least a live mainnet V4 row's rebuild must be handed (4,800,000 is not enough), and 11,510,000 the most with which four books that burn their whole `GAS_CAP` still settle at the door (11,560,000 does not): `WALK_CAP` sits between them (`Core:2523-2531`, `test/CapacityWalkBudget.t.sol`). A solve entered on less than $S$, or whose search left less than 20,000 of it, stops with empty revert data (`RouterE(17)` at the automatic door), never with a different plan; the quote door enters on more and hands the walk the same $W$. ## §13 Fee policy: the two regimes and the Surplus Rule *Plain:* the protocol takes 0.28 % once, from one measured amount, in a coin the treasury wants to hold, and counts that it did. *Precise:* `PROTOCOL_FEE_BPS = 28` is a compile-time constant in the Core (`Core:426`) with no setter anywhere in the deployed bytecode; the fee is `mulDivUp(base, 28, 10,000)` — rounded up, so a zero fee is unreachable for any non-zero base — split `TREASURY1_SHARE = 3,000` bps to the first treasury and the remainder to the second (`Router:149`; computed as `fee − t1`, so the two always sum to the fee with no dust, `_payFee`, `Router:794-803`). The rate and the split are constants. The two treasury addresses are storage: the control key can re-point them (`setTreasuries`) until it renounces control for ever (`renounceControl`), and each payee can move only its own slot (`moveTreasury`), also after renouncement. No key can raise the rate against a trader and no key can lower it for a favoured integrator: the fee question was answered at compile time and removed from the list of things a key can do. ### §13.1 Where the fee is charged: two regimes, both named The rule is one sentence: **charge once, on the first bridge coin the Router holds.** The Router asks one producer, `BPC.feeCalendar` (`Core:439`), which scans the route for the first hop whose input token is a registered bridge, in hop order — that hop is `feeHop` — and charges 28 bps of that hop's *measured* input. On hop 0 the base is the measured pull capped by what the route committed; on a later hop it is the Router's balance of the bridge coin above its foreign baseline *and* at most what the previous hop's legs measured, the quantity already resistant to fee-on-transfer and to stray balances. The Router charges nothing else on that route. A single-hop route whose destination is itself a bridge coin (TOKEN → WETH) charges on the output instead, after the floor check (`feeOnOut`, `paysOnInput`, `Core:448-453`): the floor validates swap quality, the protocol's cut comes out of the already-validated amount, and the user's minimum is compared against what they actually receive. This is the **anchored regime**. Why on the bridge and not on the destination: the bridges are WETH and USDC, and the treasury receives a liquid coin it wants to hold instead of dust of whatever tail token is the destination. Why on hop 1's input and not hop 0's output: they are the same token and the same amount, but hop 1's input is measured by the real balance, which is the measurement the Router already makes. The rule has a second regime. A hand-built route through pools the registry would not hold, with no bridge coin as any hop's input, never finds a `feeHop`; the predicate that charges is then true for *every* hop, and each hop pays 28 bps on its own measured input. This is the **exhaustion regime**, and it is a deliberate rule: charging such a route once, on hop 0, reopens the escape the exhaustion policy exists to close — a value-less first hop carries the fee spot onto dust and the real hop pays nothing (`test/FeeEscapeViaJunkPrefix.t.sol`). There is no index at which to insert dust that escapes every hop, which is what "immunity by exhaustion" means. The Solver builds every multi-hop route through registered bridges, so a Solver-built route always pays exactly once; the exhaustion regime is what a caller meets when they route around the registry, and the Quoter models it (it charges once per hop when no hop input is a bridge, once otherwise), so the preview and the delivery agree in both regimes (`test/ExhaustionRegimePreviewParity.t.sol`). The fee is pushed to each treasury with capped gas (`FEE_GAS = 150,000`, `Router:212`), so a treasury address or a fee token that refuses the transfer cannot stop a token from trading. A share the token refuses does not revert the swap: it is booked to its slot (`owed`), stays in the Router, is excluded from every balance a swap reads in that transaction, and is claimed later by the slot's holder (`claimFee`). The fee is charged either way. What counts as "paid" is measured, never taken from the token's answer: the Router's own loss and the payee's gain are both read, the larger witness is what reached the payee, and only the remainder is booked, so a claim never pays a share twice. ![FIG-9 — The two fee regimes as the Router decides them](https://blazephoenix.xyz/whitepaper/figs/v2.4/fig-9.svg) *FIG-9 — The two fee regimes as the Router decides them: scan the hops for the first bridge-coin input; anchored routes pay once at that hop (or on the output of a direct route into a bridge coin); routes with no bridged input pay once per hop; the ledger counts and refuses zero, and refuses two on an anchored route.* ### §13.2 The commitment has one producer, and the contract counts Two seals accompany the regimes. The sum of a hop's declared leg inputs — the fee base at hop 0 and the scale's denominator — is computed by one function, `_legSum` (`Router:687`): one number, one producer. And the fee ledger. `_payFee`, the one function that transfers the fee, counts into a transient slot (`TSLOT_FEE`, `Router:199`); every settlement reads the slot once, refuses a delivery that paid nothing (`RouterE(15)`, `Router:1660`) and, on an anchored route, a second payment (`RouterE(16)`, `Router:1661`), then clears it for the next swap in the same transaction. The claim: a settlement pays the fee, and pays it once where the rule says once. The enforcement site: the Router itself, at run time, on every settlement, on top of the review-time checks of §13.4. A fee at or above the amount it is charged on reverts (`RouterE(8)`), and a fee charged in hop 0 of a cyclic route reduces the route's output cap, saturated, so the cap the floor sees is the cap after the fee. ### §13.3 The Surplus Rule The **Surplus Rule** is the alignment argument of the fee design, stated as the code implements it: the protocol's take is 28 bps of one measured base, once on an anchored route and once per hop on an exhausted one, and there is no term anywhere in settlement that scales with the difference between what was quoted and what was delivered. Where the base is an input — every multi-hop route and every direct route whose destination is not a bridge coin — the output is untouched: everything the pools deliver above the quote reaches the recipient in full, and the fee cannot rise because a fill came in favourable. Where the base is the output — a direct route into a bridge coin — the fee is 28 bps of the gross delivery, surplus included, and nothing more. The axis on which an aggregator is most tempted to skim is the gap between quote and fill; this design gives that gap no fee term at all, so the headline rate is the true and only rate. The base is never read from calldata: `route.totalOut` reaches the Router as a stranger's claim and is read by nothing (`test_FeeBase_IgnoresLiedAboutTotalOut`). **Worked example 5 — the two regimes on one route.** Bridges are {WETH, USDC}; the trader sells 10,000 A. *Anchored, two hops.* A → WETH → B. Hop 0 is not charged (its input A is not a bridge). Hop 0's pools pay out 5.000 WETH, measured as the Router's WETH balance above its foreign baseline. `feeHop` = 1: the fee is $\lceil 5.000 \times 28 / 10{,}000 \rceil = 0.014$ WETH, split 0.0042 to the first treasury and 0.0098 to the second, and hop 1 spends 4.986 WETH into B. One `Fee` event; the ledger reads 1 and is satisfied; the preview deducted 28 bps once. *Anchored, direct into a bridge.* A → WETH in one hop. Nothing is charged on the input. The pools deliver 5.000 WETH gross; the floor is checked on 5.000; then the output-side fee $\lceil 5.000 \times 0.0028 \rceil = 0.014$ WETH is paid and 4.986 WETH is delivered; `userMinOut` is compared with 4.986. One `Fee` event, denominated in the output token. *Exhaustion, two hops.* A → C → B where none of A, C or B is a bridge — a route no Solver builds. Hop 0 pays $\lceil 10{,}000 \times 0.0028 \rceil = 28$ A and sends 9,972 A into its pools, which pay out 2,000 C; hop 1 pays $\lceil 2{,}000 \times 0.0028 \rceil = 5.6$ C and sends 1,994.4 C into B. Two `Fee` events; the ledger reads 2 with no `feeHop`, so `RouterE(16)` does not apply; the effective rate is $1 - 0.9972^{2} = 55.9$ bps, and the preview said so. ### §13.4 The fee, measured from outside the Router `test/FeeSeals.t.sol` reads none of the Router's numbers: the fee token comes from the rule and the bridge list, the base from the pools' balance deltas (what left the Router into the fee hop, or what the previous hop's pools paid out) or the recipient's, the fee from the treasuries' deltas, the count from the `Fee` events — over every shape the Router accepts (one or two hops; bridge in no, first, middle or last position; one or two legs per hop), fuzzed amounts from $10^{12}$ to $10^{21}$ wei, the Router holding nothing after every settlement. The table of shapes is asserted to reach the Router's hop ceiling and no further: a new ceiling turns it red until the shapes of the new depth are written. The fuzzed test runs under the default profile, 256 runs per CI pass (`foundry.toml`). | Route shape | Regime | Where the fee lands | Measured | |---|---|---|---| | A → B (neither a bridge) | exhaustion, one hop | hop 0's input, once | fee = ⌈28 bps × input⌉, one event | | W → A (bridge in) | anchored | hop 0's input | same | | A → W (bridge out, direct) | anchored, output side | the output | fee = ⌈28 bps × gross output⌉, delivered = gross − fee | | A → C → B (no bridge) | exhaustion, two hops | each hop's measured input | two events | | W → A → B | anchored at hop 0 | hop 0's input | one event | | A → W → B | anchored at hop 1 | the bridge coin hop 0 produced | one event, ⌈28 bps × what hop 0's pools paid out⌉ | | A → C → W (bridge only as output of two hops) | exhaustion | each hop's input | two events | **How often the fee tests notice a defect** is measured rather than assumed (`docs/assurance/fee-seal-detection.json`): each fee mutant — the regime predicate moved either way, the commitment producer, the doubled fee, the fee never charged on the input, the fee charged on both sides — is run under twenty fuzz seeds per fuzzed test and once per deterministic test; the detection rate is reported with a Wilson 95 % interval. The figures below were measured on 2026-09-05 (Version 2.3), before the hop ceiling fell to two. | Mutant | FeeSeals fuzz | Router campaign (2 hops, 2 legs) | Covering array t = 2 | Junk-prefix escape | Exhaustion preview parity | |---|---|---|---|---|---| | exhaustion charges hop 0 only | 20/20 [0.84, 1.00] | 20/20 [0.84, 1.00] | no | yes | yes | | exhaustion skips hop 0 | 20/20 [0.84, 1.00] | 20/20 [0.84, 1.00] | no | yes | yes | | commitment counts the first leg only | 20/20 [0.84, 1.00] | 20/20 [0.84, 1.00] | no | no | no | | fee doubled | 20/20 [0.84, 1.00] | 20/20 [0.84, 1.00] | yes | yes | yes | | input-side fee never charged | 20/20 [0.84, 1.00] | 20/20 [0.84, 1.00] | no | yes | yes | | fee charged on both sides | 20/20 [0.84, 1.00] | 20/20 [0.84, 1.00] | no | yes | yes | ![FIG-10 — Detection of each fee mutant by each test](https://blazephoenix.xyz/whitepaper/figs/v2.4/fig-10.svg) *FIG-10 — Detection rate of each fee mutant by each test, as a heat map: kills over runs with the Wilson interval.* Read across a row: which tests see this defect. Read down a column: what a test can and cannot see. The Router campaign walks two hops and splits hop 0 across two pools, with a bridge coin in the universe, so one campaign holds every regime. The covering array is built to cross the regime boundary, and every one of its rows crosses a bridge; it is the test for the doubled fee, and the other columns are what see the rest. The mutation guard admits a mutant only where a named test kills it, and runs the named test and the campaign both. Summing the section in the form this paper uses — claim, enforcement site, limit: nobody can move the rate or the split, because both are constants with no setter in the deployed bytecode; a caller cannot shrink the fee by understating a quote, because the base is a measured balance and `route.totalOut` is read by nothing; a caller cannot dodge the fee with a value-less prefix, because a route with no bridged input pays on every hop; a settlement cannot pay nothing or pay twice on an anchored route, because the Router counts and refuses; and no token's refusal of a fee share can stop a trade, because the share is booked to its slot and claimed, never lost. The limit: the treasury addresses are storage, re-pointable by the control key until it is renounced and by each payee for its own slot; the rate, the split and the count are not.