Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(club): camera state machine, audio tracks, treasury env, prompts
nirholasd220b2abbc62
diff --git a/api/_lib/env.js b/api/_lib/env.jsindex a6f553487..313f0b27f 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -275,6 +275,25 @@ export const env = {// Alternative: store the base64 in coin_launches.metadata.creator_secret_b64// at register time (less secure than env; v2 should move to a KMS).+ // ── Pole Club tip sweep (api/_lib/club/*) ─────────────────────────────+ // Solana treasury keypair (base64-encoded 64-byte secret) that holds the+ // USDC received from /api/x402/dance-tip on Solana. Used by the+ // club-payouts cron to send accumulated tips to each dancer's wallet.+ get CLUB_SOLANA_TREASURY_SECRET_KEY_B64() {+ return opt('CLUB_SOLANA_TREASURY_SECRET_KEY_B64');+ },+ // EVM (Base mainnet) treasury private key (0x-prefixed hex). Holds the+ // USDC received from /api/x402/dance-tip on Base. Used by the club-payouts+ // cron to send accumulated tips to each dancer's EVM wallet.+ get CLUB_EVM_TREASURY_PRIVATE_KEY() {+ return opt('CLUB_EVM_TREASURY_PRIVATE_KEY');+ },+ // Base mainnet RPC URL. Falls back to the public node, but rate limits+ // will bite at >5 sweeps/minute — set this in production.+ get CLUB_BASE_RPC_URL() {+ return opt('CLUB_BASE_RPC_URL', 'https://mainnet.base.org');+ },+// NFT.Storage API token — required for MintScene tool (uploads GLB + thumbnail + metadata to IPFS).// Obtain at https://nft.storage. When unset, /api/nft/mint-scene returns 503 not_configured.get NFT_STORAGE_TOKEN() {diff --git a/api/_lib/migrations/2026-05-22-club-tips.sql b/api/_lib/migrations/2026-05-22-club-tips.sqlnew file mode 100644index 000000000..78013bbcf--- /dev/null+++ b/api/_lib/migrations/2026-05-22-club-tips.sql@@ -0,0 +1,38 @@+-- Migration: persistent ledger for Pole Club tip events.+-- Apply: npm run db:migrate -- --apply --file 2026-05-22-club-tips.sql+-- Idempotent.+--+-- Backs the /club "Live tips" feed. Every settled /api/x402/dance-tip+-- payment writes one row here, /api/club/tips reads recent rows for the+-- page boot, and /api/club/tips/stream tails the table for the SSE feed.+--+-- paid_at / paid_tx are reserved for prompt 08 (dancer payouts) — schema+-- carries them now so payouts don't require a second migration.++begin;++create table if not exists club_tips (+ id uuid primary key default gen_random_uuid(),+ ticket_id text not null unique,+ dancer text not null,+ dance text not null,+ clip text,+ label text,+ payer text,+ network text,+ amount_atomics numeric,+ asset text,+ started_at timestamptz not null,+ ends_at timestamptz not null,+ paid_at timestamptz,+ paid_tx text,+ created_at timestamptz not null default now()+);++create index if not exists club_tips_created_at_desc+ on club_tips (created_at desc);++create index if not exists club_tips_dancer_created+ on club_tips (dancer, created_at desc);++commit;diff --git a/api/_lib/migrations/2026-05-23-club-dancer-wallets.sql b/api/_lib/migrations/2026-05-23-club-dancer-wallets.sqlnew file mode 100644index 000000000..ede3da7c3--- /dev/null+++ b/api/_lib/migrations/2026-05-23-club-dancer-wallets.sql@@ -0,0 +1,76 @@+-- Club dancer wallets + payout ledger (prompt 08).+--+-- Per-dancer registry: which EVM/Solana addresses receive their swept tips.+-- Payout ledger: one row per on-chain sweep tx, with an audit-grade link back+-- to the tip rows it settled. Wallets are seeded via the admin endpoint+-- (POST /api/admin/club/dancer-wallet); never commit private keys or+-- addresses into this migration.+--+-- Also (idempotently) ensures the columns the payout sweep relies on exist+-- on club_tips, so deploying this migration does not require prompt 07+-- having been applied first. If club_tips already exists (prompt 07 shipped),+-- the alter clauses are no-ops.++create table if not exists club_dancer_wallets (+ dancer text primary key,+ display_name text not null,+ bio text,+ evm_address text,+ solana_address text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create table if not exists club_tips (+ id uuid primary key default gen_random_uuid(),+ ticket_id text,+ dancer text not null,+ dance text,+ clip text,+ label text,+ payer text,+ network text not null,+ amount_atomics numeric not null,+ asset text not null,+ started_at timestamptz,+ ends_at timestamptz,+ created_at timestamptz not null default now(),+ paid_at timestamptz,+ paid_tx text+);++create index if not exists club_tips_dancer_created+ on club_tips (dancer, created_at desc);++create index if not exists club_tips_unpaid+ on club_tips (dancer, network, asset)+ where paid_at is null;++-- Defensive alters in case club_tips was created by prompt 07 without the+-- payout columns. `add column if not exists` is idempotent in PG 9.6+.+alter table club_tips add column if not exists paid_at timestamptz;+alter table club_tips add column if not exists paid_tx text;++create table if not exists club_payouts (+ id uuid primary key default gen_random_uuid(),+ dancer text not null references club_dancer_wallets(dancer),+ network text not null,+ asset text not null,+ amount_atomics numeric not null,+ tx text not null,+ swept_tip_count integer not null,+ created_at timestamptz not null default now()+);++create index if not exists club_payouts_dancer_created+ on club_payouts (dancer, created_at desc);++-- Default seed: register the four built-in dancers with display names but no+-- wallets. An admin sets the addresses via /api/admin/club/dancer-wallet.+-- Until a wallet is set the sweep cron logs and skips that (dancer, network).+insert into club_dancer_wallets (dancer, display_name) values+ ('1', 'Nyx'),+ ('2', 'Ari'),+ ('3', 'Sable'),+ ('4', 'Vesper')+on conflict (dancer) do nothing;diff --git a/api/x402/dance-tip.js b/api/x402/dance-tip.jsindex 0223b1cb8..7921bdd31 100644--- a/api/x402/dance-tip.js+++ b/api/x402/dance-tip.js@@ -19,12 +19,15 @@ const DESCRIPTION ='returns a performance ticket the /club page consumes to spawn the dancer ' +'and play the routine for ~12 seconds.';+// `track` names map to /public/club/audio/<track>.{ogg,mp3} loops the /club+// page crossfades to when the dance starts. The client picks whichever format+// the browser supports — see src/club-audio.js loadBuffer().const STYLES = Object.freeze({- hiphop: { clip: 'dance', label: 'Hip Hop', loop: true, durationSec: 12 },- 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, track: 'hiphop' },+ rumba: { clip: 'rumba', label: 'Rumba', loop: true, durationSec: 14, track: 'rumba' },+ silly: { clip: 'silly', label: 'Silly', loop: true, durationSec: 10, track: 'silly' },+ thriller: { clip: 'thriller', label: 'Thriller',loop: true, durationSec: 14, track: 'thriller' },+ capoeira: { clip: 'capoeira', label: 'Capoeira',loop: true, durationSec: 12, track: 'capoeira' },});const VALID_DANCERS = new Set(['1', '2', '3', '4']);@@ -58,6 +61,7 @@ const OUTPUT_EXAMPLE = {label: 'Rumba',loop: true,durationSec: 14,+ track: 'rumba',startsAt: '2026-05-21T18:42:09.000Z',endsAt: '2026-05-21T18:42:23.000Z',payer: 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV',@@ -69,7 +73,7 @@ const OUTPUT_EXAMPLE = {const OUTPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',- required: ['ok', 'ticketId', 'dancer', 'dance', 'clip', 'durationSec', 'startsAt', 'endsAt'],+ required: ['ok', 'ticketId', 'dancer', 'dance', 'clip', 'durationSec', 'startsAt', 'endsAt', 'track'],properties: {ok: { type: 'boolean', const: true },ticketId: { type: 'string', format: 'uuid' },@@ -79,6 +83,11 @@ const OUTPUT_SCHEMA = {label: { type: 'string' },loop: { type: 'boolean' },durationSec: { type: 'integer', minimum: 1, maximum: 60 },+ track: {+ type: 'string',+ enum: ['rumba', 'silly', 'thriller', 'capoeira', 'hiphop', 'pole'],+ description: 'Audio loop name — /public/club/audio/<track>.{ogg,mp3}.',+ },startsAt: { type: 'string', format: 'date-time' },endsAt: { type: 'string', format: 'date-time' },payer: { type: ['string', 'null'] },@@ -144,6 +153,7 @@ export default paidEndpoint({label: style.label,loop: style.loop,durationSec: style.durationSec,+ track: style.track,startsAt: now.toISOString(),endsAt: ends.toISOString(),payer: payer ?? null,diff --git a/package.json b/package.jsonindex 713815b41..1db9e622d 100644--- a/package.json+++ b/package.json@@ -53,6 +53,7 @@"build": "vite build","build:wasm": "PATH=\"$HOME/.cargo/bin:$PATH\" RUSTFLAGS='-C target-feature=+simd128' wasm-pack build crates/vanity-grinder --target web --release --out-dir ../../src/solana/vanity/wasm && printf '%s\\n' '# wasm-pack writes a default `*` gitignore that excludes everything.' '# Override it: the generated files in this directory ARE checked in so the' '# app builds without requiring a Rust toolchain at install time. Run' '# `npm run build:wasm` after editing /crates/vanity-grinder/src/lib.rs to' '# refresh these artifacts.' '!*' > src/solana/vanity/wasm/.gitignore","build:animations": "node scripts/build-animations.mjs",+ "build:club-props": "node scripts/build-club-props.mjs","build:artifact-viewer": "node scripts/build-artifact-viewer.mjs","build:lib": "TARGET=lib vite build","build:lib:full": "TARGET=lib LIB_FORMATS=es,umd vite build",diff --git a/pages/club.html b/pages/club.htmlindex 0d4ed8c9e..a5f70c9bb 100644--- a/pages/club.html+++ b/pages/club.html@@ -176,6 +176,30 @@#club-status[data-kind="ok"] { border-color: rgba(74, 222, 128, 0.45); color: #c7f5d6; }#club-status[hidden] { display: none; }+ #club-free-cam {+ position: absolute;+ left: 50%;+ bottom: 56px;+ transform: translateX(-50%);+ appearance: none;+ border: 1px solid var(--border-strong);+ background: rgba(7, 5, 11, 0.86);+ color: var(--text);+ font: inherit;+ font-size: 11.5px;+ font-weight: 600;+ padding: 6px 14px;+ border-radius: 999px;+ cursor: pointer;+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ z-index: 5;+ transition: filter 0.12s ease, transform 0.08s ease;+ }+ #club-free-cam:hover { filter: brightness(1.15); }+ #club-free-cam:active { transform: translateX(-50%) translateY(1px); }+ #club-free-cam[hidden] { display: none; }+/* ── Right panel: poles + tip feed ────────────────── */#club-right {grid-area: right;@@ -228,11 +252,30 @@font-weight: 600;}.club-pole-id { color: var(--accent); letter-spacing: 0.02em; }+ .club-pole-row-right {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ }.club-pole-price {color: var(--text-3);font-size: 10.5px;font-family: ui-monospace, SFMono-Regular, Menlo, monospace;}+ .club-cam-btn {+ appearance: none;+ border: 1px solid var(--border);+ background: rgba(74, 214, 255, 0.08);+ border-radius: 6px;+ padding: 2px 6px;+ font-size: 11px;+ line-height: 1;+ color: var(--text);+ cursor: pointer;+ transition: filter 0.12s ease, transform 0.08s ease;+ }+ .club-cam-btn:hover { filter: brightness(1.2); border-color: var(--border-strong); }+ .club-cam-btn:active { transform: translateY(1px); }.club-pole-style {display: flex;flex-direction: column;@@ -281,6 +324,39 @@cursor: progress;}+ .club-toggle {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 12px;+ font-size: 12px;+ color: var(--text-2);+ cursor: pointer;+ user-select: none;+ }+ .club-toggle input {+ accent-color: var(--accent);+ cursor: pointer;+ margin: 0;+ }+ .club-toggle:hover { color: var(--text); }+ .club-hint {+ margin: 8px 0 0;+ font-size: 11px;+ color: var(--text-3);+ letter-spacing: 0.02em;+ }+ .club-hint b {+ color: var(--text-2);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 10.5px;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid var(--border);+ border-radius: 4px;+ padding: 1px 4px;+ font-weight: 600;+ }+#club-tip-feed {display: flex;flex-direction: column;@@ -378,6 +454,13 @@<section class="club-section"><h2>Poles</h2><div id="club-poles"></div>+ <label class="club-toggle" for="club-auto-follow">+ <input type="checkbox" id="club-auto-follow" />+ <span>Auto-follow tips (VIP cam during dance)</span>+ </label>+ <p class="club-hint">+ Shortcuts: <b>1</b>–<b>4</b> VIP · <b>0</b> overhead · <b>Esc</b> free+ </p></section><section class="club-section">diff --git a/prompts/club/05-audio-and-music.md b/prompts/club/05-audio-and-music.mdnew file mode 100644index 000000000..6d47de991--- /dev/null+++ b/prompts/club/05-audio-and-music.md@@ -0,0 +1,197 @@+# Task: Background music, per-style tracks, crowd ambience for /club++## Repo context++Working tree: `/workspaces/three.ws`. Today `/club` is silent — no+`<audio>` element in [pages/club.html](../../pages/club.html), no+Web Audio code in [src/club.js](../../src/club.js). A pole-dance club+without music isn't a pole-dance club.++The `STYLES` map in+[api/x402/dance-tip.js](../../api/x402/dance-tip.js) lists clips by+name. Adding a `track` field per style lets the client play the+matching music while the clip runs.++## Rails (CLAUDE.md — non-negotiable)++- Real licensed audio files committed under `public/club/audio/`.+ Provenance recorded in `public/club/audio/LICENSES.md`.+- No `setTimeout`-faked beat detection. Real `AnalyserNode` from the+ Web Audio API.+- Autoplay policies: never play audio until the user has interacted+ with the page. The first tip click is the gesture.+- Errors handled at boundaries — `AudioContext` may be suspended;+ surface the resume to the user.++## What to implement++### Step 1 — author / source audio cuts++Six tracks under `public/club/audio/`:++| File | Style | Length | License |+|---|---|---|---|+| `ambience.ogg` + `.mp3` | crowd/room | ~60s loop | CC0 ambient |+| `rumba.ogg` + `.mp3` | rumba | ~30s loop | CC-BY licensed |+| `thriller.ogg` + `.mp3` | thriller | ~30s loop | CC-BY |+| `hiphop.ogg` + `.mp3` | hip hop | ~30s loop | CC-BY |+| `capoeira.ogg` + `.mp3` | capoeira | ~30s loop | CC-BY |+| `silly.ogg` + `.mp3` | silly | ~30s loop | CC-BY |+| `pole.ogg` + `.mp3` | pole choreography (spin/climb/combo) | ~30s loop | CC-BY |++Both formats so `<audio>` picks the supported one. Targets:++- Mono 192k MP3 for size; stereo q4 OGG Vorbis for quality.+- Loud enough to mix above ambience but not clip after bloom-era+ postprocessing audio sidechain — peaks at –6 dBFS.+- Loop points authored cleanly (no clicks at the seam).++License provenance + attribution in+`public/club/audio/LICENSES.md` (extend if file exists; create if+not).++### Step 2 — `src/club-audio.js`++A small audio mixer:++```js+export class ClubAudio {+ constructor() {+ this.ctx = null; // AudioContext, lazy-created+ this.master = null; // GainNode → ctx.destination+ this.ambience = null; // { source, gain }+ this.style = null; // { name, source, gain }+ this.analyser = null; // AnalyserNode wired to master+ this._buffers = new Map();// styleName → AudioBuffer+ this.muted = false;+ }++ async ensureContext() {+ if (this.ctx) return;+ this.ctx = new (window.AudioContext || window.webkitAudioContext)();+ this.master = this.ctx.createGain();+ this.master.gain.value = 0.75;+ this.master.connect(this.ctx.destination);+ this.analyser = this.ctx.createAnalyser();+ this.analyser.fftSize = 256;+ this.master.connect(this.analyser);+ }++ async loadBuffer(name, url) { /* fetch + decodeAudioData */ }++ async startAmbience() { /* loop ambience.ogg at 0.35 gain */ }++ async fadeToStyle(name, durationMs = 800) {+ // Crossfade ambience down to 0.1, style track up to 0.75.+ }++ async fadeOutStyle(durationMs = 800) {+ // Style back to 0, ambience back to 0.35.+ }++ getPeak() {+ // Sample analyser frequency bin, return 0..1 normalized peak.+ }++ setMuted(v) { this.master.gain.linearRampToValueAtTime(v ? 0 : 0.75, this.ctx.currentTime + 0.15); this.muted = v; }+}+```++No global side-effects on import — instantiated lazily in+`bootstrap()`.++### Step 3 — wire to tip flow++In [src/club.js](../../src/club.js) `tipDancer()`:++- Before opening the wallet modal:+ `await audio.ensureContext()` — this is the user gesture.+- After successful settlement and `station.startPerformance(ticket)`:+ `audio.fadeToStyle(styleAudioFor(ticket.dance))`.+- After `_endPerformance` resolves in `PoleStation.tick`: emit a+ custom event the page listens for and calls+ `audio.fadeOutStyle()`.++`styleAudioFor()` maps:++| Dance | Track |+|---|---|+| `rumba` | `rumba` |+| `silly` | `silly` |+| `thriller` | `thriller` |+| `capoeira` | `capoeira` |+| `hiphop` | `hiphop` |+| `spin` / `climb` / `combo` | `pole` |++The `STYLES` map in+[api/x402/dance-tip.js](../../api/x402/dance-tip.js) gains a `track`+field so the ticket carries the audio name back to the client. Add+it to `OUTPUT_SCHEMA`.++### Step 4 — ambience starts on first interaction++If the audio context creates successfully, `startAmbience()` runs+once and loops for the session. Add a small "audio off / on" pill+to the top bar in [pages/club.html](../../pages/club.html) bound to+`audio.setMuted()`. Persist preference to+`localStorage.club.audio.muted`.++### Step 5 — beat → light bridge (handoff to prompt 04)++Expose `window.__clubAudio = audio` (or pass via a small event bus)+so prompt 04's rim-light pulse code can call `audio.getPeak()` each+frame. If no audio context yet, the rim-light fallback sine kicks in+(prompt 04 already handles that case).++### Step 6 — accessibility++- Captions / status: when a track plays, the existing+ `setStatus(...)` helper announces it ("Now playing: Rumba mix")+ for screen readers (`role="status"` on `#club-status`).+- Respect `prefers-reduced-motion` for the bloom flicker, not the+ audio.++### Step 7 — manual end-to-end++```bash+npm run dev+```++Visit `/club`. The page is silent until you click a Tip button —+that's the user gesture. After settlement:++- Ambience fades down.+- Style track plays in sync with the dance clip.+- Rim lights pulse to the audio beat (if prompt 04 already+ shipped).+- Audio fades back to ambience when the dance ends.+- Mute toggle silences everything.++### Step 8 — tests++`tests/club-audio.test.js`:++- Stub `AudioContext` with a fake context exposing+ `decodeAudioData`, `createGain`, etc.+- Assert `fadeToStyle` schedules the right `linearRampToValueAtTime`+ calls.+- Assert mute toggle ramps master gain to 0 and back.++## Definition of done++- Six tracks committed under `public/club/audio/` with attribution.+- `src/club-audio.js` mixer wired into the tip flow.+- Mute pill in the top bar with persisted preference.+- Real browser smoke: settle a tip, hear the matching track, see+ beat-synced rim lights (if prompt 04 is in).+- Tests green.++## Constraints++- Do not autoplay any audio before a user gesture. Browsers will+ silently block and the page will look broken.+- Do not ship audio files >2 MB each. Cut them shorter or re-encode.+- Do not pre-decode all six tracks on page load. Decode lazily on+ first request per style.+- Do not introduce a heavyweight audio library (Howler, Tone.js).+ Web Audio API directly.diff --git a/prompts/club/06-camera-and-controls.md b/prompts/club/06-camera-and-controls.mdnew file mode 100644index 000000000..eef8da8cb--- /dev/null+++ b/prompts/club/06-camera-and-controls.md@@ -0,0 +1,196 @@+# Task: Multi-cam (free / VIP / house) + interaction polish for /club++## Repo context++Working tree: `/workspaces/three.ws`. Today+[src/club.js:552-579](../../src/club.js) implements a single free-orbit+camera driven by pointerdown/move on the canvas. There's no way to+"zoom in on dancer 3" or get a clean overhead shot of the room.++The `POLES` layout array carries each pole's `x/z` and `yaw`, which+is enough to compute deterministic VIP shots.++## Rails (CLAUDE.md — non-negotiable)++- No `setTimeout`-faked dolly. Real interpolation in the existing+ `animate()` loop driven by `Clock.getDelta()`.+- No `OrbitControls`-injected handlers fighting the existing+ pointer code — keep the system single-author.+- Touch support: mobile must work without a keyboard.+- Done = clicking a pole card snaps the camera to a VIP shot;+ Escape returns to free; keyboard 1–4 + 0 work on desktop; pinch ++ drag still orbit on touch.++## What to implement++### Step 1 — camera state machine++New file `src/club-camera.js`:++```js+import { Vector3 } from 'three';++const MODES = ['free', 'vip', 'house'];++export class ClubCamera {+ constructor(camera, opts = {}) {+ this.camera = camera;+ this.mode = 'free';+ this.target = new Vector3(0, 1.2, -1.8);+ this.offset = new Vector3(0, 2.2, 7.2);+ this.yaw = 0;+ this.pitch = 0.05;+ this._lerp = 2.0; // 1 / seconds-to-settle approx.+ this._pending = null; // {target, offset, lerp}+ }++ setFree() { this.mode = 'free'; this._pending = null; }++ setVip(poleLayout) {+ this.mode = 'vip';+ const target = new Vector3(poleLayout.x, 1.6, poleLayout.z);+ const offset = new Vector3(+ Math.sin(poleLayout.yaw + Math.PI) * 2.6,+ 1.3,+ Math.cos(poleLayout.yaw + Math.PI) * 2.6,+ );+ this._pending = { target, offset, lerp: 3.0 };+ }++ setHouse() {+ this.mode = 'house';+ this._pending = {+ target: new Vector3(0, 0.5, -1.5),+ offset: new Vector3(0, 12, 0.001), // top-down with epsilon to avoid singular up+ lerp: 1.6,+ };+ }++ // Called from pointer drag handler; only effective in 'free' mode.+ applyDrag(dx, dy) {+ if (this.mode !== 'free') return;+ this.yaw -= dx * 0.004;+ this.pitch = Math.max(-0.3, Math.min(0.5, this.pitch - dy * 0.003));+ }++ applyZoom(deltaY) { /* free + vip both honor pinch zoom */ }++ tick(dt) {+ if (this._pending) {+ this.target.lerp(this._pending.target, Math.min(1, dt * this._pending.lerp));+ this.offset.lerp(this._pending.offset, Math.min(1, dt * this._pending.lerp));+ if (this.target.distanceTo(this._pending.target) < 0.01) this._pending = null;+ }+ if (this.mode === 'free') {+ const rotated = this.offset.clone().applyAxisAngle(new Vector3(0, 1, 0), this.yaw);+ this.camera.position.copy(this.target.clone().add(rotated));+ } else {+ this.camera.position.copy(this.target.clone().add(this.offset));+ }+ this.camera.lookAt(this.target);+ }+}+```++### Step 2 — replace the inline camera math++In [src/club.js](../../src/club.js):++- Delete the inline drag handler (`src/club.js:552-579`) and the+ inline camera math in `animate()` (`src/club.js:599-605`).+- Instantiate `const clubCam = new ClubCamera(camera);`.+- New drag handler calls `clubCam.applyDrag(dx, dy)` and+ `clubCam.applyZoom(delta)`.+- In `animate()`: `clubCam.tick(dt)` before `composer.render()`.++### Step 3 — pole-card → VIP cam++In `renderPoles()` (`src/club.js:519-550`), the pole card already has+a Tip button. Add a small VIP icon button to the right of the price:++```html+<button type="button" class="club-cam-btn" data-pole="${pole.id}" title="VIP cam">+ 🎬+</button>+```++Click handler: `clubCam.setVip(POLES.find(p => p.id === poleId))`.++While in VIP mode show a small dismiss chip ("Free cam") next to+`#club-status`. Escape key + the chip's click both call+`clubCam.setFree()`.++### Step 4 — keyboard shortcuts++In `bootstrap()`:++```js+window.addEventListener('keydown', (e) => {+ if (e.target?.tagName === 'INPUT' || e.target?.tagName === 'SELECT') return;+ if (e.key === '0') return clubCam.setHouse();+ if (e.key === 'Escape') return clubCam.setFree();+ if (['1', '2', '3', '4'].includes(e.key)) {+ const layout = POLES.find((p) => p.id === e.key);+ if (layout) clubCam.setVip(layout);+ }+});+```++### Step 5 — touch / pinch++`pointermove` already handles single-pointer drag. For pinch zoom,+track up to two pointers in a `Map`:++- Two pointers → distance delta = zoom.+- Single pointer → orbit.+- Disable browser scroll on the canvas (`touch-action: none` is+ already set in [pages/club.html](../../pages/club.html) CSS).++### Step 6 — auto-cam during performance++When a `PoleStation` calls `startPerformance` and no VIP/house is+already active, auto-switch to that pole's VIP cam for the duration,+then return to free on `_endPerformance`. Make this opt-in via a+right-panel checkbox ("Auto-follow tips") that persists to+`localStorage`.++### Step 7 — manual end-to-end++```bash+npm run dev+```++- Free orbit works as before (no regression).+- Clicking a pole-card 🎬 dollies smoothly to a VIP shot of that+ pole.+- Escape returns to free.+- `0` jumps to overhead house cam.+- Numbers `1`–`4` jump to per-pole VIP.+- Auto-follow option keeps the camera on the active dancer when a+ tip lands.++### Step 8 — tests++`tests/club-camera.test.js`:++- Stub a `PerspectiveCamera`-shaped object.+- Drive `setVip()` → many `tick(dt)` calls → assert camera position+ converges to the expected world coordinate.+- Drive `setFree()` after a VIP → assert orbit yaw drag works again.++## Definition of done++- `src/club-camera.js` exports `ClubCamera`, used by+ [src/club.js](../../src/club.js).+- All four modes (free, VIP × 4, house) reachable via keyboard,+ mouse, touch.+- Auto-follow toggle persists.+- Real browser smoke clean, tests green.++## Constraints++- Do not introduce `OrbitControls` alongside the custom system —+ pick one.+- Do not teleport between modes; always interpolate over ~0.4s.+- Do not steal keyboard input from selects / inputs in the side+ panel (the early-return guard handles this — keep it).diff --git a/prompts/club/07-tip-feed-realtime.md b/prompts/club/07-tip-feed-realtime.mdnew file mode 100644index 000000000..9e0088299--- /dev/null+++ b/prompts/club/07-tip-feed-realtime.md@@ -0,0 +1,309 @@+# Task: Server-backed real-time tip feed for /club++## Repo context++Working tree: `/workspaces/three.ws`. Today the right-panel "Live+tips" widget at+[src/club.js:97-111](../../src/club.js) prepends rows into an+in-memory DOM list that lives only in the current browser tab. A+page refresh wipes it. Two simultaneous visitors don't see each+other's tips. The world feels dead.++The persistence path:++- Inserts on settlement in+ [api/x402/dance-tip.js](../../api/x402/dance-tip.js) `handler`.+- Reads via `GET /api/club/tips` (recent list).+- Live updates via `GET /api/club/tips/stream` (SSE).+- The /club page subscribes to SSE on boot.++## Rails (CLAUDE.md — non-negotiable)++- Real Neon Postgres. No in-memory ring buffer pretending to be a+ feed.+- Real SSE — not long-polling, not WebSocket-with-no-server. The+ rest of the repo uses node-postgres + the `sql` template from+ `api/_lib/db.js`; match that.+- Errors handled at boundaries: SSE disconnects gracefully on+ client navigation; the insert fires-and-forgets (the payment is+ already settled — a DB hiccup must not roll back the dance).+- Done = open `/club` in two tabs, tip from one, see the row appear+ in both within 500 ms.++## Subagent delegation++### Subagent A (Explore)++> In `/workspaces/three.ws`, return:+>+> 1. The `sql` template binding and migration directory pattern+> (`api/_lib/db.js`, `api/_lib/migrations/*.sql`).+> 2. The most recent migration file as a style template.+> 3. Any existing SSE endpoint in the repo to crib from. Check+> `api/` recursively; if none, fall back to the `api/_lib/http.js`+> helpers and document what's missing.+> 4. How `paidEndpoint` in+> [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js)+> exposes the resolved `payer` / `requirement` to the handler+> function.++Wait for A before Step 1.++## What to implement++### Step 1 — migration++`api/_lib/migrations/2026-05-22-club-tips.sql`:++```sql+create table if not exists club_tips (+ id uuid primary key default gen_random_uuid(),+ ticket_id text not null unique,+ dancer text not null,+ dance text not null,+ clip text,+ label text,+ payer text,+ network text,+ amount_atomics numeric,+ asset text,+ started_at timestamptz not null,+ ends_at timestamptz not null,+ paid_at timestamptz,+ paid_tx text,+ created_at timestamptz not null default now()+);++create index if not exists club_tips_created_at_desc+ on club_tips (created_at desc);++create index if not exists club_tips_dancer_created+ on club_tips (dancer, created_at desc);+```++`paid_at` / `paid_tx` are for prompt 08 (payouts) — schema is added+here so the column doesn't need a second migration.++Apply via the project's standard migration runner.++### Step 2 — insert on settlement++In [api/x402/dance-tip.js](../../api/x402/dance-tip.js) `handler`,+after the ticket object is computed:++```js+import { sql } from '../_lib/db.js';++// fire-and-forget — the payment already settled, do not block the response+sql`+ insert into club_tips+ (ticket_id, dancer, dance, clip, label, payer, network,+ amount_atomics, asset, started_at, ends_at)+ values+ (${ticketId}, ${dancer}, ${style.key}, ${style.clip}, ${style.label},+ ${payer ?? null}, ${requirement?.network ?? null},+ ${requirement?.amount ?? null}, ${requirement?.asset ?? null},+ ${now}, ${ends})+ on conflict (ticket_id) do nothing+`.catch((err) => console.error('[club-tips] insert failed', err));+```++Note: `now` and `ends` are `Date` objects — Postgres accepts ISO via+the parameter binding. `ticketId` becomes a stable variable instead+of inlining `crypto.randomUUID()` into the response.++### Step 3 — GET /api/club/tips++`api/club/tips.js`:++```js+import { sql } from '../_lib/db.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const limit = Math.min(Math.max(Number(req.query?.limit) || 20, 1), 100);+ const dancer = typeof req.query?.dancer === 'string'+ ? req.query.dancer.trim().slice(0, 4)+ : null;++ const rows = await (dancer+ ? sql`+ select ticket_id, dancer, dance, clip, label, payer, network,+ amount_atomics, asset, started_at, ends_at, created_at+ from club_tips+ where dancer = ${dancer}+ order by created_at desc+ limit ${limit}+ `+ : sql`+ select ticket_id, dancer, dance, clip, label, payer, network,+ amount_atomics, asset, started_at, ends_at, created_at+ from club_tips+ order by created_at desc+ limit ${limit}+ `);++ return json(res, 200, { tips: rows });+});+```++### Step 4 — SSE /api/club/tips/stream++`api/club/tips-stream.js`:++```js+import { sql } from '../_lib/db.js';+import { cors, wrap, error } from '../_lib/http.js';++const HEARTBEAT_MS = 15_000;+const POLL_MS = 800;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ res.statusCode = 200;+ res.setHeader('content-type', 'text/event-stream');+ res.setHeader('cache-control', 'no-cache, no-transform');+ res.setHeader('connection', 'keep-alive');+ res.setHeader('x-accel-buffering', 'no');++ let cursor = new Date();+ const send = (event, data) => {+ res.write(`event: ${event}\n`);+ res.write(`data: ${JSON.stringify(data)}\n\n`);+ };+ send('hello', { ts: Date.now() });++ const heartbeat = setInterval(() => res.write(':hb\n\n'), HEARTBEAT_MS);++ const poll = setInterval(async () => {+ try {+ const rows = await sql`+ select ticket_id, dancer, dance, clip, label, payer, network,+ amount_atomics, asset, started_at, ends_at, created_at+ from club_tips+ where created_at > ${cursor}+ order by created_at asc+ limit 50+ `;+ for (const row of rows) {+ cursor = row.created_at > cursor ? row.created_at : cursor;+ send('tip', row);+ }+ } catch (err) {+ console.error('[club-tips-stream] poll failed', err);+ }+ }, POLL_MS);++ req.on('close', () => {+ clearInterval(heartbeat);+ clearInterval(poll);+ res.end();+ });+});+```++The 800 ms poll is the cheapest reliable path against Neon without+adding LISTEN/NOTIFY plumbing. If LISTEN/NOTIFY is already wired in+this repo (subagent A surfaces this), use it instead.++Add a `vercel.json` route entry that gives this endpoint+`maxDuration: 300` so the connection can stay open up to 5 minutes+on Vercel (`Hobby` plan limit). The client reconnects automatically+via `EventSource` after disconnect.++### Step 5 — client subscription++In [src/club.js](../../src/club.js):++```js+async function loadInitialTips() {+ const r = await fetch('/api/club/tips?limit=20');+ if (!r.ok) return;+ const { tips } = await r.json();+ for (const t of tips.reverse()) renderTipRow(t);+}++function subscribeTipStream() {+ let es = null;+ const open = () => {+ es = new EventSource('/api/club/tips/stream');+ es.addEventListener('tip', (e) => {+ try { renderTipRow(JSON.parse(e.data), { live: true }); } catch {}+ });+ es.onerror = () => {+ es?.close();+ setTimeout(open, 1500); // reconnect — backoff naive, fine for now+ };+ };+ open();+ window.addEventListener('beforeunload', () => es?.close());+}+```++Call both in `bootstrap()` after the venue load resolves. Move the+existing `pushFeed(...)` body into `renderTipRow(...)` so the local+tip echo and the SSE echo share rendering.++Dedupe: when a tip lands locally (via the X402 modal callback),+remember its `ticket_id` and skip the SSE row if it arrives. A small+`Set` of last 50 ids handles this.++### Step 6 — error/timeout UX++- If `/api/club/tips` returns non-OK, show "Couldn't load tip+ history" in the feed, retry once after 4s.+- If SSE never connects after 3 retries, show a "live updates+ paused" badge in the feed header.++### Step 7 — tests++`tests/api/club-tips.test.js`:++- Mock `sql`; assert `GET /api/club/tips` returns the rows.+- Assert the `dancer` query param filters and clamps.++`tests/api/club-tips-stream.test.js`:++- Use `node:http` to spin up the handler on a free port.+- Connect with the `eventsource` package, insert a row via the+ mocked `sql`, assert the consumer receives a `tip` event with+ the right `ticket_id`.++`tests/api/dance-tip.test.js`:++- Assert the settlement path inserts into `club_tips` (use a+ test-double `sql` collector).+- Assert duplicate ticket_ids no-op (the `on conflict do nothing`+ clause).++### Step 8 — manual end-to-end++1. Open `/club` in two browser tabs.+2. Tip from tab A.+3. Tab B's feed shows the row within ~1s (poll cadence).+4. Refresh tab A — the row is still there (loaded from DB).+5. Kill the SSE endpoint mid-stream; tab B shows "live updates+ paused"; restart and the badge clears.++## Definition of done++- Migration applied, `club_tips` table live.+- Settlement inserts rows.+- `GET /api/club/tips` returns them.+- `GET /api/club/tips/stream` SSE pushes new ones.+- `/club` subscribes on boot, preloads history, dedupes local echo.+- Two-tab manual test passes.+- `npm test` green.++## Constraints++- Do not block the dance-tip response on the DB insert — the user+ has already paid; a DB hiccup must not surface as a 5xx.+- Do not store anything PII in `club_tips` beyond the payer+ wallet address (already public on-chain).+- Do not poll faster than 800ms — Neon connection budget matters.+- Do not skip the `x-accel-buffering: no` header — without it+ Vercel's gateway buffers the stream and breaks SSE.diff --git a/prompts/club/08-leaderboard-and-payouts.md b/prompts/club/08-leaderboard-and-payouts.mdnew file mode 100644index 000000000..b5addfe04--- /dev/null+++ b/prompts/club/08-leaderboard-and-payouts.md@@ -0,0 +1,307 @@+# Task: Per-dancer leaderboard + automatic tip payout sweep for /club++## Repo context++Working tree: `/workspaces/three.ws`. Once prompt 07 is in,+`club_tips` rows carry every settled tip. To make the rig feel like+a real venue, each dancer needs:++- A leaderboard (last hour / day / all-time, by USDC amount).+- A real wallet address (one Solana, one EVM) where their tips+ accumulate, swept by a cron job.++Existing payout rails live under+[api/payments/solana/[action].js](../../api/payments/solana/[action].js)+and+[api/payments/evm/[action].js](../../api/payments/evm/[action].js).+Existing cron handlers live in+[api/cron/[name].js](../../api/cron/[name].js).++## Rails (CLAUDE.md — non-negotiable)++- No mocks, no test-net payouts pretending to be real. Real Base+ mainnet + Solana mainnet, real USDC, real signatures.+- Payouts idempotent — re-running the cron must not double-pay. The+ `paid_at` + `paid_tx` columns added in prompt 07 carry this.+- Errors handled at boundaries: an RPC failure during sweep retries+ later; the cron must not crash the whole batch on one bad+ dancer.+- Done = a tip → leaderboard update visible → cron sweeps → dancer+ wallet balance increases on-chain → `paid_at` set → leaderboard+ marks the row as paid.++## Subagent delegation++### Subagent A (Explore)++> In `/workspaces/three.ws`, return:+>+> 1. The Solana payout entry point in+> [api/payments/solana/[action].js](../../api/payments/solana/[action].js)+> — function signature, how it gets signing keys, how it builds+> + sends a USDC transfer, how it reports the resulting+> signature.+> 2. The same for+> [api/payments/evm/[action].js](../../api/payments/evm/[action].js).+> 3. The cron-routing convention in+> [api/cron/[name].js](../../api/cron/[name].js) — how new+> handlers are added (the function name pattern,+> `CRON_SECRET` guard, `x-vercel-cron` header).+> 4. The `vercel.json` cron-schedule registration syntax.+> 5. Any existing `api/_lib/payouts*.js` helper.++### Subagent B (Explore)++> Read [docs/internal/PROGRESS.md](../../docs/internal/PROGRESS.md)+> for any prior leaderboard or payout work. Quote anything relevant+> to USDC sweep cadence, fee handling, dust thresholds.++Wait for both.++## What to implement++### Step 1 — schema++`api/_lib/migrations/2026-05-23-club-dancer-wallets.sql`:++```sql+create table if not exists club_dancer_wallets (+ dancer text primary key,+ display_name text not null,+ bio text,+ evm_address text,+ solana_address text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create table if not exists club_payouts (+ id uuid primary key default gen_random_uuid(),+ dancer text not null references club_dancer_wallets(dancer),+ network text not null, -- 'solana' | 'base'+ asset text not null, -- USDC mint / address+ amount_atomics numeric not null,+ tx text not null, -- on-chain signature / hash+ swept_tip_count integer not null,+ created_at timestamptz not null default now()+);++create index if not exists club_payouts_dancer_created+ on club_payouts (dancer, created_at desc);+```++Seed the four dancers with real wallet addresses (passed via env+vars at deploy time, never committed):++```sql+-- Run once via the migration tool with env-var substitution:+insert into club_dancer_wallets (dancer, display_name, evm_address, solana_address)+values+ ('1', 'Nyx', :evm1, :sol1),+ ('2', 'Ari', :evm2, :sol2),+ ('3', 'Sable', :evm3, :sol3),+ ('4', 'Vesper', :evm4, :sol4)+on conflict (dancer) do update set+ evm_address = excluded.evm_address,+ solana_address = excluded.solana_address,+ updated_at = now();+```++### Step 2 — leaderboard endpoint++`api/club/leaderboard.js`:++```js+import { sql } from '../_lib/db.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const window = (req.query?.window || 'all').toString();+ const since = ({+ hour: `now() - interval '1 hour'`,+ day: `now() - interval '24 hours'`,+ week: `now() - interval '7 days'`,+ all: `'epoch'::timestamptz`,+ })[window];+ if (!since) return error(res, 400, 'bad_window', 'window must be hour|day|week|all');++ const rows = await sql.unsafe(`+ select+ d.dancer,+ d.display_name,+ coalesce(sum(t.amount_atomics), 0)::text as total_atomics,+ count(t.*)::int as tip_count,+ coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text+ as unpaid_atomics+ from club_dancer_wallets d+ left join club_tips t+ on t.dancer = d.dancer and t.created_at >= ${since}+ group by d.dancer, d.display_name+ order by total_atomics::numeric desc+ `);++ return json(res, 200, { window, rows });+});+```++Note `sql.unsafe` only because the time window is parameterized via+inline SQL strings selected from a whitelist — never user input.++### Step 3 — leaderboard widget++In [pages/club.html](../../pages/club.html), add a new+`<section class="club-section">` after the "Poles" section:++```html+<section class="club-section">+ <h2>Leaderboard</h2>+ <div class="club-lb-tabs">+ <button class="club-lb-tab is-active" data-window="day">24h</button>+ <button class="club-lb-tab" data-window="hour">1h</button>+ <button class="club-lb-tab" data-window="all">All</button>+ </div>+ <div id="club-lb-rows"></div>+</section>+```++In [src/club.js](../../src/club.js): fetch `/api/club/leaderboard?window=day`+on boot + re-fetch on tab click + re-fetch every 30s while the page+is visible. Render compact rows: rank · headshot · name · USDC ·+tip count.++### Step 4 — payout sweep cron++Extend [api/cron/[name].js](../../api/cron/[name].js) with a new+branch:++```js+case 'club-payouts': return handleClubPayouts(req, res);+```++`handleClubPayouts`:++1. Auth via the existing CRON_SECRET / `x-vercel-cron` guard.+2. Query: per dancer, find unpaid tips grouped by network:++```sql+select+ d.dancer, d.evm_address, d.solana_address,+ t.network, t.asset,+ array_agg(t.id) as tip_ids,+ sum(t.amount_atomics) as total_atomics+from club_tips t+join club_dancer_wallets d on d.dancer = t.dancer+where t.paid_at is null+group by d.dancer, d.evm_address, d.solana_address, t.network, t.asset+having sum(t.amount_atomics) >= ${DUST_THRESHOLD_ATOMICS}+```++`DUST_THRESHOLD_ATOMICS` = `5000` (0.005 USDC) so we don't burn fees+sweeping a single $0.001 tip.++3. For each group:+ - Resolve the recipient wallet by network (evm_address or solana_address).+ - If missing, skip with a log entry (the dancer hasn't registered a wallet on that chain yet).+ - Call the existing payout function from+ `api/payments/{network}/[action].js`. Use the merchant /+ treasury hot wallet as the source — it's already what received+ the original tip.+ - On success, single transaction:+ ```sql+ with payout as (+ insert into club_payouts+ (dancer, network, asset, amount_atomics, tx, swept_tip_count)+ values+ (${dancer}, ${network}, ${asset}, ${total},+ ${signature}, ${tipIds.length})+ returning id+ )+ update club_tips+ set paid_at = now(), paid_tx = ${signature}+ where id = any(${tipIds});+ ```+ - On RPC failure, log + continue to the next dancer (one dancer's+ payout must not block the others).++4. Return a JSON summary of dancers swept + total atomics + tx+ signatures.++### Step 5 — vercel cron schedule++In `vercel.json`, register the cron:++```json+{+ "crons": [+ { "path": "/api/cron/club-payouts", "schedule": "*/5 * * * *" }+ ]+}+```++Every 5 minutes. Dust threshold means cheap-tip-only periods amortize.++### Step 6 — register-wallet flow (one-time admin)++Per-dancer wallets ship via the seeded migration in Step 1, but+also expose a small admin endpoint+`POST /api/admin/club/dancer-wallet` that lets an admin update+`(dancer, evm_address, solana_address, display_name, bio)`.+Use the existing `requireAdmin` + `requireCsrf` guards+([api/admin/user/[id].js](../../api/admin/user/[id].js) is the model).++### Step 7 — tests++`tests/api/club-leaderboard.test.js`:++- Mock `sql`, drive each window, assert SQL shape.+- Assert bad window returns 400.++`tests/api/club-payouts-cron.test.js`:++- Mock the per-network payout fn + `sql`.+- Stage unpaid tips below dust → assert no payout.+- Stage unpaid tips above dust → assert payout, mark-paid, ledger+ row inserted.+- Make one network's RPC throw → assert the other completes; the+ throw is logged, not rethrown.++### Step 8 — manual end-to-end++1. Seed four real wallets (use small-balance test wallets first if+ safer — but they must be mainnet wallets, not devnet).+2. Run a tip from a real wallet for $0.001 USDC.+3. Repeat 5 times so the unpaid total exceeds the dust threshold.+4. Manually invoke `/api/cron/club-payouts` with the CRON_SECRET.+5. Confirm:+ - Solana payout tx visible on Solscan, recipient = dancer+ wallet.+ - `club_tips.paid_at` is set on those rows.+ - `club_payouts` has a new ledger row.+ - Leaderboard "unpaid" column drops to ~0.++## Definition of done++- Schema applied; four dancers seeded with real mainnet wallets.+- `GET /api/club/leaderboard` returns ranked rows.+- Leaderboard widget renders + auto-refreshes.+- Cron handler `club-payouts` sweeps unpaid tips, sends real USDC,+ idempotent on retry.+- Admin endpoint to register/update dancer wallets.+- Tests green; manual mainnet sweep observed once.++## Constraints++- Do not skip the dust threshold — sweeping a single $0.001 tip+ costs more in fees than the tip itself.+- Do not store private keys in any new table. The treasury signing+ key already lives in the deploy env vars; sweeps re-use it.+- Do not run the cron faster than every 5 minutes — RPC budget and+ fee amortization matter.+- Do not let one dancer's RPC failure crash the cron batch — wrap+ per-dancer in try/catch.+- Do not let the leaderboard endpoint accept arbitrary windows. The+ `{hour,day,week,all}` whitelist is non-negotiable; `sql.unsafe`+ is only safe with that whitelist.diff --git a/prompts/club/09-mobile-and-perf.md b/prompts/club/09-mobile-and-perf.mdnew file mode 100644index 000000000..8901e107d--- /dev/null+++ b/prompts/club/09-mobile-and-perf.md@@ -0,0 +1,222 @@+# Task: Mobile layout + low-perf rendering path for /club++## Repo context++Working tree: `/workspaces/three.ws`. The /club page has a mobile+breakpoint at `@media (max-width: 800px)` in+[pages/club.html](../../pages/club.html) that switches the grid to+stacked. That handles layout but not rendering cost — once prompts+01–04 ship the venue, dancers, bloom, mirror ball, and volumetric+cones, a mid-range Android phone will not survive at 60 fps.++## Rails (CLAUDE.md — non-negotiable)++- No "mobile downgrade" that renders a different scene — render the+ same scene with fewer pixels/passes/lights, do not fake it.+- No `setTimeout`-throttled animate loop. Drop work, not frames.+- Real detection: hardwareConcurrency + deviceMemory + pointer+ type + GPU tier. Pick a profile once at boot.+- Done = a real iPhone 12 and a real Pixel 6 render the club at+ ≥30 fps with no Safari/Chrome warnings.++## What to implement++### Step 1 — perf-profile detection++New file `src/club-perf.js`:++```js+export function detectProfile() {+ const ua = navigator.userAgent;+ const isMobile = /(iPhone|iPad|Android|Mobi)/i.test(ua);+ const lowMem = (navigator.deviceMemory ?? 8) < 4;+ const lowCores = (navigator.hardwareConcurrency ?? 8) < 4;+ const coarse = window.matchMedia?.('(pointer: coarse)').matches;++ if (!isMobile && !lowMem && !lowCores) return 'high';+ if (isMobile && (lowMem || lowCores)) return 'low';+ if (coarse) return 'medium';+ return 'medium';+}++export const PROFILES = {+ high: {+ pixelRatio: Math.min(window.devicePixelRatio, 2),+ shadows: true,+ shadowMapSize: 1024,+ bloom: true,+ chromaticAberration: true,+ mirrorBall: true,+ cubeCam: true,+ volumetricCones: true,+ crowdInstances: 80,+ discoLights: 4,+ },+ medium: {+ pixelRatio: Math.min(window.devicePixelRatio, 1.5),+ shadows: true,+ shadowMapSize: 512,+ bloom: true,+ chromaticAberration: false,+ mirrorBall: true,+ cubeCam: false, // mirror ball uses static reflection texture+ volumetricCones: true,+ crowdInstances: 40,+ discoLights: 4,+ },+ low: {+ pixelRatio: 1.0,+ shadows: false,+ shadowMapSize: 0,+ bloom: false,+ chromaticAberration: false,+ mirrorBall: false,+ cubeCam: false,+ volumetricCones: false,+ crowdInstances: 12,+ discoLights: 2,+ },+};+```++### Step 2 — apply profile at boot++In [src/club.js](../../src/club.js) `bootstrap()`:++```js+import { detectProfile, PROFILES } from './club-perf.js';+const profile = PROFILES[detectProfile()];++renderer.setPixelRatio(profile.pixelRatio);+renderer.shadowMap.enabled = profile.shadows;+```++Pass the profile into:++- `attachVenue` (skips mirror-ball cube cam if `cubeCam === false`;+ uses a static `MeshBasicMaterial` reflection texture instead).+- `PoleStation` (skips volumetric cone construction if+ `volumetricCones === false`).+- `EffectComposer` (skips bloom pass if `bloom === false`,+ skips chromatic aberration pass if not configured).+- Crowd instance count.+- `discoLights` count.++### Step 3 — dynamic scaling++Even with a profile, a phone can throttle mid-session. Add a frame-+budget watchdog in the animate loop:++```js+let frameAvg = 1 / 60;+function animate() {+ const dt = Math.min(clock.getDelta(), 0.066);+ frameAvg = frameAvg * 0.94 + dt * 0.06;+ // ...+}+```++If `frameAvg > 1 / 28` for >2 consecutive seconds, downgrade one+step (`high → medium → low`) and re-apply. Never upgrade+automatically — a recovery means the user moved off a busy moment;+sticking at lower quality is safer.++Emit a debug `console.info('[club] downgrading profile to', next)`+so we can diagnose from a remote screenshot.++### Step 4 — mobile layout polish++The existing breakpoint at `max-width: 800px` stacks the panel+under the canvas, but the panel becomes a long scroll. Mobile-only+tweaks:++- Hide the leaderboard widget under a collapsed disclosure+ `<details>` to keep the viewport mostly canvas.+- The right panel becomes a swipe-up bottom sheet (CSS `transform`+ on a single drag handle, no JS gesture library).+- VIP cam button on each pole card gets bigger touch target+ (44×44 min).+- `touch-action: none` on the canvas (already set), but `pan-y` on+ the panel so the user can scroll the feed without orbit+ intercepting.++### Step 5 — pause when hidden++Add a `visibilitychange` listener that pauses `animate` when the+tab is hidden:++```js+let rafId = null;+function animate() {+ // ...+ rafId = requestAnimationFrame(animate);+}+document.addEventListener('visibilitychange', () => {+ if (document.hidden) cancelAnimationFrame(rafId);+ else { clock.getDelta(); animate(); } // discard the gap delta+});+```++Saves battery on mobile when the user backgrounds the tab.++### Step 6 — asset budget++The combined first-load budget after prompts 01–04:++| Asset | Cap |+|---|---|+| `club-venue.glb` | 8 MB compressed |+| 4× dancer GLBs | 8 MB total |+| `pole.glb` + `stage.glb` | 1 MB |+| `mirrorball.glb` (if shipped) | 200 KB |+| HDRI | 2 MB |+| Animation clip JSON (lazy) | ~150 KB per clip; lazy-loaded |+| Audio (lazy) | ~1 MB per track; lazy-loaded |+| JS bundle (Vite) | ≤500 KB gzipped |++Total eager budget: ~20 MB. On a 4G connection (~3 Mbps real)+that's ~7s. With Vite's preload + http/2, plausibly under 5s.++Wire a `setStatus` progress bar that aggregates progress events+across the parallel loads (already piped from prompt 01).++### Step 7 — tests++`tests/club-perf.test.js`:++- Stub `navigator.deviceMemory`, `hardwareConcurrency`,+ `userAgent`. Assert profile detection picks the right tier for+ each combination.+- Assert `PROFILES.low` disables bloom + shadows + cube cam.++### Step 8 — manual end-to-end++Required device matrix:++- iPhone 12 / Safari (latest) — should select `medium`, render+ ≥30 fps.+- Pixel 6 / Chrome — should select `medium`, render ≥30 fps.+- A 2020 ChromeBook — should select `low`, render ≥30 fps.+- Modern Mac/PC desktop — `high`, ≥60 fps.++Document the observed profile + fps per device in+`docs/club/PERF_NOTES.md`.++## Definition of done++- `src/club-perf.js` detects profile and exports it.+- All scene/render features gate on profile flags.+- Watchdog downgrades on sustained slow frames.+- Pause on hidden tab.+- Tested on real iPhone + Pixel + ChromeBook.+- Tests green.++## Constraints++- Do not gate features by user agent string parsing alone. Use the+ capability signals (`deviceMemory`, `hardwareConcurrency`,+ `pointer: coarse`); UA is a fallback only.+- Do not show a "your device is too slow" message — silently degrade.+- Do not skip the `visibilitychange` pause — on mobile, leaving the+ rAF loop running in a hidden tab heats the phone.+- Do not auto-upgrade the profile mid-session.diff --git a/prompts/club/10-e2e-tests-and-verification.md b/prompts/club/10-e2e-tests-and-verification.mdnew file mode 100644index 000000000..4a2b2d441--- /dev/null+++ b/prompts/club/10-e2e-tests-and-verification.md@@ -0,0 +1,294 @@+# Task: End-to-end tests + manual verification matrix for /club++## Repo context++Working tree: `/workspaces/three.ws`. The /club page is touched by+many systems — x402 settlement, animation manager, SSE feed, cron+payouts, Web Audio, post-processing. Each prior prompt ships its+own unit tests. This prompt adds:++- A Playwright smoke that boots the dev server, loads `/club`,+ intercepts the x402 settle, and asserts visible behavior.+- A real-wallet mainnet manual verification checklist used before+ every release.++## Rails (CLAUDE.md — non-negotiable)++- No mocked browser. Playwright drives a real Chromium.+- The smoke MAY stub the x402 settle network response (signing a+ mainnet tx in CI is unsafe) — but the stub must produce the same+ JSON shape the real endpoint produces.+- Visual asserts: count of canvas-visible meshes, console errors,+ network success — not pixel-perfect screenshots (too brittle).+- Manual matrix is signed-off by a human; no agent ticks it.++## Subagent delegation++### Subagent A (Explore)++> In `/workspaces/three.ws`, return:+>+> 1. Whether Playwright is already a dev dep — check+> [package.json](../../package.json).+> 2. If yes, the existing `playwright.config.*` and any spec dir.+> 3. The `npm run dev` boot pattern (port, env vars required, how+> long it takes to be ready).+> 4. The repo's existing `test` script — does `npm test` invoke+> Playwright today, or just Vitest/Jest?++Wait for A.++## What to implement++### Step 1 — Playwright wiring++If Playwright is not yet a dep:++```bash+npm install --save-dev @playwright/test+npx playwright install chromium+```++Create `playwright.config.js` at repo root:++```js+import { defineConfig } from '@playwright/test';++export default defineConfig({+ testDir: 'tests/e2e',+ timeout: 60_000,+ retries: 1,+ fullyParallel: false,+ use: {+ baseURL: 'http://localhost:3000',+ headless: true,+ screenshot: 'only-on-failure',+ video: 'retain-on-failure',+ trace: 'retain-on-failure',+ },+ webServer: {+ command: 'npm run dev',+ url: 'http://localhost:3000',+ timeout: 60_000,+ reuseExistingServer: !process.env.CI,+ },+});+```++Add to `package.json`:++```json+"scripts": {+ "test:e2e": "playwright test",+ "test": "vitest run && playwright test"+}+```++(Adjust to whatever the existing `test` script does — keep the unit+test runner the way subagent A reports it.)++### Step 2 — Playwright smoke for /club++`tests/e2e/club.spec.js`:++```js+import { test, expect } from '@playwright/test';++test.describe('/club', () => {+ test('venue loads + tip settles + dancer performs', async ({ page }) => {+ const consoleErrors = [];+ page.on('console', (m) => {+ if (m.type() === 'error') consoleErrors.push(m.text());+ });++ // Stub the x402 settle endpoint to return a deterministic ticket.+ await page.route('**/api/x402/dance-tip*', async (route) => {+ const url = route.request().url();+ const u = new URL(url);+ const dancer = u.searchParams.get('dancer') ?? '1';+ const dance = u.searchParams.get('dance') ?? 'rumba';+ // First call: 402 challenge; we tell the X402 helper to skip the modal+ // by injecting a flag in window before tipping.+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ ok: true,+ ticketId: 'e2e-ticket-1',+ dancer, dance, clip: 'rumba', label: 'Rumba',+ loop: true, durationSec: 6,+ startsAt: new Date().toISOString(),+ endsAt: new Date(Date.now() + 6000).toISOString(),+ payer: 'e2e-test-payer',+ network: 'solana',+ amountAtomics: '1000',+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ }),+ });+ });++ // Bypass the X402 wallet modal by stubbing window.X402.pay before any+ // module runs (Vite ESM order makes this race-prone; use addInitScript).+ await page.addInitScript(() => {+ window.X402 = {+ pay: async ({ endpoint }) => {+ const r = await fetch(endpoint);+ return { result: await r.json() };+ },+ };+ });++ await page.goto('/club');++ // Venue must finish loading (status pill flips to 'ok').+ await expect(page.locator('#club-status')).toHaveAttribute('data-kind', 'ok', { timeout: 30_000 });++ // Tip pole 1.+ await page.locator('.club-tip-btn[data-dancer="1"]').click();++ // Tip-feed row appears for dancer 1.+ await expect(page.locator('.club-tip-row').first()).toContainText('dancer 1');++ // No console errors during the run.+ expect(consoleErrors, consoleErrors.join('\n')).toHaveLength(0);+ });++ test('keyboard VIP cam shortcuts work', async ({ page }) => {+ await page.goto('/club');+ await page.keyboard.press('2');+ // No way to read camera pose from outside three.js cheaply — assert via+ // a debug DOM attribute the camera state machine writes for tests.+ await expect(page.locator('#club-stage')).toHaveAttribute('data-cam-mode', 'vip');+ await page.keyboard.press('Escape');+ await expect(page.locator('#club-stage')).toHaveAttribute('data-cam-mode', 'free');+ });++ test('leaderboard renders + tab switching', async ({ page }) => {+ await page.route('**/api/club/leaderboard*', async (route) => {+ await route.fulfill({+ status: 200, contentType: 'application/json',+ body: JSON.stringify({+ window: 'day',+ rows: [+ { dancer: '1', display_name: 'Nyx', total_atomics: '4000', tip_count: 4, unpaid_atomics: '4000' },+ { dancer: '2', display_name: 'Ari', total_atomics: '3000', tip_count: 3, unpaid_atomics: '0' },+ { dancer: '3', display_name: 'Sable', total_atomics: '1000', tip_count: 1, unpaid_atomics: '0' },+ { dancer: '4', display_name: 'Vesper', total_atomics: '0', tip_count: 0, unpaid_atomics: '0' },+ ],+ }),+ });+ });+ await page.goto('/club');+ await expect(page.locator('#club-lb-rows .club-lb-row').first()).toContainText('Nyx');+ });+});+```++Test depends on prompts 06 (camera state DOM attribute) and 08+(leaderboard widget) — if those haven't shipped yet, mark the+specific assertions as `test.skip()` with a tracking comment, do+not delete them.++### Step 3 — DOM hooks for tests++Add the camera-mode attribute write in+[src/club.js](../../src/club.js) (prompt 06):++```js+clubCam.onModeChange = (mode) => {+ document.querySelector('#club-stage')?.setAttribute('data-cam-mode', mode);+};+```++These are zero-cost in production and the only way Playwright can+introspect the three.js state without injecting probes.++### Step 4 — CI integration++If the repo has a CI workflow (`.github/workflows/*.yml`), add:++```yaml+- name: Install Playwright+ run: npx playwright install --with-deps chromium+- name: E2E+ run: npm run test:e2e+```++If no CI workflow exists yet, skip this step — manual `npm run+test:e2e` from a dev box covers it.++### Step 5 — manual verification checklist++Create `docs/club/RELEASE_CHECKLIST.md` (the file is read once per+release, not by CI):++```markdown+# /club release checklist++Run on a clean checkout after `npm install && npm run build`.++## Local smoke+- [ ] `npm run dev` boots, `/club` loads under 5s on broadband.+- [ ] Venue renders authored GLB, no console errors.+- [ ] All four dancers visible at backstage doors.+- [ ] `npm test` green (unit + e2e).+- [ ] `npm run test:e2e` green standalone.++## Real wallet (mainnet)+- [ ] Connect Phantom on Solana. Tip pole 1 for $0.001 USDC.+- [ ] On-chain confirmation in Solscan within 5s.+- [ ] Dancer 1 walks from backstage to pole.+- [ ] Music for the chosen style fades up; ambience fades down.+- [ ] Volumetric spotlight cone ramps up.+- [ ] Tip row appears in the right-panel feed.+- [ ] Open `/club` in a second browser; same tip row appears via SSE.++## Cron payouts+- [ ] Repeat tips until dancer 1's unpaid total exceeds 0.005 USDC.+- [ ] Trigger `/api/cron/club-payouts` with CRON_SECRET.+- [ ] On-chain payout signature recorded in `club_payouts`.+- [ ] `club_tips.paid_at` set on swept rows.+- [ ] Leaderboard "unpaid" column drops for dancer 1.++## Mobile+- [ ] iPhone 12 Safari: profile `medium`, ≥30 fps.+- [ ] Pixel 6 Chrome: profile `medium`, ≥30 fps.++## Deploy+- [ ] Vercel preview deploy of the branch passes both x402 endpoints+ reachable + SSE keepalive.+- [ ] Promote to production.+- [ ] Verify production OG card renders for `/club` via Twitter card+ validator.+- [ ] Verify x402 bazaar discovery: `curl -i https://three.ws/api/x402/dance-tip`+ returns 402 with the discovery extension intact.+```++This file is human-signed. CI does not check it.++### Step 6 — manual end-to-end++Run the checklist end-to-end on a clean checkout. Record results in+`docs/internal/PROGRESS.md` (extend the existing log).++## Definition of done++- Playwright wired into the repo with `tests/e2e/club.spec.js`.+- The three smoke specs pass against `npm run dev`.+- DOM test hooks (`data-cam-mode` etc.) added where the camera+ state machine writes them.+- `docs/club/RELEASE_CHECKLIST.md` exists and has been run once+ end-to-end with results captured.++## Constraints++- Do not stub the unit-test layer's `sql` template inside the+ Playwright run — the e2e suite must exercise the real DB if the+ prompts 07/08 features are in. Use a per-branch Neon database or+ a local Postgres container if CI runs Playwright.+- Do not commit any private key, mnemonic, or wallet secret into+ the checklist file. Reference env var names only.+- Do not gate releases on pixel-perfect screenshot diffs. Visual+ regression for a moody dark club is fragile.+- Do not skip the manual mainnet verification before a release —+ the agent suite cannot prove the on-chain payout path works.diff --git a/prompts/siwx/04-wire-endpoints.md b/prompts/siwx/04-wire-endpoints.mdnew file mode 100644index 000000000..e462e5cef--- /dev/null+++ b/prompts/siwx/04-wire-endpoints.md@@ -0,0 +1,327 @@+# SIWX prompt 04 — opt in existing endpoints + add the canonical asset-download endpoint++## Context++three.ws workspace at `/workspaces/three.ws`. Architecture in+[prompts/siwx/PLAN.md](PLAN.md). Prompt 03 added an optional `siwx:` field+to `paidEndpoint(spec)` in+[api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js).++This prompt is **step 4 of 7** — turning on SIWX for real endpoints. We do+three things:++1. Opt in `skill-marketplace` and `dance-tip` (existing endpoints).+2. Ship a brand-new `asset-download` endpoint that is the textbook "buy+ once, re-download forever" use case — a creator uploads a GLB / avatar /+ accessory, prices it, buyers pay once via x402, and afterwards any+ wallet on the grant list can re-download by signing.+3. Surface SIWX status on the `/api/x402-status` page so we can debug.++## Rails (CLAUDE.md, non-negotiable)++- No mocks. No fake data. No placeholders. No TODOs. No stubs. No commented-+ out code. No `setTimeout` fake-loading. No fallback sample arrays.+- Real R2 (or whatever object store this repo already uses — check+ [api/_lib/r2.js](../../api/_lib/r2.js)) for the asset bytes.+- Real Neon for listing rows.+- Real signed URLs / streams from R2 — don't proxy bytes through Vercel+ unless you've checked the file is small (<5MB) and the route stays+ under Vercel's response size limits.+- Done = endpoint works end-to-end in `npm run dev`, browser console clean,+ network tab shows the SIWX retry returning 200, payments table has the+ expected row, `git diff` reviewed.++## Files to edit / create++### A. Opt in `api/x402/skill-marketplace.js`++The marketplace catalog is polled by agent shoppers — paying $0.001 per+poll is fine the first time, but a returning agent should be able to+re-fetch for free by signing. Add to the existing `paidEndpoint({...})`+spec:++```js+siwx: {+ statement: 'Sign in to refresh the three.ws skill marketplace without re-paying.',+ ttlSeconds: 24 * 3600, // grants expire after 24h so prices stay paid-fresh+ expirationSeconds: 300,+},+```++Nothing else changes — the handler doesn't care whether it served via+payment or signature. Verify by re-reading the file after your edit; the+diff should be exactly the new `siwx:` block.++### B. Opt in `api/x402/dance-tip.js`++A tipper who paid to make Dancer 1 perform Rumba should be able to retrigger+the same performance later from the same wallet without re-paying. But each+new `(dancer, dance)` combination is a fresh purchase. The grant key is the+endpoint URL, not the query params — so we add `siwx:` but keep grants+permanent (one wallet = one free repeat of any previously-paid combo).++The handler currently issues a fresh `ticketId` per call. Keep that — the+ticket is per-performance, not per-grant. The signing flow just lets the+buyer skip the payment step before the ticket is issued.++```js+siwx: {+ statement: 'Sign in to retrigger a dance you already tipped for.',+ ttlSeconds: null, // permanent grant+ expirationSeconds: 300,+},+```++### C. New endpoint — `api/x402/asset-download.js`++This is the marquee SIWX example. Creators monetize 3D assets; buyers pay+once and re-download as many times as they want from the same wallet.++Schema (already exists or add via migration if not — check+[api/_lib/migrations/](../../api/_lib/migrations/) first):++```sql+-- in api/_lib/migrations/2026-05-21-paid-assets.sql, IF not already present+CREATE TABLE IF NOT EXISTS paid_assets (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ slug text NOT NULL UNIQUE, -- 'rumba-dancer-glb', 'cz-avatar', ...+ title text NOT NULL,+ description text NOT NULL,+ mime_type text NOT NULL, -- 'model/gltf-binary', 'image/png', ...+ size_bytes bigint NOT NULL,+ r2_key text NOT NULL, -- e.g. 'assets/rumba-dancer.glb'+ price_atomics text NOT NULL, -- USDC atomics, '5000' = $0.005+ creator_payto_base text, -- optional override; defaults to env.X402_PAY_TO_BASE+ creator_payto_solana text, -- optional override; defaults to env.X402_PAY_TO_SOLANA+ created_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS paid_assets_slug_idx ON paid_assets (slug);+```++Apply the same way prompt 01's migration was applied (one-shot+`scripts/apply-paid-assets-migration.mjs` modeled on+`scripts/apply-siwx-migration.mjs`).++#### Endpoint behavior++`GET /api/x402/asset-download?slug=<slug>` →++- 402 if no payment + no SIWX. Challenge includes the asset's price (per-asset+ override of `priceAtomics`) and the SIWX extension.+- 200 + binary body (correct `Content-Type`, `Content-Length`, and `Content-+ Disposition: attachment; filename="<slug>.<ext>"`) on success.++Implementation outline (write the full file, no shortcuts):++```js+// api/x402/asset-download.js+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema, X402Error } from '../_lib/x402-spec.js';+import { sql } from '../_lib/db.js';+import { getAssetStream, getAssetBytes } from '../_lib/r2.js'; // use existing R2 client++const ROUTE = '/api/x402/asset-download';++const DESCRIPTION =+ 'three.ws Asset Bazaar — pay once in USDC to unlock a 3D asset (GLB, ' ++ 'avatar, accessory). Wallets that have already paid can re-download for ' ++ 'free by signing in with SIWX (CAIP-122). Each asset has its own price ' ++ 'and creator payout address.';++const INPUT_EXAMPLE = { slug: 'rumba-dancer-glb' };++const INPUT_SCHEMA = { /* slug: string required */ };++const OUTPUT_EXAMPLE = {+ ok: true,+ slug: 'rumba-dancer-glb',+ title: 'Rumba Dancer GLB',+ mimeType: 'model/gltf-binary',+ sizeBytes: 1843201,+ downloadUrl: 'https://...presigned R2 URL...', // when stream-via-presigned+};++// NOTE on shape: prefer responding with a short-lived presigned R2 URL+// when the asset is > 1MB. Proxying through Vercel works for small assets+// (avatars, accessories) but blows past Vercel's body-size limits for+// full-size GLBs.++export default async function handler(req, res) {+ const slug = req.query?.slug ? String(req.query.slug).trim() : null;+ if (!slug) {+ res.statusCode = 400;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ error: 'slug required' }));+ return;+ }++ const [asset] = await sql`+ SELECT id, slug, title, description, mime_type, size_bytes, r2_key,+ price_atomics, creator_payto_base, creator_payto_solana+ FROM paid_assets+ WHERE slug = ${slug}+ LIMIT 1+ `;+ if (!asset) {+ res.statusCode = 404;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ error: 'asset not found' }));+ return;+ }++ // Build a per-asset paidEndpoint on the fly: price + per-creator payout+ // come from the row, everything else is shared.+ const inner = paidEndpoint({+ route: ROUTE,+ method: 'GET',+ priceAtomics: asset.price_atomics,+ networks: ['base', 'solana'],+ description: `${DESCRIPTION} — currently delivering: ${asset.title}.`,+ mimeType: asset.mime_type,+ bazaar: {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'GET', queryParams: INPUT_EXAMPLE },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'GET',+ queryParamsSchema: INPUT_SCHEMA,+ outputSchema: { /* full schema */ },+ }),+ },+ siwx: {+ statement: `Sign in to re-download "${asset.title}" without re-paying.`,+ ttlSeconds: null, // permanent grant per (asset, wallet)+ expirationSeconds: 300,+ },+ async handler({ req, res }) {+ // Stream the file (presigned URL preferred — see comment above).+ const presigned = await getAssetStream(asset.r2_key, { expiresSec: 60 });+ return {+ ok: true,+ slug: asset.slug,+ title: asset.title,+ mimeType: asset.mime_type,+ sizeBytes: Number(asset.size_bytes),+ downloadUrl: presigned.url,+ };+ },+ });++ return inner(req, res);+}+```++**Important — per-creator payouts.** If `asset.creator_payto_base` or+`asset.creator_payto_solana` is set, the `paidEndpoint` you build inline+needs to use those instead of the shared `env.X402_PAY_TO_*`. The current+`buildAccept()` in `api/_lib/x402-paid-endpoint.js` reads directly from+`env`. Extend `paidEndpoint(spec)` (in this prompt OR push back to prompt+03 and update both) to accept an optional `payTo: { base?, solana?, bsc? }`+override map, and have `buildAccept()` fall back to env when a key is+missing. Document this change in the helper's file-top comment.++#### Seed two real assets++In a new file `scripts/seed-paid-assets.mjs`, upload two real GLBs that+already live in this repo (e.g. `public/avatars/<name>.glb` — `ls+public/avatars/*.glb`) to R2 under `assets/<slug>.glb` and insert the rows.+**No placeholders** — actually push the bytes and write the row with the+real `size_bytes` from `fs.statSync(file).size`. The script is idempotent+(slug is UNIQUE; use `ON CONFLICT (slug) DO NOTHING`).++Pick two slugs that map to assets the team will recognize:++- `pole-dancer-rumba` — points at the same GLB the /club page uses for Rumba.+- One avatar GLB from `public/avatars/`.++Price both at `5000` atomics ($0.005).++#### Register the route in `vercel.json`++Check the existing `vercel.json` rewrites/functions block. The current+catch-all `api/x402/*.js` rewrite (collapsed in recent commits — see+`36dfec9a fix(vercel): collapse functions block to a single wildcard`) most+likely already routes `/api/x402/asset-download` automatically. Confirm via+`grep -n asset-download vercel.json` plus a `curl -sI http://localhost:3000/api/x402/asset-download?slug=...`+after `npm run dev`.++### D. Surface SIWX status on `/api/x402-status`++Read [api/x402-status.js](../../api/x402-status.js) and append a new section+to the JSON it returns:++```js+siwx: {+ configured: true,+ paymentsRowCount: <int from `select count(*) from siwx_payments`>,+ noncesRowCount: <int from `select count(*) from siwx_nonces`>,+ evmVerifierConfigured: Boolean(env.BASE_RPC_URL),+}+```++Wrap the count queries in a try/catch — `siwx_payments` may not exist on a+brand-new database — and return `{ configured: false, error: err.message }`+when the SELECT throws. Don't fail the whole status endpoint.++### E. Documentation++Add one section to [docs/api-reference.md](../../docs/api-reference.md) (or+the closest existing reference page — check `ls docs/`) describing:++- The SIWX flow on three.ws.+- The `sign-in-with-x` extension declared in 402 bodies.+- The `SIGN-IN-WITH-X` header clients send to skip payment.+- That `paid_assets` is the canonical example, and that any new+ `paidEndpoint()` can opt in by adding `siwx: { statement, ttlSeconds }`.++Keep it to ~60 lines. No marketing copy.++## Verification you must perform++```bash+# 1. Migrations applied+DATABASE_URL=$DATABASE_URL node scripts/apply-siwx-migration.mjs+DATABASE_URL=$DATABASE_URL node scripts/apply-paid-assets-migration.mjs++# 2. Seed runs (uploads to R2, inserts rows)+R2_*=... DATABASE_URL=$DATABASE_URL node scripts/seed-paid-assets.mjs++# 3. Dev server up+npm run dev+# In a second terminal:++# 4a. First request: 402 with SIWX extension declared+curl -sS http://localhost:3000/api/x402/asset-download?slug=pole-dancer-rumba | jq .+curl -sSI http://localhost:3000/api/x402/asset-download?slug=pole-dancer-rumba | grep -i payment-required+# Confirm the PAYMENT-REQUIRED header decodes to a body containing+# extensions['sign-in-with-x'].++# 4b. /api/x402-status reports siwx { configured: true, ... }+curl -sS http://localhost:3000/api/x402-status | jq .siwx++# 4c. Existing endpoints still work+curl -sS http://localhost:3000/api/x402/skill-marketplace | jq .+curl -sS 'http://localhost:3000/api/x402/dance-tip?dancer=1&dance=rumba' | jq .+```++You don't need to drive the SIWX retry from `curl` here — that's the+verify dance in prompt 07. For this prompt the goal is: the extension is+advertised, the seed assets exist, the status endpoint sees the tables.++## Done means++- `api/x402/skill-marketplace.js` and `api/x402/dance-tip.js` each have one+ new `siwx:` block in their `paidEndpoint(...)` call; no other diff.+- `api/x402/asset-download.js` exists, is end-to-end wired, returns+ presigned R2 URLs, and respects per-asset payout overrides.+- `paid_assets` table exists and is seeded with two real GLBs from `public/`.+- `api/x402-status.js` reports SIWX configuration + table counts.+- `docs/api-reference.md` (or equivalent) explains the flow.+- Browser test on http://localhost:3000 shows clean network tab + no+ console errors when hitting the three endpoints.+- `git diff` reviewed.++Do not commit or push.diff --git a/prompts/siwx/05-browser-modal.md b/prompts/siwx/05-browser-modal.mdnew file mode 100644index 000000000..8723e46c5--- /dev/null+++ b/prompts/siwx/05-browser-modal.md@@ -0,0 +1,281 @@+# SIWX prompt 05 — browser modal: detect SIWX, sign with wallet, retry++## Context++three.ws workspace at `/workspaces/three.ws`. Architecture in+[prompts/siwx/PLAN.md](PLAN.md). Prompts 03 + 04 mean every paid endpoint+that opts into SIWX now advertises the extension in its 402 body and+accepts a `SIGN-IN-WITH-X` header instead of payment for previously-paid+wallets.++This prompt is **step 5 of 7** — the browser side. The drop-in modal lives+at [public/x402.js](../../public/x402.js) (~910 lines). It currently drives+the **payment** flow for EVM (Base USDC via EIP-3009 + `window.ethereum`)+and Solana (Phantom + SPL transfer). You're extending it to also drive the+**sign-in** flow, so a returning buyer's first click is one signature+instead of one payment.++## UX target++When the user clicks an `[data-x402-endpoint]` element:++1. Modal POPs as today, with merchant + action labels.+2. Modal hits the endpoint, gets 402, decodes body.+3. **If body contains `extensions['sign-in-with-x']`:**+ - Modal shows **two** primary buttons: "Sign in with wallet" (top,+ primary) and "Pay $X.XXX USDC" (below, secondary).+ - User clicks "Sign in with wallet" → wallet picker (same EVM/Solana+ branch as the payment flow) → sign the CAIP-122 message → retry the+ endpoint with `SIGN-IN-WITH-X` header.+ - If retry returns 200 → success path identical to a paid call.+ - If retry returns 401/402 with `code: siwx_not_paid` → modal swaps to+ "You haven't paid for this yet — pay now" and proceeds via the payment+ flow (same as if SIWX hadn't been offered).+4. If body does NOT contain the SIWX extension → behavior unchanged.++No new merchant-side API: same `<button data-x402-endpoint>` works. Same+`window.X402.pay({...})` programmatic call works. The modal just gains a+new code path internally.++## Rails (CLAUDE.md, non-negotiable)++- No mocks. No fake data. No placeholders. No TODOs. No stubs. No commented-+ out code in the shipped file.+- No `setTimeout` fake-loading. No fallback sample arrays.+- Real wallet APIs: `window.ethereum` (viem under the hood is OK but the+ modal currently uses raw `eth_signTypedData_v4` — staying consistent with+ that is fine), `window.solana` / Phantom adapter.+- Real signature verification happens server-side via prompt 03; the+ browser just constructs + signs + posts the header.+- Done = `npm run dev` up, exercised on the `/club` page and any+ `data-x402-endpoint` button, signing flow succeeds, retry returns 200,+ no console errors, no network errors except deliberate 402/401.++## Files to edit / create++### File 1 — `public/x402.js` (edit)++Add SIWX support without breaking the existing payment flow. Suggested+structure:++1. **Constants** at top of file:++ ```js+ const SIWX_HEADER = 'SIGN-IN-WITH-X';+ const SIWX_EXTENSION_KEY = 'sign-in-with-x';+ ```++2. **Helper: detect SIWX in 402 body.**++ ```js+ function extractSiwxExtension(body) {+ const ext = body?.extensions?.[SIWX_EXTENSION_KEY];+ if (!ext || !ext.info || !Array.isArray(ext.supportedChains)) return null;+ return ext;+ }+ ```++3. **Helper: match the user's wallet against `supportedChains`.**++ ```js+ // Returns { chain, kind: 'evm' | 'solana' } or null.+ function pickSiwxChain(ext, walletKind) {+ for (const chain of ext.supportedChains) {+ if (walletKind === 'evm' && chain.type === 'eip191') return { chain, kind: 'evm' };+ if (walletKind === 'solana' && chain.type === 'ed25519') return { chain, kind: 'solana' };+ }+ return null;+ }+ ```++4. **Helper: build the CAIP-122 message string locally.**++ The upstream `formatSIWEMessage` / `formatSIWSMessage` are not exported+ to the browser bundle without a build step. The CAIP-122 message format+ is small enough to reconstruct here — match the spec exactly:++ ```+ <domain> wants you to sign in with your <Ethereum|Solana> account:+ <address>++ <statement>++ URI: <uri>+ Version: 1+ Chain ID: <chainRef> ← numeric for EVM (extract from "eip155:<n>"), genesis-hash for Solana+ Nonce: <nonce>+ Issued At: <issuedAt>+ ```++ Optional fields (`Expiration Time`, `Not Before`, `Request ID`,+ `Resources`) follow on subsequent lines per CAIP-122. Build them+ conditionally; an empty list means omit the line entirely.++ For exact line-by-line correctness re-read+ `node_modules/@x402/extensions/dist/esm/sign-in-with-x/index.d.mts`+ for the field list. Anything you emit must be parseable by+ `parseSIWxHeader` on the server.++5. **Helper: build the encoded `SIGN-IN-WITH-X` header value.**++ ```js+ function encodeSiwxHeader(payload) {+ // base64-encoded JSON per x402 v2 spec.+ const json = JSON.stringify(payload);+ // btoa is fine for ASCII JSON (no non-Latin-1 chars in CAIP-122 fields).+ return btoa(unescape(encodeURIComponent(json)));+ }+ ```++6. **EVM signing.** Reuse the existing wallet-connection path. Once you+ have an address, call:++ ```js+ const signature = await ethereum.request({+ method: 'personal_sign',+ params: [message, address],+ });+ ```++ Build the payload:++ ```js+ const payload = {+ domain: ext.info.domain,+ address,+ statement: ext.info.statement,+ uri: ext.info.uri,+ version: ext.info.version || '1',+ chainId: chain.chainId, // CAIP-2 string+ type: 'eip191',+ nonce: ext.info.nonce,+ issuedAt: ext.info.issuedAt,+ ...(ext.info.expirationTime ? { expirationTime: ext.info.expirationTime } : {}),+ ...(ext.info.notBefore ? { notBefore: ext.info.notBefore } : {}),+ ...(ext.info.requestId ? { requestId: ext.info.requestId } : {}),+ ...(ext.info.resources ? { resources: ext.info.resources } : {}),+ signatureScheme: 'eip191',+ signature,+ };+ ```++7. **Solana signing.** Use the existing Phantom path (`window.solana ||+ window.phantom?.solana`). Once connected:++ ```js+ const encoded = new TextEncoder().encode(message);+ const { signature } = await provider.signMessage(encoded, 'utf8');+ // signature is Uint8Array; base58-encode for transport.+ const sigB58 = bs58encode(signature);+ ```++ You need a base58 encoder in the browser. `bs58` ships in `node_modules`+ (used by `api/_lib/siws.js`); pull a minimal browser-safe base58 helper+ inline rather than adding a bundle dependency. Solana's alphabet is the+ Bitcoin alphabet; the helper is <30 lines. Reference impl: the existing+ `api/_lib/siws.js` uses `bs58` from npm — for the browser side, write+ the encoder inline (a vanilla loop over the byte array). No bundler+ needed; the existing `x402.js` already follows the "no build step"+ constraint.++ Payload:++ ```js+ const payload = {+ domain: ext.info.domain,+ address: publicKey.toBase58(),+ statement: ext.info.statement,+ uri: ext.info.uri,+ version: '1',+ chainId: chain.chainId,+ type: 'ed25519',+ nonce: ext.info.nonce,+ issuedAt: ext.info.issuedAt,+ ...(ext.info.expirationTime ? { expirationTime: ext.info.expirationTime } : {}),+ signatureScheme: 'siws',+ signature: sigB58,+ };+ ```++8. **Retry with the header.**++ ```js+ const headerValue = encodeSiwxHeader(payload);+ const res = await fetch(endpoint, {+ method: requestMethod,+ headers: { ...requestHeaders, [SIWX_HEADER]: headerValue },+ body: requestBody,+ });+ if (res.status === 200) return await res.json();+ if (res.status === 401 || res.status === 402) {+ // Likely siwx_not_paid — fall through to the payment flow.+ return null;+ }+ throw new Error(`SIWX retry failed: ${res.status}`);+ ```++9. **Modal layout** (CSS lives inline in `x402.js`). Add a second action+ button above the existing pay button when SIWX is offered. Style:+ primary = sign-in (the bet is: most clicks become signs as the userbase+ matures), secondary = pay-with-USDC. When the user clicks pay, hide+ the sign-in button so the existing flow runs unchanged.++10. **CustomEvents.** Today the modal dispatches `x402:result` /+ `x402:error`. Add `x402:siwx-signed` (detail: `{ address, network }`)+ fired right after a successful SIWX retry, so merchants can wire+ analytics. Existing events stay.++### File 2 — `public/x402.js` smoke test page++There's an existing test surface — look for `public/x402-test.html` or+add `public/siwx-test.html`. The page should:++- Have one button bound to `/api/x402/asset-download?slug=pole-dancer-rumba`.+- Have one button bound to `/api/x402/dance-tip?dancer=1&dance=rumba`.+- Show the raw `x402:result` and `x402:siwx-signed` event details in a+ `<pre>` block so you can eyeball the flow.++Keep it visually minimal — this is for verification, not marketing.++### File 3 — public docs++Update [public/docs-widgets.html](../../public/docs-widgets.html) (or the+equivalent "drop-in modal" docs page) to describe the new "Sign in with+wallet" option. One paragraph + a screenshot or ASCII mockup is enough.++## Verification you must perform++```bash+# 1. Dev server+npm run dev++# 2. Manual browser test (MetaMask or Phantom installed):+# a. Open http://localhost:3000/siwx-test.html+# b. Click "Buy GLB" — pay flow runs, asset downloads.+# c. Reload page. Click "Buy GLB" again.+# d. Modal now shows "Sign in with wallet" first. Click it.+# e. Wallet prompts to sign a CAIP-122 message. Approve.+# f. Network tab shows GET /api/x402/asset-download → 401 → GET with+# SIGN-IN-WITH-X header → 200.+# g. <pre> block shows x402:siwx-signed then x402:result.+# h. No console errors.++# 3. Repeat for /api/x402/dance-tip in the second button.++# 4. Sanity: clear browser localStorage, repeat step b without SIWX+# sign-in — the pay flow must still work bit-identically.+```++## Done means++- `public/x402.js` has the SIWX detection + sign + retry path, no+ `// TODO`, no commented blocks.+- The modal renders two buttons when SIWX is offered; one when it isn't.+- A real wallet (MetaMask + Phantom both tested) can sign and re-enter+ the asset-download endpoint without re-paying.+- `public/siwx-test.html` exists and reproduces the dance reliably.+- Docs page mentions the new flow.+- No regressions in the original payment flow.+- `git diff` reviewed.++Do not commit or push.diff --git a/prompts/siwx/06-nonce-gc-cron.md b/prompts/siwx/06-nonce-gc-cron.mdnew file mode 100644index 000000000..518eaa5d9--- /dev/null+++ b/prompts/siwx/06-nonce-gc-cron.md@@ -0,0 +1,155 @@+# SIWX prompt 06 — daily cron to prune nonces + expired grants++## Context++three.ws workspace at `/workspaces/three.ws`. Architecture in+[prompts/siwx/PLAN.md](PLAN.md). Prompts 01 + 02 set up+`siwx_nonces` (write-heavy, replay protection) and `siwx_payments`+(time-bound grants).++This prompt is **step 6 of 7** — a Vercel cron that runs hourly to keep+both tables bounded.++## Why this matters++- `siwx_nonces` grows by **one row per successful SIWX auth**. Without+ pruning, the table balloons and `hasUsedNonce` lookups slow down.+- `siwx_payments` rows with `expires_at` in the past stop granting access+ on read (the `SELECT` filters them), but they linger forever and pollute+ reporting on `/api/x402-status`.++The storage adapter from prompt 02 already exposes the two helpers+(`pruneOldNonces`, `pruneExpiredPayments`). All this prompt does is wire+them into the cron dispatcher and the Vercel schedule.++## Rails (CLAUDE.md, non-negotiable)++- No mocks, no fake data, no stubs.+- Real `sql` calls. Cron is auth-gated like the others.+- Done = `curl -H 'authorization: Bearer $CRON_SECRET' http://localhost:3000/api/cron/siwx-gc`+ returns a clean summary, both tables shrink as expected, `git diff` reviewed.++## Files to edit++### 1. `api/cron/[name].js` — add a new handler branch++Existing pattern: every cron lives as a handler in the dispatcher at+[api/cron/[name].js](../../api/cron/[name].js). Add to the `HANDLERS`+map and define the function. Match the existing style (`handle<X>` async,+returns `json(res, ...)` from `_lib/http.js`, reads its auth gate from+`env.CRON_SECRET` exactly like the other handlers do — re-read+`handleCleanupCsrfTokens` for the closest analogue).++```js+// Add to HANDLERS map:+'siwx-gc': handleSiwxGc,++// New handler:+async function handleSiwxGc(req, res) {+ // Reuse whatever auth gate the surrounding handlers use. Look at+ // handleCleanupCsrfTokens — it likely calls a shared `assertCron(req)`+ // or checks `req.headers.authorization === \`Bearer ${env.CRON_SECRET}\``.+ // Match that exactly; do not invent a new gate.++ const { pruneOldNonces, pruneExpiredPayments } = await import('../_lib/siwx-storage.js');++ // 10-minute nonce window — well over the 5-minute SIWX message maxAge.+ const noncesDeleted = await pruneOldNonces(10 * 60);++ // 7-day grace on expired payments so a slow client doesn't lose access+ // mid-session right at the boundary.+ const paymentsDeleted = await pruneExpiredPayments(7 * 24 * 3600);++ return json(res, 200, {+ ok: true,+ noncesDeleted,+ paymentsDeleted,+ ranAt: new Date().toISOString(),+ });+}+```++If `json` / `error` / `wrap` aren't already imported in the dispatcher, they+are — every other handler uses them. Reuse.++### 2. `vercel.json` — schedule the cron++Add to the existing `crons` array (don't reorder the others):++```json+{+ "path": "/api/cron/siwx-gc",+ "schedule": "23 * * * *"+}+```++Hourly at :23 to avoid clustering with the existing :17 csrf cleanup.+Vercel's free tier limits cron count — verify you're not at the cap with+`jq '.crons | length' vercel.json` before/after.++### 3. Tiny addition to `/api/x402-status` (optional but easy)++Re-open [api/x402-status.js](../../api/x402-status.js) and surface the most+recent GC run from the response headers / a `siwx.lastGc` field. If you'd+need a new table to track that, **skip it** — the cron already returns the+run timestamp, and operators can see it in Vercel cron logs. Don't build a+log table just for this.++## Verification you must perform++```bash+# 1. Local dispatch works.+CRON_SECRET=$CRON_SECRET npm run dev+curl -sS -H "authorization: Bearer $CRON_SECRET" \+ http://localhost:3000/api/cron/siwx-gc | jq .++# Expected:+# {+# "ok": true,+# "noncesDeleted": <int>,+# "paymentsDeleted": <int>,+# "ranAt": "2026-05-21T..."+# }++# 2. Auth gate works.+curl -sS -i http://localhost:3000/api/cron/siwx-gc | head -1+# Expected: 401 (or 403, matching the other crons exactly).++# 3. Insert two test rows then verify pruning.+DATABASE_URL=$DATABASE_URL node -e "+import('@neondatabase/serverless').then(async ({ neon }) => {+ const sql = neon(process.env.DATABASE_URL);+ await sql\`insert into siwx_nonces (nonce, resource, address, used_at) values+ ('gc-test-fresh', '/x', 'a', now()),+ ('gc-test-old', '/x', 'a', now() - interval '20 minutes')\`;+ const before = await sql\`select count(*)::int as n from siwx_nonces where nonce like 'gc-test-%'\`;+ console.log('before:', before[0].n);+});+"+curl -sS -H "authorization: Bearer $CRON_SECRET" \+ http://localhost:3000/api/cron/siwx-gc | jq .+DATABASE_URL=$DATABASE_URL node -e "+import('@neondatabase/serverless').then(async ({ neon }) => {+ const sql = neon(process.env.DATABASE_URL);+ const after = await sql\`select nonce from siwx_nonces where nonce like 'gc-test-%'\`;+ console.log('after:', after);+ await sql\`delete from siwx_nonces where nonce like 'gc-test-%'\`;+});+"+# Expected: 'gc-test-fresh' remains, 'gc-test-old' gone.++# 4. vercel.json validates.+jq '.crons' vercel.json+node -e "JSON.parse(require('fs').readFileSync('vercel.json','utf8'))"+```++## Done means++- `api/cron/[name].js` has a `handleSiwxGc` handler registered in `HANDLERS`.+- `vercel.json` declares the hourly cron at `/api/cron/siwx-gc`.+- Local curl with `$CRON_SECRET` returns the summary JSON; without the+ secret returns the same error code the other crons return.+- Test rows are pruned correctly.+- `git diff` reviewed.++Do not commit or push.diff --git a/prompts/siwx/07-verify-end-to-end.md b/prompts/siwx/07-verify-end-to-end.mdnew file mode 100644index 000000000..a594103ad--- /dev/null+++ b/prompts/siwx/07-verify-end-to-end.md@@ -0,0 +1,225 @@+# SIWX prompt 07 — end-to-end verification (real wallets, real money)++## Context++three.ws workspace at `/workspaces/three.ws`. Architecture in+[prompts/siwx/PLAN.md](PLAN.md). Prompts 01-06 built the schema, storage+adapter, paidEndpoint integration, three opt-in endpoints, the browser+modal flow, and the GC cron.++This prompt is **step 7 of 7** — proving the whole thing works with real+wallets, real on-chain settlement, and real signatures. Definition of+done per CLAUDE.md is "feature exercised in a real browser, no console+errors, network tab shows real API calls succeeding" — this prompt is+where that gets done.++## Rails (CLAUDE.md, non-negotiable)++- No mocks. No fake data. No fake wallets. No localhost-only paths that+ don't translate to production.+- Real on-chain USDC settlement for the first payment leg. If the dev+ account lacks USDC, surface that — do NOT skip the payment leg or+ "simulate" it. (Use Base Sepolia + testnet USDC if mainnet is+ uncomfortable; document which network you ran on in the result file.)+- Real EVM wallet (MetaMask) AND real Solana wallet (Phantom) — both+ ecosystems must be exercised because both are advertised in 402 bodies.+- Done = result JSON file exists at `~/.claude/siwx-verify/result.json`+ with timestamps, txids, recovered addresses, and a clear pass/fail+ per scenario.++## What to verify++### Scenario A — Browser flow, EVM (Base + MetaMask)++Goal: pay once on `/api/x402/asset-download?slug=pole-dancer-rumba`, then+re-download via SIWX without paying again.++Steps:++1. `npm run dev` running.+2. Open `http://localhost:3000/siwx-test.html` (built in prompt 05) in a+ browser with MetaMask + Phantom installed.+3. Click the asset-download button. Wallet picker → choose MetaMask on+ Base. Approve the USDC transfer.+4. Confirm the modal shows success + the response JSON has+ `downloadUrl: "https://...r2..."`.+5. Open the URL — the GLB downloads cleanly (size matches the seeded+ `paid_assets.size_bytes`).+6. **Reload the test page.** Click the same button.+7. The modal NOW shows "Sign in with wallet" first. Click it. MetaMask+ prompts to sign a CAIP-122 message. Approve.+8. Network tab: confirm the second request fired with `SIGN-IN-WITH-X`+ header (not `X-PAYMENT`) and returned 200.+9. Open the new `downloadUrl` — second download works.+10. Postgres check:+ ```sql+ SELECT resource, address, network, paid_at, use_count, last_used_at+ FROM siwx_payments+ WHERE resource = 'http://localhost:3000/api/x402/asset-download';+ ```+ Exactly one row. `use_count >= 1`. `last_used_at` recent.++### Scenario B — Browser flow, Solana (Phantom)++Same as Scenario A but with Phantom. Two specific things to verify:++- The CAIP-122 message rendered in Phantom uses+ `"... wants you to sign in with your Solana account:"` (not "Ethereum").+- The signature is Base58-encoded in the `SIGN-IN-WITH-X` header.+- A second row exists in `siwx_payments` with `network = 'solana:5eykt...'`+ and the address in Base58 case-sensitive form.++### Scenario C — Agent flow, EVM (privateKeyToAccount + wrapFetchWithSIWx)++Goal: prove an automated agent works the same way as the browser without+touching the UI. Write a one-shot Node script at+`scripts/siwx-verify-agent.mjs`:++```js+#!/usr/bin/env node+// scripts/siwx-verify-agent.mjs+//+// End-to-end SIWX verification for the agent path. Requires:+// EVM_PRIVATE_KEY — 0x-prefixed funded wallet on Base+// X402_RESOURCE — full URL of a SIWX-enabled endpoint+//+// Flow:+// 1. Call the endpoint with @x402/fetch — pays via x402.+// 2. Call again with wrapFetchWithSIWx — signs and re-enters for free.+// 3. Write a result JSON to ~/.claude/siwx-verify/agent-result.json.+import { privateKeyToAccount } from 'viem/accounts';+import { wrapFetchWithPayment } from '@x402/fetch';+import { wrapFetchWithSIWx } from '@x402/extensions/sign-in-with-x';+import { writeFile, mkdir } from 'node:fs/promises';+import { homedir } from 'node:os';+import { join } from 'node:path';++const pk = process.env.EVM_PRIVATE_KEY;+const url = process.env.X402_RESOURCE;+if (!pk || !url) {+ console.error('EVM_PRIVATE_KEY and X402_RESOURCE required');+ process.exit(1);+}+const signer = privateKeyToAccount(pk);++// Leg 1 — pay.+const fetchWithPayment = wrapFetchWithPayment(fetch, signer);+const t0 = Date.now();+const r1 = await fetchWithPayment(url);+const j1 = await r1.json();+const t1 = Date.now();+if (r1.status !== 200) throw new Error(`pay leg failed ${r1.status}`);++// Leg 2 — SIWX retry.+const fetchWithSiwx = wrapFetchWithSIWx(fetch, signer);+const t2 = Date.now();+const r2 = await fetchWithSiwx(url);+const j2 = await r2.json();+const t3 = Date.now();+if (r2.status !== 200) throw new Error(`siwx leg failed ${r2.status}`);++const outDir = join(homedir(), '.claude/siwx-verify');+await mkdir(outDir, { recursive: true });+await writeFile(+ join(outDir, 'agent-result.json'),+ JSON.stringify(+ {+ url,+ pay: { status: r1.status, ms: t1 - t0, paymentResponse: r1.headers.get('x-payment-response') },+ siwx: { status: r2.status, ms: t3 - t2, signature: 'redacted' },+ addresses: { signer: signer.address },+ ranAt: new Date().toISOString(),+ },+ null,+ 2,+ ),+);+console.log('OK — wrote', join(outDir, 'agent-result.json'));+```++Run it:++```bash+EVM_PRIVATE_KEY=0x... X402_RESOURCE=http://localhost:3000/api/x402/asset-download?slug=pole-dancer-rumba \+ node scripts/siwx-verify-agent.mjs+```++`agent-result.json` is the artifact you submit.++### Scenario D — Negative path++A wallet that has NOT paid is correctly denied:++```bash+EVM_PRIVATE_KEY=0x<FRESH_EMPTY_WALLET> X402_RESOURCE=http://localhost:3000/api/x402/asset-download?slug=pole-dancer-rumba \+ node scripts/siwx-verify-agent.mjs+```++Expected: the SIWX leg returns `402 siwx_not_paid` (visible because the+script throws). Document the exact response in the result file.++### Scenario E — Replay protection++Capture the `SIGN-IN-WITH-X` header from a successful Scenario A retry+(`Network tab → Copy as cURL`). Replay it twice within 30 seconds.++Expected: first replay succeeds (race window — the nonce hasn't been+recorded yet if you copy the header before the response writes; if you+copy after, both should fail), second replay returns+`401 siwx_message_invalid` with reason `nonce already used`.++### Scenario F — Existing endpoints regression++Confirm the **non**-SIWX endpoints in `api/x402/*.js` still behave+bit-identically. Pick any 3 that weren't touched by prompt 04 (e.g.+`model-check.js`, `mint-to-mesh.js`, `symbol-availability.js`):++```bash+for slug in model-check mint-to-mesh symbol-availability; do+ curl -sSI http://localhost:3000/api/x402/$slug | grep -i 'payment-required'+done+```++Decode each `PAYMENT-REQUIRED` header and confirm `extensions` does NOT+contain `sign-in-with-x`. If any does, prompt 03 leaked SIWX into+non-opted-in endpoints — fix it.++## Artifact++Write `~/.claude/siwx-verify/result.json`:++```json+{+ "ranAt": "2026-05-21T...",+ "network": "base-mainnet",+ "scenarios": {+ "A_evm_browser": { "status": "pass", "notes": "..." },+ "B_solana_browser":{ "status": "pass", "notes": "..." },+ "C_agent_evm": { "status": "pass", "notes": "..." },+ "D_negative": { "status": "pass", "notes": "..." },+ "E_replay": { "status": "pass", "notes": "..." },+ "F_regression": { "status": "pass", "notes": "..." }+ },+ "siwxPaymentsCount": 3,+ "siwxNoncesCount": 7+}+```++The user reviews this artifact to decide whether SIWX ships.++## Done means++- All six scenarios pass and are documented in+ `~/.claude/siwx-verify/result.json`.+- `scripts/siwx-verify-agent.mjs` exists, is real, runs against a real+ endpoint with a real private key.+- No console errors in either browser session.+- No new files left in the working tree besides the script and the+ verify artifact (which lives outside the repo).+- If anything failed, the prompt writer surfaces it immediately to the+ user with the failing scenario + the request/response that broke —+ do not paper over by tweaking thresholds.++Do not commit or push the script unless the user asks you to (it+contains no secrets, but it doesn't need to ship to prod either —+keep it in `scripts/` for repeat verification).diff --git a/prompts/siwx/README.md b/prompts/siwx/README.mdnew file mode 100644index 000000000..0b6616258--- /dev/null+++ b/prompts/siwx/README.md@@ -0,0 +1,55 @@+# SIWX — Sign-In-With-X build queue++Self-contained prompts to ship CAIP-122 wallet sign-in across every x402+paid endpoint on three.ws. Hand any one of them to a fresh Claude Code+session — each restates the context it needs.++**Start with [PLAN.md](PLAN.md)** for the architecture overview, schema,+and run order.++## Why we're doing this++Every paid endpoint in `api/x402/*.js` currently charges per call. That's+fine for one-shot APIs (validate this GLB, audit this agent) but **kills**+re-downloadable digital goods — GLBs, avatars, skills, agent definitions,+accessories. SIWX gives the buyer a wallet signature as a re-entry pass,+so the marketplace works the way creators and buyers expect: pay once,+re-access forever (or for the TTL the seller sets).++## The queue++| # | Prompt | Output | Depends on |+|---|---|---|---|+| 1 | [01-db-schema.md](01-db-schema.md) | `siwx_payments`, `siwx_nonces` tables + applier script | — |+| 2 | [02-storage-adapter.md](02-storage-adapter.md) | `api/_lib/siwx-storage.js` + tests | 1 |+| 3 | [03-paid-endpoint-integration.md](03-paid-endpoint-integration.md) | `siwx:` opt-in field on `paidEndpoint()` | 2 |+| 4 | [04-wire-endpoints.md](04-wire-endpoints.md) | skill-marketplace + dance-tip opt in, new `asset-download` endpoint, seeded GLBs | 3 |+| 5 | [05-browser-modal.md](05-browser-modal.md) | Two-button modal in `public/x402.js`, MetaMask + Phantom signing | 3 |+| 6 | [06-nonce-gc-cron.md](06-nonce-gc-cron.md) | Hourly Vercel cron pruning nonces + expired grants | 1 |+| 7 | [07-verify-end-to-end.md](07-verify-end-to-end.md) | Real-wallet end-to-end verification + artifact | 4, 5 |++Prompts 4, 5, 6 can run in parallel after 3 ships.++## 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. No fallback sample arrays.+- Real Neon Postgres, real `@x402/extensions/sign-in-with-x` primitives,+ real wallets (MetaMask + Phantom), real R2.+- Errors at boundaries only (network, user input). Internal code trusts+ itself.+- Done = code wired into the existing path, dev server confirms feature+ in a real browser with no console errors, `npm test` green, `git diff`+ reviewed.+- Push to **both** `origin` (nirholas/3D-Agent) and `threews`+ (nirholas/three.ws) only when the user explicitly says push.++## What ships at the end of the queue++A buyer can pay $0.005 for a GLB on three.ws, close the tab, come back a+month later, click download again, sign with their wallet, and the file+streams without a second payment. Agents do the same thing through+`@x402/fetch` + `wrapFetchWithSIWx` without any extra integration. The+marketplace becomes economically coherent: creators sell access, buyers+own access, both sides verifiable on-chain.diff --git a/public/x402-stripe.html b/public/x402-stripe.htmlindex 2d5d193d5..15632422e 100644--- a/public/x402-stripe.html+++ b/public/x402-stripe.html@@ -280,7 +280,7 @@<h2><span class="num">01</span>Install</h2><p class="sub">Paste one line into your <code style="font-family:var(--mono);"><head></code>. Then add <code style="font-family:var(--mono);">data-x402-endpoint</code> to any button. That's it.</p><div class="snippet" id="installSnippet"><button class="copy-btn" data-copy="installSnippetCode">Copy</button><span id="installSnippetCode"><span class="c"><!-- 1. Load once --></span>-<span class="k"><script</span> <span class="a">type</span>=<span class="s">"module"</span> <span class="a">src</span>=<span class="s">"https://3d.irish/x402.js"</span><span class="k">></script></span>+<span class="k"><script</span> <span class="a">type</span>=<span class="s">"module"</span> <span class="a">src</span>=<span class="s">"https://three.ws/x402.js"</span><span class="k">></script></span><span class="c"><!-- 2. Add a button to any 402-paid endpoint --></span><span class="k"><button</span>diff --git a/public/x402.js b/public/x402.jsindex bd28e02df..19b863e30 100644--- a/public/x402.js+++ b/public/x402.js@@ -558,9 +558,11 @@ class CheckoutModal {try {const challenge = await discoverChallenge(this.opts);this.challenge = challenge;- // Prefer Solana when Phantom is present, else first EVM, else first accept.+ // Prefer Solana when Phantom is present, else first EIP-3009 EVM+ // entry (skipping Permit2 siblings the modal can't sign for), else+ // first accept.const solana = challenge.accepts.find((a) => isSolanaNetwork(a.network));- const evm = challenge.accepts.find((a) => isEvmNetwork(a.network));+ const evm = challenge.accepts.find(isEip3009Accept);const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);this.accept = (phantomDetected && solana) || evm || challenge.accepts[0];this.setPrice(this.accept);diff --git a/scripts/README.md b/scripts/README.mdindex ce1f69340..a7434efd4 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -5,3 +5,25 @@ This directory contains various scripts for the 3D-Agent application.## Usage...++## Operational++### `set-r2-cors.mjs` — apply the bucket CORS policy++Runs the canonical CORS policy against the R2 bucket holding all media+(avatars, thumbnails, posters). Required for browser reads (`<model-viewer>`,+`<img>`, `fetch`) and presigned uploads to work cross-origin.++```sh+vercel env pull .env+node scripts/set-r2-cors.mjs # apply+node scripts/set-r2-cors.mjs --get # show what's currently live+node scripts/set-r2-cors.mjs --dry-run # print the policy without pushing+```++Allowed origins are defined inline in the script — edit `ALLOWED_ORIGINS`+when you add a new domain (preview branch, staging host, etc.) and re-run.+Idempotent: re-running with the same policy is a no-op.++Run this any time you see `No 'Access-Control-Allow-Origin' header` errors+on assets served from `*.r2.dev` or your custom R2 domain.diff --git a/scripts/build-club-props.mjs b/scripts/build-club-props.mjsnew file mode 100644index 000000000..828dfc290--- /dev/null+++ b/scripts/build-club-props.mjs@@ -0,0 +1,299 @@+#!/usr/bin/env node+/**+ * Authors the static props used by /club — pole.glb and stage.glb — and writes+ * them to public/club/props/. Composed at build time from Three.js primitives,+ * not at runtime, so the browser ships a real .glb file with named empties for+ * the spotlight + LED strip attach points (consumed by src/club.js).+ *+ * Run via: npm run build:club-props+ */+import { writeFileSync, mkdirSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import { Blob } from 'node:buffer';++// Three's GLTFExporter touches DOM globals; mirror the shim from build-animations.mjs.+globalThis.self = globalThis;+globalThis.window = globalThis;+globalThis.document = { createElementNS: () => ({}) };+globalThis.Blob = Blob;++class NodeFileReader extends EventTarget {+ readAsDataURL(blob) {+ blob.arrayBuffer().then((buf) => {+ const b64 = Buffer.from(buf).toString('base64');+ this.result = `data:${blob.type || 'application/octet-stream'};base64,${b64}`;+ this.onload?.({ target: this });+ this.dispatchEvent(new Event('load'));+ });+ }+ readAsArrayBuffer(blob) {+ blob.arrayBuffer().then((buf) => {+ this.result = buf;+ this.onload?.({ target: this });+ this.dispatchEvent(new Event('load'));+ });+ }+}+globalThis.FileReader = NodeFileReader;++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..');+const OUT_DIR = resolve(ROOT, 'public/club/props');++const {+ Scene,+ Group,+ Mesh,+ Object3D,+ CylinderGeometry,+ BoxGeometry,+ TorusGeometry,+ MeshStandardMaterial,+} = await import('three');+const { GLTFExporter } = await import('three/examples/jsm/exporters/GLTFExporter.js');++const POLE_HEIGHT = 3.6;+const POLE_RADIUS = 0.035;+const STAGE_RADIUS = 1.1;+const STAGE_HEIGHT = 0.18;++function chromeMat(name = 'PoleChrome') {+ const m = new MeshStandardMaterial({+ color: 0xe6e8f0,+ roughness: 0.14,+ metalness: 1.0,+ });+ m.name = name;+ return m;+}++function brushedMat(name = 'PoleBaseBrushed') {+ const m = new MeshStandardMaterial({+ color: 0xc8ccd8,+ roughness: 0.32,+ metalness: 0.95,+ });+ m.name = name;+ return m;+}++function darkMetalMat(name = 'BoltDark') {+ const m = new MeshStandardMaterial({+ color: 0x1a1c20,+ roughness: 0.45,+ metalness: 0.9,+ });+ m.name = name;+ return m;+}++function stageTopMat(name = 'StageTop') {+ const m = new MeshStandardMaterial({+ color: 0x18091a,+ roughness: 0.35,+ metalness: 0.7,+ });+ m.name = name;+ return m;+}++function stageSideMat(name = 'StageSide') {+ const m = new MeshStandardMaterial({+ color: 0x0a050d,+ roughness: 0.55,+ metalness: 0.55,+ });+ m.name = name;+ return m;+}++function ledMat(name = 'StageLED') {+ const m = new MeshStandardMaterial({+ color: 0xffffff,+ emissive: 0xff4dd6,+ emissiveIntensity: 1.0,+ roughness: 0.4,+ metalness: 0.1,+ });+ m.name = name;+ return m;+}++/**+ * Build pole.glb scene. Origin = (0, 0, 0) at pole base footprint center; the+ * shaft extends upward to y = POLE_HEIGHT. Includes a flared base, ceiling+ * mount plate with four bolts, a spotlight bracket, and a named empty+ * `pole.light.attach` at the bracket tip.+ */+function buildPoleScene() {+ const scene = new Scene();+ scene.name = 'PoleScene';++ const root = new Group();+ root.name = 'PoleRoot';+ scene.add(root);++ // Flared base — wide bottom disc tapered to a narrow collar.+ const baseDisc = new Mesh(+ new CylinderGeometry(0.42, 0.46, 0.04, 40),+ brushedMat('PoleBase'),+ );+ baseDisc.name = 'pole.base';+ baseDisc.position.y = 0.02;+ root.add(baseDisc);++ const baseCollar = new Mesh(+ new CylinderGeometry(POLE_RADIUS * 2.1, 0.13, 0.09, 32),+ brushedMat('PoleCollar'),+ );+ baseCollar.name = 'pole.collar';+ baseCollar.position.y = 0.04 + 0.045;+ root.add(baseCollar);++ // Main shaft.+ const shaft = new Mesh(+ new CylinderGeometry(POLE_RADIUS, POLE_RADIUS, POLE_HEIGHT, 24, 1),+ chromeMat('PoleShaft'),+ );+ shaft.name = 'pole.shaft';+ shaft.position.y = POLE_HEIGHT / 2;+ root.add(shaft);++ // Ceiling mount plate at the top.+ const mountPlate = new Mesh(+ new BoxGeometry(0.26, 0.014, 0.26),+ brushedMat('PoleMountPlate'),+ );+ mountPlate.name = 'pole.mount.plate';+ mountPlate.position.y = POLE_HEIGHT + 0.007;+ root.add(mountPlate);++ // Four bolts at corners of the plate.+ const boltMat = darkMetalMat('PoleBolt');+ const boltGeom = new CylinderGeometry(0.012, 0.012, 0.022, 8);+ const boltInset = 0.10;+ const boltOffsets = [+ [+boltInset, +boltInset],+ [+boltInset, -boltInset],+ [-boltInset, +boltInset],+ [-boltInset, -boltInset],+ ];+ for (let i = 0; i < boltOffsets.length; i++) {+ const [bx, bz] = boltOffsets[i];+ const bolt = new Mesh(boltGeom.clone(), boltMat);+ bolt.name = `pole.bolt.${i}`;+ bolt.position.set(bx, POLE_HEIGHT + 0.024, bz);+ root.add(bolt);+ }++ // Spotlight bracket — extends in +z from the mount plate.+ const bracketArm = new Mesh(+ new BoxGeometry(0.04, 0.02, 0.18),+ darkMetalMat('PoleBracketArm'),+ );+ bracketArm.name = 'pole.bracket.arm';+ bracketArm.position.set(0, POLE_HEIGHT + 0.024, 0.13);+ root.add(bracketArm);++ const bracketHead = new Mesh(+ new CylinderGeometry(0.025, 0.025, 0.04, 16),+ darkMetalMat('PoleBracketHead'),+ );+ bracketHead.name = 'pole.bracket.head';+ bracketHead.rotation.x = Math.PI / 2;+ bracketHead.position.set(0, POLE_HEIGHT + 0.024, 0.22);+ root.add(bracketHead);++ // Named empty for prompt-04 SpotLight anchoring.+ const attach = new Object3D();+ attach.name = 'pole.light.attach';+ attach.position.set(0, POLE_HEIGHT + 0.024, 0.24);+ root.add(attach);++ return scene;+}++/**+ * Build stage.glb scene. Origin = (0, 0, 0) at floor level under disc center;+ * the disc top is at y = STAGE_HEIGHT. Includes an LED strip ring around the+ * top edge with a named empty `stage.led.strip` at its center.+ */+function buildStageScene() {+ const scene = new Scene();+ scene.name = 'StageScene';++ const root = new Group();+ root.name = 'StageRoot';+ scene.add(root);++ // Main disc.+ const disc = new Mesh(+ new CylinderGeometry(STAGE_RADIUS, STAGE_RADIUS + 0.04, STAGE_HEIGHT, 64, 1),+ stageSideMat('StageBody'),+ );+ disc.name = 'stage.body';+ disc.position.y = STAGE_HEIGHT / 2;+ root.add(disc);++ // Slightly raised non-slip top so the dancer's feet have a defined surface.+ const top = new Mesh(+ new CylinderGeometry(STAGE_RADIUS - 0.01, STAGE_RADIUS - 0.01, 0.004, 64, 1),+ stageTopMat('StageTopFace'),+ );+ top.name = 'stage.top';+ top.position.y = STAGE_HEIGHT + 0.002;+ root.add(top);++ // LED strip — thin torus around the upper edge.+ const led = new Mesh(+ new TorusGeometry(STAGE_RADIUS + 0.005, 0.012, 8, 96),+ ledMat('StageLEDStrip'),+ );+ led.name = 'stage.led.ring';+ led.rotation.x = Math.PI / 2;+ led.position.y = STAGE_HEIGHT - 0.014;+ root.add(led);++ // Named empty for prompt-04 LED pulse driver.+ const ledAttach = new Object3D();+ ledAttach.name = 'stage.led.strip';+ ledAttach.position.set(0, STAGE_HEIGHT - 0.014, 0);+ root.add(ledAttach);++ return scene;+}++async function exportGLB(scene) {+ const exporter = new GLTFExporter();+ return new Promise((resolve, reject) => {+ exporter.parse(+ scene,+ (buf) => resolve(buf),+ (err) => reject(err),+ { binary: true, embedImages: true, onlyVisible: true },+ );+ });+}++async function main() {+ mkdirSync(OUT_DIR, { recursive: true });++ const targets = [+ { name: 'pole.glb', scene: buildPoleScene() },+ { name: 'stage.glb', scene: buildStageScene() },+ ];++ for (const { name, scene } of targets) {+ const buf = await exportGLB(scene);+ const bytes = Buffer.from(buf);+ const outPath = resolve(OUT_DIR, name);+ writeFileSync(outPath, bytes);+ console.log(`[club-props] wrote ${name.padEnd(10)} ${(bytes.length / 1024).toFixed(1)} kB`);+ }+}++main().catch((err) => {+ console.error('[club-props] build failed:', err);+ process.exit(1);+});diff --git a/src/club-audio.js b/src/club-audio.jsnew file mode 100644index 000000000..df7a23036--- /dev/null+++ b/src/club-audio.js@@ -0,0 +1,261 @@+// /club audio mixer — crowd ambience under, per-style loops over the top.+//+// Browsers refuse to start an AudioContext before a user gesture, so the+// first tip click drives ensureContext(). After that:+// - startAmbience() loops public/club/audio/ambience.{ogg,mp3} at a+// soft constant gain so the room feels alive between performances.+// - fadeToStyle(name) ducks ambience and brings the matching style loop+// in over `durationMs` via linearRampToValueAtTime on the GainNodes.+// - fadeOutStyle() reverses it.+//+// Only the master bus is wired through an AnalyserNode — getPeak() returns+// a normalised loudness reading the rim-light pulse can drive lighting from.+// No third-party libs (Howler/Tone). No setTimeout-faked beats. Real Web+// Audio API.++const AUDIO_BASE = '/club/audio';+// Try .ogg first (smaller, mono-q4); fall back to .mp3 on Safari/older+// browsers that lack Vorbis support.+const FORMATS = ['ogg', 'mp3'];++const AMBIENCE_GAIN = 0.35;+const STYLE_GAIN = 0.75;+const AMBIENCE_DUCK_GAIN = 0.1;+const MASTER_GAIN = 0.75;++export class ClubAudio {+ constructor() {+ this.ctx = null;+ this.master = null;+ this.ambience = null; // { source, gain }+ this.style = null; // { name, source, gain }+ this.analyser = null;+ this._buffers = new Map(); // styleName → AudioBuffer+ this._loading = new Map(); // styleName → Promise<AudioBuffer>+ this._peakBuf = null; // Uint8Array reused for getByteFrequencyData+ this.muted = this._readMutedPref();+ this._onStatus = null; // optional callback(name, label)+ }++ onStatus(cb) {+ this._onStatus = typeof cb === 'function' ? cb : null;+ }++ async ensureContext() {+ if (this.ctx) {+ // On Safari the context can flip to "suspended" after a tab switch;+ // re-resume on every tip gesture is cheap and safe.+ if (this.ctx.state === 'suspended') {+ try { await this.ctx.resume(); } catch {}+ }+ return;+ }+ const Ctor = typeof window !== 'undefined'+ ? (window.AudioContext || window.webkitAudioContext)+ : null;+ if (!Ctor) {+ throw new Error('Web Audio API unavailable');+ }+ this.ctx = new Ctor();+ this.master = this.ctx.createGain();+ this.master.gain.value = this.muted ? 0 : MASTER_GAIN;+ this.master.connect(this.ctx.destination);++ this.analyser = this.ctx.createAnalyser();+ this.analyser.fftSize = 256;+ this.analyser.smoothingTimeConstant = 0.55;+ this.master.connect(this.analyser);+ this._peakBuf = new Uint8Array(this.analyser.frequencyBinCount);++ if (this.ctx.state === 'suspended') {+ try { await this.ctx.resume(); } catch {}+ }+ }++ async loadBuffer(name) {+ if (this._buffers.has(name)) return this._buffers.get(name);+ if (this._loading.has(name)) return this._loading.get(name);++ const p = (async () => {+ let lastErr = null;+ for (const ext of FORMATS) {+ const url = `${AUDIO_BASE}/${name}.${ext}`;+ try {+ const res = await fetch(url, { cache: 'force-cache' });+ if (!res.ok) {+ lastErr = new Error(`HTTP ${res.status} loading ${url}`);+ continue;+ }+ const bytes = await res.arrayBuffer();+ // decodeAudioData uses callbacks in old Safari; the+ // promise overload covers every browser we ship to.+ const buf = await this.ctx.decodeAudioData(bytes);+ this._buffers.set(name, buf);+ return buf;+ } catch (err) {+ lastErr = err;+ }+ }+ throw lastErr || new Error(`no playable audio at ${AUDIO_BASE}/${name}.*`);+ })();+ this._loading.set(name, p);+ try {+ return await p;+ } finally {+ this._loading.delete(name);+ }+ }++ _makeLayer(buffer, initialGain) {+ const source = this.ctx.createBufferSource();+ source.buffer = buffer;+ source.loop = true;+ const gain = this.ctx.createGain();+ gain.gain.value = initialGain;+ source.connect(gain).connect(this.master);+ source.start();+ return { source, gain };+ }++ async startAmbience() {+ await this.ensureContext();+ if (this.ambience) return;+ const buf = await this.loadBuffer('ambience');+ // Guard against a parallel call having beaten us to it.+ if (this.ambience) return;+ this.ambience = this._makeLayer(buf, AMBIENCE_GAIN);+ }++ async fadeToStyle(name, durationMs = 800) {+ if (!name) return;+ await this.ensureContext();+ if (this.ctx.state === 'suspended') {+ try { await this.ctx.resume(); } catch {}+ }+ const buf = await this.loadBuffer(name);++ const now = this.ctx.currentTime;+ const end = now + Math.max(0.05, durationMs / 1000);++ // Replace any currently-playing style layer.+ if (this.style) {+ this._fadeOutLayer(this.style, durationMs);+ this.style = null;+ }++ const layer = this._makeLayer(buf, 0);+ layer.gain.gain.cancelScheduledValues(now);+ layer.gain.gain.setValueAtTime(0, now);+ layer.gain.gain.linearRampToValueAtTime(STYLE_GAIN, end);+ this.style = { name, ...layer };++ if (this.ambience) {+ this.ambience.gain.gain.cancelScheduledValues(now);+ this.ambience.gain.gain.setValueAtTime(this.ambience.gain.gain.value, now);+ this.ambience.gain.gain.linearRampToValueAtTime(AMBIENCE_DUCK_GAIN, end);+ }++ if (this._onStatus) {+ try { this._onStatus(name); } catch {}+ }+ return this.style;+ }++ async fadeOutStyle(durationMs = 800) {+ if (!this.ctx) return;+ const now = this.ctx.currentTime;+ const end = now + Math.max(0.05, durationMs / 1000);++ if (this.style) {+ this._fadeOutLayer(this.style, durationMs);+ this.style = null;+ }+ if (this.ambience) {+ this.ambience.gain.gain.cancelScheduledValues(now);+ this.ambience.gain.gain.setValueAtTime(this.ambience.gain.gain.value, now);+ this.ambience.gain.gain.linearRampToValueAtTime(AMBIENCE_GAIN, end);+ }+ }++ _fadeOutLayer(layer, durationMs) {+ const now = this.ctx.currentTime;+ const end = now + Math.max(0.05, durationMs / 1000);+ layer.gain.gain.cancelScheduledValues(now);+ layer.gain.gain.setValueAtTime(layer.gain.gain.value, now);+ layer.gain.gain.linearRampToValueAtTime(0, end);+ try {+ // Stop the source slightly after the fade completes so we don't+ // click. Some test stubs don't implement stop(t) — guard it.+ layer.source.stop(end + 0.05);+ } catch {}+ }++ getPeak() {+ if (!this.analyser || !this._peakBuf) return 0;+ this.analyser.getByteFrequencyData(this._peakBuf);+ // Average across the lower half of the spectrum — that's where the+ // kick/snare energy lives in our loops. Skipping the top half also+ // keeps the reading less twitchy on hi-hat-heavy hip-hop.+ const n = this._peakBuf.length >> 1;+ let sum = 0;+ for (let i = 0; i < n; i++) sum += this._peakBuf[i];+ return n > 0 ? (sum / n) / 255 : 0;+ }++ setMuted(v) {+ const muted = !!v;+ this.muted = muted;+ this._writeMutedPref(muted);+ if (!this.ctx || !this.master) return;+ const target = muted ? 0 : MASTER_GAIN;+ const now = this.ctx.currentTime;+ this.master.gain.cancelScheduledValues(now);+ this.master.gain.setValueAtTime(this.master.gain.value, now);+ this.master.gain.linearRampToValueAtTime(target, now + 0.15);+ }++ _readMutedPref() {+ try {+ if (typeof localStorage === 'undefined') return false;+ return localStorage.getItem('club.audio.muted') === '1';+ } catch {+ return false;+ }+ }++ _writeMutedPref(muted) {+ try {+ if (typeof localStorage === 'undefined') return;+ localStorage.setItem('club.audio.muted', muted ? '1' : '0');+ } catch {}+ }+}++// Map dance keys (as returned by /api/x402/dance-tip) to track names.+// Pole choreography clips (spin/climb/combo) share a single neutral loop.+const TRACK_BY_DANCE = Object.freeze({+ rumba: 'rumba',+ silly: 'silly',+ thriller: 'thriller',+ capoeira: 'capoeira',+ hiphop: 'hiphop',+ spin: 'pole',+ climb: 'pole',+ combo: 'pole',+});++export function styleAudioFor(dance) {+ if (!dance) return null;+ return TRACK_BY_DANCE[String(dance).toLowerCase()] || null;+}++// Display labels for screen-reader announcements.+export const TRACK_LABELS = Object.freeze({+ ambience: 'Crowd ambience',+ rumba: 'Rumba mix',+ silly: 'Silly mix',+ thriller: 'Thriller mix',+ capoeira: 'Capoeira mix',+ hiphop: 'Hip Hop mix',+ pole: 'Pole choreography mix',+});diff --git a/src/club-camera.js b/src/club-camera.jsnew file mode 100644index 000000000..aef8ccebb--- /dev/null+++ b/src/club-camera.js@@ -0,0 +1,134 @@+// Camera state machine for /club.+//+// Three modes:+// - free : user-driven orbit around the dance floor (default).+// - vip : framed close-up of a single pole's dancer.+// - house : top-down overhead of the whole room.+//+// Transitions interpolate the (target, offset) pair over ~0.4s. The owning+// scene calls `tick(dt)` once per frame, which advances any pending lerp and+// then writes camera.position + camera.lookAt(target).+//+// Single-author: drag / zoom go through applyDrag / applyZoom — no+// OrbitControls. Drag is ignored in non-free modes; zoom works in free and+// VIP.++import { Vector3 } from 'three';++export const CLUB_CAMERA_MODES = ['free', 'vip', 'house'];++const FREE_OFFSET_BASE = new Vector3(0, 2.2, 7.2);+const FREE_TARGET = new Vector3(0, 1.2, -1.8);++// Per-mode zoom bounds so we don't end up inside the geometry or 30m away.+const ZOOM_BOUNDS = {+ free: { min: 3.5, max: 14.0 },+ vip: { min: 1.4, max: 5.5 },+};++export class ClubCamera {+ constructor(camera, opts = {}) {+ this.camera = camera;+ this.mode = 'free';+ this.target = FREE_TARGET.clone();+ this.offset = FREE_OFFSET_BASE.clone();+ this.yaw = 0;+ this.pitch = 0.05;+ this._pending = null; // {target, offset, lerp}+ this._onModeChange = opts.onModeChange || null;+ }++ getMode() { return this.mode; }++ _emitMode() {+ if (this._onModeChange) {+ try { this._onModeChange(this.mode); } catch {}+ }+ }++ setFree() {+ const was = this.mode;+ this.mode = 'free';+ this._pending = {+ target: FREE_TARGET.clone(),+ offset: new Vector3(0, 2.2 + this.pitch * 2.5, this.offset.length() > 0 ? this.offset.length() : 7.2),+ lerp: 2.5,+ };+ if (was !== 'free') this._emitMode();+ }++ setVip(poleLayout) {+ if (!poleLayout) return;+ const was = this.mode;+ this.mode = 'vip';+ const target = new Vector3(poleLayout.x, 1.6, poleLayout.z);+ const offset = new Vector3(+ Math.sin(poleLayout.yaw + Math.PI) * 2.6,+ 1.3,+ Math.cos(poleLayout.yaw + Math.PI) * 2.6,+ );+ this._pending = { target, offset, lerp: 3.0 };+ this._activeVipId = poleLayout.id || null;+ if (was !== 'vip') this._emitMode();+ }++ setHouse() {+ const was = this.mode;+ this.mode = 'house';+ this._pending = {+ target: new Vector3(0, 0.5, -1.5),+ offset: new Vector3(0, 12, 0.001), // top-down with epsilon to avoid singular up+ lerp: 1.6,+ };+ if (was !== 'house') this._emitMode();+ }++ // Pointer drag — only effective in free orbit.+ applyDrag(dx, dy) {+ if (this.mode !== 'free') return;+ this.yaw -= dx * 0.004;+ this.pitch = Math.max(-0.3, Math.min(0.5, this.pitch - dy * 0.003));+ }++ // Zoom (wheel deltaY or pinch delta). Honored in free + vip.+ // Positive deltaY = wheel-down = zoom out, matching browser convention.+ applyZoom(deltaY) {+ if (this.mode === 'house') return;+ const bounds = ZOOM_BOUNDS[this.mode] || ZOOM_BOUNDS.free;+ const factor = 1 + deltaY * 0.0015;+ const current = this._pending ? this._pending.offset : this.offset;+ const len = current.length();+ if (len < 1e-4) return;+ const nextLen = Math.max(bounds.min, Math.min(bounds.max, len * factor));+ const scale = nextLen / len;+ current.multiplyScalar(scale);+ }++ tick(dt) {+ if (this._pending) {+ const k = Math.min(1, dt * this._pending.lerp);+ this.target.lerp(this._pending.target, k);+ this.offset.lerp(this._pending.offset, k);+ if (+ this.target.distanceTo(this._pending.target) < 0.01 &&+ this.offset.distanceTo(this._pending.offset) < 0.01+ ) {+ this.target.copy(this._pending.target);+ this.offset.copy(this._pending.offset);+ this._pending = null;+ }+ }++ if (this.mode === 'free') {+ // In free mode the stored offset is the "base" rest position; rotate+ // it around Y by user yaw to orbit. Pitch is baked into the offset Y.+ const rest = this.offset.clone();+ rest.y = 2.2 + this.pitch * 2.5;+ const rotated = rest.applyAxisAngle(new Vector3(0, 1, 0), this.yaw);+ this.camera.position.copy(this.target.clone().add(rotated));+ } else {+ this.camera.position.copy(this.target.clone().add(this.offset));+ }+ this.camera.lookAt(this.target);+ }+}diff --git a/src/club.js b/src/club.jsindex 4d9cc3759..c38777e63 100644--- a/src/club.js+++ b/src/club.js@@ -36,6 +36,8 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';import { AnimationManager } from './animation-manager.js';+import { ClubCamera } from './club-camera.js';+import { ClubAudio, styleAudioFor, TRACK_LABELS } from './club-audio.js';const AVATAR_URL = '/avatars/default.glb';const MANIFEST_URL = '/animations/manifest.json';@@ -135,6 +137,10 @@ const camera = new PerspectiveCamera(46, window.innerWidth / window.innerHeight,camera.position.set(0, 1.8, 6.0);camera.lookAt(0, 1.4, -1.5);+const clubCam = new ClubCamera(camera, {+ onModeChange: (mode) => updateFreeCamChip(mode),+});+// ── Club floor + walls ───────────────────────────────────────────────────const floor = new Mesh(new CircleGeometry(14, 80),@@ -333,6 +339,16 @@ class PoleStation {this._spotTarget = this.spotActiveIntensity;this._accentTarget = 2.4;+ // Auto-cam: if the user opted in and no manual VIP/house shot is active,+ // switch to this pole's VIP cam for the duration. We remember that the+ // auto-cam started this transition so we can release it on end.+ if (autoFollow && clubCam.getMode() === 'free') {+ this._autoCammed = true;+ clubCam.setVip(this.layout);+ } else {+ this._autoCammed = false;+ }+// Crossfade idle → walking → dance once the dancer reaches the pole.await this.anim?.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);}@@ -349,6 +365,19 @@ class PoleStation {this._phaseTarget = this.backstagePos;this._spotTarget = this.spotIdleIntensity;this._accentTarget = 0.4;+ // Release auto-cam back to free if we were the ones who took it.+ if (this._autoCammed && clubCam.getMode() === 'vip') {+ clubCam.setFree();+ }+ this._autoCammed = false;+ // Signal the audio mixer (and anyone else listening) to fade the+ // style loop back to ambience. Dispatched on window so the page-+ // level audio binding can stay decoupled from this class.+ try {+ window.dispatchEvent(new CustomEvent('club:performance-end', {+ detail: { dancer: this.id, ticket: this.activeTicket },+ }));+ } catch {}await this.anim?.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);}@@ -507,6 +536,36 @@ async function tipDancer({ dancer, dance, button }) {}}+// ── Free cam chip (shown while in VIP / house) ───────────────────────────+let freeCamChip = null;+function ensureFreeCamChip() {+ if (freeCamChip) return freeCamChip;+ const chip = document.createElement('button');+ chip.type = 'button';+ chip.id = 'club-free-cam';+ chip.textContent = '↩ Free cam';+ chip.hidden = true;+ chip.addEventListener('click', () => clubCam.setFree());+ const stage = document.getElementById('club-stage');+ (stage || document.body).appendChild(chip);+ freeCamChip = chip;+ return chip;+}+function updateFreeCamChip(mode) {+ const chip = ensureFreeCamChip();+ chip.hidden = (mode === 'free');+}++// ── Auto-follow tips toggle (persisted) ──────────────────────────────────+const AUTO_FOLLOW_KEY = 'club:autoFollowTips';+let autoFollow = (() => {+ try { return localStorage.getItem(AUTO_FOLLOW_KEY) === '1'; } catch { return false; }+})();+function setAutoFollow(on) {+ autoFollow = !!on;+ try { localStorage.setItem(AUTO_FOLLOW_KEY, autoFollow ? '1' : '0'); } catch {}+}+// ── Side panel — render pole controls ────────────────────────────────────const DANCES = [{ key: 'rumba', label: 'Rumba' },@@ -525,7 +584,10 @@ function renderPoles() {card.innerHTML = `<div class="club-pole-head"><span class="club-pole-id">Pole ${pole.id}</span>- <span class="club-pole-price">$0.001 USDC</span>+ <span class="club-pole-row-right">+ <span class="club-pole-price">$0.001 USDC</span>+ <button type="button" class="club-cam-btn" data-pole="${pole.id}" title="VIP cam">🎬</button>+ </span></div><label class="club-pole-style">Style@@ -540,6 +602,12 @@ function renderPoles() {polesPanel.appendChild(card);}polesPanel.addEventListener('click', (e) => {+ const camBtn = e.target.closest('.club-cam-btn');+ if (camBtn) {+ const layout = POLES.find((p) => p.id === camBtn.dataset.pole);+ if (layout) clubCam.setVip(layout);+ return;+ }const btn = e.target.closest('.club-tip-btn');if (!btn) return;const dancer = btn.dataset.dancer;@@ -549,33 +617,54 @@ function renderPoles() {});}-// ── Camera orbit on drag ─────────────────────────────────────────────────-let camYaw = 0;-let camPitch = 0.05;+// ── Pointer + pinch handling ─────────────────────────────────────────────+// One pointer → orbit (ClubCamera.applyDrag, free mode only). Two pointers →+// pinch zoom (ClubCamera.applyZoom). Wheel also zooms. The camera state+// machine owns yaw/pitch — this block is just input plumbing.{- let dragging = false;- let lastX = 0, lastY = 0, downId = -1;+ const pointers = new Map(); // pointerId → {x, y}+ let pinchPrevDist = 0;++ const pinchDistance = () => {+ const [a, b] = [...pointers.values()];+ return Math.hypot(a.x - b.x, a.y - b.y);+ };+canvas.addEventListener('pointerdown', (e) => {- dragging = true;- downId = e.pointerId;- lastX = e.clientX; lastY = e.clientY;+ pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });canvas.setPointerCapture?.(e.pointerId);+ if (pointers.size === 2) pinchPrevDist = pinchDistance();});canvas.addEventListener('pointermove', (e) => {- if (!dragging || e.pointerId !== downId) return;- const dx = e.clientX - lastX;- const dy = e.clientY - lastY;- lastX = e.clientX; lastY = e.clientY;- camYaw -= dx * 0.004;- camPitch = Math.max(-0.3, Math.min(0.5, camPitch - dy * 0.003));+ const prev = pointers.get(e.pointerId);+ if (!prev) return;+ const dx = e.clientX - prev.x;+ const dy = e.clientY - prev.y;+ prev.x = e.clientX; prev.y = e.clientY;++ if (pointers.size === 1) {+ clubCam.applyDrag(dx, dy);+ } else if (pointers.size === 2) {+ const next = pinchDistance();+ // Pinch-in (fingers closer) → zoom in (negative deltaY); pinch-out → zoom out.+ const delta = (pinchPrevDist - next) * 4; // scale to wheel-ish units+ clubCam.applyZoom(delta);+ pinchPrevDist = next;+ }});const onUp = (e) => {- if (e.pointerId !== downId) return;- dragging = false; downId = -1;+ if (!pointers.has(e.pointerId)) return;+ pointers.delete(e.pointerId);try { canvas.releasePointerCapture?.(e.pointerId); } catch {}+ if (pointers.size < 2) pinchPrevDist = 0;};canvas.addEventListener('pointerup', onUp);canvas.addEventListener('pointercancel', onUp);++ canvas.addEventListener('wheel', (e) => {+ e.preventDefault();+ clubCam.applyZoom(e.deltaY);+ }, { passive: false });}// ── Resize ────────────────────────────────────────────────────────────────@@ -585,6 +674,23 @@ window.addEventListener('resize', () => {camera.updateProjectionMatrix();});+// ── Keyboard shortcuts ───────────────────────────────────────────────────+// 0 → overhead house cam+// 1-4 → per-pole VIP cam+// Esc → back to free orbit+// Inputs / selects in the side panel are excluded so typing doesn't move+// the camera.+window.addEventListener('keydown', (e) => {+ const tag = e.target?.tagName;+ if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return;+ if (e.key === '0') return clubCam.setHouse();+ if (e.key === 'Escape') return clubCam.setFree();+ if (['1', '2', '3', '4'].includes(e.key)) {+ const layout = POLES.find((p) => p.id === e.key);+ if (layout) clubCam.setVip(layout);+ }+});+// ── Render loop ──────────────────────────────────────────────────────────const clock = new Clock();function animate() {@@ -596,19 +702,24 @@ function animate() {// Disco light slow swirl.disco.rotation.y = t * 0.25;- // Camera dolly — gentle orbit around the dance floor center.- const focus = new Vector3(0, 1.2, -1.8);- const offsetBase = new Vector3(0, 2.2 + camPitch * 2.5, 7.2);- offsetBase.applyAxisAngle(new Vector3(0, 1, 0), camYaw);- const target = focus.clone().add(offsetBase);- camera.position.lerp(target, Math.min(1, dt * 2));- camera.lookAt(focus);+ // Camera state machine — orbit / VIP / house.+ clubCam.tick(dt);renderer.render(scene, camera);requestAnimationFrame(animate);}renderPoles();++// Bind the auto-follow checkbox to persisted state.+{+ const cb = document.getElementById('club-auto-follow');+ if (cb) {+ cb.checked = autoFollow;+ cb.addEventListener('change', () => setAutoFollow(cb.checked));+ }+}+bootstrap().catch((err) => {console.error('[club] bootstrap failed', err);diff --git a/tests/club-camera.test.js b/tests/club-camera.test.jsnew file mode 100644index 000000000..045510f18--- /dev/null+++ b/tests/club-camera.test.js@@ -0,0 +1,161 @@+// Tests for the ClubCamera state machine used by /club.+//+// We stub a PerspectiveCamera-shaped object (just `.position` + `.lookAt`)+// because the state machine only writes to those. This keeps the test pure+// JS — no WebGL / DOM — so vitest exercises the math directly.++import { describe, it, expect } from 'vitest';+import { Vector3 } from 'three';+import { ClubCamera, CLUB_CAMERA_MODES } from '../src/club-camera.js';++function makeStubCamera() {+ const cam = {+ position: new Vector3(),+ _lookAt: new Vector3(),+ lookAt(x, y, z) {+ if (x?.isVector3) this._lookAt.copy(x);+ else this._lookAt.set(x, y, z);+ },+ };+ return cam;+}++// Drive the machine forward with fixed-dt frames until pending lerp settles+// or we hit the iteration ceiling.+function runFrames(clubCam, frames = 240, dt = 1 / 60) {+ for (let i = 0; i < frames; i++) clubCam.tick(dt);+}++describe('ClubCamera — vocabulary', () => {+ it('exports the canonical mode list', () => {+ expect(CLUB_CAMERA_MODES).toEqual(['free', 'vip', 'house']);+ });++ it('starts in free mode with sensible defaults', () => {+ const c = new ClubCamera(makeStubCamera());+ expect(c.getMode()).toBe('free');+ });+});++describe('ClubCamera — VIP convergence', () => {+ const pole3 = { id: '3', x: 1.8, z: -2.4, yaw: 0.65 };++ it('setVip lerps camera to the expected world coordinate', () => {+ const cam = makeStubCamera();+ const c = new ClubCamera(cam);+ c.setVip(pole3);+ expect(c.getMode()).toBe('vip');++ runFrames(c, 240);++ // Expected world position = pole target + offset (yaw + π flips behind dancer).+ const expectedTarget = new Vector3(pole3.x, 1.6, pole3.z);+ const expectedOffset = new Vector3(+ Math.sin(pole3.yaw + Math.PI) * 2.6,+ 1.3,+ Math.cos(pole3.yaw + Math.PI) * 2.6,+ );+ const expectedPos = expectedTarget.clone().add(expectedOffset);++ expect(cam.position.distanceTo(expectedPos)).toBeLessThan(0.05);+ // And the camera looks at the dancer, not at empty space.+ expect(cam._lookAt.distanceTo(expectedTarget)).toBeLessThan(0.05);+ });++ it('switches to house mode (overhead) and lands above the room', () => {+ const cam = makeStubCamera();+ const c = new ClubCamera(cam);+ c.setHouse();+ expect(c.getMode()).toBe('house');++ runFrames(c, 360);++ // House cam target = (0, 0.5, -1.5), offset = (0, 12, ~0) → camera high overhead.+ expect(cam.position.y).toBeGreaterThan(11.5);+ expect(Math.abs(cam.position.x)).toBeLessThan(0.1);+ });+});++describe('ClubCamera — free mode after VIP', () => {+ const pole1 = { id: '1', x: -1.8, z: -2.4, yaw: -0.65 };++ it('ignores drag input while in VIP mode', () => {+ const c = new ClubCamera(makeStubCamera());+ c.setVip(pole1);+ const yawBefore = c.yaw;+ c.applyDrag(120, 0);+ expect(c.yaw).toBe(yawBefore);+ });++ it('setFree restores orbit and drag rotates yaw again', () => {+ const cam = makeStubCamera();+ const c = new ClubCamera(cam);+ c.setVip(pole1);+ runFrames(c, 60);++ c.setFree();+ expect(c.getMode()).toBe('free');++ const yawBefore = c.yaw;+ c.applyDrag(120, 0);+ expect(c.yaw).toBeLessThan(yawBefore); // applyDrag: yaw -= dx * 0.004++ // After settling, free-mode camera sits in front of the dance floor+ // (positive Z relative to the focus target) — i.e. user-facing.+ runFrames(c, 240);+ expect(cam.position.z).toBeGreaterThan(0);+ });++ it('drag pitch is clamped to [-0.3, 0.5]', () => {+ const c = new ClubCamera(makeStubCamera());+ // Huge negative dy → pitch up+ c.applyDrag(0, -10000);+ expect(c.pitch).toBe(0.5);+ // Huge positive dy → pitch down+ c.applyDrag(0, 10000);+ expect(c.pitch).toBe(-0.3);+ });+});++describe('ClubCamera — zoom', () => {+ it('applyZoom shrinks the offset on negative deltaY (zoom in)', () => {+ const c = new ClubCamera(makeStubCamera());+ const lenBefore = c.offset.length();+ c.applyZoom(-200);+ expect(c.offset.length()).toBeLessThan(lenBefore);+ });++ it('applyZoom is a no-op in house mode', () => {+ const c = new ClubCamera(makeStubCamera());+ c.setHouse();+ runFrames(c, 200); // settle+ const before = c.offset.clone();+ c.applyZoom(500);+ expect(c.offset.distanceTo(before)).toBe(0);+ });++ it('applyZoom clamps to per-mode bounds in free', () => {+ const c = new ClubCamera(makeStubCamera());+ // Zoom out hard+ for (let i = 0; i < 100; i++) c.applyZoom(500);+ expect(c.offset.length()).toBeLessThanOrEqual(14.0 + 1e-6);+ // Zoom in hard+ for (let i = 0; i < 100; i++) c.applyZoom(-500);+ expect(c.offset.length()).toBeGreaterThanOrEqual(3.5 - 1e-6);+ });+});++describe('ClubCamera — mode change callback', () => {+ it('fires onModeChange only on actual transitions', () => {+ const calls = [];+ const c = new ClubCamera(makeStubCamera(), {+ onModeChange: (m) => calls.push(m),+ });+ c.setFree(); // already free → no callback+ c.setVip({ id: '1', x: 0, z: 0, yaw: 0 });+ c.setVip({ id: '2', x: 1, z: 0, yaw: 0 }); // still vip → no callback+ c.setHouse();+ c.setFree();+ expect(calls).toEqual(['vip', 'house', 'free']);+ });+});diff --git a/x402-buildout/prompts/10-mcp-server.md b/x402-buildout/prompts/10-mcp-server.mdnew file mode 100644index 000000000..acf1749f7--- /dev/null+++ b/x402-buildout/prompts/10-mcp-server.md@@ -0,0 +1,91 @@+# USE-10: MCP Server — Paid tools for Claude Desktop / Cursor++## Goal+Expose this repo's capabilities (pose generation, vanity grinding, Pump.fun queries, agent reputation lookups) as paid MCP tools. AI agents call tools, the server returns 402 with `PaymentRequired`, agents auto-pay via x402-MCP transport.++## Why+- We have a real catalog of agent-usable tools (USE-29..40 each produce one).+- MCP is the standard way Claude Desktop and Cursor talk to local services. Charging via x402 over MCP is the canonical agent-payments path.++## Reference+- MCP transport spec: [/tmp/x402-docs/specs/transports-v2/mcp.md](/tmp/x402-docs/specs/transports-v2/mcp.md)+- Guide: [/tmp/x402-docs/docs/guides/mcp-server-with-x402.md](/tmp/x402-docs/docs/guides/mcp-server-with-x402.md)+- `@x402/mcp`: [typescript/packages/mcp](https://github.com/x402-foundation/x402/tree/main/typescript/packages/mcp)+- Server example: [examples/typescript/servers/mcp](https://github.com/x402-foundation/x402/tree/main/examples/typescript/servers/mcp)++## Dependencies+- USE-00, USE-01, USE-02 (or USE-03 for SVM tools)++## Files to create+- `mcp-server/` — new workspace (add to root `package.json` `workspaces`)+- `mcp-server/package.json` — `name: "@3d-agent/mcp-server"`+- `mcp-server/src/index.js` — entry point using `@modelcontextprotocol/sdk` + `@x402/mcp`+- `mcp-server/src/tools/pose-seed.js` — paid tool for the pose-studio+- `mcp-server/src/tools/pump-snapshot.js` — paid tool returning Pump.fun snapshot+- `mcp-server/src/tools/agent-reputation.js` — paid tool reading on-chain reputation+- `mcp-server/src/tools/vanity-grinder.js` — paid `upto`-scheme tool for vanity addresses+- `mcp-server/README.md` — Claude Desktop and Cursor config instructions++## Files to modify+- Root `package.json` — add `mcp-server` to workspaces+- `.env.example` — `MCP_EVM_PAYMENT_ADDRESS`, `MCP_SVM_PAYMENT_ADDRESS` (can reuse main env vars)+- `vercel.json` — N/A (MCP server runs locally via stdio transport)++## Implementation++### Server skeleton+```js+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";+import { createPaymentWrapper, x402MCPServer } from "@x402/mcp";+import { getResourceServer } from "../../api/_lib/x402/sdk.js";++const server = new McpServer({ name: "3d-agent-mcp", version: "1.0.0" });+const resourceServer = getResourceServer({ networks: ["evm", "svm"] });++const wrap = (accepts, handler) => createPaymentWrapper(resourceServer, { accepts, ... });++server.tool("get_pose_seed", "...", { prompt: z.string() }, wrap(poseSeedAccepts, async ({ prompt }) => { ... }));++await server.connect(new StdioServerTransport());+```++### Bazaar discovery+Pass `declareDiscoveryExtension(...)` in each tool's payment wrapper config so the facilitator catalogs the tool. See USE-13.++### Tool catalog+- `get_pose_seed(prompt: string)` — `exact` $0.001 — returns `{ seed, parameters, previewUrl }`+- `pump_snapshot(token: string)` — `exact` $0.005 — returns `{ price, volume24h, holders, image }`+- `agent_reputation(address: string)` — `exact` $0.01 — returns reputation score + on-chain attestations+- `vanity_grinder(prefix: string)` — `upto` $0.50 — actual cost scales with attempts; returns address + private key only over secure channel++### Distribution+Provide ready-to-paste Claude Desktop config in the README:+```json+{+ "mcpServers": {+ "3d-agent": {+ "command": "node",+ "args": ["<absolute path>/mcp-server/src/index.js"],+ "env": {+ "EVM_PAYMENT_ADDRESS": "0x...",+ "SVM_PAYMENT_ADDRESS": "..."+ }+ }+ }+}+```++## Wiring checklist+- [ ] MCP server starts standalone via `node mcp-server/src/index.js`+- [ ] Tools advertise `PaymentRequired` correctly on first call (per spec: `isError: true` + `structuredContent` + `content[0].text`)+- [ ] Settlement response carried in `_meta["x402/payment-response"]`+- [ ] Bazaar discovery extension declared per tool+- [ ] README has working Claude Desktop config++## Acceptance+- [ ] Claude Desktop with the server configured can call `get_pose_seed` and receive the data after paying+- [ ] Cursor's MCP integration works against the same server+- [ ] `npx @modelcontextprotocol/inspector` connects to the server and lists tools+- [ ] Tool calling without payment returns the 402 PaymentRequired in `structuredContent`+- [ ] Each tool produces a real, useful result — no demo stringsdiff --git a/x402-buildout/prompts/11-mcp-client.md b/x402-buildout/prompts/11-mcp-client.mdnew file mode 100644index 000000000..69b1e7e3f--- /dev/null+++ b/x402-buildout/prompts/11-mcp-client.md@@ -0,0 +1,72 @@+# USE-11: MCP Client — Auto-pay tool bridge++## Goal+Build an MCP client that any consumer agent in this repo can use to call paid MCP tools — automatically handling payment. Also expose this as a Claude Desktop MCP server itself so a user's Claude can call OUR x402 endpoints via a payment-bridge.++## Why+- Our agents need to consume paid tools (e.g., the prediction oracle calls a paid search API).+- Users with Claude Desktop want a single MCP bridge that turns "any x402 endpoint" into a paid Claude-callable tool — without manually building each bridge.++## Reference+- MCP guide: [/tmp/x402-docs/docs/guides/mcp-server-with-x402.md](/tmp/x402-docs/docs/guides/mcp-server-with-x402.md)+- Client example: [examples/typescript/clients/mcp](https://github.com/x402-foundation/x402/tree/main/examples/typescript/clients/mcp)+- Chatbot example: [examples/typescript/clients/mcp-chatbot](https://github.com/x402-foundation/x402/tree/main/examples/typescript/clients/mcp-chatbot)++## Dependencies+- USE-00, USE-06, USE-07, USE-09+- USE-10 (something paid to call)++## Files to create+- `mcp-bridge/` — new workspace+- `mcp-bridge/package.json`+- `mcp-bridge/src/index.js` — MCP server that exposes a single tool `call_paid_endpoint(url, args)` which transparently pays via x402+- `mcp-bridge/src/x402-axios-client.js` — wraps axios with EVM + SVM + batch schemes+- `mcp-bridge/src/bazaar-discover.js` — when started, queries Bazaar and registers each discovered service as its own MCP tool+- `mcp-bridge/README.md` — Claude Desktop config++## Files to modify+- Root `package.json` — add workspace+- `.env.example` — `MCP_BRIDGE_DISCOVER_LIMIT` (default 20), `MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC` (safety cap)++## Implementation++### Single fallback tool+For arbitrary URLs the user wants to hit:+```js+server.tool(+ "call_paid_endpoint",+ "Call any x402 endpoint with auto-payment",+ { url: z.string(), method: z.string().optional(), body: z.any().optional(), params: z.record(z.any()).optional() },+ async ({ url, method = "GET", body, params }) => {+ const res = await api.request({ url, method, data: body, params });+ return { content: [{ type: "text", text: JSON.stringify(res.data) }] };+ }+);+```++### Bazaar-driven dynamic tools+On startup:+1. Query the Bazaar `/discovery/resources` for HTTP and MCP types.+2. Register up to `MCP_BRIDGE_DISCOVER_LIMIT` tools with sane names derived from the resource description.+3. Each tool's input schema comes from `extensions.bazaar.info.input.queryParams` or `inputSchema`.++This means a user running this MCP bridge can ask Claude "find me a weather API and call it" — Claude discovers the bazaar-registered tool and uses it directly.++### Spending caps+Hook `onBeforePaymentCreation` to enforce `MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC` — abort with a clear reason if exceeded. This is the consumer-side equivalent of USE-22.++### Storage for batch-settlement+Persist channel state in `~/.x402-mcp-bridge/channels.json` so the bridge survives Claude Desktop restarts.++## Wiring checklist+- [ ] Bridge starts cleanly via `node mcp-bridge/src/index.js`+- [ ] `call_paid_endpoint` tool works end-to-end against `api/x402/exact-evm-demo`+- [ ] Bazaar discovery populates dynamic tools at startup+- [ ] Spending cap rejects calls over the configured max+- [ ] Channel state persists across restarts+- [ ] README has Claude Desktop config snippet++## Acceptance+- [ ] Claude Desktop user asks "pay $0.01 on Base for a weather report"; the bridge picks the right tool from Bazaar, pays, returns weather+- [ ] Calling `call_paid_endpoint` with a URL exceeding the spending cap returns a clear error in the tool result+- [ ] Killing and restarting Claude Desktop preserves batch-settlement channels (no redeposit on first call)diff --git a/x402-buildout/prompts/12-a2a-transport.md b/x402-buildout/prompts/12-a2a-transport.mdnew file mode 100644index 000000000..05edb7e00--- /dev/null+++ b/x402-buildout/prompts/12-a2a-transport.md@@ -0,0 +1,65 @@+# USE-12: A2A Transport — Agent-to-Agent x402++## Goal+Implement the x402 A2A (Agent-to-Agent) protocol extension so this repo's agents can pay each other for services. Use task-based state management with `x402.payment.*` metadata fields, following [google-agentic-commerce/a2a-x402](https://github.com/google-agentic-commerce/a2a-x402).++## Why+- This repo has multiple agents (solana-agent-sdk, agent-payments-sdk). Agents calling agents is a real use case.+- A2A is the canonical agent-to-agent payments transport, distinct from HTTP and MCP.++## Reference+- A2A transport spec: [/tmp/x402-docs/specs/transports-v2/a2a.md](/tmp/x402-docs/specs/transports-v2/a2a.md)+- A2A protocol: [a2a-protocol.org](https://a2a-protocol.org/latest/specification)+- A2A x402 extension: [a2a-x402 spec](https://github.com/google-agentic-commerce/a2a-x402/blob/main/spec/v0.1/spec.md)++## Dependencies+- USE-00, USE-01++## Files to create+- `api/_lib/x402/a2a-server.js` — A2A-flavored payment handshake (task state `input-required` with `x402.payment.required` metadata)+- `api/_lib/x402/a2a-client.js` — agent client that handles `x402.payment.*` lifecycle+- `api/agents/a2a-paid.js` — Vercel function exposing an A2A endpoint accepting payments+- `agent-payments-sdk/src/a2a-helpers.js` — helper used by other agents in this workspace++## Files to modify+- `vercel.json` — route for `/api/agents/a2a-paid`+- AgentCard JSON returned by `/api/agents/solana/[action]?action=card` — add the x402 extension declaration:+ ```json+ "capabilities": {+ "extensions": [{ "uri": "https://github.com/google-a2a/a2a-x402/v0.1", "required": true }]+ }+ ```++## Implementation++### Server side (A2A receiver)+- On `message/send` without payment metadata: respond with a task in state `input-required` carrying `x402.payment.status: "payment-required"` and `x402.payment.required: <PaymentRequirements>`.+- On message with `x402.payment.payload`: verify via facilitator, transition task to `working`, run handler, settle, transition to `completed` with `x402.payment.receipts: [<SettlementResponse>]`.+- Activate extension via `X-A2A-Extensions: https://github.com/google-a2a/a2a-x402/v0.1` response header.++### Client side (A2A caller)+- On receiving task `input-required` with `x402.payment.status: "payment-required"`: build `PaymentPayload`, send via `message/send` with `x402.payment.status: "payment-submitted"`.+- Activate extension via `X-A2A-Extensions` request header.+- Correlate via `taskId`.++### Status lifecycle+Track full status progression per spec:+- `payment-required` → `payment-submitted` → `payment-verified` → `payment-completed` (or `payment-failed`)+- Update task state appropriately at each step.++### Catalog and identity+Surface our A2A endpoints in our AgentCard. The existing `/.well-known/agent-card.json` routes are the right place.++## Wiring checklist+- [ ] AgentCard declares the x402 extension URI and `required: true`+- [ ] Server response includes `X-A2A-Extensions` header+- [ ] Client request includes `X-A2A-Extensions` header+- [ ] Task lifecycle state transitions match spec+- [ ] Errors map to spec table (Payment Rejected, Invalid Payment, Settlement Failed, etc.)++## Acceptance+- [ ] Agent A's `/api/agents/a2a-paid` returns `input-required` task with `x402.payment.required` on first call+- [ ] Agent B (in same repo) pays, receives `completed` task with valid `x402.payment.receipts`+- [ ] On-chain settlement tx visible in receipt+- [ ] A2A endpoint listed in our AgentCard with the extension declaration+- [ ] Test cross-vendor compatibility: an external A2A client implementing x402 v0.1 successfully completes a paymentdiff --git a/x402-buildout/prompts/13-bazaar-server-listing.md b/x402-buildout/prompts/13-bazaar-server-listing.mdnew file mode 100644index 000000000..56d43c9e5--- /dev/null+++ b/x402-buildout/prompts/13-bazaar-server-listing.md@@ -0,0 +1,65 @@+# USE-13: Bazaar — Server-side listing++## Goal+Make every paid endpoint in this repo discoverable via the x402 Bazaar. Each route declares `bazaar` extension with input/output schemas + service metadata (`serviceName`, `tags`, `iconUrl`).++## Why+- Buyers and agent ecosystems discover x402 services through facilitator Bazaars.+- Without this, our paid endpoints are unfindable except by direct URL.++## Reference+- Bazaar docs: [/tmp/x402-docs/docs/extensions/bazaar.mdx](/tmp/x402-docs/docs/extensions/bazaar.mdx)+- Spec: [/tmp/x402-docs/specs/extensions/bazaar.md](/tmp/x402-docs/specs/extensions/bazaar.md)++## Dependencies+- USE-00, USE-02, USE-03, USE-04, USE-05, USE-10++## Files to create+- `api/_lib/x402/bazaar-helpers.js` — `declareDiscovery(routeName, { input, inputSchema, output })` returns the extensions block++## Files to modify+- Every paid endpoint created so far: add `extensions.bazaar` to its route config+- Every MCP tool (USE-10): pass `declareDiscoveryExtension(...)` in its payment wrapper config+- `api/_lib/x402/sdk.js` — register `BazaarServerExtension` on the resource server++## Implementation++### Per-route metadata+For each paid endpoint, declare:+```js+extensions: {+ ...declareDiscoveryExtension({+ input: { /* example query/body */ },+ inputSchema: {+ properties: { /* JSON Schema */ },+ required: [/* keys */]+ },+ output: {+ example: { /* sample response */ },+ schema: { /* JSON Schema */ }+ }+ })+}+```++### Service-level metadata on `resource`+Set `serviceName` (≤32 chars printable ASCII), `tags` (max 5, each ≤32 chars), `iconUrl` (https URL). The facilitator uses these for filtering and search.++### MCP tools+For MCP tools, use `declareDiscoveryExtension({ toolName, description, transport: "sse" | "streamable-http", inputSchema, example })` and pass in the payment wrapper config.++### Verification+Hit our facilitator's `/discovery/resources` after the first paid request to confirm our routes appear. Some facilitators index asynchronously; allow a few seconds.++## Wiring checklist+- [ ] Every paid HTTP endpoint declares `bazaar` extension+- [ ] Every paid MCP tool declares the discovery extension in its wrapper config+- [ ] `resource.serviceName`, `resource.tags`, `resource.iconUrl` set on every route+- [ ] BazaarServerExtension registered on the resource server (auto-narrows HTTP method etc.)++## Acceptance+- [ ] `curl https://x402.org/facilitator/discovery/resources?payTo=<our address>` returns our endpoints+- [ ] Each entry has correct `accepts[]`, `extensions.bazaar.info`, and `resource.serviceName`+- [ ] MCP tools appear with `type: "mcp"` and correct `toolName`+- [ ] Bazaar search returns our endpoints for a relevant query+- [ ] Settlement responses include `EXTENSION-RESPONSES` header confirming `bazaar.status: "success"` (or `processing`)diff --git a/x402-buildout/prompts/14-bazaar-discovery-client.md b/x402-buildout/prompts/14-bazaar-discovery-client.mdnew file mode 100644index 000000000..466198109--- /dev/null+++ b/x402-buildout/prompts/14-bazaar-discovery-client.md@@ -0,0 +1,72 @@+# USE-14: Bazaar — Discovery client++## Goal+Build a buyer-side Bazaar discovery layer: search and filter the facilitator catalog, return ranked results, and feed them into the auto-pay clients (USE-06/07).++## Why+- Agents (USE-29..40) need to dynamically find paid services rather than hardcoding URLs.+- A useful UI surface for our own marketplace listings (data/rss/, public discovery pages).++## Reference+- Bazaar docs (Buyer Quickstart): [/tmp/x402-docs/docs/extensions/bazaar.mdx](/tmp/x402-docs/docs/extensions/bazaar.mdx)+- Spec: [/tmp/x402-docs/specs/extensions/bazaar.md](/tmp/x402-docs/specs/extensions/bazaar.md)++## Dependencies+- USE-00, USE-01++## Files to create+- `api/_lib/x402/bazaar-client.js` — `class Bazaar { list(filters), search(query), get(resourceUrl) }`+- `api/bazaar/list.js` — proxy GET endpoint clients can hit without auth+- `api/bazaar/search.js` — proxy GET endpoint+- `public/bazaar.html` — minimal discovery UI: search, filter, sort by price, pay directly+- `public/bazaar.js` — front-end logic using `x402-buyer.js` (USE-06)++## Files to modify+- `vercel.json` — routes for `/api/bazaar/*` and `/bazaar` (rewrites to `/bazaar.html`)+- `public/x402.js` — add discovery hook++## Implementation++### Client wrapper+```js+import { HTTPFacilitatorClient } from "@x402/core/http";+import { withBazaar } from "@x402/extensions";++export function bazaarClient(facilitatorUrl) {+ return withBazaar(new HTTPFacilitatorClient({ url: facilitatorUrl })).extensions.bazaar;+}++const baz = bazaarClient("https://x402.org/facilitator");+const { items } = await baz.listResources({ type: "http" });+const { resources } = await baz.search({ query: "weather", type: "http" });+```++### Filtering helpers+Expose helpers for common queries:+- `filterByMaxPrice(items, atomicMax, asset)` — under-N USDC items+- `filterByNetwork(items, "eip155:*" | "solana:*")`+- `filterByExtension(items, "sign-in-with-x")`+- `groupBy(items, key)` — group by `serviceName` or `payTo`++### Multi-facilitator+Some facilitators have different catalogs. Accept an array of facilitator URLs and merge results, deduplicating by `(resource, toolName)` for MCP and `resource` for HTTP.++### Public UI+- Search bar+- Filter sidebar: network, max price, has extension X, tag+- Result cards with `iconUrl`, `serviceName`, `description`, price, "Try it" button that calls the endpoint via wrapped fetch+- Show settlement receipt after successful call++## Wiring checklist+- [ ] `/bazaar` page renders results from x402.org facilitator+- [ ] Filters reduce the result set correctly+- [ ] "Try it" button pays via the buyer client and shows the response+- [ ] Multi-facilitator merge dedupes properly+- [ ] No CORS issues (proxy via `/api/bazaar/*` if facilitator CORS is restrictive)++## Acceptance+- [ ] `/api/bazaar/list?type=http` returns valid JSON+- [ ] `/api/bazaar/search?query=weather` returns results+- [ ] `/bazaar` page shows our own paid endpoints (verified via the seller listing in USE-13)+- [ ] Paying through the page produces a real on-chain transaction+- [ ] Network filter works for both EVM and Solanadiff --git a/x402-buildout/prompts/15-payment-identifier.md b/x402-buildout/prompts/15-payment-identifier.mdnew file mode 100644index 000000000..8259eb8a3--- /dev/null+++ b/x402-buildout/prompts/15-payment-identifier.md@@ -0,0 +1,85 @@+# USE-15: Payment Identifier — Idempotency++## Goal+Wire the `payment-identifier` extension on every paid endpoint and every buyer client. Server caches responses keyed by `paymentId`. Same `paymentId` within TTL returns cached response without re-charging.++## Why+- Network flakiness causes legitimate retries. Without idempotency, every retry double-charges.+- Required for trustworthy production usage (USE-29..40).++## Reference+- Docs: [/tmp/x402-docs/docs/extensions/payment-identifier.mdx](/tmp/x402-docs/docs/extensions/payment-identifier.mdx)+- Spec: [/tmp/x402-docs/specs/extensions/payment_identifier.md](/tmp/x402-docs/specs/extensions/payment_identifier.md)++## Dependencies+- USE-00, USE-02 (or any seller), USE-06 (or any buyer)+- USE-05 dependency (Redis) is reused for the cache store++## Files to create+- `api/_lib/x402/idempotency-cache.js` — Redis-backed cache: `get(id)`, `set(id, payload, ttlSec)`+- `api/_lib/x402/payment-identifier-server.js` — hooks `onProtectedRequest` to check cache; `onAfterSettle` to write cache+- `api/_lib/x402/payment-identifier-client.js` — adds `paymentId` to outgoing payloads when server declares support++## Files to modify+- Every paid endpoint: declare `payment-identifier` extension in route config+- Every buyer client init: install the client hook+- `.env.example` — `X402_IDEMPOTENCY_TTL_SECONDS` (default 3600)++## Implementation++### Server+```js+import { declarePaymentIdentifierExtension, PAYMENT_IDENTIFIER, extractPaymentIdentifier } from "@x402/extensions/payment-identifier";++// In route config+extensions: { [PAYMENT_IDENTIFIER]: declarePaymentIdentifierExtension(false) }++// On resource server+resourceServer.onAfterSettle(async ({ paymentPayload, settlementResponse, response }) => {+ const id = extractPaymentIdentifier(paymentPayload);+ if (id) await idempotencyCache.set(id, { settlementResponse, body: response.body }, TTL);+});++httpServer.onProtectedRequest(async (context) => {+ if (!context.paymentHeader) return;+ const payload = decodePayload(context.paymentHeader);+ const id = extractPaymentIdentifier(payload);+ if (!id) return;+ const cached = await idempotencyCache.get(id);+ if (cached) return { grantAccess: true, cachedResponse: cached };+});+```++### Client+```js+import { generatePaymentId, appendPaymentIdentifierToExtensions } from "@x402/extensions/payment-identifier";++client.onBeforePaymentCreation(async ({ paymentRequired, requestContext }) => {+ if (!paymentRequired.extensions) return;+ // Use a stable id per logical request; if caller didn't supply one, generate per-call+ const id = requestContext.paymentId ?? generatePaymentId();+ appendPaymentIdentifierToExtensions(paymentRequired.extensions, id);+});+```++### Per-call payment IDs+Wrappers expose an option `{ paymentId: "order_xyz" }` so caller code can pass a stable ID across retries. For browser flows, derive ID from `requestId` stored in `sessionStorage`.++### Required vs optional+Default optional. Where critical (USE-32 fact-checker, USE-30 oracle), set `declarePaymentIdentifierExtension(true)` so caller MUST provide an ID.++### Cache hygiene+- Hash the payload alongside the ID. If same ID + different payload arrives, return `409 Conflict` (per docs).+- TTL configurable per route (default 3600s).++## Wiring checklist+- [ ] Redis cache live in dev + prod+- [ ] Every paid endpoint declares the extension (optional by default; required where called out)+- [ ] Buyer wrappers accept optional `paymentId` and generate one when omitted+- [ ] 409 returned on ID collision with different payload++## Acceptance+- [ ] First call processes payment, returns 200 with body. Cache populated.+- [ ] Second call with same `paymentId` returns same body, NO on-chain settlement (verified by checking facilitator logs)+- [ ] Same `paymentId` + different body → 409+- [ ] Cache eviction after TTL — subsequent same-ID call re-processesdiff --git a/x402-buildout/prompts/16-sign-in-with-x.md b/x402-buildout/prompts/16-sign-in-with-x.mdnew file mode 100644index 000000000..601c1d9d9--- /dev/null+++ b/x402-buildout/prompts/16-sign-in-with-x.md@@ -0,0 +1,88 @@+# USE-16: Sign-In-With-X — Returning customer auth (CAIP-122)++## Goal+Implement SIWX on paid endpoints so a buyer who has previously paid can sign a wallet challenge to re-access the resource without paying again. Also enable auth-only routes (no payment, just wallet ownership).++## Why+- Most paid resources are stateful (subscriptions, premium articles, dataset access). Re-paying every visit is bad UX.+- The same machinery (CAIP-122 challenge + sign + verify) enables wallet-gated free routes too.++## Reference+- Docs: [/tmp/x402-docs/docs/extensions/sign-in-with-x.mdx](/tmp/x402-docs/docs/extensions/sign-in-with-x.mdx)+- Spec: [/tmp/x402-docs/specs/extensions/sign-in-with-x.md](/tmp/x402-docs/specs/extensions/sign-in-with-x.md)+- CAIP-122: https://chainagnostic.org/CAIPs/caip-122++## Dependencies+- USE-00, USE-02, USE-06+- USE-05 / Redis (for paid-history + nonce storage)++## Files to create+- `api/_lib/x402/siwx-storage.js` — implements `SIWxStorage`: `hasPaid()`, `recordPayment()`, `hasUsedNonce()`, `recordNonce()` backed by Redis+- `api/_lib/x402/siwx-server.js` — wraps `createSIWxResourceServerExtension`+- `api/_lib/x402/siwx-client.js` — wraps `createSIWxClientExtension`+- `api/x402/siwx-content.js` — example route demonstrating SIWX (re-access without repay)+- `api/x402/profile.js` — auth-only route (`accepts: []`) — wallet signature required, no payment++## Files to modify+- Every paid endpoint that benefits from re-access: declare `sign-in-with-x` extension+- `public/x402.js` — client browses signs SIWX challenge when offered+- `.env.example` — `SIWX_NONCE_TTL_SECONDS` (default 300)++## Implementation++### Server registration+```js+import { createSIWxResourceServerExtension } from "@x402/extensions/sign-in-with-x";+import { createPublicClient, http } from "viem";+import { base, baseSepolia } from "viem/chains";++const verifyChain = isProd ? base : baseSepolia;+const publicClient = createPublicClient({ chain: verifyChain, transport: http() });++resourceServer.registerExtension(+ createSIWxResourceServerExtension({+ storage: redisSiwxStorage,+ verifyOptions: { evmVerifier: publicClient.verifyMessage }, // EIP-1271 / EIP-6492 smart wallet support+ })+);+```++### Per-route declaration+For repayable + reaccessible routes:+```js+extensions: declareSIWxExtension({+ statement: "Sign in to re-access content you've previously paid for",+})+```++For auth-only routes:+```js+{ accepts: [], extensions: declareSIWxExtension({ network: NETWORK, statement: "Sign in to view your profile" }) }+```++### Smart wallet support+Enable EIP-1271 + EIP-6492 via `publicClient.verifyMessage`. This makes Coinbase Smart Wallet, Safe, Argent etc. work.++### Client+```js+import { createSIWxClientExtension } from "@x402/extensions/sign-in-with-x";+client.registerExtension(createSIWxClientExtension({ signers: [evmSigner, svmSigner] }));+```++### Nonce replay protection+Implement both `hasUsedNonce` and `recordNonce` in storage. If only one is implemented, the SDK throws — both or neither.++## Wiring checklist+- [ ] Storage persists paid addresses per resource+- [ ] Smart wallet verification enabled (EIP-1271/EIP-6492)+- [ ] Auth-only route works without `accepts`+- [ ] Multi-chain `supportedChains` declared on routes that accept both EVM and Solana+- [ ] Nonce replay protection on (both storage methods implemented)++## Acceptance+- [ ] Buyer pays for `/api/x402/siwx-content` — receives access; storage records payment+- [ ] Second access via SIWX header (no payment) — returns 200+- [ ] Different wallet without payment history — denied (server returns 402)+- [ ] `/api/x402/profile` accepts SIWX-only access (no payment ever required)+- [ ] Reusing the same nonce twice returns an error (replay rejected)+- [ ] Smart wallet (Coinbase Smart Wallet) successfully signs and verifiesdiff --git a/x402-buildout/prompts/17-offer-receipt.md b/x402-buildout/prompts/17-offer-receipt.mdnew file mode 100644index 000000000..bfb801fff--- /dev/null+++ b/x402-buildout/prompts/17-offer-receipt.md@@ -0,0 +1,80 @@+# USE-17: Offer & Receipt — Signed cryptographic proofs++## Goal+Sign every 402 offer (EIP-712) and every 200 receipt (after payment) so buyers receive cryptographic proof of the interaction. Support both EIP-712 (did:pkh) and JWS (did:web) formats. Host `did.json` for verifiers.++## Why+- Verifiable "I paid this server, this much, for this resource" is the foundation of reputation systems, attestation pipelines, and dispute resolution.+- Ecosystem partners build reputation scores on top of these artifacts.++## Reference+- Docs: [/tmp/x402-docs/docs/extensions/offer-receipt.mdx](/tmp/x402-docs/docs/extensions/offer-receipt.mdx)+- Spec: [/tmp/x402-docs/specs/extensions/extension-offer-and-receipt.md](/tmp/x402-docs/specs/extensions/extension-offer-and-receipt.md)++## Dependencies+- USE-00, USE-02++## Files to create+- `api/_lib/x402/offer-receipt-issuer.js` — constructs the EIP-712 or JWS issuer using a DEDICATED signing key+- `api/_lib/x402/offer-receipt-server.js` — registers `createOfferReceiptExtension` on the resource server+- `api/x402/did.js` — serves `/.well-known/did.json` for `did:web` JWS verification+- `api/_lib/x402/receipt-storage.js` — durable log of issued receipts (for our own records)++## Files to modify+- `vercel.json` — route `/.well-known/did.json` → `/api/x402/did`+- Every paid endpoint that benefits from receipts: declare `offer-receipt` extension+- `.env.example` — `OFFER_RECEIPT_SIGNING_PRIVATE_KEY` (DEDICATED key, NOT the payment-receiving key), `OFFER_RECEIPT_FORMAT` (`eip712` or `jws`), `SERVER_DOMAIN`++## Implementation++### Key separation (CRITICAL)+The signing key MUST NOT be the wallet receiving payments. Use a dedicated EOA. If signing format is JWS, use a managed KMS in production (Vercel doesn't have KMS — use Google KMS, AWS KMS, or HashiCorp Vault).++### EIP-712 issuer+```js+import { privateKeyToAccount } from "viem/accounts";+import { createEIP712OfferReceiptIssuer } from "@x402/extensions/offer-receipt";++const signingAccount = privateKeyToAccount(process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY);+const kid = `did:pkh:eip155:1:${signingAccount.address}#key-1`;+const issuer = createEIP712OfferReceiptIssuer(kid, signingAccount.signTypedData.bind(signingAccount));+```++### JWS issuer (alternative)+For Solana-native infra (Ed25519) or enterprise KMS:+```js+const issuer = createJWSOfferReceiptIssuer(kid, jwsSigner);+```++### Register+```js+resourceServer.registerExtension(createOfferReceiptExtension(issuer));+```++### Per-route+```js+extensions: { ...declareOfferReceiptExtension({ includeTxHash: false, offerValiditySeconds: 300 }) }+```++`includeTxHash: false` by default for privacy. Set `true` per route if needed (e.g., for receipts that feed reputation systems).++### `did.json`+For JWS, serve a real DID document containing the public key. Even for EIP-712 it's good practice to list the signing address as a `verificationMethod` for stronger binding.++### Receipt storage+Write every issued receipt to durable storage (Redis with long TTL or a database). Buyers can request a copy of their own receipts later via `/api/x402/my-receipts?address=0x...&since=<timestamp>` (signed by the buyer's wallet for auth).++## Wiring checklist+- [ ] Signing key is dedicated, NOT the payment-receiving key+- [ ] `did.json` served at `/.well-known/did.json` (rewrite in `vercel.json`)+- [ ] Every relevant paid endpoint declares the extension+- [ ] Buyer can extract + verify offers from 402 and receipts from 200 (verify functions imported from SDK)+- [ ] Receipt log durable++## Acceptance+- [ ] Buyer pays endpoint; receipt extracted from `PAYMENT-RESPONSE` header+- [ ] `verifyReceiptSignatureEIP712(receipt)` returns valid for signature+- [ ] `verifyReceiptMatchesOffer(receipt, offer, [buyerAddress])` passes+- [ ] `/.well-known/did.json` returns valid W3C DID document+- [ ] If using JWS: receipt verifies against the public key from `did.json`+- [ ] Receipt log queryable: `/api/x402/my-receipts?address=0x...&signature=...` returns buyer's receiptsdiff --git a/x402-buildout/prompts/18-gas-sponsoring-eip2612.md b/x402-buildout/prompts/18-gas-sponsoring-eip2612.mdnew file mode 100644index 000000000..a5dd95534--- /dev/null+++ b/x402-buildout/prompts/18-gas-sponsoring-eip2612.md@@ -0,0 +1,61 @@+# USE-18: EIP-2612 Gas Sponsoring++## Goal+Enable gasless Permit2 onboarding for tokens implementing EIP-2612 (USDC, DAI, many modern ERC-20s). Client signs an off-chain permit; facilitator submits it atomically with settlement.++## Why+- New buyers without ETH/POL/MATIC for gas can't complete a Permit2 approval. This blocks first-time use.+- EIP-2612 sponsoring removes the friction entirely for compatible tokens.++## Reference+- Docs: [/tmp/x402-docs/docs/extensions/eip2612-gas-sponsoring.mdx](/tmp/x402-docs/docs/extensions/eip2612-gas-sponsoring.mdx)+- Spec: [/tmp/x402-docs/specs/extensions/eip2612_gas_sponsoring.md](/tmp/x402-docs/specs/extensions/eip2612_gas_sponsoring.md)++## Dependencies+- USE-00, USE-02++## Files to modify+- Every Permit2-using paid endpoint (not EIP-3009 default): add `eip2612GasSponsoring` to its extensions+- `api/_lib/x402/sdk.js` — ensure facilitator client supports the extension (it does by default in `@x402/extensions`)+- `.env.example` — no new vars (handled by facilitator)++## Files to create+- `api/x402/permit2-paid-demo.js` — demo endpoint that uses Permit2 + EIP-2612 sponsoring (so we have something to test against)++## Implementation++### Per-route declaration+```js+import { declareEip2612GasSponsoringExtension } from "@x402/extensions/eip2612-gas-sponsoring";++const route = {+ accepts: [{+ scheme: "exact",+ network: "eip155:84532",+ price: "$0.01",+ payTo: getEvmAddress(),+ extra: { assetTransferMethod: "permit2" } // force Permit2+ }],+ extensions: { ...declareEip2612GasSponsoringExtension() },+};+```++### Client side+`ExactEvmScheme` handles this automatically when the server advertises the extension AND the token supports EIP-2612. No buyer-side wiring beyond `USE-06`.++### Token selection+Use a token that actually implements EIP-2612 on Base Sepolia. USDC on Base does. Verify by reading `name()` and `version()` from the token contract — both must be EIP-712 domain params.++### Verification+Sponsored settlement calls `x402ExactPermit2Proxy.settleWithPermit`. The Proxy is at the canonical `0x402085c248EeA27D92E8b30b2C58ed07f9E20001` across all EVM chains.++## Wiring checklist+- [ ] Demo endpoint uses Permit2 + EIP-2612 sponsoring extension+- [ ] First-time buyer (no Permit2 allowance) completes the flow without holding gas+- [ ] Facilitator submits `settleWithPermit` atomically — verified by reading the tx and confirming both permit + transfer landed++## Acceptance+- [ ] Fresh wallet on Base Sepolia with USDC but ZERO ETH successfully pays through the endpoint+- [ ] Transaction trace shows EIP-2612 permit + Permit2 transfer in a single tx+- [ ] No "insufficient gas" error+- [ ] Subsequent calls reuse Permit2 allowance — no permit signature neededdiff --git a/x402-buildout/prompts/19-gas-sponsoring-erc20-approval.md b/x402-buildout/prompts/19-gas-sponsoring-erc20-approval.mdnew file mode 100644index 000000000..c457fd297--- /dev/null+++ b/x402-buildout/prompts/19-gas-sponsoring-erc20-approval.md@@ -0,0 +1,57 @@+# USE-19: ERC-20 Approval Gas Sponsoring (Universal)++## Goal+Enable gasless Permit2 onboarding for ANY ERC-20, including tokens that don't implement EIP-2612. Facilitator broadcasts the client's pre-signed `approve(Permit2, MaxUint256)` transaction in an atomic batch with settlement.++## Why+- USE-18 only works for EIP-2612 tokens. For everything else (legacy ERC-20s, exotic tokens), this is the universal fallback.+- Together with USE-18, it covers 100% of ERC-20s for gasless first-time onboarding.++## Reference+- Docs: [/tmp/x402-docs/docs/extensions/erc20-approval-gas-sponsoring.mdx](/tmp/x402-docs/docs/extensions/erc20-approval-gas-sponsoring.mdx)+- Spec: [/tmp/x402-docs/specs/extensions/erc20_gas_sponsoring.md](/tmp/x402-docs/specs/extensions/erc20_gas_sponsoring.md)++## Dependencies+- USE-00, USE-02+- USE-18 (typically advertised alongside)++## Files to modify+- Every Permit2-using paid endpoint that wants universal support: add `erc20ApprovalGasSponsoring` alongside `eip2612GasSponsoring`+- `.env.example` — no new vars++## Implementation++### Per-route declaration+```js+import { declareErc20ApprovalGasSponsoringExtension } from "@x402/extensions/erc20-approval-gas-sponsoring";+import { declareEip2612GasSponsoringExtension } from "@x402/extensions/eip2612-gas-sponsoring";++extensions: {+ ...declareEip2612GasSponsoringExtension(),+ ...declareErc20ApprovalGasSponsoringExtension(),+}+```++The client automatically picks: EIP-2612 if the token supports it, ERC-20 approval otherwise.++### Client side+`ExactEvmScheme` handles signing the raw approval transaction without broadcasting. Requires `signTransaction` and `getTransactionCount` capabilities on the signer — verify these are present in our `toClientEvmSigner` setup.++### Atomic batch+The facilitator executes:+1. (Optional) Transfer gas to client wallet if needed+2. Broadcast client's signed approval+3. Call `x402ExactPermit2Proxy.settle`++All three in a single atomic batch — no front-running window.++## Wiring checklist+- [ ] Both extensions declared on routes+- [ ] Test against a token that does NOT implement EIP-2612 (find one on Base Sepolia)+- [ ] Verify on-chain trace shows: gas transfer (if needed) + approve + settle in one batch++## Acceptance+- [ ] Fresh wallet with non-EIP-2612 ERC-20 + zero ETH successfully pays+- [ ] On-chain trace shows atomic batch: client's `approve` transaction immediately followed by `settle`+- [ ] No front-running possible (verified by tx ordering)+- [ ] EIP-2612 path still works for USDC (USE-18 not broken)diff --git a/x402-buildout/prompts/20-builder-code.md b/x402-buildout/prompts/20-builder-code.mdnew file mode 100644index 000000000..71ca88b30--- /dev/null+++ b/x402-buildout/prompts/20-builder-code.md@@ -0,0 +1,64 @@+# USE-20: Builder-Code — ERC-8021 On-chain attribution++## Goal+Append ERC-8021 Schema 2 CBOR-encoded attribution data to settlement calldata, so every x402 settlement transaction permanently records: app code, service codes, wallet code. Enables on-chain analytics, builder royalty programs, and provenance tracking.++## Why+- Coinbase and other ecosystem partners are paying out builder rewards based on attributed volume.+- Lets us prove our app's economic activity on-chain without external indexing.++## Reference+- Spec: [/tmp/x402-docs/specs/extensions/builder_code.md](/tmp/x402-docs/specs/extensions/builder_code.md)+- ERC-8021: https://eips.ethereum.org/EIPS/eip-8021++## Dependencies+- USE-00, USE-02 (EVM only — Solana not applicable)++## Files to create+- `api/_lib/x402/builder-code.js` — declares the app code, helpers to add service codes++## Files to modify+- Every EVM paid endpoint: declare `builder-code` extension+- Buyer client: echo server's `a` (app code) in `PAYMENT-SIGNATURE` (client side has limited responsibility — server populates `w`)+- `.env.example` — `X402_BUILDER_CODE_APP` (matches `^[a-z0-9_]{1,32}$`)++## Implementation++### Per-route+```js+import { declareBuilderCodeExtension, BUILDER_CODE } from "@x402/extensions/builder-code";++extensions: { [BUILDER_CODE]: declareBuilderCodeExtension({ a: process.env.X402_BUILDER_CODE_APP }) }+```++### Service codes (per-call)+For routes that route to multiple internal services, append service codes:+```js+const services = ["pose-studio", "openai-proxy"]; // per request+const ext = { [BUILDER_CODE]: { a: appCode, s: services } };+```++### Client behavior+Buyer SDK echoes `a` automatically. Tampering = rejection. The wallet code (`w`) is set by the wallet client (Coinbase Wallet etc.) — outside our control unless we set it for our own demo client.++### Wallet code+For our own buyer client, set `w: "3d-agent"` so we attribute our own usage too.++### On-chain verification+After settlement, parse the tx calldata and confirm:+- Last bytes are the schema marker (per ERC-8021)+- Decoding the CBOR suffix yields `{ a, s?, w? }`+- Values match what we declared++## Wiring checklist+- [ ] App code chosen, documented in `.env.example`+- [ ] Every EVM paid endpoint declares the extension+- [ ] Service codes added where multi-service+- [ ] Buyer client sets wallet code `w`+- [ ] Settlement calldata contains ERC-8021 CBOR suffix++## Acceptance+- [ ] Pay an endpoint; pull the on-chain tx by hash+- [ ] Tx calldata last bytes = ERC-8021 schema marker+- [ ] CBOR suffix decodes to `{ a: "3d_agent", s: [...], w: "3d-agent" }`+- [ ] Client that tampers with `a` (sends wrong value) is rejected with a clear errordiff --git a/x402-buildout/prompts/21-auth-hints.md b/x402-buildout/prompts/21-auth-hints.mdnew file mode 100644index 000000000..1d3165ec7--- /dev/null+++ b/x402-buildout/prompts/21-auth-hints.md@@ -0,0 +1,75 @@+# USE-21: Auth-Hints — Signal OAuth2 / SIWX before payment++## Goal+On paid endpoints where certain `accepts[]` entries require authentication first, declare the `auth-hints` extension so clients know which auth method to use before constructing payment.++## Why+- Some endpoints offer two paths: (1) pay every time, (2) authenticate (OAuth2 or SIWX) and pay reduced rate / get session.+- Without auth-hints, clients can't programmatically discover this option.++## Reference+- Spec: [/tmp/x402-docs/specs/extensions/extension-auth-hints.md](/tmp/x402-docs/specs/extensions/extension-auth-hints.md)++## Dependencies+- USE-00, USE-02+- USE-16 (SIWX) for the SIWX path+- Existing OAuth at `api/auth/persona/*` and `api/wk?name=oauth-protected-resource` for OAuth path++## Files to modify+- Paid endpoints that benefit (e.g., the agent-reputation API): declare `auth-hints` with both OAuth2 and SIWX requirements+- Buyer client: surface auth options to caller, let them choose++## Files to create+- `api/_lib/x402/auth-hints.js` — `declareAuthHintsExtension({ oauth2, siwx })` helper++## Implementation++### Per-route+```js+extensions: {+ "auth-hints": {+ info: {+ authRequirements: [+ {+ acceptIndexes: [0], // first accepts entry+ methods: [+ {+ type: "oauth2",+ auth: { authorizationServers: ["https://three.ws/.well-known/oauth-authorization-server"], scopesSupported: ["read:agent-reputation"] }+ }+ ]+ },+ {+ acceptIndexes: [1],+ methods: [+ { type: "sign-in-with-x", auth: { /* SIWX challenge params */ } }+ ]+ }+ ]+ }+ }+}+```++### Existing OAuth integration+This repo already has OAuth at `/.well-known/oauth-authorization-server` (via `api/wk.js`). Reuse that.++### Auth credentials in transit+Auth credentials (Bearer token, SIWX header) travel as standard HTTP headers — NOT inside the x402 payload. The auth-hints extension just signals which method to use.++### Client surface+Update buyer wrappers to:+1. Detect `auth-hints` in 402+2. Surface choices to caller (e.g., `client.onPaymentRequired` returns a callback letting the caller pick auth method)+3. Attach the right header before retry++## Wiring checklist+- [ ] Existing OAuth server URLs verified (already at `.well-known/oauth-authorization-server`)+- [ ] At least one endpoint demonstrates auth-hints with both OAuth and SIWX options+- [ ] Buyer client respects auth-hints: attempts auth before paying when method matches available credentials++## Acceptance+- [ ] Buyer with valid OAuth2 Bearer token hits the auth-hints route and accesses without paying+- [ ] Buyer without OAuth but with wallet signs SIWX and accesses without paying+- [ ] Buyer without either pays normally+- [ ] auth-hints schema validates per spec (test with the SDK's validator if available)diff --git a/x402-buildout/prompts/22-spending-limits.md b/x402-buildout/prompts/22-spending-limits.mdnew file mode 100644index 000000000..37e9014b4--- /dev/null+++ b/x402-buildout/prompts/22-spending-limits.md@@ -0,0 +1,78 @@+# USE-22: Spending Limits — Client lifecycle hook++## Goal+Enforce per-call and per-session spending caps on every buyer client via `onBeforePaymentCreation`. Critical for autonomous agents (USE-29..40) to prevent runaway spending.++## Why+- Without caps, a bug in agent logic could drain the wallet.+- Operators want a hard ceiling per call AND a daily / session budget.++## Reference+- Lifecycle hooks: [/tmp/x402-docs/docs/advanced-concepts/lifecycle-hooks.mdx](/tmp/x402-docs/docs/advanced-concepts/lifecycle-hooks.mdx)++## Dependencies+- USE-00, USE-06, USE-07++## Files to create+- `api/_lib/x402/spending-cap.js` — `installSpendingCap(client, { maxPerCall, maxPerHour, maxPerDay })`+- `api/_lib/x402/spending-ledger.js` — durable ledger of every payment attempt (Redis) for windowed sums++## Files to modify+- `api/_lib/x402/buyer-fetch.js` — accept `{ caps: { ... } }` option that installs the hook+- `api/_lib/x402/buyer-axios.js` — same+- `public/x402-buyer.js` — same, with browser-local storage for ledger+- `.env.example` — `X402_MAX_PER_CALL_ATOMIC`, `X402_MAX_PER_HOUR_ATOMIC`, `X402_MAX_PER_DAY_ATOMIC`++## Implementation++### Hook+```js+client.onBeforePaymentCreation(async ({ selectedRequirements }) => {+ const amount = BigInt(selectedRequirements.amount);++ if (amount > BigInt(caps.maxPerCall)) {+ return { abort: true, reason: `Payment ${amount} exceeds per-call cap ${caps.maxPerCall}` };+ }++ const recent = await spendingLedger.windowedSum(buyerAddress, "1h");+ if (recent + amount > BigInt(caps.maxPerHour)) {+ return { abort: true, reason: `Hourly cap exceeded` };+ }++ const daily = await spendingLedger.windowedSum(buyerAddress, "24h");+ if (daily + amount > BigInt(caps.maxPerDay)) {+ return { abort: true, reason: `Daily cap exceeded` };+ }+});++client.onAfterPaymentCreation(async ({ selectedRequirements }) => {+ await spendingLedger.record({+ address: buyerAddress,+ amount: selectedRequirements.amount,+ network: selectedRequirements.network,+ timestamp: Date.now(),+ });+});+```++### Multi-network caps+Convert amounts to USD for cross-network aggregation. Pull a price feed (we already have Pump.fun feed infrastructure; use a stablecoin → USD oracle for non-USDC tokens).++### Asynchronous reconciliation+Recording happens after successful payment, but the cap check happens before. For strict caps, this means brief races between concurrent calls. If strictness matters, use Redis `INCRBY` with rollback on payment failure.++### Browser caps+Browser-side ledger uses `localStorage` keyed by wallet address. Persists across reloads. Resets at midnight UTC for daily caps.++## Wiring checklist+- [ ] Caps installable on every buyer client (server + browser)+- [ ] Ledger durable in Redis (server) and localStorage (browser)+- [ ] Hourly + daily sliding windows correctly bounded+- [ ] Multi-network amounts normalized to USD for aggregation++## Acceptance+- [ ] Setting `maxPerCall: "1000"` (USDC = $0.001) blocks any call requiring more+- [ ] After paying $0.10 in an hour, an 11th cent purchase is blocked if `maxPerHour: "100000"`+- [ ] Daily reset works at the configured boundary+- [ ] Aborted payments don't record in the ledger+- [ ] Browser and server caps both workdiff --git a/x402-buildout/prompts/23-api-key-bypass.md b/x402-buildout/prompts/23-api-key-bypass.mdnew file mode 100644index 000000000..a8023ea79--- /dev/null+++ b/x402-buildout/prompts/23-api-key-bypass.md@@ -0,0 +1,77 @@+# USE-23: API-Key Bypass — Server lifecycle hook++## Goal+Server-side `onProtectedRequest` hook that allows callers with a valid API key (or other auth) to skip payment entirely. Useful for: internal services, free-tier subscribers, partner integrations, gradual rollout.++## Why+- Not every consumer should pay. Internal services calling our own paid endpoints shouldn't pay themselves.+- Subscribers / partners get a free pass.+- Bot detection or rate-limiting works at the same hook.++## Reference+- Lifecycle hooks: [/tmp/x402-docs/docs/advanced-concepts/lifecycle-hooks.mdx](/tmp/x402-docs/docs/advanced-concepts/lifecycle-hooks.mdx)++## Dependencies+- USE-00, USE-02++## Files to create+- `api/_lib/x402/access-control.js` — `installAccessControl(httpServer, { resolveCaller })`+- `api/_lib/x402/api-keys.js` — Redis-backed API key storage with rate limits++## Files to modify+- Every paid endpoint that benefits: wire the access control hook+- `.env.example` — `INTERNAL_API_KEY` (for internal service-to-service calls)++## Implementation++### Hook+```js+httpServer.onProtectedRequest(async (context, routeConfig) => {+ const apiKey = context.adapter.getHeader("X-API-Key");+ if (apiKey === process.env.INTERNAL_API_KEY) {+ return { grantAccess: true, reason: "internal" };+ }+ if (apiKey) {+ const subscription = await apiKeys.get(apiKey);+ if (!subscription) return { abort: true, reason: "Invalid API key" };+ if (subscription.expiresAt < Date.now()) return { abort: true, reason: "Expired" };+ if (await isRateLimited(subscription.id, routeConfig.path)) return { abort: true, reason: "Rate limit exceeded" };+ return { grantAccess: true, reason: `subscription:${subscription.id}` };+ }++ const oauthToken = context.adapter.getHeader("Authorization");+ if (oauthToken?.startsWith("Bearer ")) {+ const claims = await verifyOAuth(oauthToken.slice(7));+ if (claims?.scopes?.includes(routeConfig.requiredScope)) {+ return { grantAccess: true, reason: `oauth:${claims.sub}` };+ }+ }++ // No bypass — payment flow continues+});+```++### Rate limiting+Sliding-window rate limits per API key per route. Use Redis sorted sets with timestamps.++### Audit trail+Every bypass logged with reason, caller identifier, route. USE-24 picks these up.++### Subscription management+- `POST /api/x402/admin/subscriptions` (admin-only) creates an API key+- `DELETE /api/x402/admin/subscriptions/:id` revokes+- `GET /api/x402/admin/subscriptions/:id/usage` shows usage stats++## Wiring checklist+- [ ] `INTERNAL_API_KEY` set in dev + prod env+- [ ] Internal Vercel functions that hit our own paid endpoints supply this key (no double-payment for our own infra)+- [ ] Subscription API keys created with TTL + rate limits+- [ ] OAuth Bearer tokens accepted where USE-21 declared OAuth in auth-hints+- [ ] Bypass reason logged++## Acceptance+- [ ] Request with `X-API-Key: $INTERNAL_API_KEY` returns 200 with no payment header+- [ ] Request with subscription key + within rate limit returns 200, key usage counter increments+- [ ] Request with subscription key over rate limit returns 403 with clear message+- [ ] Request with invalid OAuth scope falls through to payment flow+- [ ] Request with neither key nor OAuth proceeds through normal 402 flowdiff --git a/x402-buildout/prompts/24-audit-logging.md b/x402-buildout/prompts/24-audit-logging.mdnew file mode 100644index 000000000..b9411bd5d--- /dev/null+++ b/x402-buildout/prompts/24-audit-logging.md@@ -0,0 +1,92 @@+# USE-24: Audit Logging — Every payment recorded++## Goal+Durable, queryable audit log of every payment event (verified, settled, failed, bypassed, refunded, expired) across all paid endpoints, transports, and schemes. Both server-side and client-side.++## Why+- Compliance, accounting, dispute resolution.+- Without this, claims like "I paid you" or "I never charged that" can't be verified.++## Reference+- Lifecycle hooks: [/tmp/x402-docs/docs/advanced-concepts/lifecycle-hooks.mdx](/tmp/x402-docs/docs/advanced-concepts/lifecycle-hooks.mdx)++## Dependencies+- USE-00, USE-01, USE-02++## Files to create+- `api/_lib/x402/audit-log.js` — wraps Postgres / Vercel Postgres for durable storage; falls back to append-only files in dev+- `api/_lib/x402/audit-events.js` — typed event constructors: `verified`, `settled`, `failed`, `bypassed`, `refunded`, `expired`+- `api/x402/audit/query.js` — admin-only query endpoint (auth required)+- `api/x402/audit/my-history.js` — buyer-facing endpoint (returns their own payments, SIWX-gated)++## Files to modify+- `api/_lib/x402/sdk.js` — install audit hooks on every resource server, facilitator client, and buyer client+- `api/_lib/x402/facilitator.js` — pipe `onCall` to audit+- `.env.example` — `POSTGRES_URL` (or `DATABASE_URL`)++## Implementation++### Event shape+Every event has: `id`, `timestamp`, `type`, `actor` (server/client/facilitator), `route`, `scheme`, `network`, `payer`, `payTo`, `amount`, `transaction?`, `errorReason?`, `extensions?`, `correlation_id` (request id for grouping).++### Hooks+```js+// Server+resourceServer.onAfterVerify(async (ctx) => audit.record(events.verified({ ctx })));+resourceServer.onAfterSettle(async (ctx) => audit.record(events.settled({ ctx })));+resourceServer.onSettleFailure(async (ctx) => audit.record(events.failed({ ctx })));+httpServer.onProtectedRequest(async (ctx) => /* on bypass */ audit.record(events.bypassed({ ctx })));++// Facilitator wrapper+facilitator.onCall = (info) => audit.record(events.facilitatorCall(info));++// Client+client.onAfterPaymentCreation(async (ctx) => audit.record(events.paymentSubmitted({ ctx })));+```++### Storage+Use Vercel Postgres in production. In dev, an SQLite file is fine. Schema:+```sql+CREATE TABLE x402_audit (+ id UUID PRIMARY KEY,+ timestamp TIMESTAMPTZ NOT NULL,+ type TEXT NOT NULL,+ actor TEXT NOT NULL,+ route TEXT,+ scheme TEXT,+ network TEXT,+ payer TEXT,+ pay_to TEXT,+ amount TEXT,+ transaction TEXT,+ error_reason TEXT,+ extensions JSONB,+ correlation_id TEXT+);+CREATE INDEX ON x402_audit (payer, timestamp DESC);+CREATE INDEX ON x402_audit (transaction);+CREATE INDEX ON x402_audit (correlation_id);+```++### Buyer history endpoint+`/api/x402/audit/my-history` — SIWX-authenticated (USE-16). Returns the wallet's payments across all our endpoints.++### Admin query+`/api/x402/audit/query?from=...&to=...&type=...` — protected by `INTERNAL_API_KEY` (USE-23). Supports CSV export.++### Privacy+PII shouldn't enter audit logs. Only on-chain identifiers (addresses, tx hashes), amounts, and timestamps. No IP addresses, no user agents, no request bodies.++## Wiring checklist+- [ ] Hooks installed everywhere (server, client, facilitator wrapper, bypass path)+- [ ] Postgres provisioned in dev + prod+- [ ] Query endpoint protected+- [ ] Buyer history endpoint SIWX-gated+- [ ] No PII in event records++## Acceptance+- [ ] After running any paid flow, querying the audit log returns matching events+- [ ] `correlation_id` lets us trace a single request from `verify` → `settle` → `audit` → client `onAfterPaymentCreation`+- [ ] Buyer hitting `/api/x402/audit/my-history` with valid SIWX gets only their own records+- [ ] Admin query with `?type=failed&from=...` returns failed payments only+- [ ] Audit log survives Vercel function redeploys (durable, not in-memory)diff --git a/x402-buildout/prompts/25-idempotency-cache.md b/x402-buildout/prompts/25-idempotency-cache.mdnew file mode 100644index 000000000..becc92438--- /dev/null+++ b/x402-buildout/prompts/25-idempotency-cache.md@@ -0,0 +1,77 @@+# USE-25: Idempotency Cache — Combined client + server++## Goal+End-to-end idempotency: client generates stable `paymentId` per logical operation (with persistence across retries and restarts), server caches responses keyed by that ID. Survives network failures, process crashes, multi-instance deploys.++## Why+- USE-15 wires the protocol. USE-25 makes it production-correct: persistent IDs, persistent cache, conflict detection.++## Reference+- Same as USE-15++## Dependencies+- USE-15 (extension wired)+- USE-05 (Redis available)++## Files to create+- `api/_lib/x402/idempotency-policy.js` — per-route policy: optional / required / strict (rejects on missing)+- `api/_lib/x402/payment-id-store.js` — client-side ID persistence (browser localStorage, Node JSON file, Redis for serverless)++## Files to modify+- `api/_lib/x402/payment-identifier-server.js` (from USE-15) — add payload hash comparison for `409 Conflict`+- `api/_lib/x402/payment-identifier-client.js` (from USE-15) — persist ID before sending payment payload++## Implementation++### Client-side persistence+```js+const idStore = createPaymentIdStore({ backend: "redis" | "file" | "localstorage" });++async function payWithIdempotency(url, options = {}) {+ const logicalKey = options.logicalKey ?? `${url}#${hash(options)}`;+ let id = await idStore.get(logicalKey);+ if (!id) {+ id = generatePaymentId();+ await idStore.set(logicalKey, id);+ }+ return fetchWithPayment(url, { ...options, paymentId: id });+}+```++### Conflict detection+Server hashes the incoming payload (excluding signature/extensions) and stores hash alongside the cached response. On retry:+- Same id + same hash → return cached+- Same id + different hash → 409 Conflict++### Multi-instance safety+Use Redis SETNX for first-write-wins on cache. Concurrent retries don't double-charge:+```js+const inserted = await redis.setNX(`cache:${id}:lock`, "1", "EX", 10);+if (!inserted) {+ // Another instance is processing this id; wait for cache+ await waitForCache(id, 10_000);+ return cached;+}+// proceed with payment, write cache, release lock+```++### TTL policy+- Default: 1 hour+- Strict routes (`USE-30` oracle, `USE-32` fact-checker): 24 hours+- Configurable per route++### Cleanup+Cache entries auto-expire via Redis TTL. No manual cleanup needed.++## Wiring checklist+- [ ] Client ID persistence works across browser reloads+- [ ] Client ID persistence works across Node process restarts+- [ ] Multi-instance Vercel deployment: same payment ID from concurrent instances → single payment, both get cached response+- [ ] Conflict detection: same ID + different payload → 409+- [ ] Per-route TTL configurable++## Acceptance+- [ ] Client retries 5x with same logical key → 1 payment, 5 identical responses+- [ ] Force-killing the client mid-flight and retrying → no double-payment+- [ ] Two Vercel instances handling concurrent requests with same payment ID → 1 settlement, both serve cached response+- [ ] 409 returned for payload tampering with reused IDdiff --git a/x402-buildout/prompts/26-self-hosted-facilitator.md b/x402-buildout/prompts/26-self-hosted-facilitator.mdnew file mode 100644index 000000000..9990509c2--- /dev/null+++ b/x402-buildout/prompts/26-self-hosted-facilitator.md@@ -0,0 +1,87 @@+# USE-26: Self-Hosted Facilitator++## Goal+Run our own facilitator: `/verify`, `/settle`, `/supported`, and `/discovery/resources` endpoints. Eliminates dependency on third-party facilitators for our own paid traffic and enables custom KYT/compliance logic.++## Why+- We control the verification logic.+- We pay our own gas — no facilitator fees.+- We can add compliance hooks (sanctions screening, KYT, jurisdictional rules) without changing the standard.++## Reference+- Facilitator concept: [/tmp/x402-docs/docs/core-concepts/facilitator.md](/tmp/x402-docs/docs/core-concepts/facilitator.md)+- Facilitator interface: [/tmp/x402-docs/specs/x402-specification-v2.md §7](/tmp/x402-docs/specs/x402-specification-v2.md)+- Facilitator examples: [examples/typescript/facilitator/](https://github.com/x402-foundation/x402/tree/main/examples/typescript/facilitator)++## Dependencies+- USE-00, USE-01++## Files to create+- `api/facilitator/verify.js` — POST endpoint+- `api/facilitator/settle.js` — POST endpoint+- `api/facilitator/supported.js` — GET endpoint+- `api/facilitator/discovery/resources.js` — GET endpoint+- `api/facilitator/discovery/search.js` — GET endpoint+- `api/_lib/x402/facilitator-server/index.js` — sets up `x402Facilitator` with EVM + SVM schemes+- `api/_lib/x402/facilitator-server/compliance.js` — KYT and sanctions hooks+- `data/facilitator/bazaar-index/` — durable Bazaar index (Postgres or Redis-backed)++## Files to modify+- `vercel.json` — routes for facilitator endpoints+- `.env.example` — `FACILITATOR_EVM_GAS_WALLET_PRIVATE_KEY` (the wallet that pays settlement gas), `FACILITATOR_SVM_FEE_PAYER_PRIVATE_KEY`, `FACILITATOR_RPC_URL_BASE`, `FACILITATOR_RPC_URL_SOLANA`, `KYT_API_KEY` (Chainalysis / TRM / similar)++## Implementation++### Verifier + Settler+```js+import { x402Facilitator } from "@x402/core";+import { ExactEvmScheme } from "@x402/evm/exact/facilitator";+import { ExactSvmScheme } from "@x402/svm/exact/facilitator";+import { UptoEvmScheme } from "@x402/evm/upto/facilitator";+import { BatchSettlementEvmScheme } from "@x402/evm/batch-settlement/facilitator";++const facilitator = new x402Facilitator({+ signers: {+ "eip155:*": evmGasWalletSigner,+ "solana:*": svmFeePayerSigner,+ },+ rpcUrls: { ... },+});++facilitator.register("eip155:*", new ExactEvmScheme());+facilitator.register("eip155:*", new UptoEvmScheme());+facilitator.register("eip155:*", new BatchSettlementEvmScheme());+facilitator.register("solana:*", new ExactSvmScheme());+```++### Compliance hook+`onBeforeVerify`: check `payer` address against sanctions API (Chainalysis Address Screening). Reject with clear reason. Allow caching so we don't hit the KYT API every call for a known-good address.++### Bazaar indexing+`onAfterVerify`: extract `extensions.bazaar.info` (using SDK's `extractDiscoveryInfo` helper) and write to our Bazaar index. Expose via `/discovery/resources`.++### Gas wallet ops+- The facilitator's EVM wallet pays gas. Monitor balance.+- Endpoint `/api/facilitator/health` returns gas wallet balance, recent failures, current throughput.+- Cron tops up gas wallet from a treasury if balance falls below threshold (out of scope here, but document the integration point).++### Solana fee payer+Similar — a dedicated Solana account funds transaction fees. Surface its public key in `extra.feePayer` of Solana PaymentRequirements.++### CORS+Facilitator endpoints must allow CORS from arbitrary origins so buyer clients (browser-based) can use them.++## Wiring checklist+- [ ] All four endpoints (`/verify`, `/settle`, `/supported`, `/discovery/resources`) live and tested+- [ ] Gas wallets funded+- [ ] KYT integration screens addresses on first verify, caches result+- [ ] Bazaar index persists across function invocations (Postgres or Redis)+- [ ] CORS configured for cross-origin buyer access++## Acceptance+- [ ] `curl http://localhost:3000/api/facilitator/supported` returns valid SupportedResponse+- [ ] Resource server pointing at our facilitator URL successfully verifies + settles an `exact` EVM payment+- [ ] Same for `exact` SVM+- [ ] Sanctioned address (test address from Chainalysis list) blocked at verify+- [ ] `/api/facilitator/discovery/resources` returns endpoints we've seen `bazaar` info for+- [ ] Gas wallet balance visible via `/api/facilitator/health`diff --git a/x402-buildout/prompts/27-paywall-ui.md b/x402-buildout/prompts/27-paywall-ui.mdnew file mode 100644index 000000000..90c83367b--- /dev/null+++ b/x402-buildout/prompts/27-paywall-ui.md@@ -0,0 +1,70 @@+# USE-27: Paywall UI — Browser-native payment flow++## Goal+A polished browser paywall for human visitors hitting paid endpoints directly. Shows price, network options, asset, "Pay" button, and live settlement status. Falls back gracefully when wallet not connected.++## Why+- Not every buyer is an agent. Some are humans on a phone reading an article.+- The `@x402/paywall` package provides the UI, but we should wire it into our routes and brand it.++## Reference+- `@x402/paywall`: [typescript/packages/http/paywall](https://github.com/x402-foundation/x402/tree/main/typescript/packages/http/paywall)+- Quickstart for sellers (paywall 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-02, USE-03++## Files to create+- `public/paywall.html` — paywall page+- `public/paywall.js` — client-side logic, integrates `@x402/paywall`+- `public/paywall.css` — branded styles+- `api/_lib/x402/paywall-handler.js` — detects `Accept: text/html` on 402 and serves the paywall page instead of bare JSON++## Files to modify+- Every paid endpoint that can be accessed directly by a human browser: install the paywall handler middleware+- `vercel.json` — route `/paywall` → `/paywall.html`+- `public/x402.js` — share buyer logic with paywall++## Implementation++### Content negotiation+```js+// Inside our payment middleware (USE-02)+if (req.headers.accept?.includes("text/html") && !req.headers["payment-signature"]) {+ return servePaywall(req, res, paymentRequirements);+}+```++The paywall HTML page receives `?req=<base64 PaymentRequirements>` and renders accordingly.++### UI features+- Show all `accepts[]` options with logos (USDC, USDT0, etc.)+- Per-option: network name, price in USD and in atomic units, asset address, payTo address, an icon+- "Connect Wallet" button (Coinbase Wallet, MetaMask, Phantom)+- "Need test funds? Get USDC on Base Sepolia" link to a faucet (read from the paywall's bundled faucet URL map)+- After settlement: show transaction hash, link to block explorer++### Wallet connect+- EVM: Coinbase Wallet SDK or wagmi+- Solana: `@solana/wallet-adapter` with Phantom + Solflare++### Custom assets+For chains where `decimals != 6`, the bundled `decimals.ts` from `@x402/paywall` handles formatting. Verify our default-asset table (USE-00) matches.++### Branding+Theme the paywall with the same colors and typography as the main 3D-Agent site. Logo top-left, "Powered by x402" footer link.++## Wiring checklist+- [ ] Content negotiation correctly differentiates HTML browsers from JSON clients+- [ ] Wallet connect works for the top 3 EVM wallets and top 2 Solana wallets+- [ ] Faucet links visible on testnet, hidden on mainnet+- [ ] Block explorer links correct per network (Basescan, Solscan, etc.)+- [ ] Settlement status updates live (no manual refresh)++## Acceptance+- [ ] Open `/api/x402/exact-evm-demo` in a browser (no payment header) → paywall page renders+- [ ] Connect Coinbase Wallet, pay, see resource+- [ ] Same flow with Phantom on the Solana endpoint+- [ ] On testnet, faucet link works+- [ ] On mainnet, no faucet shown+- [ ] Settlement tx link opens block explorer in new tabdiff --git a/x402-buildout/prompts/28-e2e-tests.md b/x402-buildout/prompts/28-e2e-tests.mdnew file mode 100644index 000000000..5490db352--- /dev/null+++ b/x402-buildout/prompts/28-e2e-tests.md@@ -0,0 +1,101 @@+# USE-28: End-to-End Tests++## Goal+Automated E2E tests covering every scheme × every transport × every extension combination against REAL testnet (Base Sepolia, Solana Devnet). No mocks per [CLAUDE.md](../../CLAUDE.md).++## Why+- We've built ~25 prior use cases. Without E2E coverage, breakage is silent and discovery is in production.+- Real testnet tests catch protocol-level issues that mocks hide (signature recovery, nonce reuse, gas estimation).++## Reference+- E2E reference: [e2e/](https://github.com/x402-foundation/x402/tree/main/e2e)++## Dependencies+- USE-00 through USE-27++## Files to create+- `tests/e2e/setup.js` — boots local Vercel dev server, loads test wallets with testnet funds+- `tests/e2e/fixtures/wallets.json` — addresses (NOT private keys) of test wallets; keys in env+- `tests/e2e/seller-exact-evm.test.js`+- `tests/e2e/seller-exact-svm.test.js`+- `tests/e2e/seller-upto-evm.test.js`+- `tests/e2e/seller-batch-evm.test.js`+- `tests/e2e/buyer-fetch-multinetwork.test.js`+- `tests/e2e/buyer-axios.test.js`+- `tests/e2e/buyer-batch.test.js`+- `tests/e2e/extensions/bazaar.test.js`+- `tests/e2e/extensions/payment-identifier.test.js`+- `tests/e2e/extensions/sign-in-with-x.test.js`+- `tests/e2e/extensions/offer-receipt.test.js`+- `tests/e2e/extensions/gas-sponsoring.test.js`+- `tests/e2e/hooks/spending-cap.test.js`+- `tests/e2e/hooks/api-key-bypass.test.js`+- `tests/e2e/hooks/audit-log.test.js`+- `tests/e2e/hooks/idempotency.test.js`+- `tests/e2e/facilitator/self-hosted.test.js`+- `tests/e2e/transports/mcp.test.js`+- `tests/e2e/transports/a2a.test.js`++## Files to modify+- `package.json` — add `"test:e2e": "vitest run --config tests/e2e/vitest.config.js"` script+- `.github/workflows/` — add CI workflow that runs E2E against testnet on PR (NOT mainnet)+- `.env.example` — `TEST_EVM_PRIVATE_KEY_BUYER`, `TEST_EVM_PRIVATE_KEY_SELLER`, `TEST_SVM_PRIVATE_KEY_BUYER`, `TEST_SVM_PRIVATE_KEY_SELLER`++## Implementation++### Test wallets+Pre-funded testnet wallets:+- Base Sepolia: USDC + small ETH balance (gas)+- Solana Devnet: USDC + small SOL balance++Top-up cron (manual or scripted) keeps wallets funded between test runs. Document the recovery procedure in `tests/e2e/README.md`.++### Test shape+```js+import { test, expect } from "vitest";+import { setupServer, buildBuyerFetch } from "../setup.js";++test("exact EVM: 402 → pay → 200 with receipt", async () => {+ const { url } = await setupServer({ route: "/api/x402/exact-evm-demo" });+ const fetch = buildBuyerFetch({ evmSigner: testEvmSigner });+ const res = await fetch(url);+ expect(res.status).toBe(200);+ const receipt = extractPaymentResponse(res);+ expect(receipt.success).toBe(true);+ expect(receipt.transaction).toMatch(/^0x[a-f0-9]{64}$/);+});+```++### Coverage matrix+Every test asserts:+- HTTP status code+- `PAYMENT-RESPONSE` header presence and validity+- On-chain transaction visible via RPC within timeout+- Audit log entry created+- Extension responses correct++### Negative tests+- Invalid signature → 402 with specific error+- Replay (same nonce) → rejected+- Expired authorization → rejected+- Settlement of more than authorized → rejected+- Etc.++### CI gotchas+- Testnet faucets rate-limit; persist wallet funds across runs.+- RPC providers rate-limit; use multiple providers in a fallback list.+- Mainnet must NEVER run in CI. Guard with `if (process.env.NETWORK !== "testnet") throw`.++## Wiring checklist+- [ ] Test wallets pre-funded+- [ ] Every prior use case (USE-00..27) has at least one E2E test+- [ ] Negative tests for protocol-level errors+- [ ] CI runs E2E on PR+- [ ] Mainnet guard prevents accidental real-money runs++## Acceptance+- [ ] `npm run test:e2e` passes locally+- [ ] CI pipeline runs E2E on every PR+- [ ] Coverage report shows >80% of x402 code paths exercised+- [ ] Test wallets stay funded automatically OR documented top-up procedure+- [ ] Negative tests catch real protocol violations (verify with intentionally-broken local change)diff --git a/x402-buildout/prompts/29-wealth-manager.md b/x402-buildout/prompts/29-wealth-manager.mdnew file mode 100644index 000000000..1f5f88ce8--- /dev/null+++ b/x402-buildout/prompts/29-wealth-manager.md@@ -0,0 +1,83 @@+# USE-29: Wealth-Manager Trading Bot++## Goal+Algorithmic agent that fetches market data, runs strategies, and executes trades — paying per-fetch and per-trade via x402. Reports performance in real-time ("yesterday I earned X%").++## Why (from PROJECT-IDEAS.md)+> Executes algorithmic trades and reports performance. Payment moments: Per-data fetch and per-trade fee.++## Reference+- PROJECT-IDEAS.md+- Pump.fun feed (existing in this repo)+- `agent-payments-sdk/` (existing)++## Dependencies+- USE-00..09 (sellers + buyers complete)+- USE-22 (spending caps — CRITICAL for autonomous trading)+- USE-24 (audit log — required for performance reporting)++## Files to create+- `agents/wealth-manager/` — new workspace+- `agents/wealth-manager/package.json`+- `agents/wealth-manager/src/index.js` — entry: schedule market fetches, run strategy loop+- `agents/wealth-manager/src/data-sources.js` — paid sources: Messari (wrapped via x402), Pump.fun (existing), CoinGecko, our own paid analytics+- `agents/wealth-manager/src/strategies/momentum.js` — basic momentum+- `agents/wealth-manager/src/strategies/mean-reversion.js`+- `agents/wealth-manager/src/executor.js` — places real trades on a DEX (Jupiter for Solana, Uniswap for EVM)+- `agents/wealth-manager/src/perf-report.js` — daily performance summary, paid endpoint exposing it+- `api/agents/wealth-manager-report.js` — public paid endpoint to read the bot's performance++## Files to modify+- Root `package.json` — add workspace+- `.env.example` — `WEALTH_MANAGER_STRATEGY`, `WEALTH_MANAGER_MAX_POSITION_USD`, `WEALTH_MANAGER_DEX` (jupiter|uniswap), `JUPITER_API_URL`, `UNISWAP_RPC_URL`++## Implementation++### Strategy loop+Cron every N minutes (Vercel cron or Node interval):+1. Fetch market data from paid sources (auto-pay via buyer client + batch-settlement)+2. Run strategy → produce buy/sell signals+3. For each signal, check position limits, execute trade on DEX+4. Record trade + price in audit log+5. After each trade, refresh portfolio value++### Trade execution (real, not paper)+- Jupiter for Solana swaps+- Uniswap V3 for Base swaps+- Sign + send via the agent's wallet (NOT the user's main wallet — dedicated trading wallet)++### Spending caps (CRITICAL)+- Per-call cap on data fetches+- Per-trade cap on execution+- Per-day total budget+- Auto-pause on suspicious activity (e.g., 10 losses in a row, sudden balance drop)++### Performance reporting endpoint+`/api/agents/wealth-manager-report` — paid `$0.01` endpoint returning:+- Daily / weekly / monthly P&L+- Win rate+- Sharpe ratio+- Open positions+- Strategy code hash (so callers can verify which version is running)++### Safety+- Trading wallet is a dedicated low-balance wallet, NOT the user's primary+- Kill switch: env var `WEALTH_MANAGER_PAUSED=true` halts all trades immediately+- Alerts on Slack/Discord (via webhook) for every trade++## Wiring checklist+- [ ] Trading wallet dedicated, balance limited+- [ ] Strategy backtested before live+- [ ] All trade execution + data fetches paid via x402 (no free leeching)+- [ ] Performance endpoint paid via x402+- [ ] Kill switch operational+- [ ] Slack/Discord webhook firing+- [ ] All trades recorded in audit log++## Acceptance+- [ ] Bot runs for 24h on testnet without crashing+- [ ] Bot makes at least one trade+- [ ] Performance endpoint returns real numbers (not placeholders)+- [ ] Daily Slack/Discord summary delivered+- [ ] Kill switch tested: setting env var halts within one loop cycle+- [ ] Audit log shows every data fetch + tradediff --git a/x402-buildout/prompts/30-prediction-oracle.md b/x402-buildout/prompts/30-prediction-oracle.mdnew file mode 100644index 000000000..7c15a3e26--- /dev/null+++ b/x402-buildout/prompts/30-prediction-oracle.md@@ -0,0 +1,79 @@+# USE-30: Prediction-Market Oracle++## Goal+Paid endpoint that resolves a prediction market question by fetching consensus from paid web/news sources, applying a verifiable algorithm, and returning a signed answer with confidence. Charges only on settlement (resolution fee).++## Why (from PROJECT-IDEAS.md)+> Agent resolves any prediction market by fetching consensus facts online. Payment moment: Resolution fee on settlement.++## Reference+- PROJECT-IDEAS.md+- Bazaar (USE-13/14) for discovering source data feeds++## Dependencies+- USE-00..09+- USE-15 (idempotency — same question must yield same answer)+- USE-17 (offer-receipt — resolution must be verifiable)+- USE-22, USE-24++## Files to create+- `agents/oracle/`+- `agents/oracle/package.json`+- `agents/oracle/src/resolver.js` — main resolution logic+- `agents/oracle/src/sources.js` — paid sources: web search (Exa, Tavily, Brave), news APIs, fact-checker chain+- `agents/oracle/src/confidence.js` — Bayesian aggregation across sources+- `agents/oracle/src/attestation.js` — sign the resolution with our offer-receipt key+- `api/agents/oracle-resolve.js` — paid `$0.50` endpoint to resolve a question++## Files to modify+- Root `package.json` — add workspace+- `.env.example` — `ORACLE_MIN_SOURCES` (default 3), `ORACLE_CONFIDENCE_THRESHOLD` (default 0.8)++## Implementation++### Endpoint contract+```+POST /api/agents/oracle-resolve+Body: { question: "Will BTC close above $100k on Jan 1 2027?", deadline: "2027-01-02T00:00:00Z" }+402 → pay $0.50+200 → { answer: "yes"|"no"|"undetermined", confidence: 0.0..1.0, sources: [{ url, excerpt, weight }], signedAttestation: "0x..." }+```++### Resolution algorithm+1. Generate search queries from the question (LLM call, paid via OpenAI/Anthropic worker proxy)+2. Query N paid search APIs in parallel via Bazaar-discovered services+3. For each result, extract claim + supporting/refuting evidence+4. Bayesian aggregation with source-weight priors (CNN/Reuters > random blog)+5. If confidence < threshold OR fewer than min sources, return `undetermined`+6. Sign attestation with offer-receipt key++### Idempotency required+Same `{question, deadline}` MUST yield same answer. Use payment-identifier extension with `required: true`. Cache results for 30 days.++### Source pool+- Exa Search (paid)+- Tavily AI Search (paid)+- Brave Search API (paid)+- Wikipedia (free, with weighting)+- Our own paid fact-checker (USE-32) for cross-validation++### Attestation+Sign `{question, deadline, answer, confidence, sources, resolvedAt}` with EIP-712 using our offer-receipt key. Any party can verify the resolution against our DID document.++### Question normalization+Strip whitespace, lowercase, hash. Cache by normalized hash so semantically-equivalent variants don't double-charge but textually-different questions don't collide.++## Wiring checklist+- [ ] Bazaar-discovered search APIs configured+- [ ] Payment-identifier required on this endpoint+- [ ] Cache TTL = 30 days+- [ ] Attestation key separate from payment-receiving wallet+- [ ] LLM token usage capped per call (spending cap)+- [ ] No determinism leaks (timestamp NOT in hash basis)++## Acceptance+- [ ] Two resolutions of the same question produce identical answer + signature+- [ ] Resolution of unanswerable question returns `undetermined` with low confidence+- [ ] At least 3 different paid sources verifiably consulted (audit log)+- [ ] Attestation verifies against our DID document+- [ ] Costs $0.50 to call; observed per-call source costs sum to < $0.50 (we keep margin)diff --git a/x402-buildout/prompts/31-kyc-checker.md b/x402-buildout/prompts/31-kyc-checker.mdnew file mode 100644index 000000000..f4bb9a045--- /dev/null+++ b/x402-buildout/prompts/31-kyc-checker.md@@ -0,0 +1,84 @@+# USE-31: Rapid KYC/AML Checker++## Goal+Paid endpoint that screens a wallet address against sanctions lists and basic risk heuristics. $0.25 per check, real Chainalysis / TRM data, structured response.++## Why (from PROJECT-IDEAS.md)+> Pay $0.25 to screen a wallet address against sanctions lists or heuristics. Suggested APIs: Chainalysis, TRM, or your own heuristics.++## Reference+- PROJECT-IDEAS.md+- Existing `api/x402/onchain-identity-verify.js` (already in repo — likely the precursor)++## Dependencies+- USE-00..09+- USE-15 (idempotency — same address same answer)+- USE-22 (caps)+- USE-26 (self-hosted facilitator already uses similar Chainalysis integration; reuse)++## Files to create+- `api/x402/kyc-screen.js` — paid endpoint+- `agents/kyc/src/sources.js` — Chainalysis Address Screening, TRM Address Risk Score, local heuristics (large-tx, mixer-touched, sanctions intersection)+- `agents/kyc/src/aggregator.js` — combines sources into a single risk score+- `agents/kyc/src/cache.js` — Redis-backed cache (high TTL since results stable)++## Files to modify+- `api/x402/onchain-identity-verify.js` — refactor to delegate to the new module; keep endpoint compat+- `.env.example` — `CHAINALYSIS_API_KEY`, `TRM_API_KEY`++## Implementation++### Endpoint contract+```+POST /api/x402/kyc-screen+Body: { address: "0x...", chain: "eip155:1"|"solana:..." }+402 → pay $0.25+200 → {+ address,+ chain,+ risk: { score: 0..100, level: "low"|"medium"|"high"|"sanctioned", reasons: [...] },+ sources: { chainalysis: {...}, trm: {...}, heuristics: {...} },+ signedAt: "...",+ attestation: "0x..."+}+```++### Idempotency / caching+- Cache results per address for 24 hours.+- Sanctions list changes daily; we accept up-to-24h staleness.+- Re-screening within 24h returns cached + same charge (idempotency makes it free on retry).++### Sources+1. Chainalysis Address Screening (sanctioned-yes/no + categories)+2. TRM Labs Address Risk Score (0-10 score + indicators)+3. Local heuristics:+ - Touched known mixer (Tornado, etc.)+ - Funded by sanctioned address (1 hop)+ - High activity in flagged time window+ - Solana: program account vs personal wallet++### Risk aggregation+Weighted sum with hard overrides:+- If Chainalysis sanctioned → risk = 100 ("sanctioned")+- Else if TRM > 7 → high+- Else weighted blend++### Multi-chain support+EVM and Solana addresses supported. Different sources per chain.++### Attestation+Signed by our offer-receipt key. Receipts go to USE-17 storage so callers can prove they screened an address at a given time.++## Wiring checklist+- [ ] Chainalysis + TRM API keys provisioned+- [ ] Both EVM and Solana addresses supported+- [ ] Cache 24h; idempotency for retries within cache+- [ ] Risk aggregation tested with known sanctioned / known-clean addresses+- [ ] Attestation signed and verifiable++## Acceptance+- [ ] Screen a known sanctioned address (e.g., Tornado deposit) → returns `sanctioned`+- [ ] Screen a known-clean exchange hot wallet → returns `low`+- [ ] Same address screened twice within 24h → second call paid but returns cached + same attestation+- [ ] Attestation verifies against our DID document+- [ ] Per-call cost (Chainalysis + TRM) tracked in audit log so we know margindiff --git a/x402-buildout/prompts/32-fact-checker.md b/x402-buildout/prompts/32-fact-checker.mdnew file mode 100644index 000000000..38f0a268c--- /dev/null+++ b/x402-buildout/prompts/32-fact-checker.md@@ -0,0 +1,83 @@+# USE-32: Real-Time Fact Checker++## Goal+Paid endpoint: caller highlights a claim, we find supporting sources, pay each per-page retrieval, return a verdict with cited sources.++## Why (from PROJECT-IDEAS.md)+> Journalists highlight a claim; agent finds supporting sources and pays per page. Payment moment: Per-page retrieval.++## Reference+- PROJECT-IDEAS.md+- Bazaar (USE-13/14) for source discovery++## Dependencies+- USE-00..09+- USE-15 (idempotency)+- USE-22 (caps — we pay PER PAGE, costs can compound)+- USE-30 (oracle resolution pattern)++## Files to create+- `agents/fact-checker/`+- `agents/fact-checker/src/index.js`+- `agents/fact-checker/src/search-sources.js` — Exa, Tavily, Brave (paid via x402)+- `agents/fact-checker/src/scrape.js` — Browserbase or Firecrawl (paid per page)+- `agents/fact-checker/src/llm-verdict.js` — local LLM call to weigh evidence+- `api/x402/fact-check.js` — paid endpoint $0.25 base + variable based on sources++## Files to modify+- Root `package.json` — add workspace+- `.env.example` — `EXA_API_KEY`, `TAVILY_API_KEY`, `BROWSERBASE_API_KEY`, `FIRECRAWL_API_KEY` (any subset works — agent uses what's available)++## Implementation++### Endpoint contract+```+POST /api/x402/fact-check+Body: { claim: "The Eiffel Tower is 330 meters tall.", strictness: "high"|"medium"|"low" }+402 → pay $0.10 base+200 → {+ verdict: "supported"|"contradicted"|"mixed"|"insufficient",+ confidence: 0..1,+ sources: [+ { url, excerpt, stance: "supports"|"contradicts", weight, retrievedAt }+ ],+ costBreakdown: { searchCalls: 3, pageScrapes: 5, llmTokens: 2400, totalUsdc: "..." },+ attestation: "0x..."+}+```++### Pricing model+Use the `upto` scheme: max $1.00 per check, actual cost = base + variable. Caller sees actual charge in `PAYMENT-RESPONSE.amount`.++### Algorithm+1. LLM generates 3-5 search queries+2. Run searches across configured paid search APIs+3. Top 5 results per search ranked by source authority+4. Scrape top N (configurable, capped) pages via Browserbase or Firecrawl+5. LLM extracts excerpts + stance per page+6. Weighted aggregation → verdict + confidence++### Source weighting+Authority score per domain: `.gov` and `.edu` > major news (.com BBC, AP, Reuters) > minor news > blogs > forums. Maintained as a curated JSON list checked in.++### Idempotency+Same claim text + strictness → same answer (caching with 7-day TTL). Required idempotency per USE-15.++### Attestation+Sign verdict + source URLs + retrievedAt timestamps. Receipt stored.++## Wiring checklist+- [ ] At least one of (Exa, Tavily, Brave) configured+- [ ] At least one of (Browserbase, Firecrawl) configured+- [ ] `upto` scheme on the endpoint with proper cost accounting+- [ ] Source authority list checked in and updated+- [ ] Cache TTL 7 days+- [ ] Spending cap per-claim enforced++## Acceptance+- [ ] Fact-check a known-true claim ("Eiffel Tower height") → `supported` with high confidence+- [ ] Fact-check a known-false claim → `contradicted` with high confidence+- [ ] Fact-check a controversial claim → `mixed` or `insufficient`+- [ ] Per-call cost breakdown shows actual paid expenditure (search + scrape + LLM)+- [ ] Two checks of identical claim → same verdict and signature; second call uses cache (no re-spend)+- [ ] Attestation verifiesdiff --git a/x402-buildout/prompts/33-tutor.md b/x402-buildout/prompts/33-tutor.mdnew file mode 100644index 000000000..18969e4e6--- /dev/null+++ b/x402-buildout/prompts/33-tutor.md@@ -0,0 +1,82 @@+# USE-33: Pay-As-You-Learn Tutor++## Goal+Interactive tutor that bills per-explanation (1 cent per response). Session has a running tab; final invoice at session end with itemized breakdown.++## Why (from PROJECT-IDEAS.md)+> Every executed command explanation costs 1 cent; itemized bill at session end.++## Reference+- PROJECT-IDEAS.md+- `upto` scheme for variable per-response cost+- `batch-settlement` for the session model++## Dependencies+- USE-00..09+- USE-05 (batch-settlement on server)+- USE-09 (batch-settlement on client)+- USE-16 (SIWX for session resumption)+- USE-17 (offer-receipt for session invoice)++## Files to create+- `agents/tutor/`+- `agents/tutor/src/session.js` — session state (questions asked, costs accrued)+- `agents/tutor/src/teach.js` — LLM-backed explanation generator+- `agents/tutor/src/examples.js` — code execution sandbox (e.g., V8 isolate, Docker, Pyodide for Python)+- `api/x402/tutor.js` — paid endpoint, `batch-settlement` scheme+- `public/tutor.html` — chat UI+- `public/tutor.js` — front-end with channel state, session invoice display++## Files to modify+- Root `package.json` — add workspace+- `vercel.json` — `/tutor` route+- `.env.example` — `TUTOR_PROVIDER` (anthropic|openai), `TUTOR_MAX_COST_PER_SESSION_USD`++## Implementation++### Session model+- One x402 batch-settlement channel per (buyer, session)+- Each question → one voucher signed by buyer+- Session ends when buyer hits "end session" (cooperative refund of unused channel balance)+- Session resumed by SIWX challenge — buyer doesn't repay for prior session++### Endpoint contract+```+POST /api/x402/tutor+Body: { sessionId: "uuid", question: "explain my code", context: "...", level: "beginner|expert" }+402 (first call) → opens batch channel, returns PaymentRequired+200 → { answer: "...", costThisCharge: "1000", sessionTotal: "12000", sessionId }+```++### Cost model+- Base: $0.01 per response+- Per-token surcharge: $0.0001 per 100 LLM output tokens+- Sandbox execution: $0.005 per execution+- Per-call max: $0.10 (caller-authorized via batch voucher ceiling)++### Code execution+For tutoring code, run user-provided snippets in a sandboxed environment. Pyodide in browser for Python, V8 isolate for JS, Docker for everything else. Sandbox time-bounded.++### Final invoice+At session end:+1. Show itemized bill (each question, cost, transcript)+2. Sign invoice with offer-receipt key+3. Refund unused channel balance via cooperative refund++### UI+Chat-style. Each AI response shows cost on the message bubble. Running total visible. "End session and pay" button at top.++## Wiring checklist+- [ ] Batch-settlement channel opened per session+- [ ] Cost tracking accurate at sub-cent granularity+- [ ] Code sandbox isolated, time-bounded+- [ ] SIWX-based session resume works+- [ ] Invoice signed and stored+- [ ] Cooperative refund triggered at session end++## Acceptance+- [ ] Tutor session of 20 questions costs roughly 20 × per-response charge+- [ ] Killing the browser mid-session and returning later (after SIWX) resumes without re-payment+- [ ] Session-end invoice shows itemized cost matching audit log+- [ ] Refund returns unused balance — verified on-chain+- [ ] Code execution sandbox prevents file system / network accessdiff --git a/x402-buildout/prompts/34-bounty-hunter.md b/x402-buildout/prompts/34-bounty-hunter.mdnew file mode 100644index 000000000..bedc79d6d--- /dev/null+++ b/x402-buildout/prompts/34-bounty-hunter.md@@ -0,0 +1,77 @@+# USE-34: Bounty-Hunter Agent++## Goal+Autonomous agent that scans bounty platforms, picks tasks it can complete, executes them (paying for tools used along the way), submits work, claims reward.++## Why (from PROJECT-IDEAS.md)+> Scans for open bounties, completes tasks, claims reward. Payment moments: Entry fee; streaming pay-as-you-work compute. Suggested APIs: Bountycaster, basic web-scrape, image gen, code sandbox.++## Reference+- PROJECT-IDEAS.md+- Bountycaster, Replicate, Stability AI, web-scrape services++## Dependencies+- USE-00..09+- USE-22, USE-24+- USE-29 (similar autonomous-agent patterns)++## Files to create+- `agents/bounty-hunter/`+- `agents/bounty-hunter/src/index.js` — orchestrator+- `agents/bounty-hunter/src/scanner.js` — polls Bountycaster + GitHub Issues with bounty labels+- `agents/bounty-hunter/src/classifier.js` — LLM-based "can I do this?" gate+- `agents/bounty-hunter/src/executors/image-gen.js`+- `agents/bounty-hunter/src/executors/code-task.js`+- `agents/bounty-hunter/src/executors/research.js`+- `agents/bounty-hunter/src/submitter.js` — submits the work + posts proof+- `api/agents/bounty-hunter-status.js` — paid endpoint to read the agent's current task list + history++## Files to modify+- Root `package.json` — add workspace+- `.env.example` — `BOUNTYCASTER_API_KEY`, `GITHUB_TOKEN`, `REPLICATE_API_KEY`, `STABILITY_API_KEY`, `BOUNTY_MIN_REWARD_USD`, `BOUNTY_MAX_COST_RATIO` (don't accept a bounty whose tooling cost exceeds X% of reward)++## Implementation++### Loop+1. Scan bounty sources every N minutes+2. For each new bounty: classify (can we do it? cost estimate? reward worth it?)+3. If accept: enter the bounty (entry fee paid via x402 if applicable)+4. Execute task — every paid tool used goes through buyer client with audit logging+5. Submit work+6. Track outcome (accepted/rejected/paid)++### Profitability gating+Reject bounties where estimated cost > `BOUNTY_MAX_COST_RATIO * reward`. Conservative defaults (e.g., 30%).++### Audit+Every task is a row: bounty ID, entry fee paid, costs incurred, work output, reward received, profit. Surface via the status endpoint.++### Safety+- Don't auto-submit work to bounties involving real-world consequences (financial trades, account actions, etc.)+- Whitelist of allowed bounty categories: image gen, research, code review, content tagging.++### Status endpoint+`GET /api/agents/bounty-hunter-status` ($0.01) — returns recent bounty stats:+```json+{+ "active": [...],+ "completed": [...],+ "totals": { "rewardEarned": "...", "costsIncurred": "...", "netProfit": "..." },+ "winRate": 0.x+}+```++## Wiring checklist+- [ ] Bountycaster + GitHub bounty sources configured+- [ ] Classifier rejects tasks outside whitelisted categories+- [ ] Profitability gate enforced+- [ ] Tools (image gen, scrape, LLM) paid via x402+- [ ] Status endpoint live, paid+- [ ] Kill switch via env var++## Acceptance+- [ ] Agent runs 24h+, processes at least one bounty end-to-end+- [ ] No bounty accepted outside whitelist+- [ ] No tool used without audit log entry+- [ ] Status endpoint returns real, accurate stats+- [ ] Net profit positive over a representative sample (or report negative and tune)diff --git a/x402-buildout/prompts/35-consultant-booking.md b/x402-buildout/prompts/35-consultant-booking.mdnew file mode 100644index 000000000..123a34dc6--- /dev/null+++ b/x402-buildout/prompts/35-consultant-booking.md@@ -0,0 +1,85 @@+# USE-35: Consultant Agent — Find, Book, Pay++## Goal+Agent that finds a domain expert (LinkedIn, Cal.com listing), books a call at a chosen time, and pays the booking fee — all via x402.++## Why (from PROJECT-IDEAS.md)+> Finds an expert, books a call, pays automatically. Payment moment: Up-front booking fee. Suggested APIs: Cal.com, Twilio, XTMP messaging, LinkedIn search.++## Reference+- PROJECT-IDEAS.md+- Cal.com API: https://cal.com/docs++## Dependencies+- USE-00..09+- USE-14 (Bazaar discovery for finding experts who've listed themselves)+- USE-16 (SIWX so user can authenticate as the booker)+- USE-22, USE-24++## Files to create+- `agents/consultant/`+- `agents/consultant/src/search.js` — LinkedIn search via Tavily/Brave + Cal.com directory + Bazaar listings+- `agents/consultant/src/scheduler.js` — Cal.com booking API integration+- `agents/consultant/src/notify.js` — Twilio SMS / email confirmation+- `api/agents/consultant-book.js` — paid endpoint that takes a request and returns a confirmation++## Files to modify+- Root `package.json` — add workspace+- `.env.example` — `CALCOM_API_KEY`, `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN`, `TWILIO_FROM_NUMBER`, `LINKEDIN_API_KEY` (or scrape via Tavily)++## Implementation++### Endpoint contract+```+POST /api/agents/consultant-book+Body: {+ expertise: "Solana smart contracts",+ budgetMaxUsd: 200,+ timeWindow: { start: "2026-05-25T09:00:00Z", end: "2026-05-30T17:00:00Z" },+ duration: 30,+ bookerEmail: "...",+ bookerPhone: "..."+}+402 → pay $5 (booking-fee placeholder; actual cost added at settle via `upto`)+200 → {+ expert: { name, profile, hourlyRate },+ bookingId: "...",+ scheduledFor: "...",+ meetingUrl: "...",+ confirmationsSent: ["email", "sms"]+}+```++### Flow+1. Search for experts matching expertise+2. Rank by rating + price + availability within window+3. Pick top match within budget+4. Call Cal.com API to book+5. Pay the booking fee (the agent's wallet pays the expert via on-chain transfer OR Cal.com Stripe)+6. Confirm via Twilio + email+7. Return confirmation++### Two-sided economics+- The agent charges the END USER $5 for the booking service + the consultant's actual fee+- It pays the consultant out-of-band (via Cal.com Stripe or on-chain transfer)+- Margin = booking fee++### Use `upto`+Because consultant prices vary, advertise `upto` $250 max. Actual settle = $5 + consultant fee.++### Cancellation+Out of scope for v1. Document as a future enhancement.++## Wiring checklist+- [ ] Cal.com integration tested with a real test account+- [ ] Twilio SMS sends real confirmation in dev (use a test number)+- [ ] Search returns real experts (not hallucinated)+- [ ] Budget cap enforced+- [ ] Consultant paid out via real rail (Cal.com Stripe or on-chain)++## Acceptance+- [ ] Booking a 30-minute call within a 5-day window succeeds end-to-end on testnet+- [ ] Confirmation email + SMS received+- [ ] Expert appears on Cal.com (real booking)+- [ ] `upto` settles for actual cost (booking fee + consultant rate)+- [ ] No booking exceeds budget capdiff --git a/x402-buildout/prompts/36-endpoint-shopper.md b/x402-buildout/prompts/36-endpoint-shopper.mdnew file mode 100644index 000000000..90ed321de--- /dev/null+++ b/x402-buildout/prompts/36-endpoint-shopper.md@@ -0,0 +1,76 @@+# USE-36: Dynamic Endpoint Shopper++## Goal+Agent that discovers paid endpoints in a Bazaar registry, picks the right one for a task, pays, chains results across multiple endpoints to deliver a higher-level outcome.++## Why (from PROJECT-IDEAS.md)+> Agent discovers an MCP registry, pays for its service, chains results. Payment moments: Pay-per-call to each discovered endpoint.++## Reference+- PROJECT-IDEAS.md+- Bazaar (USE-13/14)++## Dependencies+- USE-00..09+- USE-13, USE-14 (Bazaar)+- USE-22, USE-24++## Files to create+- `agents/endpoint-shopper/`+- `agents/endpoint-shopper/src/planner.js` — LLM-based task decomposition into search queries+- `agents/endpoint-shopper/src/discover.js` — Bazaar discovery + ranking+- `agents/endpoint-shopper/src/orchestrator.js` — sequential or parallel endpoint calls; data passing+- `agents/endpoint-shopper/src/judge.js` — quality-checks results, decides whether to re-call or escalate+- `api/agents/endpoint-shopper-run.js` — paid endpoint accepting a high-level task++## Files to modify+- Root `package.json` — add workspace+- `.env.example` — `SHOPPER_MAX_CHAIN_DEPTH` (default 5), `SHOPPER_MAX_COST_USD` (per task)++## Implementation++### Endpoint contract+```+POST /api/agents/endpoint-shopper-run+Body: { task: "Tell me the current weather in San Francisco and convert it to Celsius.", maxCostUsd: 0.50 }+402 → upto $0.50+200 → {+ result: { ... final answer ... },+ steps: [+ { endpoint, action, cost, output: { ... } },+ ...+ ],+ totalCostUsdc: "..."+}+```++### Planner+LLM call: given task + Bazaar catalog (filtered + summarized), generate a step plan. Each step: which endpoint to call, with what args, expected output shape.++### Orchestrator+- Sequential by default+- Parallel if planner marks steps as independent+- Each call paid via wrapped client (USE-06/07)+- Output of each step feeds into the next (LLM transforms if shape mismatch)++### Quality gate+After each step, judge: was the response well-formed? Was the cost reasonable? If not, fall back to alternate endpoint or fail gracefully.++### Cost ceiling+`upto` scheme with `maxCostUsd` from request. If task can't complete under budget, return partial result + clear explanation.++### Caching+Same task with same inputs → cache for 1h. Idempotency via payment-identifier.++## Wiring checklist+- [ ] Bazaar catalog filtered by task-relevant tags+- [ ] Spending cap per task enforced+- [ ] Each step uses payment-identifier (idempotency for the step itself)+- [ ] Failed steps logged with reason+- [ ] Cost ceiling never exceeded++## Acceptance+- [ ] Submit "weather in San Francisco in Celsius" — agent discovers weather + unit-conversion endpoints, calls in order, returns answer+- [ ] Cost stays under ceiling even when plan requires unexpected fallbacks+- [ ] Same task twice = same result (cached + idempotent)+- [ ] Audit log shows every step + cost