Skip to content

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

feat(x402): Permit2 gas-sponsoring siblings + R2 CORS + buildout/club/siwx docs

nirholasf5b5395bc406
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index e25e6f6b2..a6f1a31aa 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -21,6 +21,7 @@ import {
NETWORK_SOLANA_MAINNET,
X402Error,
encodePaymentResponseHeader,
+ permit2VariantOf,
resolveResourceUrl,
send402,
settlePayment,
@@ -96,7 +97,16 @@ function buildRequirements({ priceAtomics, networks, resourceUrl }) {
if (net === NETWORK_BASE_MAINNET && !env.X402_PAY_TO_BASE) continue;
if (net === NETWORK_SOLANA_MAINNET && !env.X402_PAY_TO_SOLANA) continue;
if (net === NETWORK_BSC_MAINNET && !env.X402_PAY_TO_BSC) continue;
- out.push(buildAccept(net, priceAtomics, resourceUrl));
+ const accept = buildAccept(net, priceAtomics, resourceUrl);
+ out.push(accept);
+ // For EVM `exact` networks, advertise a Permit2 sibling so @x402/* SDK
+ // clients can pick the gasless Permit2-via-EIP-2612 path. The EIP-3009
+ // entry stays first so the browser modal (which only signs
+ // transferWithAuthorization) keeps selecting it. send402/build402Body
+ // auto-declares the eip2612GasSponsoring extension when this sibling
+ // is present — no per-endpoint opt-in needed.
+ const sibling = permit2VariantOf(accept);
+ if (sibling) out.push(sibling);
}
if (!out.length) {
throw new X402Error(
diff --git a/api/_lib/x402-permit2.js b/api/_lib/x402-permit2.js
deleted file mode 100644
index bcbb9c818..000000000
--- a/api/_lib/x402-permit2.js
+++ /dev/null
@@ -1,102 +0,0 @@
-// x402 EVM Permit2 helpers — adds a Permit2-flavored acceptance entry and
-// advertises the gas-sponsoring extensions that let buyers pay USDC (or any
-// ERC-20 we choose to accept) without holding native gas.
-//
-// Why both extensions:
-// • EIP-2612 gas sponsoring — preferred path for tokens that implement
-// EIP-2612 (Base USDC v2 does). Client signs an off-chain permit; the
-// CDP facilitator submits it on-chain via x402ExactPermit2Proxy.settleWithPermit
-// in the same batch as the Permit2 transfer.
-// • ERC-20 approval gas sponsoring — universal fallback for any other
-// ERC-20. Client signs (but does not broadcast) a raw approve(Permit2,
-// MaxUint256) tx; the facilitator broadcasts it atomically before
-// calling x402ExactPermit2Proxy.settle.
-//
-// Both are server-side ADVERTISEMENTS only. Whether they actually fire
-// depends on the facilitator we route Base traffic to. CDP supports both
-// today; PayAI does not (it only settles EIP-3009). When the resource server
-// uses CDP (CDP_API_KEY_ID + CDP_API_KEY_SECRET set), advertise. Otherwise
-// keep the 402 body to EIP-3009 only so we don't promise capabilities the
-// facilitator won't honor.
-//
-// We keep the existing EIP-3009 acceptance entry as the FIRST item in
-// `accepts[]` so default clients (including our drop-in modal at
-// public/x402.js) continue using the simpler gasless EIP-3009 flow. The
-// Permit2 entry is appended as a secondary option for agentic clients using
-// @x402/evm's ExactEvmScheme, which auto-routes to Permit2 when the
-// `assetTransferMethod` extra is present.
-
-import {
- declareEip2612GasSponsoringExtension,
- declareErc20ApprovalGasSponsoringExtension,
-} from '@x402/extensions';
-
-import { env } from './env.js';
-import { NETWORK_BASE_MAINNET } from './x402-spec.js';
-
-// Canonical Permit2 contract — same address on every EVM chain via CREATE2.
-// See https://github.com/Uniswap/permit2 and @x402/evm constants.
-export const PERMIT2_ADDRESS = '0x000000000022D473030F116dDEE9F6B43aC78BA3';
-
-// x402ExactPermit2Proxy — vanity 0x4020…0001. Facilitator calls
-// settle()/settleWithPermit() on this contract. Buyers don't interact with
-// it directly; we just declare it as the Permit2 spender witness target.
-export const X402_EXACT_PERMIT2_PROXY_ADDRESS = '0x402085c248EeA27D92E8b30b2C58ed07f9E20001';
-
-// Per-network EIP-2612 domain `version` for the canonical native USDC.
-// Used by clients that want to skip an on-chain DOMAIN_SEPARATOR fetch. Base
-// USDC (FiatTokenV2_2) is at "2"; Arbitrum native USDC also "2".
-const USDC_EIP2612_VERSION_BY_NETWORK = {
- [NETWORK_BASE_MAINNET]: '2',
-};
-
-// CDP is the only facilitator we route to that currently settles Permit2 +
-// gas-sponsoring. If CDP creds are absent we must NOT advertise these
-// extensions — the buyer would sign Permit2 typed-data, send it to our
-// PayAI-routed Base endpoint, and the settle call would fail with a clean
-// `unsupported_scheme` from PayAI.
-export function facilitatorSupportsPermit2GasSponsoring() {
- return Boolean(env.CDP_API_KEY_ID && env.CDP_API_KEY_SECRET);
-}
-
-// Build a v2 PaymentRequirements accept entry that uses Permit2 instead of
-// EIP-3009. Same `payTo` (the seller wallet) and same `asset` (USDC); just
-// flips `extra.assetTransferMethod` so the client routes through the proxy.
-//
-// The `extra.spender` field is non-standard but harmless — some clients use
-// it as a hint for the Permit2 PermitWitnessTransferFrom typed-data, which
-// requires the spender (= x402ExactPermit2Proxy) explicitly.
-export function buildBaseUsdcPermit2Accept({ priceAtomics, resourceUrl }) {
- if (!env.X402_PAY_TO_BASE) return null;
- const network = NETWORK_BASE_MAINNET;
- return {
- scheme: 'exact',
- network,
- amount: String(priceAtomics),
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- payTo: env.X402_PAY_TO_BASE,
- asset: env.X402_ASSET_ADDRESS_BASE,
- extra: {
- name: 'USD Coin',
- version: USDC_EIP2612_VERSION_BY_NETWORK[network] || '2',
- decimals: 6,
- assetTransferMethod: 'permit2',
- spender: X402_EXACT_PERMIT2_PROXY_ADDRESS,
- permit2Address: PERMIT2_ADDRESS,
- },
- };
-}
-
-// Merged extension declarations advertising both gas-sponsoring extensions.
-// Returns the object shape expected at `PaymentRequired.extensions` — keyed
-// by extension identifier (`eip2612GasSponsoring`, `erc20ApprovalGasSponsoring`).
-// Returns null when the facilitator can't honor them, so callers can spread
-// `...(permit2GasSponsoringExtensions() || {})` without conditionals.
-export function permit2GasSponsoringExtensions() {
- if (!facilitatorSupportsPermit2GasSponsoring()) return null;
- return {
- ...declareEip2612GasSponsoringExtension(),
- ...declareErc20ApprovalGasSponsoringExtension(),
- };
-}
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 1597fff08..540174263 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -34,7 +34,9 @@
import { createCdpAuthHeaders } from '@coinbase/x402';
import {
EIP2612_GAS_SPONSORING,
+ ERC20_APPROVAL_GAS_SPONSORING,
declareEip2612GasSponsoringExtension,
+ declareErc20ApprovalGasSponsoringExtension,
} from '@x402/extensions';
import { env } from './env.js';
@@ -46,16 +48,23 @@ import {
} from './x402-bsc-direct.js';
export { X402Error };
+export { declareEip2612GasSponsoringExtension };
export const X402_VERSION = 2;
-// Extension keys we advertise alongside the bazaar discovery entry. The
-// eip2612 gas-sponsoring extension is a non-binding hint to clients: when a
+// Extension keys we advertise alongside the bazaar discovery entry. Both
+// gas-sponsoring extensions are non-binding hints to clients: when a
// requirement opts into the Permit2 asset-transfer method, the facilitator
-// (CDP's x402ExactPermit2Proxy) accepts an off-chain EIP-2612 permit so the
-// payer never broadcasts the Permit2-approval tx themselves. Legacy clients
-// stay on the EIP-3009 accept entry (offered first below) and ignore this.
+// (CDP's x402ExactPermit2Proxy) lets the payer skip broadcasting the Permit2
+// approval themselves. EIP-2612 sponsorship is the preferred path for tokens
+// that implement EIP-2612 (Base USDC v2 does — the facilitator submits the
+// off-chain permit via settleWithPermit). ERC-20 approval sponsorship is the
+// universal fallback for any other ERC-20: the client signs (but does not
+// broadcast) a raw approve(Permit2, MaxUint256) tx and the facilitator
+// broadcasts it atomically before settling. Legacy clients stay on the
+// EIP-3009 accept entry (offered first) and ignore both extensions.
export const EIP2612_EXTENSION_KEY = EIP2612_GAS_SPONSORING.key;
+export const ERC20_APPROVAL_EXTENSION_KEY = ERC20_APPROVAL_GAS_SPONSORING.key;
// CAIP-2 network IDs as advertised by Coinbase x402 facilitators (PayAI, CDP).
// Solana mainnet's CAIP-2 namespace uses the truncated genesis-block hash.
@@ -85,11 +94,18 @@ const DIRECT_NETWORKS = new Set([NETWORK_BSC_MAINNET]);
// `assetTransferMethod` field is what @x402/evm's ExactEvmScheme keys on; with
// `supportsEip2612: true` set, the scheme will sign an EIP-2612 permit when
// its Permit2 allowance is insufficient and stuff it into the payment payload
-// extensions for the facilitator to submit. Returns null when the source
-// accept is not an EVM `exact` entry (BSC direct + Solana fall through to null).
+// extensions for the facilitator to submit.
+//
+// Returns null when:
+// 1. The source accept is not an EVM `exact` entry (BSC direct + Solana).
+// 2. CDP credentials are missing — Permit2 settlement is a CDP-only path
+// (PayAI's facilitator only advertises `exact` with EIP-3009). Emitting
+// a Permit2 sibling we can't actually settle would mislead clients into
+// signing a typed-data we'd then reject at /verify time.
export function permit2VariantOf(accept) {
if (!accept || accept.scheme !== 'exact') return null;
if (typeof accept.network !== 'string' || !accept.network.startsWith('eip155:')) return null;
+ if (!env.CDP_API_KEY_ID || !env.CDP_API_KEY_SECRET) return null;
return {
...accept,
extra: {
@@ -376,12 +392,25 @@ export async function probeFacilitators() {
});
continue;
}
- const supports = data.kinds.some(
+ const matching = data.kinds.filter(
(k) =>
k.scheme === 'exact' &&
k.network === t.network &&
(k.x402Version ?? 1) === X402_VERSION,
);
+ const supports = matching.length > 0;
+ // Aggregate the extension keys the facilitator advertises for this
+ // scheme/network. Each /supported `kind` carries an `extensions: string[]`
+ // list (see @x402/core server schema). We surface whether each gas-
+ // sponsoring extension is present so /api/x402-status can flag silently-
+ // degraded setups where we advertise an extension but the facilitator
+ // won't actually settle it.
+ const advertisedExtensions = new Set();
+ for (const k of matching) {
+ if (Array.isArray(k.extensions)) {
+ for (const ext of k.extensions) advertisedExtensions.add(ext);
+ }
+ }
results.push({
network: t.network,
url: t.url,
@@ -389,6 +418,9 @@ export async function probeFacilitators() {
reason: supports
? `facilitator advertises exact/${t.network}`
: `facilitator does NOT advertise scheme=exact network=${t.network} (configure X402_FACILITATOR_URL_${t.network.toUpperCase()} to a facilitator that does)`,
+ extensions: [...advertisedExtensions],
+ supportsEip2612GasSponsoring: advertisedExtensions.has(EIP2612_EXTENSION_KEY),
+ supportsErc20ApprovalGasSponsoring: advertisedExtensions.has(ERC20_APPROVAL_EXTENSION_KEY),
});
}
return results;
@@ -673,11 +705,29 @@ export function bazaarExtension() {
};
}
+// True when any offered requirement asks the client to use the Permit2
+// asset-transfer method. When so, we automatically advertise BOTH gas-
+// sponsoring extensions at the top level — the facilitator (CDP's
+// x402ExactPermit2Proxy) submits the approval atomically with settlement so
+// the payer never broadcasts the approval tx themselves. EIP-2612 is the
+// preferred path for tokens that implement it (Base USDC v2 does);
+// ERC-20 approval is the universal fallback that works with any ERC-20.
+// permit2VariantOf already gates Permit2 emission on CDP creds being
+// present, so by the time any accept reaches this check, the facilitator
+// can honor both extensions.
+function hasPermit2Accept(accepts) {
+ const list = Array.isArray(accepts) ? accepts : [accepts];
+ return list.some((a) => a?.extra?.assetTransferMethod === 'permit2');
+}
+
// Build the v2 PaymentRequired body. Top-level `resource` carries url/description/
// mimeType (per v2 spec); per-accept entries no longer repeat them.
//
// `description`, `mimeType`, and `bazaar` are per-route — each paid endpoint
// wants its own catalog entry on agentic.market, not the MCP boilerplate.
+// 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`.
export function build402Body({
resourceUrl,
accepts,
@@ -685,13 +735,25 @@ export function build402Body({
description = RESOURCE_DESCRIPTION,
mimeType = 'application/json',
bazaar = bazaarExtension(),
+ extensions: extraExtensions,
}) {
+ const extensions = { bazaar };
+ if (hasPermit2Accept(accepts)) {
+ Object.assign(
+ extensions,
+ declareEip2612GasSponsoringExtension(),
+ declareErc20ApprovalGasSponsoringExtension(),
+ );
+ }
+ if (extraExtensions && typeof extraExtensions === 'object') {
+ Object.assign(extensions, extraExtensions);
+ }
return {
x402Version: X402_VERSION,
error,
resource: { url: resourceUrl, description, mimeType },
accepts: Array.isArray(accepts) ? accepts : [accepts],
- extensions: { bazaar },
+ extensions,
};
}
diff --git a/api/wk.js b/api/wk.js
index 28df6c836..2ddd633a8 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -7,9 +7,12 @@ import {
paymentRequirements,
bazaarExtension,
build402Body,
+ declareEip2612GasSponsoringExtension,
+ permit2VariantOf,
NETWORK_BASE_MAINNET,
NETWORK_SOLANA_MAINNET,
} from './_lib/x402-spec.js';
+import { declareErc20ApprovalGasSponsoringExtension } from '@x402/extensions';
// ── agent-attestation-schemas ─────────────────────────────────────────────────
@@ -184,11 +187,38 @@ const RAW_AMOUNT_TO_USDC = (raw) => {
// Each new /api/x402/* endpoint has its own price set in its handler via
// paidEndpoint(priceAtomics); the discovery doc has to mirror that or
// agentic.market shows the wrong price to potential buyers.
+// Push an EVM accept entry followed by its Permit2 sibling so the Bazaar
+// discovery doc mirrors the live 402 response exactly (EIP-3009 first,
+// Permit2 second). Non-EVM entries get no sibling.
+function pushAcceptWithPermit2Sibling(out, accept) {
+ out.push(accept);
+ const sibling = permit2VariantOf(accept);
+ if (sibling) out.push(sibling);
+}
+
+// Per-resource extensions for the discovery catalog. The bazaar entry is
+// always present; the two gasless-Permit2-onboarding extensions are added
+// whenever any accept in the list opts into the Permit2 transfer method.
+// EIP-2612 covers tokens that implement `permit()` (USDC, DAI, ...); the
+// ERC-20 approval variant covers tokens that don't. Both let the facilitator
+// sponsor the approve() so the payer never broadcasts the approval tx.
+function extensionsForAccepts(accepts, bazaar) {
+ const exts = { bazaar };
+ if (accepts.some((a) => a?.extra?.assetTransferMethod === 'permit2')) {
+ Object.assign(
+ exts,
+ declareEip2612GasSponsoringExtension(),
+ declareErc20ApprovalGasSponsoringExtension(),
+ );
+ }
+ return exts;
+}
+
function acceptsForPrice(amountAtomics) {
const out = [];
const price = RAW_AMOUNT_TO_USDC(amountAtomics);
if (env.X402_PAY_TO_BASE) {
- out.push({
+ pushAcceptWithPermit2Sibling(out, {
scheme: 'exact',
network: NETWORK_BASE_MAINNET,
network_label: 'base-mainnet',
@@ -228,7 +258,7 @@ function handleX402Discovery(req, res) {
const mcpAccepts = [];
if (env.X402_PAY_TO_BASE) {
- mcpAccepts.push({
+ pushAcceptWithPermit2Sibling(mcpAccepts, {
scheme: 'exact',
network: NETWORK_BASE_MAINNET,
network_label: 'base-mainnet',
@@ -259,33 +289,34 @@ function handleX402Discovery(req, res) {
// /api/x402/model-check is the CDP-Bazaar-cataloged endpoint. CDP supports
// Base mainnet + Arbitrum One; advertise both here so agentic.market shows
// the same network options buyers will see in the live 402 challenge.
+ // Each EVM entry gets a Permit2 sibling so EIP-2612-aware clients can pick
+ // the gasless Permit2-via-EIP-2612 path.
const ARB_USDC = env.X402_ASSET_ADDRESS_ARBITRUM;
- const modelCheckAccepts = [
- {
- scheme: 'exact',
- network: NETWORK_BASE_MAINNET,
- network_label: 'base-mainnet',
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- price,
- payTo: env.X402_PAY_TO_BASE,
- asset: env.X402_ASSET_ADDRESS_BASE,
- asset_symbol: 'USDC',
- maxTimeoutSeconds: 60,
- extra: { name: 'USDC', version: '2', decimals: 6 },
- },
- {
- scheme: 'exact',
- network: 'eip155:42161',
- network_label: 'arbitrum-one',
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- price,
- payTo: env.X402_PAY_TO_BASE,
- asset: ARB_USDC,
- asset_symbol: 'USDC',
- maxTimeoutSeconds: 60,
- extra: { name: 'USDC', version: '2', decimals: 6 },
- },
- ];
+ const modelCheckAccepts = [];
+ pushAcceptWithPermit2Sibling(modelCheckAccepts, {
+ scheme: 'exact',
+ network: NETWORK_BASE_MAINNET,
+ network_label: 'base-mainnet',
+ amount: env.X402_MAX_AMOUNT_REQUIRED,
+ price,
+ payTo: env.X402_PAY_TO_BASE,
+ asset: env.X402_ASSET_ADDRESS_BASE,
+ asset_symbol: 'USDC',
+ maxTimeoutSeconds: 60,
+ extra: { name: 'USDC', version: '2', decimals: 6 },
+ });
+ pushAcceptWithPermit2Sibling(modelCheckAccepts, {
+ scheme: 'exact',
+ network: 'eip155:42161',
+ network_label: 'arbitrum-one',
+ amount: env.X402_MAX_AMOUNT_REQUIRED,
+ price,
+ payTo: env.X402_PAY_TO_BASE,
+ asset: ARB_USDC,
+ asset_symbol: 'USDC',
+ maxTimeoutSeconds: 60,
+ extra: { name: 'USDC', version: '2', decimals: 6 },
+ });
return json(
res,
@@ -331,24 +362,22 @@ function handleX402Discovery(req, res) {
'Fetches a glTF/GLB model from a URL and returns structural stats (vertex/triangle counts, materials, textures, animations, extensions) plus a prioritized list of optimization recommendations. Single GET, ?url=…. CDP-Bazaar-cataloged.',
mimeType: 'application/json',
accepts: modelCheckAccepts,
- extensions: {
- bazaar: {
- method: 'GET',
- discoverable: true,
- input: { url: 'https://three.ws/avatar/character-studio/sample.glb' },
- inputSchema: {
- type: 'object',
- required: ['url'],
- properties: {
- url: {
- type: 'string',
- format: 'uri',
- description: 'Public HTTPS URL of a glTF/GLB model.',
- },
+ extensions: extensionsForAccepts(modelCheckAccepts, {
+ method: 'GET',
+ discoverable: true,
+ input: { url: 'https://three.ws/avatar/character-studio/sample.glb' },
+ inputSchema: {
+ type: 'object',
+ required: ['url'],
+ properties: {
+ url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public HTTPS URL of a glTF/GLB model.',
},
},
},
- },
+ }),
},
{
path: '/api/x402/mint-to-mesh',
@@ -358,25 +387,23 @@ function handleX402Discovery(req, res) {
'Mint to Mesh — pass a Solana fungible-token mint, get back a binary glTF (GLB) cube themed for that token. Color is derived from a stable hash of the mint; when the off-chain Metaplex JSON exposes a PNG/JPEG, that image is embedded as a baseColor texture on every face. Asset.extras carry mint, name, symbol, and timestamp. Useful for any agent that needs an instantly renderable 3D representation of a token. CDP-Bazaar-cataloged.',
mimeType: 'application/json',
accepts: modelCheckAccepts,
- extensions: {
- bazaar: {
- method: 'GET',
- discoverable: true,
- input: { mint: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263' },
- inputSchema: {
- type: 'object',
- required: ['mint'],
- properties: {
- mint: {
- type: 'string',
- minLength: 32,
- maxLength: 64,
- description: 'Base58 SPL mint address on Solana mainnet.',
- },
+ extensions: extensionsForAccepts(modelCheckAccepts, {
+ method: 'GET',
+ discoverable: true,
+ input: { mint: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263' },
+ inputSchema: {
+ type: 'object',
+ required: ['mint'],
+ properties: {
+ mint: {
+ type: 'string',
+ minLength: 32,
+ maxLength: 64,
+ description: 'Base58 SPL mint address on Solana mainnet.',
},
},
},
- },
+ }),
},
{
path: '/api/insights/revenue-vision',
@@ -386,31 +413,29 @@ function handleX402Discovery(req, res) {
'Revenue Vision — agentic growth analysis powered by Claude. Hand over a mission_brief and get back a single prioritized next-best move, a data-grounded insight, and an honestly-calibrated confidence rating. CDP-Bazaar-cataloged.',
mimeType: 'application/json',
accepts: modelCheckAccepts,
- extensions: {
- bazaar: {
- method: 'GET',
- discoverable: true,
- input: {
- agent_codename: 'ledger-bot',
- power_request: 'revenue-vision',
- mission_brief:
- 'Find the highest-converting buyer segment this week.',
- },
- inputSchema: {
- type: 'object',
- required: ['agent_codename', 'power_request', 'mission_brief'],
- properties: {
- agent_codename: { type: 'string' },
- power_request: { type: 'string', enum: ['revenue-vision'] },
- mission_brief: {
- type: 'string',
- minLength: 4,
- maxLength: 4000,
- },
+ extensions: extensionsForAccepts(modelCheckAccepts, {
+ method: 'GET',
+ discoverable: true,
+ input: {
+ agent_codename: 'ledger-bot',
+ power_request: 'revenue-vision',
+ mission_brief:
+ 'Find the highest-converting buyer segment this week.',
+ },
+ inputSchema: {
+ type: 'object',
+ required: ['agent_codename', 'power_request', 'mission_brief'],
+ properties: {
+ agent_codename: { type: 'string' },
+ power_request: { type: 'string', enum: ['revenue-vision'] },
+ mission_brief: {
+ type: 'string',
+ minLength: 4,
+ maxLength: 4000,
},
},
},
- },
+ }),
},
{
path: '/api/mcp',
@@ -420,7 +445,7 @@ function handleX402Discovery(req, res) {
'MCP 2025-06-18 Streamable HTTP transport — 3D avatar viewer, glTF model validation/inspection/optimization, and Solana agent data exposed as MCP tools. JSON-RPC 2.0 batch-aware. Currency: USDC.',
mimeType: 'application/json',
accepts: mcpAccepts,
- extensions: { bazaar: bazaarExtension() },
+ extensions: extensionsForAccepts(mcpAccepts, bazaarExtension()),
links: {
openapi: `${origin}/openapi.json`,
docs: `${origin}/docs/mcp`,
@@ -428,16 +453,17 @@ function handleX402Discovery(req, res) {
payment_config: `${origin}/.well-known/x402`,
},
},
- {
- path: '/api/x402/agent-reputation',
- url: `${origin}/api/x402/agent-reputation`,
- method: 'GET',
- description:
- 'Agent Reputation — return a reputation snapshot for a three.ws agent (USDC paid in to its pump-agent tokens, distinct payers, deployed mints, distribution success rate, Solana attestation counts). Built from three.ws\'s proprietary index of pump_agent_payments, pump_distribute_runs, and solana_attestations.',
- mimeType: 'application/json',
- accepts: acceptsForPrice('10000'),
- extensions: {
- bazaar: {
+ (() => {
+ const accepts = acceptsForPrice('10000');
+ return {
+ path: '/api/x402/agent-reputation',
+ url: `${origin}/api/x402/agent-reputation`,
+ method: 'GET',
+ description:
+ 'Agent Reputation — return a reputation snapshot for a three.ws agent (USDC paid in to its pump-agent tokens, distinct payers, deployed mints, distribution success rate, Solana attestation counts). Built from three.ws\'s proprietary index of pump_agent_payments, pump_distribute_runs, and solana_attestations.',
+ mimeType: 'application/json',
+ accepts,
+ extensions: extensionsForAccepts(accepts, {
method: 'GET',
discoverable: true,
input: { agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55' },
@@ -446,19 +472,20 @@ function handleX402Discovery(req, res) {
required: ['agent_id'],
properties: { agent_id: { type: 'string', format: 'uuid' } },
},
- },
- },
- },
- {
- path: '/api/x402/onchain-identity-verify',
- url: `${origin}/api/x402/onchain-identity-verify`,
- method: 'GET',
- description:
- 'On-Chain Identity Verifier — given a three.ws agent_id + CAIP-2 chain + contract/mint, verify ownership from the canonical meta.onchain index and return tx_hash/wallet/deploy time evidence when verified. Trust primitive before paying counterparty agents.',
- mimeType: 'application/json',
- accepts: acceptsForPrice('5000'),
- extensions: {
- bazaar: {
+ }),
+ };
+ })(),
+ (() => {
+ const accepts = acceptsForPrice('5000');
+ return {
+ path: '/api/x402/onchain-identity-verify',
+ url: `${origin}/api/x402/onchain-identity-verify`,
+ method: 'GET',
+ description:
+ 'On-Chain Identity Verifier — given a three.ws agent_id + CAIP-2 chain + contract/mint, verify ownership from the canonical meta.onchain index and return tx_hash/wallet/deploy time evidence when verified. Trust primitive before paying counterparty agents.',
+ mimeType: 'application/json',
+ accepts,
+ extensions: extensionsForAccepts(accepts, {
method: 'GET',
discoverable: true,
input: {
@@ -475,19 +502,20 @@ function handleX402Discovery(req, res) {
contract_or_mint: { type: 'string' },
},
},
- },
- },
- },
- {
- path: '/api/x402/pump-agent-audit',
- url: `${origin}/api/x402/pump-agent-audit`,
- method: 'GET',
- description:
- 'Pump-Agent Audit — full operational audit of a pump.fun agent-payments token: total USDC in, unique payers, distribute/buyback success history, latest error reasons, and risk flags (never_distributed, high_distribute_failure_rate, no_buybacks_run). Backed by three.ws\'s indexed pump_distribute_runs and pump_buyback_runs tables.',
- mimeType: 'application/json',
- accepts: acceptsForPrice('20000'),
- extensions: {
- bazaar: {
+ }),
+ };
+ })(),
+ (() => {
+ const accepts = acceptsForPrice('20000');
+ return {
+ path: '/api/x402/pump-agent-audit',
+ url: `${origin}/api/x402/pump-agent-audit`,
+ method: 'GET',
+ description:
+ 'Pump-Agent Audit — full operational audit of a pump.fun agent-payments token: total USDC in, unique payers, distribute/buyback success history, latest error reasons, and risk flags (never_distributed, high_distribute_failure_rate, no_buybacks_run). Backed by three.ws\'s indexed pump_distribute_runs and pump_buyback_runs tables.',
+ mimeType: 'application/json',
+ accepts,
+ extensions: extensionsForAccepts(accepts, {
method: 'GET',
discoverable: true,
input: { mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi' },
@@ -496,19 +524,20 @@ function handleX402Discovery(req, res) {
required: ['mint'],
properties: { mint: { type: 'string', minLength: 32, maxLength: 44 } },
},
- },
- },
- },
- {
- path: '/api/x402/skill-marketplace',
- url: `${origin}/api/x402/skill-marketplace`,
- method: 'GET',
- description:
- 'Skill Marketplace — list active skill listings with prices across all three.ws agents. Filter by skill name to find the cheapest provider for a given capability. Returns price atomics, chain, currency, trial offer, and time-pass terms.',
- mimeType: 'application/json',
- accepts: acceptsForPrice('1000'),
- extensions: {
- bazaar: {
+ }),
+ };
+ })(),
+ (() => {
+ const accepts = acceptsForPrice('1000');
+ return {
+ path: '/api/x402/skill-marketplace',
+ url: `${origin}/api/x402/skill-marketplace`,
+ method: 'GET',
+ description:
+ 'Skill Marketplace — list active skill listings with prices across all three.ws agents. Filter by skill name to find the cheapest provider for a given capability. Returns price atomics, chain, currency, trial offer, and time-pass terms.',
+ mimeType: 'application/json',
+ accepts,
+ extensions: extensionsForAccepts(accepts, {
method: 'GET',
discoverable: true,
input: { skill: 'inspect_model', limit: 20 },
@@ -519,19 +548,20 @@ function handleX402Discovery(req, res) {
limit: { type: 'integer', minimum: 1, maximum: 200 },
},
},
- },
- },
- },
- {
- path: '/api/x402/symbol-availability',
- url: `${origin}/api/x402/symbol-availability`,
- method: 'GET',
- description:
- 'Symbol Availability — pre-launch ticker collision check against three.ws\'s pump.fun mint index. Returns exact-symbol collisions plus trigram-similar tickers so launch agents can avoid name confusion and aggregator-search dilution.',
- mimeType: 'application/json',
- accepts: acceptsForPrice('1000'),
- extensions: {
- bazaar: {
+ }),
+ };
+ })(),
+ (() => {
+ const accepts = acceptsForPrice('1000');
+ return {
+ path: '/api/x402/symbol-availability',
+ url: `${origin}/api/x402/symbol-availability`,
+ method: 'GET',
+ description:
+ 'Symbol Availability — pre-launch ticker collision check against three.ws\'s pump.fun mint index. Returns exact-symbol collisions plus trigram-similar tickers so launch agents can avoid name confusion and aggregator-search dilution.',
+ mimeType: 'application/json',
+ accepts,
+ extensions: extensionsForAccepts(accepts, {
method: 'GET',
discoverable: true,
input: { ticker: 'HELIO', network: 'mainnet' },
@@ -543,19 +573,20 @@ function handleX402Discovery(req, res) {
network: { type: 'string', enum: ['mainnet', 'devnet'] },
},
},
- },
- },
- },
- {
- path: '/api/x402/mint-to-mesh-batch',
- url: `${origin}/api/x402/mint-to-mesh-batch`,
- method: 'POST',
- description:
- 'Mint-to-Mesh (Batch) — resolve 1–10 Solana SPL mints to themed binary glTF cubes in a single paid call. Per-mint failures report ok:false individually instead of failing the whole batch. Output is base64 GLB bytes for Three.js / Babylon.js / model-viewer.',
- mimeType: 'application/json',
- accepts: acceptsForPrice('50000'),
- extensions: {
- bazaar: {
+ }),
+ };
+ })(),
+ (() => {
+ const accepts = acceptsForPrice('50000');
+ return {
+ path: '/api/x402/mint-to-mesh-batch',
+ url: `${origin}/api/x402/mint-to-mesh-batch`,
+ method: 'POST',
+ description:
+ 'Mint-to-Mesh (Batch) — resolve 1–10 Solana SPL mints to themed binary glTF cubes in a single paid call. Per-mint failures report ok:false individually instead of failing the whole batch. Output is base64 GLB bytes for Three.js / Babylon.js / model-viewer.',
+ mimeType: 'application/json',
+ accepts,
+ extensions: extensionsForAccepts(accepts, {
method: 'POST',
discoverable: true,
input: {
@@ -576,9 +607,9 @@ function handleX402Discovery(req, res) {
},
},
},
- },
- },
- },
+ }),
+ };
+ })(),
],
},
{ 'cache-control': 'public, max-age=300' },
diff --git a/api/x402-status.js b/api/x402-status.js
index 67490b921..fe8f9f667 100644
--- a/api/x402-status.js
+++ b/api/x402-status.js
@@ -8,7 +8,15 @@
import { cors, json, method, wrap } from './_lib/http.js';
import { env } from './_lib/env.js';
-import { paymentRequirements, probeFacilitators, X402_VERSION } from './_lib/x402-spec.js';
+import {
+ EIP2612_EXTENSION_KEY,
+ ERC20_APPROVAL_EXTENSION_KEY,
+ declareEip2612GasSponsoringExtension,
+ paymentRequirements,
+ probeFacilitators,
+ X402_VERSION,
+} from './_lib/x402-spec.js';
+import { declareErc20ApprovalGasSponsoringExtension } from '@x402/extensions';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -18,6 +26,21 @@ export default wrap(async (req, res) => {
const facilitators = await probeFacilitators();
const ok = facilitators.every((f) => f.ok);
+ // Surface what we advertise in 402 challenges so operators can confirm at a
+ // glance: which accept entries opt into the Permit2 transfer method, and
+ // whether each facilitator's /supported probe actually advertises the
+ // `eip2612GasSponsoring` extension we declare. A green `ok` here plus
+ // `extensions.eip2612GasSponsoring.facilitatorsSupporting` matching the
+ // EVM facilitator set means the gasless Permit2 onboarding path is live.
+ const permit2Accepts = accepts.filter((a) => a?.extra?.assetTransferMethod === 'permit2');
+ const sponsorshipDeclared = permit2Accepts.length > 0;
+ const eip2612FacilitatorsSupporting = facilitators
+ .filter((f) => f.supportsEip2612GasSponsoring)
+ .map((f) => f.network);
+ const erc20FacilitatorsSupporting = facilitators
+ .filter((f) => f.supportsErc20ApprovalGasSponsoring)
+ .map((f) => f.network);
+
return json(
res,
ok ? 200 : 503,
@@ -26,6 +49,24 @@ export default wrap(async (req, res) => {
x402Version: X402_VERSION,
accepts,
facilitators,
+ extensions: {
+ [EIP2612_EXTENSION_KEY]: {
+ declared: sponsorshipDeclared,
+ declaration: sponsorshipDeclared
+ ? declareEip2612GasSponsoringExtension()[EIP2612_EXTENSION_KEY]
+ : null,
+ appliesTo: permit2Accepts.map((a) => a.network),
+ facilitatorsSupporting: eip2612FacilitatorsSupporting,
+ },
+ [ERC20_APPROVAL_EXTENSION_KEY]: {
+ declared: sponsorshipDeclared,
+ declaration: sponsorshipDeclared
+ ? declareErc20ApprovalGasSponsoringExtension()[ERC20_APPROVAL_EXTENSION_KEY]
+ : null,
+ appliesTo: permit2Accepts.map((a) => a.network),
+ facilitatorsSupporting: erc20FacilitatorsSupporting,
+ },
+ },
env: {
X402_PAY_TO_SOLANA: env.X402_PAY_TO_SOLANA || null,
X402_PAY_TO_BASE: env.X402_PAY_TO_BASE || null,
diff --git a/docs/club/PLAN.md b/docs/club/PLAN.md
new file mode 100644
index 000000000..132712b30
--- /dev/null
+++ b/docs/club/PLAN.md
@@ -0,0 +1,242 @@
+# Pole Club — Build-Out Plan
+
+The `/club` page at [pages/club.html](../../pages/club.html) and
+[src/club.js](../../src/club.js) currently runs on Three.js primitives:
+cylinders for poles, circles for stages, neon rings, four clones of
+`/avatars/default.glb`, and the generic dance clips already in
+`/animations/manifest.json`. The paid x402 endpoint
+[api/x402/dance-tip.js](../../api/x402/dance-tip.js) is wired and
+indexed by the bazaar; tipping triggers a real settlement, returns a
+ticket, and a stand-in dancer walks the rig from "backstage" to the
+pole.
+
+This plan tracks what's required to turn that placeholder rig into a
+fully wired, professional 3D venue with distinct dancers, real pole
+choreography, club lighting + audio, server-side tip persistence, and
+per-dancer leaderboards/payouts. No primitives shipped to prod; no
+synthesized art; no `setTimeout`-faked timing.
+
+Each task lives as a self-contained prompt under [prompts/club/](../../prompts/club/).
+Run them in any order — each restates its own context.
+
+## Hard rails (from [CLAUDE.md](../../CLAUDE.md))
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs.
+- Real APIs, real animations, real GLBs, real audio.
+- Errors handled at boundaries only.
+- Done = wired in the UI, exercised in a real browser, no console
+ errors, `npm test` green, `git diff` reviewed.
+- Push to **both** remotes (`threeD` → `nirholas/3D-Agent`,
+ `threews` → `nirholas/three.ws`) only when the user says push.
+
+## Scope — the venue
+
+| Element | Today | Target |
+|---|---|---|
+| Walls / floor / ceiling | `PlaneGeometry` + `CircleGeometry` + `MeshStandardMaterial` | Authored `club-venue.glb` with PBR materials, baked AO, real architectural detail (girders, ceiling beams, ducts, alcoves) |
+| Bar | A single flat plane | A bar GLB with bottles, glassware, neon backsplash, animated bartender or static idle figure |
+| Dance floor | Emissive circle | Lit panel floor (animated emissive tiles), reflective varnish, scuff/wear baked in |
+| Crowd | None | Low-poly cheering crowd silhouettes lining the perimeter (instanced) + occasional VIP figures in alcoves |
+| Backstage | Invisible offstage point | A visible curtain/door GLB the dancer emerges from |
+| Skybox | Solid `#07050b` | HDRI of a dim club ceiling with disco-ball highlight + low key red/magenta cast |
+
+→ [prompts/club/01-venue-glb-and-environment.md](../../prompts/club/01-venue-glb-and-environment.md)
+
+## Scope — the dancers
+
+Each of the four pole slots needs a **distinct authored dancer GLB**,
+not a cloned default avatar. Outfits, hair, body shape, skin tone, and
+accent palette must read differently across slots. All four share the
+canonical Avaturn skeleton so the existing animation JSON clips drive
+them without retargeting at runtime.
+
+- `public/club/dancers/dancer-01.glb` — neon pink palette
+- `public/club/dancers/dancer-02.glb` — cyan palette
+- `public/club/dancers/dancer-03.glb` — amber palette
+- `public/club/dancers/dancer-04.glb` — violet palette
+
+Bound at runtime via a small registry that maps slot → GLB URL +
+display name + bio + tip wallet.
+
+→ [prompts/club/02-dancer-glbs.md](../../prompts/club/02-dancer-glbs.md)
+
+## Scope — the pole rig + pole choreography
+
+The cylinder pole prop becomes a textured pole GLB with a flared base
+and a ceiling-mounted top. A small spotlight rig hangs off the ceiling
+mount.
+
+The current dance clips (`rumba`, `silly`, `thriller`, `capoeira`,
+`hiphop`) aren't pole choreography — they're free-floor Mixamo clips.
+Add pole-specific clips:
+
+- `pole-walk-on` — entry routine from backstage
+- `pole-spin` — single revolution, looping
+- `pole-climb` — climb to mid-pole
+- `pole-invert` — upside-down hang
+- `pole-floorwork` — return to ground crawl
+- `pole-bow` — exit bow
+
+Each clip authored from Mixamo or freely-licensed mocap, retargeted by
+[scripts/build-animations.mjs](../../scripts/build-animations.mjs) (or
+its successor), output to `public/animations/clips/pole-*.json`,
+registered in `public/animations/manifest.json`, exposed via the
+`dance-tip` endpoint's `STYLES` map.
+
+The `dance-tip` endpoint adds new style keys (`spin`, `climb`,
+`invert`, `floor`, `combo`) that map to clip sequences played back to
+back during the performance window.
+
+→ [prompts/club/03-pole-rig-and-pole-animations.md](../../prompts/club/03-pole-rig-and-pole-animations.md)
+
+## Scope — lighting + post-processing
+
+- Volumetric spotlights with visible cones (god-rays through fog
+ density volume) — one per pole, color from `POLE_COLORS`.
+- A real mirror ball with cube-camera reflections that scatter dots
+ across the floor and walls.
+- RGB strip lights along the bar edge + ceiling rails (instanced
+ `LineSegments` with bloom).
+- Animated rim lights that pulse on the beat of the active dancer's
+ music track.
+- Bloom + vignette + filmic tone mapping via `EffectComposer` from
+ `three/addons/postprocessing/*`. Optional subtle chromatic
+ aberration during high-energy clips (`thriller`, `pole-spin`).
+- Real fog volume (the existing `Fog` is fine as a baseline) tuned
+ for visibility through god-rays without obscuring dancers.
+
+→ [prompts/club/04-lighting-and-postfx.md](../../prompts/club/04-lighting-and-postfx.md)
+
+## Scope — audio + music
+
+- Background club ambience (crowd murmur, low rumble, occasional
+ glass clinks) looping at –24 LUFS via Web Audio API.
+- Per-style music tracks under `public/club/audio/<style>.mp3` (or
+ `.ogg`) — short loopable cuts (~30-60s) licensed CC-BY or
+ public-domain. Each `STYLE` in `api/x402/dance-tip.js` adds a
+ `track` field pointing at the audio file.
+- Crossfade ambience ↓ + style track ↑ when a dancer starts
+ performing. Reverse on exit.
+- Master mute / volume controls in the right panel.
+- Optional: WebAudio analyser feeding a beat-detection pulse into the
+ rim lighting in prompt 04.
+
+→ [prompts/club/05-audio-and-music.md](../../prompts/club/05-audio-and-music.md)
+
+## Scope — camera + interaction
+
+- Free orbit (current) as default.
+- Click a pole-card → camera dollies to a VIP shot of that pole
+ (front + low + slight tilt up). Escape returns to free orbit.
+- `1` / `2` / `3` / `4` keys jump to each pole's VIP shot.
+- `0` key returns to overhead "house" cam (top-down, gentle yaw).
+- Smooth interpolated transitions, no teleports.
+- Touch controls: tap a pole-card on mobile, drag to orbit, pinch to
+ zoom.
+
+→ [prompts/club/06-camera-and-controls.md](../../prompts/club/06-camera-and-controls.md)
+
+## Scope — server-backed live tip feed
+
+Today the feed lives in-memory in the browser tab — refresh wipes it,
+other visitors can't see your tips. Persist:
+
+- Schema migration: `club_tips (id uuid pk, ticket_id text, dancer
+ text, dance text, label text, payer text, network text,
+ amount_atomics numeric, asset text, started_at timestamptz,
+ ends_at timestamptz, created_at timestamptz default now())`.
+- The `dance-tip` paid endpoint, on a settled payment, inserts a row.
+- New endpoint `GET /api/club/tips?limit=20` returns recent rows.
+- New SSE endpoint `GET /api/club/tips/stream` pushes new rows live.
+- `/club` page renders the SSE stream into the right panel and
+ preloads the last 20 on boot.
+
+→ [prompts/club/07-tip-feed-realtime.md](../../prompts/club/07-tip-feed-realtime.md)
+
+## Scope — per-dancer leaderboard + payout sweep
+
+- Schema: `club_dancer_wallets (dancer text pk, evm_address text,
+ solana_address text, label text, bio text)`.
+- Aggregate view: `club_leaderboard` materialized view computing
+ per-dancer tip count and atomic sum for `last_hour`, `last_day`,
+ `all_time`.
+- New endpoint `GET /api/club/leaderboard` returns it.
+- Right-panel leaderboard widget rendering live ranks.
+- Cron `api/cron/[name].js` handler `club-payouts`: every N minutes,
+ sums unpaid tips per dancer, sends payout via existing Solana /
+ EVM payout rails (see `api/payments/*`), records the payout
+ signature, marks tips paid.
+
+→ [prompts/club/08-leaderboard-and-payouts.md](../../prompts/club/08-leaderboard-and-payouts.md)
+
+## Scope — mobile + low-perf path
+
+- Detect low-perf devices via `navigator.deviceMemory` / `hardwareConcurrency` / pointer type.
+- Drop shadow map size, disable bloom + cube-cam reflections, halve
+ pixel ratio, skip the mirror ball animation, switch fog to linear.
+- Single-pole VIP cam locks become the default layout on screens
+ <768px (no orbit drag).
+- Test: real iPhone Safari + Pixel Chrome. Frame rate ≥30fps locked.
+
+→ [prompts/club/09-mobile-and-perf.md](../../prompts/club/09-mobile-and-perf.md)
+
+## Scope — end-to-end tests + verification
+
+- Unit: `tests/api/club-tip.test.js` covers `dance-tip` handler — all
+ styles, all dancers, error paths.
+- Unit: `tests/api/club-feed.test.js` covers `/api/club/tips` +
+ SSE handshake.
+- Unit: `tests/club-leaderboard.test.js` covers the materialized
+ view query and payout sweep math.
+- Playwright smoke: `tests/e2e/club.spec.js` boots `npm run dev`,
+ visits `/club`, stubs the x402 settle (network intercept), asserts
+ a dancer walks to the pole and the named clip plays.
+- Manual: tip from a real Phantom wallet on Solana mainnet, watch
+ the on-chain confirmation, see the dancer perform.
+
+→ [prompts/club/10-e2e-tests-and-verification.md](../../prompts/club/10-e2e-tests-and-verification.md)
+
+## Asset pipeline
+
+GLBs (venue, dancers, props) authored in Blender, exported with Draco
+mesh compression and KTX2 texture compression (see
+[prompts/finish-features/add-mesh-compression-deps.md](../../prompts/finish-features/add-mesh-compression-deps.md)
+for the loader wiring). All animation clips bake from Mixamo FBX
+through the existing
+[scripts/build-animations.mjs](../../scripts/build-animations.mjs)
+retarget pass; output JSON is committed under
+`public/animations/clips/`.
+
+Audio cuts trimmed in Audacity, encoded to OGG Vorbis q4 and MP3 192k
+side-by-side; `<audio>` element picks the supported one. License
+provenance recorded in `public/club/audio/LICENSES.md`.
+
+## Integration map
+
+| New thing | Touches |
+|---|---|
+| Venue GLB | [src/club.js](../../src/club.js) bootstrap + scene replacement |
+| Dancer GLBs | [src/club.js](../../src/club.js) `PoleStation.attachAvatar` + new dancer registry |
+| Pole rig GLB | [src/club.js](../../src/club.js) pole primitive replacement |
+| Pole clips | [public/animations/manifest.json](../../public/animations/manifest.json), `STYLES` in [api/x402/dance-tip.js](../../api/x402/dance-tip.js) |
+| Lighting + postfx | [src/club.js](../../src/club.js) renderer + light setup |
+| Audio | New `src/club-audio.js`, right-panel UI in [pages/club.html](../../pages/club.html) |
+| Camera | New `src/club-camera.js`, [src/club.js](../../src/club.js) animate loop |
+| Tip feed (SSE) | New `api/club/tips.js`, [api/x402/dance-tip.js](../../api/x402/dance-tip.js) `handler`, [src/club.js](../../src/club.js) feed render |
+| Leaderboard + payouts | New `api/club/leaderboard.js`, `api/cron/[name].js` new branch, schema migration |
+| Tests | New `tests/api/club-*.test.js`, `tests/e2e/club.spec.js` |
+
+## Done
+
+The full feature is shippable when:
+
+1. Every prompt under `prompts/club/` is closed.
+2. `/club` loads in <3s on broadband desktop, <6s on 4G mobile.
+3. A real Phantom wallet on mainnet can tip a dancer end-to-end with
+ no console errors, the dancer performs the chosen routine with
+ pole choreography, the tip lands in the live feed across all open
+ browser tabs, the leaderboard updates, and the dancer's wallet
+ receives the payout within the cron window.
+4. `npm test` green.
+5. Playwright smoke green.
+6. Both remotes pushed.
diff --git a/docs/x402-offer-receipt/00-plan.md b/docs/x402-offer-receipt/00-plan.md
new file mode 100644
index 000000000..582f6ddcb
--- /dev/null
+++ b/docs/x402-offer-receipt/00-plan.md
@@ -0,0 +1,71 @@
+# x402 Signed Offers & Receipts — Integration Plan
+
+Wire the x402 Offer & Receipt extension into every paid endpoint in this repo so every `402` response carries one signed offer per accepted network, and every `200` response carries one signed receipt — without changing any handler's business logic.
+
+## Why this exists (one paragraph)
+
+The x402 Offer & Receipt extension produces portable, cryptographically signed artifacts that prove (a) the server committed to specific payment terms, and (b) the client received the service it paid for. Today the upside for `$0.001`-priced endpoints is mostly positioning: being early on a spec that reputation aggregators may eventually crawl. The cost is modest and the surface is contained, so this plan ships it cleanly with a single signer module and two hook points in the existing `paidEndpoint` wrapper.
+
+## Locked-in decisions
+
+These are decided up front so prompts don't re-litigate them. If a prompt encounters a reason to change one of these, stop and surface it before deviating.
+
+| Decision | Value | Reason |
+|---|---|---|
+| Signing format | **EIP-712** (`did:pkh`) | secp256k1 only is fine — the *receipt signing key* is independent of how payers pay. No DID document to host. |
+| Signing key env var | `X402_RECEIPT_SIGNING_KEY` | Hex-encoded 32-byte private key, `0x`-prefixed. **Must be a dedicated key**, not `X402_PAY_TO_*`. |
+| KID format | `did:pkh:eip155:1:${signerAddress}#key-1` | Chain `1` (Ethereum mainnet) is conventional for `did:pkh` identity. The signing identity is independent of the payment chain. |
+| Extension scope | **Global** in [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) | All 9 paid endpoints are symmetric; one toggle beats 9 per-file edits. |
+| Extension placement on 402 body | Sibling under top-level `extensions["offer-receipt"]`, **not** nested under `bazaar` | The agentic.market validator mirrors `@x402/extensions/bazaar` exactly; nesting risks failing their schema check. |
+| Receipt placement on `200` | Inside `x-payment-response` header payload's `extensions["offer-receipt"]` | Matches the spec's wire format — clients call `extractReceiptFromResponse` on the response. |
+| `includeTxHash` default | `false` | Privacy-preserving default; payer address is already in the receipt. |
+| Offer `validUntil` | `now + 60s` | Matches existing `maxTimeoutSeconds: 60` in every accept entry. |
+| BSC `direct` scheme handling | Sign the offer with `offerType: 'direct'` | The field is a free-form string per spec. Third-party verifiers expecting `'exact'` won't accept it, which is fine — BSC users aren't the target audience for portable receipts yet. |
+| Signer module location | [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js) (new) | Sits next to `x402-paid-endpoint.js` and `x402-spec.js` so the hook points import it cleanly. |
+| DID document hosting | **Out of scope for v1** | Not required for EIP-712 (`did:pkh` is self-describing). Add later if a verifier requires it. |
+
+## Files touched
+
+- [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js) — **new**, exports a singleton issuer + offer/receipt sign helpers.
+- [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js) — wire offers into `build402Body`, wire receipts into `encodePaymentResponseHeader`.
+- [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) — pass payer/network through to settle so the receipt payload has what it needs.
+- [api/_lib/env.js](../../api/_lib/env.js) — surface `X402_RECEIPT_SIGNING_KEY` as a typed env field.
+- [.env.example](../../.env.example) — document the new env var.
+- [package.json](../../package.json) — add `@x402/extensions` and (if missing) `viem`.
+- All 9 endpoints in [api/x402/](../../api/x402/) — **no edits needed**. The global wrapper handles it.
+- [scripts/verify-x402-receipts.js](../../scripts/verify-x402-receipts.js) — **new**, smoke test that hits a paid endpoint and verifies the signed offer + receipt round-trip.
+
+## Prompt sequence
+
+Each prompt is self-contained and assumes only that prior prompts in the sequence completed successfully. Run them in order.
+
+1. [01-foundation.md](01-foundation.md) — install deps, add env var, create the signer module.
+2. [02-offer-signing.md](02-offer-signing.md) — wire offer signing into the `402` response path.
+3. [03-receipt-signing.md](03-receipt-signing.md) — wire receipt signing into the `200` response path.
+4. [04-bazaar-declaration.md](04-bazaar-declaration.md) — declare the extension in the discovery envelope so bazaar crawlers know we sign.
+5. [05-verification-script.md](05-verification-script.md) — build the end-to-end smoke test that proves offers and receipts verify.
+6. [06-completionist-and-push.md](06-completionist-and-push.md) — final audit pass and push to both remotes.
+
+## Definition of done (whole feature)
+
+All of these must be verifiable, not asserted:
+
+- [ ] `X402_RECEIPT_SIGNING_KEY` is set in `.env.example` (placeholder), `.env` (real value), and configured in Vercel for `production` + `preview`.
+- [ ] `npm test` passes.
+- [ ] Hitting any paid endpoint without a payment header returns `402` with `body.extensions["offer-receipt"].signedOffers[]` containing one entry per accepted network.
+- [ ] Hitting any paid endpoint with a valid payment returns `200` with `x-payment-response` decoding to an envelope whose `extensions["offer-receipt"].signedReceipt` verifies under the signer's recovered address.
+- [ ] The verification script at `scripts/verify-x402-receipts.js` runs against a deployed (or `vercel dev`) instance, verifies both artifacts, and exits `0`.
+- [ ] No handler in `api/x402/*.js` was modified — the wiring is purely in the shared lib.
+- [ ] Completionist agent run against the diff returns clean.
+- [ ] Pushed to **both** `origin` and `threews` remotes.
+
+## Risks & caveats
+
+- **Key compromise.** `X402_RECEIPT_SIGNING_KEY` is the single point of failure. If it leaks, an attacker can forge offers and receipts in your name. Provision it via Vercel encrypted env, never commit it, and rotate by updating env + bumping the KID's `#key-1` → `#key-2`.
+- **Settle-failure ordering.** Receipts must only be signed *after* `settlePayment` succeeds, never before. The wiring in prompt 03 must enforce this.
+- **`vercel.json` collapse.** Recent commit `36dfec9a` collapsed functions config to a single wildcard. The new signer module is a `_lib` helper, not a function entry, so no `vercel.json` change is needed. Verify this assumption holds before claiming done.
+- **`bazaar` schema strictness.** Per [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js#L457), the bazaar extension must mirror `@x402/extensions/bazaar` exactly. The new `offer-receipt` extension is a **sibling** to `bazaar`, not nested under it. Do not modify `bazaarExtension()` or `buildBazaarSchema()`.
+
+## Rollback
+
+Single env-var toggle controls the feature: if `X402_RECEIPT_SIGNING_KEY` is unset, the signer module exports a no-op issuer, the offer/receipt arrays are omitted from responses, and the feature degrades gracefully to current behavior. To roll back: unset the env var in Vercel and redeploy. Code does not need to be reverted.
diff --git a/docs/x402-offer-receipt/01-foundation.md b/docs/x402-offer-receipt/01-foundation.md
new file mode 100644
index 000000000..6504cf2d5
--- /dev/null
+++ b/docs/x402-offer-receipt/01-foundation.md
@@ -0,0 +1,95 @@
+# Prompt 01 — Foundation: deps, env, signer module
+
+You are landing the **foundation** for the x402 Signed Offers & Receipts feature. See [00-plan.md](00-plan.md) for the locked-in decisions — do not re-litigate them.
+
+## Project rules (must follow)
+
+From [CLAUDE.md](../../CLAUDE.md):
+
+- **No mocks. No fake data. No placeholders.** Real APIs, real keys.
+- **No `// TODO`, no stub functions, no commented-out code.** If you write it, finish it.
+- **No `throw new Error("not implemented")`.**
+- Errors handled at boundaries (network, user input). Internal code trusts itself.
+
+## Inputs
+
+- Locked decisions in [00-plan.md](00-plan.md):
+ - Signing format: **EIP-712** (`did:pkh:eip155:1:${address}#key-1`).
+ - Env var: `X402_RECEIPT_SIGNING_KEY` (hex private key, `0x`-prefixed, 32 bytes).
+ - Module path: `api/_lib/x402-offer-receipt.js`.
+ - When env is unset, exports a **no-op issuer** that returns `null` for sign calls. This is the rollback toggle.
+- Existing env loader: [api/_lib/env.js](../../api/_lib/env.js). Add the new field there using whatever pattern the existing `X402_PAY_TO_*` fields use.
+
+## Task
+
+### 1. Install dependencies
+
+```bash
+npm install @x402/extensions @x402/core viem
+```
+
+`viem` may already be in [package.json](../../package.json). If so, ensure the installed version is `>=2.0.0` (required by `@x402/extensions`). Do not downgrade other packages.
+
+### 2. Add the env var
+
+- In [api/_lib/env.js](../../api/_lib/env.js), add `X402_RECEIPT_SIGNING_KEY` next to the existing `X402_PAY_TO_*` fields. Do not assert it as required — the no-op fallback depends on the field being optional.
+- In [.env.example](../../.env.example), add a documented block. The placeholder value must clearly be a placeholder (e.g. `0xREPLACE_WITH_DEDICATED_SIGNING_KEY_HEX_64_CHARS`) and the comment must say "dedicated signing key, NOT a wallet that holds funds" and "rotate by changing the value and bumping `#key-1` → `#key-2` in code if needed."
+
+### 3. Create the signer module
+
+Create [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js) exporting:
+
+```js
+// One singleton issuer per process. Resolves to the EIP-712 issuer when
+// X402_RECEIPT_SIGNING_KEY is set, otherwise to a no-op that returns null.
+// The no-op is the feature flag — unset the env var in Vercel to roll back
+// without redeploying code.
+export const issuer; // { kid, signerAddress, sign } | null
+
+// Sign one offer per accept entry on a 402 response. Returns the array of
+// signed offers in the wire shape consumed by extractOffersFromPaymentRequired
+// on the client side. Returns [] when the issuer is null (feature disabled).
+export async function signOffersForAccepts({ accepts, resourceUrl, validitySeconds });
+
+// Sign one receipt for a settled 200 response. Returns the signed receipt
+// in the wire shape consumed by extractReceiptFromResponse on the client
+// side. Returns null when the issuer is null (feature disabled) or when
+// the inputs are insufficient.
+export async function signReceipt({ resourceUrl, payer, network, txHash, includeTxHash });
+```
+
+Implementation requirements:
+
+- Import `createEIP712OfferReceiptIssuer` from `@x402/extensions/offer-receipt` and `privateKeyToAccount` from `viem/accounts`.
+- `kid` is exactly `did:pkh:eip155:1:${signerAddress}#key-1`. Lowercase the address per CAIP-10.
+- `validitySeconds` defaults to `60` if omitted (matches `maxTimeoutSeconds`).
+- `includeTxHash` defaults to `false`.
+- `validUntil` is `Math.floor(Date.now() / 1000) + validitySeconds`.
+- The `offerType` field on each signed offer comes from the accept's `scheme` field (so BSC's `'direct'` flows through unchanged).
+- If `X402_RECEIPT_SIGNING_KEY` is malformed (wrong length, not hex), throw at module-load time with a clear `x402_receipt_signing_key_invalid` error. Don't fail silently — a malformed key means the operator intended to enable signing but configured it wrong.
+- If `signReceipt` is called with `payer == null` or `network == null`, return `null` and do not throw. That's a normal condition for endpoints whose settlement skipped the facilitator (e.g. BSC `direct`); we want to keep the response shape clean.
+
+### 4. Smoke check
+
+After writing the module:
+
+```bash
+node --input-type=module -e "import { issuer, signOffersForAccepts, signReceipt } from './api/_lib/x402-offer-receipt.js'; console.log('issuer:', issuer ? issuer.signerAddress : 'no-op'); console.log('offers (no-op safe):', await signOffersForAccepts({ accepts: [], resourceUrl: 'https://example.com/x' })); console.log('receipt (no-op safe):', await signReceipt({ resourceUrl: 'https://example.com/x', payer: null, network: null }));"
+```
+
+With `X402_RECEIPT_SIGNING_KEY` unset, this should print `issuer: no-op`, `offers: []`, `receipt: null`. With a real key set, `issuer` should print the recovered address.
+
+## Definition of done
+
+- [ ] `@x402/extensions`, `@x402/core`, and `viem` (>=2) are in `package.json` `dependencies` and `npm install` succeeds.
+- [ ] `api/_lib/env.js` exposes `X402_RECEIPT_SIGNING_KEY`.
+- [ ] `.env.example` documents the new var with a clear placeholder and the rotation guidance.
+- [ ] `api/_lib/x402-offer-receipt.js` exists and exports `issuer`, `signOffersForAccepts`, `signReceipt`.
+- [ ] The smoke check above works in both modes (env set, env unset).
+- [ ] `npm test` still passes.
+- [ ] `git diff` reviewed by you. No `TODO`, no stubs, no commented-out code.
+
+## Stop conditions
+
+- If `@x402/extensions` does not expose `createEIP712OfferReceiptIssuer` at the documented path, surface this **before** writing anything else — the spec or package layout may have changed since the planning doc was written.
+- If `viem` cannot be upgraded to `>=2` without breaking other packages, surface this with the conflict before proceeding.
diff --git a/docs/x402-offer-receipt/02-offer-signing.md b/docs/x402-offer-receipt/02-offer-signing.md
new file mode 100644
index 000000000..6c84a0032
--- /dev/null
+++ b/docs/x402-offer-receipt/02-offer-signing.md
@@ -0,0 +1,127 @@
+# Prompt 02 — Wire offer signing into the 402 response path
+
+You are wiring **offer signing** into the `402 Payment Required` flow. The signer module from [01-foundation.md](01-foundation.md) is already in place at [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js). Locked-in decisions live in [00-plan.md](00-plan.md).
+
+## Project rules (must follow)
+
+From [CLAUDE.md](../../CLAUDE.md):
+
+- **No fake data, no placeholders, no stubs.**
+- **Errors handled at boundaries only.**
+
+Additional rule for this task:
+
+- **Do not modify `bazaarExtension()` or `buildBazaarSchema()`** in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js). The bazaar crawler validator mirrors the `@x402/extensions/bazaar` shape exactly — any deviation breaks discovery. The new `offer-receipt` extension is a **sibling** to `bazaar`, not nested under it.
+
+## Inputs
+
+- Hook point: [api/_lib/x402-spec.js:610](../../api/_lib/x402-spec.js#L610) — the `build402Body` function.
+- Signer surface (already built in prompt 01):
+ ```js
+ import { signOffersForAccepts } from './x402-offer-receipt.js';
+ const signedOffers = await signOffersForAccepts({
+ accepts: requirements, // array of accept entries (the 'requirements')
+ resourceUrl, // string
+ validitySeconds: 60, // matches maxTimeoutSeconds
+ });
+ // Returns [] when feature is disabled (env unset).
+ ```
+- Wire shape required by the spec — what the client's `extractOffersFromPaymentRequired` expects:
+ ```json
+ {
+ "extensions": {
+ "bazaar": { ... existing ... },
+ "offer-receipt": {
+ "signedOffers": [ { kid, signature, payload: { resourceUrl, offerType, network, amount, payTo, validUntil } }, ... ]
+ }
+ }
+ }
+ ```
+
+## Task
+
+### 1. Make `build402Body` async-friendly
+
+`build402Body` is currently synchronous. The offer signer is async. The cleanest change:
+
+- Convert `build402Body` to `async function build402Body(...)`.
+- Convert `send402` to `async function send402(res, opts = {})` and `await build402Body(opts)`.
+- Update **every** caller of `send402` to `await` it. Audit with:
+ ```bash
+ grep -rn "send402(" api/
+ ```
+ Every call site must be inside an `async` function and prefixed with `await`. There are calls in [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) (already async) and possibly others — verify exhaustively.
+
+### 2. Attach signed offers to the 402 body
+
+Inside `build402Body`, after the existing fields are assembled, call `signOffersForAccepts` with the final `accepts` array and `resourceUrl`. Merge the result into `extensions`:
+
+```js
+const signedOffers = await signOffersForAccepts({
+ accepts: Array.isArray(accepts) ? accepts : [accepts],
+ resourceUrl,
+ validitySeconds: 60,
+});
+
+return {
+ x402Version: X402_VERSION,
+ error,
+ resource: { url: resourceUrl, description, mimeType },
+ accepts: Array.isArray(accepts) ? accepts : [accepts],
+ extensions: signedOffers.length
+ ? { bazaar, 'offer-receipt': { signedOffers } }
+ : { bazaar },
+};
+```
+
+When the feature is disabled (env unset), `signedOffers` is `[]` and the `offer-receipt` key is omitted entirely. This keeps the 402 body byte-identical to current behaviour for the disabled case.
+
+### 3. Mirror into the `PAYMENT-REQUIRED` header
+
+The current code at [api/_lib/x402-spec.js:634](../../api/_lib/x402-spec.js#L634) base64-encodes the 402 body into the `PAYMENT-REQUIRED` header. After your changes that body now includes the signed offers, so the header automatically carries them — confirm this by inspection. **Do not** add a separate header.
+
+### 4. Sanity test
+
+Start the dev server and curl a paid endpoint without a payment header:
+
+```bash
+npm run dev &
+sleep 3
+curl -s -i http://localhost:3000/api/x402/dance-tip?dancer=1\&dance=rumba | tee /tmp/402.txt
+```
+
+With `X402_RECEIPT_SIGNING_KEY` set, the response body should include `extensions["offer-receipt"].signedOffers` with one entry per accept. With it unset, the body should be **byte-identical** to current behaviour (no `offer-receipt` key). Verify both modes.
+
+Then verify a signed offer cryptographically:
+
+```bash
+node --input-type=module -e "
+import { decodeSignedOffers, verifyOfferSignatureEIP712 } from '@x402/extensions/offer-receipt';
+import fs from 'fs';
+const raw = fs.readFileSync('/tmp/402.txt', 'utf8').split('\r\n\r\n')[1];
+const body = JSON.parse(raw);
+const offers = body.extensions['offer-receipt'].signedOffers;
+const decoded = decodeSignedOffers(offers);
+for (const d of decoded) {
+ const ok = await verifyOfferSignatureEIP712(d.signedOffer);
+ console.log(d.signedOffer.payload.network, '->', ok ? 'VERIFIED' : 'FAILED');
+}
+"
+```
+
+Every accept-entry network should print `VERIFIED`.
+
+## Definition of done
+
+- [ ] `build402Body` and `send402` are `async`; all call sites updated to `await`.
+- [ ] 402 responses include `extensions["offer-receipt"].signedOffers` when env is set, and omit it cleanly when env is unset.
+- [ ] Each signed offer verifies under `verifyOfferSignatureEIP712`.
+- [ ] `bazaarExtension()` and `buildBazaarSchema()` are **unchanged**.
+- [ ] No paid endpoint handler in `api/x402/*.js` was modified.
+- [ ] `npm test` still passes.
+- [ ] `git diff` reviewed.
+
+## Stop conditions
+
+- If you discover a `send402` caller in a non-async function that cannot trivially become async, surface the conflict instead of plumbing a `.then()` shim — async-to-callback bridging in this codebase has caused settlement-ordering bugs before.
+- If the bazaar crawler validator schema test fails after the change, the extension shape leaked into `bazaar` — restore the sibling structure.
diff --git a/docs/x402-offer-receipt/03-receipt-signing.md b/docs/x402-offer-receipt/03-receipt-signing.md
new file mode 100644
index 000000000..bdf5929e7
--- /dev/null
+++ b/docs/x402-offer-receipt/03-receipt-signing.md
@@ -0,0 +1,145 @@
+# Prompt 03 — Wire receipt signing into the 200 response path
+
+You are wiring **receipt signing** into the post-settlement `200` flow. Prompts [01](01-foundation.md) and [02](02-offer-signing.md) are complete: the signer module exists and offer signing on `402` works end-to-end. Locked-in decisions live in [00-plan.md](00-plan.md).
+
+## Project rules (must follow)
+
+From [CLAUDE.md](../../CLAUDE.md):
+
+- **No fake data, no placeholders, no stubs.**
+- **Errors handled at boundaries only.**
+
+Additional rules for this task:
+
+- **Receipts are signed only AFTER `settlePayment` succeeds.** A receipt signed before settle would attest to delivery for a payment that may not have cleared. The wiring must enforce this ordering — there is no acceptable shortcut.
+- **A failed receipt sign must not fail the response.** The user paid and the work ran; we deliver the result regardless. Log the error and continue with an unsigned response.
+
+## Inputs
+
+- Receipt-signing hook point: [api/_lib/x402-paid-endpoint.js:199](../../api/_lib/x402-paid-endpoint.js#L199), where `x-payment-response` is set from `encodePaymentResponseHeader(settled)`.
+- All inputs the receipt needs are already in scope at that point:
+ - `resourceUrl` — defined at line 143.
+ - `verified.payer` — from the `verifyPayment` step.
+ - `verified.requirement.network` — the accept entry that matched.
+ - `settled.txHash` (optional) — from `settlePayment` return value. Field name is whatever `settlePayment` actually returns; verify in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js).
+- Signer surface (already built in prompt 01):
+ ```js
+ import { signReceipt } from './x402-offer-receipt.js';
+ const signedReceipt = await signReceipt({
+ resourceUrl,
+ payer: verified.payer,
+ network: verified.requirement.network,
+ txHash: settled.txHash,
+ includeTxHash: false, // privacy-preserving default
+ });
+ // Returns null when feature is disabled or inputs insufficient.
+ ```
+- Wire shape required — what the client's `extractReceiptFromResponse` expects on `x-payment-response`:
+ ```json
+ {
+ ... existing settle response ...,
+ "extensions": {
+ "offer-receipt": {
+ "signedReceipt": { kid, signature, payload: { resourceUrl, payer, network, issuedAt, txHash? } }
+ }
+ }
+ }
+ ```
+
+## Task
+
+### 1. Locate `encodePaymentResponseHeader`
+
+It's at [api/_lib/x402-spec.js:436](../../api/_lib/x402-spec.js#L436). Read its current shape — it takes a `settleResult` object and returns a base64-JSON string.
+
+You have two integration options. Pick **Option A** unless you find a concrete reason to prefer B.
+
+**Option A (recommended): attach the receipt at the call site.**
+
+In [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js), after the existing `settled = await settlePayment(...)` block (around line 197), sign the receipt and merge it into the envelope before encoding. Change `encodePaymentResponseHeader` to accept an envelope rather than a raw `settleResult`, or add a sibling helper. Keep the change tight — do not refactor unrelated code.
+
+**Option B: thread the signer through `encodePaymentResponseHeader`.**
+
+Make `encodePaymentResponseHeader` async and take `{ settleResult, signedReceipt }`. Update all callers. This is fine but slightly more churn.
+
+### 2. Implement the wiring (Option A example shape)
+
+```js
+let settled;
+try {
+ settled = await settlePayment({ ... });
+} catch (err) {
+ return error(res, err.status || 502, err.code || 'settle_failed', err.message);
+}
+
+let signedReceipt = null;
+try {
+ signedReceipt = await signReceipt({
+ resourceUrl,
+ payer: verified.payer,
+ network: verified.requirement.network,
+ txHash: settled.txHash,
+ includeTxHash: false,
+ });
+} catch (err) {
+ // Sign failures must not break the response. Log and proceed unsigned.
+ console.error('x402_receipt_sign_failed', err);
+}
+
+const headerEnvelope = signedReceipt
+ ? { ...settled, extensions: { 'offer-receipt': { signedReceipt } } }
+ : settled;
+
+res.setHeader('x-payment-response', encodePaymentResponseHeader(headerEnvelope));
+```
+
+Verify that `encodePaymentResponseHeader` is shape-agnostic enough to accept this. If it currently does field-by-field re-encoding, generalize it minimally — do not refactor beyond what's needed.
+
+### 3. Confirm `verified.payer` and `verified.requirement.network` are populated
+
+These come from `verifyPayment` at [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js). Trace the code path and confirm both fields are present on the returned object. If `verifyPayment` does not currently expose `payer`, fix that in the shared lib — but only the minimum needed.
+
+For BSC `direct` flows, `verified.payer` may be `null` (the contract emits an event, no signed payload). That's expected — `signReceipt` returns `null` when payer is null, which means BSC responses ship without a receipt. Document this in a one-line comment at the call site.
+
+### 4. Sanity test
+
+```bash
+npm run dev &
+sleep 3
+# Hit any paid endpoint with a valid x-payment header from a test client.
+# (Use the existing test/example client in the repo — find it with: grep -rln "x-payment" --include="*.js" .)
+```
+
+After the call returns 200, decode `x-payment-response`:
+
+```bash
+node --input-type=module -e "
+import { verifyReceiptSignatureEIP712 } from '@x402/extensions/offer-receipt';
+const headerB64 = process.argv[2];
+const envelope = JSON.parse(Buffer.from(headerB64, 'base64').toString('utf8'));
+const sr = envelope.extensions?.['offer-receipt']?.signedReceipt;
+if (!sr) { console.error('no signed receipt'); process.exit(1); }
+const ok = await verifyReceiptSignatureEIP712(sr);
+console.log(ok ? 'VERIFIED' : 'FAILED', JSON.stringify(sr.payload, null, 2));
+" "<paste-the-header-value-here>"
+```
+
+Expected: `VERIFIED` and a payload containing `resourceUrl`, `payer`, `network`, `issuedAt`. No `txHash` (because `includeTxHash: false`).
+
+## Definition of done
+
+- [ ] After successful settlement, `x-payment-response` decodes to an envelope containing `extensions["offer-receipt"].signedReceipt`.
+- [ ] The signed receipt verifies under `verifyReceiptSignatureEIP712`.
+- [ ] Receipt payload includes `resourceUrl`, `payer`, `network`, `issuedAt`. No `txHash` unless `includeTxHash: true` (it's not).
+- [ ] Receipts are signed **only** after `settlePayment` resolves — never before.
+- [ ] A receipt-sign failure logs `x402_receipt_sign_failed` and returns the 200 anyway.
+- [ ] BSC `direct` 200 responses ship without a receipt (graceful null), no error thrown.
+- [ ] When `X402_RECEIPT_SIGNING_KEY` is unset, response is byte-identical to current behaviour.
+- [ ] No paid endpoint handler in `api/x402/*.js` was modified.
+- [ ] `npm test` still passes.
+- [ ] `git diff` reviewed.
+
+## Stop conditions
+
+- If `verifyPayment` does not return the payer address for the EVM `exact` scheme, do not invent one — fix the upstream verifier first or surface the gap.
+- If `settlePayment` does not return a `txHash` field, that's fine (we default `includeTxHash: false`). Do not add fake tx hashes.
diff --git a/docs/x402-offer-receipt/04-bazaar-declaration.md b/docs/x402-offer-receipt/04-bazaar-declaration.md
new file mode 100644
index 000000000..f033a498b
--- /dev/null
+++ b/docs/x402-offer-receipt/04-bazaar-declaration.md
@@ -0,0 +1,130 @@
+# Prompt 04 — Declare extension support in bazaar discovery
+
+The signing wiring from prompts [02](02-offer-signing.md) and [03](03-receipt-signing.md) is live. Bazaar crawlers (e.g. agentic.market) won't know your endpoints sign offers and receipts unless you advertise capability in the discovery envelope. This prompt adds that declaration.
+
+## Project rules (must follow)
+
+From [CLAUDE.md](../../CLAUDE.md):
+
+- **No fake data, no placeholders, no stubs.**
+
+Additional rule for this task:
+
+- **Do not modify `bazaarExtension()` or `buildBazaarSchema()` in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js).** Their schemas mirror `@x402/extensions/bazaar` exactly; deviating breaks the crawler. The offer-receipt capability declaration is part of the **402 body's top-level `extensions`**, not part of `bazaar`.
+
+## Background
+
+Two different things live under `extensions`:
+
+| Key | What it is | Per-request? |
+|---|---|---|
+| `bazaar` | Discovery metadata for crawlers — input/output schemas, descriptions. | Static per endpoint. |
+| `offer-receipt` | The signed offers themselves (on 402) or the signed receipt (on 200). | **Dynamic** — generated per request. |
+
+The plan in [00-plan.md](00-plan.md) decided they are **siblings** at the top level of `extensions`, not nested. Prompt 02 already emits the dynamic `offer-receipt` payload on 402 responses. What's missing is the **capability declaration** that a crawler reads at discovery time to know "this endpoint signs offers and receipts."
+
+Per the x402 docs, that declaration comes from `declareOfferReceiptExtension({ includeTxHash, offerValiditySeconds })`. It returns an object describing the extension that gets merged into the discovery envelope.
+
+## Inputs
+
+- Helper exported by the package:
+ ```js
+ import { declareOfferReceiptExtension } from '@x402/extensions/offer-receipt';
+ const declaration = declareOfferReceiptExtension({
+ includeTxHash: false,
+ offerValiditySeconds: 60,
+ });
+ // Returns something like:
+ // { 'offer-receipt': { signer: { kid, format: 'eip712' }, includeTxHash: false, offerValiditySeconds: 60 } }
+ ```
+- The current 402 body shape after prompt 02:
+ ```js
+ extensions: { bazaar, 'offer-receipt': { signedOffers } } // signing enabled
+ extensions: { bazaar } // signing disabled
+ ```
+- After this prompt, the shape becomes:
+ ```js
+ extensions: {
+ bazaar,
+ 'offer-receipt': {
+ signer: { kid, format: 'eip712' },
+ includeTxHash: false,
+ offerValiditySeconds: 60,
+ signedOffers: [ ... ]
+ }
+ }
+ ```
+
+The **declaration fields** (`signer`, `includeTxHash`, `offerValiditySeconds`) are static and identical across all 9 endpoints. The **dynamic field** (`signedOffers`) is generated per request.
+
+## Task
+
+### 1. Export a declaration helper from the signer module
+
+In [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js), add an export:
+
+```js
+// Static capability declaration for crawlers. Returns null when the feature
+// is disabled, so callers can skip merging it.
+export function offerReceiptDeclaration() {
+ if (!issuer) return null;
+ return declareOfferReceiptExtension({
+ includeTxHash: false,
+ offerValiditySeconds: 60,
+ });
+}
+```
+
+`declareOfferReceiptExtension` returns the **whole** `{ 'offer-receipt': { ... } }` object. Be sure to merge correctly so you end up with one `'offer-receipt'` key (not two) in the final `extensions` object.
+
+### 2. Merge the declaration into the 402 body
+
+Update [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js) `build402Body`. Take the declaration produced by `offerReceiptDeclaration()` and merge it with the per-request `signedOffers`:
+
+```js
+import { signOffersForAccepts, offerReceiptDeclaration } from './x402-offer-receipt.js';
+
+// ...inside build402Body, after computing signedOffers...
+const declaration = offerReceiptDeclaration();
+const extensions = { bazaar };
+if (declaration && signedOffers.length) {
+ extensions['offer-receipt'] = { ...declaration['offer-receipt'], signedOffers };
+} else if (declaration) {
+ extensions['offer-receipt'] = declaration['offer-receipt'];
+}
+return { x402Version: X402_VERSION, error, resource: {...}, accepts: [...], extensions };
+```
+
+The `signedOffers` array shadows nothing in the declaration (declaration has no `signedOffers` key), so this is a clean merge.
+
+### 3. Confirm `bazaar` is untouched
+
+```bash
+git diff api/_lib/x402-spec.js | grep -E 'bazaar(Extension|Schema)' | head
+```
+
+This grep should return only context lines — no `+` or `-` lines touching `bazaarExtension` or `buildBazaarSchema` function bodies.
+
+### 4. Sanity test
+
+```bash
+npm run dev &
+sleep 3
+curl -s http://localhost:3000/api/x402/dance-tip?dancer=1\&dance=rumba | jq '.extensions["offer-receipt"]'
+```
+
+With `X402_RECEIPT_SIGNING_KEY` set, the output should show **both** the static declaration fields (`signer`, `includeTxHash`, `offerValiditySeconds`) **and** the dynamic `signedOffers` array. With the env unset, the `offer-receipt` key should be absent entirely.
+
+## Definition of done
+
+- [ ] `offerReceiptDeclaration()` is exported from `api/_lib/x402-offer-receipt.js`.
+- [ ] `build402Body` merges declaration + `signedOffers` into a single `extensions["offer-receipt"]` object.
+- [ ] `bazaarExtension()` and `buildBazaarSchema()` source is unchanged.
+- [ ] 402 responses with env set show declaration + signed offers together.
+- [ ] 402 responses with env unset show no `offer-receipt` key.
+- [ ] `npm test` still passes.
+- [ ] `git diff` reviewed.
+
+## Stop conditions
+
+- If `declareOfferReceiptExtension` is not exported from `@x402/extensions/offer-receipt` at the documented path, surface it. Do not hand-roll the declaration shape — it must match what crawlers parse.
diff --git a/docs/x402-offer-receipt/05-verification-script.md b/docs/x402-offer-receipt/05-verification-script.md
new file mode 100644
index 000000000..fd603654d
--- /dev/null
+++ b/docs/x402-offer-receipt/05-verification-script.md
@@ -0,0 +1,108 @@
+# Prompt 05 — End-to-end verification script
+
+Prompts [01](01-foundation.md) through [04](04-bazaar-declaration.md) have wired the feature. This prompt builds a standalone script that proves the whole chain works against a live (or local) server: hit a paid endpoint, extract and verify the signed offer, pay, extract and verify the signed receipt, confirm the receipt matches the offer.
+
+This is the gate that flips the feature from "wired" to "verified end-to-end." Per [CLAUDE.md](../../CLAUDE.md): a feature is not done until this passes.
+
+## Project rules (must follow)
+
+From [CLAUDE.md](../../CLAUDE.md):
+
+- **No mocks. No fake data.** Real endpoints, real payment, real verification.
+- **No `setTimeout` fake-loading or fake progress bars.** Real async or nothing.
+
+## Inputs
+
+- The signer module from prompt 01.
+- A real payer wallet for the script to spend from. Use `X402_TEST_PAYER_KEY` (a separate env var, must be a low-balance test wallet on Base mainnet — never a production wallet).
+- The exact bazaar endpoint to test against: [api/x402/dance-tip.js](../../api/x402/dance-tip.js) is the cheapest at $0.001 — use it.
+- Verification helpers from `@x402/extensions/offer-receipt`:
+ - `extractOffersFromPaymentRequired`
+ - `decodeSignedOffers`
+ - `verifyOfferSignatureEIP712`
+ - `extractReceiptFromResponse`
+ - `verifyReceiptSignatureEIP712`
+ - `verifyReceiptMatchesOffer`
+- Payment client: there's likely an existing test/example client in the repo. Find it with:
+ ```bash
+ grep -rln "x-payment" --include="*.js" . | grep -vE 'node_modules|api/_lib|api/x402'
+ ```
+ If no suitable client exists, use `@x402/fetch` (install if missing) to handle the 402 challenge automatically.
+
+## Task
+
+Create [scripts/verify-x402-receipts.js](../../scripts/verify-x402-receipts.js) as an executable Node script (`#!/usr/bin/env node`). It must:
+
+### 1. Read config from env or argv
+
+```
+node scripts/verify-x402-receipts.js [--base https://three.ws] [--route /api/x402/dance-tip?dancer=1&dance=rumba]
+```
+
+Defaults:
+- `--base` → `process.env.PUBLIC_APP_ORIGIN` or `http://localhost:3000`
+- `--route` → `/api/x402/dance-tip?dancer=1&dance=rumba`
+- `X402_TEST_PAYER_KEY` from env (required; fail with a clear error if missing)
+
+### 2. Step 1 — fetch 402 and verify the signed offer
+
+```
+fetch(base + route, { method: 'GET' }) // no x-payment header
+→ expect status 402
+→ body = await res.json()
+→ offers = extractOffersFromPaymentRequired(body)
+→ decoded = decodeSignedOffers(offers)
+→ for each decoded offer, await verifyOfferSignatureEIP712(d.signedOffer)
+```
+
+Print one line per offer: `OFFER <network> <kid> -> VERIFIED | FAILED`. Exit non-zero if any fails.
+
+Pick the Base-mainnet offer for the next step. If no Base offer is advertised, exit with a clear `no_base_offer` error.
+
+### 3. Step 2 — pay the selected offer
+
+Use the existing payment client found in the codebase (or `@x402/fetch`) with the test payer key. The exact wiring depends on which client is in use — read its docstring and follow its pattern. Expect a `200` response.
+
+Do **not** swallow payment errors. If the test wallet has insufficient balance, surface the actual error message and exit non-zero. **Do not retry**, **do not fall back to mocks**.
+
+### 4. Step 3 — verify the signed receipt
+
+```
+signedReceipt = extractReceiptFromResponse(paidResponse)
+→ await verifyReceiptSignatureEIP712(signedReceipt)
+→ verifyReceiptMatchesOffer(signedReceipt, selectedOffer, [payerAddress])
+```
+
+Print `RECEIPT <kid> -> VERIFIED | FAILED`. Print the receipt's `payload` (resourceUrl, payer, network, issuedAt).
+
+If `verifyReceiptMatchesOffer` fails, dump the offer payload and the receipt payload side by side and exit non-zero — the mismatch tells the operator which field drifted.
+
+### 5. Exit code
+
+- Exit `0` on full success.
+- Exit `1` on any verification failure or payment error, with a clear final line: `verify-x402-receipts: FAILED (<reason>)`.
+
+### 6. Add an npm script
+
+In [package.json](../../package.json), add:
+
+```json
+"scripts": {
+ ...
+ "verify:x402-receipts": "node scripts/verify-x402-receipts.js"
+}
+```
+
+## Definition of done
+
+- [ ] `scripts/verify-x402-receipts.js` exists, is executable, and uses real payment + verification (no mocks).
+- [ ] Against a running `npm run dev` instance (or a deployed `https://three.ws`), it prints `OFFER ... VERIFIED` for every advertised network, `RECEIPT ... VERIFIED`, and exits `0`.
+- [ ] With `X402_RECEIPT_SIGNING_KEY` unset on the server, the script exits non-zero with `no_signed_offers_in_response` — confirming the absence test.
+- [ ] With a tampered offer (manually flip a byte in the signature), the script exits non-zero with the verifier's error message.
+- [ ] `npm run verify:x402-receipts` works as documented.
+- [ ] `git diff` reviewed.
+
+## Stop conditions
+
+- If the codebase has no existing way to drive a real x402 payment from a script, **do not** invent one with mocked signatures. Either use `@x402/fetch` (real implementation), or surface that you need the operator to install a real client. The whole point of this script is to be real.
+- If `verifyReceiptMatchesOffer` requires the payer address but the test client doesn't expose it, derive it deterministically from `X402_TEST_PAYER_KEY` via `privateKeyToAccount(...).address`. That's the real address, not a mock.
diff --git a/docs/x402-offer-receipt/06-completionist-and-push.md b/docs/x402-offer-receipt/06-completionist-and-push.md
new file mode 100644
index 000000000..f684720cc
--- /dev/null
+++ b/docs/x402-offer-receipt/06-completionist-and-push.md
@@ -0,0 +1,111 @@
+# Prompt 06 — Completionist pass + push to both remotes
+
+Prompts [01](01-foundation.md)–[05](05-verification-script.md) have wired and verified the feature. This is the final gate before shipping: audit the diff against [CLAUDE.md](../../CLAUDE.md)'s hard rules, fix anything flagged, then push to both GitHub remotes.
+
+## Project rules (must follow)
+
+From [CLAUDE.md](../../CLAUDE.md):
+
+- **No mocks. No fake data. No placeholders.**
+- **No TODO comments. No stubs.**
+- **No commented-out code.**
+- **No `throw new Error("not implemented")`.**
+- **No `setTimeout` fake-loading.**
+- **No fallback sample arrays shipped to production.**
+- **Errors handled at boundaries only.**
+- Push to **both** `origin` (3D-Agent) **and** `threews` (three.ws) remotes. Never push without explicit user approval. Never force-push.
+
+## Task
+
+### 1. Verify the feature is wired end-to-end
+
+Before auditing, confirm the feature works:
+
+```bash
+# With X402_RECEIPT_SIGNING_KEY set in your local .env:
+npm run dev &
+sleep 3
+npm run verify:x402-receipts
+# Expect: every OFFER VERIFIED, RECEIPT VERIFIED, exit 0
+```
+
+If this fails, **stop** — go back to whichever prompt the failure points to. Do not push a broken feature.
+
+### 2. Run the completionist audit
+
+From [CLAUDE.md](../../CLAUDE.md): "Before stopping on a feature task, run the **completionist** subagent to audit your changed files for the rules above. Fix every item it flags. Then stop."
+
+Run the completionist on the diff:
+
+```bash
+git status
+git diff main -- api/_lib/ scripts/ package.json .env.example
+```
+
+Spawn the completionist subagent with the full diff and the list of changed files. Fix every flagged item — no exceptions. Re-run the audit until it returns clean.
+
+### 3. Sanity check against the full Definition of Done in [00-plan.md](00-plan.md)
+
+Go through the plan's DoD checklist line by line. For each unchecked item, either check it (with evidence) or fix the underlying issue. The list:
+
+- [ ] `X402_RECEIPT_SIGNING_KEY` documented in `.env.example`, real value in local `.env`, configured in Vercel `production` + `preview` (operator confirms this — surface it explicitly if you can't verify Vercel state).
+- [ ] `npm test` passes.
+- [ ] Paid endpoints return `402` with `extensions["offer-receipt"].signedOffers[]` — verify with the script.
+- [ ] Paid endpoints return `200` with `x-payment-response` containing a verifiable `signedReceipt` — verify with the script.
+- [ ] `scripts/verify-x402-receipts.js` exits `0`.
+- [ ] No handler in `api/x402/*.js` was modified (`git diff main -- api/x402/`).
+- [ ] Completionist returns clean.
+- [ ] Ready to push to **both** remotes.
+
+### 4. Commit
+
+Stage only the files this feature touched. Do **not** `git add .` — there are unrelated modifications in the working tree (see `git status` from the start of this session: `api/_lib/x402-paid-endpoint.js`, `api/_lib/x402-permit2.js` deletion, `api/_lib/x402-spec.js`, `api/wk.js`, `api/x402-status.js`, `public/x402.js`, `vercel.json`). Some of those may overlap with our changes; verify carefully.
+
+Use the project's commit-message style (check `git log` for tone). Single commit, descriptive:
+
+```
+feat(x402): signed offers on 402 + signed receipts on 200
+
+Wires the x402 Offer & Receipt extension into the shared paidEndpoint
+wrapper so every paid endpoint signs offers on 402 challenges and
+receipts on 200 deliveries. EIP-712 signing under did:pkh, controlled
+by X402_RECEIPT_SIGNING_KEY (unset = feature off, byte-identical to
+prior behaviour).
+
+Co-Authored-By: Claude Opus 4.7 <[email protected]>
+```
+
+(Pass via HEREDOC per [CLAUDE.md](../../CLAUDE.md)'s git protocol.)
+
+### 5. Push to BOTH remotes
+
+```bash
+git push origin <branch>
+git push threews <branch>
+```
+
+If either push fails, surface the error and stop. **Do not** silently leave the repos out of sync. **Do not** force-push.
+
+### 6. Confirm
+
+After both pushes succeed, print a short summary:
+
+- Files changed (count + key paths).
+- Verification script status.
+- Both push targets and their resulting commit SHAs.
+
+## Definition of done
+
+- [ ] `npm run verify:x402-receipts` passes end-to-end against a live server.
+- [ ] Completionist audit returns clean.
+- [ ] All plan DoD items checked.
+- [ ] One descriptive commit on the working branch.
+- [ ] `git push origin` succeeded.
+- [ ] `git push threews` succeeded.
+- [ ] Summary printed.
+
+## Stop conditions
+
+- If the completionist flags issues you cannot fix without changing locked-in decisions from [00-plan.md](00-plan.md), surface the conflict instead of overriding the plan unilaterally.
+- If `git push` to either remote fails (auth, hook rejection, conflict), surface the error verbatim. Do not retry destructively, do not skip hooks, do not force-push.
+- If unrelated modifications in the working tree (the ones listed in step 4) are intermixed with the feature changes, ask the operator how to split before committing. Do not lump unrelated work into the feature commit.
diff --git a/prompts/club/01-venue-glb-and-environment.md b/prompts/club/01-venue-glb-and-environment.md
new file mode 100644
index 000000000..33156ba5e
--- /dev/null
+++ b/prompts/club/01-venue-glb-and-environment.md
@@ -0,0 +1,219 @@
+# Task: Real club venue GLB + environment for /club
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. The `/club` page lives at
+[pages/club.html](../../pages/club.html) and
+[src/club.js](../../src/club.js). Today the entire venue is built from
+Three.js primitives in `src/club.js:138-206`:
+
+- A `CircleGeometry(14, 80)` floor.
+- A `CircleGeometry(STAGE_RADIUS + 1.4)` dance floor inlay.
+- Three `PlaneGeometry(30, 8)` walls.
+- A flat `PlaneGeometry(9, 0.9)` "bar."
+- Two `RingGeometry` neon rings.
+
+No ceiling, no real bar, no crowd, no backstage door, no architectural
+detail. Looks like a CAD mockup, not a club.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No primitives shipped to production. No synthesized "good enough"
+ art. The venue is an authored GLB or it doesn't ship.
+- Real assets. No procedurally-generated stand-ins.
+- No `setTimeout` fake-loading the venue. Real `GLTFLoader.loadAsync`
+ with progress callback piped to the existing `setStatus` UI.
+- Errors handled at boundaries — the load can throw; the page must
+ surface that, not silently fall back to primitives.
+- Done = `/club` loads a real authored venue, dev server confirms in
+ a real browser, no console errors, `npm test` green.
+
+## Subagent delegation
+
+### Subagent A (Explore)
+
+> In `/workspaces/three.ws`, return:
+>
+> 1. The full current scene setup in `src/club.js` — every
+> primitive being added to the scene with its file:line.
+> 2. Where avatar GLBs are loaded elsewhere (e.g. `src/viewer.js`,
+> `src/agent-avatar.js`) and what loader configuration is used
+> (Draco? KTX2? Meshopt? bare `GLTFLoader`?).
+> 3. Whether the repo has any existing static-GLB serving pattern
+> (R2 vs `public/`, Vite-bundled vs CDN-hosted).
+> 4. `vercel.json` rules for `/public/club/` — anything special
+> about how large assets get served.
+> 5. Any prior "scene environment" code we can crib from
+> (RoomEnvironment is already in use; check for HDRI loaders).
+
+### Subagent B (Explore)
+
+> Quote the GLB-loader configuration the rest of the app uses for
+> compressed assets (Draco / KTX2 / Meshopt). Specifically, return:
+>
+> 1. Whether `THREE.DRACOLoader` / `KTX2Loader` / `MeshoptDecoder`
+> are wired into `GLTFLoader` anywhere.
+> 2. If not, what the recommended wiring path is per
+> [prompts/finish-features/add-mesh-compression-deps.md](../finish-features/add-mesh-compression-deps.md).
+
+Wait for both before Step 1.
+
+## What to implement
+
+### Step 1 — author / acquire the venue GLB
+
+Source: Blender authored, or a CC0 / paid asset (e.g. Sketchfab CC-BY
+nightclub, Quixel Megascans interior). License must be commercial-use.
+Record provenance in `public/club/assets/LICENSES.md`.
+
+Required contents of `club-venue.glb`:
+
+- Floor with PBR varnish material (scuffed roughness map).
+- Four perimeter walls with offsets for alcoves.
+- Real ceiling with exposed beams, ducts, lighting truss geometry
+ (the truss is where mirror-ball + spotlights will be mounted in
+ prompt 04 — leave named empties `truss.mirrorball`,
+ `truss.spot.01`–`truss.spot.04`).
+- Bar GLB with bottles (instanced), neon backsplash, an empty named
+ `bar.backsplash.neon` where prompt 04 attaches an emissive strip.
+- Backstage door / curtain props on the deep wall, one per dancer
+ slot. Each has a named empty `backstage.door.01`–`.04` whose
+ world position becomes the dancer spawn point.
+- Crowd silhouettes lining the perimeter (instanced low-poly,
+ ~1.5–1.7m tall, slight idle bob via a vertex shader or a single
+ shared animation clip).
+- Bake AO + light maps on static geo to keep the runtime lighting
+ budget for the active spotlights.
+
+Targets:
+
+- ≤8 MB compressed (`gltf-pipeline -i venue.glb -o club-venue.glb
+ --draco.compressionLevel=10`).
+- ≤4 draw calls per material category once instanced.
+- Origin at the dance-floor center, +X right, +Y up, +Z forward
+ (camera looks down -Z).
+
+Save to `public/club/venue/club-venue.glb`.
+
+### Step 2 — load + place the venue
+
+Replace `src/club.js:138-206` (floor / walls / bar / neon rings) with:
+
+```js
+const venue = await loader.loadAsync('/club/venue/club-venue.glb');
+venue.scene.traverse((n) => {
+ if (n.isMesh) {
+ n.receiveShadow = true;
+ n.castShadow = n.userData?.castShadow === true;
+ }
+});
+scene.add(venue.scene);
+```
+
+Stash the resolved `backstage.door.NN` and `truss.spot.NN` world
+positions into the `POLES` layout array so `PoleStation` reads them
+instead of computing `backstageX/backstageZ` analytically.
+
+### Step 3 — HDRI environment
+
+Replace the inline `RoomEnvironment` with an HDRI exr/hdr file at
+`public/club/venue/club-hdri.hdr`. Use `RGBELoader` +
+`PMREMGenerator.fromEquirectangular`. Keep `scene.environment` set
+to the resulting texture; `scene.background` stays the dark color so
+the HDRI only affects PBR reflections, not the visible sky.
+
+### Step 4 — Draco + KTX2 wiring
+
+If subagent B reports those loaders are not wired in this repo yet,
+wire them now in a shared module (`src/loaders/gltf.js`):
+
+```js
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
+
+let _loader;
+export function gltfLoader(renderer) {
+ if (_loader) return _loader;
+ const loader = new GLTFLoader();
+ const draco = new DRACOLoader();
+ draco.setDecoderPath('/three/draco/');
+ loader.setDRACOLoader(draco);
+ const ktx2 = new KTX2Loader().setTranscoderPath('/three/basis/').detectSupport(renderer);
+ loader.setKTX2Loader(ktx2);
+ loader.setMeshoptDecoder(MeshoptDecoder);
+ _loader = loader;
+ return loader;
+}
+```
+
+Copy the decoder + transcoder binaries into `public/three/draco/` and
+`public/three/basis/` at install time (a `postinstall` script
+copying from `node_modules/three/examples/jsm/libs/{draco,basis}/`).
+
+### Step 5 — progress + error UI
+
+Pipe `GLTFLoader.loadAsync`'s second-arg progress event into the
+existing `setStatus()` helper:
+
+```js
+loader.load(
+ '/club/venue/club-venue.glb',
+ resolve,
+ (e) => setStatus(`Loading club… ${Math.round((e.loaded / e.total) * 100)}%`),
+ reject,
+);
+```
+
+On failure: surface the error in `setStatus({ kind: 'error' })` and
+re-throw — `bootstrap()`'s catch handler already logs.
+
+### Step 6 — wire pole/stage placement to venue empties
+
+The pole props (prompt 03) ride on stage discs whose center comes from
+the venue's `stage.NN` named empties. Read those during venue load
+and overwrite the analytical `POLES[i].x/z` so the artist can move
+poles in Blender without touching code.
+
+### Step 7 — manual end-to-end
+
+```bash
+npm run dev
+```
+
+Visit `http://localhost:3000/club`. The venue should:
+
+- Show the authored ceiling/walls/bar, no primitives visible.
+- Place poles + stages on the stage empties.
+- Have the crowd silhouettes around the perimeter idling.
+- Hit ≥60 fps on desktop Chrome with shadows on.
+
+### Step 8 — tests
+
+`tests/club-venue-load.test.js`:
+
+- Mock `GLTFLoader.loadAsync` to return a synthetic scene with the
+ required named empties.
+- Assert `bootstrap()` resolves spotlight + backstage + stage
+ positions from those empties (not from the analytical fallback).
+- Assert it surfaces a non-blocking error if a required empty is
+ missing, naming which one.
+
+## Definition of done
+
+- `public/club/venue/club-venue.glb` exists with the required named
+ empties + materials.
+- `src/club.js` loads it, removes all primitive scene props, and
+ resolves stage/pole/backstage/spot positions from the GLB.
+- HDRI environment lighting in place.
+- Draco/KTX2/Meshopt loaders shared across the app via
+ `src/loaders/gltf.js`.
+- Real-browser smoke clean, `npm test` green.
+
+## Constraints
+
+- Do not commit decoder binaries; copy them in via `postinstall`.
+- Do not ship a 50 MB venue. Hard-cap at 8 MB compressed.
+- Do not silently fall back to primitives on load failure. Surface
+ the error to the user and keep the canvas blank.
diff --git a/prompts/club/02-dancer-glbs.md b/prompts/club/02-dancer-glbs.md
new file mode 100644
index 000000000..c180466d6
--- /dev/null
+++ b/prompts/club/02-dancer-glbs.md
@@ -0,0 +1,169 @@
+# Task: Four distinct dancer GLBs for /club
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. Today
+[src/club.js](../../src/club.js) clones a single template from
+`/avatars/default.glb` four times (`src/club.js:286-316`,
+`attachAvatar()`), tints each clone's emissive by pole index, and
+calls it four "different" dancers. Four identical avatars in four
+different lights is not four dancers.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No mocks, no placeholders, no "good enough" tinting trick.
+- Real authored GLBs, one per dancer slot.
+- All four must share the same skeleton so the existing animation
+ clips in `/animations/manifest.json` drive them without per-dancer
+ retargeting at runtime.
+- Done = `/club` renders four visibly distinct dancers, animations
+ play on each without bone mismatch warnings, `npm test` green.
+
+## Subagent delegation
+
+### Subagent A (Explore)
+
+> In `/workspaces/three.ws`, document the canonical Avaturn /
+> three.ws skeleton:
+>
+> 1. What loader/builder authors `/avatars/default.glb`? Is it
+> Avaturn? Custom Blender rig? Quote the source.
+> 2. Where is the bone name list canonicalized? (Look in
+> `src/animation-manager.js`, `scripts/build-animations.mjs`,
+> `docs/avatar-creation.md`.)
+> 3. How are animation clips retargeted to it from Mixamo? Quote
+> the retarget mapping table.
+> 4. Whether any other authored GLB in the repo uses the same
+> skeleton (e.g. `/avatars/cz.glb`).
+
+### Subagent B (Explore)
+
+> Read [docs/avaturn.md](../../docs/avaturn.md) +
+> [docs/avatar-creation.md](../../docs/avatar-creation.md) and quote
+> the avatar-authoring pipeline: which platform produces the GLBs,
+> what blendshapes are required (for lip-sync), what the texture
+> resolution targets are.
+
+Wait for both.
+
+## What to implement
+
+### Step 1 — author / acquire the four dancer GLBs
+
+Use the same pipeline that authors `/avatars/default.glb`. Each
+dancer is a stylistic variant — different outfit, hair, body shape,
+skin tone, accent palette — sharing the canonical skeleton.
+
+| Slot | File | Palette | Vibe |
+|---|---|---|---|
+| 1 | `public/club/dancers/dancer-01.glb` | neon pink (`#ff3bd6`) | cyberpunk, neon-streak hair |
+| 2 | `public/club/dancers/dancer-02.glb` | cyan (`#4ad6ff`) | latex, mirrored visor |
+| 3 | `public/club/dancers/dancer-03.glb` | amber (`#ff8a3b`) | streetwear, oversized hoodie |
+| 4 | `public/club/dancers/dancer-04.glb` | violet (`#9b5dff`) | goth-couture, choker |
+
+Each GLB:
+
+- ≤2 MB compressed via `gltf-pipeline --draco.compressionLevel=10`.
+- KTX2 textures (basis-universal) for clothing albedos.
+- Identical bone hierarchy + names as `/avatars/default.glb`.
+- Identical blendshape names (for lip-sync compatibility, even
+ though the club doesn't use them yet).
+- Idle origin at feet on Y=0, facing -Z, scale 1.0.
+
+### Step 2 — dancer registry
+
+Create `src/club-dancers.js`:
+
+```js
+export const DANCERS = [
+ {
+ slot: '1',
+ glb: '/club/dancers/dancer-01.glb',
+ name: 'Nyx',
+ bio: 'Neon-fast spin queen.',
+ accent: 0xff3bd6,
+ walletEvm: process.env?.CLUB_DANCER_01_EVM ?? null,
+ walletSolana: process.env?.CLUB_DANCER_01_SOLANA ?? null,
+ },
+ // ...slots 2-4
+];
+```
+
+Wallets are read at request time on the server (prompt 08) — the
+browser only needs `slot/glb/name/bio/accent`. Export the registry
+without secret fields.
+
+### Step 3 — bind to PoleStation
+
+In `src/club.js`:
+
+1. `bootstrap()` `await Promise.all(DANCERS.map(d => loader.loadAsync(d.glb)))`.
+2. Pass the resolved scene + dancer metadata into each
+ `PoleStation.attachAvatar(template, animationDefs, dancer)`.
+3. Drop the emissive-tinting block (`src/club.js:295-301`) — the
+ GLB's own materials carry the visual identity. Keep an optional
+ gentle rim-light tint via the accent color, but the dancer must
+ read different even with the rim light off.
+
+`attachAvatar(template, animationDefs, dancer)` now stores `this.dancer
+= dancer` so the side-panel render shows the name + bio (Step 5).
+
+### Step 4 — animation retarget verification
+
+Run `npm run build:animations` (or whatever
+[scripts/build-animations.mjs](../../scripts/build-animations.mjs)
+exposes) against each new dancer GLB to confirm the clips bind.
+
+If retargeting fails on any dancer (bone mismatch), do not patch the
+runtime — fix the GLB. The runtime must trust the skeleton.
+
+### Step 5 — side-panel UX
+
+`src/club.js` `renderPoles()` (`src/club.js:519-550`) currently shows
+"Pole 1 / 2 / 3 / 4." Change to show the dancer's name + bio +
+small headshot:
+
+- Pre-render a headshot PNG per dancer at build time
+ (`scripts/render-dancer-headshots.mjs`) using the existing
+ `api/_lib/render-glb.js` from
+ [prompts/finish-features/server-side-glb-render.md](../finish-features/server-side-glb-render.md),
+ output to `public/club/dancers/headshot-NN.png` 256×256.
+- Right-panel card: 48×48 headshot + name + bio + tip button.
+
+### Step 6 — manual end-to-end
+
+```bash
+npm run dev
+```
+
+Visit `/club`. The four dancers should be visibly distinct on stage
+(zoomed out and zoomed in). Tipping any dancer should still play the
+chosen clip without console errors.
+
+### Step 7 — tests
+
+`tests/club-dancers.test.js`:
+
+- Assert `DANCERS` exports four slots with distinct GLB URLs.
+- Mock `GLTFLoader.loadAsync` to return scenes with matching bone
+ names; assert `PoleStation.attachAvatar` runs without throwing.
+- Add a fixture GLB with mismatched bones; assert the load throws
+ with a clear `clip_skeleton_mismatch` error code.
+
+## Definition of done
+
+- Four authored `public/club/dancers/dancer-0N.glb` files exist,
+ each ≤2 MB compressed.
+- `src/club-dancers.js` registry exports the four slots.
+- `PoleStation` uses per-slot GLB; the emissive-tint stand-in is
+ removed.
+- Right-panel cards show name + bio + headshot.
+- All existing dance clips play on every dancer with no skeleton
+ warnings.
+
+## Constraints
+
+- Do not procedurally tint the same GLB four ways and call it done.
+- Do not ship a dancer GLB whose bones don't match the canonical
+ skeleton — fix the GLB, not the retarget.
+- Do not bake dancer wallets into the client bundle. Server only.
diff --git a/prompts/club/03-pole-rig-and-pole-animations.md b/prompts/club/03-pole-rig-and-pole-animations.md
new file mode 100644
index 000000000..843907442
--- /dev/null
+++ b/prompts/club/03-pole-rig-and-pole-animations.md
@@ -0,0 +1,242 @@
+# Task: Real pole rig GLB + pole-specific dance clips
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. Today the pole at
+[src/club.js:234-247](../../src/club.js) is a single
+`CylinderGeometry(0.05, 0.05, 3.6)` chrome cylinder, floating between
+a stage disc and nothing. There's no ceiling mount, no flared base, no
+spotlight hardware attached.
+
+The animation clips driven by tips
+([api/x402/dance-tip.js:22-28](../../api/x402/dance-tip.js)) —
+`rumba`, `silly`, `thriller`, `capoeira`, `hiphop` — are generic
+Mixamo free-floor clips. None of them touch the pole. The dancer
+performs *next to* the pole, not *on* it.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No primitive cylinder shipped as a "pole." Authored GLB.
+- No reusing existing free-floor clips as "pole choreography."
+- Animation clips authored / sourced under a commercial-use license,
+ baked via the project's existing retarget pipeline, registered in
+ `public/animations/manifest.json`, exposed via the
+ `dance-tip` `STYLES` map.
+- Done = a tip with `dance=spin` plays a real pole-spin clip on the
+ dancer, the dancer's hands actually grip the pole (foot/hand IK
+ matches the pole position).
+
+## Subagent delegation
+
+### Subagent A (Explore)
+
+> In `/workspaces/three.ws`, return:
+>
+> 1. The retarget pipeline in
+> [scripts/build-animations.mjs](../../scripts/build-animations.mjs)
+> — what it consumes, what it emits, how it's invoked, and
+> whether it supports pole-anchored hand/foot targets.
+> 2. The current `STYLES` map in
+> [api/x402/dance-tip.js](../../api/x402/dance-tip.js):26-28 and
+> every place it's referenced.
+> 3. How `AnimationManager.crossfadeTo` is invoked from
+> [src/club.js](../../src/club.js) (`PoleStation.startPerformance`,
+> `_arriveAtPole`, `_endPerformance`).
+> 4. Whether `src/animation-state-machine.js` is used anywhere
+> relevant — would a state machine help for the entry → spin →
+> invert → bow sequence?
+
+### Subagent B (Explore)
+
+> Quote `public/animations/manifest.json` clip list. Confirm which
+> clip names already exist (e.g. `walk`, `idle`, `rumba`). Then list
+> the new pole-specific clip names this task needs to add and what
+> Mixamo / source clip each should originate from.
+
+Wait for both.
+
+## What to implement
+
+### Step 1 — pole rig GLB
+
+Author `public/club/props/pole.glb`:
+
+- A 3.6m chrome pole (`PoleHeight` in `src/club.js:57`).
+- Flared circular base, 0.45m radius, brushed chrome material.
+- Ceiling mount: a flat plate at the top, four small bolts visible.
+- Spotlight bracket on the mount with an empty `pole.light.attach`
+ for prompt 04 to anchor `SpotLight`s.
+- Optional: subtle smudge/handprint roughness map (no two poles
+ identical — variation comes from material instance tint).
+
+Save to `public/club/props/pole.glb`. ≤500 KB compressed.
+
+Replace the cylinder in
+[src/club.js:234-247](../../src/club.js) with an instanced
+`SkeletonUtils.clone()` of the pole GLB, positioned at each
+`POLES[i].x/z`. Tint the chrome material with the slot accent via a
+`material.clone()` + emissive offset (subtle — 0.02–0.05).
+
+### Step 2 — pole stage disc
+
+Replace the `CylinderGeometry` stage disc
+([src/club.js:218-230](../../src/club.js)) with a stage GLB:
+
+- 1.1m radius, 0.18m tall, slightly tilted top with anti-slip
+ texture, LED strip around the edge (named empty
+ `stage.led.strip` for prompt 04 to drive emissive pulse).
+- Save to `public/club/props/stage.glb`.
+
+### Step 3 — pole choreography clips
+
+Author / source the following clips, retargeted to the canonical
+skeleton via
+[scripts/build-animations.mjs](../../scripts/build-animations.mjs).
+Each ends with the dancer's hands and feet at known offsets relative
+to a 3.6m pole at origin:
+
+| Clip name | Duration | Loop? | Source | Notes |
+|---|---|---|---|---|
+| `pole-walk-on` | ~3.0s | false | Mixamo "Strut Walk" trimmed | Ends at pole with right hand on pole at 1.4m height |
+| `pole-spin` | ~4.0s | true | Mixamo "Pole Spin" or custom mocap | Right hand at 2.0m, left hand at 1.4m, full body revolution |
+| `pole-climb` | ~5.0s | false | Custom mocap | Climbs from 0 to 2.0m, holds, descends |
+| `pole-invert` | ~6.0s | true | Custom mocap | Upside-down hang, legs locked around pole at 2.4m |
+| `pole-floorwork` | ~5.0s | true | Mixamo "Floor Work" retargeted | On the stage disc, low to ground |
+| `pole-bow` | ~2.0s | false | Mixamo "Bow" | Exits forward off the stage |
+
+Output JSON to `public/animations/clips/pole-*.json`. Register in
+`public/animations/manifest.json` with `icon` field (a Unicode glyph
+or emoji to render in the picker — pole emoji 🪩, spin 🌀, etc.).
+
+Source licensing recorded in
+`public/animations/LICENSES.md` (extend the existing one if it
+exists; create if not).
+
+### Step 4 — sequence playback
+
+The current `PoleStation.startPerformance` plays a single clip then
+ends. Add a sequence-capable wrapper:
+
+```js
+// In PoleStation:
+async startPerformance(ticket) {
+ this.performing = true;
+ this.activeTicket = ticket;
+ const seq = ticket.sequence ?? [{ clip: ticket.clip, durationSec: ticket.durationSec }];
+ this.walkPhase = 'to-pole';
+ await this.anim.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);
+ // ...arrive at pole...
+ for (const step of seq) {
+ if (!this.performing) break;
+ await this.anim.crossfadeTo(step.clip, PERFORMANCE_FADE);
+ await sleep(step.durationSec * 1000);
+ }
+ await this._endPerformance();
+}
+```
+
+A `sleep()` helper that's *not* `setTimeout` faking work — it
+awaits a real timer that participates in the render loop's clock.
+
+### Step 5 — expand `STYLES`
+
+In [api/x402/dance-tip.js:22-28](../../api/x402/dance-tip.js):
+
+```js
+const STYLES = Object.freeze({
+ // Free-floor (existing)
+ rumba: { clip: 'rumba', label: 'Rumba', loop: true, durationSec: 14 },
+ silly: { clip: 'silly', label: 'Silly', loop: true, durationSec: 10 },
+ thriller: { clip: 'thriller', label: 'Thriller',loop: true, durationSec: 14 },
+ capoeira: { clip: 'capoeira', label: 'Capoeira',loop: true, durationSec: 12 },
+ hiphop: { clip: 'dance', label: 'Hip Hop', loop: true, durationSec: 12 },
+
+ // Pole choreography (new)
+ spin: { sequence: [
+ { clip: 'pole-spin', durationSec: 8 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ], label: 'Pole Spin', durationSec: 10 },
+ climb: { sequence: [
+ { clip: 'pole-climb', durationSec: 5 },
+ { clip: 'pole-invert', durationSec: 6 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ], label: 'Climb + Invert', durationSec: 13 },
+ combo: { sequence: [
+ { clip: 'pole-spin', durationSec: 4 },
+ { clip: 'pole-climb', durationSec: 4 },
+ { clip: 'pole-invert', durationSec: 4 },
+ { clip: 'pole-floorwork',durationSec: 4 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ], label: 'Combo', durationSec: 18 },
+});
+```
+
+Update `OUTPUT_EXAMPLE`, `OUTPUT_SCHEMA`, `INPUT_SCHEMA`'s `dance`
+enum, and the bazaar schema.
+
+### Step 6 — hand/foot IK alignment (optional but recommended)
+
+If the pole GLB's exact world position drifts from where the clip
+was authored, the dancer's hand will pass through the pole or miss
+it. Add a one-pass IK correction at clip load time:
+
+- Read the pole's world `x/z` from the venue empty.
+- Translate the clip's `track` keyframes for the hand bones by the
+ delta from the clip's authored origin. This is a small offset, no
+ per-frame solver needed.
+
+If the artist can author all clips at the same canonical pole
+position relative to the dancer rig origin, this step is a no-op.
+
+### Step 7 — manual end-to-end
+
+```bash
+npm run dev
+```
+
+Tip a dancer with `dance=spin`. Confirm:
+
+- Dancer walks from backstage to pole.
+- Hand makes contact at the right height (no clipping, no air gap).
+- Clip loops cleanly for 8s.
+- `pole-bow` plays, dancer walks back.
+
+Repeat for `climb` and `combo`.
+
+### Step 8 — tests
+
+`tests/api/dance-tip.test.js` (extend existing if present):
+
+- All new style keys return a 402 challenge then settle to a
+ ticket whose `sequence` matches the `STYLES` table.
+- Unknown style returns 400 with `unknown_dance`.
+- Bazaar schema validates.
+
+`tests/club-station.test.js`:
+
+- Mock `AnimationManager.crossfadeTo`; assert
+ `PoleStation.startPerformance` calls it in sequence order with
+ matching durations.
+- Cancellation: setting `performing = false` mid-sequence stops
+ the next crossfade.
+
+## Definition of done
+
+- `public/club/props/pole.glb` + `stage.glb` authored and loaded.
+- 6 new pole-* clips exist in
+ `public/animations/clips/` and `public/animations/manifest.json`.
+- `STYLES` exports `spin`, `climb`, `combo` (free-floor still
+ available).
+- `/club` tip flow plays sequences end-to-end with visible hand
+ contact on the pole.
+- Tests green.
+
+## Constraints
+
+- Do not synthesize pole clips with a clever procedural shader. If
+ the choreography isn't authored, it doesn't ship.
+- Do not author the new clips against a different skeleton — they
+ must drive the same bones as `idle`/`walk`.
+- Do not break existing free-floor styles (`rumba`, etc.) when
+ adding sequences. The `STYLES` schema must accept both `clip`-
+ only entries and `sequence` entries.
diff --git a/prompts/club/04-lighting-and-postfx.md b/prompts/club/04-lighting-and-postfx.md
new file mode 100644
index 000000000..b90b51eb2
--- /dev/null
+++ b/prompts/club/04-lighting-and-postfx.md
@@ -0,0 +1,197 @@
+# Task: Volumetric lighting + mirror ball + post-processing for /club
+
+## Repo context
+
+Working tree: `/workspaces/three.ws`. Today
+[src/club.js](../../src/club.js) sets up:
+
+- One `AmbientLight` + one `HemisphereLight` (low intensity).
+- Four `SpotLight`s pointing at each pole base.
+- Four `PointLight` floor accents.
+- Four orbiting `PointLight`s in a "disco" group
+ ([src/club.js:418-426](../../src/club.js)).
+- No post-processing — `renderer.render(scene, camera)` direct.
+
+There's no volumetric glow, no mirror ball reflection, no bloom, no
+beat-synced animation, no rim lights along bar/ceiling. The room
+looks evenly lit instead of moody.
+
+## Rails (CLAUDE.md — non-negotiable)
+
+- No fake "volumetric" rendered as a static texture decal — the
+ cones must respond to camera position via real billboarded
+ geometry or a proper volumetric pass.
+- No `setTimeout`-driven light pulses. Phase off the render loop's
+ `clock.elapsedTime`.
+- Bloom + tone mapping wired via `EffectComposer` from
+ `three/addons/postprocessing/*`. Cleanly disposable on resize.
+- Done = real-browser smoke shows visible spotlight cones through
+ fog, mirror-ball dots scattering across the room, bar neon strip
+ glowing, no fps regression on desktop.
+
+## What to implement
+
+### Step 1 — postprocessing pipeline
+
+Wire `EffectComposer` in [src/club.js](../../src/club.js):
+
+```js
+import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
+import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
+import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
+import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
+
+const composer = new EffectComposer(renderer);
+composer.addPass(new RenderPass(scene, camera));
+const bloom = new UnrealBloomPass(
+ new Vector2(window.innerWidth, window.innerHeight),
+ 0.55, // strength
+ 0.85, // radius
+ 0.7, // threshold
+);
+composer.addPass(bloom);
+composer.addPass(new OutputPass());
+
+renderer.toneMapping = ACESFilmicToneMapping;
+renderer.toneMappingExposure = 1.1;
+```
+
+Replace `renderer.render(scene, camera)` in the animate loop with
+`composer.render()`. Update `resize` to call
+`composer.setSize(w, h)` and `bloom.resolution.set(w, h)`.
+
+### Step 2 — volumetric spotlight cones
+
+For each `SpotLight`, add a billboarded cone mesh that fakes
+volumetric glow. Cleanest pattern:
+
+- `ConeGeometry` (open bottom) sized to match the spotlight angle
+ and distance.
+- Custom `ShaderMaterial`:
+ - vertex shader passes view-space normal and position;
+ - fragment shader fades by `dot(view, normal)` so the cone is
+ bright when looking across it and faint when looking along it;
+ - density falls off with distance from cone axis.
+- Additive blending, depth write off, `transparent: true`.
+- The cone color matches the slot accent (`POLE_COLORS[i]`).
+- Intensity follows `this.spot.intensity` from `PoleStation` so it
+ ramps up when a dancer takes the pole.
+
+The volumetric cone is a child of the spotlight target group so it
+moves correctly with the spotlight orientation.
+
+Don't try a screen-space fullscreen volumetric pass — too expensive
+for four cones on mobile.
+
+### Step 3 — mirror ball
+
+Add `public/club/props/mirrorball.glb` (or build procedurally — an
+`IcosahedronGeometry(0.35, 2)` with per-face material variation):
+
+- Hangs from the venue's `truss.mirrorball` empty.
+- Rotates slowly: `mirrorball.rotation.y = t * 0.4` in the animate
+ loop.
+- Cube camera (`CubeCamera`) parented to the ball, captures the
+ scene every frame at 64×64 px into a `CubeRenderTarget`.
+- A small instanced `PointsMaterial` of "reflection dots" scattered
+ across the floor and walls, where each dot's brightness is
+ modulated by sampling the cube-cam target. Practical shortcut:
+ instead of a real reflection bounce, project ~80 spotlight-like
+ beams from the ball position at random outward angles and let
+ them paint emissive specks on the wall via a `Points` system
+ whose positions are computed on the CPU once and rotated with the
+ ball.
+
+Cube camera updates only when the camera is in a wide shot — skip
+when the active camera is a VIP zoom (prompt 06).
+
+### Step 4 — bar neon strip + ceiling rim
+
+Find the venue's `bar.backsplash.neon` and `truss.rim.*` empties.
+Attach `LineSegments` along their paths with an emissive material
+(0xff3bd6 for the bar, color-cycling for the truss). Bloom does the
+heavy lifting — the lines don't need to be thick.
+
+### Step 5 — beat-synced rim pulse
+
+The audio prompt (prompt 05) wires a Web Audio analyser. Read its
+peak value every frame and modulate the rim-light intensity:
+
+```js
+const peak = audioAnalyser?.getPeak?.() ?? 0; // 0..1
+rimMat.emissiveIntensity = 0.4 + peak * 1.6;
+```
+
+If audio isn't available (analyser is null), default to a slow
+sine: `0.4 + 0.4 * Math.sin(t * 1.2)`. No fake beat detection —
+real audio drives it when audio plays, real sine when it doesn't.
+
+### Step 6 — chromatic aberration during high-energy clips
+
+For `pole-spin`, `pole-invert`, `thriller`:
+
+- Add an `ShaderPass` between `bloom` and `OutputPass` with a small
+ chromatic-aberration shader (per-channel UV offset).
+- Strength interpolates from 0 → 0.004 during the active clip and
+ back to 0 on exit.
+- Driver: `composer.passes` reads each `PoleStation.performing` +
+ `activeTicket.clip` to compute a global "intensity" 0..1.
+
+### Step 7 — shadow tuning
+
+Today every spotlight has shadows on. With four spots + bloom +
+volumetric cones + mirror ball this gets heavy.
+
+- Only the spot whose station is `performing` casts shadows. The
+ rest set `castShadow = false`. Toggle on in
+ `_spotTarget = active`, off when returning to idle.
+- Shadow map size 512×512 (already the default in `src/club.js:254`).
+- `shadow.bias = -0.0008` (already set).
+
+### Step 8 — manual end-to-end
+
+```bash
+npm run dev
+```
+
+Visit `/club`. Confirm:
+
+- Spotlight cones visible through fog when looking across them.
+- Mirror ball rotates and paints reflection dots on the floor/walls.
+- Bar neon strip glows with bloom.
+- Tipping a dancer ramps the cone intensity up + chromatic
+ aberration in on high-energy clips, then back.
+- Frame rate ≥60fps on a 2020-era laptop.
+
+### Step 9 — tests
+
+`tests/club-lighting.test.js`:
+
+- Construct a `PoleStation` with a stubbed `SpotLight`; assert the
+ volumetric cone child mesh exists and shares intensity.
+- Drive `tick()` with a fake `dt` and assert the cone material's
+ intensity lerps toward the target.
+
+Visual / postprocessing has no unit test that adds value — rely on
+the manual smoke and on the Playwright snapshot in prompt 10.
+
+## Definition of done
+
+- `EffectComposer` pipeline live with bloom + tone mapping +
+ optional chromatic aberration.
+- Volumetric cones visible per spotlight.
+- Mirror ball + reflection dots render.
+- Bar + ceiling rim lights render and pulse.
+- No fps regression vs primitives-only baseline on the same
+ hardware.
+
+## Constraints
+
+- Do not require WebGPU; everything must work on WebGL2 + bloom.
+- Do not write a fullscreen volumetric god-rays pass — too costly
+ for the budget. Billboarded cones only.
+- Do not leave the cube-camera updating every frame when a VIP cam
+ is active.
+- Do not allow bloom to clip the dancer's albedo into white on the
+ brightest clips — set `material.toneMapped = true` on dancer
+ skin shaders.
diff --git a/prompts/club/README.md b/prompts/club/README.md
new file mode 100644
index 000000000..c7df08f29
--- /dev/null
+++ b/prompts/club/README.md
@@ -0,0 +1,47 @@
+# Pole Club build-out — task prompts
+
+Each file in this directory is a **fully self-contained prompt** for
+turning the placeholder rig at [/club](../../pages/club.html) +
+[src/club.js](../../src/club.js) into a real authored venue with
+distinct dancers, pole choreography, club lighting/audio, server-backed
+tip persistence, and per-dancer leaderboards/payouts.
+
+You can hand any one of these to a fresh Claude Code session without
+loading anything else from this directory — they restate the rails
+from [CLAUDE.md](../../CLAUDE.md) and quote the relevant existing
+files.
+
+The high-level vision and integration map lives in
+[docs/club/PLAN.md](../../docs/club/PLAN.md).
+
+## Rails every prompt repeats (CLAUDE.md, non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
+ `throw new Error('not implemented')`, no commented-out code, no
+ `setTimeout` fake-loading.
+- Real APIs only: x402 paid endpoints, Solana RPC, EVM RPC, Neon
+ Postgres, R2.
+- Done = code wired, dev server confirms feature in a real browser
+ with no console errors, `npm test` green, `git diff` reviewed.
+- Push to **both** `threeD` (nirholas/3D-Agent) and `threews`
+ (nirholas/three.ws) only when the user explicitly says push.
+
+## The queue
+
+| # | File | Subagents? | Estimate |
+|---|---|---|---|
+| 01 | [01-venue-glb-and-environment.md](01-venue-glb-and-environment.md) | Yes — Explore for asset/loader conventions | large |
+| 02 | [02-dancer-glbs.md](02-dancer-glbs.md) | Yes — Explore for canonical skeleton + Avaturn pipeline | large |
+| 03 | [03-pole-rig-and-pole-animations.md](03-pole-rig-and-pole-animations.md) | Yes — Explore for `build-animations.mjs` retarget pass | large |
+| 04 | [04-lighting-and-postfx.md](04-lighting-and-postfx.md) | No | medium |
+| 05 | [05-audio-and-music.md](05-audio-and-music.md) | No | medium |
+| 06 | [06-camera-and-controls.md](06-camera-and-controls.md) | No | medium |
+| 07 | [07-tip-feed-realtime.md](07-tip-feed-realtime.md) | Yes — Explore for existing SSE / Neon patterns | medium |
+| 08 | [08-leaderboard-and-payouts.md](08-leaderboard-and-payouts.md) | Yes — Explore for payout rails in `api/payments/*` | large |
+| 09 | [09-mobile-and-perf.md](09-mobile-and-perf.md) | No | small |
+| 10 | [10-e2e-tests-and-verification.md](10-e2e-tests-and-verification.md) | Yes — Explore for existing Playwright setup | medium |
+
+Run order: 01–03 unblock the visual + animation work; 04–06 polish it;
+07–08 add server state; 09 keeps it usable on mobile; 10 verifies the
+whole thing. Files do not strictly depend on each other — a fresh
+session can pick any one and ship it.
diff --git a/prompts/siwx/01-db-schema.md b/prompts/siwx/01-db-schema.md
new file mode 100644
index 000000000..dc3330a54
--- /dev/null
+++ b/prompts/siwx/01-db-schema.md
@@ -0,0 +1,163 @@
+# SIWX prompt 01 — Postgres schema for payment-history + nonce store
+
+## Context
+
+You are working in the **three.ws** workspace at `/workspaces/three.ws`. This
+project sells access to x402 paid endpoints (3D assets, agent skills, dance
+performances) and is adding **Sign-In-With-X (SIWX, CAIP-122)** so a wallet
+that has already paid for a resource can re-access it by signing a message
+instead of re-paying.
+
+Architecture overview lives in [prompts/siwx/PLAN.md](PLAN.md). Read it first.
+
+You are implementing **step 1 of 7**: the Postgres tables that back the SIWX
+storage adapter. Everything else in the plan depends on these tables existing.
+
+## Rails (CLAUDE.md, non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
+ `throw new Error('not implemented')`, no commented-out code.
+- Real Neon Postgres — same `sql` tag from
+ [api/_lib/db.js](../../api/_lib/db.js) every other migration uses.
+- Errors at boundaries only.
+- Done = migration written, applied locally against the Neon database
+ pointed at by `$DATABASE_URL`, both tables visible via `\dt` (or
+ equivalent SELECT against `information_schema`), `git diff` reviewed.
+
+## What to build
+
+### File 1 — `api/_lib/migrations/2026-05-21-siwx.sql`
+
+Match the style of existing migrations in
+[api/_lib/migrations/](../../api/_lib/migrations/) (look at
+`2026-05-14-x402-skus.sql` and `2026-05-10-skill-purchases.sql` for tone).
+Idempotent (`IF NOT EXISTS` on every CREATE) and self-contained.
+
+Two tables:
+
+```sql
+CREATE TABLE IF NOT EXISTS siwx_payments (
+ resource text NOT NULL,
+ address text NOT NULL,
+ network text NOT NULL, -- CAIP-2, e.g. 'eip155:8453'
+ paid_at timestamptz NOT NULL DEFAULT now(),
+ expires_at timestamptz, -- NULL = permanent grant
+ last_used_at timestamptz, -- updated on each siwx auth
+ use_count integer NOT NULL DEFAULT 0,
+ PRIMARY KEY (resource, address)
+);
+
+CREATE INDEX IF NOT EXISTS siwx_payments_expires_idx
+ ON siwx_payments (expires_at)
+ WHERE expires_at IS NOT NULL;
+
+CREATE TABLE IF NOT EXISTS siwx_nonces (
+ nonce text PRIMARY KEY,
+ resource text NOT NULL,
+ address text NOT NULL,
+ used_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS siwx_nonces_used_at_idx
+ ON siwx_nonces (used_at);
+```
+
+Notes that must be true in the file:
+
+- `address` is stored exactly as the CAIP-122 payload carries it — for EVM
+ that means **lowercase hex** (NOT checksummed), for Solana that means the
+ Base58 public key. The storage adapter (prompt 02) is responsible for
+ normalizing before SELECT/INSERT. Document this in a 2-line comment above
+ the `siwx_payments` table — the adapter relies on the storage layer's
+ normalization, not a CHECK constraint.
+- Composite PK (`resource`, `address`) gives us O(1) `hasPaid` lookups and
+ natural upserts via `ON CONFLICT (resource, address) DO UPDATE`.
+- `siwx_nonces` is intentionally separate from `siwx_payments` because nonces
+ are write-heavy + garbage-collected hourly (prompt 06), while payments are
+ read-mostly + long-lived.
+- No FK to any other table — SIWX storage is decoupled from `users`,
+ `agent_identities`, `skill_purchases`. A wallet might be SIWX-paid for a
+ resource without ever creating an account.
+
+### File 2 — `scripts/apply-siwx-migration.mjs`
+
+A one-shot script that reads the migration file and applies it via the same
+Neon HTTP client. Pattern to match:
+
+```js
+#!/usr/bin/env node
+// Apply the SIWX migration against $DATABASE_URL.
+// Usage: DATABASE_URL=... node scripts/apply-siwx-migration.mjs
+import { readFile } from 'node:fs/promises';
+import { neon } from '@neondatabase/serverless';
+
+const url = process.env.DATABASE_URL;
+if (!url) {
+ console.error('DATABASE_URL not set');
+ process.exit(1);
+}
+const sql = neon(url);
+const text = await readFile(
+ new URL('../api/_lib/migrations/2026-05-21-siwx.sql', import.meta.url),
+ 'utf8',
+);
+// Neon's HTTP API runs one statement per call. Split on semicolons that
+// terminate top-level statements (no quoted/escaped ; in this migration).
+const statements = text
+ .split(/;\s*$/m)
+ .map((s) => s.trim())
+ .filter((s) => s && !s.startsWith('--'));
+for (const s of statements) {
+ await sql.query(s);
+ console.log('OK:', s.slice(0, 80).replace(/\s+/g, ' '));
+}
+console.log('siwx tables ready');
+```
+
+Verify by running it once against the dev database. If a similar `scripts/*`
+helper already exists for another migration (e.g. `scripts/apply-*.mjs`),
+match its style. If not, create the file fresh.
+
+### File 3 — wire it into the codebase
+
+If the project has a migration registry (look for `api/_lib/migrations.js`,
+`scripts/migrate.mjs`, or similar — do NOT create one if none exists), add
+the new migration there in the right place. If migrations are tracked only
+by file name on disk (the current pattern, per `ls api/_lib/migrations/`),
+nothing else to do.
+
+## Verification you must perform
+
+```bash
+# 1. The migration applies cleanly.
+DATABASE_URL=$DATABASE_URL node scripts/apply-siwx-migration.mjs
+
+# 2. Both tables exist with the expected columns.
+DATABASE_URL=$DATABASE_URL node -e "
+import('@neondatabase/serverless').then(async ({ neon }) => {
+ const sql = neon(process.env.DATABASE_URL);
+ const cols = await sql\`
+ select table_name, column_name, data_type
+ from information_schema.columns
+ where table_name in ('siwx_payments','siwx_nonces')
+ order by table_name, ordinal_position\`;
+ console.table(cols);
+});
+"
+
+# 3. Re-running the migration is a no-op (no errors).
+DATABASE_URL=$DATABASE_URL node scripts/apply-siwx-migration.mjs
+```
+
+All three must succeed before you call this done. Paste the column listing
+into the final status update so the next prompt can confirm the shape.
+
+## Done means
+
+- `api/_lib/migrations/2026-05-21-siwx.sql` exists and matches the spec above.
+- `scripts/apply-siwx-migration.mjs` exists and runs idempotently.
+- Both tables exist in the Neon database.
+- `git diff` reviewed: nothing committed-out, nothing TODO, no stubs.
+
+Do **not** commit or push. Surface the diff to the user; they'll call the
+push when they're ready.
diff --git a/prompts/siwx/02-storage-adapter.md b/prompts/siwx/02-storage-adapter.md
new file mode 100644
index 000000000..098d0e37f
--- /dev/null
+++ b/prompts/siwx/02-storage-adapter.md
@@ -0,0 +1,203 @@
+# SIWX prompt 02 — Postgres-backed `SIWxStorage` adapter
+
+## Context
+
+three.ws workspace at `/workspaces/three.ws`. Architecture in
+[prompts/siwx/PLAN.md](PLAN.md). Prompt 01 created the `siwx_payments` and
+`siwx_nonces` tables in Neon Postgres.
+
+You are implementing **step 2 of 7**: a Postgres adapter that implements the
+`SIWxStorage` interface from `@x402/extensions/sign-in-with-x` so the
+`paidEndpoint()` integration (prompt 03) has something concrete to write to.
+
+The interface (from
+`node_modules/@x402/extensions/dist/esm/sign-in-with-x/index.d.mts`):
+
+```ts
+interface SIWxStorage {
+ hasPaid(resource: string, address: string): boolean | Promise<boolean>;
+ recordPayment(resource: string, address: string): void | Promise<void>;
+ hasUsedNonce?(nonce: string): boolean | Promise<boolean>;
+ recordNonce?(nonce: string): void | Promise<void>;
+}
+```
+
+Per upstream docs: `hasUsedNonce` and `recordNonce` MUST both be implemented
+or both be omitted; implementing only one throws at startup.
+
+## Rails (CLAUDE.md, non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
+ commented-out code.
+- Real Neon queries via `sql` from [api/_lib/db.js](../../api/_lib/db.js).
+- Errors at boundaries only — internal calls trust each other.
+- `npm test` green when you're done.
+
+## What to build
+
+### File 1 — `api/_lib/siwx-storage.js`
+
+ESM module exporting one factory and one helper. No class hierarchy — keep
+it flat. Match the file-header style of
+[api/_lib/skill-access.js](../../api/_lib/skill-access.js) (purpose comment +
+inline usage example).
+
+```js
+// api/_lib/siwx-storage.js
+//
+// Postgres-backed SIWxStorage for the Sign-In-With-X extension.
+//
+// Wired into api/_lib/x402-paid-endpoint.js (prompt 03). Every paid endpoint
+// that opts into SIWX shares one instance — this module's `siwxStorage`
+// singleton — so the underlying connection pool stays warm across handlers.
+//
+// Address normalization rule: EVM addresses are stored LOWERCASED, Solana
+// addresses are stored AS-IS (Base58, case-sensitive). The normalizer below
+// is the only place that decides — every caller goes through it.
+
+import { sql } from './db.js';
+
+// Normalize an address before SELECT/INSERT. Network is the CAIP-2 string
+// from the verified SIWX payload (e.g. "eip155:8453" or
+// "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp").
+export function normalizeAddress(network, address) {
+ if (!network || !address) throw new Error('siwx-storage: network+address required');
+ if (network.startsWith('eip155:')) return String(address).toLowerCase();
+ if (network.startsWith('solana:')) return String(address);
+ throw new Error(`siwx-storage: unsupported CAIP-2 namespace "${network}"`);
+}
+```
+
+#### `siwxStorage` singleton
+
+Export `siwxStorage` as a plain object implementing the four `SIWxStorage`
+methods. Method bodies:
+
+- `hasPaid(resource, address)`
+ - Looks up `siwx_payments` by `(resource, normalizedAddress)`.
+ - Returns `false` when no row.
+ - Returns `false` when `expires_at IS NOT NULL AND expires_at <= now()`.
+ - Otherwise returns `true` AND fires-and-forgets an
+ `UPDATE ... SET last_used_at = now(), use_count = use_count + 1`
+ (await it; the savings of fire-and-forget aren't worth the dropped
+ audit trail).
+ - **Important:** the upstream contract passes `address` already-recovered
+ from the verified signature. EVM verifiers return the checksummed form,
+ so we must lowercase before hitting `siwx_payments` regardless of how
+ callers stored it. Apply `normalizeAddress` using the network we
+ persisted at `recordPayment` time. Since the call site only gives us
+ `(resource, address)`, store the network on the row and look it up
+ when the call comes in: the `SELECT` matches case-insensitively for
+ EVM by lowercasing the input; Solana stays exact. Implement the
+ SELECT as:
+
+ ```sql
+ SELECT 1
+ FROM siwx_payments
+ WHERE resource = ${resource}
+ AND (
+ (network LIKE 'eip155:%' AND address = ${String(address).toLowerCase()})
+ OR
+ (network LIKE 'solana:%' AND address = ${String(address)})
+ )
+ AND (expires_at IS NULL OR expires_at > now())
+ LIMIT 1
+ ```
+
+- `recordPayment(resource, address, opts = {})`
+ - `opts = { network, ttlSeconds? }`. `network` is required (so we know
+ which normalization to apply). `ttlSeconds` defaults to `null` →
+ permanent grant.
+ - `INSERT ... ON CONFLICT (resource, address) DO UPDATE` so re-purchases
+ refresh `paid_at` and extend `expires_at`.
+ - Implementation:
+
+ ```sql
+ INSERT INTO siwx_payments
+ (resource, address, network, expires_at)
+ VALUES
+ (${resource}, ${normalizeAddress(network, address)}, ${network},
+ ${ttlSeconds ? sql`now() + (${ttlSeconds} || ' seconds')::interval` : null})
+ ON CONFLICT (resource, address) DO UPDATE
+ SET network = EXCLUDED.network,
+ paid_at = now(),
+ expires_at = EXCLUDED.expires_at
+ ```
+
+- `hasUsedNonce(nonce)`
+ - `SELECT 1 FROM siwx_nonces WHERE nonce = ${nonce} LIMIT 1`.
+ - Returns boolean.
+
+- `recordNonce(nonce, opts = {})`
+ - `opts = { resource, address }` (so the GC job and audit have context).
+ - `INSERT ... ON CONFLICT (nonce) DO NOTHING` — safe to call twice.
+
+#### Helpers exported for tests + cron
+
+- `pruneExpiredPayments(graceSeconds = 7 * 24 * 3600)`
+ - `DELETE FROM siwx_payments WHERE expires_at IS NOT NULL AND expires_at < now() - (${graceSeconds} || ' seconds')::interval`.
+ - Returns deleted row count.
+- `pruneOldNonces(maxAgeSeconds = 600)`
+ - `DELETE FROM siwx_nonces WHERE used_at < now() - (${maxAgeSeconds} || ' seconds')::interval`.
+ - Returns deleted row count.
+
+### File 2 — `api/_lib/siwx-storage.test.js`
+
+Vitest test (this project uses Vitest — confirm via `grep '"test"' package.json`
+or the existing `api/_lib/*.test.js` files). The test hits the real `$DATABASE_URL`
+when set, and `it.skipIf(!process.env.DATABASE_URL)` when it isn't, so CI can run
+without leaking secrets and a local dev can run it after `01-db-schema.md`.
+
+Cover:
+
+1. `hasPaid` returns false for an unknown wallet.
+2. `recordPayment` + `hasPaid` round-trips for EVM (mixed-case → lowercase
+ match) on `eip155:8453`.
+3. `recordPayment` + `hasPaid` round-trips for Solana (Base58 case-sensitive).
+4. `recordPayment` with `ttlSeconds: 1` then `hasPaid` returns true; after
+ `await new Promise(r => setTimeout(r, 1500))` it returns false.
+5. `recordNonce` + `hasUsedNonce` round-trips and is idempotent.
+6. `pruneOldNonces(0)` clears all nonces inserted by the test.
+
+Each test uses a per-run resource string like
+`test-resource-${crypto.randomUUID()}` so concurrent test runs don't collide.
+Tear down explicitly at the end with `DELETE FROM siwx_payments WHERE resource LIKE 'test-resource-%'`
+plus the equivalent for `siwx_nonces`.
+
+### File 3 — register the singleton
+
+Nothing global; prompt 03 imports `siwxStorage` directly from this module.
+Just make sure the export is named and stable.
+
+## Verification you must perform
+
+```bash
+# 1. Lint clean
+npx eslint api/_lib/siwx-storage.js api/_lib/siwx-storage.test.js
+
+# 2. Tests pass against the real DB
+DATABASE_URL=$DATABASE_URL npx vitest run api/_lib/siwx-storage.test.js
+
+# 3. No leftover test rows
+DATABASE_URL=$DATABASE_URL node -e "
+import('@neondatabase/serverless').then(async ({ neon }) => {
+ const sql = neon(process.env.DATABASE_URL);
+ const a = await sql\`select count(*)::int as n from siwx_payments where resource like 'test-resource-%'\`;
+ const b = await sql\`select count(*)::int as n from siwx_nonces where resource like 'test-resource-%'\`;
+ console.log('residual payments:', a[0].n, 'nonces:', b[0].n);
+});
+"
+# Both must print 0.
+```
+
+## Done means
+
+- `api/_lib/siwx-storage.js` implements the four `SIWxStorage` methods
+ exactly as specified, plus the two `prune*` helpers.
+- `api/_lib/siwx-storage.test.js` exercises every method with real Postgres,
+ passes locally with `$DATABASE_URL` set, and cleans up after itself.
+- No mocks, no in-memory fallbacks, no `process.env` defaults that silently
+ bypass the DB.
+- `git diff` reviewed.
+
+Do not commit or push.
diff --git a/prompts/siwx/03-paid-endpoint-integration.md b/prompts/siwx/03-paid-endpoint-integration.md
new file mode 100644
index 000000000..953ebaae0
--- /dev/null
+++ b/prompts/siwx/03-paid-endpoint-integration.md
@@ -0,0 +1,337 @@
+# SIWX prompt 03 — wire SIWX into the `paidEndpoint()` helper
+
+## Context
+
+three.ws workspace at `/workspaces/three.ws`. Architecture in
+[prompts/siwx/PLAN.md](PLAN.md). Prompts 01 + 02 created
+`siwx_payments` / `siwx_nonces` and a Postgres adapter at
+[api/_lib/siwx-storage.js](../../api/_lib/siwx-storage.js).
+
+This prompt is **step 3 of 7** — the core integration. Every x402 paid
+endpoint in `api/x402/*.js` is built on top of
+[api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js)'s
+`paidEndpoint(spec)` factory. We extend that one helper so any endpoint can
+opt into SIWX by adding a single `siwx:` block to its spec — and existing
+endpoints that don't opt in are unchanged.
+
+Read [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js)
+in full before you start. The 7-step dance (CORS → method-check → 402 →
+verify → handler → settle → response) is the spine you're extending.
+
+## Rails (CLAUDE.md, non-negotiable)
+
+- No mocks, no fake data, no placeholders, no TODOs, no stubs.
+- No commented-out code in the diff.
+- Real Postgres writes via `siwxStorage`. Real signature verification via
+ `@x402/extensions/sign-in-with-x` — not your own crypto.
+- Errors at boundaries only.
+- `npm test` green.
+- Existing endpoints that don't pass a `siwx:` block must continue to
+ behave **bit-identically** to today (same 402 body, same headers, same
+ response shape). Snapshot-style test in prompt 07 will catch regressions.
+
+## Files to edit / create
+
+### File 1 — `api/_lib/siwx-server.js` (new)
+
+Thin wrapper around the upstream SIWX primitives so `paidEndpoint()` stays
+readable. Match the file-header style of
+[api/_lib/x402-spec.js](../../api/_lib/x402-spec.js).
+
+Exports:
+
+```js
+// api/_lib/siwx-server.js
+//
+// 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.
+
+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;
+}
+
+// Build the extensions block that goes into the 402 body when SIWX is
+// enabled for an endpoint. The upstream helper auto-derives `domain`,
+// `resourceUri`, and refreshes `nonce`/`issuedAt` — we just pass network +
+// the human-readable statement.
+//
+// `networks` is the same CAIP-2 array the rest of paidEndpoint() uses
+// (e.g. ['eip155:8453', 'solana:5eykt...']). Multi-chain support is the
+// whole reason CAIP-122 exists — emit all of them, the client picks one.
+export function declareSiwxExtensionFor({ networks, statement, expirationSeconds = 300 }) {
+ return declareSIWxExtension({
+ network: networks.length === 1 ? networks[0] : networks,
+ statement,
+ expirationSeconds,
+ });
+}
+
+// Given an incoming Vercel request, attempt to authenticate via SIGN-IN-WITH-X.
+// Returns { ok: true, address, network } when the signature is valid AND the
+// (resource, address) pair is on record. Returns { ok: false, status, error }
+// on validation/verification failure (caller emits 401/402 accordingly).
+// Returns null when the header is absent — caller continues with the normal
+// 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, {
+ // Tighten the default 5-min window slightly so we don't accept stale
+ // signatures across deploys / cold starts.
+ 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.
+export async function recordSiwxPayment({ resourceUrl, payer, network, ttlSeconds = null }) {
+ if (!payer) return; // direct-scheme settlements without a payer (BSC fallback) skip recording.
+ await siwxStorage.recordPayment(resourceUrl, payer, { network, ttlSeconds });
+}
+```
+
+Add `BASE_RPC_URL` to [api/_lib/env.js](../../api/_lib/env.js) if it isn't
+already listed (look first — `env.BASE_RPC_URL` may already exist for the
+Permit2 / BSC flow). If you add it, keep the existing alphabetical/grouping
+convention of that file.
+
+### File 2 — extend `api/_lib/x402-paid-endpoint.js`
+
+Three changes, **and nothing else**:
+
+#### 2a. New optional `siwx` field on the `spec` argument
+
+```js
+const {
+ route,
+ method = 'GET',
+ priceAtomics = env.X402_MAX_AMOUNT_REQUIRED,
+ networks = ['base', 'solana'],
+ description,
+ mimeType = 'application/json',
+ bazaar,
+ handler,
+ // NEW: when present, this endpoint advertises and accepts SIWX auth.
+ // { statement: string; ttlSeconds?: number | null; expirationSeconds?: number }
+ // - statement: human-readable purpose shown to the wallet on signing
+ // - ttlSeconds: how long the payment grant lasts (null = permanent)
+ // - expirationSeconds: SIWX message validity window (default 300s)
+ siwx,
+} = spec;
+```
+
+#### 2b. Declare the SIWX extension on the 402 challenge
+
+Inside the `paidHandler` async function, after building `requirements` but
+before constructing the `challenge` object, build the extensions block when
+SIWX is enabled and pass it through `send402` (which already supports an
+`extensions` option via `build402Body`):
+
+```js
+const siwxExtensions = siwx
+ ? declareSiwxExtensionFor({
+ networks: requirements.map((r) => r.network),
+ statement: siwx.statement,
+ expirationSeconds: siwx.expirationSeconds,
+ })
+ : null;
+
+const challenge = {
+ resourceUrl,
+ accepts: requirements,
+ description,
+ mimeType,
+ bazaar,
+ ...(siwxExtensions ? { extensions: siwxExtensions } : {}),
+};
+```
+
+`build402Body` in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js)
+already merges arbitrary extensions — confirm by re-reading lines around
+`extraExtensions`. No change needed there.
+
+#### 2c. SIWX auth path: before falling through to the 402 flow
+
+Right after `const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];`,
+add the SIWX short-circuit:
+
+```js
+if (siwx && !paymentHeader) {
+ const auth = await authenticateSiwx({ req, resourceUrl });
+ if (auth?.ok) {
+ let result;
+ try {
+ result = await handler({
+ req,
+ res,
+ requirement: null, // no payment requirement was used
+ payer: auth.address, // recovered SIWX wallet
+ siwx: { address: auth.address, network: auth.network },
+ });
+ } catch (err) {
+ if (err instanceof X402Error && err.status === 402) {
+ return send402(res, { ...challenge, error: err.message });
+ }
+ return error(res, err.status || 500, err.code || 'internal_error', err.message);
+ }
+ if (res.writableEnded) return;
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', `${mimeType}; charset=utf-8`);
+ res.end(typeof result === 'string' ? result : JSON.stringify(result));
+ return;
+ }
+ if (auth && !auth.ok) {
+ // Validation/verification failed — return a 401 so callers don't keep
+ // retrying with the same broken signature. They can drop the header and
+ // re-attempt the normal pay-with-USDC flow.
+ return error(res, auth.status, auth.code, auth.error);
+ }
+ // auth === null → header absent → fall through to standard 402 dance.
+}
+```
+
+Import `X402Error` (already imported), `authenticateSiwx`, and
+`declareSiwxExtensionFor` from `./siwx-server.js`. The `siwx` extra arg to
+`handler` is opt-in — existing handlers ignore it; new handlers can branch on
+"served via signature" vs. "served via payment" if they care (most won't).
+
+#### 2d. Record the payment after settlement
+
+In the same handler, after the existing `settlePayment(...)` call succeeds
+and before `res.setHeader('x-payment-response', ...)`, record the grant:
+
+```js
+if (siwx) {
+ await recordSiwxPayment({
+ resourceUrl,
+ payer: verified.payer,
+ network: verified.requirement.network,
+ ttlSeconds: siwx.ttlSeconds ?? null,
+ });
+}
+```
+
+Import `recordSiwxPayment` from `./siwx-server.js`. Don't try/catch this:
+if Postgres is down, the payment already settled on-chain; logging the
+error and surfacing a 500 is fine — we don't want to silently lose a
+grant on a Neon hiccup. Let it throw; the outer `error(res, ...)` already
+catches handler errors and returns a clean response.
+
+Actually — wait. The settle path doesn't currently wrap further work in a
+try/catch (it goes straight to writing headers). Wrap the `recordSiwxPayment`
+call in a `try/catch` that returns a `502 siwx_record_failed` so the buyer
+sees a clear error instead of a hung connection. They can retry; the upsert
+on `siwx_payments` is idempotent and the on-chain transaction is final.
+
+### File 3 — JSDoc + tests
+
+Update the JSDoc / file-top comment of
+[api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) so the
+8-step dance is correctly described (was 7). Add one paragraph explaining
+the SIWX opt-in.
+
+New test file `api/_lib/x402-paid-endpoint.siwx.test.js` (Vitest) covering:
+
+1. Endpoint without `siwx:` — 402 body has no `extensions['sign-in-with-x']`
+ (current behavior preserved).
+2. Endpoint with `siwx:` — 402 body has `extensions['sign-in-with-x']` with
+ `supportedChains` matching `requirements[].network`.
+3. With a real Solana keypair (`@solana/web3.js` is already a dep — see
+ `package.json`), generate a SIWX message, sign it, send the encoded
+ header → endpoint returns 402 with `siwx_not_paid` because no grant
+ exists.
+4. After calling `siwxStorage.recordPayment(resourceUrl, address, { network })`
+ directly, the same SIWX request now returns 200 with the handler's
+ response body.
+
+Use `$DATABASE_URL` like prompt 02's tests; `it.skipIf(!process.env.DATABASE_URL)`.
+
+## Verification you must perform
+
+```bash
+# 1. Lint
+npx eslint api/_lib/siwx-server.js api/_lib/x402-paid-endpoint.js api/_lib/x402-paid-endpoint.siwx.test.js
+
+# 2. Existing tests still pass
+npm test
+
+# 3. New SIWX tests pass against real DB
+DATABASE_URL=$DATABASE_URL npx vitest run api/_lib/x402-paid-endpoint.siwx.test.js
+
+# 4. A no-siwx endpoint's 402 is bit-identical (snapshot the body before and
+# after your diff to confirm).
+```
+
+## Done means
+
+- `api/_lib/siwx-server.js` exists and is the only place that touches the
+ `@x402/extensions/sign-in-with-x` API surface.
+- `api/_lib/x402-paid-endpoint.js` accepts an optional `siwx:` spec and
+ handles the three new responsibilities (declare, authenticate, record).
+- Tests above all green.
+- Existing endpoints (skill-marketplace, dance-tip, others in `api/x402/*.js`)
+ are **untouched** by this prompt. Wiring them is prompt 04.
+- `git diff` reviewed.
+
+Do not commit or push.
diff --git a/prompts/siwx/PLAN.md b/prompts/siwx/PLAN.md
new file mode 100644
index 000000000..fc2d53960
--- /dev/null
+++ b/prompts/siwx/PLAN.md
@@ -0,0 +1,182 @@
+# SIWX — Sign-In-With-X for three.ws x402 endpoints
+
+**One-line:** add CAIP-122 wallet sign-in to every paid x402 endpoint so a wallet
+that has paid once can re-access the resource by signing instead of paying again.
+
+## Why this matters for three.ws
+
+The bazaar is becoming a marketplace for **re-downloadable digital goods**: GLBs,
+avatars, agent skills, agent definitions, lobby characters, accessories,
+animations, mint metadata, and time-pass-style API access. Without SIWX every
+re-download is a re-purchase — which kills creator economics and buyer trust.
+
+With SIWX:
+
+- **Buyers** sign with their wallet to re-enter content they've already paid for.
+- **Sellers** keep the original 402-paid sale; subsequent fetches are free for
+ the same wallet but blocked for everyone else.
+- **Agents** integrate exactly the same way — the `@x402/fetch` client
+ auto-signs when it sees the `sign-in-with-x` extension in a 402 response.
+
+## What we're building
+
+A small, opt-in layer wired through the existing `paidEndpoint()` helper in
+[api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js). Every
+endpoint can advertise SIWX by adding one field to its spec; the helper takes
+care of declaring the extension, validating the incoming `SIGN-IN-WITH-X`
+header, looking up payment history in Postgres, and recording payments when a
+fresh 402 settles.
+
+```
+┌───────────────────────────────────────────────────────────────────────────┐
+│ x402 PAID ENDPOINT │
+│ │
+│ ┌──────────────────────────────┐ ┌──────────────────────────────┐ │
+│ │ request hits /api/x402/* │ │ /api/x402/* with SIGN-IN- │ │
+│ │ with X-PAYMENT header │ │ WITH-X header (no X-PAYMENT) │ │
+│ └─────────────┬────────────────┘ └─────────────┬────────────────┘ │
+│ │ verify + settle │ parseSIWxHeader │
+│ ▼ │ validateSIWxMessage │
+│ ┌────────────────────┐ │ verifySIWxSignature │
+│ │ siwx storage: │ ▼ │
+│ │ recordPayment( │ ┌────────────────────┐ │
+│ │ resource, payer) │ │ siwx storage: │ │
+│ └─────────┬──────────┘ │ hasPaid(resource, │ │
+│ │ │ address) │ │
+│ └────► run handler ◄──────┴────────┬───────────┘ │
+│ │ │ │
+│ │ true │ true │
+│ ▼ ▼ │
+│ 200 + JSON / binary │
+└───────────────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+ siwx_payments + siwx_nonces (Neon Postgres)
+```
+
+## Architecture
+
+### 1. Persistence — Neon Postgres (`api/_lib/migrations/2026-05-21-siwx.sql`)
+
+Two tables:
+
+- `siwx_payments(resource, address, network, payer_chain, paid_at, expires_at)`
+ — one row per `(resource, address)`. `expires_at` NULL = permanent grant
+ (downloadable assets). Set to `now() + INTERVAL` for time-pass access.
+- `siwx_nonces(nonce, resource, address, used_at)` — replay protection.
+ Indexed on `used_at` for the GC job.
+
+Why Neon and not Vercel KV: we already use Neon for `agent_skill_prices`,
+`skill_purchases`, etc. — same connection pool, transactional, queryable from
+the marketplace UI without a second store.
+
+### 2. Storage adapter (`api/_lib/siwx-storage.js`)
+
+Implements the `SIWxStorage` interface from `@x402/extensions/sign-in-with-x`:
+
+```js
+{
+ hasPaid(resource, address) → boolean
+ recordPayment(resource, address, { network, ttlSeconds? }) → void
+ hasUsedNonce(nonce) → boolean
+ recordNonce(nonce, { resource, address }) → void
+}
+```
+
+Pure SQL via `sql` from [api/_lib/db.js](../../api/_lib/db.js). Address
+normalization: lowercased for EVM (CAIP `eip155:*`), Base58 for Solana.
+
+### 3. `paidEndpoint()` integration (`api/_lib/x402-paid-endpoint.js`)
+
+Each endpoint opts in by adding `siwx: { statement, ttlSeconds? }` to its
+`paidEndpoint(spec)` call. The helper then:
+
+1. **On every request** — declares the `sign-in-with-x` extension in the 402
+ body (`declareSIWxExtension`), using nonces & timestamps refreshed per
+ request.
+2. **When `SIGN-IN-WITH-X` header is present (no `X-PAYMENT`)** — parses /
+ validates / verifies via the upstream `@x402/extensions/sign-in-with-x`
+ helpers. If signature is valid, the wallet has paid, and the nonce is
+ fresh → run handler, skip facilitator settlement, no `X-PAYMENT-RESPONSE`
+ header. Mark nonce used.
+3. **When `X-PAYMENT` settles successfully** — call
+ `storage.recordPayment(resource, payer, { network, ttlSeconds })` from the
+ existing settle path. This is the only place we mutate `siwx_payments`.
+
+For EVM smart-wallet support (Coinbase Smart Wallet / Safe), pass
+`publicClient.verifyMessage` from viem as `verifyOptions.evmVerifier`. The
+public client uses our own RPC URL (`env.BASE_RPC_URL`), not a public endpoint.
+
+### 4. Endpoints to wire (initial batch)
+
+| Route | Why | TTL |
+|---|---|---|
+| `/api/x402/skill-marketplace` | Buyers refresh the catalog without paying every poll | 24h |
+| `/api/x402/dance-tip` | Tipper re-watches their performance from /club | permanent (per dancer+style) |
+| `/api/x402/asset-download` *(new)* | Canonical "buy once, re-download forever" example for GLB / avatar / accessory files served from R2 | permanent |
+| `/api/x402/skill-marketplace` (auth-only mode) | Logged-in buyer page | n/a |
+
+### 5. Browser modal (`public/x402.js`)
+
+The existing payment modal already drives `window.ethereum` (Base USDC) and
+Phantom (Solana SPL). We extend it to:
+
+- On 402, inspect `extensions['sign-in-with-x']`. If present **and** the
+ buyer's connected wallet was previously used here (best-effort hint), offer
+ "Sign in with wallet" as the **first** option.
+- If the user signs and the retry returns 200 → done.
+- If it returns 402 again (wallet not in storage) → fall back to the normal
+ pay-with-USDC flow.
+- For agents: nothing to do; `@x402/fetch` + `wrapFetchWithSIWx` handles this
+ automatically when both extension and signer are present.
+
+### 6. Cron GC (`api/cron/siwx-gc.js` + `vercel.json`)
+
+A daily Vercel cron prunes:
+
+- `siwx_nonces` rows older than 10 minutes (replay window ≪ `maxAge` of
+ `validateSIWxMessage`).
+- `siwx_payments` rows with `expires_at < now() - INTERVAL '7 days'`
+ (grace window so a slow client doesn't lose access mid-session).
+
+### 7. Verification
+
+End-to-end test plan in `07-verify-end-to-end.md`:
+
+1. Manual `curl` dance: pay → header → 402 with extension → sign → 200.
+2. Browser dance on `/club`: tip dancer, refresh page, re-trigger without
+ second pay.
+3. Agent dance via `agent-payments-sdk` script: prove `wrapFetchWithSIWx`
+ path works end-to-end.
+
+## Out of scope (deliberately, for v1)
+
+- Cross-resource access tokens (one signature granting access to many routes).
+ Each `(resource, address)` pair is independent. Bundling can come later.
+- Off-the-shelf JWT issuance. SIWX is the credential; we don't reissue.
+- Wallet-only registration (account creation) — SIWX here is **access
+ control**, not identity. A future prompt can layer ERC-8004 identity on top.
+
+## Conventions every prompt follows
+
+- **CLAUDE.md rails** — no mocks, no TODOs, no stubs, no commented-out code,
+ no fake data, no fallback sample arrays. Real Neon writes, real wallets,
+ real signatures.
+- **Definition of done** — code wired into the existing path, dev server
+ spun up, manually exercised in browser **or** via real `curl`/agent
+ script, `npm test` green, `git diff` reviewed.
+- **Push** — only on user request, to both `origin` and `threews`.
+
+## Run order
+
+| # | Prompt | Depends on |
+|---|---|---|
+| 1 | [01-db-schema.md](01-db-schema.md) | — |
+| 2 | [02-storage-adapter.md](02-storage-adapter.md) | 1 |
+| 3 | [03-paid-endpoint-integration.md](03-paid-endpoint-integration.md) | 2 |
+| 4 | [04-wire-endpoints.md](04-wire-endpoints.md) | 3 |
+| 5 | [05-browser-modal.md](05-browser-modal.md) | 3 |
+| 6 | [06-nonce-gc-cron.md](06-nonce-gc-cron.md) | 1 |
+| 7 | [07-verify-end-to-end.md](07-verify-end-to-end.md) | 4, 5 |
+
+Prompts 4, 5, 6 can run in parallel after 3 is merged.
diff --git a/public/x402.js b/public/x402.js
index 4396273ad..bd28e02df 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -60,6 +60,17 @@ function isSolanaNetwork(net) {
function isEvmNetwork(net) {
return typeof net === 'string' && net.startsWith('eip155:');
}
+// The modal only signs EIP-3009 transferWithAuthorization for EVM. When the
+// server publishes both an EIP-3009 entry and a Permit2 sibling (the
+// gas-sponsoring path used by @x402/evm SDK clients), we must pick the
+// EIP-3009 one — signing typed-data against the Permit2 entry would build a
+// payload the facilitator rejects. The sibling carries
+// `extra.assetTransferMethod === 'permit2'`; the legacy entry omits it.
+function isEip3009Accept(accept) {
+ if (!isEvmNetwork(accept?.network)) return false;
+ const method = accept?.extra?.assetTransferMethod;
+ return !method || method === 'eip3009';
+}
function networkLabel(net, accept) {
if (isSolanaNetwork(net)) return 'Solana';
const meta = EVM_NETWORKS[net];
@@ -449,7 +460,7 @@ class CheckoutModal {
const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);
const evmDetected = typeof window !== 'undefined' && window.ethereum;
const solanaAccept = this.challenge?.accepts.find((a) => isSolanaNetwork(a.network));
- const evmAccept = this.challenge?.accepts.find((a) => isEvmNetwork(a.network));
+ const evmAccept = this.challenge?.accepts.find(isEip3009Accept);
const buttons = [];
if (solanaAccept) {
buttons.push(`
diff --git a/scripts/set-r2-cors.mjs b/scripts/set-r2-cors.mjs
new file mode 100644
index 000000000..c7ba62fff
--- /dev/null
+++ b/scripts/set-r2-cors.mjs
@@ -0,0 +1,139 @@
+#!/usr/bin/env node
+/**
+ * Apply the canonical CORS policy to the R2 bucket backing all media.
+ *
+ * Why this exists: <model-viewer>, fetch(), and the avatar upload flow all
+ * hit R2 from the browser. Without a CORS policy the public r2.dev host
+ * returns no Access-Control-Allow-Origin header and every cross-origin
+ * read (or presigned PUT) fails. Symptom: empty marketplace previews,
+ * broken upload modals, console flooded with `ERR_FAILED`.
+ *
+ * Two rules:
+ * 1. Read — GET/HEAD of GLBs, thumbnails, posters from web origins.
+ * 2. Write — PUT of presigned uploads from the same web origins.
+ *
+ * Usage:
+ * # Pull production R2 creds into .env, then run.
+ * vercel env pull .env
+ * node scripts/set-r2-cors.mjs # apply (idempotent)
+ * node scripts/set-r2-cors.mjs --get # show what's live
+ * node scripts/set-r2-cors.mjs --dry-run # print the policy, don't push
+ *
+ * Requires the same env as the API: S3_ENDPOINT, S3_ACCESS_KEY_ID,
+ * S3_SECRET_ACCESS_KEY, S3_BUCKET. R2 implements the S3 PutBucketCors
+ * API verbatim, so this script also works against AWS S3 and B2.
+ */
+
+import {
+ S3Client,
+ GetBucketCorsCommand,
+ PutBucketCorsCommand,
+} from '@aws-sdk/client-s3';
+import { readFileSync, existsSync } from 'node:fs';
+
+// Lightweight .env loader so this runs standalone without dotenv as a dep.
+loadDotenv('.env');
+
+const required = ['S3_ENDPOINT', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'S3_BUCKET'];
+const missing = required.filter((k) => !process.env[k]);
+if (missing.length) {
+ console.error(`Missing env: ${missing.join(', ')}`);
+ console.error('Hint: run `vercel env pull .env` first.');
+ process.exit(1);
+}
+
+// Web origins allowed to read assets from R2 and to PUT uploads via presigned
+// URLs. Keep this list authoritative — any origin not listed will be blocked
+// by the browser even if the URL itself is correct.
+const ALLOWED_ORIGINS = [
+ 'https://three.ws',
+ 'https://www.three.ws',
+ 'https://3d-agent.vercel.app',
+ 'http://localhost:3000',
+ 'http://localhost:5173',
+];
+
+const POLICY = {
+ CORSRules: [
+ {
+ ID: 'public-read',
+ AllowedOrigins: ALLOWED_ORIGINS,
+ AllowedMethods: ['GET', 'HEAD'],
+ AllowedHeaders: ['*'],
+ ExposeHeaders: ['ETag', 'Content-Length', 'Content-Type', 'Accept-Ranges'],
+ MaxAgeSeconds: 86400,
+ },
+ {
+ ID: 'browser-upload',
+ AllowedOrigins: ALLOWED_ORIGINS,
+ AllowedMethods: ['PUT'],
+ AllowedHeaders: ['*'],
+ ExposeHeaders: ['ETag'],
+ MaxAgeSeconds: 3600,
+ },
+ ],
+};
+
+const flag = (name) => process.argv.includes(name);
+
+const s3 = new S3Client({
+ region: 'auto',
+ endpoint: process.env.S3_ENDPOINT,
+ credentials: {
+ accessKeyId: process.env.S3_ACCESS_KEY_ID,
+ secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
+ },
+});
+
+const Bucket = process.env.S3_BUCKET;
+
+if (flag('--get')) {
+ const current = await getCors();
+ console.log(JSON.stringify(current, null, 2));
+ process.exit(0);
+}
+
+if (flag('--dry-run')) {
+ console.log('Would apply to bucket:', Bucket);
+ console.log(JSON.stringify(POLICY, null, 2));
+ process.exit(0);
+}
+
+const before = await getCors();
+await s3.send(new PutBucketCorsCommand({ Bucket, CORSConfiguration: POLICY }));
+const after = await getCors();
+
+if (JSON.stringify(before) === JSON.stringify(after)) {
+ console.log(`CORS policy on ${Bucket} unchanged (already current).`);
+} else {
+ console.log(`Applied CORS policy to ${Bucket}.`);
+ console.log('Rules:', after.CORSRules.map((r) => `${r.ID || '(no id)'} → ${r.AllowedMethods.join(',')}`).join(' | '));
+}
+
+async function getCors() {
+ try {
+ const r = await s3.send(new GetBucketCorsCommand({ Bucket }));
+ return { CORSRules: r.CORSRules || [] };
+ } catch (err) {
+ if (err?.name === 'NoSuchCORSConfiguration' || err?.$metadata?.httpStatusCode === 404) {
+ return { CORSRules: [] };
+ }
+ throw err;
+ }
+}
+
+function loadDotenv(path) {
+ if (!existsSync(path)) return;
+ const text = readFileSync(path, 'utf8');
+ for (const line of text.split('\n')) {
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
+ if (!m) continue;
+ const [, key, rawVal] = m;
+ if (process.env[key]) continue;
+ let val = rawVal;
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
+ val = val.slice(1, -1);
+ }
+ process.env[key] = val;
+ }
+}
diff --git a/scripts/x402-all.mjs b/scripts/x402-all.mjs
new file mode 100644
index 000000000..088aab8db
--- /dev/null
+++ b/scripts/x402-all.mjs
@@ -0,0 +1,144 @@
+// Exercise every paid x402 endpoint on three.ws end-to-end from a funded EVM
+// wallet on Base. For each endpoint: GET the 402 challenge, sign the EIP-3009
+// TransferWithAuthorization, retry with X-PAYMENT, capture the response +
+// settlement receipt. Prints a summary table at the end.
+//
+// Costs are billed in USDC on Base (eip155:8453) — the funded vanity wallet
+// 0x33369135724F53521dF38e69262792a1EC068cd7 holds the USDC; the facilitator
+// covers ETH gas. The handler runs BEFORE settle, so a 4xx from the route's
+// validation logic means no USDC was moved.
+
+import { Wallet, randomBytes, hexlify } from 'ethers';
+
+const PRIVATE_KEY = '0x5e306b436ea9cf2e9840eb9922094cc4a32beebc23588a8856ab75aab3f3f7b5';
+const BASE = 'https://three.ws';
+const wallet = new Wallet(PRIVATE_KEY);
+
+const ENDPOINTS = [
+ { name: 'model-check', path: '/api/x402/model-check?url=https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb', method: 'GET' },
+ { name: 'dance-tip', path: '/api/x402/dance-tip?dancer=1&dance=rumba', method: 'GET' },
+ { name: 'skill-marketplace', path: '/api/x402/skill-marketplace?skill=inspect_model&limit=5', method: 'GET' },
+ { name: 'symbol-availability', path: '/api/x402/symbol-availability?ticker=HELIO&network=mainnet', method: 'GET' },
+ { name: 'onchain-identity-verify',path: '/api/x402/onchain-identity-verify?address=0x33369135724F53521dF38e69262792a1EC068cd7', method: 'GET' },
+ { name: 'agent-reputation', path: '/api/x402/agent-reputation?agent_id=7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55', method: 'GET' },
+ { name: 'pump-agent-audit', path: '/api/x402/pump-agent-audit?mint=C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi', method: 'GET' },
+ { name: 'mint-to-mesh', path: '/api/x402/mint-to-mesh?mint=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263', method: 'GET' },
+ { name: 'mint-to-mesh-batch', path: '/api/x402/mint-to-mesh-batch', method: 'POST', body: { mints: ['DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263'] } },
+];
+
+const results = [];
+
+function fmtAmount(atomics) {
+ return '$' + (Number(atomics) / 1_000_000).toFixed(3);
+}
+
+async function callOne({ name, path, method, body }) {
+ const url = `${BASE}${path}`;
+ // Step 1: 402 challenge.
+ const headers0 = { accept: 'application/json' };
+ if (method === 'POST') headers0['content-type'] = 'application/json';
+ const init0 = { method, headers: headers0, cache: 'no-store' };
+ if (body) init0.body = JSON.stringify(body);
+ const r0 = await fetch(url, init0);
+ if (r0.status !== 402) {
+ return { name, ok: false, step: 'challenge', status: r0.status, detail: (await r0.text()).slice(0, 200) };
+ }
+ const challenge = JSON.parse(Buffer.from(r0.headers.get('payment-required'), 'base64').toString());
+ const accept = challenge.accepts.find((a) => a.network === 'eip155:8453' && a.scheme === 'exact');
+ if (!accept) return { name, ok: false, step: 'no-base-accept', detail: 'endpoint does not advertise Base mainnet exact' };
+
+ // Step 2: sign EIP-3009.
+ const now = Math.floor(Date.now() / 1000);
+ const authorization = {
+ from: wallet.address,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter: String(now - 600),
+ validBefore: String(now + Math.max(60, accept.maxTimeoutSeconds || 60)),
+ nonce: hexlify(randomBytes(32)),
+ };
+ const domain = { name: accept.extra.name, version: accept.extra.version, chainId: 8453, verifyingContract: accept.asset };
+ const types = {
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+ };
+ const signature = await wallet.signTypedData(domain, types, authorization);
+ const payment = {
+ x402Version: 2,
+ payload: { authorization, signature },
+ extensions: challenge.extensions || {},
+ resource: challenge.resource,
+ accepted: accept,
+ };
+ const xPayment = Buffer.from(JSON.stringify(payment)).toString('base64');
+
+ // Step 3: retry with X-PAYMENT.
+ const init1 = { method, headers: { ...headers0, 'X-PAYMENT': xPayment }, cache: 'no-store' };
+ if (body) init1.body = JSON.stringify(body);
+ const r1 = await fetch(url, init1);
+ const xpr = r1.headers.get('x-payment-response');
+ let receipt = null;
+ if (xpr) {
+ try { receipt = JSON.parse(Buffer.from(xpr, 'base64').toString()); } catch {}
+ }
+ let respBody = null;
+ const ct = r1.headers.get('content-type') || '';
+ if (ct.includes('json')) {
+ try { respBody = await r1.json(); } catch { respBody = null; }
+ } else {
+ respBody = (await r1.text()).slice(0, 200);
+ }
+ return {
+ name,
+ ok: r1.status === 200,
+ status: r1.status,
+ priceAtomics: accept.amount,
+ priceUsd: fmtAmount(accept.amount),
+ tx: receipt?.transaction || null,
+ payer: receipt?.payer || null,
+ body: respBody,
+ };
+}
+
+console.log('Payer wallet :', wallet.address);
+console.log('Network : Base mainnet (eip155:8453)');
+console.log('');
+
+let totalCharged = 0n;
+for (const ep of ENDPOINTS) {
+ process.stdout.write(`→ ${ep.name.padEnd(28)} `);
+ try {
+ const r = await callOne(ep);
+ results.push(r);
+ const tag = r.ok ? 'OK ' : 'FAIL';
+ const tx = r.tx ? r.tx.slice(0, 10) + '…' : '(no settle)';
+ console.log(`${tag} status=${r.status} price=${r.priceUsd ?? '-'} tx=${tx}`);
+ if (r.ok && r.priceAtomics) totalCharged += BigInt(r.priceAtomics);
+ if (!r.ok) {
+ console.log(` body: ${typeof r.body === 'object' ? JSON.stringify(r.body).slice(0, 240) : String(r.body).slice(0, 240)}`);
+ }
+ } catch (err) {
+ results.push({ name: ep.name, ok: false, step: 'exception', detail: err.message });
+ console.log(`EXCEPTION ${err.message}`);
+ }
+ await new Promise((r) => setTimeout(r, 800)); // gentle pacing
+}
+
+console.log('\n=== Summary ===');
+console.log(`Endpoints tested : ${ENDPOINTS.length}`);
+console.log(`Successful (200) : ${results.filter((r) => r.ok).length}`);
+console.log(`Settled USDC : $${(Number(totalCharged) / 1_000_000).toFixed(6)} (${totalCharged} atomic)`);
+console.log('');
+for (const r of results) {
+ const status = r.ok ? '✓' : '✗';
+ const summary = r.ok
+ ? (typeof r.body === 'object' ? Object.keys(r.body || {}).slice(0, 6).join(',') : '')
+ : (r.step || `status=${r.status}`);
+ console.log(` ${status} ${r.name.padEnd(28)} ${r.priceUsd?.padStart(8) || ' -'} ${summary}`);
+}
diff --git a/vercel.json b/vercel.json
index 233d9910f..e53c56daa 100644
--- a/vercel.json
+++ b/vercel.json
@@ -225,6 +225,10 @@
"src": "/pose/?",
"dest": "/pose.html"
},
+ {
+ "src": "/club/?",
+ "dest": "/club.html"
+ },
{
"src": "/walkaround/?",
"dest": "/demos/walkaround.html"
diff --git a/x402-buildout/PLAN.md b/x402-buildout/PLAN.md
new file mode 100644
index 000000000..b5bf0f5d1
--- /dev/null
+++ b/x402-buildout/PLAN.md
@@ -0,0 +1,195 @@
+# x402 Buildout Plan
+
+Comprehensive plan to wire every use case documented in [x402-foundation/x402](https://github.com/x402-foundation/x402) into this codebase, end-to-end, professionally, with no mocks.
+
+## Source material
+
+- v2 spec: `specs/x402-specification-v2.md`
+- Transports (v2): `specs/transports-v2/{http,mcp,a2a}.md`
+- Schemes: `specs/schemes/{exact,upto,batch-settlement,auth-capture}/`
+- Extensions: `specs/extensions/`
+- Developer docs: `docs/` (Mintlify source for docs.x402.org)
+- Project ideas: `PROJECT-IDEAS.md`
+
+Local clone of source: `/tmp/x402-docs/`.
+
+## Conventions across every prompt
+
+Every prompt assumes the operating rules in [CLAUDE.md](../CLAUDE.md):
+
+- No mocks, fake data, placeholders, TODOs, or stubs.
+- Real APIs only. Real network calls. Real signatures. Real on-chain settlement on configured networks.
+- UI work must be exercised in a real browser. Server work must be exercised with `curl` or a real client.
+- Push to BOTH `origin` and `threews` after merges.
+- Use real env vars from `.env` (or `vercel env`). If a secret is missing, surface it once and stop — never invent.
+
+Each prompt ends with an **Acceptance** checklist. A use case is not done until every box is ticked.
+
+## Layout
+
+```
+x402-buildout/
+├── PLAN.md # this file
+└── prompts/
+ ├── 00-foundation-packages.md
+ ├── 01-facilitator-client.md
+ ├── 02-seller-exact-evm.md
+ ├── 03-seller-exact-svm.md
+ ├── 04-seller-upto-evm.md
+ ├── 05-seller-batch-evm.md
+ ├── 06-buyer-fetch-multinetwork.md
+ ├── 07-buyer-axios.md
+ ├── 08-buyer-upto.md
+ ├── 09-buyer-batch.md
+ ├── 10-mcp-server.md
+ ├── 11-mcp-client.md
+ ├── 12-a2a-transport.md
+ ├── 13-bazaar-server-listing.md
+ ├── 14-bazaar-discovery-client.md
+ ├── 15-payment-identifier.md
+ ├── 16-sign-in-with-x.md
+ ├── 17-offer-receipt.md
+ ├── 18-gas-sponsoring-eip2612.md
+ ├── 19-gas-sponsoring-erc20-approval.md
+ ├── 20-builder-code.md
+ ├── 21-auth-hints.md
+ ├── 22-spending-limits.md
+ ├── 23-api-key-bypass.md
+ ├── 24-audit-logging.md
+ ├── 25-idempotency-cache.md
+ ├── 26-self-hosted-facilitator.md
+ ├── 27-paywall-ui.md
+ ├── 28-e2e-tests.md
+ ├── 29-wealth-manager.md
+ ├── 30-prediction-oracle.md
+ ├── 31-kyc-checker.md
+ ├── 32-fact-checker.md
+ ├── 33-tutor.md
+ ├── 34-bounty-hunter.md
+ ├── 35-consultant-booking.md
+ ├── 36-endpoint-shopper.md
+ ├── 37-crypto-shopper.md
+ ├── 38-bounty-poster.md
+ ├── 39-weather-donations.md
+ └── 40-unstoppable-agent.md
+```
+
+## Build order (dependency-respecting)
+
+### Phase 1 — Foundation
+Required by every other phase.
+
+| # | File | Goal |
+|---|---|---|
+| 00 | [foundation-packages.md](prompts/00-foundation-packages.md) | Install SDKs, set up env, shared signers |
+| 01 | [facilitator-client.md](prompts/01-facilitator-client.md) | Unified facilitator client (testnet + mainnet, EVM + SVM) |
+
+### Phase 2 — Sellers (resource servers)
+Servers that accept payment.
+
+| # | File | Scheme / Network |
+|---|---|---|
+| 02 | [seller-exact-evm.md](prompts/02-seller-exact-evm.md) | `exact` on Base, Base Sepolia |
+| 03 | [seller-exact-svm.md](prompts/03-seller-exact-svm.md) | `exact` on Solana, Solana Devnet |
+| 04 | [seller-upto-evm.md](prompts/04-seller-upto-evm.md) | `upto` (usage-metered) on Base |
+| 05 | [seller-batch-evm.md](prompts/05-seller-batch-evm.md) | `batch-settlement` channels with Redis storage |
+
+### Phase 3 — Buyers (clients)
+Clients that auto-pay.
+
+| # | File | Surface |
+|---|---|---|
+| 06 | [buyer-fetch-multinetwork.md](prompts/06-buyer-fetch-multinetwork.md) | Wrapped `fetch` for EVM + SVM |
+| 07 | [buyer-axios.md](prompts/07-buyer-axios.md) | Wrapped `axios` interceptor |
+| 08 | [buyer-upto.md](prompts/08-buyer-upto.md) | `upto`-aware client |
+| 09 | [buyer-batch.md](prompts/09-buyer-batch.md) | `batch-settlement` client with persistent channel state |
+
+### Phase 4 — Transports
+Beyond HTTP.
+
+| # | File | Transport |
+|---|---|---|
+| 10 | [mcp-server.md](prompts/10-mcp-server.md) | Paid MCP server (Claude Desktop + Cursor compatible) |
+| 11 | [mcp-client.md](prompts/11-mcp-client.md) | Auto-paying MCP client |
+| 12 | [a2a-transport.md](prompts/12-a2a-transport.md) | Agent-to-Agent x402 extension |
+
+### Phase 5 — Extensions
+Optional capabilities that compose into payment lifecycle.
+
+| # | File | Extension |
+|---|---|---|
+| 13 | [bazaar-server-listing.md](prompts/13-bazaar-server-listing.md) | Publish endpoints to Bazaar discovery |
+| 14 | [bazaar-discovery-client.md](prompts/14-bazaar-discovery-client.md) | Search/list Bazaar from buyer |
+| 15 | [payment-identifier.md](prompts/15-payment-identifier.md) | Idempotency keys |
+| 16 | [sign-in-with-x.md](prompts/16-sign-in-with-x.md) | CAIP-122 returning customer auth |
+| 17 | [offer-receipt.md](prompts/17-offer-receipt.md) | Signed offers + receipts (EIP-712 + JWS) |
+| 18 | [gas-sponsoring-eip2612.md](prompts/18-gas-sponsoring-eip2612.md) | EIP-2612 gasless Permit2 |
+| 19 | [gas-sponsoring-erc20-approval.md](prompts/19-gas-sponsoring-erc20-approval.md) | Universal gasless ERC-20 approval |
+| 20 | [builder-code.md](prompts/20-builder-code.md) | ERC-8021 calldata attribution |
+| 21 | [auth-hints.md](prompts/21-auth-hints.md) | Signal OAuth2 / SIWX before payment |
+
+### Phase 6 — Hooks & Ops
+Production operability.
+
+| # | File | Capability |
+|---|---|---|
+| 22 | [spending-limits.md](prompts/22-spending-limits.md) | Client `onBeforePaymentCreation` caps |
+| 23 | [api-key-bypass.md](prompts/23-api-key-bypass.md) | Server `onProtectedRequest` subscriber bypass |
+| 24 | [audit-logging.md](prompts/24-audit-logging.md) | `onAfterSettle` durable ledger |
+| 25 | [idempotency-cache.md](prompts/25-idempotency-cache.md) | Combined client+server idempotency |
+| 26 | [self-hosted-facilitator.md](prompts/26-self-hosted-facilitator.md) | Run our own `/verify`, `/settle`, `/supported` |
+| 27 | [paywall-ui.md](prompts/27-paywall-ui.md) | Browser paywall UI |
+| 28 | [e2e-tests.md](prompts/28-e2e-tests.md) | End-to-end tests against real testnets |
+
+### Phase 7 — Productized agents
+Concrete consumer apps from `PROJECT-IDEAS.md`, wired to this repo's 3D-agent stack.
+
+| # | File | Agent |
+|---|---|---|
+| 29 | [wealth-manager.md](prompts/29-wealth-manager.md) | Trading bot paying per-fetch + per-trade |
+| 30 | [prediction-oracle.md](prompts/30-prediction-oracle.md) | Prediction-market resolver |
+| 31 | [kyc-checker.md](prompts/31-kyc-checker.md) | Per-check sanctions / KYT screen |
+| 32 | [fact-checker.md](prompts/32-fact-checker.md) | Real-time claim verifier |
+| 33 | [tutor.md](prompts/33-tutor.md) | Pay-as-you-learn tutor |
+| 34 | [bounty-hunter.md](prompts/34-bounty-hunter.md) | Auto-completes bounties for reward |
+| 35 | [consultant-booking.md](prompts/35-consultant-booking.md) | Books and pays for expert calls |
+| 36 | [endpoint-shopper.md](prompts/36-endpoint-shopper.md) | Bazaar-driven dynamic endpoint chaining |
+| 37 | [crypto-shopper.md](prompts/37-crypto-shopper.md) | Cart checkout via crypto |
+| 38 | [bounty-poster.md](prompts/38-bounty-poster.md) | Auto-outsources tasks via bounty platforms |
+| 39 | [weather-donations.md](prompts/39-weather-donations.md) | Trigger-based donations |
+| 40 | [unstoppable-agent.md](prompts/40-unstoppable-agent.md) | Self-funding agent provisioning its own infra |
+
+## Cross-cutting touchpoints
+
+These ship with every paid endpoint:
+
+- `vercel.json` — register the route (existing `functions` wildcard covers `api/**/*.js`, but well-known paths and custom rewrites must be added).
+- `.env.example` — every new env var documented.
+- `public/x402.js` — UI surface for client-side flows.
+- `api/_lib/x402.js` — shared helpers (already exists; extend, don't fork).
+- `data/archives/` and `data/rss/` — discovery and feed integrations where relevant.
+
+## How to execute
+
+Each prompt is self-contained. To pick one up:
+
+1. Read the prompt fully.
+2. Read every linked spec/doc.
+3. Build only what the prompt asks for. Do not invent surrounding scope.
+4. Wire it through the full stack (server, client, UI if relevant, env, vercel.json).
+5. Run the dev server. Exercise the path. Capture the result in the Acceptance checklist.
+6. Commit. Push to BOTH remotes.
+
+## Status tracking
+
+Track progress by editing the checkboxes in each prompt's **Acceptance** section. Roll up status here when finishing a phase.
+
+| Phase | Status |
+|---|---|
+| 1 Foundation | not started |
+| 2 Sellers | not started |
+| 3 Buyers | not started |
+| 4 Transports | not started |
+| 5 Extensions | not started |
+| 6 Hooks & Ops | not started |
+| 7 Productized agents | not started |
diff --git a/x402-buildout/prompts/00-foundation-packages.md b/x402-buildout/prompts/00-foundation-packages.md
new file mode 100644
index 000000000..625e0f3f5
--- /dev/null
+++ b/x402-buildout/prompts/00-foundation-packages.md
@@ -0,0 +1,75 @@
+# USE-00: Foundation — Packages, Env, Shared Signers
+
+## Goal
+Stand up the v2 x402 SDK foundation that every other use case depends on: package install, env vars, shared EVM + SVM signer factories, single `x402.js` helper module.
+
+## Why
+The existing `api/_lib/x402.js`, `x402-spec.js`, `x402-paid-endpoint.js` predate the v2 SDK. Before we expand, every other prompt needs:
+- `@x402/core`, `@x402/evm`, `@x402/svm`, `@x402/express`, `@x402/extensions`, `@x402/fetch`, `@x402/axios` installed
+- Signers constructed from `EVM_PRIVATE_KEY` and `SVM_PRIVATE_KEY` / `EVM_PAYMENT_PRIVATE_KEY` etc.
+- A single `getFacilitatorClient()` and `getResourceServer()` factory the rest of the codebase shares.
+
+## Reference
+- v2 spec: [/tmp/x402-docs/specs/x402-specification-v2.md](/tmp/x402-docs/specs/x402-specification-v2.md)
+- Quickstart: [/tmp/x402-docs/docs/getting-started/quickstart-for-sellers.mdx](/tmp/x402-docs/docs/getting-started/quickstart-for-sellers.mdx)
+- Existing wiring: [api/_lib/x402.js](../../api/_lib/x402.js), [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js), [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js)
+
+## Dependencies
+None — this is the root.
+
+## Files to create
+- `api/_lib/x402/sdk.js` — exports `getEvmSigner()`, `getSvmSigner()`, `getFacilitatorClient()`, `getResourceServer()`, `getEvmAddress()`, `getSvmAddress()`, network constants
+- `api/_lib/x402/networks.js` — CAIP-2 constants for every network we use (`eip155:8453`, `eip155:84532`, `solana:5eykt4Us...`, `solana:EtWTRABZ...`)
+- `api/_lib/x402/signers.js` — reads private keys from env, returns viem account / `@solana/kit` signer
+
+## Files to modify
+- `package.json` — add SDK deps
+- `.env.example` (create if missing) — `EVM_PRIVATE_KEY`, `SVM_PRIVATE_KEY`, `EVM_PAYMENT_ADDRESS`, `SVM_PAYMENT_ADDRESS`, `X402_FACILITATOR_URL`
+- `vercel.json` — ensure `node_modules/@x402/**` is in function `includeFiles`
+
+## Implementation
+
+### 1. Install packages
+```bash
+npm install @x402/core @x402/evm @x402/svm @x402/express @x402/extensions @x402/fetch @x402/axios viem @solana/kit @scure/base
+```
+
+Keep `serialize-javascript` override in place.
+
+### 2. `api/_lib/x402/networks.js`
+Export constants only. No env access in this file.
+- `BASE_MAINNET = "eip155:8453"`
+- `BASE_SEPOLIA = "eip155:84532"`
+- `SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"`
+- `SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"`
+- `DEFAULT_EVM_NETWORK` = mainnet when `NODE_ENV === "production"`, sepolia otherwise
+- `DEFAULT_SVM_NETWORK` = mainnet in prod, devnet otherwise
+- `FACILITATOR_URL_TESTNET = "https://x402.org/facilitator"`
+- `FACILITATOR_URL_MAINNET` from `process.env.X402_FACILITATOR_URL` (default `https://api.cdp.coinbase.com/platform/v2/x402`)
+
+### 3. `api/_lib/x402/signers.js`
+- `getEvmSigner()` — `privateKeyToAccount(process.env.EVM_PRIVATE_KEY)`. Throw clear error if missing.
+- `getSvmSigner()` — `createKeyPairSignerFromBytes(base58.decode(process.env.SVM_PRIVATE_KEY))`. Returns a Promise.
+- `getEvmAddress()` — `process.env.EVM_PAYMENT_ADDRESS` (where the resource server receives funds).
+- `getSvmAddress()` — `process.env.SVM_PAYMENT_ADDRESS`.
+
+### 4. `api/_lib/x402/sdk.js`
+- `getFacilitatorClient({ mainnet } = {})` returns `new HTTPFacilitatorClient({ url })`.
+- `getResourceServer({ networks = ["evm", "svm"], mainnet } = {})` builds a `new x402ResourceServer(getFacilitatorClient(...))` and registers `ExactEvmScheme()` and/or `ExactSvmScheme()` against the right CAIP-2 networks.
+- All exports are singletons cached per-process (these are stateless and safe).
+
+### 5. Update `api/_lib/x402.js`
+Re-export from `./x402/sdk.js` so existing callers continue to work while new code points at the v2 helpers. Do NOT silently remove old fields used by existing endpoints — read what's there first, then add.
+
+## Wiring checklist
+- [ ] `npm install` succeeds and `node -e "import('@x402/core')"` resolves
+- [ ] `.env.example` lists every new variable with one-line description
+- [ ] `vercel.json` `includeFiles` updated for `@x402/**` packages
+- [ ] `api/_lib/x402.js` continues to export everything the existing `api/x402-*.js` endpoints depend on (verify by grepping the codebase)
+- [ ] `getResourceServer()` registered for both `eip155:*` and `solana:*` namespaces
+
+## Acceptance
+- [ ] `node --eval "import('./api/_lib/x402/sdk.js').then(m => console.log(Object.keys(m)))"` prints every export
+- [ ] `curl -X GET https://x402.org/facilitator/supported` succeeds and parses
+- [ ] No existing `api/x402-*.js` endpoint regresses (smoke-test each that's wired)
+- [ ] Committed to a branch; PR opened against `main`
diff --git a/x402-buildout/prompts/01-facilitator-client.md b/x402-buildout/prompts/01-facilitator-client.md
new file mode 100644
index 000000000..7db1126da
--- /dev/null
+++ b/x402-buildout/prompts/01-facilitator-client.md
@@ -0,0 +1,64 @@
+# USE-01: Unified Facilitator Client
+
+## Goal
+Wrap `HTTPFacilitatorClient` with our own caching, failover, and observability layer so every paid endpoint in this repo uses a single facilitator entry point.
+
+## Why
+- Facilitators differ by network (x402.org for testnet, CDP / PayAI / self-hosted for mainnet).
+- We need a single place to swap between them, add timeouts, retries, and log every `/verify` and `/settle` call for audit.
+- Downstream prompts (sellers, buyers, hooks) all consume this client.
+
+## Reference
+- Facilitator interface: [/tmp/x402-docs/specs/x402-specification-v2.md §7](/tmp/x402-docs/specs/x402-specification-v2.md)
+- Facilitator concept doc: [/tmp/x402-docs/docs/core-concepts/facilitator.md](/tmp/x402-docs/docs/core-concepts/facilitator.md)
+- Networks: [/tmp/x402-docs/docs/core-concepts/network-and-token-support.mdx](/tmp/x402-docs/docs/core-concepts/network-and-token-support.mdx)
+
+## Dependencies
+- USE-00 (foundation)
+
+## Files to create
+- `api/_lib/x402/facilitator.js` — `class X402Facilitator { verify(), settle(), supported(), discovery() }`
+- `api/_lib/x402/facilitator-routes.js` — routing layer that selects facilitator URL by `(scheme, network)` tuple
+- `api/x402-facilitator-supported.js` — HTTP endpoint that proxies our resolved facilitator's `/supported` for clients
+
+## Files to modify
+- `api/_lib/x402/sdk.js` — `getFacilitatorClient()` returns our wrapper instead of raw `HTTPFacilitatorClient`
+- `.env.example` — add `X402_FACILITATOR_TIMEOUT_MS`, `X402_FACILITATOR_MAINNET_URL`, `X402_FACILITATOR_TESTNET_URL`
+
+## Implementation
+
+### `X402Facilitator` API surface
+```
+new X402Facilitator({ url, timeoutMs, onCall })
+ .verify({ paymentPayload, paymentRequirements }) → VerifyResponse
+ .settle({ paymentPayload, paymentRequirements }) → SettlementResponse
+ .supported() → SupportedResponse
+ .discovery({ type, scheme, network, extensions, limit, offset })
+ .search({ query, type })
+```
+
+- Wrap the underlying `HTTPFacilitatorClient` from `@x402/core`.
+- Add `AbortController` for `timeoutMs` (default 30000).
+- Wrap every call in `onCall({ method, url, request, response, durationMs, error })` for audit logging — consumers wire this to USE-24.
+- Retry once on 502/503/504, never on 4xx.
+
+### Routing rules
+- Production (`NODE_ENV === "production"`): mainnet URL.
+- Otherwise: testnet URL (x402.org).
+- Override per-call via `getFacilitatorClient({ mainnet: true })`.
+- For `batch-settlement`: same routing, but expose `mainnet` knob explicitly (some facilitators don't support all schemes).
+
+### `/api/x402-facilitator-supported` endpoint
+Proxy our resolved facilitator's `/supported` to the browser so `public/x402.js` can list supported `(scheme, network)` tuples without hardcoding.
+
+## Wiring checklist
+- [ ] `api/_lib/x402/facilitator.js` exported and consumed by `getFacilitatorClient()`
+- [ ] `vercel.json` route added for `/api/x402-facilitator-supported`
+- [ ] Browser-side `public/x402.js` calls `/api/x402-facilitator-supported` on init and caches result
+- [ ] Logs every facilitator call to console in dev mode (don't log signatures or private keys)
+
+## Acceptance
+- [ ] `curl http://localhost:3000/api/x402-facilitator-supported` returns supported kinds JSON
+- [ ] `X402Facilitator.verify()` rejects within `timeoutMs` if facilitator stalls (simulate with a `127.0.0.1:1` URL)
+- [ ] Single retry observed in logs when facilitator returns 503
+- [ ] Existing paid endpoints (`api/x402/*.js`) verified — none broken
diff --git a/x402-buildout/prompts/02-seller-exact-evm.md b/x402-buildout/prompts/02-seller-exact-evm.md
new file mode 100644
index 000000000..44ca24ba4
--- /dev/null
+++ b/x402-buildout/prompts/02-seller-exact-evm.md
@@ -0,0 +1,66 @@
+# USE-02: Seller — `exact` scheme on EVM (Base + Base Sepolia)
+
+## Goal
+Stand up a production-grade `exact`-scheme paid endpoint on EVM. The endpoint accepts USDC on Base mainnet (`eip155:8453`) with Base Sepolia (`eip155:84532`) for dev, settles via our facilitator, and uses EIP-3009 by default with Permit2 fallback.
+
+## Why
+`exact` is the default payment scheme. Every other scheme (`upto`, `batch-settlement`) is an extension of this. We must have a clean reference implementation in our repo before layering on extensions.
+
+## Reference
+- Scheme overview: [/tmp/x402-docs/docs/schemes/exact.mdx](/tmp/x402-docs/docs/schemes/exact.mdx)
+- EVM spec: [/tmp/x402-docs/specs/schemes/exact/scheme_exact_evm.md](/tmp/x402-docs/specs/schemes/exact/scheme_exact_evm.md)
+- Quickstart for sellers: [/tmp/x402-docs/docs/getting-started/quickstart-for-sellers.mdx](/tmp/x402-docs/docs/getting-started/quickstart-for-sellers.mdx)
+- Existing endpoint pattern to follow: [api/x402/dance-tip.js](../../api/x402/dance-tip.js)
+
+## Dependencies
+- USE-00 (foundation), USE-01 (facilitator client)
+
+## Files to create
+- `api/x402/exact-evm-demo.js` — Vercel function exposing a paid endpoint
+- `api/_lib/x402/middleware-exact.js` — reusable `paymentMiddleware`-style helper for Vercel functions (Vercel doesn't use Express middleware natively; we build the equivalent)
+
+## Files to modify
+- `api/_lib/x402/sdk.js` — `getResourceServer()` registers `ExactEvmScheme` for `eip155:*`
+- `vercel.json` — route for `/api/x402/exact-evm-demo`
+- `public/x402.js` — add a "Demo: pay $0.001 on Base" button that calls the endpoint with the buyer fetch client
+
+## Implementation
+
+### Vercel-flavored middleware
+Vercel functions are single-handler; `@x402/express` won't work directly. Build the equivalent:
+
+```
+// api/_lib/x402/middleware-exact.js
+export function withExactPayment(routeConfig, handler) {
+ return async function (req, res) {
+ const server = getResourceServer({ mainnet: process.env.NODE_ENV === "production" });
+ const httpServer = new x402HTTPResourceServer(server, { [`${req.method} ${routeConfig.path}`]: routeConfig });
+ return httpServer.handle(req, res, handler);
+ };
+}
+```
+
+Wrap with `withExactPayment({ path, accepts, description, mimeType }, async (req, res) => { ... })`.
+
+### The endpoint
+- Price: `"$0.001"` (1 hundredth of a cent — micropayment demo).
+- Network: dynamic (mainnet in prod, sepolia in dev).
+- `payTo`: `getEvmAddress()` from foundation.
+- On success, return a real payload: structured JSON describing the buyer's payment receipt + a sample resource (e.g., a randomly generated 3D pose seed).
+
+### Tie to the 3D-Agent stack
+Pick a real demo resource. Suggestion: paid pose-seed generator — `/api/x402/exact-evm-demo?prompt=ballerina` returns `{ seed, parameters, preview }` that `pose-studio` can consume.
+
+## Wiring checklist
+- [ ] Endpoint returns 402 + `PAYMENT-REQUIRED` header on unauthenticated GET
+- [ ] Endpoint returns 200 + resource + `PAYMENT-RESPONSE` header after valid `PAYMENT-SIGNATURE`
+- [ ] Real settlement observed on Basescan (mainnet) or Base Sepolia explorer (dev)
+- [ ] `vercel.json` route added
+- [ ] UI surface in `public/x402.js` exercises the endpoint via the buyer client (USE-06)
+
+## Acceptance
+- [ ] `curl -i http://localhost:3000/api/x402/exact-evm-demo` shows 402 with PAYMENT-REQUIRED header
+- [ ] Wallet with Base Sepolia USDC pays through the UI and receives the resource
+- [ ] Transaction hash appears in PAYMENT-RESPONSE header and on the block explorer
+- [ ] No console errors in browser; no error logs server-side
+- [ ] Existing `api/x402/dance-tip.js` and siblings still work (regression check)
diff --git a/x402-buildout/prompts/03-seller-exact-svm.md b/x402-buildout/prompts/03-seller-exact-svm.md
new file mode 100644
index 000000000..6cc7c14b0
--- /dev/null
+++ b/x402-buildout/prompts/03-seller-exact-svm.md
@@ -0,0 +1,62 @@
+# USE-03: Seller — `exact` scheme on SVM (Solana + Devnet)
+
+## Goal
+Add `exact`-scheme paid endpoint on Solana, accepting USDC on `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` (mainnet) with `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` (devnet) for dev. Use `TransferChecked` with facilitator as fee payer.
+
+## Why
+This repo is Solana-heavy (Pump.fun feed, Solana RPC, agent payments SDK). Native Solana x402 is essential. Solana settlement differs from EVM: partially-signed transactions and strict instruction layout rules.
+
+## Reference
+- SVM spec: [/tmp/x402-docs/specs/schemes/exact/scheme_exact_svm.md](/tmp/x402-docs/specs/schemes/exact/scheme_exact_svm.md)
+- Scheme overview SVM section: [/tmp/x402-docs/docs/schemes/exact.mdx](/tmp/x402-docs/docs/schemes/exact.mdx)
+- Solana buyer quickstart: [/tmp/x402-docs/docs/getting-started/quickstart-for-buyers.mdx](/tmp/x402-docs/docs/getting-started/quickstart-for-buyers.mdx) (SVM section)
+- Existing SVM wiring: `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`
+
+## Dependencies
+- USE-00, USE-01
+- (Recommended) USE-02 to confirm middleware pattern works for EVM first
+
+## Files to create
+- `api/x402/exact-svm-demo.js` — paid Solana endpoint
+- `api/_lib/x402/svm-settlement-cache.js` — 120-second in-memory cache (REQUIRED by spec for self-settling, recommended even with facilitator) — see SVM spec §"Duplicate Settlement Mitigation"
+
+## Files to modify
+- `api/_lib/x402/sdk.js` — register `ExactSvmScheme` for `solana:*`
+- `vercel.json` — route for `/api/x402/exact-svm-demo`
+- `public/x402.js` — Solana button using `@solana/kit` signer
+
+## Implementation
+
+### Solana-specific configuration
+The Solana scheme requires `extra.feePayer` (facilitator's address) in `PaymentRequirements`. The facilitator typically populates this; verify our facilitator client surfaces it.
+
+### Duplicate settlement protection
+Per spec, on Solana the same signed transaction can be submitted multiple times before confirmation. The facilitator's RPC returns success each time but the transfer only executes once.
+
+If we use a facilitator: the `@x402/svm` package includes built-in `SettlementCache` — enable it when registering the scheme.
+
+If we ever self-settle (USE-26): we MUST implement our own short-lived cache keyed on the base64 transaction string with 120s TTL.
+
+Wire `api/_lib/x402/svm-settlement-cache.js` so it can be passed in either mode.
+
+### The endpoint
+- Price: `"$0.001"`
+- `payTo`: `getSvmAddress()` (base58 Solana address)
+- Returns a real resource (e.g., a Solana-themed pose seed, or pulls one bar of Pump.fun data through the existing feed)
+
+### Memo support
+Optional but useful: support `extra.memo` so payments carry an invoice / order ID per spec. Surface this via a query parameter `?ref=<id>` that becomes the memo.
+
+## Wiring checklist
+- [ ] Endpoint returns 402 + PAYMENT-REQUIRED header listing `solana:*` accepts
+- [ ] Settlement cache enabled when constructing `ExactSvmScheme`
+- [ ] `vercel.json` route added
+- [ ] UI in `public/x402.js` includes Solana payment flow using `@solana/kit` and base58 private key (env-only, never hardcoded)
+- [ ] `extra.memo` honored when `?ref` query param present
+
+## Acceptance
+- [ ] `curl -i http://localhost:3000/api/x402/exact-svm-demo` shows 402 with `solana:*` accepts
+- [ ] Solana wallet with devnet USDC pays through UI; transaction visible on solscan devnet
+- [ ] Memo from `?ref=invoice-123` appears in the on-chain Memo instruction
+- [ ] Duplicate submission of same signed tx returns `duplicate_settlement` error (test by replaying)
+- [ ] Confirmed transfer destination is the ATA PDA for `(payTo, USDC mint)` — not an arbitrary account
diff --git a/x402-buildout/prompts/04-seller-upto-evm.md b/x402-buildout/prompts/04-seller-upto-evm.md
new file mode 100644
index 000000000..046f70fa9
--- /dev/null
+++ b/x402-buildout/prompts/04-seller-upto-evm.md
@@ -0,0 +1,69 @@
+# USE-04: Seller — `upto` scheme on EVM (usage-metered)
+
+## Goal
+Add an `upto`-scheme paid endpoint where the buyer authorizes a max (e.g., $0.10) and we settle for the actual usage (e.g., LLM tokens generated, frames rendered, bytes served). EVM only, Permit2-based.
+
+## Why
+- Variable-cost endpoints can't use `exact`. LLM gen, asset rendering, vanity grinder runs — all variable.
+- This repo already has a vanity grinder and pose studio; both are perfect `upto` candidates.
+
+## Reference
+- Scheme overview: [/tmp/x402-docs/docs/schemes/upto.mdx](/tmp/x402-docs/docs/schemes/upto.mdx)
+- Spec: [/tmp/x402-docs/specs/schemes/upto/scheme_upto.md](/tmp/x402-docs/specs/schemes/upto/scheme_upto.md)
+- EVM impl: [/tmp/x402-docs/specs/schemes/upto/scheme_upto_evm.md](/tmp/x402-docs/specs/schemes/upto/scheme_upto_evm.md)
+- Seller quickstart `upto` section: [/tmp/x402-docs/docs/getting-started/quickstart-for-sellers.mdx](/tmp/x402-docs/docs/getting-started/quickstart-for-sellers.mdx)
+
+## Dependencies
+- USE-00, USE-01
+- USE-02 (reuses Vercel middleware pattern)
+
+## Files to create
+- `api/x402/upto-llm-gen.js` — paid LLM-style endpoint; price is per-token-generated, capped at the authorized max
+- `api/x402/upto-pose-render.js` — paid pose rendering; price scales with frame count
+- `api/_lib/x402/upto-billing.js` — shared usage-to-amount converter (atomic units, percentage, dollar-string formats)
+
+## Files to modify
+- `api/_lib/x402/sdk.js` — register `UptoEvmScheme` for `eip155:*` alongside `ExactEvmScheme`
+- `vercel.json` — routes
+- `public/x402.js` — UI flow showing authorized max, then actual charged amount in the receipt
+
+## Implementation
+
+### Key differences vs `exact`
+1. `accepts[].scheme: "upto"` and `accepts[].price: "$0.10"` (the MAX).
+2. After the work completes, call `setSettlementOverrides(res, { amount: <actualAtomicUnits> })` BEFORE returning the body.
+3. Settle amount must be `<=` authorized max. `"0"` is valid (no on-chain tx, no charge).
+
+### Settlement amount formats (USE-09 buyer must read same)
+- Raw atomic units: `"1000"` → 1000 base units (USDC: $0.001)
+- Percentage: `"50%"` → 50% of authorized max
+- Dollar: `"$0.05"` (only works when route price was `$`-prefixed)
+
+### LLM endpoint
+- Wire the OpenAI/Anthropic worker proxy that already exists in this repo
+- Count tokens generated; convert to USDC atomic units; cap at `maxPrice`
+- Return `{ result, usage: { actualChargedAtomic, authorizedMaxAtomic } }`
+- Set settlement overrides to actual usage
+
+### Pose-render endpoint
+- Wire to the existing pose-studio renderer
+- Price-per-frame at a fixed rate; cap at `maxPrice`
+- Return preview URLs + actual frame count
+
+### Facilitator address binding
+Per spec, `upto` requires `extra.facilitatorAddress` in `PaymentRequirements` so the client binds the authorization to a specific facilitator. Query the facilitator's `/supported` endpoint on cold start to grab its address and cache it.
+
+## Wiring checklist
+- [ ] `UptoEvmScheme` registered on resource server
+- [ ] `setSettlementOverrides` called in every handler before returning success
+- [ ] `extra.facilitatorAddress` populated correctly (read from cached `/supported`)
+- [ ] UI shows authorized max AND actual charged amount post-settlement
+- [ ] Routes in `vercel.json`
+- [ ] `.env.example` updated if any new vars
+
+## Acceptance
+- [ ] Buyer authorizes $0.10, server settles $0.04, on-chain tx confirms $0.04 transfer
+- [ ] $0.00 settle path verified — no on-chain transaction sent, no gas burned
+- [ ] Attempting to settle > authorized max returns `invalid_upto_evm_payload_settlement_exceeds_amount`
+- [ ] Each settlement format (atomic, percent, dollar) tested
+- [ ] Existing `exact` endpoints still working (regression)
diff --git a/x402-buildout/prompts/05-seller-batch-evm.md b/x402-buildout/prompts/05-seller-batch-evm.md
new file mode 100644
index 000000000..170008d7c
--- /dev/null
+++ b/x402-buildout/prompts/05-seller-batch-evm.md
@@ -0,0 +1,87 @@
+# USE-05: Seller — `batch-settlement` scheme on EVM (channel-based micropayments)
+
+## Goal
+Stand up the `batch-settlement` scheme: client funds a channel once, signs offchain cumulative vouchers per request, server claims many channels in one tx and settles separately. Use Redis-backed channel storage so the server is multi-instance safe (Vercel serverless).
+
+## Why
+- For high-volume paid traffic (per-call API, streaming, repeated tool calls) — gas of `exact`/`upto` per request becomes prohibitive.
+- Vercel functions are stateless and multi-instance; in-memory channel storage will lose state between invocations.
+
+## Reference
+- Scheme overview: [/tmp/x402-docs/docs/schemes/batch-settlement.mdx](/tmp/x402-docs/docs/schemes/batch-settlement.mdx)
+- Spec: [/tmp/x402-docs/specs/schemes/batch-settlement/scheme_batch_settlement.md](/tmp/x402-docs/specs/schemes/batch-settlement/scheme_batch_settlement.md)
+- EVM impl (long): [/tmp/x402-docs/specs/schemes/batch-settlement/scheme_batch_settlement_evm.md](/tmp/x402-docs/specs/schemes/batch-settlement/scheme_batch_settlement_evm.md)
+- Reference Redis example: [examples/typescript/fullstack/next-batch-settlement-redis](https://github.com/x402-foundation/x402/tree/main/examples/typescript/fullstack/next-batch-settlement-redis)
+
+## Dependencies
+- USE-00, USE-01, USE-02
+
+## Files to create
+- `api/x402/batch-stream.js` — paid endpoint advertising `batch-settlement`
+- `api/_lib/x402/batch/redis-channel-storage.js` — implements `ChannelStorage` interface backed by Vercel KV / Upstash Redis
+- `api/_lib/x402/batch/channel-manager.js` — server-side periodic claim + settle + refund runner
+- `api/x402-batch/claim.js` — cron-callable route to trigger `claim`
+- `api/x402-batch/settle.js` — cron-callable route to trigger `settle`
+- `api/x402-batch/refund.js` — cron-callable route to trigger refund of idle channels
+
+## Files to modify
+- `api/_lib/x402/sdk.js` — register `BatchSettlementEvmScheme` with our facilitator
+- `vercel.json` — routes for `/api/x402-batch/{claim,settle,refund}` AND a Vercel cron config to fire them on a schedule
+- `.env.example` — `REDIS_URL` (or `KV_URL` / `UPSTASH_REDIS_REST_URL`), `BATCH_RECEIVER_AUTHORIZER_PRIVATE_KEY`, `BATCH_WITHDRAW_DELAY_SECONDS`
+- `package.json` — `ioredis` or `@upstash/redis`
+
+## Implementation
+
+### Channel storage shape
+The `ChannelStorage` interface needs (per spec):
+- `getChannel(channelId)`
+- `saveChannel(channelId, state)` — atomic write with optimistic concurrency
+- `listChannelsByReceiver(receiver, token)` — for batch claim
+- `deleteChannel(channelId)` — after full refund
+
+Use Redis hashes keyed by `channel:<channelId>` + a secondary index `receiver:<addr>:<token>` (Redis Set of channelIds). Use Lua / `MULTI` for atomic voucher updates.
+
+### Receiver authorizer
+- Generate a dedicated `receiverAuthorizerSigner` key (NOT the payment-receiving address).
+- This signs claim and refund authorizations via EIP-712.
+- Store private key in env, surface address via `extra.receiverAuthorizer` in `PaymentRequirements`.
+
+### Withdraw delay
+- Default to 900 seconds (15 minutes — minimum per spec).
+- Configurable via `BATCH_WITHDRAW_DELAY_SECONDS`.
+
+### Channel manager (cron-driven)
+Vercel cron config:
+```json
+"crons": [
+ { "path": "/api/x402-batch/claim", "schedule": "* * * * *" },
+ { "path": "/api/x402-batch/settle", "schedule": "*/5 * * * *" },
+ { "path": "/api/x402-batch/refund", "schedule": "0 */1 * * *" }
+]
+```
+(Adjust based on volume. Claim every minute is safe. Settle less often saves gas.)
+
+### Paid endpoint
+- `accepts[].scheme: "batch-settlement"` with per-request max price
+- `accepts[].extra.receiverAuthorizer`, `accepts[].extra.withdrawDelay`, `accepts[].extra.assetTransferMethod` ("eip3009" default)
+- `setSettlementOverrides()` in handler to charge actual usage per request
+
+### Auth on cron routes
+Vercel crons hit cron routes with the standard `Authorization: Bearer ${CRON_SECRET}` header. Validate this.
+
+## Wiring checklist
+- [ ] `REDIS_URL` provisioned (or Vercel KV linked)
+- [ ] `receiverAuthorizer` address printed at startup for verification
+- [ ] Channel manager idempotent — replay-safe; multiple cron firings don't double-claim
+- [ ] Cron routes return 401 if `Authorization` header missing in production
+- [ ] Endpoint advertises `extra.withdrawDelay` between 900 and 2592000 (spec bounds)
+- [ ] UI in `public/x402.js` shows channel state (balance, charged, claimed)
+
+## Acceptance
+- [ ] Buyer opens channel with first paid request (deposit + voucher in single payload)
+- [ ] Subsequent requests use voucher-only payload (no on-chain tx per request)
+- [ ] Cron-triggered claim consolidates multiple channels into one onchain tx
+- [ ] Settle moves claimed funds to receiver; transaction visible on Basescan
+- [ ] Cooperative refund returns idle balance to payer
+- [ ] Server restart preserves channel state via Redis (verified by killing dev server and reading state)
+- [ ] Corrective 402 on cumulative-amount mismatch — buyer recovers automatically
diff --git a/x402-buildout/prompts/06-buyer-fetch-multinetwork.md b/x402-buildout/prompts/06-buyer-fetch-multinetwork.md
new file mode 100644
index 000000000..953964ecc
--- /dev/null
+++ b/x402-buildout/prompts/06-buyer-fetch-multinetwork.md
@@ -0,0 +1,65 @@
+# USE-06: Buyer — `fetch` client (multi-network EVM + SVM)
+
+## Goal
+Wrap `fetch` so any call to an x402-paid URL automatically handles 402 → sign → retry. Register EVM and SVM schemes so the same wrapped fetch handles both networks transparently.
+
+## Why
+- Any in-repo code that consumes paid APIs (other agents, workers, server-to-server calls) needs a turnkey HTTP client.
+- The browser side of `public/x402.js` and Node-side scripts both benefit.
+
+## Reference
+- Buyer quickstart: [/tmp/x402-docs/docs/getting-started/quickstart-for-buyers.mdx](/tmp/x402-docs/docs/getting-started/quickstart-for-buyers.mdx)
+- `@x402/fetch`: [typescript/packages/http/fetch](https://github.com/x402-foundation/x402/tree/main/typescript/packages/http/fetch)
+
+## Dependencies
+- USE-00, USE-01
+
+## Files to create
+- `api/_lib/x402/buyer-fetch.js` — server-side wrapped fetch (works in Vercel functions, scripts, workers)
+- `public/x402-buyer.js` — browser-side wrapped fetch, ES module
+- `scripts/x402-buy.mjs` — CLI utility: `node scripts/x402-buy.mjs <url> [--network=eip155:8453]`
+
+## Files to modify
+- `public/x402.js` — replace ad-hoc payment logic with `x402-buyer.js`
+- `.env.example` — `EVM_PRIVATE_KEY`, `SVM_PRIVATE_KEY` (buyer side)
+
+## Implementation
+
+### Shared client factory
+```js
+// api/_lib/x402/buyer-fetch.js
+import { x402Client } from "@x402/core/client";
+import { ExactEvmScheme } from "@x402/evm/exact/client";
+import { ExactSvmScheme } from "@x402/svm/exact/client";
+import { wrapFetchWithPayment } from "@x402/fetch";
+
+export function buildBuyerFetch({ evmSigner, svmSigner } = {}) {
+ const client = new x402Client();
+ if (evmSigner) client.register("eip155:*", new ExactEvmScheme(evmSigner));
+ if (svmSigner) client.register("solana:*", new ExactSvmScheme(svmSigner));
+ return wrapFetchWithPayment(globalThis.fetch, client);
+}
+```
+
+### Browser variant
+Same factory but with browser-friendly signers:
+- EVM via `viem/accounts.privateKeyToAccount` reading from `localStorage` or a wallet connector (NEVER expose private key in HTML; use connectors or BYO key flow with explicit user warning)
+- SVM via `@solana/kit` `createKeyPairSignerFromBytes`
+
+### CLI
+`node scripts/x402-buy.mjs https://api.example.com/weather` — exits 0 on success, prints response body, settle response in stderr. Useful for QA + cron-driven agents.
+
+### Server-to-server use
+Any internal Vercel function that calls another paid endpoint uses `buildBuyerFetch()` with env-loaded signers. NEVER expose buyer private keys to clients.
+
+## Wiring checklist
+- [ ] `public/x402.js` reads from `public/x402-buyer.js` (no duplicated sign logic)
+- [ ] Browser flow uses a connected wallet (Phantom, Coinbase Wallet, Metamask) — NOT a private key in env
+- [ ] Server-side `buildBuyerFetch()` works in both Vercel function (`api/*.js`) and Node script (`scripts/*.mjs`)
+- [ ] CLI exits with non-zero on payment error
+
+## Acceptance
+- [ ] `node scripts/x402-buy.mjs http://localhost:3000/api/x402/exact-evm-demo` returns the resource and prints settlement tx
+- [ ] Same CLI works against the Solana endpoint (`exact-svm-demo`)
+- [ ] Browser pays through UI without copying private keys anywhere
+- [ ] No leaked private keys in network tab or console logs
diff --git a/x402-buildout/prompts/07-buyer-axios.md b/x402-buildout/prompts/07-buyer-axios.md
new file mode 100644
index 000000000..d3bcefe5d
--- /dev/null
+++ b/x402-buildout/prompts/07-buyer-axios.md
@@ -0,0 +1,68 @@
+# USE-07: Buyer — `axios` interceptor
+
+## Goal
+Add an axios-based variant of the buyer client. Many of our worker scripts and SDK helpers use axios; wrap with `@x402/axios` so they can hit paid endpoints with zero code change.
+
+## Why
+- Several existing modules (workers/, agent-payments-sdk/) use axios.
+- Some downstream consumers (USE-30, USE-32) prefer axios for retry config and interceptor inspection.
+
+## Reference
+- Buyer quickstart axios tab: [/tmp/x402-docs/docs/getting-started/quickstart-for-buyers.mdx](/tmp/x402-docs/docs/getting-started/quickstart-for-buyers.mdx)
+- `@x402/axios`: [typescript/packages/http/axios](https://github.com/x402-foundation/x402/tree/main/typescript/packages/http/axios)
+
+## Dependencies
+- USE-00, USE-01
+- USE-06 (mirror its signer factory)
+
+## Files to create
+- `api/_lib/x402/buyer-axios.js` — exports `buildBuyerAxios({ baseURL, ...axiosOpts })`
+
+## Files to modify
+- Any existing call site in `workers/` or `agent-payments-sdk/` that hits paid endpoints — migrate to `buildBuyerAxios()`
+- `.env.example` — same signer vars as USE-06
+
+## Implementation
+
+```js
+// api/_lib/x402/buyer-axios.js
+import axios from "axios";
+import { wrapAxiosWithPayment, x402Client, x402HTTPClient } from "@x402/axios";
+import { ExactEvmScheme } from "@x402/evm/exact/client";
+import { ExactSvmScheme } from "@x402/svm/exact/client";
+import { getEvmSigner, getSvmSigner } from "./signers.js";
+
+export async function buildBuyerAxios(opts = {}) {
+ const client = new x402Client();
+ client.register("eip155:*", new ExactEvmScheme(getEvmSigner()));
+ client.register("solana:*", new ExactSvmScheme(await getSvmSigner()));
+ return {
+ api: wrapAxiosWithPayment(axios.create(opts), client),
+ httpClient: new x402HTTPClient(client),
+ client
+ };
+}
+```
+
+### Receipt extraction
+After every successful call, expose the settlement response:
+```js
+const { api, httpClient } = await buildBuyerAxios();
+const res = await api.get("/paid-endpoint");
+const receipt = httpClient.getPaymentSettleResponse(name => res.headers[name.toLowerCase()]);
+```
+Return `receipt` from every helper so callers can record transactions.
+
+### Migration audit
+- Search the repo for `axios.create(`, `axios.get(`, `axios.post(` in `workers/`, `agent-payments-sdk/`, `sdk/`.
+- Decide per call site whether it's hitting a paid endpoint. If yes, swap to `buildBuyerAxios()`.
+
+## Wiring checklist
+- [ ] `buildBuyerAxios()` returns `{ api, httpClient, client }` so callers can both make requests and inspect receipts
+- [ ] Existing axios call sites identified and updated where appropriate (don't blindly swap every one)
+- [ ] Retries on network error preserved; payment retry is a separate concern handled by the wrapper
+
+## Acceptance
+- [ ] Axios call to `/api/x402/exact-evm-demo` returns 200 with body
+- [ ] Receipt object contains `transaction`, `network`, `payer`
+- [ ] Worker scripts that previously failed against paid endpoints now succeed
diff --git a/x402-buildout/prompts/08-buyer-upto.md b/x402-buildout/prompts/08-buyer-upto.md
new file mode 100644
index 000000000..2bf5067f2
--- /dev/null
+++ b/x402-buildout/prompts/08-buyer-upto.md
@@ -0,0 +1,53 @@
+# USE-08: Buyer — `upto`-aware client
+
+## Goal
+Register `UptoEvmScheme` on the buyer client so when a paid endpoint returns 402 with `scheme: "upto"`, the client correctly signs an authorization for the maximum amount and accepts a settle response that may be lower.
+
+## Why
+- `exact` client schemes don't accept `upto` 402 responses.
+- Without this, any call to a `upto` endpoint (USE-04, USE-29, USE-32) fails.
+
+## Reference
+- `upto` scheme: [/tmp/x402-docs/docs/schemes/upto.mdx](/tmp/x402-docs/docs/schemes/upto.mdx)
+- Spec: [/tmp/x402-docs/specs/schemes/upto/scheme_upto_evm.md](/tmp/x402-docs/specs/schemes/upto/scheme_upto_evm.md)
+
+## Dependencies
+- USE-00, USE-06, USE-07
+
+## Files to modify
+- `api/_lib/x402/buyer-fetch.js` — register `UptoEvmScheme` alongside `ExactEvmScheme`
+- `api/_lib/x402/buyer-axios.js` — same
+- `public/x402-buyer.js` — same on browser side
+
+## Files to create
+- `api/_lib/x402/upto-receipt.js` — helper that pulls the `amount` field from the settle response to show actual charge
+
+## Implementation
+
+```js
+import { UptoEvmScheme } from "@x402/evm/upto/client";
+
+client.register("eip155:*", new ExactEvmScheme(signer));
+client.register("eip155:*", new UptoEvmScheme(signer));
+```
+
+Both schemes coexist under the same network namespace — the SDK selects per the 402 response's `scheme` field.
+
+### UI surface
+Browser UI should:
+1. Show authorized maximum in the confirmation dialog.
+2. After settlement, render the actual `amount` field from `SettlementResponse.amount` — which is now required for `upto`.
+
+### Receipt diff
+For audit logging, record both the authorized max (`PaymentRequirements.amount`) and the actual settled (`SettlementResponse.amount`). The delta is "money the buyer would've spent under `exact`".
+
+## Wiring checklist
+- [ ] Both `ExactEvmScheme` and `UptoEvmScheme` registered everywhere a buyer client is constructed
+- [ ] UI displays "Authorized up to: $X.XX" before signing, "Actually charged: $Y.YY" after settlement
+- [ ] Audit log captures both values
+
+## Acceptance
+- [ ] Calling `/api/x402/upto-llm-gen` from the wrapped fetch returns 200 with body
+- [ ] Receipt shows `amount` < authorized max in at least one test run
+- [ ] $0.00 settle path: receipt shows `transaction: ""` and `amount: "0"` (no on-chain tx)
+- [ ] `exact` endpoints still work (regression)
diff --git a/x402-buildout/prompts/09-buyer-batch.md b/x402-buildout/prompts/09-buyer-batch.md
new file mode 100644
index 000000000..285fb5f36
--- /dev/null
+++ b/x402-buildout/prompts/09-buyer-batch.md
@@ -0,0 +1,74 @@
+# USE-09: Buyer — `batch-settlement` client with persistent channel state
+
+## Goal
+Register `BatchSettlementEvmScheme` on the buyer client with file-backed (Node) or IndexedDB-backed (browser) channel storage. Survive process restarts. Auto-recover via corrective 402.
+
+## Why
+- Long-lived agent processes (USE-29, USE-30, USE-40) make many small paid calls. Without batch-settlement they'd burn gas on every request.
+- Per-process in-memory channel state is lost when the process dies; clients must persist state OR rely on corrective 402 recovery.
+
+## Reference
+- Scheme docs: [/tmp/x402-docs/docs/schemes/batch-settlement.mdx](/tmp/x402-docs/docs/schemes/batch-settlement.mdx)
+- EVM spec: [/tmp/x402-docs/specs/schemes/batch-settlement/scheme_batch_settlement_evm.md](/tmp/x402-docs/specs/schemes/batch-settlement/scheme_batch_settlement_evm.md)
+- Client example: [examples/typescript/clients/batch-settlement](https://github.com/x402-foundation/x402/tree/main/examples/typescript/clients/batch-settlement)
+
+## Dependencies
+- USE-00, USE-06, USE-07
+- USE-05 (so a `batch-settlement` endpoint exists to test against)
+
+## Files to create
+- `api/_lib/x402/buyer-batch.js` — registers `BatchSettlementEvmScheme` with `FileClientChannelStorage`
+- `public/x402-buyer-batch.js` — browser variant with IndexedDB storage
+- `scripts/x402-batch-refund.mjs` — CLI to issue cooperative refunds for idle channels
+
+## Files to modify
+- `api/_lib/x402/buyer-fetch.js` — accept `{ withBatch: true }` option that adds batch scheme
+- `.env.example` — `EVM_VOUCHER_SIGNER_PRIVATE_KEY` (optional, for smart-wallet payers)
+
+## Implementation
+
+### Node-side storage
+```js
+import { BatchSettlementEvmScheme } from "@x402/evm/batch-settlement/client";
+import { FileClientChannelStorage } from "@x402/evm/batch-settlement/client/file-storage";
+import { toClientEvmSigner } from "@x402/evm";
+
+const batchScheme = new BatchSettlementEvmScheme(toClientEvmSigner(signer, publicClient), {
+ depositPolicy: { depositMultiplier: 5 },
+ storage: new FileClientChannelStorage({ directory: process.env.X402_CHANNEL_STORAGE_DIR || "./.x402-channels" }),
+});
+client.register("eip155:*", batchScheme);
+```
+
+### Browser storage
+Use IndexedDB via `idb` package. Channels are keyed by `channelId`. Store voucher signatures + cumulative amounts. Provide an `inspectChannels()` helper for the UI to render channel state.
+
+### Voucher signer delegation
+For browser flows with smart wallets (Coinbase Smart Wallet, etc.) — pass an EOA `voucherSigner` so vouchers are verified by ECDSA recovery instead of EIP-1271 RPC checks. This is faster and avoids per-voucher RPC calls.
+
+### Cooperative refund CLI
+`node scripts/x402-batch-refund.mjs <resourceUrl> [--amount=<atomicUnits>]` — calls `batchScheme.refund(url, { amount })`. Returns the refund tx hash on success.
+
+### Deposit strategy
+Cap deposits at a sane max (e.g., $5 default) so a bug in the multiplier doesn't drain the wallet:
+```js
+depositStrategy: ({ depositAmount }) => {
+ const max = BigInt(process.env.X402_MAX_DEPOSIT_ATOMIC || "5000000");
+ const amt = BigInt(depositAmount);
+ return amt > max ? max : undefined;
+}
+```
+
+## Wiring checklist
+- [ ] Node clients persist `.x402-channels/*.json` across restarts
+- [ ] Browser clients persist channel state to IndexedDB
+- [ ] Both `BatchSettlementEvmScheme` and `ExactEvmScheme` registered — the SDK picks per server response
+- [ ] Deposit cap prevents runaway deposits
+- [ ] Refund CLI usable for ops
+
+## Acceptance
+- [ ] First request to a `batch-settlement` endpoint opens a channel (deposit + voucher in one payload, on-chain tx visible)
+- [ ] Subsequent requests use voucher-only payloads (no on-chain tx, server returns `transaction: ""`)
+- [ ] Killing the process and restarting picks up where we left off (verified by reading `.x402-channels/`)
+- [ ] Corrective 402 (server's channel state differs from client's) triggers client recovery and the next request succeeds
+- [ ] `scripts/x402-batch-refund.mjs` returns idle funds to the buyer wallet