Skip to content

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

feat(x402): SKU catalog, Stripe-like checkout flow, /dashboard/x402

nirholas4d932a9376c8
diff --git a/api/_lib/http.js b/api/_lib/http.js
index 8233e4ad1..0a767d890 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -97,7 +97,14 @@ export function cors(
res.setHeader('access-control-allow-methods', methods);
res.setHeader(
'access-control-allow-headers',
- 'authorization, content-type, mcp-session-id, mcp-protocol-version',
+ 'authorization, content-type, mcp-session-id, mcp-protocol-version, x-payment, payment-signature, idempotency-key',
+ );
+ // x402: clients (drop-in modal, x402-fetch) must read these to drive the
+ // 402-pay-retry flow and surface settlement receipts. Without `expose`,
+ // cross-origin readers only see CORS-safelisted response headers.
+ res.setHeader(
+ 'access-control-expose-headers',
+ 'payment-required, x-payment-response, x-payment-network, x-payment-tx, link',
);
res.setHeader('access-control-max-age', '86400');
if (req.method === 'OPTIONS') {
diff --git a/api/_lib/migrations/2026-05-14-x402-skus.sql b/api/_lib/migrations/2026-05-14-x402-skus.sql
new file mode 100644
index 000000000..10a57ded7
--- /dev/null
+++ b/api/_lib/migrations/2026-05-14-x402-skus.sql
@@ -0,0 +1,73 @@
+-- x402 Checkout — hosted-link SKUs.
+--
+-- A SKU is a hosted checkout link a merchant creates in their dashboard. It
+-- captures a target paid endpoint, branding, and post-payment redirect, so the
+-- buyer-facing URL `/pay/c/<slug>` can render a clean checkout page without
+-- the merchant writing any frontend code.
+--
+-- Each SKU is owned by a single user. The slug is unique globally so the
+-- hosted link can be a single short path.
+--
+-- x402_checkout_calls records every successful paid call against a SKU so
+-- the dashboard can surface revenue + click-through. Failed attempts are not
+-- recorded (we never see them — the buyer's wallet rejected before settle).
+
+CREATE TABLE IF NOT EXISTS x402_skus (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ owner_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+
+ -- public-facing identifier; the URL is /pay/c/<slug>
+ slug text NOT NULL UNIQUE
+ CONSTRAINT x402_skus_slug_format
+ CHECK (slug ~ '^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$'),
+
+ -- target endpoint this SKU charges for; must be a 402-enabled URL
+ target_endpoint text NOT NULL,
+ target_method text NOT NULL DEFAULT 'GET'
+ CHECK (target_method IN ('GET', 'POST')),
+ target_body jsonb, -- POST body, when applicable
+
+ -- branding shown in the modal + hosted page
+ merchant_name text NOT NULL,
+ action_name text NOT NULL,
+ description text, -- optional longer copy on the hosted page
+ logo_url text, -- optional merchant logo (https only enforced in API)
+ accent_color text DEFAULT '#0a84ff'
+ CHECK (accent_color ~* '^#[0-9a-f]{6}$'),
+
+ -- post-payment redirect; if NULL we render the response inline
+ success_url text,
+
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ archived_at timestamptz
+);
+
+CREATE INDEX IF NOT EXISTS idx_x402_skus_owner ON x402_skus (owner_user_id, created_at DESC);
+CREATE INDEX IF NOT EXISTS idx_x402_skus_active ON x402_skus (slug) WHERE archived_at IS NULL;
+
+CREATE TABLE IF NOT EXISTS x402_checkout_calls (
+ id bigserial PRIMARY KEY,
+ sku_id uuid NOT NULL REFERENCES x402_skus(id) ON DELETE CASCADE,
+ paid_at timestamptz NOT NULL DEFAULT now(),
+
+ -- on-chain settlement
+ network text NOT NULL, -- CAIP-2 id e.g. 'eip155:8453' or 'solana:...'
+ tx_signature text, -- the on-chain tx hash from facilitator settle
+ payer_address text, -- buyer's wallet
+ amount_atomics text NOT NULL, -- raw token units (string, fits bigint)
+ asset text NOT NULL, -- token contract / mint address
+
+ -- merchant endpoint outcome
+ response_status int NOT NULL, -- HTTP status returned to the buyer
+ error_code text, -- when response_status >= 400
+
+ -- traceback for support
+ buyer_ip_hash text,
+ user_agent text
+);
+
+CREATE INDEX IF NOT EXISTS idx_x402_checkout_calls_sku
+ ON x402_checkout_calls (sku_id, paid_at DESC);
+CREATE INDEX IF NOT EXISTS idx_x402_checkout_calls_recent
+ ON x402_checkout_calls (paid_at DESC);
diff --git a/api/x402-checkout-record.js b/api/x402-checkout-record.js
new file mode 100644
index 000000000..2bc5679c9
--- /dev/null
+++ b/api/x402-checkout-record.js
@@ -0,0 +1,69 @@
+// Records a successful paid checkout call against a SKU.
+//
+// The hosted checkout page (/pay/c/<slug>) calls this after the drop-in
+// modal returns a settled payment. The endpoint is public — anyone can record
+// a call against any SKU — so we authenticate the entry by verifying the
+// X-PAYMENT-RESPONSE blob from the facilitator's /settle response.
+//
+// In v1 we trust the client-reported payment header (the facilitator already
+// gated settlement; spoofing means lying to yourself about analytics). Future
+// hardening: verify the tx on-chain before recording.
+
+import { z } from 'zod';
+import { sql } from './_lib/db.js';
+import { cors, json, readJson, wrap, error } from './_lib/http.js';
+import { parse } from './_lib/validate.js';
+
+const recordSchema = z.object({
+ sku_id: z.string().uuid(),
+ network: z.string().min(3).max(80),
+ tx_signature: z.string().max(180).optional(),
+ payer_address: z.string().max(64).optional(),
+ amount_atomics: z.string().regex(/^\d+$/),
+ asset: z.string().max(64),
+ response_status: z.number().int().min(100).max(599),
+ error_code: z.string().max(80).optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;
+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'use POST');
+
+ const body = parse(recordSchema, await readJson(req));
+
+ // Confirm the SKU exists (and is active) before inserting — keeps the table
+ // clean of orphan rows pointing at archived SKUs.
+ const [sku] = await sql`select id from x402_skus where id = ${body.sku_id} and archived_at is null limit 1`;
+ if (!sku) return error(res, 404, 'sku_not_found', 'no active SKU with that id');
+
+ const ip = (req.headers['x-forwarded-for'] || req.socket?.remoteAddress || '').toString().split(',')[0].trim();
+ const ipHash = ip ? simpleHash(ip) : null;
+ const ua = (req.headers['user-agent'] || '').toString().slice(0, 240);
+
+ const [row] = await sql`
+ insert into x402_checkout_calls (
+ sku_id, network, tx_signature, payer_address,
+ amount_atomics, asset, response_status, error_code,
+ buyer_ip_hash, user_agent
+ ) values (
+ ${body.sku_id}, ${body.network},
+ ${body.tx_signature ?? null}, ${body.payer_address ?? null},
+ ${body.amount_atomics}, ${body.asset},
+ ${body.response_status}, ${body.error_code ?? null},
+ ${ipHash}, ${ua}
+ )
+ returning id, paid_at
+ `;
+ return json(res, 201, { ok: true, id: row.id, paid_at: row.paid_at });
+});
+
+function simpleHash(s) {
+ // Tiny FNV-1a — we just need a stable non-reversible bucket for abuse
+ // detection. Not crypto. 32-bit hex output is enough granularity.
+ let h = 0x811c9dc5;
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;
+ }
+ return h.toString(16).padStart(8, '0');
+}
diff --git a/api/x402-checkout.js b/api/x402-checkout.js
new file mode 100644
index 000000000..a2636ada2
--- /dev/null
+++ b/api/x402-checkout.js
@@ -0,0 +1,195 @@
+// x402-checkout — buyer-side helper for the drop-in modal.
+//
+// The buyer's wallet (Phantom for Solana, MetaMask for EVM) needs to sign the
+// payment payload that goes into the `X-PAYMENT` header. For EVM that's an
+// EIP-712 typed-data signature the wallet builds locally. For Solana the
+// wallet only signs serialized transactions — it does NOT build instructions.
+// So we expose this endpoint: client posts { accept, buyer }, server returns
+// a partially-signed v0 transaction ready for Phantom to add the payer's sig.
+//
+// Endpoints:
+// POST /api/x402-checkout?action=prepare { accept, buyer }
+// → { network, tx_base64 } v0 SPL transferChecked, fee payer
+// is accept.extra.feePayer (the
+// facilitator's sponsor account)
+// POST /api/x402-checkout?action=encode { signed_tx_base64, accept, resource_url }
+// → { x_payment } base64 paymentPayload ready for
+// X-PAYMENT header
+//
+// We split prepare + encode so the modal can show "Sign in your wallet…" while
+// Phantom is open, then "Sending…" while we wrap the signed tx into the
+// x402 envelope. Keeps each step short and visible.
+
+import { z } from 'zod';
+import {
+ Connection,
+ PublicKey,
+ TransactionMessage,
+ VersionedTransaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ getAssociatedTokenAddressSync,
+ createAssociatedTokenAccountIdempotentInstruction,
+ createTransferCheckedInstruction,
+ getMint,
+} from '@solana/spl-token';
+import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
+import { parse } from './_lib/validate.js';
+import {
+ NETWORK_SOLANA_MAINNET,
+ NETWORK_SOLANA_DEVNET,
+} from './_lib/x402-spec.js';
+
+const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+const SOLANA_DEVNET_RPC = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
+
+const acceptSchema = z.object({
+ scheme: z.literal('exact'),
+ network: z.string().min(1).max(80),
+ amount: z.string().regex(/^\d+$/),
+ asset: z.string().min(32).max(44),
+ payTo: z.string().min(32).max(44),
+ maxTimeoutSeconds: z.number().int().positive().optional(),
+ extra: z
+ .object({
+ name: z.string().optional(),
+ decimals: z.number().int().nonnegative().optional(),
+ feePayer: z.string().min(32).max(44),
+ })
+ .passthrough(),
+});
+
+const prepareSchema = z.object({
+ accept: acceptSchema,
+ buyer: z.string().min(32).max(44),
+});
+
+const encodeSchema = z.object({
+ accept: acceptSchema,
+ signed_tx_base64: z.string().min(40).max(20_000),
+ resource_url: z.string().url(),
+});
+
+export default wrap(async (req, res) => {
+ // Public, cross-origin endpoint — the drop-in script runs on any merchant
+ // site and POSTs here. No credentials, allow any origin.
+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const action = req.query?.action;
+ if (action === 'prepare') return handlePrepare(req, res);
+ if (action === 'encode') return handleEncode(req, res);
+ return error(res, 404, 'not_found', `unknown action: ${action ?? '(none)'}`);
+});
+
+function isSolanaNetwork(network) {
+ return (
+ network === NETWORK_SOLANA_MAINNET ||
+ network === NETWORK_SOLANA_DEVNET ||
+ network === 'solana'
+ );
+}
+
+function rpcFor(network) {
+ if (network === NETWORK_SOLANA_DEVNET) return SOLANA_DEVNET_RPC;
+ return SOLANA_RPC;
+}
+
+async function handlePrepare(req, res) {
+ const body = parse(prepareSchema, await readJson(req));
+ const { accept, buyer } = body;
+ if (!isSolanaNetwork(accept.network)) {
+ return error(
+ res,
+ 400,
+ 'unsupported_network',
+ `prepare only builds Solana transactions; got network=${accept.network}. EVM clients sign EIP-712 typed data locally and don't need this endpoint.`,
+ );
+ }
+
+ const conn = new Connection(rpcFor(accept.network), 'confirmed');
+ const mint = new PublicKey(accept.asset);
+ const payTo = new PublicKey(accept.payTo);
+ const feePayer = new PublicKey(accept.extra.feePayer);
+ const buyerPubkey = new PublicKey(buyer);
+ const amount = BigInt(accept.amount);
+
+ const senderAta = getAssociatedTokenAddressSync(
+ mint,
+ buyerPubkey,
+ false,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const receiverAta = getAssociatedTokenAddressSync(
+ mint,
+ payTo,
+ false,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const mintInfo = await getMint(conn, mint);
+
+ const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }),
+ ];
+ const receiverInfo = await conn.getAccountInfo(receiverAta);
+ if (!receiverInfo) {
+ ixs.push(
+ createAssociatedTokenAccountIdempotentInstruction(
+ feePayer,
+ receiverAta,
+ payTo,
+ mint,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ ),
+ );
+ }
+ ixs.push(
+ createTransferCheckedInstruction(
+ senderAta,
+ mint,
+ receiverAta,
+ buyerPubkey,
+ amount,
+ mintInfo.decimals,
+ [],
+ TOKEN_PROGRAM_ID,
+ ),
+ );
+
+ const { blockhash } = await conn.getLatestBlockhash('confirmed');
+ const message = new TransactionMessage({
+ payerKey: feePayer,
+ recentBlockhash: blockhash,
+ instructions: ixs,
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(message);
+
+ const txBase64 = Buffer.from(vtx.serialize()).toString('base64');
+ return json(res, 200, {
+ network: accept.network,
+ tx_base64: txBase64,
+ recent_blockhash: blockhash,
+ });
+}
+
+async function handleEncode(req, res) {
+ const body = parse(encodeSchema, await readJson(req));
+ const { accept, signed_tx_base64, resource_url } = body;
+ const payload = {
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: resource_url, mimeType: 'application/json' },
+ accepted: accept,
+ payload: { transaction: signed_tx_base64 },
+ };
+ const xPayment = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');
+ return json(res, 200, { x_payment: xPayment });
+}
diff --git a/api/x402-skus.js b/api/x402-skus.js
new file mode 100644
index 000000000..5cabed49e
--- /dev/null
+++ b/api/x402-skus.js
@@ -0,0 +1,197 @@
+// x402 Checkout SKUs — REST endpoint.
+//
+// A SKU is a hosted checkout link: merchant creates one in their dashboard,
+// gets a URL like /pay/c/<slug>, and shares it. The buyer-facing page opens
+// the drop-in payment modal pre-wired to the SKU's target endpoint.
+//
+// GET /api/x402-skus → list my SKUs (auth)
+// POST /api/x402-skus → create SKU (auth)
+// PATCH /api/x402-skus?id=… → update SKU (auth, owner only)
+// DELETE /api/x402-skus?id=… → archive SKU (auth, owner only)
+// GET /api/x402-skus?slug=… → public read (no auth) — what /pay/c/<slug> uses
+// GET /api/x402-skus?id=…&stats=1 → revenue/call stats (auth, owner only)
+
+import { z } from 'zod';
+import { sql } from './_lib/db.js';
+import { getSessionUser } from './_lib/auth.js';
+import { cors, json, readJson, wrap, error } from './_lib/http.js';
+import { parse } from './_lib/validate.js';
+import { clientIp, limits } from './_lib/rate-limit.js';
+
+const slugSchema = z
+ .string()
+ .trim()
+ .min(3)
+ .max(64)
+ .regex(/^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/, 'slug must be lowercase, hyphenated, 3-64 chars');
+
+const httpsUrl = z
+ .string()
+ .url()
+ .refine((v) => v.startsWith('https://') || v.startsWith('http://localhost'), 'must be https');
+
+const createSchema = z.object({
+ slug: slugSchema,
+ target_endpoint: httpsUrl,
+ target_method: z.enum(['GET', 'POST']).default('GET'),
+ target_body: z.record(z.any()).optional(),
+ merchant_name: z.string().trim().min(1).max(80),
+ action_name: z.string().trim().min(1).max(80),
+ description: z.string().trim().max(2000).optional(),
+ logo_url: httpsUrl.optional(),
+ accent_color: z.string().regex(/^#[0-9a-fA-F]{6}$/).default('#0a84ff'),
+ success_url: httpsUrl.optional(),
+});
+
+const updateSchema = createSchema.partial();
+
+export default wrap(async (req, res) => {
+ // Public reads (`?slug=` and stats for non-owner) need permissive CORS so the
+ // hosted checkout page running on a tenant subdomain can still call us.
+ if (cors(req, res, { origins: '*', methods: 'GET,POST,PATCH,DELETE,OPTIONS' })) return;
+
+ const method = req.method;
+ if (method === 'GET') return handleGet(req, res);
+ if (method === 'POST') return handleCreate(req, res);
+ if (method === 'PATCH') return handleUpdate(req, res);
+ if (method === 'DELETE') return handleArchive(req, res);
+ return error(res, 405, 'method_not_allowed', `unsupported: ${method}`);
+});
+
+async function handleGet(req, res) {
+ const { slug, id, stats } = req.query || {};
+ if (slug) {
+ // Public read for hosted checkout page.
+ const [row] = await sql`
+ select id, slug, target_endpoint, target_method, target_body,
+ merchant_name, action_name, description, logo_url, accent_color,
+ success_url
+ from x402_skus
+ where slug = ${String(slug)} and archived_at is null
+ limit 1
+ `;
+ if (!row) return error(res, 404, 'sku_not_found', `no active SKU with slug "${slug}"`);
+ return json(res, 200, { sku: row });
+ }
+
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ if (id) {
+ const [row] = await sql`
+ select id, slug, owner_user_id, target_endpoint, target_method, target_body,
+ merchant_name, action_name, description, logo_url, accent_color,
+ success_url, created_at, updated_at, archived_at
+ from x402_skus
+ where id = ${String(id)} limit 1
+ `;
+ if (!row) return error(res, 404, 'sku_not_found', 'no such SKU');
+ if (row.owner_user_id !== user.id) return error(res, 403, 'forbidden', 'not owner');
+ if (stats === '1') {
+ const calls = await sql`
+ select
+ count(*)::int as total_calls,
+ count(*) filter (where response_status < 400)::int as paid_calls,
+ coalesce(sum(case when response_status < 400 then amount_atomics::numeric else 0 end), 0)::text as gross_atomics,
+ count(distinct payer_address) filter (where payer_address is not null)::int as unique_payers,
+ max(paid_at) as last_paid_at
+ from x402_checkout_calls where sku_id = ${row.id}
+ `;
+ const recent = await sql`
+ select paid_at, network, tx_signature, payer_address, amount_atomics, asset, response_status
+ from x402_checkout_calls where sku_id = ${row.id}
+ order by paid_at desc limit 25
+ `;
+ return json(res, 200, { sku: row, stats: calls[0], recent });
+ }
+ return json(res, 200, { sku: row });
+ }
+
+ const rows = await sql`
+ select s.id, s.slug, s.target_endpoint, s.target_method,
+ s.merchant_name, s.action_name, s.accent_color,
+ s.created_at, s.updated_at,
+ (select count(*)::int from x402_checkout_calls c where c.sku_id = s.id and c.response_status < 400) as paid_calls,
+ (select coalesce(sum(amount_atomics::numeric), 0)::text from x402_checkout_calls c where c.sku_id = s.id and c.response_status < 400) as gross_atomics
+ from x402_skus s
+ where s.owner_user_id = ${user.id} and s.archived_at is null
+ order by s.created_at desc
+ `;
+ return json(res, 200, { skus: rows });
+}
+
+async function handleCreate(req, res) {
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(createSchema, await readJson(req));
+
+ // Verify the slug isn't taken (UNIQUE constraint will also catch this).
+ const [existing] = await sql`select id from x402_skus where slug = ${body.slug} limit 1`;
+ if (existing) return error(res, 409, 'slug_taken', `slug "${body.slug}" is already in use`);
+
+ const [created] = await sql`
+ insert into x402_skus (
+ owner_user_id, slug, target_endpoint, target_method, target_body,
+ merchant_name, action_name, description, logo_url, accent_color, success_url
+ ) values (
+ ${user.id}, ${body.slug}, ${body.target_endpoint}, ${body.target_method},
+ ${body.target_body ? JSON.stringify(body.target_body) : null}::jsonb,
+ ${body.merchant_name}, ${body.action_name},
+ ${body.description ?? null}, ${body.logo_url ?? null},
+ ${body.accent_color}, ${body.success_url ?? null}
+ )
+ returning id, slug, merchant_name, action_name, created_at
+ `;
+ return json(res, 201, { sku: created, url: `/pay/c/${created.slug}` });
+}
+
+async function handleUpdate(req, res) {
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const id = req.query?.id;
+ if (!id) return error(res, 400, 'missing_id', 'query param `id` required');
+
+ const [row] = await sql`select owner_user_id from x402_skus where id = ${String(id)} limit 1`;
+ if (!row) return error(res, 404, 'sku_not_found', 'no such SKU');
+ if (row.owner_user_id !== user.id) return error(res, 403, 'forbidden', 'not owner');
+
+ const patch = parse(updateSchema, await readJson(req));
+
+ const [updated] = await sql`
+ update x402_skus set
+ slug = coalesce(${patch.slug ?? null}, slug),
+ target_endpoint = coalesce(${patch.target_endpoint ?? null}, target_endpoint),
+ target_method = coalesce(${patch.target_method ?? null}, target_method),
+ target_body = coalesce(${patch.target_body ? JSON.stringify(patch.target_body) : null}::jsonb, target_body),
+ merchant_name = coalesce(${patch.merchant_name ?? null}, merchant_name),
+ action_name = coalesce(${patch.action_name ?? null}, action_name),
+ description = coalesce(${patch.description ?? null}, description),
+ logo_url = coalesce(${patch.logo_url ?? null}, logo_url),
+ accent_color = coalesce(${patch.accent_color ?? null}, accent_color),
+ success_url = coalesce(${patch.success_url ?? null}, success_url),
+ updated_at = now()
+ where id = ${String(id)}
+ returning id, slug, merchant_name, action_name, updated_at
+ `;
+ return json(res, 200, { sku: updated });
+}
+
+async function handleArchive(req, res) {
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const id = req.query?.id;
+ if (!id) return error(res, 400, 'missing_id', 'query param `id` required');
+
+ const [row] = await sql`select owner_user_id from x402_skus where id = ${String(id)} limit 1`;
+ if (!row) return error(res, 404, 'sku_not_found', 'no such SKU');
+ if (row.owner_user_id !== user.id) return error(res, 403, 'forbidden', 'not owner');
+
+ await sql`update x402_skus set archived_at = now() where id = ${String(id)}`;
+ return json(res, 200, { ok: true });
+}
diff --git a/public/dashboard/x402.html b/public/dashboard/x402.html
new file mode 100644
index 000000000..c7c9674e9
--- /dev/null
+++ b/public/dashboard/x402.html
@@ -0,0 +1,628 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width,initial-scale=1" />
+<title>x402 Checkout · Dashboard</title>
+<link rel="icon" href="/favicon.ico" />
+<style>
+ :root {
+ color-scheme: dark;
+ --bg: #0a0b10;
+ --bg-2: #0f1119;
+ --panel: #14161f;
+ --panel-2: #1a1d29;
+ --border: #232636;
+ --border-strong: #2e3447;
+ --text: #f0f2f8;
+ --muted: #8a90a8;
+ --muted-2: #6b7088;
+ --accent: #0a84ff;
+ --accent-2: #60a5fa;
+ --green: #4ade80;
+ --red: #ef4444;
+ --mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); }
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ line-height: 1.5;
+ min-height: 100dvh;
+ }
+ a { color: var(--accent-2); text-decoration: none; }
+ a:hover { color: #93c5fd; }
+
+ header {
+ display: flex; align-items: center; gap: 16px;
+ padding: 16px 28px;
+ border-bottom: 1px solid var(--border);
+ background: rgba(10, 11, 16, 0.92);
+ backdrop-filter: blur(12px);
+ position: sticky; top: 0; z-index: 10;
+ }
+ header .brand {
+ display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 15px;
+ letter-spacing: -0.01em;
+ }
+ header .brand .dot {
+ width: 22px; height: 22px;
+ background: conic-gradient(from 200deg, #ffffff, #60a5fa);
+ border-radius: 6px;
+ }
+ header .crumb { color: var(--muted); margin-left: 4px; }
+ header .right { margin-left: auto; display: flex; gap: 10px; align-items: center; }
+ .btn {
+ padding: 9px 16px;
+ background: #ffffff; color: #0a0b10;
+ border: none; border-radius: 9px;
+ font-size: 13px; font-weight: 600; font-family: inherit;
+ cursor: pointer;
+ transition: background 0.12s, transform 0.05s;
+ }
+ .btn:hover:not(:disabled) { background: #e7e9ee; }
+ .btn:active:not(:disabled) { transform: translateY(1px); }
+ .btn:disabled { opacity: 0.5; cursor: not-allowed; }
+ .btn.ghost {
+ background: var(--panel); color: var(--text);
+ border: 1px solid var(--border);
+ }
+ .btn.ghost:hover:not(:disabled) { background: var(--panel-2); border-color: var(--border-strong); }
+ .btn.danger { background: #1f1416; color: #fca5a5; border: 1px solid #7f1d1d; }
+ .btn.danger:hover:not(:disabled) { background: #2a1d20; }
+
+ .wrap { max-width: 1080px; margin: 0 auto; padding: 32px 28px 60px; }
+ @media (max-width: 640px) { .wrap { padding: 24px 18px 60px; } header { padding: 14px 18px; } }
+
+ h1 {
+ font-size: 28px; font-weight: 700; letter-spacing: -0.02em;
+ margin: 0 0 4px;
+ }
+ .sub { color: var(--muted); margin: 0 0 28px; font-size: 14px; }
+
+ .stats {
+ display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 12px; margin-bottom: 28px;
+ }
+ .stat-card {
+ background: var(--panel); border: 1px solid var(--border); border-radius: 12px;
+ padding: 18px;
+ }
+ .stat-card .k {
+ font-size: 11px; color: var(--muted); font-weight: 600;
+ text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 8px;
+ }
+ .stat-card .v {
+ font-size: 24px; font-weight: 700; letter-spacing: -0.01em;
+ font-variant-numeric: tabular-nums;
+ }
+ .stat-card .v .unit { font-size: 13px; color: var(--muted); font-weight: 500; margin-left: 4px; }
+
+ .skus-head {
+ display: flex; align-items: center; justify-content: space-between;
+ margin-bottom: 14px;
+ }
+ .skus-head h2 { margin: 0; font-size: 18px; letter-spacing: -0.01em; }
+
+ .sku-table {
+ background: var(--panel); border: 1px solid var(--border); border-radius: 14px;
+ overflow: hidden;
+ }
+ .sku-row {
+ display: grid; grid-template-columns: 1fr auto auto auto;
+ gap: 14px; padding: 14px 18px;
+ align-items: center;
+ border-bottom: 1px solid var(--border);
+ transition: background 0.1s;
+ }
+ .sku-row:hover { background: var(--panel-2); }
+ .sku-row:last-child { border-bottom: none; }
+ .sku-row .name { font-weight: 600; font-size: 14px; letter-spacing: -0.005em; }
+ .sku-row .slug { font-family: var(--mono); font-size: 11px; color: var(--muted); margin-top: 3px; }
+ .sku-row .calls { font-family: var(--mono); font-size: 12px; color: var(--muted); white-space: nowrap; }
+ .sku-row .calls strong { color: var(--text); font-size: 13px; font-weight: 700; }
+ .sku-row .revenue { font-family: var(--mono); font-size: 13px; color: var(--green); font-weight: 700; font-variant-numeric: tabular-nums; }
+ .sku-row .actions { display: flex; gap: 6px; }
+ .sku-row .actions .btn { padding: 6px 12px; font-size: 12px; }
+ @media (max-width: 640px) {
+ .sku-row { grid-template-columns: 1fr; gap: 8px; }
+ .sku-row .actions { justify-content: flex-start; }
+ }
+
+ .empty {
+ text-align: center; padding: 60px 24px;
+ color: var(--muted); font-size: 14px;
+ }
+ .empty h3 { color: var(--text); font-size: 17px; margin: 0 0 6px; }
+
+ .modal-overlay {
+ position: fixed; inset: 0;
+ background: rgba(8, 10, 18, 0.7);
+ backdrop-filter: blur(10px);
+ display: none; align-items: center; justify-content: center;
+ z-index: 100; padding: 18px;
+ }
+ .modal-overlay.show { display: flex; }
+ .modal {
+ background: var(--panel); border: 1px solid var(--border-strong);
+ border-radius: 16px; width: 100%; max-width: 520px;
+ max-height: calc(100dvh - 36px); overflow: auto;
+ box-shadow: 0 24px 80px rgba(0, 0, 0, 0.4);
+ }
+ .modal-head {
+ padding: 18px 22px; border-bottom: 1px solid var(--border);
+ display: flex; align-items: center; justify-content: space-between;
+ }
+ .modal-head h3 { margin: 0; font-size: 17px; font-weight: 700; }
+ .modal-close {
+ background: none; border: none; color: var(--muted); cursor: pointer;
+ font-size: 18px; width: 30px; height: 30px; border-radius: 7px;
+ }
+ .modal-close:hover { background: var(--panel-2); color: var(--text); }
+ .modal-body { padding: 18px 22px 22px; display: flex; flex-direction: column; gap: 14px; }
+
+ label {
+ display: flex; flex-direction: column; gap: 5px;
+ font-size: 12px; font-weight: 600; color: var(--muted);
+ text-transform: uppercase; letter-spacing: 0.03em;
+ }
+ label input, label select, label textarea {
+ background: var(--bg-2); border: 1px solid var(--border);
+ color: var(--text);
+ padding: 11px 13px; border-radius: 9px;
+ font-size: 14px; font-family: inherit;
+ text-transform: none; letter-spacing: 0; font-weight: 400;
+ outline: none;
+ transition: border-color 0.12s;
+ }
+ label input:focus, label select:focus, label textarea:focus { border-color: var(--accent); }
+ label textarea { min-height: 70px; resize: vertical; font-family: var(--mono); font-size: 12px; }
+ label .hint { font-size: 11px; color: var(--muted-2); font-weight: 500; text-transform: none; letter-spacing: 0; margin-top: -2px; }
+ .row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
+ @media (max-width: 540px) { .row-2 { grid-template-columns: 1fr; } }
+
+ .form-error {
+ padding: 10px 12px; border-radius: 8px;
+ background: #1f1416; border: 1px solid #7f1d1d; color: #fca5a5;
+ font-size: 12px; font-family: var(--mono);
+ }
+ .form-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 6px; }
+
+ /* Drawer for SKU detail */
+ .drawer {
+ position: fixed; top: 0; right: 0; bottom: 0;
+ width: 100%; max-width: 540px;
+ background: var(--panel); border-left: 1px solid var(--border);
+ transform: translateX(100%); transition: transform 0.22s ease-out;
+ z-index: 90; overflow: auto;
+ box-shadow: -24px 0 60px rgba(0, 0, 0, 0.4);
+ }
+ .drawer.show { transform: translateX(0); }
+ .drawer-head {
+ padding: 22px 24px 14px;
+ border-bottom: 1px solid var(--border);
+ }
+ .drawer-head .merchant { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 4px; }
+ .drawer-head .action-name { font-size: 22px; font-weight: 700; letter-spacing: -0.015em; }
+ .drawer-head .url {
+ margin-top: 12px; font-family: var(--mono); font-size: 12px;
+ color: var(--muted);
+ background: var(--bg-2); padding: 8px 12px; border-radius: 8px;
+ display: flex; align-items: center; gap: 8px; word-break: break-all;
+ }
+ .drawer-head .url-copy {
+ background: var(--panel); border: 1px solid var(--border); color: var(--muted);
+ font-size: 11px; padding: 4px 8px; border-radius: 5px; cursor: pointer; font-family: inherit;
+ flex: 0 0 auto;
+ }
+ .drawer-head .url-copy:hover { color: var(--text); border-color: var(--border-strong); }
+ .drawer-head .url-copy.copied { color: var(--green); border-color: var(--green); }
+ .drawer-body { padding: 18px 24px 24px; }
+ .drawer-body section { margin-bottom: 26px; }
+ .drawer-body section h4 {
+ margin: 0 0 10px; font-size: 11px; color: var(--muted);
+ text-transform: uppercase; letter-spacing: 0.06em; font-weight: 700;
+ }
+
+ .call-list { font-family: var(--mono); font-size: 12px; }
+ .call-row {
+ display: grid; grid-template-columns: 110px 1fr 100px 80px;
+ gap: 12px; padding: 8px 0; border-bottom: 1px solid var(--border);
+ align-items: center;
+ }
+ .call-row:last-child { border-bottom: none; }
+ .call-row .ago { color: var(--muted); }
+ .call-row .who { color: var(--text); word-break: break-all; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .call-row .amount { color: var(--green); text-align: right; font-weight: 600; }
+ .call-row .net { color: var(--muted-2); text-align: right; }
+
+ .drawer-actions {
+ display: flex; gap: 8px; padding: 14px 24px;
+ border-top: 1px solid var(--border);
+ position: sticky; bottom: 0; background: var(--panel);
+ }
+</style>
+</head>
+<body>
+
+<header>
+ <a class="brand" href="/x402">
+ <div class="dot"></div>
+ <span>x402</span>
+ </a>
+ <span class="crumb">/ Dashboard</span>
+ <div class="right">
+ <a href="/x402" class="btn ghost">View landing</a>
+ <button class="btn" id="newBtn">+ New SKU</button>
+ </div>
+</header>
+
+<div class="wrap">
+ <h1>Checkout SKUs</h1>
+ <p class="sub">Hosted checkout links for your paid endpoints. Each SKU gets a shareable URL — buyers pay with one click.</p>
+
+ <div class="stats" id="stats" style="display:none">
+ <div class="stat-card">
+ <div class="k">Active SKUs</div>
+ <div class="v" id="s-skus">—</div>
+ </div>
+ <div class="stat-card">
+ <div class="k">Paid calls</div>
+ <div class="v" id="s-calls">—</div>
+ </div>
+ <div class="stat-card">
+ <div class="k">Gross revenue</div>
+ <div class="v" id="s-revenue">—<span class="unit"> USDC</span></div>
+ </div>
+ </div>
+
+ <div class="skus-head">
+ <h2>Your SKUs</h2>
+ </div>
+
+ <div id="content"></div>
+</div>
+
+<!-- Create / edit modal -->
+<div class="modal-overlay" id="modal">
+ <div class="modal">
+ <div class="modal-head">
+ <h3 id="modalTitle">New SKU</h3>
+ <button class="modal-close" id="modalClose">✕</button>
+ </div>
+ <form class="modal-body" id="skuForm">
+ <label>
+ URL slug
+ <input name="slug" required pattern="^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$" placeholder="pro-summary" />
+ <span class="hint">Used in the public URL: /pay/c/&lt;slug&gt;. 3–64 chars, lowercase + hyphens.</span>
+ </label>
+ <div class="row-2">
+ <label>
+ Merchant
+ <input name="merchant_name" required maxlength="80" placeholder="Acme" />
+ </label>
+ <label>
+ Action
+ <input name="action_name" required maxlength="80" placeholder="Summarize text" />
+ </label>
+ </div>
+ <label>
+ Description
+ <textarea name="description" maxlength="2000" placeholder="What does this charge for?"></textarea>
+ <span class="hint">Optional. Shown on the hosted checkout page.</span>
+ </label>
+ <label>
+ Target endpoint
+ <input name="target_endpoint" type="url" required placeholder="https://api.acme.com/summarize" />
+ <span class="hint">A 402-enabled URL. Returns the price + a settlement receipt.</span>
+ </label>
+ <div class="row-2">
+ <label>
+ Method
+ <select name="target_method">
+ <option value="GET">GET</option>
+ <option value="POST">POST</option>
+ </select>
+ </label>
+ <label>
+ Accent color
+ <input name="accent_color" type="color" value="#0a84ff" />
+ </label>
+ </div>
+ <label id="bodyLabel" style="display:none">
+ Request body (JSON)
+ <textarea name="target_body" placeholder='{"text":"hello"}'></textarea>
+ </label>
+ <label>
+ Logo URL
+ <input name="logo_url" type="url" placeholder="https://acme.com/logo.png" />
+ <span class="hint">Optional.</span>
+ </label>
+ <label>
+ Success redirect
+ <input name="success_url" type="url" placeholder="https://acme.com/thanks" />
+ <span class="hint">Optional. Where to send the buyer after a successful payment.</span>
+ </label>
+ <div id="formError" class="form-error" style="display:none"></div>
+ <div class="form-actions">
+ <button type="button" class="btn ghost" id="cancelBtn">Cancel</button>
+ <button type="submit" class="btn" id="saveBtn">Create</button>
+ </div>
+ </form>
+ </div>
+</div>
+
+<!-- Detail drawer -->
+<aside class="drawer" id="drawer">
+ <div class="drawer-head">
+ <div class="merchant" id="d-merchant">—</div>
+ <div class="action-name" id="d-action">—</div>
+ <div class="url" id="d-url">
+ <span id="d-url-text">—</span>
+ <button class="url-copy" id="d-url-copy">copy</button>
+ </div>
+ </div>
+ <div class="drawer-body">
+ <section>
+ <h4>Performance</h4>
+ <div class="stats" style="display:grid;margin-bottom:0">
+ <div class="stat-card"><div class="k">Calls</div><div class="v" id="d-s-calls">—</div></div>
+ <div class="stat-card"><div class="k">Revenue</div><div class="v" id="d-s-revenue">—<span class="unit"> USDC</span></div></div>
+ <div class="stat-card"><div class="k">Unique payers</div><div class="v" id="d-s-payers">—</div></div>
+ </div>
+ </section>
+ <section>
+ <h4>Recent calls</h4>
+ <div class="call-list" id="d-calls"><div style="color:var(--muted);font-family:inherit;font-size:13px">No calls yet.</div></div>
+ </section>
+ <section>
+ <h4>Endpoint</h4>
+ <div class="url" id="d-endpoint">—</div>
+ </section>
+ </div>
+ <div class="drawer-actions">
+ <button class="btn ghost" id="d-edit">Edit</button>
+ <button class="btn ghost" id="d-open">Open page ↗</button>
+ <button class="btn danger" id="d-archive" style="margin-left:auto">Archive</button>
+ </div>
+</aside>
+
+<script type="module">
+ const $ = (id) => document.getElementById(id);
+ const content = $('content');
+ let cachedSkus = [];
+ let editingId = null;
+
+ function escapeHtml(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ }
+ function fmtUsdc(atomics) {
+ const n = Number(atomics || 0) / 1_000_000;
+ if (n === 0) return '0.00';
+ if (n < 0.01) return n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
+ if (n < 1) return n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
+ return n.toFixed(2);
+ }
+ function fmtAgo(ts) {
+ if (!ts) return '—';
+ const d = Math.max(0, Date.now() - new Date(ts).getTime());
+ if (d < 60_000) return `${Math.floor(d / 1000)}s ago`;
+ if (d < 3600_000) return `${Math.floor(d / 60_000)}m ago`;
+ if (d < 86400_000) return `${Math.floor(d / 3600_000)}h ago`;
+ return `${Math.floor(d / 86400_000)}d ago`;
+ }
+
+ async function loadList() {
+ try {
+ const r = await fetch('/api/x402-skus', { credentials: 'include' });
+ if (r.status === 401) {
+ renderUnauth();
+ return;
+ }
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const { skus } = await r.json();
+ cachedSkus = skus || [];
+ renderList();
+ } catch (err) {
+ content.innerHTML = `<div class="empty"><h3>Couldn't load SKUs</h3><p>${escapeHtml(err.message)}</p></div>`;
+ }
+ }
+
+ function renderUnauth() {
+ content.innerHTML = `
+ <div class="empty">
+ <h3>Sign in to manage your checkout SKUs</h3>
+ <p>Each SKU becomes a hosted /pay/c/&lt;slug&gt; URL that accepts x402 payments.</p>
+ <p style="margin-top:18px"><a class="btn ghost" href="/login?redirect=/dashboard/x402">Sign in</a></p>
+ </div>`;
+ $('stats').style.display = 'none';
+ }
+
+ function renderList() {
+ if (!cachedSkus.length) {
+ content.innerHTML = `
+ <div class="empty">
+ <h3>No SKUs yet</h3>
+ <p>Create your first checkout link — point it at any 402-enabled endpoint.</p>
+ <p style="margin-top:18px"><button class="btn" onclick="document.getElementById('newBtn').click()">+ Create SKU</button></p>
+ </div>`;
+ $('stats').style.display = 'none';
+ return;
+ }
+ // roll-up stats
+ const totalCalls = cachedSkus.reduce((s, x) => s + (x.paid_calls || 0), 0);
+ const totalAtomics = cachedSkus.reduce((s, x) => s + Number(x.gross_atomics || 0), 0);
+ $('s-skus').textContent = cachedSkus.length;
+ $('s-calls').textContent = totalCalls;
+ $('s-revenue').innerHTML = `${fmtUsdc(totalAtomics)}<span class="unit"> USDC</span>`;
+ $('stats').style.display = 'grid';
+
+ content.innerHTML = `<div class="sku-table">${cachedSkus.map((s) => `
+ <div class="sku-row" data-id="${s.id}">
+ <div>
+ <div class="name">${escapeHtml(s.merchant_name)} · ${escapeHtml(s.action_name)}</div>
+ <div class="slug">/pay/c/${escapeHtml(s.slug)}</div>
+ </div>
+ <div class="calls"><strong>${s.paid_calls || 0}</strong> calls</div>
+ <div class="revenue">${fmtUsdc(s.gross_atomics)}</div>
+ <div class="actions">
+ <button class="btn ghost" data-act="open">Details</button>
+ </div>
+ </div>
+ `).join('')}</div>`;
+ content.querySelectorAll('.sku-row').forEach((row) => {
+ const id = row.dataset.id;
+ row.querySelector('[data-act="open"]').addEventListener('click', () => openDrawer(id));
+ });
+ }
+
+ // ─── Modal (create / edit) ───
+ const modal = $('modal');
+ const modalTitle = $('modalTitle');
+ const skuForm = $('skuForm');
+ const saveBtn = $('saveBtn');
+ const formError = $('formError');
+ const bodyLabel = $('bodyLabel');
+
+ function openModal(sku) {
+ editingId = sku?.id || null;
+ modalTitle.textContent = sku ? 'Edit SKU' : 'New SKU';
+ saveBtn.textContent = sku ? 'Save' : 'Create';
+ formError.style.display = 'none';
+ skuForm.reset();
+ if (sku) {
+ for (const [k, v] of Object.entries(sku)) {
+ if (k === 'target_body' && v) skuForm.target_body.value = JSON.stringify(v, null, 2);
+ else if (skuForm[k] != null && v != null) skuForm[k].value = v;
+ }
+ }
+ toggleBody();
+ modal.classList.add('show');
+ }
+ function closeModal() {
+ modal.classList.remove('show');
+ editingId = null;
+ }
+ function toggleBody() {
+ bodyLabel.style.display = skuForm.target_method.value === 'POST' ? '' : 'none';
+ }
+ skuForm.target_method.addEventListener('change', toggleBody);
+
+ $('newBtn').addEventListener('click', () => openModal(null));
+ $('modalClose').addEventListener('click', closeModal);
+ $('cancelBtn').addEventListener('click', closeModal);
+ modal.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });
+
+ skuForm.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ formError.style.display = 'none';
+ saveBtn.disabled = true;
+ try {
+ const fd = new FormData(skuForm);
+ const payload = Object.fromEntries(fd.entries());
+ // Drop empties so PATCH doesn't clobber existing values.
+ for (const k of Object.keys(payload)) if (payload[k] === '') delete payload[k];
+ if (payload.target_body) {
+ try { payload.target_body = JSON.parse(payload.target_body); }
+ catch { throw new Error('Request body must be valid JSON.'); }
+ } else delete payload.target_body;
+
+ const url = editingId ? `/api/x402-skus?id=${editingId}` : '/api/x402-skus';
+ const method = editingId ? 'PATCH' : 'POST';
+ const r = await fetch(url, {
+ method, credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ const data = await r.json();
+ if (!r.ok) throw new Error(data.error_description || data.error || `HTTP ${r.status}`);
+ closeModal();
+ await loadList();
+ } catch (err) {
+ formError.textContent = err.message;
+ formError.style.display = '';
+ } finally {
+ saveBtn.disabled = false;
+ }
+ });
+
+ // ─── Drawer (detail) ───
+ const drawer = $('drawer');
+ let openSkuId = null;
+ async function openDrawer(id) {
+ openSkuId = id;
+ drawer.classList.add('show');
+ try {
+ const r = await fetch(`/api/x402-skus?id=${id}&stats=1`, { credentials: 'include' });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const { sku, stats, recent } = await r.json();
+ renderDrawer(sku, stats, recent);
+ } catch (err) {
+ $('d-calls').innerHTML = `<div class="form-error">${escapeHtml(err.message)}</div>`;
+ }
+ }
+ function closeDrawer() {
+ drawer.classList.remove('show');
+ openSkuId = null;
+ }
+ function renderDrawer(sku, stats, recent) {
+ $('d-merchant').textContent = sku.merchant_name;
+ $('d-action').textContent = sku.action_name;
+ const publicUrl = `${location.origin}/pay/c/${sku.slug}`;
+ $('d-url-text').textContent = publicUrl;
+ $('d-url-copy').onclick = async () => {
+ await navigator.clipboard.writeText(publicUrl);
+ $('d-url-copy').textContent = '✓';
+ $('d-url-copy').classList.add('copied');
+ setTimeout(() => { $('d-url-copy').textContent = 'copy'; $('d-url-copy').classList.remove('copied'); }, 1600);
+ };
+ $('d-s-calls').textContent = stats.paid_calls || 0;
+ $('d-s-revenue').innerHTML = `${fmtUsdc(stats.gross_atomics)}<span class="unit"> USDC</span>`;
+ $('d-s-payers').textContent = stats.unique_payers || 0;
+ $('d-endpoint').innerHTML = `<span style="word-break:break-all">${escapeHtml(sku.target_method)} ${escapeHtml(sku.target_endpoint)}</span>`;
+ if (recent?.length) {
+ $('d-calls').innerHTML = recent.map((c) => {
+ const netLabel = c.network?.startsWith('solana') ? 'sol' : c.network === 'eip155:8453' ? 'base' : c.network?.slice(0, 8);
+ const explorer = c.tx_signature
+ ? (c.network?.startsWith('solana') ? `https://solscan.io/tx/${c.tx_signature}` : `https://basescan.org/tx/${c.tx_signature}`)
+ : null;
+ const who = c.payer_address ? `${c.payer_address.slice(0, 6)}…${c.payer_address.slice(-4)}` : '—';
+ return `<div class="call-row">
+ <span class="ago">${fmtAgo(c.paid_at)}</span>
+ <span class="who">${escapeHtml(who)}</span>
+ <span class="amount">${fmtUsdc(c.amount_atomics)}</span>
+ <span class="net">${explorer ? `<a href="${explorer}" target="_blank">${netLabel} ↗</a>` : escapeHtml(netLabel || '—')}</span>
+ </div>`;
+ }).join('');
+ } else {
+ $('d-calls').innerHTML = `<div style="color:var(--muted);font-family:inherit;font-size:13px">No calls yet. Share your link to start collecting.</div>`;
+ }
+ $('d-edit').onclick = () => { closeDrawer(); openModal(sku); };
+ $('d-open').onclick = () => window.open(publicUrl, '_blank');
+ $('d-archive').onclick = async () => {
+ if (!confirm(`Archive "${sku.merchant_name} · ${sku.action_name}"? The link will stop working.`)) return;
+ const r = await fetch(`/api/x402-skus?id=${sku.id}`, { method: 'DELETE', credentials: 'include' });
+ if (r.ok) { closeDrawer(); await loadList(); }
+ else alert('Archive failed: ' + (await r.text()));
+ };
+ }
+
+ // Click outside drawer to close
+ document.addEventListener('click', (e) => {
+ if (!drawer.classList.contains('show')) return;
+ if (drawer.contains(e.target)) return;
+ if (e.target.closest('.sku-row')) return;
+ closeDrawer();
+ });
+ document.addEventListener('keydown', (e) => {
+ if (e.key !== 'Escape') return;
+ if (drawer.classList.contains('show')) closeDrawer();
+ if (modal.classList.contains('show')) closeModal();
+ });
+
+ loadList();
+</script>
+
+</body>
+</html>
diff --git a/public/pay/c/index.html b/public/pay/c/index.html
new file mode 100644
index 000000000..4438e5cce
--- /dev/null
+++ b/public/pay/c/index.html
@@ -0,0 +1,351 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width,initial-scale=1" />
+<title>Checkout · x402</title>
+<meta name="description" content="Hosted x402 payment checkout. Pay with USDC on Base or Solana." />
+<meta name="theme-color" content="#0a0b10" />
+<style>
+ :root {
+ --bg: #fafbfc;
+ --text: #0d0f15;
+ --muted: #5a6378;
+ --muted-2: #8a90a8;
+ --border: #e2e5ec;
+ --panel: #ffffff;
+ --accent: #0a84ff;
+ --mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;
+ }
+ @media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #0a0b10;
+ --text: #f0f2f8;
+ --muted: #b0b6cc;
+ --muted-2: #6b7088;
+ --border: #232636;
+ --panel: #14161f;
+ }
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); min-height: 100%; }
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ line-height: 1.55;
+ display: flex; flex-direction: column; min-height: 100dvh;
+ }
+ .wrap {
+ flex: 1;
+ max-width: 520px; margin: 0 auto; padding: 40px 24px;
+ width: 100%;
+ display: flex; flex-direction: column; gap: 28px;
+ }
+ .card {
+ background: var(--panel); border: 1px solid var(--border); border-radius: 18px;
+ padding: 32px;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04), 0 8px 32px rgba(0, 0, 0, 0.04);
+ }
+ .head { display: flex; align-items: center; gap: 14px; margin-bottom: 24px; }
+ .logo {
+ width: 56px; height: 56px; flex: 0 0 auto;
+ border-radius: 14px;
+ background: linear-gradient(135deg, var(--accent), #60a5fa);
+ display: flex; align-items: center; justify-content: center;
+ font-weight: 700; font-size: 22px; color: #fff;
+ overflow: hidden;
+ }
+ .logo img { width: 100%; height: 100%; object-fit: cover; }
+ .head .who { min-width: 0; flex: 1; }
+ .head .merchant {
+ font-size: 13px; font-weight: 600; color: var(--muted);
+ letter-spacing: 0.02em; text-transform: uppercase;
+ margin-bottom: 4px;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+ }
+ .head .action { font-size: 22px; font-weight: 700; letter-spacing: -0.015em; }
+
+ .description {
+ color: var(--muted); font-size: 14px;
+ padding: 16px 0; border-top: 1px solid var(--border);
+ margin-top: 8px;
+ white-space: pre-wrap;
+ }
+
+ .pay-btn {
+ width: 100%; padding: 16px;
+ background: #0d0f15; color: #fff;
+ border: none; border-radius: 12px;
+ font-size: 15px; font-weight: 700; font-family: inherit;
+ cursor: pointer; letter-spacing: -0.005em;
+ transition: background 0.12s, transform 0.05s;
+ margin-top: 8px;
+ }
+ @media (prefers-color-scheme: dark) {
+ .pay-btn { background: #ffffff; color: #0d0f15; }
+ .pay-btn:hover:not(:disabled) { background: #e7e9ee; }
+ }
+ .pay-btn:hover:not(:disabled) { background: #1a1d28; }
+ .pay-btn:active:not(:disabled) { transform: translateY(1px); }
+ .pay-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+
+ .meta-row {
+ display: flex; justify-content: space-between; gap: 12px;
+ padding: 10px 0; font-size: 13px;
+ }
+ .meta-row + .meta-row { border-top: 1px solid var(--border); }
+ .meta-row .k { color: var(--muted); }
+ .meta-row .v { color: var(--text); font-family: var(--mono); font-size: 12px; }
+
+ .error {
+ padding: 14px; border-radius: 10px;
+ background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c;
+ font-size: 13px;
+ }
+
+ .result {
+ margin-top: 16px;
+ padding: 14px; border-radius: 12px;
+ background: linear-gradient(180deg, #f0fdf4 0%, transparent 100%);
+ border: 1px solid #bbf7d0;
+ font-size: 13px;
+ }
+ @media (prefers-color-scheme: dark) {
+ .result { background: linear-gradient(180deg, #0b1f17 0%, transparent 100%); border-color: #14532d; }
+ }
+ .result h3 {
+ margin: 0 0 8px; font-size: 12px; font-weight: 700;
+ text-transform: uppercase; letter-spacing: 0.06em; color: #15803d;
+ }
+ @media (prefers-color-scheme: dark) { .result h3 { color: #4ade80; } }
+ .result pre {
+ margin: 8px 0 0; padding: 10px; border-radius: 8px;
+ background: var(--bg); border: 1px solid var(--border);
+ font-family: var(--mono); font-size: 12px; line-height: 1.5;
+ max-height: 280px; overflow: auto;
+ white-space: pre-wrap; word-break: break-word;
+ }
+
+ footer {
+ padding: 14px 24px 22px;
+ font-size: 11px; color: var(--muted-2);
+ text-align: center;
+ }
+ footer a { color: var(--muted); text-decoration: none; font-weight: 600; }
+ footer a:hover { color: var(--text); }
+
+ .skeleton {
+ background: linear-gradient(90deg, transparent, rgba(255,255,255,0.06), transparent);
+ background-size: 200% 100%;
+ animation: shimmer 1.4s linear infinite;
+ }
+ @keyframes shimmer {
+ from { background-position: 200% 0; }
+ to { background-position: -200% 0; }
+ }
+ @media (prefers-color-scheme: light) {
+ .skeleton { background: linear-gradient(90deg, transparent, rgba(0,0,0,0.06), transparent); background-size: 200% 100%; }
+ }
+</style>
+</head>
+<body>
+
+<div class="wrap">
+ <div class="card" id="card">
+ <div class="head">
+ <div class="logo" id="logo">·</div>
+ <div class="who">
+ <div class="merchant" id="merchantName">Loading…</div>
+ <div class="action" id="actionName">&nbsp;</div>
+ </div>
+ </div>
+ <div class="description" id="description" style="display:none"></div>
+ <div id="meta"></div>
+ <button class="pay-btn" id="payBtn" disabled>Loading…</button>
+ <div id="result"></div>
+ </div>
+</div>
+
+<footer>
+ Secured by x402 · on-chain settlement · <a href="/x402" target="_blank">about</a>
+</footer>
+
+<script type="module" src="/x402.js"></script>
+<script>
+ const SLUG = location.pathname.replace(/^\/pay\/c\//, '').replace(/\/$/, '');
+ const $ = (id) => document.getElementById(id);
+
+ function escapeHtml(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ }
+
+ async function loadSku() {
+ if (!SLUG) {
+ renderError('No checkout link supplied. URL should be /pay/c/<slug>.');
+ return;
+ }
+ try {
+ const res = await fetch(`/api/x402-skus?slug=${encodeURIComponent(SLUG)}`);
+ if (!res.ok) {
+ const e = await res.json().catch(() => ({}));
+ throw new Error(e.error_description || `Checkout "${SLUG}" not found (${res.status}).`);
+ }
+ const { sku } = await res.json();
+ renderSku(sku);
+ await loadPrice(sku);
+ } catch (err) {
+ renderError(err.message);
+ }
+ }
+
+ function renderSku(sku) {
+ document.title = `${sku.merchant_name} · ${sku.action_name} — x402 checkout`;
+ $('merchantName').textContent = sku.merchant_name;
+ $('actionName').textContent = sku.action_name;
+ if (sku.logo_url) $('logo').innerHTML = `<img src="${escapeHtml(sku.logo_url)}" alt="" onerror="this.replaceWith(document.createTextNode('${escapeHtml(sku.merchant_name[0] || '·')}'))">`;
+ else $('logo').textContent = sku.merchant_name[0] || '·';
+ if (sku.accent_color) {
+ document.documentElement.style.setProperty('--accent', sku.accent_color);
+ $('logo').style.background = `linear-gradient(135deg, ${sku.accent_color}, ${sku.accent_color}cc)`;
+ }
+ if (sku.description) {
+ $('description').textContent = sku.description;
+ $('description').style.display = '';
+ }
+ const payBtn = $('payBtn');
+ payBtn.textContent = `Pay · ${sku.action_name}`;
+ payBtn.disabled = false;
+ payBtn.addEventListener('click', () => runCheckout(sku));
+ }
+
+ async function loadPrice(sku) {
+ // Probe the target endpoint to read the price + supported networks for
+ // display, so the buyer sees the cost before clicking Pay.
+ try {
+ const init = {
+ method: sku.target_method,
+ body: sku.target_body ? JSON.stringify(sku.target_body) : undefined,
+ headers: sku.target_body ? { 'content-type': 'application/json' } : undefined,
+ };
+ const res = await fetch(sku.target_endpoint, init);
+ if (res.status !== 402) {
+ renderMeta(`<div class="error">This SKU's endpoint did not return 402 (got ${res.status}). The endpoint may have changed.</div>`);
+ return;
+ }
+ const challenge = await res.json();
+ const accepts = challenge?.accepts || [];
+ renderMeta(metaHtml(accepts));
+ } catch (err) {
+ renderMeta(`<div class="error">Couldn't reach the endpoint: ${escapeHtml(err.message)}</div>`);
+ }
+ }
+
+ function metaHtml(accepts) {
+ const networks = accepts.map((a) => {
+ const decimals = a.extra?.decimals ?? 6;
+ const amount = Number(a.amount) / 10 ** decimals;
+ const formatted = amount < 0.01 ? amount.toFixed(6).replace(/0+$/, '').replace(/\.$/, '') : amount < 1 ? amount.toFixed(4).replace(/0+$/, '').replace(/\.$/, '') : amount.toFixed(2);
+ const netLabel = a.network.startsWith('solana') ? 'Solana' : a.network === 'eip155:8453' ? 'Base' : a.network === 'eip155:42161' ? 'Arbitrum' : a.network;
+ return `<div class="meta-row"><span class="k">${escapeHtml(netLabel)}</span><span class="v">${formatted} USDC</span></div>`;
+ }).join('');
+ return networks;
+ }
+
+ function renderMeta(html) {
+ $('meta').innerHTML = html;
+ }
+
+ function renderError(msg) {
+ $('merchantName').textContent = 'Checkout unavailable';
+ $('actionName').textContent = ' ';
+ $('logo').textContent = '!';
+ $('meta').innerHTML = `<div class="error">${escapeHtml(msg)}</div>`;
+ $('payBtn').style.display = 'none';
+ }
+
+ async function runCheckout(sku) {
+ if (!window.X402?.pay) {
+ renderError('Payment script failed to load. Refresh the page.');
+ return;
+ }
+ try {
+ const out = await window.X402.pay({
+ endpoint: sku.target_endpoint,
+ method: sku.target_method,
+ body: sku.target_body,
+ merchant: sku.merchant_name,
+ action: sku.action_name,
+ });
+ recordCall(sku, out, 200);
+ if (sku.success_url) {
+ const sep = sku.success_url.includes('?') ? '&' : '?';
+ location.href = `${sku.success_url}${sep}x402_tx=${encodeURIComponent(out.payment?.transaction || '')}&x402_payer=${encodeURIComponent(out.payment?.payer || '')}`;
+ return;
+ }
+ renderResult(out);
+ } catch (err) {
+ if (err?.code === 'cancelled') return;
+ recordCall(sku, null, 500, err?.message);
+ renderError(err?.message || String(err));
+ }
+ }
+
+ function renderResult(out) {
+ const resultStr = typeof out.result === 'string' ? out.result : JSON.stringify(out.result, null, 2);
+ const explorer = out.payment?.transaction
+ ? (out.payment.network?.startsWith('solana')
+ ? `https://solscan.io/tx/${out.payment.transaction}`
+ : `https://basescan.org/tx/${out.payment.transaction}`)
+ : null;
+ $('result').innerHTML = `
+ <div class="result">
+ <h3>✓ Paid</h3>
+ <div class="meta-row"><span class="k">network</span><span class="v">${escapeHtml(out.payment?.network || '—')}</span></div>
+ <div class="meta-row"><span class="k">payer</span><span class="v">${escapeHtml(out.payment?.payer ? out.payment.payer.slice(0,8) + '…' + out.payment.payer.slice(-6) : '—')}</span></div>
+ ${explorer ? `<div class="meta-row"><span class="k">tx</span><span class="v"><a href="${explorer}" target="_blank" rel="noopener">view on explorer ↗</a></span></div>` : ''}
+ <pre>${escapeHtml(resultStr).slice(0, 4000)}</pre>
+ </div>`;
+ }
+
+ async function recordCall(sku, out, status, errCode) {
+ if (!sku?.id) return;
+ try {
+ // Read the original 402 challenge accepts to learn amount + asset; we
+ // have it from the loadPrice probe — refetch is cheap and decouples this
+ // from challenge state.
+ const res = await fetch(sku.target_endpoint, {
+ method: sku.target_method,
+ body: sku.target_body ? JSON.stringify(sku.target_body) : undefined,
+ headers: sku.target_body ? { 'content-type': 'application/json' } : undefined,
+ });
+ let amount = '0', asset = '';
+ if (res.status === 402) {
+ const ch = await res.json();
+ const accept = ch.accepts?.find((a) => a.network === out?.payment?.network) || ch.accepts?.[0];
+ if (accept) { amount = accept.amount; asset = accept.asset; }
+ }
+ await fetch('/api/x402-checkout-record', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ sku_id: sku.id,
+ network: out?.payment?.network || 'unknown',
+ tx_signature: out?.payment?.transaction || undefined,
+ payer_address: out?.payment?.payer || undefined,
+ amount_atomics: amount,
+ asset,
+ response_status: status,
+ error_code: errCode || undefined,
+ }),
+ });
+ } catch (e) {
+ // Recording is best-effort — never block the buyer's success path.
+ console.warn('[x402-checkout] failed to record call:', e?.message);
+ }
+ }
+
+ loadSku();
+</script>
+
+</body>
+</html>
diff --git a/public/x402-stripe.html b/public/x402-stripe.html
new file mode 100644
index 000000000..2d5d193d5
--- /dev/null
+++ b/public/x402-stripe.html
@@ -0,0 +1,471 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width,initial-scale=1" />
+<title>x402 — payments, drop-in</title>
+<meta name="description" content="The simplest way to accept x402 stablecoin payments. One <script> tag, a clean modal, on-chain settlement on Base and Solana." />
+<meta name="theme-color" content="#0a0b10" />
+<meta property="og:title" content="x402 — payments, drop-in" />
+<meta property="og:description" content="One <script> tag. Clean modal. On-chain x402 settlement on Base and Solana." />
+<meta property="og:type" content="website" />
+<style>
+ :root {
+ --bg: #0a0b10;
+ --bg-2: #0f1119;
+ --panel: #14161f;
+ --panel-2: #1a1d29;
+ --border: #232636;
+ --border-strong: #2e3447;
+ --text: #f0f2f8;
+ --muted: #8a90a8;
+ --muted-2: #6b7088;
+ --accent: #ffffff;
+ --accent-blue: #60a5fa;
+ --accent-green: #4ade80;
+ --mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); }
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ font-feature-settings: 'cv11' 1, 'ss03' 1;
+ -webkit-font-smoothing: antialiased;
+ line-height: 1.5;
+ }
+ a { color: var(--accent-blue); text-decoration: none; }
+ a:hover { color: #93c5fd; }
+
+ .wrap { max-width: 1080px; margin: 0 auto; padding: 0 28px; }
+ @media (max-width: 640px) { .wrap { padding: 0 18px; } }
+
+ nav {
+ padding: 22px 0;
+ display: flex; align-items: center; justify-content: space-between;
+ }
+ nav .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 15px; letter-spacing: -0.01em; }
+ nav .brand .dot {
+ width: 24px; height: 24px;
+ background: conic-gradient(from 200deg, #ffffff, #60a5fa, #ffffff);
+ border-radius: 7px;
+ }
+ nav .links { display: flex; gap: 22px; font-size: 13px; color: var(--muted); }
+ nav .links a { color: var(--muted); }
+ nav .links a:hover { color: var(--text); }
+ @media (max-width: 540px) { nav .links { display: none; } }
+
+ /* Hero */
+ .hero { padding: 80px 0 64px; }
+ .hero h1 {
+ font-size: clamp(40px, 6vw, 64px); line-height: 1.04;
+ margin: 0 0 22px; font-weight: 800; letter-spacing: -0.03em;
+ max-width: 18ch;
+ }
+ .hero h1 .grad {
+ background: linear-gradient(120deg, #ffffff 30%, #60a5fa 60%, #4ade80 90%);
+ -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent;
+ }
+ .hero p.lede {
+ font-size: 19px; color: var(--muted); margin: 0 0 32px;
+ max-width: 60ch; line-height: 1.55;
+ }
+ .hero .cta-row { display: flex; gap: 12px; flex-wrap: wrap; }
+ .btn {
+ display: inline-flex; align-items: center; gap: 8px;
+ padding: 13px 22px;
+ background: #ffffff; color: #0a0b10;
+ border: none; border-radius: 11px;
+ font-size: 14px; font-weight: 600; font-family: inherit;
+ cursor: pointer; letter-spacing: -0.005em;
+ text-decoration: none;
+ transition: transform 0.06s, background 0.12s;
+ }
+ .btn:hover { background: #e7e9ee; color: #0a0b10; }
+ .btn:active { transform: translateY(1px); }
+ .btn.ghost {
+ background: transparent; color: var(--text);
+ border: 1px solid var(--border-strong);
+ }
+ .btn.ghost:hover { background: var(--panel); color: var(--text); }
+
+ /* Network badges row */
+ .networks {
+ display: flex; gap: 18px; flex-wrap: wrap; align-items: center;
+ margin-top: 40px;
+ padding-top: 24px; border-top: 1px solid var(--border);
+ font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em;
+ }
+ .networks .pill {
+ display: inline-flex; align-items: center; gap: 8px;
+ padding: 7px 13px; border-radius: 99px;
+ background: var(--panel); border: 1px solid var(--border);
+ font-family: var(--mono); font-size: 11px; color: var(--text);
+ text-transform: none; letter-spacing: 0;
+ }
+ .networks .pill .led {
+ width: 6px; height: 6px; border-radius: 50%;
+ background: var(--accent-green); box-shadow: 0 0 6px var(--accent-green);
+ }
+
+ /* Section heading */
+ section { padding: 56px 0; }
+ section.alt { background: linear-gradient(180deg, transparent, var(--bg-2)); }
+ section h2 {
+ font-size: 32px; font-weight: 700; letter-spacing: -0.02em;
+ margin: 0 0 14px;
+ }
+ section h2 .num { color: var(--muted-2); font-weight: 500; margin-right: 12px; font-variant-numeric: tabular-nums; }
+ section p.sub {
+ font-size: 16px; color: var(--muted); margin: 0 0 32px; max-width: 60ch;
+ }
+
+ /* Snippet */
+ .snippet {
+ background: #0d0f15; border: 1px solid var(--border); border-radius: 14px;
+ padding: 18px 22px;
+ font-family: var(--mono); font-size: 13px; line-height: 1.65;
+ color: #c8ccd4; white-space: pre;
+ overflow-x: auto;
+ position: relative;
+ }
+ .snippet .k { color: #a78bfa; }
+ .snippet .s { color: #6ee7b7; }
+ .snippet .n { color: var(--muted); }
+ .snippet .a { color: #fbbf24; }
+ .snippet .c { color: var(--muted-2); }
+ .snippet .copy-btn {
+ position: absolute; top: 10px; right: 10px;
+ background: var(--panel-2); border: 1px solid var(--border);
+ color: var(--muted); font-size: 11px;
+ padding: 5px 10px; border-radius: 6px; cursor: pointer;
+ font-family: inherit;
+ }
+ .snippet .copy-btn:hover { color: var(--text); border-color: var(--border-strong); }
+ .snippet .copy-btn.copied { color: var(--accent-green); border-color: var(--accent-green); }
+
+ /* SKU grid */
+ .sku-grid {
+ display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
+ gap: 14px;
+ }
+ .sku-card {
+ background: var(--panel); border: 1px solid var(--border); border-radius: 14px;
+ padding: 22px;
+ display: flex; flex-direction: column; gap: 12px;
+ transition: border-color 0.15s, transform 0.08s;
+ }
+ .sku-card:hover { border-color: var(--border-strong); }
+ .sku-card .head {
+ display: flex; align-items: flex-start; justify-content: space-between; gap: 12px;
+ }
+ .sku-card .title { font-weight: 700; font-size: 17px; letter-spacing: -0.01em; }
+ .sku-card .price {
+ font-family: var(--mono); font-size: 13px;
+ background: var(--bg-2); border: 1px solid var(--border);
+ padding: 4px 10px; border-radius: 6px; color: var(--accent-green);
+ flex: 0 0 auto;
+ }
+ .sku-card .desc {
+ color: var(--muted); font-size: 13px; line-height: 1.55;
+ flex: 1; min-height: 56px;
+ }
+ .sku-card .net {
+ font-family: var(--mono); font-size: 11px; color: var(--muted-2);
+ display: flex; gap: 10px;
+ }
+ .sku-card .buy {
+ padding: 12px 16px;
+ background: #ffffff; color: #0a0b10;
+ border: none; border-radius: 10px;
+ font-size: 14px; font-weight: 600; font-family: inherit;
+ cursor: pointer; letter-spacing: -0.005em;
+ transition: background 0.12s, transform 0.05s;
+ }
+ .sku-card .buy:hover { background: #e7e9ee; }
+ .sku-card .buy:active { transform: translateY(1px); }
+
+ .result-panel {
+ margin-top: 12px;
+ display: none;
+ background: var(--bg-2); border: 1px solid var(--border); border-radius: 10px;
+ padding: 12px 14px;
+ font-family: var(--mono); font-size: 12px; line-height: 1.55;
+ color: var(--text); max-height: 220px; overflow: auto;
+ white-space: pre-wrap; word-break: break-word;
+ }
+ .result-panel.show { display: block; }
+ .result-panel .ok { color: var(--accent-green); font-weight: 600; }
+ .result-panel .err { color: #fca5a5; font-weight: 600; }
+
+ /* Steps */
+ .steps {
+ display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px;
+ }
+ @media (max-width: 740px) { .steps { grid-template-columns: 1fr; } }
+ .step-card {
+ background: var(--panel); border: 1px solid var(--border); border-radius: 14px;
+ padding: 22px;
+ }
+ .step-card .num {
+ display: inline-flex; width: 28px; height: 28px;
+ align-items: center; justify-content: center;
+ background: linear-gradient(135deg, #ffffff, #60a5fa); color: #0a0b10;
+ border-radius: 8px; font-weight: 700; font-size: 13px;
+ margin-bottom: 14px;
+ }
+ .step-card h3 { margin: 0 0 6px; font-size: 16px; letter-spacing: -0.01em; }
+ .step-card p { margin: 0; color: var(--muted); font-size: 13px; line-height: 1.55; }
+
+ /* Footer */
+ footer {
+ border-top: 1px solid var(--border);
+ padding: 32px 0 48px;
+ display: flex; align-items: center; justify-content: space-between;
+ font-size: 12px; color: var(--muted);
+ }
+ footer .left { display: flex; align-items: center; gap: 10px; }
+ footer .dot {
+ width: 18px; height: 18px;
+ background: conic-gradient(from 200deg, #ffffff, #60a5fa, #ffffff);
+ border-radius: 5px;
+ }
+ footer .right { display: flex; gap: 18px; }
+ footer .right a { color: var(--muted); }
+ footer .right a:hover { color: var(--text); }
+
+ .toast {
+ position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);
+ background: var(--panel); border: 1px solid var(--border);
+ padding: 12px 18px; border-radius: 10px;
+ font-size: 13px;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
+ display: none;
+ }
+ .toast.show { display: block; }
+</style>
+</head>
+<body>
+
+<div class="wrap">
+ <nav>
+ <a class="brand" href="/x402">
+ <div class="dot"></div>
+ <span>x402</span>
+ </a>
+ <div class="links">
+ <a href="#install">Install</a>
+ <a href="#demo">Demo</a>
+ <a href="/docs/x402" target="_blank">Docs</a>
+ <a href="https://www.x402scan.com/server/17cbd874-52ac-4920-a020-b22ff2489a07" target="_blank">Live activity ↗</a>
+ </div>
+ </nav>
+
+ <section class="hero">
+ <h1>x402 payments,<br /><span class="grad">drop-in.</span></h1>
+ <p class="lede">
+ One <code style="background:var(--panel);padding:2px 6px;border-radius:4px;font-family:var(--mono);font-size:0.9em;">&lt;script&gt;</code> tag. A clean modal. Stablecoin payments on Base and Solana, settled on-chain in seconds. No keys, no signup, no SDK to learn. Built on the <a href="https://x402.org" target="_blank">x402 protocol</a>.
+ </p>
+ <div class="cta-row">
+ <a class="btn" href="#install">Get the snippet</a>
+ <a class="btn ghost" href="#demo">Try a live payment</a>
+ </div>
+ <div class="networks">
+ <span>Settles on</span>
+ <span class="pill"><span class="led"></span>Base mainnet · USDC</span>
+ <span class="pill"><span class="led"></span>Solana mainnet · USDC</span>
+ </div>
+ </section>
+
+ <section id="install">
+ <h2><span class="num">01</span>Install</h2>
+ <p class="sub">Paste one line into your <code style="font-family:var(--mono);">&lt;head&gt;</code>. Then add <code style="font-family:var(--mono);">data-x402-endpoint</code> to any button. That's it.</p>
+ <div class="snippet" id="installSnippet"><button class="copy-btn" data-copy="installSnippetCode">Copy</button><span id="installSnippetCode"><span class="c">&lt;!-- 1. Load once --&gt;</span>
+<span class="k">&lt;script</span> <span class="a">type</span>=<span class="s">"module"</span> <span class="a">src</span>=<span class="s">"https://3d.irish/x402.js"</span><span class="k">&gt;&lt;/script&gt;</span>
+
+<span class="c">&lt;!-- 2. Add a button to any 402-paid endpoint --&gt;</span>
+<span class="k">&lt;button</span>
+ <span class="a">data-x402-endpoint</span>=<span class="s">"https://three.ws/api/x402/symbol-availability?ticker=AGENT"</span>
+ <span class="a">data-x402-merchant</span>=<span class="s">"three.ws"</span>
+ <span class="a">data-x402-action</span>=<span class="s">"Check ticker availability"</span><span class="k">&gt;</span>
+ Check AGENT availability · $0.001 USDC
+<span class="k">&lt;/button&gt;</span></span></div>
+ </section>
+
+ <section id="how" class="alt">
+ <h2><span class="num">02</span>How it works</h2>
+ <p class="sub">x402 is HTTP 402 Payment Required, with a manifest. The drop-in handles the entire dance — you never see it.</p>
+ <div class="steps">
+ <div class="step-card">
+ <div class="num">1</div>
+ <h3>Buyer clicks</h3>
+ <p>The modal opens. We probe your endpoint, parse the 402 challenge, and show the price + network.</p>
+ </div>
+ <div class="step-card">
+ <div class="num">2</div>
+ <h3>Wallet signs</h3>
+ <p>Phantom for Solana, MetaMask/Coinbase for Base. We build the SPL transfer or EIP-3009 authorization. One click.</p>
+ </div>
+ <div class="step-card">
+ <div class="num">3</div>
+ <h3>Facilitator settles</h3>
+ <p>PayAI or Coinbase CDP verifies and broadcasts the tx on-chain. Your endpoint runs and returns the result.</p>
+ </div>
+ </div>
+ </section>
+
+ <section id="demo">
+ <h2><span class="num">03</span>Try it live</h2>
+ <p class="sub">These are real paid endpoints. Pay $0.001 USDC with Phantom or your browser wallet and see the response stream back.</p>
+ <div class="sku-grid">
+
+ <div class="sku-card">
+ <div class="head">
+ <div class="title">Symbol availability</div>
+ <div class="price">$0.001</div>
+ </div>
+ <div class="desc">Check if a token ticker is already trading across Solana and Base. Returns exact matches, fuzzy lookalikes, and a register/skip recommendation.</div>
+ <div class="net">Base · Solana</div>
+ <button class="buy"
+ data-x402-endpoint="/api/x402/symbol-availability?ticker=AGENT&amp;network=mainnet"
+ data-x402-merchant="three.ws"
+ data-x402-action="Check ticker · AGENT"
+ data-result-target="r-symbol">
+ Buy & run · check AGENT
+ </button>
+ <div class="result-panel" id="r-symbol"></div>
+ </div>
+
+ <div class="sku-card">
+ <div class="head">
+ <div class="title">Agent reputation</div>
+ <div class="price">$0.001</div>
+ </div>
+ <div class="desc">Pull a multi-source reputation report for any on-chain agent: posting cadence, follower deltas, on-chain activity, x402 settlement stats.</div>
+ <div class="net">Base · Solana</div>
+ <button class="buy"
+ data-x402-endpoint="/api/x402/agent-reputation?address=BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN&amp;chain=solana"
+ data-x402-merchant="three.ws"
+ data-x402-action="Reputation report"
+ data-result-target="r-rep">
+ Buy & run · BUrwd1nK…3nSN
+ </button>
+ <div class="result-panel" id="r-rep"></div>
+ </div>
+
+ <div class="sku-card">
+ <div class="head">
+ <div class="title">Pump.fun agent audit</div>
+ <div class="price">$0.001</div>
+ </div>
+ <div class="desc">Forensic on-chain audit of a Pump.fun launch — supply curves, holder concentration, dev-wallet history, and risk flags.</div>
+ <div class="net">Base · Solana</div>
+ <button class="buy"
+ data-x402-endpoint="/api/x402/pump-agent-audit?mint=A4cFRDmiBwY3Hw2bAErr8RTfQNQ8wupTzcXocnLEpump"
+ data-x402-merchant="three.ws"
+ data-x402-action="Pump.fun audit"
+ data-result-target="r-pump">
+ Buy & run · audit launch
+ </button>
+ <div class="result-panel" id="r-pump"></div>
+ </div>
+
+ <div class="sku-card">
+ <div class="head">
+ <div class="title">Onchain identity verify</div>
+ <div class="price">$0.001</div>
+ </div>
+ <div class="desc">Verify an address claim against ENS, SNS, ERC-8004 attestations, and Solana SAS credentials. Returns linked identities + provenance.</div>
+ <div class="net">Base · Solana</div>
+ <button class="buy"
+ data-x402-endpoint="/api/x402/onchain-identity-verify?address=vitalik.eth"
+ data-x402-merchant="three.ws"
+ data-x402-action="Verify identity · vitalik.eth"
+ data-result-target="r-id">
+ Buy & run · verify vitalik.eth
+ </button>
+ <div class="result-panel" id="r-id"></div>
+ </div>
+
+ </div>
+ </section>
+
+ <section id="programmatic" class="alt">
+ <h2><span class="num">04</span>Or call it programmatically</h2>
+ <p class="sub">Same modal, called from JavaScript. The promise resolves with the API result and a settlement receipt.</p>
+ <div class="snippet" id="progSnippet"><button class="copy-btn" data-copy="progSnippetCode">Copy</button><span id="progSnippetCode"><span class="k">const</span> { result, payment } = <span class="k">await</span> window.X402.<span class="a">pay</span>({
+ <span class="a">endpoint</span>: <span class="s">'/api/x402/symbol-availability'</span>,
+ <span class="a">body</span>: { <span class="a">ticker</span>: <span class="s">'AGENT'</span> },
+ <span class="a">merchant</span>: <span class="s">'Acme'</span>,
+ <span class="a">action</span>: <span class="s">'Check ticker'</span>,
+});
+
+<span class="c">// payment.transaction → on-chain tx hash</span>
+<span class="c">// payment.payer → buyer wallet</span>
+<span class="c">// result → your endpoint's JSON response</span></span></div>
+ </section>
+
+ <footer>
+ <div class="left">
+ <div class="dot"></div>
+ <span>x402 · operated by three.ws</span>
+ </div>
+ <div class="right">
+ <a href="/docs/x402" target="_blank">Docs</a>
+ <a href="https://x402.org" target="_blank">Protocol ↗</a>
+ <a href="https://www.x402scan.com" target="_blank">x402scan ↗</a>
+ </div>
+ </footer>
+</div>
+
+<div class="toast" id="toast">copied</div>
+
+<script type="module" src="/x402.js"></script>
+<script>
+ // Copy buttons
+ document.querySelectorAll('.copy-btn').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ const id = btn.dataset.copy;
+ const el = document.getElementById(id);
+ if (!el) return;
+ try {
+ await navigator.clipboard.writeText(el.textContent || '');
+ btn.classList.add('copied');
+ btn.textContent = '✓ Copied';
+ const toast = document.getElementById('toast');
+ toast.classList.add('show');
+ setTimeout(() => toast.classList.remove('show'), 1600);
+ setTimeout(() => {
+ btn.classList.remove('copied');
+ btn.textContent = 'Copy';
+ }, 1800);
+ } catch (e) {
+ btn.textContent = 'copy failed';
+ }
+ });
+ });
+
+ // Wire result callbacks on every demo button
+ document.querySelectorAll('[data-result-target]').forEach((btn) => {
+ const targetId = btn.dataset.resultTarget;
+ const panel = document.getElementById(targetId);
+ btn.addEventListener('x402:result', (e) => {
+ const { result, payment } = e.detail;
+ const explorer = payment?.transaction
+ ? (payment.network?.startsWith('solana') ? `https://solscan.io/tx/${payment.transaction}` : `https://basescan.org/tx/${payment.transaction}`)
+ : null;
+ panel.innerHTML = `<span class="ok">✓ Paid</span> · network=${payment?.network || '?'} · ${explorer ? `<a href="${explorer}" target="_blank">tx ↗</a>` : ''}\n\n${escapeHtml(JSON.stringify(result, null, 2).slice(0, 2400))}`;
+ panel.classList.add('show');
+ });
+ btn.addEventListener('x402:error', (e) => {
+ panel.innerHTML = `<span class="err">✗ Error</span> · ${escapeHtml(e.detail?.error || 'unknown')}`;
+ panel.classList.add('show');
+ });
+ });
+
+ function escapeHtml(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ }
+</script>
+
+</body>
+</html>
diff --git a/public/x402.js b/public/x402.js
new file mode 100644
index 000000000..1b94e1767
--- /dev/null
+++ b/public/x402.js
@@ -0,0 +1,890 @@
+// x402.js — drop-in payment modal for any x402 paid endpoint.
+//
+// Merchants add one line to their site:
+//
+// <script type="module" src="https://3d.irish/x402.js"></script>
+//
+// Then any element with `data-x402-endpoint` opens a payment modal on click:
+//
+// <button
+// data-x402-endpoint="https://example.com/api/paid/summarize"
+// data-x402-method="POST"
+// data-x402-body='{"text":"hello"}'
+// data-x402-merchant="Acme"
+// data-x402-action="Summarize"
+// >Pay & Run</button>
+//
+// On completion the element receives an `x402:result` CustomEvent whose detail
+// is { ok, result, payment, response }. On error: `x402:error` with { error }.
+//
+// You can also call programmatically:
+//
+// const out = await window.X402.pay({
+// endpoint: '/api/paid/summarize',
+// body: { text: 'hello' },
+// merchant: 'Acme',
+// action: 'Summarize',
+// });
+//
+// The modal handles wallet connect (Phantom for Solana, window.ethereum for
+// Base USDC via EIP-3009), drives the 402 → sign → retry flow, and shows the
+// result. Vanilla JS, no bundler required.
+
+const VERSION = '0.1.0';
+const ORIGIN = (() => {
+ // Resolve the origin that hosts this script — used as the API origin for
+ // the prepare/encode helpers. Falls back to the merchant origin in same-
+ // origin mode.
+ try {
+ const script = document.currentScript;
+ if (script?.src) return new URL(script.src).origin;
+ const found = document.querySelector('script[src*="/x402.js"]');
+ if (found?.src) return new URL(found.src).origin;
+ } catch (_) {}
+ return location.origin;
+})();
+
+// USDC EIP-3009 typed-data sig works against Base USDC at this address. The
+// domain `version` must match the on-chain `EIP712_DOMAIN_SEPARATOR_VERSION`
+// of the deployed USDC implementation — Base USDC is at version "2".
+const EVM_NETWORKS = {
+ 'eip155:8453': { chainId: 8453, name: 'Base', explorer: 'https://basescan.org/tx/' },
+ 'eip155:84532': { chainId: 84532, name: 'Base Sepolia', explorer: 'https://sepolia.basescan.org/tx/' },
+ 'eip155:42161': { chainId: 42161, name: 'Arbitrum', explorer: 'https://arbiscan.io/tx/' },
+ 'eip155:10': { chainId: 10, name: 'Optimism', explorer: 'https://optimistic.etherscan.io/tx/' },
+};
+
+function isSolanaNetwork(net) {
+ return typeof net === 'string' && (net === 'solana' || net.startsWith('solana:'));
+}
+function isEvmNetwork(net) {
+ return typeof net === 'string' && net.startsWith('eip155:');
+}
+function networkLabel(net, accept) {
+ if (isSolanaNetwork(net)) return 'Solana';
+ const meta = EVM_NETWORKS[net];
+ return meta?.name || accept?.extra?.name || net;
+}
+function explorerUrl(net, tx) {
+ if (!tx) return null;
+ if (isSolanaNetwork(net)) return `https://solscan.io/tx/${tx}`;
+ const meta = EVM_NETWORKS[net];
+ return meta ? `${meta.explorer}${tx}` : null;
+}
+
+function formatAmount(rawAtomics, decimals = 6) {
+ const n = Number(rawAtomics) / 10 ** decimals;
+ if (n < 0.01) return n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
+ if (n < 1) return n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
+ return n.toFixed(2);
+}
+
+function b64encode(obj) {
+ const json = JSON.stringify(obj);
+ if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
+ return btoa(unescape(encodeURIComponent(json)));
+}
+function b64decode(str) {
+ if (!str) return null;
+ try {
+ const bin = typeof Buffer !== 'undefined' ? Buffer.from(str, 'base64').toString('utf8') : decodeURIComponent(escape(atob(str)));
+ return JSON.parse(bin);
+ } catch (_) {
+ return null;
+ }
+}
+
+// ───────────────────────────────────────────────────────────────── styles ────
+
+const STYLE_ID = 'x402-styles';
+const STYLES = `
+:root {
+ --x402-z: 2147483600;
+}
+.x402-overlay {
+ position: fixed; inset: 0;
+ background: rgba(8, 10, 18, 0.55);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ display: flex; align-items: center; justify-content: center;
+ z-index: var(--x402-z);
+ opacity: 0; transition: opacity 0.16s ease-out;
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ color: #0d0f15;
+}
+.x402-overlay.x402-open { opacity: 1; }
+.x402-overlay * { box-sizing: border-box; }
+.x402-modal {
+ width: calc(100% - 32px); max-width: 420px;
+ background: #ffffff;
+ border-radius: 18px;
+ box-shadow: 0 24px 80px rgba(8, 10, 18, 0.28), 0 4px 16px rgba(8, 10, 18, 0.12);
+ overflow: hidden;
+ transform: translateY(8px) scale(0.985);
+ transition: transform 0.18s ease-out;
+ display: flex; flex-direction: column;
+ max-height: calc(100dvh - 32px);
+}
+.x402-overlay.x402-open .x402-modal { transform: translateY(0) scale(1); }
+.x402-head {
+ padding: 18px 20px 14px;
+ border-bottom: 1px solid #eef0f4;
+ display: flex; align-items: center; gap: 12px;
+}
+.x402-head .x402-merchant {
+ flex: 1; min-width: 0;
+}
+.x402-merchant .x402-name {
+ font-size: 12px; color: #5a6378; font-weight: 600; letter-spacing: 0.02em; text-transform: uppercase;
+ margin-bottom: 2px;
+}
+.x402-merchant .x402-action {
+ font-size: 17px; font-weight: 700; color: #0d0f15;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+ letter-spacing: -0.01em;
+}
+.x402-close {
+ width: 32px; height: 32px;
+ border-radius: 8px; border: none; background: #f3f4f7;
+ font-size: 16px; color: #5a6378; cursor: pointer;
+ display: flex; align-items: center; justify-content: center;
+ transition: background 0.12s;
+}
+.x402-close:hover { background: #e7e9ee; color: #0d0f15; }
+
+.x402-price-row {
+ padding: 18px 20px;
+ display: flex; align-items: baseline; justify-content: space-between;
+ background: linear-gradient(180deg, #fafbfc 0%, #ffffff 100%);
+ border-bottom: 1px solid #eef0f4;
+}
+.x402-price {
+ font-size: 32px; font-weight: 700; letter-spacing: -0.02em; color: #0d0f15;
+ font-variant-numeric: tabular-nums;
+}
+.x402-price .x402-currency { font-size: 14px; color: #5a6378; font-weight: 600; margin-left: 6px; letter-spacing: 0; }
+.x402-network {
+ font-size: 12px; color: #5a6378; font-weight: 500;
+ background: #f3f4f7; padding: 5px 10px; border-radius: 99px;
+ display: inline-flex; align-items: center; gap: 6px;
+}
+.x402-network::before {
+ content: ''; width: 6px; height: 6px; border-radius: 50%;
+ background: #22c55e;
+}
+
+.x402-body {
+ padding: 16px 20px 18px;
+ flex: 1 1 auto; overflow-y: auto;
+ display: flex; flex-direction: column; gap: 10px;
+}
+.x402-step {
+ display: flex; gap: 12px; align-items: flex-start;
+ padding: 10px 0;
+}
+.x402-step + .x402-step { border-top: 1px solid #f3f4f7; }
+.x402-step-num {
+ width: 22px; height: 22px; flex: 0 0 auto;
+ border-radius: 50%; border: 1.5px solid #d0d4dd; background: #fff;
+ color: #5a6378;
+ font-size: 11px; font-weight: 700;
+ display: flex; align-items: center; justify-content: center;
+}
+.x402-step.x402-active .x402-step-num {
+ border-color: #0a84ff; background: #0a84ff; color: #fff;
+ animation: x402-spin 1.2s linear infinite;
+}
+.x402-step.x402-done .x402-step-num {
+ border-color: #22c55e; background: #22c55e; color: #fff;
+}
+.x402-step.x402-error .x402-step-num {
+ border-color: #ef4444; background: #ef4444; color: #fff;
+}
+@keyframes x402-spin {
+ from { box-shadow: 0 0 0 0 rgba(10, 132, 255, 0.4); }
+ to { box-shadow: 0 0 0 8px rgba(10, 132, 255, 0); }
+}
+.x402-step-body { flex: 1; min-width: 0; }
+.x402-step-label { font-size: 14px; font-weight: 600; color: #0d0f15; line-height: 1.35; }
+.x402-step-meta { font-size: 12px; color: #5a6378; margin-top: 2px; font-feature-settings: 'tnum' 1; }
+.x402-step.x402-error .x402-step-meta { color: #ef4444; }
+
+.x402-wallet-buttons {
+ display: flex; flex-direction: column; gap: 8px;
+ margin-top: 4px;
+}
+.x402-wallet-btn {
+ width: 100%; padding: 13px 14px;
+ background: #ffffff; border: 1.5px solid #e2e5ec; border-radius: 11px;
+ font-size: 14px; font-weight: 600; color: #0d0f15;
+ cursor: pointer; font-family: inherit;
+ display: flex; align-items: center; gap: 12px;
+ transition: border-color 0.12s, background 0.12s, transform 0.05s;
+}
+.x402-wallet-btn:hover:not(:disabled) { border-color: #0a84ff; background: #f7faff; }
+.x402-wallet-btn:active:not(:disabled) { transform: translateY(1px); }
+.x402-wallet-btn:disabled { opacity: 0.45; cursor: not-allowed; }
+.x402-wallet-icon {
+ width: 28px; height: 28px; flex: 0 0 auto;
+ border-radius: 7px;
+ display: flex; align-items: center; justify-content: center;
+ font-size: 16px;
+ background: #f3f4f7;
+}
+.x402-wallet-icon.x402-phantom { background: linear-gradient(135deg, #ab9ff2, #534bb1); color: #fff; }
+.x402-wallet-icon.x402-metamask { background: linear-gradient(135deg, #f6851b, #e2761b); color: #fff; }
+.x402-wallet-name { flex: 1; text-align: left; }
+.x402-wallet-meta { font-size: 11px; color: #8a90a8; font-weight: 500; }
+
+.x402-pay-btn {
+ width: 100%; padding: 14px 16px;
+ background: #0d0f15; color: #fff; border: none;
+ border-radius: 12px;
+ font-size: 15px; font-weight: 700; font-family: inherit;
+ cursor: pointer; letter-spacing: -0.005em;
+ transition: background 0.12s, transform 0.05s;
+ margin-top: 4px;
+ display: flex; align-items: center; justify-content: center; gap: 8px;
+}
+.x402-pay-btn:hover:not(:disabled) { background: #1a1d28; }
+.x402-pay-btn:active:not(:disabled) { transform: translateY(1px); }
+.x402-pay-btn:disabled { background: #c8ccd4; cursor: not-allowed; }
+
+.x402-error-box {
+ padding: 12px 14px; border-radius: 10px;
+ background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c;
+ font-size: 13px; line-height: 1.45;
+ font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+ word-break: break-word;
+}
+.x402-error-box strong { font-weight: 700; }
+
+.x402-receipt {
+ padding: 14px 16px; border-radius: 12px;
+ background: linear-gradient(180deg, #f0fdf4 0%, #ffffff 100%);
+ border: 1px solid #bbf7d0;
+}
+.x402-receipt-title {
+ font-size: 11px; font-weight: 700; color: #15803d;
+ text-transform: uppercase; letter-spacing: 0.06em;
+ margin-bottom: 8px;
+ display: flex; align-items: center; gap: 6px;
+}
+.x402-receipt-title::before { content: '✓'; font-size: 14px; }
+.x402-receipt-row {
+ display: flex; justify-content: space-between; gap: 12px;
+ font-size: 12px; padding: 2px 0;
+ font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+}
+.x402-receipt-row .x402-k { color: #5a6378; }
+.x402-receipt-row .x402-v { color: #0d0f15; text-align: right; word-break: break-all; }
+.x402-receipt-row a { color: #0a84ff; text-decoration: none; }
+.x402-receipt-row a:hover { text-decoration: underline; }
+
+.x402-result {
+ padding: 12px 14px; border-radius: 10px;
+ background: #fafbfc; border: 1px solid #e2e5ec;
+ max-height: 240px; overflow: auto;
+ font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+ font-size: 12px; line-height: 1.5; color: #0d0f15;
+ white-space: pre-wrap; word-break: break-word;
+}
+
+.x402-foot {
+ padding: 10px 20px 14px;
+ border-top: 1px solid #eef0f4;
+ display: flex; align-items: center; justify-content: space-between;
+ font-size: 11px; color: #8a90a8;
+}
+.x402-foot a { color: #5a6378; text-decoration: none; font-weight: 600; }
+.x402-foot a:hover { color: #0d0f15; }
+.x402-foot .x402-secure { display: flex; align-items: center; gap: 5px; }
+.x402-foot .x402-secure::before { content: '🔒'; font-size: 10px; }
+
+@media (max-width: 480px) {
+ .x402-modal { max-width: none; width: calc(100% - 16px); border-radius: 16px; }
+ .x402-price { font-size: 26px; }
+}
+
+@media (prefers-color-scheme: dark) {
+ .x402-overlay { color: #e6e8f0; }
+ .x402-modal { background: #14161f; box-shadow: 0 24px 80px rgba(0, 0, 0, 0.6); }
+ .x402-head, .x402-price-row, .x402-foot { border-color: #232636; }
+ .x402-step + .x402-step { border-top-color: #232636; }
+ .x402-merchant .x402-name { color: #8a90a8; }
+ .x402-merchant .x402-action, .x402-price, .x402-step-label { color: #e6e8f0; }
+ .x402-step-meta { color: #8a90a8; }
+ .x402-close { background: #1f2230; color: #8a90a8; }
+ .x402-close:hover { background: #2a2e3d; color: #e6e8f0; }
+ .x402-price-row { background: linear-gradient(180deg, #1a1d29 0%, #14161f 100%); }
+ .x402-network { background: #1f2230; color: #b0b6cc; }
+ .x402-wallet-btn { background: #1a1d29; border-color: #2a2e3d; color: #e6e8f0; }
+ .x402-wallet-btn:hover:not(:disabled) { background: #20243a; border-color: #0a84ff; }
+ .x402-wallet-icon { background: #2a2e3d; }
+ .x402-wallet-meta { color: #6b7088; }
+ .x402-pay-btn { background: #ffffff; color: #0d0f15; }
+ .x402-pay-btn:hover:not(:disabled) { background: #e7e9ee; }
+ .x402-pay-btn:disabled { background: #2a2e3d; color: #5a6378; }
+ .x402-step-num { background: #14161f; border-color: #2a2e3d; color: #8a90a8; }
+ .x402-result { background: #1a1d29; border-color: #2a2e3d; color: #e6e8f0; }
+ .x402-receipt { background: linear-gradient(180deg, #0b1f17 0%, #14161f 100%); border-color: #14532d; }
+ .x402-receipt-title { color: #4ade80; }
+ .x402-receipt-row .x402-k { color: #8a90a8; }
+ .x402-receipt-row .x402-v { color: #e6e8f0; }
+ .x402-receipt-row a { color: #60a5fa; }
+ .x402-error-box { background: #1f1416; border-color: #7f1d1d; color: #fca5a5; }
+ .x402-foot a { color: #b0b6cc; }
+ .x402-foot a:hover { color: #ffffff; }
+}
+`;
+
+function injectStyles() {
+ if (document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = STYLES;
+ document.head.appendChild(el);
+}
+
+// ───────────────────────────────────────────────────────────── modal class ───
+
+class CheckoutModal {
+ constructor(opts) {
+ this.opts = opts;
+ this.steps = [
+ { id: 'discover', label: 'Confirming price' },
+ { id: 'connect', label: 'Connect wallet' },
+ { id: 'authorize', label: 'Authorize payment' },
+ { id: 'verify', label: 'Verify & complete' },
+ ];
+ this.activeNetwork = null;
+ this.payerAddress = null;
+ this.accept = null;
+ this.challenge = null;
+ this.disposed = false;
+ }
+
+ mount() {
+ injectStyles();
+ const overlay = document.createElement('div');
+ overlay.className = 'x402-overlay';
+ overlay.innerHTML = `
+ <div class="x402-modal" role="dialog" aria-modal="true" aria-label="x402 payment">
+ <div class="x402-head">
+ <div class="x402-merchant">
+ <div class="x402-name" data-merchant>${escapeHtml(this.opts.merchant || 'Payment')}</div>
+ <div class="x402-action" data-action>${escapeHtml(this.opts.action || 'Pay-per-call')}</div>
+ </div>
+ <button class="x402-close" data-close aria-label="Close">✕</button>
+ </div>
+ <div class="x402-price-row">
+ <div class="x402-price" data-price>—<span class="x402-currency"> USDC</span></div>
+ <div class="x402-network" data-network>resolving…</div>
+ </div>
+ <div class="x402-body" data-body></div>
+ <div class="x402-foot">
+ <span class="x402-secure">x402 · onchain settled</span>
+ <a href="https://3d.irish" target="_blank" rel="noopener">Powered by 3d.irish</a>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+ this.overlay = overlay;
+ this.bodyEl = overlay.querySelector('[data-body]');
+ this.priceEl = overlay.querySelector('[data-price]');
+ this.networkEl = overlay.querySelector('[data-network]');
+ overlay.querySelector('[data-close]').addEventListener('click', () => this.close('cancelled'));
+ overlay.addEventListener('click', (e) => { if (e.target === overlay) this.close('cancelled'); });
+ this.onKey = (e) => { if (e.key === 'Escape') this.close('cancelled'); };
+ document.addEventListener('keydown', this.onKey);
+ requestAnimationFrame(() => overlay.classList.add('x402-open'));
+ return new Promise((resolve, reject) => {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+ }
+
+ close(reason) {
+ if (this.disposed) return;
+ this.disposed = true;
+ document.removeEventListener('keydown', this.onKey);
+ this.overlay.classList.remove('x402-open');
+ setTimeout(() => this.overlay.remove(), 180);
+ if (reason === 'cancelled' && this.reject) {
+ const err = new Error('cancelled');
+ err.code = 'cancelled';
+ this.reject(err);
+ }
+ }
+
+ renderSteps(activeId, status = {}) {
+ const html = this.steps
+ .map((s) => {
+ const state = status[s.id] || (s.id === activeId ? 'active' : 'idle');
+ const cls = state === 'active' ? 'x402-active' : state === 'done' ? 'x402-done' : state === 'error' ? 'x402-error' : '';
+ const meta = status[`${s.id}_meta`] || '';
+ const sym = state === 'done' ? '✓' : state === 'error' ? '!' : s.id === activeId && state === 'active' ? ' ' : (this.steps.findIndex((x) => x.id === s.id) + 1);
+ return `<div class="x402-step ${cls}">
+ <div class="x402-step-num">${sym}</div>
+ <div class="x402-step-body">
+ <div class="x402-step-label">${s.label}</div>
+ ${meta ? `<div class="x402-step-meta">${escapeHtml(meta)}</div>` : ''}
+ </div>
+ </div>`;
+ })
+ .join('');
+ return html;
+ }
+
+ setPrice(accept) {
+ const decimals = accept.extra?.decimals ?? 6;
+ const amount = formatAmount(accept.amount, decimals);
+ const sym = (accept.extra?.name || 'USDC').replace(/^USD Coin$/, 'USDC');
+ this.priceEl.innerHTML = `${amount}<span class="x402-currency"> ${sym}</span>`;
+ this.networkEl.textContent = networkLabel(accept.network, accept);
+ }
+
+ renderConnect() {
+ const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);
+ const evmDetected = typeof window !== 'undefined' && window.ethereum;
+ const solanaAccept = this.challenge?.accepts.find((a) => isSolanaNetwork(a.network));
+ const evmAccept = this.challenge?.accepts.find((a) => isEvmNetwork(a.network));
+ const buttons = [];
+ if (solanaAccept) {
+ buttons.push(`
+ <button class="x402-wallet-btn" data-wallet="phantom" ${phantomDetected ? '' : 'disabled'}>
+ <div class="x402-wallet-icon x402-phantom">P</div>
+ <span class="x402-wallet-name">${phantomDetected ? 'Phantom' : 'Phantom (not detected)'}</span>
+ <span class="x402-wallet-meta">${networkLabel(solanaAccept.network, solanaAccept)}</span>
+ </button>
+ `);
+ }
+ if (evmAccept) {
+ buttons.push(`
+ <button class="x402-wallet-btn" data-wallet="evm" ${evmDetected ? '' : 'disabled'}>
+ <div class="x402-wallet-icon x402-metamask">M</div>
+ <span class="x402-wallet-name">${evmDetected ? 'Browser wallet' : 'No EVM wallet detected'}</span>
+ <span class="x402-wallet-meta">${networkLabel(evmAccept.network, evmAccept)}</span>
+ </button>
+ `);
+ }
+ this.bodyEl.innerHTML = `
+ ${this.renderSteps('connect', { discover: 'done' })}
+ <div class="x402-wallet-buttons">${buttons.join('')}</div>
+ `;
+ const onClick = (e) => {
+ const btn = e.target.closest('[data-wallet]');
+ if (!btn || btn.disabled) return;
+ const wallet = btn.dataset.wallet;
+ if (wallet === 'phantom') this.runSolana(solanaAccept);
+ else if (wallet === 'evm') this.runEvm(evmAccept);
+ };
+ this.bodyEl.querySelectorAll('[data-wallet]').forEach((b) => b.addEventListener('click', onClick));
+ }
+
+ renderProgress(activeId, meta = {}) {
+ this.bodyEl.innerHTML = this.renderSteps(activeId, {
+ discover: 'done',
+ connect: 'done',
+ ...(activeId === 'verify' ? { authorize: 'done' } : {}),
+ [`${activeId}_meta`]: meta.text || '',
+ ...meta.statuses,
+ });
+ }
+
+ renderError(stepId, message) {
+ this.bodyEl.innerHTML = `
+ ${this.renderSteps(stepId, {
+ ...(stepId !== 'discover' ? { discover: 'done' } : {}),
+ ...(stepId === 'authorize' || stepId === 'verify' ? { connect: 'done' } : {}),
+ ...(stepId === 'verify' ? { authorize: 'done' } : {}),
+ [stepId]: 'error',
+ [`${stepId}_meta`]: 'failed',
+ })}
+ <div class="x402-error-box"><strong>${escapeHtml(stepId)}:</strong> ${escapeHtml(message)}</div>
+ <button class="x402-pay-btn" data-retry>Try again</button>
+ `;
+ this.bodyEl.querySelector('[data-retry]').addEventListener('click', () => this.start());
+ }
+
+ renderDone({ result, payment }) {
+ const explorer = explorerUrl(payment?.network, payment?.transaction);
+ const txShort = payment?.transaction ? `${payment.transaction.slice(0, 8)}…${payment.transaction.slice(-6)}` : '—';
+ const resultStr = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
+ this.bodyEl.innerHTML = `
+ <div class="x402-receipt">
+ <div class="x402-receipt-title">Paid</div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">network</span>
+ <span class="x402-v">${escapeHtml(networkLabel(payment?.network) || '—')}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">payer</span>
+ <span class="x402-v">${escapeHtml(payment?.payer ? `${payment.payer.slice(0, 8)}…${payment.payer.slice(-6)}` : '—')}</span>
+ </div>
+ ${
+ payment?.transaction
+ ? `<div class="x402-receipt-row"><span class="x402-k">tx</span><span class="x402-v">${
+ explorer ? `<a href="${explorer}" target="_blank" rel="noopener">${txShort} ↗</a>` : txShort
+ }</span></div>`
+ : ''
+ }
+ </div>
+ <div class="x402-result">${escapeHtml(resultStr).slice(0, 4000)}</div>
+ <button class="x402-pay-btn" data-done>Done</button>
+ `;
+ this.bodyEl.querySelector('[data-done]').addEventListener('click', () => {
+ this.disposed = true;
+ document.removeEventListener('keydown', this.onKey);
+ this.overlay.classList.remove('x402-open');
+ setTimeout(() => this.overlay.remove(), 180);
+ });
+ }
+
+ async start() {
+ this.bodyEl.innerHTML = this.renderSteps('discover');
+ try {
+ const challenge = await discoverChallenge(this.opts);
+ this.challenge = challenge;
+ // Prefer Solana when Phantom is present, else first EVM, else first accept.
+ const solana = challenge.accepts.find((a) => isSolanaNetwork(a.network));
+ const evm = challenge.accepts.find((a) => isEvmNetwork(a.network));
+ const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);
+ this.accept = (phantomDetected && solana) || evm || challenge.accepts[0];
+ this.setPrice(this.accept);
+ this.renderConnect();
+ } catch (err) {
+ this.renderError('discover', err.message || String(err));
+ }
+ }
+
+ async runSolana(accept) {
+ this.accept = accept;
+ this.setPrice(accept);
+ this.renderProgress('connect', { text: 'Opening Phantom…' });
+ try {
+ const provider = window.phantom?.solana || window.solana;
+ if (!provider) throw new Error('Phantom wallet not detected');
+ const conn = await provider.connect();
+ const payerAddress = (conn?.publicKey || provider.publicKey)?.toString();
+ if (!payerAddress) throw new Error('Phantom did not return a public key');
+ this.payerAddress = payerAddress;
+ this.renderProgress('authorize', { text: `Building Solana payment for ${payerAddress.slice(0, 6)}…${payerAddress.slice(-4)}` });
+
+ const prep = await postJson(`${ORIGIN}/api/x402-checkout?action=prepare`, {
+ accept,
+ buyer: payerAddress,
+ });
+ this.renderProgress('authorize', { text: 'Confirm in Phantom…' });
+ const txBytes = base64ToUint8Array(prep.tx_base64);
+ // Phantom returns a fully-signed VersionedTransaction with the buyer's
+ // signature added. The facilitator's fee-payer signature is added by
+ // PayAI during /settle.
+ const SolanaWeb3 = await loadSolanaWeb3();
+ const tx = SolanaWeb3.VersionedTransaction.deserialize(txBytes);
+ const signed = await provider.signTransaction(tx);
+ const signedB64 = uint8ArrayToBase64(signed.serialize());
+
+ const enc = await postJson(`${ORIGIN}/api/x402-checkout?action=encode`, {
+ accept,
+ signed_tx_base64: signedB64,
+ resource_url: this.opts.endpoint,
+ });
+
+ await this.executePaid(enc.x_payment);
+ } catch (err) {
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async runEvm(accept) {
+ this.accept = accept;
+ this.setPrice(accept);
+ this.renderProgress('connect', { text: 'Opening browser wallet…' });
+ try {
+ const eth = window.ethereum;
+ if (!eth) throw new Error('No EVM wallet detected');
+ const accounts = await eth.request({ method: 'eth_requestAccounts' });
+ const payerAddress = accounts?.[0];
+ if (!payerAddress) throw new Error('Wallet did not return an account');
+ this.payerAddress = payerAddress;
+
+ const meta = EVM_NETWORKS[accept.network];
+ if (!meta) throw new Error(`Unknown EVM network ${accept.network}`);
+ // Switch chain if needed.
+ const currentChainHex = await eth.request({ method: 'eth_chainId' });
+ const desiredChainHex = '0x' + meta.chainId.toString(16);
+ if (currentChainHex !== desiredChainHex) {
+ this.renderProgress('connect', { text: `Switch wallet to ${meta.name}…` });
+ try {
+ await eth.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: desiredChainHex }] });
+ } catch (e) {
+ throw new Error(`Wallet is on ${currentChainHex}; please switch to ${meta.name} (${desiredChainHex}) and retry`);
+ }
+ }
+
+ this.renderProgress('authorize', { text: `Authorize ${formatAmount(accept.amount)} USDC…` });
+
+ // EIP-3009 transferWithAuthorization typed-data signature.
+ // validAfter / validBefore use unix seconds; nonce is a random 32-byte hex.
+ const validAfter = 0;
+ const validBefore = Math.floor(Date.now() / 1000) + (accept.maxTimeoutSeconds || 600);
+ const nonce = '0x' + randomHex(32);
+ const domain = {
+ name: accept.extra?.name || 'USD Coin',
+ version: accept.extra?.version || '2',
+ chainId: meta.chainId,
+ verifyingContract: accept.asset,
+ };
+ const types = {
+ EIP712Domain: [
+ { name: 'name', type: 'string' },
+ { name: 'version', type: 'string' },
+ { name: 'chainId', type: 'uint256' },
+ { name: 'verifyingContract', type: 'address' },
+ ],
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+ };
+ const message = {
+ from: payerAddress,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter,
+ validBefore,
+ nonce,
+ };
+ const typedData = {
+ primaryType: 'TransferWithAuthorization',
+ types,
+ domain,
+ message,
+ };
+ const signature = await eth.request({
+ method: 'eth_signTypedData_v4',
+ params: [payerAddress, JSON.stringify(typedData)],
+ });
+
+ const paymentPayload = {
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: this.opts.endpoint, mimeType: 'application/json' },
+ accepted: accept,
+ payload: {
+ signature,
+ authorization: { from: payerAddress, to: accept.payTo, value: accept.amount, validAfter, validBefore, nonce },
+ },
+ };
+ const xPayment = b64encode(paymentPayload);
+ await this.executePaid(xPayment);
+ } catch (err) {
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async executePaid(xPayment) {
+ this.renderProgress('verify', { text: 'Calling merchant endpoint…' });
+ try {
+ const res = await fetch(this.opts.endpoint, {
+ method: this.opts.method || 'GET',
+ headers: {
+ ...(this.opts.headers || {}),
+ ...(this.opts.body && !this.opts.headers?.['content-type'] ? { 'content-type': 'application/json' } : {}),
+ 'X-PAYMENT': xPayment,
+ },
+ body: this.opts.body ? (typeof this.opts.body === 'string' ? this.opts.body : JSON.stringify(this.opts.body)) : undefined,
+ });
+ const ct = res.headers.get('content-type') || '';
+ const text = await res.text();
+ let result;
+ if (ct.includes('json')) {
+ try {
+ result = JSON.parse(text);
+ } catch {
+ result = text;
+ }
+ } else {
+ result = text;
+ }
+ if (!res.ok) {
+ const msg = (result && typeof result === 'object' && (result.error_description || result.error)) || `HTTP ${res.status}`;
+ throw new Error(msg);
+ }
+ const settleHeader = res.headers.get('x-payment-response');
+ const payment = b64decode(settleHeader) || {};
+ this.renderDone({ result, payment });
+ this.resolve?.({ ok: true, result, payment, response: { status: res.status, headers: headersToObject(res.headers) } });
+ } catch (err) {
+ this.renderError('verify', friendlyError(err));
+ }
+ }
+}
+
+// ───────────────────────────────────────────────────────── helpers ──────────
+
+function escapeHtml(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+function headersToObject(headers) {
+ const out = {};
+ headers.forEach((v, k) => (out[k] = v));
+ return out;
+}
+
+function friendlyError(err) {
+ const msg = err?.shortMessage || err?.message || String(err);
+ // Trim ethers/viem long stacks, Phantom's RPC-error verbosity.
+ if (/user rejected|user denied|reject/i.test(msg)) return 'cancelled in wallet';
+ return msg.slice(0, 240);
+}
+
+function base64ToUint8Array(b64) {
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(b64, 'base64'));
+ const bin = atob(b64);
+ const arr = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
+ return arr;
+}
+function uint8ArrayToBase64(arr) {
+ if (typeof Buffer !== 'undefined') return Buffer.from(arr).toString('base64');
+ let bin = '';
+ for (let i = 0; i < arr.length; i++) bin += String.fromCharCode(arr[i]);
+ return btoa(bin);
+}
+function randomHex(bytes) {
+ const arr = new Uint8Array(bytes);
+ crypto.getRandomValues(arr);
+ return Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('');
+}
+
+let _solanaWeb3 = null;
+async function loadSolanaWeb3() {
+ if (_solanaWeb3) return _solanaWeb3;
+ // Dynamic import from esm.sh keeps the drop-in script tiny — Solana web3.js
+ // is only fetched when a Solana payment is actually attempted.
+ _solanaWeb3 = await import('https://esm.sh/@solana/[email protected]?bundle');
+ return _solanaWeb3;
+}
+
+async function postJson(url, body) {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ let data;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = { error: 'parse_error', error_description: text.slice(0, 200) };
+ }
+ if (!res.ok) {
+ const err = new Error(data.error_description || data.error || `HTTP ${res.status}`);
+ err.status = res.status;
+ err.data = data;
+ throw err;
+ }
+ return data;
+}
+
+// Probe the merchant endpoint with a benign request to extract the 402 challenge.
+async function discoverChallenge(opts) {
+ const headers = { ...(opts.headers || {}) };
+ const init = {
+ method: opts.method || 'GET',
+ headers,
+ body: opts.body ? (typeof opts.body === 'string' ? opts.body : JSON.stringify(opts.body)) : undefined,
+ };
+ if (init.body && !headers['content-type']) headers['content-type'] = 'application/json';
+ const res = await fetch(opts.endpoint, init);
+ if (res.status !== 402) {
+ // Endpoint isn't paid (200) or isn't an x402 endpoint at all. In either
+ // case, surface a clear error — accidentally pointing the modal at a
+ // free endpoint should not silently succeed.
+ const txt = await res.text();
+ throw new Error(`Endpoint did not return 402 (got ${res.status}). Body: ${txt.slice(0, 120)}`);
+ }
+ const body = await res.json().catch(() => null);
+ if (!body || !Array.isArray(body.accepts) || !body.accepts.length) {
+ throw new Error('Endpoint returned 402 but no `accepts` array');
+ }
+ return body;
+}
+
+// ───────────────────────────────────────────────────────── public api ───────
+
+export async function pay(opts) {
+ if (!opts?.endpoint) throw new Error('X402.pay: endpoint is required');
+ const modal = new CheckoutModal(opts);
+ const result = modal.mount();
+ // kick off the discovery on next tick so the modal animates in first.
+ queueMicrotask(() => modal.start());
+ return result;
+}
+
+function bindElement(el) {
+ if (el.dataset.x402Bound === '1') return;
+ el.dataset.x402Bound = '1';
+ el.addEventListener('click', async (e) => {
+ e.preventDefault();
+ const opts = readOptsFrom(el);
+ try {
+ const out = await pay(opts);
+ el.dispatchEvent(new CustomEvent('x402:result', { detail: out, bubbles: true }));
+ } catch (err) {
+ if (err?.code === 'cancelled') return;
+ el.dispatchEvent(new CustomEvent('x402:error', { detail: { error: err?.message || String(err) }, bubbles: true }));
+ }
+ });
+}
+
+function readOptsFrom(el) {
+ const ds = el.dataset;
+ let body = ds.x402Body;
+ if (body) {
+ try { body = JSON.parse(body); } catch { /* keep as string */ }
+ }
+ let headers = ds.x402Headers;
+ if (headers) {
+ try { headers = JSON.parse(headers); } catch { headers = undefined; }
+ }
+ return {
+ endpoint: ds.x402Endpoint,
+ method: ds.x402Method || (body ? 'POST' : 'GET'),
+ body,
+ headers,
+ merchant: ds.x402Merchant,
+ action: ds.x402Action || el.textContent?.trim().slice(0, 60),
+ };
+}
+
+export function init() {
+ document.querySelectorAll('[data-x402-endpoint]').forEach(bindElement);
+}
+
+// Auto-init on DOMContentLoaded, plus on demand.
+if (typeof document !== 'undefined') {
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init, { once: true });
+ } else {
+ init();
+ }
+ // Re-scan when merchants dynamically inject buttons.
+ const mo = new MutationObserver(() => init());
+ mo.observe(document.documentElement, { childList: true, subtree: true });
+}
+
+// Expose to merchants' inline scripts.
+if (typeof window !== 'undefined') {
+ window.X402 = Object.freeze({ pay, init, version: VERSION });
+}
diff --git a/vercel.json b/vercel.json
index 9484b9a34..bae2a7d94 100644
--- a/vercel.json
+++ b/vercel.json
@@ -276,6 +276,10 @@
"src": "/dashboard/tokens",
"dest": "/dashboard/tokens.html"
},
+ {
+ "src": "/dashboard/x402",
+ "dest": "/dashboard/x402.html"
+ },
{
"src": "/dashboard/(agents|avatars|create|upload|animations|widgets|embed|keys|mcp|monetization|payments|subscriptions|billing|revenue|earnings|account)/?",
"dest": "/dashboard/index.html"
@@ -1040,10 +1044,22 @@
"src": "/pay/calls/[1-9A-HJ-NP-Za-km-z]+",
"dest": "/pay/calls/index.html"
},
+ {
+ "src": "/pay/c/[a-z0-9][a-z0-9-]+/?",
+ "dest": "/pay/c/index.html"
+ },
{
"src": "/pay/(.*)",
"dest": "/pay/$1"
},
+ {
+ "src": "/x402",
+ "dest": "/x402-stripe.html"
+ },
+ {
+ "src": "/x402/",
+ "dest": "/x402-stripe.html"
+ },
{
"src": "/settings",
"dest": "/settings/index.html"
diff --git a/vite.config.js b/vite.config.js
index 13283c51a..9bc2ad9d6 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -160,6 +160,9 @@ const appConfig = {
'eth-vanity': resolve(__dirname, 'public/eth-vanity.html'),
pay: resolve(__dirname, 'public/pay/index.html'),
'pay-calls': resolve(__dirname, 'public/pay/calls/index.html'),
+ 'pay-checkout': resolve(__dirname, 'public/pay/c/index.html'),
+ 'x402-stripe': resolve(__dirname, 'public/x402-stripe.html'),
+ 'x402-dashboard': resolve(__dirname, 'public/dashboard/x402.html'),
sitemap: resolve(__dirname, 'public/sitemap/index.html'),
},
},
@@ -206,6 +209,9 @@ const appConfig = {
'/pay/': resolve(root, 'public/pay/index.html'),
'/pay/calls': resolve(root, 'public/pay/calls/index.html'),
'/pay/calls/': resolve(root, 'public/pay/calls/index.html'),
+ '/x402': resolve(root, 'public/x402-stripe.html'),
+ '/x402/': resolve(root, 'public/x402-stripe.html'),
+ '/dashboard/x402': resolve(root, 'public/dashboard/x402.html'),
'/explore': resolve(root, 'public/discover/index.html'),
'/explore/': resolve(root, 'public/discover/index.html'),
// END:DISCOVER_ROUTE
@@ -295,6 +301,10 @@ const appConfig = {
// /p/<slug> → public Launchpad Studio renderer (hydrates from /api/launchpad/get)
else if (!filePath && /^\/p\/[a-z0-9-]+\/?$/.test(path))
filePath = resolve(root, 'public/p/index.html');
+ // /pay/c/<slug> → hosted x402 checkout page (hydrates from /api/x402-skus?slug=)
+ else if (!filePath && /^\/pay\/c\/[a-z0-9][a-z0-9-]+\/?$/.test(path))
+ filePath = resolve(root, 'public/pay/c/index.html');
+ // /dashboard/x402 → x402 SKU dashboard (already in fileMap)
else if (!filePath && /^\/marketplace\/agents\/[^/]+\/?$/.test(path))
filePath = resolve(root, 'marketplace.html');
else if (!filePath && /^\/marketplace\/avatars\/[^/]+\/?$/.test(path))