From 09ff4ae635de1849dc5b7d652a114f0f0c81adf1 Mon Sep 17 00:00:00 2001 From: amanraj1608 Date: Wed, 2 Sep 2026 01:10:23 +0400 Subject: [PATCH] Export the design as a Royco Deploy market config --- components/day-v3/DayV3Deploy.tsx | 76 --- components/day-v3/DayV3Deployment.tsx | 853 -------------------------- components/day-v3/DayV3Summary.tsx | 82 ++- lib/day-v3/deploy-config.test.ts | 153 +++++ lib/day-v3/deploy-config.ts | 212 +++++++ lib/day-v3/handoff.ts | 2 +- package.json | 2 +- 7 files changed, 439 insertions(+), 941 deletions(-) delete mode 100644 components/day-v3/DayV3Deploy.tsx delete mode 100644 components/day-v3/DayV3Deployment.tsx create mode 100644 lib/day-v3/deploy-config.test.ts create mode 100644 lib/day-v3/deploy-config.ts diff --git a/components/day-v3/DayV3Deploy.tsx b/components/day-v3/DayV3Deploy.tsx deleted file mode 100644 index f07d041..0000000 --- a/components/day-v3/DayV3Deploy.tsx +++ /dev/null @@ -1,76 +0,0 @@ -"use client"; - -import { pct } from "@/components/day-v3/format"; - -/** The Royco deploy flow this page hands its design off to. */ -const DEPLOY_URL = "https://royco.org/deploy-market/"; - -/** - * The one action the page is asking for, and the only place on it that is not - * cream. The break in rhythm is the point: everything above is a readout, and - * this is the thing to press. - * - * It restates the reader's own terms rather than generic marketing copy. The - * figures are the live slider values, so the invitation is to deploy the design - * actually on screen and not some default. - */ -export default function DayV3Deploy({ - coverage, - liquidity, - query, - seniorApy, - sourceApy, -}: { - coverage: number; - liquidity: number; - /** The design, encoded the same way this page's own link is. */ - query: string; - seniorApy: number; - sourceApy: number; -}) { - // The query is carried on the honest understanding that the flow does not - // read it: /deploy-market restores from a Jotai store in localStorage - // (royco:deploy-market:draft:v1) and has no searchParams path at all, and a - // different origin cannot write that key anyway. It costs nothing and becomes - // useful the day the flow accepts a link, but the reader must not be told - // their design travels with it, because it does not. - const href = `${DEPLOY_URL}?${query}`; - return ( -
-
-

- This design is deployable today. -

-

- Every term above is a parameter a real Royco Day market takes. Yours pays - Sr{" "} - - {pct(seniorApy)} - {" "} - a year from a source at {pct(sourceApy)}, with {pct(coverage)} coverage and{" "} - {pct(liquidity)} liquidity behind it. The flow starts from a blank draft, so - export the config first and set these terms against it. -

-
- -
- {/* New tab on purpose: the reader has a design on this page and losing - it to a navigation would cost them the whole session. */} - - Deploy this market - - - Opens royco.org in a new tab. It will not carry these terms across. - -
-
- ); -} diff --git a/components/day-v3/DayV3Deployment.tsx b/components/day-v3/DayV3Deployment.tsx deleted file mode 100644 index bca7765..0000000 --- a/components/day-v3/DayV3Deployment.tsx +++ /dev/null @@ -1,853 +0,0 @@ -"use client"; - -import { memo, useState } from "react"; - -import DayV3Button, { - dayV3ButtonVariants, -} from "@/components/day-v3/DayV3Button"; -import type { - DayV3ExitView, - DayV3ProtectedExitView, - DayV3ProtectionView, -} from "@/components/day-v3/DayV3Goals"; -import { Badge } from "@/components/ui/badge"; -import { - Card, - CardContent, - CardNote, - CardHeader, - CardTitle, -} from "@/components/ui/card"; -import { - buildDayV3DeploymentUrl, - buildDayV3HandoffV3, - dayV3DeploymentCta, - isDayV3HandoffReady, -} from "@/lib/day-v3/handoff"; -import type { - DayV3PoolDesignResult, - DayV3PoolDesignTarget, -} from "@/lib/day-v3/pool-design"; -import type { DayV3ExpiryPolicy, DayV3Goals } from "@/lib/day-v3/types"; -import type { DayV3YieldCurveDesign } from "@/lib/day-v3/yield-curves"; -import { - dayV3DepthAtNavBps, - dayV3MaximumDiscountBps, -} from "@/lib/day-v3/exit-units"; -import { cn } from "@/lib/utils"; - -const DEPLOY_URL = "https://www.royco.org/deploy-market"; -type ResolvedPoolDesign = Extract< - DayV3PoolDesignResult, - { status: "resolved" } ->; - -type GoalDraft = { - protectedDrawdownPct: number | null; - recoveryDays: number | null; - immediateExitSharePct: number | null; - minimumProceedsPer100: number | null; - entryPointSettlementDays: number | null; - collateralToExitDays: number | null; - collateralToExitCostBps: number | null; - fixedTermGraceDays: number | null; - navUpdateDays: number | null; - target: { chainId: number; templateId: string } | null; -}; - -type DeploymentPolicyDraft = { - depositDelaySeconds: number | null; - depositExpirySeconds: DayV3ExpiryPolicy | null; - withdrawalExpirySeconds: DayV3ExpiryPolicy | null; - gateByOracleUpdate: boolean | null; - maxReinvestmentSlippageBps: number | null; -}; - -function Row({ label, value }: { label: string; value: string }) { - return ( -
- - {label} - - - {value} - -
- ); -} - -const shown = (value: number | null, suffix = "") => - value === null ? "Unresolved" : `${value.toFixed(2)}${suffix}`; - -const shownBps = (value: number | null) => - value === null ? "Unresolved" : `${value.toFixed(0)} bps`; - -function DayV3Deployment({ - exit, - goals, - market, - poolDesign, - yieldTarget, - protectedExit, - protection, - deploymentPolicy, - sourceApyPct, - yieldCurveDesign, - yieldCurvePolicyResolved, -}: { - exit: DayV3ExitView; - goals: GoalDraft; - market: { id: string; name: string; asset: string }; - poolDesign: ResolvedPoolDesign | null; - yieldTarget: DayV3PoolDesignTarget | null; - protectedExit: DayV3ProtectedExitView; - protection: DayV3ProtectionView; - deploymentPolicy: DeploymentPolicyDraft; - sourceApyPct: number | null; - yieldCurveDesign: DayV3YieldCurveDesign; - yieldCurvePolicyResolved: boolean; -}) { - const [copied, setCopied] = useState(false); - const [open, setOpen] = useState(false); - const contentId = "day-v3-deployment-handoff-content"; - const protectionDisabled = protection.status === "disabled"; - const exitDisabled = exit.status === "disabled"; - const readinessChecks = [ - { - label: "Source yield", - ready: sourceApyPct !== null, - scope: "v3-handoff" as const, - missing: "Enter the source’s net annual yield.", - }, - { - label: "Protected drawdown", - ready: goals.protectedDrawdownPct !== null, - scope: "v3-handoff" as const, - missing: "Choose the source drawdown Senior should withstand.", - }, - { - label: "Minimum Coverage", - ready: - protectionDisabled || - (protection.status === "recommended" && - protection.coveragePct !== null), - scope: "v3-handoff" as const, - missing: "Resolve the accountant-backed coverage recommendation.", - }, - { - label: "Recovery time", - ready: protectionDisabled || goals.recoveryDays !== null, - scope: "v3-handoff" as const, - missing: "Choose no recovery window or enter its duration.", - }, - { - label: "Underlying redemption delay", - ready: goals.entryPointSettlementDays !== null, - scope: "v3-handoff" as const, - missing: "Enter the in-kind Senior redemption queue.", - }, - { - label: "Underlying conversion time", - ready: exitDisabled || goals.collateralToExitDays !== null, - scope: "v3-handoff" as const, - missing: "Enter the time from the redeemed underlying asset to the exit asset.", - }, - { - label: "External spread assumption", - ready: exitDisabled || goals.collateralToExitCostBps !== null, - scope: "v3-handoff" as const, - missing: - "Choose the conservative external conversion spread the refill test should withstand.", - }, - { - label: "Fixed-Term Grace Period", - ready: protectionDisabled || goals.fixedTermGraceDays !== null, - scope: "v3-handoff" as const, - missing: - "Choose how long after deployment before a loss may start a recovery window.", - }, - { - label: "NAV refresh cadence", - ready: goals.navUpdateDays !== null, - scope: "v3-handoff" as const, - missing: "Enter how often Senior’s value is published.", - }, - { - label: "Depth at NAV", - ready: goals.immediateExitSharePct !== null, - scope: "v3-handoff" as const, - missing: "Choose the Senior depth available at NAV in basis points.", - }, - { - label: "Maximum discount", - ready: goals.minimumProceedsPer100 !== null, - scope: "v3-handoff" as const, - missing: "Choose the maximum discount to NAV in basis points.", - }, - { - label: "Deployment target", - ready: goals.target !== null, - scope: "v3-handoff" as const, - missing: "The supported deployment configuration is unavailable.", - }, - { - label: "Canonical pool design", - ready: - exitDisabled || (poolDesign !== null && exit.status === "recommended"), - scope: "v3-handoff" as const, - missing: - exit.status === "infeasible" - ? "These exit terms do not produce a deployable pool. Change the exit settings or operational costs." - : "Resolve the pool fee, parameters, and exit outcomes.", - }, - { - label: "Restock scenario", - ready: - exitDisabled || - (goals.collateralToExitDays !== null && - goals.collateralToExitCostBps !== null && - exit.restockPoint !== null), - scope: "v3-handoff" as const, - missing: - goals.collateralToExitDays !== null && - goals.collateralToExitCostBps !== null - ? exit.status === "infeasible" - ? "Conversion facts are complete, but these exit settings fail the restock hurdle. Change Section 3 or shorten/lower the conversion assumptions." - : "Re-run the live pool design to resolve the restock point." - : "Add underlying conversion time and cost, then resolve the scenario restock point.", - }, - { - label: "Live protocol fee policy", - ready: exitDisabled || poolDesign !== null, - scope: "v3-handoff" as const, - missing: - exit.status === "infeasible" - ? "The market terms were checked, but no feasible pool recommendation can be exported for these inputs." - : "Resolve the current market fee terms.", - }, - { - label: "Registered yield-share models", - ready: - yieldCurvePolicyResolved && - yieldTarget !== null && - Boolean( - yieldTarget.yieldModels.jt[ - protectionDisabled ? "FIXED" : "STATIC_CURVE" - ], - ) && - Boolean( - yieldTarget.yieldModels.lpt[exitDisabled ? "FIXED" : "STATIC_CURVE"], - ), - scope: "v3-handoff" as const, - missing: - "Resolve the live template registry for the exact Junior and SLP shapes required by this design.", - }, - { - label: "Minimum Liquidity", - ready: - exitDisabled || - (exit.status === "recommended" && exit.minimumLiquidityPct !== null), - scope: "v3-handoff" as const, - missing: - exit.status === "infeasible" - ? "Minimum Liquidity cannot be derived because the current exit settings have no feasible pool." - : "Resolve the pool-funding-to-liquidity mapping.", - }, - { - label: "Protected Exit trigger", - ready: protectionDisabled || protectedExit.thresholdPct !== null, - scope: "v3-handoff" as const, - missing: "Use a history-backed trigger or enter a manual comparison.", - }, - { - label: "Protected Exit bonus", - ready: protectionDisabled || protectedExit.bonusPct !== null, - scope: "v3-handoff" as const, - missing: "Resolve the optional bonus; no budget should produce 0%.", - }, - { - label: "Protected Exit scenarios", - ready: protectionDisabled || protectedExit.status === "scenario-ready", - scope: "v3-handoff" as const, - missing: "Run the 25%, 50%, and 100% redemption scenarios.", - }, - ]; - const handoffChecks = readinessChecks.filter( - (check) => check.scope === "v3-handoff", - ); - const issuerChecks = readinessChecks.filter((check) => - [ - "Source yield", - "Protected drawdown", - "Recovery time", - "Underlying redemption delay", - "Underlying conversion time", - "External spread assumption", - "Fixed-Term Grace Period", - "NAV refresh cadence", - "Depth at NAV", - "Maximum discount", - "Deployment target", - "Protected Exit trigger", - "Protected Exit bonus", - ].includes(check.label), - ); - const calculationChecks = readinessChecks.filter( - (check) => check.scope === "v3-handoff" && !issuerChecks.includes(check), - ); - // Deployment-owned identity, addresses, oracle construction, administrators, - // seed amounts, and approvals are intentionally collected and validated only - // after import in Royco Deploy. - const deploymentChecks: typeof readinessChecks = [ - { - label: "Request scheduling", - ready: false, - scope: "v3-handoff" as const, - missing: - "Royco Deploy sets deposit timing, request expiry, and the post-request price-update gate.", - }, - { - label: "SLP reinvestment limit", - ready: false, - scope: "v3-handoff" as const, - missing: - "Royco Deploy sets the maximum value an SLP premium reinvestment may give up.", - }, - ]; - const hrefFor = (label: string) => { - if (["Source yield"].includes(label)) return "#day-v3-source-inputs"; - if (["Deployment target", "Live protocol fee policy"].includes(label)) - return "#day-v3-source-inputs"; - if ( - [ - "Underlying redemption delay", - "Underlying conversion time", - "External spread assumption", - "Fixed-Term Grace Period", - "NAV refresh cadence", - "Restock scenario", - ].includes(label) - ) - return "#day-v3-source-operations"; - if ( - ["Protected drawdown", "Minimum Coverage", "Recovery time"].includes( - label, - ) - ) - return "#day-v3-protection-inputs"; - if ( - [ - "Depth at NAV", - "Maximum discount", - "Canonical pool design", - "Minimum Liquidity", - ].includes(label) - ) - return "#day-v3-exit-inputs"; - if (["Registered yield-share models"].includes(label)) - return "#day-v3-premium-inputs"; - return "#day-v3-protected-exit-inputs"; - }; - const handoffReady = isDayV3HandoffReady(readinessChecks); - const primaryCta = dayV3DeploymentCta(handoffReady); - const confirmedCount = handoffChecks.filter((check) => check.ready).length; - const reviewCount = calculationChecks.filter((check) => !check.ready).length; - const missingCount = issuerChecks.filter((check) => !check.ready).length; - const firstMissing = issuerChecks.find((check) => !check.ready); - const exportedExit: DayV3ExitView = - exit.status === "recommended" - ? exit - : { - ...exit, - status: "unresolved", - message: - "Illustrative starter values were omitted. Deployment must resolve the selected live template.", - sellablePer100: null, - proceeds: null, - lowestPayoutPer100: null, - slpPer100: null, - restockPoint: null, - restockOperationalHurdleBps: null, - restockHurdleBps: null, - restockMarginBps: null, - minimumLiquidityPct: null, - maximumDiscountPct: null, - lambda: null, - maximumPremiumBps: null, - restingExitAssetPct: null, - restingSeniorPct: null, - swapFeeBps: null, - feeSource: null, - }; - - // JSON export remains useful while required deployment fields are open, but - // only the explicit handoff builder below may claim readiness. - const payload = (exportedAt: string) => ({ - schema: "royco.day.v3-draft", - version: 1, - exportedAt, - status: "incomplete", - normalization: { senior: 100, targetUtilizationPct: 90 }, - market, - goals, - recommendations: { - protection, - exit: exportedExit, - protectedExit, - canonicalPoolSnapshot: poolDesign, - }, - modeledInputs: { - staticYieldShareCurves: yieldCurveDesign, - }, - warnings: [ - "This draft is untrusted input to deployment.", - "The deployment flow must refresh template policy and recompute every derived pool field.", - "The static Junior and SLP curve anchors are issuer-edited modeling inputs. Deployment must select and validate a registered YDM shape before using them.", - ], - }); - - const copy = async () => { - await navigator.clipboard.writeText( - JSON.stringify(payload(new Date().toISOString()), null, 2), - ); - setCopied(true); - window.setTimeout(() => setCopied(false), 1800); - }; - - const download = () => { - const exportedAt = new Date().toISOString(); - const blob = new Blob([JSON.stringify(payload(exportedAt), null, 2)], { - type: "application/json", - }); - const url = URL.createObjectURL(blob); - const link = document.createElement("a"); - link.href = url; - link.download = `${market.id || "day-market"}-v3-design.json`; - link.click(); - URL.revokeObjectURL(url); - }; - - const openDeployment = () => { - if ( - !handoffReady || - goals.protectedDrawdownPct === null || - (!protectionDisabled && goals.recoveryDays === null) || - goals.immediateExitSharePct === null || - goals.minimumProceedsPer100 === null || - goals.entryPointSettlementDays === null || - (!exitDisabled && goals.collateralToExitDays === null) || - (!exitDisabled && goals.collateralToExitCostBps === null) || - (!protectionDisabled && goals.fixedTermGraceDays === null) || - goals.navUpdateDays === null || - goals.target === null || - protection.coveragePct === null || - exit.minimumLiquidityPct === null || - (!protectionDisabled && - (protectedExit.thresholdPct === null || - protectedExit.bonusPct === null)) || - (!exitDisabled && poolDesign === null) || - yieldTarget === null || - sourceApyPct === null - ) { - return; - } - const { - depositDelaySeconds, - depositExpirySeconds, - gateByOracleUpdate, - maxReinvestmentSlippageBps, - withdrawalExpirySeconds, - } = deploymentPolicy; - if ( - depositDelaySeconds === null || - depositExpirySeconds === null || - withdrawalExpirySeconds === null || - gateByOracleUpdate === null - ) { - window.open(DEPLOY_URL, "_blank", "noopener,noreferrer"); - return; - } - let resolvedMaxReinvestmentSlippageBps = 0; - if (!exitDisabled) { - if (maxReinvestmentSlippageBps === null) { - window.open(DEPLOY_URL, "_blank", "noopener,noreferrer"); - return; - } - resolvedMaxReinvestmentSlippageBps = maxReinvestmentSlippageBps; - } - const resolvedGoals: DayV3Goals = { - protectedDrawdownPct: protectionDisabled ? 0 : goals.protectedDrawdownPct, - recoveryDays: protectionDisabled ? 0 : (goals.recoveryDays as number), - immediateExitSharePct: exitDisabled ? 0 : goals.immediateExitSharePct, - minimumProceedsPer100: exitDisabled ? 0 : goals.minimumProceedsPer100, - entryPointSettlementDays: goals.entryPointSettlementDays, - collateralToExitDays: exitDisabled ? null : goals.collateralToExitDays, - collateralToExitCostBps: exitDisabled - ? null - : goals.collateralToExitCostBps, - fixedTermGraceDays: protectionDisabled - ? 0 - : (goals.fixedTermGraceDays as number), - navUpdateDays: goals.navUpdateDays, - target: goals.target, - }; - const handoff = buildDayV3HandoffV3({ - exportedAt: new Date().toISOString(), - source: { - marketId: market.id, - name: market.name, - asset: market.asset, - sourceApyPct, - }, - features: { - seniorProtection: protectionDisabled ? "disabled" : "enabled", - immediateExit: exitDisabled ? "disabled" : "enabled", - }, - goals: resolvedGoals, - deploymentPolicy: { - settlement: { - appliesTo: "all-tranches", - depositDelaySeconds, - depositExpirySeconds, - withdrawalDelaySeconds: - resolvedGoals.entryPointSettlementDays * 86_400, - withdrawalExpirySeconds, - gateByOracleUpdate, - }, - maxReinvestmentSlippageBps: resolvedMaxReinvestmentSlippageBps, - }, - minimumCoveragePct: protectionDisabled ? 0 : protection.coveragePct, - minimumLiquidityPct: exitDisabled ? 0 : exit.minimumLiquidityPct, - protectedExitThresholdPct: protectionDisabled - ? 0 - : (protectedExit.thresholdPct as number), - protectedExitBonusPct: protectionDisabled - ? 0 - : (protectedExit.bonusPct as number), - canonicalPoolSnapshot: exitDisabled ? null : poolDesign, - liveYieldTarget: yieldTarget, - staticYieldShareCurves: yieldCurveDesign, - }); - window.open( - buildDayV3DeploymentUrl(DEPLOY_URL, handoff), - "_blank", - "noopener,noreferrer", - ); - }; - - return ( - -
- - - {handoffReady ? ( - - Open Royco Deploy - - ) : ( - - Complete setup to deploy - - )} -
- - -
- ); -} - -export default memo(DayV3Deployment); diff --git a/components/day-v3/DayV3Summary.tsx b/components/day-v3/DayV3Summary.tsx index 3d16745..b12029d 100644 --- a/components/day-v3/DayV3Summary.tsx +++ b/components/day-v3/DayV3Summary.tsx @@ -12,6 +12,10 @@ import DayV3Comparison, { } from "@/components/day-v3/DayV3Comparison"; import DayV3CapitalStack from "@/components/day-v3/DayV3CapitalStack"; import { dayV3ButtonVariants } from "@/components/day-v3/DayV3Button"; +import { + buildDayV3DeployConfig, + dayV3DeployConfigFilename, +} from "@/lib/day-v3/deploy-config"; import DayV3DocsLink from "@/components/day-v3/DayV3DocsLink"; import DayV3ExitCost from "@/components/day-v3/DayV3ExitCost"; import DayV3ExitModel from "@/components/day-v3/DayV3ExitModel"; @@ -1841,6 +1845,54 @@ export default function DayV3Summary({ const nextInputStep = inputSteps.find((step) => !step.complete) ?? null; const defaultOpenInputId = nextInputStep?.id ?? null; + // The design as the deploy flow's own draft. Only modeled terms travel; + // whatever this page does not decide stays blank for Royco Deploy to ask. + const downloadDeployConfig = () => { + const config = buildDayV3DeployConfig({ + exportedAt: new Date().toISOString(), + marketName: customSource ? "" : market.identity.marketName, + chainId: canonicalPoolDesign?.policy.chainId ?? null, + sourceApyPct: inputs.sourceApyPct, + exitAssetYieldPct: quoteAssetYieldPct, + coveragePct: protectionView.coveragePct, + minimumLiquidityPct: exitView.minimumLiquidityPct, + observationDays: inputs.observationDays, + curveModels: { + junior: pricingModelSelections.risk, + slp: pricingModelSelections.liquidity, + }, + curves: { + junior: { + y0Pct: resolved.y0 * 100, + yTargetPct: resolved.riskYieldShare * 100, + y100Pct: resolved.y100 * 100, + }, + slp: { + y0Pct: resolved.liqY0 * 100, + yTargetPct: resolved.liquidityYieldShare * 100, + y100Pct: resolved.liqY100 * 100, + }, + }, + maximumDiscountBps: + exitView.maximumDiscountPct === null + ? null + : exitView.maximumDiscountPct * 100, + maximumPremiumBps: exitView.maximumPremiumBps, + lambda: exitView.lambda, + swapFeeBps: exitView.swapFeeBps, + redemptionDelayDays: redemptionDays, + }); + const blob = new Blob([JSON.stringify(config, null, 2)], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = dayV3DeployConfigFilename(config.draft.identity.marketName); + link.click(); + URL.revokeObjectURL(url); + }; + return ( // Capped well inside a laptop viewport. At 1440px a two-column input row // gave each control a 644px cell to hold three characters, so every field @@ -2636,18 +2688,28 @@ export default function DayV3Summary({ Finish in Royco Deploy

- Royco Deploy collects final contract settings and revalidates the - live market before deployment. + Download this design as a market config, then Import it in Royco + Deploy. The asset, its price feed, the observation grace period, + and the Protected Exit terms are set there.

- - Open Royco Deploy - +
+ + + Open Royco Deploy + +

diff --git a/lib/day-v3/deploy-config.test.ts b/lib/day-v3/deploy-config.test.ts new file mode 100644 index 0000000..8ecad2e --- /dev/null +++ b/lib/day-v3/deploy-config.test.ts @@ -0,0 +1,153 @@ +import assert from "node:assert/strict"; + +import { + buildDayV3DeployConfig, + dayV3DeployConfigFilename, + type DayV3DeployConfigInput, +} from "@/lib/day-v3/deploy-config"; + +let passed = 0; +const check = (label: string, run: () => void) => { + run(); + passed += 1; + console.log(` ✓ ${label}`); +}; + +console.log("Day V3 Royco Deploy config export"); + +const input: DayV3DeployConfigInput = { + exportedAt: "2026-09-02T00:00:00.000Z", + marketName: "Pareto FalconX", + chainId: 42161, + sourceApyPct: 9.94, + exitAssetYieldPct: 3.5, + coveragePct: 3, + minimumLiquidityPct: 10, + observationDays: 7, + curveModels: { junior: "ADAPTIVE_CURVE_V2", slp: "STATIC_CURVE" }, + curves: { + junior: { y0Pct: 0.5, yTargetPct: 2.7, y100Pct: 31 }, + slp: { y0Pct: 5.1, yTargetPct: 9.1, y100Pct: 31 }, + }, + maximumDiscountBps: 200, + maximumPremiumBps: 12.5, + lambda: 250, + swapFeeBps: 10, + redemptionDelayDays: 7, +}; + +check("carries the modeled terms in the flow's envelope and units", () => { + const config = buildDayV3DeployConfig(input); + assert.equal(config.format, "royco-day-market-config"); + assert.equal(config.source, "royco-day-simulator"); + const { draft } = config; + assert.equal(draft.version, 1); + assert.equal(draft.createdAt, Date.parse(input.exportedAt)); + assert.equal(draft.chainId, 42161); + assert.equal(draft.identity.marketName, "Pareto FalconX"); + assert.equal(draft.economics.minCoverageWAD, "30000000000000000"); + assert.equal(draft.economics.minLiquidityWAD, "100000000000000000"); + assert.equal(draft.economics.fixedTermDurationSeconds, 7 * 86_400); + assert.equal(draft.economics.maxJTYieldShareWAD, "310000000000000000"); + assert.equal(draft.economics.maxLPTYieldShareWAD, "310000000000000000"); + assert.deepEqual(draft.yield.jt, { + ydmType: "ADAPTIVE_CURVE_V2", + curveParams: { + zeroUtilizationDiscountWAD: "5000000000000000", + targetUtilizationYieldShareWAD: "27000000000000000", + fullUtilizationYieldShareWAD: "310000000000000000", + }, + }); + assert.deepEqual(draft.yield.lpt, { + ydmType: "STATIC_CURVE", + curveParams: { + zeroUtilizationYieldShareWAD: "51000000000000000", + targetUtilizationYieldShareWAD: "91000000000000000", + fullUtilizationYieldShareWAD: "310000000000000000", + }, + }); + assert.deepEqual(draft.poolSizing, { + assetYieldPct: "9.94", + exitLiquidityTvl: "", + maxDiscountBps: "200", + maxPremiumBps: "12.5", + redemptionDelayDays: "7", + navUpdateCadenceHours: "", + exitFeeBps: "10", + lambda: "250", + stablecoinYieldPct: "3.5", + }); +}); + +check("leaves every deployment-only field for Royco Deploy", () => { + const { draft } = buildDayV3DeployConfig(input); + assert.equal(draft.assets.collateralAsset, ""); + assert.equal(draft.assets.quoteAsset, ""); + assert.equal(draft.oracle.recipe, null); + assert.equal(draft.economics.fixedTermGracePeriodSeconds, 0); + assert.equal( + draft.economics.coverageLiquidationUtilizationWAD, + (2n ** 256n - 1n).toString(), + ); + assert.equal(draft.economics.stSelfLiquidationBonusWAD, "0"); + assert.equal(draft.kernel.maxReinvestmentSlippageWAD, ""); + assert.deepEqual(draft.entryPoint.st, { + enabled: true, + depositDelaySeconds: 300, + depositExpirySeconds: 4_294_967_295, + redemptionDelaySeconds: 86_400, + redemptionExpirySeconds: 4_294_967_295, + gateByOracleUpdate: true, + }); + assert.equal(draft.seed.quoteAmount, ""); + assert.equal(draft.mining.minedMarketId, null); + assert.equal(draft.execution.backendRecordStatus, "idle"); +}); + +check("encodes disabled mechanisms as the flow's no-op payloads", () => { + const { draft } = buildDayV3DeployConfig({ + ...input, + coveragePct: 0, + minimumLiquidityPct: 0, + chainId: null, + maximumPremiumBps: null, + lambda: null, + }); + assert.equal(draft.chainId, 1); + assert.equal(draft.economics.minCoverageWAD, "0"); + assert.equal(draft.economics.minLiquidityWAD, "0"); + assert.equal(draft.economics.fixedTermDurationSeconds, 0); + assert.equal(draft.economics.maxJTYieldShareWAD, "0"); + assert.deepEqual(draft.yield.jt, { + ydmType: "FIXED", + curveParams: { fixedYieldShareWAD: "0" }, + }); + assert.deepEqual(draft.yield.lpt, draft.yield.jt); + assert.equal(draft.poolSizing.maxPremiumBps, ""); + assert.equal(draft.poolSizing.lambda, ""); +}); + +check("maps the two-anchor and fixed shapes onto their own params", () => { + const { draft } = buildDayV3DeployConfig({ + ...input, + curveModels: { junior: "ADAPTIVE_CURVE_V1", slp: "FIXED" }, + }); + assert.deepEqual(draft.yield.jt.curveParams, { + targetUtilizationYieldShareWAD: "27000000000000000", + fullUtilizationYieldShareWAD: "310000000000000000", + }); + assert.deepEqual(draft.yield.lpt.curveParams, { + fixedYieldShareWAD: "91000000000000000", + }); + assert.equal(draft.economics.maxLPTYieldShareWAD, "91000000000000000"); +}); + +check("names the file after the market", () => { + assert.equal( + dayV3DeployConfigFilename("Pareto FalconX"), + "royco-day-market-pareto-falconx.json", + ); + assert.equal(dayV3DeployConfigFilename(""), "royco-day-market-config.json"); +}); + +console.log(`${passed} checks passed`); diff --git a/lib/day-v3/deploy-config.ts b/lib/day-v3/deploy-config.ts new file mode 100644 index 0000000..a5f86bc --- /dev/null +++ b/lib/day-v3/deploy-config.ts @@ -0,0 +1,212 @@ +import type { DayCurveModel } from "@/lib/day-simulator-template/deploy-fields"; +import { percentToWad } from "@/lib/day-v3/handoff"; +import type { DayV3YieldCurveDesign } from "@/lib/day-v3/yield-curves"; + +/** + * The Royco Deploy market config: the deploy flow's own draft (DraftV1 in + * royco-rwa-frontend/lib/deploy-market/types.ts) in the envelope the flow's + * own download uses, so the file restores through its Import with no + * converter. Modeled terms are filled; every deployment-only field is left + * the way a fresh draft starts, so the flow asks for it instead of adopting + * a value the issuer never decided. Slices the flow's restore migrations + * back-fill (presentation, blacklist) are omitted. A new DraftV1 slice the + * flow's structural check requires must be added here. + */ +export interface DayV3DeployConfigInput { + exportedAt: string; + /** Blank for a custom source: the flow derives a name from the asset. */ + marketName: string; + /** The canonical pool design's chain, null until one resolves. */ + chainId: number | null; + sourceApyPct: number | null; + exitAssetYieldPct: number | null; + /** 0 when Senior protection is off. */ + coveragePct: number | null; + /** 0 when immediate exit is off. */ + minimumLiquidityPct: number | null; + /** The recovery window in days, 0 for none. */ + observationDays: number; + curveModels: { junior: DayCurveModel; slp: DayCurveModel }; + curves: DayV3YieldCurveDesign; + maximumDiscountBps: number | null; + maximumPremiumBps: number | null; + lambda: number | null; + swapFeeBps: number | null; + redemptionDelayDays: number | null; +} + +export type DayV3DeployConfig = ReturnType; + +// Mirrors of royco-rwa-frontend/lib/deploy-market/constants.ts. +const COVERAGE_DISABLED_LIQ_UTIL_WAD = (2n ** 256n - 1n).toString(); +const UINT32_MAX = 4_294_967_295; +// deriveDustTolerance(8), re-derived by the flow once the pricing route is known. +const DEFAULT_DUST_TOLERANCE_NAV_WEI = "50000000000"; +const settlementQueueConfig = () => ({ + enabled: true, + depositDelaySeconds: 300, + depositExpirySeconds: UINT32_MAX, + redemptionDelaySeconds: 86_400, + redemptionExpirySeconds: UINT32_MAX, + gateByOracleUpdate: true, +}); + +const text = (value: number | null) => (value === null ? "" : String(value)); + +type Anchors = DayV3YieldCurveDesign["junior"]; + +// Param keys per shape (the flow's YDM_CURVE_PARAM_KEYS). The V2 "discount" +// key carries the absolute share at 0% utilization; the contract derives its +// stored discount from it (AdaptiveCurveYDM_V2.sol:424). +function ydmSelection(model: DayCurveModel, enabled: boolean, curve: Anchors) { + if (!enabled) { + return { ydmType: "FIXED", curveParams: { fixedYieldShareWAD: "0" } }; + } + const zero = percentToWad(curve.y0Pct); + const target = percentToWad(curve.yTargetPct); + const full = percentToWad(curve.y100Pct); + const curveParams = { + STATIC_CURVE: { + zeroUtilizationYieldShareWAD: zero, + targetUtilizationYieldShareWAD: target, + fullUtilizationYieldShareWAD: full, + }, + ADAPTIVE_CURVE_V1: { + targetUtilizationYieldShareWAD: target, + fullUtilizationYieldShareWAD: full, + }, + ADAPTIVE_CURVE_V2: { + zeroUtilizationDiscountWAD: zero, + targetUtilizationYieldShareWAD: target, + fullUtilizationYieldShareWAD: full, + }, + FIXED: { fixedYieldShareWAD: target }, + }[model]; + return { ydmType: model, curveParams }; +} + +/** The cap the contract would derive from the curve's own peak. */ +const yieldShareCap = (enabled: boolean, model: DayCurveModel, curve: Anchors) => + !enabled + ? "0" + : percentToWad( + model === "FIXED" + ? curve.yTargetPct + : Math.max(curve.y0Pct, curve.yTargetPct, curve.y100Pct), + ); + +export function buildDayV3DeployConfig(input: DayV3DeployConfigInput) { + const now = Date.parse(input.exportedAt); + const coveragePct = input.coveragePct ?? 0; + const liquidityPct = input.minimumLiquidityPct ?? 0; + const protection = coveragePct > 0; + const exit = liquidityPct > 0; + const { junior, slp } = input.curveModels; + return { + format: "royco-day-market-config", + version: 1, + source: "royco-day-simulator", + exportedAt: input.exportedAt, + draft: { + version: 1, + createdAt: now, + updatedAt: now, + chainId: input.chainId ?? 1, + intendedDeployer: null, + furthestStep: 0, + identity: { + marketName: input.marketName, + st: { name: "", symbol: "" }, + jt: { name: "", symbol: "" }, + lpt: { name: "", symbol: "" }, + pool: { name: "", symbol: "" }, + }, + assets: { + collateralAsset: "", + quoteMode: "custom", + quoteAsset: "", + quoteAssetRateProvider: "", + quoteAssetRateProviderDeployment: null, + quoteYieldBearing: true, + }, + oracle: { + mode: "deploy", + valuationUnit: "USD", + existingAddress: "", + recipe: null, + deployedAddress: null, + deployTxHash: null, + deployDeployer: null, + }, + economics: { + minCoverageWAD: protection ? percentToWad(coveragePct) : "0", + coverageLiquidationUtilizationWAD: COVERAGE_DISABLED_LIQ_UTIL_WAD, + minLiquidityWAD: exit ? percentToWad(liquidityPct) : "0", + fixedTermDurationSeconds: protection + ? Math.round(input.observationDays * 86_400) + : 0, + fixedTermGracePeriodSeconds: 0, + stSelfLiquidationBonusWAD: "0", + dustTolerance: DEFAULT_DUST_TOLERANCE_NAV_WEI, + maxJTYieldShareWAD: yieldShareCap(protection, junior, input.curves.junior), + maxLPTYieldShareWAD: yieldShareCap(exit, slp, input.curves.slp), + }, + yield: { + jt: ydmSelection(junior, protection, input.curves.junior), + lpt: ydmSelection(slp, exit, input.curves.slp), + }, + poolSizing: { + assetYieldPct: text(input.sourceApyPct), + exitLiquidityTvl: "", + maxDiscountBps: + input.maximumDiscountBps === null + ? "" + : String(Math.round(input.maximumDiscountBps)), + maxPremiumBps: text(input.maximumPremiumBps), + redemptionDelayDays: text(input.redemptionDelayDays), + navUpdateCadenceHours: "", + exitFeeBps: text(input.swapFeeBps), + lambda: text(input.lambda), + stablecoinYieldPct: text(input.exitAssetYieldPct), + }, + poolParams: null, + seed: { collateralAmount: "", quoteAmount: "", minLPTAssetsOut: "0" }, + kernel: { + sequencerUptimeFeed: null, + gracePeriodSeconds: 0, + maxReinvestmentSlippageWAD: "", + }, + entryPoint: { + st: settlementQueueConfig(), + jt: settlementQueueConfig(), + lpt: settlementQueueConfig(), + }, + mining: { + seed: null, + minedMarketId: null, + paramsHash: null, + predictedAddresses: null, + }, + execution: { + approvals: {}, + deployTxHash: null, + result: null, + deployerAddress: null, + factoryAddress: null, + templateAddress: null, + encodedParameters: null, + configurationSnapshot: null, + backendRecordStatus: "idle", + }, + }, + }; +} + +/** The same name the flow's own download uses. */ +export function dayV3DeployConfigFilename(marketName: string): string { + const slug = marketName + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + return `royco-day-market-${slug || "config"}.json`; +} diff --git a/lib/day-v3/handoff.ts b/lib/day-v3/handoff.ts index 6fcc722..46ef19d 100644 --- a/lib/day-v3/handoff.ts +++ b/lib/day-v3/handoff.ts @@ -172,7 +172,7 @@ function assertFeatureInvariants(input: { } } -const percentToWad = (value: number): string => { +export const percentToWad = (value: number): string => { if (!Number.isFinite(value) || value < 0 || value >= 100) { throw new Error("INVALID_DAY_V3_YIELD_SHARE"); } diff --git a/package.json b/package.json index a26b4ce..1550753 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "build": "next build --webpack", "start": "next start", "lint": "eslint", - "test": "node scripts/day-simulator/factory.test.mjs && npx tsx lib/day/engine/engine.test.ts && npx tsx lib/day-simulator-template/runtime.test.ts && npx tsx lib/day-simulator-template/explorer-market.test.ts && npx tsx lib/day-simulator-template/erasure.test.ts && npx tsx lib/day-simulator-template/explainer.test.ts && npx tsx lib/day-simulator-template/stress.test.ts && npx tsx lib/day-simulator-template/source-parser.test.ts && npx tsx lib/day-simulator-template/permalink.test.ts && npx tsx lib/day-simulator-template/config-export.test.ts && npx tsx lib/day-simulator-template/backtest.test.ts && npx tsx lib/day-simulator-template/deploy-fields.test.ts && npx tsx lib/day-simulator-template/capital-sizing.test.ts && npx tsx components/day-v2/url-state.test.ts && npx tsx scripts/day-v3/v2-output-regression.test.ts && node scripts/day-v3/model-output-parity.test.mjs && npx tsx components/day-v3/url-state.test.ts && npx tsx components/day-v3/DayV3Hero.test.tsx && npx tsx components/day-v3/DayV3NumberField.test.tsx && npx tsx components/day-v3/DayV3Group.test.ts && npx tsx components/day-v3/DayV3ModelGroup.test.ts && npx tsx components/day-v3/DayV3DeploymentTarget.test.tsx && npx tsx components/day-v3/DayV3DeploymentPolicy.test.tsx && npx tsx components/day-v3/DayV3ExitModel.test.tsx && npx tsx components/day-v3/DayV3Comparison.test.tsx && npx tsx components/day-v3/DayV3ProtectionSensitivity.test.tsx && npx tsx components/day-v3/DayV3ProtectedExitModel.test.tsx && npx tsx components/day-v3/DayV3PremiumCurveEditor.test.tsx && npx tsx components/day-v3/DayV3PricingModelExplorer.test.tsx && npx tsx components/day-v3/DayV3Backtest.test.ts && npx tsx components/day-v3/DayV3DesignOutcome.test.tsx && npx tsx lib/day-v3/yield-curves.test.ts && npx tsx lib/day-v3/model-state.test.ts && npx tsx lib/day-v3/mode-state.test.ts && npx tsx lib/day-v3/restock-arbitrage.test.ts && npx tsx lib/day-v3/historical-returns.test.ts && npx tsx lib/day-v3/pool-curve.test.ts && npx tsx lib/day-v3/pool-seed.test.ts && npx tsx lib/day-v3/exit-goal-sizing.test.ts && npx tsx lib/day-v3/simulation-pool-design.test.ts && npx tsx lib/day-v3/day-v3.test.ts && npx tsx app/api/day-v3/accountant-validation/v1/route.test.ts && npx tsx app/api/day-v3/pool-design/route.test.ts && npx tsx app/api/day-v3/pool-design/simulation/route.test.ts && node scripts/day-v3/route-boundary.test.mjs && npx tsx lib/hybond/timeframe.test.ts && npx tsx lib/hybond/permalink.test.ts", + "test": "node scripts/day-simulator/factory.test.mjs && npx tsx lib/day/engine/engine.test.ts && npx tsx lib/day-simulator-template/runtime.test.ts && npx tsx lib/day-simulator-template/explorer-market.test.ts && npx tsx lib/day-simulator-template/erasure.test.ts && npx tsx lib/day-simulator-template/explainer.test.ts && npx tsx lib/day-simulator-template/stress.test.ts && npx tsx lib/day-simulator-template/source-parser.test.ts && npx tsx lib/day-simulator-template/permalink.test.ts && npx tsx lib/day-simulator-template/config-export.test.ts && npx tsx lib/day-simulator-template/backtest.test.ts && npx tsx lib/day-simulator-template/deploy-fields.test.ts && npx tsx lib/day-simulator-template/capital-sizing.test.ts && npx tsx components/day-v2/url-state.test.ts && npx tsx scripts/day-v3/v2-output-regression.test.ts && node scripts/day-v3/model-output-parity.test.mjs && npx tsx components/day-v3/url-state.test.ts && npx tsx components/day-v3/DayV3Hero.test.tsx && npx tsx components/day-v3/DayV3NumberField.test.tsx && npx tsx components/day-v3/DayV3Group.test.ts && npx tsx components/day-v3/DayV3ModelGroup.test.ts && npx tsx components/day-v3/DayV3DeploymentTarget.test.tsx && npx tsx components/day-v3/DayV3DeploymentPolicy.test.tsx && npx tsx components/day-v3/DayV3ExitModel.test.tsx && npx tsx components/day-v3/DayV3Comparison.test.tsx && npx tsx components/day-v3/DayV3ProtectionSensitivity.test.tsx && npx tsx components/day-v3/DayV3ProtectedExitModel.test.tsx && npx tsx components/day-v3/DayV3PremiumCurveEditor.test.tsx && npx tsx components/day-v3/DayV3PricingModelExplorer.test.tsx && npx tsx components/day-v3/DayV3Backtest.test.ts && npx tsx components/day-v3/DayV3DesignOutcome.test.tsx && npx tsx lib/day-v3/yield-curves.test.ts && npx tsx lib/day-v3/model-state.test.ts && npx tsx lib/day-v3/mode-state.test.ts && npx tsx lib/day-v3/restock-arbitrage.test.ts && npx tsx lib/day-v3/historical-returns.test.ts && npx tsx lib/day-v3/pool-curve.test.ts && npx tsx lib/day-v3/pool-seed.test.ts && npx tsx lib/day-v3/exit-goal-sizing.test.ts && npx tsx lib/day-v3/simulation-pool-design.test.ts && npx tsx lib/day-v3/day-v3.test.ts && npx tsx lib/day-v3/deploy-config.test.ts && npx tsx app/api/day-v3/accountant-validation/v1/route.test.ts && npx tsx app/api/day-v3/pool-design/route.test.ts && npx tsx app/api/day-v3/pool-design/simulation/route.test.ts && node scripts/day-v3/route-boundary.test.mjs && npx tsx lib/hybond/timeframe.test.ts && npx tsx lib/hybond/permalink.test.ts", "parity": "npx tsx lib/try/parity.ts && npx tsx lib/hybond/parity.ts", "audit:v2-math": "node scripts/v2-math-invariants.mjs", "sim:new": "node scripts/simulator/create.mjs",