Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,30 @@ jobs:
env:
NEXT_TELEMETRY_DISABLED: "1"

e2e:
name: E2E (demo journey, desktop + phone)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm e2e
env:
NEXT_TELEMETRY_DISABLED: "1"
- uses: actions/upload-artifact@v4
if: failure()
with:
name: playwright-report
path: |
playwright-report
test-results
retention-days: 7

contracts:
name: Contracts (cargo check + test)
runs-on: ubuntu-latest
Expand Down
12 changes: 11 additions & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,17 @@ On-chain vault = truth for plan and balance. DB = history and metadata.
---

## 8. Demo and dry-run
`pnpm demo`: PGlite + seed (vault with plan, deposits, 3 weeks of buys including `skipped_cost`), `DemoVaultClient` + demo quote/status providers behind `lib/core/adapters.ts`; "fast-forward 30 days"; real dry quotes when online, recorded fixtures offline. No secrets, no funds.
`pnpm demo` = migrate the local PGlite DB, then `next dev`. Zero secrets, no external DB (verified from a fresh clone, K7.5).

- **Per-visitor demo:** `/demo` → `POST /api/demo/start` creates a fresh `isDemo` user (`saver-<id>.demo`, vault `v<id>.vaults.demo`) with a weekly $100 BTC plan, two credited deposits ($1,296.70) and four weeks of buys including one `skipped_cost`, then signs the visitor in with a demo session. Visitors never share data.
- **Same routes, demo adapters:** `servicesFor(session)` (lib/server/adapters.ts) swaps in `demoQuotes`, `demoStatus` (lib/oneclick/demo.ts) and `demoVaultClient` (lib/near/demo.ts) on the same DB. A session whose demo flag doesn't match the user is rejected.
- **Quotes:** dry quotes try live 1Click first (stand-in refund account `near`; dry quotes move nothing) and fall back to a fee model calibrated on real quotes ($10 BTC ≈ 15%, $100 ≈ 1.75%). Non-dry demo quotes get a `demo-<ms>-<rand>` deposit address whose status advances on its own (~20 s per step → `SUCCESS`).
- **Vault:** plan in `demo_vaults.state` (migration 0002); balance derived from the user's rows (credited deposits − sent/success buys − withdrawn). Owner transactions from the UI go to `POST /api/demo/owner-tx` and follow the contract's rules (1-yocto rules aside): `set_plan` ranges, `resume` needs a plan, `withdraw` ≤ balance, `recover_token` refused.
- **Controls:** `fast-forward` (next 30 days of the plan, same cost check, one fee spike → skip) and `reset`.
- **Isolation:** real worker queries exclude demo users (`listUsersWithVault`, `listActiveFunding`, `listInFlightBuys`); demo tx hashes start with `demo-` and the UI shows "Example only" instead of explorer links.
- **Token list:** `GET /api/tokens` falls back to a small built-in list (`offline: true`) when 1Click is unreachable.

Two production bugs found by this phase's browser run (both fixed): PGlite must be a Next `serverExternalPackages` entry (bundling breaks its WebAssembly path); the dev session secret lives on `globalThis` because each Next route is its own bundle.

---

Expand Down
7 changes: 6 additions & 1 deletion ARCHITECTURE_ESSENTIALS.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,12 @@ On-chain vault = truth for plan + balance.
- Every skip/refusal/failure writes `buys.note`; refusals and failures `log.alert`

## Demo & dry-run
`pnpm demo` = zero secrets, PGlite, seeded vault + history, fast-forward 30 days with one `skipped_cost`. Never moves funds.
`pnpm demo` = zero secrets, PGlite (verified from a fresh clone). `/demo` → per-visitor demo saver + demo session; Never moves funds.
- Demo sessions use `servicesFor(session)` → demo quotes (live dry first, calibrated model fallback), demo status (time-based), demo vault (`demo_vaults` + balance from rows)
- Owner actions in demo → `POST /api/demo/owner-tx`, same rules as the contract; `fast-forward` 30 days, `reset`
- Real worker queries **exclude demo users**; `demo-` hashes never link to explorers
- `pnpm e2e` = Playwright PRD §8 journey on demo mode, desktop + phone, in CI
- Keep `@electric-sql/pglite` in `serverExternalPackages`; keep the dev session secret on `globalThis`

## Never
Add an admin withdraw path · use an unverified quote · show unconfirmed statuses · commit secrets · deploy, sign with real keys, send funds, post, push or submit without the human's explicit OK · finish a contribution without updating `ROADMAP.md`
Expand Down
17 changes: 9 additions & 8 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@
| 4. API routes | Nov 8–9 | 100% | ✅ done |
| 5. Worker (scheduler) | Nov 9–10 | 100% | ✅ done |
| 6. UI | Nov 9–11 | 100% | ✅ done |
| 7. Demo mode & dry-run | Nov 11 | 0% | not started |
| 7. Demo mode & dry-run | Nov 11 | 100% | ✅ done |
| 8. Hardening & edge cases | Nov 11–12 | 0% | not started |
| 9. Deploy & real run | Nov 12 | 0% | not started |
| 10. README & public repo | Nov 12–13 | 14% | in progress |
| 11. Launch: video, post, submission | Nov 13–14 | 0% | not started |
| 12. After submission | Nov 14–25 | 0% | not started |
| **Overall (MVP)** | | **~55%** | |
| **Overall (MVP)** | | **~62%** | |

Phase % = done tasks ÷ non-dropped tasks in that phase. Overall = average of all 14 rows (D + phases 0–12). (Earlier entries over-estimated the overall %; recalculated 2026-11-04.)

Expand Down Expand Up @@ -148,12 +148,12 @@ Format: `- [task id] what blocks it · who can unblock · since date`

## Phase 7 — Demo mode & dry-run (Nov 11)

- [ ] **K7.1** [#63](https://github.com/MFrancis-dev/stack/issues/63) Demo adapters (`DemoVaultClient`, demo quote/status)
- [ ] **K7.2** [#64](https://github.com/MFrancis-dev/stack/issues/64) `seed-demo.ts`: vault with plan, deposits, 3 weeks of buys incl. `skipped_cost`
- [ ] **K7.3** [#65](https://github.com/MFrancis-dev/stack/issues/65) `pnpm demo`: PGlite + seed + banner; real dry quotes online, fixtures offline
- [ ] **K7.4** [#66](https://github.com/MFrancis-dev/stack/issues/66) "Fast-forward 30 days"
- [ ] **K7.5** [#67](https://github.com/MFrancis-dev/stack/issues/67) Fresh-clone check with no `.env`
- [ ] **K7.6** [#68](https://github.com/MFrancis-dev/stack/issues/68) Playwright journey = PRD §8, in CI
- [x] **K7.1** [#63](https://github.com/MFrancis-dev/stack/issues/63) Demo adapters (`DemoVaultClient`, demo quote/status) · 2026-11-05: demo quotes (live dry first, calibrated model fallback), time-based demo status, demo vault client (`demo_vaults`, balance from rows), owner actions without a wallet; routes pick adapters by session
- [x] **K7.2** [#64](https://github.com/MFrancis-dev/stack/issues/64) `seed-demo.ts`: vault with plan, deposits, 3 weeks of buys incl. `skipped_cost` · 2026-11-05: per-visitor demo saver: weekly $100 BTC plan, 2 deposits, 4 weeks of buys incl. a fee-spike skip
- [x] **K7.3** [#65](https://github.com/MFrancis-dev/stack/issues/65) `pnpm demo`: PGlite + seed + banner; real dry quotes online, fixtures offline · 2026-11-05: `pnpm demo` + `/demo` entry + banner; token list falls back offline; browser-reviewed at 1280/390 px
- [x] **K7.4** [#66](https://github.com/MFrancis-dev/stack/issues/66) "Fast-forward 30 days" · 2026-11-05: fast-forward 30 days (same cost check, one skip) + start over
- [x] **K7.5** [#67](https://github.com/MFrancis-dev/stack/issues/67) Fresh-clone check with no `.env` · 2026-11-05: fresh `git clone` → `pnpm install` → `pnpm demo` with no `.env`: demo page 200, start 201, vault/fast-forward/CSV all OK
- [x] **K7.6** [#68](https://github.com/MFrancis-dev/stack/issues/68) Playwright journey = PRD §8, in CI · 2026-11-05: Playwright PRD §8 journey on desktop + phone (4 passing), CI job with trace upload on failure

## Phase 8 — Hardening & edge cases (Nov 11–12)

Expand Down Expand Up @@ -216,6 +216,7 @@ Format: `- [task id] what blocks it · who can unblock · since date`
## Update log
One line per contribution, newest first: `YYYY-MM-DD · who/agent · what changed · tasks`

- 2026-11-05 · agent · Phase 7 demo mode: per-visitor demo, demo adapters, owner actions without a wallet, fast-forward/reset, worker isolation, offline token fallback, Playwright journey in CI; fixed PGlite bundling + per-route dev session secret found in the browser; 119 unit/route tests + 4 e2e · K7.1–K7.6
- 2026-11-05 · agent · Phase 6 UI reviewed in the browser (desktop + phone, redirect and signed-out states, no server errors); sign-in button width fix · K6.1–K6.8
- 2026-11-04 · agent · Phase 6 UI built on branch feat/ui (landing, sign-in, vault creation, fund, plan + cost preview, pause/resume, overview stack, history, settings); visual review pending · K6.1–K6.8
- 2026-11-04 · agent · Phase 5 worker: pollFunding, scheduleBuys (full safety chain, backoff, insert-before-execute), pollBuys, expireQuotes, keeper gas alert, no-overlap runner; `buys.note` migration; 100 TS tests · K5.1–K5.5
Expand Down
2 changes: 2 additions & 0 deletions app/(dashboard)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Button } from "@/components/ui/Button";
import { Notice } from "@/components/ui/Notice";
import { PauseButton } from "@/components/plan/PauseButton";
import { CreateVault } from "@/components/vault/CreateVault";
import { DemoBanner } from "@/components/vault/DemoBanner";
import { SignInButton } from "@/components/wallet/SignInButton";
import { useWallet } from "@/components/wallet/WalletProvider";
import { useVault } from "@/lib/client/hooks";
Expand Down Expand Up @@ -58,6 +59,7 @@ export default function DashboardLayout({ children }: { children: ReactNode }) {
) : null}
</div>
</header>
{v?.signedIn && v.demo ? <DemoBanner /> : null}
<nav aria-label="Sections" className="-mx-5 overflow-x-auto px-5 sm:mx-0 sm:px-0">
<ul className="flex gap-1 border-b border-mist">
{NAV.map((n) => {
Expand Down
77 changes: 70 additions & 7 deletions app/api/demo/[action]/route.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,74 @@
import { NextResponse } from "next/server";

/**
* POST /api/demo/:action — fast-forward, reset (demo sessions only).
* Roadmap: K7.4 · Spec: ARCHITECTURE.md §4.1
* Status: scaffold — not implemented yet.
* Demo mode (K7.x). `start` creates a fresh demo saver and signs the visitor in as them; the rest need a
* demo session: `reset`, `fast-forward` (30 days), `owner-tx` (apply a vault transaction without a wallet).
* Nothing here touches real services or funds. Roadmap: K7.1–K7.4
*/

export async function POST() {
return NextResponse.json({ error: "Not implemented (K7.4)" }, { status: 501 });
import { z } from "zod";
import { getUserById } from "@/lib/db/queries/users";
import { fastForward, resetDemoUser, seedDemoUser } from "@/lib/db/seed-demo";
import { applyOwnerTx, DemoRuleError } from "@/lib/near/demo";
import { getServices } from "@/lib/server/adapters";
import { clientIp, handle, HttpError, json, parseBody } from "@/lib/server/http";
import { rateLimit } from "@/lib/server/rateLimit";
import { requireSession, sessionCookie } from "@/lib/server/session";

const ownerTxInput = z.object({
tx: z.object({
receiverId: z.string().min(1),
actions: z
.array(
z.object({
type: z.literal("FunctionCall"),
params: z.object({ methodName: z.string(), args: z.record(z.unknown()), gas: z.string(), deposit: z.string() }),
}),
)
.min(1)
.max(4),
}),
});

async function demoUser(req: Request) {
const session = requireSession(req);
if (!session.demo) throw new HttpError(403, "Only available in demo mode");
const { db } = await getServices();
const user = await getUserById(db, session.userId);
if (!user?.isDemo) throw new HttpError(401, "Demo expired, start it again");
return { db, user };
}

export const POST = handle(async (req: Request, ctx: { params: Promise<{ action: string }> }) => {
const { action } = await ctx.params;
try {
switch (action) {
case "start": {
rateLimit(`demo-start:${clientIp(req)}`, 10, 60_000);
const { db } = await getServices();
const user = await seedDemoUser(db);
return json(
{ accountId: user.nearAccountId, vaultAccountId: user.vaultAccountId },
{ status: 201, headers: { "set-cookie": sessionCookie({ userId: user.id, accountId: user.nearAccountId, demo: true }) } },
);
}
case "reset": {
const { db, user } = await demoUser(req);
await resetDemoUser(db, user);
return json({ ok: true });
}
case "fast-forward": {
const { db, user } = await demoUser(req);
return json(await fastForward(db, user, 30));
}
case "owner-tx": {
const { db, user } = await demoUser(req);
const { tx } = await parseBody(req, ownerTxInput);
return json({ state: await applyOwnerTx(db, user.vaultAccountId!, tx) });
}
default:
throw new HttpError(404, "Unknown demo action");
}
} catch (e) {
if (e instanceof DemoRuleError) throw new HttpError(409, e.message);
throw e;
}
});
12 changes: 9 additions & 3 deletions app/api/tokens/route.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
/**
* GET /api/tokens — cached 1Click token list (what users can fund from).
* GET /api/tokens — cached 1Click token list (what users can fund from). Falls back to a small built-in
* list (flagged `offline`) when 1Click can't be reached, so the page still works.
* Roadmap: K4.3 · Spec: ARCHITECTURE.md §4.1
*/

import { FALLBACK_TOKENS } from "@/lib/oneclick/demo";
import { getServices } from "@/lib/server/adapters";
import { handle, json } from "@/lib/server/http";

export const GET = handle(async () => {
const tokens = await (await getServices()).listTokens();
return json({ tokens }, { headers: { "cache-control": "public, max-age=300" } });
try {
const tokens = await (await getServices()).listTokens();
return json({ tokens, offline: false }, { headers: { "cache-control": "public, max-age=300" } });
} catch {
return json({ tokens: FALLBACK_TOKENS, offline: true }, { headers: { "cache-control": "no-store" } });
}
});
5 changes: 3 additions & 2 deletions app/api/vault/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ import { requireUser } from "@/lib/server/context";
import { handle, json } from "@/lib/server/http";

export const GET = handle(async (req: Request) => {
const { services, user } = await requireUser(req);
if (!user.vaultAccountId) return json({ accountId: user.nearAccountId, vaultAccountId: null });
const { services, user, session } = await requireUser(req);
if (!user.vaultAccountId) return json({ accountId: user.nearAccountId, vaultAccountId: null, demo: session.demo });
const vaults = requireVaultClient(services);
const [state, balance] = await Promise.all([vaults.getState(user.vaultAccountId), vaults.usdcBalance(user.vaultAccountId)]);
return json({
accountId: user.nearAccountId,
vaultAccountId: user.vaultAccountId,
demo: session.demo,
state,
usdcBalance: balance,
usdcBalanceFormatted: formatAmount(balance, USDC_DECIMALS),
Expand Down
49 changes: 42 additions & 7 deletions app/demo/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,49 @@
"use client";

/**
* Starts a demo session; fast-forward 30 days.
* Roadmap: K7.3
* Status: scaffold — not implemented yet.
* Demo entry: explains what you'll see and starts a private demo session (fresh example data,
* no wallet, no money). Roadmap: K7.3
*/

export default function Page() {
import { useMutation } from "@tanstack/react-query";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/Button";
import { Notice } from "@/components/ui/Notice";
import { api } from "@/lib/client/api";

export default function DemoPage() {
const router = useRouter();
const start = useMutation({
mutationFn: () => api("/api/demo/start", { method: "POST" }),
onSuccess: () => router.push("/dashboard"),
});
return (
<main className="mx-auto max-w-3xl p-6">
<h1 className="text-2xl font-semibold">Demo mode</h1>
<p className="text-sm text-neutral-500">Not built yet (K7.3).</p>
<main className="mx-auto max-w-2xl px-5 py-16 sm:px-8">
<Link href="/" className="font-display text-2xl font-extrabold tracking-tight">
Stack
</Link>
<h1 className="mt-12 text-[clamp(2.2rem,6vw,3.6rem)] font-extrabold">See Stack with example data</h1>
<p className="mt-5 text-lg text-sage">
You get your own example saver: $1,300 deposited from two chains, a plan to buy $100 of Bitcoin every week, and
four weeks of history, including one week that was skipped because fees were too high.
</p>
<ul className="mt-6 grid gap-2 text-lg">
<li>Change the plan and watch the fee estimate. Prices are live when we can reach NEAR Intents.</li>
<li>Add funds to see a deposit go from waiting to done in about a minute.</li>
<li>Fast-forward 30 days to see the plan keep buying on its own.</li>
</ul>
<div className="mt-10 grid justify-items-start gap-3">
<Button onClick={() => start.mutate()} disabled={start.isPending}>
{start.isPending ? "Setting up your demo…" : "Open the demo"}
</Button>
<p className="text-sm text-sage">No wallet and no money involved. Your example data is private to this browser.</p>
</div>
{start.isError ? (
<div className="mt-6">
<Notice tone="error">{start.error.message}</Notice>
</div>
) : null}
</main>
);
}
3 changes: 3 additions & 0 deletions components/fund/DepositPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ export function DepositPanel({
</p>
</div>
</div>
{depositAddress.startsWith("demo-") ? (
<Notice tone="error">This is a demo address. Don&apos;t send anything to it. The deposit will complete on its own in about a minute.</Notice>
) : null}
<Notice tone="warn">
Sending from an exchange? Exchanges take a withdrawal fee, so add it on top. If less than {amountLabel} arrives,
the deposit is marked short and may be refunded to your refund address.
Expand Down
7 changes: 6 additions & 1 deletion components/history/BuyTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import { formatTarget, formatUsdc } from "@/lib/client/format";
import { SkipReason } from "./SkipReason";
import { TxLinks } from "./TxLinks";

/** Statuses where dollars actually left the vault. Skipped, failed and refunded buys spent nothing. */
const SPENT = new Set(["success", "sent", "processing"]);

export function BuyTable({ buys }: { buys: BuyDto[] }) {
if (buys.length === 0) return <p className="text-sage">No buys yet. Once your plan is running, every buy shows up here, including skipped ones.</p>;
return (
Expand All @@ -27,7 +30,9 @@ export function BuyTable({ buys }: { buys: BuyDto[] }) {
{buys.map((b) => (
<tr key={b.id} className="grid grid-cols-2 gap-x-4 gap-y-1 border-b border-mist py-4 sm:table-row sm:py-0">
<td className="sm:py-3 sm:pr-4">{new Date(b.createdAt).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" })}</td>
<td className="text-right sm:py-3 sm:pr-4 sm:text-left">${formatUsdc(b.amountIn)}</td>
<td className="text-right sm:py-3 sm:pr-4 sm:text-left">
{SPENT.has(b.status) ? `$${formatUsdc(b.amountIn)}` : <span className="text-sage">Nothing spent</span>}
</td>
<td className="sm:py-3 sm:pr-4">{b.status === "success" || b.status === "sent" || b.status === "processing" ? formatTarget(b.amountOut, b.targetAsset) : "—"}</td>
<td className="text-right sm:py-3 sm:pr-4 sm:text-left">{b.costBps === null ? "—" : `${(b.costBps / 100).toFixed(2)}%`}</td>
<td className="col-span-2 sm:py-3 sm:pr-4">
Expand Down
4 changes: 3 additions & 1 deletion components/history/SkipReason.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ export function SkipReason({ status, note }: { status: BuyStatus; note: string |
return (
<span className="grid">
<span className={`font-bold ${bad ? "text-rust" : ""}`}>{WORDS[status]}</span>
{note && status !== "success" ? <span className="text-sm text-sage">{note}</span> : null}
{note && status !== "success" ? (
<span className="text-sm text-sage">{status === "skipped_cost" || status === "no_quote" ? `${note}. Nothing was spent.` : note}</span>
) : null}
</span>
);
}
Loading
Loading