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.

the stripe of x402, the wix of 3d, the amazon of ai agents

originols50b4e7b13cf3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cb64504ea..e530f784f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -67,6 +67,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Shared agent links now unfurl with the agent's own avatar** — When you paste a link to an agent on X, Discord, Slack, Telegram or iMessage, the preview card now shows that agent's actual avatar, name and description instead of a generic three.ws image — so every shared link is visual proof of the collectible. Bots that don't run JavaScript get the right image and text rendered on the server, and agents without an avatar yet fall back to a clean branded card with their initial. We also fixed the canonical and share URLs on agent pages to point at the real /agents/<id> address. `[feature, improvement]`
- **Smart Money directory comes to Copy Trading** — The Copy Trading dashboard now has a Smart Money section: a ranked, searchable directory of over a thousand ecosystem-proven wallets drawn from gmgn.ai's smart-money taxonomy across both Solana and BSC. Filter by chain and by category — smart money, KOLs, launchpad specialists, snipers — and sort by 30-day realized profit, best multiple, win rate, or follower count. Each wallet shows its real 30-day performance and links straight to its live trade history, so you can vet a trader's track record before you decide to mirror them. (`/dashboard/copy`) `[feature]`
- **Smoother switch between camera AR and Place on floor** — On phones that can anchor an agent to your real floor, flipping between plain Camera AR and the Place on floor flow is now seamless. Before, tapping the two in quick succession could fight over the camera and leave you on a black screen with the camera light stuck on; now each switch waits for the previous one to finish releasing the camera, so it never double-grabs it. Leaving a floor session drops you straight back into the live camera view you came from — passthrough resumes instantly instead of flashing a dark frame — and taps on the screen behind the floor-anchor panel no longer slip through to open the wrong thing. If a floor session can't start, the scene keeps running and you get the calm "use Pin here instead" card rather than a frozen view. (`/irl`) `[fix]`
+- **Swap your avatar without leaving roaming mode** — When you detach the walking companion into full-page roaming — stroll or platformer — you can now change who you're playing as on the spot. A new Avatar button in the playground toolbar (or just press C) opens the same searchable roster picker, and the rig hot-swaps live without dropping you out of the page. Your pick is remembered across movement modes, the corner companion, and every page you visit next. `[feature, improvement]`
- **Switching avatars in the Club never freezes you in a T-pose** — The Club's avatar switcher lists public gallery rigs alongside the built-in ones, and not every gallery model is a humanoid our dance and walk clips can drive. Picking one of those used to leave your character frozen stiff, arms out, sliding around without moving her legs. Now the Club checks that a chosen avatar can actually be animated before committing to it — if it can't, it instantly rolls back to the one you were already walking as and tells you why, so your character keeps idling and walking with her legs moving no matter what you pick. (`/club`) `[fix]`
- **Tapping an agent in AR now lands every time** — Inspecting an agent in IRL AR is a tap — and we made that tap far harder to miss. There's now a finger-sized catch zone around each agent's floating name, so a tap that lands just beside a small or distant agent still opens its card instead of doing nothing. When several agents overlap on screen, your tap resolves to the one in front of you, and it never selects an agent that's behind you or off-screen. We also kept agents from vanishing when you bring your phone right up to one to look closely. Inspecting works whether the agent is centered, near the edge of the frame, close, or far. (`/irl`) `[improvement]`
- **The $THREE token page is now the single home for the coin** — We retired the separate economy explainer and consolidated everything about $THREE onto one page: live price, the bonding-curve chart, streaming trades, and one-click buy. Every place that pointed you to "learn about $THREE" or "get $THREE" — the holder badges, the Forge high-quality unlock prompts, and the holder gates across the app — now takes you straight to the token page where you can act. Old /three links redirect there automatically. (`/three-token`) `[improvement]`
diff --git a/api/_lib/migrations/20260619180000_x402_merchant.sql b/api/_lib/migrations/20260619180000_x402_merchant.sql
new file mode 100644
index 000000000..6735b2e2f
--- /dev/null
+++ b/api/_lib/migrations/20260619180000_x402_merchant.sql
@@ -0,0 +1,83 @@
+-- x402 Merchant Console — the "Stripe of x402" account settings.
+--
+-- One row per merchant (user). Captures everything a merchant configures to run
+-- a paid x402 business on three.ws: payout/agent wallets (where settled USDC
+-- arrives), default settlement network, branding, CORS/domain allow-list,
+-- security limits (spend caps, SIWX, network allow-list), an API key for the
+-- key-bypass lane, a webhook URL for settlement events, and a drag-and-drop
+-- storefront layout published at /store/<handle>.
+--
+-- The API key is stored hashed (sha256, hex). We keep only a short display
+-- prefix so the dashboard can show `x402_live_ab12…` without holding the secret.
+
+CREATE TABLE IF NOT EXISTS x402_merchant_settings (
+ owner_user_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
+
+ -- Branding shown across hosted checkout + storefront
+ business_name text,
+ support_email text,
+ logo_url text,
+ accent_color text DEFAULT '#0a84ff'
+ CHECK (accent_color IS NULL OR accent_color ~* '^#[0-9a-f]{6}$'),
+
+ -- Payout / agent wallets — where settled funds land. The most important
+ -- config: a misconfigured payout sends real money to the wrong place.
+ payout_evm text CHECK (payout_evm IS NULL OR payout_evm ~* '^0x[0-9a-f]{40}$'),
+ payout_solana text CHECK (payout_solana IS NULL OR char_length(payout_solana) BETWEEN 32 AND 44),
+ default_network text NOT NULL DEFAULT 'base'
+ CHECK (default_network IN ('base', 'solana')),
+
+ -- Agent wallets — the named on-chain identities a merchant authorizes to
+ -- AUTO-PAY (role=payer) or RECEIVE (role=payout) on its behalf, each scoped
+ -- by its own per-call / daily USDC cap. This is the heart of the console: a
+ -- merchant runs a fleet of agents that transact x402 with no human in the
+ -- loop, and this is where they bound what each one may move.
+ -- [{ id, label, address, chain, role, enabled,
+ -- per_call_cap_atomics, daily_cap_atomics }]
+ agent_wallets jsonb NOT NULL DEFAULT '[]'::jsonb,
+
+ -- Settlement facilitator override. NULL/'' → platform default facilitator.
+ facilitator text,
+
+ -- CORS / domain allow-list for the merchant's own embeds (jsonb array of origins)
+ cors_origins jsonb NOT NULL DEFAULT '[]'::jsonb,
+
+ -- Security
+ spend_cap_per_call_atomics text, -- null = no cap
+ spend_cap_daily_atomics text, -- null = no cap
+ require_siwx boolean NOT NULL DEFAULT false, -- re-entry must sign in
+ allowed_networks jsonb NOT NULL DEFAULT '["base","solana"]'::jsonb,
+
+ -- Developer: API key (hashed) + settlement webhook
+ api_key_hash text,
+ api_key_prefix text,
+ api_key_created_at timestamptz,
+ webhook_url text,
+
+ -- Storefront (drag-and-drop builder)
+ store_handle text UNIQUE
+ CHECK (store_handle IS NULL OR store_handle ~ '^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$'),
+ store_published boolean NOT NULL DEFAULT false,
+ store_layout jsonb NOT NULL DEFAULT '[]'::jsonb, -- ordered array of blocks
+ store_theme jsonb NOT NULL DEFAULT '{}'::jsonb, -- { mode, bg, accent }
+
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS idx_x402_merchant_store
+ ON x402_merchant_settings (store_handle) WHERE store_published = true;
+
+-- Idempotent column adds (guard for environments where an earlier cut of this
+-- table already exists without the agent-wallet / facilitator config).
+ALTER TABLE x402_merchant_settings ADD COLUMN IF NOT EXISTS agent_wallets jsonb NOT NULL DEFAULT '[]'::jsonb;
+ALTER TABLE x402_merchant_settings ADD COLUMN IF NOT EXISTS facilitator text;
+
+-- Products = SKUs. Add commerce/display columns so storefront cards can render
+-- a price + image without a live 402 probe, and so products can be ordered and
+-- toggled active without archiving. All optional → backward compatible.
+ALTER TABLE x402_skus ADD COLUMN IF NOT EXISTS image_url text;
+ALTER TABLE x402_skus ADD COLUMN IF NOT EXISTS price_atomics text; -- display price (raw token units)
+ALTER TABLE x402_skus ADD COLUMN IF NOT EXISTS price_network text; -- 'base' | 'solana' the price is quoted in
+ALTER TABLE x402_skus ADD COLUMN IF NOT EXISTS position int NOT NULL DEFAULT 0;
+ALTER TABLE x402_skus ADD COLUMN IF NOT EXISTS active boolean NOT NULL DEFAULT true;
diff --git a/api/x402-merchant.js b/api/x402-merchant.js
new file mode 100644
index 000000000..16f80dfe2
--- /dev/null
+++ b/api/x402-merchant.js
@@ -0,0 +1,292 @@
+// x402 Merchant Console — account settings for the "Stripe of x402".
+//
+// One settings row per merchant (user). Holds payout/agent wallets, default
+// settlement network, branding, CORS allow-list, security limits, a hashed API
+// key for the key-bypass lane, a settlement webhook, and a drag-and-drop
+// storefront layout published at /store/<handle>.
+//
+// GET /api/x402-merchant → my settings (auth; lazily created)
+// PUT /api/x402-merchant → upsert my settings (auth)
+// POST /api/x402-merchant?action=rotate-key → mint a fresh API key (auth; shown once)
+// GET /api/x402-merchant?store=<handle> → public storefront + products (no auth)
+
+import { z } from 'zod';
+import { sql } from './_lib/db.js';
+import { getSessionUser } from './_lib/auth.js';
+import { cors, json, readJson, wrap, error, rateLimited } from './_lib/http.js';
+import { parse } from './_lib/validate.js';
+import { randomToken, sha256 } from './_lib/crypto.js';
+import { clientIp, limits } from './_lib/rate-limit.js';
+
+const evmAddress = z.string().trim().regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 0x EVM address');
+const solAddress = z
+ .string()
+ .trim()
+ .regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'must be a base58 Solana address');
+const httpsOrigin = z
+ .string()
+ .trim()
+ .regex(/^https?:\/\/[a-z0-9.-]+(:\d+)?$/i, 'must be an origin like https://example.com');
+const httpsUrl = z
+ .string()
+ .trim()
+ .url()
+ .refine((v) => v.startsWith('https://') || v.startsWith('http://localhost'), 'must be https');
+const atomics = z.string().trim().regex(/^\d{1,20}$/, 'must be a whole token amount');
+const storeHandle = z
+ .string()
+ .trim()
+ .toLowerCase()
+ .regex(/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/, 'handle: lowercase, hyphenated, 3-40 chars');
+
+// Agent wallets — the named on-chain identities a merchant authorizes to
+// auto-pay (payer) or receive (payout) on its behalf, each capped independently.
+// A misconfigured agent wallet moves real USDC, so the address is validated
+// against its declared chain and the caps are whole-token atomics strings.
+const agentWalletSchema = z
+ .object({
+ id: z.string().trim().min(1).max(40),
+ label: z.string().trim().min(1).max(60),
+ chain: z.enum(['base', 'solana']),
+ role: z.enum(['payer', 'payout']),
+ address: z.string().trim().min(1).max(64),
+ enabled: z.boolean().default(true),
+ per_call_cap_atomics: z
+ .string()
+ .regex(/^\d{1,20}$/)
+ .nullish(),
+ daily_cap_atomics: z
+ .string()
+ .regex(/^\d{1,20}$/)
+ .nullish(),
+ })
+ .superRefine((w, ctx) => {
+ const ok =
+ w.chain === 'base'
+ ? /^0x[0-9a-fA-F]{40}$/.test(w.address)
+ : /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(w.address);
+ if (!ok) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['address'], message: `invalid ${w.chain} address` });
+ });
+
+// Storefront blocks. The builder serialises an ordered array of these; the
+// hosted renderer walks it. Keep the schema permissive on copy fields but tight
+// on type + referenced ids so a published store can't carry junk.
+const blockSchema = z.object({
+ id: z.string().min(1).max(40),
+ type: z.enum(['hero', 'products', 'product', 'text', 'image', 'button', 'divider', 'footer']),
+ heading: z.string().max(160).optional(),
+ subheading: z.string().max(400).optional(),
+ body: z.string().max(4000).optional(),
+ image_url: httpsUrl.optional(),
+ href: httpsUrl.optional(),
+ label: z.string().max(80).optional(),
+ sku_id: z.string().uuid().optional(),
+ sku_ids: z.array(z.string().uuid()).max(48).optional(),
+ align: z.enum(['left', 'center']).optional(),
+});
+
+const settingsSchema = z.object({
+ business_name: z.string().trim().max(80).nullish(),
+ support_email: z.string().trim().email().max(254).nullish(),
+ logo_url: httpsUrl.nullish(),
+ accent_color: z
+ .string()
+ .regex(/^#[0-9a-fA-F]{6}$/)
+ .nullish(),
+ payout_evm: evmAddress.nullish(),
+ payout_solana: solAddress.nullish(),
+ default_network: z.enum(['base', 'solana']).optional(),
+ cors_origins: z.array(httpsOrigin).max(50).optional(),
+ spend_cap_per_call_atomics: atomics.nullish(),
+ spend_cap_daily_atomics: atomics.nullish(),
+ require_siwx: z.boolean().optional(),
+ allowed_networks: z.array(z.enum(['base', 'solana'])).min(1).max(2).optional(),
+ agent_wallets: z.array(agentWalletSchema).max(50).optional(),
+ facilitator: httpsUrl.nullish(),
+ webhook_url: httpsUrl.nullish(),
+ store_handle: storeHandle.nullish(),
+ store_published: z.boolean().optional(),
+ store_layout: z.array(blockSchema).max(60).optional(),
+ store_theme: z
+ .object({
+ mode: z.enum(['light', 'dark', 'auto']).optional(),
+ bg: z
+ .string()
+ .regex(/^#[0-9a-fA-F]{6}$/)
+ .optional(),
+ accent: z
+ .string()
+ .regex(/^#[0-9a-fA-F]{6}$/)
+ .optional(),
+ })
+ .partial()
+ .optional(),
+});
+
+const DEFAULTS = {
+ business_name: null,
+ support_email: null,
+ logo_url: null,
+ accent_color: '#0a84ff',
+ payout_evm: null,
+ payout_solana: null,
+ default_network: 'base',
+ cors_origins: [],
+ spend_cap_per_call_atomics: null,
+ spend_cap_daily_atomics: null,
+ require_siwx: false,
+ allowed_networks: ['base', 'solana'],
+ agent_wallets: [],
+ facilitator: null,
+ webhook_url: null,
+ store_handle: null,
+ store_published: false,
+ store_layout: [],
+ store_theme: {},
+};
+
+// Columns we return to the owner. Never expose api_key_hash.
+const OWNER_COLS = sql`
+ owner_user_id, business_name, support_email, logo_url, accent_color,
+ payout_evm, payout_solana, default_network, cors_origins,
+ spend_cap_per_call_atomics, spend_cap_daily_atomics, require_siwx, allowed_networks,
+ agent_wallets, facilitator,
+ api_key_prefix, api_key_created_at, webhook_url,
+ store_handle, store_published, store_layout, store_theme, created_at, updated_at
+`;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { origins: '*', methods: 'GET,PUT,POST,OPTIONS' })) return;
+
+ const method = req.method;
+ if (method === 'GET') return handleGet(req, res);
+ if (method === 'PUT') return handleUpsert(req, res);
+ if (method === 'POST') return handlePost(req, res);
+ return error(res, 405, 'method_not_allowed', `unsupported: ${method}`);
+});
+
+async function handleGet(req, res) {
+ const { store } = req.query || {};
+
+ // Public storefront read — no auth. Returns the published layout + its
+ // products so /store/<handle> can render without exposing owner-only fields.
+ if (store) {
+ const [m] = await sql`
+ select owner_user_id, business_name, logo_url, accent_color,
+ store_handle, store_layout, store_theme
+ from x402_merchant_settings
+ where store_handle = ${String(store).toLowerCase()} and store_published = true
+ limit 1
+ `;
+ if (!m) return error(res, 404, 'store_not_found', `no published store "${store}"`);
+ const products = await sql`
+ select id, slug, merchant_name, action_name, description, logo_url, image_url,
+ accent_color, price_atomics, price_network, target_method, position
+ from x402_skus
+ where owner_user_id = ${m.owner_user_id} and archived_at is null and active = true
+ order by position asc, created_at desc
+ `;
+ return json(res, 200, { store: m, products }, { 'cache-control': 'public, max-age=30' });
+ }
+
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const settings = await getOrCreate(user.id);
+ return json(res, 200, { settings });
+}
+
+async function getOrCreate(userId) {
+ const [existing] = await sql`select ${OWNER_COLS} from x402_merchant_settings where owner_user_id = ${userId} limit 1`;
+ if (existing) return existing;
+ const [created] = await sql`
+ insert into x402_merchant_settings (owner_user_id)
+ values (${userId})
+ on conflict (owner_user_id) do update set updated_at = now()
+ returning ${OWNER_COLS}
+ `;
+ return created;
+}
+
+async function handleUpsert(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 rateLimited(res, rl);
+
+ const patch = parse(settingsSchema, await readJson(req));
+
+ // Publishing requires a handle.
+ if (patch.store_published === true) {
+ const [cur] = await sql`select store_handle from x402_merchant_settings where owner_user_id = ${user.id} limit 1`;
+ const handle = patch.store_handle ?? cur?.store_handle;
+ if (!handle) return error(res, 400, 'handle_required', 'set a store handle before publishing');
+ }
+
+ // Storefront handle is globally unique — surface a clean 409 instead of a raw
+ // constraint error.
+ if (patch.store_handle) {
+ const [taken] = await sql`
+ select owner_user_id from x402_merchant_settings
+ where store_handle = ${patch.store_handle} and owner_user_id <> ${user.id} limit 1
+ `;
+ if (taken) return error(res, 409, 'handle_taken', `store handle "${patch.store_handle}" is taken`);
+ }
+
+ await getOrCreate(user.id);
+
+ // Build the row with current values as the base, overlaying provided keys.
+ const [cur] = await sql`select ${OWNER_COLS} from x402_merchant_settings where owner_user_id = ${user.id} limit 1`;
+ const next = { ...DEFAULTS, ...cur };
+ for (const [k, v] of Object.entries(patch)) next[k] = v;
+
+ const [updated] = await sql`
+ update x402_merchant_settings set
+ business_name = ${next.business_name},
+ support_email = ${next.support_email},
+ logo_url = ${next.logo_url},
+ accent_color = ${next.accent_color ?? '#0a84ff'},
+ payout_evm = ${next.payout_evm},
+ payout_solana = ${next.payout_solana},
+ default_network = ${next.default_network ?? 'base'},
+ cors_origins = ${JSON.stringify(next.cors_origins ?? [])}::jsonb,
+ spend_cap_per_call_atomics = ${next.spend_cap_per_call_atomics},
+ spend_cap_daily_atomics = ${next.spend_cap_daily_atomics},
+ require_siwx = ${next.require_siwx ?? false},
+ allowed_networks = ${JSON.stringify(next.allowed_networks ?? ['base', 'solana'])}::jsonb,
+ agent_wallets = ${JSON.stringify(next.agent_wallets ?? [])}::jsonb,
+ facilitator = ${next.facilitator},
+ webhook_url = ${next.webhook_url},
+ store_handle = ${next.store_handle},
+ store_published = ${next.store_published ?? false},
+ store_layout = ${JSON.stringify(next.store_layout ?? [])}::jsonb,
+ store_theme = ${JSON.stringify(next.store_theme ?? {})}::jsonb,
+ updated_at = now()
+ where owner_user_id = ${user.id}
+ returning ${OWNER_COLS}
+ `;
+ return json(res, 200, { settings: updated });
+}
+
+async function handlePost(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 rateLimited(res, rl);
+
+ const action = req.query?.action;
+ if (action !== 'rotate-key') return error(res, 404, 'not_found', `unknown action: ${action ?? '(none)'}`);
+
+ await getOrCreate(user.id);
+
+ // Mint a fresh key, store only its hash + a display prefix. Returned once.
+ const secret = `x402_live_${randomToken(24)}`;
+ const hash = await sha256(secret);
+ const prefix = secret.slice(0, 18);
+ await sql`
+ update x402_merchant_settings
+ set api_key_hash = ${hash}, api_key_prefix = ${prefix}, api_key_created_at = now(), updated_at = now()
+ where owner_user_id = ${user.id}
+ `;
+ return json(res, 200, { api_key: secret, api_key_prefix: prefix });
+}
diff --git a/api/x402-skus.js b/api/x402-skus.js
index aa8eb210c..91f5cde45 100644
--- a/api/x402-skus.js
+++ b/api/x402-skus.js
@@ -39,11 +39,20 @@ const createSchema = z.object({
action_name: z.string().trim().min(1).max(80),
description: z.string().trim().max(2000).optional(),
logo_url: httpsUrl.optional(),
+ image_url: httpsUrl.optional(),
accent_color: z
.string()
.regex(/^#[0-9a-fA-F]{6}$/)
.default('#0a84ff'),
success_url: httpsUrl.optional(),
+ // Storefront display fields — optional, never block a paid call.
+ price_atomics: z
+ .string()
+ .regex(/^\d{1,20}$/)
+ .optional(),
+ price_network: z.enum(['base', 'solana']).optional(),
+ position: z.number().int().min(0).max(9999).optional(),
+ active: z.boolean().optional(),
});
const updateSchema = createSchema.partial();
@@ -67,8 +76,8 @@ async function handleGet(req, res) {
// 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
+ merchant_name, action_name, description, logo_url, image_url, accent_color,
+ success_url, price_atomics, price_network
from x402_skus
where slug = ${String(slug)} and archived_at is null
limit 1
@@ -83,8 +92,9 @@ async function handleGet(req, res) {
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
+ merchant_name, action_name, description, logo_url, image_url, accent_color,
+ success_url, price_atomics, price_network, position, active,
+ created_at, updated_at, archived_at
from x402_skus
where id = ${String(id)} limit 1
`;
@@ -112,13 +122,14 @@ async function handleGet(req, res) {
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.merchant_name, s.action_name, s.accent_color, s.image_url,
+ s.price_atomics, s.price_network, s.position, s.active,
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
+ order by s.position asc, s.created_at desc
`;
return json(res, 200, { skus: rows });
}
@@ -138,13 +149,16 @@ async function handleCreate(req, res) {
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
+ merchant_name, action_name, description, logo_url, image_url, accent_color, success_url,
+ price_atomics, price_network, position, active
) 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}
+ ${body.description ?? null}, ${body.logo_url ?? null}, ${body.image_url ?? null},
+ ${body.accent_color}, ${body.success_url ?? null},
+ ${body.price_atomics ?? null}, ${body.price_network ?? null},
+ ${body.position ?? 0}, ${body.active ?? true}
)
returning id, slug, merchant_name, action_name, created_at
`;
@@ -176,8 +190,13 @@ async function handleUpdate(req, res) {
action_name = coalesce(${patch.action_name ?? null}, action_name),
description = coalesce(${patch.description ?? null}, description),
logo_url = coalesce(${patch.logo_url ?? null}, logo_url),
+ image_url = coalesce(${patch.image_url ?? null}, image_url),
accent_color = coalesce(${patch.accent_color ?? null}, accent_color),
success_url = coalesce(${patch.success_url ?? null}, success_url),
+ price_atomics = coalesce(${patch.price_atomics ?? null}, price_atomics),
+ price_network = coalesce(${patch.price_network ?? null}, price_network),
+ position = coalesce(${patch.position ?? null}, position),
+ active = coalesce(${patch.active ?? null}, active),
updated_at = now()
where id = ${String(id)}
returning id, slug, merchant_name, action_name, updated_at
diff --git a/data/changelog.json b/data/changelog.json
index 6ce2ad1d2..c3c319084 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-19",
+ "title": "Swap your avatar without leaving roaming mode",
+ "summary": "When you detach the walking companion into full-page roaming — stroll or platformer — you can now change who you're playing as on the spot. A new Avatar button in the playground toolbar (or just press C) opens the same searchable roster picker, and the rig hot-swaps live without dropping you out of the page. Your pick is remembered across movement modes, the corner companion, and every page you visit next.",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-19",
"title": "Configure your Walk Companion from the dashboard",
diff --git a/pages/launch.html b/pages/launch.html
index 0493cf140..f7bdd4358 100644
--- a/pages/launch.html
+++ b/pages/launch.html
@@ -150,9 +150,12 @@
<script type="module">
// launch.js and its dependency chain (/studio/launch-panel.js,
// /studio/fees-panel.js) live in public/ and are loaded by URL at
- // runtime. @vite-ignore keeps rollup from trying to bundle a
- // public-dir asset (which it cannot resolve) and aborting build:app.
- const { mountLaunchCoin } = await import(/* @vite-ignore */ '/launch/launch.js');
+ // runtime. The specifier is kept in a var so Vite's import-analysis
+ // leaves it as a browser-resolved runtime import instead of trying
+ // to resolve a public-dir asset (which it refuses, aborting the dev
+ // server / build:app).
+ const spec = '/launch/launch.js';
+ const { mountLaunchCoin } = await import(/* @vite-ignore */ spec);
mountLaunchCoin(document.getElementById('launch-root'));
</script>
<script src="/brand.js" defer></script>
diff --git a/public/changelog.json b/public/changelog.json
index ffe48b39f..fa444b616 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T22:37:56.369Z",
+ "generated_at": "2026-06-19T22:44:40.616Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -632,6 +632,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Swap your avatar without leaving roaming mode",
+ "summary": "When you detach the walking companion into full-page roaming — stroll or platformer — you can now change who you're playing as on the spot. A new Avatar button in the playground toolbar (or just press C) opens the same searchable roster picker, and the rig hot-swaps live without dropping you out of the page. Your pick is remembered across movement modes, the corner companion, and every page you visit next.",
+ "link": null,
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 303995657..fb68c0ac1 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -494,6 +494,14 @@
<category>fix</category>
<description>On phones that can anchor an agent to your real floor, flipping between plain Camera AR and the Place on floor flow is now seamless. Before, tapping the two in quick succession could fight over the camera and leave you on a black screen with the camera light stuck on; now each switch waits for the previous one to finish releasing the camera, so it never double-grabs it. Leaving a floor session drops you straight back into the live camera view you came from — passthrough resumes instantly instead of flashing a dark frame — and taps on the screen behind the floor-anchor panel no longer slip through to open the wrong thing. If a floor session can't start, the scene keeps running and you get the calm &quot;use Pin here instead&quot; card rather than a frozen view.</description>
</item>
+ <item>
+ <title>Swap your avatar without leaving roaming mode</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-19:Swap your avatar without leaving roaming mode</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>When you detach the walking companion into full-page roaming — stroll or platformer — you can now change who you're playing as on the spot. A new Avatar button in the playground toolbar (or just press C) opens the same searchable roster picker, and the rig hot-swaps live without dropping you out of the page. Your pick is remembered across movement modes, the corner companion, and every page you visit next.</description>
+ </item>
<item>
<title>Switching avatars in the Club never freezes you in a T-pose</title>
<link>https://three.ws/club</link>
diff --git a/public/dashboard/x402-admin.html b/public/dashboard/x402-admin.html
new file mode 100644
index 000000000..dbcda78c6
--- /dev/null
+++ b/public/dashboard/x402-admin.html
@@ -0,0 +1,1054 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width,initial-scale=1" />
+<title>x402 Console · three.ws</title>
+<meta name="description" content="The Stripe of x402. Configure payout wallets, products, pricing, CORS, security, API keys, and a drag-and-drop storefront — all in one console." />
+<meta name="theme-color" content="#0b0b0b" />
+<style>
+ :root {
+ color-scheme: dark;
+ --bg: #0b0b0b;
+ --bg-2: #111111;
+ --panel: #161616;
+ --panel-2: #1d1d1d;
+ --border: #272727;
+ --border-strong: #343434;
+ --text: #f0f2f8;
+ --muted: #8a90a8;
+ --muted-2: #6b7088;
+ --accent: #0a84ff;
+ --accent-2: #60a5fa;
+ --green: #4ade80;
+ --amber: #fbbf24;
+ --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 ── */
+ header {
+ display: flex; align-items: center; gap: 14px;
+ padding: 14px 24px; border-bottom: 1px solid var(--border);
+ background: rgba(10, 11, 16, 0.92); backdrop-filter: blur(12px);
+ position: sticky; top: 0; z-index: 30;
+ }
+ 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); }
+ header .right { margin-left: auto; display: flex; gap: 10px; align-items: center; }
+ header .save-state { font-size: 12px; color: var(--muted); font-family: var(--mono); min-width: 90px; text-align: right; }
+ header .save-state.saving { color: var(--amber); }
+ header .save-state.saved { color: var(--green); }
+ header .save-state.error { color: #fca5a5; }
+
+ .btn {
+ padding: 9px 16px; background: #ffffff; color: #0b0b0b; border: none; border-radius: 9px;
+ font-size: 13px; font-weight: 600; font-family: inherit; cursor: pointer;
+ transition: background 0.12s, transform 0.05s; display: inline-flex; align-items: center; gap: 7px;
+ }
+ .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; }
+ .btn.sm { padding: 6px 12px; font-size: 12px; }
+
+ /* ── Layout ── */
+ .shell { display: grid; grid-template-columns: 232px 1fr; min-height: calc(100dvh - 57px); }
+ @media (max-width: 860px) { .shell { grid-template-columns: 1fr; } }
+
+ nav.side {
+ border-right: 1px solid var(--border); padding: 18px 12px;
+ display: flex; flex-direction: column; gap: 2px;
+ position: sticky; top: 57px; align-self: start; height: calc(100dvh - 57px); overflow: auto;
+ }
+ @media (max-width: 860px) {
+ nav.side { position: static; height: auto; flex-direction: row; overflow-x: auto; border-right: none; border-bottom: 1px solid var(--border); padding: 10px; gap: 4px; }
+ }
+ nav.side .nav-item {
+ display: flex; align-items: center; gap: 11px; padding: 10px 12px; border-radius: 9px;
+ font-size: 13.5px; font-weight: 500; color: var(--muted); cursor: pointer; white-space: nowrap;
+ transition: background 0.1s, color 0.1s; border: 1px solid transparent;
+ }
+ nav.side .nav-item:hover { background: var(--panel); color: var(--text); }
+ nav.side .nav-item.active { background: var(--panel-2); color: var(--text); border-color: var(--border); }
+ nav.side .nav-item .ico { width: 17px; height: 17px; flex: 0 0 auto; opacity: 0.85; }
+ nav.side .nav-item .badge { margin-left: auto; font-size: 10px; font-family: var(--mono); background: var(--bg-2); border: 1px solid var(--border); padding: 1px 6px; border-radius: 99px; color: var(--muted); }
+ nav.side .nav-sep { height: 1px; background: var(--border); margin: 10px 6px; }
+ @media (max-width: 860px) { nav.side .nav-sep { display: none; } nav.side .nav-item .badge { display: none; } }
+
+ main { padding: 30px 32px 80px; max-width: 920px; width: 100%; }
+ @media (max-width: 640px) { main { padding: 22px 16px 60px; } }
+
+ .panel-title { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; margin: 0 0 4px; }
+ .panel-sub { color: var(--muted); font-size: 14px; margin: 0 0 26px; max-width: 64ch; }
+
+ .tab { display: none; animation: fade 0.18s ease; }
+ .tab.active { display: block; }
+ @keyframes fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
+
+ .card { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 22px; margin-bottom: 18px; }
+ .card h3 { margin: 0 0 4px; font-size: 15px; font-weight: 700; letter-spacing: -0.01em; }
+ .card .card-sub { color: var(--muted); font-size: 13px; margin: 0 0 16px; }
+
+ label.field { display: flex; flex-direction: column; gap: 6px; font-size: 12px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.03em; margin-bottom: 14px; }
+ label.field:last-child { margin-bottom: 0; }
+ label.field input, label.field select, label.field 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, box-shadow 0.12s;
+ }
+ label.field input:focus, label.field select:focus, label.field textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(10,132,255,0.15); }
+ label.field input.mono { font-family: var(--mono); font-size: 12.5px; }
+ label.field input.invalid { border-color: #7f1d1d; box-shadow: 0 0 0 3px rgba(239,68,68,0.12); }
+ label.field input.valid { border-color: #1c5f3a; }
+ label.field textarea { min-height: 70px; resize: vertical; font-family: var(--mono); font-size: 12px; }
+ label.field .hint { font-size: 11px; color: var(--muted-2); font-weight: 500; text-transform: none; letter-spacing: 0; }
+ label.field .hint.warn { color: var(--amber); }
+ .row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
+ @media (max-width: 560px) { .row-2 { grid-template-columns: 1fr; } }
+
+ /* toggle */
+ .toggle-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 12px 0; border-top: 1px solid var(--border); }
+ .toggle-row:first-child { border-top: none; }
+ .toggle-row .tr-text { font-size: 13.5px; }
+ .toggle-row .tr-text b { display: block; font-weight: 600; }
+ .toggle-row .tr-text span { color: var(--muted); font-size: 12px; }
+ .switch { position: relative; width: 42px; height: 24px; flex: 0 0 auto; }
+ .switch input { opacity: 0; width: 0; height: 0; }
+ .switch .slider { position: absolute; inset: 0; background: var(--panel-2); border: 1px solid var(--border-strong); border-radius: 99px; cursor: pointer; transition: background 0.15s; }
+ .switch .slider::before { content: ""; position: absolute; width: 18px; height: 18px; left: 2px; top: 2px; background: var(--muted); border-radius: 50%; transition: transform 0.15s, background 0.15s; }
+ .switch input:checked + .slider { background: rgba(10,132,255,0.25); border-color: var(--accent); }
+ .switch input:checked + .slider::before { transform: translateX(18px); background: var(--accent-2); }
+
+ /* network segmented */
+ .seg { display: inline-flex; background: var(--bg-2); border: 1px solid var(--border); border-radius: 10px; padding: 3px; gap: 3px; }
+ .seg button { background: none; border: none; color: var(--muted); font-family: inherit; font-size: 13px; font-weight: 600; padding: 7px 16px; border-radius: 7px; cursor: pointer; transition: background 0.1s, color 0.1s; }
+ .seg button.on { background: var(--panel); color: var(--text); }
+
+ /* chips (CORS / networks) */
+ .chips { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
+ .chip { display: inline-flex; align-items: center; gap: 8px; background: var(--bg-2); border: 1px solid var(--border); border-radius: 99px; padding: 6px 8px 6px 13px; font-family: var(--mono); font-size: 12px; }
+ .chip button { background: none; border: none; color: var(--muted); cursor: pointer; font-size: 14px; line-height: 1; padding: 2px 4px; border-radius: 5px; }
+ .chip button:hover { color: var(--red); background: rgba(239,68,68,0.1); }
+ .add-row { display: flex; gap: 8px; }
+ .add-row input { flex: 1; }
+
+ /* stats */
+ .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 22px; }
+ .stat { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 16px 18px; }
+ .stat .k { font-size: 11px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 7px; }
+ .stat .v { font-size: 22px; font-weight: 700; letter-spacing: -0.01em; font-variant-numeric: tabular-nums; }
+ .stat .v .u { font-size: 12px; color: var(--muted); font-weight: 500; margin-left: 3px; }
+
+ /* checklist */
+ .checklist { display: flex; flex-direction: column; gap: 2px; }
+ .check-item { display: flex; align-items: center; gap: 11px; padding: 11px 0; border-top: 1px solid var(--border); font-size: 13.5px; }
+ .check-item:first-child { border-top: none; }
+ .check-item .dot2 { width: 18px; height: 18px; border-radius: 50%; flex: 0 0 auto; border: 2px solid var(--border-strong); display: flex; align-items: center; justify-content: center; font-size: 11px; }
+ .check-item.done .dot2 { background: rgba(74,222,128,0.15); border-color: var(--green); color: var(--green); }
+ .check-item .ci-text { flex: 1; }
+ .check-item .ci-text span { display: block; color: var(--muted); font-size: 12px; }
+ .check-item.done .ci-main { color: var(--muted); text-decoration: line-through; }
+
+ /* products table */
+ .prod-list { display: flex; flex-direction: column; gap: 10px; }
+ .prod-card { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 14px 16px; display: grid; grid-template-columns: auto 1fr auto auto; gap: 14px; align-items: center; }
+ .prod-card .pc-img { width: 44px; height: 44px; border-radius: 10px; background: var(--bg-2); display: flex; align-items: center; justify-content: center; font-weight: 700; overflow: hidden; flex: 0 0 auto; }
+ .prod-card .pc-img img { width: 100%; height: 100%; object-fit: cover; }
+ .prod-card .pc-name { font-weight: 600; font-size: 14px; }
+ .prod-card .pc-meta { font-family: var(--mono); font-size: 11px; color: var(--muted); margin-top: 3px; }
+ .prod-card .pc-price { font-family: var(--mono); font-size: 13px; color: var(--green); font-weight: 700; white-space: nowrap; }
+ .prod-card .pc-actions { display: flex; gap: 6px; }
+ .prod-card.inactive { opacity: 0.55; }
+ @media (max-width: 560px) { .prod-card { grid-template-columns: auto 1fr; } .prod-card .pc-price, .prod-card .pc-actions { grid-column: 2; justify-content: flex-start; } }
+
+ .empty { text-align: center; padding: 48px 24px; color: var(--muted); font-size: 14px; border: 1px dashed var(--border); border-radius: 14px; }
+ .empty h4 { color: var(--text); font-size: 16px; margin: 0 0 6px; }
+
+ /* code block */
+ .code { background: #0f0f0f; border: 1px solid var(--border); border-radius: 11px; padding: 14px 16px; font-family: var(--mono); font-size: 12.5px; line-height: 1.6; color: #c8ccd4; white-space: pre-wrap; word-break: break-all; position: relative; }
+ .code .copy { position: absolute; top: 8px; right: 8px; background: var(--panel-2); border: 1px solid var(--border); color: var(--muted); font-size: 11px; padding: 4px 9px; border-radius: 6px; cursor: pointer; font-family: inherit; }
+ .code .copy:hover { color: var(--text); }
+ .code .copy.copied { color: var(--green); border-color: var(--green); }
+
+ .key-box { display: flex; align-items: center; gap: 10px; background: var(--bg-2); border: 1px solid var(--border); border-radius: 10px; padding: 11px 14px; font-family: var(--mono); font-size: 13px; }
+ .key-box .kb-val { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+ /* ── Storefront builder ── */
+ .builder { display: grid; grid-template-columns: 200px 1fr; gap: 18px; align-items: start; }
+ @media (max-width: 760px) { .builder { grid-template-columns: 1fr; } }
+ .palette { display: flex; flex-direction: column; gap: 8px; position: sticky; top: 72px; }
+ @media (max-width: 760px) { .palette { position: static; flex-direction: row; flex-wrap: wrap; } }
+ .palette .pal-block {
+ display: flex; align-items: center; gap: 9px; background: var(--panel); border: 1px solid var(--border);
+ border-radius: 10px; padding: 10px 12px; font-size: 13px; font-weight: 500; cursor: grab; user-select: none;
+ transition: border-color 0.1s, background 0.1s;
+ }
+ .palette .pal-block:hover { border-color: var(--border-strong); background: var(--panel-2); }
+ .palette .pal-block:active { cursor: grabbing; }
+ .palette .pal-block .pico { width: 16px; height: 16px; opacity: 0.8; }
+
+ .canvas { background: var(--bg-2); border: 1px solid var(--border); border-radius: 14px; padding: 14px; min-height: 280px; }
+ .canvas.drag-over { border-color: var(--accent); box-shadow: inset 0 0 0 2px rgba(10,132,255,0.2); }
+ .canvas-empty { text-align: center; color: var(--muted); padding: 60px 20px; font-size: 13.5px; }
+
+ .cblock {
+ background: var(--panel); border: 1px solid var(--border); border-radius: 11px; margin-bottom: 10px;
+ transition: border-color 0.12s, box-shadow 0.12s; position: relative;
+ }
+ .cblock:last-child { margin-bottom: 0; }
+ .cblock.dragging { opacity: 0.4; }
+ .cblock.drop-target { border-color: var(--accent); }
+ .cblock-head { display: flex; align-items: center; gap: 10px; padding: 11px 13px; cursor: grab; }
+ .cblock-head .grip { color: var(--muted-2); font-size: 15px; cursor: grab; letter-spacing: -2px; }
+ .cblock-head .ctype { font-size: 12.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: var(--accent-2); }
+ .cblock-head .csum { font-size: 12px; color: var(--muted); margin-left: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
+ .cblock-head .cdel { margin-left: auto; background: none; border: none; color: var(--muted); cursor: pointer; font-size: 15px; padding: 3px 7px; border-radius: 6px; }
+ .cblock-head .cdel:hover { color: var(--red); background: rgba(239,68,68,0.1); }
+ .cblock-body { padding: 0 13px 14px; display: none; }
+ .cblock.open .cblock-body { display: block; }
+ .cblock-body label.field { margin-bottom: 11px; }
+
+ /* live preview */
+ .preview-frame { background: #ffffff; color: #111; border: 1px solid var(--border); border-radius: 14px; overflow: hidden; }
+ .preview-frame iframe { width: 100%; border: none; height: 520px; display: block; background: #fff; }
+ .preview-bar { display: flex; align-items: center; gap: 10px; padding: 10px 14px; border-bottom: 1px solid var(--border); background: var(--panel); }
+ .preview-bar .url { flex: 1; font-family: var(--mono); font-size: 12px; color: var(--muted); background: var(--bg-2); border: 1px solid var(--border); border-radius: 7px; padding: 6px 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+ /* modal */
+ .overlay { position: fixed; inset: 0; background: rgba(8,10,18,0.72); backdrop-filter: blur(10px); display: none; align-items: center; justify-content: center; z-index: 100; padding: 18px; }
+ .overlay.show { display: flex; }
+ .modal { background: var(--panel); border: 1px solid var(--border-strong); border-radius: 16px; width: 100%; max-width: 540px; max-height: calc(100dvh - 36px); overflow: auto; box-shadow: 0 24px 80px rgba(0,0,0,0.5); }
+ .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; }
+ .form-error { padding: 10px 12px; border-radius: 8px; background: #1f1416; border: 1px solid #7f1d1d; color: #fca5a5; font-size: 12px; font-family: var(--mono); margin-top: 4px; }
+ .form-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 14px; }
+
+ .toast { position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%) translateY(20px); background: var(--panel); border: 1px solid var(--border-strong); padding: 12px 18px; border-radius: 10px; font-size: 13px; box-shadow: 0 12px 40px rgba(0,0,0,0.4); opacity: 0; pointer-events: none; transition: opacity 0.2s, transform 0.2s; z-index: 200; }
+ .toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
+ .toast.err { border-color: #7f1d1d; color: #fca5a5; }
+
+ .skeleton { background: linear-gradient(90deg, transparent, rgba(255,255,255,0.05), transparent); background-size: 200% 100%; animation: shim 1.4s linear infinite; border-radius: 8px; }
+ @keyframes shim { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+ .gate { text-align: center; padding: 80px 24px; }
+ .gate h2 { font-size: 20px; margin: 0 0 8px; }
+ .gate p { color: var(--muted); margin: 0 0 22px; }
+</style>
+</head>
+<body>
+
+<header>
+ <a class="brand" href="/x402"><div class="dot"></div><span>x402</span></a>
+ <span class="crumb">/ Console</span>
+ <div class="right">
+ <span class="save-state" id="saveState"></span>
+ <a href="/dashboard/x402" class="btn ghost sm">Checkout SKUs</a>
+ <button class="btn" id="topSave">Save changes</button>
+ </div>
+</header>
+
+<div id="app">
+ <div class="shell" id="shell" style="display:none">
+ <nav class="side">
+ <div class="nav-item active" data-tab="overview"><svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></svg><span>Overview</span></div>
+ <div class="nav-item" data-tab="payout"><svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="6" width="20" height="13" rx="2.5"/><path d="M2 10h20"/><circle cx="17.5" cy="14.5" r="1.3" fill="currentColor"/></svg><span>Payout & Wallets</span></div>
+ <div class="nav-item" data-tab="products"><svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M3 9l1.5-5h15L21 9M3 9h18M3 9v10a1.5 1.5 0 0 0 1.5 1.5h15A1.5 1.5 0 0 0 21 19V9M9 13h6"/></svg><span>Products</span><span class="badge" id="prodBadge">0</span></div>
+ <div class="nav-item" data-tab="storefront"><svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18M8 4v5"/></svg><span>Storefront</span></div>
+ <div class="nav-sep"></div>
+ <div class="nav-item" data-tab="developers"><svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M9 8l-5 4 5 4M15 8l5 4-5 4"/></svg><span>Developers</span></div>
+ <div class="nav-item" data-tab="cors"><svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg><span>CORS & Domains</span></div>
+ <div class="nav-item" data-tab="security"><svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 3l8 3v6c0 4.5-3 7.8-8 9-5-1.2-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg><span>Security</span></div>
+ </nav>
+
+ <main>
+ <!-- ───── OVERVIEW ───── -->
+ <section class="tab active" data-tab="overview">
+ <h1 class="panel-title">Console</h1>
+ <p class="panel-sub">Everything you need to accept x402 stablecoin payments — payout wallets, products, pricing, a hosted storefront, API keys, and security. The Stripe of x402.</p>
+ <div class="stats">
+ <div class="stat"><div class="k">Products</div><div class="v" id="ov-prods">—</div></div>
+ <div class="stat"><div class="k">Paid calls</div><div class="v" id="ov-calls">—</div></div>
+ <div class="stat"><div class="k">Gross revenue</div><div class="v" id="ov-rev">—<span class="u">USDC</span></div></div>
+ <div class="stat"><div class="k">Storefront</div><div class="v" id="ov-store" style="font-size:15px">—</div></div>
+ </div>
+ <div class="card">
+ <h3>Get paid in 4 steps</h3>
+ <p class="card-sub">Complete each to start collecting real on-chain payments.</p>
+ <div class="checklist" id="checklist"></div>
+ </div>
+ </section>
+
+ <!-- ───── PAYOUT & WALLETS ───── -->
+ <section class="tab" data-tab="payout">
+ <h1 class="panel-title">Payout & agent wallets</h1>
+ <p class="panel-sub">Where settled funds land and which wallets your agents may transact from. Buyers pay USDC; the facilitator settles on-chain. <b>Double-check every address — payments are irreversible.</b></p>
+
+ <div class="card">
+ <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:14px">
+ <div><h3>Agent wallets</h3><p class="card-sub" style="margin-bottom:0">Named wallets your agents use to <b>auto-pay</b> (payer) or <b>receive</b> (payout) x402 — each capped independently. Run a fleet that transacts with no human in the loop.</p></div>
+ <button class="btn sm" id="newWallet" style="flex:0 0 auto">+ Add wallet</button>
+ </div>
+ <div id="walletList" style="margin-top:16px"></div>
+ </div>
+
+ <div class="card">
+ <h3>Default settlement network</h3>
+ <p class="card-sub">Which chain new products quote in by default.</p>
+ <div class="seg" id="defaultNet">
+ <button data-net="base" class="on">Base</button>
+ <button data-net="solana">Solana</button>
+ </div>
+ </div>
+
+ <div class="card">
+ <h3>Default payout addresses</h3>
+ <p class="card-sub">Fallback destination per chain when a product has no dedicated payout agent wallet. Use a wallet you control — these receive real money.</p>
+ <label class="field">
+ Base · EVM payout address
+ <input id="payout_evm" class="mono" placeholder="0x0000000000000000000000000000000000000000" spellcheck="false" autocomplete="off" />
+ <span class="hint" id="evmHint">USDC on Base settles here. Must be a 42-char 0x address.</span>
+ </label>
+ <label class="field">
+ Solana payout address
+ <input id="payout_solana" class="mono" placeholder="So11111111111111111111111111111111111111112" spellcheck="false" autocomplete="off" />
+ <span class="hint" id="solHint">USDC on Solana settles here. Base58, 32–44 chars.</span>
+ </label>
+ </div>
+
+ <div class="card">
+ <h3>Business identity</h3>
+ <p class="card-sub">Shown on hosted checkout pages and your storefront.</p>
+ <div class="row-2">
+ <label class="field">Business name<input id="business_name" maxlength="80" placeholder="Acme Intelligence" /></label>
+ <label class="field">Support email<input id="support_email" type="email" placeholder="[email protected]" /></label>
+ </div>
+ <div class="row-2">
+ <label class="field">Logo URL<input id="logo_url" class="mono" placeholder="https://acme.com/logo.png" spellcheck="false" /></label>
+ <label class="field">Accent color<input id="accent_color" type="color" value="#0a84ff" style="height:44px;padding:5px" /></label>
+ </div>
+ </div>
+ </section>
+
+ <!-- ───── PRODUCTS ───── -->
+ <section class="tab" data-tab="products">
+ <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:8px">
+ <div>
+ <h1 class="panel-title" style="margin-bottom:4px">Products</h1>
+ <p class="panel-sub" style="margin-bottom:0">Each product is a paid endpoint with a price. Sell them on your storefront or as standalone checkout links.</p>
+ </div>
+ <button class="btn" id="newProd" style="flex:0 0 auto;margin-top:4px">+ New product</button>
+ </div>
+ <div id="prodList" style="margin-top:20px"></div>
+ </section>
+
+ <!-- ───── STOREFRONT ───── -->
+ <section class="tab" data-tab="storefront">
+ <h1 class="panel-title">Storefront builder</h1>
+ <p class="panel-sub">Drag blocks onto the canvas to compose a hosted store — no code. Publish to a public <span class="mono" style="font-size:12px">/store/&lt;handle&gt;</span> page that takes real x402 payments.</p>
+
+ <div class="card">
+ <div class="toggle-row">
+ <div class="tr-text"><b>Publish storefront</b><span>Make your store live at a public URL.</span></div>
+ <label class="switch"><input type="checkbox" id="store_published" /><span class="slider"></span></label>
+ </div>
+ <label class="field" style="margin-top:14px">
+ Store handle
+ <div class="add-row">
+ <input id="store_handle" class="mono" placeholder="acme" spellcheck="false" autocomplete="off" />
+ <a class="btn ghost sm" id="viewStore" target="_blank" style="white-space:nowrap">View store ↗</a>
+ </div>
+ <span class="hint" id="handleHint">Public URL: <span id="handlePreview" class="mono">/store/acme</span></span>
+ </label>
+ </div>
+
+ <div class="builder">
+ <div class="palette" id="palette">
+ <div class="pal-block" draggable="true" data-type="hero"><svg class="pico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M7 10h10M7 14h6"/></svg>Hero</div>
+ <div class="pal-block" draggable="true" data-type="products"><svg class="pico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg>Product grid</div>
+ <div class="pal-block" draggable="true" data-type="product"><svg class="pico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="5" y="3" width="14" height="18" rx="2"/><path d="M9 17h6"/></svg>Featured product</div>
+ <div class="pal-block" draggable="true" data-type="text"><svg class="pico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 6h16M4 12h16M4 18h10"/></svg>Text</div>
+ <div class="pal-block" draggable="true" data-type="image"><svg class="pico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M21 16l-5-5L5 20"/></svg>Image</div>
+ <div class="pal-block" draggable="true" data-type="button"><svg class="pico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="8" width="18" height="8" rx="4"/></svg>Button</div>
+ <div class="pal-block" draggable="true" data-type="divider"><svg class="pico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M3 12h18"/></svg>Divider</div>
+ <div class="pal-block" draggable="true" data-type="footer"><svg class="pico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="15" width="18" height="5" rx="1.5"/><path d="M6 4h12M6 8h8"/></svg>Footer</div>
+ </div>
+
+ <div>
+ <div class="canvas" id="canvas">
+ <div class="canvas-empty" id="canvasEmpty">Drag blocks here, or tap a block on the left to add it.<br />Reorder by dragging. Click a block to edit.</div>
+ </div>
+ <div style="margin-top:16px">
+ <div class="preview-bar">
+ <span style="font-size:12px;color:var(--muted);font-weight:600">LIVE PREVIEW</span>
+ <span class="url" id="previewUrl">/store/acme</span>
+ <button class="btn ghost sm" id="refreshPreview">Refresh</button>
+ </div>
+ <div class="preview-frame"><iframe id="previewFrame" title="Storefront preview"></iframe></div>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <!-- ───── DEVELOPERS ───── -->
+ <section class="tab" data-tab="developers">
+ <h1 class="panel-title">Developers</h1>
+ <p class="panel-sub">API keys, webhooks, and the endpoints that power your checkout. Drop the snippet into any site to start charging.</p>
+
+ <div class="card">
+ <h3>API key</h3>
+ <p class="card-sub">Use for the key-bypass lane and server-to-server calls. Shown once at creation — store it securely.</p>
+ <div class="key-box" id="keyBox"><span class="kb-val" id="keyVal">No key yet</span><button class="btn ghost sm" id="copyKey" style="display:none">Copy</button></div>
+ <div style="margin-top:12px;display:flex;gap:10px"><button class="btn" id="rotateKey">Generate new key</button></div>
+ </div>
+
+ <div class="card">
+ <h3>Settlement webhook</h3>
+ <p class="card-sub">We POST a signed event to this URL on every successful payment.</p>
+ <label class="field">Webhook URL<input id="webhook_url" class="mono" placeholder="https://acme.com/hooks/x402" spellcheck="false" /></label>
+ </div>
+
+ <div class="card">
+ <h3>Facilitator</h3>
+ <p class="card-sub">Override the settlement facilitator. Leave blank to use the three.ws default (PayAI on Solana, Coinbase CDP on Base).</p>
+ <label class="field">Facilitator URL<input id="facilitator" class="mono" placeholder="https://facilitator.example.com" spellcheck="false" /><span class="hint">Advanced — only set this if you run your own x402 facilitator.</span></label>
+ </div>
+
+ <div class="card">
+ <h3>Drop-in snippet</h3>
+ <p class="card-sub">One script tag plus a button. The modal handles wallet connect, signing, settlement, and the receipt.</p>
+ <div class="code" id="snippet"><button class="copy" data-copy>Copy</button><span id="snippetCode"></span></div>
+ </div>
+
+ <div class="card">
+ <h3>Platform endpoints</h3>
+ <p class="card-sub">The x402 plumbing behind your checkout.</p>
+ <div class="code"><span>GET /api/x402-skus?slug=&lt;slug&gt; public product read
+POST /api/x402-checkout?action=prepare build Solana payment tx
+POST /api/x402-checkout?action=encode wrap signed tx → X-PAYMENT
+GET /api/x402-merchant?store=&lt;handle&gt; public storefront read
+POST /api/x402-merchant?action=rotate-key mint a fresh API key</span></div>
+ </div>
+ </section>
+
+ <!-- ───── CORS & DOMAINS ───── -->
+ <section class="tab" data-tab="cors">
+ <h1 class="panel-title">CORS & domains</h1>
+ <p class="panel-sub">Restrict which sites may embed your checkout. Leave empty to allow any origin (good for public, paid endpoints).</p>
+ <div class="card">
+ <h3>Allowed origins</h3>
+ <p class="card-sub">Exact origins only — scheme + host (+ port). e.g. <span class="mono" style="font-size:12px">https://acme.com</span></p>
+ <div class="chips" id="corsChips"></div>
+ <div class="add-row">
+ <input id="corsInput" class="mono" placeholder="https://acme.com" spellcheck="false" />
+ <button class="btn ghost" id="corsAdd">Add</button>
+ </div>
+ </div>
+ </section>
+
+ <!-- ───── SECURITY ───── -->
+ <section class="tab" data-tab="security">
+ <h1 class="panel-title">Security</h1>
+ <p class="panel-sub">Caps and gates that protect you and your buyers. Caps are enforced in the modal before any wallet signs.</p>
+
+ <div class="card">
+ <h3>Spending caps</h3>
+ <p class="card-sub">Block payments above these USDC limits. Leave blank for no cap.</p>
+ <div class="row-2">
+ <label class="field">Per-call cap (USDC)<input id="cap_call" type="number" min="0" step="0.000001" placeholder="e.g. 5" /></label>
+ <label class="field">Daily cap (USDC)<input id="cap_day" type="number" min="0" step="0.000001" placeholder="e.g. 100" /></label>
+ </div>
+ </div>
+
+ <div class="card">
+ <h3>Accepted networks</h3>
+ <p class="card-sub">Chains your checkout will settle on.</p>
+ <div class="toggle-row"><div class="tr-text"><b>Base</b><span>USDC via EIP-3009 · instant, gasless for the buyer.</span></div><label class="switch"><input type="checkbox" id="net_base" /><span class="slider"></span></label></div>
+ <div class="toggle-row"><div class="tr-text"><b>Solana</b><span>USDC via SPL transfer · sponsored fees.</span></div><label class="switch"><input type="checkbox" id="net_solana" /><span class="slider"></span></label></div>
+ </div>
+
+ <div class="card">
+ <h3>Re-entry</h3>
+ <div class="toggle-row"><div class="tr-text"><b>Require sign-in with wallet (SIWX)</b><span>Buyers who already paid sign in to re-access instead of paying again.</span></div><label class="switch"><input type="checkbox" id="require_siwx" /><span class="slider"></span></label></div>
+ </div>
+ </section>
+ </main>
+ </div>
+
+ <div class="gate" id="gate" style="display:none">
+ <h2>Sign in to open your x402 Console</h2>
+ <p>Configure payout wallets, products, your storefront, and security in one place.</p>
+ <a class="btn" href="/login?redirect=/dashboard/x402-admin">Sign in</a>
+ </div>
+
+ <div class="gate" id="loadingGate">
+ <div class="skeleton" style="height:24px;width:200px;margin:0 auto 14px"></div>
+ <div class="skeleton" style="height:14px;width:320px;margin:0 auto"></div>
+ </div>
+</div>
+
+<!-- Product modal -->
+<div class="overlay" id="prodModal">
+ <div class="modal">
+ <div class="modal-head"><h3 id="pmTitle">New product</h3><button class="modal-close" id="pmClose">✕</button></div>
+ <form class="modal-body" id="prodForm">
+ <div class="row-2">
+ <label class="field">Name<input name="action_name" required maxlength="80" placeholder="Reputation report" /></label>
+ <label class="field">URL slug<input name="slug" required class="mono" pattern="^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$" placeholder="reputation-report" /></label>
+ </div>
+ <label class="field">Description<textarea name="description" maxlength="2000" placeholder="What does this charge for?"></textarea></label>
+ <label class="field">Paid endpoint (returns 402)<input name="target_endpoint" type="url" required class="mono" placeholder="https://api.acme.com/paid/report" /></label>
+ <div class="row-2">
+ <label class="field">Method<select name="target_method"><option>GET</option><option>POST</option></select></label>
+ <label class="field">Price network<select name="price_network"><option value="base">Base</option><option value="solana">Solana</option></select></label>
+ </div>
+ <div class="row-2">
+ <label class="field">Price (USDC, display)<input name="price_display" type="number" min="0" step="0.000001" placeholder="0.05" /><span class="hint">Shown on cards. Actual charge comes from the endpoint's 402.</span></label>
+ <label class="field">Image URL<input name="image_url" type="url" class="mono" placeholder="https://…/product.png" /></label>
+ </div>
+ <label class="field" id="pmBodyLabel" style="display:none">Request body (JSON)<textarea name="target_body" class="mono" placeholder='{"address":"…"}'></textarea></label>
+ <div class="row-2">
+ <label class="field">Merchant label<input name="merchant_name" required maxlength="80" placeholder="Acme" /></label>
+ <label class="field">Active<select name="active"><option value="true">Active</option><option value="false">Hidden</option></select></label>
+ </div>
+ <div id="pmError" class="form-error" style="display:none"></div>
+ <div class="form-actions"><button type="button" class="btn ghost" id="pmCancel">Cancel</button><button type="submit" class="btn" id="pmSave">Create</button></div>
+ </form>
+ </div>
+</div>
+
+<div class="toast" id="toast"></div>
+
+<script type="module">
+const $ = (id) => document.getElementById(id);
+const api = {
+ get: (u) => fetch(u, { credentials: 'include' }),
+ json: async (u, method, body) => {
+ const r = await fetch(u, { method, credentials: 'include', headers: { 'content-type': 'application/json' }, body: body ? JSON.stringify(body) : undefined });
+ const d = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);
+ return d;
+ },
+};
+function esc(s){ return String(s==null?'':s).replace(/[&<>"']/g,(c)=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
+function toast(msg, isErr){ const t=$('toast'); t.textContent=msg; t.className='toast show'+(isErr?' err':''); setTimeout(()=>t.className='toast',2200); }
+function fmtUsdc(atomics){ const n=Number(atomics||0)/1e6; if(!n)return '0'; 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); }
+const toAtomics = (usdc) => { const n=Number(usdc); if(!isFinite(n)||n<=0)return null; return String(Math.round(n*1e6)); };
+
+let settings = null;
+let products = [];
+let dirty = false;
+let saveTimer = null;
+
+// ── Boot ──
+async function boot(){
+ try {
+ const r = await api.get('/api/x402-merchant');
+ if (r.status === 401){ $('loadingGate').style.display='none'; $('gate').style.display='block'; return; }
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ settings = (await r.json()).settings;
+ await loadProducts();
+ $('loadingGate').style.display='none';
+ $('shell').style.display='grid';
+ hydrate();
+ renderAll();
+ } catch (e) {
+ $('loadingGate').innerHTML = `<h2>Couldn't load console</h2><p>${esc(e.message)}</p><button class="btn ghost" onclick="location.reload()">Retry</button>`;
+ }
+}
+
+async function loadProducts(){
+ try { const r = await api.get('/api/x402-skus'); if (r.ok) products = (await r.json()).skus || []; }
+ catch { products = []; }
+}
+
+// ── Hydrate form fields from settings ──
+function hydrate(){
+ const s = settings;
+ $('payout_evm').value = s.payout_evm || '';
+ $('payout_solana').value = s.payout_solana || '';
+ $('business_name').value = s.business_name || '';
+ $('support_email').value = s.support_email || '';
+ $('logo_url').value = s.logo_url || '';
+ $('accent_color').value = s.accent_color || '#0a84ff';
+ setNetSeg(s.default_network || 'base');
+ $('webhook_url').value = s.webhook_url || '';
+ $('store_handle').value = s.store_handle || '';
+ $('store_published').checked = !!s.store_published;
+ $('cap_call').value = s.spend_cap_per_call_atomics ? fmtUsdc(s.spend_cap_per_call_atomics) : '';
+ $('cap_day').value = s.spend_cap_daily_atomics ? fmtUsdc(s.spend_cap_daily_atomics) : '';
+ const nets = Array.isArray(s.allowed_networks) ? s.allowed_networks : ['base','solana'];
+ $('net_base').checked = nets.includes('base');
+ $('net_solana').checked = nets.includes('solana');
+ $('require_siwx').checked = !!s.require_siwx;
+ if (s.api_key_prefix){ $('keyVal').textContent = s.api_key_prefix + '…'; }
+ renderCors();
+ layout = Array.isArray(s.store_layout) ? structuredClone(s.store_layout) : [];
+ renderCanvas();
+ updateHandlePreview();
+ updateSnippet();
+}
+
+// ── Collect settings from form into a patch ──
+function collect(){
+ const nets = [];
+ if ($('net_base').checked) nets.push('base');
+ if ($('net_solana').checked) nets.push('solana');
+ return {
+ payout_evm: $('payout_evm').value.trim() || null,
+ payout_solana: $('payout_solana').value.trim() || null,
+ business_name: $('business_name').value.trim() || null,
+ support_email: $('support_email').value.trim() || null,
+ logo_url: $('logo_url').value.trim() || null,
+ accent_color: $('accent_color').value || '#0a84ff',
+ default_network: currentNet,
+ webhook_url: $('webhook_url').value.trim() || null,
+ store_handle: $('store_handle').value.trim().toLowerCase() || null,
+ store_published: $('store_published').checked,
+ store_layout: layout,
+ cors_origins: corsOrigins,
+ spend_cap_per_call_atomics: toAtomics($('cap_call').value),
+ spend_cap_daily_atomics: toAtomics($('cap_day').value),
+ allowed_networks: nets.length ? nets : ['base','solana'],
+ require_siwx: $('require_siwx').checked,
+ };
+}
+
+// ── Save (explicit + autosave) ──
+async function save(){
+ const patch = collect();
+ // Client-side address guards — block obviously bad payout wallets.
+ if (patch.payout_evm && !/^0x[0-9a-fA-F]{40}$/.test(patch.payout_evm)){ goTab('payout'); toast('Base payout address is invalid', true); return; }
+ if (patch.payout_solana && !/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(patch.payout_solana)){ goTab('payout'); toast('Solana payout address is invalid', true); return; }
+ setSaveState('saving');
+ try {
+ const d = await api.json('/api/x402-merchant', 'PUT', patch);
+ settings = d.settings;
+ dirty = false;
+ setSaveState('saved');
+ renderOverview();
+ updateHandlePreview();
+ refreshPreview();
+ } catch (e) {
+ setSaveState('error');
+ toast(e.message, true);
+ }
+}
+function markDirty(){ dirty = true; setSaveState('unsaved'); clearTimeout(saveTimer); saveTimer = setTimeout(save, 1200); }
+function setSaveState(st){
+ const el = $('saveState');
+ el.className = 'save-state ' + (st === 'saved' ? 'saved' : st === 'saving' ? 'saving' : st === 'error' ? 'error' : '');
+ el.textContent = st === 'saving' ? 'Saving…' : st === 'saved' ? '✓ Saved' : st === 'error' ? 'Save failed' : st === 'unsaved' ? 'Unsaved' : '';
+ if (st === 'saved') setTimeout(()=>{ if(!dirty){ el.textContent=''; el.className='save-state'; } }, 2400);
+}
+
+// Watch all setting inputs.
+['payout_evm','payout_solana','business_name','support_email','logo_url','accent_color','webhook_url','store_handle','cap_call','cap_day']
+ .forEach((id)=> $(id).addEventListener('input', markDirty));
+['store_published','net_base','net_solana','require_siwx'].forEach((id)=> $(id).addEventListener('change', markDirty));
+$('topSave').addEventListener('click', save);
+
+// Live address validation feedback
+function validateAddr(id, re, hintId, okMsg){
+ const el = $(id); const v = el.value.trim();
+ el.classList.toggle('valid', !!v && re.test(v));
+ el.classList.toggle('invalid', !!v && !re.test(v));
+ if (hintId){ const h=$(hintId); if(v && !re.test(v)){ h.textContent='That doesn\'t look like a valid address.'; h.classList.add('warn'); } else { h.classList.remove('warn'); h.textContent = okMsg; } }
+}
+$('payout_evm').addEventListener('input', ()=> validateAddr('payout_evm', /^0x[0-9a-fA-F]{40}$/, 'evmHint', 'USDC on Base settles here. Must be a 42-char 0x address.'));
+$('payout_solana').addEventListener('input', ()=> validateAddr('payout_solana', /^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'solHint', 'USDC on Solana settles here. Base58, 32–44 chars.'));
+$('store_handle').addEventListener('input', updateHandlePreview);
+
+// ── Tabs ──
+function goTab(name){
+ document.querySelectorAll('nav.side .nav-item').forEach((n)=> n.classList.toggle('active', n.dataset.tab===name));
+ document.querySelectorAll('main .tab').forEach((t)=> t.classList.toggle('active', t.dataset.tab===name));
+ if (name==='storefront') refreshPreview();
+ if (location.hash !== '#'+name) history.replaceState(null,'','#'+name);
+}
+document.querySelectorAll('nav.side .nav-item').forEach((n)=> n.addEventListener('click', ()=> goTab(n.dataset.tab)));
+
+// ── Default network segmented ──
+let currentNet = 'base';
+function setNetSeg(net){ currentNet = net; $('defaultNet').querySelectorAll('button').forEach((b)=> b.classList.toggle('on', b.dataset.net===net)); }
+$('defaultNet').querySelectorAll('button').forEach((b)=> b.addEventListener('click', ()=>{ setNetSeg(b.dataset.net); markDirty(); }));
+
+// ── CORS chips ──
+let corsOrigins = [];
+function renderCors(){
+ corsOrigins = Array.isArray(settings.cors_origins) ? [...settings.cors_origins] : [];
+ drawCors();
+}
+function drawCors(){
+ const wrap = $('corsChips');
+ if (!corsOrigins.length){ wrap.innerHTML = `<span style="color:var(--muted-2);font-size:12.5px">No restrictions — any origin may embed your checkout.</span>`; return; }
+ wrap.innerHTML = corsOrigins.map((o,i)=>`<span class="chip">${esc(o)}<button data-i="${i}" aria-label="remove">✕</button></span>`).join('');
+ wrap.querySelectorAll('button').forEach((b)=> b.addEventListener('click', ()=>{ corsOrigins.splice(+b.dataset.i,1); drawCors(); markDirty(); }));
+}
+function addCors(){
+ const v = $('corsInput').value.trim();
+ if (!v) return;
+ if (!/^https?:\/\/[a-z0-9.-]+(:\d+)?$/i.test(v)){ toast('Enter an origin like https://acme.com', true); return; }
+ if (corsOrigins.includes(v)){ toast('Already added'); return; }
+ corsOrigins.push(v); $('corsInput').value=''; drawCors(); markDirty();
+}
+$('corsAdd').addEventListener('click', addCors);
+$('corsInput').addEventListener('keydown', (e)=>{ if(e.key==='Enter'){ e.preventDefault(); addCors(); } });
+
+// ── API key rotation ──
+$('rotateKey').addEventListener('click', async ()=>{
+ if (settings.api_key_prefix && !confirm('Generate a new key? The old key stops working immediately.')) return;
+ $('rotateKey').disabled = true;
+ try {
+ const d = await api.json('/api/x402-merchant?action=rotate-key', 'POST');
+ $('keyVal').textContent = d.api_key;
+ $('copyKey').style.display = '';
+ $('copyKey').onclick = async ()=>{ await navigator.clipboard.writeText(d.api_key); toast('API key copied'); };
+ settings.api_key_prefix = d.api_key_prefix;
+ toast('New key generated — copy it now, it won\'t be shown again');
+ } catch(e){ toast(e.message, true); }
+ finally { $('rotateKey').disabled = false; }
+});
+$('copyKey').addEventListener('click', async ()=>{ await navigator.clipboard.writeText($('keyVal').textContent); toast('Copied'); });
+
+// Snippet copy
+document.querySelector('#snippet .copy').addEventListener('click', async (e)=>{
+ await navigator.clipboard.writeText($('snippetCode').textContent);
+ e.target.textContent='✓ Copied'; e.target.classList.add('copied');
+ setTimeout(()=>{ e.target.textContent='Copy'; e.target.classList.remove('copied'); }, 1600);
+});
+function updateSnippet(){
+ const ex = products[0];
+ const ep = ex ? ex.target_endpoint : 'https://api.acme.com/paid/report';
+ $('snippetCode').textContent =
+`<script type="module" src="https://three.ws/x402.js"><\/script>
+
+<button
+ data-x402-endpoint="${ep}"
+ data-x402-merchant="${settings.business_name || 'Acme'}"
+ data-x402-action="${ex ? ex.action_name : 'Run'}">
+ Pay & run
+</button>`;
+}
+
+// ───────── Products ─────────
+function renderProducts(){
+ const list = $('prodList');
+ $('prodBadge').textContent = products.length;
+ if (!products.length){
+ list.innerHTML = `<div class="empty"><h4>No products yet</h4><p>Create your first paid endpoint — set a price and it shows up on your storefront.</p><p style="margin-top:16px"><button class="btn" id="emptyNew">+ New product</button></p></div>`;
+ $('emptyNew')?.addEventListener('click', ()=> openProd(null));
+ return;
+ }
+ list.innerHTML = `<div class="prod-list">${products.map((p)=>{
+ const price = p.price_atomics ? `${fmtUsdc(p.price_atomics)} USDC` : '—';
+ const net = p.price_network ? p.price_network : 'live 402';
+ const img = p.image_url ? `<img src="${esc(p.image_url)}" alt="">` : esc((p.merchant_name||p.action_name||'·')[0]);
+ return `<div class="prod-card ${p.active===false?'inactive':''}" data-id="${p.id}">
+ <div class="pc-img">${img}</div>
+ <div><div class="pc-name">${esc(p.action_name)}</div><div class="pc-meta">/pay/c/${esc(p.slug)} · ${esc(net)}${p.paid_calls?` · ${p.paid_calls} calls`:''}</div></div>
+ <div class="pc-price">${esc(price)}</div>
+ <div class="pc-actions"><button class="btn ghost sm" data-act="edit">Edit</button><button class="btn ghost sm" data-act="link">Link</button></div>
+ </div>`;
+ }).join('')}</div>`;
+ list.querySelectorAll('.prod-card').forEach((row)=>{
+ const p = products.find((x)=> x.id===row.dataset.id);
+ row.querySelector('[data-act="edit"]').addEventListener('click', ()=> openProd(p));
+ row.querySelector('[data-act="link"]').addEventListener('click', async ()=>{ await navigator.clipboard.writeText(`${location.origin}/pay/c/${p.slug}`); toast('Checkout link copied'); });
+ });
+}
+
+const prodModal = $('prodModal'), prodForm = $('prodForm');
+let editingProd = null;
+function openProd(p){
+ editingProd = p;
+ $('pmTitle').textContent = p ? 'Edit product' : 'New product';
+ $('pmSave').textContent = p ? 'Save' : 'Create';
+ $('pmError').style.display='none';
+ prodForm.reset();
+ prodForm.merchant_name.value = settings.business_name || '';
+ prodForm.price_network.value = currentNet;
+ if (p){
+ prodForm.action_name.value = p.action_name || '';
+ prodForm.slug.value = p.slug || '';
+ prodForm.description.value = p.description || '';
+ prodForm.target_endpoint.value = p.target_endpoint || '';
+ prodForm.target_method.value = p.target_method || 'GET';
+ prodForm.price_network.value = p.price_network || currentNet;
+ prodForm.price_display.value = p.price_atomics ? fmtUsdc(p.price_atomics) : '';
+ prodForm.image_url.value = p.image_url || '';
+ prodForm.merchant_name.value = p.merchant_name || '';
+ prodForm.active.value = p.active===false ? 'false' : 'true';
+ if (p.target_body) prodForm.target_body.value = JSON.stringify(p.target_body, null, 2);
+ }
+ toggleBody();
+ prodModal.classList.add('show');
+}
+function closeProd(){ prodModal.classList.remove('show'); editingProd=null; }
+function toggleBody(){ $('pmBodyLabel').style.display = prodForm.target_method.value==='POST' ? '' : 'none'; }
+prodForm.target_method.addEventListener('change', toggleBody);
+$('newProd').addEventListener('click', ()=> openProd(null));
+$('pmClose').addEventListener('click', closeProd);
+$('pmCancel').addEventListener('click', closeProd);
+prodModal.addEventListener('click', (e)=>{ if(e.target===prodModal) closeProd(); });
+
+prodForm.addEventListener('submit', async (e)=>{
+ e.preventDefault();
+ $('pmError').style.display='none'; $('pmSave').disabled=true;
+ try {
+ const fd = new FormData(prodForm);
+ const payload = {
+ slug: fd.get('slug').trim(),
+ action_name: fd.get('action_name').trim(),
+ merchant_name: fd.get('merchant_name').trim(),
+ target_endpoint: fd.get('target_endpoint').trim(),
+ target_method: fd.get('target_method'),
+ price_network: fd.get('price_network'),
+ active: fd.get('active')==='true',
+ };
+ const desc = fd.get('description').trim(); if (desc) payload.description = desc;
+ const img = fd.get('image_url').trim(); if (img) payload.image_url = img;
+ const price = toAtomics(fd.get('price_display')); if (price) payload.price_atomics = price;
+ const body = fd.get('target_body').trim();
+ if (payload.target_method==='POST' && body){ try { payload.target_body = JSON.parse(body); } catch { throw new Error('Request body must be valid JSON'); } }
+ const url = editingProd ? `/api/x402-skus?id=${editingProd.id}` : '/api/x402-skus';
+ await api.json(url, editingProd ? 'PATCH' : 'POST', payload);
+ closeProd();
+ await loadProducts();
+ renderProducts(); renderOverview(); updateSnippet(); renderProductPickers(); refreshPreview();
+ toast(editingProd ? 'Product saved' : 'Product created');
+ } catch (err) { $('pmError').textContent = err.message; $('pmError').style.display=''; }
+ finally { $('pmSave').disabled=false; }
+});
+
+// ───────── Storefront builder ─────────
+let layout = [];
+let blockSeq = 0;
+const BLOCK_DEFAULTS = {
+ hero: () => ({ heading: settings.business_name || 'Welcome', subheading: 'Pay-per-call APIs, settled on-chain.', label: 'Browse', align: 'center' }),
+ products: () => ({ heading: 'Products', sku_ids: [] }),
+ product: () => ({ sku_id: products[0]?.id }),
+ text: () => ({ body: 'Tell buyers what you offer.', align: 'left' }),
+ image: () => ({ image_url: '' }),
+ button: () => ({ label: 'Learn more', href: '' }),
+ divider: () => ({}),
+ footer: () => ({ body: '© ' + (settings.business_name || 'Your store') }),
+};
+function newBlock(type){ return { id: 'b'+(++blockSeq)+'_'+Math.round(performance.now()), type, ...BLOCK_DEFAULTS[type]() }; }
+
+function renderCanvas(){
+ const c = $('canvas');
+ if (!layout.length){ c.innerHTML = `<div class="canvas-empty" id="canvasEmpty">Drag blocks here, or tap a block on the left to add it.<br>Reorder by dragging. Click a block to edit.</div>`; return; }
+ c.innerHTML = layout.map((b)=> blockEditorHtml(b)).join('');
+ bindBlocks();
+}
+function blockSummary(b){
+ if (b.type==='hero') return b.heading||'';
+ if (b.type==='products') return (b.sku_ids?.length||0)+' products';
+ if (b.type==='product'){ const p=products.find(x=>x.id===b.sku_id); return p?p.action_name:'pick a product'; }
+ if (b.type==='text'||b.type==='footer') return (b.body||'').slice(0,40);
+ if (b.type==='image') return b.image_url||'no image';
+ if (b.type==='button') return b.label||'';
+ return '';
+}
+function blockEditorHtml(b){
+ return `<div class="cblock" data-id="${b.id}" draggable="true">
+ <div class="cblock-head"><span class="grip">⋮⋮</span><span class="ctype">${b.type}</span><span class="csum">${esc(blockSummary(b))}</span><button class="cdel" aria-label="delete">✕</button></div>
+ <div class="cblock-body">${blockFields(b)}</div>
+ </div>`;
+}
+function blockFields(b){
+ const f = [];
+ const txt = (k,label,ph='') => `<label class="field">${label}<input data-k="${k}" value="${esc(b[k]||'')}" placeholder="${ph}" /></label>`;
+ const area = (k,label,ph='') => `<label class="field">${label}<textarea data-k="${k}" placeholder="${ph}">${esc(b[k]||'')}</textarea></label>`;
+ const align = () => `<label class="field">Align<select data-k="align"><option value="left"${b.align==='left'?' selected':''}>Left</option><option value="center"${b.align!=='left'?' selected':''}>Center</option></select></label>`;
+ if (b.type==='hero'){ f.push(txt('heading','Heading'), area('subheading','Subheading'), txt('label','Button label'), align()); }
+ else if (b.type==='products'){ f.push(txt('heading','Section heading'), productMultiHtml(b)); }
+ else if (b.type==='product'){ f.push(productPickHtml(b)); }
+ else if (b.type==='text'){ f.push(txt('heading','Heading (optional)'), area('body','Text'), align()); }
+ else if (b.type==='image'){ f.push(txt('image_url','Image URL','https://…'), txt('href','Links to (optional)','https://…')); }
+ else if (b.type==='button'){ f.push(txt('label','Label'), txt('href','URL','https://…')); }
+ else if (b.type==='footer'){ f.push(area('body','Footer text')); }
+ else if (b.type==='divider'){ f.push(`<div style="color:var(--muted-2);font-size:12.5px">A horizontal divider. No settings.</div>`); }
+ return f.join('');
+}
+function productPickHtml(b){
+ if (!products.length) return `<div style="color:var(--amber);font-size:12.5px">Create a product first (Products tab).</div>`;
+ return `<label class="field">Product<select data-k="sku_id">${products.map((p)=>`<option value="${p.id}"${b.sku_id===p.id?' selected':''}>${esc(p.action_name)}</option>`).join('')}</select></label>`;
+}
+function productMultiHtml(b){
+ if (!products.length) return `<div style="color:var(--amber);font-size:12.5px">Create products first to feature them here.</div>`;
+ const sel = new Set(b.sku_ids||[]);
+ return `<div class="field" style="text-transform:none"><span style="font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.03em">Products in grid</span>
+ <div style="display:flex;flex-direction:column;gap:6px;margin-top:6px">${products.map((p)=>`<label style="display:flex;gap:9px;align-items:center;font-size:13px;color:var(--text);cursor:pointer"><input type="checkbox" data-multi="${p.id}" ${sel.has(p.id)?'checked':''} style="width:auto">${esc(p.action_name)}</label>`).join('')}</div>
+ <span class="hint" style="margin-top:6px">Leave all unchecked to show every active product.</span></div>`;
+}
+function renderProductPickers(){ renderCanvas(); }
+
+function bindBlocks(){
+ const c = $('canvas');
+ c.querySelectorAll('.cblock').forEach((el)=>{
+ const id = el.dataset.id;
+ const b = layout.find((x)=> x.id===id);
+ el.querySelector('.cblock-head').addEventListener('click', (e)=>{ if (e.target.closest('.cdel')) return; el.classList.toggle('open'); });
+ el.querySelector('.cdel').addEventListener('click', ()=>{ layout = layout.filter((x)=> x.id!==id); renderCanvas(); markDirty(); refreshPreview(); });
+ el.querySelectorAll('[data-k]').forEach((inp)=>{
+ inp.addEventListener('input', ()=>{ b[inp.dataset.k] = inp.value; el.querySelector('.csum').textContent = blockSummary(b); markDirty(); schedulePreview(); });
+ inp.addEventListener('click', (e)=> e.stopPropagation());
+ });
+ el.querySelectorAll('[data-multi]').forEach((cb)=>{
+ cb.addEventListener('change', ()=>{ const ids = [...c.querySelectorAll('[data-multi]:checked')].map((x)=> x.dataset.multi); b.sku_ids = ids; el.querySelector('.csum').textContent = blockSummary(b); markDirty(); schedulePreview(); });
+ cb.addEventListener('click', (e)=> e.stopPropagation());
+ });
+ // keep open if it was open
+ el.addEventListener('dragstart', (e)=>{ dragId = id; el.classList.add('dragging'); e.dataTransfer.effectAllowed='move'; });
+ el.addEventListener('dragend', ()=>{ dragId=null; el.classList.remove('dragging'); c.querySelectorAll('.drop-target').forEach((x)=> x.classList.remove('drop-target')); });
+ el.addEventListener('dragover', (e)=>{ e.preventDefault(); if(!dragId||dragId===id)return; el.classList.add('drop-target'); });
+ el.addEventListener('dragleave', ()=> el.classList.remove('drop-target'));
+ el.addEventListener('drop', (e)=>{ e.preventDefault(); el.classList.remove('drop-target'); if(!dragId||dragId===id)return; reorder(dragId, id); });
+ });
+}
+let dragId = null;
+function reorder(from, to){
+ const fi = layout.findIndex((x)=> x.id===from), ti = layout.findIndex((x)=> x.id===to);
+ if (fi<0||ti<0) return;
+ const [m] = layout.splice(fi,1); layout.splice(ti,0,m);
+ renderCanvas(); markDirty(); refreshPreview();
+}
+// Palette → canvas DnD + click-to-add
+$('palette').querySelectorAll('.pal-block').forEach((pb)=>{
+ pb.addEventListener('dragstart', (e)=>{ e.dataTransfer.setData('text/x402-type', pb.dataset.type); e.dataTransfer.effectAllowed='copy'; });
+ pb.addEventListener('click', ()=>{ layout.push(newBlock(pb.dataset.type)); renderCanvas(); markDirty(); refreshPreview(); goEndOfCanvas(); });
+});
+const canvas = $('canvas');
+canvas.addEventListener('dragover', (e)=>{ if (e.dataTransfer.types.includes('text/x402-type')){ e.preventDefault(); canvas.classList.add('drag-over'); } });
+canvas.addEventListener('dragleave', (e)=>{ if (e.target===canvas) canvas.classList.remove('drag-over'); });
+canvas.addEventListener('drop', (e)=>{
+ const type = e.dataTransfer.getData('text/x402-type');
+ canvas.classList.remove('drag-over');
+ if (!type) return;
+ e.preventDefault();
+ layout.push(newBlock(type)); renderCanvas(); markDirty(); refreshPreview();
+});
+function goEndOfCanvas(){ const c=$('canvas'); c.scrollIntoView({behavior:'smooth',block:'nearest'}); }
+
+// Handle + preview
+function updateHandlePreview(){
+ const h = ($('store_handle').value.trim().toLowerCase()) || 'your-store';
+ $('handlePreview').textContent = '/store/'+h;
+ $('previewUrl').textContent = '/store/'+h + (settings.store_published?'':' (draft)');
+ $('viewStore').href = '/store/'+h;
+ $('viewStore').style.pointerEvents = $('store_handle').value.trim() ? '' : 'none';
+ $('viewStore').style.opacity = $('store_handle').value.trim() ? '' : '0.5';
+}
+let previewTimer = null;
+function schedulePreview(){ clearTimeout(previewTimer); previewTimer = setTimeout(refreshPreview, 600); }
+function refreshPreview(){
+ const frame = $('previewFrame');
+ if (!frame) return;
+ const data = { store: { business_name: $('business_name').value || 'Your store', logo_url: $('logo_url').value || null, accent_color: $('accent_color').value, store_handle: $('store_handle').value || 'preview', store_layout: layout, store_theme: {} }, products };
+ frame.srcdoc = renderStoreHtml(data, true);
+}
+$('refreshPreview').addEventListener('click', refreshPreview);
+$('store_published').addEventListener('change', updateHandlePreview);
+
+// Shared storefront renderer (also used standalone by /store). Kept inline so
+// the preview and the live page render identically.
+function renderStoreHtml(data, isPreview){
+ const s = data.store, prods = data.products || [];
+ const accent = (s.store_theme && s.store_theme.accent) || s.accent_color || '#0a84ff';
+ const byId = (id)=> prods.find((p)=> p.id===id);
+ const priceLabel = (p)=> p.price_atomics ? `${(Number(p.price_atomics)/1e6).toString()} USDC` : 'Pay-per-call';
+ const card = (p)=> p ? `<div class="p-card">
+ <div class="p-img">${p.image_url?`<img src="${esc(p.image_url)}" alt="">`:esc((p.merchant_name||p.action_name||'·')[0])}</div>
+ <div class="p-name">${esc(p.action_name)}</div>
+ <div class="p-desc">${esc(p.description||'')}</div>
+ <div class="p-foot"><span class="p-price">${esc(priceLabel(p))}</span>
+ <button class="p-buy" ${isPreview?'disabled':''} data-x402-endpoint="${esc(p.target_endpoint||'')}" data-x402-method="${esc(p.target_method||'GET')}" data-x402-merchant="${esc(p.merchant_name||s.business_name||'')}" data-x402-action="${esc(p.action_name)}">Buy</button></div>
+ </div>` : '';
+ const block = (b)=>{
+ const al = b.align==='left'?'left':'center';
+ if (b.type==='hero') return `<section class="b-hero" style="text-align:${al}"><h1>${esc(b.heading||'')}</h1>${b.subheading?`<p>${esc(b.subheading)}</p>`:''}${b.label?`<a class="b-cta" href="#products">${esc(b.label)}</a>`:''}</section>`;
+ if (b.type==='products'){ const ids=b.sku_ids&&b.sku_ids.length?b.sku_ids:prods.map(p=>p.id); return `<section class="b-products" id="products">${b.heading?`<h2>${esc(b.heading)}</h2>`:''}<div class="p-grid">${ids.map(byId).filter(Boolean).map(card).join('')||'<p class="b-empty">No products yet.</p>'}</div></section>`; }
+ if (b.type==='product'){ const p=byId(b.sku_id); return `<section class="b-feature">${card(p)||'<p class="b-empty">Pick a product.</p>'}</section>`; }
+ if (b.type==='text') return `<section class="b-text" style="text-align:${al}">${b.heading?`<h2>${esc(b.heading)}</h2>`:''}${b.body?`<p>${esc(b.body)}</p>`:''}</section>`;
+ if (b.type==='image') return `<section class="b-image">${b.image_url?(b.href?`<a href="${esc(b.href)}"><img src="${esc(b.image_url)}" alt=""></a>`:`<img src="${esc(b.image_url)}" alt="">`):'<div class="b-imgph">Image</div>'}</section>`;
+ if (b.type==='button') return `<section class="b-btnwrap"><a class="b-cta" href="${esc(b.href||'#')}">${esc(b.label||'Button')}</a></section>`;
+ if (b.type==='divider') return `<hr class="b-div">`;
+ if (b.type==='footer') return `<footer class="b-footer">${esc(b.body||'')}</footer>`;
+ return '';
+ };
+ const body = (s.store_layout||[]).map(block).join('') || '<section class="b-text"><p class="b-empty">This store has no content yet.</p></section>';
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>${esc(s.business_name||'Store')}</title>
+<style>
+:root{--accent:${accent}}*{box-sizing:border-box}html,body{margin:0;background:#fff;color:#111;font-family:-apple-system,BlinkMacSystemFont,Inter,"Segoe UI",Roboto,sans-serif;-webkit-font-smoothing:antialiased;line-height:1.55}
+.b-hero{padding:80px 24px 56px;max-width:760px;margin:0 auto}.b-hero h1{font-size:clamp(32px,6vw,52px);font-weight:800;letter-spacing:-.03em;margin:0 0 14px}.b-hero p{font-size:18px;color:#555;margin:0 0 26px;max-width:60ch;margin-left:auto;margin-right:auto}
+.b-cta{display:inline-block;background:var(--accent);color:#fff;padding:13px 26px;border-radius:11px;font-weight:600;text-decoration:none}
+.b-products,.b-text,.b-feature{max-width:1040px;margin:0 auto;padding:30px 24px}.b-products h2,.b-text h2{font-size:26px;font-weight:700;letter-spacing:-.02em;margin:0 0 22px}
+.p-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:16px}
+.p-card{border:1px solid #e6e8ee;border-radius:16px;padding:20px;display:flex;flex-direction:column;gap:10px;background:#fff;transition:box-shadow .15s,transform .08s}
+.p-card:hover{box-shadow:0 12px 32px rgba(0,0,0,.07);transform:translateY(-2px)}
+.p-img{width:52px;height:52px;border-radius:13px;background:linear-gradient(135deg,var(--accent),#60a5fa);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:22px;overflow:hidden}.p-img img{width:100%;height:100%;object-fit:cover}
+.p-name{font-weight:700;font-size:17px;letter-spacing:-.01em}.p-desc{color:#667;font-size:13.5px;flex:1;min-height:36px}
+.p-foot{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:4px}.p-price{font-weight:700;color:#0a7d3a;font-size:14px}
+.p-buy{background:#111;color:#fff;border:none;border-radius:10px;padding:10px 20px;font-weight:600;font-size:14px;cursor:pointer;font-family:inherit}.p-buy:hover:not(:disabled){background:#000}.p-buy:disabled{opacity:.5;cursor:default}
+.b-feature .p-card{max-width:420px;margin:0 auto}
+.b-image{max-width:1040px;margin:0 auto;padding:18px 24px}.b-image img{width:100%;border-radius:16px;display:block}.b-imgph{height:240px;border:1px dashed #ccc;border-radius:16px;display:flex;align-items:center;justify-content:center;color:#aaa}
+.b-btnwrap{text-align:center;padding:20px}.b-div{border:none;border-top:1px solid #eaecf1;max-width:1040px;margin:18px auto}
+.b-footer{padding:40px 24px;text-align:center;color:#889;font-size:13px;border-top:1px solid #eef0f4;margin-top:30px}
+.b-empty{color:#99a;text-align:center}
+@media (prefers-color-scheme:dark){html,body{background:#0b0b0b;color:#f0f2f8}.p-card{background:#161616;border-color:#272727}.b-hero p,.p-desc{color:#9aa0b8}.p-buy{background:#fff;color:#111}.b-div{border-color:#222}.b-footer{border-color:#222;color:#777}.b-imgph{border-color:#333}}
+</style></head><body>${body}
+${isPreview?'':'<script type="module" src="/x402.js"><\/script>'}
+</body></html>`;
+}
+// expose for the standalone /store page via querystring? No — /store has its own copy.
+
+// ── Overview ──
+function renderOverview(){
+ const calls = products.reduce((a,p)=> a+(p.paid_calls||0), 0);
+ const gross = products.reduce((a,p)=> a+Number(p.gross_atomics||0), 0);
+ $('ov-prods').textContent = products.length;
+ $('ov-calls').textContent = calls;
+ $('ov-rev').innerHTML = `${fmtUsdc(gross)}<span class="u">USDC</span>`;
+ $('ov-store').innerHTML = settings.store_published && settings.store_handle ? `<a href="/store/${esc(settings.store_handle)}" target="_blank">Live ↗</a>` : '<span style="color:var(--muted)">Draft</span>';
+ const checks = [
+ { done: !!(settings.payout_evm || settings.payout_solana), main: 'Add a payout wallet', sub: 'Where your USDC settles', tab: 'payout' },
+ { done: products.length>0, main: 'Create a product', sub: 'A paid endpoint with a price', tab: 'products' },
+ { done: (settings.store_layout||[]).length>0, main: 'Build your storefront', sub: 'Drag blocks onto the canvas', tab: 'storefront' },
+ { done: !!settings.store_published, main: 'Publish your store', sub: 'Go live at /store/'+(settings.store_handle||'<handle>'), tab: 'storefront' },
+ ];
+ $('checklist').innerHTML = checks.map((c)=>`<div class="check-item ${c.done?'done':''}" data-tab="${c.tab}" style="cursor:pointer"><div class="dot2">${c.done?'✓':''}</div><div class="ci-text"><span class="ci-main" style="font-weight:600;color:var(--text)">${esc(c.main)}</span><span>${esc(c.sub)}</span></div></div>`).join('');
+ $('checklist').querySelectorAll('.check-item').forEach((el)=> el.addEventListener('click', ()=> goTab(el.dataset.tab)));
+}
+
+function renderAll(){ renderOverview(); renderProducts(); updateSnippet(); }
+
+// Warn on unsaved navigation
+window.addEventListener('beforeunload', (e)=>{ if (dirty){ e.preventDefault(); e.returnValue=''; } });
+
+// Deep-link to tab via hash
+if (location.hash){ const t = location.hash.slice(1); if (document.querySelector(`nav.side .nav-item[data-tab="${t}"]`)) setTimeout(()=> goTab(t), 0); }
+
+boot();
+</script>
+
+<script src="/brand.js" defer></script>
+</body>
+</html>
diff --git a/public/features.json b/public/features.json
index 4f6dc0aeb..72533b8fb 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T22:37:56.338Z",
+ "generated_at": "2026-06-19T22:44:40.535Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/mirror/face-tracker.js b/src/mirror/face-tracker.js
index b2fffc52f..340ef6fc1 100644
--- a/src/mirror/face-tracker.js
+++ b/src/mirror/face-tracker.js
@@ -244,12 +244,8 @@ export class FaceTracker {
throw err;
}
- try {
- await this.init();
- } catch (err) {
- // init() already emitted a typed error; re-surface to the caller.
- throw err;
- }
+ // init() already emits a typed error on failure; let it surface to the caller.
+ await this.init();
this._video = videoEl;
this._setStatus('requesting-camera');
diff --git a/walk-sdk/src/playground.js b/walk-sdk/src/playground.js
index 10c0c27b3..ec9ff70b4 100644
--- a/walk-sdk/src/playground.js
+++ b/walk-sdk/src/playground.js
@@ -40,6 +40,7 @@ import {
clamp,
} from './internal/storage.js';
import { loadWalkAvatar } from './internal/load-avatar.js';
+import { createAvatarPicker } from './picker.js';
import { resolveConfig, resolveAvatarEntry } from './config.js';
// Active config — set by launchPlayground. Defaults keep the module usable if a
@@ -136,6 +137,89 @@ function modeButtonHTML(mode) {
return `<button type="button" class="walk-pg-mode" aria-label="Switch movement mode (currently ${label})" title="Switch mode (M)"><span class="walk-pg-mode-ic" aria-hidden="true">${icon}</span><span class="walk-pg-mode-tx">${label}</span></button>`;
}
+// The "choose avatar" button shown in the playground toolbar. Only rendered when
+// the picker is enabled; carries `data-walk-picker-toggle` so the picker's
+// outside-click dismiss ignores re-clicks on the button itself.
+function pickButtonHTML() {
+ return `<button type="button" class="walk-pg-pick" data-walk-picker-toggle aria-label="Choose your avatar" title="Choose avatar (C)"><span class="walk-pg-pick-ic" aria-hidden="true">🧑</span><span class="walk-pg-pick-tx">Avatar</span></button>`;
+}
+
+// Free a model's GPU resources (geometries, materials, textures) when it leaves
+// the rig after a live avatar swap. Mirrors the per-mesh disposal in teardown.
+function disposeModel(model) {
+ model.traverse((n) => {
+ if (!n.isMesh) return;
+ n.geometry?.dispose?.();
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ mats.forEach((m) => {
+ if (!m) return;
+ for (const v of Object.values(m)) if (v && v.isTexture) v.dispose();
+ m.dispose?.();
+ });
+ });
+}
+
+// Open (or toggle) the avatar picker for a running playground. Lazily builds the
+// popover once, then reuses it. Selecting an avatar hot-swaps the live rig.
+function openAvatarPicker(pg) {
+ if (_config.enablePicker === false) return;
+ if (!pg._picker) {
+ pg._picker = createAvatarPicker({
+ avatars: _config.avatars,
+ currentId: pg._avatarId || _config.defaultAvatarId,
+ assetBase: _config.assetBase,
+ docsUrl: _config.docsUrl,
+ onSelect: (entry) => swapAvatar(pg, entry),
+ });
+ }
+ pg._picker.toggle();
+}
+
+// Reload the chosen avatar and swap it into the live rig without leaving the
+// playground. Persists the selection to the shared companion/playground key so
+// the choice carries across mode switches, the corner companion, and pages.
+async function swapAvatar(pg, idOrEntry) {
+ const entry =
+ typeof idOrEntry === 'string' ? resolveAvatarEntry(idOrEntry, _config) : idOrEntry;
+ if (!entry || !pg.mounted || !pg.rig) return;
+ if (entry.id === pg._avatarId) return;
+ pg._avatarId = entry.id;
+ try {
+ localStorage.setItem(_config.keys.avatar, entry.id);
+ } catch {
+ /* non-fatal — selection still applies for this session */
+ }
+ pg._picker?.setCurrent(entry.id);
+ pg._say?.('Switching…', 4000);
+ try {
+ const next = await loadCharacter(entry.id, pg._charPx);
+ if (!pg.mounted || !pg.rig) {
+ disposeModel(next.model);
+ next.controller?.dispose?.();
+ return;
+ }
+ if (pg.model) {
+ pg.rig.remove(pg.model);
+ disposeModel(pg.model);
+ }
+ pg.controller?.dispose?.();
+ pg.rig.add(next.model);
+ pg.model = next.model;
+ pg.controller = next.controller;
+ pg.modelHalfW = next.halfW;
+ if (typeof pg._shadowR === 'number') pg._shadowR = Math.max(22, next.halfW * 1.15);
+ pg._say?.(`Say hi to ${entry.name}!`);
+ } catch (err) {
+ log.warn('avatar swap failed:', err?.message || err);
+ pg._say?.('Couldn’t load that one — try another.');
+ }
+}
+
+function destroyPicker(pg) {
+ pg._picker?.destroy();
+ pg._picker = null;
+}
+
// Load + scale the chosen avatar to a fixed pixel height, feet at the rig
// origin. Goes through the shared unified loader so any roster avatar animates.
async function loadCharacter(avatarId, charPx) {
@@ -183,6 +267,9 @@ class StrollPlayground {
this._spawnGuardUntil = 0;
this._v0 = new Vector3();
this._v1 = new Vector3();
+ this._picker = null;
+ this.model = null;
+ this._charPx = CHAR_PX;
}
async mount({ avatarId = null, startScreen = null, dropIn = false, switched = false } = {}) {
@@ -219,6 +306,7 @@ class StrollPlayground {
window.removeEventListener('keyup', this._onKeyUp, true);
window.removeEventListener('resize', this._onResize);
this._clearArm();
+ destroyPicker(this);
this._teardown();
}
@@ -235,6 +323,7 @@ class StrollPlayground {
host.innerHTML = `
<canvas class="walk-pg-canvas"></canvas>
<div class="walk-pg-hint" aria-live="polite"></div>
+ ${_config.enablePicker === false ? '' : pickButtonHTML()}
${modeButtonHTML(this.mode)}
<button type="button" class="walk-pg-exit" aria-label="Exit playground" title="Exit (Esc)">Exit ✕</button>
<div class="walk-pg-pad" aria-hidden="true">
@@ -255,6 +344,10 @@ class StrollPlayground {
this.flashEl = host.querySelector('.walk-pg-flash');
host.querySelector('.walk-pg-exit').addEventListener('click', () => exitPlayground());
host.querySelector('.walk-pg-mode').addEventListener('click', () => switchPlaygroundMode());
+ host.querySelector('.walk-pg-pick')?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ openAvatarPicker(this);
+ });
host.querySelectorAll('.walk-pg-btn').forEach((btn) => {
const act = btn.getAttribute('data-act');
const on = (e) => {
@@ -318,6 +411,7 @@ class StrollPlayground {
this.modelHalfW = halfW;
this._shadowR = Math.max(22, halfW * 1.15);
rig.add(model);
+ this.model = model;
this.controller = controller;
}
@@ -374,6 +468,8 @@ class StrollPlayground {
_onKeyDown(e) {
const k = e.key;
+ // While the picker is open it owns the keyboard (search, arrows, Escape).
+ if (this._picker?.isOpen()) return;
if (k === 'Escape') {
exitPlayground();
return;
@@ -383,6 +479,11 @@ class StrollPlayground {
switchPlaygroundMode();
return;
}
+ if (k === 'c' || k === 'C') {
+ e.preventDefault();
+ openAvatarPicker(this);
+ return;
+ }
let handled = true;
if (k === 'ArrowLeft' || k === 'a' || k === 'A') this.input.left = true;
else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = true;
@@ -616,6 +717,9 @@ class PlatformerPlayground {
this._armAt = 0;
this._armHref = null;
this._diving = false;
+ this._picker = null;
+ this.model = null;
+ this._charPx = PLAT_CHAR_PX;
}
async mount({ avatarId = null, startScreen = null, dropIn = false, switched = false } = {}) {
@@ -655,6 +759,7 @@ class PlatformerPlayground {
window.removeEventListener('resize', this._onResize);
window.removeEventListener('scroll', this._scheduleRescan, true);
this._clearArm();
+ destroyPicker(this);
this._teardown();
}
@@ -674,6 +779,7 @@ class PlatformerPlayground {
host.innerHTML = `
<canvas class="walk-pg-canvas"></canvas>
<div class="walk-pg-hint" aria-live="polite"></div>
+ ${_config.enablePicker === false ? '' : pickButtonHTML()}
${modeButtonHTML(this.mode)}
<button type="button" class="walk-pg-exit" aria-label="Exit playground" title="Exit (Esc)">Exit ✕</button>
<div class="walk-pg-pad" aria-hidden="true">
@@ -691,6 +797,10 @@ class PlatformerPlayground {
this.flashEl = host.querySelector('.walk-pg-flash');
host.querySelector('.walk-pg-exit').addEventListener('click', () => exitPlayground());
host.querySelector('.walk-pg-mode').addEventListener('click', () => switchPlaygroundMode());
+ host.querySelector('.walk-pg-pick')?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ openAvatarPicker(this);
+ });
host.querySelectorAll('.walk-pg-btn').forEach((btn) => {
const act = btn.getAttribute('data-act');
const on = (e) => {
@@ -752,6 +862,7 @@ class PlatformerPlayground {
const { model, controller, halfW } = await loadCharacter(this._avatarId, PLAT_CHAR_PX);
this.modelHalfW = halfW;
rig.add(model);
+ this.model = model;
this.controller = controller;
}
@@ -843,6 +954,8 @@ class PlatformerPlayground {
_onKeyDown(e) {
const k = e.key;
+ // While the picker is open it owns the keyboard (search, arrows, Escape).
+ if (this._picker?.isOpen()) return;
if (k === 'Escape') {
exitPlayground();
return;
@@ -852,6 +965,11 @@ class PlatformerPlayground {
switchPlaygroundMode();
return;
}
+ if (k === 'c' || k === 'C') {
+ e.preventDefault();
+ openAvatarPicker(this);
+ return;
+ }
let handled = true;
if (k === 'ArrowLeft' || k === 'a' || k === 'A') this.input.left = true;
else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = true;
@@ -1121,6 +1239,11 @@ function ensureStyles() {
.walk-pg-mode:active{transform:scale(.96)}
.walk-pg-mode:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
.walk-pg-mode-ic{font-size:14px;line-height:1}
+.walk-pg-pick{position:fixed;top:14px;right:192px;z-index:3;pointer-events:auto;display:inline-flex;align-items:center;gap:6px;border:1px solid rgba(255,255,255,.16);background:rgba(14,16,22,.72);color:#f2f4f8;font:600 12.5px/1 system-ui,sans-serif;padding:9px 13px;border-radius:999px;cursor:pointer;backdrop-filter:blur(6px);transition:background .2s ease,transform .15s ease}
+.walk-pg-pick:hover{background:rgba(122,162,255,.55)}
+.walk-pg-pick:active{transform:scale(.96)}
+.walk-pg-pick:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
+.walk-pg-pick-ic{font-size:14px;line-height:1}
.walk-pg-hint{position:fixed;left:50%;bottom:22px;transform:translateX(-50%) translateY(8px);z-index:3;pointer-events:none;max-width:88vw;width:max-content;background:rgba(18,20,28,.92);color:#f2f4f8;font:500 13px/1.4 system-ui,sans-serif;padding:9px 14px;border-radius:12px;border:1px solid rgba(255,255,255,.1);box-shadow:0 10px 28px rgba(0,0,0,.35);opacity:0;transition:opacity .3s ease,transform .3s ease;text-align:center}
.walk-pg-hint.is-in{opacity:1;transform:translateX(-50%) translateY(0)}
.walk-pg-btn{pointer-events:auto;border:1px solid rgba(255,255,255,.18);background:rgba(16,18,26,.78);color:#fff;display:grid;place-items:center;backdrop-filter:blur(6px);-webkit-user-select:none;user-select:none;touch-action:none}
@@ -1137,7 +1260,7 @@ function ensureStyles() {
.walk-pg-portal{outline:2px solid rgba(122,162,255,.9)!important;outline-offset:3px;border-radius:6px;box-shadow:0 0 0 4px rgba(122,162,255,.18),0 0 28px rgba(122,162,255,.45)!important;transition:box-shadow .2s ease,transform .25s ease;animation:walk-pg-pulse 1.1s ease-in-out infinite}
.walk-pg-portal.is-open{transform:scale(.94);box-shadow:0 0 0 6px rgba(122,162,255,.3),0 0 48px rgba(122,162,255,.7)!important}
@keyframes walk-pg-pulse{0%,100%{box-shadow:0 0 0 4px rgba(122,162,255,.16),0 0 22px rgba(122,162,255,.35)}50%{box-shadow:0 0 0 6px rgba(122,162,255,.3),0 0 36px rgba(122,162,255,.6)}}
-@media (pointer: coarse){.walk-pg--stroll .walk-pg-pad,.walk-pg--plat .walk-pg-pad{display:flex}.walk-pg--stroll .walk-pg-hint{bottom:200px}.walk-pg--plat .walk-pg-hint{bottom:110px}.walk-pg-mode .walk-pg-mode-tx{display:none}.walk-pg-mode{right:84px}}
+@media (pointer: coarse){.walk-pg--stroll .walk-pg-pad,.walk-pg--plat .walk-pg-pad{display:flex}.walk-pg--stroll .walk-pg-hint{bottom:200px}.walk-pg--plat .walk-pg-hint{bottom:110px}.walk-pg-mode .walk-pg-mode-tx{display:none}.walk-pg-mode{right:84px}.walk-pg-pick .walk-pg-pick-tx{display:none}.walk-pg-pick{right:132px}}
@media (prefers-reduced-motion:reduce){.walk-pg,.walk-pg-hint,.walk-pg-flash{transition:none}.walk-pg-portal{animation:none}}
`;
document.head.appendChild(style);
diff --git a/x402-payment-modal/server/checkout.js b/x402-payment-modal/server/checkout.js
index 51aa18edc..a7739b84e 100644
--- a/x402-payment-modal/server/checkout.js
+++ b/x402-payment-modal/server/checkout.js
@@ -41,6 +41,105 @@ export const NETWORK_SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
const DEFAULT_MAINNET_RPC = 'https://api.mainnet-beta.solana.com';
const DEFAULT_DEVNET_RPC = 'https://api.devnet.solana.com';
+// ─────────────────────────────────────────────── Well-known Solana tokens ────
+// The two settlement assets the modal treats as first-class on Solana. USDC is
+// the universal dollar-stable rail; THREE is the three.ws utility token, so any
+// endpoint can let holders pay in THREE alongside USDC. `solanaAccept()` builds
+// the x402 `accept` entry for either (or any other SPL mint) — the prepare path
+// already transfers any mint, so offering THREE needs no further wiring.
+export const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+export const WELL_KNOWN_SOLANA_TOKENS = Object.freeze({
+ usdc: { mint: USDC_MINT_SOLANA, symbol: 'USDC', name: 'USD Coin', decimals: 6 },
+ three: { mint: THREE_MINT, symbol: 'THREE', name: 'THREE', decimals: 6 },
+});
+
+/**
+ * Build one x402 Solana `accept` entry for a merchant's 402 challenge.
+ *
+ * Pass `token: 'usdc' | 'three'` for a well-known asset, or an explicit `mint`
+ * (+ optional `decimals`/`name`) for any other SPL token. Supply the price as
+ * either `amount` (atomic integer string) or `uiAmount` (human units, converted
+ * with the token's decimals). `feePayer` is the facilitator sponsor that pays
+ * the SOL network fee so buyers need only the token itself.
+ *
+ * @param {object} args
+ * @param {'usdc'|'three'} [args.token] well-known token shortcut
+ * @param {string} [args.mint] explicit SPL mint (base58); overrides token
+ * @param {string} args.payTo recipient address (base58)
+ * @param {string} args.feePayer facilitator sponsor address (base58)
+ * @param {string|number|bigint} [args.amount] atomic integer amount
+ * @param {string|number} [args.uiAmount] human amount (e.g. 0.25) — converted via decimals
+ * @param {number} [args.decimals] token decimals (default: well-known or 6)
+ * @param {string} [args.name] display name for the modal (default: well-known symbol)
+ * @param {string} [args.network] CAIP-2 network (default: Solana mainnet)
+ * @param {number} [args.maxTimeoutSeconds]
+ * @returns {SolanaAccept}
+ */
+export function solanaAccept({
+ token,
+ mint,
+ payTo,
+ feePayer,
+ amount,
+ uiAmount,
+ decimals,
+ name,
+ network = NETWORK_SOLANA_MAINNET,
+ maxTimeoutSeconds,
+} = {}) {
+ const known = token ? WELL_KNOWN_SOLANA_TOKENS[String(token).toLowerCase()] : null;
+ if (token && !known) {
+ throw new CheckoutError(400, 'invalid_request', `unknown token '${token}'. Use 'usdc', 'three', or pass an explicit mint.`);
+ }
+ const asset = mint || known?.mint;
+ if (!asset) {
+ throw new CheckoutError(400, 'invalid_request', "solanaAccept needs a token ('usdc'|'three') or an explicit mint");
+ }
+ assertPubkey(asset, 'mint');
+ assertPubkey(payTo, 'payTo');
+ assertPubkey(feePayer, 'feePayer');
+
+ const dec = Number.isFinite(decimals) ? decimals : (known?.decimals ?? 6);
+ let atomic;
+ if (amount != null) {
+ atomic = BigInt(amount).toString();
+ } else if (uiAmount != null) {
+ atomic = uiToAtomic(uiAmount, dec);
+ } else {
+ throw new CheckoutError(400, 'invalid_request', 'solanaAccept needs amount (atomic) or uiAmount (human)');
+ }
+
+ const accept = {
+ scheme: 'exact',
+ network,
+ amount: atomic,
+ asset,
+ payTo,
+ extra: {
+ name: name || known?.name || 'USDC',
+ decimals: dec,
+ feePayer,
+ },
+ };
+ if (maxTimeoutSeconds != null) accept.maxTimeoutSeconds = maxTimeoutSeconds;
+ return accept;
+}
+
+// Convert a human token amount (e.g. "0.25", 1.5) to an atomic integer string
+// without floating-point drift: split on the decimal point and pad/truncate.
+function uiToAtomic(uiAmount, decimals) {
+ const s = String(uiAmount).trim();
+ if (!/^\d+(\.\d+)?$/.test(s)) {
+ throw new CheckoutError(400, 'invalid_request', `uiAmount must be a non-negative number, got '${uiAmount}'`);
+ }
+ const [whole, frac = ''] = s.split('.');
+ const fracPadded = (frac + '0'.repeat(decimals)).slice(0, decimals);
+ const atomic = BigInt(whole) * 10n ** BigInt(decimals) + BigInt(fracPadded || '0');
+ return atomic.toString();
+}
+
// Short-lived caches so repeated prepare calls don't re-issue identical RPC
// round-trips. Mint decimals are effectively immutable; a Solana blockhash stays
// valid for ~60-90s, so a few seconds of reuse cuts redundant traffic without
diff --git a/x402-payment-modal/src/index.js b/x402-payment-modal/src/index.js
index 4256bffa5..b855e571c 100644
--- a/x402-payment-modal/src/index.js
+++ b/x402-payment-modal/src/index.js
@@ -134,6 +134,57 @@ function normalizeAccept(accept) {
return amount != null && accept.amount == null ? { ...accept, amount: String(amount) } : accept;
}
+// ─────────────────────────────────────────────── Well-known Solana tokens ────
+// Mints the modal recognizes on sight, so a 402 `accept` can omit
+// `extra.name`/`extra.decimals` and still render with the correct symbol,
+// decimals, and branding. Two settlement assets are first-class on Solana:
+// • USDC — the universal dollar-stable rail.
+// • THREE — the three.ws utility token. Holders can pay any x402 endpoint
+// that opts into accepting it, right alongside USDC. See three.ws/three-token.
+// A merchant offers THREE simply by adding a Solana `accept` whose `asset` is
+// THREE_MINT (the server checkout transfers any SPL mint, so no extra wiring).
+export const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+export const KNOWN_SOLANA_TOKENS = Object.freeze({
+ [USDC_MINT_SOLANA]: { symbol: 'USDC', name: 'USD Coin', decimals: 6, stable: true },
+ [THREE_MINT]: { symbol: 'THREE', name: 'THREE', decimals: 6, accent: '#7aa2ff', glyph: '◆' },
+});
+
+// Resolve display metadata for an `accept`. A merchant-supplied `extra.name`/
+// `extra.decimals` always wins; otherwise we fall back to the known-token
+// registry keyed by mint, then to USDC defaults. Never throws.
+function tokenInfo(accept) {
+ const known = (accept && accept.asset && KNOWN_SOLANA_TOKENS[accept.asset]) || null;
+ const rawName = accept?.extra?.name;
+ const symbol = (rawName ? String(rawName).replace(/^USD Coin$/, 'USDC') : known?.symbol) || 'USDC';
+ const decimals = Number(accept?.extra?.decimals ?? known?.decimals ?? 6);
+ const stable = known?.stable || STABLE_NAMES.has(String(rawName || '').toLowerCase());
+ return { symbol, decimals, stable, accent: known?.accent || null, glyph: known?.glyph || null };
+}
+
+function isThreeAccept(accept) {
+ return accept?.asset === THREE_MINT;
+}
+
+// Every Solana `accept` the challenge offers, in challenge order. More than one
+// means the merchant accepts multiple tokens (e.g. USDC and THREE) and the buyer
+// gets to choose which to pay in.
+function listSolanaAccepts(challenge) {
+ return (challenge?.accepts || []).filter((a) => isSolanaNetwork(a.network));
+}
+
+// Default Solana token to surface first: USDC (stable, predictable price) when
+// offered, then any other stable, then the first accept. The buyer can switch.
+function pickDefaultSolana(list) {
+ return (
+ list.find((a) => a.asset === USDC_MINT_SOLANA) ||
+ list.find((a) => tokenInfo(a).stable) ||
+ list[0] ||
+ null
+ );
+}
+
function isSolanaNetwork(net) {
return typeof net === 'string' && (net === 'solana' || net.startsWith('solana:'));
}
@@ -228,9 +279,10 @@ function writeSpend(address, kind, bucket, value) {
function toMicroUsdBrowser(amount, accept) {
const atomic = BigInt(amount);
- const decimals = Number(accept?.extra?.decimals ?? 6);
+ const known = (accept && accept.asset && KNOWN_SOLANA_TOKENS[accept.asset]) || null;
+ const decimals = Number(accept?.extra?.decimals ?? known?.decimals ?? 6);
const name = String(accept?.extra?.name || '').toLowerCase();
- if (STABLE_NAMES.has(name)) {
+ if (STABLE_NAMES.has(name) || known?.stable) {
if (decimals === 6) return atomic;
if (decimals > 6) return atomic / 10n ** BigInt(decimals - 6);
return atomic * 10n ** BigInt(6 - decimals);
@@ -564,6 +616,22 @@ const STYLES = `
.x402-wallet-name { flex: 1; text-align: left; }
.x402-wallet-meta { font-size: 11px; color: #8a90a8; font-weight: 500; }
+.x402-token-row {
+ display: flex; gap: 8px; margin-bottom: 10px;
+}
+.x402-token-pill {
+ flex: 1; min-width: 0; cursor: pointer; font-family: inherit;
+ padding: 9px 12px; border-radius: 10px;
+ background: #ffffff; border: 1.5px solid #e2e5ec;
+ display: flex; flex-direction: column; align-items: flex-start; gap: 2px;
+ transition: border-color 0.12s, background 0.12s, transform 0.05s;
+}
+.x402-token-pill:hover { border-color: #c3c9d6; background: #f9fafc; }
+.x402-token-pill:active { transform: translateY(1px); }
+.x402-token-pill.x402-on { border-color: #0f0f0f; background: #f7faff; }
+.x402-token-sym { font-size: 13px; font-weight: 700; color: #0f0f0f; letter-spacing: -0.005em; }
+.x402-token-amt { font-size: 11px; color: #8a90a8; font-weight: 600; font-variant-numeric: tabular-nums; }
+
.x402-pay-btn {
width: 100%; padding: 14px 16px;
background: #0f0f0f; color: #fff; border: none;
@@ -796,17 +864,21 @@ class CheckoutModal {
}
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>`;
+ const info = tokenInfo(accept);
+ const amount = formatAmount(accept.amount, info.decimals);
+ const glyph = info.glyph ? `${info.glyph} ` : '';
+ this.priceEl.innerHTML = `${amount}<span class="x402-currency"> ${glyph}${escapeHtml(info.symbol)}</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 solanaList = listSolanaAccepts(this.challenge);
+ // Keep a valid selection: honour the buyer's prior pick if it's still on
+ // offer, otherwise fall back to the default (USDC-first).
+ let solanaAccept = solanaList.find((a) => a === this.solanaAccept) || pickDefaultSolana(solanaList);
+ this.solanaAccept = solanaAccept;
const evmAccept = this.challenge?.accepts.find(isEip3009Accept);
// SIWX-first path: when the 402 advertises sign-in-with-x AND we have a
@@ -838,13 +910,34 @@ class CheckoutModal {
if (evmViable && !solanaViable) { this.runEvm(evmAccept); return; }
}
+ // When the merchant offers more than one Solana token (e.g. USDC and
+ // THREE), let the buyer choose which to pay in. The selected token drives
+ // the headline price and the transaction the Phantom button builds.
+ const tokenChooser = solanaList.length > 1
+ ? `<div class="x402-token-row" role="group" aria-label="Choose payment token">
+ ${solanaList.map((a) => {
+ const info = tokenInfo(a);
+ const on = a === solanaAccept;
+ const amt = formatAmount(a.amount, info.decimals);
+ return `<button type="button" class="x402-token-pill${on ? ' x402-on' : ''}" data-token-asset="${escapeHtml(a.asset)}" aria-pressed="${on}"${info.accent && on ? ` style="border-color:${escapeHtml(info.accent)}"` : ''}>
+ <span class="x402-token-sym">${info.glyph ? escapeHtml(info.glyph) + ' ' : ''}${escapeHtml(info.symbol)}</span>
+ <span class="x402-token-amt">${amt}</span>
+ </button>`;
+ }).join('')}
+ </div>`
+ : '';
+
const buttons = [];
if (solanaAccept) {
+ const solInfo = tokenInfo(solanaAccept);
+ const solMeta = solanaList.length > 1
+ ? `${networkLabel(solanaAccept.network, solanaAccept)} · ${solInfo.symbol}`
+ : networkLabel(solanaAccept.network, 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>
+ <span class="x402-wallet-meta" data-sol-meta>${escapeHtml(solMeta)}</span>
</button>
`);
}
@@ -863,16 +956,39 @@ class CheckoutModal {
this.bodyEl.innerHTML = `
${this.renderSteps('connect', { discover: 'done' })}
${fallbackBox}
+ ${tokenChooser}
<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);
+ if (wallet === 'phantom') this.runSolana(this.solanaAccept);
else if (wallet === 'evm') this.runEvm(evmAccept);
};
this.bodyEl.querySelectorAll('[data-wallet]').forEach((b) => b.addEventListener('click', onClick));
+
+ // Token chooser — switch the active Solana token in place: update the
+ // headline price and the Phantom button's token label without a re-render
+ // flash, and mark the new pill pressed.
+ this.bodyEl.querySelectorAll('[data-token-asset]').forEach((pill) => {
+ pill.addEventListener('click', () => {
+ const next = solanaList.find((a) => a.asset === pill.dataset.tokenAsset);
+ if (!next || next === this.solanaAccept) return;
+ this.solanaAccept = next;
+ this.accept = next;
+ this.setPrice(next);
+ const info = tokenInfo(next);
+ const metaEl = this.bodyEl.querySelector('[data-sol-meta]');
+ if (metaEl) metaEl.textContent = `${networkLabel(next.network, next)} · ${info.symbol}`;
+ this.bodyEl.querySelectorAll('[data-token-asset]').forEach((p) => {
+ const on = p === pill;
+ p.classList.toggle('x402-on', on);
+ p.setAttribute('aria-pressed', String(on));
+ p.style.borderColor = on && info.accent ? info.accent : '';
+ });
+ });
+ });
}
renderSiwxChoice({ siwxSolana, siwxEvm }) {
@@ -999,7 +1115,9 @@ class CheckoutModal {
// Prefer Solana when Phantom is present, else first EIP-3009 EVM
// entry (skipping Permit2 siblings the modal can't sign for), else
// first accept.
- const solana = challenge.accepts.find((a) => isSolanaNetwork(a.network));
+ const solanaList = listSolanaAccepts(challenge);
+ const solana = pickDefaultSolana(solanaList);
+ this.solanaAccept = solana; // buyer-selected Solana token (USDC/THREE/…)
const evm = challenge.accepts.find(isEip3009Accept);
const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);
this.accept = (phantomDetected && solana) || evm || challenge.accepts[0];
@@ -1648,5 +1766,10 @@ if (typeof document !== 'undefined') {
// Expose to merchants' inline scripts.
if (typeof window !== 'undefined') {
- window.X402 = Object.freeze({ pay, init, configure, version: VERSION });
+ window.X402 = Object.freeze({
+ pay, init, configure, version: VERSION,
+ // Well-known Solana settlement assets, so merchants building a 402
+ // challenge inline can reference them without hardcoding base58 mints.
+ tokens: Object.freeze({ USDC_MINT_SOLANA, THREE_MINT, KNOWN_SOLANA_TOKENS }),
+ });
}
diff --git a/x402-payment-modal/types/index.d.ts b/x402-payment-modal/types/index.d.ts
index c729ccf8a..db52ab23e 100644
--- a/x402-payment-modal/types/index.d.ts
+++ b/x402-payment-modal/types/index.d.ts
@@ -105,6 +105,24 @@ export function init(): void;
/** Library version. */
export const version: string;
+/** Solana USDC mint (mainnet). */
+export const USDC_MINT_SOLANA: string;
+/** $THREE — the three.ws utility token mint. Recognized by the modal so a 402
+ * `accept` using it renders as THREE without merchant-supplied metadata. */
+export const THREE_MINT: string;
+
+export interface KnownSolanaToken {
+ symbol: string;
+ name: string;
+ decimals: number;
+ stable?: boolean;
+ accent?: string;
+ glyph?: string;
+}
+
+/** Well-known Solana settlement assets, keyed by mint address. */
+export const KNOWN_SOLANA_TOKENS: Readonly<Record<string, KnownSolanaToken>>;
+
/** Global exposed for non-module / inline-script usage. */
declare global {
interface Window {
@@ -113,6 +131,11 @@ declare global {
init: typeof init;
configure: typeof configure;
version: string;
+ tokens: {
+ USDC_MINT_SOLANA: string;
+ THREE_MINT: string;
+ KNOWN_SOLANA_TOKENS: Readonly<Record<string, KnownSolanaToken>>;
+ };
};
}
}
diff --git a/x402-payment-modal/types/server.d.ts b/x402-payment-modal/types/server.d.ts
index 6e7b9ca2a..71916f400 100644
--- a/x402-payment-modal/types/server.d.ts
+++ b/x402-payment-modal/types/server.d.ts
@@ -45,6 +45,42 @@ export const X402_VERSION: number;
export const NETWORK_SOLANA_MAINNET: string;
export const NETWORK_SOLANA_DEVNET: string;
+/** Solana USDC mint (mainnet). */
+export const USDC_MINT_SOLANA: string;
+/** $THREE — the three.ws utility token mint. */
+export const THREE_MINT: string;
+
+export interface WellKnownToken {
+ mint: string;
+ symbol: string;
+ name: string;
+ decimals: number;
+}
+
+/** Well-known Solana settlement assets, keyed by lowercase shortcut. */
+export const WELL_KNOWN_SOLANA_TOKENS: {
+ usdc: WellKnownToken;
+ three: WellKnownToken;
+};
+
+/**
+ * Build one x402 Solana `accept` entry. Pass `token: 'usdc' | 'three'` for a
+ * well-known asset or an explicit `mint`, and the price as atomic `amount` or
+ * human `uiAmount`.
+ */
+export function solanaAccept(args: {
+ token?: 'usdc' | 'three';
+ mint?: string;
+ payTo: string;
+ feePayer: string;
+ amount?: string | number | bigint;
+ uiAmount?: string | number;
+ decimals?: number;
+ name?: string;
+ network?: string;
+ maxTimeoutSeconds?: number;
+}): SolanaAccept;
+
export class CheckoutError extends Error {
status: number;
code: string;