From 02667cb36ea10672e8316b9fe1629750d467ba5b Mon Sep 17 00:00:00 2001 From: 2NNatural Date: Fri, 28 Aug 2026 18:15:01 -0700 Subject: [PATCH] Align Day V4 SLP valuation with Balancer ECLP oracle --- AGENTS.md | 2 +- .../pool-design/simulation/route.test.ts | 12 +- components/day-v3/DayV3Backtest.tsx | 10 +- components/day-v3/DayV3Deployment.tsx | 2 +- components/day-v3/DayV3DeploymentTarget.tsx | 4 +- components/day-v3/DayV3ExitModel.test.tsx | 33 +- components/day-v3/DayV3ExitModel.tsx | 4 +- components/day-v3/DayV3Goals.tsx | 7 +- components/day-v3/DayV3QuoteAsset.tsx | 23 +- components/day-v3/DayV3RestockCheck.tsx | 43 +- components/day-v3/DayV3Summary.tsx | 114 ++-- components/day-v3/url-state.test.ts | 8 +- components/day-v3/useDayV3PoolDesign.ts | 14 +- .../day-v3/useDayV3SimulationPoolDesign.ts | 23 +- docs/DAY_V3_DEPLOYMENT_PARITY_AUDIT.md | 15 +- docs/NEW_DAY_SIMULATOR.md | 2 +- lib/day-markets/acred/market.json | 20 +- lib/day-markets/blockhouse/market.json | 20 +- lib/day-markets/dualmint/market.json | 20 +- lib/day-markets/infinifi/market.json | 20 +- lib/day-markets/makina-dbit/market.json | 20 +- lib/day-markets/makina-deth/market.json | 20 +- lib/day-markets/makina-dusd/market.json | 20 +- lib/day-markets/makina-usdshfmk/market.json | 20 +- lib/day-markets/pareto-falconx/market.json | 20 +- lib/day-markets/reusde/market.json | 20 +- lib/day-markets/susdai/market.json | 20 +- lib/day-simulator-template/runtime.test.ts | 6 +- lib/day-v3/day-v3.test.ts | 18 +- lib/day-v3/handoff.ts | 2 +- lib/day-v3/mode-state.test.ts | 1 + lib/day-v3/model-state.ts | 2 +- lib/day-v3/pool-design.ts | 32 +- lib/day-v3/restock-arbitrage.ts | 2 +- lib/day-v3/simulation-pool-design.test.ts | 34 +- lib/day-v3/simulation-pool-design.ts | 20 +- lib/day-v3/types.ts | 4 +- lib/day-v3/url-state.ts | 27 +- lib/day/engine/eclp.ts | 622 +++++++++++++++++- lib/day/engine/engine.test.ts | 112 +++- lib/day/engine/engine.ts | 28 +- lib/day/engine/vectors/contract-lock.json | 2 +- lib/day/engine/vectors/golden.json | 2 +- scripts/day-simulator/template-lock.json | 14 +- scripts/day-v3/model-output-parity.test.mjs | 55 +- scripts/day-v3/v2-output-regression.test.ts | 7 +- 46 files changed, 1256 insertions(+), 270 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6bb58e5..11fc401 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ Changes to `lib/try/engine.ts`, `lib/try/backtest.ts`, `components/simulator/`, 5. Pareto FalconX v3 is the grounded default. Fonts, colors, borders, spacing, charts, diagrams, and behavior remain shared and byte-locked; an authorized market may use supported section-visibility or copy overrides without forking the component. 6. Never guess provenance, price type, fee treatment, desired yield ranges, hidden parameters, or customization authority. Incomplete intake must remain `unknown` and fail verification. 7. Calibrate with `npm run day-sim:calibrate -- `; never calculate tranche outputs independently. -8. Run `npm run day-sim:verify -- ` and `npm run day-sim:certify -- ` before requesting publication. Certification must pass all 74 Solidity vectors, tests, lint, and build. +8. Run `npm run day-sim:verify -- ` and `npm run day-sim:certify -- ` before requesting publication. Certification must pass all 78 Solidity vectors, tests, lint, and build. 9. If an explicitly authorized customization is not yet supported, extend the shared manifest-driven customization schema with tests; do not create a one-off market component. Updating the template lock is a maintainer action after full certification. 10. Do not create or merge a PR until verification and certification pass and the user approves the browser preview. 11. Erasure annotations consume the accountant's structured erased amount and pre-refill Junior valuation. Never parse event copy or size erasure against a same-timestamp refill. diff --git a/app/api/day-v3/pool-design/simulation/route.test.ts b/app/api/day-v3/pool-design/simulation/route.test.ts index 4abb2dc..c2c07a9 100644 --- a/app/api/day-v3/pool-design/simulation/route.test.ts +++ b/app/api/day-v3/pool-design/simulation/route.test.ts @@ -8,14 +8,14 @@ import { import { resetDayV3SimulationProxyForTests } from "@/lib/day-v3/pool-proxy-cache"; const requestBody = JSON.stringify({ - schemaVersion: "1.0", + schemaVersion: "1.1", goals: { protectedDrawdownPct: 15, recoveryDays: 20, immediateExitSharePct: 10, minimumProceedsPer100: 95, }, - context: { sourceApyPct: 6 }, + context: { sourceApyPct: 6, swapFeeBps: 10 }, }); function request(body = requestBody, declaredLength?: number) { @@ -99,8 +99,8 @@ async function main() { ); return new Response( JSON.stringify({ - schemaVersion: "1.0", - modelVersion: "day-v3-eclp-goal-solver-1.1.0", + schemaVersion: "1.1", + modelVersion: "day-v3-eclp-goal-solver-1.2.0", mode: "simulation", status: "infeasible", recommendation: null, @@ -131,8 +131,8 @@ async function main() { await heldUpstream; return new Response( JSON.stringify({ - schemaVersion: "1.0", - modelVersion: "day-v3-eclp-goal-solver-1.1.0", + schemaVersion: "1.1", + modelVersion: "day-v3-eclp-goal-solver-1.2.0", mode: "simulation", status: "infeasible", recommendation: null, diff --git a/components/day-v3/DayV3Backtest.tsx b/components/day-v3/DayV3Backtest.tsx index dfcfce4..84692e8 100644 --- a/components/day-v3/DayV3Backtest.tsx +++ b/components/day-v3/DayV3Backtest.tsx @@ -223,12 +223,10 @@ function DayV3Backtest({ ); // The engine is template code under the byte lock, so a pool assumption it - // cannot integrate is caught here rather than fixed there. Modeled fee income - // is `turnover x fee`, compounded every step: JBBB at 100x turnover and a - // 100% swap fee runs `pool.stable` to Infinity and the run throws - // `cannot convert non-finite number to WAD`, which took the page down. The - // fee bound below keeps real inputs well clear of that; this makes it - // impossible to reach by any route at all. + // cannot integrate is caught here rather than fixed there. Contract-valid + // fees can still be economically extreme when combined with high turnover; + // surface a bounded backtest error instead of letting the history take down + // the page. const [result, resultError] = useMemo< [DayBacktestResult | null, string | null] >(() => { diff --git a/components/day-v3/DayV3Deployment.tsx b/components/day-v3/DayV3Deployment.tsx index 44fbe1d..bca7765 100644 --- a/components/day-v3/DayV3Deployment.tsx +++ b/components/day-v3/DayV3Deployment.tsx @@ -621,7 +621,7 @@ function DayV3Deployment({ One relative design, normalized to $100 Senior. Deployment must - revalidate it against the live template; absolute funding stays open + revalidate it against the selected market pool; absolute funding stays open until deployment has a notional and initialization policy. diff --git a/components/day-v3/DayV3DeploymentTarget.tsx b/components/day-v3/DayV3DeploymentTarget.tsx index fd34c65..7d560c4 100644 --- a/components/day-v3/DayV3DeploymentTarget.tsx +++ b/components/day-v3/DayV3DeploymentTarget.tsx @@ -110,8 +110,8 @@ export default function DayV3DeploymentTarget({ className="text-[10.5px] leading-relaxed text-[var(--tertiary)]" id="day-v3-deployment-target-message" > - {message} Selecting a target resolves its live swap fee and validates - the pool design. No fallback fee is used. + {message} Selecting a target resolves the canonical market-pool fee + and validates the pool design. No fallback fee is used. diff --git a/components/day-v3/DayV3ExitModel.test.tsx b/components/day-v3/DayV3ExitModel.test.tsx index 96724be..1a2e110 100644 --- a/components/day-v3/DayV3ExitModel.test.tsx +++ b/components/day-v3/DayV3ExitModel.test.tsx @@ -51,7 +51,7 @@ assert.match(resolvedMarkup, /Maximum discount the pool has/); assert.match(resolvedMarkup, /1000 bps/); assert.match(resolvedMarkup, /500 bps/); assert.match(resolvedMarkup, /380 bps/); -assert.match(resolvedMarkup, /Proceeds: \$9\.62 after the live swap fee/); +assert.match(resolvedMarkup, /Proceeds: \$9\.62 after the canonical pool swap fee/); // The swap fee, minimum liquidity and maximum discount are pool terms, not // results of this comparison, and the cards that depend on them state them. assert.doesNotMatch(resolvedMarkup, /Swap fee: /); @@ -108,7 +108,7 @@ const unresolvedMarkup = renderToStaticMarkup( assert.match(unresolvedMarkup, /data-model-state="resolving"/); assert.match( unresolvedMarkup, - /Refreshing the live template and recalculating this model/, + /Refreshing the canonical pool and recalculating this model/, ); assert.doesNotMatch(unresolvedMarkup, /Proceeds:/); @@ -367,14 +367,14 @@ assert.match( assert.doesNotMatch(goalsMarkup, /of \$100/); assert.doesNotMatch(goalsMarkup, /See .*impact/i); -// The pool's swap fee is the issuer's to set, with an inherited default. An +// The pool's swap fee is the issuer's to set, with a market-declared default. An // empty field is labelled for what it is — the fee the model is assuming — and // a typed one is never presented as the template's own policy. assert.match( goalsMarkup, /What swap fee should the pool charge on a sale\?/, ); -assert.match(goalsMarkup, /Use the live fee/); +assert.match(goalsMarkup, /Use the market fee/); assert.match(goalsMarkup, /Model assumption/); assert.doesNotMatch(goalsMarkup, /Manual override/); @@ -383,13 +383,10 @@ const handSetFeeMarkup = renderToStaticMarkup( ); assert.match(handSetFeeMarkup, /Manual override/); assert.doesNotMatch(handSetFeeMarkup, /Live template|Product policy/); -// These two bounds are the only guard against `previewSecondarySell` throwing -// INVALID_SWAP_FEE inside a render-time memo with no error boundary above it. +// The field mirrors Gyro's inclusive contract bounds; render-time engine errors +// remain surfaced by the model/backtest error paths. assert.match(handSetFeeMarkup, /min="0\.01"/); -// 10% is an order of magnitude above any pool anyone runs, and well clear of -// the corner where turnover x fee compounds modeled income past what the engine -// can hold — measured: JBBB threw at 100x turnover and a 100% fee. -assert.match(handSetFeeMarkup, /max="1000"/); +assert.match(handSetFeeMarkup, /max="10000"/); const protectionStart = goalsMarkup.indexOf('id="day-v3-protection-inputs"'); const observationMode = goalsMarkup.indexOf('aria-label="Observation mode"'); @@ -514,8 +511,8 @@ assert.match(restockMarkup, /Margin above restock hurdle/); assert.doesNotMatch(restockMarkup, /cost of capital/i); assert.doesNotMatch(restockMarkup, /break[- ]even/i); -// A live template solved its own band; saying the payout floor set it named the -// wrong pool, and it was named beside quotes taken off the template's curve. +// A canonical pool solved its own band; saying the payout floor set it named the +// wrong pool, and it was named beside quotes taken off the canonical curve. assert.match( renderToStaticMarkup( , ), - /the live template solved for/, + /the canonical pool solved for/, ); -// A sale the pool cannot absorb is priced for the slice that fills, so it is -// described as that slice rather than as the exit the issuer promised. +// A sale the pool cannot absorb is shown at its capacity boundary, while the +// copy makes clear that the requested exact-input trade would revert atomically. const partialMarkup = renderToStaticMarkup( , ); -assert.match(partialMarkup, /the part that fills/); -assert.match(partialMarkup, /only \$4\.00 fits in the pool/); +assert.match(partialMarkup, /maximum atomic order below NAV/); +assert.match(partialMarkup, /requested \$10\.00 exit is too large/); +assert.match(partialMarkup, /largest order this pool can accept is \$4\.00/); +assert.match(partialMarkup, /not partially filled/); // A market quoted in ETH never gets a dollar sign in front of a number of ETH. const ethMarkup = renderToStaticMarkup( diff --git a/components/day-v3/DayV3ExitModel.tsx b/components/day-v3/DayV3ExitModel.tsx index db00647..877967d 100644 --- a/components/day-v3/DayV3ExitModel.tsx +++ b/components/day-v3/DayV3ExitModel.tsx @@ -210,7 +210,7 @@ export default function DayV3ExitModel({ ) : exit.status === "resolving" || exit.message ? (

{exit.status === "resolving" - ? "Refreshing the live template and recalculating this model…" + ? "Refreshing the canonical pool and recalculating this model…" : exit.message}

) : null} @@ -222,7 +222,7 @@ export default function DayV3ExitModel({ Proceeds: {dollars(exit.proceeds, 2)}{" "} {illustrative ? "after the modeled swap fee" - : "after the live swap fee"} + : "after the canonical pool swap fee"} ) : null} {/* diff --git a/components/day-v3/DayV3Goals.tsx b/components/day-v3/DayV3Goals.tsx index e1f315d..b7d0ef6 100644 --- a/components/day-v3/DayV3Goals.tsx +++ b/components/day-v3/DayV3Goals.tsx @@ -47,7 +47,7 @@ export type DayV3ExitView = { lowestPayoutPer100: MaybeNumber; slpPer100: MaybeNumber; restockPoint: MaybeNumber; - /** Time/carry and external-conversion hurdle before the live pool fee. */ + /** Time/carry and external-conversion hurdle before the market pool fee. */ restockOperationalHurdleBps: MaybeNumber; /** All-in hurdle used by the canonical pool-design calculation. */ restockHurdleBps: MaybeNumber; @@ -130,6 +130,7 @@ export default function DayV3Goals({ poolPremiumEdited = false, poolTurnoverPerYear, defaultPremiumBps, + defaultSwapFeeBps, onPoolPremiumBps, poolPremiumBps, restingSeniorWeight, @@ -169,9 +170,10 @@ export default function DayV3Goals({ quoteAssetYieldPct: MaybeNumber; recoveryDays: MaybeNumber; recoveryMode: "none" | "window" | null; - /** The issuer's own pool fee. `null` inherits the live template's. */ + /** The issuer's per-market pool fee. `null` uses the market declaration. */ swapFeeBps: MaybeNumber; defaultPremiumBps: MaybeNumber; + defaultSwapFeeBps?: number; onPoolPremiumBps: (value: number | null) => void; poolPremiumEdited?: boolean; poolPremiumBps: MaybeNumber; @@ -510,6 +512,7 @@ export default function DayV3Goals({ label={quoteAssetLabel} onLabel={onQuoteAssetLabel} defaultPremiumBps={defaultPremiumBps} + defaultSwapFeeBps={defaultSwapFeeBps} onPoolPremiumBps={onPoolPremiumBps} poolPremiumEdited={poolPremiumEdited} poolPremiumBps={poolPremiumBps} diff --git a/components/day-v3/DayV3QuoteAsset.tsx b/components/day-v3/DayV3QuoteAsset.tsx index afa4c50..c86efa4 100644 --- a/components/day-v3/DayV3QuoteAsset.tsx +++ b/components/day-v3/DayV3QuoteAsset.tsx @@ -5,6 +5,7 @@ import { useState } from "react"; import DayV3Button from "@/components/day-v3/DayV3Button"; import DayV3NumberField from "@/components/day-v3/DayV3NumberField"; import { DAY_V3_POOL_PREMIUM_BPS_RANGE } from "@/lib/day-v3/pool-curve"; +import { DAY_V3_POOL_SWAP_FEE_BPS_RANGE } from "@/lib/day-v3/pool-design"; import DayV3Origin, { type DayV3VisibleOrigin, } from "@/components/day-v3/DayV3Origin"; @@ -41,6 +42,7 @@ export default function DayV3QuoteAsset({ label, onLabel, defaultPremiumBps, + defaultSwapFeeBps, onPoolPremiumBps, poolPremiumEdited, poolPremiumBps, @@ -57,6 +59,8 @@ export default function DayV3QuoteAsset({ onLabel: (value: string) => void; /** What the pool rests on today, in bps, so an empty field can say so. */ defaultPremiumBps: number | null; + /** The selected market's declared fee, used to distinguish a default from an edit. */ + defaultSwapFeeBps?: number; onPoolPremiumBps: (value: number | null) => void; /** Whether the displayed premium is an issuer edit or a loaded default. */ poolPremiumEdited: boolean; @@ -77,7 +81,10 @@ export default function DayV3QuoteAsset({ // either until one resolves, so it is labelled for what it is: the fee the // model is assuming. A hand-set fee is always the issuer's own override. const feeOrigin: DayV3VisibleOrigin = - swapFeeBps === null ? "model-assumption" : "manual-override"; + swapFeeBps === null || + (defaultSwapFeeBps !== undefined && swapFeeBps === defaultSwapFeeBps) + ? "model-assumption" + : "manual-override"; // A parent reset (switching source, clearing the exit) replaces the label. // React's adjusted-state pattern re-seeds the draft without a second render. if (!Object.is(draft.source, label)) { @@ -195,8 +202,7 @@ export default function DayV3QuoteAsset({ onChange={onPoolPremiumBps} origin={poolPremiumEdited ? "manual-override" : "model-assumption"} // The premium actually in force, whatever set it — the market's own - // declared curve, a live template, or the modeled default. Calling it - // "the market's own" was false whenever it was not. + // declared curve, a canonical pool, or the modeled default. placeholder={ defaultPremiumBps === null ? "Use the modeled premium" @@ -216,15 +222,12 @@ export default function DayV3QuoteAsset({
= 0; const selectedPays = resolved && check.status === "profitable"; const unpriced = resolved && check.status === "no-selected-sale"; - // The live template sizes the pool to the promised sale, so the deepest point - // and the selected sale usually coincide. - // A quote for less than the sale is a quote for a different trade. - const partialFill = + // The engine exposes the largest quoteable slice so the reader can see the + // capacity boundary. Balancer exact-input swaps are atomic: a request larger + // than that slice reverts rather than partially filling. + const atomicOrderTooLarge = resolved && selectedUnfilledPer100 !== null && selectedUnfilledPer100 > 0.005 && @@ -441,8 +440,12 @@ export default function DayV3RestockCheck({ unpriced ? " The selected sale has not been priced yet, so it is not yet known whether it reaches that depth on its own." : selectedPays - ? ` The ${partialFill ? `${amount(selectedFilledPer100, unit)} of the ${amount(selectedSalePer100, unit)} exit the pool can actually take` : `${amount(selectedSalePer100, unit)} exit you promised`} ${(check.selectedMarginBps ?? 0) < 0.5 ? "only just covers that" : `beats it by ${bps(check.selectedMarginBps)}`}, so the pool resets without waiting for a deeper seller.${partialFill ? ` The other ${amount(selectedUnfilledPer100, unit)} does not fill at any price, so nothing about it is priced here.` : ""}` - : ` The ${partialFill ? `${amount(selectedFilledPer100, unit)} of the ${amount(selectedSalePer100, unit)} exit the pool can actually take` : `${amount(selectedSalePer100, unit)} exit you promised`} only reaches ${bps(check.selectedDiscountBps)}, short of the restock hurdle, so one exit of that size does not attract a refill on its own.${partialFill ? ` The other ${amount(selectedUnfilledPer100, unit)} does not fill at any price.` : ""}` + ? atomicOrderTooLarge + ? ` The requested ${amount(selectedSalePer100, unit)} exit is too large for one atomic Balancer trade and would revert. The largest order this pool can accept is ${amount(selectedFilledPer100, unit)}; that smaller order ${(check.selectedMarginBps ?? 0) < 0.5 ? "only just covers the hurdle" : `clears it by ${bps(check.selectedMarginBps)}`}, so a max-size restock trade resets the pool. The excess ${amount(selectedUnfilledPer100, unit)} is not partially filled.` + : ` The ${amount(selectedSalePer100, unit)} exit you promised ${(check.selectedMarginBps ?? 0) < 0.5 ? "only just covers that" : `beats it by ${bps(check.selectedMarginBps)}`}, so the pool resets without waiting for a deeper seller.` + : atomicOrderTooLarge + ? ` The requested ${amount(selectedSalePer100, unit)} exit would revert because one Balancer trade is atomic. The largest order this pool can accept is ${amount(selectedFilledPer100, unit)}, and it only reaches ${bps(check.selectedDiscountBps)}, short of the restock hurdle. The excess ${amount(selectedUnfilledPer100, unit)} is not partially filled.` + : ` The ${amount(selectedSalePer100, unit)} exit you promised only reaches ${bps(check.selectedDiscountBps)}, short of the restock hurdle, so one exit of that size does not attract a refill on its own.` }`}

@@ -452,18 +455,20 @@ export default function DayV3RestockCheck({ before the answer existed anywhere on screen. */}

- One restock trade, per {stake100(unit)} of Senior bought + {atomicOrderTooLarge ? "One maximum atomic restock trade" : "One restock trade"}, per {stake100(unit)} of Senior bought

normalizeDayV3Defaults(market.defaults), [market.defaults], ); + // Some sample sources have a separate V3 issuer-design manifest (for + // example JBBB). Its fee is the selected market's declared pool fee even + // when the generic explorer market carries the shared starter value. + const marketDesignDefaults = dayV3MarketDefaults(market.id); + const declaredSwapFeeBps = + marketDesignDefaults?.swapFeeBps ?? defaults.swapFeeBps; // The custom design is normalized in dollars because every capital and exit // amount is quoted per $100 Senior. const returnUnit = customSource @@ -300,14 +306,18 @@ export default function DayV3Summary({ const [poolTurnoverPerYear, setPoolTurnoverPerYear] = useState( linked?.poolTurnoverPerYear ?? DAY_V3_DEFAULT_POOL_TURNOVER, ); - // What the pool charges to trade. Null is the only honest default: it means - // the live template's own fee decides, with the market's declared fee - // standing in until that template resolves. Naming a number here would - // invent a fee policy the issuer never chose. + // What the market's Gyro pool charges to trade. Null means the selected + // market's declared default; a number means the issuer explicitly supplied + // the per-market pool creation fee. Royco Day no longer inherits this value + // from TemplatePolicy. const [swapFeeBps, setSwapFeeBps] = useState( linked?.swapFeeBps ?? null, ); - const feeOverridden = swapFeeBps !== null; + // A value materialized from a listed market's manifest is still the market + // default, not an issuer override. Only a fee different from that declaration + // is sent as an explicit override in the local engine metadata. + const feeOverridden = + swapFeeBps !== null && swapFeeBps !== declaredSwapFeeBps; // The pool's balance point, set the way deployment sets it: by the maximum // premium. Empty starts with the model's loaded premium; a value here means // the issuer explicitly changed this field. Keeping those states separate @@ -358,6 +368,7 @@ export default function DayV3Summary({ const modeledSourceApyPct = sourceApyPct ?? 0; const modeledQuoteAssetYieldPct = quoteAssetYieldPct ?? 0; const modeledPoolTurnover = poolTurnoverPerYear ?? 0; + const requestedSwapFeeBps = swapFeeBps ?? declaredSwapFeeBps; const simulationDefaults = useMemo( () => ({ ...defaults, @@ -367,23 +378,21 @@ export default function DayV3Summary({ // at zero here, which is right for a plain stablecoin and silently wrong // for anything that accrues. stableYield: modeledQuoteAssetYieldPct / 100, - // Annual swap volume is the issuer's forecast too. At zero the live - // template fee still prices canonical execution quotes but contributes + // Annual swap volume is the issuer's forecast too. At zero the selected + // market pool fee still prices canonical execution quotes but contributes // no speculative fee income to SLP APY. poolTurnoverPerYear: modeledPoolTurnover, - // The shared template's disclosed simulation assumption, unless the - // issuer stated their own fee. A live RWA response replaces the - // assumption atomically when the exit design resolves; it cannot replace - // the issuer's answer, which is why that answer is applied here as well - // as through `engineOverrides`. - swapFeeBps: swapFeeBps ?? defaults.swapFeeBps, + // The simulation solver receives the same market-specific fee that the + // engine uses. An omitted field uses the selected market's declared + // default; it is never silently replaced by a template policy fee. + swapFeeBps: requestedSwapFeeBps, }), [ defaults, modeledPoolTurnover, modeledQuoteAssetYieldPct, modeledSourceApyPct, - swapFeeBps, + requestedSwapFeeBps, ], ); @@ -513,13 +522,11 @@ export default function DayV3Summary({ const activePoolDesign = useDayV3SimulationPoolDesign( poolDesignGoals, sourceApyPct, + requestedSwapFeeBps, ); - // A hand-set fee belongs in this gate. The canonical service solves the pool - // at the template's own fee and cannot be asked to solve it at another one: - // its request body is key-restricted, and its parser asserts that the - // returned fee, its `template-policy` origin, and the restock fee all equal - // the live policy. Reporting those outcomes beside a different fee would - // attribute a result to a pool that was never priced. + // Curve overrides still withhold the canonical recommendation because the + // service must re-solve geometry. A fee override does not: it is a first-class + // per-market input sent to the solver and echoed by its resolved policy. const hasPoolOverride = [ activeManualOverrides.minimumLiquidityPct, @@ -527,7 +534,7 @@ export default function DayV3Summary({ activeManualOverrides.depthAtNav, activeManualOverrides.maximumPremiumPct, activeManualOverrides.poolCapitalPer100, - ].some((value) => value !== null) || feeOverridden || premiumOverridden; + ].some((value) => value !== null) || premiumOverridden; const rawCanonicalPoolDesign = activePoolDesign.status === "resolved" || activePoolDesign.status === "resolving" @@ -550,9 +557,21 @@ export default function DayV3Summary({ c: fromWad(raw.c), s: fromWad(raw.s), lambda: fromWad(raw.lambda), + // Preserve the exact constructor/derived values returned by the pool + // design service. The engine uses these fixed-point fields to match + // Balancer's EclpLPOracle instead of re-deriving geometry from rounded + // display numbers. + fixedParams: raw, + derivedParams: rawCanonicalPoolDesign.recommendation.eclp.derivedParams, }; if ( - !Object.values(params).every(Number.isFinite) || + ![ + params.alpha, + params.beta, + params.c, + params.s, + params.lambda, + ].every(Number.isFinite) || params.alpha <= 0 || params.beta <= params.alpha || params.lambda <= 0 @@ -584,17 +603,15 @@ export default function DayV3Summary({ rawCanonicalPoolDesign && !hasPoolOverride && canonicalEngineOverrides ? rawCanonicalPoolDesign : null; - // What the pool is actually priced at, in the order that wins: the issuer's - // own fee, then the live template's, then the market's declared assumption. + // What the pool is actually priced at. The resolved policy must echo the + // requested per-market fee; while it is pending, use the same request value. const modeledSwapFeeBps = - swapFeeBps ?? - rawCanonicalPoolDesign?.policy.swapFeeBps ?? - defaults.swapFeeBps; + rawCanonicalPoolDesign?.policy.swapFeeBps ?? requestedSwapFeeBps; // Built by OMITTING keys rather than setting them `undefined`. Both the // structural run and the backtest merge this by spread, so an `undefined` // `eclpParams` would erase the market's own curve instead of leaving it be. // Overrides that redraw the curve itself, as opposed to policy sitting on top - // of it. A hand-set fee is policy: the template's geometry is still the right + // of it. A hand-set fee is policy: the canonical geometry is still the right // geometry, it is just being charged differently. A hand-set maximum discount, // depth or premium IS the geometry, and the canonical `eclpParams` would win // the spread below and silently discard it — the reader would drag "maximum @@ -622,7 +639,7 @@ export default function DayV3Summary({ lambda, }); } - // A live template's own curve is the real pool and always wins. + // A canonical pool's own curve is the real pool and always wins. if (canonicalEngineOverrides) return null; // So does the market's own declared curve, whenever it survives. // `buildDayMarketConfig` keeps `defaults.eclpParams` while the requested @@ -735,7 +752,7 @@ export default function DayV3Summary({ exitSharePct: modeledImmediateExitSharePct, minimumProceedsPer100, ...(premiumCurve ? { eclpParams: premiumCurve } : {}), - ...(swapFeeBps === null ? {} : { swapFeeBps }), + swapFeeBps: requestedSwapFeeBps, }), [ coveragePct, @@ -745,7 +762,7 @@ export default function DayV3Summary({ minimumProceedsPer100, modeledImmediateExitSharePct, premiumCurve, - swapFeeBps, + requestedSwapFeeBps, ], ); // The canonical service's own sizing wins when it has resolved — it prices @@ -756,9 +773,9 @@ export default function DayV3Summary({ : (liquidityRecommendation?.minimumLiquidity.value ?? exitGoalSizing?.minimumLiquidityPct ?? defaults.minLiquidity * 100); - // The band IS the pool's maximum discount — when the template resolves this + // The band IS the pool's maximum discount — when the canonical pool resolves this // reads its `maximumDiscountBps` directly. The fallback used the market's own - // fixed `eclpBandWidth`, so with no live template the payout floor shaped + // fixed `eclpBandWidth`, so with no canonical pool the payout floor shaped // nothing: an issuer could drag it from $99 to $50 and the pool, the exit // curve and the arbitrage economics would not move at all. Measured on the // shared engine, the band moves the deepest fill exactly as you would expect @@ -768,10 +785,10 @@ export default function DayV3Summary({ ? canonicalPoolRecommendation.fields.maximumDiscountBps.value / 100 : floorBandPct; // The maximum discount the engine ACTUALLY priced, which is not always the one - // above. `canonicalPoolRecommendation` is withheld by any pool override - // including a hand-set fee, but the canonical `eclpParams` keep pricing unless + // above. `canonicalPoolRecommendation` is withheld by a curve override, but + // the canonical `eclpParams` keep pricing unless // the override was to the curve — so a page that read `effectiveBandPct` there - // named the payout floor's band beside quotes taken off the template's curve. + // named the payout floor's band beside quotes taken off the canonical pool's curve. const pricedBand: { pct: number; source: "live-template" | "payout-floor" | "your-answer"; @@ -788,7 +805,7 @@ export default function DayV3Summary({ : { pct: floorBandPct, source: "payout-floor" }; // Defer one stable, complete accountant input rather than an inline object. - // The former version deferred the terms but read the live E-CLP and fee + // The former version deferred the terms but read the canonical E-CLP and fee // policy outside this snapshot. A newly resolved pool could therefore run // briefly with the previous 0% liquidity requirement (or a new goal with the // previous pool policy), producing combinations such as a funded SLP showing @@ -1569,7 +1586,7 @@ export default function DayV3Summary({ ? model.scenario.juniorApy * 100 : null, status: "recommended", - message: `${protectionRecommendation.reason}${feeOverridden ? ` The displayed return is priced at the ${swapFeeBps} bps pool fee set above, not the live market's.` : canonicalEngineOverrides ? " Current market fees are included in the displayed return." : " The forward return remains visible while exact pool terms are being checked."}`, + message: `${protectionRecommendation.reason}${feeOverridden ? ` The displayed return is priced at the ${swapFeeBps} bps market pool fee set above.` : canonicalEngineOverrides ? " Current market pool fees are included in the displayed return." : " The forward return remains visible while exact pool terms are being checked."}`, } : { coveragePct: null, @@ -1614,9 +1631,7 @@ export default function DayV3Summary({ : !exitGoalsComplete ? "Choose an exit amount and payout to check the exact pool design. Forward APYs remain available in the meantime." : hasPoolOverride - ? feeOverridden - ? `This design charges a hand-set ${swapFeeBps} bps swap fee. The canonical pool outcomes are withheld because they were solved at the live template's own fee, which this page cannot ask it to change. Every model below is priced at ${swapFeeBps} bps.` - : premiumOverridden + ? premiumOverridden ? // Not "this link": the premium is a field on this page, and the // canonical service takes no premium input — it reports one as a // derived, scenario-only output — so there is nothing for it to @@ -1674,18 +1689,12 @@ export default function DayV3Summary({ restingSeniorPct: canonicalOutcomes?.seniorShareAtNavPct ?? null, swapFeeBps: canonicalExit?.policy.swapFeeBps ?? model.pool.swapFeeBps, - // A hand-set fee is never attributed to a template or to product policy, - // and the template's own fee is named beside it whenever it is known, so - // the reader can see exactly what was replaced and by how much. + // A hand-set fee is a per-market pool setting, not a template-policy value. feeSource: feeOverridden - ? `Issuer-set pool swap fee: ${modeledSwapFeeBps} bps. ${ - rawCanonicalPoolDesign - ? `The live ${rawCanonicalPoolDesign.policy.templateName} template on ${rawCanonicalPoolDesign.policy.chainName} charges ${rawCanonicalPoolDesign.policy.swapFeeBps} bps at block ${rawCanonicalPoolDesign.policy.blockNumber}.` - : `The live template has not resolved, so its own fee is unknown; without this answer the market's declared ${defaults.swapFeeBps} bps would apply.` - }` + ? `Issuer-set market pool swap fee: ${modeledSwapFeeBps} bps. The fee is carried in the selected market's Gyro pool creation parameters.` : canonicalExit - ? `${canonicalExit.policy.templateName} on ${canonicalExit.policy.chainName}, block ${canonicalExit.policy.blockNumber}. Protocol fees: ST ${(Number(BigInt(canonicalExit.policy.protocolFees.stProtocolFeeWad)) / 1e16).toFixed(1)}%, JT ${(Number(BigInt(canonicalExit.policy.protocolFees.jtProtocolFeeWad)) / 1e16).toFixed(1)}%, JT premium ${(Number(BigInt(canonicalExit.policy.protocolFees.jtYieldShareProtocolFeeWad)) / 1e16).toFixed(1)}%, SLP premium ${(Number(BigInt(canonicalExit.policy.protocolFees.lptYieldShareProtocolFeeWad)) / 1e16).toFixed(1)}%. Resolved ${canonicalExit.policy.resolvedAt}` - : null, + ? `${canonicalExit.policy.templateName} on ${canonicalExit.policy.chainName}, block ${canonicalExit.policy.blockNumber}. Pool swap fee: ${canonicalExit.policy.swapFeeBps} bps. Protocol fees: ST ${(Number(BigInt(canonicalExit.policy.protocolFees.stProtocolFeeWad)) / 1e16).toFixed(1)}%, JT ${(Number(BigInt(canonicalExit.policy.protocolFees.jtProtocolFeeWad)) / 1e16).toFixed(1)}%, JT premium ${(Number(BigInt(canonicalExit.policy.protocolFees.jtYieldShareProtocolFeeWad)) / 1e16).toFixed(1)}%, SLP premium ${(Number(BigInt(canonicalExit.policy.protocolFees.lptYieldShareProtocolFeeWad)) / 1e16).toFixed(1)}%. Resolved ${canonicalExit.policy.resolvedAt}` + : `Selected market declares a ${declaredSwapFeeBps} bps Gyro pool fee until a canonical pool design resolves.`, }; // Both discounts come from one engine run against one pool: the deepest fill // it can do, and the fill the promised exit takes. That is what an @@ -1950,6 +1959,7 @@ export default function DayV3Summary({ drawdownPct={protectedDrawdownPct} exit={exitView} defaultPremiumBps={model.pool.premiumBps} + defaultSwapFeeBps={declaredSwapFeeBps} onPoolPremiumBps={setPoolPremiumBps} poolPremiumEdited={premiumOverridden} poolPremiumBps={poolPremiumBps ?? loadedPoolPremiumBps} @@ -2411,7 +2421,7 @@ export default function DayV3Summary({ {exitView.status === "infeasible" ? "These exit terms do not produce a deployable pool. Change the inputs identified in the Senior exit section to redraw the curve." - : "Finish the Senior exit section and resolve its live template. The one-trade curve will appear here; V3 does not fill this space with dashes or a fallback pool."} + : "Finish the Senior exit section and resolve its canonical pool. The one-trade curve will appear here; V3 does not fill this space with dashes or a fallback pool."} diff --git a/components/day-v3/url-state.test.ts b/components/day-v3/url-state.test.ts index 666d0e7..f328e17 100644 --- a/components/day-v3/url-state.test.ts +++ b/components/day-v3/url-state.test.ts @@ -556,7 +556,8 @@ assert.equal(readDayV3UrlState("fee=30").swapFeeBps, 30); assert.equal(readDayV3UrlState("fee=0").swapFeeBps, null); assert.equal(readDayV3UrlState("fee=0.01").swapFeeBps, 0.01); assert.equal(readDayV3UrlState("fee=1000").swapFeeBps, 1_000); -assert.equal(readDayV3UrlState("fee=1001").swapFeeBps, null); +assert.equal(readDayV3UrlState("fee=10000").swapFeeBps, 10_000); +assert.equal(readDayV3UrlState("fee=10001").swapFeeBps, null); assert.equal(readDayV3UrlState("fee=-5").swapFeeBps, null); assert.equal(readDayV3UrlState("fee=abc").swapFeeBps, null); assert.equal(readDayV3UrlState("").swapFeeBps, null); @@ -621,7 +622,10 @@ for (const dropped of ["quote", "quoteApy", "fee", "mmCost", "mmDays"]) { // A swap fee arriving by link is bounded exactly like the field, because a link // is a way into the app and not a way around it. 10000 bps compounded modeled // fee income past what the engine can hold and took the backtest down. -assert.equal(readDayV3UrlState("m=custom&apy=8&fee=10000").swapFeeBps, null); +assert.equal( + readDayV3UrlState("m=custom&apy=8&fee=10000").swapFeeBps, + 10_000, +); // The pool's balance point, carried as the premium that sets it. Bounded to the // range the deploy step accepts, so a link cannot describe a market that cannot diff --git a/components/day-v3/useDayV3PoolDesign.ts b/components/day-v3/useDayV3PoolDesign.ts index be0ea3b..e53015d 100644 --- a/components/day-v3/useDayV3PoolDesign.ts +++ b/components/day-v3/useDayV3PoolDesign.ts @@ -85,7 +85,7 @@ export function useDayV3PoolDesign( throw new Error( dayV3PoolDesignIssueMessage( issues, - "Live deployment targets could not be loaded.", + "Canonical deployment targets could not be loaded.", ), ); } @@ -94,10 +94,10 @@ export function useDayV3PoolDesign( targets: body.targets, message: body.targets.length > 0 - ? "Choose the chain and template whose live fee should be used." + ? "Choose the chain and template whose canonical pool policy should be used." : dayV3PoolDesignIssueMessage( body.issues, - "No live deployment template is currently available.", + "No canonical deployment template is currently available.", ), }); }) @@ -109,7 +109,7 @@ export function useDayV3PoolDesign( message: error instanceof Error ? error.message - : "Live deployment targets could not be loaded.", + : "Canonical deployment targets could not be loaded.", }); }); return () => controller.abort(); @@ -163,7 +163,7 @@ export function useDayV3PoolDesign( body.issues, response.ok ? "The exit terms could not be resolved." - : "The live template policy could not be refreshed.", + : "The canonical pool policy could not be refreshed.", ), }, }); @@ -178,7 +178,7 @@ export function useDayV3PoolDesign( message: error instanceof Error ? error.message - : "The live template policy could not be refreshed.", + : "The canonical pool policy could not be refreshed.", }, }); }); @@ -199,7 +199,7 @@ export function useDayV3PoolDesign( status: "resolving", result: null, message: - "Refreshing the template fee and solving the exact E-CLP design…", + "Refreshing the market pool fee and solving the exact E-CLP design…", }; return { design, inventory, retry }; diff --git a/components/day-v3/useDayV3SimulationPoolDesign.ts b/components/day-v3/useDayV3SimulationPoolDesign.ts index 983fa39..a753fb1 100644 --- a/components/day-v3/useDayV3SimulationPoolDesign.ts +++ b/components/day-v3/useDayV3SimulationPoolDesign.ts @@ -88,14 +88,20 @@ async function fetchSimulationDesign( } /** - * Resolves a simulation design from only the four issuer goals and source APY. - * Deployment facts and target selection are intentionally not accepted here. + * Resolves a simulation design from the four issuer goals, source APY, and the + * selected market's pool fee. Deployment facts and target selection are + * intentionally not accepted here. */ export function useDayV3SimulationPoolDesign( goals: DayV3SimulationPoolDesignGoals | null, sourceApyPct: number | null, + swapFeeBps: number | null, ): DayV3SimulationDesignState { - const requestKey = dayV3SimulationPoolDesignRequestKey(goals, sourceApyPct); + const requestKey = dayV3SimulationPoolDesignRequestKey( + goals, + sourceApyPct, + swapFeeBps, + ); const [resolved, setResolved] = useState<{ key: string; state: DayV3SimulationDesignState; @@ -108,7 +114,7 @@ export function useDayV3SimulationPoolDesign( const currentKey = requestKey; const request = JSON.parse(currentKey) as { goals: DayV3SimulationPoolDesignGoals; - context: { sourceApyPct: number }; + context: { sourceApyPct: number; swapFeeBps: number }; }; const timeout = window.setTimeout(() => { @@ -125,6 +131,7 @@ export function useDayV3SimulationPoolDesign( body, request.goals, request.context.sourceApyPct, + request.context.swapFeeBps, ) ) { throw new Error( @@ -153,8 +160,8 @@ export function useDayV3SimulationPoolDesign( message: dayV3PoolDesignIssueMessage( body.issues, body.status === "infeasible" - ? "The exit terms are not feasible under the live simulation policy." - : "The live simulation policy could not be resolved.", + ? "The exit terms are not feasible under the canonical simulation policy." + : "The canonical simulation policy could not be resolved.", ), }, }); @@ -169,7 +176,7 @@ export function useDayV3SimulationPoolDesign( message: error instanceof Error ? error.message - : "The live simulation policy could not be resolved.", + : "The canonical simulation policy could not be resolved.", }, }); }); @@ -201,6 +208,6 @@ export function useDayV3SimulationPoolDesign( status: "resolving", result: previous, message: - "Updating the live fee and pool design. The last valid result stays visible until this finishes.", + "Updating the market pool fee and design. The last valid result stays visible until this finishes.", }; } diff --git a/docs/DAY_V3_DEPLOYMENT_PARITY_AUDIT.md b/docs/DAY_V3_DEPLOYMENT_PARITY_AUDIT.md index d2f9599..4f226b2 100644 --- a/docs/DAY_V3_DEPLOYMENT_PARITY_AUDIT.md +++ b/docs/DAY_V3_DEPLOYMENT_PARITY_AUDIT.md @@ -1,9 +1,9 @@ # Day V3 deployment parity audit -Audited 2026-08-13 against: +Audited 2026-08-28 against: - the current `royco-rwa-frontend` deployment flow; -- `royco-day` commit `9764c9e20c8e8af7df1358f228c4be83b78be97f`; +- `royco-day` commit `107a5dd8b1e069ca23855c7f7e89de523678269b`; - the canonical E-CLP implementation and differential vectors used by Royco Deploy. This audit distinguishes issuer design decisions from deployment plumbing. V3 @@ -23,8 +23,8 @@ the final transaction. | Reinvestment protection | Issuer supplies the maximum value SLP reinvestment may give up | `maxReinvestmentSlippageWAD` | The handoff is versioned, normalized to $100 Senior, and includes chain, -template, block, resolution time, exact registered YDM instances, live fee -provenance, exact E-CLP parameters, and field origins. Illustrative starter +template, block, resolution time, exact registered YDM instances, market +pool-fee provenance, exact E-CLP parameters, and field origins. Illustrative starter values cannot become deployment-approved merely by surviving a URL reload. ## Fail-closed handoff behavior @@ -84,7 +84,10 @@ requirements: off-chain derivation. Royco Deploy therefore performs stricter canonical E-CLP and quote validation before deployment. 6. The pool swap-fee interval is a contract rule and is inclusive: - `0.01–10,000 bps`. Dawn and Royco Deploy now use those exact endpoints. + `0.01–10,000 bps`. It is the selected market's + `poolCreationParams.swapFeePercentage` for the Gyro E-CLP pool, not a + `TemplatePolicy` value; Dawn and Royco Deploy should carry that per-market + field through unchanged. Minimum Coverage, Minimum Liquidity, yield caps, fixed-term settings, oracle configuration, and reinvestment slippage can also be changed later by authorized @@ -95,7 +98,7 @@ does not imply that every parameter is forever immutable. - Dawn full regression suite: pass. - Royco Day parity: 78/78 pinned Solidity vectors pass at commit - `9764c9e20c8e8af7df1358f228c4be83b78be97f`. + `107a5dd8b1e069ca23855c7f7e89de523678269b`. - Dawn lint, TypeScript, and production build: pass. - RWA TypeScript and production build: pass. - RWA runnable tests: 474 pass, 3 skip. diff --git a/docs/NEW_DAY_SIMULATOR.md b/docs/NEW_DAY_SIMULATOR.md index 43f54d0..2b50f4f 100644 --- a/docs/NEW_DAY_SIMULATOR.md +++ b/docs/NEW_DAY_SIMULATOR.md @@ -139,7 +139,7 @@ Certification runs data verification, accountant runtime checks, every checked-i ```text Data integrity: PASS -Accountant parity: PASS (78/78 replayed vectors from royco-day @9764c9e20c) +Accountant parity: PASS (78/78 replayed vectors from royco-day @107a5dd8b1) Calibration guardrails: PASS Locked copy: PASS Design contract: PASS diff --git a/lib/day-markets/acred/market.json b/lib/day-markets/acred/market.json index 9d681cd..01f852f 100644 --- a/lib/day-markets/acred/market.json +++ b/lib/day-markets/acred/market.json @@ -45,7 +45,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "reinvestLiquidityPremium": true, "initialST": 1000, diff --git a/lib/day-markets/blockhouse/market.json b/lib/day-markets/blockhouse/market.json index d214583..2a95ca8 100644 --- a/lib/day-markets/blockhouse/market.json +++ b/lib/day-markets/blockhouse/market.json @@ -45,7 +45,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "reinvestLiquidityPremium": true, "initialST": 1000, diff --git a/lib/day-markets/dualmint/market.json b/lib/day-markets/dualmint/market.json index 66ca79d..086455a 100644 --- a/lib/day-markets/dualmint/market.json +++ b/lib/day-markets/dualmint/market.json @@ -45,7 +45,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "reinvestLiquidityPremium": true, "initialST": 1000, diff --git a/lib/day-markets/infinifi/market.json b/lib/day-markets/infinifi/market.json index 6a93820..77b2a75 100644 --- a/lib/day-markets/infinifi/market.json +++ b/lib/day-markets/infinifi/market.json @@ -45,7 +45,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "reinvestLiquidityPremium": true, "initialST": 1000, diff --git a/lib/day-markets/makina-dbit/market.json b/lib/day-markets/makina-dbit/market.json index 62e2591..3ea0c97 100644 --- a/lib/day-markets/makina-dbit/market.json +++ b/lib/day-markets/makina-dbit/market.json @@ -45,7 +45,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "reinvestLiquidityPremium": true, "initialST": 1000, diff --git a/lib/day-markets/makina-deth/market.json b/lib/day-markets/makina-deth/market.json index 4cb036f..c60c306 100644 --- a/lib/day-markets/makina-deth/market.json +++ b/lib/day-markets/makina-deth/market.json @@ -45,7 +45,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "reinvestLiquidityPremium": true, "initialST": 1000, diff --git a/lib/day-markets/makina-dusd/market.json b/lib/day-markets/makina-dusd/market.json index 4f33b2d..909ff18 100644 --- a/lib/day-markets/makina-dusd/market.json +++ b/lib/day-markets/makina-dusd/market.json @@ -52,7 +52,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "maxJTYieldShare": 0.5, "maxLTYieldShare": 0.5, diff --git a/lib/day-markets/makina-usdshfmk/market.json b/lib/day-markets/makina-usdshfmk/market.json index 8514d4f..373762c 100644 --- a/lib/day-markets/makina-usdshfmk/market.json +++ b/lib/day-markets/makina-usdshfmk/market.json @@ -45,7 +45,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "reinvestLiquidityPremium": true, "initialST": 1000, diff --git a/lib/day-markets/pareto-falconx/market.json b/lib/day-markets/pareto-falconx/market.json index 149854b..965a366 100644 --- a/lib/day-markets/pareto-falconx/market.json +++ b/lib/day-markets/pareto-falconx/market.json @@ -52,7 +52,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "maxJTYieldShare": 0.5, "maxLTYieldShare": 0.5, diff --git a/lib/day-markets/reusde/market.json b/lib/day-markets/reusde/market.json index 084f207..87ae598 100644 --- a/lib/day-markets/reusde/market.json +++ b/lib/day-markets/reusde/market.json @@ -45,7 +45,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "reinvestLiquidityPremium": true, "initialST": 1000, diff --git a/lib/day-markets/susdai/market.json b/lib/day-markets/susdai/market.json index 1f13feb..727b843 100644 --- a/lib/day-markets/susdai/market.json +++ b/lib/day-markets/susdai/market.json @@ -52,7 +52,25 @@ "beta": 1.0003, "c": 0.7071067811865476, "s": 0.7071067811865476, - "lambda": 250 + "lambda": 250, + "fixedParams": { + "alpha": "980000000000000000", + "beta": "1000300000000000000", + "c": "707106781186547524", + "s": "707106781186547524", + "lambda": "250000000000000000000" + }, + "derivedParams": { + "tauAlphaX": "-92975357432315416605491271255356493443", + "tauAlphaY": "36818241543196904975774583017121171403", + "tauBetaX": "3746804827358009532998249894673148143", + "tauBetaY": "99929782615523019584751990190862643080", + "u": "48361081129836713014414996374502815654", + "v": "68374012079359962202743630490639666742", + "w": "31555770536163057268712062638611327323", + "z": "-44614276302478703485664720423548546517", + "dSq": "99999999999999999886624093342106115200" + } }, "maxJTYieldShare": 0.5, "maxLTYieldShare": 0.5, diff --git a/lib/day-simulator-template/runtime.test.ts b/lib/day-simulator-template/runtime.test.ts index 7ece2c3..017d317 100644 --- a/lib/day-simulator-template/runtime.test.ts +++ b/lib/day-simulator-template/runtime.test.ts @@ -205,7 +205,7 @@ const terms = { liquidityYieldShare: market.defaults.liqYDM.yTarget, }; -// V3 supplies exact canonical E-CLP parameters and the live template fee. The +// V3 supplies exact canonical E-CLP parameters and the market pool fee. The // shared runtime must consume both rather than regenerating either one. const canonicalEclp = { alpha: 0.99, @@ -347,9 +347,9 @@ const yields = runDayTargetScenario(market.defaults); // Junior return bands after the uniform 5% Junior/SLP yield-premium protocol // fee is applied. These exact outputs also pin the manifest decimal through the // runtime adapter and the contract-mirrored fee-share minting path. -assert.ok(Math.abs(yields.seniorApy - 0.0913920169096325) < 1e-12); +assert.ok(Math.abs(yields.seniorApy - 0.0913920160458408) < 1e-12); assert.ok(Math.abs(yields.juniorApy - 0.13924177159090334) < 1e-12); -assert.ok(Math.abs(yields.liquidityApy - 0.10248258285545275) < 1e-12); +assert.ok(Math.abs(yields.liquidityApy - 0.1024825578810733) < 1e-12); const forwardSeries = buildDayForwardSeries( 0.114, diff --git a/lib/day-v3/day-v3.test.ts b/lib/day-v3/day-v3.test.ts index 4d8961c..6cd9514 100644 --- a/lib/day-v3/day-v3.test.ts +++ b/lib/day-v3/day-v3.test.ts @@ -237,6 +237,7 @@ const poolGoals = { check("target and operational facts invalidate canonical pool results", () => { const context = { sourceApyPct: 12, + swapFeeBps: 10, exitAsset: null, exitAssetRateProvider: null, exitAssetYieldBearing: null, @@ -274,11 +275,12 @@ check("target and operational facts invalidate canonical pool results", () => { }); const canonicalPoolSnapshot = { schemaVersion: DAY_V3_POOL_DESIGN_SCHEMA, - modelVersion: "day-v3-eclp-goal-solver-1.1.0", + modelVersion: "day-v3-eclp-goal-solver-1.2.0", status: "resolved", goals: poolGoals, context: { sourceApyPct: 12, + swapFeeBps: 10, exitAsset: null, exitAssetRateProvider: null, exitAssetYieldBearing: null, @@ -335,7 +337,7 @@ const canonicalPoolSnapshot = { unit: "test", origin: key === "swapFeeBps" - ? "template-policy" + ? "market-policy" : key === "maximumPremiumBps" ? "derived" : "recommended", @@ -402,7 +404,7 @@ check("canonical inventory and result guards reject shape drift", () => { assert.equal( isDayV3PoolDesignInventory({ schemaVersion: DAY_V3_POOL_DESIGN_SCHEMA, - modelVersion: "day-v3-eclp-goal-solver-1.1.0", + modelVersion: "day-v3-eclp-goal-solver-1.2.0", status: "resolved", targets: [canonicalPoolSnapshot.policy], issues: [], @@ -412,7 +414,7 @@ check("canonical inventory and result guards reject shape drift", () => { assert.equal( isDayV3PoolDesignInventory({ schemaVersion: "0.9", - modelVersion: "day-v3-eclp-goal-solver-1.1.0", + modelVersion: "day-v3-eclp-goal-solver-1.2.0", status: "resolved", targets: [], issues: [], @@ -487,10 +489,10 @@ check("canonical inventory and result guards reject shape drift", () => { assert.equal( isDayV3PoolDesignResult({ schemaVersion: DAY_V3_POOL_DESIGN_SCHEMA, - modelVersion: "day-v3-eclp-goal-solver-1.1.0", + modelVersion: "day-v3-eclp-goal-solver-1.2.0", status: "unresolved", recommendation: null, - issues: [{ code: "POLICY_UNRESOLVED", message: "Live fee unavailable." }], + issues: [{ code: "POLICY_UNRESOLVED", message: "Market pool fee unavailable." }], }), true, ); @@ -500,13 +502,13 @@ check("canonical inventory and result guards reject shape drift", () => { modelVersion: "wrong-model", status: "unresolved", recommendation: null, - issues: [{ code: "POLICY_UNRESOLVED", message: "Live fee unavailable." }], + issues: [{ code: "POLICY_UNRESOLVED", message: "Market pool fee unavailable." }], }), false, ); }); -check("live fee policy mirrors the contract's inclusive endpoints", () => { +check("market pool fee mirrors the contract's inclusive endpoints", () => { const policy = canonicalPoolSnapshot.policy; assert.equal(isDayV3ResolvedPolicy({ ...policy, swapFeeBps: 0 }), false); assert.equal(isDayV3ResolvedPolicy({ ...policy, swapFeeBps: 0.0099 }), false); diff --git a/lib/day-v3/handoff.ts b/lib/day-v3/handoff.ts index f4c3080..6fcc722 100644 --- a/lib/day-v3/handoff.ts +++ b/lib/day-v3/handoff.ts @@ -286,7 +286,7 @@ export function buildDayV3HandoffV3(input: { warnings: [ "This handoff is untrusted input to deployment.", "Deployment must validate every goal, refresh template policy, and recompute E-CLP fields. Absolute genesis funding remains unresolved until deployment has a notional and initialization policy.", - "Senior redemption returns the underlying asset. The external underlying-to-exit spread is an issuer-selected stress assumption; the pool-state discount and live SLP fee are modeled separately, and none is a protocol guarantee.", + "Senior redemption returns the underlying asset. The external underlying-to-exit spread is an issuer-selected stress assumption; the pool-state discount and selected market pool fee are modeled separately, and none is a protocol guarantee.", "Settlement is a market-level product decision applied identically to Senior, Junior, and Senior LP, even though the contracts store three separate queue configs.", "Finite execution windows must be revalidated against the selected oracle recipe's freshness limits. NAV cadence is a modeling fact, not an EntryPoint contract field.", "Reinvestment slippage is an on-chain ceiling. Deployment must revalidate it against the final exit asset, rate provider, and canonical E-CLP.", diff --git a/lib/day-v3/mode-state.test.ts b/lib/day-v3/mode-state.test.ts index 5cfb2a7..2ade651 100644 --- a/lib/day-v3/mode-state.test.ts +++ b/lib/day-v3/mode-state.test.ts @@ -260,6 +260,7 @@ const canonicalGoals: DayV3Goals = { }; const canonicalContext = { sourceApyPct: canonicalState.sourceApyPct as number, + swapFeeBps: canonicalState.swapFeeBps as number, exitAsset: null, exitAssetRateProvider: null, exitAssetYieldBearing: null, diff --git a/lib/day-v3/model-state.ts b/lib/day-v3/model-state.ts index 4361893..8fc1649 100644 --- a/lib/day-v3/model-state.ts +++ b/lib/day-v3/model-state.ts @@ -1,7 +1,7 @@ /** * Keep every input to one displayed accountant run in the same value. React may * defer this snapshot, but it must never defer the goals separately from the - * live template policy that prices them. + * canonical market-pool policy that prices them. */ export function createDayV3ModelSnapshot< TTerms extends Record, diff --git a/lib/day-v3/pool-design.ts b/lib/day-v3/pool-design.ts index 01775ca..fba9a34 100644 --- a/lib/day-v3/pool-design.ts +++ b/lib/day-v3/pool-design.ts @@ -1,8 +1,14 @@ import type { DayV3Goals } from "@/lib/day-v3/types"; -export const DAY_V3_POOL_DESIGN_SCHEMA = "1.2" as const; +export const DAY_V3_POOL_DESIGN_SCHEMA = "1.3" as const; export const DAY_V3_POOL_DESIGN_MODEL = - "day-v3-eclp-goal-solver-1.1.0" as const; + "day-v3-eclp-goal-solver-1.2.0" as const; + +/** Royco Day's current Gyro E-CLP pool-fee bounds, expressed in bps. */ +export const DAY_V3_POOL_SWAP_FEE_BPS_RANGE = { + min: 0.01, + max: 10_000, +} as const; export const DAY_V3_DERIVED_ECLP_KEYS = [ "tauAlphaX", @@ -54,6 +60,8 @@ export interface DayV3PoolDesignTarget { export interface DayV3PoolDesignContext { sourceApyPct: number; + /** Market-specific Gyro pool creation fee, not a template policy value. */ + swapFeeBps: number; exitAsset: `0x${string}` | null; exitAssetRateProvider: `0x${string}` | null; exitAssetYieldBearing: boolean | null; @@ -67,6 +75,7 @@ export interface DayV3PoolDesignIssue { export interface DayV3ResolvedPolicy extends DayV3PoolDesignTarget { status: "resolved"; + /** `poolCreationParams.swapFeePercentage` in Royco Day deployment params. */ swapFeeBps: number; chargeYieldFeeOnSeniorTrancheShares: boolean; chargeYieldFeeOnQuoteAsset: boolean; @@ -87,7 +96,7 @@ export interface DayV3PoolDesignField { | "issuer-goal" | "recommended" | "derived" - | "template-policy" + | "market-policy" | "manual-override" | "unresolved"; deployPath: string | null; @@ -178,7 +187,7 @@ const FIELD_ORIGINS = new Set([ "issuer-goal", "recommended", "derived", - "template-policy", + "market-policy", "manual-override", "unresolved", ]); @@ -332,12 +341,8 @@ function isResolvedPolicy(value: unknown): value is DayV3ResolvedPolicy { isRecord(value) && value.status === "resolved" && isFiniteNumber(value.swapFeeBps) && - // Template validation accepts swap fees from 1e12 through 1e18 WAD, - // inclusive. In basis points that is 0.01 through 10,000. Mirror those - // contract endpoints exactly: zero is not deployable, while the upper - // endpoint is. - value.swapFeeBps >= 0.01 && - value.swapFeeBps <= 10_000 && + value.swapFeeBps >= DAY_V3_POOL_SWAP_FEE_BPS_RANGE.min && + value.swapFeeBps <= DAY_V3_POOL_SWAP_FEE_BPS_RANGE.max && typeof value.chargeYieldFeeOnSeniorTrancheShares === "boolean" && typeof value.chargeYieldFeeOnQuoteAsset === "boolean" && validProtocolFees && @@ -406,6 +411,9 @@ function isContext(value: unknown): value is DayV3PoolDesignContext { isFiniteNumber(value.sourceApyPct) && value.sourceApyPct >= 0 && value.sourceApyPct <= 100 && + isFiniteNumber(value.swapFeeBps) && + value.swapFeeBps >= DAY_V3_POOL_SWAP_FEE_BPS_RANGE.min && + value.swapFeeBps <= DAY_V3_POOL_SWAP_FEE_BPS_RANGE.max && optionalAddress(value.exitAsset) && optionalAddress(value.exitAssetRateProvider) && (value.exitAssetYieldBearing === null || @@ -490,11 +498,12 @@ export function isDayV3PoolDesignResult( !isDesignField(fields.swapFeeBps) || !isDesignField(fields.poolFundingPer100Senior) || fields.swapFeeBps.value !== value.policy.swapFeeBps || + value.context.swapFeeBps !== value.policy.swapFeeBps || fields.maximumDiscountBps.origin !== "recommended" || fields.depthAtNavLambda.origin !== "recommended" || fields.maximumPremiumBps.origin !== "derived" || fields.maximumPremiumBps.modelUsage !== "scenario-only" || - fields.swapFeeBps.origin !== "template-policy" || + fields.swapFeeBps.origin !== "market-policy" || fields.poolFundingPer100Senior.origin !== "recommended" ) { return false; @@ -615,6 +624,7 @@ export function dayV3PoolDesignMatchesGoals( result.goals.target.templateId === goals.target.templateId && (context === undefined || (result.context.sourceApyPct === context.sourceApyPct && + result.context.swapFeeBps === context.swapFeeBps && result.context.exitAsset === context.exitAsset && result.context.exitAssetRateProvider === context.exitAssetRateProvider && diff --git a/lib/day-v3/restock-arbitrage.ts b/lib/day-v3/restock-arbitrage.ts index 7f7ce61..377a3ab 100644 --- a/lib/day-v3/restock-arbitrage.ts +++ b/lib/day-v3/restock-arbitrage.ts @@ -89,7 +89,7 @@ export interface DayV3RestockHurdleInputs { redemptionDays: number; /** Senior's modeled annual return, earned by whoever holds it while waiting. */ seniorApyPct: number; - /** The live pool fee the desk pays to trade back in. */ + /** The selected market pool fee the desk pays to trade back in. */ swapFeeBps: number; } diff --git a/lib/day-v3/simulation-pool-design.test.ts b/lib/day-v3/simulation-pool-design.test.ts index 745de75..c771238 100644 --- a/lib/day-v3/simulation-pool-design.test.ts +++ b/lib/day-v3/simulation-pool-design.test.ts @@ -84,7 +84,7 @@ const fields = Object.fromEntries( unit: "test", origin: key === "swapFeeBps" - ? "template-policy" + ? "market-policy" : key === "maximumPremiumBps" ? "derived" : "recommended", @@ -98,11 +98,11 @@ const fields = Object.fromEntries( const resolved = { schemaVersion: DAY_V3_SIMULATION_POOL_DESIGN_SCHEMA, - modelVersion: "day-v3-eclp-goal-solver-1.1.0", + modelVersion: "day-v3-eclp-goal-solver-1.2.0", mode: "simulation", status: "resolved", goals, - context: { sourceApyPct: 6 }, + context: { sourceApyPct: 6, swapFeeBps: 10 }, policy, deployment, recommendation: { @@ -164,29 +164,37 @@ const resolved = { >; assert.equal(isDayV3SimulationPoolDesignResult(resolved), true); -assert.equal(dayV3SimulationPoolDesignMatchesRequest(resolved, goals, 6), true); assert.equal( - dayV3SimulationPoolDesignMatchesRequest(resolved, goals, 7), + dayV3SimulationPoolDesignMatchesRequest(resolved, goals, 6, 10), + true, +); +assert.equal( + dayV3SimulationPoolDesignMatchesRequest(resolved, goals, 7, 10), false, ); -const key = dayV3SimulationPoolDesignRequestKey(goals, 6); +const key = dayV3SimulationPoolDesignRequestKey(goals, 6, 10); assert.notEqual(key, null); assert.deepEqual(JSON.parse(key as string), { - schemaVersion: "1.0", + schemaVersion: "1.1", goals, - context: { sourceApyPct: 6 }, + context: { sourceApyPct: 6, swapFeeBps: 10 }, }); -assert.notEqual(dayV3SimulationPoolDesignRequestKey(goals, 0), null); -assert.equal(dayV3SimulationPoolDesignRequestKey(goals, null), null); +assert.notEqual(dayV3SimulationPoolDesignRequestKey(goals, 0, 10), null); +assert.equal(dayV3SimulationPoolDesignRequestKey(goals, null, 10), null); assert.equal( - dayV3SimulationPoolDesignRequestKey({ ...goals, recoveryDays: 20.5 }, 6), + dayV3SimulationPoolDesignRequestKey( + { ...goals, recoveryDays: 20.5 }, + 6, + 10, + ), null, ); assert.equal( dayV3SimulationPoolDesignRequestKey( { ...goals, navUpdateDays: 1 } as typeof goals, 6, + 10, ), null, "deployment fields must not enter the simulation request", @@ -221,8 +229,8 @@ assert.equal(isDayV3SimulationPoolDesignResult(infeasible), true); assert.equal( isDayV3SimulationPoolDesignResult({ - schemaVersion: "1.0", - modelVersion: "day-v3-eclp-goal-solver-1.1.0", + schemaVersion: "1.1", + modelVersion: "day-v3-eclp-goal-solver-1.2.0", mode: "simulation", status: "unresolved", policy: null, diff --git a/lib/day-v3/simulation-pool-design.ts b/lib/day-v3/simulation-pool-design.ts index a4cc707..508c1c6 100644 --- a/lib/day-v3/simulation-pool-design.ts +++ b/lib/day-v3/simulation-pool-design.ts @@ -3,12 +3,13 @@ import { DAY_V3_POOL_DESIGN_SCHEMA, isDayV3PoolDesignResult, isDayV3ResolvedPolicy, + DAY_V3_POOL_SWAP_FEE_BPS_RANGE, type DayV3PoolDesignIssue, type DayV3PoolDesignRecommendation, type DayV3ResolvedPolicy, } from "@/lib/day-v3/pool-design"; -export const DAY_V3_SIMULATION_POOL_DESIGN_SCHEMA = "1.0" as const; +export const DAY_V3_SIMULATION_POOL_DESIGN_SCHEMA = "1.1" as const; export interface DayV3SimulationPoolDesignGoals { protectedDrawdownPct: number; @@ -19,6 +20,8 @@ export interface DayV3SimulationPoolDesignGoals { export interface DayV3SimulationPoolDesignContext { sourceApyPct: number; + /** Market-specific pool creation fee supplied to the simulation solver. */ + swapFeeBps: number; } export interface DayV3SimulationPoolDesignRequest { @@ -124,10 +127,13 @@ export function isDayV3SimulationPoolDesignContext( ): value is DayV3SimulationPoolDesignContext { return ( isRecord(value) && - hasOnlyKeys(value, ["sourceApyPct"]) && + hasOnlyKeys(value, ["sourceApyPct", "swapFeeBps"]) && isFiniteNumber(value.sourceApyPct) && value.sourceApyPct >= 0 && - value.sourceApyPct <= 100 + value.sourceApyPct <= 100 && + isFiniteNumber(value.swapFeeBps) && + value.swapFeeBps >= DAY_V3_POOL_SWAP_FEE_BPS_RANGE.min && + value.swapFeeBps <= DAY_V3_POOL_SWAP_FEE_BPS_RANGE.max ); } @@ -217,6 +223,7 @@ function isSimulationRecommendation( }, context: { sourceApyPct: context.sourceApyPct, + swapFeeBps: context.swapFeeBps, exitAsset: null, exitAssetRateProvider: null, exitAssetYieldBearing: null, @@ -284,6 +291,7 @@ export function dayV3SimulationPoolDesignMatchesRequest( result: DayV3SimulationPoolDesignResult, goals: DayV3SimulationPoolDesignGoals, sourceApyPct: number, + swapFeeBps: number, ): boolean { return ( result.goals !== undefined && @@ -292,7 +300,8 @@ export function dayV3SimulationPoolDesignMatchesRequest( result.goals.recoveryDays === goals.recoveryDays && result.goals.immediateExitSharePct === goals.immediateExitSharePct && result.goals.minimumProceedsPer100 === goals.minimumProceedsPer100 && - result.context.sourceApyPct === sourceApyPct + result.context.sourceApyPct === sourceApyPct && + result.context.swapFeeBps === swapFeeBps ); } @@ -300,8 +309,9 @@ export function dayV3SimulationPoolDesignMatchesRequest( export function dayV3SimulationPoolDesignRequestKey( goals: DayV3SimulationPoolDesignGoals | null, sourceApyPct: number | null, + swapFeeBps: number | null, ): string | null { - const context = { sourceApyPct }; + const context = { sourceApyPct, swapFeeBps }; if ( !isDayV3SimulationPoolDesignGoals(goals) || !isDayV3SimulationPoolDesignContext(context) diff --git a/lib/day-v3/types.ts b/lib/day-v3/types.ts index 8dedf54..61531ba 100644 --- a/lib/day-v3/types.ts +++ b/lib/day-v3/types.ts @@ -5,7 +5,7 @@ export type DayV3FieldOrigin = | "issuer-goal" | "recommended" | "derived" - | "template-policy" + | "market-policy" | "manual-override" | "unresolved"; @@ -71,7 +71,7 @@ export interface DayV3DeploymentPolicy { * Issuer goals accepted by the canonical pool-design service. * * The nullable deployment facts are deliberate. They are forwarded so a - * response can still resolve live template policy and price the immediate + * response can still resolve canonical pool policy and price the immediate * pool exit, but a deployment handoff may not be marked ready until the * issuer has supplied them. */ diff --git a/lib/day-v3/url-state.ts b/lib/day-v3/url-state.ts index f777489..79b2cd7 100644 --- a/lib/day-v3/url-state.ts +++ b/lib/day-v3/url-state.ts @@ -10,6 +10,7 @@ import { DAY_CURVE_MODELS, type DayCurveModel, } from "@/lib/day-simulator-template/deploy-fields"; +import { DAY_V3_POOL_SWAP_FEE_BPS_RANGE } from "@/lib/day-v3/pool-design"; export type DayV3Mode = "simulate" | "deploy"; @@ -26,11 +27,7 @@ export interface DayV3UrlState extends DayV3GoalDraft { quoteAssetYieldPct: number | null; /** Annual swap volume as a multiple of pool value. Zero means no forecast. */ poolTurnoverPerYear: number | null; - /** - * The pool's trading fee. `null` is the honest default: it means the live - * template's own fee decides, and the market's declared fee stands in until - * that template resolves. A number here is the issuer's own fee policy. - */ + /** The selected market's Gyro pool trading fee, in bps. */ swapFeeBps: number | null; /** * The pool's balance point, carried as the maximum premium in bps that sets @@ -462,13 +459,13 @@ export function readDayV3UrlState(search: string): DayV3UrlState { quoteAssetLabel: label(params.get("quote")), quoteAssetYieldPct: finite(params.get("quoteApy"), 0, 30), poolTurnoverPerYear: finite(params.get("turnover"), 0, 100), - // `previewSecondarySell` throws outside 0–10000 bps, inside a render-time - // memo with no error boundary above it, so this bound is what keeps a - // hand-edited link from crashing the page rather than a cosmetic range. - // Matches the field's own bound. A link is a way into the app, not a way - // around it: 10000 bps arrived here and compounded modeled fee income past - // what the engine can hold, taking the backtest down. - swapFeeBps: finite(params.get("fee"), 0.01, 1_000), + // Match Gyro's contract range. The engine/backtest still validates whether + // a particular high-fee scenario has finite modeled outcomes. + swapFeeBps: finite( + params.get("fee"), + DAY_V3_POOL_SWAP_FEE_BPS_RANGE.min, + DAY_V3_POOL_SWAP_FEE_BPS_RANGE.max, + ), // The pool's balance point, carried as the premium that sets it — the same // quantity the deployment interface takes, in the range it accepts // (`PREMIUM_BP = { min: 0, max: 50 }`). A link that carried a premium the @@ -563,9 +560,9 @@ export function buildDayV3Query(state: DayV3UrlWriteState): string { if (state.quoteAssetLabel) params.set("quote", state.quoteAssetLabel); setNumber("quoteApy", state.quoteAssetYieldPct); setNumber("turnover", state.poolTurnoverPerYear); - // Only a hand-set fee is written. A null fee means the live template's own - // fee decides, and serializing a placeholder for it would turn an inherited - // policy into a stated one the moment a link was shared. + // Only a hand-set fee is written. A null fee means the selected market's + // declared fee; serializing a placeholder would turn that declaration into + // an explicit issuer override the moment a link was shared. setNumber("fee", state.swapFeeBps); setNumber("premiumBps", state.poolPremiumBps); setNumber("mmCost", state.marketMakerCostOfCapitalPct); diff --git a/lib/day/engine/eclp.ts b/lib/day/engine/eclp.ts index cc76eea..ec1ab69 100644 --- a/lib/day/engine/eclp.ts +++ b/lib/day/engine/eclp.ts @@ -1,3 +1,5 @@ +import { WAD, toWadFloor } from './wad'; + // ============================================================================= // Gyroscope E-CLP math + Balancer manipulation-resistant LP valuation. // Mirrors GyroECLPMath.sol (tau/eta/zeta, mulA/mulAinv, invariant) and @@ -16,6 +18,39 @@ export interface EclpParams { c: number; // cos(phi) s: number; // sin(phi) lambda: number; // stretching / concentration + /** + * The 18-decimal values passed to the Gyro pool constructor. The display + * fields above remain numbers because the quote explorer is number-facing, + * but the oracle path keeps these strings so parsing a canonical response + * cannot throw away the last few wei of c, s, or a bound. + */ + fixedParams?: EclpFixedParams; + /** + * The 38-decimal values stored by GyroECLPPool. Balancer deliberately does + * not derive these on-chain; Royco Deploy returns them with the pool design. + * When present, the simulator uses them for the BPT oracle valuation. + */ + derivedParams?: EclpDerivedParams; +} + +export interface EclpFixedParams { + alpha: string; + beta: string; + c: string; + s: string; + lambda: string; +} + +export interface EclpDerivedParams { + tauAlphaX: string; + tauAlphaY: string; + tauBetaX: string; + tauBetaY: string; + u: string; + v: string; + w: string; + z: string; + dSq: string; } interface V2 { x: number; y: number; } @@ -49,14 +84,41 @@ function zeta(p: EclpParams, px: number): number { // tau(px) = eta(zeta(px)) — point on the unit circle for price px const tau = (p: EclpParams, px: number): V2 => eta(zeta(p, px)); +function numberFromFixed(value: string, scale: bigint): number { + return Number(BigInt(value)) / Number(scale); +} + +/** Use the pool's stored tau endpoints whenever Royco Deploy supplied them. + * A Balancer ECLP stores these at 38 decimals and the oracle reads those + * values back; recomputing them from a rounded UI number can move the BPT mark + * by more than one wei. */ +function tauEndpoint(p: EclpParams, endpoint: 'alpha' | 'beta'): V2 { + const d = p.derivedParams; + if (d) { + const x = endpoint === 'alpha' ? d.tauAlphaX : d.tauBetaX; + const y = endpoint === 'alpha' ? d.tauAlphaY : d.tauBetaY; + try { + return { + x: numberFromFixed(x, 10n ** 38n), + y: numberFromFixed(y, 10n ** 38n), + }; + } catch { + // A malformed optional payload must not make the educational quote + // explorer unusable; the canonical response validator rejects it before + // it reaches this path, and local configs can still use the fallback. + } + } + return tau(p, endpoint === 'alpha' ? p.alpha : p.beta); +} + // Reserves per unit invariant at price pxIny. token0 (ST) reserve is max at the // price floor and 0 at the ceil; token1 (stable) is the mirror. Both >= 0 in band. // Real reserves are (corner − v), with corner = (mulAinv(tauβ).x, mulAinv(tauα).y); // the offsets are *subtracted* from the curve point, matching GyroECLPMath's virtual // offsets and EclpLPOracle._computeEclpTvl (vec.x = mulAinv(tauβ).x − mulAinv(tau).x). export function reservesPerL(p: EclpParams, pxIny: number): V2 { - const aB = mulAinv(p, tau(p, p.beta)); - const aA = mulAinv(p, tau(p, p.alpha)); + const aB = mulAinv(p, tauEndpoint(p, 'beta')); + const aA = mulAinv(p, tauEndpoint(p, 'alpha')); if (pxIny < p.alpha) return { x: aB.x - aA.x, y: 0 }; if (pxIny > p.beta) return { x: 0, y: aA.y - aB.y }; const v = mulAinv(p, tau(p, pxIny)); @@ -69,6 +131,558 @@ export function eclpTVL(p: EclpParams, invariant: number, px: number, py: number return (px * r.x + py * r.y) * invariant; } +// --------------------------------------------------------------------------- +// Balancer fixed-point oracle path +// --------------------------------------------------------------------------- + +// Balancer's normal and extra-precision scales. Keeping this path in bigint +// arithmetic is important: the pool oracle floors both the live balances and +// the invariant before it computes TVL, while a Number round-trip can move a +// large pool by many WADs even when the displayed dollar value looks unchanged. +const ONE_XP = 10n ** 38n; +const XP_TO_NP = 10n ** 20n; +const XP_SPLIT = 10n ** 19n; +const ONE_20 = 10n ** 20n; +const ONE_36 = 10n ** 36n; + +type FixedEclpParams = { + alpha: bigint; + beta: bigint; + c: bigint; + s: bigint; + lambda: bigint; +}; + +type FixedDerivedEclpParams = { + tauAlphaX: bigint; + tauAlphaY: bigint; + tauBetaX: bigint; + tauBetaY: bigint; + u: bigint; + v: bigint; + w: bigint; + z: bigint; + dSq: bigint; +}; + +const mulDownMagFixed = (a: bigint, b: bigint, scale = WAD): bigint => (a * b) / scale; +const mulUpMagFixed = (a: bigint, b: bigint, scale = WAD): bigint => { + const product = a * b; + if (product > 0n) return ((product - 1n) / scale) + 1n; + if (product < 0n) return ((product + 1n) / scale) - 1n; + return 0n; +}; +const divDownMagFixed = (a: bigint, b: bigint, scale = WAD): bigint => { + if (b === 0n) throw new Error('ECLP_DIVISION_BY_ZERO'); + return (a * scale) / b; +}; +const divUpMagFixed = (a: bigint, b: bigint, scale = WAD): bigint => { + if (b === 0n) throw new Error('ECLP_DIVISION_BY_ZERO'); + if (a === 0n) return 0n; + let numerator = a; + let denominator = b; + if (denominator < 0n) { + denominator = -denominator; + numerator = -numerator; + } + const inflated = numerator * scale; + return inflated > 0n + ? ((inflated - 1n) / denominator) + 1n + : ((inflated + 1n) / denominator) - 1n; +}; + +/** Signed normal × extra-precision → normal, copied from + * SignedFixedPoint.mul{Down,Up}XpToNpU. */ +function mulDownXpToNpFixed(a: bigint, b: bigint): bigint { + const b1 = b / XP_SPLIT; + const b2 = b % XP_SPLIT; + const prod1 = a * b1; + const prod2 = a * b2; + const partial = prod1 + prod2 / XP_SPLIT; + return prod1 >= 0n && prod2 >= 0n + ? partial / XP_SPLIT + : (partial + 1n) / XP_SPLIT - 1n; +} + +function mulUpXpToNpFixed(a: bigint, b: bigint): bigint { + const b1 = b / XP_SPLIT; + const b2 = b % XP_SPLIT; + const prod1 = a * b1; + const prod2 = a * b2; + const partial = prod1 + prod2 / XP_SPLIT; + return prod1 <= 0n && prod2 <= 0n + ? partial / XP_SPLIT + : (partial - 1n) / XP_SPLIT + 1n; +} + +const mulXpFixed = (a: bigint, b: bigint): bigint => (a * b) / ONE_XP; +const divXpFixed = (a: bigint, b: bigint): bigint => { + if (b === 0n) throw new Error('ECLP_DIVISION_BY_ZERO'); + return (a * ONE_XP) / b; +}; + +function fixedParamsFor(p: EclpParams): FixedEclpParams | null { + const raw = p.fixedParams; + if (!raw) return null; + try { + return { + alpha: BigInt(raw.alpha), + beta: BigInt(raw.beta), + c: BigInt(raw.c), + s: BigInt(raw.s), + lambda: BigInt(raw.lambda), + }; + } catch { + return null; + } +} + +function fixedDerivedFor(p: EclpParams): FixedDerivedEclpParams | null { + const raw = p.derivedParams; + if (!raw) return null; + try { + return { + tauAlphaX: BigInt(raw.tauAlphaX), + tauAlphaY: BigInt(raw.tauAlphaY), + tauBetaX: BigInt(raw.tauBetaX), + tauBetaY: BigInt(raw.tauBetaY), + u: BigInt(raw.u), + v: BigInt(raw.v), + w: BigInt(raw.w), + z: BigInt(raw.z), + dSq: BigInt(raw.dSq), + }; + } catch { + return null; + } +} + +function fixedMulA(p: FixedEclpParams, t: { x: bigint; y: bigint }) { + return { + x: + divDownMagFixed(mulDownMagFixed(p.c, t.x), p.lambda) - + divDownMagFixed(mulDownMagFixed(p.s, t.y), p.lambda), + y: mulDownMagFixed(p.s, t.x) + mulDownMagFixed(p.c, t.y), + }; +} + +/** A^-1 for normal-precision vectors (the output is normal precision). */ +function fixedMulAinv(p: FixedEclpParams, t: { x: bigint; y: bigint }) { + return { + x: + mulDownMagFixed(mulDownMagFixed(t.x, p.lambda), p.c) + + mulDownMagFixed(t.y, p.s), + y: + -mulDownMagFixed(mulDownMagFixed(t.x, p.lambda), p.s) + + mulDownMagFixed(t.y, p.c), + }; +} + +/** A^-1 for the 38-decimal stored tau endpoints (the output is extra + * precision, matching GyroECLPMath.mulAinv). */ +function fixedMulAinvXp(p: FixedEclpParams, t: { x: bigint; y: bigint }) { + return { + x: + mulDownMagFixed(mulDownMagFixed(t.x, p.lambda), p.c) + + mulDownMagFixed(t.y, p.s), + y: + -mulDownMagFixed(mulDownMagFixed(t.x, p.lambda), p.s) + + mulDownMagFixed(t.y, p.c), + }; +} + +function integerSqrt(value: bigint): bigint { + if (value <= 0n) return 0n; + let guess = 1n << BigInt((value.toString(2).length + 1) >> 1); + while (true) { + const next = (guess + value / guess) >> 1n; + if (next >= guess) return guess; + guess = next; + } +} + +/** GyroPoolMath.sqrt(input, 5): fixed-point floor sqrt(input). */ +function sqrtFixed(value: bigint): bigint { + return integerSqrt(value * WAD); +} + +/** + * The Balancer FixedPoint/LogExpMath implementation used by + * GyroECLPMath.eta. This is intentionally kept separate from GyroPoolMath's + * integer square root: Balancer's `powDown(x, 0.5e18)` first evaluates the + * logarithm/exponential approximation and then subtracts its relative-error + * margin. A mathematically exact square root is close, but not interchangeable + * at the wei level on the ECLP boundary branches. + */ +function ln36Fixed(value: bigint): bigint { + const x = value * WAD; + const z = ((x - ONE_36) * ONE_36) / (x + ONE_36); + const zSquared = (z * z) / ONE_36; + let num = z; + let series = num; + for (const denominator of [3n, 5n, 7n, 9n, 11n, 13n, 15n]) { + num = (num * zSquared) / ONE_36; + series += num / denominator; + } + return series * 2n; +} + +function lnFixed(value: bigint): bigint { + let a = value; + let negative = false; + if (a < WAD) { + a = (WAD * WAD) / a; + negative = true; + } + + // Exact 18/20-decimal constants from Balancer's LogExpMath.sol. They + // decompose ln(a) into powers of two before the short Taylor series around + // one. + const a0 = 38877084059945950922200000000000000000000000000000000000n; + const a1 = 6235149080811616882910000000n; + const a2 = 7896296018268069516100000000000000n; + const a3 = 888611052050787263676000000n; + const a4 = 298095798704172827474000n; + const a5 = 5459815003314423907810n; + const a6 = 738905609893065022723n; + const a7 = 271828182845904523536n; + const a8 = 164872127070012814685n; + const a9 = 128402541668774148407n; + const a10 = 113314845306682631683n; + const a11 = 106449445891785942956n; + let sum = 0n; + if (a >= a0 * WAD) { + a /= a0; + sum += 128n * WAD; + } + if (a >= a1 * WAD) { + a /= a1; + sum += 64n * WAD; + } + + sum *= 100n; + a *= 100n; + const decompositions: Array<[bigint, bigint]> = [ + [a2, 32n * ONE_20], + [a3, 16n * ONE_20], + [a4, 8n * ONE_20], + [a5, 4n * ONE_20], + [a6, 2n * ONE_20], + [a7, ONE_20], + [a8, ONE_20 / 2n], + [a9, ONE_20 / 4n], + [a10, ONE_20 / 8n], + [a11, ONE_20 / 16n], + ]; + for (const [factor, exponent] of decompositions) { + if (a >= factor) { + a = (a * ONE_20) / factor; + sum += exponent; + } + } + + const z = ((a - ONE_20) * ONE_20) / (a + ONE_20); + const zSquared = (z * z) / ONE_20; + let num = z; + let series = num; + for (const denominator of [3n, 5n, 7n, 9n, 11n]) { + num = (num * zSquared) / ONE_20; + series += num / denominator; + } + const result = (sum + series * 2n) / 100n; + return negative ? -result : result; +} + +function expFixed(value: bigint): bigint { + let x = value; + let negative = false; + if (x < 0n) { + x = -x; + negative = true; + } + + const x0 = 128n * WAD; + const x1 = 64n * WAD; + const a0 = 38877084059945950922200000000000000000000000000000000000n; + const a1 = 6235149080811616882910000000n; + const a2 = 7896296018268069516100000000000000n; + const a3 = 888611052050787263676000000n; + const a4 = 298095798704172827474000n; + const a5 = 5459815003314423907810n; + const a6 = 738905609893065022723n; + const a7 = 271828182845904523536n; + const a8 = 164872127070012814685n; + const a9 = 128402541668774148407n; + let first = 1n; + if (x >= x0) { + x -= x0; + first = a0; + } else if (x >= x1) { + x -= x1; + first = a1; + } + x *= 100n; + + let product = ONE_20; + const products: Array<[bigint, bigint]> = [ + [32n * ONE_20, a2], + [16n * ONE_20, a3], + [8n * ONE_20, a4], + [4n * ONE_20, a5], + [2n * ONE_20, a6], + [ONE_20, a7], + [ONE_20 / 2n, a8], + [ONE_20 / 4n, a9], + ]; + for (const [threshold, factor] of products) { + if (x >= threshold) { + x -= threshold; + product = (product * factor) / ONE_20; + } + } + + let term = x; + let series = ONE_20 + term; + for (const denominator of [2n, 3n, 4n, 5n, 6n, 7n, 8n, 9n, 10n, 11n, 12n]) { + term = ((term * x) / ONE_20) / denominator; + series += term; + } + const result = (((product * series) / ONE_20) * first) / 100n; + return negative ? (WAD * WAD) / result : result; +} + +function logExpPowFixed(value: bigint, exponent: bigint): bigint { + if (exponent === 0n) return WAD; + if (value === 0n) return 0n; + const lower = WAD - 100_000_000_000_000_000n; + const upper = WAD + 100_000_000_000_000_000n; + const log = lower < value && value < upper + ? (() => { + const ln36 = ln36Fixed(value); + return ((ln36 / WAD) * exponent + ((ln36 % WAD) * exponent) / WAD) / WAD; + })() + : (lnFixed(value) * exponent) / WAD; + return expFixed(log); +} + +function sqrtPowDownFixed(value: bigint): bigint { + const raw = logExpPowFixed(value, WAD / 2n); + const maxError = ((raw * 10_000n + WAD - 1n) / WAD) + 1n; + return raw > maxError ? raw - maxError : 0n; +} + +/** GyroECLPMath.tau in normal precision. The simulator only feeds the + * oracle NAV mark positive prices, so the signed intermediate operations below + * cover the complete E-CLP range without a floating-point fallback. */ +function fixedTau(p: FixedEclpParams, pxIny: bigint) { + const nd = fixedMulA(p, { x: -WAD, y: pxIny }); + const pxc = -divDownMagFixed(nd.y, nd.x); + const z = sqrtPowDownFixed(WAD + mulDownMagFixed(pxc, pxc)); + return { + x: divDownMagFixed(pxc, z), + y: divDownMagFixed(WAD, z), + }; +} + +function calcAtAChi( + x: bigint, + y: bigint, + p: FixedEclpParams, + d: FixedDerivedEclpParams, +): bigint { + const dSq2 = mulXpFixed(d.dSq, d.dSq); + let termXp = divDownMagFixed(d.w, p.lambda) + d.z; + termXp = divDownMagFixed(termXp, p.lambda); + termXp = divXpFixed(termXp, dSq2); + let value = mulDownXpToNpFixed( + mulDownMagFixed(x, p.c) - mulDownMagFixed(y, p.s), + termXp, + ); + let termNp = + mulDownMagFixed(mulDownMagFixed(x, p.lambda), p.s) + + mulDownMagFixed(mulDownMagFixed(y, p.lambda), p.c); + value += mulDownXpToNpFixed(termNp, divXpFixed(d.u, dSq2)); + termNp = mulDownMagFixed(x, p.s) + mulDownMagFixed(y, p.c); + value += mulDownXpToNpFixed(termNp, divXpFixed(d.v, dSq2)); + return value; +} + +function calcAChiAChiInXp( + p: FixedEclpParams, + d: FixedDerivedEclpParams, +): bigint { + const dSq3 = mulXpFixed(mulXpFixed(d.dSq, d.dSq), d.dSq); + let value = mulUpMagFixed( + p.lambda, + divXpFixed(mulXpFixed(2n * d.u, d.v), dSq3), + ); + const lambdaSquaredTerm = divXpFixed( + mulXpFixed(d.u + 1n, d.u + 1n), + dSq3, + ); + value += mulUpMagFixed(mulUpMagFixed(lambdaSquaredTerm, p.lambda), p.lambda); + value += divXpFixed(mulXpFixed(d.v, d.v), dSq3); + const termXp = divUpMagFixed(d.w, p.lambda) + d.z; + value += divXpFixed(mulXpFixed(termXp, termXp), dSq3); + return value; +} + +function calcMinAtxAChiySqPlusAtxSq( + x: bigint, + y: bigint, + p: FixedEclpParams, + d: FixedDerivedEclpParams, +): bigint { + let termNp = + mulUpMagFixed(mulUpMagFixed(mulUpMagFixed(x, x), p.c), p.c) + + mulUpMagFixed(mulUpMagFixed(mulUpMagFixed(y, y), p.s), p.s); + termNp -= mulDownMagFixed(mulDownMagFixed(mulDownMagFixed(x, y), 2n * p.c), p.s); + + const dSq4 = mulXpFixed(mulXpFixed(mulXpFixed(d.dSq, d.dSq), d.dSq), d.dSq); + let termXp = mulXpFixed(d.u, d.u); + termXp += divDownMagFixed(mulXpFixed(2n * d.u, d.v), p.lambda); + termXp += divDownMagFixed(divDownMagFixed(mulXpFixed(d.v, d.v), p.lambda), p.lambda); + termXp = divXpFixed(termXp, dSq4); + let value = mulDownXpToNpFixed(-termNp, termXp); + value += mulDownXpToNpFixed( + divDownMagFixed(divDownMagFixed(termNp - 9n, p.lambda), p.lambda), + divXpFixed(ONE_XP, d.dSq), + ); + return value; +} + +function calc2AtxAtyAChixAChiy( + x: bigint, + y: bigint, + p: FixedEclpParams, + d: FixedDerivedEclpParams, +): bigint { + let termNp = mulDownMagFixed( + mulDownMagFixed(mulDownMagFixed(x, x) - mulUpMagFixed(y, y), 2n * p.c), + p.s, + ); + const xy = mulDownMagFixed(y, 2n * x); + termNp += mulDownMagFixed(mulDownMagFixed(xy, p.c), p.c); + termNp -= mulDownMagFixed(mulDownMagFixed(xy, p.s), p.s); + + const dSq4 = mulXpFixed(mulXpFixed(mulXpFixed(d.dSq, d.dSq), d.dSq), d.dSq); + let termXp = mulXpFixed(d.z, d.u) + divDownMagFixed(divDownMagFixed(mulXpFixed(d.w, d.v), p.lambda), p.lambda); + termXp += divDownMagFixed(mulXpFixed(d.w, d.u) + mulXpFixed(d.z, d.v), p.lambda); + termXp = divXpFixed(termXp, dSq4); + return mulDownXpToNpFixed(termNp, termXp); +} + +function calcMinAtyAChixSqPlusAtySq( + x: bigint, + y: bigint, + p: FixedEclpParams, + d: FixedDerivedEclpParams, +): bigint { + let termNp = + mulUpMagFixed(mulUpMagFixed(mulUpMagFixed(x, x), p.s), p.s) + + mulUpMagFixed(mulUpMagFixed(mulUpMagFixed(y, y), p.c), p.c); + termNp += mulUpMagFixed(mulUpMagFixed(mulUpMagFixed(x, y), 2n * p.s), p.c); + + const dSq4 = mulXpFixed(mulXpFixed(mulXpFixed(d.dSq, d.dSq), d.dSq), d.dSq); + let termXp = mulXpFixed(d.z, d.z) + divDownMagFixed(divDownMagFixed(mulXpFixed(d.w, d.w), p.lambda), p.lambda); + termXp += divDownMagFixed(mulXpFixed(2n * d.z, d.w), p.lambda); + termXp = divXpFixed(termXp, dSq4); + let value = mulDownXpToNpFixed(-termNp, termXp); + value += mulDownXpToNpFixed(termNp - 9n, divXpFixed(ONE_XP, d.dSq)); + return value; +} + +function balancerInvariantDown( + p: FixedEclpParams, + d: FixedDerivedEclpParams, + x: bigint, + y: bigint, +): bigint { + const atAChi = calcAtAChi(x, y, p, d); + const term1 = calcMinAtxAChiySqPlusAtxSq(x, y, p, d); + const term2 = calc2AtxAtyAChixAChiy(x, y, p, d); + const term3 = calcMinAtyAChixSqPlusAtySq(x, y, p, d); + let sqrtTerm = term1 + term2 + term3; + let error = (mulUpMagFixed(x, x) + mulUpMagFixed(y, y)) / ONE_XP; + sqrtTerm = sqrtTerm > 0n ? sqrtFixed(sqrtTerm) : 0n; + if (sqrtTerm > 0n) { + error = divUpMagFixed(error + 1n, 2n * sqrtTerm); + } else { + error = error > 0n ? sqrtFixed(error) : 1_000_000_000n; + } + error = ((mulUpMagFixed(p.lambda, x + y) / ONE_XP) + error + 1n) * 20n; + + const denominator = divXpFixed(ONE_XP, calcAChiAChiInXp(p, d) - ONE_XP); + const current = mulDownXpToNpFixed(atAChi + sqrtTerm - error, denominator); + error = mulUpXpToNpFixed(error, denominator); + const lambdaSq = (p.lambda * p.lambda) / (10n ** 36n); + error += (mulUpXpToNpFixed(current, denominator) * lambdaSq * 40n) / ONE_XP + 1n; + const roundedDown = current - error; + return roundedDown > 0n ? roundedDown : 0n; +} + +function removeExtraPrecision(value: bigint): bigint { + return value / XP_TO_NP; +} + +/** + * The Balancer EclpLPOracle TVL mark for WAD balances and WAD token prices. + * It follows the oracle's order exactly: live scaled balances → Gyro + * `computeInvariant(..., ROUND_DOWN)` → `_computeEclpTvl` → floor. A local + * curve without both deployment response payloads (`fixedParams` and + * `derivedParams`) falls back to the geometric curve already used by the quote + * explorer; a canonical response carries both, so production APYs take the + * fixed-point path. + */ +export function eclpOracleTvlWad( + p: EclpParams, + balances: { x: bigint; y: bigint }, + prices: { x: bigint; y: bigint } = { x: WAD, y: WAD }, +): bigint { + if (balances.x <= 0n && balances.y <= 0n) return 0n; + const d = fixedDerivedFor(p); + const fp = fixedParamsFor(p); + if (!d || !fp) { + const invariant = eclpInvariant(p, fromFixedWad(balances.x), fromFixedWad(balances.y)); + return toWadFloor( + eclpTVL(p, invariant, fromFixedWad(prices.x), fromFixedWad(prices.y)), + ); + } + const invariant = balancerInvariantDown(fp, d, balances.x, balances.y); + if (invariant <= 0n) return 0n; + // EclpLPOracle rejects either feed before doing its branch calculation. + // Keep the same lower bound instead of silently returning a plausible but + // non-contract value for a malformed/underflowed price feed. + const minPrice = 100_000_000_000n; // 1e-7 in 18-decimal scale + if (prices.x < minPrice || prices.y < minPrice) { + throw new Error('ECLP_TOKEN_PRICE_TOO_SMALL'); + } + const pxIny = divDownMagFixed(prices.x, prices.y); + let valuePerInvariant: bigint; + const tauBeta = fixedMulAinvXp(fp, { x: d.tauBetaX, y: d.tauBetaY }); + const tauAlpha = fixedMulAinvXp(fp, { x: d.tauAlphaX, y: d.tauAlphaY }); + if (pxIny < fp.alpha) { + const bP = removeExtraPrecision(tauBeta.x - tauAlpha.x); + valuePerInvariant = mulDownMagFixed(bP, prices.x); + } else if (pxIny > fp.beta) { + const bP = removeExtraPrecision(tauAlpha.y - tauBeta.y); + valuePerInvariant = mulDownMagFixed(bP, prices.y); + } else { + const v = fixedMulAinv(fp, fixedTau(fp, pxIny)); + const vec = { + x: removeExtraPrecision(tauBeta.x) - v.x, + y: removeExtraPrecision(tauAlpha.y) - v.y, + }; + valuePerInvariant = + mulDownMagFixed(prices.x, vec.x) + mulDownMagFixed(prices.y, vec.y); + } + return valuePerInvariant > 0n + ? mulDownMagFixed(valuePerInvariant, invariant) + : 0n; +} + +const fromFixedWad = (value: bigint): number => Number(value) / 1e18; + // Invariant L from NAV-value balances (X, Y), in closed form. The pool sits on // the curve where (X, Y) = L·reservesPerL(p) = L·(corner − mulAinv(tau(p))), with // corner = (mulAinv(tauβ).x, mulAinv(tauα).y). Since mulA(mulAinv(tau)) = tau and @@ -78,8 +692,8 @@ export function eclpTVL(p: EclpParams, invariant: number, px: number, py: number // the EclpLPOracle TVL does not drift as the pool is imbalanced. Conserved by swaps. export function eclpInvariant(p: EclpParams, X: number, Y: number): number { if (X <= 0 && Y <= 0) return 0; - const aB = mulAinv(p, tau(p, p.beta)); - const aA = mulAinv(p, tau(p, p.alpha)); + const aB = mulAinv(p, tauEndpoint(p, 'beta')); + const aA = mulAinv(p, tauEndpoint(p, 'alpha')); if (Y <= 0) return X / (aB.x - aA.x); // out of band: all token0 if (X <= 0) return Y / (aA.y - aB.y); // out of band: all token1 const corner: V2 = { x: aB.x, y: aA.y }; diff --git a/lib/day/engine/engine.test.ts b/lib/day/engine/engine.test.ts index 97b7a28..630a64e 100644 --- a/lib/day/engine/engine.test.ts +++ b/lib/day/engine/engine.test.ts @@ -5,10 +5,10 @@ import { MarketState } from "./types"; import { Sim, defaultConfig, steadyYear, type StepInput } from "./runner"; -import { adaptYTargetWadWithAverage, jtRedeem, newMarket, postOpAccountingWad, sharesForValueWad, valueForSharesWad, ydmShareWad } from "./engine"; -import { toWad } from "./wad"; +import { accruePoolCarry, adaptYTargetWadWithAverage, jtRedeem, ltRawNAVWad, newMarket, poolValueWad, postOpAccountingWad, secondarySell, sharesForValueWad, valueForSharesWad, ydmShareWad } from "./engine"; +import { WAD, mulDiv, toWad } from "./wad"; import { YEAR_SEC, ydmShare } from "./ydm"; -import { eclpParamsForWeight, eclpSellValue, eclpInvariant, eclpTVL, reservesPerL } from "./eclp"; +import { eclpOracleTvlWad, eclpParamsForWeight, eclpSellValue, eclpInvariant, eclpTVL, reservesPerL, type EclpParams } from "./eclp"; import "./secondary-exit-fee.test"; let passed = 0; @@ -496,7 +496,109 @@ console.log("\n25. Share mint and redemption pricing carry the one-wei virtual o } // --------------------------------------------------------------------------- -console.log("\n26. Adaptive YDM evolution matches Solady expWad below the clamp"); +console.log("\n26. SLP BPT valuation follows Balancer's EclpLPOracle fixed-point path"); +{ + // Production Royco Day E-CLP params/derived values from the deployment + // registry. The expected mark is the result of + // GyroECLPPool.computeInvariant(ROUND_DOWN) + EclpLPOracle._computeEclpTvl + // for 100 ST and 900 quote units at 1:1 oracle prices. + const productionEclp: EclpParams = { + alpha: 0.98, + beta: 1.0003, + c: 0.7071067811865475, + s: 0.7071067811865475, + lambda: 250, + fixedParams: { + alpha: "980000000000000000", + beta: "1000300000000000000", + c: "707106781186547524", + s: "707106781186547524", + lambda: "250000000000000000000", + }, + derivedParams: { + tauAlphaX: "-92975357432315416605491271255356493443", + tauAlphaY: "36818241543196904975774583017121171403", + tauBetaX: "3746804827358009532998249894673148143", + tauBetaY: "99929782615523019584751990190862643080", + u: "48361081129836713014414996374502815654", + v: "68374012079359962202743630490639666742", + w: "31555770536163057268712062638611327323", + z: "-44614276302478703485664720423548546517", + dSq: "99999999999999999886624093342106115200", + }, + }; + const oracleTvl = eclpOracleTvlWad(productionEclp, { + x: 100n * WAD, + y: 900n * WAD, + }); + check( + "canonical production E-CLP mark matches Balancer's Solidity oracle", + oracleTvl === 999985554810015442264n, + `tvl=${oracleTvl}`, + ); + check( + "E-CLP lower-bound price branch matches Balancer's Solidity oracle", + eclpOracleTvlWad( + productionEclp, + { x: 100n * WAD, y: 900n * WAD }, + { x: 980_000_000_000_000_000n, y: WAD }, + ) === 985120519499604236300n, + ); + check( + "E-CLP interior price branch preserves Balancer LogExpMath rounding", + eclpOracleTvlWad( + productionEclp, + { x: 100n * WAD, y: 900n * WAD }, + { x: WAD, y: 1_010_000_000_000_000_000n }, + ) === 1004630484111324783237n, + ); + let smallPriceRejected = false; + try { + eclpOracleTvlWad( + productionEclp, + { x: 100n * WAD, y: 900n * WAD }, + { x: 99_999_999_999n, y: WAD }, + ); + } catch (error) { + smallPriceRejected = error instanceof Error && error.message === 'ECLP_TOKEN_PRICE_TOO_SMALL'; + } + check('E-CLP rejects prices below Balancer\'s oracle floor', smallPriceRejected); + + const cfg = defaultConfig({ + eclpParams: productionEclp, + stableYield: 0, + poolTurnoverPerYear: 1, + swapFeeBps: 100, + riskYDM: { mode: "static", y0: 0, yTarget: 0, y100: 0 }, + liqYDM: { mode: "static", y0: 0, yTarget: 0, y100: 0 }, + }); + const state = newMarket(cfg, { st: 1000, jt: 250, lt: 150 }); + const sale = secondarySell(state, cfg, 10); + check("secondary sale used to create an off-peg pool", sale.ok); + const oracleBase = ltRawNAVWad(state, cfg); + const spotBase = poolValueWad(state); + check( + "off-peg SLP mark is distinct from manipulable spot reserve sum", + oracleBase !== spotBase, + `oracle=${oracleBase} spot=${spotBase}`, + ); + const stableBefore = state.pool.stable; + accruePoolCarry(state, cfg, YEAR_SEC); + const swapIncome = state.pool.stable - stableBefore; + const expectedSwapIncome = mulDiv( + mulDiv(oracleBase, toWad(0.01), WAD), + BigInt(YEAR_SEC), + BigInt(YEAR_SEC), + ); + check( + "swap-fee carry/APY uses the oracle-valued BPT base", + swapIncome === expectedSwapIncome, + `income=${swapIncome} expected=${expectedSwapIncome}`, + ); +} + +// --------------------------------------------------------------------------- +console.log("\n27. Adaptive YDM evolution matches Solady expWad below the clamp"); { const cfg = { mode: "adaptive" as const, @@ -522,7 +624,7 @@ console.log("\n26. Adaptive YDM evolution matches Solady expWad below the clamp" } // --------------------------------------------------------------------------- -console.log("\n27. Junior redemption preserves the accountant recovery ledger"); +console.log("\n28. Junior redemption preserves the accountant recovery ledger"); { const result = postOpAccountingWad( { diff --git a/lib/day/engine/engine.ts b/lib/day/engine/engine.ts index 90ad7c5..5a7dd12 100644 --- a/lib/day/engine/engine.ts +++ b/lib/day/engine/engine.ts @@ -3,8 +3,9 @@ // ----------------------------------------------------------------------------- // Senior/Junior accounting, utilization, premiums, fees, share conversion, and // kernel operation gates use 18-decimal bigint arithmetic with explicit -// Solidity rounding. The ECLP invariant is an off-chain venue model; its -// floating-point result is quantized to WAD before it enters accountant state. +// Solidity rounding. The ECLP venue mark follows Balancer's EclpLPOracle when +// the deployment response includes the pool's stored fixed/derived parameters; +// legacy/local curves use the deterministic geometric fallback in eclp.ts. // ============================================================================= import { @@ -32,10 +33,9 @@ import { } from './wad'; import { type EclpParams, - eclpInvariant, + eclpOracleTvlWad, eclpParamsForWeight, eclpSellValue, - eclpTVL, reservesPerL, } from './eclp'; @@ -175,7 +175,7 @@ export function poolSeniorWeightAtPeg(cfg: MarketConfig): number { function eclpParamsFor(cfg: MarketConfig): EclpParams { const supplied = cfg.eclpParams; const key = supplied - ? `${supplied.alpha}|${supplied.beta}|${supplied.c}|${supplied.s}|${supplied.lambda}` + ? `${supplied.alpha}|${supplied.beta}|${supplied.c}|${supplied.s}|${supplied.lambda}|${supplied.fixedParams ? JSON.stringify(supplied.fixedParams) : ''}|${supplied.derivedParams ? JSON.stringify(supplied.derivedParams) : ''}` : `${DAY_ECLP_SIMULATION_LAMBDA}|${cfg.eclpBandWidth}`; if (!eclpCache || eclpCache.key !== key) { eclpCache = { @@ -203,11 +203,16 @@ export const poolValueWad = (state: LiveState): bigint => mulDiv(state.pool.stShares, stPriceWad(state), WAD) + state.pool.stable; export function ltRawNAVWad(state: LiveState, cfg: MarketConfig): bigint { - const seniorLeg = fromWad(mulDiv(state.pool.stShares, stPriceWad(state), WAD)); - const stableLeg = fromWad(state.pool.stable); - if (seniorLeg <= 0 && stableLeg <= 0) return 0n; const params = eclpParamsFor(cfg); - return toWad(eclpTVL(params, eclpInvariant(params, seniorLeg, stableLeg), 1, 1)); + // The Balancer oracle consumes the Vault's live scaled balances, not a + // Number approximation of the pool composition. Keep both legs in WAD and + // let eclpOracleTvlWad reproduce GyroECLPPool.computeInvariant(ROUND_DOWN) + // followed by EclpLPOracle._computeEclpTvl. + const seniorLegWad = mulDiv(state.pool.stShares, stPriceWad(state), WAD); + return eclpOracleTvlWad(params, { + x: seniorLegWad, + y: state.pool.stable, + }); } export const ltOwnedSTValueWad = (state: LiveState): bigint => @@ -1245,7 +1250,10 @@ export function accruePoolCarry(state: LiveState, cfg: MarketConfig, dtSec: numb if (dt <= 0n) return; const swapAPY = toWad((cfg.poolTurnoverPerYear * cfg.swapFeeBps) / 10_000); const stableAPY = toWad(cfg.stableYield); - const swapIncome = mulDiv(mulDiv(poolValueWad(state), swapAPY, WAD), dt, BigInt(YEAR_SEC)); + // Swap fees accrue on the oracle-valued BPT, not the naive spot sum of its + // reserves. The latter changes when a trader moves the E-CLP off peg and + // would make the simulator's SLP APY depend on a manipulable composition. + const swapIncome = mulDiv(mulDiv(ltRawNAVWad(state, cfg), swapAPY, WAD), dt, BigInt(YEAR_SEC)); const stableIncome = mulDiv(mulDiv(state.pool.stable, stableAPY, WAD), dt, BigInt(YEAR_SEC)); state.pool.stable += swapIncome + stableIncome; } diff --git a/lib/day/engine/vectors/contract-lock.json b/lib/day/engine/vectors/contract-lock.json index 0ff5d81..a65f1b4 100644 --- a/lib/day/engine/vectors/contract-lock.json +++ b/lib/day/engine/vectors/contract-lock.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/roycoprotocol/royco-day", - "commit": "9764c9e20c8e8af7df1358f228c4be83b78be97f", + "commit": "107a5dd8b1e069ca23855c7f7e89de523678269b", "solc": "0.8.35", "foundry": "1.7.1", "schemaVersion": 3 diff --git a/lib/day/engine/vectors/golden.json b/lib/day/engine/vectors/golden.json index bd83344..946fae4 100644 --- a/lib/day/engine/vectors/golden.json +++ b/lib/day/engine/vectors/golden.json @@ -83,7 +83,7 @@ ], "provenance": { "repository": "https://github.com/roycoprotocol/royco-day", - "commit": "9764c9e20c8e8af7df1358f228c4be83b78be97f", + "commit": "107a5dd8b1e069ca23855c7f7e89de523678269b", "solc": "0.8.35", "foundry": "1.7.1", "harness": "lib/day/engine/harness/DayVectorGen.t.sol", diff --git a/scripts/day-simulator/template-lock.json b/scripts/day-simulator/template-lock.json index 33438ce..05d2627 100644 --- a/scripts/day-simulator/template-lock.json +++ b/scripts/day-simulator/template-lock.json @@ -34,21 +34,21 @@ "lib/day-simulator-template/permalink.ts": "776525c1a9928ebaf876b45d197e19b2ef12a7f51114d94ab03defd0caf5b1e0", "lib/day-simulator-template/permalink.test.ts": "13fe4d22f7f49c1a96677e31f882068270f9943be00edc5493a64f2b12e620b2", "lib/day-simulator-template/refill.ts": "bb41d8ef450523aa9006fe1f9f2ed422ae0640053d44c3709151fe2bd2ada20d", - "lib/day-simulator-template/runtime.test.ts": "1d50ce597a7a16807dfa5e670dc2e51310e19115b2ba6bfeb18f52faa0ae3cd8", + "lib/day-simulator-template/runtime.test.ts": "50ea274c467c2ca1f37afdaf62a0862e0c3586cf1caf6fe4abb862a81f9c1cc9", "lib/day-simulator-template/runtime.ts": "f54ea48cbbfc5ad4d1977aa7b0507cf7ddb91ae10606e90ab1ed280c89a83b86", "lib/day-simulator-template/series.ts": "fcfad3de9a17225bdf1aedf672eb2c756af5100db417169bff0569a7e3082db4", "lib/day-simulator-template/stress.test.ts": "9637ea95cea0c6c002873b74caca5bde780d92c929076b7568e3e28075ff87f0", "lib/day-simulator-template/source-parser.d.mts": "9923e23ea6dd8a5f1284abd04f385a8bf896dda721db2ed7fa26fea03d1c569c", "lib/day-simulator-template/source-parser.mjs": "1b8b84544388e9b59b15db199b170e0e53f70acae53210970783f1dc18f63350", - "lib/day/engine/eclp.ts": "579241688bb6d6f23e7649c4289a3744b2c778fcf10bf336f6407edd9858e74a", - "lib/day/engine/engine.test.ts": "f15a8c5af000c3780a95dc7bd9750c3ee7919cd80d3b600117ba22de2de33769", - "lib/day/engine/engine.ts": "b2db6ae68f37b064a4dd6677fdfa0aad15a2ed97ea18b6668dc0874b85d85e1c", + "lib/day/engine/eclp.ts": "3ed588e6fc924a8cce5edb4fb5b570c4f4fdb388fc4e6d8a307f9193dc119969", + "lib/day/engine/engine.test.ts": "202ce75fb241a3688de2569752f67be986a4c51bdaded06918a401e95797e8ad", + "lib/day/engine/engine.ts": "a5892b9752c5129e202a17d35911682ba6545b968af8b0e18f6aab22b608552d", "lib/day/engine/harness/DayVectorGen.t.sol": "89934cfbb6d9b162636127c261cd507509b0f7b046e1a7d429cab14d9975f6e7", "lib/day/engine/parity.ts": "fae87e6f36bb65c1158754f5af283e094758d942fbc13663f99c6846faca9280", "lib/day/engine/runner.ts": "a66f034d968daebac9b67f8c8405130e078b2b45ef7899f520cfd70f92b422be", "lib/day/engine/types.ts": "34fb53648ae9deebbd8de93708830371e14ab4cb33ea1e1f9200b7238c17e70f", - "lib/day/engine/vectors/contract-lock.json": "28a51e29f37153e4a3a7ff33a74d9d0a9bd1d3a3dedb33aaf2cbf03debaf7b82", - "lib/day/engine/vectors/golden.json": "39e94f0bed4b6c883fe043efc9475c7f599c27c42480b10b4d6ced3bb2af93b7", + "lib/day/engine/vectors/contract-lock.json": "1827f9f6f09e669321dc24c98aa07e6f090932a81020997a8b597f8d5156d20f", + "lib/day/engine/vectors/golden.json": "baff011ac15f88ad88d7fff471b7f5611fea85b17b057ed6a41928ac10cdf248", "lib/day/engine/wad.ts": "8f789372baeba5ef3c33c7f62c78aec0356d30ba217e456e0e65fa9a3daa4474", "lib/day/engine/ydm.ts": "5e472bbf7df56099a6c9ff5ea58bb6abd265032eacaaf28273a5276fd1fb3ecf", "lib/try/vectors.golden.json": "5c77dfea7fb61f92fb747f0d16ba248eaa3b31f04317d48ad69b471d4ad36828", @@ -63,7 +63,7 @@ "scripts/day-simulator/preview.mjs": "9cdfe3c04fb07c3b78434459cb43ec7cb713a1d9012775140c892665af2fc4af", "scripts/day-simulator/verify-runtime.ts": "2d797bcd7cf976c71889d74c5ece3dc84d5bce94d6ea3766b272f08f5b1610c4", "scripts/day-simulator/verify.mjs": "d85b10098723c21787af0e8739f1f9d73eaec1fde60932a4a1b615971392117e", - "docs/NEW_DAY_SIMULATOR.md": "3ea014ee0839f715c1a5469ee4a0ce4161f4e2cc20ab622f1cd7605b4b0048d5", + "docs/NEW_DAY_SIMULATOR.md": "bfa092f18f7bd3ec49ec1399eab948e2b5a971efb50bb8ef3204d37f5907c83d", "package.json": "6b6bb91c0e1669381ecd008f9409140b354edd6b6559ac486dd5a777a6040992", "lib/day-simulator-template/backtest.test.ts": "d978f6fe8755d22778a51ac3699d5ae1de36dcfa8690ba65ffcc481afc93cb6f", "lib/day-simulator-template/backtest.ts": "d2495ef2256bb3b529df60bb6e13dfb28fa774476661a3573b2c896e8137c8e6" diff --git a/scripts/day-v3/model-output-parity.test.mjs b/scripts/day-v3/model-output-parity.test.mjs index 75e32cc..f38c206 100644 --- a/scripts/day-v3/model-output-parity.test.mjs +++ b/scripts/day-v3/model-output-parity.test.mjs @@ -235,8 +235,8 @@ for (const gate of [ // remain the responsibility of Royco Deploy and cannot gate scenario APYs. assert.match( summary, - /useDayV3SimulationPoolDesign\(\s*poolDesignGoals,\s*sourceApyPct,?\s*\)/, - "The unified simulator must use the four-goal simulation pool-design request", + /useDayV3SimulationPoolDesign\(\s*poolDesignGoals,\s*sourceApyPct,\s*requestedSwapFeeBps,?\s*\)/, + "The unified simulator must use the four goals plus selected market fee in the simulation request", ); assert.doesNotMatch( summary, @@ -447,44 +447,47 @@ assert.match( "Annual volume is the issuer's forecast, not a pinned zero", ); -// The pool's swap fee is settable per market. It is the one issuer answer the -// canonical service cannot be asked to honour — its request body is -// key-restricted and its parser asserts the returned fee equals the live -// template policy — so the whole feature turns on the fee winning locally and -// the canonical outcomes standing down when it does. +// The pool's swap fee is a per-market Gyro pool-creation parameter. It is part +// of the canonical solver context, so the response must echo the exact fee +// requested by the simulator instead of inheriting a TemplatePolicy value. assert.match( summary, - /swapFeeBps: swapFeeBps \?\? defaults\.swapFeeBps/, - "A hand-set pool fee must reach the shared accountant, not just the display", + /swapFeeBps: requestedSwapFeeBps/, + "The selected market fee must reach the shared accountant, not just the display", ); assert.match( summary, /\.\.\.\(hasCurveOverride \? canonicalPolicy : canonical\),\s*\.\.\.\(feeOverridden \? \{ swapFeeBps: swapFeeBps as number \} : \{\}\),/, - "The engine override must keep the live E-CLP and protocol fees while replacing only the fee — except when the reader drew the curve themselves", + "An explicit market-fee edit must keep the canonical E-CLP and protocol fees while replacing only the fee", ); assert.match( summary, - /\]\.some\(\(value\) => value !== null\) \|\| feeOverridden \|\| premiumOverridden;/, - "A hand-set fee must suppress the canonical pool design like any other pool override", + /\]\.some\(\(value\) => value !== null\) \|\| premiumOverridden;/, + "Only curve edits must suppress the canonical pool design", ); assert.match( summary, /const canonicalPoolDesign =\s*rawCanonicalPoolDesign && !hasPoolOverride/, - "Canonical outcomes solved at another fee must not survive the override gate", + "Canonical outcomes must survive when the per-market fee is part of the solve", ); const poolDesignRequest = summary.slice( summary.indexOf("const poolDesignGoals ="), summary.indexOf("const activePoolDesign ="), ); +assert.match( + summary, + /useDayV3SimulationPoolDesign\(\s*poolDesignGoals,\s*sourceApyPct,\s*requestedSwapFeeBps,?\s*\)/, + "The selected market fee must enter the canonical simulation request", +); assert.doesNotMatch( poolDesignRequest, /swapFeeBps|feeOverridden/, - "A hand-set fee must never enter the canonical pool-design request", + "The selected market fee belongs in simulation context, not in the four-goal payload", ); -assert.doesNotMatch( +assert.match( simulationPoolDesign, /swapFeeBps/, - "The simulation pool-design contract must stay the four goals and the source APY", + "The simulation pool-design contract must carry the selected market fee", ); // The projection and the history have to run the same pool. Both merge these // overrides by spread, so a key present and `undefined` erases a real value. @@ -503,33 +506,33 @@ assert.match( /poolConfigOverrides=\{backtestConfigOverrides\}/, "The historical backtest must receive the same override object", ); -// Honesty: a fee the issuer typed is never presented as the market's own, and -// the swap-fee line in the position comparison stays a two-run engine +// Honesty: the fee's source names the selected market's Gyro pool parameters, +// and the swap-fee line in the position comparison stays a two-run engine // differential rather than fee x turnover arithmetic written into the UI. assert.match( summary, /policyBasis: feeOverridden\s*\?\s*\("issuer-fee" as const\)/, - "The live-models eyebrow must not claim to be live while a hand-set fee is in force", + "An explicit fee edit must be labeled as an issuer fee in the local model", ); assert.match( summary, - /feeSource: feeOverridden\s*\?\s*`Issuer-set pool swap fee/, - "The fee's provenance must name the issuer, never a template or product policy", + /feeSource: feeOverridden\s*\?\s*`Issuer-set market pool swap fee/, + "The fee's provenance must name the market pool parameter", ); assert.doesNotMatch( quoteAsset, /"live-template"|"product-policy"|"source-fact"/, - "The fee field must not label a hand-set fee as a template or policy fact", + "The fee field must not label a market fee as a template or product-policy fact", ); assert.match( quoteAsset, - /swapFeeBps === null \? "model-assumption" : "manual-override"/, - "A fee the reader typed reads as a manual override", + /swapFeeBps === null \|\|[\s\S]{0,160}defaultSwapFeeBps !== undefined[\s\S]{0,80}swapFeeBps === defaultSwapFeeBps/, + "An omitted or declared market fee reads as a model assumption", ); assert.match( quoteAsset, - /max=\{1000\}\s*min=\{0\.01\}/, - "The fee field's bounds are what keep previewSecondarySell from throwing", + /max=\{DAY_V3_POOL_SWAP_FEE_BPS_RANGE\.max\}\s*min=\{DAY_V3_POOL_SWAP_FEE_BPS_RANGE\.min\}/, + "The fee field must mirror Gyro's inclusive contract bounds", ); assert.doesNotMatch( `${summary}\n${goals}\n${quoteAsset}`, diff --git a/scripts/day-v3/v2-output-regression.test.ts b/scripts/day-v3/v2-output-regression.test.ts index 770dd4a..9ad6806 100644 --- a/scripts/day-v3/v2-output-regression.test.ts +++ b/scripts/day-v3/v2-output-regression.test.ts @@ -43,7 +43,8 @@ const actual = { }; // Captured after the authorized shared-engine correction that applies the -// exact-input pool fee before E-CLP pricing and the uniform 5% protocol fee on +// exact-input pool fee before E-CLP pricing, values the SLP BPT with Balancer's +// fixed-point EclpLPOracle path, and applies the uniform 5% protocol fee on // Junior and SLP yield premiums. The route/components remain frozen; this // baseline intentionally records the corrected all-in returns and exit quote. assert.deepEqual(actual, { @@ -62,9 +63,9 @@ assert.deepEqual(actual, { lt: 4444444.444444445, }, scenario: { - seniorApy: 0.04461662188292803, + seniorApy: 0.044616621878814655, juniorApy: 0.09985058019648951, - liquidityApy: 0.07048239010733948, + liquidityApy: 0.07048238362780723, }, capitalStack: { coverageLossLimit: 0.22222222222299992,