Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(wallet): re-point every on-screen copy of the deposit request at once

nirholasbad0e8d230fe
diff --git a/scripts/shoot-wallet-deposit.mjs b/scripts/shoot-wallet-deposit.mjs
new file mode 100644
index 000000000..0307198e3
--- /dev/null
+++ b/scripts/shoot-wallet-deposit.mjs
@@ -0,0 +1,294 @@
+#!/usr/bin/env node
+/**
+ * Capture the /wallet surfaces for the tutorial, and fail on any console error.
+ *
+ * Why this hosts its own server instead of using `npm run dev`: several agents
+ * share this worktree, every write to vite.config.js restarts the dev server,
+ * and a capture that races those restarts fails for reasons that have nothing
+ * to do with the page. This bundles the real modules with esbuild (the same
+ * bundler the production build runs through), serves the real page and the real
+ * stylesheet, and answers the two API routes the page calls. Nothing about the
+ * rendering is faked: the QR comes from the real `qrcode` encoder over a real
+ * Solana Pay URI, and the layout is the shipped CSS.
+ *
+ * The signed-out shot is the genuine anon state, reached the genuine way: the
+ * page calls /api/user/wallet, gets a 401, and renders it.
+ *
+ * node scripts/shoot-wallet-deposit.mjs [--out public/docs/img] [--keep]
+ */
+
+import { chromium } from 'playwright';
+import { build } from 'esbuild';
+import { createServer } from 'node:http';
+import { readFile, mkdir } from 'node:fs/promises';
+import { resolve, extname, join } from 'node:path';
+
+const ROOT = process.cwd();
+const args = process.argv.slice(2);
+const flag = (name, fallback) => {
+ const i = args.indexOf(`--${name}`);
+ return i >= 0 && args[i + 1] ? args[i + 1] : fallback;
+};
+const OUT = resolve(ROOT, flag('out', 'public/docs/img'));
+
+const VIEWPORTS = [
+ { name: 'mobile', width: 390, height: 880 },
+ { name: 'desktop', width: 1280, height: 900 },
+];
+
+// A plausible mid-use wallet. Only these figures are supplied; the encoding,
+// the layout and the QR are all produced by the shipped code.
+const BALANCES = { sol: 0.482, sol_usdc: 124.5, evm_usdc: 40, total_usd: 233.1 };
+const SOL_ADDR = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const EVM_ADDR = '0x2f1b7d5c9a4e6b8f0c3d5e7a9b1c3d5e7f9a1b3c';
+
+/**
+ * Root-level scripts the production build emits from src/. The page loads them
+ * by their built names, so the harness bundles the same sources to the same
+ * paths; otherwise the nav renders half-dressed in every screenshot.
+ */
+const BUILT_ENTRIES = {
+ '/src/master-wallet.js': 'src/master-wallet.js',
+ '/src/wallet-deposit.js': 'src/wallet-deposit.js',
+ '/i18n.js': 'src/i18n.js',
+ '/nav-tier-badge.js': 'src/nav-tier-badge.js',
+ '/walk-companion.js': 'src/walk-companion.js',
+};
+
+/**
+ * Paths this harness legitimately does not serve: the locale bundles come from
+ * build:pages and the favicon set is generated. A 404 on anything NOT in this
+ * list means the page references something that genuinely does not exist.
+ */
+const HARNESS_GAPS = [/^\/locales\//, /^\/favicon/, /^\/apple-touch-icon/];
+
+const MIME = {
+ '.html': 'text/html; charset=utf-8',
+ '.js': 'text/javascript; charset=utf-8',
+ '.mjs': 'text/javascript; charset=utf-8',
+ '.css': 'text/css; charset=utf-8',
+ '.json': 'application/json; charset=utf-8',
+ '.svg': 'image/svg+xml',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.webp': 'image/webp',
+ '.woff2': 'font/woff2',
+ '.woff': 'font/woff',
+};
+
+/** Bundle a browser module exactly as the production build would. */
+async function bundle(entry) {
+ const out = await build({
+ entryPoints: [resolve(ROOT, entry)],
+ bundle: true,
+ format: 'esm',
+ platform: 'browser',
+ write: false,
+ logLevel: 'silent',
+ });
+ return out.outputFiles[0].text;
+}
+
+async function startServer(modules) {
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+ const path = url.pathname;
+
+ const send = (status, body, type) => {
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' });
+ res.end(body);
+ };
+
+ if (modules[path]) return send(200, modules[path], MIME['.js']);
+ if (path === '/wallet' || path === '/wallet/' || path === '/') {
+ return send(200, await readFile(resolve(ROOT, 'pages/wallet.html')), MIME['.html']);
+ }
+ // 401 across the board is exactly what a signed-out visitor gets from the
+ // real API, and rendering that state correctly is one of the things being
+ // captured. The nav, the notification bell and the wallet page all read
+ // their own route and all have to handle it.
+ if (path.startsWith('/api/')) {
+ return send(401, JSON.stringify({ error: 'unauthorized' }), MIME['.json']);
+ }
+
+ try {
+ const file = join(resolve(ROOT, 'public'), path);
+ return send(200, await readFile(file), MIME[extname(path)] || 'application/octet-stream');
+ } catch {
+ return send(404, 'not found', 'text/plain');
+ }
+ });
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
+ return { server, base: `http://127.0.0.1:${server.address().port}` };
+}
+
+async function main() {
+ await mkdir(OUT, { recursive: true });
+
+ const modules = {};
+ for (const [route, entry] of Object.entries(BUILT_ENTRIES)) {
+ modules[route] = await bundle(entry);
+ }
+ const { server, base } = await startServer(modules);
+
+ const browser = await chromium.launch();
+ const problems = [];
+ const shots = [];
+
+ for (const vp of VIEWPORTS) {
+ const ctx = await browser.newContext({
+ viewport: { width: vp.width, height: vp.height },
+ deviceScaleFactor: 2,
+ colorScheme: 'dark',
+ });
+ const page = await ctx.newPage();
+ // A bare "failed to load resource" says nothing about which one, so the
+ // request itself is inspected. This harness only serves public/ plus two
+ // routes, so a locale bundle or a font missing here is the harness, not
+ // the page; anything else is a real break and is reported.
+ page.on('requestfailed', (r) => problems.push(`[${vp.name}] request failed: ${r.url()}`));
+ page.on('response', (r) => {
+ if (r.status() < 400 || r.status() === 401) return;
+ const path = new URL(r.url()).pathname;
+ if (HARNESS_GAPS.some((re) => re.test(path))) return;
+ problems.push(`[${vp.name}] ${r.status()} on ${path}`);
+ });
+ page.on('console', (m) => {
+ // The generic resource-error text is redundant with the response
+ // listener above, which knows the URL.
+ if (m.type() === 'error' && !/Failed to load resource/.test(m.text())) {
+ problems.push(`[${vp.name}] console: ${m.text()}`);
+ }
+ });
+ page.on('pageerror', (e) => problems.push(`[${vp.name}] pageerror: ${e.message}`));
+
+ await page.goto(`${base}/wallet`, { waitUntil: 'load' });
+
+ await page.waitForSelector('.wlt-hero-title', { timeout: 15000 });
+ const anon = `wallet-signed-out-${vp.name}.png`;
+ await page.screenshot({ path: resolve(OUT, anon) });
+ shots.push(anon);
+
+ // Drive the real sheet. Only the balance reader is supplied.
+ await page.evaluate(
+ async ({ balances, solAddr, evmAddr }) => {
+ const mod = await import('/src/wallet-deposit.js');
+ mod.openDepositSheet({
+ solanaAddress: solAddr,
+ evmAddress: evmAddr,
+ balances,
+ readBalances: async () => balances,
+ });
+ },
+ { balances: BALANCES, solAddr: SOL_ADDR, evmAddr: EVM_ADDR },
+ );
+
+ await page.waitForSelector('.wlt-qr canvas', { timeout: 20000 });
+ await page.waitForTimeout(500); // let the entry animation settle
+ const sheet = `wallet-deposit-${vp.name}.png`;
+ await page.screenshot({ path: resolve(OUT, sheet) });
+ shots.push(sheet);
+
+ // Typing an amount must re-encode the request, or the "pre-filled" claim
+ // in the tutorial is false.
+ await page.fill('#wlt-dep-amount', '25');
+ await page.waitForTimeout(700);
+ const uri = await page.getAttribute('[data-dep="open"]', 'href');
+ if (!uri?.includes('amount=25')) {
+ problems.push(`[${vp.name}] amount never reached the payment URI: ${uri}`);
+ }
+
+ // USDC has to pin the mint, or the request silently asks for native SOL.
+ await page.click('[data-asset="usdc"]');
+ await page.waitForSelector('.wlt-qr canvas', { timeout: 20000 });
+ await page.waitForTimeout(400);
+ const usdcUri = await page.getAttribute('[data-dep="open"]', 'href');
+ if (!usdcUri?.includes('spl-token=')) {
+ problems.push(`[${vp.name}] USDC request lost its mint: ${usdcUri}`);
+ }
+ if (vp.name === 'desktop') {
+ const usdc = 'wallet-deposit-usdc-desktop.png';
+ await page.screenshot({ path: resolve(OUT, usdc) });
+ shots.push(usdc);
+ }
+
+ // Base must target the EVM address. Encoding it against the Solana one
+ // would send real funds nowhere recoverable.
+ await page.click('[data-asset="base"]');
+ await page.waitForTimeout(500);
+ const baseUri = await page.getAttribute('[data-dep="open"]', 'href');
+ if (!baseUri?.startsWith('ethereum:') || baseUri.includes(SOL_ADDR)) {
+ problems.push(`[${vp.name}] Base request was misrouted: ${baseUri}`);
+ }
+
+ // The arrival view is a real state of the real component, reached by
+ // letting the watcher observe a balance that grew.
+ await page.click('[data-asset="sol"]');
+ await page.waitForTimeout(300);
+ await page.evaluate(
+ ({ balances }) => {
+ // The page-level watcher polls this; returning more than the
+ // baseline is exactly what an inbound deposit looks like to it.
+ window.__deposited = { ...balances, sol: balances.sol + 0.25 };
+ },
+ { balances: BALANCES },
+ );
+ await ctx.close();
+ }
+
+ // The arrival state deserves its own pass with a reader that grows, rather
+ // than being bolted onto the tail of the one above.
+ {
+ const ctx = await browser.newContext({
+ viewport: { width: 1280, height: 900 },
+ deviceScaleFactor: 2,
+ colorScheme: 'dark',
+ });
+ const page = await ctx.newPage();
+ page.on('pageerror', (e) => problems.push(`[arrival] pageerror: ${e.message}`));
+ await page.goto(`${base}/wallet`, { waitUntil: 'load' });
+ await page.waitForSelector('.wlt-hero-title', { timeout: 15000 });
+ await page.evaluate(
+ async ({ balances, solAddr, evmAddr }) => {
+ const mod = await import('/src/wallet-deposit.js');
+ let reads = 0;
+ mod.openDepositSheet({
+ solanaAddress: solAddr,
+ evmAddress: evmAddr,
+ balances,
+ // First read matches the baseline; the second is 0.25 SOL richer,
+ // which is precisely what an arriving deposit looks like.
+ readBalances: async () =>
+ ++reads < 2 ? balances : { ...balances, sol: balances.sol + 0.25 },
+ });
+ },
+ { balances: BALANCES, solAddr: SOL_ADDR, evmAddr: EVM_ADDR },
+ );
+ await page.waitForSelector('.wlt-sheet-done-title', { timeout: 30000 });
+ const text = await page.textContent('.wlt-sheet-done-title');
+ if (!text?.includes('0.25')) {
+ problems.push(`[arrival] wrong delta reported: ${text?.trim()}`);
+ }
+ await page.waitForTimeout(600);
+ const arrived = 'wallet-deposit-arrived.png';
+ await page.screenshot({ path: resolve(OUT, arrived) });
+ shots.push(arrived);
+ await ctx.close();
+ }
+
+ await browser.close();
+ server.close();
+
+ for (const s of shots) console.log(`wrote ${join(OUT, s)}`);
+ if (problems.length) {
+ console.error(`\n${problems.length} problem(s):`);
+ for (const p of problems) console.error(` ${p}`);
+ process.exit(1);
+ }
+ console.log('\nno console errors; every payment URI encoded correctly; arrival delta exact.');
+}
+
+main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
diff --git a/src/wallet-deposit.js b/src/wallet-deposit.js
index 841f9581c..aba538faf 100644
--- a/src/wallet-deposit.js
+++ b/src/wallet-deposit.js
@@ -350,6 +350,25 @@ export function openDepositSheet({ solanaAddress, evmAddress, balances, readBala
if (view.phase === 'request') drawQr();
}
+ /**
+ * Re-point every representation of the request at once.
+ *
+ * The QR is not the only copy of the URI on screen: "Open in wallet" is a
+ * deep link and "Copy payment link" is a clipboard payload, and all three
+ * must agree. Redrawing only the code left the link carrying the amount the
+ * user had typed BEFORE their last edit, which is exactly the kind of
+ * mismatch that sends the wrong number to a stranger's wallet.
+ */
+ function refreshRequest() {
+ const uri = currentUri();
+ if (!uri) return;
+ const open = dlg.querySelector('[data-dep="open"]');
+ if (open) open.setAttribute('href', uri);
+ const copyUri = dlg.querySelector('[data-dep="copy-uri"]');
+ if (copyUri) copyUri.dataset.copy = uri;
+ drawQr();
+ }
+
/**
* Render the QR from the `qrcode` package, loaded on demand so the wallet
* page does not carry it for the majority of visits that never deposit.
@@ -450,7 +469,7 @@ export function openDepositSheet({ solanaAddress, evmAddress, balances, readBala
if (e.target?.dataset?.dep !== 'amount') return;
view.amount = e.target.value.trim();
clearTimeout(amountTimer);
- amountTimer = setTimeout(drawQr, 280);
+ amountTimer = setTimeout(refreshRequest, 280);
});
async function rebaselineThenWatch() {
diff --git a/tests/master-wallet-page.test.js b/tests/master-wallet-page.test.js
index b5473084d..bec71b6ce 100644
--- a/tests/master-wallet-page.test.js
+++ b/tests/master-wallet-page.test.js
@@ -258,3 +258,138 @@ describe('master wallet page is reachable', () => {
expect(read('STRUCTURE.md')).toContain('pages/wallet.html');
});
});
+
+describe('reviewing a top-up prices it on the server and signs nothing', () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('sends simulate:true and the agent_id body key', async () => {
+ const calls = stubFetch(() =>
+ jsonResponse({ simulation: { human_amount: 4, usd_value: 4, agent_wallet: 'AgentSol' } }),
+ );
+ const { previewFundAgent } = await loadClient();
+ const res = await previewFundAgent({ agentId: 'a-1', asset: 'USDC', amount: 'max' });
+
+ expect(res.ok).toBe(true);
+ const call = calls.find((c) => c.path.endsWith('/api/user/wallet/fund-agent'));
+ const body = JSON.parse(call.init.body);
+ expect(call.init.method).toBe('POST');
+ expect(body.simulate).toBe(true);
+ // snake_case: the handler reads body.agent_id, not agentId.
+ expect(body.agent_id).toBe('a-1');
+ expect(body).not.toHaveProperty('agentId');
+ expect(call.init.headers['x-csrf-token']).toBe(CSRF);
+ });
+
+ it('omits simulate entirely on the real top-up', async () => {
+ const calls = stubFetch(() => jsonResponse({ signature: 'sig' }));
+ const { fundAgent } = await loadClient();
+ await fundAgent({ agentId: 'a-1', asset: 'SOL', amount: '0.1' });
+
+ const body = JSON.parse(
+ calls.find((c) => c.path.endsWith('/api/user/wallet/fund-agent')).init.body,
+ );
+ // `simulate: false` would still be a truthy key some future handler could
+ // misread. The broadcast path carries no simulate key at all.
+ expect(body).not.toHaveProperty('simulate');
+ });
+
+ it('returns before the key is ever recovered on the simulate path', () => {
+ const src = read('api/user/wallet/fund-agent.js');
+ const simulateReturn = src.indexOf('if (simulate) {');
+ const keyRecovery = src.indexOf('recoverSolanaAgentKeypair(mw.encrypted_solana_secret');
+ expect(simulateReturn).toBeGreaterThan(-1);
+ expect(keyRecovery).toBeGreaterThan(-1);
+ // Ordering IS the guarantee: a preview that reached the decrypt call
+ // would be one refactor away from signing.
+ expect(simulateReturn).toBeLessThan(keyRecovery);
+ });
+
+ it('discloses the token-account rent a top-up silently pays', () => {
+ const src = read('api/user/wallet/fund-agent.js');
+ expect(src).toContain('creates_token_account');
+ expect(src).toContain('token_account_rent_sol');
+ // And the page has to actually show it, not just receive it.
+ expect(read('src/master-wallet.js')).toContain('wlt-confirm-flag');
+ });
+});
+
+describe('pricing a transfer does not consume the daily withdrawal budget', () => {
+ // withdrawalPerUser is 5 per user per DAY. Both spend routes used to charge
+ // it before checking `simulate`, so four price checks locked a user out of
+ // their own funds for 24 hours. A preview moves nothing and must not count.
+ it('routes simulate to the per-minute limiter on both spend routes', () => {
+ for (const path of ['api/user/wallet/send.js', 'api/user/wallet/fund-agent.js']) {
+ const src = read(path);
+ expect(src).toContain('limits.walletSimulate(session.id)');
+ expect(src).toContain('limits.withdrawalPerUser(session.id)');
+ // The body must be parsed BEFORE the limiter, or the branch cannot
+ // know which budget to draw on.
+ expect(src.indexOf('await readJson(req)')).toBeLessThan(
+ src.indexOf('limits.walletSimulate(session.id)'),
+ );
+ }
+ });
+
+ it('defines walletSimulate as a real per-minute limiter', () => {
+ const src = read('api/_lib/rate-limit.js');
+ expect(src).toMatch(/walletSimulate:[\s\S]{0,200}?wallet:simulate/);
+ expect(src).toMatch(/wallet:simulate['"],\s*\{\s*limit:\s*\d+,\s*window:\s*'1 m'/);
+ });
+
+ it('guards fund-agent by IP as well, matching send', () => {
+ // clientIp was imported here and unused, leaving this the only
+ // funds-moving wallet route without a per-IP ceiling.
+ expect(read('api/user/wallet/fund-agent.js')).toContain('limits.authIp(clientIp(req))');
+ });
+});
+
+describe('scan-to-fund is wired into the page', () => {
+ it('offers Add funds as the primary action and opens the sheet', () => {
+ const src = read('src/master-wallet.js');
+ expect(src).toContain("import { openDepositSheet } from './wallet-deposit.js'");
+ expect(src).toContain('data-act="deposit"');
+ expect(src).toContain('openDepositSheet(');
+ });
+
+ it('hands the sheet a balance reader rather than the whole client', () => {
+ // The watcher only needs balances; a narrow injection is what keeps
+ // wallet-deposit.js testable with no network at all.
+ expect(read('src/master-wallet.js')).toContain('async readBalances()');
+ });
+
+ it('opens the sheet straight after provisioning, since an empty wallet does nothing', () => {
+ const src = read('src/master-wallet.js');
+ const create = src.indexOf('async function onCreate()');
+ const next = src.indexOf('function ', create + 10);
+ expect(src.slice(create, next)).toContain('onDeposit()');
+ });
+
+ it('offers max on every amount field, not just send', () => {
+ const src = read('src/master-wallet.js');
+ expect(src).toContain("maxHint('wlt-amount')");
+ expect(src).toContain("maxHint('wlt-fund-amount')");
+ // The handler must target the field that asked, not a hardcoded one.
+ expect(src).toContain('root.querySelector(`#${el.dataset.target}`)');
+ });
+
+ it('ships the deposit sheet styles the module depends on', () => {
+ const css = read('public/master-wallet.css');
+ for (const cls of ['.wlt-sheet', '.wlt-qr', '.wlt-chip', '.wlt-watch-pulse', '.wlt-tip-body']) {
+ expect(css).toContain(cls);
+ }
+ // The QR stays light in both themes; a theme-inverted code fails scanners.
+ expect(css).toMatch(/\.wlt-qr\s*\{[^}]*background:\s*#fff/);
+ });
+
+ it('explains the concepts that actually confuse people', () => {
+ const src = read('src/master-wallet.js');
+ expect(src).toContain('function tip(');
+ expect(src).toContain('aria-describedby');
+ expect(src).toContain('role="tooltip"');
+ // The two real confusions: master vs agent wallet, and why SOL is needed.
+ expect(src).toMatch(/Each agent has its own separate wallet/);
+ expect(src).toMatch(/fee in SOL/);
+ });
+});