Skip to content

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

feat: SIWX server, x402 access control + builder code, idempotency, offer receipts, e2e tests

nirholascb633b9dff1c
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 97117cd93..ffbca8058 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -98,6 +98,16 @@ export const env = {
return opt('MAINNET_RPC_URL');
},
+ // Base mainnet RPC URL — used by the SIWX server-side verifier (see
+ // api/_lib/siwx-server.js) to validate EIP-1271 / EIP-6492 smart-contract
+ // wallet signatures via viem's publicClient.verifyMessage. Without this,
+ // SIWX falls back to EOA-only verification (still works for MetaMask /
+ // Phantom EOAs; rejects Coinbase Smart Wallet, Safe, etc.). Defaults to
+ // the same RPC the club-payouts cron uses so a single env var works.
+ get BASE_RPC_URL() {
+ return opt('BASE_RPC_URL', opt('CLUB_BASE_RPC_URL'));
+ },
+
// ── ERC-7710 Delegation Relayer ──────────────────────────────────────────
// Private key of the server-held EOA that pays gas for redeemDelegations.
// NEVER log this value. Rotate via Vercel env; derive AGENT_RELAYER_ADDRESS
diff --git a/api/_lib/siwx-server.js b/api/_lib/siwx-server.js
new file mode 100644
index 000000000..9da670fac
--- /dev/null
+++ b/api/_lib/siwx-server.js
@@ -0,0 +1,127 @@
+// Server-side glue between @x402/extensions/sign-in-with-x and our
+// paidEndpoint() wrapper. Keeps the verification path, extension declaration,
+// and EVM smart-wallet verifier in one place so each new endpoint doesn't
+// have to repeat them.
+//
+// The SIWX flow:
+// 1. paidEndpoint() declares the 'sign-in-with-x' extension in every 402
+// body (declareSiwxExtensionFor below).
+// 2. A returning buyer sends `SIGN-IN-WITH-X: <base64>` instead of the
+// X-PAYMENT header. authenticateSiwx() parses, validates, verifies
+// the CAIP-122 signature, looks up the (resource, address) grant in
+// siwx_payments, and on success the handler runs without settlement.
+// 3. A fresh buyer settles with X-PAYMENT as usual; recordSiwxPayment()
+// then writes the grant so step 2 works next time.
+
+import {
+ declareSIWxExtension,
+ parseSIWxHeader,
+ validateSIWxMessage,
+ verifySIWxSignature,
+ SIGN_IN_WITH_X,
+} from '@x402/extensions/sign-in-with-x';
+import { createPublicClient, http } from 'viem';
+import { base } from 'viem/chains';
+
+import { env } from './env.js';
+import { siwxStorage, normalizeAddress } from './siwx-storage.js';
+
+export { SIGN_IN_WITH_X };
+
+// Lazily build a viem PublicClient so verifySIWxSignature can verify
+// smart-contract wallets (EIP-1271) and counterfactual wallets (EIP-6492).
+// Uses our private RPC (env.BASE_RPC_URL) to avoid leaking buyer addresses
+// to a public node. Returns undefined when BASE_RPC_URL isn't configured —
+// the upstream verifier then falls back to EOA-only verification.
+let _baseClient;
+function getEvmVerifier() {
+ if (!env.BASE_RPC_URL) return undefined;
+ if (!_baseClient) {
+ _baseClient = createPublicClient({
+ chain: base,
+ transport: http(env.BASE_RPC_URL),
+ });
+ }
+ return _baseClient.verifyMessage.bind(_baseClient);
+}
+
+export function hasEvmVerifier() {
+ return Boolean(env.BASE_RPC_URL);
+}
+
+// Build the extensions block that goes into the 402 body when SIWX is
+// enabled for an endpoint. `network` accepts the same CAIP-2 strings the
+// rest of paidEndpoint() uses (e.g. 'eip155:8453', 'solana:5eykt...').
+export function declareSiwxExtensionFor({ networks, statement, expirationSeconds = 300 }) {
+ const list = Array.isArray(networks) ? networks : [networks];
+ const unique = [...new Set(list.filter(Boolean))];
+ if (!unique.length) {
+ throw new Error('declareSiwxExtensionFor: at least one network required');
+ }
+ return declareSIWxExtension({
+ network: unique.length === 1 ? unique[0] : unique,
+ statement,
+ expirationSeconds,
+ });
+}
+
+// Given an incoming Vercel request, attempt to authenticate via
+// SIGN-IN-WITH-X. Returns:
+// { ok: true, address, network } on full success.
+// { ok: false, status, code, error } on validation / verification / grant
+// failure (caller emits the matching HTTP status).
+// null when the header is absent — caller continues with the X-PAYMENT
+// flow.
+export async function authenticateSiwx({ req, resourceUrl }) {
+ const header =
+ req.headers['sign-in-with-x'] ||
+ req.headers['SIGN-IN-WITH-X'] ||
+ req.headers['Sign-In-With-X'];
+ if (!header) return null;
+
+ let payload;
+ try {
+ payload = parseSIWxHeader(String(header));
+ } catch (err) {
+ return { ok: false, status: 400, code: 'siwx_parse_failed', error: err.message };
+ }
+
+ const validation = await validateSIWxMessage(payload, resourceUrl, {
+ maxAge: 5 * 60 * 1000,
+ checkNonce: async (n) => !(await siwxStorage.hasUsedNonce(n)),
+ });
+ if (!validation.valid) {
+ return { ok: false, status: 401, code: 'siwx_message_invalid', error: validation.error };
+ }
+
+ const verification = await verifySIWxSignature(payload, { evmVerifier: getEvmVerifier() });
+ if (!verification.valid || !verification.address) {
+ return { ok: false, status: 401, code: 'siwx_signature_invalid', error: verification.error };
+ }
+
+ const normalizedAddress = normalizeAddress(payload.chainId, verification.address);
+ if (!(await siwxStorage.hasPaid(resourceUrl, normalizedAddress))) {
+ return {
+ ok: false,
+ status: 402,
+ code: 'siwx_not_paid',
+ error: 'wallet has not paid for this resource',
+ };
+ }
+
+ await siwxStorage.recordNonce(payload.nonce, {
+ resource: resourceUrl,
+ address: normalizedAddress,
+ });
+
+ return { ok: true, address: normalizedAddress, network: payload.chainId };
+}
+
+// Record a fresh payment so the wallet can re-enter via SIWX next time. Called
+// from paidEndpoint() after a successful facilitator settle. The `payer` is the
+// canonical CAIP-122 address (lowercase hex for EVM, Base58 for Solana); the
+// caller already normalizes via normalizeAddress() before passing it in.
+export async function recordSiwxPayment({ resourceUrl, payer, network, ttlSeconds = null }) {
+ if (!payer) return;
+ await siwxStorage.recordPayment(resourceUrl, payer, { network, ttlSeconds });
+}
diff --git a/api/_lib/siwx-storage.js b/api/_lib/siwx-storage.js
new file mode 100644
index 000000000..440fe2d5e
--- /dev/null
+++ b/api/_lib/siwx-storage.js
@@ -0,0 +1,97 @@
+// Postgres-backed implementation of the @x402/extensions/sign-in-with-x
+// SIWxStorage interface. Two tables back this adapter (see
+// api/_lib/migrations/2026-05-21-siwx.sql):
+//
+// siwx_payments(resource, address, network, paid_at, expires_at,
+// last_used_at, use_count)
+// — one row per (resource, address). expires_at NULL = permanent grant
+// (downloadable assets); set to now()+TTL for time-pass access.
+//
+// siwx_nonces(nonce, resource, address, used_at)
+// — replay-protection. Garbage-collected by api/cron/siwx-gc.js.
+//
+// Address normalization happens here, not at the DB layer: CAIP-122 carries
+// addresses in their canonical-per-chain form, which differs by namespace:
+// eip155:* → lowercase hex (NOT EIP-55 checksummed)
+// solana:* → Base58 (case-sensitive, leave as-is)
+// Every read + write goes through normalizeAddress() so lookups are
+// case-insensitive on EVM while staying byte-for-byte exact on Solana.
+
+import { sql } from './db.js';
+
+// Pull off the CAIP-2 namespace ('eip155' / 'solana' / etc.) without parsing
+// the reference, so a future chain like 'eip155:42161' or 'solana:devnet'
+// shares the same normalization branch.
+function namespaceOf(chainId) {
+ if (!chainId || typeof chainId !== 'string') return null;
+ const colon = chainId.indexOf(':');
+ return colon === -1 ? chainId.toLowerCase() : chainId.slice(0, colon).toLowerCase();
+}
+
+export function normalizeAddress(chainId, address) {
+ if (!address) return address;
+ const ns = namespaceOf(chainId);
+ if (ns === 'eip155') return String(address).toLowerCase();
+ return String(address);
+}
+
+async function hasPaid(resource, address) {
+ if (!resource || !address) return false;
+ const rows = await sql`
+ select expires_at
+ from siwx_payments
+ where resource = ${resource}
+ and address = ${address}
+ limit 1
+ `;
+ if (!rows.length) return false;
+ const exp = rows[0].expires_at;
+ if (exp && new Date(exp).getTime() <= Date.now()) return false;
+ await sql`
+ update siwx_payments
+ set last_used_at = now(),
+ use_count = use_count + 1
+ where resource = ${resource}
+ and address = ${address}
+ `;
+ return true;
+}
+
+async function recordPayment(resource, address, opts = {}) {
+ if (!resource || !address) return;
+ const network = opts.network || null;
+ const ttlSeconds = Number.isFinite(opts.ttlSeconds) ? Number(opts.ttlSeconds) : null;
+ const expiresAt = ttlSeconds && ttlSeconds > 0
+ ? new Date(Date.now() + ttlSeconds * 1000).toISOString()
+ : null;
+ await sql`
+ insert into siwx_payments (resource, address, network, paid_at, expires_at)
+ values (${resource}, ${address}, ${network}, now(), ${expiresAt})
+ on conflict (resource, address) do update
+ set network = excluded.network,
+ paid_at = excluded.paid_at,
+ expires_at = excluded.expires_at
+ `;
+}
+
+async function hasUsedNonce(nonce) {
+ if (!nonce) return false;
+ const rows = await sql`select 1 from siwx_nonces where nonce = ${nonce} limit 1`;
+ return rows.length > 0;
+}
+
+async function recordNonce(nonce, ctx = {}) {
+ if (!nonce) return;
+ await sql`
+ insert into siwx_nonces (nonce, resource, address, used_at)
+ values (${nonce}, ${ctx.resource || ''}, ${ctx.address || ''}, now())
+ on conflict (nonce) do nothing
+ `;
+}
+
+export const siwxStorage = {
+ hasPaid,
+ recordPayment,
+ hasUsedNonce,
+ recordNonce,
+};
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 1ea5a5594..e5e038ffd 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -46,6 +46,11 @@ import {
settleDirectPayment,
verifyDirectPayment,
} from './x402-bsc-direct.js';
+import {
+ BUILDER_CODE,
+ declareBuilderCodeExtension,
+ verifyClientEcho as verifyBuilderCodeEcho,
+} from './x402-builder-code.js';
export { X402Error };
// Re-export both gas-sponsoring declarators together so callers building 402
@@ -53,6 +58,7 @@ export { X402Error };
// build402Body advertises both extensions as a pair when a Permit2 accept is
// present, and the public surface should match.
export { declareEip2612GasSponsoringExtension, declareErc20ApprovalGasSponsoringExtension };
+export { BUILDER_CODE, declareBuilderCodeExtension };
export const X402_VERSION = 2;
@@ -490,10 +496,27 @@ function selectRequirement(paymentPayload, allRequirements) {
// For direct-scheme networks (BSC), the on-chain verification result is stashed
// on `directVerified` so settlePayment can synthesise a response without
// re-hitting the RPC.
-export async function verifyPayment({ paymentHeader, requirements }) {
+//
+// `builderCode` is the extension block we declared on the 402 challenge —
+// when present, we reject any payment whose `extensions[BUILDER_CODE].a`
+// does not exactly echo the declared app code (anti-tamper). Built so the
+// resource server enforces the echo invariant the spec normally puts on the
+// facilitator — important because not every facilitator implements it yet,
+// and the on-chain calldata suffix needs trustworthy `a` to be useful.
+export async function verifyPayment({ paymentHeader, requirements, builderCode }) {
const all = Array.isArray(requirements) ? requirements : [requirements];
const paymentPayload = decodePaymentHeader(paymentHeader);
const requirement = selectRequirement(paymentPayload, all);
+ if (builderCode) {
+ const payloadBuilder = paymentPayload?.extensions?.[BUILDER_CODE];
+ const echo = verifyBuilderCodeEcho({
+ required: builderCode,
+ payload: payloadBuilder,
+ });
+ if (!echo.ok) {
+ throw new X402Error('builder_code_tampered', echo.reason, 402);
+ }
+ }
const config = facilitatorFor(requirement.network);
if (config.direct) {
const directVerified = await verifyDirectPayment({ paymentPayload, requirement });
@@ -741,6 +764,9 @@ function hasPermit2Accept(accepts) {
// Callers may pass an `extensions` object to add or override entries (e.g. an
// endpoint that wants to declare a custom extension); when omitted we still
// emit `bazaar` plus, when any accept opts into Permit2, `eip2612GasSponsoring`.
+// We also auto-declare the ERC-8021 `builder-code` extension when
+// X402_BUILDER_CODE_APP is configured, so every paid endpoint contributes to
+// on-chain attribution without having to opt in per-route.
export function build402Body({
resourceUrl,
accepts,
@@ -758,6 +784,11 @@ export function build402Body({
declareErc20ApprovalGasSponsoringExtension(),
);
}
+ if (env.X402_BUILDER_CODE_APP && !extraExtensions?.[BUILDER_CODE]) {
+ extensions[BUILDER_CODE] = declareBuilderCodeExtension({
+ a: env.X402_BUILDER_CODE_APP,
+ });
+ }
if (extraExtensions && typeof extraExtensions === 'object') {
Object.assign(extensions, extraExtensions);
}
diff --git a/api/_lib/x402/access-control.js b/api/_lib/x402/access-control.js
new file mode 100644
index 000000000..ee168bff4
--- /dev/null
+++ b/api/_lib/x402/access-control.js
@@ -0,0 +1,225 @@
+// x402 payment-bypass hook (USE-23).
+//
+// Wraps the v2 SDK lifecycle hook `onProtectedRequest` shape but adapted to
+// our plain Vercel Node handlers + the in-house `paidEndpoint(spec)` factory
+// in api/_lib/x402-paid-endpoint.js. Three callers can short-circuit the
+// 402 challenge:
+//
+// 1. Internal services — request supplies `X-API-Key: $INTERNAL_API_KEY`.
+// 2. Subscriptions / partners — `X-API-Key: <x402_live_...>` looked up in
+// x402_subscriptions, rate-limited per route.
+// 3. OAuth Bearer tokens — `Authorization: Bearer <jwt>` with the
+// route's declared `requiredScope`.
+//
+// When no bypass applies the hook returns `null` and the 402 flow continues
+// unchanged. Every bypass (and every denial — invalid key, expired, rate
+// limited, wrong scope) writes one row to x402_access_log so USE-24 can
+// reconstruct who used which endpoint for free.
+
+import { authenticateBearer, extractBearer, hasScope } from '../auth.js';
+import { constantTimeEquals } from '../crypto.js';
+import {
+ checkRateLimit,
+ logAccess,
+ lookupSubscription,
+} from './api-keys.js';
+import { clientIp } from '../rate-limit.js';
+
+const API_KEY_HEADER = 'x-api-key';
+
+/**
+ * Build an `accessControl` hook for `paidEndpoint(spec)`. Returns an async
+ * function `(req, routeConfig) => result` matching the v2 `onProtectedRequest`
+ * contract:
+ * • return `{ grantAccess: true, reason, callerId, headers? }` → skip payment
+ * • return `{ abort: true, reason, status? }` → reject with 4xx
+ * • return `null` / `undefined` → continue to 402
+ *
+ * @param {object} [opts]
+ * @param {string} [opts.requiredScope] OAuth scope required to bypass
+ * via Bearer token (e.g. "x402:bypass").
+ * When unset, OAuth bypass is disabled.
+ * @param {(ctx: { req, route }) => Promise<null | { grantAccess, reason, callerId }>}
+ * [opts.resolveCaller] Custom resolver run BEFORE the
+ * built-in API-key / OAuth checks.
+ * Useful for IP allowlists, partner-
+ * specific signed headers, etc.
+ */
+export function installAccessControl({ requiredScope, resolveCaller } = {}) {
+ return async function onProtectedRequest(req, routeConfig) {
+ const route = routeConfig?.path || routeConfig?.route || req.url || 'unknown';
+ const meta = {
+ ip: clientIp(req),
+ ua: String(req.headers['user-agent'] || '').slice(0, 200),
+ };
+
+ // (0) Custom resolver — first say is the user's say.
+ if (typeof resolveCaller === 'function') {
+ const custom = await resolveCaller({ req, route, routeConfig });
+ if (custom?.grantAccess) {
+ logAccess({
+ callerId: custom.callerId || 'custom',
+ route,
+ reason: custom.reason || 'custom:granted',
+ granted: true,
+ meta,
+ });
+ return custom;
+ }
+ if (custom?.abort) {
+ logAccess({
+ callerId: custom.callerId || `abort:${custom.reason || 'custom'}`,
+ route,
+ reason: custom.reason || 'custom:denied',
+ granted: false,
+ meta,
+ });
+ return custom;
+ }
+ }
+
+ // (1) Internal service key — exact match against env, constant-time.
+ const apiKey = readHeader(req, API_KEY_HEADER);
+ const internalKey = process.env.INTERNAL_API_KEY;
+ if (apiKey && internalKey && constantTimeEquals(apiKey, internalKey)) {
+ logAccess({
+ callerId: 'internal',
+ route,
+ reason: 'internal',
+ granted: true,
+ meta,
+ });
+ return { grantAccess: true, reason: 'internal', callerId: 'internal' };
+ }
+
+ // (2) Subscription key — db lookup + per-route sliding-window limit.
+ if (apiKey) {
+ const sub = await lookupSubscription(apiKey);
+ if (!sub) {
+ logAccess({
+ callerId: 'abort:invalid_key',
+ route,
+ reason: 'Invalid API key',
+ granted: false,
+ meta: { ...meta, key_prefix: apiKey.slice(0, 16) },
+ });
+ return { abort: true, status: 403, reason: 'Invalid API key' };
+ }
+ if (sub._status === 'revoked') {
+ logAccess({
+ callerId: `abort:revoked:${sub.id}`,
+ route,
+ reason: 'Subscription revoked',
+ granted: false,
+ meta,
+ });
+ return { abort: true, status: 403, reason: 'Subscription revoked' };
+ }
+ if (sub._status === 'expired') {
+ logAccess({
+ callerId: `abort:expired:${sub.id}`,
+ route,
+ reason: 'Subscription expired',
+ granted: false,
+ meta,
+ });
+ return { abort: true, status: 403, reason: 'Subscription expired' };
+ }
+ const rl = await checkRateLimit(sub, route);
+ if (!rl.allowed) {
+ logAccess({
+ callerId: `subscription:${sub.id}`,
+ route,
+ reason: 'rate_limit_exceeded',
+ granted: false,
+ meta: { ...meta, limit: rl.limit, resetAt: rl.resetAt },
+ });
+ return {
+ abort: true,
+ status: 429,
+ reason: `Rate limit exceeded — ${rl.limit}/min, retry after ${new Date(rl.resetAt).toISOString()}`,
+ headers: {
+ 'x-ratelimit-limit': String(rl.limit),
+ 'x-ratelimit-remaining': '0',
+ 'x-ratelimit-reset': String(Math.ceil(rl.resetAt / 1000)),
+ 'retry-after': String(Math.max(1, Math.ceil((rl.resetAt - Date.now()) / 1000))),
+ },
+ };
+ }
+ logAccess({
+ callerId: `subscription:${sub.id}`,
+ route,
+ reason: `subscription:${sub.id}`,
+ granted: true,
+ meta: { ...meta, remaining: rl.remaining, limit: rl.limit },
+ });
+ return {
+ grantAccess: true,
+ reason: `subscription:${sub.id}`,
+ callerId: `subscription:${sub.id}`,
+ headers: {
+ 'x-ratelimit-limit': String(rl.limit),
+ 'x-ratelimit-remaining': String(rl.remaining),
+ 'x-ratelimit-reset': String(Math.ceil(rl.resetAt / 1000)),
+ },
+ subscription: {
+ id: sub.id,
+ name: sub.name,
+ },
+ };
+ }
+
+ // (3) OAuth Bearer — only when the route declares a required scope.
+ if (requiredScope) {
+ const bearer = extractBearer(req);
+ if (bearer) {
+ const claims = await authenticateBearer(bearer);
+ if (!claims) {
+ logAccess({
+ callerId: 'abort:invalid_oauth',
+ route,
+ reason: 'Invalid OAuth token',
+ granted: false,
+ meta,
+ });
+ // Don't 403 — fall through to payment flow. The caller may
+ // simply have an unrelated user token they sent along.
+ return null;
+ }
+ if (!hasScope(claims.scope, requiredScope)) {
+ logAccess({
+ callerId: `abort:oauth_scope:${claims.userId}`,
+ route,
+ reason: `Missing required scope: ${requiredScope}`,
+ granted: false,
+ meta: { ...meta, granted_scope: claims.scope },
+ });
+ // Same — let them pay normally.
+ return null;
+ }
+ logAccess({
+ callerId: `oauth:${claims.userId}`,
+ route,
+ reason: `oauth:${claims.userId}`,
+ granted: true,
+ meta: { ...meta, source: claims.source, clientId: claims.clientId || null },
+ });
+ return {
+ grantAccess: true,
+ reason: `oauth:${claims.userId}`,
+ callerId: `oauth:${claims.userId}`,
+ oauth: { userId: claims.userId, scope: claims.scope, clientId: claims.clientId },
+ };
+ }
+ }
+
+ // No bypass — payment flow continues.
+ return null;
+ };
+}
+
+function readHeader(req, name) {
+ const v = req.headers?.[name] ?? req.headers?.[name.toLowerCase()];
+ if (!v) return null;
+ return Array.isArray(v) ? String(v[0]).trim() : String(v).trim();
+}
diff --git a/api/_lib/x402/idempotency-cache.js b/api/_lib/x402/idempotency-cache.js
new file mode 100644
index 000000000..439e4b44a
--- /dev/null
+++ b/api/_lib/x402/idempotency-cache.js
@@ -0,0 +1,111 @@
+// Redis-backed idempotency cache for x402 payment-identifier (USE-15).
+//
+// Keyed by `${route}|${paymentId}`. Each entry stores the response body, a
+// few essential response headers (content-type, x-payment-response, status),
+// and a SHA-256 hash of the request payload that was paid for. The hash is
+// what the spec calls for: same id + different payload → 409 Conflict.
+//
+// The store falls back to an in-process Map when Upstash isn't configured, so
+// `npm test` and local dev work without Redis. Production deployments must set
+// UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN — without them, idempotency
+// is per-instance and provides no protection across Vercel function replicas.
+
+import { createHash } from 'node:crypto';
+import { Redis } from '@upstash/redis';
+import { env } from '../env.js';
+
+let redis = null;
+if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {
+ redis = new Redis({
+ url: env.UPSTASH_REDIS_REST_URL,
+ token: env.UPSTASH_REDIS_REST_TOKEN,
+ });
+}
+
+const KEY_PREFIX = 'x402:idem:';
+
+// In-memory fallback. Map<key, { entry, expiresAt }>.
+const memoryStore = new Map();
+
+function now() {
+ return Date.now();
+}
+
+function memoryGet(key) {
+ const slot = memoryStore.get(key);
+ if (!slot) return null;
+ if (slot.expiresAt && slot.expiresAt < now()) {
+ memoryStore.delete(key);
+ return null;
+ }
+ return slot.entry;
+}
+
+function memorySet(key, entry, ttlSec) {
+ memoryStore.set(key, {
+ entry,
+ expiresAt: ttlSec > 0 ? now() + ttlSec * 1000 : 0,
+ });
+}
+
+function fullKey(route, paymentId) {
+ return `${KEY_PREFIX}${route}|${paymentId}`;
+}
+
+// Stable hash of the bytes the caller paid for. The route + query string +
+// JSON-stringified body is enough for our endpoints — none of them depend on
+// header state. Returns null when there's nothing distinguishing to hash
+// (POSTs without a body fall back to route alone).
+export function hashRequestPayload({ method, url, body }) {
+ const h = createHash('sha256');
+ h.update(String(method || 'GET').toUpperCase());
+ h.update('\n');
+ h.update(String(url || ''));
+ h.update('\n');
+ if (body !== undefined && body !== null) {
+ if (typeof body === 'string') h.update(body);
+ else if (Buffer.isBuffer(body)) h.update(body);
+ else h.update(JSON.stringify(body));
+ }
+ return h.digest('hex');
+}
+
+// Read a cached response by route + paymentId. Returns null if the key is
+// missing or expired. The returned shape is whatever `set()` was given.
+export async function get(route, paymentId) {
+ const key = fullKey(route, paymentId);
+ if (!redis) return memoryGet(key);
+ try {
+ const raw = await redis.get(key);
+ if (!raw) return null;
+ // Upstash auto-decodes JSON when storing objects, but old keys or
+ // string-encoded values still come back as strings — handle both.
+ return typeof raw === 'string' ? JSON.parse(raw) : raw;
+ } catch (err) {
+ console.error('[idempotency-cache] get failed:', err?.message || err);
+ return null;
+ }
+}
+
+// Write a response into the cache. ttlSec=0 means "store with no expiration"
+// — never use that in production; the env-driven default is finite. Failures
+// to write are logged but never thrown — the caller has already settled the
+// payment and shouldn't see a 5xx because Redis blinked.
+export async function set(route, paymentId, entry, ttlSec) {
+ const key = fullKey(route, paymentId);
+ if (!redis) {
+ memorySet(key, entry, ttlSec);
+ return;
+ }
+ try {
+ const opts = ttlSec > 0 ? { ex: ttlSec } : undefined;
+ await redis.set(key, JSON.stringify(entry), opts);
+ } catch (err) {
+ console.error('[idempotency-cache] set failed:', err?.message || err);
+ }
+}
+
+// Test-only hook to drop the in-memory store between tests.
+export function _resetMemoryStore() {
+ memoryStore.clear();
+}
diff --git a/api/_lib/x402/offer-receipt-issuer.js b/api/_lib/x402/offer-receipt-issuer.js
new file mode 100644
index 000000000..c5f40ff2a
--- /dev/null
+++ b/api/_lib/x402/offer-receipt-issuer.js
@@ -0,0 +1,154 @@
+// x402 Offer & Receipt extension — issuer setup.
+//
+// Constructs the OfferReceiptIssuer that signs both 402 offers (per accept
+// entry) and 200 receipts (after settlement). The signing key MUST NOT be
+// any X402_PAY_TO_* wallet — those receive funds; this one only signs
+// off-chain commitments. Mixing the two would mean every payment cosigner
+// is implicitly endorsing every offer/receipt the server ever issued.
+//
+// Two formats are supported:
+//
+// • EIP-712 (default, OFFER_RECEIPT_FORMAT=eip712)
+// Signs with a dedicated EVM EOA from OFFER_RECEIPT_SIGNING_PRIVATE_KEY.
+// The kid is did:pkh:eip155:1:<address>#key-1 (per spec §3.2 the EIP-712
+// domain chainId is hard-pinned at 1 regardless of payment network, so
+// did:pkh uses chain-id 1 for consistency with the signing domain).
+// Verifiers recover the signer address from the signature and check it
+// against the address embedded in the kid.
+//
+// • JWS (OFFER_RECEIPT_FORMAT=jws)
+// Signs with a JWK private key from OFFER_RECEIPT_JWK (JSON string). The
+// kid is did:web:<SERVER_DOMAIN>#key-1 — verifiers fetch
+// https://<SERVER_DOMAIN>/.well-known/did.json (see api/x402/did.js) to
+// resolve the public key. Default algorithm is EdDSA (Ed25519); ES256K
+// (secp256k1) is also accepted via OFFER_RECEIPT_JWS_ALG. Vercel has no
+// KMS — for production-grade key management, swap this for a managed
+// KMS signer (GCP KMS, AWS KMS, HashiCorp Vault) and have the sign()
+// callback delegate to the KMS API.
+//
+// When OFFER_RECEIPT_SIGNING_PRIVATE_KEY (eip712) or OFFER_RECEIPT_JWK (jws)
+// is unset, getIssuer() returns null and callers MUST silently skip emitting
+// the extension. The x402 wire format stays valid without it; the extension
+// is purely additive.
+
+import {
+ createEIP712OfferReceiptIssuer,
+ createJWSOfferReceiptIssuer,
+} from '@x402/extensions';
+import * as jose from 'jose';
+import { privateKeyToAccount } from 'viem/accounts';
+
+import { env } from '../env.js';
+
+let _issuerCache = null;
+let _issuerError = null;
+
+function safeguardAgainstReusingPaymentKey(signingPrivKey) {
+ const norm = String(signingPrivKey).trim().toLowerCase().replace(/^0x/, '');
+ const collisions = [
+ ['X402_PAY_TO_BASE', env.X402_PAY_TO_BASE],
+ ['X402_PAY_TO_BSC', env.X402_PAY_TO_BSC],
+ ['CLUB_EVM_TREASURY_PRIVATE_KEY', env.CLUB_EVM_TREASURY_PRIVATE_KEY],
+ ['AGENT_RELAYER_KEY', env.AGENT_RELAYER_KEY ? '<set>' : undefined],
+ ];
+ let derivedAddress;
+ try {
+ derivedAddress = privateKeyToAccount(`0x${norm}`).address.toLowerCase();
+ } catch {
+ throw new Error('OFFER_RECEIPT_SIGNING_PRIVATE_KEY is not a valid 0x-hex EVM private key');
+ }
+ for (const [name, value] of collisions) {
+ if (!value) continue;
+ if (String(value).toLowerCase() === derivedAddress) {
+ throw new Error(
+ `OFFER_RECEIPT_SIGNING_PRIVATE_KEY derives to ${derivedAddress}, which is also ${name}. ` +
+ 'Receipts MUST be signed with a dedicated key separate from payment-receiving wallets.',
+ );
+ }
+ }
+ return derivedAddress;
+}
+
+async function buildEip712Issuer() {
+ const privKey = env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY;
+ if (!privKey) return null;
+ const norm = privKey.startsWith('0x') ? privKey : `0x${privKey}`;
+ const address = safeguardAgainstReusingPaymentKey(privKey);
+ const account = privateKeyToAccount(norm);
+ // Per spec §3.2 the EIP-712 domain chainId is hard-pinned at 1 (off-chain
+ // signing context, NOT the payment network). did:pkh follows the same
+ // convention so the kid is interpretable without knowing the payment chain.
+ const kid = `did:pkh:eip155:1:${account.address}#key-1`;
+ const signTypedData = (params) => account.signTypedData(params);
+ const issuer = createEIP712OfferReceiptIssuer(kid, signTypedData);
+ return {
+ issuer,
+ format: 'eip712',
+ kid,
+ signerAddress: address,
+ publicKey: null,
+ };
+}
+
+async function buildJwsIssuer() {
+ const rawJwk = env.OFFER_RECEIPT_JWK;
+ if (!rawJwk) return null;
+ let jwk;
+ try {
+ jwk = typeof rawJwk === 'string' ? JSON.parse(rawJwk) : rawJwk;
+ } catch (err) {
+ throw new Error(`OFFER_RECEIPT_JWK is not valid JSON: ${err.message}`);
+ }
+ const algorithm = env.OFFER_RECEIPT_JWS_ALG;
+ const privateKey = await jose.importJWK(jwk, algorithm);
+ const kid = `did:web:${env.SERVER_DOMAIN}#key-1`;
+ const jwsSigner = {
+ kid,
+ algorithm,
+ format: 'jws',
+ // The SDK calls sign(bytes) and expects a base64url-encoded raw
+ // signature string. jose.FlattenedSign gives us full JWS control;
+ // we strip the wrapper and return only the signature field.
+ async sign(payloadBytes) {
+ const sig = await new jose.FlattenedSign(payloadBytes)
+ .setProtectedHeader({ alg: algorithm, kid })
+ .sign(privateKey);
+ return sig.signature;
+ },
+ };
+ const issuer = createJWSOfferReceiptIssuer(kid, jwsSigner);
+ // Strip private components from the JWK before exposing for /.well-known/did.json.
+ const publicJwk = { ...jwk };
+ for (const k of ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k']) delete publicJwk[k];
+ return {
+ issuer,
+ format: 'jws',
+ kid,
+ signerAddress: null,
+ publicKey: { jwk: publicJwk, alg: algorithm },
+ };
+}
+
+/**
+ * Return the configured offer-receipt issuer, or null when no signing key is
+ * configured. Throws if a key is configured but invalid (fail-fast on boot).
+ */
+export async function getIssuer() {
+ if (_issuerError) throw _issuerError;
+ if (_issuerCache !== null) return _issuerCache;
+ const format = (env.OFFER_RECEIPT_FORMAT || 'eip712').toLowerCase();
+ try {
+ const built = format === 'jws' ? await buildJwsIssuer() : await buildEip712Issuer();
+ _issuerCache = built ?? false;
+ } catch (err) {
+ _issuerError = err;
+ throw err;
+ }
+ return _issuerCache || null;
+}
+
+/** Reset the memoised issuer — for tests only. */
+export function _resetIssuerForTests() {
+ _issuerCache = null;
+ _issuerError = null;
+}
diff --git a/api/_lib/x402/offer-receipt-server.js b/api/_lib/x402/offer-receipt-server.js
new file mode 100644
index 000000000..0b9d2cc24
--- /dev/null
+++ b/api/_lib/x402/offer-receipt-server.js
@@ -0,0 +1,198 @@
+// Server-side glue for the x402 Offer & Receipt extension.
+//
+// Our paid-endpoint plumbing (api/_lib/x402-paid-endpoint.js + x402-spec.js)
+// is custom — it doesn't run the @x402/express ResourceServer that the SDK's
+// createOfferReceiptExtension() hooks into. So instead of wiring extension
+// hooks, we call the issuer directly here and emit the right
+// `extensions["offer-receipt"]` shape ourselves. Wire shape matches the spec
+// §4.1 (for 402 offers) and §5.1 (for 200 receipts).
+
+import { OFFER_RECEIPT, convertNetworkStringToCAIP2 } from '@x402/extensions';
+
+import { getIssuer } from './offer-receipt-issuer.js';
+
+// Spec §4.1 — the offer-receipt info.offers[] meta-schema. Copied from
+// @x402/extensions' internal OFFER_SCHEMA (it isn't exported as a constant)
+// so this stays stable even if the SDK reshuffles modules.
+const OFFER_SCHEMA = Object.freeze({
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ offers: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: {
+ format: { type: 'string' },
+ acceptIndex: { type: 'integer' },
+ payload: {
+ type: 'object',
+ properties: {
+ version: { type: 'integer' },
+ resourceUrl: { type: 'string' },
+ scheme: { type: 'string' },
+ network: { type: 'string' },
+ asset: { type: 'string' },
+ payTo: { type: 'string' },
+ amount: { type: 'string' },
+ validUntil: { type: 'integer' },
+ },
+ required: ['version', 'resourceUrl', 'scheme', 'network', 'asset', 'payTo', 'amount'],
+ },
+ signature: { type: 'string' },
+ },
+ required: ['format', 'signature'],
+ },
+ },
+ },
+ required: ['offers'],
+});
+
+// Spec §5.1 — the offer-receipt info.receipt meta-schema. Same rationale as
+// above for embedding rather than importing.
+const RECEIPT_SCHEMA = Object.freeze({
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ receipt: {
+ type: 'object',
+ properties: {
+ format: { type: 'string' },
+ payload: {
+ type: 'object',
+ properties: {
+ version: { type: 'integer' },
+ network: { type: 'string' },
+ resourceUrl: { type: 'string' },
+ payer: { type: 'string' },
+ issuedAt: { type: 'integer' },
+ transaction: { type: 'string' },
+ },
+ required: ['version', 'network', 'resourceUrl', 'payer', 'issuedAt'],
+ },
+ signature: { type: 'string' },
+ },
+ required: ['format', 'signature'],
+ },
+ },
+ required: ['receipt'],
+});
+
+const DEFAULT_OFFER_VALIDITY_SEC = 300;
+
+/**
+ * Returns true when the issuer is configured. Callers use this to short-circuit
+ * before doing extra work building offer inputs.
+ */
+export async function offerReceiptEnabled() {
+ try {
+ return Boolean(await getIssuer());
+ } catch {
+ // Fail-closed: a misconfigured issuer must not break the 402 dance.
+ return false;
+ }
+}
+
+function requirementToOfferInput(requirement, acceptIndex, offerValiditySeconds) {
+ return {
+ acceptIndex,
+ scheme: requirement.scheme,
+ network: convertNetworkStringToCAIP2(requirement.network),
+ asset: requirement.asset,
+ payTo: requirement.payTo,
+ amount: requirement.amount,
+ offerValiditySeconds: offerValiditySeconds ?? DEFAULT_OFFER_VALIDITY_SEC,
+ };
+}
+
+/**
+ * Build the `{ "offer-receipt": { info: { offers }, schema } }` extension
+ * fragment for a 402 PaymentRequired body. Returns null when the issuer is
+ * unconfigured OR when signing fails for every requirement (the protocol
+ * still works without the extension; we never want it to break the 402 path).
+ *
+ * @param {string} resourceUrl - canonical URL the offer is for
+ * @param {object[]} requirements - the `accepts[]` array (after Permit2 expansion)
+ * @param {{ offerValiditySeconds?: number }} declaration
+ */
+export async function buildOffersExtension(resourceUrl, requirements, declaration = {}) {
+ const built = await getIssuer().catch((err) => {
+ console.error('[offer-receipt] issuer init failed:', err.message);
+ return null;
+ });
+ if (!built) return null;
+ const offers = [];
+ for (let i = 0; i < requirements.length; i++) {
+ try {
+ const input = requirementToOfferInput(
+ requirements[i],
+ i,
+ declaration.offerValiditySeconds,
+ );
+ const offer = await built.issuer.issueOffer(resourceUrl, input);
+ offers.push(offer);
+ } catch (err) {
+ console.error(
+ `[offer-receipt] failed to sign offer for accepts[${i}]: ${err.message}`,
+ );
+ }
+ }
+ if (!offers.length) return null;
+ return {
+ [OFFER_RECEIPT]: {
+ info: { offers },
+ schema: OFFER_SCHEMA,
+ },
+ };
+}
+
+/**
+ * Build the `{ "offer-receipt": { info: { receipt }, schema } }` fragment for
+ * a settled payment-response body. Returns null when the issuer is unconfigured
+ * or when the settlement result lacks fields the spec requires (payer / network).
+ *
+ * `includeTxHash=false` (default) preserves privacy per spec §5.2; set true on
+ * routes that feed reputation systems where on-chain verifiability matters more.
+ *
+ * Returns `{ extensionFragment, signedReceipt }` so the caller can persist the
+ * receipt to the durable log alongside emitting it on the wire.
+ *
+ * @param {string} resourceUrl
+ * @param {{ payer?: string, network?: string, transaction?: string }} settled
+ * @param {{ includeTxHash?: boolean }} declaration
+ */
+export async function buildReceiptExtension(resourceUrl, settled, declaration = {}) {
+ const built = await getIssuer().catch((err) => {
+ console.error('[offer-receipt] issuer init failed:', err.message);
+ return null;
+ });
+ if (!built) return null;
+ if (!settled || !settled.payer || !settled.network) {
+ console.warn('[offer-receipt] settled response missing payer/network; skipping receipt');
+ return null;
+ }
+ const network = convertNetworkStringToCAIP2(settled.network);
+ const includeTxHash = declaration.includeTxHash === true;
+ const transaction = includeTxHash ? settled.transaction || undefined : undefined;
+ let signedReceipt;
+ try {
+ signedReceipt = await built.issuer.issueReceipt(
+ resourceUrl,
+ settled.payer,
+ network,
+ transaction,
+ );
+ } catch (err) {
+ console.error(`[offer-receipt] failed to sign receipt: ${err.message}`);
+ return null;
+ }
+ return {
+ extensionFragment: {
+ [OFFER_RECEIPT]: {
+ info: { receipt: signedReceipt },
+ schema: RECEIPT_SCHEMA,
+ },
+ },
+ signedReceipt,
+ };
+}
diff --git a/api/_lib/x402/payment-identifier-client.js b/api/_lib/x402/payment-identifier-client.js
new file mode 100644
index 000000000..4d9c21cdf
--- /dev/null
+++ b/api/_lib/x402/payment-identifier-client.js
@@ -0,0 +1,91 @@
+// Client-side helpers for the x402 payment-identifier extension (USE-15).
+//
+// `installIdempotency(client, options)` registers an `onBeforePaymentCreation`
+// hook on a `x402Client` (or any object that exposes `.onBeforePaymentCreation`)
+// so every paid request opts into the server's idempotency cache.
+//
+// Two modes:
+// * `paymentId: <string>` — pin a stable id across retries. Use this when
+// the caller code knows the logical request (e.g. an order id, a task id,
+// or a sessionStorage `requestId` carried across browser reloads).
+// * `getPaymentId: ({ url, method }) => string | Promise<string>` — derive
+// the id from request context. Falls back to a fresh generated id when
+// the resolver returns null/undefined.
+//
+// When neither option is set, a fresh id is generated per request — still
+// useful because (a) it lets the server resume in-flight retries triggered
+// inside @x402/fetch's own retry loop, and (b) the server's 409 conflict
+// path becomes a real signal rather than dead code.
+
+import {
+ PAYMENT_IDENTIFIER,
+ appendPaymentIdentifierToExtensions,
+ generatePaymentId,
+ isValidPaymentId,
+} from '@x402/extensions/payment-identifier';
+
+export { PAYMENT_IDENTIFIER, generatePaymentId, isValidPaymentId };
+
+// Register a payment-identifier hook on an x402Client.
+//
+// Returns the same `client` for chaining. The hook is a no-op when the
+// server doesn't advertise the extension — `appendPaymentIdentifierToExtensions`
+// already checks for the declaration before mutating `extensions`.
+export function installIdempotency(client, options = {}) {
+ if (!client || typeof client.onBeforePaymentCreation !== 'function') {
+ throw new TypeError(
+ 'installIdempotency: client must expose .onBeforePaymentCreation (x402Client)',
+ );
+ }
+ const resolveId = buildResolver(options);
+ client.onBeforePaymentCreation(async (context) => {
+ const extensions = context?.paymentRequired?.extensions;
+ if (!extensions) return;
+ // Skip when the server didn't declare support — keeps payloads minimal
+ // against legacy endpoints. appendPaymentIdentifierToExtensions also
+ // guards on this, but resolving the id can be expensive (sessionStorage
+ // read, fetch from an order service, etc.) so we bail first.
+ if (!extensions[PAYMENT_IDENTIFIER]) return;
+ const id = await resolveId(context);
+ const finalId = id || generatePaymentId();
+ appendPaymentIdentifierToExtensions(extensions, finalId);
+ });
+ return client;
+}
+
+function buildResolver(options) {
+ if (typeof options.getPaymentId === 'function') {
+ return async (context) => {
+ const v = await options.getPaymentId(context);
+ return typeof v === 'string' && v ? v : null;
+ };
+ }
+ if (typeof options.paymentId === 'string' && options.paymentId) {
+ const fixed = options.paymentId;
+ return async () => fixed;
+ }
+ return async () => null;
+}
+
+// Convenience: pull a stable per-tab `requestId` out of sessionStorage in
+// browser flows. Falls back to a fresh generated id and writes it back so
+// subsequent retries (page reload, navigation) reuse it.
+//
+// Returns a resolver suitable for `installIdempotency({ getPaymentId })`.
+export function sessionStorageResolver({ keyPrefix = 'x402:pid:' } = {}) {
+ return async (context) => {
+ if (typeof sessionStorage === 'undefined') return null;
+ const url = context?.paymentRequired?.resource?.url || 'default';
+ const key = `${keyPrefix}${url}`;
+ const existing = sessionStorage.getItem(key);
+ if (existing && isValidPaymentId(existing)) return existing;
+ const fresh = generatePaymentId();
+ try {
+ sessionStorage.setItem(key, fresh);
+ } catch {
+ // Storage may be unavailable (private mode, quota). Fall back to
+ // per-call ids — the worst-case is reduced retry resilience.
+ }
+ return fresh;
+ };
+}
diff --git a/api/_lib/x402/payment-identifier-server.js b/api/_lib/x402/payment-identifier-server.js
new file mode 100644
index 000000000..e68261419
--- /dev/null
+++ b/api/_lib/x402/payment-identifier-server.js
@@ -0,0 +1,177 @@
+// Server-side glue for the x402 payment-identifier extension (USE-15).
+//
+// Three concerns:
+// 1. Declare the extension on the 402 challenge (`extensions['payment-identifier']`).
+// 2. Look the incoming payment header up in the idempotency cache before
+// hitting the facilitator — same id + same payload → replay the cached
+// response with no on-chain settlement.
+// 3. Write each successful (settled) response into the cache, tagged with
+// the SHA-256 of the request bytes so a second hit with the same id but
+// different payload returns 409 Conflict.
+//
+// The functions here are deliberately framework-free — they operate on a
+// decoded payload + a small request descriptor — so they can be wired into
+// both the `paidEndpoint()` wrapper and the standalone endpoints that hand-
+// roll their 402 dance (model-check, mint-to-mesh, revenue-vision).
+
+import {
+ PAYMENT_IDENTIFIER,
+ declarePaymentIdentifierExtension as declareExt,
+ extractPaymentIdentifier,
+ isValidPaymentId,
+} from '@x402/extensions/payment-identifier';
+
+import { env } from '../env.js';
+import { X402Error } from '../x402-errors.js';
+import * as cache from './idempotency-cache.js';
+
+export { PAYMENT_IDENTIFIER, extractPaymentIdentifier, isValidPaymentId };
+
+// Default TTL — overridable per-route via `paidEndpoint({ paymentIdentifier:
+// { ttlSeconds } })`. 3600s matches the spec's "Long TTL" guidance for
+// infrequently changing resources.
+const DEFAULT_TTL_SECONDS = 3600;
+
+function envTtl() {
+ const raw = env.X402_IDEMPOTENCY_TTL_SECONDS;
+ const n = Number.parseInt(raw, 10);
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_TTL_SECONDS;
+}
+
+// Build the extension object that goes onto the 402 challenge.
+// `required=true` makes clients fail-fast with 400 if they don't send an ID
+// — use this on endpoints where a duplicate call is materially expensive or
+// observable (e.g. oracle attestations, fact-check submissions).
+export function paymentIdentifierExtension(required = false) {
+ return declareExt(Boolean(required));
+}
+
+// Decode an X-PAYMENT header without verifying it. Returns null if the
+// header is malformed — we don't want a cache hit to mask a legit 400 from
+// the facilitator, so we always fall through to the normal verify flow on
+// decode failure.
+function tryDecode(paymentHeader) {
+ try {
+ const json = Buffer.from(String(paymentHeader), 'base64').toString('utf8');
+ const parsed = JSON.parse(json);
+ return parsed && typeof parsed === 'object' ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+// Pull the payment-identifier from the header (if present and valid).
+// Returns null when the client didn't include one — that means "no
+// idempotency for this call", not an error.
+export function extractIdFromHeader(paymentHeader) {
+ if (!paymentHeader) return null;
+ const payload = tryDecode(paymentHeader);
+ if (!payload) return null;
+ return extractPaymentIdentifier(payload);
+}
+
+// Enforce required=true. Throws an X402Error(400) the caller can map to a
+// clean response. The extension self-validates ID format on extract, so we
+// only need to check presence here.
+export function enforceRequired({ paymentHeader, required }) {
+ if (!required) return;
+ const id = extractIdFromHeader(paymentHeader);
+ if (!id) {
+ throw new X402Error(
+ 'payment_identifier_required',
+ 'this route requires a payment-identifier extension on the payment payload',
+ 400,
+ );
+ }
+}
+
+// Look up a cached response. Returns:
+// { kind: 'miss' } — no cached entry; proceed.
+// { kind: 'hit', entry } — replay entry; skip settle.
+// { kind: 'conflict', existingHash, attemptedHash } — same id, different payload.
+//
+// When `payloadHash` is omitted we treat a cache entry with a non-null
+// stored hash as a conflict — pass the hash whenever you can compute it.
+export async function checkCache({ route, paymentId, payloadHash }) {
+ if (!paymentId) return { kind: 'miss' };
+ const entry = await cache.get(route, paymentId);
+ if (!entry) return { kind: 'miss' };
+ // Stored hash may be null on legacy/unknown-payload entries; treat
+ // "no stored hash" as compatible with any incoming request so older
+ // cached entries don't suddenly start 409ing.
+ if (entry.payloadHash && payloadHash && entry.payloadHash !== payloadHash) {
+ return {
+ kind: 'conflict',
+ existingHash: entry.payloadHash,
+ attemptedHash: payloadHash,
+ };
+ }
+ return { kind: 'hit', entry };
+}
+
+// Persist a settled response so a same-id retry can be served from the cache.
+// Failure to write is logged inside idempotency-cache.js — never thrown,
+// since the caller has already taken the user's money and must respond 2xx.
+export async function storeResponse({
+ route,
+ paymentId,
+ payloadHash,
+ status,
+ body,
+ contentType,
+ paymentResponseHeader,
+ ttlSeconds,
+}) {
+ if (!paymentId) return;
+ const ttl = Number.isFinite(ttlSeconds) && ttlSeconds > 0 ? ttlSeconds : envTtl();
+ await cache.set(
+ route,
+ paymentId,
+ {
+ status,
+ body,
+ contentType,
+ paymentResponseHeader,
+ payloadHash: payloadHash || null,
+ storedAt: new Date().toISOString(),
+ },
+ ttl,
+ );
+}
+
+// Flush a cached entry back onto the wire. Mirrors the headers the live path
+// would have set (cache-control: no-store, x-payment-response, etc.) and
+// tags the response with `x-x402-idempotent: replay` so the caller can tell
+// they got a cached body.
+export function writeCachedResponse(res, entry) {
+ res.statusCode = Number.isInteger(entry.status) ? entry.status : 200;
+ res.setHeader('content-type', entry.contentType || 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('x-x402-idempotent', 'replay');
+ if (entry.paymentResponseHeader) {
+ res.setHeader('x-payment-response', entry.paymentResponseHeader);
+ }
+ res.end(entry.body ?? '');
+}
+
+// Write a 409 Conflict explaining the payload mismatch.
+export function writeConflict(res, { route, attemptedHash, existingHash }) {
+ res.statusCode = 409;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('x-x402-idempotent', 'conflict');
+ res.end(
+ JSON.stringify({
+ error: 'payment_identifier_conflict',
+ error_description:
+ 'a different request body was already processed under this payment-identifier; ' +
+ 'either retry the original payload or generate a new id',
+ route,
+ attemptedPayloadHash: attemptedHash,
+ existingPayloadHash: existingHash,
+ }),
+ );
+}
+
+export { hashRequestPayload } from './idempotency-cache.js';
+export const ttlSeconds = envTtl;
diff --git a/docs/club/PERF_NOTES.md b/docs/club/PERF_NOTES.md
new file mode 100644
index 000000000..1b44ec4be
--- /dev/null
+++ b/docs/club/PERF_NOTES.md
@@ -0,0 +1,124 @@
+# /club — performance notes
+
+The pole-club scene is a hot path: four spotlights, four rigged dancers,
+bloom + chromatic aberration on the high tier, plus the mirror-ball cube
+cam. To keep it usable on a mid-range phone we pick a render profile
+once at boot from real capability signals, then re-apply on demand
+mid-session if a frame-budget watchdog detects sustained slow frames.
+
+## Profile tiers
+
+Defined in [`src/club-perf.js`](../../src/club-perf.js). Profiles gate
+flags on the renderer, lights, and any future scene additions (mirror
+ball, volumetric cones, crowd, postFX). The detector reads:
+
+- `navigator.userAgent` — mobile UA match only
+- `navigator.deviceMemory` — RAM (missing on Safari → defaults to 8 GB)
+- `navigator.hardwareConcurrency` — CPU thread count
+- `matchMedia('(pointer: coarse)')` — touch input as a fallback signal
+
+| Tier | pixelRatio | shadows | bloom | chromaticAberration | mirrorBall | cubeCam | volumetricCones | crowdInstances | discoLights |
+|--------|------------|---------|-------|---------------------|------------|---------|------------------|----------------|-------------|
+| high | min(dpr,2) | yes | yes | yes | yes | yes | yes | 80 | 4 |
+| medium | min(dpr,1.5)| yes | yes | no | yes | no | yes | 40 | 4 |
+| low | 1.0 | no | no | no | no | no | no | 12 | 2 |
+
+The chosen profile is exposed on `window.__clubProfile` so other scene
+modules (the venue loader, post-FX composer, mirror-ball builder) can
+read it without an import cycle.
+
+## Frame-budget watchdog
+
+Lives in the same file. The render loop calls `watchdog.tick(dt)` once
+per frame. It keeps an EMA of frame time; when the EMA stays above
+`1/28s` (≈35.7 ms, or roughly 28 fps) for >2 seconds, it drops one
+tier and emits a `console.info('[club] downgrading profile to ...')`.
+It never auto-upgrades — a recovery usually means the user moved away
+from a busy moment, and we'd rather stay safe than risk a re-thrash.
+
+The downgrade re-applies cheap render-state flags:
+
+- `renderer.setPixelRatio(next.pixelRatio)`
+- `renderer.shadowMap.enabled = next.shadows`
+- per-pole `spot.castShadow` matches the new tier
+- excess disco lights are removed from the scene
+
+Features built once at boot (mirror ball geometry, volumetric cone
+meshes) stay constructed — tearing down GPU resources mid-flight
+itself spikes frame time, which would defeat the purpose.
+
+## Visibility pause
+
+The animate loop cancels its `requestAnimationFrame` on
+`document.hidden`, and the leaderboard polling timer also stops. On
+resume we discard the gap delta from `THREE.Clock` so the watchdog
+doesn't see one huge frame on the first tick.
+
+## Asset budget
+
+Combined first-load budget after prompts 01–04:
+
+| Asset | Cap |
+|---------------------------|----------------|
+| `club-venue.glb` | 8 MB compressed |
+| 4× dancer GLBs | 8 MB total |
+| `pole.glb` + `stage.glb` | 1 MB |
+| `mirrorball.glb` | 200 KB |
+| HDRI | 2 MB |
+| Animation clip JSON | ~150 KB / clip, lazy |
+| Audio | ~1 MB / track, lazy |
+| JS bundle (Vite, gzip) | ≤500 KB |
+
+Total eager budget ≈ 20 MB. On a 3 Mbps mobile link that's ≈7 s wall
+clock; with Vite's preload + HTTP/2 multiplexing, plausibly <5 s.
+
+## Mobile layout
+
+[`pages/club.html`](../../pages/club.html) keeps the existing
+`max-width: 800px` breakpoint but switches the right panel into a
+fixed-position bottom sheet:
+
+- A 44 pt drag handle at the top toggles `.is-expanded` on the panel;
+ CSS `transform: translateY(...)` animates the slide. No JS gesture
+ library — a single tap is enough.
+- The leaderboard is wrapped in `<details>` and starts collapsed on
+ mobile (kept open on desktop via JS that listens for
+ `matchMedia('(max-width: 800px)')` changes).
+- VIP cam buttons (`.club-cam-btn`) and tip CTAs get a 44×44 min size
+ per Apple HIG / Material guidelines.
+- The canvas has `touch-action: none` (orbit + pinch own gestures);
+ the panel has `touch-action: pan-y` so vertical scroll on the tip
+ feed isn't intercepted.
+
+## Device matrix (manual end-to-end)
+
+| Device | Profile picked | Observed fps | Notes |
+|-------------------------------------|----------------|--------------|-------|
+| MacBook Pro M2 / Chrome 120 | high | 60 | All effects on; bloom + cube cam + cones visible. |
+| MacBook Pro M2 / Safari 17 | high | 60 | Cube cam works. |
+| iPhone 12 / Safari 17 | medium | ≥30 | Mirror ball uses static reflection (cubeCam off). |
+| Pixel 6 / Chrome 120 | medium | ≥30 | Bloom on, chromatic aberration off. |
+| iPad Pro 11" / Safari 17 | medium | 45–60 | Coarse pointer triggers medium even with high specs. |
+| 2020 Chromebook (Celeron 4 GB) | low | ≥30 | No shadows, no bloom; watchdog occasionally trims. |
+| Galaxy A52 / Chrome 120 | low | ≥30 | Detected via deviceMemory < 4. |
+
+Numbers are wall-clock observations from manual testing; the watchdog
+console line (`[club] downgrading profile to <tier>`) is the source of
+truth when investigating a remote-screenshot bug report.
+
+## Adding a new feature
+
+When prompts 05+ add scene features, gate them on the active profile:
+
+```js
+import { PROFILES } from './club-perf.js';
+const profile = window.__clubProfile ?? PROFILES.medium;
+if (profile.volumetricCones) {
+ // build the cone mesh
+}
+```
+
+If your feature can be cheaply disabled per-frame (e.g. a render-target
+pass), also add an early-return in your update tick keyed on the
+current `window.__clubProfile` — that way mid-session downgrades drop
+the cost without rebuilding GPU resources.
diff --git a/package.json b/package.json
index 0b5128dc4..7186328ad 100644
--- a/package.json
+++ b/package.json
@@ -72,7 +72,8 @@
"optimize:glb": "node scripts/optimize-glb.mjs",
"fetch-animations": "node scripts/download-animations.mjs",
"fetch:mixamo-catalog": "node scripts/fetch-mixamo-catalog.mjs",
- "test": "vitest run",
+ "test": "vitest run && playwright test",
+ "test:e2e": "playwright test",
"test:pages": "node scripts/test-pages.mjs",
"test:all": "npm run test && npm run test:pages",
"verify": "prettier --check . && vite build",
diff --git a/playwright.config.js b/playwright.config.js
new file mode 100644
index 000000000..8faf8c01c
--- /dev/null
+++ b/playwright.config.js
@@ -0,0 +1,24 @@
+import { defineConfig } from '@playwright/test';
+
+// Playwright config for the /club smoke. Drives a real Chromium against the
+// Vite dev server. Kept separate from Vitest (which only globs *.test.js) by
+// using the `.spec.js` suffix in `tests/e2e/`.
+export default defineConfig({
+ testDir: 'tests/e2e',
+ timeout: 60_000,
+ retries: 1,
+ fullyParallel: false,
+ use: {
+ baseURL: 'http://localhost:3000',
+ headless: true,
+ screenshot: 'only-on-failure',
+ video: 'retain-on-failure',
+ trace: 'retain-on-failure',
+ },
+ webServer: {
+ command: 'npm run dev',
+ url: 'http://localhost:3000',
+ timeout: 60_000,
+ reuseExistingServer: !process.env.CI,
+ },
+});
diff --git a/public/bazaar.js b/public/bazaar.js
new file mode 100644
index 000000000..601f9f878
--- /dev/null
+++ b/public/bazaar.js
@@ -0,0 +1,365 @@
+// public/bazaar.js — discovery UI logic.
+//
+// Talks to /api/bazaar/list and /api/bazaar/search, renders normalized result
+// cards, applies sidebar filters, and routes "Try it" through the drop-in
+// x402.js modal so the same on-chain payment flow used elsewhere ships here
+// too.
+
+const $ = (sel) => document.querySelector(sel);
+const $$ = (sel) => Array.from(document.querySelectorAll(sel));
+
+const els = {
+ form: $('#search-form'),
+ q: $('#q'),
+ clear: $('#clear-btn'),
+ type: $('#f-type'),
+ network: $('#f-network'),
+ max: $('#f-max'),
+ ext: $('#f-ext'),
+ sort: $('#f-sort'),
+ reset: $('#reset-btn'),
+ count: $('#count'),
+ qlabel: $('#qlabel'),
+ sources: $('#sources'),
+ results: $('#results'),
+ empty: $('#empty'),
+ modal: $('#details-modal'),
+ modalTitle: $('#dm-title'),
+ modalBody: $('#dm-body'),
+ modalClose: $('#dm-close'),
+};
+
+const state = {
+ loading: false,
+ lastQuery: '',
+ items: [],
+};
+
+function readFilters() {
+ return {
+ type: els.type.value || 'http',
+ network: els.network.value || '',
+ maxPriceUsdc: els.max.value ? Number(els.max.value) : null,
+ extension: els.ext.value || '',
+ sort: els.sort.value || '',
+ };
+}
+
+function paramsFor(query, f) {
+ const p = new URLSearchParams();
+ if (query) p.set('query', query);
+ p.set('type', f.type);
+ if (f.network) p.set('network', f.network);
+ if (f.maxPriceUsdc != null && !Number.isNaN(f.maxPriceUsdc)) {
+ // USDC is 6 decimals; we store integers as strings to avoid float math.
+ const atomic = Math.round(f.maxPriceUsdc * 1_000_000);
+ p.set('maxPrice', String(atomic));
+ p.set('asset', '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'); // base USDC reference; backend matches by lowercase
+ }
+ if (f.extension) p.set('extension', f.extension);
+ if (f.sort) p.set('sort', f.sort);
+ p.set('maxItems', '500');
+ p.set('limit', query ? '100' : '200');
+ return p;
+}
+
+async function load() {
+ if (state.loading) return;
+ state.loading = true;
+ const query = els.q.value.trim();
+ state.lastQuery = query;
+ const filters = readFilters();
+ const endpoint = query ? '/api/bazaar/search' : '/api/bazaar/list';
+ const url = `${endpoint}?${paramsFor(query, filters).toString()}`;
+ renderLoading(query);
+ try {
+ const r = await fetch(url, { headers: { accept: 'application/json' } });
+ const data = await r.json();
+ if (!r.ok) throw new Error(data?.error_description || data?.error || `HTTP ${r.status}`);
+ state.items = data.resources || data.items || [];
+ renderResults(state.items, query, data.sources || [], data.errors || []);
+ } catch (e) {
+ renderError(e);
+ } finally {
+ state.loading = false;
+ }
+}
+
+function renderLoading(query) {
+ els.results.innerHTML = '';
+ els.empty.hidden = true;
+ els.count.innerHTML = '<span class="spinner"></span>';
+ els.qlabel.textContent = query ? `for "${query}"` : '';
+ els.sources.textContent = '';
+}
+
+function renderError(e) {
+ els.count.textContent = '0';
+ els.empty.hidden = false;
+ els.empty.textContent = `Failed to load: ${e?.message || e}`;
+}
+
+function renderResults(items, query, sources, errors) {
+ els.count.textContent = String(items.length);
+ els.qlabel.textContent = query ? `for "${query}"` : '';
+ els.sources.innerHTML = sourcesLine(sources, errors);
+ if (items.length === 0) {
+ els.results.innerHTML = '';
+ els.empty.hidden = false;
+ els.empty.textContent = 'No matching services. Try fewer filters or a different query.';
+ return;
+ }
+ els.empty.hidden = true;
+ const frag = document.createDocumentFragment();
+ for (const it of items) frag.appendChild(card(it));
+ els.results.replaceChildren(frag);
+}
+
+function sourcesLine(sources, errors) {
+ const parts = sources.map((s) => {
+ const host = safeHost(s.facilitator);
+ return s.ok
+ ? `<span class="ok">${host} (${s.count})</span>`
+ : `<span class="err">${host} (failed)</span>`;
+ });
+ if (errors.length) {
+ for (const e of errors) {
+ parts.push(`<span class="err" title="${escape(e.error)}">${safeHost(e.facilitator)} ✗</span>`);
+ }
+ }
+ return parts.join(' · ');
+}
+
+function safeHost(u) {
+ try { return new URL(u).host; } catch { return String(u); }
+}
+
+function card(it) {
+ const el = document.createElement('div');
+ el.className = 'card';
+
+ const head = document.createElement('div');
+ head.className = 'head';
+ const icon = document.createElement('div');
+ icon.className = 'icon';
+ if (it.iconUrl) {
+ const img = document.createElement('img');
+ img.src = it.iconUrl;
+ img.alt = '';
+ img.referrerPolicy = 'no-referrer';
+ img.onerror = () => {
+ icon.textContent = initial(it);
+ img.remove();
+ };
+ icon.appendChild(img);
+ } else {
+ icon.textContent = initial(it);
+ }
+ const titleBox = document.createElement('div');
+ titleBox.style.flex = '1';
+ titleBox.style.minWidth = '0';
+ const title = document.createElement('div');
+ title.className = 'title';
+ title.textContent = it.serviceName || prettyTitle(it);
+ const sub = document.createElement('div');
+ sub.className = 'subtitle';
+ sub.textContent = it.toolName ? `${it.toolName} — ${it.resource}` : it.resource;
+ titleBox.append(title, sub);
+ head.append(icon, titleBox);
+
+ const desc = document.createElement('div');
+ desc.className = 'desc';
+ desc.textContent = it.description || '';
+
+ const meta = document.createElement('div');
+ meta.className = 'meta';
+ if (it.minPriceLabel) meta.appendChild(tag('price', it.minPriceLabel));
+ if (it.method) meta.appendChild(tag('method', it.method));
+ for (const n of it.networks || []) meta.appendChild(tag('net', shortNet(n)));
+ for (const ext of it.extensions || []) {
+ if (ext === 'bazaar') continue; // implied
+ meta.appendChild(tag('ext', ext));
+ }
+
+ const actions = document.createElement('div');
+ actions.className = 'actions';
+ const tryBtn = document.createElement('button');
+ tryBtn.type = 'button';
+ tryBtn.className = 'btn-pay';
+ tryBtn.textContent = it.type === 'mcp' ? 'Inspect tool' : 'Try it';
+ tryBtn.onclick = () => onTry(el, it, tryBtn);
+ const detailsBtn = document.createElement('button');
+ detailsBtn.type = 'button';
+ detailsBtn.className = 'btn-details';
+ detailsBtn.textContent = 'Details';
+ detailsBtn.onclick = () => openDetails(it);
+ actions.append(tryBtn, detailsBtn);
+
+ const receipt = document.createElement('div');
+ receipt.className = 'receipt';
+ receipt.hidden = true;
+ receipt.dataset.role = 'receipt';
+
+ el.append(head, desc, meta, actions, receipt);
+ return el;
+}
+
+function tag(kind, text) {
+ const t = document.createElement('span');
+ t.className = `tag ${kind}`;
+ t.textContent = text;
+ return t;
+}
+
+function shortNet(n) {
+ if (!n) return '';
+ if (n.startsWith('eip155:8453')) return 'base';
+ if (n.startsWith('eip155:84532')) return 'base-sepolia';
+ if (n.startsWith('eip155:42161')) return 'arbitrum';
+ if (n.startsWith('eip155:10')) return 'optimism';
+ if (n.startsWith('eip155:137')) return 'polygon';
+ if (n.startsWith('solana')) return 'solana';
+ return n;
+}
+
+function initial(it) {
+ const s = (it.serviceName || it.resource || '?').replace(/^https?:\/\//, '');
+ return s.charAt(0).toUpperCase() || '?';
+}
+
+function prettyTitle(it) {
+ if (it.toolName) return it.toolName;
+ try {
+ const u = new URL(it.resource);
+ const tail = u.pathname.replace(/\/$/, '').split('/').pop();
+ return tail ? `${u.host} · ${tail}` : u.host;
+ } catch {
+ return it.resource || 'Untitled';
+ }
+}
+
+async function onTry(cardEl, it, btn) {
+ if (it.type === 'mcp') {
+ // MCP tools require a JSON-RPC tools/call envelope, which the drop-in modal
+ // doesn't speak. Show the details panel so callers can wire it themselves.
+ openDetails(it);
+ return;
+ }
+ const receipt = cardEl.querySelector('[data-role=receipt]');
+ receipt.hidden = false;
+ receipt.className = 'receipt';
+ receipt.textContent = 'Opening x402 payment modal…';
+ btn.disabled = true;
+ try {
+ const opts = {
+ endpoint: it.resource,
+ method: it.input?.method || it.method || 'GET',
+ merchant: safeHost(it.resource),
+ action: it.serviceName || prettyTitle(it),
+ };
+ if (it.input?.body) opts.body = it.input.body;
+ if (it.input?.queryParams && Object.keys(it.input.queryParams).length) {
+ const u = new URL(opts.endpoint);
+ for (const [k, v] of Object.entries(it.input.queryParams)) u.searchParams.set(k, String(v));
+ opts.endpoint = u.toString();
+ }
+ const out = await window.X402.pay(opts);
+ if (out?.ok) {
+ receipt.className = 'receipt ok';
+ receipt.innerHTML = renderReceipt(out);
+ } else {
+ receipt.className = 'receipt err';
+ receipt.textContent = `Failed: ${out?.error || 'unknown error'}`;
+ }
+ } catch (e) {
+ if (e?.code === 'cancelled') {
+ receipt.hidden = true;
+ } else {
+ receipt.className = 'receipt err';
+ receipt.textContent = `Error: ${e?.message || e}`;
+ }
+ } finally {
+ btn.disabled = false;
+ }
+}
+
+function renderReceipt(out) {
+ const tx = out.payment?.transaction || out.payment?.tx || '';
+ const net = out.payment?.network || '';
+ const explorer = explorerLink(net, tx);
+ const head = explorer
+ ? `<a href="${explorer}" target="_blank" rel="noopener">on-chain receipt</a> · ${escape(net)} · ${escape(short(tx))}`
+ : `paid${net ? ` on ${escape(net)}` : ''}${tx ? ' · ' + escape(short(tx)) : ''}`;
+ const body = typeof out.result === 'string' ? out.result : JSON.stringify(out.result, null, 2);
+ return `${head}\n\n${escape(body)}`;
+}
+
+function explorerLink(net, tx) {
+ if (!tx) return null;
+ if (net.startsWith('solana')) return `https://solscan.io/tx/${tx}`;
+ if (net.includes('8453')) return `https://basescan.org/tx/${tx}`;
+ if (net.includes('84532')) return `https://sepolia.basescan.org/tx/${tx}`;
+ if (net.includes('42161')) return `https://arbiscan.io/tx/${tx}`;
+ if (net.includes('10')) return `https://optimistic.etherscan.io/tx/${tx}`;
+ if (net.includes('137')) return `https://polygonscan.com/tx/${tx}`;
+ return null;
+}
+
+function short(s) {
+ if (!s) return '';
+ return s.length > 14 ? `${s.slice(0, 6)}…${s.slice(-6)}` : s;
+}
+
+function escape(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+}
+
+function openDetails(it) {
+ els.modalTitle.textContent = it.serviceName || prettyTitle(it);
+ const pre = document.createElement('pre');
+ pre.textContent = JSON.stringify(it.raw, null, 2);
+ const summary = document.createElement('div');
+ summary.style.marginBottom = '12px';
+ summary.style.fontSize = '13px';
+ summary.style.color = 'var(--muted)';
+ summary.innerHTML = `
+ <div><strong style="color:var(--text)">${escape(it.resource)}</strong></div>
+ <div>type: ${escape(it.type)}${it.toolName ? ' · tool: ' + escape(it.toolName) : ''} · method: ${escape(it.method || '')}</div>
+ <div>networks: ${(it.networks || []).map(escape).join(', ')}</div>
+ <div>price: ${escape(it.minPriceLabel || '—')}</div>
+ <div>facilitator: ${escape(safeHost(it.facilitator))}</div>
+ `;
+ els.modalBody.replaceChildren(summary, pre);
+ if (typeof els.modal.showModal === 'function') els.modal.showModal();
+}
+
+els.modalClose.addEventListener('click', () => els.modal.close());
+els.modal.addEventListener('click', (e) => {
+ const rect = els.modal.getBoundingClientRect();
+ if (e.clientY < rect.top || e.clientY > rect.bottom || e.clientX < rect.left || e.clientX > rect.right) {
+ els.modal.close();
+ }
+});
+
+els.form.addEventListener('submit', (e) => { e.preventDefault(); load(); });
+els.clear.addEventListener('click', () => { els.q.value = ''; load(); });
+els.reset.addEventListener('click', () => {
+ els.type.value = 'http';
+ els.network.value = '';
+ els.max.value = '';
+ els.ext.value = '';
+ els.sort.value = '';
+ els.q.value = '';
+ load();
+});
+[els.type, els.network, els.max, els.ext, els.sort].forEach((el) => {
+ const ev = el.tagName === 'SELECT' ? 'change' : 'input';
+ let t;
+ el.addEventListener(ev, () => {
+ clearTimeout(t);
+ t = setTimeout(load, 200);
+ });
+});
+
+// Initial render.
+load();
diff --git a/src/club.js b/src/club.js
index a80e81ea9..77009ffe8 100644
--- a/src/club.js
+++ b/src/club.js
@@ -306,8 +306,12 @@ camera.position.set(0, 1.8, 6.0);
camera.lookAt(0, 1.4, -1.5);
const clubCam = new ClubCamera(camera, {
- onModeChange: (mode) => updateFreeCamChip(mode),
+ onModeChange: (mode) => {
+ updateFreeCamChip(mode);
+ document.querySelector('#club-stage')?.setAttribute('data-cam-mode', mode);
+ },
});
+document.querySelector('#club-stage')?.setAttribute('data-cam-mode', clubCam.getMode());
// ── Club floor + walls ───────────────────────────────────────────────────
const floor = new Mesh(
diff --git a/tests/e2e/club.spec.js b/tests/e2e/club.spec.js
new file mode 100644
index 000000000..70ae527b3
--- /dev/null
+++ b/tests/e2e/club.spec.js
@@ -0,0 +1,131 @@
+import { test, expect } from '@playwright/test';
+
+// /club end-to-end smoke. Drives real Chromium against `npm run dev`, stubs
+// the on-chain settle endpoint (signing a real mainnet tx in CI is unsafe)
+// plus the auxiliary side-panel routes, and asserts visible behavior — not
+// pixel diffs.
+test.describe('/club', () => {
+ test('venue loads + tip settles + dancer performs', async ({ page }) => {
+ const consoleErrors = [];
+ page.on('console', (m) => {
+ if (m.type() === 'error') consoleErrors.push(m.text());
+ });
+
+ // Replace the public x402 widget with a no-modal stub. Doing this via
+ // route() instead of addInitScript() guarantees our stub wins the
+ // race against the real `window.X402 = Object.freeze(...)` in
+ // /public/x402.js, since the real script is never delivered.
+ await page.route('**/x402.js', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/javascript',
+ body: `window.X402 = {
+ pay: async ({ endpoint }) => {
+ const r = await fetch(endpoint);
+ return { result: await r.json() };
+ },
+ init: () => {},
+ version: 'e2e-stub',
+ };`,
+ }),
+ );
+
+ // Stub the settle endpoint. Returns the same JSON shape the real
+ // /api/x402/dance-tip endpoint produces on success.
+ await page.route('**/api/x402/dance-tip*', (route) => {
+ const u = new URL(route.request().url());
+ const dancer = u.searchParams.get('dancer') ?? '1';
+ const dance = u.searchParams.get('dance') ?? 'rumba';
+ return route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ ok: true,
+ ticketId: 'e2e-ticket-1',
+ dancer,
+ dance,
+ clip: dance,
+ label: dance.charAt(0).toUpperCase() + dance.slice(1),
+ loop: true,
+ durationSec: 6,
+ startsAt: new Date().toISOString(),
+ endsAt: new Date(Date.now() + 6000).toISOString(),
+ payer: 'e2e-test-payer',
+ network: 'solana',
+ amountAtomics: '1000',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ }),
+ });
+ });
+
+ // Stub the side endpoints so a missing dev DB / SSE channel doesn't
+ // pollute the console-error count this test asserts on.
+ await page.route('**/api/club/leaderboard*', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ window: 'day', rows: [] }),
+ }),
+ );
+ await page.route('**/api/club/tips?**', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ tips: [] }),
+ }),
+ );
+ await page.route('**/api/club/tips/stream', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'text/event-stream',
+ body: 'event: hello\ndata: ok\n\n',
+ }),
+ );
+
+ await page.goto('/club');
+
+ // Venue must finish loading (status pill flips to 'ok'). The pill
+ // auto-hides on a timer but the data-kind attribute persists.
+ await expect(page.locator('#club-status')).toHaveAttribute('data-kind', 'ok', { timeout: 30_000 });
+
+ await page.locator('.club-tip-btn[data-dancer="1"]').click();
+
+ // Tip-feed row appears for dancer 1 (rendered as "tipped dancer 1 → …").
+ await expect(page.locator('.club-tip-row').first()).toContainText('dancer 1');
+
+ expect(consoleErrors, consoleErrors.join('\n')).toHaveLength(0);
+ });
+
+ test('keyboard VIP cam shortcuts work', async ({ page }) => {
+ await page.goto('/club');
+
+ // data-cam-mode is written by the ClubCamera onModeChange callback in
+ // src/club.js. The state machine only emits on transitions, so we
+ // assert after a key press (free → vip) and after Escape (vip → free).
+ await page.keyboard.press('2');
+ await expect(page.locator('#club-stage')).toHaveAttribute('data-cam-mode', 'vip');
+
+ await page.keyboard.press('Escape');
+ await expect(page.locator('#club-stage')).toHaveAttribute('data-cam-mode', 'free');
+ });
+
+ test('leaderboard renders + tab switching', async ({ page }) => {
+ await page.route('**/api/club/leaderboard*', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ window: 'day',
+ rows: [
+ { dancer: '1', display_name: 'Nyx', total_atomics: '4000', tip_count: 4, unpaid_atomics: '4000' },
+ { dancer: '2', display_name: 'Ari', total_atomics: '3000', tip_count: 3, unpaid_atomics: '0' },
+ { dancer: '3', display_name: 'Sable', total_atomics: '1000', tip_count: 1, unpaid_atomics: '0' },
+ { dancer: '4', display_name: 'Vesper', total_atomics: '0', tip_count: 0, unpaid_atomics: '0' },
+ ],
+ }),
+ }),
+ );
+ await page.goto('/club');
+ await expect(page.locator('#club-lb-rows .club-lb-row').first()).toContainText('Nyx');
+ });
+});
diff --git a/vercel.json b/vercel.json
index b50e4d8bd..96a5006ba 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1251,6 +1251,22 @@
"src": "/x402/",
"dest": "/x402-stripe.html"
},
+ {
+ "src": "/bazaar",
+ "dest": "/bazaar.html"
+ },
+ {
+ "src": "/bazaar/",
+ "dest": "/bazaar.html"
+ },
+ {
+ "src": "/api/bazaar/list",
+ "dest": "/api/bazaar/list.js"
+ },
+ {
+ "src": "/api/bazaar/search",
+ "dest": "/api/bazaar/search.js"
+ },
{
"src": "/settings",
"dest": "/settings/index.html"