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
fix(shopper): settle x402 payment on the page so a paid run replays the task you typed
nirholas467c430b534e
diff --git a/api/_lib/x402/receipt-storage.js b/api/_lib/x402/receipt-storage.jsindex fd21ae245..9ad57a410 100644--- a/api/_lib/x402/receipt-storage.js+++ b/api/_lib/x402/receipt-storage.js@@ -73,33 +73,90 @@ export function recordReceipt({ resourceUrl, signedReceipt, settled, payment })});}+/** ISO string for a timestamptz that may arrive as a Date or a string. */+function isoOf(value) {+ return value instanceof Date ? value.toISOString() : value;+}++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/**+ * The keyset cursor is the last row's id, and the boundary timestamp is looked+ * up from that row inside the query.+ *+ * Carrying the timestamp in the cursor instead is the obvious design and it is+ * wrong: `issued_at` is a timestamptz with microsecond precision, JavaScript+ * Dates hold milliseconds, so a client-echoed ISO cursor rounds the boundary+ * DOWN and every row inside the truncated microsecond is skipped. Measured on+ * the live table, that dropped a receipt at the page-1/page-2 seam (the busiest+ * single second there holds 60 receipts, so same-timestamp ties are routine,+ * not theoretical). Resolving the boundary server-side from the row itself+ * compares at full precision.+ */+export function encodeReceiptCursor(row) {+ return row?.id ? String(row.id) : null;+}++export function decodeReceiptCursor(cursor) {+ if (!cursor) return null;+ const id = String(cursor).trim();+ return UUID_RE.test(id) ? id : null;+}+/*** Fetch receipts for a payer address. Used by /api/x402/my-receipts after* verifying a buyer-signed SIWE message proving wallet ownership.*+ * Newest first. Pass the previous page's `nextCursor` to walk backwards+ * through the whole history rather than seeing only the newest `limit` rows.+ ** @param {object} args* @param {string} args.payer - wallet address (will be lower-cased for EVM)* @param {number} [args.sinceUnix] - return receipts issued >= this time (seconds)+ * @param {string} [args.cursor] - opaque keyset cursor from a previous page* @param {number} [args.limit] - clamp 1..200, default 50+ * @returns {Promise<{receipts: object[], nextCursor: string|null}>}*/-export async function listReceiptsForPayer({ payer, sinceUnix, limit }) {+export async function listReceiptPage({ payer, sinceUnix, cursor, limit }) {const normPayer = normalisePayer(payer);- if (!normPayer) return [];+ if (!normPayer) return { receipts: [], nextCursor: null };const clampedLimit = clampInt(limit, { max: 200, fallback: 50 });const sinceDate =sinceUnix && Number.isFinite(Number(sinceUnix))? new Date(Number(sinceUnix) * 1000): new Date(0);- const rows = await sql`- select id, payer, network, resource_url, format, receipt, transaction,- amount_atomics, asset, issued_at- from x402_receipts- where payer = ${normPayer}- and issued_at >= ${sinceDate.toISOString()}- order by issued_at desc- limit ${clampedLimit}- `;- return rows.map((r) => ({+ const after = decodeReceiptCursor(cursor);+ // A cursor that is not a well-formed id is a client bug, not a reason to+ // silently restart from the newest page and repeat rows the caller has.+ if (cursor && !after) return { receipts: [], nextCursor: null };+ // One extra row decides hasMore without a second round trip.+ const probeLimit = clampedLimit + 1;+ const rows = after+ ? await sql`+ select id, payer, network, resource_url, format, receipt, transaction,+ amount_atomics, asset, issued_at+ from x402_receipts+ where payer = ${normPayer}+ and issued_at >= ${sinceDate.toISOString()}+ and (issued_at, id) < (+ select issued_at, id from x402_receipts+ where id = ${after}::uuid and payer = ${normPayer}+ )+ order by issued_at desc, id desc+ limit ${probeLimit}+ `+ : await sql`+ select id, payer, network, resource_url, format, receipt, transaction,+ amount_atomics, asset, issued_at+ from x402_receipts+ where payer = ${normPayer}+ and issued_at >= ${sinceDate.toISOString()}+ order by issued_at desc, id desc+ limit ${probeLimit}+ `;+ const hasMore = rows.length > clampedLimit;+ const page = hasMore ? rows.slice(0, clampedLimit) : rows;+ const receipts = page.map((r) => ({id: r.id,payer: r.payer,network: r.network,@@ -109,6 +166,99 @@ export async function listReceiptsForPayer({ payer, sinceUnix, limit }) {transaction: r.transaction,amountAtomics: r.amount_atomics ?? null,asset: r.asset ?? null,- issuedAt: r.issued_at instanceof Date ? r.issued_at.toISOString() : r.issued_at,+ issuedAt: isoOf(r.issued_at),}));+ return {+ receipts,+ nextCursor: hasMore ? encodeReceiptCursor(receipts.at(-1)) : null,+ };+}++/**+ * Fetch receipts for a payer address (first page only).+ *+ * Retained as the simple shape for callers that want the newest N rows and+ * nothing else. Anything that must show a payer their WHOLE history should+ * use listReceiptPage() and follow `nextCursor`.+ *+ * @param {object} args - same as listReceiptPage+ */+export async function listReceiptsForPayer({ payer, sinceUnix, limit }) {+ const { receipts } = await listReceiptPage({ payer, sinceUnix, limit });+ return receipts;+}++/**+ * Account-wide totals for one payer, independent of the page window.+ *+ * The vault's KPI strip used to be computed from the loaded page, so a wallet+ * with 60k receipts was told it had 200 and shown the spend of its newest 200+ * only. These aggregates ride the same (payer, issued_at desc) index as the+ * page query and answer for the entire history.+ *+ * Amounts stay per-asset and atomic: different settlement assets have+ * different scales, and summing them into one number server-side would bake in+ * a conversion we have no business inventing.+ *+ * @param {object} args+ * @param {string} args.payer+ * @param {number} [args.sinceUnix]+ * @returns {Promise<{total: number, endpoints: number, networks: string[],+ * firstAt: string|null, lastAt: string|null,+ * spend: Array<{asset: string, count: number, atomics: string}>, unpriced: number}>}+ */+export async function summarizeReceiptsForPayer({ payer, sinceUnix }) {+ const empty = {+ total: 0,+ endpoints: 0,+ networks: [],+ firstAt: null,+ lastAt: null,+ spend: [],+ unpriced: 0,+ };+ const normPayer = normalisePayer(payer);+ if (!normPayer) return empty;+ const sinceIso = (+ sinceUnix && Number.isFinite(Number(sinceUnix))+ ? new Date(Number(sinceUnix) * 1000)+ : new Date(0)+ ).toISOString();+ const [totals, byAsset] = await Promise.all([+ sql`+ select count(*)::int as total,+ count(distinct resource_url)::int as endpoints,+ coalesce(array_agg(distinct network), '{}') as networks,+ min(issued_at) as first_at,+ max(issued_at) as last_at,+ count(*) filter (where amount_atomics is null)::int as unpriced+ from x402_receipts+ where payer = ${normPayer} and issued_at >= ${sinceIso}+ `,+ sql`+ select asset,+ count(*)::int as n,+ sum(amount_atomics::numeric)::text as atomics+ from x402_receipts+ where payer = ${normPayer} and issued_at >= ${sinceIso}+ and amount_atomics is not null and asset is not null+ group by asset+ order by sum(amount_atomics::numeric) desc+ `,+ ]);+ const t = totals?.[0];+ if (!t) return empty;+ return {+ total: Number(t.total) || 0,+ endpoints: Number(t.endpoints) || 0,+ networks: (t.networks || []).filter(Boolean),+ firstAt: t.first_at ? isoOf(t.first_at) : null,+ lastAt: t.last_at ? isoOf(t.last_at) : null,+ spend: (byAsset || []).map((r) => ({+ asset: r.asset,+ count: Number(r.n) || 0,+ atomics: String(r.atomics ?? '0'),+ })),+ unpriced: Number(t.unpriced) || 0,+ };}diff --git a/api/x402-pay.js b/api/x402-pay.jsindex 61e29105a..e49307e79 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -45,6 +45,7 @@ import { dispatch } from './_mcp/dispatch.js';import { env } from './_lib/env.js';import { getRedis as _getSharedRedis } from './_lib/redis.js';import { sql } from './_lib/db.js';+import { thumbnailUrl } from './_lib/r2.js';import { logger } from './_lib/usage.js';import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';import { recoverSolanaAgentKeypair } from './_lib/agent-wallet.js';@@ -217,10 +218,13 @@ async function loadAgentKeypairForUser(agentId, userId) {async function getAgentsForUser(userId) {const rows = await sql`- SELECT id, name, description, avatar_id, meta- FROM agent_identities- WHERE user_id = ${userId} AND deleted_at IS NULL- ORDER BY created_at ASC+ SELECT i.id, i.name, i.description, i.avatar_id, i.meta,+ a.thumbnail_key AS avatar_thumbnail_key,+ a.visibility AS avatar_visibility+ FROM agent_identities i+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL+ WHERE i.user_id = ${userId} AND i.deleted_at IS NULL+ ORDER BY i.created_at ASC`;const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });return Promise.all(rows.map(async (row) => {@@ -251,11 +255,22 @@ async function getAgentsForUser(userId) {usdc = 0;}}+ // Thumbnails carry the same public/unlisted gate as everywhere else+ // (api/agents.js, characters.js): a private avatar's R2 object is not+ // publicly readable, so emitting its URL only paints a broken image.+ // Null lets the card fall back to the initial-letter avatar it already+ // renders as a sibling.+ const avatarPubliclyReadable =+ row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted';return {id: row.id,name: row.name,description: row.description,avatar_id: row.avatar_id,+ avatar_thumbnail_url:+ row.avatar_thumbnail_key && avatarPubliclyReadable+ ? thumbnailUrl(row.avatar_thumbnail_key)+ : null,solana_address: address,solana_wallet_source: source,usdc,diff --git a/api/x402/my-receipts.js b/api/x402/my-receipts.jsindex 0bb061fb3..7eab1ad5c 100644--- a/api/x402/my-receipts.js+++ b/api/x402/my-receipts.js@@ -1,4 +1,4 @@-// GET /api/x402/my-receipts?address=<addr>&signature=<sig>&issuedAt=<iso>&network=<evm|solana>&sinceUnix=<n>+// GET /api/x402/my-receipts?address=<addr>&signature=<sig>&issuedAt=<iso>&network=<evm|solana>&sinceUnix=<n>&cursor=<c>&limit=<n>//// Buyer-side read endpoint for the x402 Offer & Receipt extension (USE-17).// Returns every signed receipt we issued to the requested wallet so a buyer@@ -22,7 +22,10 @@ import { evmTransport } from '../_lib/evm/rpc.js';import { cors, error, json, method, rateLimited } from '../_lib/http.js';import { env } from '../_lib/env.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { listReceiptsForPayer } from '../_lib/x402/receipt-storage.js';+import {+ listReceiptPage,+ summarizeReceiptsForPayer,+} from '../_lib/x402/receipt-storage.js';import { verifySiwsSignature } from '../_lib/siws.js';const MAX_AGE_SECONDS = 300;@@ -54,29 +57,50 @@ function withinFreshnessWindow(issuedAt) {return ageSec >= 0 && ageSec <= MAX_AGE_SECONDS;}-// Decimals for the settlement assets THIS deployment actually pays in, read-// from the same env config that builds the 402 accepts — so a client never has-// to keep its own copy of our asset addresses (which would silently drift the-// day an asset is repointed). Every asset advertised in an accept is covered:-// USDC on Solana/Base/BSC, USD₮0 on X Layer, and $THREE on the Solana rail. An-// asset we don't recognise returns null and the client renders the raw atomic-// amount rather than guessing a scale.-export function assetDecimals(asset) {+// The settlement assets THIS deployment actually pays in, read from the same+// env config that builds the 402 accepts — so a client never has to keep its+// own copy of our asset addresses (which would silently drift the day an asset+// is repointed). Every asset advertised in an accept is covered: USDC on+// Solana/Base/BSC, USD₮0 on X Layer, and $THREE on the Solana rail.+//+// The symbol travels with the scale because scale alone is not enough to+// render an amount: $THREE and USDC are both divisible assets, and printing a+// $THREE payment as "$1.23" claims a dollar value nobody quoted. One table so+// a new asset cannot arrive with a scale but no symbol.+function settlementAssets() {+ return [+ [env.X402_ASSET_MINT_SOLANA, 6, 'USDC'],+ [env.X402_ASSET_ADDRESS_BASE, 6, 'USDC'],+ [env.X402_ASSET_ADDRESS_BSC, 6, 'USDC'],+ [env.X402_ASSET_ADDRESS_XLAYER, 6, 'USD₮0'],+ [env.THREE_TOKEN_MINT, env.THREE_TOKEN_DECIMALS, 'THREE'],+ ];+}++function lookupAsset(asset) {if (!asset) return null;const want = String(asset).toLowerCase();- const configured = [- [env.X402_ASSET_MINT_SOLANA, 6],- [env.X402_ASSET_ADDRESS_BASE, 6],- [env.X402_ASSET_ADDRESS_BSC, 6],- [env.X402_ASSET_ADDRESS_XLAYER, 6],- [env.THREE_TOKEN_MINT, env.THREE_TOKEN_DECIMALS],- ];- for (const [known, decimals] of configured) {- if (known && String(known).toLowerCase() === want) return decimals;+ for (const [known, decimals, symbol] of settlementAssets()) {+ if (known && String(known).toLowerCase() === want) return { decimals, symbol };}return null;}+/**+ * Scale for a settlement asset, or null for one this deployment never pays in+ * (the client then renders the raw atomic amount rather than guessing).+ */+export function assetDecimals(asset) {+ const found = lookupAsset(asset);+ return found ? found.decimals : null;+}++/** Ticker for a settlement asset, or null when we do not recognise it. */+export function assetSymbol(asset) {+ const found = lookupAsset(asset);+ return found ? found.symbol : null;+}+function detectNetwork(address, declared) {if (declared === 'evm' || declared === 'solana') return declared;if (EVM_RE.test(address)) return 'evm';@@ -98,6 +122,7 @@ export default async function handler(req, res) {const declaredNetwork = String(url.searchParams.get('network') || '').trim().toLowerCase();const sinceUnix = url.searchParams.get('sinceUnix');const limit = url.searchParams.get('limit');+ const cursor = url.searchParams.get('cursor');const network = detectNetwork(address, declaredNetwork);if (!network) {@@ -159,9 +184,17 @@ export default async function handler(req, res) {// Storage layer stores EVM addresses lowercased and Solana addresses as-is;// match that convention so the join hits.const payerKey = network === 'evm' ? address.toLowerCase() : address;- let rows;+ let page;+ let summary;try {- rows = await listReceiptsForPayer({ payer: payerKey, sinceUnix, limit });+ // The summary is account-wide on purpose: a payer with tens of thousands+ // of receipts must be told the real total, not the size of the page they+ // happen to be holding. It is only computed for the first page, since+ // paging never changes it.+ [page, summary] = await Promise.all([+ listReceiptPage({ payer: payerKey, sinceUnix, cursor, limit }),+ cursor ? Promise.resolve(null) : summarizeReceiptsForPayer({ payer: payerKey, sinceUnix }),+ ]);} catch (err) {return error(res, 502, 'receipt_query_failed', err.message);}@@ -169,7 +202,24 @@ export default async function handler(req, res) {json(res, 200, {network,address: payerKey,- count: rows.length,- receipts: rows.map((r) => ({ ...r, assetDecimals: assetDecimals(r.asset) })),+ count: page.receipts.length,+ nextCursor: page.nextCursor,+ ...(summary+ ? {+ summary: {+ ...summary,+ spend: summary.spend.map((s) => ({+ ...s,+ decimals: assetDecimals(s.asset),+ symbol: assetSymbol(s.asset),+ })),+ },+ }+ : {}),+ receipts: page.receipts.map((r) => ({+ ...r,+ assetDecimals: assetDecimals(r.asset),+ assetSymbol: assetSymbol(r.asset),+ })),});}diff --git a/docs/listings.md b/docs/listings.mdindex 03c35d833..68a82d992 100644--- a/docs/listings.md+++ b/docs/listings.md@@ -113,7 +113,7 @@ The codebase includes the `<agent-3d>` browser component, the Solana minting SDKEvery listing is announced through:- **RSS** — [`https://three.ws/rss/announcements.xml`](https://three.ws/rss/announcements.xml)-- **News index** — [`https://three.ws/news/`](https://three.ws/news/)+- **News index**: [`https://three.ws/news`](https://three.ws/news)- **Blog** — [`https://three.ws/blog/`](https://three.ws/blog/)Subscribe via RSS to track new listings, integrations, and protocol updates.diff --git a/pages/shopper.html b/pages/shopper.htmlindex 919d49076..213f16ebf 100644--- a/pages/shopper.html+++ b/pages/shopper.html@@ -86,9 +86,23 @@transition: border-color 0.15s, background 0.15s;}.nav-end .console:hover { border-color: var(--text); background: rgba(255,255,255,0.04); }+ /* Below 880px the links used to be display:none, which left the+ Marketplace and Fact Checker routes unreachable from this page on a+ phone. They stay in the bar and scroll horizontally instead. */@media (max-width: 880px) {- .nav-main { display: none; }- .nav-inner { padding: 14px 20px; gap: 16px; }+ .nav-inner { padding: 14px 20px; gap: 12px; }+ .nav-main {+ margin-left: 0; min-width: 0;+ overflow-x: auto; scrollbar-width: none;+ -webkit-overflow-scrolling: touch;+ }+ .nav-main::-webkit-scrollbar { display: none; }+ .nav-main a { padding: 7px 9px; white-space: nowrap; }+ }+ @media (max-width: 560px) {+ .nav-inner { gap: 8px; }+ .brand { font-size: 15px; }+ .nav-end .console { margin-left: 0; padding: 7px 12px; }}/* ── BUTTONS ─────────────────────────────────────────────── */@@ -397,6 +411,89 @@}.empty-tips strong { color: var(--text-2); font-weight: 500; }+ /* Inline payment card (402) */+ .pay-card {+ background: var(--surface-1);+ border: 1px solid rgba(255, 180, 0, 0.28);+ border-radius: 12px;+ overflow: hidden;+ }+ .pay-head { padding: 22px 24px 18px; border-bottom: 1px solid var(--hairline); }+ .pay-eyebrow {+ font-family: var(--font-mono); font-size: 10.5px;+ letter-spacing: 0.2em; text-transform: uppercase;+ color: #e6a820; margin-bottom: 10px;+ }+ .pay-price {+ font-family: var(--font-display);+ font-size: 34px; font-weight: 600; letter-spacing: -0.03em;+ color: var(--text); line-height: 1.1;+ }+ .pay-price span {+ font-family: var(--font-mono); font-size: 13px;+ font-weight: 400; color: var(--text-3); letter-spacing: 0;+ margin-left: 6px;+ }+ .pay-desc {+ margin: 10px 0 0; font-size: 13.5px;+ color: var(--text-2); line-height: 1.5; max-width: 44ch;+ }+ .pay-body { padding: 20px 24px; }+ .pay-net-label {+ font-family: var(--font-mono); font-size: 10.5px;+ letter-spacing: 0.2em; text-transform: uppercase;+ color: var(--text-3); margin-bottom: 14px;+ }+ .pay-wallets {+ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: 20px; align-items: start;+ }+ .pay-net { display: flex; flex-direction: column; gap: 8px; min-width: 0; }+ .pay-net-name {+ font-size: 12px; color: var(--text-3);+ letter-spacing: 0.04em;+ }+ .wallet-btn {+ justify-content: space-between; width: 100%;+ padding: 11px 14px; font-size: 13.5px;+ background: var(--surface-2);+ }+ .wallet-btn span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .wallet-arrow { color: var(--text-4); transition: transform 0.15s, color 0.15s; }+ .wallet-btn:hover .wallet-arrow { transform: translateX(3px); color: var(--text-2); }+ .pay-status {+ margin: 16px 0 0; min-height: 0;+ font-size: 13px; line-height: 1.45; color: var(--text-2);+ }+ .pay-status:empty { display: none; }+ .pay-status-error { color: #e07070; }+ .pay-foot {+ padding: 14px 24px 18px;+ border-top: 1px solid var(--hairline);+ }+ .pay-cancel { padding: 8px 14px; font-size: 13px; }++ /* Settlement receipt above a paid run */+ .receipt-row {+ display: flex; align-items: center; justify-content: space-between;+ gap: 12px; flex-wrap: wrap;+ padding: 10px 16px; margin-bottom: 12px;+ background: var(--surface-2);+ border: 1px solid var(--hairline);+ border-radius: 8px;+ }+ .receipt-lbl {+ font-family: var(--font-mono); font-size: 11.5px;+ letter-spacing: 0.12em; text-transform: uppercase;+ color: var(--text-3);+ }+ .receipt-val {+ font-family: var(--font-mono); font-size: 12px;+ color: var(--text-2); word-break: break-all;+ }+ .receipt-val a { text-decoration: underline; text-underline-offset: 3px; }+ .receipt-val a:hover { color: var(--text); }+/* 402 badge */.badge-402 {display: inline-flex; align-items: center; gap: 6px;@@ -465,7 +562,7 @@<!-- Left: form --><div class="form-panel">- <div class="panel-label">Task</div>+ <label class="panel-label" for="task-input">Task</label><textareaid="task-input"class="task-input"@@ -473,16 +570,16 @@rows="5"></textarea>- <div class="chip-row" id="chip-row">- <span class="chip" data-task="What is Ethereum's current price?" data-i18n="shopper.eth_price">ETH price</span>- <span class="chip" data-task="Check reputation of agent with address 0x1234" data-i18n="shopper.agent_reputation">Agent reputation</span>- <span class="chip" data-task="Search for available x402 endpoints for weather data" data-i18n="shopper.find_weather_apis">Find weather APIs</span>- <span class="chip" data-task="List the top paid AI model endpoints in the Bazaar" data-i18n="shopper.ai_model_endpoints">AI model endpoints</span>- <span class="chip" data-task="What pump.fun tokens are trending right now?" data-i18n="shopper.pump_fun_trends">Pump.fun trends</span>+ <div class="chip-row" id="chip-row" role="group" aria-label="Example tasks">+ <button type="button" class="chip" data-task="What is Ethereum's current price?" data-i18n="shopper.eth_price">ETH price</button>+ <button type="button" class="chip" data-task="Check reputation of agent with address 0x1234" data-i18n="shopper.agent_reputation">Agent reputation</button>+ <button type="button" class="chip" data-task="Search for available x402 endpoints for weather data" data-i18n="shopper.find_weather_apis">Find weather APIs</button>+ <button type="button" class="chip" data-task="List the top paid AI model endpoints in the Bazaar" data-i18n="shopper.ai_model_endpoints">AI model endpoints</button>+ <button type="button" class="chip" data-task="What pump.fun tokens are trending right now?" data-i18n="shopper.pump_fun_trends">Pump.fun trends</button></div><div class="budget-row">- <span class="budget-label" data-i18n="shopper.max_budget">Max budget</span>+ <label class="budget-label" for="budget-slider" data-i18n="shopper.max_budget">Max budget</label><inputid="budget-slider"type="range"diff --git a/public/pay/index.html b/public/pay/index.htmlindex 1597c51ef..b4a62d7e3 100644--- a/public/pay/index.html+++ b/public/pay/index.html@@ -956,8 +956,11 @@ function renderAgentCards(agents) {const el = document.createElement('div');el.className = 'agent-card' + (selectedAgent?.id === agent.id ? ' selected' : '');el.dataset.agentId = agent.id;- const avatarHtml = agent.avatar_id- ? `<img src="https://three.ws/avatars/${agent.avatar_id}/thumbnail.png" data-fallback="sibling" alt="" /><span style="display:none">${escape(agent.name[0]||'?')}</span>`+ // The thumbnail URL comes from the API (R2, public/unlisted avatars only).+ // There is no /avatars/<id>/thumbnail.png route on this origin, so deriving+ // one from avatar_id only ever 404'd and painted the fallback anyway.+ const avatarHtml = agent.avatar_thumbnail_url+ ? `<img src="${attr(agent.avatar_thumbnail_url)}" data-fallback="sibling" alt="" /><span style="display:none">${escape(agent.name[0]||'?')}</span>`: `<span>${escape(agent.name[0]||'?')}</span>`;const walletHtml = agent.solana_address? `<span class="bal">${agent.usdc != null ? agent.usdc.toFixed(3)+' USDC' : ''}</span>`@@ -1429,6 +1432,9 @@ const renderTicker = () => { tickerText.textContent = `${sessionTotal.toFixed(3)renderTicker();function escape(s) { return String(s).replace(/[<>&]/g, c => ({'<':'<','>':'>','&':'&'}[c])); }+// Attribute context needs the quote characters escaped too; `escape` above is+// text-node safe only.+function attr(s) { return escape(s).replace(/"/g, '"').replace(/'/g, '''); }function formatBytes(n) {if (!Number.isFinite(n)) return '—';if (n < 1024) return `${n} B`;diff --git a/public/x402-pay-core.js b/public/x402-pay-core.jsindex 2b9d3cd66..af527b0bf 100644--- a/public/x402-pay-core.js+++ b/public/x402-pay-core.js@@ -507,12 +507,21 @@ function mobileRedirectError() {// Retry the gated resource with the X-PAYMENT proof and return the unlocked// content plus the decoded settlement receipt.-async function executePaid({ xPayment, resourceUrl, onStatus, accept, payerAddress }) {+//+// `request` lets a caller replay a resource that is not a plain GET. A paid+// POST route (the Endpoint Shopper takes its task and budget in a JSON body)+// answers a bodyless GET with a 405, so the buyer would settle on-chain and+// then get nothing back. Callers pass { method, body, headers } to replay the+// exact request that earned the 402. Default stays GET for the paywall page.+async function executePaid({ xPayment, resourceUrl, onStatus, accept, payerAddress, request }) {onStatus?.('confirming', 'Unlocking content…');- const res = await fetch(resourceUrl, {- method: 'GET',- headers: { 'X-PAYMENT': xPayment, Accept: '*/*' },- });+ const method = String(request?.method || 'GET').toUpperCase();+ const init = {+ method,+ headers: { 'X-PAYMENT': xPayment, Accept: '*/*', ...(request?.headers || {}) },+ };+ if (request?.body != null && method !== 'GET' && method !== 'HEAD') init.body = request.body;+ const res = await fetch(resourceUrl, init);const ct = res.headers.get('content-type') || '';const text = await res.text();let result;@@ -547,7 +556,7 @@ async function executePaid({ xPayment, resourceUrl, onStatus, accept, payerAddre// ────────────────────────────────────────────────────────────── Solana pay ───-export async function paySolana({ accept, resourceUrl, walletName, onStatus, origin }) {+export async function paySolana({ accept, resourceUrl, walletName, onStatus, origin, request }) {accept = normalizeAccept(accept);const apiOrigin = origin || (typeof location !== 'undefined' ? location.origin : '');const label = walletName === 'solflare' ? 'Solflare' : 'Phantom';@@ -588,7 +597,7 @@ export async function paySolana({ accept, resourceUrl, walletName, onStatus, oriresource_url: resourceUrl,});- return executePaid({ xPayment: enc.x_payment, resourceUrl, onStatus, accept, payerAddress });+ return executePaid({ xPayment: enc.x_payment, resourceUrl, onStatus, accept, payerAddress, request });}// ───────────────────────────────────────────────────────────────── EVM pay ───@@ -637,7 +646,7 @@ function getWcProjectId() {return null;}-export async function payEvm({ accept, resourceUrl, walletName, onStatus }) {+export async function payEvm({ accept, resourceUrl, walletName, onStatus, request }) {accept = normalizeAccept(accept);const meta = EVM_NETWORKS[accept.network];if (!meta) throw new Error(`Unsupported EVM network ${accept.network}`);@@ -687,19 +696,19 @@ export async function payEvm({ accept, resourceUrl, walletName, onStatus }) {resourceUrl,});const xPayment = b64encode(paymentPayload);- return executePaid({ xPayment, resourceUrl, onStatus, accept, payerAddress });+ return executePaid({ xPayment, resourceUrl, onStatus, accept, payerAddress, request });}// ─────────────────────────────────────────────────────────── dispatcher ──────// Single entry point for the paywall controller. Routes a wallet button to the// correct chain-specific payer based on the network of the matching `accept`.-export async function pay({ accept, resourceUrl, walletName, onStatus, origin }) {+export async function pay({ accept, resourceUrl, walletName, onStatus, origin, request }) {if (isSolanaNetwork(accept?.network)) {- return paySolana({ accept, resourceUrl, walletName, onStatus, origin });+ return paySolana({ accept, resourceUrl, walletName, onStatus, origin, request });}if (isEvmNetwork(accept?.network)) {- return payEvm({ accept, resourceUrl, walletName, onStatus });+ return payEvm({ accept, resourceUrl, walletName, onStatus, request });}throw new Error(`Unsupported network ${accept?.network}`);}diff --git a/src/shopper-app.js b/src/shopper-app.jsindex 3dfab48ed..816d03511 100644--- a/src/shopper-app.js+++ b/src/shopper-app.js@@ -19,6 +19,60 @@ const ACTION_LABELS = {// calls, so a budget below the base fee can't fund a single paid step.const MIN_BUDGET_USD = 0.01;+const RUN_ROUTE = '/api/agents/endpoint-shopper-run';++// The browser payment core is a static asset in public/, so it is pulled in as a+// script tag (the interface it exposes is window.PaywallWallet, exactly what the+// full-page paywall consumes) rather than a bundler import, and only once a 402+// actually arrives, so the wallet + web3 code never costs the first paint.+const PAY_CORE_URL = '/x402-pay-core.js';++let payCorePromise = null;++function loadPayCore() {+ if (window.PaywallWallet) return Promise.resolve(window.PaywallWallet);+ if (payCorePromise) return payCorePromise;+ payCorePromise = new Promise((resolve, reject) => {+ const tag = document.createElement('script');+ tag.type = 'module';+ tag.src = PAY_CORE_URL;+ tag.addEventListener('load', () => {+ if (window.PaywallWallet) resolve(window.PaywallWallet);+ else reject(new Error('The payment module loaded but did not initialise. Reload the page and try again.'));+ });+ tag.addEventListener('error', () => {+ payCorePromise = null;+ tag.remove();+ reject(new Error('The payment module failed to load. Check your connection and try again.'));+ });+ document.head.appendChild(tag);+ });+ return payCorePromise;+}++const WALLETS = {+ base: [+ { id: 'coinbase', label: 'Coinbase Wallet' },+ { id: 'metamask', label: 'MetaMask' },+ { id: 'walletconnect', label: 'WalletConnect' },+ ],+ solana: [+ { id: 'phantom', label: 'Phantom' },+ { id: 'solflare', label: 'Solflare' },+ ],+};++const RUN_BTN_HTML =+ '<svg width="14" height="14" fill="none" viewBox="0 0 14 14" aria-hidden="true"><path d="M3 2l9 5-9 5V2z" fill="currentColor"/></svg> Run Task';++// The empty state ships in the page markup so it paints before this module+// loads. Captured once here so any later state can hand the panel back to it.+let emptyStateHtml = '';++function renderEmptyState(panel) {+ panel.innerHTML = emptyStateHtml;+}+export function init() {const taskInput = document.getElementById('task-input');const runBtn = document.getElementById('run-btn');@@ -30,6 +84,8 @@ export function init() {if (!taskInput || !runBtn || !resultPanel) return;+ emptyStateHtml = resultPanel.innerHTML;+// Gate the CTA on a non-empty task and a fundable budget. Distinct hints// tell the user exactly which precondition is unmet before they pay.function refreshGate() {@@ -97,7 +153,7 @@ async function runTask({ task, maxCostUsd, resultPanel, runBtn, refreshGate }) {let data;try {- const res = await fetch('/api/agents/endpoint-shopper-run', {+ const res = await fetch(RUN_ROUTE, {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ task, maxCostUsd }),@@ -105,7 +161,12 @@ async function runTask({ task, maxCostUsd, resultPanel, runBtn, refreshGate }) {if (res.status === 402) {const body = await res.json().catch(() => ({}));- showPaywallPrompt(resultPanel, body, res.headers.get('payment-required'));+ showPaymentRequired(resultPanel, {+ body,+ header: res.headers.get('payment-required'),+ task,+ maxCostUsd,+ });return;}@@ -132,11 +193,10 @@ async function runTask({ task, maxCostUsd, resultPanel, runBtn, refreshGate }) {data = await res.json();} catch (err) {- showError(resultPanel, err.message || 'Network error — please try again');+ showError(resultPanel, err.message || 'Network error. Check your connection and try again.');return;} finally {- runBtn.innerHTML =- '<svg width="14" height="14" fill="none" viewBox="0 0 14 14"><path d="M3 2l9 5-9 5V2z" fill="currentColor"/></svg> Run Task';+ runBtn.innerHTML = RUN_BTN_HTML;// Re-evaluate preconditions so the CTA only re-enables when valid.if (typeof refreshGate === 'function') refreshGate();else runBtn.disabled = false;@@ -173,33 +233,273 @@ function showError(panel, message) {}}-function showPaywallPrompt(panel, body, paymentRequiredHeader) {- // The payment challenge can arrive in the `payment-required` header or, on- // proxies that strip it, inside the 402 JSON body. Fall back to the body- // (and finally to a bare paywall) so the Pay button always works.- const challenge = paymentRequiredHeader- || body?.paymentRequired- || body?.payment_required- || (body?.accepts ? JSON.stringify(body) : '');+// ── Payment (402) ─────────────────────────────────────────────────────────+//+// The run route is a real x402 paid endpoint. Rather than bounce the user to+// the generic /paywall.html (which loses the task and budget they typed, and+// replays the resource as a bodyless GET that this POST route cannot answer),+// the payment happens inline: the wallet signs against the advertised+// requirement, and the SAME request that earned the 402 is replayed with the+// X-PAYMENT proof, so the buyer gets the run they paid for.++// Pull the payment requirements out of a 402. The canonical copy is the JSON+// body's `accepts`; the base64 `payment-required` header carries the same+// envelope for proxies that rewrite bodies, so it is the fallback.+export function readAccepts(body, header) {+ const fromBody = Array.isArray(body?.accepts) ? body.accepts : null;+ if (fromBody?.length) return fromBody;++ const decoded = decodeChallengeHeader(header);+ const fromHeader = Array.isArray(decoded?.accepts)+ ? decoded.accepts+ : Array.isArray(decoded)+ ? decoded+ : null;+ return fromHeader?.length ? fromHeader : [];+}- const reqParam = challenge ? encodeURIComponent(challenge) : '';- const ret = encodeURIComponent(location.pathname);- const paywallUrl = reqParam- ? `/paywall.html?req=${reqParam}&return=${ret}`- : `/paywall.html?return=${ret}`;+function decodeChallengeHeader(header) {+ if (!header || typeof header !== 'string') return null;+ try {+ let b64 = header.replace(/-/g, '+').replace(/_/g, '/');+ while (b64.length % 4 !== 0) b64 += '=';+ return JSON.parse(decodeURIComponent(escape(atob(b64))));+ } catch {+ return null;+ }+}- const detail = body?.error || body?.message- || 'This endpoint costs USDC on Base or Solana. Use a wallet to pay and unlock the result.';+// Pick the requirement to sign for one network. The server advertises several+// entries per chain (a plain USDC transfer, a Permit2 sibling, and a $THREE+// option); the wallet flow signs EIP-3009 typed data on EVM, and a stablecoin+// price is the one a first-time buyer expects to see quoted.+export function pickAccept(accepts, net) {+ const onNet = accepts.filter((a) =>+ net === 'solana' ? isSolanaNet(a?.network) : isEvmNet(a?.network) && isEip3009(a),+ );+ if (!onNet.length) return null;+ const stable = onNet.find((a) => /usdc|usd coin/i.test(String(a?.extra?.name || '')));+ return stable || onNet[0];+}++function isSolanaNet(net) {+ return typeof net === 'string' && (net === 'solana' || net.startsWith('solana:'));+}++function isEvmNet(net) {+ return typeof net === 'string' && net.startsWith('eip155:');+}++function isEip3009(accept) {+ const method = accept?.extra?.assetTransferMethod;+ return !method || method === 'eip3009';+}++export function networkLabel(network) {+ const n = String(network || '');+ if (n.startsWith('eip155:8453')) return 'Base';+ if (n.startsWith('eip155:84532')) return 'Base Sepolia';+ if (n.startsWith('solana:') || n === 'solana') return 'Solana';+ return n || 'Unknown';+}++// Atomic amount to a human price. BigInt because token amounts can exceed+// Number's safe range.+export function formatAmount(atomic, decimals = 6) {+ let n;+ try {+ n = BigInt(String(atomic ?? '0'));+ } catch {+ return '0';+ }+ const base = 10n ** BigInt(decimals);+ const whole = n / base;+ const frac = (n % base).toString().padStart(decimals, '0').replace(/0+$/, '');+ return frac ? `${whole}.${frac}` : String(whole);+}++function showPaymentRequired(panel, { body, header, task, maxCostUsd }) {+ const accepts = readAccepts(body, header);+ const options = [+ { net: 'base', accept: pickAccept(accepts, 'base') },+ { net: 'solana', accept: pickAccept(accepts, 'solana') },+ ].filter((o) => o.accept);++ if (!options.length) {+ showError(+ panel,+ 'This run needs a USDC payment, but the endpoint did not return a payment option this browser can sign. Try again in a moment.',+ );+ return;+ }++ const quoted = options[0].accept;+ const price = formatAmount(quoted.amount, Number(quoted.extra?.decimals ?? 6));+ const asset = quoted.extra?.name || 'USDC';panel.innerHTML = `- <div class="error-card" style="border-color: rgba(255,180,0,0.3)">- <p style="color:#e6a820">Payment required to use the Endpoint Shopper agent.</p>- <p style="color:var(--text-3); font-size:13.5px; margin:0 0 14px">- ${escHtml(detail)}- </p>- <a class="btn primary" href="${paywallUrl}">Pay with Wallet</a>+ <div class="pay-card">+ <div class="pay-head">+ <div class="pay-eyebrow">Payment required</div>+ <div class="pay-price">${escHtml(price)} <span>${escHtml(asset)}</span></div>+ <p class="pay-desc">+ Base fee to start the agent. It then spends up to+ $${maxCostUsd.toFixed(2)} of your budget on the endpoints it calls, and+ reports every cent in the trace.+ </p>+ </div>+ <div class="pay-body">+ <div class="pay-net-label" id="pay-net-label">Pay with</div>+ <div class="pay-wallets" role="group" aria-labelledby="pay-net-label">+ ${options.map(renderWalletGroup).join('')}+ </div>+ <p class="pay-status" id="pay-status" role="status" aria-live="polite"></p>+ </div>+ <div class="pay-foot">+ <button class="btn pay-cancel" type="button" id="pay-cancel">Edit the task instead</button>+ </div></div>`;++ const statusEl = panel.querySelector('#pay-status');+ const cancel = panel.querySelector('#pay-cancel');+ if (cancel) {+ cancel.addEventListener('click', () => {+ renderEmptyState(panel);+ document.getElementById('task-input')?.focus();+ });+ }++ let inFlight = false;+ panel.querySelectorAll('.wallet-btn').forEach((btn) => {+ btn.addEventListener('click', async () => {+ if (inFlight) return;+ const option = options.find((o) => o.net === btn.dataset.net);+ if (!option) return;+ inFlight = true;+ setWalletsDisabled(panel, true);+ try {+ const outcome = await payAndRun({+ accept: option.accept,+ walletName: btn.dataset.wallet,+ task,+ maxCostUsd,+ statusEl,+ });+ renderPaidRun(panel, outcome, task);+ } catch (err) {+ // A mobile browser with no injected wallet navigates into the+ // wallet app; the page is unloading, so leave the status as-is.+ if (err?.code === 'mobile_redirect') return;+ inFlight = false;+ setWalletsDisabled(panel, false);+ setPayError(statusEl, err?.message || 'Payment failed. Please try again.');+ }+ });+ });+}++function renderWalletGroup({ net, accept }) {+ const wallets = WALLETS[net] || [];+ return `+ <div class="pay-net">+ <div class="pay-net-name">${escHtml(networkLabel(accept.network))}</div>+ ${wallets+ .map(+ (w) => `<button class="btn wallet-btn" type="button" data-net="${escHtml(net)}" data-wallet="${escHtml(w.id)}">+ <span>${escHtml(w.label)}</span>+ <span class="wallet-arrow" aria-hidden="true">→</span>+ </button>`,+ )+ .join('')}+ </div>+ `;+}++function setWalletsDisabled(panel, disabled) {+ panel.querySelectorAll('.wallet-btn').forEach((b) => {+ b.disabled = disabled;+ });+}++function setPayStatus(statusEl, message) {+ if (!statusEl) return;+ statusEl.classList.remove('pay-status-error');+ statusEl.setAttribute('role', 'status');+ statusEl.textContent = message;+}++function setPayError(statusEl, message) {+ if (!statusEl) return;+ statusEl.classList.add('pay-status-error');+ statusEl.setAttribute('role', 'alert');+ statusEl.textContent = message;+}++const PHASE_TEXT = {+ connecting: 'Connecting wallet…',+ building: 'Building payment…',+ signing: 'Waiting for your signature…',+ confirming: 'Settling on-chain…',+};++// Sign the payment, then replay the ORIGINAL POST (task + budget) with the+// X-PAYMENT proof so the paid run returns the answer the buyer asked for.+async function payAndRun({ accept, walletName, task, maxCostUsd, statusEl }) {+ setPayStatus(statusEl, PHASE_TEXT.connecting);+ const core = await loadPayCore();+ const resourceUrl = core.resolveResourceUrl(accept, RUN_ROUTE);++ return core.pay({+ accept,+ resourceUrl,+ walletName,+ onStatus: (phase, text) => {+ if (phase === 'done') return;+ if (phase === 'error') setPayError(statusEl, text);+ else setPayStatus(statusEl, text || PHASE_TEXT[phase] || 'Working…');+ },+ request: {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ task, maxCostUsd }),+ },+ });+}++// Render the paid run: the settlement receipt above the normal execution+// trace, so the buyer can see both what they paid and what they got.+function renderPaidRun(panel, outcome, task) {+ const data = typeof outcome?.result === 'object' && outcome.result !== null ? outcome.result : {};+ renderResults(panel, data, task);++ const receipt = document.createElement('div');+ receipt.className = 'receipt-row';+ const explorer = outcome?.transaction+ ? explorerLink(outcome.network || null, outcome.transaction)+ : null;+ receipt.innerHTML = `+ <span class="receipt-lbl">Paid on ${escHtml(networkLabel(outcome?.network))}</span>+ <span class="receipt-val">${+ explorer+ ? `<a href="${escHtml(explorer)}" target="_blank" rel="noopener noreferrer">${escHtml(shortId(outcome.transaction))}</a>`+ : 'Settled'+ }</span>+ `;+ panel.insertBefore(receipt, panel.firstChild);+}++function explorerLink(network, tx) {+ if (!tx) return null;+ if (isSolanaNet(network)) return `https://solscan.io/tx/${tx}`;+ if (String(network || '').startsWith('eip155:84532')) return `https://sepolia.basescan.org/tx/${tx}`;+ if (isEvmNet(network)) return `https://basescan.org/tx/${tx}`;+ return null;+}++function shortId(value) {+ const v = String(value || '');+ return v.length > 20 ? `${v.slice(0, 10)}…${v.slice(-8)}` : v;}function renderResults(panel, data, task) {@@ -303,9 +603,12 @@ function escHtml(str) {.replace(/'/g, ''');}-// Auto-init on DOMContentLoaded-if (document.readyState === 'loading') {- document.addEventListener('DOMContentLoaded', init);-} else {- init();+// Auto-init on DOMContentLoaded. Guarded on a DOM so the 402-parsing helpers+// above stay importable outside a browser (tests/shopper-402.test.js).+if (typeof document !== 'undefined') {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', init);+ } else {+ init();+ }}diff --git a/tests/shopper-402.test.js b/tests/shopper-402.test.jsnew file mode 100644index 000000000..da6a4c9c1--- /dev/null+++ b/tests/shopper-402.test.js@@ -0,0 +1,127 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';++// /shopper runs a real paid x402 endpoint, so a 402 is the normal first answer+// for anyone who has not paid. These cover how the page reads that challenge:+// which payment option it quotes, and where it finds the challenge when a proxy+// has rewritten one of the two carriers (JSON body, `payment-required` header).++const { readAccepts, pickAccept, formatAmount, networkLabel } = await import(+ '../src/shopper-app.js'+);++const SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';++// The exact envelope the deployed route answers with, captured from the live+// endpoint so the parsing is held to the real wire format.+const CHALLENGE = {+ x402Version: 2,+ error: 'X-PAYMENT header is required',+ accepts: [+ {+ scheme: 'exact',+ amount: '10000',+ network: 'eip155:8453',+ payTo: '0x4022de2d36c334e73c7a108805cea11c0564f402',+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ extra: { name: 'USD Coin', version: '2', decimals: 6 },+ },+ {+ scheme: 'exact',+ amount: '10000',+ network: 'eip155:8453',+ payTo: '0x4022de2d36c334e73c7a108805cea11c0564f402',+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ extra: {+ name: 'USD Coin',+ version: '2',+ decimals: 6,+ assetTransferMethod: 'permit2',+ supportsEip2612: true,+ },+ },+ {+ scheme: 'exact',+ amount: '10000',+ network: SOLANA,+ payTo: 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU',+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ extra: { name: 'USDC', decimals: 6 },+ },+ {+ scheme: 'exact',+ amount: '10000000',+ network: SOLANA,+ payTo: 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU',+ asset: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ extra: { name: 'THREE', decimals: 6 },+ },+ ],+};++const HEADER = Buffer.from(JSON.stringify(CHALLENGE), 'utf8').toString('base64');++describe('reading the 402 challenge', () => {+ it('prefers the JSON body', () => {+ expect(readAccepts(CHALLENGE, null)).toHaveLength(4);+ });++ it('falls back to the base64 payment-required header when the body is stripped', () => {+ const accepts = readAccepts({ x402Version: 2, error: 'X-PAYMENT header is required' }, HEADER);+ expect(accepts).toHaveLength(4);+ expect(accepts[0].network).toBe('eip155:8453');+ });++ it('returns nothing when neither carrier holds a challenge', () => {+ expect(readAccepts({}, null)).toEqual([]);+ expect(readAccepts({}, 'not-base64-at-all!!')).toEqual([]);+ });+});++describe('choosing the requirement to sign', () => {+ it('skips the Permit2 sibling on EVM, which the wallet flow cannot sign', () => {+ const base = pickAccept(CHALLENGE.accepts, 'base');+ expect(base.network).toBe('eip155:8453');+ expect(base.extra.assetTransferMethod).toBeUndefined();+ });++ it('quotes the stablecoin option on Solana, not the alternative asset', () => {+ const sol = pickAccept(CHALLENGE.accepts, 'solana');+ expect(sol.network).toBe(SOLANA);+ expect(sol.extra.name).toBe('USDC');+ });++ it('returns null for a network the challenge does not offer', () => {+ const evmOnly = CHALLENGE.accepts.filter((a) => a.network.startsWith('eip155:'));+ expect(pickAccept(evmOnly, 'solana')).toBeNull();+ });+});++describe('quoting the price', () => {+ it('renders atomic USDC as a trimmed decimal', () => {+ expect(formatAmount('10000', 6)).toBe('0.01');+ expect(formatAmount('1000000', 6)).toBe('1');+ expect(formatAmount('1500000', 6)).toBe('1.5');+ });++ it('survives a missing or unparseable amount instead of printing NaN', () => {+ expect(formatAmount(undefined, 6)).toBe('0');+ expect(formatAmount('abc', 6)).toBe('0');+ });++ it('names the chains it quotes', () => {+ expect(networkLabel('eip155:8453')).toBe('Base');+ expect(networkLabel(SOLANA)).toBe('Solana');+ });+});++describe('the page no longer hands the challenge to the generic paywall', () => {+ // The paywall decodes `?req=` as a base64 requirements ARRAY and replays the+ // resource as a bodyless GET. This route's challenge is an envelope and its+ // resource is a POST that needs the task body, so both assumptions broke:+ // the buyer saw an empty paywall, and a payment would have unlocked nothing.+ it('builds no paywall.html URL', () => {+ const source = readFileSync(new URL('../src/shopper-app.js', import.meta.url), 'utf8');+ expect(source).not.toMatch(/\/paywall\.html\?/);+ });+});diff --git a/tests/x402-pay-core-paid-replay.test.js b/tests/x402-pay-core-paid-replay.test.jsnew file mode 100644index 000000000..74aaaa357--- /dev/null+++ b/tests/x402-pay-core-paid-replay.test.js@@ -0,0 +1,131 @@+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';+import http from 'node:http';++// The browser payment core replays the gated resource with the X-PAYMENT proof+// once the wallet has signed. It replayed as a bodyless GET unconditionally,+// which is right for a paid GET page but silently wrong for a paid POST route:+// /api/agents/endpoint-shopper-run takes the task and budget in a JSON body, so+// the buyer settled on-chain and then got a 400 back instead of the run they+// paid for. `pay({ request })` carries the original request into the replay.+//+// These tests drive the real payEvm against a local server. Only the injected+// EIP-1193 provider stands in for a browser wallet extension (there is no+// extension in Node); the payload building, base64 encoding and replay are the+// shipped code paths, and nothing is broadcast to a chain.++const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';+const PAYER = '0x1111111111111111111111111111111111111111';++// window must exist before the module is imported: it attaches+// window.PaywallWallet on load and reads window.ethereum on every payment.+globalThis.window = globalThis.window || {};++const { payEvm, b64decode } = await import('../public/x402-pay-core.js');++function accept(origin) {+ return {+ scheme: 'exact',+ network: 'eip155:8453',+ asset: USDC,+ payTo: '0x4022de2d36c334e73c7a108805cea11c0564f402',+ amount: '10000',+ maxTimeoutSeconds: 60,+ resource: `${origin}/api/agents/endpoint-shopper-run`,+ extra: { name: 'USD Coin', version: '2', decimals: 6 },+ };+}++// Minimal EIP-1193 wallet: enough for connect, chain check, balance read and+// the typed-data signature. Balance is deliberately ample so the fail-open+// pre-flight guard never short-circuits the flow under test.+function stubWallet() {+ return {+ isMetaMask: true,+ async request({ method }) {+ if (method === 'eth_requestAccounts') return [PAYER];+ if (method === 'eth_chainId') return '0x2105';+ if (method === 'eth_call') return '0x' + (10n ** 12n).toString(16).padStart(64, '0');+ if (method === 'eth_signTypedData_v4') return '0x' + 'ab'.repeat(65);+ throw new Error(`unexpected provider method ${method}`);+ },+ };+}++let server;+let origin;+let seen;++beforeAll(async () => {+ server = http.createServer((req, res) => {+ const chunks = [];+ req.on('data', (c) => chunks.push(c));+ req.on('end', () => {+ seen = {+ method: req.method,+ body: Buffer.concat(chunks).toString('utf8'),+ contentType: req.headers['content-type'] || null,+ xPayment: req.headers['x-payment'] || null,+ };+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ result: { answer: 'ok' }, steps: [], totalCostUsdc: '0.000000' }));+ });+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ origin = `http://127.0.0.1:${server.address().port}`;+});++afterAll(() => new Promise((resolve) => server.close(resolve)));++beforeEach(() => {+ seen = null;+ globalThis.window.ethereum = stubWallet();+});++describe('paid replay carries the request that earned the 402', () => {+ it('replays a paid POST route with its original JSON body', async () => {+ const a = accept(origin);+ const outcome = await payEvm({+ accept: a,+ resourceUrl: a.resource,+ walletName: 'metamask',+ request: {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ task: 'What is Ethereum current price?', maxCostUsd: 0.5 }),+ },+ });++ expect(seen.method).toBe('POST');+ expect(seen.contentType).toContain('application/json');+ expect(JSON.parse(seen.body)).toEqual({+ task: 'What is Ethereum current price?',+ maxCostUsd: 0.5,+ });+ expect(outcome.result).toEqual({ result: { answer: 'ok' }, steps: [], totalCostUsdc: '0.000000' });+ });++ it('signs the payment for the same resource it replays', async () => {+ const a = accept(origin);+ await payEvm({+ accept: a,+ resourceUrl: a.resource,+ walletName: 'metamask',+ request: { method: 'POST', body: '{"task":"t"}' },+ });++ const payload = b64decode(seen.xPayment);+ expect(payload.resource.url).toBe(a.resource);+ expect(payload.network).toBe('eip155:8453');+ expect(payload.payload.authorization.from.toLowerCase()).toBe(PAYER);+ });++ it('still replays as a bodyless GET when no request is supplied', async () => {+ const a = accept(origin);+ await payEvm({ accept: a, resourceUrl: a.resource, walletName: 'metamask' });++ expect(seen.method).toBe('GET');+ expect(seen.body).toBe('');+ expect(seen.xPayment).toBeTruthy();+ });+});