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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(wallet): deposit flow and master wallet updates
nirholasaecbca3ab05d
diff --git a/api/user/wallet/fund-agent.js b/api/user/wallet/fund-agent.jsindex d6d8d8ac8..e31c77515 100644--- a/api/user/wallet/fund-agent.js+++ b/api/user/wallet/fund-agent.js@@ -1,6 +1,13 @@// POST /api/user/wallet/fund-agent// Transfer USDC or SOL from the user's master wallet into one of their agent wallets.-// Body: { agent_id: string, amount: number | "max", asset: "SOL" | "USDC" }+// Body: { agent_id: string, amount: number | "max", asset: "SOL" | "USDC", simulate?: boolean }+//+// `simulate: true` runs the identical ownership, balance, rent and fee path and+// returns the resolved numbers WITHOUT recovering the key or signing anything.+// It is what the /wallet confirmation step is built from, so the amount a user+// reads back is the amount the chain produced (notably for `"max"`, which the+// browser cannot compute, and for the extra rent when the agent has no token+// account yet). Mirrors the simulate contract in send.js.import { getSessionUser } from '../../_lib/auth.js';import { sql } from '../../_lib/db.js';@@ -35,8 +42,22 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, session.id))) return;- const rl = await limits.withdrawalPerUser(session.id);+ let body;+ try { body = await readJson(req); }+ catch (e) { return error(res, 400, 'bad_request', e?.message || 'invalid body'); }++ // Parsed before the limiter so a preview does not spend the 5-per-DAY+ // withdrawal budget. See the matching note in send.js.+ const simulate = body.simulate === true;+ const rl = simulate+ ? await limits.walletSimulate(session.id)+ : await limits.withdrawalPerUser(session.id);if (!rl.success) return json(res, 429, { error: 'rate_limited' });+ // Parity with send.js: the per-user budget bounds one account, the per-IP one+ // bounds a caller cycling accounts. `clientIp` was imported here and never+ // used, which left this the only funds-moving wallet route without it.+ const rlIp = await limits.authIp(clientIp(req));+ if (!rlIp.success) return json(res, 429, { error: 'rate_limited' });// Load master walletconst [mw] = await sql`@@ -45,10 +66,6 @@ export default wrap(async (req, res) => {`;if (!mw?.solana_address) return error(res, 404, 'not_found', 'master wallet not set up');- let body;- try { body = await readJson(req); }- catch (e) { return error(res, 400, 'bad_request', e?.message || 'invalid body'); }-const agentId = body.agent_id;if (!agentId || typeof agentId !== 'string') return error(res, 400, 'bad_request', 'agent_id required');@@ -80,6 +97,10 @@ export default wrap(async (req, res) => {let ixs = [];let humanAmount, usdValue;+ // Set when the agent has no USDC token account yet: the transfer then also+ // pays that account's rent, which the confirmation step surfaces rather than+ // letting the user discover it as a surprise SOL debit.+ let tokenAccountRentLamports = 0n;if (asset === 'SOL') {let rentReserve;@@ -126,6 +147,7 @@ export default wrap(async (req, res) => {if (balanceLamports < SOL_FEE_RESERVE_LAMPORTS + ataRent) {return error(res, 400, 'insufficient_sol_for_fees', 'need more SOL in master wallet for fees');}+ tokenAccountRentLamports = ataRent;ixs.push(createAssociatedTokenAccountIdempotentInstruction(fromPk, destAta, destPk, mintPk, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,));@@ -133,6 +155,24 @@ export default wrap(async (req, res) => {ixs.push(createTransferCheckedInstruction(sourceAta, mintPk, destAta, fromPk, amountRaw, USDC_DECIMALS, [], TOKEN_PROGRAM_ID));}+ // Everything above is validation and chain reads. Returning here means the+ // encrypted secret is never decrypted and no transaction is ever built.+ if (simulate) {+ return json(res, 200, {+ simulation: {+ asset,+ agent_id: agentId,+ agent_wallet: agentSolAddr,+ human_amount: humanAmount,+ usd_value: usdValue,+ creates_token_account: tokenAccountRentLamports > 0n,+ token_account_rent_sol:+ tokenAccountRentLamports > 0n ? Number(tokenAccountRentLamports) / 1e9 : 0,+ network: 'mainnet',+ },+ });+ }+const keypair = await recoverSolanaAgentKeypair(mw.encrypted_solana_secret, {agentId: `master:${session.id}`,userId: session.id,diff --git a/api/user/wallet/send.js b/api/user/wallet/send.jsindex ddfc34ef7..d5868d011 100644--- a/api/user/wallet/send.js+++ b/api/user/wallet/send.js@@ -35,7 +35,22 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, session.id))) return;- const rlUser = await limits.withdrawalPerUser(session.id);+ let body;+ try { body = await readJson(req); }+ catch (e) { return error(res, 400, 'bad_request', e?.message || 'invalid body'); }++ const network = 'mainnet';+ const asset = typeof body.asset === 'string' && body.asset.trim() ? body.asset.trim() : 'SOL';+ const simulate = body.simulate === true;++ // The body is parsed before the limiters on purpose: a simulate moves no+ // funds, so it must not draw on the 5-per-DAY withdrawal budget. Charging+ // previews against it meant a user who priced a transfer four times could+ // not send at all until the next day. Previews get their own per-minute+ // ceiling; only a real broadcast spends the daily one.+ const rlUser = simulate+ ? await limits.walletSimulate(session.id)+ : await limits.withdrawalPerUser(session.id);if (!rlUser.success) return json(res, 429, { error: 'rate_limited' });const rlIp = await limits.authIp(clientIp(req));if (!rlIp.success) return json(res, 429, { error: 'rate_limited' });@@ -48,14 +63,6 @@ export default wrap(async (req, res) => {return error(res, 404, 'not_found', 'master wallet not set up yet');}- let body;- try { body = await readJson(req); }- catch (e) { return error(res, 400, 'bad_request', e?.message || 'invalid body'); }-- const network = 'mainnet';- const asset = typeof body.asset === 'string' && body.asset.trim() ? body.asset.trim() : 'SOL';- const simulate = body.simulate === true;-const dest = validateSolanaAddress(body.destination);if (!dest.valid) return error(res, 400, 'invalid_destination', `not a valid Solana address (${dest.reason})`);if (!dest.onCurve) return error(res, 400, 'invalid_destination', 'program/off-curve address — funds may be unrecoverable');diff --git a/public/master-wallet.css b/public/master-wallet.cssindex d8ed6cb4e..d468efc3f 100644--- a/public/master-wallet.css+++ b/public/master-wallet.css@@ -746,3 +746,389 @@ input.wlt-input {flex: 1 1 100%;}}++/* ── Explainers ───────────────────────────────────────────────────────────+ *+ * A "?" that opens on hover AND on keyboard focus, with the body text in the+ * DOM and wired through aria-describedby. No JavaScript participates, so the+ * explanation survives a failed bundle, and :focus-within means a keyboard+ * user reaches it in exactly the tab order the mouse user sees.+ */++.wlt-tip {+ position: relative;+ display: inline-flex;+ vertical-align: middle;+ margin-inline-start: 6px;+}+.wlt-tip-btn {+ appearance: none;+ width: 1.05rem;+ height: 1.05rem;+ line-height: 1;+ font: var(--text-xs) var(--font-body);+ font-weight: var(--weight-bold);+ color: var(--wallet-accent);+ background: var(--wallet-accent-soft);+ border: 1px solid var(--wallet-stroke);+ border-radius: 50%;+ cursor: help;+ padding: 0;+ transition:+ background var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard);+}+.wlt-tip-btn:hover,+.wlt-tip-btn:focus-visible {+ background: var(--wallet-accent-fill);+ border-color: var(--wallet-stroke-strong);+}+.wlt-tip-btn:focus-visible {+ outline: 2px solid var(--wallet-focus);+ outline-offset: 2px;+}+.wlt-tip-body {+ position: absolute;+ bottom: calc(100% + 8px);+ left: 50%;+ translate: -50% 0;+ z-index: 20;+ width: max-content;+ max-width: min(19rem, 78vw);+ padding: var(--space-sm) 12px;+ font: var(--text-sm) var(--font-body);+ font-weight: var(--weight-regular);+ line-height: 1.5;+ text-align: left;+ white-space: normal;+ color: var(--ink);+ background: var(--surface-3);+ border: 1px solid var(--stroke-strong);+ border-radius: var(--radius-md);+ box-shadow: 0 10px 30px rgb(0 0 0 / 0.35);+ opacity: 0;+ visibility: hidden;+ translate: -50% 4px;+ transition:+ opacity var(--duration-fast) var(--ease-standard),+ translate var(--duration-fast) var(--ease-standard),+ visibility var(--duration-fast);+}+.wlt-tip:hover .wlt-tip-body,+.wlt-tip:focus-within .wlt-tip-body {+ opacity: 1;+ visibility: visible;+ translate: -50% 0;+}++.wlt-head-actions {+ display: flex;+ align-items: center;+ gap: var(--space-sm);+ flex-wrap: wrap;+}++/* The extra cost a top-up incurs when it also opens a token account. Styled as+ * a caution rather than an error: nothing is wrong, there is just a charge the+ * user has not been told about anywhere else. */+.wlt-confirm-flag {+ margin: var(--space-sm) 0 0;+ padding: 10px 12px;+ font: var(--text-sm) var(--font-body);+ line-height: 1.55;+ color: var(--ink);+ background: var(--wallet-accent-soft);+ border: 1px solid var(--wallet-stroke);+ border-radius: var(--radius-md);+}++/* ── Deposit sheet ────────────────────────────────────────────────────────+ *+ * A native <dialog>, so the focus trap, Esc handling, inert background and+ * top-layer stacking are the platform's job rather than four hand-rolled+ * behaviours that drift.+ */++.wlt-sheet {+ /* Surface, border, radius, shadow and scrim all come from the --modal-*+ * family that .tws-modal uses, so this reads as the same dialog system.+ * Only the width differs: the shared 480px is too narrow for a QR beside+ * its fields. */+ width: min(48rem, calc(100vw - 2 * var(--space-md)));+ max-height: min(92dvh, 46rem);+ overflow: auto;+ padding: var(--space-lg);+ color: var(--ink);+ background: var(--modal-bg);+ border: 1px solid var(--modal-border);+ border-radius: var(--modal-radius);+ box-shadow: var(--modal-shadow);+}+.wlt-sheet::backdrop {+ background: var(--modal-backdrop);+ backdrop-filter: blur(3px);+}+.wlt-sheet[open] {+ animation: wlt-sheet-in var(--duration-normal) var(--ease-standard);+}+@keyframes wlt-sheet-in {+ from {+ opacity: 0;+ transform: translateY(10px) scale(0.985);+ }+}++.wlt-sheet-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-md);+ margin-bottom: var(--space-md);+}+.wlt-sheet-title {+ font: var(--text-xl) var(--font-display);+ font-weight: var(--weight-bold);+ color: var(--ink-bright);+ margin: 0;+}++.wlt-chips {+ display: flex;+ gap: var(--space-xs);+ flex-wrap: wrap;+}+.wlt-chip {+ appearance: none;+ display: inline-flex;+ align-items: baseline;+ gap: 6px;+ font: var(--text-md) var(--font-body);+ font-weight: var(--weight-medium);+ color: var(--ink-dim);+ background: var(--surface-2);+ border: 1px solid var(--stroke);+ border-radius: 999px;+ padding: 7px 14px;+ cursor: pointer;+ transition:+ color var(--duration-fast) var(--ease-standard),+ background var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard);+}+.wlt-chip:hover {+ color: var(--ink);+ border-color: var(--stroke-strong);+}+.wlt-chip:focus-visible {+ outline: 2px solid var(--wallet-focus);+ outline-offset: 2px;+}+.wlt-chip.is-active {+ color: var(--ink-bright);+ background: var(--wallet-accent-fill);+ border-color: var(--wallet-stroke-strong);+}+.wlt-chip-net {+ font: var(--text-xs) var(--font-body);+ color: var(--ink-dim);+ opacity: 0.85;+}++.wlt-sheet-hint {+ margin: var(--space-sm) 0 var(--space-md);+ font: var(--text-sm) var(--font-body);+ color: var(--ink-dim);+}++.wlt-sheet-body {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr);+ gap: var(--space-lg);+ align-items: start;+}++/* The code stays on white in both themes: a QR inverted to suit a dark UI is a+ * QR that half the scanners in circulation will not read. */+.wlt-qr-wrap {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-sm);+ max-width: 15rem;+}+.wlt-qr {+ display: grid;+ place-items: center;+ width: 15rem;+ height: 15rem;+ padding: 10px;+ background: #fff;+ border-radius: var(--radius-md);+ box-shadow: 0 0 0 1px var(--wallet-stroke);+}+.wlt-qr canvas {+ display: block;+ max-width: 100%;+ height: auto;+}+.wlt-qr-cap,+.wlt-qr-fallback {+ margin: 0;+ font: var(--text-xs) var(--font-body);+ line-height: 1.5;+ color: var(--ink-dim);+ text-align: center;+}++.wlt-sheet-fields {+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+ min-width: 0;+}+.wlt-field-label {+ display: block;+ font: var(--text-sm) var(--font-body);+ font-weight: var(--weight-medium);+ color: var(--ink);+ margin-bottom: 6px;+}+.wlt-optional {+ font-weight: var(--weight-regular);+ color: var(--ink-dim);+}+.wlt-dep-addr {+ display: block;+ font: var(--text-sm) var(--font-mono);+ color: var(--ink);+ background: var(--surface-2);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-sm);+ padding: 10px 12px;+ /* An address must stay fully readable to be verified, so it wraps rather+ * than truncating. anywhere keeps that from forcing a horizontal scroll. */+ overflow-wrap: anywhere;+ user-select: all;+}+.wlt-sheet-actions {+ display: flex;+ gap: var(--space-xs);+ flex-wrap: wrap;+ margin-top: var(--space-sm);+}++.wlt-sheet-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-md);+ flex-wrap: wrap;+ margin-top: var(--space-lg);+ padding-top: var(--space-md);+ border-top: 1px solid var(--stroke);+ font: var(--text-sm) var(--font-body);+ color: var(--ink-dim);+}+.wlt-watch {+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs);+}+.wlt-watch-pulse {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: var(--wallet-accent);+ box-shadow: 0 0 0 0 var(--wallet-glow);+ animation: wlt-pulse 2s var(--ease-standard) infinite;+}+@keyframes wlt-pulse {+ 70% {+ box-shadow: 0 0 0 9px rgb(139 92 246 / 0);+ }+ 100% {+ box-shadow: 0 0 0 0 rgb(139 92 246 / 0);+ }+}+.wlt-watch-held {+ font-variant-numeric: tabular-nums;+}++.wlt-sheet-done {+ display: flex;+ flex-direction: column;+ align-items: center;+ text-align: center;+ gap: var(--space-sm);+ padding: var(--space-lg) var(--space-md);+}+.wlt-sheet-tick {+ color: var(--wallet-accent);+}+.wlt-sheet-tick path {+ stroke-dasharray: 44;+ stroke-dashoffset: 44;+ animation: wlt-tick var(--duration-slow) var(--ease-standard) forwards;+}+@keyframes wlt-tick {+ to {+ stroke-dashoffset: 0;+ }+}+.wlt-sheet-done-title {+ font: var(--text-xl) var(--font-display);+ font-weight: var(--weight-bold);+ color: var(--ink-bright);+ margin: 0;+ font-variant-numeric: tabular-nums;+}+.wlt-sheet-done-sub {+ margin: 0;+ font: var(--text-md) var(--font-body);+ color: var(--ink-dim);+ max-width: 32rem;+}+.wlt-sheet-done-actions {+ display: flex;+ gap: var(--space-sm);+ flex-wrap: wrap;+ justify-content: center;+ margin-top: var(--space-sm);+}++@media (prefers-reduced-motion: reduce) {+ .wlt-sheet[open],+ .wlt-watch-pulse,+ .wlt-sheet-tick path {+ animation: none;+ }+ .wlt-sheet-tick path {+ stroke-dashoffset: 0;+ }+ .wlt-tip-body,+ .wlt-chip {+ transition: none;+ }+}++@media (max-width: 44rem) {+ .wlt-sheet {+ padding: var(--space-md);+ }+ /* Below this width the two columns would each be too narrow to be usable,+ * so the QR leads and the fields follow it. */+ .wlt-sheet-body {+ grid-template-columns: minmax(0, 1fr);+ justify-items: center;+ }+ .wlt-qr-wrap {+ max-width: 100%;+ }+ .wlt-sheet-fields {+ width: 100%;+ }+ .wlt-sheet-foot {+ flex-direction: column;+ align-items: flex-start;+ }+}diff --git a/src/master-wallet.js b/src/master-wallet.jsindex d4d945e7e..73ea6cb14 100644--- a/src/master-wallet.js+++ b/src/master-wallet.js@@ -32,8 +32,10 @@ import {previewSend,send as sendFunds,fetchMyAgents,+ previewFundAgent,fundAgent,} from './wallet-api.js';+import { openDepositSheet } from './wallet-deposit.js';const root = document.getElementById('wlt-root');const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';@@ -122,6 +124,28 @@ function humanError(res) {return ERROR_COPY[res?.code] || res?.message || 'Something went wrong.';}+/**+ * A hover/focus explainer for one idea. The body text lives in the DOM and is+ * wired with aria-describedby, so it reaches assistive tech and shows on+ * keyboard focus. Visibility is pure CSS: a tooltip that needs JavaScript to+ * appear is one that disappears when the JavaScript does.+ */+let tipSeq = 0;+function tip(text) {+ const id = `wlt-tip-${++tipSeq}`;+ return `<span class="wlt-tip"+ ><button class="wlt-tip-btn" type="button" aria-describedby="${id}" aria-label="Explain this"+ >?</button+ ><span class="wlt-tip-body" role="tooltip" id="${id}">${esc(text)}</span+ ></span>`;+}++/** Amount fields all offer the same escape hatch: let the server work out max. */+function maxHint(targetId) {+ return `<p class="wlt-help">Type an amount, or <button class="wlt-linkbtn" type="button"+ data-act="max" data-target="${targetId}">use my full balance</button>.</p>`;+}+// ── Rendering ────────────────────────────────────────────────────────────────function skeleton() {@@ -193,8 +217,19 @@ function emptyState() {function balanceCards(b) {const cards = [- { label: 'Total value', value: fmtUsd(b?.total_usd), sub: 'Solana + Base', accent: true },- { label: 'SOL', value: fmtAmount(b?.sol, 6), sub: 'Solana' },+ {+ label: 'Total value',+ value: fmtUsd(b?.total_usd),+ sub: 'Solana + Base',+ accent: true,+ tip: 'Both chains added together, priced live. A balance the network did not answer for is left out rather than counted as zero.',+ },+ {+ label: 'SOL',+ value: fmtAmount(b?.sol, 6),+ sub: 'Solana',+ tip: 'Solana charges every transaction a fee in SOL, so a wallet holding only USDC cannot send anything. Around 0.01 SOL covers a lot of activity.',+ },{ label: 'USDC', value: fmtAmount(b?.sol_usdc, 2), sub: 'Solana' },{ label: 'USDC', value: fmtAmount(b?.evm_usdc, 2), sub: 'Base' },];@@ -202,7 +237,7 @@ function balanceCards(b) {.map((c) => `<div class="wlt-bal${c.accent ? ' wlt-bal--accent' : ''}">- <span class="wlt-bal-label">${esc(c.label)}</span>+ <span class="wlt-bal-label">${esc(c.label)}${c.tip ? tip(c.tip) : ''}</span><span class="wlt-bal-value">${c.value == null? '<span class="wlt-bal-na" title="This balance could not be read just now">unavailable</span>'@@ -260,6 +295,13 @@ function confirmPanel() {}<div><dt>Network</dt><dd>Solana mainnet</dd></div></dl>+ ${+ p.rentSol+ ? `<p class="wlt-confirm-flag">This agent has no ${esc(p.assetLabel)} account yet, so the transfer also opens one.+ That costs an extra <strong>${esc(fmtAmount(p.rentSol, 6))} SOL</strong> in rent from this wallet, once.+ The agent keeps the account afterwards.</p>`+ : ''+ }<div class="wlt-confirm-actions"><button class="wlt-btn wlt-btn--primary" type="button" data-act="confirm" ${state.busy ? 'disabled' : ''}>${state.busy ? 'Sending…' : 'Confirm and send'}@@ -292,7 +334,7 @@ function sendPanel() {<label for="wlt-amount">Amount</label><input class="wlt-input" id="wlt-amount" name="amount" type="text" requiredspellcheck="false" autocomplete="off" inputmode="decimal" placeholder="0.0" />- <p class="wlt-help">Type an amount, or <button class="wlt-linkbtn" type="button" data-act="max">send max</button>.</p>+ ${maxHint('wlt-amount')}</div></div><button class="wlt-btn wlt-btn--primary" type="submit" ${state.busy ? 'disabled' : ''}>@@ -355,6 +397,7 @@ function fundPanel() {<label for="wlt-fund-amount">Amount</label><input class="wlt-input" id="wlt-fund-amount" name="amount" type="text" requiredspellcheck="false" autocomplete="off" inputmode="decimal" placeholder="0.0" />+ ${maxHint('wlt-fund-amount')}</div></div><button class="wlt-btn wlt-btn--primary" type="submit" ${state.busy ? 'disabled' : ''}>@@ -433,11 +476,15 @@ function readyState() {<header class="wlt-head"><div><span class="wlt-eyebrow">Master wallet</span>- <h1 class="wlt-title">Your wallet</h1>+ <h1 class="wlt-title">Your wallet${tip(+ 'Your account holds this one. Each agent has its own separate wallet, funded from here, so an agent can only ever spend what you moved into it.',+ )}</h1>+ </div>+ <div class="wlt-head-actions">+ <button class="wlt-btn wlt-btn--primary" type="button" data-act="deposit">Add funds</button>+ <button class="wlt-btn wlt-btn--sm" type="button" data-act="refresh" ${state.busy ? 'disabled' : ''}+ aria-label="Re-read balances from Solana and Base">Refresh</button></div>- <button class="wlt-btn wlt-btn--sm" type="button" data-act="refresh" ${state.busy ? 'disabled' : ''}>- Refresh balances- </button></header>${noticeBanner()}@@ -449,7 +496,11 @@ function readyState() {<section class="wlt-addresses" aria-label="Wallet addresses">${addressRow('Solana', w.solana_address, `https://solscan.io/account/${w.solana_address}`)}${addressRow('Base', w.evm_address, `https://basescan.org/address/${w.evm_address}`)}- <p class="wlt-addr-note">Fund this wallet by sending SOL or SPL tokens to the Solana address, or USDC on Base to the Base address.</p>+ <p class="wlt-addr-note">+ Copying an address by hand is the slow way in.+ <button class="wlt-linkbtn" type="button" data-act="deposit">Add funds</button>+ shows a scannable payment request instead, and this page announces the deposit the moment it lands on chain.+ </p></section><section class="wlt-actions">@@ -537,9 +588,13 @@ async function onCreate() {state.notice = {kind: 'ok',title: 'Your master wallet is ready.',- body: 'Send SOL or USDC to the Solana address below to fund it.',+ body: 'It is empty until you fund it. Scan the code to send it something.',};await loadWallet();+ // A wallet with nothing in it can do nothing, so the very next step is+ // always funding. Opening the sheet here removes the hunt for the button+ // that every new user would otherwise have to make on their own.+ if (state.phase === 'ready') onDeposit();}/**@@ -578,7 +633,13 @@ async function onReviewSend(form) {render();}-function onReviewFund(form) {+/**+ * Price an agent top-up the same way a send is priced: ask the server, which+ * resolves it against the chain and signs nothing. This is why the confirmation+ * can state what "max" actually means and warn when the transfer also opens a+ * token account for the agent at the sender's expense.+ */+async function onReviewFund(form) {const agentId = form.agent_id.value;const asset = form.asset.value;const amount = form.amount.value.trim();@@ -587,28 +648,29 @@ function onReviewFund(form) {render();return;}- const isMax = amount === 'max' || amount === 'MAX';- const n = isMax ? null : Number(amount);- if (!isMax && (!Number.isFinite(n) || n <= 0)) {- state.notice = { kind: 'err', title: 'Enter an amount greater than zero.' };+ state.busy = true;+ state.notice = null;+ render();+ const res = await previewFundAgent({ agentId, asset, amount });+ state.busy = false;+ if (!res.ok) {+ state.notice = { kind: 'err', title: 'That top-up was not accepted.', body: humanError(res) };render();return;}+ const sim = res.data?.simulation || {};const agent = state.agents.items.find((a) => a.id === agentId);- // fund-agent has no simulate path, so this confirmation is built from the- // user's own input plus the agent record. The server re-validates ownership,- // balance, rent and fees before it signs anything.- state.notice = null;state.pending = {kind: 'fund',agentId,agentName: agent?.name || 'Your agent',- destination: agent?.solana_address || '',+ destination: sim.agent_wallet || agent?.solana_address || '',asset,assetLabel: asset,amount,- humanAmount: n,- usdValue: asset === 'USDC' ? n : null,+ humanAmount: sim.human_amount,+ usdValue: sim.usd_value,+ rentSol: sim.creates_token_account ? sim.token_account_rent_sol : 0,};render();}@@ -645,6 +707,44 @@ async function onConfirm() {if (state.history.status !== 'idle') loadHistory();}+/**+ * Open the scan-to-fund sheet.+ *+ * `readBalances` is handed to the sheet rather than a whole API client: the+ * watcher only ever needs the balance object, and passing a narrow function+ * keeps the sheet testable without a network. Whatever the sheet last read is+ * already the truth, so on close the page adopts it instead of issuing another+ * request for a number it just saw.+ */+async function onDeposit() {+ const w = state.wallet;+ if (!w) return;+ let latest = null;+ const arrival = await openDepositSheet({+ solanaAddress: w.solana_address,+ evmAddress: w.evm_address,+ balances: w.balances,+ async readBalances() {+ const res = await fetchWallet();+ if (!res.ok || !res.data?.wallet?.balances) return null;+ latest = res.data.wallet;+ return latest.balances;+ },+ });+ if (latest) state.wallet = latest;+ if (arrival) {+ state.notice = {+ kind: 'ok',+ title: `${fmtAmount(arrival.delta, arrival.asset === 'sol' ? 6 : 2)} ${arrival.label} landed in your wallet.`,+ body: 'You can send it, or top up an agent with it, right now.',+ };+ // A deposit is a history event too, so a tab already showing history+ // should not keep showing the list from before the money arrived.+ if (state.history.status !== 'idle') loadHistory();+ }+ render();+}+async function onCopy(text, btn) {try {await navigator.clipboard.writeText(text);@@ -682,6 +782,7 @@ root.addEventListener('click', (e) => {const act = el.dataset.act;if (act === 'create') return void onCreate();if (act === 'reload' || act === 'refresh') return void loadWallet();+ if (act === 'deposit') return void onDeposit();if (act === 'reload-history') return void loadHistory();if (act === 'reload-agents') return void loadAgents();if (act === 'tab') return switchTab(el.dataset.tab);@@ -698,7 +799,9 @@ root.addEventListener('click', (e) => {return;}if (act === 'max') {- const input = root.querySelector('#wlt-amount');+ // "max" is a server-side word, not a number: only the API knows what is+ // left after rent and fees. The review step reads back what it resolved to.+ const input = root.querySelector(`#${el.dataset.target}`);if (input) {input.value = 'max';input.focus();@@ -712,7 +815,7 @@ root.addEventListener('submit', (e) => {e.preventDefault();if (state.busy) return;if (form.dataset.form === 'send') return void onReviewSend(form);- if (form.dataset.form === 'fund') return onReviewFund(form);+ if (form.dataset.form === 'fund') return void onReviewFund(form);});// Arrow-key navigation across the tablist, per the WAI-ARIA tabs pattern.diff --git a/src/wallet-api.js b/src/wallet-api.jsindex 2e146c8c8..5967448fc 100644--- a/src/wallet-api.js+++ b/src/wallet-api.js@@ -113,7 +113,24 @@ export function fetchMyAgents() {return call('/api/agents');}-/** Top up an agent you own, in SOL or USDC. */+/**+ * Price an agent top-up without signing anything. Same ownership, balance, rent+ * and fee checks as the real call, and it never decrypts the wallet key. Returns+ * `{ simulation: { asset, agent_id, agent_wallet, human_amount, usd_value,+ * creates_token_account, token_account_rent_sol, network } }`.+ *+ * Two of those the browser genuinely cannot work out on its own: what `"max"`+ * resolves to, and whether this transfer also pays rent to open a token account+ * for the agent. Both are shown before the user confirms.+ */+export function previewFundAgent({ agentId, asset, amount }) {+ return call('/api/user/wallet/fund-agent', {+ method: 'POST',+ body: { agent_id: agentId, asset, amount, simulate: true },+ });+}++/** Top up an agent you own, in SOL or USDC. Only after the preview is confirmed. */export function fundAgent({ agentId, asset, amount }) {return call('/api/user/wallet/fund-agent', {method: 'POST',diff --git a/src/wallet-deposit.js b/src/wallet-deposit.jsnew file mode 100644index 000000000..841f9581c--- /dev/null+++ b/src/wallet-deposit.js@@ -0,0 +1,482 @@+/**+ * Deposit sheet: scan-to-fund with live on-chain arrival detection.+ *+ * The hardest step in a custodial wallet is the first one. A page that prints a+ * base58 string and stops has handed the user a transcription job: switch to a+ * phone, retype 44 characters, send, then come back and refresh until something+ * changes. Every part of that is a place to lose someone, and mistyping the+ * address loses the funds outright.+ *+ * This replaces all of it with two real mechanisms:+ *+ * 1. A payment-request QR, not an address QR. The code encodes a Solana Pay+ * URI (`solana:<addr>?amount=&spl-token=`) or, for Base, an EIP-681 token+ * transfer. Scanning it opens Phantom or Solflare with the recipient, the+ * token AND the amount already filled in, so the sender confirms rather+ * than types. On a phone the same URI is a tappable deep link, so the+ * handoff works without a second device.+ *+ * 2. A watcher that notices the money land. While the sheet is open it re-reads+ * the wallet's real balances and compares them to the baseline captured at+ * open. When a balance rises it reports the exact delta, from the chain, and+ * the user never refreshes anything.+ *+ * The watcher is deliberately polite: it backs off as the wait gets longer, it+ * suspends entirely while the tab is hidden (a user who switched to their phone+ * is not watching this tab, and their rate-limit budget should not be spent on+ * an invisible page), and it gives up after WATCH_CEILING_MS rather than polling+ * a forgotten tab forever.+ *+ * `readBalances` is injected rather than imported so this module owns no+ * transport and can be exercised without a network.+ */++const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';+const BASE_CHAIN_ID = 8453;++/**+ * Backoff schedule. Deposits usually confirm inside a few seconds on Solana, so+ * the early polls are tight; a wait that has already run minutes is unlikely to+ * resolve in the next four seconds, so the later ones relax. Cumulative cost+ * stays far under the 60/min the wallet read endpoint allows.+ */+const WATCH_STEPS = [+ { until: 5, delay: 4000 },+ { until: 15, delay: 8000 },+];+const WATCH_TAIL_DELAY = 15000;+const WATCH_CEILING_MS = 10 * 60 * 1000;++/** The three things a user can actually deposit, and how each is encoded. */+const ASSETS = {+ sol: {+ id: 'sol',+ label: 'SOL',+ network: 'Solana',+ balanceKey: 'sol',+ decimals: 6,+ hint: 'Native SOL. Also what pays network fees, so keep a little here.',+ },+ usdc: {+ id: 'usdc',+ label: 'USDC',+ network: 'Solana',+ balanceKey: 'sol_usdc',+ decimals: 2,+ hint: 'USDC on Solana. The token agents spend for x402 calls.',+ },+ base: {+ id: 'base',+ label: 'USDC',+ network: 'Base',+ balanceKey: 'evm_usdc',+ decimals: 2,+ hint: 'USDC on Base. Sent to your EVM address, not the Solana one.',+ },+};++function esc(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function fmt(n, decimals = 6) {+ if (n == null || !Number.isFinite(n)) return null;+ if (n === 0) return '0';+ if (Math.abs(n) < 10 ** -decimals) return `<${10 ** -decimals}`;+ return n.toLocaleString(undefined, { maximumFractionDigits: decimals });+}++/**+ * Build the wallet-openable request URI for one asset.+ *+ * Solana Pay for the Solana assets, EIP-681 for Base. Both are read by the+ * mainstream wallets, and both carry the amount, so the sender is confirming a+ * prepared request rather than composing one. An amount of zero or blank is+ * omitted, which yields a valid open-ended request the sender fills in.+ */+export function buildRequestUri({ asset, solanaAddress, evmAddress, amount }) {+ const n = Number(amount);+ const hasAmount = Number.isFinite(n) && n > 0;++ if (asset === 'base') {+ if (!evmAddress) return null;+ if (!hasAmount) return `ethereum:${evmAddress}@${BASE_CHAIN_ID}`;+ // EIP-681 ERC-20 transfer: the target is the token contract, and the+ // recipient rides in the `address` parameter. USDC has 6 decimals.+ const raw = BigInt(Math.round(n * 1e6)).toString();+ return `ethereum:${BASE_USDC}@${BASE_CHAIN_ID}/transfer?address=${evmAddress}&uint256=${raw}`;+ }++ if (!solanaAddress) return null;+ const params = new URLSearchParams();+ if (hasAmount) params.set('amount', String(n));+ if (asset === 'usdc') params.set('spl-token', USDC_MINT);+ params.set('label', 'three.ws');+ params.set('message', 'Fund your master wallet');+ return `solana:${solanaAddress}?${params.toString()}`;+}++/** Which address a given asset actually lands on. Getting this wrong loses funds. */+export function addressFor(asset, { solanaAddress, evmAddress }) {+ return asset === 'base' ? evmAddress : solanaAddress;+}++/**+ * Compare a fresh balance snapshot against the baseline and return the first+ * asset that grew, with its delta.+ *+ * A balance the API could not read comes back as null. Treating null as zero+ * would invent an arrival the moment an RPC hiccup resolved, so an unreadable+ * side of the comparison is skipped rather than guessed at. The epsilon keeps+ * float noise in a re-quoted balance from reading as a deposit.+ */+export function detectArrival(baseline, current) {+ for (const asset of Object.values(ASSETS)) {+ const before = baseline?.[asset.balanceKey];+ const after = current?.[asset.balanceKey];+ if (typeof before !== 'number' || typeof after !== 'number') continue;+ const delta = after - before;+ if (delta > 1e-9) {+ return { asset: asset.id, label: asset.label, network: asset.network, delta };+ }+ }+ return null;+}++/** The poll delay for the nth check, per the backoff schedule above. */+export function watchDelay(pollCount) {+ for (const step of WATCH_STEPS) {+ if (pollCount < step.until) return step.delay;+ }+ return WATCH_TAIL_DELAY;+}++/**+ * Watch for an inbound deposit.+ *+ * Returns a handle with `.stop()`. Never throws: a failed read is a skipped+ * poll, because a transient RPC error mid-wait is not something to show a user+ * who is busy sending money on their phone.+ */+export function watchForDeposit({ baseline, readBalances, onArrival, onTick }) {+ let stopped = false;+ let polls = 0;+ let timer = null;+ const startedAt = Date.now();++ function schedule() {+ if (stopped) return;+ if (Date.now() - startedAt > WATCH_CEILING_MS) {+ stopped = true;+ onTick?.({ state: 'timeout', polls });+ return;+ }+ timer = setTimeout(tick, watchDelay(polls));+ }++ async function tick() {+ if (stopped) return;+ // A hidden tab is not being watched. Re-check later instead of spending a+ // read; the timer keeps the loop alive without touching the network.+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {+ timer = setTimeout(tick, watchDelay(polls));+ return;+ }+ polls += 1;+ let balances = null;+ try {+ balances = await readBalances();+ } catch {+ balances = null;+ }+ if (stopped) return;+ const arrival = balances ? detectArrival(baseline, balances) : null;+ if (arrival) {+ stopped = true;+ onArrival?.(arrival);+ return;+ }+ // Balances ride along so a caller can show a live figure without issuing+ // a second read of its own for the number it just fetched.+ onTick?.({ state: 'waiting', polls, balances });+ schedule();+ }++ schedule();+ return {+ stop() {+ stopped = true;+ if (timer) clearTimeout(timer);+ },+ get stopped() {+ return stopped;+ },+ };+}++// ── The sheet ────────────────────────────────────────────────────────────────++/**+ * Open the deposit sheet. Resolves when it closes.+ *+ * Uses a native <dialog>, which brings the focus trap, the Esc handler, the+ * inert background and the top-layer stacking with it rather than+ * reimplementing four accessibility behaviours by hand.+ */+export function openDepositSheet({ solanaAddress, evmAddress, balances, readBalances, defaultAsset = 'sol' }) {+ const dlg = document.createElement('dialog');+ dlg.className = 'wlt-sheet';+ dlg.setAttribute('aria-labelledby', 'wlt-sheet-title');++ const view = {+ asset: ASSETS[defaultAsset] ? defaultAsset : 'sol',+ amount: '',+ phase: 'request', // request | arrived+ arrival: null,+ polls: 0,+ qrError: false,+ };+ // `baseline` is frozen at open and is what an arrival is measured against.+ // `live` tracks the most recent read, so the footer figure stays honest+ // during a long wait without a second request.+ const baseline = { ...(balances || {}) };+ const live = { ...(balances || {}) };+ let watcher = null;++ function currentUri() {+ return buildRequestUri({+ asset: view.asset,+ solanaAddress,+ evmAddress,+ amount: view.amount,+ });+ }++ function assetTabs() {+ return Object.values(ASSETS)+ .filter((a) => (a.id === 'base' ? Boolean(evmAddress) : Boolean(solanaAddress)))+ .map((a) => {+ const on = view.asset === a.id;+ return `<button class="wlt-chip${on ? ' is-active' : ''}" type="button" role="tab"+ aria-selected="${on}" data-dep="asset" data-asset="${a.id}">+ ${esc(a.label)}<span class="wlt-chip-net">${esc(a.network)}</span>+ </button>`;+ })+ .join('');+ }++ function arrivedView() {+ const a = view.arrival;+ return `+ <div class="wlt-sheet-done" role="status">+ <div class="wlt-sheet-tick" aria-hidden="true">+ <svg viewBox="0 0 52 52" width="52" height="52"><circle cx="26" cy="26" r="24" fill="none" stroke="currentColor" stroke-width="2.5" opacity="0.35"/><path fill="none" stroke="currentColor" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round" d="M15 27l8 8 15-16"/></svg>+ </div>+ <h2 class="wlt-sheet-done-title" id="wlt-sheet-title">+ ${esc(fmt(a.delta, a.asset === 'sol' ? 6 : 2))} ${esc(a.label)} arrived+ </h2>+ <p class="wlt-sheet-done-sub">Confirmed on ${esc(a.network)}. Your balance is already up to date.</p>+ <div class="wlt-sheet-done-actions">+ <button class="wlt-btn wlt-btn--primary" type="button" data-dep="close">Done</button>+ <button class="wlt-btn" type="button" data-dep="again">Deposit more</button>+ </div>+ </div>`;+ }++ function requestView() {+ const asset = ASSETS[view.asset];+ const addr = addressFor(view.asset, { solanaAddress, evmAddress });+ const uri = currentUri();+ const held = live[asset.balanceKey];+ return `+ <header class="wlt-sheet-head">+ <h2 class="wlt-sheet-title" id="wlt-sheet-title">Add funds</h2>+ <button class="wlt-icon-btn" type="button" data-dep="close" aria-label="Close">Close</button>+ </header>++ <div class="wlt-chips" role="tablist" aria-label="Which asset to deposit">${assetTabs()}</div>+ <p class="wlt-sheet-hint">${esc(asset.hint)}</p>++ <div class="wlt-sheet-body">+ <div class="wlt-qr-wrap">+ <div class="wlt-qr" id="wlt-qr" aria-hidden="true"></div>+ ${+ view.qrError+ ? `<p class="wlt-qr-fallback">The QR could not be drawn here. The address below is the same request, copy it instead.</p>`+ : `<p class="wlt-qr-cap">Scan with Phantom, Solflare or any wallet that reads ${esc(view.asset === 'base' ? 'EIP-681' : 'Solana Pay')}.</p>`+ }+ </div>++ <div class="wlt-sheet-fields">+ <div class="wlt-field">+ <label for="wlt-dep-amount">Amount <span class="wlt-optional">optional</span></label>+ <input class="wlt-input" id="wlt-dep-amount" type="text" inputmode="decimal"+ spellcheck="false" autocomplete="off" placeholder="0.0" value="${esc(view.amount)}"+ data-dep="amount" aria-describedby="wlt-dep-amount-help" />+ <p class="wlt-help" id="wlt-dep-amount-help">+ Fill this in and the sending wallet opens with the amount already set, so there is nothing to type on the other device.+ </p>+ </div>++ <div class="wlt-field">+ <span class="wlt-field-label">${esc(asset.network)} address</span>+ <code class="wlt-dep-addr">${esc(addr || '')}</code>+ <div class="wlt-sheet-actions">+ <button class="wlt-btn wlt-btn--sm" type="button" data-dep="copy-addr" data-copy="${esc(addr || '')}">Copy address</button>+ ${uri ? `<button class="wlt-btn wlt-btn--sm" type="button" data-dep="copy-uri" data-copy="${esc(uri)}">Copy payment link</button>` : ''}+ ${uri ? `<a class="wlt-btn wlt-btn--sm wlt-btn--primary" href="${esc(uri)}" data-dep="open">Open in wallet</a>` : ''}+ </div>+ </div>+ </div>+ </div>++ <footer class="wlt-sheet-foot">+ <span class="wlt-watch" aria-live="polite">+ <span class="wlt-watch-pulse" aria-hidden="true"></span>+ Watching ${esc(asset.network)} for your deposit. It appears here on its own.+ </span>+ <span class="wlt-watch-held" id="wlt-watch-held">${+ held == null ? '' : `Holding ${esc(fmt(held, asset.decimals))} ${esc(asset.label)} now`+ }</span>+ </footer>`;+ }++ function paint() {+ dlg.innerHTML = view.phase === 'arrived' ? arrivedView() : requestView();+ if (view.phase === 'request') 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.+ * A failure downgrades to the copyable address rather than an empty box.+ */+ async function drawQr() {+ const host = dlg.querySelector('#wlt-qr');+ const uri = currentUri();+ if (!host || !uri) return;+ try {+ const mod = await import('qrcode');+ const QRCode = mod.default ?? mod;+ const canvas = document.createElement('canvas');+ host.replaceChildren(canvas);+ await QRCode.toCanvas(canvas, uri, {+ width: 208,+ margin: 1,+ errorCorrectionLevel: 'M',+ color: { dark: '#0b0714', light: '#ffffff' },+ });+ } catch {+ if (!view.qrError) {+ view.qrError = true;+ paint();+ }+ }+ }++ function startWatching() {+ watcher?.stop();+ watcher = watchForDeposit({+ baseline,+ readBalances,+ onArrival(arrival) {+ view.phase = 'arrived';+ view.arrival = arrival;+ paint();+ },+ onTick(t) {+ view.polls = t.polls;+ if (!t.balances) return;+ Object.assign(live, t.balances);+ // Patch the one figure that changed rather than repainting: a+ // repaint here would drop the caret out of the amount field+ // mid-typing.+ const asset = ASSETS[view.asset];+ const held = live[asset.balanceKey];+ const node = dlg.querySelector('#wlt-watch-held');+ if (node) {+ node.textContent =+ held == null ? '' : `Holding ${fmt(held, asset.decimals)} ${asset.label} now`;+ }+ },+ });+ }++ async function copy(text, btn) {+ try {+ await navigator.clipboard.writeText(text);+ const prev = btn.textContent;+ btn.textContent = 'Copied';+ btn.classList.add('is-copied');+ setTimeout(() => {+ btn.textContent = prev;+ btn.classList.remove('is-copied');+ }, 1400);+ } catch {+ // Selecting the code element is the manual path, and it is right there.+ dlg.querySelector('.wlt-dep-addr')?.focus?.();+ }+ }++ dlg.addEventListener('click', (e) => {+ const el = e.target.closest('[data-dep]');+ if (!el) return;+ const act = el.dataset.dep;+ if (act === 'close') return dlg.close();+ if (act === 'asset') {+ view.asset = el.dataset.asset;+ paint();+ return;+ }+ if (act === 'copy-addr' || act === 'copy-uri') return void copy(el.dataset.copy, el);+ if (act === 'again') {+ // A second deposit needs a fresh baseline, or the first one's delta+ // would be re-detected the instant the watcher restarts.+ view.phase = 'request';+ view.arrival = null;+ paint();+ rebaselineThenWatch();+ }+ });++ // Re-encode the QR as the amount is typed, but only once typing settles:+ // redrawing on every keystroke burns work nobody sees.+ let amountTimer = null;+ dlg.addEventListener('input', (e) => {+ if (e.target?.dataset?.dep !== 'amount') return;+ view.amount = e.target.value.trim();+ clearTimeout(amountTimer);+ amountTimer = setTimeout(drawQr, 280);+ });++ async function rebaselineThenWatch() {+ try {+ const fresh = await readBalances();+ if (fresh) {+ Object.assign(baseline, fresh);+ Object.assign(live, fresh);+ }+ } catch {+ /* keep the previous baseline; a stale one only delays detection */+ }+ startWatching();+ }++ document.body.appendChild(dlg);+ paint();+ dlg.showModal();+ startWatching();++ return new Promise((resolve) => {+ dlg.addEventListener('close', () => {+ watcher?.stop();+ clearTimeout(amountTimer);+ dlg.remove();+ resolve(view.arrival);+ });+ });+}diff --git a/tests/wallet-deposit.test.js b/tests/wallet-deposit.test.jsnew file mode 100644index 000000000..83b45c3db--- /dev/null+++ b/tests/wallet-deposit.test.js@@ -0,0 +1,252 @@+// Scan-to-fund: the deposit request encoding and the arrival watcher.+//+// The two things that are genuinely dangerous here are not visual:+//+// 1. The QR encodes an address a stranger's wallet will send real money to.+// A Base asset encoded against the Solana address, or a USDC request that+// forgets the mint and therefore asks for native SOL, loses funds with no+// error anywhere. These lock the encoding per asset.+// 2. "Your deposit arrived" is a claim about the chain. It must come from an+// actual balance increase, never from an unreadable balance, a re-quote of+// the same number, or float noise. detectArrival is the whole guard.+//+// The watcher is exercised with fake timers and an injected reader, so the+// backoff, the hidden-tab suspension and the stop path are asserted directly+// rather than inferred from a comment.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ buildRequestUri,+ addressFor,+ detectArrival,+ watchDelay,+ watchForDeposit,+} from '../src/wallet-deposit.js';++const SOL_ADDR = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const EVM_ADDR = '0x1111111111111111111111111111111111111111';+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';++describe('deposit request encoding', () => {+ it('encodes a bare SOL request as Solana Pay against the Solana address', () => {+ const uri = buildRequestUri({ asset: 'sol', solanaAddress: SOL_ADDR, evmAddress: EVM_ADDR });+ expect(uri.startsWith(`solana:${SOL_ADDR}?`)).toBe(true);+ const q = new URLSearchParams(uri.slice(uri.indexOf('?') + 1));+ // No amount asked for, so the sender chooses one.+ expect(q.get('amount')).toBeNull();+ // Critically: no spl-token, so this is native SOL and not a token request.+ expect(q.get('spl-token')).toBeNull();+ expect(q.get('label')).toBe('three.ws');+ });++ it('carries the amount so the sending wallet opens pre-filled', () => {+ const uri = buildRequestUri({ asset: 'sol', solanaAddress: SOL_ADDR, amount: '1.25' });+ expect(new URLSearchParams(uri.split('?')[1]).get('amount')).toBe('1.25');+ });++ it('pins the USDC mint on a Solana USDC request', () => {+ const uri = buildRequestUri({ asset: 'usdc', solanaAddress: SOL_ADDR, amount: '10' });+ const q = new URLSearchParams(uri.split('?')[1]);+ // Without spl-token this would silently request 10 SOL instead of 10 USDC.+ expect(q.get('spl-token')).toBe(USDC_MINT);+ expect(q.get('amount')).toBe('10');+ });++ it('encodes a Base USDC request as an EIP-681 transfer to the EVM address', () => {+ const uri = buildRequestUri({+ asset: 'base',+ solanaAddress: SOL_ADDR,+ evmAddress: EVM_ADDR,+ amount: '2.5',+ });+ // Target is the token contract; the recipient rides in `address`.+ expect(uri.startsWith(`ethereum:${BASE_USDC}@8453/transfer?`)).toBe(true);+ const q = new URLSearchParams(uri.split('?')[1]);+ expect(q.get('address')).toBe(EVM_ADDR);+ expect(q.get('uint256')).toBe('2500000'); // 6 decimals+ // The Solana address must never appear in a Base request.+ expect(uri).not.toContain(SOL_ADDR);+ });++ it('falls back to a plain chain-scoped address when Base has no amount', () => {+ expect(buildRequestUri({ asset: 'base', evmAddress: EVM_ADDR })).toBe(+ `ethereum:${EVM_ADDR}@8453`,+ );+ });++ it('treats a blank, zero or unparsable amount as no amount rather than zero', () => {+ for (const amount of ['', ' ', '0', 'abc', null, undefined]) {+ const uri = buildRequestUri({ asset: 'sol', solanaAddress: SOL_ADDR, amount });+ expect(new URLSearchParams(uri.split('?')[1]).get('amount')).toBeNull();+ }+ });++ it('returns null instead of a malformed URI when the address is missing', () => {+ expect(buildRequestUri({ asset: 'sol', solanaAddress: null })).toBeNull();+ expect(buildRequestUri({ asset: 'base', evmAddress: null })).toBeNull();+ });++ it('routes each asset to the address it actually settles on', () => {+ const addrs = { solanaAddress: SOL_ADDR, evmAddress: EVM_ADDR };+ expect(addressFor('sol', addrs)).toBe(SOL_ADDR);+ expect(addressFor('usdc', addrs)).toBe(SOL_ADDR);+ expect(addressFor('base', addrs)).toBe(EVM_ADDR);+ });+});++describe('arrival detection', () => {+ const base = { sol: 1, sol_usdc: 5, evm_usdc: 2 };++ it('reports the delta when a balance rises', () => {+ const hit = detectArrival(base, { ...base, sol_usdc: 8 });+ expect(hit).toMatchObject({ asset: 'usdc', label: 'USDC', network: 'Solana' });+ expect(hit.delta).toBeCloseTo(3, 9);+ });++ it('detects a Base deposit and names Base as the network', () => {+ expect(detectArrival(base, { ...base, evm_usdc: 2.5 })).toMatchObject({+ asset: 'base',+ network: 'Base',+ });+ });++ it('reports nothing when balances are unchanged', () => {+ expect(detectArrival(base, { ...base })).toBeNull();+ });++ it('never invents an arrival from an unreadable balance', () => {+ // An RPC failure surfaces as null. Reading null as zero and back again+ // would announce a deposit that never happened.+ expect(detectArrival({ ...base, sol: null }, base)).toBeNull();+ expect(detectArrival(base, { ...base, sol: null })).toBeNull();+ expect(detectArrival(base, {})).toBeNull();+ });++ it('ignores a falling balance, which is a send and not a deposit', () => {+ expect(detectArrival(base, { ...base, sol: 0.4 })).toBeNull();+ });++ it('ignores float noise below the dust threshold', () => {+ expect(detectArrival(base, { ...base, sol: 1 + 1e-12 })).toBeNull();+ });+});++describe('watch backoff', () => {+ it('polls tightly at first and relaxes as the wait lengthens', () => {+ expect(watchDelay(0)).toBe(4000);+ expect(watchDelay(4)).toBe(4000);+ expect(watchDelay(5)).toBe(8000);+ expect(watchDelay(14)).toBe(8000);+ expect(watchDelay(15)).toBe(15000);+ expect(watchDelay(500)).toBe(15000);+ });++ it('stays well inside the 60-per-minute wallet read budget', () => {+ // Worst case is the opening burst: five polls at 4s is 5 reads in 20s,+ // which extrapolates to 15/min against a ceiling of 60.+ const firstMinute = [0, 1, 2, 3, 4].reduce((ms, i) => ms + watchDelay(i), 0);+ expect(5 / (firstMinute / 60000)).toBeLessThan(60);+ });+});++describe('watchForDeposit', () => {+ // The watcher reads exactly one DOM property, behind a typeof guard, so a+ // two-line stub is a truer test than a jsdom environment: it runs in the+ // default node pool (jsdom workers time out in this workspace) and it makes+ // the module's entire DOM surface visible in one place.+ let visibility = 'visible';+ beforeEach(() => {+ vi.useFakeTimers();+ visibility = 'visible';+ globalThis.document = {+ get visibilityState() {+ return visibility;+ },+ };+ });+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ delete globalThis.document;+ });++ it('fires onArrival once with the delta and then stops polling', async () => {+ const baseline = { sol: 1, sol_usdc: 0, evm_usdc: 0 };+ const readBalances = vi+ .fn()+ .mockResolvedValueOnce({ ...baseline })+ .mockResolvedValue({ ...baseline, sol: 1.5 });+ const onArrival = vi.fn();++ const w = watchForDeposit({ baseline, readBalances, onArrival });+ await vi.advanceTimersByTimeAsync(4000);+ expect(onArrival).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(4000);++ expect(onArrival).toHaveBeenCalledTimes(1);+ expect(onArrival.mock.calls[0][0].delta).toBeCloseTo(0.5, 9);+ expect(w.stopped).toBe(true);++ // Nothing further is read once it has fired.+ const after = readBalances.mock.calls.length;+ await vi.advanceTimersByTimeAsync(60000);+ expect(readBalances).toHaveBeenCalledTimes(after);+ });++ it('survives a failing read and keeps waiting', async () => {+ const baseline = { sol: 1 };+ const readBalances = vi+ .fn()+ .mockRejectedValueOnce(new Error('rpc down'))+ .mockResolvedValue({ sol: 2 });+ const onArrival = vi.fn();++ watchForDeposit({ baseline, readBalances, onArrival });+ await vi.advanceTimersByTimeAsync(4000);+ expect(onArrival).not.toHaveBeenCalled(); // the throw was absorbed+ await vi.advanceTimersByTimeAsync(4000);+ expect(onArrival).toHaveBeenCalledTimes(1);+ });++ it('spends no reads while the tab is hidden', async () => {+ visibility = 'hidden';+ const readBalances = vi.fn().mockResolvedValue({ sol: 99 });+ const onArrival = vi.fn();++ watchForDeposit({ baseline: { sol: 1 }, readBalances, onArrival });+ await vi.advanceTimersByTimeAsync(40000);++ // The loop stayed alive but never hit the network, so a user who+ // switched to their phone burns none of their rate-limit budget.+ expect(readBalances).not.toHaveBeenCalled();+ expect(onArrival).not.toHaveBeenCalled();+ });++ it('stops on demand and issues no further reads', async () => {+ const readBalances = vi.fn().mockResolvedValue({ sol: 1 });+ const w = watchForDeposit({ baseline: { sol: 1 }, readBalances });+ await vi.advanceTimersByTimeAsync(4000);+ w.stop();+ const after = readBalances.mock.calls.length;+ await vi.advanceTimersByTimeAsync(120000);+ expect(readBalances).toHaveBeenCalledTimes(after);+ });++ it('gives up rather than polling a forgotten tab forever', async () => {+ const readBalances = vi.fn().mockResolvedValue({ sol: 1 });+ const onTick = vi.fn();+ watchForDeposit({ baseline: { sol: 1 }, readBalances, onTick });+ await vi.advanceTimersByTimeAsync(11 * 60 * 1000);+ expect(onTick.mock.calls.some(([t]) => t.state === 'timeout')).toBe(true);+ });++ it('hands the fresh balances to onTick so a caller needs no second read', async () => {+ const readBalances = vi.fn().mockResolvedValue({ sol: 1, sol_usdc: 7 });+ const onTick = vi.fn();+ watchForDeposit({ baseline: { sol: 1, sol_usdc: 7 }, readBalances, onTick });+ await vi.advanceTimersByTimeAsync(4000);+ const waiting = onTick.mock.calls.map(([t]) => t).find((t) => t.state === 'waiting');+ expect(waiting.balances).toEqual({ sol: 1, sol_usdc: 7 });+ });+});