No buys yet. Once your plan is running, every buy shows up here, including skipped ones.
;
return (
@@ -27,7 +30,9 @@ export function BuyTable({ buys }: { buys: BuyDto[] }) {
{buys.map((b) => (
{new Date(b.createdAt).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" })}
- ${formatUsdc(b.amountIn)}
+
+ {SPENT.has(b.status) ? `$${formatUsdc(b.amountIn)}` : Nothing spent }
+
{b.status === "success" || b.status === "sent" || b.status === "processing" ? formatTarget(b.amountOut, b.targetAsset) : "—"}
{b.costBps === null ? "—" : `${(b.costBps / 100).toFixed(2)}%`}
diff --git a/components/history/SkipReason.tsx b/components/history/SkipReason.tsx
index 9a9c06e..6fa149c 100644
--- a/components/history/SkipReason.tsx
+++ b/components/history/SkipReason.tsx
@@ -21,7 +21,9 @@ export function SkipReason({ status, note }: { status: BuyStatus; note: string |
return (
{WORDS[status]}
- {note && status !== "success" ? {note} : null}
+ {note && status !== "success" ? (
+ {status === "skipped_cost" || status === "no_quote" ? `${note}. Nothing was spent.` : note}
+ ) : null}
);
}
diff --git a/components/history/TxLinks.tsx b/components/history/TxLinks.tsx
index cb51019..0890539 100644
--- a/components/history/TxLinks.tsx
+++ b/components/history/TxLinks.tsx
@@ -6,6 +6,7 @@
import { destinationTxUrl, nearTxUrl } from "@/lib/client/format";
export function TxLinks({ nearTxHash, destinationTxHash, targetAsset }: { nearTxHash: string | null; destinationTxHash: string | null; targetAsset: string }) {
+ if (nearTxHash?.startsWith("demo-") || destinationTxHash?.startsWith("demo-")) return Example only ;
const dest = destinationTxHash ? destinationTxUrl(targetAsset, destinationTxHash) : null;
if (!nearTxHash && !dest) return — ;
return (
diff --git a/components/ui/Field.tsx b/components/ui/Field.tsx
index 3531bf6..8176452 100644
--- a/components/ui/Field.tsx
+++ b/components/ui/Field.tsx
@@ -11,7 +11,7 @@ const control =
function Wrapper({ id, label, hint, error, children }: FieldProps & { id: string; children: ReactNode }) {
return (
-
+
{label}
diff --git a/components/vault/DemoBanner.tsx b/components/vault/DemoBanner.tsx
new file mode 100644
index 0000000..c0e039f
--- /dev/null
+++ b/components/vault/DemoBanner.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+/**
+ * Shown on every page of a demo session: says it's example data and offers the two demo controls.
+ * Roadmap: K7.3, K7.4
+ */
+
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { api } from "@/lib/client/api";
+
+export function DemoBanner() {
+ const qc = useQueryClient();
+ const [message, setMessage] = useState
(null);
+ const done = () => qc.invalidateQueries();
+ const forward = useMutation({
+ mutationFn: () => api<{ bought: number; skipped: number; stoppedEmpty: boolean }>("/api/demo/fast-forward", { method: "POST" }),
+ onSuccess: (r) => {
+ setMessage(
+ `30 days later: ${r.bought} ${r.bought === 1 ? "buy" : "buys"}${r.skipped ? `, ${r.skipped} skipped for fees` : ""}${r.stoppedEmpty ? ". The vault ran out of dollars" : ""}.`,
+ );
+ return done();
+ },
+ onError: (e) => setMessage(e.message),
+ });
+ const reset = useMutation({
+ mutationFn: () => api("/api/demo/reset", { method: "POST" }),
+ onSuccess: () => {
+ setMessage("Back to the start.");
+ return done();
+ },
+ });
+ return (
+
+
+ Demo mode. Example data, no real money. Your wallet isn't used.
+ {message ? {message} : null}
+
+
+ forward.mutate()}>
+ {forward.isPending ? "Fast-forwarding…" : "Fast-forward 30 days"}
+
+ reset.mutate()}>
+ Start over
+
+
+
+ );
+}
diff --git a/components/vault/StackColumn.tsx b/components/vault/StackColumn.tsx
index 27bd834..c10e578 100644
--- a/components/vault/StackColumn.tsx
+++ b/components/vault/StackColumn.tsx
@@ -18,15 +18,15 @@ export function StackColumn({ bars, empty }: { bars: StackBar[]; empty?: string
}
const max = Math.max(1, ...bars.filter((b) => b.state !== "skipped").map((b) => b.weight));
return (
-
+
{bars.map((b) => (
-
+
- {b.label}
+ {b.label}
))}
diff --git a/components/wallet/WalletProvider.tsx b/components/wallet/WalletProvider.tsx
index 90195dc..4783323 100644
--- a/components/wallet/WalletProvider.tsx
+++ b/components/wallet/WalletProvider.tsx
@@ -78,8 +78,14 @@ export function WalletProvider({ children }: { children: ReactNode }) {
}),
send: (tx) =>
run(async () => {
- const wallet = await (await getConnector()).wallet();
- await wallet.signAndSendTransaction({ receiverId: tx.receiverId, actions: tx.actions });
+ const vault = queryClient.getQueryData<{ demo?: boolean }>(["vault"]);
+ if (vault?.demo) {
+ // Demo mode: same transaction, applied to the demo vault with the contract's rules.
+ await api("/api/demo/owner-tx", { body: { tx } });
+ } else {
+ const wallet = await (await getConnector()).wallet();
+ await wallet.signAndSendTransaction({ receiverId: tx.receiverId, actions: tx.actions });
+ }
await queryClient.invalidateQueries({ queryKey: ["vault"] });
}),
}),
diff --git a/drizzle/0002_demo_vaults.sql b/drizzle/0002_demo_vaults.sql
new file mode 100644
index 0000000..3c33693
--- /dev/null
+++ b/drizzle/0002_demo_vaults.sql
@@ -0,0 +1,12 @@
+CREATE TABLE IF NOT EXISTS "demo_vaults" (
+ "vault_account_id" text PRIMARY KEY NOT NULL,
+ "user_id" uuid NOT NULL,
+ "state" jsonb NOT NULL,
+ "withdrawn" numeric(78, 0) DEFAULT '0' NOT NULL
+);
+--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "demo_vaults" ADD CONSTRAINT "demo_vaults_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json
new file mode 100644
index 0000000..1e9ad3f
--- /dev/null
+++ b/drizzle/meta/0002_snapshot.json
@@ -0,0 +1,451 @@
+{
+ "id": "2043b2a0-d9c1-44e3-81cc-6529c780d49a",
+ "prevId": "e3b2ba63-4d7b-446c-bd57-f320950743ec",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.buys": {
+ "name": "buys",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "quote_ref": {
+ "name": "quote_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount_in": {
+ "name": "amount_in",
+ "type": "numeric(78, 0)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_asset": {
+ "name": "target_asset",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "destination_address": {
+ "name": "destination_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cost_bps": {
+ "name": "cost_bps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "amount_in_usd": {
+ "name": "amount_in_usd",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "amount_out": {
+ "name": "amount_out",
+ "type": "numeric(78, 0)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deposit_address": {
+ "name": "deposit_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "quote_signature": {
+ "name": "quote_signature",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "quote_raw": {
+ "name": "quote_raw",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "near_tx_hash": {
+ "name": "near_tx_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "oneclick_status": {
+ "name": "oneclick_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "destination_tx_hash": {
+ "name": "destination_tx_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "buys_user_idx": {
+ "name": "buys_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "buys_user_id_users_id_fk": {
+ "name": "buys_user_id_users_id_fk",
+ "tableFrom": "buys",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "buys_quote_ref_unique": {
+ "name": "buys_quote_ref_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "quote_ref"
+ ]
+ },
+ "buys_deposit_address_unique": {
+ "name": "buys_deposit_address_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "deposit_address"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.demo_vaults": {
+ "name": "demo_vaults",
+ "schema": "",
+ "columns": {
+ "vault_account_id": {
+ "name": "vault_account_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "state": {
+ "name": "state",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "withdrawn": {
+ "name": "withdrawn",
+ "type": "numeric(78, 0)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'0'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "demo_vaults_user_id_users_id_fk": {
+ "name": "demo_vaults_user_id_users_id_fk",
+ "tableFrom": "demo_vaults",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.funding_attempts": {
+ "name": "funding_attempts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "origin_asset": {
+ "name": "origin_asset",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount_in": {
+ "name": "amount_in",
+ "type": "numeric(78, 0)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expected_out": {
+ "name": "expected_out",
+ "type": "numeric(78, 0)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refund_to": {
+ "name": "refund_to",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deposit_address": {
+ "name": "deposit_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "quote_deadline": {
+ "name": "quote_deadline",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "quote_signature": {
+ "name": "quote_signature",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "quote_raw": {
+ "name": "quote_raw",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "oneclick_status": {
+ "name": "oneclick_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'awaiting_deposit'"
+ },
+ "deposit_tx_hash": {
+ "name": "deposit_tx_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "funding_attempts_user_idx": {
+ "name": "funding_attempts_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "funding_attempts_user_id_users_id_fk": {
+ "name": "funding_attempts_user_id_users_id_fk",
+ "tableFrom": "funding_attempts",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "funding_attempts_deposit_address_unique": {
+ "name": "funding_attempts_deposit_address_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "deposit_address"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.users": {
+ "name": "users",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "near_account_id": {
+ "name": "near_account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "vault_account_id": {
+ "name": "vault_account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_demo": {
+ "name": "is_demo",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "users_near_account_id_unique": {
+ "name": "users_near_account_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "near_account_id"
+ ]
+ },
+ "users_vault_account_id_unique": {
+ "name": "users_vault_account_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "vault_account_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 8f5a4e1..728f1ed 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -15,6 +15,13 @@
"when": 1793820914606,
"tag": "0001_buy_note",
"breakpoints": true
+ },
+ {
+ "idx": 2,
+ "version": "7",
+ "when": 1793865866986,
+ "tag": "0002_demo_vaults",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/e2e/demo-journey.spec.ts b/e2e/demo-journey.spec.ts
index fd8c929..8b2786b 100644
--- a/e2e/demo-journey.spec.ts
+++ b/e2e/demo-journey.spec.ts
@@ -1,8 +1,49 @@
-import { test } from "@playwright/test";
+import { expect, test } from "@playwright/test";
// PRD §8 judge journey, demo mode only. Roadmap: K7.6
-test.fixme("demo dashboard shows vault balance and history", async () => {});
-test.fixme("fund preview: SOL on Solana → USDC in vault (dry-run)", async () => {});
-test.fixme("plan screen shows cost % for $10 vs $100 BTC buys", async () => {});
-test.fixme("fast-forward records buys incl. one skipped for cost", async () => {});
-test.fixme("CSV export downloads", async () => {});
+test("a judge can try Stack end to end with no wallet and no funds", async ({ page }) => {
+ // 1. Landing → demo → own example vault
+ await page.goto("/");
+ await expect(page.getByRole("heading", { name: "Put your savings on a schedule." })).toBeVisible();
+ await page.getByRole("link", { name: "See it with example data" }).click();
+ await page.getByRole("button", { name: "Open the demo" }).click();
+ await expect(page.getByText("Your stack")).toBeVisible();
+ await expect(page.getByLabel("Demo mode")).toBeVisible();
+ await expect(page.getByText(/From 3 buys totalling \$300/)).toBeVisible();
+
+ // 2. Fund preview: SOL on Solana → dollars in the vault
+ const nav = page.getByRole("navigation", { name: "Sections" });
+ await nav.getByRole("link", { name: "Add funds" }).click();
+ await page.getByLabel("You send").selectOption("nep141:sol.omft.near");
+ await page.getByLabel("How much SOL").fill("2");
+ await page.getByLabel(/Your refund address/).fill("4Nd1mBQtrMJVYVfKf2PJy9NZUZdTAsp7D4xWLs4gDB4T");
+ await page.getByRole("button", { name: "Preview" }).click();
+ await expect(page.getByText(/2 SOL becomes about \$/)).toBeVisible();
+
+ // 3. Plan: a $10 BTC buy is mostly fees, and the page says so
+ await nav.getByRole("link", { name: "Plan", exact: true }).click();
+ await page.getByLabel("Each buy, in US dollars").fill("10");
+ await expect(page.getByText(/Small BTC buys are mostly network fees/)).toBeVisible();
+
+ // 4. Fast-forward 30 days: more buys, one skipped for fees
+ await page.getByRole("button", { name: "Fast-forward 30 days" }).click();
+ await expect(page.getByText(/30 days later: \d+ buys, 1 skipped for fees/)).toBeVisible();
+
+ // 5. History explains skips; CSV export works
+ await nav.getByRole("link", { name: "History" }).click();
+ await expect(page.getByText("Skipped: fees too high").first()).toBeVisible();
+ await expect(page.getByText(/Fees were .*% limit\. Nothing was spent\./).first()).toBeVisible();
+ const csv = await page.request.get("/api/export.csv");
+ expect(csv.headers()["content-type"]).toContain("text/csv");
+ expect((await csv.text()).split("\r\n")[0]).toBe("date_utc,type,status,amount_in,asset_in,amount_out,asset_out,usd_value_in,cost_bps,deposit_address,near_tx,destination_tx");
+
+ // Pause is one tap and always visible
+ await page.getByRole("button", { name: "Pause" }).click();
+ await expect(page.getByRole("button", { name: "Resume" })).toBeVisible();
+
+});
+
+test("signed-out visits to app pages land on the landing page", async ({ page }) => {
+ await page.goto("/plan");
+ await expect(page).toHaveURL(/\/\?next=%2Fplan$/);
+});
diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts
index 11523da..3b4c2cf 100644
--- a/e2e/playwright.config.ts
+++ b/e2e/playwright.config.ts
@@ -1,8 +1,23 @@
-import { defineConfig } from "@playwright/test";
+import { defineConfig, devices } from "@playwright/test";
+import path from "node:path";
-// Runs against demo mode only. Never against real funds.
+// Runs against demo mode only (zero config, no wallet, no funds). Roadmap: K7.6
export default defineConfig({
testDir: ".",
- use: { baseURL: "http://localhost:3000" },
- webServer: { command: "pnpm demo", url: "http://localhost:3000", reuseExistingServer: true, cwd: ".." },
+ timeout: 90_000,
+ expect: { timeout: 20_000 },
+ retries: process.env.CI ? 1 : 0,
+ reporter: process.env.CI ? [["list"], ["html", { open: "never" }]] : "list",
+ use: { baseURL: "http://localhost:3000", trace: "retain-on-failure" },
+ projects: [
+ { name: "desktop", use: { ...devices["Desktop Chrome"] } },
+ { name: "phone", use: { ...devices["Pixel 7"] } },
+ ],
+ webServer: {
+ command: "pnpm demo",
+ url: "http://localhost:3000",
+ reuseExistingServer: !process.env.CI,
+ cwd: path.resolve(import.meta.dirname, ".."),
+ timeout: 180_000,
+ },
});
diff --git a/lib/client/api.ts b/lib/client/api.ts
index a136192..97ad10a 100644
--- a/lib/client/api.ts
+++ b/lib/client/api.ts
@@ -30,6 +30,8 @@ export async function api(path: string, init?: { method?: string; body?: unkn
export interface VaultResponse {
accountId: string;
vaultAccountId: string | null;
+ /** Demo session: example data, owner actions applied without a wallet. */
+ demo?: boolean;
state?: VaultState;
usdcBalance?: string;
usdcBalanceFormatted?: string;
diff --git a/lib/client/format.test.ts b/lib/client/format.test.ts
index a9a77a8..86ff83a 100644
--- a/lib/client/format.test.ts
+++ b/lib/client/format.test.ts
@@ -6,6 +6,7 @@ describe("format", () => {
it("formats USDC and target amounts", () => {
expect(formatUsdc("100000000")).toBe("100");
expect(formatUsdc("123456789")).toBe("123.45");
+ expect(formatUsdc("996700000")).toBe("996.70");
expect(formatTarget("121000", "nep141:btc.omft.near")).toBe("0.00121 BTC");
expect(formatTarget(null, "nep141:btc.omft.near")).toBe("—");
});
diff --git a/lib/client/format.ts b/lib/client/format.ts
index 66c7cf8..4e95110 100644
--- a/lib/client/format.ts
+++ b/lib/client/format.ts
@@ -6,7 +6,12 @@
import { TARGET_ASSETS, targetByAssetId, USDC_DECIMALS } from "../core/assets";
import { formatAmount } from "../core/money";
-export const formatUsdc = (base: string, maxFraction = 2) => formatAmount(base, USDC_DECIMALS, maxFraction);
+/** Dollars: whole numbers stay whole ("100"), anything with cents shows two decimals ("996.70"). */
+export function formatUsdc(base: string, maxFraction = 2): string {
+ const s = formatAmount(base, USDC_DECIMALS, maxFraction);
+ const [whole, frac] = s.split(".");
+ return frac && maxFraction === 2 ? `${whole}.${frac.padEnd(2, "0")}` : s;
+}
export function formatTarget(base: string | null, assetId: string): string {
const t = targetByAssetId(assetId);
diff --git a/lib/core/cost.test.ts b/lib/core/cost.test.ts
index 648eb5a..addafc0 100644
--- a/lib/core/cost.test.ts
+++ b/lib/core/cost.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { checkCost, costBps } from "./cost";
+import { checkCost, costBps, costSkipNote } from "./cost";
// Roadmap: K2.2 · numbers from real dry quotes on 2026-11-04 (ARCHITECTURE §12)
describe("cost", () => {
@@ -20,6 +20,11 @@ describe("cost", () => {
expect(costBps({ amountInUsd: "10", amountOutUsd: "10.5" })).toBe(0);
});
+ it("explains skips in plain language", () => {
+ expect(costSkipNote(435, 300)).toBe("Fees were 4.35%, above your 3.00% limit");
+ expect(costSkipNote(null, 300)).toMatch(/didn't include a cost/);
+ });
+
it("checks against the plan limit", () => {
expect(checkCost({ amountInUsd: "100", amountOutUsd: "99" }, 300)).toEqual({ ok: true, costBps: 100 });
expect(checkCost({ amountInUsd: "10", amountOutUsd: "8.454" }, 300)).toEqual({ ok: false, costBps: 1546, reason: "over_limit" });
diff --git a/lib/core/cost.ts b/lib/core/cost.ts
index c81f95a..55628a5 100644
--- a/lib/core/cost.ts
+++ b/lib/core/cost.ts
@@ -26,6 +26,14 @@ export function costBps(quote: Pick `${(bps / 100).toFixed(2)}%`;
+ return costBps === null
+ ? "The price quote didn't include a cost, so it wasn't safe to buy"
+ : `Fees were ${pct(costBps)}, above your ${pct(maxCostBps)} limit`;
+}
+
export type CostVerdict = { ok: true; costBps: number } | { ok: false; costBps: number | null; reason: "unknown_cost" | "over_limit" };
export function checkCost(quote: Pick, maxCostBps: number): CostVerdict {
diff --git a/lib/db/queries/buys.ts b/lib/db/queries/buys.ts
index a6e121c..40babf9 100644
--- a/lib/db/queries/buys.ts
+++ b/lib/db/queries/buys.ts
@@ -2,10 +2,10 @@
* Queries for buys, including skipped ones. Roadmap: K3.4
*/
-import { desc, eq, inArray } from "drizzle-orm";
+import { and, desc, eq, inArray, notInArray } from "drizzle-orm";
import type { BuyStatus } from "../../core/status";
import type { Db } from "../client";
-import { buys, type Buy } from "../schema";
+import { buys, users, type Buy } from "../schema";
export type NewBuy = typeof buys.$inferInsert;
@@ -22,9 +22,10 @@ export async function listBuysByUser(db: Db, userId: string, limit = 200): Promi
return db.select().from(buys).where(eq(buys.userId, userId)).orderBy(desc(buys.createdAt)).limit(limit);
}
-/** Buys sent on-chain whose 1Click status isn't final yet. */
+/** Real buys sent on-chain whose 1Click status isn't final yet (demo users excluded). */
export async function listInFlightBuys(db: Db): Promise {
- return db.select().from(buys).where(inArray(buys.status, ["sent", "processing"]));
+ const demoUsers = db.select({ id: users.id }).from(users).where(eq(users.isDemo, true));
+ return db.select().from(buys).where(and(inArray(buys.status, ["sent", "processing"]), notInArray(buys.userId, demoUsers)));
}
/** Most recent buy row for a user (any status), used for in-flight and retry-backoff checks. */
diff --git a/lib/db/queries/fundingAttempts.ts b/lib/db/queries/fundingAttempts.ts
index 685859a..9cd602f 100644
--- a/lib/db/queries/fundingAttempts.ts
+++ b/lib/db/queries/fundingAttempts.ts
@@ -5,7 +5,7 @@
import { and, desc, eq, lt, notInArray } from "drizzle-orm";
import { FUNDING_TERMINAL, type FundingStatus } from "../../core/status";
import type { Db } from "../client";
-import { fundingAttempts, type FundingAttempt } from "../schema";
+import { fundingAttempts, users, type FundingAttempt } from "../schema";
export type NewFundingAttempt = typeof fundingAttempts.$inferInsert;
@@ -22,9 +22,13 @@ export async function listFundingByUser(db: Db, userId: string, limit = 50): Pro
return db.select().from(fundingAttempts).where(eq(fundingAttempts.userId, userId)).orderBy(desc(fundingAttempts.createdAt)).limit(limit);
}
-/** Attempts the worker still polls. */
+/** Attempts the real worker still polls (demo users excluded). */
export async function listActiveFunding(db: Db): Promise {
- return db.select().from(fundingAttempts).where(notInArray(fundingAttempts.status, [...FUNDING_TERMINAL]));
+ const demoUsers = db.select({ id: users.id }).from(users).where(eq(users.isDemo, true));
+ return db
+ .select()
+ .from(fundingAttempts)
+ .where(and(notInArray(fundingAttempts.status, [...FUNDING_TERMINAL]), notInArray(fundingAttempts.userId, demoUsers)));
}
export async function updateFundingStatus(
diff --git a/lib/db/queries/users.ts b/lib/db/queries/users.ts
index 4b6e019..7769c5a 100644
--- a/lib/db/queries/users.ts
+++ b/lib/db/queries/users.ts
@@ -2,7 +2,7 @@
* Queries for users. Roadmap: K3.4
*/
-import { eq, isNotNull } from "drizzle-orm";
+import { and, eq, isNotNull } from "drizzle-orm";
import type { Db } from "../client";
import { users, type User } from "../schema";
@@ -27,7 +27,7 @@ export async function setVault(db: Db, userId: string, vaultAccountId: string):
await db.update(users).set({ vaultAccountId }).where(eq(users.id, userId));
}
-/** Everyone the scheduler has to look at. */
+/** Everyone the real scheduler has to look at. Demo users never reach real-mode loops. */
export async function listUsersWithVault(db: Db): Promise {
- return db.select().from(users).where(isNotNull(users.vaultAccountId));
+ return db.select().from(users).where(and(isNotNull(users.vaultAccountId), eq(users.isDemo, false)));
}
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 4b19e25..08cd327 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -72,6 +72,17 @@ export const buys = pgTable(
(t) => [index("buys_user_idx").on(t.userId)],
);
+/** Demo mode only: the fake vault's on-chain state. Balances are derived from demo rows (lib/near/demo.ts). */
+export const demoVaults = pgTable("demo_vaults", {
+ vaultAccountId: text("vault_account_id").primaryKey(),
+ userId: uuid("user_id")
+ .notNull()
+ .references(() => users.id, { onDelete: "cascade" }),
+ state: jsonb("state").notNull(),
+ withdrawn: baseUnits("withdrawn").notNull().default("0"),
+});
+
export type User = typeof users.$inferSelect;
export type FundingAttempt = typeof fundingAttempts.$inferSelect;
export type Buy = typeof buys.$inferSelect;
+export type DemoVault = typeof demoVaults.$inferSelect;
diff --git a/lib/db/seed-demo.ts b/lib/db/seed-demo.ts
index 0b026c5..5329a69 100644
--- a/lib/db/seed-demo.ts
+++ b/lib/db/seed-demo.ts
@@ -1,7 +1,148 @@
/**
- * Seeds a demo vault with a plan, deposits and 3 weeks of buys incl. skipped_cost.
- * Roadmap: K7.2 · Spec: PRD.md FR-17
- * Status: scaffold — not implemented yet.
+ * Demo data: a fresh fictional saver per visitor (never shared), with a weekly $100 BTC plan, two
+ * deposits and three weeks of buys including one skipped for fees. Fast-forward simulates the next
+ * 30 days of the plan. Everything is marked demo and never touches real services.
+ * Roadmap: K7.2, K7.4
*/
-export {};
+import { randomUUID } from "node:crypto";
+import { and, eq } from "drizzle-orm";
+import { TARGET_ASSETS, USDC_DECIMALS } from "../core/assets";
+import { costSkipNote } from "../core/cost";
+import { asBaseUnits } from "../core/money";
+import type { DemoVaultState } from "../near/demo";
+import { DemoRuleError, demoBalance, loadDemoVault, saveDemoVaultState } from "../near/demo";
+import { FALLBACK_TOKENS, fromBase, modelCostBps, toBase } from "../oneclick/demo";
+import type { Db } from "./client";
+import { buys, demoVaults, fundingAttempts, users, type User } from "./schema";
+
+const DAY_S = 86_400;
+const BTC = TARGET_ASSETS.btc;
+/** BIP-173 test vector — a valid address nobody's funds depend on. */
+export const DEMO_BTC_ADDRESS = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4";
+const priceOf = (assetId: string) => FALLBACK_TOKENS.find((t) => t.assetId === assetId)?.priceUsd ?? 1;
+
+const usdc = (dollars: number) => toBase(dollars, USDC_DECIMALS);
+const fakeHash = (kind: string) => `demo-${kind}-${randomUUID().slice(0, 12)}`;
+
+function buyRow(userId: string, s: DemoVaultState, atS: number, amountIn: string, spikeBps = 0) {
+ const usd = fromBase(amountIn, USDC_DECIMALS);
+ const cost = modelCostBps(s.targetAsset!, usd, spikeBps);
+ const base = {
+ userId,
+ quoteRef: `demo_${randomUUID()}`,
+ amountIn: asBaseUnits(amountIn),
+ targetAsset: s.targetAsset!,
+ destinationAddress: s.destinationAddress!,
+ costBps: cost,
+ amountInUsd: usd.toFixed(2),
+ createdAt: new Date(atS * 1000),
+ completedAt: new Date(atS * 1000 + 8 * 60_000),
+ };
+ if (cost > s.maxCostBps) {
+ return { ...base, status: "skipped_cost" as const, note: costSkipNote(cost, s.maxCostBps), completedAt: new Date(atS * 1000) };
+ }
+ const target = Object.values(TARGET_ASSETS).find((t) => t.assetId === s.targetAsset)!;
+ const amountOut = toBase((usd * (1 - cost / 10_000)) / priceOf(target.assetId), target.decimals);
+ return { ...base, status: "success" as const, amountOut, depositAddress: fakeHash("dep"), nearTxHash: fakeHash("near"), destinationTxHash: fakeHash("dest") };
+}
+
+async function writeHistory(db: Db, userId: string, nowS: number): Promise {
+ const state: DemoVaultState = {
+ targetAsset: BTC.assetId,
+ destinationAddress: DEMO_BTC_ADDRESS,
+ amountPerRun: usdc(100),
+ intervalS: 7 * DAY_S,
+ maxCostBps: 300,
+ paused: false,
+ lastRunAtS: nowS - 6 * DAY_S,
+ };
+ const deposit = (daysAgo: number, originAsset: string, amountIn: string, dollars: number) => ({
+ userId,
+ originAsset,
+ amountIn: asBaseUnits(amountIn),
+ expectedOut: usdc(dollars),
+ refundTo: "demo-refund-address",
+ depositAddress: fakeHash("fund"),
+ quoteDeadline: new Date((nowS - daysAgo * DAY_S + 1800) * 1000),
+ quoteSignature: "demo",
+ quoteRaw: { demo: true },
+ status: "credited" as const,
+ createdAt: new Date((nowS - daysAgo * DAY_S) * 1000),
+ updatedAt: new Date((nowS - daysAgo * DAY_S) * 1000),
+ });
+ await db.insert(fundingAttempts).values([
+ deposit(28, "nep141:sol.omft.near", "10600000000", 997.1),
+ deposit(9, "nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near", "300000000", 299.6),
+ ]);
+ await db.insert(buys).values([
+ buyRow(userId, state, nowS - 27 * DAY_S, usdc(100)),
+ buyRow(userId, state, nowS - 20 * DAY_S, usdc(100), 220), // fee spike → skipped, nothing spent
+ buyRow(userId, state, nowS - 13 * DAY_S, usdc(100)),
+ buyRow(userId, state, nowS - 6 * DAY_S, usdc(100)),
+ ]);
+ return state;
+}
+
+/** Creates a new demo saver with a vault and history. */
+export async function seedDemoUser(db: Db, now = Date.now()): Promise {
+ const id = randomUUID().slice(0, 8);
+ const [user] = await db
+ .insert(users)
+ .values({ nearAccountId: `saver-${id}.demo`, vaultAccountId: `v${id}.vaults.demo`, isDemo: true })
+ .returning();
+ const state = await writeHistory(db, user!.id, Math.floor(now / 1000));
+ await db.insert(demoVaults).values({ vaultAccountId: user!.vaultAccountId!, userId: user!.id, state });
+ return user!;
+}
+
+/** Back to the starting story for this demo user. */
+export async function resetDemoUser(db: Db, user: User, now = Date.now()): Promise {
+ if (!user.isDemo || !user.vaultAccountId) throw new DemoRuleError("Not a demo user");
+ await db.delete(buys).where(eq(buys.userId, user.id));
+ await db.delete(fundingAttempts).where(eq(fundingAttempts.userId, user.id));
+ const state = await writeHistory(db, user.id, Math.floor(now / 1000));
+ await db.update(demoVaults).set({ state, withdrawn: "0" }).where(and(eq(demoVaults.vaultAccountId, user.vaultAccountId), eq(demoVaults.userId, user.id)));
+}
+
+/**
+ * Simulates the plan for the next `days`: one buy per interval while there's money, the same cost check
+ * as the real scheduler, and one fee spike so a skip shows up. Rows are dated in the future.
+ */
+export async function fastForward(db: Db, user: User, days = 30, now = Date.now()): Promise<{ bought: number; skipped: number; stoppedEmpty: boolean }> {
+ if (!user.isDemo || !user.vaultAccountId) throw new DemoRuleError("Not a demo user");
+ const { state } = await loadDemoVault(db, user.vaultAccountId);
+ if (state.paused || !state.targetAsset || !state.destinationAddress) throw new DemoRuleError("Resume your plan first: a paused vault doesn't buy");
+ const nowS = Math.floor(now / 1000);
+ const endS = nowS + days * DAY_S;
+ let t = Math.max(nowS, state.lastRunAtS + state.intervalS);
+ let balance = BigInt(await demoBalance(db, user.vaultAccountId));
+ let bought = 0;
+ let skipped = 0;
+ let runs = 0;
+ let stoppedEmpty = false;
+ const rows = [];
+ while (t <= endS && runs < 200) {
+ if (balance < BigInt(usdc(1))) {
+ stoppedEmpty = true;
+ break;
+ }
+ const amount = balance < BigInt(state.amountPerRun) ? balance.toString() : state.amountPerRun;
+ const row = buyRow(user.id, state, t, amount, runs === 1 ? 260 : 0);
+ rows.push(row);
+ if (row.status === "success") {
+ balance -= BigInt(amount);
+ bought++;
+ state.lastRunAtS = t;
+ t += state.intervalS;
+ } else {
+ skipped++;
+ t += Math.max(15 * 60, Math.min(state.intervalS, DAY_S)); // retry the next day, like the scheduler's backoff
+ }
+ runs++;
+ }
+ if (rows.length) await db.insert(buys).values(rows);
+ await saveDemoVaultState(db, user.vaultAccountId, state);
+ return { bought, skipped, stoppedEmpty };
+}
+
diff --git a/lib/near/demo.ts b/lib/near/demo.ts
index 5b36d80..f486e50 100644
--- a/lib/near/demo.ts
+++ b/lib/near/demo.ts
@@ -1,7 +1,138 @@
/**
- * DemoVaultClient for demo mode.
- * Roadmap: K7.1 · Spec: ARCHITECTURE.md §3
- * Status: scaffold — not implemented yet.
+ * Demo-mode VaultClient. The fake vault's plan lives in `demo_vaults`; its USDC balance is derived from
+ * the demo user's rows (credited deposits − buys − withdrawals), so there is one source of truth.
+ * Owner actions (set_plan, resume, pause, withdraw) arrive from the UI instead of a wallet and follow
+ * the same rules as contracts/vault. Roadmap: K7.1
*/
-export {};
+import { and, eq, inArray, sql } from "drizzle-orm";
+import type { VaultClient } from "../core/adapters";
+import { asBaseUnits } from "../core/money";
+import type { BaseUnits, VaultState } from "../core/types";
+import type { OwnerTx } from "../client/ownerTx";
+import type { Db } from "../db/client";
+import { buys, demoVaults, fundingAttempts, users } from "../db/schema";
+
+export interface DemoVaultState {
+ targetAsset: string | null;
+ destinationAddress: string | null;
+ amountPerRun: string;
+ intervalS: number;
+ maxCostBps: number;
+ paused: boolean;
+ lastRunAtS: number;
+}
+
+export class DemoRuleError extends Error {}
+
+export async function loadDemoVault(db: Db, vaultAccountId: string) {
+ const row = (await db.select().from(demoVaults).where(eq(demoVaults.vaultAccountId, vaultAccountId)).limit(1))[0];
+ if (!row) throw new DemoRuleError("Demo vault not found");
+ return { row, state: row.state as DemoVaultState };
+}
+
+export function toVaultState(owner: string, s: DemoVaultState): VaultState {
+ const hasPlan = !!s.targetAsset && !!s.destinationAddress && BigInt(s.amountPerRun) > 0n && s.intervalS > 0;
+ return {
+ owner,
+ keeper: "demo-keeper",
+ usdc: "demo-usdc",
+ targetAsset: s.targetAsset,
+ destinationAddress: s.destinationAddress,
+ amountPerRun: asBaseUnits(s.amountPerRun),
+ intervalS: s.intervalS,
+ maxCostBps: s.maxCostBps,
+ paused: s.paused,
+ lastRunAtS: s.lastRunAtS,
+ nextRunAtS: s.paused || !hasPlan ? null : s.lastRunAtS + s.intervalS,
+ };
+}
+
+export async function demoBalance(db: Db, vaultAccountId: string): Promise {
+ const { row } = await loadDemoVault(db, vaultAccountId);
+ const [inRow] = await db
+ .select({ v: sql`coalesce(sum(${fundingAttempts.expectedOut}), 0)` })
+ .from(fundingAttempts)
+ .where(and(eq(fundingAttempts.userId, row.userId), eq(fundingAttempts.status, "credited")));
+ const [outRow] = await db
+ .select({ v: sql`coalesce(sum(${buys.amountIn}), 0)` })
+ .from(buys)
+ .where(and(eq(buys.userId, row.userId), inArray(buys.status, ["sent", "processing", "success"])));
+ const bal = BigInt(String(inRow?.v ?? "0").split(".")[0]!) - BigInt(String(outRow?.v ?? "0").split(".")[0]!) - BigInt(row.withdrawn);
+ return asBaseUnits((bal > 0n ? bal : 0n).toString());
+}
+
+async function save(db: Db, vaultAccountId: string, state: DemoVaultState, withdrawn?: string) {
+ await db
+ .update(demoVaults)
+ .set(withdrawn === undefined ? { state } : { state, withdrawn })
+ .where(eq(demoVaults.vaultAccountId, vaultAccountId));
+}
+
+/** Applies an owner transaction with the contract's rules (ARCHITECTURE §3.3). */
+export async function applyOwnerTx(db: Db, vaultAccountId: string, tx: OwnerTx): Promise {
+ if (tx.receiverId !== vaultAccountId) throw new DemoRuleError("Transaction is for a different vault");
+ const { row, state } = await loadDemoVault(db, vaultAccountId);
+ let s = { ...state };
+ let withdrawn = BigInt(row.withdrawn);
+ for (const { params } of tx.actions) {
+ const args = params.args as Record;
+ switch (params.methodName) {
+ case "set_plan": {
+ const amount = String(args.amount_per_run ?? "");
+ const interval = Number(args.interval_s);
+ const cost = Number(args.max_cost_bps);
+ if (!/^\d+$/.test(amount) || BigInt(amount) <= 0n) throw new DemoRuleError("amount_per_run must be positive");
+ if (!(interval >= 60)) throw new DemoRuleError("interval_s too short");
+ if (!(cost > 0 && cost <= 5_000)) throw new DemoRuleError("max_cost_bps out of range");
+ s = { ...s, targetAsset: String(args.target_asset), destinationAddress: String(args.destination_address), amountPerRun: amount, intervalS: interval, maxCostBps: cost };
+ break;
+ }
+ case "resume":
+ if (!s.targetAsset || !s.destinationAddress) throw new DemoRuleError("Set a plan first");
+ s.paused = false;
+ break;
+ case "pause":
+ s.paused = true;
+ break;
+ case "withdraw": {
+ const amount = BigInt(String(args.amount ?? "0"));
+ const balance = BigInt(await demoBalance(db, vaultAccountId));
+ if (amount <= 0n || amount > balance) throw new DemoRuleError("Withdraw amount is more than the vault holds");
+ withdrawn += amount;
+ break;
+ }
+ case "recover_token":
+ throw new DemoRuleError("The demo vault holds no other tokens");
+ default:
+ throw new DemoRuleError(`Unknown method ${params.methodName}`);
+ }
+ }
+ await save(db, vaultAccountId, s, withdrawn.toString());
+ return toVaultState(await ownerOf(db, row.userId), s);
+}
+
+async function ownerOf(db: Db, userId: string): Promise {
+ return (await db.select({ a: users.nearAccountId }).from(users).where(eq(users.id, userId)).limit(1))[0]?.a ?? "demo";
+}
+
+export function demoVaultClient(db: Db): VaultClient {
+ return {
+ async findVault(owner) {
+ return (await db.select({ v: users.vaultAccountId }).from(users).where(eq(users.nearAccountId, owner)).limit(1))[0]?.v ?? null;
+ },
+ async createVaultFor() {
+ throw new DemoRuleError("Demo vaults are created when the demo starts");
+ },
+ async getState(vaultAccountId) {
+ const { row, state } = await loadDemoVault(db, vaultAccountId);
+ return toVaultState(await ownerOf(db, row.userId), state);
+ },
+ usdcBalance: (vaultAccountId) => demoBalance(db, vaultAccountId),
+ async executeBuy() {
+ return { txHash: `demo-tx-${Date.now()}` };
+ },
+ };
+}
+
+export { save as saveDemoVaultState };
diff --git a/lib/oneclick/demo.ts b/lib/oneclick/demo.ts
index fccd158..a8e95d5 100644
--- a/lib/oneclick/demo.ts
+++ b/lib/oneclick/demo.ts
@@ -1,7 +1,170 @@
/**
- * Demo QuoteProvider/StatusProvider: real dry quotes online, fixtures offline.
- * Roadmap: K7.1 · Spec: ARCHITECTURE.md §4.2
- * Status: scaffold — not implemented yet.
+ * Demo-mode QuoteProvider / StatusProvider. Dry quotes try live 1Click first (real prices, no funds) and
+ * fall back to a fee model calibrated on real quotes (ARCHITECTURE §12) when offline. "Real" demo quotes
+ * get a fake `demo-…` deposit address whose status advances with time. Nothing here can move funds.
+ * Roadmap: K7.1, K7.3
*/
-export {};
+import type { QuoteProvider, StatusProvider } from "../core/adapters";
+import { targetByAssetId, USDC_DECIMALS, USDC_ON_NEAR } from "../core/assets";
+import { asBaseUnits } from "../core/money";
+import type { OneClickStatus } from "../core/status";
+import type { AssetId, BaseUnits, QuoteSummary } from "../core/types";
+import { oneClickQuotes } from "./index";
+import { getTokens, type TokenInfo } from "./tokens";
+
+/** An existing NEAR account to stand in as refund/recipient for live dry quotes (dry quotes never move funds). */
+const LIVE_STAND_IN_ACCOUNT = "near";
+const LIVE_TIMEOUT_MS = 5_000;
+
+/** Used when /v0/tokens can't be reached. Prices are rough, for the demo model only. */
+export const FALLBACK_TOKENS: TokenInfo[] = [
+ { assetId: USDC_ON_NEAR, symbol: "USDC", blockchain: "near", decimals: 6, priceUsd: 1 },
+ { assetId: "nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near", symbol: "USDC", blockchain: "base", decimals: 6, priceUsd: 1 },
+ { assetId: "nep141:arb-0xaf88d065e77c8cc2239327c5edb3a432268e5831.omft.near", symbol: "USDC", blockchain: "arb", decimals: 6, priceUsd: 1 },
+ { assetId: "nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near", symbol: "USDC", blockchain: "sol", decimals: 6, priceUsd: 1 },
+ { assetId: "nep141:eth-0xdac17f958d2ee523a2206206994597c13d831ec7.omft.near", symbol: "USDT", blockchain: "eth", decimals: 6, priceUsd: 1 },
+ { assetId: "nep141:sol.omft.near", symbol: "SOL", blockchain: "sol", decimals: 9, priceUsd: 95 },
+ { assetId: "nep141:eth.omft.near", symbol: "ETH", blockchain: "eth", decimals: 18, priceUsd: 2_400 },
+ { assetId: "nep141:btc.omft.near", symbol: "BTC", blockchain: "btc", decimals: 8, priceUsd: 80_000 },
+ { assetId: "nep141:wrap.near", symbol: "wNEAR", blockchain: "near", decimals: 24, priceUsd: 4.1 },
+];
+
+/** Payout network fee in USD per target chain + solver spread. Calibrated: $10 BTC ≈ 15%, $100 BTC ≈ 1.6%. */
+export const NETWORK_FEE_USD: Record = { btc: 1.5, eth: 0.2, near: 0.02 };
+export const SPREAD_BPS = 25;
+
+async function tokens(): Promise {
+ try {
+ return await getTokens();
+ } catch {
+ return FALLBACK_TOKENS;
+ }
+}
+
+async function tokenInfo(assetId: AssetId): Promise {
+ return (await tokens()).find((t) => t.assetId === assetId) ?? FALLBACK_TOKENS.find((t) => t.assetId === assetId);
+}
+
+/** Display-model math only; on-chain amounts never come from here. */
+export function toBase(amount: number, decimals: number): BaseUnits {
+ if (!(amount > 0)) return asBaseUnits("0");
+ const precise = Math.min(decimals, 8);
+ const scaled = BigInt(Math.floor(amount * 10 ** precise));
+ return asBaseUnits((scaled * 10n ** BigInt(decimals - precise)).toString());
+}
+
+export function fromBase(amount: string, decimals: number): number {
+ return Number(BigInt(amount)) / 10 ** decimals;
+}
+
+/** Modelled cost in bps for buying `usd` of `targetAssetId`, plus an optional fee spike. */
+export function modelCostBps(targetAssetId: AssetId, usd: number, spikeBps = 0): number {
+ const chain = targetByAssetId(targetAssetId)?.chain ?? "near";
+ return Math.ceil(SPREAD_BPS + ((NETWORK_FEE_USD[chain] ?? 0.1) / usd) * 10_000 + spikeBps);
+}
+
+export const demoDepositAddress = (now = Date.now()) => `demo-${now}-${Math.random().toString(36).slice(2, 8)}`;
+
+async function modelQuote(p: {
+ dry: boolean;
+ originAsset: AssetId;
+ destinationAsset: AssetId;
+ amountIn: BaseUnits;
+ recipient: string;
+ refundTo: string;
+ costBps: (usd: number) => number;
+}): Promise {
+ const [inTok, outTok] = await Promise.all([tokenInfo(p.originAsset), tokenInfo(p.destinationAsset)]);
+ const inDec = inTok?.decimals ?? USDC_DECIMALS;
+ const outDec = outTok?.decimals ?? USDC_DECIMALS;
+ const inUsd = fromBase(p.amountIn, inDec) * (inTok?.priceUsd ?? 1);
+ const outUsd = inUsd * (1 - p.costBps(inUsd) / 10_000);
+ const amountOut = toBase(outUsd / (outTok?.priceUsd ?? 1), outDec);
+ return {
+ dry: p.dry,
+ originAsset: p.originAsset,
+ refundTo: p.refundTo,
+ depositAddress: p.dry ? null : demoDepositAddress(),
+ amountIn: p.amountIn,
+ amountOut,
+ minAmountOut: asBaseUnits(((BigInt(amountOut) * 99n) / 100n).toString()),
+ timeEstimateS: p.destinationAsset === "nep141:btc.omft.near" ? 465 : 30,
+ amountInUsd: inUsd.toFixed(4),
+ amountOutUsd: outUsd.toFixed(4),
+ recipient: p.recipient,
+ destinationAsset: p.destinationAsset,
+ deadline: new Date(Date.now() + 30 * 60_000).toISOString(),
+ signature: "demo",
+ raw: { demo: true },
+ };
+}
+
+async function tryLive(fn: () => Promise): Promise {
+ try {
+ return await Promise.race([fn(), new Promise((r) => setTimeout(() => r(null), LIVE_TIMEOUT_MS))]);
+ } catch {
+ return null;
+ }
+}
+
+export const demoQuotes: QuoteProvider = {
+ async fundingQuote(input, { dry }) {
+ if (dry) {
+ const live = await tryLive(() => oneClickQuotes.fundingQuote({ ...input, vault: LIVE_STAND_IN_ACCOUNT }, { dry: true }));
+ if (live) return { ...live, recipient: input.vault };
+ }
+ return modelQuote({
+ dry,
+ originAsset: input.originAsset,
+ destinationAsset: USDC_ON_NEAR,
+ amountIn: input.amountIn,
+ recipient: input.vault,
+ refundTo: input.refundTo,
+ costBps: () => 30,
+ });
+ },
+ async buyQuote({ vault, vaultAccountId, amountIn }, { dry }) {
+ if (dry) {
+ const live = await tryLive(() => oneClickQuotes.buyQuote({ vault, vaultAccountId: LIVE_STAND_IN_ACCOUNT, amountIn }, { dry: true }));
+ if (live) return { ...live, refundTo: vaultAccountId };
+ }
+ return modelQuote({
+ dry,
+ originAsset: USDC_ON_NEAR,
+ destinationAsset: vault.targetAsset!,
+ amountIn,
+ recipient: vault.destinationAddress!,
+ refundTo: vaultAccountId,
+ costBps: (usd) => modelCostBps(vault.targetAsset!, usd),
+ });
+ },
+};
+
+/** Demo deposits advance on their own: waiting → seen → converting → done, ~20 s per step. */
+export function demoStatusAt(depositAddress: string, now = Date.now()): OneClickStatus {
+ const created = Number(depositAddress.split("-")[1]);
+ if (!Number.isFinite(created)) return "FAILED";
+ const s = (now - created) / 1000;
+ if (s < 20) return "PENDING_DEPOSIT";
+ if (s < 40) return "KNOWN_DEPOSIT_TX";
+ if (s < 60) return "PROCESSING";
+ return "SUCCESS";
+}
+
+export const demoStatus: StatusProvider = {
+ async getStatus(depositAddress) {
+ return { status: demoStatusAt(depositAddress), raw: { demo: true } };
+ },
+ async submitDepositTx() {
+ /* nothing to tell anyone in demo mode */
+ },
+};
+
+export async function tokensWithFallback(): Promise<{ tokens: TokenInfo[]; offline: boolean }> {
+ try {
+ return { tokens: await getTokens(), offline: false };
+ } catch {
+ return { tokens: FALLBACK_TOKENS, offline: true };
+ }
+}
diff --git a/lib/server/adapters.ts b/lib/server/adapters.ts
index 663b0ff..fc138bc 100644
--- a/lib/server/adapters.ts
+++ b/lib/server/adapters.ts
@@ -9,9 +9,11 @@ import "server-only";
import type { QuoteProvider, StatusProvider, VaultClient } from "../core/adapters";
import { getDb, type Db } from "../db/client";
import { nearVaultClient } from "../near";
+import { demoVaultClient } from "../near/demo";
import { createKeeper } from "../near/keeper";
import { createProvider, type NearProvider } from "../near/rpc";
import { configureOneClick, getTokens, oneClickQuotes, oneClickStatus } from "../oneclick";
+import { demoQuotes, demoStatus, tokensWithFallback } from "../oneclick/demo";
import type { TokenInfo } from "../oneclick/tokens";
import { NotConfiguredError } from "./http";
@@ -57,6 +59,23 @@ export async function getServices(): Promise {
return real;
}
+/** Demo sessions get the same routes with demo adapters on the same database (K7.1). */
+export function demoServices(base: Services): Services {
+ return {
+ db: base.db,
+ quotes: demoQuotes,
+ status: demoStatus,
+ listTokens: async () => (await tokensWithFallback()).tokens,
+ near: null,
+ vault: demoVaultClient(base.db),
+ };
+}
+
+export async function servicesFor(session: { demo: boolean }): Promise {
+ const base = await getServices();
+ return session.demo ? demoServices(base) : base;
+}
+
export function requireVaultClient(s: Services): VaultClient {
if (!s.vault) throw new NotConfiguredError("NEAR keeper/factory (NEAR_RPC_URL, KEEPER_*, FACTORY_ACCOUNT_ID, USDC_CONTRACT_ID)");
return s.vault;
diff --git a/lib/server/context.ts b/lib/server/context.ts
index c2652de..e7c2021 100644
--- a/lib/server/context.ts
+++ b/lib/server/context.ts
@@ -6,7 +6,7 @@ import "server-only";
import { getUserById } from "../db/queries/users";
import type { User } from "../db/schema";
-import { getServices, type Services } from "./adapters";
+import { servicesFor, type Services } from "./adapters";
import { HttpError } from "./http";
import { requireSession, type Session } from "./session";
@@ -18,9 +18,9 @@ export interface UserContext {
export async function requireUser(req: Request): Promise {
const session = requireSession(req);
- const services = await getServices();
+ const services = await servicesFor(session);
const user = await getUserById(services.db, session.userId);
- if (!user) throw new HttpError(401, "Sign in again");
+ if (!user || user.isDemo !== session.demo) throw new HttpError(401, "Sign in again");
return { session, services, user };
}
diff --git a/lib/server/demo.test.ts b/lib/server/demo.test.ts
new file mode 100644
index 0000000..59eac50
--- /dev/null
+++ b/lib/server/demo.test.ts
@@ -0,0 +1,150 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+import * as demoRoute from "@/app/api/demo/[action]/route";
+import * as fundQuoteRoute from "@/app/api/fund/quote/route";
+import * as vaultRoute from "@/app/api/vault/route";
+import { planTx, pauseTx, recoverTokenTx, resumeTx, withdrawTx } from "../client/ownerTx";
+import { asBaseUnits } from "../core/money";
+import { createDb, type Db } from "../db/client";
+import { listBuysByUser } from "../db/queries/buys";
+import { listActiveFunding, insertFundingAttempt } from "../db/queries/fundingAttempts";
+import { listInFlightBuys, insertBuy } from "../db/queries/buys";
+import { listUsersWithVault, upsertUser } from "../db/queries/users";
+import { fastForward, seedDemoUser } from "../db/seed-demo";
+import { applyOwnerTx, demoBalance, demoVaultClient, DemoRuleError } from "../near/demo";
+import { demoStatusAt, modelCostBps } from "../oneclick/demo";
+import { setServicesForTest, type Services } from "./adapters";
+import { resetRateLimits } from "./rateLimit";
+import { sessionCookie } from "./session";
+
+// Roadmap: K7.1–K7.4
+let db: Db;
+beforeEach(async () => {
+ db = createDb({ pgliteDataDir: "memory://" });
+ await db.migrate();
+ resetRateLimits();
+ // Real-mode services that must never be touched by a demo session.
+ const untouchable = () => {
+ throw new Error("real service used in demo mode");
+ };
+ setServicesForTest({
+ db,
+ quotes: { fundingQuote: untouchable, buyQuote: untouchable },
+ status: { getStatus: untouchable, submitDepositTx: untouchable },
+ listTokens: async () => [],
+ near: null,
+ vault: null,
+ } as unknown as Services);
+});
+afterAll(() => setServicesForTest(null));
+
+const cookieOf = (res: Response) => res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; ");
+const req = (path: string, init: { method?: string; cookie?: string; body?: unknown } = {}) =>
+ new Request(`http://localhost:3000${path}`, {
+ method: init.method ?? "POST",
+ headers: { "content-type": "application/json", ...(init.cookie ? { cookie: init.cookie } : {}) },
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
+ });
+const action = (a: string) => ({ params: Promise.resolve({ action: a }) });
+
+describe("seed (K7.2)", () => {
+ it("creates a private demo saver with a running plan, deposits and history", async () => {
+ const u = await seedDemoUser(db);
+ expect(u.isDemo).toBe(true);
+ expect(await demoBalance(db, u.vaultAccountId!)).toBe("996700000"); // $997.10 + $299.60 − 3 × $100
+ const rows = await listBuysByUser(db, u.id);
+ expect(rows.map((b) => b.status).sort()).toEqual(["skipped_cost", "success", "success", "success"]);
+ expect(rows.find((b) => b.status === "skipped_cost")?.note).toMatch(/^Fees were/);
+ const state = await demoVaultClient(db).getState(u.vaultAccountId!);
+ expect(state).toMatchObject({ paused: false, targetAsset: "nep141:btc.omft.near" });
+ });
+
+ it("keeps demo users out of every real worker query", async () => {
+ const demo = await seedDemoUser(db);
+ await insertFundingAttempt(db, { userId: demo.id, originAsset: "x", amountIn: asBaseUnits("1"), expectedOut: asBaseUnits("1"), refundTo: "r", depositAddress: "demo-1-a", quoteDeadline: new Date(Date.now() + 60_000), quoteSignature: "s", quoteRaw: {} });
+ await insertBuy(db, { userId: demo.id, quoteRef: "demo-q", amountIn: asBaseUnits("1"), targetAsset: "t", destinationAddress: "d", status: "sent" });
+ await upsertUser(db, "real.near");
+ expect(await listUsersWithVault(db)).toHaveLength(0);
+ expect(await listActiveFunding(db)).toHaveLength(0);
+ expect(await listInFlightBuys(db)).toHaveLength(0);
+ });
+});
+
+describe("owner actions without a wallet (K7.1)", () => {
+ it("follows the contract's rules", async () => {
+ const u = await seedDemoUser(db);
+ const v = u.vaultAccountId!;
+ expect((await applyOwnerTx(db, v, pauseTx(v))).paused).toBe(true);
+ expect((await applyOwnerTx(db, v, resumeTx(v))).paused).toBe(false);
+ const s = await applyOwnerTx(db, v, planTx(v, { targetAsset: "nep141:eth.omft.near", destinationAddress: "0xabc", amountPerRun: asBaseUnits("50000000"), intervalS: 86_400, maxCostBps: 200 }));
+ expect(s).toMatchObject({ targetAsset: "nep141:eth.omft.near", amountPerRun: "50000000", paused: false });
+ await expect(applyOwnerTx(db, v, planTx(v, { targetAsset: "a", destinationAddress: "b", amountPerRun: asBaseUnits("1"), intervalS: 59, maxCostBps: 100 }))).rejects.toThrow(/interval_s too short/);
+ await expect(applyOwnerTx(db, v, withdrawTx(v, asBaseUnits("996700001")))).rejects.toThrow(DemoRuleError);
+ await applyOwnerTx(db, v, withdrawTx(v, asBaseUnits("100000000")));
+ expect(await demoBalance(db, v)).toBe("896700000");
+ await expect(applyOwnerTx(db, v, recoverTokenTx(v, "t.near", asBaseUnits("1")))).rejects.toThrow(/no other tokens/);
+ await expect(applyOwnerTx(db, v, pauseTx("someone-else.vaults.demo"))).rejects.toThrow(/different vault/);
+ });
+});
+
+describe("fast-forward (K7.4)", () => {
+ it("simulates the next 30 days: weekly buys, one fee-spike skip, balance spent", async () => {
+ const u = await seedDemoUser(db);
+ const r = await fastForward(db, u, 30);
+ expect(r.bought).toBeGreaterThanOrEqual(4);
+ expect(r.skipped).toBe(1);
+ expect(BigInt(await demoBalance(db, u.vaultAccountId!))).toBe(996_700_000n - BigInt(r.bought) * 100_000_000n);
+ });
+
+ it("refuses while paused", async () => {
+ const u = await seedDemoUser(db);
+ await applyOwnerTx(db, u.vaultAccountId!, pauseTx(u.vaultAccountId!));
+ await expect(fastForward(db, u, 30)).rejects.toThrow(/Resume your plan/);
+ });
+});
+
+describe("demo model (K7.3)", () => {
+ it("advances demo deposits with time", () => {
+ const t = 1_000_000;
+ const addr = `demo-${t}-abc`;
+ expect([0, 25, 45, 70].map((s) => demoStatusAt(addr, t + s * 1000))).toEqual(["PENDING_DEPOSIT", "KNOWN_DEPOSIT_TX", "PROCESSING", "SUCCESS"]);
+ });
+
+ it("is calibrated on real quotes: $10 BTC ≈ 15%, $100 BTC ≈ 1.75%", () => {
+ expect(modelCostBps("nep141:btc.omft.near", 10)).toBe(1525);
+ expect(modelCostBps("nep141:btc.omft.near", 100)).toBe(175);
+ });
+});
+
+describe("demo routes", () => {
+ it("start signs in a fresh demo saver and every route then uses demo adapters", async () => {
+ const start = await demoRoute.POST(req("/api/demo/start"), action("start"));
+ expect(start.status).toBe(201);
+ const cookie = cookieOf(start);
+ expect(await (await vaultRoute.GET(req("/api/vault", { method: "GET", cookie }))).json()).toMatchObject({ demo: true, usdcBalance: "996700000" });
+ const q = await fundQuoteRoute.POST(req("/api/fund/quote", { cookie, body: { originAsset: "nep141:sol.omft.near", amountIn: "2000000000", refundTo: "So1", dry: false } }));
+ expect(q.status).toBe(201);
+ expect((await q.json()).attempt.depositAddress).toMatch(/^demo-/);
+ });
+
+ it("applies owner-tx, fast-forward and reset for demo sessions only", async () => {
+ const cookie = cookieOf(await demoRoute.POST(req("/api/demo/start"), action("start")));
+ const v = (await (await vaultRoute.GET(req("/api/vault", { method: "GET", cookie }))).json()).vaultAccountId;
+ expect((await demoRoute.POST(req("/api/demo/owner-tx", { cookie, body: { tx: pauseTx(v) } }), action("owner-tx"))).status).toBe(200);
+ expect((await demoRoute.POST(req("/api/demo/fast-forward", { cookie }), action("fast-forward"))).status).toBe(409); // paused
+ expect((await demoRoute.POST(req("/api/demo/reset", { cookie }), action("reset"))).status).toBe(200);
+ expect((await demoRoute.POST(req("/api/demo/fast-forward", { cookie }), action("fast-forward"))).status).toBe(200);
+
+ const real = await upsertUser(db, "alice.near");
+ const realCookie = sessionCookie({ userId: real.id, accountId: "alice.near", demo: false }).split(";")[0];
+ expect((await demoRoute.POST(req("/api/demo/reset", { cookie: realCookie }), action("reset"))).status).toBe(403);
+ expect((await demoRoute.POST(req("/api/demo/nope", { cookie }), action("nope"))).status).toBe(404);
+ });
+
+ it("rejects a session whose demo flag doesn't match the user", async () => {
+ const u = await seedDemoUser(db);
+ const forged = sessionCookie({ userId: u.id, accountId: u.nearAccountId, demo: false }).split(";")[0];
+ expect((await vaultRoute.GET(req("/api/vault", { method: "GET", cookie: forged }))).status).toBe(401);
+ });
+});
+
+vi.setConfig({ testTimeout: 20_000 });
diff --git a/lib/server/session.ts b/lib/server/session.ts
index 37df5f6..cccf5c7 100644
--- a/lib/server/session.ts
+++ b/lib/server/session.ts
@@ -29,15 +29,17 @@ export interface Challenge {
exp: number;
}
-let devSecret: Buffer | undefined;
+// On globalThis, not module state: Next compiles each route into its own bundle, and a module-level
+// secret would differ between the route that signs a session and the one that checks it.
+const g = globalThis as typeof globalThis & { __stackDevSessionSecret?: Buffer };
function secret(): Buffer {
const s = process.env.SESSION_SECRET;
if (s && s.length >= 32) return Buffer.from(s);
if (process.env.NODE_ENV === "production") throw new HttpError(500, "SESSION_SECRET is not set");
// Local and demo mode: a per-process secret, so sessions reset on restart. Fine without real funds.
- devSecret ??= randomBytes(32);
- return devSecret;
+ g.__stackDevSessionSecret ??= randomBytes(32);
+ return g.__stackDevSessionSecret;
}
const b64url = (b: Buffer | string) => Buffer.from(b).toString("base64url");
diff --git a/next.config.ts b/next.config.ts
index 2f6491c..2df5b91 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -2,6 +2,8 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
reactStrictMode: true,
+ // PGlite loads its WebAssembly via import.meta.url; bundling breaks that, so Node loads it directly.
+ serverExternalPackages: ["@electric-sql/pglite"],
};
export default nextConfig;
diff --git a/project_structure.md b/project_structure.md
index 98db981..add54e1 100644
--- a/project_structure.md
+++ b/project_structure.md
@@ -83,7 +83,7 @@ components/
├─ fund/ # TokenPicker, AmountInput, DepositPanel, FundStatus
├─ plan/ # PlanForm (address typed twice, chain name), CostPreview, PauseButton
├─ history/ # BuyTable, SkipReason, TxLinks
-├─ vault/ # BalanceCard, NextBuy, WhereIsMyMoney, WithdrawForm
+├─ vault/ # StackColumn, BalanceCard, NextBuy, WhereIsMyMoney, WithdrawForm (+ RecoverTokenForm), CreateVault, DemoBanner
└─ wallet/ # WalletProvider, SignInButton, OwnerTx (builds set_plan/resume/withdraw txs)
```
@@ -107,7 +107,7 @@ worker/index.ts (entry, intervals, shutdown) · runner.ts (no-overlap loops) ·
## 7. `e2e/`, `scripts/`
```
-e2e/demo-journey.spec.ts # PRD §8
+e2e/playwright.config.ts · e2e/demo-journey.spec.ts # PRD §8 on demo mode, desktop + phone (`pnpm e2e`, CI job)
scripts/build-contracts.sh · scripts/seed-demo.ts · scripts/check-env.ts
```
diff --git a/scripts/seed-demo.ts b/scripts/seed-demo.ts
index 4740478..d239be3 100644
--- a/scripts/seed-demo.ts
+++ b/scripts/seed-demo.ts
@@ -1,7 +1,12 @@
/**
- * Runs lib/db/seed-demo.ts against PGlite before `pnpm demo` starts the app.
+ * Prepares the local PGlite database for `pnpm demo` (migrations only). Each visitor gets their own demo
+ * data when they press "Open the demo", so nothing is shared between visitors.
* Roadmap: K7.3
- * Status: scaffold — not implemented yet.
*/
-export {};
+import { createDb } from "../lib/db/client";
+
+const db = createDb({ databaseUrl: process.env.DATABASE_URL || undefined });
+await db.migrate();
+console.log("demo: database ready — open http://localhost:3000/demo");
+process.exit(0);
diff --git a/worker/scheduleBuys.ts b/worker/scheduleBuys.ts
index b5a7373..122d06e 100644
--- a/worker/scheduleBuys.ts
+++ b/worker/scheduleBuys.ts
@@ -5,7 +5,7 @@
*/
import { randomUUID } from "node:crypto";
-import { checkCost } from "../lib/core/cost";
+import { checkCost, costSkipNote } from "../lib/core/cost";
import { minUnits } from "../lib/core/money";
import { quoteMatchesPlan } from "../lib/core/planMatch";
import type { BaseUnits, QuoteSummary, VaultState } from "../lib/core/types";
@@ -77,7 +77,7 @@ async function runForUser(deps: WorkerDeps, user: User): Promise {
const cost = checkCost(quote, state.maxCostBps);
if (!cost.ok) {
- const note = cost.reason === "unknown_cost" ? "quote had no USD values" : `cost ${cost.costBps} bps above limit ${state.maxCostBps}`;
+ const note = costSkipNote(cost.costBps, state.maxCostBps);
await record("skipped_cost", note, quote, cost.costBps);
deps.log.info("buy skipped for cost", { userId: user.id, costBps: cost.costBps });
return "skipped_cost";
diff --git a/worker/worker.test.ts b/worker/worker.test.ts
index 8bd434f..9300167 100644
--- a/worker/worker.test.ts
+++ b/worker/worker.test.ts
@@ -137,7 +137,7 @@ describe("scheduleBuys (K5.3)", () => {
expect((await scheduleBuys(deps())).get(userId)).toBe("skipped_cost");
expect(fakes.executeBuy).not.toHaveBeenCalled();
const [b] = await listBuysByUser(db, userId);
- expect(b).toMatchObject({ status: "skipped_cost", costBps: 1540, note: "cost 1540 bps above limit 300" });
+ expect(b).toMatchObject({ status: "skipped_cost", costBps: 1540, note: "Fees were 15.40%, above your 3.00% limit" });
});
it("refuses and alerts when the quote doesn't match the on-chain plan", async () => {