Skip to content

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

feat: poll-based live token trades + coin-trades proxy; animation studio prompts

nirholasc473df09db86
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 052b079cb..e909290c0 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -116,6 +116,7 @@ const wrapped = wrap(async (req, res) => {
case 'first-claims': return handleFirstClaims(req, res);
case 'recent-graduations': return handleRecentGraduations(req, res);
case 'trending': return handleTrending(req, res);
+ case 'coin-trades': return handleCoinTrades(req, res);
case 'search': return handleSearch(req, res);
case 'collect-creator-fee-prep': return handleCollectCreatorFeePrep(req, res);
case 'distribute-creator-fees-prep': return handleDistributeCreatorFeesPrep(req, res);
@@ -2424,53 +2425,82 @@ async function handleChannelFeed(req, res) {
// ── trending / search (proxies for the CORS-protected pump.fun frontend API) ──
const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';
-// Cache keyed by sort+order+limit so the market_cap view and the
-// last_trade_timestamp view (used by the homepage live feed to find an
-// actively-trading bonding-curve coin) don't clobber each other.
-const TRENDING_CACHE = new Map();
+const TRENDING_CACHE = { at: 0, body: null };
const TRENDING_TTL_MS = 15_000;
-const TRENDING_SORTS = new Set([
- 'market_cap',
- 'last_trade_timestamp',
- 'created_timestamp',
- 'currently_live',
-]);
async function handleTrending(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
const rl = await limits.mcpIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
- const url = new URL(req.url, `http://${req.headers.host}`);
- const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 50)), 100);
- const sortParam = String(url.searchParams.get('sort') || 'market_cap');
- const sort = TRENDING_SORTS.has(sortParam) ? sortParam : 'market_cap';
- const order = url.searchParams.get('order') === 'ASC' ? 'ASC' : 'DESC';
- const cacheKey = `${sort}:${order}:${limit}`;
-
const now = Date.now();
- const cached = TRENDING_CACHE.get(cacheKey);
- if (cached && now - cached.at < TRENDING_TTL_MS) {
+ if (TRENDING_CACHE.body && now - TRENDING_CACHE.at < TRENDING_TTL_MS) {
res.setHeader('cache-control', 'public, max-age=15');
- return json(res, 200, cached.body);
+ return json(res, 200, TRENDING_CACHE.body);
}
-
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 50)), 100);
const upstream = new URL('/coins', PUMP_FRONTEND_BASE);
upstream.searchParams.set('offset', '0');
upstream.searchParams.set('limit', String(limit));
- upstream.searchParams.set('sort', sort);
- upstream.searchParams.set('order', order);
+ upstream.searchParams.set('sort', 'market_cap');
+ upstream.searchParams.set('order', 'DESC');
upstream.searchParams.set('includeNsfw', 'false');
const resp = await fetch(upstream, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });
if (!resp.ok) return error(res, 502, 'upstream_failed', `pump.fun returned ${resp.status}`);
const body = await resp.json();
const arr = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : [];
- TRENDING_CACHE.set(cacheKey, { at: now, body: arr });
- if (TRENDING_CACHE.size > 16) TRENDING_CACHE.delete(TRENDING_CACHE.keys().next().value);
+ TRENDING_CACHE.at = now;
+ TRENDING_CACHE.body = arr;
res.setHeader('cache-control', 'public, max-age=15');
return json(res, 200, arr);
}
+// ── coin-trades ────────────────────────────────────────────────────────────
+// Recent buy/sell trades for a single mint, proxied from pump.fun's swap API
+// (CORS-protected from the browser). Powers the homepage live token card's
+// green/red flow. Covers both bonding-curve and migrated (AMM) trades.
+
+const PUMP_SWAP_BASE = 'https://swap-api.pump.fun';
+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+async function handleCoinTrades(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const mint = (url.searchParams.get('mint') || '').trim();
+ if (!MINT_RE.test(mint)) return error(res, 400, 'invalid_mint', 'mint must be a base58 address');
+ const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 30)), 100);
+ const upstream = `${PUMP_SWAP_BASE}/v2/coins/${mint}/trades?limit=${limit}`;
+ let resp;
+ try {
+ resp = await fetch(upstream, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(8000),
+ });
+ } catch {
+ return error(res, 504, 'upstream_timeout', 'pump.fun swap API did not respond');
+ }
+ if (!resp.ok) return error(res, 502, 'upstream_failed', `pump.fun returned ${resp.status}`);
+ const body = await resp.json();
+ const raw = Array.isArray(body) ? body : Array.isArray(body?.trades) ? body.trades : [];
+ const trades = raw
+ .map((t) => ({
+ tx: t.tx,
+ timestamp: t.timestamp,
+ user: t.userAddress || t.user || null,
+ is_buy: String(t.type).toLowerCase() === 'buy',
+ sol_amount: Number(t.amountSol),
+ usd_amount: t.amountUsd != null ? Number(t.amountUsd) : null,
+ price_usd: t.priceUsd != null ? Number(t.priceUsd) : null,
+ }))
+ .filter((t) => t.tx && isFinite(t.sol_amount) && t.sol_amount > 0);
+ res.setHeader('cache-control', 'public, max-age=3');
+ return json(res, 200, { mint, trades });
+}
+
async function handleSearch(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
diff --git a/prompts/animation-studio/00-README.md b/prompts/animation-studio/00-README.md
new file mode 100644
index 000000000..aa4266da7
--- /dev/null
+++ b/prompts/animation-studio/00-README.md
@@ -0,0 +1,183 @@
+# Animation Studio — build plan
+
+This directory contains **sequenced task prompts**. Each `NN-*.md` file is meant to be
+pasted into a **fresh agent chat** in this repo. Run them **in order** — later tasks
+depend on earlier ones. Every task assumes the agent has already loaded the repo's
+`CLAUDE.md` operating rules (no mocks, no stubs, wire 100%, real APIs, design every state).
+
+## The goal (what we are building)
+
+Turn the existing `/pose` page (today: a click-to-pose primitive mannequin) into a full
+**Animation Studio**:
+
+1. **Load a rig.** Users can pose either the built-in primitive mannequin (default) **or**
+ a real rigged GLB — including **their own custom avatars made on three.ws**, loaded by
+ `?avatar=<id>` or picked from a gallery.
+2. **Pose ergonomically.** Click/drag joints with rotation gizmos and **inverse kinematics**
+ (drag a hand or foot, the limb solves) — not just raw per-axis sliders.
+3. **Keyframe a timeline.** Set a pose → drop a keyframe → advance the playhead → re-pose →
+ drop another. The tool interpolates between keyframes and plays the result. This is how a
+ user authors a walk cycle, a wave, a dance.
+4. **Export.** Download as a **GLB with embedded animation** and/or as a three.ws **clip JSON**.
+5. **Save to account.** Persist animations to the signed-in user's account; manage a library
+ (rename, retag, set visibility, delete).
+6. **Works across three.ws.** Saved/public animations play back anywhere via the existing
+ `AnimationManager` / viewer (avatar pages, embeds).
+7. **Monetize.** Users can put a price on an animation and sell it for USDC via the existing
+ x402 rails; buyers pay once and download. Listed in the marketplace + bazaar.
+
+## Task sequence
+
+| # | File | Depends on | What it delivers |
+|---|------|-----------|------------------|
+| 1 | `01-avatar-loading-and-rigged-posing.md` | — | Load rigged GLB + own avatars into `/pose`; pose real skeletons with gizmos + IK; keep mannequin as default |
+| 2 | `02-keyframe-timeline-and-export.md` | 1 | Timeline UI, keyframe model, bake to `AnimationClip`, live preview, GLB + clip-JSON export |
+| 3 | `03-backend-animation-clips-api.md` | — (can run anytime) | DB migration + `/api/animations` CRUD with auth, ownership, visibility, pricing columns |
+| 4 | `04-save-and-library.md` | 2, 3 | "Save to account", thumbnail capture, "My animations" library drawer in the editor |
+| 5 | `05-playback-across-platform.md` | 3 | Saved/public animations resolvable + playable via `AnimationManager`/viewer; public gallery |
+| 6 | `06-monetization.md` | 3, 4 | Price an animation → x402 paid download (USDC), per-creator payout, marketplace + bazaar listing |
+| 7 | `07-nav-promotion-and-polish.md` | 1–6 | Shared nav/header/footer on the page, rename + promote out of Labs, cross-linking, final QA |
+
+Tasks 1 and 3 are independent and can be started in parallel. Everything else follows the
+dependency column.
+
+---
+
+## Shared architecture & conventions (READ THIS — every task relies on it)
+
+These are real, verified facts about the codebase as of this writing. Cite file paths in your
+work and **read the referenced files before editing**.
+
+### The pose studio today
+- Page: [pages/pose.html](../../pages/pose.html) — standalone page, routed at `/pose`
+ ([vercel.json](../../vercel.json), [vite.config.js](../../vite.config.js)). It loads
+ `/nav.css` but does **not** currently inject the shared nav/header/footer.
+- Logic: [src/pose-studio.js](../../src/pose-studio.js) — `setupScene()` builds the
+ `Scene`/`PerspectiveCamera`/`WebGLRenderer` (with `preserveDrawingBuffer: true` for PNG
+ export), `OrbitControls`, lights, a `ShadowMaterial` ground + `GridHelper`, and a `propLayer`
+ `Group`. Raycaster-based joint picking + drag-to-rotate. PNG export via `canvas.toDataURL`.
+- Mannequin: [src/pose-mannequin.js](../../src/pose-mannequin.js) — `Mannequin` class with 16
+ joints (`JOINT_NAMES`: pelvis, spine, chest, neck, head, shoulder/elbow/wrist L+R,
+ hip/knee/ankle L+R). API: `setJointRotation(name, axis, radians)`, `getJointRotation(name)`,
+ `applyPose(pose)`, `getPose()`, `resetPose()`, `setConstraintsEnabled()`, `setBuild()`,
+ `setColor()`. Pose JSON is a flat map `{ jointName: {x,y,z}, rootPosition?: {x,y,z} }`.
+- Presets: [src/pose-presets.js](../../src/pose-presets.js) — `PRESETS[]`, `getPresetById()`,
+ `getPresetsByGroup()`.
+
+### Loading rigged avatars
+- GLTFLoader pattern with Draco/KTX2/Meshopt decoders lives in
+ [src/viewer.js](../../src/viewer.js) (~lines 841–887). Reuse the same decoder setup — do not
+ hand-roll a bare loader.
+- The `Viewer` class ([src/viewer.js](../../src/viewer.js)) loads avatars and exposes an
+ `AnimationManager`. A loaded `gltf` gives `gltf.scene` and `gltf.animations` (`AnimationClip[]`).
+- **Avatar gallery picker (ready to use):** [src/avatar-gallery-picker.js](../../src/avatar-gallery-picker.js)
+ — `new AvatarGalleryPicker({ source: 'mine'|'public'|'both', onSelect: (avatar)=>{}, ... })`,
+ `.openModal()` / `.mountInline(el)`. `onSelect` receives an avatar with `id`, `name`,
+ `model_url`, `thumbnail_url`, `tags`.
+- **Avatar list API:** `GET /api/avatars` (session auth, `credentials: 'include'`) returns
+ `{ avatars: [{ id, slug, name, model_url, thumbnail_url, tags, ... }], next_cursor }`.
+ Public variant: `GET /api/avatars/public`. Avatar decoration shape is in
+ [api/_lib/avatars.js](../../api/_lib/avatars.js) (`model_url` is the resolved/presigned GLB URL).
+- **Demo avatars** (for `?avatar=` testing without auth): [api/_lib/demo-avatars.js](../../api/_lib/demo-avatars.js)
+ — ids like `avatar_demo_disk_cz`, `avatar_demo_disk_saga` (robot, animated), etc. Note: the
+ `?avatar=` param is currently **not read** by the pose studio — wiring it is Task 1.
+
+### Bone naming (critical for cross-platform playback)
+- Canonical skeleton = **Avaturn / Mixamo-retargeted** names: `Hips`, `Spine`, `Spine1`,
+ `Spine2`, `Neck`, `Head`, `LeftArm`/`LeftForeArm`/`LeftHand`, `RightArm`/`RightForeArm`/`RightHand`,
+ `LeftUpLeg`/`LeftLeg`/`LeftFoot`/`LeftToeBase`, `RightUpLeg`/`RightLeg`/`RightFoot`/`RightToeBase`,
+ plus finger bones.
+- A robust bone-name normalizer already exists: `normalizeBoneName()` in
+ [src/avatar-export.js](../../src/avatar-export.js) (strips `mixamorig:`, `CC_Base_`, `Armature|`,
+ `rig:`, `Bip01`, separators). Reuse it; do not write a new one.
+- Reference rig used by the build pipeline: `public/avatars/cz.glb`.
+
+### Animation clip format (the format that "works on three.ws")
+- Stored clips are `THREE.AnimationClip.toJSON()` output:
+ ```json
+ {
+ "name": "wave",
+ "duration": 1.0,
+ "tracks": [
+ { "name": "Hips.position", "type": "vector", "times": [...], "values": [x,y,z, ...] },
+ { "name": "Hips.quaternion", "type": "quaternion", "times": [...], "values": [x,y,z,w, ...] },
+ { "name": "Head.quaternion", "type": "quaternion", "times": [...], "values": [...] }
+ ]
+ }
+ ```
+ Track name = `BoneName.property`. Parse with `AnimationClip.parse(json)`.
+- Manifest of built-in clips: [public/animations/manifest.json](../../public/animations/manifest.json)
+ — entries `{ name, url, label, icon, loop }`. Clips live in `public/animations/clips/*.json`.
+- Build pipeline (reference only — we author in-browser, not via FBX): [scripts/build-animations.mjs](../../scripts/build-animations.mjs).
+- **Playback engine:** [src/animation-manager.js](../../src/animation-manager.js) — `AnimationManager`
+ with `setAnimationDefs(defs)`, `attach(model)`, `loadAll()`, `ensureLoaded(name)`, `play(name)`,
+ `crossfadeTo(name, dur)`, `update(dt)`. It wraps a `THREE.AnimationMixer`. This is what your
+ exported/saved clips must be compatible with.
+- **Export with animations:** [src/avatar-export.js](../../src/avatar-export.js) uses
+ `GLTFExporter` and already passes `animations: gltf.animations` — i.e., exporting a GLB with
+ embedded animation tracks is a solved path; reuse it.
+
+### Posing aids available (already in node_modules — no install)
+- `three/examples/jsm/animation/CCDIKSolver.js` — inverse kinematics.
+- `three/examples/jsm/controls/TransformControls.js` — rotation/translation gizmos.
+- three.js version: **0.176.0**. Import addons via `three/addons/...` or
+ `three/examples/jsm/...` consistent with existing imports in the file you're editing.
+
+### Backend patterns (DB, auth, x402)
+- **DB client:** [api/_lib/db.js](../../api/_lib/db.js) — `import { sql } from '../_lib/db.js'`,
+ Neon serverless, tagged-template queries (`await sql\`select ... ${val}\``).
+- **Auth:** [api/_lib/auth.js](../../api/_lib/auth.js) — `getSessionUser(req)` (session cookie),
+ `authenticateBearer(extractBearer(req))` (API key / OAuth), `hasScope()`. The mocap endpoints
+ use a `resolveAuth(req, scope)` helper that tries session then bearer — mirror it.
+- **Migrations:** `api/_lib/migrations/<YYYY-MM-DD>-<slug>.sql`, applied via
+ `npm run db:migrate` (runner: [scripts/apply-migrations.mjs](../../scripts/apply-migrations.mjs);
+ SHA-tracked in `schema_migrations` — never edit an applied file, roll forward). Also mirror the
+ table into [api/_lib/schema.sql](../../api/_lib/schema.sql) for clean deploys.
+- **Closest precedent for user-owned clips:** the `mocap_clips` table + endpoints —
+ [api/mocap/clips.js](../../api/mocap/clips.js), [api/mocap/[id].js](../../api/mocap/[id].js),
+ migration [api/_lib/migrations/2026-05-24-mocap-clips.sql](../../api/_lib/migrations/2026-05-24-mocap-clips.sql).
+ It already has `owner_id`, `avatar_id`, `slug`, `visibility (private|unlisted|public)`,
+ `price_amount`, `price_currency`, `frames jsonb`, `storage_key` (R2 for large), soft-delete.
+ Zod validation, slug uniqueness per owner, avatar-ownership check — copy these patterns.
+- **Monetization (the key reuse):** the platform already sells downloadable assets for USDC:
+ - `paid_assets` table + [api/x402/asset-download.js](../../api/x402/asset-download.js) —
+ "pay once → presigned R2 download", with per-creator payout overrides
+ (`creator_payto_base` / `creator_payto_solana` / `creator_payto_bsc`) and SIWX re-download.
+ - Paid-endpoint helper: [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js)
+ (`paidEndpoint()`), spec/bazaar schema in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js)
+ (`buildBazaarSchema()`, `bazaarExtension()`). Prices are USDC atomics (6 decimals:
+ `1_000_000` = $1.00).
+ - Hosted checkout SKUs: [api/x402-skus.js](../../api/x402-skus.js) → `/pay/c/<slug>`.
+ - Marketplace page + bazaar UI: search the repo for `pages/marketplace*.html` /
+ `public/bazaar.js` and their data APIs.
+
+### Navigation
+- Nav is injected client-side: a page includes `<div id="nav-container"></div>` +
+ `<script src="/nav.js"></script>`; [public/nav.js](../../public/nav.js) fetches
+ [public/nav.html](../../public/nav.html) and wires handlers. `/pose` currently sits in the
+ **Labs** submenu of `nav.html` (~line 270). Promoting it is Task 7.
+
+---
+
+## Rules for every task (do not skip)
+
+- **Follow [CLAUDE.md](../../CLAUDE.md).** No mocks, no fake data, no stubs, no TODOs, no
+ commented-out code, no `setTimeout` fake loading. Real APIs, real wiring, every state designed
+ (loading/empty/error/populated), accessibility, hover/active/focus states.
+- **Read before you write.** Open the referenced files and match existing patterns, naming, and
+ CSS variables/tokens already in the page.
+- **Wire 100%.** Every button works, every link goes somewhere, every state is reachable. No dead
+ paths. Trace the full data flow before writing UI.
+- **Verify in a real browser.** `npm run dev` (port 3000), exercise the feature, confirm no
+ console errors and real network calls succeed. State explicitly what you verified.
+- **Keep the repo root clean.** No throwaway scripts in root (use `scripts/`), no committed
+ scratch files/screenshots.
+- **Run the `completionist` subagent** over your changed files before declaring done; fix
+ everything it flags.
+- **Do not push** unless the user explicitly approves. When they do, push to **both** remotes
+ (`git push threeD main` and `git push threews main`) as per CLAUDE.md. Never pull/fetch from
+ `threeD`.
+- **Tests:** keep `npm test` green; add tests where the existing suite has a matching pattern
+ (e.g. contract tests under `tests/`).
+- At the end of your task, write a short note of what changed and what the **next** task in the
+ sequence should build on, so the next chat has continuity.
diff --git a/prompts/animation-studio/01-avatar-loading-and-rigged-posing.md b/prompts/animation-studio/01-avatar-loading-and-rigged-posing.md
new file mode 100644
index 000000000..141122781
--- /dev/null
+++ b/prompts/animation-studio/01-avatar-loading-and-rigged-posing.md
@@ -0,0 +1,101 @@
+# Task 1 — Load rigged avatars into /pose and pose real skeletons (gizmos + IK)
+
+> Read `prompts/animation-studio/00-README.md` first — it has the shared architecture, file
+> references, data shapes, and the non-negotiable rules. Follow `CLAUDE.md`. No mocks, no stubs,
+> wire 100%, design every state, verify in a real browser.
+
+You are extending the existing Pose Studio at `/pose` so it can pose **real rigged 3D avatars**,
+not just the built-in primitive mannequin. This is the foundation the keyframe timeline (Task 2)
+builds on, so the posing API you expose must be clean and skeleton-agnostic.
+
+## Outcome
+
+A user opening `/pose` can:
+1. Keep using the built-in primitive **mannequin** (current behavior) — this stays the default
+ when no avatar is requested.
+2. Load a **rigged GLB avatar** via the `?avatar=<id>` URL param (works for demo avatar ids like
+ `avatar_demo_disk_saga` and for real avatar ids), and via a **"Load avatar"** button that opens
+ the existing avatar gallery picker (their own avatars when signed in, public/demo otherwise).
+3. **Pose the loaded rig**: select a bone, rotate it with on-screen **gizmos** (TransformControls)
+ and fine sliders, and use **inverse kinematics** — drag a hand or foot and the limb chain solves.
+4. Reset pose, switch back to the mannequin, and read clear status/empty/error states throughout.
+
+## What to build
+
+### 1. Read the existing code first
+- [src/pose-studio.js](../../src/pose-studio.js), [src/pose-mannequin.js](../../src/pose-mannequin.js),
+ [pages/pose.html](../../pages/pose.html). Understand `setupScene()`, the render loop, the
+ raycaster/drag posing, the control panel, and the pose JSON shape.
+- [src/viewer.js](../../src/viewer.js) (~841–887) for the **GLTFLoader + Draco/KTX2/Meshopt decoder
+ setup** — reuse this exact decoder configuration. Do not create a bare loader.
+- [src/avatar-gallery-picker.js](../../src/avatar-gallery-picker.js) — the picker you'll mount.
+- [src/avatar-export.js](../../src/avatar-export.js) for `normalizeBoneName()` — reuse it.
+- [api/_lib/demo-avatars.js](../../api/_lib/demo-avatars.js) for demo ids to test with.
+
+### 2. A skeleton-agnostic "rig" abstraction
+Introduce a small module (e.g. `src/pose-rig.js`) that presents a **uniform posing interface**
+over either the primitive `Mannequin` or a loaded skinned GLB:
+
+- `getBones()` → ordered list of posable bones with a canonical key (use `normalizeBoneName()`),
+ a display label, and the underlying `THREE.Bone`/joint.
+- `getBoneQuaternion(key)` / `setBoneQuaternion(key, quat)` and Euler convenience getters/setters.
+- `getRootPosition()` / `setRootPosition(vec)` (Hips/pelvis translation).
+- `getPose()` / `applyPose(pose)` / `resetPose()` returning a **canonical pose object** keyed by
+ normalized bone names with quaternions (so Task 2 can keyframe any rig uniformly). For the
+ primitive mannequin, map its 16 joints onto the canonical names (pelvis→Hips, head→Head,
+ shoulderL→LeftArm, etc.) so both paths produce the same pose shape.
+- A `bindToTarget` for IK chains (see below).
+
+The point: Task 2's timeline records `getPose()` snapshots and never needs to know whether it's a
+mannequin or a real avatar.
+
+### 3. Avatar loading
+- On boot, read `?avatar=<id>` from the URL. If present, fetch the avatar's GLB URL and load it:
+ - For ids starting with `avatar_demo_`, resolve via the demo-avatars source / the public avatar
+ API. For real ids, use `GET /api/avatars/public` (and `GET /api/avatars` with
+ `credentials: 'include'` when signed in). Resolve to `model_url`.
+ - Load with the reused GLTFLoader+decoders. On success, frame the camera to the model, swap the
+ rig abstraction to the GLB skeleton, and remove/hide the primitive mannequin.
+- **"Load avatar" button** in the toolbar → `new AvatarGalleryPicker({ source: <'mine' if signed
+ in else 'public'>, onSelect })`. On select, load that `model_url` and update the URL (`?avatar=`)
+ without a full reload (history pushState) so the state is shareable.
+- A **"Mannequin"** option to return to the default primitive rig.
+- Handle every state: loading (skeleton/spinner with real progress from GLTFLoader `onProgress`),
+ error (failed fetch / non-rigged GLB → actionable message), empty (signed-out user opening the
+ picker sees public/demo avatars with a sign-in hint).
+
+### 4. Posing UX (the craftsmanship)
+- **Gizmos:** integrate `three/examples/jsm/controls/TransformControls.js` in rotate mode on the
+ selected bone. Disable `OrbitControls` while dragging the gizmo (`dragging-changed` event).
+- **IK:** integrate `three/examples/jsm/animation/CCDIKSolver.js`. Define IK chains for the four
+ limbs (shoulder→forearm→hand with a hand target; upper-leg→leg→foot with a foot target). Add
+ draggable IK target handles so the user can pull a hand/foot and the chain solves. Provide a
+ toggle between **FK** (rotate individual bones) and **IK** (drag end-effectors) posing modes.
+ For the primitive mannequin, map IK chains onto its joints too (best-effort) or cleanly disable
+ IK with an explanatory tooltip if a chain can't be built — never leave a dead toggle.
+- **Bone selection:** keep raycast click-to-select; also add a searchable bone list in the panel
+ for rigs with many bones. Highlight the selected bone.
+- **Sliders:** keep per-axis fine rotation for the selected bone, driven by the rig abstraction.
+- **Presets:** keep the existing presets working for the mannequin; for real rigs, apply presets
+ by mapping canonical bone names (skip bones the rig lacks).
+- Preserve PNG export.
+
+### 5. UI/UX + accessibility
+- Match the page's existing dark design tokens / CSS variables. Add hover/active/focus states and
+ ARIA labels to every new control. Keyboard: `F`/`I` to toggle FK/IK, `R` to reset selected bone,
+ `Esc` to deselect — show these in a small shortcuts hint.
+- Mobile-considerate layout (panels collapse at narrow widths).
+
+## Definition of done
+- `?avatar=avatar_demo_disk_saga` loads a real rigged avatar into `/pose`; "Load avatar" picker
+ works; "Mannequin" returns to default — all verified in the browser with no console errors.
+- A user can select a bone, rotate it via gizmo + sliders, and drag a hand/foot with IK to repose
+ the limb. FK/IK toggle works; no dead controls.
+- `getPose()` returns a canonical, normalized pose object for **both** mannequin and GLB rigs
+ (verify by logging two snapshots). This is the contract Task 2 consumes.
+- Loading/empty/error states all designed and reachable. Network tab shows real avatar fetches.
+- `npm test` still green. Run the `completionist` subagent on changed files; fix all findings.
+- Leave a short handoff note: the rig API surface (method names) Task 2 should call.
+
+Do **not** build the timeline, saving, or monetization here — those are Tasks 2, 4, 6.
+Do not push unless the user explicitly approves (then push to both remotes per CLAUDE.md).
diff --git a/prompts/animation-studio/02-keyframe-timeline-and-export.md b/prompts/animation-studio/02-keyframe-timeline-and-export.md
new file mode 100644
index 000000000..5fdc3b181
--- /dev/null
+++ b/prompts/animation-studio/02-keyframe-timeline-and-export.md
@@ -0,0 +1,98 @@
+# Task 2 — Keyframe timeline, AnimationClip baking, live preview, and export
+
+> Read `prompts/animation-studio/00-README.md` first (shared architecture, clip format, rules).
+> Follow `CLAUDE.md`. No mocks, no stubs, wire 100%, design every state, verify in a real browser.
+>
+> **Depends on Task 1** (`01-avatar-loading-and-rigged-posing.md`): a skeleton-agnostic rig
+> abstraction exposing `getPose()` / `applyPose(pose)` / per-bone quaternion getters/setters for
+> both the primitive mannequin and loaded GLB avatars. Read Task 1's handoff note for the exact
+> method names before starting.
+
+You are turning the poser into an **animation recorder**: the user sets a pose, drops a keyframe on
+a timeline, advances the playhead, re-poses, drops another keyframe — and the studio interpolates
+between keyframes and plays the result. This is how a walk cycle / wave / dance gets authored.
+
+## Outcome
+
+On `/pose`, with a mannequin or rigged avatar loaded, a user can:
+1. Add/move/delete **keyframes** on a timeline scrubber. Each keyframe captures the current pose.
+2. Scrub the playhead and see the rig interpolate between keyframes; **play/pause/loop** the whole
+ animation in real time.
+3. Set animation **duration**, **fps**, per-keyframe **easing**, and **loop** on/off.
+4. **Bake** the keyframes into a `THREE.AnimationClip` whose tracks use canonical bone names — i.e.
+ the exact format that plays everywhere on three.ws (see README "Animation clip format").
+5. **Export** the result as (a) a **GLB with embedded animation** and (b) a three.ws **clip JSON**.
+
+## What to build
+
+### 1. Keyframe data model
+- A keyframe = `{ id, time /* seconds */, pose /* canonical getPose() snapshot */, easing }`.
+- Keep them sorted by time. Adding a keyframe captures `rig.getPose()` at the current playhead.
+ Re-dropping at an existing time updates it. Deleting and dragging-to-retime are supported.
+- Store the editing document as `{ name, duration, fps, loop, keyframes[] }` in module state. This
+ is the in-memory project Task 4 will serialize/save.
+
+### 2. Interpolation + live preview
+Two acceptable approaches — choose one and implement it fully:
+- **(Preferred) Bake-then-mix:** build a `THREE.AnimationClip` from the keyframes (see baking
+ below) and drive it with a `THREE.AnimationMixer`; scrub by `mixer.setTime(t)`; play by ticking
+ `mixer.update(dt)` in the existing render loop. Re-bake when keyframes change (debounced).
+- **Manual interpolation:** between bracketing keyframes, `slerp` each bone quaternion and `lerp`
+ the root position by the eased fraction, then `applyPose()`.
+
+Quaternion interpolation (slerp) for rotations is required — do not lerp Euler angles (gimbal
+artifacts). Apply per-keyframe easing (at minimum: linear, ease-in, ease-out, ease-in-out).
+
+### 3. Baking to a three.ws-compatible AnimationClip
+- For each posed bone, emit a `QuaternionKeyframeTrack` named `"<CanonicalBone>.quaternion"` with
+ `times` = keyframe times and `values` = flattened `[x,y,z,w,...]`. Emit a
+ `VectorKeyframeTrack`/position track `"Hips.position"` for root translation.
+- Use the **canonical Avaturn/Mixamo bone names** from the README (`Hips`, `Spine`, `Head`,
+ `LeftArm`, `RightUpLeg`, ...). The rig abstraction from Task 1 already keys poses by normalized
+ names — map them to these canonical track names so the clip plays on standard three.ws avatars.
+- The baked clip's `.toJSON()` must match the documented clip JSON shape
+ (`{ name, duration, tracks:[{name,type,times,values}] }`). Verify by round-tripping through
+ `AnimationClip.parse()`.
+
+### 4. Timeline UI (the craftsmanship)
+- A horizontal **timeline track** with a draggable **playhead**, time ruler (seconds), and
+ **keyframe diamonds** the user can click to select, drag to retime, and delete.
+- Transport controls: play / pause / stop, loop toggle, jump-to-start/end, current-time readout.
+- Inputs for total **duration** and **fps**; an **easing** picker for the selected keyframe.
+- An **"Add keyframe"** button (and a keyboard shortcut, e.g. `K`) that captures the current pose
+ at the playhead. Visual confirmation when a keyframe is added/updated.
+- **Optional polish (do if time allows, fully wired or omitted):** onion-skinning (ghost the
+ neighbouring keyframe poses) to help align a walk cycle.
+- Empty state: when there are zero keyframes, explain the workflow ("Pose the figure, then press
+ Add keyframe to start your animation"). Never a blank void.
+
+### 5. Export
+- **GLB with animation:** reuse the `GLTFExporter` path from [src/avatar-export.js](../../src/avatar-export.js)
+ (it already passes `animations`). Export the current rig (or a clean skeleton when on the
+ mannequin) with the baked clip embedded; download as `.glb`. The exported file must play its
+ animation when re-opened in the three.ws viewer.
+- **Clip JSON:** download the baked `clip.toJSON()` as a `.json` matching
+ `public/animations/clips/*.json`. This is the artifact that Task 4 saves to the account and Task
+ 5 plays via `AnimationManager`.
+- Both export buttons must have loading + success + error states.
+
+### 6. Provide a clean handoff API for Task 4/5/6
+Expose (in module state or a small exported object): the current editing document, a
+`bake()` returning the `AnimationClip`, `serializeClip()` returning the clip JSON, and a
+`captureThumbnail()` (reuse the existing PNG capture) so Task 4 can save without re-implementing.
+
+## Definition of done
+- A user can build a multi-keyframe animation (e.g. a 4–6 keyframe walk cycle on a rigged avatar),
+ scrub it, and **play it looping** smoothly — verified in the browser, no console errors.
+- Rotations interpolate via slerp (no gimbal popping); easing visibly changes timing.
+- "Export GLB" produces a file that **plays its animation** when loaded in the three.ws viewer
+ (verify by loading the exported GLB). "Export JSON" matches the clip JSON schema and
+ `AnimationClip.parse()` accepts it.
+- Timeline empty/loading/error states designed; every control has hover/active/focus + ARIA.
+- `npm test` green. Add a small unit/contract test for the bake → `toJSON` → `parse` round-trip if
+ the suite has a matching location (e.g. under `tests/`). Run `completionist`; fix all findings.
+- Handoff note: the names of the `bake()`/`serializeClip()`/`captureThumbnail()` accessors Task 4
+ will call, and the editing-document shape.
+
+Do not build account saving or monetization here (Tasks 4 and 6).
+Do not push unless the user explicitly approves (then both remotes per CLAUDE.md).
diff --git a/prompts/animation-studio/03-backend-animation-clips-api.md b/prompts/animation-studio/03-backend-animation-clips-api.md
new file mode 100644
index 000000000..0f5fecbb4
--- /dev/null
+++ b/prompts/animation-studio/03-backend-animation-clips-api.md
@@ -0,0 +1,95 @@
+# Task 3 — Backend: animation_clips table + /api/animations CRUD
+
+> Read `prompts/animation-studio/00-README.md` first (backend patterns, DB/auth/migration
+> conventions, the `mocap_clips` precedent). Follow `CLAUDE.md`. No mocks, real DB, wire 100%.
+>
+> This task is **independent of the frontend** and can run in parallel with Tasks 1–2. Tasks 4, 5,
+> and 6 depend on it.
+
+You are adding the persistence layer for user-created animations: a table and a REST API to
+create, list, read, update, and delete animation clips owned by a user, with public/private
+visibility and fields ready for monetization (Task 6).
+
+**Mirror the existing `mocap_clips` implementation closely** — it already solves auth, ownership,
+slugs, visibility, soft-delete, and large-payload storage. Read it before writing:
+- [api/mocap/clips.js](../../api/mocap/clips.js) (GET list + POST create)
+- [api/mocap/[id].js](../../api/mocap/[id].js) (GET / PATCH / DELETE)
+- [api/_lib/migrations/2026-05-24-mocap-clips.sql](../../api/_lib/migrations/2026-05-24-mocap-clips.sql)
+- [api/_lib/db.js](../../api/_lib/db.js), [api/_lib/auth.js](../../api/_lib/auth.js),
+ [api/_lib/schema.sql](../../api/_lib/schema.sql)
+
+## What to build
+
+### 1. Migration: `animation_clips`
+Create `api/_lib/migrations/<today's date>-animation-clips.sql` (use the real current date,
+`YYYY-MM-DD`). Mirror `mocap_clips` columns and indexes:
+
+- `id uuid pk default gen_random_uuid()`
+- `owner_id uuid not null references users(id) on delete cascade`
+- `avatar_id uuid references avatars(id) on delete set null` (the rig the animation targets)
+- `slug text not null`, `name text not null`, `description text`
+- `kind text not null default 'animation' check (kind in ('animation','loop','sequence'))`
+- `format text not null default 'three.ws.animation.v1'`
+- `duration_ms int not null default 0`, `frame_count int not null default 0`
+- `fps int`, `loop boolean not null default true`
+- `clip jsonb` — the baked `AnimationClip.toJSON()` (see README clip format). For large clips,
+ support `storage_key text` (R2) exactly like `mocap_clips.frames`/`storage_key` does.
+- `thumbnail_key text`
+- `tags text[] not null default '{}'`
+- `visibility text not null default 'private' check (visibility in ('private','unlisted','public'))`
+- `price_amount numeric(30,9)`, `price_currency text` (populated by Task 6; nullable here)
+- `play_count bigint not null default 0`
+- `created_at`, `updated_at`, `deleted_at timestamptz`
+- `unique (owner_id, slug)`
+- Indexes mirroring mocap: owner+created_at (where not deleted), visibility+created_at (where
+ public, not deleted), kind+created_at, and a GIN index on `tags`.
+- `updated_at` trigger using the shared `set_updated_at()` function (guard with the
+ `EXCEPTION WHEN duplicate_object` block like other migrations).
+
+Also add the table definition to [api/_lib/schema.sql](../../api/_lib/schema.sql) after
+`mocap_clips`, so fresh deploys get it. Apply locally with `npm run db:migrate` and confirm via
+`npm run db:status` (do **not** edit the file after it's applied — roll forward).
+
+### 2. API: `api/animations/clips.js` (GET list, POST create)
+- Use a `resolveAuth(req, scope)` helper identical in spirit to mocap's (`getSessionUser` →
+ `authenticateBearer`). Use the avatars scopes already in use (`'avatars:read'` / `'avatars:write'`)
+ unless a more specific scope already exists.
+- **POST create:** validate with `zod` (mirror mocap's `createSchema`). Accept
+ `{ name, slug?, description?, avatar_id?, tags?, visibility?, fps?, loop?, clip: { name, duration,
+ tracks[] } }`. Validate the clip JSON shape (tracks have `name`, `times`, `values`, `type`).
+ Enforce reasonable size limits; if the inline JSON exceeds the inline cap (mirror mocap's
+ threshold), store to R2 and set `storage_key` instead of `clip`. Auto-generate a unique slug if
+ absent. If `avatar_id` is provided, verify the avatar is owned by the caller (mirror mocap's
+ ownership check). Insert with `sql`...`` tagged template; return the created row.
+- **GET list:** mirror mocap's dynamic-WHERE logic — unauthenticated → only `visibility='public'`;
+ authenticated → own clips, plus public when `include_public=true`. Support `limit`, `cursor`
+ (created_at DESC), `visibility`, and a `tag` filter. Never return soft-deleted rows.
+
+### 3. API: `api/animations/[id].js` (GET, PATCH, DELETE)
+- **GET:** return a single clip by id. Private clips → 404 for non-owners; public/unlisted →
+ visible. Optionally increment `play_count` on a query flag (mirror any mocap behavior). Resolve
+ `clip` from R2 when `storage_key` is set (presigned or inlined per mocap's read path).
+- **PATCH:** owner-only; update `name`, `description`, `tags`, `visibility`, `avatar_id` (re-check
+ ownership), `loop`. Do not allow changing `owner_id`.
+- **DELETE:** owner-only **soft delete** (`deleted_at = now()`), mirroring mocap.
+
+### 4. Errors, validation, security
+- Handle all error boundaries: unauthenticated (401), not-owner/not-found (404), validation (400),
+ oversized payload (413/400). Use the same error helper/shape the mocap endpoints use.
+- No SQL injection (tagged templates only). No leaking other users' private clips. Rate/size limits
+ consistent with mocap.
+
+## Definition of done
+- `npm run db:migrate` applies cleanly; `npm run db:status` shows it applied; schema.sql updated.
+- POST creates a clip (verify with a real authenticated request — e.g. via the dev server and a
+ signed-in session, or a documented `curl` using a session cookie/API key). GET lists own +
+ public correctly; private clips are invisible to others. PATCH and soft-DELETE work and respect
+ ownership. Verify each with real requests and paste the responses in your summary.
+- Avatar-ownership check rejects linking an avatar the caller doesn't own.
+- Add contract tests mirroring any existing API test pattern under `tests/` if present.
+- `npm test` green. Run `completionist` on changed files; fix all findings.
+- Handoff note: the exact request/response shapes for create + list + get, so Task 4 (save UI),
+ Task 5 (playback), and Task 6 (monetization) can integrate without guessing.
+
+Do not build UI here. Do not wire payments here (Task 6 adds pricing on top of these rows).
+Do not push unless the user explicitly approves (then both remotes per CLAUDE.md).
diff --git a/prompts/animation-studio/04-save-and-library.md b/prompts/animation-studio/04-save-and-library.md
new file mode 100644
index 000000000..c5b799400
--- /dev/null
+++ b/prompts/animation-studio/04-save-and-library.md
@@ -0,0 +1,89 @@
+# Task 4 — Save animations to account + "My animations" library in the editor
+
+> Read `prompts/animation-studio/00-README.md` first. Follow `CLAUDE.md`. No mocks, real APIs,
+> wire 100%, design every state, verify in a real browser.
+>
+> **Depends on Task 2** (timeline + `bake()`/`serializeClip()`/`captureThumbnail()` accessors and
+> the editing-document shape) and **Task 3** (`/api/animations` CRUD + request/response shapes).
+> Read both tasks' handoff notes before starting.
+
+You are connecting the in-browser animation editor to the user's account: save, load, manage, and
+re-edit animations. This is what makes the studio a real tool instead of a one-shot exporter.
+
+## Outcome
+
+On `/pose`, a signed-in user can:
+1. **Save** the current animation to their account (name, description, tags, visibility, linked
+ avatar, thumbnail) via `POST /api/animations/clips`.
+2. Open a **"My animations"** library (drawer/modal) listing their saved clips with thumbnails,
+ open one back into the editor to continue editing, **update** it (`PATCH`), or **delete** it.
+3. See proper auth handling: a signed-out user who tries to save is prompted to sign in, then
+ returns to their work intact.
+
+## What to build
+
+### 1. Save flow
+- A **"Save"** button in the toolbar. On click:
+ - If not signed in → show a sign-in prompt. Use the existing auth/session mechanism the rest of
+ the app uses (session cookie via `credentials: 'include'`; check how other authed pages detect
+ sign-in — search for the session/me endpoint and the `authenticate-wallet` flow). Do **not**
+ invent a new auth path. Preserve the in-progress editing document across sign-in (e.g. keep it
+ in memory / sessionStorage and restore on return).
+ - If signed in → open a **save dialog**: name (required), description, tags, visibility
+ (private/unlisted/public), and the linked avatar (default to the currently loaded avatar's id
+ when one is loaded; otherwise none/mannequin).
+- On submit: call `serializeClip()` (Task 2) for the `clip` payload, `captureThumbnail()` for the
+ thumbnail, and POST to `/api/animations/clips` with the metadata. Upload the thumbnail using the
+ same mechanism mocap/avatars use for thumbnails (check `thumbnail_key` handling in
+ [api/mocap/clips.js](../../api/mocap/clips.js) / the avatars upload path) — real upload, not a
+ placeholder.
+- After save: switch the editor into "editing saved clip" state (store the returned id), so
+ subsequent saves **PATCH** the existing clip and offer "Save as copy" to create a new one.
+- Loading + success + error states on the save action (disable button while in flight, real
+ spinner, surfaced API errors).
+
+### 2. "My animations" library
+- A button opening a drawer/modal that fetches `GET /api/animations/clips` (own clips; offer a
+ tab/toggle for public/community clips via `include_public=true`).
+- Render each clip as a card: thumbnail, name, duration, visibility badge, tags, updated date.
+ Actions per card: **Open** (loads the clip's keyframes back into the editor — see below),
+ **Rename/edit metadata** (PATCH), **Delete** (soft delete with confirm), **Export**, and (stub
+ the hook for) **Sell** which Task 6 will fully wire.
+- States: loading (skeletons), empty ("You haven't saved any animations yet — create one and press
+ Save" with a clear CTA), error (retry).
+
+### 3. Re-open a saved clip into the editor
+- Opening a saved clip must reconstruct the **editing document** (keyframes/duration/fps/loop), not
+ just play a baked clip. Two paths — pick the one consistent with how Task 2 stored things:
+ - If Task 2 persists the keyframe document (preferred), save that alongside the baked `clip` (add
+ it to the create payload as part of `clip` metadata or a sibling field) so it can be restored
+ losslessly for editing.
+ - Otherwise, reconstruct an editable keyframe document from the baked clip's tracks (sample each
+ track at its keyframe times back into per-bone pose snapshots).
+ Coordinate with Task 2's document shape; if you need to extend the saved payload to make
+ re-editing lossless, do it and update Task 3's create handler/validation accordingly (keep it
+ backward compatible).
+- After opening, the correct avatar/mannequin should be loaded (use the clip's `avatar_id`); if the
+ avatar can't be loaded (deleted/not owned), fall back to the mannequin with a clear notice.
+
+### 4. UX + accessibility
+- Match existing design tokens. Hover/active/focus states + ARIA on every control. Keyboard:
+ `Ctrl/Cmd+S` to save. Confirm-before-delete. Toasts/inline status for save/update/delete results.
+- Optimistic UI is fine but must reconcile with the server response; never show a fake success.
+
+## Definition of done
+- A signed-in user saves an animation; it appears in "My animations" with a real thumbnail; the row
+ exists in `animation_clips` (verify via the API/DB). Re-saving PATCHes; "Save as copy" creates a
+ new clip.
+- Opening a saved clip restores an **editable** animation (keyframes intact) on the right rig, then
+ plays correctly.
+- Signed-out save prompts sign-in and restores the in-progress work afterward.
+- Rename/edit-metadata and delete work and respect ownership (verify a second account can't see
+ private clips).
+- All states designed; no console errors; network tab shows real `/api/animations` calls.
+- `npm test` green. Run `completionist`; fix all findings.
+- Handoff note: confirm the saved payload shape (esp. how the editable keyframe document is stored)
+ for Task 5 (playback) and Task 6 (selling).
+
+Do not implement payments/pricing here — leave the "Sell" affordance as a clearly-labeled hook for
+Task 6. Do not push unless the user explicitly approves (then both remotes per CLAUDE.md).
diff --git a/prompts/animation-studio/05-playback-across-platform.md b/prompts/animation-studio/05-playback-across-platform.md
new file mode 100644
index 000000000..e9684bfb9
--- /dev/null
+++ b/prompts/animation-studio/05-playback-across-platform.md
@@ -0,0 +1,67 @@
+# Task 5 — Make saved/public animations play across three.ws
+
+> Read `prompts/animation-studio/00-README.md` first (clip format, `AnimationManager`, viewer).
+> Follow `CLAUDE.md`. No mocks, real APIs, wire 100%, design every state, verify in a real browser.
+>
+> **Depends on Task 3** (`/api/animations` CRUD; clip JSON resolvable by id/slug). Benefits from
+> Task 4 (clips actually exist to test with). Read their handoff notes first.
+
+The animations a user creates must not be trapped in the editor. This task makes any
+saved/public animation **playable anywhere three.ws renders an avatar**, using the existing
+`AnimationManager` playback engine — and adds a public gallery to discover community animations.
+
+## What to build
+
+### 1. Load user animations into the playback engine
+- The playback engine is [src/animation-manager.js](../../src/animation-manager.js)
+ (`setAnimationDefs`, `attach`, `ensureLoaded`, `play`, `crossfadeTo`, `update`). Built-in clips
+ come from [public/animations/manifest.json](../../public/animations/manifest.json). Read how
+ [src/viewer.js](../../src/viewer.js) wires the manager to a loaded avatar (~lines 1545–1612).
+- Add a path for the manager to load a **user/public animation by id or slug** from the API
+ (`GET /api/animations/clips/:id` / list), parsing the stored `AnimationClip.toJSON()` with
+ `AnimationClip.parse()` and registering it as an animation def (give it a name/label/icon/loop
+ consistent with manifest entries). Reuse the manager's existing caching/lazy-load — extend it,
+ don't fork it.
+- Filter tracks to bones present on the target model (the manager/viewer already has a clip-filter
+ helper — reuse it) so a clip authored on one rig degrades gracefully on another.
+
+### 2. Play a specific animation in the viewer / on avatar pages
+- Support a URL param on the viewer/avatar page (e.g. `?anim=<id|slug>`) that, after the avatar
+ loads, fetches and plays that animation via the manager. Mirror how the viewer already
+ `ensureLoaded('idle')` / `play()`s built-ins.
+- Where avatars are shown with an animation control panel, list the user's saved animations (when
+ signed in) and public ones alongside the built-in clips so they're selectable. Real fetch, real
+ playback — design loading/empty/error states for that list.
+- Ensure embeds keep working: if there's a gesture/postMessage API in the viewer
+ (`onGesture`), allow triggering a user animation by id through the same channel.
+
+### 3. Public animation gallery
+- Add a gallery view (a page or a clearly-linked section) listing **public** animations
+ (`GET /api/animations/clips?include_public=true` filtered to public, or a public list endpoint
+ consistent with Task 3). Each card: thumbnail, name, author, duration, tags, a live preview
+ (play on hover/click on a small viewer), and links to **open in the studio** (`/pose?...`) and to
+ the seller flow when priced (Task 6).
+- Reuse existing gallery/card patterns and the viewer/preview components already in the repo rather
+ than inventing new ones. Match design tokens. Design loading (skeletons), empty, and error states.
+- Cross-link: from an avatar page, "Animate this avatar" → opens `/pose?avatar=<id>`; from a public
+ animation, "Use on my avatar" → opens the studio with that animation loaded.
+
+### 4. Correctness
+- `play_count` increments on real plays where Task 3 exposed that (don't double-count scrubbing).
+- A private animation is never playable/listable by non-owners. A public one is.
+- Clips authored on the primitive mannequin (canonical bone names) must still apply to standard
+ rigged avatars — verify a mannequin-authored clip plays on a real avatar.
+
+## Definition of done
+- A saved animation plays on a rigged avatar in the viewer via `?anim=<id>` — verified in browser,
+ no console errors, real network calls.
+- The animation control panel lists and plays user/public animations next to built-ins.
+- The public gallery lists real public animations with working previews and correct empty/loading/
+ error states; cross-links to the studio and back work.
+- Visibility is enforced (private clips invisible/unplayable to others).
+- `npm test` green. Run `completionist`; fix all findings.
+- Handoff note: how a clip is addressed for playback (id/slug + any param), for Task 6's
+ post-purchase "play/download" UX.
+
+Do not build payments here (Task 6). Do not push unless the user explicitly approves (then both
+remotes per CLAUDE.md).
diff --git a/prompts/animation-studio/06-monetization.md b/prompts/animation-studio/06-monetization.md
new file mode 100644
index 000000000..69f1c5dba
--- /dev/null
+++ b/prompts/animation-studio/06-monetization.md
@@ -0,0 +1,92 @@
+# Task 6 — Monetize animations: sell for USDC via x402, list in marketplace + bazaar
+
+> Read `prompts/animation-studio/00-README.md` first (x402 patterns, `paid_assets` +
+> `asset-download.js`, payout overrides, bazaar schema). Follow `CLAUDE.md`. No mocks, real
+> payments rails, wire 100%, design every state, verify in a real browser.
+>
+> **Depends on Task 3** (`animation_clips` rows with `price_amount`/`price_currency`) and **Task 4**
+> (clips saved to accounts + the "Sell" hook in the library). Benefits from Task 5 (playback for
+> previews/post-purchase). Read their handoff notes first.
+
+You are letting creators **sell** the animations they make. The platform already sells downloadable
+assets for USDC — **reuse that machinery**, don't build a parallel one.
+
+Read these before writing:
+- [api/x402/asset-download.js](../../api/x402/asset-download.js) — the "pay once → presigned R2
+ download" endpoint, with per-creator payout overrides + SIWX re-download. This is your template.
+- [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) — `paidEndpoint()` helper.
+- [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js) — `buildBazaarSchema()`, `bazaarExtension()`,
+ payment requirement structs (prices are **USDC atomics**, 6 decimals: `1_000_000` = $1.00).
+- [api/x402-skus.js](../../api/x402-skus.js) — hosted checkout SKUs → `/pay/c/<slug>`.
+- The marketplace page + bazaar UI and their data APIs (search `pages/marketplace*.html`,
+ `public/bazaar.js`, `api/bazaar/*`).
+- Payout config + per-asset overrides in [api/_lib/env.js](../../api/_lib/env.js)
+ (`X402_PAY_TO_*`, `creator_payto_base/solana/bsc`).
+
+## What to build
+
+### 1. Pricing an animation (creator side)
+- In the "My animations" library (Task 4), wire the **"Sell"** affordance into a real flow: set a
+ **price** (USDC) and the **payout wallet(s)** (Base / Solana), then publish for sale.
+- Publishing for sale must:
+ - Set `price_amount` / `price_currency` on the `animation_clips` row (Task 3 added these), and
+ set visibility appropriately (a priced clip should be discoverable — `public`/`unlisted` as the
+ UI specifies; gate the actual file behind payment, not behind listing visibility).
+ - Make the clip's downloadable artifact available to the paid endpoint. Decide the artifact:
+ the **GLB with embedded animation** (preferred for broad compatibility) and/or the clip JSON.
+ Store it in R2 the way `paid_assets` stores files, and capture the per-creator payout addresses.
+ If reusing the `paid_assets` table is the cleanest fit, create the `paid_assets` row from the
+ animation (link it back to the `animation_clips.id`); otherwise add the needed columns to
+ `animation_clips` and serve from there. Choose the approach that **minimizes divergence** from
+ `asset-download.js` and document it.
+- Let the creator set/rotate price, unpublish, and see basic **earnings/stats** (mirror the stats
+ pattern in [api/x402-skus.js](../../api/x402-skus.js) — paid calls, revenue, recent txs).
+
+### 2. Paid download endpoint
+- Add `api/x402/animation-download.js` modeled directly on `asset-download.js`:
+ - `GET /api/x402/animation-download?id=<id>` (or `?slug=`). Look up the priced animation; if not
+ priced/published, 404.
+ - Wrap with `paidEndpoint()`: price from the row's atomics, networks Base + Solana, payout via the
+ per-creator override (`buildPayToOverride`-style), bazaar extension via `buildBazaarSchema()`.
+ - On payment: presign the R2 artifact (GLB/JSON) and return `{ ok, title, mimeType, sizeBytes,
+ downloadUrl, expiresAt }` exactly like `asset-download.js`. Wire **SIWX re-download** so buyers
+ re-download without re-paying (reuse the `siwx_payments` flow).
+ - Increment a purchase counter / record the checkout call for stats.
+
+### 3. Buyer experience
+- On the public gallery / animation detail (Task 5) and in the marketplace, a priced animation shows
+ its price and a **Buy** button that runs the existing x402 payment flow (reuse the drop-in
+ payment modal / SKU checkout used elsewhere — search for the existing client payment widget;
+ do not hand-roll wallet signing). After payment, the buyer can **download** the GLB/JSON and
+ **play** it (link into Task 5's playback / "use on my avatar").
+- Optionally create a hosted SKU (`/pay/c/<slug>`) per the `x402-skus.js` pattern so creators get a
+ shareable checkout link. If you add it, wire it fully (creation + the `/pay/c/<slug>` page render).
+- States: price display, buy in-flight, payment success (download + play CTA), payment
+ error/cancel (recoverable), already-purchased (SIWX → free re-download).
+
+### 4. Listing in marketplace + bazaar
+- Make priced animations appear in the **marketplace** (whatever data source the marketplace page
+ reads — add animations to it with title, price, seller, thumbnail, category "Animation") and
+ discoverable in the **bazaar** via the `bazaarExtension()`/`buildBazaarSchema()` declaration on
+ the paid endpoint so x402 discovery validation passes.
+- Cross-link: marketplace card → animation detail/preview (Task 5) → Buy. No dead links.
+
+## Definition of done
+- A creator can price + publish an animation; the row carries `price_amount`/`price_currency` and a
+ per-creator payout address; the artifact is in R2.
+- `GET /api/x402/animation-download?id=...` returns a real 402 challenge with the correct price and
+ payout, and — after a real payment on a test network/wallet — returns a working presigned
+ download. SIWX re-download works without re-paying. **Verify the 402 challenge and the post-
+ payment response with real requests and paste them.** (If a live settlement can't be performed in
+ the environment, demonstrate the 402 envelope + verify path and document exactly what a real
+ payment would complete — but do not fake a settlement.)
+- The animation appears in the marketplace and validates in the bazaar discovery schema.
+- Buyer flow works end-to-end in the browser: see price → Buy → pay → download + play. All states
+ designed; no console errors.
+- Creator earnings/stats reflect real checkout records.
+- `npm test` green. Run `completionist`; fix all findings.
+- Handoff note: anything Task 7 should cross-link (marketplace entry points, gallery, studio).
+
+Reuse the existing x402 facilitator/settlement rails and payout config — never mock a payment, a
+settlement, or an on-chain tx. Do not push unless the user explicitly approves (then both remotes
+per CLAUDE.md).
diff --git a/prompts/animation-studio/07-nav-promotion-and-polish.md b/prompts/animation-studio/07-nav-promotion-and-polish.md
new file mode 100644
index 000000000..53997ef17
--- /dev/null
+++ b/prompts/animation-studio/07-nav-promotion-and-polish.md
@@ -0,0 +1,76 @@
+# Task 7 — Promote the studio in nav, add page chrome, cross-link, final QA
+
+> Read `prompts/animation-studio/00-README.md` first (nav injection, page-chrome pattern). Follow
+> `CLAUDE.md`. No mocks, wire 100%, design every state, verify in a real browser.
+>
+> **Depends on Tasks 1–6.** This is the integration + polish pass that makes the Animation Studio a
+> first-class, discoverable platform feature. Read each prior task's handoff note.
+
+The studio is now functional but the page is still a bare canvas buried in the **Labs** submenu
+with no shared header/nav/footer. This task gives it real platform chrome, promotes it, wires every
+cross-link, and runs a final quality audit.
+
+## What to build
+
+### 1. Page chrome on `/pose`
+- Add the shared **nav** to [pages/pose.html](../../pages/pose.html): include
+ `<div id="nav-container"></div>` + `<script src="/nav.js"></script>` and the site header wrapper,
+ matching how an existing full page does it (e.g. study `pages/avatar-page.html` — its header,
+ nav-container, footer, and the CSS it links: `/nav.css` is already present; add `/footer.css`).
+- Add the shared **footer** (copy the structure used by other pages; include the newsletter script
+ if other pages do). Ensure the 3D canvas + studio panels still lay out correctly **with** the
+ header/footer present (the studio currently assumes full-viewport; adjust so it sits in the page
+ shell without clipping or scroll-jank, responsive at 320 / 768 / 1440).
+
+### 2. Rename + promote
+- The page is currently "Pose Studio" in `nav.html` (~line 270, under Labs). Rename to
+ **"Animation Studio"** (keep `/pose` as the route; it's already public-facing and SEO-indexed —
+ do not break the URL). Update the page `<title>`, OG/Twitter meta, and `<meta name="description">`
+ in `pages/pose.html` to describe the animation authoring + marketplace capabilities.
+- **Promote it out of Labs** into a prominent menu: add a top-level or **Build**-menu entry in
+ [public/nav.html](../../public/nav.html) (study the existing nav-item / submenu markup and copy
+ it exactly — title + subtitle spans, `role="menuitem"`). Decide whether to keep a Labs entry too;
+ if you remove it from Labs, make sure there are no orphaned references. Verify the nav still
+ renders and is keyboard-navigable after the edit.
+
+### 3. Cross-linking (make it feel like one product)
+Wire every natural connection (no dead links):
+- **Avatar pages / gallery / dashboard:** an "Animate" / "Create animation" action that opens
+ `/pose?avatar=<id>` for that avatar.
+- **Public animation gallery (Task 5):** links into the studio and to buy/play.
+- **Marketplace (Task 6):** animation listings link to their detail/preview and Buy.
+- **Studio → account:** the "My animations" library and (if signed in) a link to the user's
+ dashboard/marketplace seller view.
+- **Docs/features:** add the Animation Studio to the features list / docs where other features are
+ catalogued (search for `public/features.json` and the features page) with accurate copy.
+
+### 4. Final QA — run the self-review + completionist protocol over the whole feature
+Exercise the full flow in a real browser and confirm:
+- Open `/pose` cold (no params) → mannequin loads, nav + footer present, no console errors.
+- `?avatar=<id>` and the picker load real rigged avatars; FK/IK posing works.
+- Build a multi-keyframe animation, scrub + play it looping.
+- Export GLB (plays its animation on re-open) and clip JSON.
+- Sign in → Save → appears in "My animations"; reopen → keyframes restored; PATCH + delete work.
+- Saved/public animation plays in the viewer via `?anim=<id>`; public gallery works.
+- Price + publish an animation; it lists in marketplace + bazaar; the paid download endpoint serves
+ a real 402 and post-payment download (per Task 6's verification note).
+- Every interactive element has hover/active/focus; every list has loading/empty/error states;
+ responsive at 320/768/1440; keyboard shortcuts documented in-UI; ARIA on controls.
+- `npm test` green. Run the `completionist` subagent across **all** files touched by Tasks 1–7 and
+ fix everything it flags.
+
+### 5. Documentation
+- Update any READMEs/docs that enumerate routes or features to include the Animation Studio. Per the
+ project's docs-mirror note, if you edit `docs/`, sync the corresponding `public/docs/` mirror.
+
+## Definition of done
+- `/pose` is a fully-chromed, discoverable, prominently-linked **Animation Studio** with working
+ nav/header/footer, responsive at all three breakpoints, zero console errors.
+- Every cross-link in section 3 exists and works; no dead paths anywhere in the feature.
+- The end-to-end flow (load avatar → animate → save → play across platform → sell → buy) works in a
+ real browser; you've exercised it and can describe what you verified.
+- `npm test` green; `completionist` clean.
+- Summarize the shipped feature and call out anything intentionally deferred.
+
+This is the last task. When the user approves, push to **both** remotes (`git push threeD main`
+then `git push threews main`) per CLAUDE.md. Never pull/fetch from `threeD`.
diff --git a/src/home-live-token.js b/src/home-live-token.js
index f17594892..0d57f9420 100644
--- a/src/home-live-token.js
+++ b/src/home-live-token.js
@@ -1,23 +1,21 @@
/**
* Live token card (homepage) — real pump.fun token + live buy/sell flow.
*
- * Picks an actively-trading bonding-curve coin from pump.fun's trending feed,
- * renders it in the token card, then streams its real trades over SSE
- * (/api/pump/trades-stream). Buys render green, sells red. No sample data:
- * every row is a real on-chain trade. Loading, empty, and error states are all
- * designed.
+ * Features a real trending pump.fun coin in the token card, then polls its
+ * recent on-chain trades (/api/pump/coin-trades, proxied from pump.fun's swap
+ * API) and renders them as a live feed: buys green, sells red. No sample data —
+ * every row is a real trade. Loading, empty, and error states are all designed.
*
- * Graduated coins trade on Raydium, not the bonding curve, so PumpPortal emits
- * no trade events for them — we filter them out and pick a live curve coin.
+ * Polling (not SSE) because pump.fun's per-mint trade websocket no longer
+ * delivers reliably; the REST trades endpoint covers both bonding-curve and
+ * migrated (AMM) trades and is rock-solid.
*/
-const TRENDING_URL =
- '/api/pump/trending?sort=last_trade_timestamp&order=DESC&limit=40';
-const TRENDING_FALLBACK_URL = '/api/pump/trending?limit=40';
-const STREAM_URL = (mint) =>
- `/api/pump/trades-stream?mint=${encodeURIComponent(mint)}`;
+const TRENDING_URL = '/api/pump/trending?limit=24';
+const TRADES_URL = (mint, limit = 30) =>
+ `/api/pump/coin-trades?mint=${encodeURIComponent(mint)}&limit=${limit}`;
const MAX_ROWS = 6;
-const RECONNECT_DELAY_MS = 2500;
+const POLL_MS = 4000;
function esc(s) {
return String(s ?? '').replace(
@@ -49,7 +47,8 @@ function usdFmt(n) {
if (!isFinite(v) || v <= 0) return null;
if (v >= 1_000_000) return `$${(v / 1_000_000).toFixed(1)}M`;
if (v >= 1_000) return `$${(v / 1_000).toFixed(1)}K`;
- return `$${v.toFixed(0)}`;
+ if (v >= 1) return `$${v.toFixed(0)}`;
+ return `$${v.toFixed(2)}`;
}
function relTime(tsMs) {
@@ -58,32 +57,35 @@ function relTime(tsMs) {
if (secs < 60) return `${secs}s ago`;
const mins = Math.round(secs / 60);
if (mins < 60) return `${mins}m ago`;
- return `${Math.round(mins / 60)}h ago`;
+ const hrs = Math.round(mins / 60);
+ if (hrs < 24) return `${hrs}h ago`;
+ return `${Math.round(hrs / 24)}d ago`;
}
class HomeLiveToken {
constructor(root) {
this.root = root;
+ // The label sits just outside the card container; resolve by id so it
+ // updates too. The rest live inside the card.
+ const q = (id) => root.querySelector(`#${id}`) || document.getElementById(id);
this.el = {
- label: root.querySelector('#hlt-label'),
- avatar: root.querySelector('#hlt-avatar'),
- name: root.querySelector('#hlt-name'),
- ticker: root.querySelector('#hlt-ticker'),
- price: root.querySelector('#hlt-price'),
- rows: root.querySelector('#hlt-rows'),
- link: root.querySelector('#hlt-pump-link'),
+ label: q('hlt-label'),
+ avatar: q('hlt-avatar'),
+ name: q('hlt-name'),
+ ticker: q('hlt-ticker'),
+ price: q('hlt-price'),
+ rows: q('hlt-rows'),
+ link: q('hlt-pump-link'),
};
this.coin = null;
- this.es = null;
- this.trades = []; // { isBuy, sol, usd, trader, ts, sig }
- this.firstMc = null;
- this.lastMc = null;
- this.reconnectTimer = null;
+ this.trades = []; // { isBuy, sol, usd, price, trader, ts, tx }
+ this.seen = new Set();
+ this.pollTimer = null;
this.tickTimer = null;
+ this.failCount = 0;
this.visible = false;
this.destroyed = false;
this.started = false;
- this.idleTimer = null;
}
async start() {
@@ -100,7 +102,7 @@ class HomeLiveToken {
this.coin = coin;
this._renderHeader(coin);
this._armIdleState();
- this._connect();
+ this._poll();
this.tickTimer = setInterval(() => this._refreshTimes(), 4000);
} catch {
if (!this.destroyed) this._renderError('Could not reach the live feed.');
@@ -108,101 +110,89 @@ class HomeLiveToken {
}
async _pickCoin() {
- const pick = (arr) => {
- const list = Array.isArray(arr) ? arr : arr?.coins || [];
- const live = list.filter(
- (c) => c && c.mint && c.symbol && !c.complete && !c.raydium_pool,
- );
- live.sort(
- (a, b) =>
- (b.last_trade_timestamp || 0) - (a.last_trade_timestamp || 0),
- );
- return live[0] || list.find((c) => c && c.mint && c.symbol) || null;
- };
- const r1 = await fetch(TRENDING_URL, { headers: { accept: 'application/json' } });
- if (r1.ok) {
- const got = pick(await r1.json());
- if (got && !got.complete) return got;
- // Older proxy ignores the sort param and returns graduated whales.
- // Retry the plain list and keep whichever has a live bonding curve.
- const r2 = await fetch(TRENDING_FALLBACK_URL, {
- headers: { accept: 'application/json' },
- });
- if (r2.ok) {
- const alt = pick(await r2.json());
- if (alt) return alt;
- }
- return got;
+ let r;
+ try {
+ r = await fetch(TRENDING_URL, { headers: { accept: 'application/json' } });
+ } catch {
+ return null;
}
- return null;
+ if (!r.ok) return null;
+ const data = await r.json();
+ const list = Array.isArray(data) ? data : data?.coins || [];
+ // Prefer a coin with an image and a real market cap; fall back to any with
+ // a mint + symbol so the card is never empty.
+ const usable = list.filter((c) => c && c.mint && c.symbol);
+ const withImg = usable.filter((c) => c.image_uri);
+ return withImg[0] || usable[0] || null;
}
- // ── Connection ────────────────────────────────────────────────────────────
+ // ── Polling ─────────────────────────────────────────────────────────────────
- _connect() {
- if (this.destroyed || !this.coin || !this.visible) return;
- this._teardownStream();
- const es = new EventSource(STREAM_URL(this.coin.mint));
- this.es = es;
- es.addEventListener('trade', (e) => {
- try {
- this._onTrade(JSON.parse(e.data));
- } catch {
- /* malformed frame — skip */
- }
+ _poll() {
+ if (this.destroyed || !this.coin) return;
+ clearTimeout(this.pollTimer);
+ this._fetchTrades().finally(() => {
+ if (this.destroyed || !this.visible) return;
+ this.pollTimer = setTimeout(() => this._poll(), POLL_MS);
});
- es.addEventListener('close', () => this._scheduleReconnect());
- es.onerror = () => {
- // EventSource auto-retries, but the server caps stream duration; force a
- // clean reconnect so we don't sit on a dead socket.
- this._scheduleReconnect();
- };
}
- _scheduleReconnect() {
- this._teardownStream();
- if (this.destroyed || !this.visible) return;
- clearTimeout(this.reconnectTimer);
- this.reconnectTimer = setTimeout(() => this._connect(), RECONNECT_DELAY_MS);
+ async _fetchTrades() {
+ let resp;
+ try {
+ resp = await fetch(TRADES_URL(this.coin.mint), { headers: { accept: 'application/json' } });
+ } catch {
+ this._onPollFail();
+ return;
+ }
+ if (!resp.ok) {
+ this._onPollFail();
+ return;
+ }
+ let data;
+ try {
+ data = await resp.json();
+ } catch {
+ this._onPollFail();
+ return;
+ }
+ const incoming = Array.isArray(data?.trades) ? data.trades : [];
+ this.failCount = 0;
+ this._ingest(incoming);
}
- _teardownStream() {
- if (this.es) {
- try {
- this.es.close();
- } catch {
- /* already closed */
- }
- this.es = null;
+ _onPollFail() {
+ this.failCount += 1;
+ // Only surface an error once we've truly failed repeatedly and have nothing
+ // to show — a single blip shouldn't wipe a populated feed.
+ if (this.failCount >= 3 && !this.trades.length) {
+ this._renderError('Live trades are momentarily unavailable.');
}
- clearTimeout(this.reconnectTimer);
}
- _onTrade(d) {
- if (this.destroyed) return;
- const sol =
- typeof d.sol_amount === 'number'
- ? d.sol_amount
- : typeof d.solAmount === 'number'
- ? d.solAmount
- : 0;
- if (sol <= 0) return;
- const isBuy = d.is_buy === true || d.txType === 'buy' || d.tx_type === 'buy';
- const mc = typeof d.market_cap_usd === 'number' ? d.market_cap_usd : null;
- if (mc) {
- if (this.firstMc == null) this.firstMc = mc;
- this.lastMc = mc;
+ _ingest(incoming) {
+ // Upstream returns newest-first. Add any unseen trades, keep newest MAX_ROWS.
+ const fresh = [];
+ for (const t of incoming) {
+ if (!t.tx || this.seen.has(t.tx)) continue;
+ this.seen.add(t.tx);
+ fresh.push({
+ isBuy: t.is_buy === true,
+ sol: Number(t.sol_amount) || 0,
+ usd: t.usd_amount != null ? Number(t.usd_amount) : null,
+ price: t.price_usd != null ? Number(t.price_usd) : null,
+ trader: t.user || '',
+ ts: t.timestamp ? Date.parse(t.timestamp) : Date.now(),
+ tx: t.tx,
+ });
}
- this.trades.unshift({
- isBuy,
- sol,
- usd: typeof d.sol_value_usd === 'number' ? d.sol_value_usd : null,
- trader: d.trader || d.traderPublicKey || '',
- ts: Date.now(),
- sig: d.signature || d.tx_signature || '',
- });
- if (this.trades.length > MAX_ROWS) this.trades.length = MAX_ROWS;
- clearTimeout(this.idleTimer);
+ if (!fresh.length && this.trades.length) return;
+ // Merge, sort newest-first, cap.
+ this.trades = [...fresh, ...this.trades]
+ .sort((a, b) => b.ts - a.ts)
+ .slice(0, MAX_ROWS);
+ // Keep the seen-set from growing unbounded.
+ if (this.seen.size > 400) this.seen = new Set(this.trades.map((t) => t.tx));
this._renderRows();
this._renderPrice();
}
@@ -238,8 +228,7 @@ class HomeLiveToken {
if (this.el.avatar) {
const img = coin.image_uri;
if (img) {
- this.el.avatar.innerHTML = '';
- this.el.avatar.style.background = '#111';
+ this.el.avatar.textContent = '';
const im = new Image();
im.src = img;
im.alt = name;
@@ -264,17 +253,24 @@ class HomeLiveToken {
_renderPrice() {
const p = this.el.price;
if (!p) return;
- if (this.firstMc != null && this.lastMc != null && this.firstMc > 0) {
- const pct = ((this.lastMc - this.firstMc) / this.firstMc) * 100;
- const up = pct >= 0;
- p.textContent = `${up ? '+' : ''}${pct.toFixed(1)}%`;
- p.className = `token-price ${up ? 'up' : 'down'}`;
- p.title = 'Change since this card started streaming';
- } else {
- const mc = usdFmt(this.coin?.usd_market_cap);
- p.textContent = mc ? `${mc} MC` : 'Live';
- p.className = 'token-price';
+ // Recent price change from the trades we're showing (newest vs oldest in
+ // the live window). Real, derived from on-chain prices.
+ const priced = this.trades.filter((t) => t.price > 0);
+ if (priced.length >= 2) {
+ const newest = priced[0].price;
+ const oldest = priced[priced.length - 1].price;
+ if (oldest > 0) {
+ const pct = ((newest - oldest) / oldest) * 100;
+ const up = pct >= 0;
+ p.textContent = `${up ? '+' : ''}${pct.toFixed(1)}%`;
+ p.className = `token-price ${up ? 'up' : 'down'}`;
+ p.title = 'Price change across the latest trades';
+ return;
+ }
}
+ const mc = usdFmt(this.coin?.usd_market_cap);
+ p.textContent = mc ? `${mc} MC` : 'Live';
+ p.className = 'token-price';
}
_renderRows() {
@@ -341,17 +337,16 @@ class HomeLiveToken {
this.visible = v;
if (v) {
if (!this.started) this.start();
- else if (!this.es) this._connect();
+ else this._poll();
} else {
- this._teardownStream();
+ clearTimeout(this.pollTimer);
}
}
destroy() {
this.destroyed = true;
- this._teardownStream();
+ clearTimeout(this.pollTimer);
clearInterval(this.tickTimer);
- clearTimeout(this.idleTimer);
}
}