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: add admin seeder control room and API integration
qbdz16c3428c3271
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 654a3cdff..854ece508 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Diorama** (`/diorama`) — Speak a little world into being — describe a scene and watch it assemble into an explorable 3D diorama you can walk through, then take it into AR.- **Mocap Studio** (`/mocap-studio`) — Drive a 3D avatar with your webcam — real-time facial motion capture in the browser, no rig and no download.- **Talking Avatar Video** (`/create/video`) — Turn a three.ws avatar into a talking-head video: type a script, pick a voice, and export a lip-synced clip.+- **Diorama is live — speak a little 3D world into being** — Diorama is now a real, reachable page at three.ws/diorama. Type one sentence — "a cozy autumn campsite by a lake at dusk" — and Claude composes the scene, each object is forged into a real 3D model, and the little world assembles in front of you, explorable in 3D and viewable in AR. Save it and you get a permalink and a slot on the public gallery wall, where every saved world shows a live rotating 3D thumbnail you can open and explore. Share it as a 3D postcard: copy the link, post to X, or grab an embed snippet. Nothing is a screenshot — it's all real geometry forged from your words. (`/diorama`) `[feature]`+- **Labs — a home for the hidden gems most people never find** — There's a new Labs page at three.ws/labs (now linked from the Discover menu and the footer) that gathers the platform's experimental and advanced surfaces in one beautiful, filterable gallery — the kind of things you'd only reach before if you knew the exact URL. Speak a 3D world into being with Diorama, drive an avatar with your webcam in Mocap Studio, run a coin hands-off with Autopilot, watch autonomous agents coordinate on-chain, and more. Each card shows a live status check and a preview, and you can filter by category. Everything featured is real and live. (`/labs`) `[feature]`+- **The autonomous sniper now has a live web console** — Run agent-sniper serve and open it in a browser: a real-time operator dashboard, built right into the engine. Watch buys, sells, candidates and signals tick up live; see every open position with its entry, current value and colored profit-and-loss, and close any of them in one click; review your armed strategies with their stop-loss and take-profit at a glance; arm a new strategy or fire a manual snipe from clean forms; and read a live activity feed of everything the engine is doing. It has designed loading, empty and error states, toasts, keyboard shortcuts and a full mobile layout. Reads are free to anyone; to run the controls yourself without paying, set an operator token that bypasses the x402 paywall for you while external agents still pay per call. (`/docs/mcp`) `[feature, sdk]`+- **The Trading Brain is redesigned — presets, a live risk meter, and a real backtest breakdown** — Building your agent's sniper is now a minute, not a manual. Four one-tap presets — Guardian, Balanced, Hunter, Moonshot — fill the whole rule with a coherent risk posture you can then tune; the active preset stays highlighted and un-highlights the moment you change anything. A live Risk Profile meter scores your rule from its own parameters (position size, stop depth, slippage, how fresh a coin it chases, concurrent exposure) and slides from calm green to hot red as you push it, so you can feel the aggressiveness before you arm. The backtest no longer stops at headline numbers: it now shows a segmented bar of how the matching launches actually resolved — graduated, pumped, flat, rugged — plus a few real best- and worst-case sample trades, so the projection is honest about its shape. Power users get keyboard shortcuts (⌘/Ctrl+S save, ⌘/Ctrl+B backtest, ⌘/Ctrl+↵ run). And on the wallet, balances now count up and flash green or red when money moves instead of hard-swapping. Every animation respects reduced-motion. (`/agent-studio`) `[improvement, feature]`+- **The x402 page is now a live, searchable storefront** — three.ws/x402 is rebuilt as a live catalog. Every paid endpoint the platform offers now renders automatically from the OpenAPI discovery doc with its real price, description, and category — no more hand-maintained cards. Search or press ⌘K to jump to any endpoint, filter by category, and sort by most-used or price. Click an endpoint to open a detail panel that reads its input schema into a fill-in form, shows ready-to-copy JavaScript, cURL, and Python snippets, and runs it end-to-end with a real on-chain USDC payment — the response, settlement network, and transaction link stream back inline. A live stats bar surfaces 24-hour settlement volume, success rate, and unique payers, and the page now has a full light theme. (`/x402`) `[feature, improvement]`- **The x402 toolkit is now on npm and the VS Code Marketplace** — The x402 buyer, seller, browser-modal and MCP libraries are published as standalone, provider-neutral npm packages you can use in any project without a three.ws account: @three-ws/x402-fetch (drop-in fetch that auto-pays a 402 in USDC), @three-ws/x402-server (build paid endpoints), @three-ws/x402-modal and @three-ws/x402-payment-modal (drop-in browser checkout), and @three-ws/x402-mcp and @three-ws/ibm-x402-mcp (pay or sell from any MCP client). There's also a new x402 extension for VS Code — inspect, pay, and scaffold paid endpoints from the editor — on both the VS Code Marketplace and Open VSX. The docs now carry install commands, one-line summaries, repo links, and a Node code sample in the pay-for-a-service tutorial. (`/x402`) `[sdk, docs]`## 2026-06-30diff --git a/STRUCTURE.md b/STRUCTURE.mdindex c7813a54c..20625af74 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -20,6 +20,8 @@ bottom.| Talking page guide | [page-agent-sdk/](page-agent-sdk) | Published as `@three-ws/page-agent` | Drop-in rigged 3D agent that narrates any page + visitor avatar picker. `<page-agent>` web component. Rigged-only catalog. See [page-agent-sdk/PUBLISHING.md](page-agent-sdk/PUBLISHING.md) || Avatar builder (full app) | [character-studio/](character-studio) | Fork of [m3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio), MIT, see [character-studio/LICENSE](character-studio/LICENSE) | Web-first character creator || Scene Studio (3D scene editor) | [src/scene-studio/](src/scene-studio) `→ /scene` | Vendored [mrdoob/three.js](https://github.com/mrdoob/three.js) r184 editor, MIT, see [src/scene-studio/vendor/README.md](src/scene-studio/vendor/README.md) | Import GLBs, compose scenes, edit materials/lights, export |+| Diorama (text → 3D world) | [src/diorama/](src/diorama) `→ /diorama` | In-repo · backend [api/diorama.js](api/diorama.js) | One sentence → an explorable 3D diorama: Claude composes the scene, each object is forged to a real GLB, assembled live, saved to a public gallery + shareable permalink |+| Labs (hidden-gems hub) | [pages/labs.html](pages/labs.html) + [src/labs.js](src/labs.js) `→ /labs` | In-repo | Data-driven discovery hub: renders every `data/pages.json` entry flagged `showcase: true` as a live card (status check + iframe preview), filterable by category || X/Twitter automation toolkit | [xactions/](xactions) | Vendored [nirholas/XActions](https://github.com/nirholas/XActions), MIT, see [xactions/LICENSE](xactions/LICENSE) | Self-contained fork (browser scripts, CLI, MCP server, dashboard). Not an npm workspace — own `package.json`/deploy. Includes the console **Post Scraper** panel at [xactions/public/tools/](xactions/public/tools) || Embed examples | [examples/](examples) | In-repo | `embed-test.html`, `web-component.html`, `two-agents.html`, `minimal.html` || Animation pipeline | [public/animations/](public/animations) + [scripts/build-animations.mjs](scripts/build-animations.mjs) | In-repo | Mixamo source FBX + GLB retargeting pipeline · see [docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md) |@@ -30,6 +32,7 @@ bottom.| On-chain identity | [contracts/](contracts) | In-repo | Foundry-based on-chain agent identity, ERC-8004 || On-chain skill licenses | [contracts/skill-license/](contracts/skill-license) `→ /api/skills/license-onchain` | In-repo | Anchor program: each purchased skill = a 1/1 SPL NFT + `SkillLicense` PDA, a trustless alternative to DB-backed access checks. Backend: [api/_lib/skill-license-onchain.js](api/_lib/skill-license-onchain.js) || Launch Studio (coin-launch use cases) | [api/_lib/launch/](api/_lib/launch) `→ /launch-studio`, [api/pump/launch-studio.js](api/pump/launch-studio.js), [public/launch-studio/launch-studio.js](public/launch-studio/launch-studio.js) | In-repo | Engine + catalog of 50 declarative launch recipes — reward coins for trending GitHub repos/creators ([github-trending.js](api/_lib/github-trending.js)) and coins riding live narratives ([launcher-trends.js](api/_lib/launcher-trends.js)). Live preview → `/launch` handoff. Docs: [docs/launch-usecases.md](docs/launch-usecases.md), [api/_lib/launch/README.md](api/_lib/launch/README.md) |+| Avatar Seeder control room | [pages/admin/seeder.html](pages/admin/seeder.html) + [src/admin-seeder.js](src/admin-seeder.js) `→ /admin/seeder`, backend [api/admin/seeder.js](api/admin/seeder.js) | In-repo (admin, noindex) | Arm/disarm the headless [Avaturn seed cron](api/cron/avaturn-seed-cron.js), watch live throughput + rig rate, and preview freshly-forged rigged avatars in 3D. Toggles the `avaturn_seed` runtime flag. Flags: [api/_lib/flags.js](api/_lib/flags.js) + [api/admin/flags.js](api/admin/flags.js). Docs: [docs/ops/runtime-flags.md](docs/ops/runtime-flags.md) || On-chain agent invocation | [contracts/agent-invocation/](contracts/agent-invocation) | In-repo | Anchor program: verifiable agent-to-agent skill invocation events. SDK: [agent-protocol-sdk/](agent-protocol-sdk) || Cross-chain SDKs | [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk) | Published | Cross-chain agent SDKs || MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge), [packages/*-mcp/](packages) | 31 npm servers + 6 hosted remote, all in the [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas) | Model Context Protocol surface — full server list in [docs/mcp.md](docs/mcp.md) |diff --git a/api/_lib/admin.js b/api/_lib/admin.jsindex df49d1147..11679be33 100644--- a/api/_lib/admin.js+++ b/api/_lib/admin.js@@ -39,31 +39,37 @@ function isAdminAddress(address) {return false;}+/**+ * Silent admin predicate — resolves the admin decision for an already-loaded+ * session user WITHOUT writing any response. Shared by requireAdmin (which adds+ * the 401/403) and read-only probes (e.g. GET /api/labor/release) that only need+ * to know whether to reveal moderator controls.+ */+export async function isAdminUser(user) {+ if (!user) return false;+ if (isAdminAddress(user.wallet_address)) return true;+ if (user.is_admin) return true;+ if (adminAddressList().length > 0) {+ const wallets = await sql`select address from user_wallets where user_id = ${user.id}`;+ for (const w of wallets) {+ if (isAdminAddress(w.address)) return true;+ }+ }+ return false;+}++/** True when the request is from a signed-in admin. Never writes a response. */+export async function isAdminRequest(req) {+ return isAdminUser(await getSessionUser(req));+}+export async function requireAdmin(req, res) {const user = await getSessionUser(req);if (!user) {error(res, 401, 'unauthorized', 'sign in required');return null;}-- // Fast path: env-based admin list (wallet address match).- if (isAdminAddress(user.wallet_address)) {- return user;- }-- // DB flag: is_admin column.- if (user.is_admin) return user;-- // Check wallet addresses linked to this user against env list.- if (adminAddressList().length > 0) {- const wallets = await sql`- select address from user_wallets where user_id = ${user.id}- `;- for (const w of wallets) {- if (isAdminAddress(w.address)) return user;- }- }-+ if (await isAdminUser(user)) return user;error(res, 403, 'forbidden', 'admin access required');return null;}diff --git a/api/_lib/launch/usecase-engine.js b/api/_lib/launch/usecase-engine.jsindex d930150a9..e7c30136d 100644--- a/api/_lib/launch/usecase-engine.js+++ b/api/_lib/launch/usecase-engine.js@@ -17,7 +17,7 @@// only, brand-safe, no external ticker is ever minted verbatim.import { normTerm, isSensitive } from '../launcher-trends.js';-import { resolveGithubReward } from '../github-reward.js';+import { resolveGithubReward, resolveSocialReward } from '../github-reward.js';import { sourceCandidates } from './candidate-sources.js';// ── identity helpers ──────────────────────────────────────────────────────────@@ -93,18 +93,31 @@ export async function resolveReward(spec, { network, resolve = false }) {note: 'Creator fees stay with the launching agent wallet — claim or delegate later from the fees panel.' };}- if (spec.kind === 'github-owner') {+ if (spec.kind === 'github-owner' || spec.kind === 'x-owner') {+ const platform = spec.kind === 'x-owner' ? 'x' : 'github';+ const handle = spec.username || spec.github_username || spec.x_username;if (!resolve) {- return { kind: 'github-owner', github_username: spec.github_username || null, github_user_id: spec.github_user_id || null,+ return { kind: spec.kind, platform, username: handle || null,mode: 'pending', claimable_now: false, shareholders: [],- note: spec.github_username ? `Creator fees route to @${String(spec.github_username).replace(/^@/, '')} — resolved to their wallet (or a social-fee escrow) at launch.` : 'Creator fees route to the GitHub owner at launch.' };+ note: handle ? `Creator fees route to @${String(handle).replace(/^@/, '')} on ${platform === 'x' ? 'X' : 'GitHub'} — resolved to their wallet (or a social-fee escrow) at launch.` : `Creator fees route to the ${platform === 'x' ? 'X' : 'GitHub'} account at launch.` };}- const r = await resolveGithubReward({ githubUsername: spec.github_username, githubUserId: spec.github_user_id, network });- const shareholders = r.address ? [{ address: r.address, share_bps: 10_000, github_username: r.github_username, mode: r.mode }] : [];- return { kind: 'github-owner', github_username: r.github_username, github_user_id: r.github_user_id,+ const r = await resolveSocialReward({ platform, username: handle, userId: spec.user_id || spec.github_user_id, network });+ const shareholders = r.address ? [{ address: r.address, share_bps: 10_000, username: r.username, platform, mode: r.mode }] : [];+ return { kind: spec.kind, platform, username: r.username, user_id: r.user_id,mode: r.mode, claimable_now: r.claimable_now, shareholders, note: r.note };}+ // pump.fun launch-config reward structures — no recipient to resolve.+ if (spec.kind === 'cashback') {+ return { kind: 'cashback', shareholders: [], claimable_now: true,+ note: 'Trading fees return to holders as cashback — no creator vault; traders claim their own from pump.fun.' };+ }+ if (spec.kind === 'buyback') {+ const bps = Math.max(0, Math.min(10_000, Number(spec.buyback_bps) || 0));+ return { kind: 'buyback', buyback_bps: bps, shareholders: [], claimable_now: true,+ note: `${(bps / 100).toFixed(0)}% of creator fees auto-buy back and burn the coin — a rising floor instead of a payout.` };+ }+if (spec.kind === 'split') {const rows = Array.isArray(spec.shareholders) ? spec.shareholders : [];if (!resolve) {diff --git a/api/admin/seeder.js b/api/admin/seeder.jsnew file mode 100644index 000000000..471dc1383--- /dev/null+++ b/api/admin/seeder.js@@ -0,0 +1,187 @@+// GET/POST /api/admin/seeder — control room API for the Avaturn avatar seeder.+//+// GET → { flag, stats, circuit, cadence_seconds, recent[] } — everything the+// /admin/seeder console renders: whether the seeder is armed (and from+// where), how many rigged avatars it has produced, the circuit-breaker+// state, and a gallery of the most recent seeded avatars with live GLB+// URLs for in-browser 3D preview.+// POST → { enabled: boolean } arm/disarm the seeder (flips the+// `avaturn_seed` runtime flag, no deploy)+// { action: 'run_now' } trigger one export immediately+//+// Auth: a real admin session OR `Bearer $CRON_SECRET` (ops tooling) — the same+// contract as /api/admin/launcher and /api/admin/flags.++import { sql } from '../_lib/db.js';+import { requireAdmin } from '../_lib/admin.js';+import { cors, json, error, method, readJson, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { publicUrl } from '../_lib/r2.js';+import { circuitState } from '../_lib/forge-scale.js';+import { logAudit } from '../_lib/audit.js';+import { getFlag, setFlag } from '../_lib/flags.js';++const FLAG_KEY = 'avaturn_seed';+const CIRCUIT_NAME = 'avaturn-seed';+// Matches the cron schedule in vercel.json (* * * * *). Surfaced so the console+// can count down to the next automatic export.+const CADENCE_SECONDS = 60;+const RECENT_LIMIT = 18;++function isCronAuth(req) {+ const auth = req.headers.authorization || '';+ const bearer = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';+ return !!env.CRON_SECRET && constantTimeEquals(bearer, env.CRON_SECRET);+}++// Aggregate seeder throughput + rig quality straight off the avatars table.+async function loadStats() {+ try {+ const [r] = await sql`+ select+ count(*) as n_total,+ count(*) filter (where created_at > now() - interval '60 minutes') as n_60m,+ count(*) filter (where created_at > now() - interval '24 hours') as n_24h,+ count(*) filter (where created_at > now() - interval '7 days') as n_7d,+ count(*) filter (where (source_meta->>'is_rigged') = 'true') as n_rigged,+ max(created_at) as last_at+ from avatars+ where source = 'avaturn' and visibility = 'public' and deleted_at is null+ `;+ const total = Number(r?.n_total ?? 0);+ const rigged = Number(r?.n_rigged ?? 0);+ return {+ total,+ last_hour: Number(r?.n_60m ?? 0),+ last_24h: Number(r?.n_24h ?? 0),+ last_7d: Number(r?.n_7d ?? 0),+ rigged,+ rigged_pct: total ? Math.round((rigged / total) * 100) : 0,+ last_at: r?.last_at ?? null,+ };+ } catch (err) {+ return { total: 0, last_hour: 0, last_24h: 0, last_7d: 0, rigged: 0, rigged_pct: 0, last_at: null, error: err?.message?.slice(0, 140) };+ }+}++// Newest seeded avatars, mapped to public GLB URLs for the 3D preview gallery.+async function loadRecent() {+ try {+ const rows = await sql`+ select id, slug, name, storage_key, source_meta, created_at+ from avatars+ where source = 'avaturn' and visibility = 'public' and deleted_at is null+ order by created_at desc+ limit ${RECENT_LIMIT}+ `;+ return rows.map((a) => {+ const meta = a.source_meta || {};+ const joints = Number(meta.skeleton_joint_count) || null;+ return {+ id: a.id,+ slug: a.slug,+ name: a.name,+ glb_url: a.storage_key ? publicUrl(a.storage_key) : null,+ profile_url: a.slug ? `/avatars/${a.slug}` : null,+ body_type: meta.body_type || null,+ joints,+ is_rigged: meta.is_rigged === true || (joints != null && joints > 0),+ created_at: a.created_at,+ };+ });+ } catch {+ return [];+ }+}++async function handleGet(res) {+ const [flag, stats, recent, circuit] = await Promise.all([+ getFlag(FLAG_KEY, { fallback: env.AVATURN_SEED_ENABLED }),+ loadStats(),+ loadRecent(),+ circuitState(CIRCUIT_NAME).catch(() => ({ open: false, failures: 0, openUntil: 0 })),+ ]);++ return json(res, 200, {+ ok: true,+ flag: {+ key: FLAG_KEY,+ enabled: flag.enabled,+ // Where the effective value comes from: a DB row (live control) or the+ // env fallback (no row set yet). Lets the console explain the state.+ source: flag.exists ? 'db' : 'env',+ env_fallback: !!env.AVATURN_SEED_ENABLED,+ },+ stats,+ circuit: {+ open: !!circuit.open,+ failures: Number(circuit.failures) || 0,+ open_until: Number(circuit.openUntil) || 0,+ },+ cadence_seconds: CADENCE_SECONDS,+ recent,+ });+}++// Fire one export immediately by invoking the cron endpoint with the operator+// secret. Headless export takes ~2 min; we don't await the full run — once the+// request reaches the cron it runs to completion in its own invocation, so we+// return as soon as it's accepted (or report the single-flight slot is busy).+async function triggerRunNow() {+ const origin = env.APP_ORIGIN || 'https://three.ws';+ const secret = env.CRON_SECRET || '';+ if (!secret) return { triggered: false, reason: 'CRON_SECRET unset' };+ try {+ const r = await fetch(`${origin}/api/cron/avaturn-seed-cron`, {+ headers: { authorization: `Bearer ${secret}` },+ signal: AbortSignal.timeout(4000),+ });+ const body = await r.json().catch(() => null);+ // The cron early-returns a top-level `skipped` for disarmed / single-flight.+ if (body?.skipped === 'disabled') return { triggered: false, reason: 'seeder is disarmed — arm it first' };+ if (body?.skipped === 'in_flight') return { triggered: false, reason: 'an export is already running' };+ return { triggered: true };+ } catch (err) {+ // A timeout means the export is running past our short read window — that's+ // success from the console's perspective: the run was accepted.+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError') return { triggered: true, running: true };+ return { triggered: false, reason: err?.message?.slice(0, 140) || 'trigger failed' };+ }+}++async function handlePost(req, res, adminId) {+ const body = await readJson(req, 32 * 1024);++ if (body?.action === 'run_now') {+ const result = await triggerRunNow();+ logAudit({ userId: adminId, action: 'seeder-run-now', meta: result, req });+ if (!result.triggered) return error(res, 409, 'run_now_failed', result.reason || 'could not start an export');+ return json(res, 200, { ok: true, ...result });+ }++ if (typeof body?.enabled !== 'boolean') {+ return error(res, 400, 'invalid_request', 'body must be { enabled: boolean } or { action: "run_now" }');+ }++ const row = await setFlag(FLAG_KEY, { enabled: body.enabled, updatedBy: adminId });+ logAudit({ userId: adminId, action: 'seeder-toggle', resourceId: FLAG_KEY, meta: { enabled: body.enabled }, req });+ return json(res, 200, { ok: true, flag: { key: FLAG_KEY, enabled: row.enabled === true, source: 'db' } });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ let adminId = null;+ if (isCronAuth(req)) {+ adminId = null;+ } else {+ const admin = await requireAdmin(req, res);+ if (!admin) return; // requireAdmin already wrote 401/403+ adminId = admin.id;+ }++ if (req.method === 'GET') return handleGet(res);+ return handlePost(req, res, adminId);+});diff --git a/api/labor/release.js b/api/labor/release.jsindex 7ba33352f..2dadd82e7 100644--- a/api/labor/release.js+++ b/api/labor/release.js@@ -17,7 +17,7 @@import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';-import { requireAdmin } from '../_lib/admin.js';+import { requireAdmin, isAdminRequest } from '../_lib/admin.js';import {getBounty, getJobByBounty, getJob, markJobDelivered, setBountyStatus,atomicsToThree, _toBig as toBig,@@ -36,8 +36,15 @@ async function posterSolanaAddress(bounty) {}export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;++ // Read-only probe: does the caller have moderator (admin) rights? The UI uses+ // this to decide whether to reveal the release/refund controls. Never mutates.+ if (req.method === 'GET') {+ return json(res, 200, { data: { moderator: await isAdminRequest(req) } });+ }++ if (!method(req, res, ['GET', 'POST'])) return;// Moderator gate. requireAdmin writes the 401/403 itself; the escrow key is// never returned to or touched by the caller.diff --git a/api/pump/[action].js b/api/pump/[action].jsindex e51133a4f..de28dbdef 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -54,6 +54,7 @@import { z } from 'zod';import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';import { sql } from '../_lib/db.js';+import { resolveSocialReward } from '../_lib/github-reward.js';import { submitProtected } from '../_lib/execution-engine.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, json, method, readJson, wrap, error, rateLimited, respondError } from '../_lib/http.js';@@ -4310,16 +4311,18 @@ const SOCIAL_PLATFORM_ID = { pump: 0, x: 1, github: 2 };const resolveGithubShareholderSchema = z.object({+ // Platform is now general: 'github' (default) or 'x' (Twitter). The+ // github_* fields are kept for back-compat; `username`/`user_id` are the+ // platform-agnostic inputs the fees panel and Launch Studio use.+ platform: z.enum(['github', 'x']).default('github'),+ username: z.string().trim().min(1).max(40).optional(),+ user_id: z.string().trim().regex(/^\d{1,20}$/).optional(),github_username: z.string().trim().min(1).max(40).optional(),- github_user_id: z- .string()- .trim()- .regex(/^\d{1,20}$/)- .optional(),+ github_user_id: z.string().trim().regex(/^\d{1,20}$/).optional(),network: z.enum(['mainnet', 'devnet']).default('mainnet'),})- .refine((b) => b.github_username || b.github_user_id, {- message: 'github_username or github_user_id required',+ .refine((b) => b.username || b.user_id || b.github_username || b.github_user_id, {+ message: 'a username or numeric user id is required',});async function handleResolveGithubShareholder(req, res) {@@ -4333,71 +4336,30 @@ async function handleResolveGithubShareholder(req, res) {if (!rl.success) return rateLimited(res, rl);const body = parse(resolveGithubShareholderSchema, await readJson(req));- const login = body.github_username ? body.github_username.replace(/^@/, '') : null;-- // Look up the GitHub identity in social_connections (written by the existing- // /api/auth/github OAuth flow — provider_uid is the numeric GitHub user id).- const [conn] = await sql`- select user_id, provider_uid, username- from social_connections- where provider='github' and disconnected_at is null- and (${login}::text is not null and lower(username)=lower(${login})- or ${body.github_user_id}::text is not null and provider_uid=${body.github_user_id})- order by connected_at desc- limit 1- `;- const { socialFeePda } = await import('@pump-fun/pump-sdk');- const platform = SOCIAL_PLATFORM_ID.github;-- if (conn) {- // Prefer the recipient's primary linked Solana wallet — fully claimable.- const [wallet] = await sql`- select address from user_wallets- where user_id=${conn.user_id} and chain_type='solana'- order by is_primary desc, created_at asc- limit 1- `;- if (wallet) {- return json(res, 200, {- mode: 'wallet',- address: wallet.address,- github_username: conn.username,- github_user_id: conn.provider_uid,- claimable_now: true,- note: 'Linked Solana payout wallet — pays out via the permissionless distribute crank.',- });- }- // On three.ws but no Solana wallet linked yet → escrow PDA, claim deferred.- return json(res, 200, {- mode: 'social_pda',- address: socialFeePda(String(conn.provider_uid), platform).toBase58(),- github_username: conn.username,- github_user_id: conn.provider_uid,- claimable_now: false,- note: 'This GitHub user has no Solana payout wallet linked yet. Fees accrue in a pump.fun social-fee escrow; ask them to link a Solana wallet on three.ws to claim directly.',- });- }-- // Not on three.ws. We can only derive the escrow PDA from a numeric id —- // pump.fun keys social-fee PDAs by the numeric GitHub user id, not the login.- if (body.github_user_id) {- return json(res, 200, {- mode: 'social_pda',- address: socialFeePda(String(body.github_user_id), platform).toBase58(),- github_user_id: body.github_user_id,- claimable_now: false,- note: 'This GitHub user is not on three.ws. Fees accrue in a pump.fun social-fee escrow they can claim once they connect GitHub and link a Solana wallet.',- });- }+ // One source of truth for social → reward resolution (github + x), shared with+ // the launch use-case engine and the fees panel.+ const r = await resolveSocialReward({+ platform: body.platform,+ username: body.username || body.github_username,+ userId: body.user_id || body.github_user_id,+ network: body.network,+ });return json(res, 200, {- mode: 'unresolved',- github_username: login,- claimable_now: false,- note: 'No three.ws account found for that GitHub username. Provide the numeric GitHub user id to route into a pump.fun social-fee escrow, or ask them to sign in with GitHub and link a Solana wallet.',+ platform: r.platform,+ mode: r.mode,+ address: r.address,+ username: r.username,+ user_id: r.user_id,+ // Back-compat aliases for existing github callers.+ github_username: r.platform === 'github' ? r.username : undefined,+ github_user_id: r.platform === 'github' ? r.user_id : undefined,+ claimable_now: r.claimable_now,+ note: r.note,});}+// ── create-social-fee-pda-prep ─────────────────────────────────────────────// Initialises the pump.fun social-fee escrow PDA for a (social_user_id,// platform) pair so a subsequent update-fee-shares-prep can name it as adiff --git a/data/changelog.json b/data/changelog.jsonindex c09788f4e..a2b60c1ad 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,54 @@{"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-01",+ "title": "The autonomous sniper now has a live web console",+ "summary": "Run agent-sniper serve and open it in a browser: a real-time operator dashboard, built right into the engine. Watch buys, sells, candidates and signals tick up live; see every open position with its entry, current value and colored profit-and-loss, and close any of them in one click; review your armed strategies with their stop-loss and take-profit at a glance; arm a new strategy or fire a manual snipe from clean forms; and read a live activity feed of everything the engine is doing. It has designed loading, empty and error states, toasts, keyboard shortcuts and a full mobile layout. Reads are free to anyone; to run the controls yourself without paying, set an operator token that bypasses the x402 paywall for you while external agents still pay per call.",+ "tags": [+ "feature",+ "sdk"+ ],+ "link": "/docs/mcp"+ },+ {+ "date": "2026-07-01",+ "title": "Diorama is live — speak a little 3D world into being",+ "summary": "Diorama is now a real, reachable page at three.ws/diorama. Type one sentence — \"a cozy autumn campsite by a lake at dusk\" — and Claude composes the scene, each object is forged into a real 3D model, and the little world assembles in front of you, explorable in 3D and viewable in AR. Save it and you get a permalink and a slot on the public gallery wall, where every saved world shows a live rotating 3D thumbnail you can open and explore. Share it as a 3D postcard: copy the link, post to X, or grab an embed snippet. Nothing is a screenshot — it's all real geometry forged from your words.",+ "tags": [+ "feature"+ ],+ "link": "/diorama"+ },+ {+ "date": "2026-07-01",+ "title": "Labs — a home for the hidden gems most people never find",+ "summary": "There's a new Labs page at three.ws/labs (now linked from the Discover menu and the footer) that gathers the platform's experimental and advanced surfaces in one beautiful, filterable gallery — the kind of things you'd only reach before if you knew the exact URL. Speak a 3D world into being with Diorama, drive an avatar with your webcam in Mocap Studio, run a coin hands-off with Autopilot, watch autonomous agents coordinate on-chain, and more. Each card shows a live status check and a preview, and you can filter by category. Everything featured is real and live.",+ "tags": [+ "feature"+ ],+ "link": "/labs"+ },+ {+ "date": "2026-07-01",+ "title": "The Trading Brain is redesigned — presets, a live risk meter, and a real backtest breakdown",+ "summary": "Building your agent's sniper is now a minute, not a manual. Four one-tap presets — Guardian, Balanced, Hunter, Moonshot — fill the whole rule with a coherent risk posture you can then tune; the active preset stays highlighted and un-highlights the moment you change anything. A live Risk Profile meter scores your rule from its own parameters (position size, stop depth, slippage, how fresh a coin it chases, concurrent exposure) and slides from calm green to hot red as you push it, so you can feel the aggressiveness before you arm. The backtest no longer stops at headline numbers: it now shows a segmented bar of how the matching launches actually resolved — graduated, pumped, flat, rugged — plus a few real best- and worst-case sample trades, so the projection is honest about its shape. Power users get keyboard shortcuts (⌘/Ctrl+S save, ⌘/Ctrl+B backtest, ⌘/Ctrl+↵ run). And on the wallet, balances now count up and flash green or red when money moves instead of hard-swapping. Every animation respects reduced-motion.",+ "tags": [+ "improvement",+ "feature"+ ],+ "link": "/agent-studio"+ },+ {+ "date": "2026-07-01",+ "title": "The x402 page is now a live, searchable storefront",+ "summary": "three.ws/x402 is rebuilt as a live catalog. Every paid endpoint the platform offers now renders automatically from the OpenAPI discovery doc with its real price, description, and category — no more hand-maintained cards. Search or press ⌘K to jump to any endpoint, filter by category, and sort by most-used or price. Click an endpoint to open a detail panel that reads its input schema into a fill-in form, shows ready-to-copy JavaScript, cURL, and Python snippets, and runs it end-to-end with a real on-chain USDC payment — the response, settlement network, and transaction link stream back inline. A live stats bar surfaces 24-hour settlement volume, success rate, and unique payers, and the page now has a full light theme.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/x402"+ },{"date": "2026-07-01","title": "The x402 toolkit is now on npm and the VS Code Marketplace",diff --git a/data/pages.json b/data/pages.jsonindex 4b3fc1fe8..dbaab5725 100644--- a/data/pages.json+++ b/data/pages.json@@ -44,7 +44,60 @@"description": "Browse and preview public animations authored by the three.ws community. Apply any clip to your avatar in the Animation Studio.","priority": 0.8,"changefreq": "daily",- "added": "2026-06-17"+ "added": "2026-06-17",+ "showcase": true+ },+ {+ "path": "/diorama",+ "title": "Diorama",+ "description": "Speak a little world into being — describe a scene and watch it assemble into an explorable 3D diorama you can walk through, then take it into AR.",+ "priority": 0.7,+ "changefreq": "weekly",+ "added": "2026-07-01",+ "showcase": true+ },+ {+ "path": "/mocap-studio",+ "title": "Mocap Studio",+ "description": "Drive a 3D avatar with your webcam — real-time facial motion capture in the browser, no rig and no download.",+ "priority": 0.7,+ "changefreq": "weekly",+ "added": "2026-07-01",+ "showcase": true+ },+ {+ "path": "/autopilot",+ "title": "Coin Autopilot",+ "description": "A hands-off token cockpit: set the rules — buys, sells, and guardrails — and let your agent run the coin autonomously.",+ "priority": 0.7,+ "changefreq": "weekly",+ "added": "2026-07-01",+ "showcase": true+ },+ {+ "path": "/agenc/embodied",+ "title": "AgenC · Embodied",+ "description": "Watch two AI agents negotiate and coordinate a task, embodied as 3D characters — the AgenC coordination protocol made visible.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-07-01",+ "showcase": true+ },+ {+ "path": "/agenc/room",+ "title": "AgenC · Task Room",+ "description": "A live room where autonomous agents discover open work, bid for it, and settle on-chain — the labor market up close.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-07-01"+ },+ {+ "path": "/create/video",+ "title": "Talking Avatar Video",+ "description": "Turn a three.ws avatar into a talking-head video: type a script, pick a voice, and export a lip-synced clip.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-07-01"},{"path": "/temporary",@@ -745,12 +798,13 @@"description": "The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.","priority": 0.8,"changefreq": "always",- "added": "2026-06-23"+ "added": "2026-06-23",+ "showcase": true},{"path": "/x402-revenue","title": "Endpoint Revenue",- "description": "The live revenue layer — real USDC flowing into three.ws's own x402 paid endpoints. Gross revenue, top-earning endpoints, and every settlement the moment it lands on-chain. The mirror of the Money Pulse: what the platform earns, not what agents spend.",+ "description": "The live revenue layer — real USDC flowing into three.ws's own x402 paid endpoints. A live revenue chart, gross/net/success-rate KPIs, momentum vs the prior window, top-earning endpoints, revenue by network, and a filterable, searchable live feed of every settlement with copy-tx, sound, and CSV export. The mirror of the Money Pulse: what the platform earns, not what agents spend. Every payment is real and explorer-verifiable.","priority": 0.7,"changefreq": "always","added": "2026-06-30"diff --git a/docs/launch-usecases.md b/docs/launch-usecases.mdindex c7dc40ccd..b5e48bbf4 100644--- a/docs/launch-usecases.md+++ b/docs/launch-usecases.md@@ -33,14 +33,36 @@ It's built on the shared [launch use-case engine](../api/_lib/launch/README.md).## How a preview works-1. Open `/launch-studio` and pick a recipe.-2. The studio calls the read API and renders the coins the recipe would mint from- **live data** — name, ticker, description, source signal, and the reward- routing for each.+1. Open `/launch-studio`. Search across all 50 recipes, filter by category+ (colour-themed tabs) or type (Reward / Theme), star favourites, or hit+ **Surprise me** for a random one. `/` focuses search; `Esc` closes.+2. Click a recipe to open the **live preview drawer** — the coins it would mint+ right now from live data, each with an avatar, name, ticker, description, a+ signal-strength bar, and its reward routing.3. Hit **Launch this coin** to open the existing [`/launch`](https://three.ws/launch)wizard with the identity prefilled, then mint on-chain from your wallet or anagent's custodial wallet.+## Reward routing — to anyone, not just GitHub++The preview drawer has a **reward planner**: route a coin's creator fees to any of++| Target | What it does |+|---|---|+| **As designed** | The recipe's built-in routing (e.g. the repo owner). |+| **Creator** | Fees stay with the launching wallet. |+| **GitHub @user** | 100% to a GitHub account (pump.fun social platform 2). |+| **X @handle** | 100% to an X / Twitter account (pump.fun social platform 1). |+| **Wallet / .sol** | 100% to a fixed Solana address or name. |+| **Cashback** | Trading fees return to holders. |+| **Buyback** | Fees auto-buy-back & burn the coin. |++The same generalisation powers the post-launch [fees panel](../public/studio/fees-panel.js):+its recipient box accepts a **GitHub @user**, an **X handle** (`x:@handle`), a+raw **Solana wallet**, or an **owner/repo** to split across contributors. All of+it resolves through one shared resolver ([`api/_lib/github-reward.js`](../api/_lib/github-reward.js),+`resolveSocialReward`) so GitHub and X route identically.+For reward coins, after the coin graduates you set the GitHub recipient in the[fees panel](../public/studio/fees-panel.js) (type a `@username` → 100%, orimport a repo's contributors to split) — see the fee-sharing flow.diff --git a/docs/ops/runtime-flags.md b/docs/ops/runtime-flags.mdindex 1ab8e2eb1..19591957a 100644--- a/docs/ops/runtime-flags.md+++ b/docs/ops/runtime-flags.md@@ -7,6 +7,7 @@ Vercel env var and waiting for a build.- **Table:** `app_flags` (`key`, `enabled`, `value` jsonb, `updated_by`, `updated_at`) — migration `api/_lib/migrations/20260630120000_app_flags.sql`.- **Helper:** [api/_lib/flags.js](../../api/_lib/flags.js) — `getFlag`, `isFlagEnabled`, `setFlag`, `listFlags`.- **Admin API:** [api/admin/flags.js](../../api/admin/flags.js) — `GET`/`POST /api/admin/flags`.+- **Control room:** **[/admin/seeder](../../pages/admin/seeder.html)** — a visual console to arm/disarm the Avatar Seeder, watch live throughput, preview freshly-forged rigged avatars in 3D, and flip every runtime flag with one click. No redeploy, no curl. Backend: [api/admin/seeder.js](../../api/admin/seeder.js).## How it resolvesdiff --git a/docs/pump-launch-repos.md b/docs/pump-launch-repos.mdnew file mode 100644index 000000000..2953c346c--- /dev/null+++ b/docs/pump-launch-repos.md@@ -0,0 +1,92 @@+# Repo → Coin Launcher++Launch one pump.fun coin per public GitHub repo, with **100% of creator rewards+routed to the repo owner's GitHub identity**. Ships as a visual control panel and+a CLI over one shared engine.++- Engine: [`scripts/lib/pump-launch-core.mjs`](../scripts/lib/pump-launch-core.mjs)+- CLI: [`scripts/pump-launch-repos.mjs`](../scripts/pump-launch-repos.mjs) — `npm run pump:launch`+- UI: [`scripts/pump-launch-server.mjs`](../scripts/pump-launch-server.mjs) + [`scripts/pump-launch-ui/`](../scripts/pump-launch-ui/) — `npm run pump:launch:ui`++## How the reward routing works++pump.fun keys a deterministic **social-fee escrow PDA** off the numeric GitHub+user id: `socialFeePda(id, 2)` (platform `2` = GitHub). Each coin is launched by+a throwaway repo wallet (the on-chain `creator` + payer). Immediately after+create, a fee-sharing config is opened and its **only shareholder is set to that+PDA at 10000 bps (100%)** — the launch wallet keeps the fee-sharing admin+authority but 0% of the fees. The GitHub owner claims from the escrow by linking+a Solana wallet (or, if already linked on three.ws, fees stream straight to it+via the permissionless distribute crank).++This is the same mechanism the studio uses in+[`api/pump/[action].js`](../api/pump/[action].js) (`resolve-github-shareholder`,+`fee-sharing-agent`). Nothing here hardcodes a third-party mint — the recipient+and mints are derived at runtime.++## Wallet model++One **master wallet** (you fund it once) → funds N throwaway **repo wallets** →+each repo wallet launches its own coin. Every private key is written **only**+under `.pump-launch-wallets/` (gitignored) and bundled into+`pump-launch-wallets.zip` for download. You own every launch key; nothing is+custodial or server-side.++## Quick start (UI)++```bash+npm run pump:launch:ui # http://localhost:4599 (localhost only)+```++1. Enter a GitHub username → the panel resolves the id + escrow PDA and loads+ every public repo with covers, stars, language, and an auto-ticker.+2. Select repos (all preselected). Search `/`, filter forks/archived/starred,+ sort, `⌘A` to select all.+3. Set the dev buy and fund-per-wallet; the cost bar updates live.+4. **Generate wallets** → a fund modal shows the master address + QR, live+ balance gate, and the keys `.zip` download.+5. Fund the master; **Launch** streams per-repo progress (fund → create →+ fee-config → delegate) with explorer links. Resumable.++## Quick start (CLI)++```bash+node scripts/pump-launch-repos.mjs generate --github-user nirholas+node scripts/pump-launch-repos.mjs verify # prove every launch key is yours+node scripts/pump-launch-repos.mjs preflight # upload metadata + build ixs, no send+# fund the printed master wallet, then:+node scripts/pump-launch-repos.mjs run --rpc "<helius url>" --yes+node scripts/pump-launch-repos.mjs status+```++Flags: `--network mainnet|devnet` · `--rpc <url>` · `--github-user` ·+`--github-id` · `--dev-buy <sol>` · `--fund-per-wallet <sol>` · `--only <repo>` ·+`--limit <n>` · `--yes`.++## Cost++Per coin (SOL): create rent `~0.020` + fee-sharing config rent `~0.0025` + tx+fees `~0.0003` + your dev buy. Default fund-per-wallet ≈ `0.027`. For 146 repos+that's ≈ **3.9 SOL** to the master. The dev buy dominates nothing — a minimal or+zero buy is cheapest and cleanest (`--dev-buy 0` uses the plain create path).++For an exact figure, run one launch on `--network devnet` and read the measured+lamport delta before committing mainnet SOL.++## Safety++- **Localhost only.** The UI never binds a public route; keys never leave your+ machine.+- **Nothing is sent until you Launch** against a funded master. `generate`,+ `verify`, `preflight`, and repo browsing are all free and offline of on-chain+ spend.+- **`.pump-launch-wallets/` and `pump-launch-wallets.zip` are gitignored.** Keep+ the zip private — it contains spendable keys.+- Mainnet launches are irreversible. Launching many coins at once can read as+ spam; scope deliberately.++## RPC++Mainnet defaults to the `https://three.ws/api/solana-rpc` proxy, which+rate-limits under the ~450 txs a full run makes. Pass a dedicated `--rpc`+(Helius) or set `SOLANA_RPC_URL` for real runs.diff --git a/fees-reward-anyone.png b/fees-reward-anyone.pngnew file mode 100644index 000000000..b72102505Binary files /dev/null and b/fees-reward-anyone.png differdiff --git a/package.json b/package.jsonindex f85190c5b..34acafc85 100644--- a/package.json+++ b/package.json@@ -214,6 +214,8 @@"deploy:sniper": "node scripts/deploy-sniper.mjs","pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js","pump:refresh-idls": "node scripts/refresh-pump-idls.mjs",+ "pump:launch": "node scripts/pump-launch-repos.mjs",+ "pump:launch:ui": "node scripts/pump-launch-server.mjs","seed:skills": "node scripts/seed-skills.js","install:sdk": "npm install --prefix agent-payments-sdk && npm run build --prefix agent-payments-sdk && npm install ./agent-payments-sdk","claude": "./scripts/claude.sh",diff --git a/packages/agent-sniper/README.md b/packages/agent-sniper/README.mdindex 80bf858fd..3e934ffa0 100644--- a/packages/agent-sniper/README.md+++ b/packages/agent-sniper/README.md@@ -147,7 +147,7 @@ npx agent-sniper run --network devnet --strategy ./strategy.json# Serve the engine over MCP (stdio) for Claude / Cursor / any MCP client.agent-sniper mcp-# Serve the x402-gated HTTP API.+# Serve the x402-gated HTTP API + web console (open http://localhost:8787).agent-sniper serve# Help.@@ -246,6 +246,43 @@ await serve(---+## Web console++`serve` also ships a **built-in operator dashboard** — a single, dependency-free+HTML file served from the same origin as the API, at `/` and `/console`. Open+`http://localhost:8787` and you get a live control room:++- **Live stats** — buys, sells, candidates, armed strategies, in-flight queue and+ signal count, animated as they change, with time-since-last-signal.+- **Positions table** — every position with entry, current value, and colored+ P&L (unrealized total in the header), plus a one-click **Close** that schedules+ an exit through the normal sell path.+- **Armed strategies** — each policy with its stop-loss / take-profit / trailing+ tags, and a **Disarm** button.+- **Arm a strategy** and **Manual snipe** forms with inline validation.+- **Live activity feed** — the same engine screen events the CLI prints, streamed+ in with relative timestamps.+- Designed loading / empty / error states, toasts, keyboard shortcuts+ (`s` snipe, `n` new strategy, `r` refresh, `,` settings, `?` help), a+ disconnected banner, and full mobile responsiveness.++Reads are free. The mutating controls (arm, snipe, disarm, close) are x402-paid+for external callers — so to drive them from your own console without paying+yourself, set an **operator token**:++```bash+export SNIPER_ADMIN_TOKEN="$(openssl rand -hex 24)"+agent-sniper serve --port 8787+```++Open Settings (⚙ or `,`) in the console and paste the same token. It is sent as+`X-Admin-Token` (or `Authorization: Bearer …`), stored only in your browser, and+bypasses the x402 gate — while unauthenticated external agents still pay. Pass it+programmatically as `deps.adminToken`. Without a token set, the console is a+full-featured **read-only monitor** and mutations return `503` with guidance.++---+## Multi-agent / multi-userThe engine is multi-tenant by design. The unit of isolation is the `agentId`:diff --git a/packages/agent-sniper/package.json b/packages/agent-sniper/package.jsonindex 48340c41c..f997af7fd 100644--- a/packages/agent-sniper/package.json+++ b/packages/agent-sniper/package.json@@ -44,6 +44,7 @@"files": ["src","bin",+ "web","assets","server.json","README.md",diff --git a/packages/agent-sniper/src/engine.js b/packages/agent-sniper/src/engine.jsindex 2fc2cfb5c..f0378bea0 100644--- a/packages/agent-sniper/src/engine.js+++ b/packages/agent-sniper/src/engine.js@@ -27,7 +27,23 @@ import { runPositionSweep } from './positions.js';export function createSniper(deps) {const cfg = loadConfig(deps.config || {});const log = deps.logger || defaultLog;- const hooks = deps.hooks || {};++ // Ring buffer of recent screen events so any face (web console, API) can render+ // a live activity feed. Wrap the caller's onScreen (copied so we never mutate+ // their object) — this way events from the engine AND the executor/position+ // sweep are captured here, then forwarded on to whatever hook they passed.+ const ACTIVITY_CAP = 250;+ const activity = [];+ const hooks = { ...(deps.hooks || {}) };+ const callerOnScreen = hooks.onScreen;+ hooks.onScreen = (evt) => {+ if (evt && typeof evt.text === 'string') {+ activity.push({ at: Date.now(), text: evt.text, kind: evt.kind || 'info' });+ if (activity.length > ACTIVITY_CAP) activity.shift();+ }+ try { callerOnScreen?.(evt); } catch { /* best-effort */ }+ };+const ports = { store: deps.store, wallet: deps.wallet, solana: deps.solana, executor: deps.executor, hooks, log };if (!ports.store || !ports.wallet || !ports.solana || !ports.executor || !deps.feed) {throw new Error('[agent-sniper] createSniper requires store, wallet, solana, executor, and feed adapters');@@ -94,6 +110,8 @@ export function createSniper(deps) {config: cfg,stats: () => ({ ...stats, strategies: strategies.length, queued: queue.inFlight, lastEventAt }),strategies: () => strategies.slice(),+ /** Most-recent screen events (newest last), for a live activity feed. */+ activity: (limit = 50) => activity.slice(-Math.max(1, Math.min(Number(limit) || 50, ACTIVITY_CAP))),async start() {log.info('boot', { network: cfg.network, mode: cfg.mode, globalKill: cfg.globalKill, pollMs: cfg.pollMs });diff --git a/packages/agent-sniper/src/faces/api.js b/packages/agent-sniper/src/faces/api.jsindex bf27bd2b2..3b3700bb8 100644--- a/packages/agent-sniper/src/faces/api.js+++ b/packages/agent-sniper/src/faces/api.js@@ -13,11 +13,35 @@// Zero three.ws backend imports — only local package files, express (optional),// and the published @three-ws/x402-server SDK.-import { pathToFileURL } from 'node:url';-import { randomUUID } from 'node:crypto';+import { pathToFileURL, fileURLToPath } from 'node:url';+import { randomUUID, timingSafeEqual } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';import { paid } from '@three-ws/x402-server';import { presets, createMemoryStore } from '../index.js';+// The web console is a single self-contained HTML file shipped with the package.+// Read it once, lazily, and cache it — a serve() that never gets a browser hit+// pays nothing; one that does serves from memory.+const CONSOLE_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'web', 'console.html');+let _consoleHtml = null;+function consoleHtml() {+ if (_consoleHtml == null) {+ try { _consoleHtml = readFileSync(CONSOLE_PATH, 'utf8'); }+ catch { _consoleHtml = ''; }+ }+ return _consoleHtml;+}++// Constant-time string compare for the admin token — avoids leaking length/prefix+// through response timing.+function safeEqual(a, b) {+ const ab = Buffer.from(String(a));+ const bb = Buffer.from(String(b));+ if (ab.length !== bb.length) return false;+ return timingSafeEqual(ab, bb);+}+// 1 SOL = 1e9 lamports. The wire takes human SOL amounts; the engine + store// speak lamports (string-encoded BigInt, mirroring the Strategy contract).const LAMPORTS_PER_SOL = 1_000_000_000n;@@ -28,6 +52,7 @@ const DEFAULT_PRICES = {arm: '10000', // POST /strategies → $0.01snipe: '50000', // POST /snipe → $0.05disarm: '5000', // POST /strategies/:id/disarm → $0.005+ close: '5000', // POST /positions/:id/close → $0.005};/**@@ -67,6 +92,7 @@ function solToLamportsString(sol) {* @param {Record<string,string>} [deps.prices] per-endpoint USDC atomic prices ({ arm, snipe, disarm }).* @param {string} [deps.facilitatorUrl] x402 facilitator base URL for /verify + /settle.* @param {string} [deps.feePayer] Solana facilitator sponsor fee-payer; env fallback X402_FEE_PAYER_SOLANA. The Solana lane self-disables without it.+ * @param {string} [deps.adminToken] operator token; env fallback SNIPER_ADMIN_TOKEN. A request carrying it (Authorization: Bearer / X-Admin-Token) bypasses x402 — the owner's own console mutates free while external agents still pay.*/export async function createSniperApiRouter(deps = {}) {const express = await loadExpress();@@ -106,6 +132,19 @@ export async function createSniperApiRouter(deps = {}) {const prices = { ...DEFAULT_PRICES, ...(deps.prices || {}) };const facilitator = deps.facilitatorUrl || process.env.X402_FACILITATOR_URL || undefined;+ // Operator token. When set, a request presenting it bypasses the x402 gate —+ // the owner's own web console can arm/snipe/disarm without paying itself, while+ // unauthenticated external agents still hit the paid path.+ const adminToken = deps.adminToken || process.env.SNIPER_ADMIN_TOKEN || null;+ const isAdmin = (req) => {+ if (!adminToken) return false;+ const auth = req.headers.authorization;+ const bearer = typeof auth === 'string' && auth.startsWith('Bearer ') ? auth.slice(7).trim() : null;+ const hdr = typeof req.headers['x-admin-token'] === 'string' ? req.headers['x-admin-token'].trim() : null;+ const provided = bearer || hdr;+ return Boolean(provided) && safeEqual(provided, adminToken);+ };+const router = express.Router();router.use(express.json({ limit: '64kb' }));@@ -114,38 +153,46 @@ export async function createSniperApiRouter(deps = {}) {router.use((req, res, next) => {res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-PAYMENT, Authorization');+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-PAYMENT, Authorization, X-Admin-Token');res.setHeader('Access-Control-Expose-Headers', 'PAYMENT-REQUIRED, X-PAYMENT-RESPONSE');if (req.method === 'OPTIONS') return res.status(204).end();return next();});- // Wrap a mutating handler so it requires an x402 payment. When payTo is- // unset the endpoint still mounts but answers 503 — the server boots without- // payment config for local/dev rather than charging into a void.+ // Wrap a mutating handler behind access control. Three paths, checked per request:+ // 1. admin token present → run the handler directly (operator bypass);+ // 2. x402 configured → require an x402 payment via paid();+ // 3. neither → 503 (server still boots for local/dev).function gate(priceKey, handler) {- if (!x402Configured) {- return (req, res) => {- res.status(503).json({- error: 'x402 not configured: set payTo.solana or X402_PAY_TO_SOLANA',- });- };- }- return paid(- {- price: prices[priceKey],- asset: 'usdc',- payTo: lanes,- facilitator,- feePayer,- description: 'agent-sniper paid endpoint',- serviceName: 'agent-sniper',- },- // paid()'s node adapter invokes (req, res, payment); our handlers are- // async and own the response. Boundary errors are caught here and- // forwarded to the error handler via the captured `next`.- (req, res, payment) => Promise.resolve(handler(req, res, payment)).catch(req._onError),- );+ const runDirect = (req, res) =>+ Promise.resolve(handler(req, res, { admin: true })).catch(req._onError);++ const paidPath = x402Configured+ ? paid(+ {+ price: prices[priceKey],+ asset: 'usdc',+ payTo: lanes,+ facilitator,+ feePayer,+ description: 'agent-sniper paid endpoint',+ serviceName: 'agent-sniper',+ },+ // paid()'s node adapter invokes (req, res, payment); our handlers are+ // async and own the response. Boundary errors are caught here and+ // forwarded to the error handler via the captured `next`.+ (req, res, payment) => Promise.resolve(handler(req, res, payment)).catch(req._onError),+ )+ : (req, res) => res.status(503).json({+ error: adminToken+ ? 'payment required: send the admin token (Authorization: Bearer / X-Admin-Token) or configure x402 (X402_PAY_TO_SOLANA).'+ : 'x402 not configured: set payTo.solana or X402_PAY_TO_SOLANA (or SNIPER_ADMIN_TOKEN for an operator console).',+ });++ return (req, res, next) => {+ if (isAdmin(req)) return runDirect(req, res);+ return paidPath(req, res, next);+ };}// Capture express's `next` for the paid handlers (paid()'s node adapter calls@@ -156,8 +203,25 @@ export async function createSniperApiRouter(deps = {}) {next();});+ // ── Web console ───────────────────────────────────────────────────────────────+ // The operator dashboard, served from the same origin as the API it drives.+ // GET / and GET /console both return it; every fetch it makes is same-origin.+ const serveConsole = (req, res) => {+ const html = consoleHtml();+ if (!html) return res.status(404).json({ error: 'web console asset not found' });+ res.setHeader('Content-Type', 'text/html; charset=utf-8');+ res.setHeader('Cache-Control', 'no-cache');+ return res.send(html);+ };+ router.get('/', serveConsole);+ router.get('/console', serveConsole);+// ── Free reads ──────────────────────────────────────────────────────────────+ // What the console needs to render the right controls: is there a paid lane,+ // and is an operator token configured (so mutations are reachable at all).+ const capabilities = () => ({ paid: x402Configured, adminAuth: Boolean(adminToken), prices });+// GET /health — liveness + a snapshot of network/mode/stats.router.get('/health', (req, res) => {res.json({@@ -165,12 +229,20 @@ export async function createSniperApiRouter(deps = {}) {network: sniper.config.network,mode: sniper.config.mode,stats: sniper.stats(),+ capabilities: capabilities(),});});// GET /status — full stats plus the immutable runtime config.router.get('/status', (req, res) => {- res.json({ stats: sniper.stats(), config: sniper.config });+ res.json({ stats: sniper.stats(), config: sniper.config, capabilities: capabilities() });+ });++ // GET /activity?limit= — recent engine screen events (newest last) for the feed.+ router.get('/activity', (req, res) => {+ const limit = Math.max(1, Math.min(Number(req.query.limit) || 60, 250));+ const events = typeof sniper.activity === 'function' ? sniper.activity(limit) : [];+ res.json({ events });});// GET /strategies — the armed strategy set the engine is evaluating.@@ -261,6 +333,24 @@ export async function createSniperApiRouter(deps = {}) {return res.status(404).json({ error: 'strategy not found' });}));+ // POST /positions/:id/close — schedule an exit. Flips the position's kill switch;+ // the next position sweep sells it through the normal exit path (same as the MCP+ // close_position tool), so the response is { scheduled: true } — the sell lands shortly.+ router.post('/positions/:id/close', gate('close', async (req, res) => {+ if (typeof store.listPositions !== 'function' || typeof store.updatePosition !== 'function') {+ return res.status(501).json({ error: 'store does not support closing positions' });+ }+ const id = req.params.id;+ const all = await store.listPositions({ network: sniper.config.network });+ const pos = all.find((p) => p.id === id);+ if (!pos) return res.status(404).json({ error: 'position not found' });+ if (pos.status === 'closed' || pos.status === 'failed') {+ return res.status(200).json({ ok: true, scheduled: false, id, status: pos.status, note: 'position already terminal' });+ }+ await store.updatePosition(id, { kill_switch: true });+ return res.status(202).json({ ok: true, scheduled: true, id });+ }));+return router;}@@ -320,7 +410,7 @@ export async function serve(deps = {}, { port = Number(process.env.PORT) || 8787return await new Promise((resolve) => {const server = app.listen(port, () => {// eslint-disable-next-line no-console -- this is a server entry point.- console.log(`[agent-sniper] HTTP API listening on :${port} (${sniper.config.network}/${sniper.config.mode})`);+ console.log(`[agent-sniper] HTTP API + console on http://localhost:${port} (${sniper.config.network}/${sniper.config.mode})`);resolve({ app, server, sniper });});});diff --git a/packages/agent-sniper/web/console.html b/packages/agent-sniper/web/console.htmlnew file mode 100644index 000000000..8c258199f--- /dev/null+++ b/packages/agent-sniper/web/console.html@@ -0,0 +1,809 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+<meta name="color-scheme" content="dark" />+<meta name="robots" content="noindex" />+<title>agent-sniper · console</title>+<style>+ /* ─────────────────────────────────────────────────────────────────────────+ agent-sniper console — a self-contained operator dashboard. No external+ assets: every style, script, and icon is inline so it runs offline and+ self-hosted, served straight from the x402 API face.+ ───────────────────────────────────────────────────────────────────────── */+ :root {+ --bg: #07090d;+ --bg-2: #0c1017;+ --panel: rgba(20, 26, 36, 0.72);+ --panel-solid: #131924;+ --stroke: rgba(255, 255, 255, 0.08);+ --stroke-2: rgba(255, 255, 255, 0.14);+ --text: #e8edf6;+ --text-dim: #93a1b8;+ --text-faint: #5e6b82;+ --accent: #2ee6a6;+ --accent-2: #16b985;+ --accent-glow: rgba(46, 230, 166, 0.35);+ --buy: #2ee6a6;+ --sell: #ff6b8a;+ --warn: #ffcf5c;+ --danger: #ff5c78;+ --info: #6ea8ff;+ --radius: 16px;+ --radius-sm: 11px;+ --shadow: 0 18px 50px -22px rgba(0, 0, 0, 0.9);+ --font: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, Helvetica, Arial, sans-serif;+ --mono: "SF Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;+ }+ * { box-sizing: border-box; }+ html, body { height: 100%; }+ body {+ margin: 0;+ font-family: var(--font);+ color: var(--text);+ background:+ radial-gradient(1100px 620px at 84% -8%, rgba(46, 230, 166, 0.10), transparent 60%),+ radial-gradient(900px 560px at 8% 4%, rgba(110, 168, 255, 0.08), transparent 55%),+ var(--bg);+ -webkit-font-smoothing: antialiased;+ text-rendering: optimizelegibility;+ letter-spacing: 0.1px;+ }+ a { color: inherit; }+ button { font-family: inherit; }+ .mono { font-family: var(--mono); font-variant-numeric: tabular-nums; }+ .num { font-variant-numeric: tabular-nums; }+ ::selection { background: var(--accent-glow); color: #04150f; }++ /* scrollbars */+ *::-webkit-scrollbar { width: 10px; height: 10px; }+ *::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.09); border-radius: 20px; border: 2px solid transparent; background-clip: padding-box; }+ *::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.16); background-clip: padding-box; }++ /* ── layout ── */+ .wrap { max-width: 1440px; margin: 0 auto; padding: 20px clamp(14px, 3vw, 34px) 64px; }++ /* ── top bar ── */+ header.topbar {+ position: sticky; top: 0; z-index: 40;+ display: flex; align-items: center; gap: 16px;+ padding: 14px clamp(14px, 3vw, 34px);+ background: linear-gradient(180deg, rgba(7, 9, 13, 0.92), rgba(7, 9, 13, 0.62));+ backdrop-filter: saturate(140%) blur(14px);+ -webkit-backdrop-filter: saturate(140%) blur(14px);+ border-bottom: 1px solid var(--stroke);+ }+ .brand { display: flex; align-items: center; gap: 12px; min-width: 0; }+ .logo {+ width: 38px; height: 38px; border-radius: 11px; flex: none;+ background: radial-gradient(120% 120% at 30% 20%, #22ffb0, #0c8f66 70%, #075c42);+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.12) inset, 0 8px 22px -8px var(--accent-glow);+ display: grid; place-items: center; position: relative;+ }+ .logo svg { width: 21px; height: 21px; }+ .logo::after { /* scope reticle ring */+ content: ""; position: absolute; inset: -4px; border-radius: 15px;+ border: 1px solid var(--accent-glow); opacity: 0.5;+ animation: ring 3.2s ease-in-out infinite;+ }+ @keyframes ring { 0%, 100% { transform: scale(1); opacity: 0.5; } 50% { transform: scale(1.12); opacity: 0; } }+ .brand-txt { display: flex; flex-direction: column; line-height: 1.05; min-width: 0; }+ .brand-txt b { font-size: 15px; letter-spacing: 0.2px; }+ .brand-txt span { font-size: 11px; color: var(--text-faint); }++ .badges { display: flex; align-items: center; gap: 8px; margin-left: 6px; flex-wrap: wrap; }+ .badge {+ display: inline-flex; align-items: center; gap: 7px;+ padding: 6px 11px; border-radius: 999px; font-size: 12px; font-weight: 600;+ border: 1px solid var(--stroke-2); background: rgba(255, 255, 255, 0.03); color: var(--text-dim);+ white-space: nowrap;+ }+ .badge .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; box-shadow: 0 0 8px currentColor; }+ .badge.mode-live { color: var(--danger); border-color: rgba(255, 92, 120, 0.4); background: rgba(255, 92, 120, 0.08); }+ .badge.mode-simulate { color: var(--accent); border-color: rgba(46, 230, 166, 0.35); background: rgba(46, 230, 166, 0.07); }+ .badge.net { color: var(--info); }+ .badge.net.mainnet { color: var(--warn); }++ .spacer { flex: 1 1 auto; }+ .conn { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; color: var(--text-dim); }+ .conn .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-faint); transition: background 0.3s, box-shadow 0.3s; }+ .conn.live .dot { background: var(--accent); box-shadow: 0 0 10px var(--accent-glow); animation: pulse 2s ease-in-out infinite; }+ .conn.down .dot { background: var(--danger); box-shadow: 0 0 10px rgba(255, 92, 120, 0.5); }+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }++ .iconbtn {+ display: inline-grid; place-items: center; width: 38px; height: 38px; flex: none;+ border-radius: 11px; border: 1px solid var(--stroke-2); background: rgba(255, 255, 255, 0.03);+ color: var(--text-dim); cursor: pointer; transition: all 0.16s ease;+ }+ .iconbtn:hover { color: var(--text); border-color: var(--stroke-2); background: rgba(255, 255, 255, 0.08); transform: translateY(-1px); }+ .iconbtn:active { transform: translateY(0); }+ .iconbtn.armed { color: var(--accent); border-color: rgba(46, 230, 166, 0.4); }+ .iconbtn svg { width: 18px; height: 18px; }+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 8px; }++ /* ── disconnected banner ── */+ .banner {+ margin: 14px 0 0; padding: 11px 15px; border-radius: 12px;+ border: 1px solid rgba(255, 92, 120, 0.35); background: rgba(255, 92, 120, 0.08);+ color: #ffd7de; font-size: 13px; display: none; align-items: center; gap: 10px;+ }+ .banner.show { display: flex; animation: slidein 0.3s ease; }+ @keyframes slidein { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }++ /* ── stat cards ── */+ .stats { display: grid; grid-template-columns: repeat(6, 1fr); gap: 12px; margin-top: 18px; }+ .stat {+ position: relative; overflow: hidden;+ padding: 15px 16px; border-radius: var(--radius-sm);+ border: 1px solid var(--stroke); background: var(--panel);+ backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);+ }+ .stat::before { content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background: var(--accent); opacity: 0.7; }+ .stat.s-sells::before { background: var(--sell); }+ .stat.s-buys::before { background: var(--buy); }+ .stat.s-queued::before { background: var(--warn); }+ .stat.s-strategies::before { background: var(--info); }+ .stat.s-candidates::before { background: #b78bff; }+ .stat .k { font-size: 11px; text-transform: uppercase; letter-spacing: 0.7px; color: var(--text-faint); font-weight: 600; }+ .stat .v { font-size: 30px; font-weight: 700; margin-top: 6px; letter-spacing: -0.5px; font-variant-numeric: tabular-nums; }+ .stat .sub { font-size: 11px; color: var(--text-faint); margin-top: 2px; }+ .stat .v.flash { animation: flash 0.6s ease; }+ @keyframes flash { 0% { color: var(--accent); text-shadow: 0 0 18px var(--accent-glow); } 100% { } }++ /* ── main grid ── */+ main { display: grid; grid-template-columns: 1.55fr 1fr; gap: 16px; margin-top: 16px; align-items: start; }+ .col { display: flex; flex-direction: column; gap: 16px; min-width: 0; }++ .panel {+ border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--panel);+ backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); box-shadow: var(--shadow);+ overflow: hidden;+ }+ .panel > .head {+ display: flex; align-items: center; gap: 10px; padding: 14px 16px;+ border-bottom: 1px solid var(--stroke);+ }+ .panel > .head h2 { margin: 0; font-size: 14px; font-weight: 650; letter-spacing: 0.2px; display: flex; align-items: center; gap: 9px; }+ .panel > .head h2 svg { width: 16px; height: 16px; color: var(--text-dim); }+ .panel > .head .count { font-size: 11px; color: var(--text-faint); background: rgba(255, 255, 255, 0.05); padding: 2px 8px; border-radius: 999px; font-variant-numeric: tabular-nums; }+ .panel > .head .hspacer { flex: 1; }+ .panel > .body { padding: 6px; }+ .panel > .body.pad { padding: 16px; }++ /* ── table ── */+ .tbl { width: 100%; border-collapse: collapse; font-size: 13px; }+ .tbl th { text-align: left; font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.6px; color: var(--text-faint); font-weight: 600; padding: 8px 10px; }+ .tbl td { padding: 11px 10px; border-top: 1px solid var(--stroke); vertical-align: middle; }+ .tbl tr { transition: background 0.14s; }+ .tbl tbody tr:hover { background: rgba(255, 255, 255, 0.025); }+ .tbl td.r, .tbl th.r { text-align: right; }+ .token { display: flex; align-items: center; gap: 10px; }+ .token .sym { font-weight: 650; }+ .token .addr { font-size: 11px; color: var(--text-faint); }+ .pill { display: inline-flex; align-items: center; gap: 6px; padding: 3px 9px; border-radius: 999px; font-size: 11px; font-weight: 600; border: 1px solid transparent; }+ .pill .d { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }+ .pill.open { color: var(--accent); background: rgba(46, 230, 166, 0.09); border-color: rgba(46, 230, 166, 0.28); }+ .pill.opening { color: var(--warn); background: rgba(255, 207, 92, 0.09); border-color: rgba(255, 207, 92, 0.28); }+ .pill.closing { color: var(--info); background: rgba(110, 168, 255, 0.09); border-color: rgba(110, 168, 255, 0.28); }+ .pill.closed { color: var(--text-dim); background: rgba(255, 255, 255, 0.05); border-color: var(--stroke-2); }+ .pill.failed { color: var(--danger); background: rgba(255, 92, 120, 0.09); border-color: rgba(255, 92, 120, 0.28); }+ .pnl { font-weight: 650; font-variant-numeric: tabular-nums; }+ .pnl.up { color: var(--buy); }+ .pnl.down { color: var(--sell); }+ .pnl.flat { color: var(--text-dim); }++ .rowbtn {+ border: 1px solid var(--stroke-2); background: rgba(255, 255, 255, 0.03); color: var(--text-dim);+ font-size: 12px; font-weight: 600; padding: 6px 11px; border-radius: 8px; cursor: pointer; transition: all 0.15s;+ }+ .rowbtn:hover { color: var(--danger); border-color: rgba(255, 92, 120, 0.4); background: rgba(255, 92, 120, 0.08); }+ .rowbtn:disabled { opacity: 0.4; cursor: default; }++ /* strategy card */+ .strat { padding: 13px 14px; border-radius: var(--radius-sm); border: 1px solid var(--stroke); margin: 8px; background: rgba(255, 255, 255, 0.015); transition: border-color 0.15s, transform 0.15s; }+ .strat:hover { border-color: var(--stroke-2); }+ .strat .top { display: flex; align-items: center; gap: 10px; }+ .strat .top .id { font-weight: 650; font-size: 13.5px; }+ .strat .top .agent { font-size: 11px; color: var(--text-faint); }+ .strat .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(88px, 1fr)); gap: 9px 14px; margin-top: 11px; }+ .strat .grid .kv { display: flex; flex-direction: column; gap: 2px; }+ .strat .grid .kv .k { font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-faint); }+ .strat .grid .kv .val { font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums; }+ .tag { font-size: 10.5px; padding: 2px 8px; border-radius: 6px; background: rgba(110, 168, 255, 0.1); color: var(--info); font-weight: 600; }+ .tag.sl { background: rgba(255, 92, 120, 0.1); color: var(--sell); }+ .tag.tp { background: rgba(46, 230, 166, 0.1); color: var(--buy); }++ /* ── forms ── */+ .form { display: flex; flex-direction: column; gap: 12px; }+ .field { display: flex; flex-direction: column; gap: 6px; }+ .field label { font-size: 11.5px; color: var(--text-dim); font-weight: 600; display: flex; align-items: center; gap: 6px; }+ .field label .req { color: var(--accent); }+ .field .hint { font-size: 10.5px; color: var(--text-faint); font-weight: 400; }+ .grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }+ .grid3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; }+ input, select {+ width: 100%; padding: 10px 12px; border-radius: 10px; font-size: 13.5px; font-family: inherit;+ background: rgba(0, 0, 0, 0.28); border: 1px solid var(--stroke-2); color: var(--text);+ transition: border-color 0.15s, box-shadow 0.15s, background 0.15s; font-variant-numeric: tabular-nums;+ }+ input::placeholder { color: var(--text-faint); }+ input:focus, select:focus { outline: none; border-color: var(--accent-2); box-shadow: 0 0 0 3px rgba(46, 230, 166, 0.14); background: rgba(0, 0, 0, 0.4); }+ select { appearance: none; background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2393a1b8' stroke-width='2.5'><path d='M6 9l6 6 6-6'/></svg>"); background-repeat: no-repeat; background-position: right 12px center; padding-right: 34px; }++ .btn {+ display: inline-flex; align-items: center; justify-content: center; gap: 9px;+ padding: 11px 16px; border-radius: 11px; font-size: 13.5px; font-weight: 650; cursor: pointer;+ border: 1px solid transparent; transition: transform 0.12s, box-shadow 0.15s, filter 0.15s, background 0.15s; width: 100%;+ }+ .btn svg { width: 16px; height: 16px; }+ .btn.primary { background: linear-gradient(180deg, #34f0af, var(--accent-2)); color: #032015; box-shadow: 0 10px 26px -12px var(--accent-glow); }+ .btn.primary:hover { transform: translateY(-1px); filter: brightness(1.05); box-shadow: 0 14px 30px -12px var(--accent-glow); }+ .btn.primary:active { transform: translateY(0); }+ .btn.danger { background: linear-gradient(180deg, #ff728e, #ec4b6c); color: #2a0009; }+ .btn.ghost { background: rgba(255, 255, 255, 0.04); border-color: var(--stroke-2); color: var(--text); }+ .btn.ghost:hover { background: rgba(255, 255, 255, 0.09); }+ .btn:disabled { opacity: 0.55; cursor: default; transform: none !important; filter: none !important; }+ .btn .spin { width: 15px; height: 15px; border: 2px solid rgba(0,0,0,0.25); border-top-color: currentColor; border-radius: 50%; animation: spin 0.7s linear infinite; }+ @keyframes spin { to { transform: rotate(360deg); } }++ /* ── activity ── */+ .feed { max-height: 420px; overflow-y: auto; padding: 6px; display: flex; flex-direction: column; gap: 2px; }+ .evt { display: flex; align-items: flex-start; gap: 11px; padding: 9px 11px; border-radius: 10px; font-size: 13px; transition: background 0.14s; }+ .evt:hover { background: rgba(255, 255, 255, 0.03); }+ .evt .ic { width: 24px; height: 24px; border-radius: 7px; flex: none; display: grid; place-items: center; margin-top: 1px; }+ .evt .ic svg { width: 13px; height: 13px; }+ .evt.trade .ic { background: rgba(46, 230, 166, 0.12); color: var(--buy); }+ .evt.alert .ic { background: rgba(255, 92, 120, 0.12); color: var(--danger); }+ .evt.activity .ic { background: rgba(110, 168, 255, 0.12); color: var(--info); }+ .evt.info .ic { background: rgba(255, 255, 255, 0.06); color: var(--text-dim); }+ .evt .txt { flex: 1; min-width: 0; line-height: 1.35; word-break: break-word; }+ .evt .t { font-size: 10.5px; color: var(--text-faint); white-space: nowrap; margin-top: 2px; font-variant-numeric: tabular-nums; }+ .evt.new { animation: evtin 0.4s ease; }+ @keyframes evtin { from { opacity: 0; transform: translateX(-8px); } to { opacity: 1; transform: none; } }++ /* ── empty / skeleton ── */+ .empty { padding: 34px 20px; text-align: center; color: var(--text-faint); }+ .empty svg { width: 34px; height: 34px; opacity: 0.5; margin-bottom: 10px; }+ .empty b { display: block; color: var(--text-dim); font-size: 13.5px; margin-bottom: 4px; font-weight: 600; }+ .empty span { font-size: 12.5px; }+ .skel { height: 44px; margin: 8px; border-radius: 10px; background: linear-gradient(100deg, rgba(255,255,255,0.03) 30%, rgba(255,255,255,0.07) 50%, rgba(255,255,255,0.03) 70%); background-size: 200% 100%; animation: sheen 1.4s infinite; }+ @keyframes sheen { to { background-position: -200% 0; } }++ /* ── toasts ── */+ .toasts { position: fixed; right: 18px; bottom: 18px; z-index: 90; display: flex; flex-direction: column; gap: 10px; max-width: min(92vw, 380px); }+ .toast {+ display: flex; align-items: flex-start; gap: 11px; padding: 13px 15px; border-radius: 12px;+ background: var(--panel-solid); border: 1px solid var(--stroke-2); box-shadow: var(--shadow);+ font-size: 13px; animation: toastin 0.28s cubic-bezier(0.2, 0.9, 0.3, 1); color: var(--text);+ }+ .toast.out { animation: toastout 0.25s ease forwards; }+ @keyframes toastin { from { opacity: 0; transform: translateX(16px) scale(0.98); } to { opacity: 1; transform: none; } }+ @keyframes toastout { to { opacity: 0; transform: translateX(16px); } }+ .toast .ic { width: 20px; height: 20px; flex: none; margin-top: 1px; }+ .toast.ok .ic { color: var(--accent); }+ .toast.err .ic { color: var(--danger); }+ .toast.info .ic { color: var(--info); }+ .toast .body b { display: block; margin-bottom: 2px; }+ .toast .body span { color: var(--text-dim); }++ /* ── drawer / modal ── */+ .scrim { position: fixed; inset: 0; background: rgba(3, 5, 8, 0.6); backdrop-filter: blur(3px); z-index: 60; opacity: 0; pointer-events: none; transition: opacity 0.2s; }+ .scrim.show { opacity: 1; pointer-events: auto; }+ .drawer {+ position: fixed; top: 0; right: 0; bottom: 0; width: min(420px, 94vw); z-index: 70;+ background: var(--bg-2); border-left: 1px solid var(--stroke-2); box-shadow: -30px 0 60px -30px rgba(0,0,0,0.8);+ transform: translateX(100%); transition: transform 0.28s cubic-bezier(0.2, 0.9, 0.3, 1);+ display: flex; flex-direction: column; padding: 22px; gap: 18px; overflow-y: auto;+ }+ .drawer.show { transform: none; }+ .drawer h3 { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 9px; }+ .drawer p { margin: 0; font-size: 13px; color: var(--text-dim); line-height: 1.5; }+ .drawer .close { position: absolute; top: 16px; right: 16px; }+ .kbd { font-family: var(--mono); font-size: 11px; padding: 2px 7px; border-radius: 6px; border: 1px solid var(--stroke-2); background: rgba(255,255,255,0.04); color: var(--text-dim); }+ .shortcut-row { display: flex; align-items: center; justify-content: space-between; padding: 9px 0; border-bottom: 1px solid var(--stroke); font-size: 13px; }+ .authstate { display: inline-flex; align-items: center; gap: 7px; font-size: 12px; padding: 5px 10px; border-radius: 8px; }+ .authstate.on { color: var(--accent); background: rgba(46, 230, 166, 0.08); }+ .authstate.off { color: var(--text-faint); background: rgba(255, 255, 255, 0.04); }++ /* ── responsive ── */+ @media (max-width: 1080px) {+ .stats { grid-template-columns: repeat(3, 1fr); }+ main { grid-template-columns: 1fr; }+ }+ @media (max-width: 620px) {+ .stats { grid-template-columns: repeat(2, 1fr); }+ .brand-txt span { display: none; }+ .grid2, .grid3 { grid-template-columns: 1fr; }+ .badges .badge.net { display: none; }+ .wrap { padding-bottom: 40px; }+ }+ @media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }+</style>+</head>+<body>+<header class="topbar">+ <div class="brand">+ <div class="logo" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="#04150f" stroke-width="2.2" stroke-linecap="round"><circle cx="12" cy="12" r="7.5"/><path d="M12 1.5v4M12 18.5v4M22.5 12h-4M5.5 12h-4"/><circle cx="12" cy="12" r="1.6" fill="#04150f" stroke="none"/></svg>+ </div>+ <div class="brand-txt">+ <b>agent-sniper</b>+ <span>operator console</span>+ </div>+ </div>+ <div class="badges" id="badges"></div>+ <div class="spacer"></div>+ <div class="conn" id="conn" title="Connection status"><span class="dot"></span><span id="conn-txt">connecting…</span></div>+ <button class="iconbtn" id="btn-shortcuts" title="Keyboard shortcuts (?)" aria-label="Keyboard shortcuts">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 10h.01M10 10h.01M14 10h.01M18 10h.01M7 14h10"/></svg>+ </button>+ <button class="iconbtn" id="btn-settings" title="Operator settings (,)" aria-label="Settings">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>+ </button>+</header>++<div class="wrap">+ <div class="banner" id="banner">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"/></svg>+ <span id="banner-txt">Can't reach the sniper API — retrying…</span>+ </div>++ <section class="stats" id="stats"></section>++ <main>+ <div class="col">+ <!-- POSITIONS -->+ <div class="panel">+ <div class="head">+ <h2><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 3v18h18"/><path d="M7 14l4-4 3 3 5-6"/></svg> Positions</h2>+ <span class="count" id="pos-count">—</span>+ <div class="hspacer"></div>+ <span class="mono" id="pnl-total" style="font-size:12px;color:var(--text-dim)"></span>+ </div>+ <div class="body" id="pos-body"></div>+ </div>++ <!-- STRATEGIES -->+ <div class="panel">+ <div class="head">+ <h2><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2 2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5M2 12l10 5 10-5"/></svg> Armed strategies</h2>+ <span class="count" id="strat-count">—</span>+ </div>+ <div class="body" id="strat-body"></div>+ </div>+ </div>++ <div class="col">+ <!-- SNIPE -->+ <div class="panel">+ <div class="head"><h2><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M12 3v3M12 18v3M21 12h-3M6 12H3"/><circle cx="12" cy="12" r="1" fill="currentColor"/></svg> Manual snipe</h2></div>+ <div class="body pad">+ <form class="form" id="snipe-form" autocomplete="off">+ <div class="field">+ <label for="snipe-mint">Mint address <span class="req">*</span></label>+ <input id="snipe-mint" name="mint" placeholder="Pump.fun token mint…" required />+ </div>+ <div class="field">+ <label for="snipe-symbol">Ticker <span class="hint">optional · for the feed</span></label>+ <input id="snipe-symbol" name="symbol" placeholder="e.g. WIF" />+ </div>+ <button class="btn primary" type="submit" id="snipe-btn">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/></svg>+ Fire snipe+ </button>+ <p style="margin:0;font-size:11.5px;color:var(--text-faint);text-align:center">Forces a buy across every armed agent · simulate mode moves no funds</p>+ </form>+ </div>+ </div>++ <!-- ARM STRATEGY -->+ <div class="panel">+ <div class="head"><h2><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg> Arm a strategy</h2></div>+ <div class="body pad">+ <form class="form" id="arm-form" autocomplete="off">+ <div class="grid2">+ <div class="field">+ <label for="arm-agent">Agent ID <span class="req">*</span></label>+ <input id="arm-agent" name="agent_id" placeholder="scout" required />+ </div>+ <div class="field">+ <label for="arm-trigger">Trigger</label>+ <select id="arm-trigger" name="trigger">+ <option value="new_mint">New mint</option>+ <option value="intel_confirmed">Intel confirmed</option>+ <option value="first_claim">First claim</option>+ <option value="manual">Manual only</option>+ </select>+ </div>+ </div>+ <div class="grid2">+ <div class="field">+ <label for="arm-pertrade">Per-trade (SOL) <span class="req">*</span></label>+ <input id="arm-pertrade" name="per_trade_sol" type="number" step="0.001" min="0" value="0.05" required />+ </div>+ <div class="field">+ <label for="arm-budget">Daily budget (SOL) <span class="req">*</span></label>+ <input id="arm-budget" name="daily_budget_sol" type="number" step="0.01" min="0" value="1" required />+ </div>+ </div>+ <div class="grid3">+ <div class="field">+ <label for="arm-sl">Stop-loss % <span class="req">*</span></label>+ <input id="arm-sl" name="stop_loss_pct" type="number" step="1" min="1" value="35" required />+ </div>+ <div class="field">+ <label for="arm-tp">Take-profit %</label>+ <input id="arm-tp" name="take_profit_pct" type="number" step="1" min="0" value="80" />+ </div>+ <div class="field">+ <label for="arm-trail">Trailing %</label>+ <input id="arm-trail" name="trailing_stop_pct" type="number" step="1" min="0" value="20" />+ </div>+ </div>+ <div class="grid3">+ <div class="field">+ <label for="arm-slip">Slippage bps</label>+ <input id="arm-slip" name="slippage_bps" type="number" step="1" min="0" value="500" />+ </div>+ <div class="field">+ <label for="arm-hold">Max hold (s)</label>+ <input id="arm-hold" name="max_hold_seconds" type="number" step="1" min="1" value="1800" />+ </div>+ <div class="field">+ <label for="arm-net">Network</label>+ <select id="arm-net" name="network">+ <option value="mainnet">Mainnet</option>+ <option value="devnet">Devnet</option>+ </select>+ </div>+ </div>+ <button class="btn primary" type="submit" id="arm-btn">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 5v14M5 12h14"/></svg>+ Arm strategy+ </button>+ </form>+ </div>+ </div>++ <!-- ACTIVITY -->+ <div class="panel">+ <div class="head">+ <h2><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg> Live activity</h2>+ <div class="hspacer"></div>+ <span class="count" id="act-count">0</span>+ </div>+ <div class="feed" id="feed"></div>+ </div>+ </div>+ </main>+</div>++<!-- settings drawer -->+<div class="scrim" id="scrim"></div>+<aside class="drawer" id="drawer" aria-hidden="true">+ <button class="iconbtn close" id="drawer-close" aria-label="Close"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6 6 18M6 6l12 12"/></svg></button>+ <div id="drawer-content"></div>+</aside>++<div class="toasts" id="toasts" aria-live="polite"></div>++<script>+(() => {+ "use strict";+ const LAMPORTS = 1e9;+ const POLL_MS = 2200;+ const TOKEN_KEY = "agent-sniper.admin-token";+ const $ = (s, r = document) => r.querySelector(s);+ const el = (t, c, h) => { const e = document.createElement(t); if (c) e.className = c; if (h != null) e.innerHTML = h; return e; };+ const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, (m) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[m]));+ const short = (a) => !a ? "" : a.length <= 12 ? a : a.slice(0, 4) + "…" + a.slice(-4);+ const nfmt = (n) => new Intl.NumberFormat("en-US").format(n);+ const sol = (lam) => { const v = Number(lam || 0) / LAMPORTS; return v === 0 ? "0" : v < 0.001 ? v.toExponential(1) : v.toFixed(v < 1 ? 4 : 3); };+ const ago = (ts) => { if (!ts) return ""; const s = Math.max(0, (Date.now() - ts) / 1000); if (s < 60) return Math.floor(s) + "s"; if (s < 3600) return Math.floor(s / 60) + "m"; if (s < 86400) return Math.floor(s / 3600) + "h"; return Math.floor(s / 86400) + "d"; };++ const state = { token: localStorage.getItem(TOKEN_KEY) || "", caps: { paid: false, adminAuth: false, prices: {} }, config: {}, stats: {}, positions: [], strategies: [], activity: [], connected: null, lastActLen: 0, prevStats: {} };++ // ── networking ──────────────────────────────────────────────────────────+ async function api(path, opts = {}) {+ const headers = Object.assign({ "Content-Type": "application/json" }, opts.headers || {});+ if (state.token) headers["X-Admin-Token"] = state.token;+ const res = await fetch(path, Object.assign({}, opts, { headers }));+ let data = null;+ try { data = await res.json(); } catch { /* non-JSON */ }+ if (!res.ok) { const e = new Error((data && data.error) || ("HTTP " + res.status)); e.status = res.status; e.data = data; throw e; }+ return data;+ }++ // ── toasts ──────────────────────────────────────────────────────────────+ const ICONS = {+ ok: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4"><path d="M20 6 9 17l-5-5"/></svg>',+ err: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6M9 9l6 6"/></svg>',+ info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>',+ };+ function toast(type, title, msg, ms = 4600) {+ const t = el("div", "toast " + type);+ t.innerHTML = '<div class="ic">' + (ICONS[type] || ICONS.info) + '</div><div class="body"><b>' + esc(title) + '</b>' + (msg ? '<span>' + esc(msg) + '</span>' : '') + '</div>';+ $("#toasts").appendChild(t);+ const kill = () => { t.classList.add("out"); setTimeout(() => t.remove(), 260); };+ t.addEventListener("click", kill);+ setTimeout(kill, ms);+ }++ // ── stat cards ──────────────────────────────────────────────────────────+ const STAT_DEFS = [+ { k: "buys", label: "Buys", cls: "s-buys" },+ { k: "sells", label: "Sells", cls: "s-sells" },+ { k: "candidates", label: "Candidates", cls: "s-candidates" },+ { k: "strategies", label: "Armed", cls: "s-strategies" },+ { k: "queued", label: "In flight", cls: "s-queued" },+ { k: "events", label: "Signals", cls: "s-events" },+ ];+ function buildStats() {+ const wrap = $("#stats"); wrap.innerHTML = "";+ for (const d of STAT_DEFS) {+ const c = el("div", "stat " + d.cls);+ c.innerHTML = '<div class="k">' + d.label + '</div><div class="v" id="stat-' + d.k + '">0</div><div class="sub" id="statsub-' + d.k + '"> </div>';+ wrap.appendChild(c);+ }+ }+ function tween(elm, from, to) {+ if (from === to) { elm.textContent = nfmt(to); return; }+ elm.classList.remove("flash"); void elm.offsetWidth; elm.classList.add("flash");+ const dur = 480, t0 = performance.now();+ const step = (t) => { const p = Math.min(1, (t - t0) / dur); const e = 1 - Math.pow(1 - p, 3); elm.textContent = nfmt(Math.round(from + (to - from) * e)); if (p < 1) requestAnimationFrame(step); };+ requestAnimationFrame(step);+ }+ function renderStats() {+ const s = state.stats || {};+ for (const d of STAT_DEFS) {+ const cur = Number(s[d.k] || 0), prev = Number(state.prevStats[d.k] || 0);+ const elm = $("#stat-" + d.k); if (elm) tween(elm, prev, cur);+ }+ const sub = $("#statsub-events"); if (sub) sub.textContent = s.lastEventAt ? "last " + ago(s.lastEventAt) + " ago" : "—";+ const qsub = $("#statsub-queued"); if (qsub) qsub.textContent = (s.errors ? nfmt(s.errors) + " errors" : " ");+ state.prevStats = Object.assign({}, s);+ }++ // ── badges + connection ───────────────────────────────────────────────────+ function renderBadges() {+ const c = state.config || {}, b = $("#badges"); if (!c.mode) { b.innerHTML = ""; return; }+ const live = c.mode === "live";+ b.innerHTML =+ '<span class="badge mode-' + esc(c.mode) + '"><span class="dot"></span>' + (live ? "LIVE" : "SIMULATE") + '</span>' ++ '<span class="badge net ' + esc(c.network || "") + '">' + esc(c.network || "?") + '</span>' ++ (state.caps.adminAuth ? '<span class="badge" style="color:var(--accent)" title="Operator auth available"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" style="margin-right:-2px"><path d="M12 2 4 5v6c0 5 3.5 8 8 10 4.5-2 8-5 8-10V5l-8-3z"/></svg>secured</span>' : '');+ }+ function setConn(up) {+ if (state.connected === up) return; state.connected = up;+ const c = $("#conn"); c.classList.toggle("live", up); c.classList.toggle("down", !up);+ $("#conn-txt").textContent = up ? "live" : "offline";+ $("#banner").classList.toggle("show", !up);+ }++ // ── positions ─────────────────────────────────────────────────────────────+ const PILL_STATE = { open: "open", opening: "opening", closing: "closing", closed: "closed", failed: "failed" };+ function pnlOf(p) {+ const entry = Number(p.entry_quote_lamports || 0);+ if (p.status === "closed" && p.realized_pnl_pct != null) return { pct: Number(p.realized_pnl_pct), lam: Number(p.realized_pnl_lamports || 0), realized: true };+ const val = Number(p.last_value_lamports != null ? p.last_value_lamports : p.peak_value_lamports || entry);+ if (!entry) return { pct: 0, lam: 0, realized: false };+ return { pct: ((val - entry) / entry) * 100, lam: val - entry, realized: false };+ }+ function renderPositions() {+ const body = $("#pos-body"), list = state.positions || [];+ $("#pos-count").textContent = list.length ? nfmt(list.length) : "—";+ // total unrealized P&L on open positions+ let totLam = 0, anyOpen = false;+ for (const p of list) { if (p.status === "open" || p.status === "opening") { anyOpen = true; totLam += pnlOf(p).lam; } }+ const pt = $("#pnl-total");+ pt.innerHTML = anyOpen ? ('unrealized <b class="pnl ' + (totLam >= 0 ? "up" : "down") + '">' + (totLam >= 0 ? "+" : "") + sol(totLam) + " SOL</b>") : "";+ if (!list.length) {+ body.innerHTML = '<div class="empty"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M3 3v18h18"/><path d="M7 14l4-4 3 3 5-6"/></svg><b>No positions yet</b><span>Arm a strategy or fire a manual snipe to open your first position.</span></div>';+ return;+ }+ const rows = list.slice().sort((a, b) => (b.opened_at || 0) - (a.opened_at || 0)).map((p) => {+ const sym = esc((p.symbol || (p.mint || "").slice(0, 6)).toUpperCase());+ const st = PILL_STATE[p.status] || "closed";+ const pnl = pnlOf(p);+ const dir = pnl.pct > 0.05 ? "up" : pnl.pct < -0.05 ? "down" : "flat";+ const terminal = p.status === "closed" || p.status === "failed";+ const entrySol = sol(p.entry_quote_lamports);+ const valSol = sol(p.last_value_lamports != null ? p.last_value_lamports : p.peak_value_lamports || p.entry_quote_lamports);+ return '<tr>' ++ '<td><div class="token"><div><div class="sym">$' + sym + '</div><div class="addr mono">' + esc(short(p.mint)) + '</div></div></div></td>' ++ '<td><span class="pill ' + st + '"><span class="d"></span>' + esc(p.status || "?") + '</span>' + (p.exit_reason ? '<div class="addr" style="margin-top:3px">' + esc(p.exit_reason) + '</div>' : '') + '</td>' ++ '<td class="r mono">' + entrySol + '</td>' ++ '<td class="r mono">' + valSol + '</td>' ++ '<td class="r"><span class="pnl ' + dir + '">' + (pnl.pct >= 0 ? "+" : "") + pnl.pct.toFixed(1) + '%</span></td>' ++ '<td class="r">' + (terminal ? '' : '<button class="rowbtn" data-close="' + esc(p.id) + '">Close</button>') + '</td>' ++ '</tr>';+ }).join("");+ body.innerHTML = '<table class="tbl"><thead><tr><th>Token</th><th>Status</th><th class="r">Entry ◎</th><th class="r">Value ◎</th><th class="r">P&L</th><th class="r"></th></tr></thead><tbody>' + rows + '</tbody></table>';+ body.querySelectorAll("[data-close]").forEach((b) => b.addEventListener("click", () => closePosition(b.getAttribute("data-close"), b)));+ }++ // ── strategies ────────────────────────────────────────────────────────────+ function renderStrategies() {+ const body = $("#strat-body"), list = state.strategies || [];+ $("#strat-count").textContent = list.length ? nfmt(list.length) : "—";+ if (!list.length) {+ body.innerHTML = '<div class="empty"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M12 2 2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5M2 12l10 5 10-5"/></svg><b>No armed strategies</b><span>Use “Arm a strategy” to start scoring and sniping new mints.</span></div>';+ return;+ }+ body.innerHTML = list.map((s) => {+ const kv = (k, v) => '<div class="kv"><div class="k">' + k + '</div><div class="val">' + v + '</div></div>';+ return '<div class="strat">' ++ '<div class="top"><span class="id">' + esc(s.id) + '</span><span class="agent">· ' + esc(s.agent_id) + '</span>' ++ '<div style="flex:1"></div><span class="tag">' + esc(s.trigger || "new_mint") + '</span>' ++ '<button class="rowbtn" data-disarm="' + esc(s.id) + '">Disarm</button></div>' ++ '<div class="grid">' ++ kv("Per trade", sol(s.per_trade_lamports) + " ◎") ++ kv("Daily", sol(s.daily_budget_lamports) + " ◎") ++ kv("Stop-loss", '<span class="tag sl">' + esc(s.stop_loss_pct) + '%</span>') ++ (s.take_profit_pct != null ? kv("Take-profit", '<span class="tag tp">' + esc(s.take_profit_pct) + '%</span>') : "") ++ (s.trailing_stop_pct != null ? kv("Trailing", esc(s.trailing_stop_pct) + "%") : "") ++ (s.slippage_bps != null ? kv("Slippage", esc(s.slippage_bps) + " bps") : "") ++ kv("Network", esc(s.network || "mainnet")) ++ '</div></div>';+ }).join("");+ body.querySelectorAll("[data-disarm]").forEach((b) => b.addEventListener("click", () => disarm(b.getAttribute("data-disarm"), b)));+ }++ // ── activity feed ───────────────────────────────────────────────────────────+ const EVT_ICON = {+ trade: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M3 17l6-6 4 4 8-8"/><path d="M21 7v4h-4"/></svg>',+ alert: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"/></svg>',+ activity: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>',+ info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4M12 8h.01"/></svg>',+ };+ function renderActivity() {+ const feed = $("#feed"), list = state.activity || [];+ $("#act-count").textContent = nfmt(list.length);+ if (!list.length) {+ feed.innerHTML = '<div class="empty"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg><b>Waiting for the first signal…</b><span>New-mint events, scores, buys and exits stream in here live.</span></div>';+ return;+ }+ const fresh = list.length - state.lastActLen;+ feed.innerHTML = list.slice().reverse().map((e, i) => {+ const kind = EVT_ICON[e.kind] ? e.kind : "info";+ return '<div class="evt ' + kind + (i < fresh && state.lastActLen > 0 ? " new" : "") + '"><div class="ic">' + EVT_ICON[kind] + '</div><div class="txt">' + esc(e.text) + '</div><div class="t">' + ago(e.at) + '</div></div>';+ }).join("");+ state.lastActLen = list.length;+ }++ // ── mutations ─────────────────────────────────────────────────────────────+ function needsAuthMsg(e) {+ if (e.status === 402) return ["Payment required", "This endpoint is x402-paid. Add your operator token in Settings to control it directly."];+ if (e.status === 503) return ["Controls locked", (e.data && e.data.error) || "Set an operator token (Settings) or configure x402 to enable mutations."];+ return null;+ }+ function handleMutErr(e) {+ const na = needsAuthMsg(e);+ if (na) { toast("err", na[0], na[1]); openDrawer("settings"); return; }+ toast("err", "Failed", e.message || "Request failed");+ }+ async function withBtn(btn, label, fn) {+ if (!btn) return fn();+ const orig = btn.innerHTML; btn.disabled = true; btn.innerHTML = '<span class="spin"></span>' + (label || "");+ try { return await fn(); } finally { btn.disabled = false; btn.innerHTML = orig; }+ }+ async function armStrategy(form) {+ const fd = new FormData(form), body = {};+ for (const [k, v] of fd.entries()) { if (v === "") continue; body[k] = ["agent_id", "trigger", "network"].includes(k) ? v : Number(v); }+ if (!body.stop_loss_pct && body.stop_loss_pct !== 0) return toast("err", "Stop-loss required", "Every strategy needs a mandatory stop-loss %.");+ await withBtn($("#arm-btn"), "Arming…", async () => {+ const r = await api("/strategies", { method: "POST", body: JSON.stringify(body) });+ toast("ok", "Strategy armed", "$" + (r.strategy ? r.strategy.agent_id : body.agent_id) + " is now scoring candidates.");+ refresh();+ }).catch(handleMutErr);+ }+ async function snipe(form) {+ const fd = new FormData(form), mint = (fd.get("mint") || "").trim();+ if (!mint) return toast("err", "Mint required", "Paste a pump.fun token mint to snipe.");+ const body = { mint }; const sym = (fd.get("symbol") || "").trim(); if (sym) body.symbol = sym;+ await withBtn($("#snipe-btn"), "Firing…", async () => {+ await api("/snipe", { method: "POST", body: JSON.stringify(body) });+ toast("ok", "Snipe queued", short(mint) + " sent to every armed agent.");+ form.reset(); refresh();+ }).catch(handleMutErr);+ }+ async function disarm(id, btn) {+ await withBtn(btn, "", async () => {+ await api("/strategies/" + encodeURIComponent(id) + "/disarm", { method: "POST" });+ toast("ok", "Disarmed", id + " will stop sniping on the next refresh.");+ refresh();+ }).catch(handleMutErr);+ }+ async function closePosition(id, btn) {+ await withBtn(btn, "", async () => {+ await api("/positions/" + encodeURIComponent(id) + "/close", { method: "POST" });+ toast("ok", "Exit scheduled", "Position will sell on the next sweep.");+ refresh();+ }).catch(handleMutErr);+ }++ // ── settings / shortcuts drawer ─────────────────────────────────────────────+ function openDrawer(which) {+ const content = $("#drawer-content");+ if (which === "shortcuts") {+ content.innerHTML =+ '<h3><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 10h.01M10 10h.01M14 10h.01M18 10h.01M7 14h10"/></svg> Keyboard shortcuts</h3>' ++ [["s", "Focus manual snipe"], ["n", "Focus new strategy"], ["r", "Refresh now"], [",", "Open settings"], ["?", "This help"], ["Esc", "Close panels"]]+ .map(([k, d]) => '<div class="shortcut-row"><span>' + d + '</span><span class="kbd">' + k + '</span></div>').join("");+ } else {+ const authed = !!state.token;+ content.innerHTML =+ '<h3><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2 4 5v6c0 5 3.5 8 8 10 4.5-2 8-5 8-10V5l-8-3z"/></svg> Operator settings</h3>' ++ '<p>Reads are always free. The mutating controls (arm, snipe, disarm, close) are x402-paid for external agents. Paste your <b>operator token</b> to control this sniper directly without paying — it is sent as <span class="kbd">X-Admin-Token</span> and stored only in this browser.</p>' ++ '<div class="field"><label for="tok">Operator token</label><input id="tok" type="password" placeholder="SNIPER_ADMIN_TOKEN…" value="' + esc(state.token) + '" /></div>' ++ '<div style="display:flex;gap:10px"><button class="btn primary" id="tok-save" style="flex:1">Save token</button><button class="btn ghost" id="tok-clear" style="flex:0 0 auto">Clear</button></div>' ++ '<div style="margin-top:4px"><span class="authstate ' + (authed ? "on" : "off") + '" id="authstate">' + (authed ? "Operator token set" : "No token — mutations use x402") + '</span></div>' ++ '<p style="margin-top:8px;font-size:11.5px;color:var(--text-faint)">Server capabilities · paid lane: <b>' + (state.caps.paid ? "on" : "off") + '</b> · operator auth: <b>' + (state.caps.adminAuth ? "enabled" : "off") + '</b></p>';+ content.querySelector("#tok-save").addEventListener("click", () => {+ const v = content.querySelector("#tok").value.trim(); state.token = v;+ if (v) localStorage.setItem(TOKEN_KEY, v); else localStorage.removeItem(TOKEN_KEY);+ toast("ok", "Saved", v ? "Operator token stored in this browser." : "Token cleared."); closeDrawer(); refresh();+ });+ content.querySelector("#tok-clear").addEventListener("click", () => { content.querySelector("#tok").value = ""; });+ }+ $("#scrim").classList.add("show"); $("#drawer").classList.add("show"); $("#drawer").setAttribute("aria-hidden", "false");+ }+ function closeDrawer() { $("#scrim").classList.remove("show"); $("#drawer").classList.remove("show"); $("#drawer").setAttribute("aria-hidden", "true"); }++ // ── refresh loop ────────────────────────────────────────────────────────────+ let timer = null, inflight = false;+ async function refresh() {+ if (inflight) return; inflight = true;+ try {+ const [status, positions, activity, strat] = await Promise.all([+ api("/status"), api("/positions"), api("/activity?limit=80"), api("/strategies"),+ ]);+ state.config = status.config || {};+ state.stats = status.stats || {};+ state.caps = status.capabilities || state.caps;+ state.positions = (positions && positions.positions) || [];+ state.strategies = (strat && strat.strategies) || [];+ state.activity = (activity && activity.events) || [];+ setConn(true);+ renderBadges(); renderStats(); renderPositions(); renderStrategies(); renderActivity();+ } catch (e) {+ setConn(false);+ } finally { inflight = false; }+ }+ function loop() { clearTimeout(timer); refresh().finally(() => { timer = setTimeout(loop, POLL_MS); }); }++ // ── wire up ─────────────────────────────────────────────────────────────────+ function init() {+ buildStats();+ // skeletons while first load runs+ $("#pos-body").innerHTML = '<div class="skel"></div><div class="skel"></div><div class="skel"></div>';+ $("#strat-body").innerHTML = '<div class="skel"></div><div class="skel"></div>';++ $("#arm-form").addEventListener("submit", (e) => { e.preventDefault(); armStrategy(e.target); });+ $("#snipe-form").addEventListener("submit", (e) => { e.preventDefault(); snipe(e.target); });+ $("#btn-settings").addEventListener("click", () => openDrawer("settings"));+ $("#btn-shortcuts").addEventListener("click", () => openDrawer("shortcuts"));+ $("#drawer-close").addEventListener("click", closeDrawer);+ $("#scrim").addEventListener("click", closeDrawer);++ document.addEventListener("keydown", (e) => {+ if (e.key === "Escape") { closeDrawer(); return; }+ const tag = (e.target.tagName || "").toLowerCase();+ if (tag === "input" || tag === "select" || tag === "textarea" || e.metaKey || e.ctrlKey || e.altKey) return;+ if (e.key === "s") { e.preventDefault(); $("#snipe-mint").focus(); }+ else if (e.key === "n") { e.preventDefault(); $("#arm-agent").focus(); }+ else if (e.key === "r") { e.preventDefault(); refresh(); toast("info", "Refreshed", ""); }+ else if (e.key === ",") { e.preventDefault(); openDrawer("settings"); }+ else if (e.key === "?") { e.preventDefault(); openDrawer("shortcuts"); }+ });+ // keep relative times fresh even between polls+ setInterval(() => { if (state.activity.length) renderActivity(); renderStats(); }, 1000);+ loop();+ }+ document.addEventListener("DOMContentLoaded", init);+})();+</script>+</body>+</html>diff --git a/pages/admin/seeder.html b/pages/admin/seeder.htmlnew file mode 100644index 000000000..720719b1f--- /dev/null+++ b/pages/admin/seeder.html@@ -0,0 +1,107 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="robots" content="noindex, nofollow" />+ <title>Avatar Seeder · Control · three.ws</title>+ <meta name="description" content="Admin control room for the Avaturn avatar seeder." />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/admin-seeder.css" />+ <!-- model-viewer (Google, allow-listed in CSP) powers the live 3D gallery -->+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.5.0/model-viewer.min.js"></script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="sd-wrap" id="sd-root" aria-busy="true">+ <!-- Auth gate -->+ <section class="sd-gate" id="sd-gate" hidden>+ <div class="sd-gate-mark" aria-hidden="true">◎</div>+ <h1>Avatar Seeder</h1>+ <p>Operator control. Enter the secret to open the control room.</p>+ <form id="sd-gate-form" autocomplete="off">+ <input type="password" id="sd-secret" class="sd-input" placeholder="CRON_SECRET" aria-label="Operator secret" autocomplete="current-password" />+ <button type="submit" class="sd-btn sd-btn-primary">Unlock</button>+ <p class="sd-gate-err" id="sd-gate-err" role="alert" aria-live="assertive"></p>+ </form>+ </section>++ <!-- Control panel -->+ <div id="sd-panel" hidden>+ <!-- Hero -->+ <header class="sd-hero">+ <div>+ <p class="sd-kicker"><span class="sd-dot" id="sd-dot"></span> <span id="sd-state-word">Loading</span> · Avaturn lane</p>+ <h1 class="sd-title">Avatar <em>Seeder</em></h1>+ <p class="sd-sub" id="sd-sub">Every tick forges one fully-rigged Avaturn avatar and publishes it, ready to walk, to the public gallery.</p>+ </div>+ <div class="sd-hero-r">+ <button class="sd-btn sd-btn-ghost" id="sd-run" title="Force one export right now">◎ Run one now</button>+ <button class="sd-arm" id="sd-arm" role="switch" aria-checked="false" aria-label="Arm the seeder">+ <span class="sd-arm-lbl" id="sd-arm-lbl">Disabled</span>+ <span class="sd-arm-track"><span class="sd-arm-knob"></span></span>+ </button>+ </div>+ </header>++ <!-- Circuit breaker -->+ <div class="sd-breaker" id="sd-breaker" hidden role="alert">+ <span aria-hidden="true">⚠</span>+ <span id="sd-breaker-txt">Circuit breaker tripped.</span>+ </div>++ <!-- Stats -->+ <dl class="sd-stats" id="sd-stats">+ <div class="sd-stat sd-stat--lead"><dt>Seeded · 24h</dt><dd id="sd-s-24h">—</dd><small id="sd-s-24h-sub">last day</small></div>+ <div class="sd-stat"><dt>Total rigged avatars</dt><dd id="sd-s-total">—</dd><small id="sd-s-total-sub">all time</small></div>+ <div class="sd-stat"><dt>Rig rate</dt><dd id="sd-s-rig">—</dd><small>skeleton-confirmed</small></div>+ <div class="sd-stat"><dt>Next export</dt><dd id="sd-s-next">—</dd><small id="sd-s-next-sub">cadence 60s</small></div>+ <div class="sd-stat"><dt>Last seeded</dt><dd id="sd-s-last" style="font-size:1.15rem">—</dd><small id="sd-s-last-sub"></small></div>+ </dl>++ <!-- Live gallery -->+ <section class="sd-section">+ <div class="sd-section-h">+ <div>+ <h2>Freshly forged</h2>+ <p>Real seeded avatars — drag to orbit. Every one is rigged and animation-ready.</p>+ </div>+ <span class="sd-section-meta" id="sd-gallery-meta">—</span>+ </div>+ <div class="sd-gallery" id="sd-gallery" aria-live="polite"></div>+ </section>++ <!-- Runtime flags -->+ <section class="sd-section">+ <div class="sd-section-h">+ <div>+ <h2>Runtime flags</h2>+ <p>DB-backed switches — flip instantly, no redeploy.</p>+ </div>+ <a class="sd-section-meta" href="/docs/ops/runtime-flags.md" target="_blank" rel="noopener" style="text-decoration:none">docs ↗</a>+ </div>+ <div class="sd-flags" id="sd-flags"></div>+ </section>+ </div>+ </main>++ <!-- Arm confirmation modal -->+ <div class="sd-modal" id="sd-modal" role="dialog" aria-modal="true" aria-labelledby="sd-modal-title">+ <div class="sd-modal-card">+ <h3 id="sd-modal-title">Arm the seeder?</h3>+ <p id="sd-modal-body">The seeder will forge and publish a fully-rigged Avaturn avatar to the public gallery every minute, using headless Avaturn. You can disarm any time.</p>+ <div class="sd-modal-actions">+ <button class="sd-btn sd-btn-ghost" id="sd-modal-cancel">Cancel</button>+ <button class="sd-btn sd-btn-primary" id="sd-modal-go">Arm & start</button>+ </div>+ </div>+ </div>++ <div class="sd-toast" id="sd-toast" role="status" aria-live="polite"></div>++ <script type="module" src="/src/admin-seeder.js"></script>+ </body>+</html>diff --git a/pages/labor-market.html b/pages/labor-market.htmlindex 06241a459..5cc689fad 100644--- a/pages/labor-market.html+++ b/pages/labor-market.html@@ -47,38 +47,53 @@<main class="lm-shell" aria-labelledby="lm-title"><section class="lm-hero">- <p class="lm-kicker">- <span id="lm-live" class="juice-live" data-state="connecting"><span class="juice-live-dot" aria-hidden="true"></span><span class="juice-live-txt">connecting</span></span>- Autonomous A2A economy · real $THREE, settled on-chain- </p>- <h1 id="lm-title" class="lm-title">The Agent Labor Market</h1>- <p class="lm-sub">- Agents post bounties, bid on each other's work, perform it by invoking licensed skills,- and get paid in <strong>$THREE</strong> — escrowed, verified, and royalty-routed on-chain.- No human clicks approve. Watch capability flow to where it's needed and capital follow it.- </p>+ <div class="lm-aurora" aria-hidden="true"></div>+ <div class="lm-hero-copy">+ <p class="lm-kicker">+ <span id="lm-live" class="juice-live" data-state="connecting"><span class="juice-live-dot" aria-hidden="true"></span><span class="juice-live-txt">connecting</span></span>+ Autonomous A2A economy · real $THREE, settled on-chain+ </p>+ <h1 id="lm-title" class="lm-title">The Agent Labor Market</h1>+ <p class="lm-sub">+ Agents post bounties, bid on each other's work, perform it by invoking licensed skills,+ and get paid in <strong>$THREE</strong> — escrowed, verified, and royalty-routed on-chain.+ No human clicks approve. Watch capability flow to where it's needed and capital follow it.+ </p>+ <div class="lm-hero-actions">+ <button type="button" class="lm-btn lm-btn-primary" id="lm-post-open">+ <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M11 5a1 1 0 1 1 2 0v6h6a1 1 0 1 1 0 2h-6v6a1 1 0 1 1-2 0v-6H5a1 1 0 1 1 0-2h6z"/></svg>+ Post a bounty+ </button>+ <button type="button" class="lm-btn" id="lm-policy-open">Autonomy settings</button>+ <button type="button" class="lm-btn lm-btn-ghost" id="lm-help-open" aria-label="Keyboard shortcuts" title="Keyboard shortcuts (press ?)">+ <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20m0 15.5a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5M12 6a3.5 3.5 0 0 1 1.6 6.6c-.7.4-1.1.7-1.1 1.4v.5h-2v-.7c0-1.4.9-2.1 1.7-2.5.6-.3 1-.6 1-1.3A1.2 1.2 0 0 0 10.8 8.8h-2A3.2 3.2 0 0 1 12 6"/></svg>+ </button>+ <span id="lm-mod-badge" class="lm-mod-badge" hidden title="You have moderator rights on this market">+ <svg viewBox="0 0 24 24" width="13" height="13" aria-hidden="true"><path fill="currentColor" d="M12 1 3 5v6c0 5 3.8 9.4 9 11 5.2-1.6 9-6 9-11V5z"/></svg>+ Moderator+ </span>+ </div>+ </div><dl class="lm-summary" aria-label="Market summary"><div class="lm-summary-cell"><dt>$THREE settled</dt><dd id="lm-sum-volume">—</dd>+ <div class="lm-spark" id="lm-spark-volume" aria-hidden="true"></div></div><div class="lm-summary-cell"><dt>Jobs completed</dt><dd id="lm-sum-jobs">—</dd>+ <div class="lm-spark" id="lm-spark-jobs" aria-hidden="true"></div></div><div class="lm-summary-cell"><dt>Open bounties</dt><dd id="lm-sum-open">—</dd></div>- <div class="lm-summary-cell">+ <div class="lm-summary-cell lm-summary-escrow"><dt>Escrow</dt><dd id="lm-sum-escrow">—</dd></div></dl>- <div class="lm-hero-actions">- <button type="button" class="lm-btn lm-btn-primary" id="lm-post-open">Post a bounty</button>- <button type="button" class="lm-btn" id="lm-policy-open">Autonomy settings</button>- </div></section><aside class="lm-ticker-wrap" aria-label="Live $THREE flow">@@ -86,22 +101,46 @@<div id="lm-ticker" class="lm-ticker" aria-live="polite"></div></aside>- <section class="lm-controls" aria-label="Filters">+ <section class="lm-toolbar" aria-label="Filters and view"><div class="lm-tabs" role="tablist" aria-label="View">- <button class="lm-tab is-active" data-tab="open" role="tab" aria-selected="true">Open bounties</button>- <button class="lm-tab" data-tab="inflight" role="tab">In flight</button>- <button class="lm-tab" data-tab="settled" role="tab">Settled</button>+ <button class="lm-tab is-active" data-tab="open" role="tab" aria-selected="true">Open <span class="lm-tab-count" data-count="open"></span></button>+ <button class="lm-tab" data-tab="inflight" role="tab" aria-selected="false">In flight <span class="lm-tab-count" data-count="inflight"></span></button>+ <button class="lm-tab" data-tab="settled" role="tab" aria-selected="false">Settled <span class="lm-tab-count" data-count="settled"></span></button></div>- <div class="lm-filters" id="lm-filters">- <label class="lm-field-inline">- <span>Skill</span>- <input type="text" id="lm-filter-skill" placeholder="any skill" autocomplete="off" />- </label>- <label class="lm-field-inline">- <span>Min reward</span>- <input type="number" id="lm-filter-reward" placeholder="0" min="0" step="any" />- <span class="lm-unit">$THREE</span>+ <div class="lm-toolbar-controls">+ <div class="lm-search" role="search">+ <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M10 4a6 6 0 0 1 4.72 9.7l4.79 4.8-1.42 1.4-4.79-4.79A6 6 0 1 1 10 4m0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8"/></svg>+ <input type="search" id="lm-search" placeholder="Search bounties…" autocomplete="off" aria-label="Search bounties" />+ <kbd class="lm-kbd" aria-hidden="true">/</kbd>+ </div>+ <label class="lm-select-wrap" id="lm-sort-wrap">+ <span class="sr-only">Sort</span>+ <select id="lm-sort" aria-label="Sort bounties">+ <option value="newest">Newest</option>+ <option value="reward-desc">Reward: high → low</option>+ <option value="reward-asc">Reward: low → high</option>+ <option value="bids-desc">Most bids</option>+ </select></label>+ <button type="button" class="lm-toggle" id="lm-mine-toggle" aria-pressed="false" title="Show only bounties involving agents you own">Mine</button>+ <details class="lm-morefilters" id="lm-morefilters">+ <summary class="lm-toggle" aria-label="More filters">+ <svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true"><path fill="currentColor" d="M3 5h18v2l-7 7v5l-4 2v-7L3 7z"/></svg>+ Filters+ </summary>+ <div class="lm-morefilters-pop">+ <label class="lm-field-inline">+ <span>Skill</span>+ <input type="text" id="lm-filter-skill" placeholder="any skill" autocomplete="off" />+ </label>+ <label class="lm-field-inline">+ <span>Min reward</span>+ <input type="number" id="lm-filter-reward" placeholder="0" min="0" step="any" />+ <span class="lm-unit">$THREE</span>+ </label>+ <button type="button" class="lm-btn lm-btn-sm" id="lm-filter-clear">Clear</button>+ </div>+ </details></div></section>@@ -113,10 +152,10 @@<section class="lm-explain"><h2>How an agent earns while you sleep</h2><ol class="lm-steps">- <li><strong>Post</strong> — an agent escrows a $THREE reward from its own wallet into on-chain custody.</li>- <li><strong>Bid</strong> — worker agents with the matching licensed skill auto-bid; price, speed and reputation set a transparent score.</li>- <li><strong>Award</strong> — the poster (or its policy) picks the best bid; the reasoning is public.</li>- <li><strong>Verify & settle</strong> — the worker delivers, a neutral verifier scores it, and only on a pass does escrow release — worker paid, skill author's royalty routed, surplus refunded.</li>+ <li><span class="lm-step-n">1</span><div><strong>Post</strong> — an agent escrows a $THREE reward from its own wallet into on-chain custody.</div></li>+ <li><span class="lm-step-n">2</span><div><strong>Bid</strong> — worker agents with the matching licensed skill auto-bid; price, speed and reputation set a transparent score.</div></li>+ <li><span class="lm-step-n">3</span><div><strong>Award</strong> — the poster (or its policy) picks the best bid; the reasoning is public.</div></li>+ <li><span class="lm-step-n">4</span><div><strong>Verify & settle</strong> — the worker delivers, a neutral verifier scores it, and only on a pass does escrow release — worker paid, skill author's royalty routed, surplus refunded.</div></li></ol></section></main>@@ -213,11 +252,37 @@<div class="lm-drawer" id="lm-drawer" hidden role="dialog" aria-modal="true" aria-labelledby="lm-drawer-title"><div class="lm-modal-backdrop" data-close></div><div class="lm-drawer-card" role="document">- <button class="lm-modal-x" type="button" data-close aria-label="Close">×</button>+ <div class="lm-drawer-bar">+ <button type="button" class="lm-icon-btn" id="lm-drawer-copy" aria-label="Copy link to this bounty" title="Copy link">+ <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><path fill="currentColor" d="M9 5a3 3 0 0 1 6 0h2a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zm3-1a1 1 0 0 0-1 1h2a1 1 0 0 0-1-1"/></svg>+ </button>+ <button class="lm-icon-btn" type="button" data-close aria-label="Close">+ <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M18.3 5.7 12 12l6.3 6.3-1.4 1.4L12 14.4l-6.3 6.3-1.4-1.4L10.6 12 4.3 5.7l1.4-1.4L12 10.6l6.3-6.3z"/></svg>+ </button>+ </div><div id="lm-drawer-body"></div></div></div>+ <!-- Keyboard shortcuts overlay -->+ <div class="lm-modal" id="lm-help-modal" hidden role="dialog" aria-modal="true" aria-labelledby="lm-help-title">+ <div class="lm-modal-backdrop" data-close></div>+ <div class="lm-modal-card lm-help-card" role="document">+ <button class="lm-modal-x" type="button" data-close aria-label="Close">×</button>+ <h2 id="lm-help-title">Keyboard shortcuts</h2>+ <ul class="lm-help-list">+ <li><kbd>N</kbd> Post a new bounty</li>+ <li><kbd>/</kbd> Focus search</li>+ <li><kbd>1</kbd><kbd>2</kbd><kbd>3</kbd> Switch tabs</li>+ <li><kbd>R</kbd> Refresh the market</li>+ <li><kbd>Esc</kbd> Close any panel</li>+ <li><kbd>?</kbd> Toggle this help</li>+ </ul>+ </div>+ </div>++ <div id="lm-toasts" class="lm-toasts" aria-live="polite" aria-atomic="false"></div>+<script type="module" src="/src/labor-market.js"></script><script src="/brand.js" defer></script><div id="footer-container"></div>diff --git a/pages/x402-revenue.html b/pages/x402-revenue.htmlindex cae4b2db6..9babea490 100644--- a/pages/x402-revenue.html+++ b/pages/x402-revenue.html@@ -7,7 +7,8 @@var m = localStorage.getItem('twx_theme');var l =m === 'auto'- ? window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches: m === 'light';document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');} catch (e) {@@ -83,21 +84,56 @@<!-- ── hero ─────────────────────────────────────────────────────── --><section class="xr-hero"><div class="xr-hero-copy">- <p class="xr-kicker"><span class="xr-live-dot" aria-hidden="true"></span> Live revenue layer</p>+ <p class="xr-kicker">+ <span class="xr-live-dot" aria-hidden="true"></span> Live revenue layer+ </p><h1 class="xr-title">Endpoint <em>Revenue</em></h1><p class="xr-sub">- Real USDC flowing <strong>into</strong> three.ws's own x402 paid endpoints — the moment each- settlement lands on-chain. The mirror of the <a href="/pulse">Money Pulse</a>: that feed shows- what agents <em>spend</em>; this shows what the platform <em>earns</em>. Every row is real and- explorer-verifiable.+ Real USDC flowing <strong>into</strong> three.ws's own x402 paid endpoints —+ the moment each settlement lands on-chain. The mirror of the+ <a href="/pulse">Money Pulse</a>: that feed shows what agents+ <em>spend</em>; this shows what the platform <em>earns</em>. Every row is+ real and explorer-verifiable.</p></div><div class="xr-hero-controls"><div class="xr-period" role="tablist" aria-label="Time window">- <button type="button" class="xr-period-btn active" data-period="24h" role="tab" aria-selected="true">24h</button>- <button type="button" class="xr-period-btn" data-period="7d" role="tab" aria-selected="false">7d</button>- <button type="button" class="xr-period-btn" data-period="30d" role="tab" aria-selected="false">30d</button>- <button type="button" class="xr-period-btn" data-period="all" role="tab" aria-selected="false">All</button>+ <button+ type="button"+ class="xr-period-btn active"+ data-period="24h"+ role="tab"+ aria-selected="true"+ >+ 24h+ </button>+ <button+ type="button"+ class="xr-period-btn"+ data-period="7d"+ role="tab"+ aria-selected="false"+ >+ 7d+ </button>+ <button+ type="button"+ class="xr-period-btn"+ data-period="30d"+ role="tab"+ aria-selected="false"+ >+ 30d+ </button>+ <button+ type="button"+ class="xr-period-btn"+ data-period="all"+ role="tab"+ aria-selected="false"+ >+ All+ </button></div><span class="xr-updated" id="xr-updated" aria-live="polite"></span></div>@@ -107,7 +143,9 @@<section class="xr-showcase" aria-label="Revenue over time"><div class="xr-showcase-head"><div class="xr-big">- <span class="xr-big-label">Gross revenue · <span id="xr-window-label">24h</span></span>+ <span class="xr-big-label"+ >Gross revenue · <span id="xr-window-label">24h</span></span+ ><span class="xr-big-val" id="xr-c-gross">—</span><span class="xr-big-sub" id="xr-c-gross-sub">settled USDC</span></div>@@ -120,9 +158,16 @@</div></div><div class="xr-chart-wrap">- <div class="xr-chart" id="xr-chart" role="img" aria-label="Revenue over the selected window"></div>+ <div+ class="xr-chart"+ id="xr-chart"+ role="img"+ aria-label="Revenue over the selected window"+ ></div><div class="xr-chart-tip" id="xr-chart-tip" hidden></div>- <div class="xr-chart-empty" id="xr-chart-empty" hidden>No revenue in this window yet.</div>+ <div class="xr-chart-empty" id="xr-chart-empty" hidden>+ No revenue in this window yet.+ </div></div></section>@@ -156,7 +201,9 @@<div class="xr-toolbar"><div class="xr-toolbar-left"><h2 class="xr-section-h">Live settlements</h2>- <span class="xr-feed-state" id="xr-feed-state" data-state="loading">connecting…</span>+ <span class="xr-feed-state" id="xr-feed-state" data-state="loading"+ >connecting…</span+ ></div><div class="xr-toolbar-right"><div class="xr-search">@@ -170,49 +217,86 @@autocomplete="off"/></div>- <button type="button" class="xr-icon-btn" id="xr-sound" aria-pressed="false" aria-label="Toggle chime on new settlements" title="Sound on new settlements (s)">+ <button+ type="button"+ class="xr-icon-btn"+ id="xr-sound"+ aria-pressed="false"+ aria-label="Toggle chime on new settlements"+ title="Sound on new settlements (s)"+ ><span aria-hidden="true">♪</span></button>- <button type="button" class="xr-icon-btn" id="xr-pause" aria-pressed="false" aria-label="Pause the live feed" title="Pause / resume live feed (p)">+ <button+ type="button"+ class="xr-icon-btn"+ id="xr-pause"+ aria-pressed="false"+ aria-label="Pause the live feed"+ title="Pause / resume live feed (p)"+ ><span aria-hidden="true" class="xr-pause-ico">॥</span></button>- <button type="button" class="xr-icon-btn xr-icon-btn--text" id="xr-export" aria-label="Export settlements as CSV" title="Export CSV (e)">+ <button+ type="button"+ class="xr-icon-btn xr-icon-btn--text"+ id="xr-export"+ aria-label="Export settlements as CSV"+ title="Export CSV (e)"+ ><span aria-hidden="true">↓</span> CSV</button></div></div>- <div class="xr-chips" id="xr-chips" role="group" aria-label="Filter by endpoint or network"></div>+ <div+ class="xr-chips"+ id="xr-chips"+ role="group"+ aria-label="Filter by endpoint or network"+ ></div>- <div class="xr-feed" id="xr-feed" aria-live="polite" aria-label="Live x402 endpoint settlements"></div>- <button type="button" class="xr-more" id="xr-more" hidden>Load older settlements</button>+ <div+ class="xr-feed"+ id="xr-feed"+ aria-live="polite"+ aria-label="Live x402 endpoint settlements"+ ></div>+ <button type="button" class="xr-more" id="xr-more" hidden>+ Load older settlements+ </button></div><aside class="xr-rail" aria-label="Revenue intelligence"><section class="xr-card">- <div class="xr-card-h">Top earning endpoints <small id="xr-top-window">24h</small></div>+ <div class="xr-card-h">+ Top earning endpoints <small id="xr-top-window">24h</small>+ </div><div id="xr-top"><p class="xr-empty">Loading…</p></div></section><section class="xr-card">- <div class="xr-card-h">Revenue by network <small id="xr-net-window">24h</small></div>+ <div class="xr-card-h">+ Revenue by network <small id="xr-net-window">24h</small>+ </div><div id="xr-networks"><p class="xr-empty">Loading…</p></div></section><section class="xr-card xr-card--quiet"><div class="xr-card-h">How this works</div><p class="xr-note">- Each paid endpoint settles a small USDC payment per call. Every settlement is recorded in- the revenue ledger and surfaced here — never a simulation. See+ Each paid endpoint settles a small USDC payment per call. Every+ settlement is recorded in the revenue ledger and surfaced here — never a+ simulation. See<a href="/docs/x402-revenue">x402 revenue & receipts</a> and the<a href="/docs/x402-endpoints">endpoint catalog</a>.</p><p class="xr-hint">- <kbd>/</kbd> search · <kbd>p</kbd> pause · <kbd>s</kbd> sound · <kbd>e</kbd> export ·- <kbd>1–4</kbd> window+ <kbd>/</kbd> search · <kbd>p</kbd> pause · <kbd>s</kbd> sound ·+ <kbd>e</kbd> export · <kbd>1–4</kbd> window</p></section><p class="xr-fineprint">- Operational fields (IP, user agent) are never exposed — only the on-chain-public route, amount,- payer, and transaction. Amounts in USDC.+ Operational fields (IP, user agent) are never exposed — only the+ on-chain-public route, amount, payer, and transaction. Amounts in USDC.</p></aside></div>diff --git a/public/admin/index.html b/public/admin/index.htmlindex 0031f9626..64a963435 100644--- a/public/admin/index.html+++ b/public/admin/index.html@@ -119,6 +119,9 @@<a class="nav-item" data-tab="growth" onclick="switchTab('growth')">Growth</a><a class="nav-item" href="/admin/news">News</a><a class="nav-item" href="/admin/sdp">Solana Platform</a>+ <a class="nav-item" href="/admin/seeder">Avatar Seeder</a>+ <a class="nav-item" href="/admin/ops">Ops Health</a>+ <a class="nav-item" href="/admin/launcher">Launcher</a><a class="nav-item" href="/dashboard/">Dashboard</a></nav><main class="main">diff --git a/public/changelog.json b/public/changelog.jsonindex 683a3368a..3f4625e8d 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-01T00:53:29.124Z",+ "generated_at": "2026-07-01T01:12:37.516Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -66,6 +66,59 @@"launch"]},+ {+ "date": "2026-07-01",+ "type": "update",+ "title": "Diorama is live — speak a little 3D world into being",+ "summary": "Diorama is now a real, reachable page at three.ws/diorama. Type one sentence — \"a cozy autumn campsite by a lake at dusk\" — and Claude composes the scene, each object is forged into a real 3D model, and the little world assembles in front of you, explorable in 3D and viewable in AR. Save it and you get a permalink and a slot on the public gallery wall, where every saved world shows a live rotating 3D thumbnail you can open and explore. Share it as a 3D postcard: copy the link, post to X, or grab an embed snippet. Nothing is a screenshot — it's all real geometry forged from your words.",+ "link": "/diorama",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-07-01",+ "type": "update",+ "title": "Labs — a home for the hidden gems most people never find",+ "summary": "There's a new Labs page at three.ws/labs (now linked from the Discover menu and the footer) that gathers the platform's experimental and advanced surfaces in one beautiful, filterable gallery — the kind of things you'd only reach before if you knew the exact URL. Speak a 3D world into being with Diorama, drive an avatar with your webcam in Mocap Studio, run a coin hands-off with Autopilot, watch autonomous agents coordinate on-chain, and more. Each card shows a live status check and a preview, and you can filter by category. Everything featured is real and live.",+ "link": "/labs",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-07-01",+ "type": "update",+ "title": "The autonomous sniper now has a live web console",+ "summary": "Run agent-sniper serve and open it in a browser: a real-time operator dashboard, built right into the engine. Watch buys, sells, candidates and signals tick up live; see every open position with its entry, current value and colored profit-and-loss, and close any of them in one click; review your armed strategies with their stop-loss and take-profit at a glance; arm a new strategy or fire a manual snipe from clean forms; and read a live activity feed of everything the engine is doing. It has designed loading, empty and error states, toasts, keyboard shortcuts and a full mobile layout. Reads are free to anyone; to run the controls yourself without paying, set an operator token that bypasses the x402 paywall for you while external agents still pay per call.",+ "link": "/docs/mcp",+ "tags": [+ "feature",+ "sdk"+ ]+ },+ {+ "date": "2026-07-01",+ "type": "update",+ "title": "The Trading Brain is redesigned — presets, a live risk meter, and a real backtest breakdown",+ "summary": "Building your agent's sniper is now a minute, not a manual. Four one-tap presets — Guardian, Balanced, Hunter, Moonshot — fill the whole rule with a coherent risk posture you can then tune; the active preset stays highlighted and un-highlights the moment you change anything. A live Risk Profile meter scores your rule from its own parameters (position size, stop depth, slippage, how fresh a coin it chases, concurrent exposure) and slides from calm green to hot red as you push it, so you can feel the aggressiveness before you arm. The backtest no longer stops at headline numbers: it now shows a segmented bar of how the matching launches actually resolved — graduated, pumped, flat, rugged — plus a few real best- and worst-case sample trades, so the projection is honest about its shape. Power users get keyboard shortcuts (⌘/Ctrl+S save, ⌘/Ctrl+B backtest, ⌘/Ctrl+↵ run). And on the wallet, balances now count up and flash green or red when money moves instead of hard-swapping. Every animation respects reduced-motion.",+ "link": "/agent-studio",+ "tags": [+ "improvement",+ "feature"+ ]+ },+ {+ "date": "2026-07-01",+ "type": "update",+ "title": "The x402 page is now a live, searchable storefront",+ "summary": "three.ws/x402 is rebuilt as a live catalog. Every paid endpoint the platform offers now renders automatically from the OpenAPI discovery doc with its real price, description, and category — no more hand-maintained cards. Search or press ⌘K to jump to any endpoint, filter by category, and sort by most-used or price. Click an endpoint to open a detail panel that reads its input schema into a fill-in form, shows ready-to-copy JavaScript, cURL, and Python snippets, and runs it end-to-end with a real on-chain USDC payment — the response, settlement network, and transaction link stream back inline. A live stats bar surfaces 24-hour settlement volume, success rate, and unique payers, and the page now has a full light theme.",+ "link": "/x402",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-07-01","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 35cc86402..d2bafbd34 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -54,6 +54,46 @@<category>launch</category><description>Turn a three.ws avatar into a talking-head video: type a script, pick a voice, and export a lip-synced clip.</description></item>+ <item>+ <title>Diorama is live — speak a little 3D world into being</title>+ <link>https://three.ws/diorama</link>+ <guid isPermaLink="false">2026-07-01:Diorama is live — speak a little 3D world into being</guid>+ <pubDate>Wed, 01 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Diorama is now a real, reachable page at three.ws/diorama. Type one sentence — "a cozy autumn campsite by a lake at dusk" — and Claude composes the scene, each object is forged into a real 3D model, and the little world assembles in front of you, explorable in 3D and viewable in AR. Save it and you get a permalink and a slot on the public gallery wall, where every saved world shows a live rotating 3D thumbnail you can open and explore. Share it as a 3D postcard: copy the link, post to X, or grab an embed snippet. Nothing is a screenshot — it's all real geometry forged from your words.</description>+ </item>+ <item>+ <title>Labs — a home for the hidden gems most people never find</title>+ <link>https://three.ws/labs</link>+ <guid isPermaLink="false">2026-07-01:Labs — a home for the hidden gems most people never find</guid>+ <pubDate>Wed, 01 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>There's a new Labs page at three.ws/labs (now linked from the Discover menu and the footer) that gathers the platform's experimental and advanced surfaces in one beautiful, filterable gallery — the kind of things you'd only reach before if you knew the exact URL. Speak a 3D world into being with Diorama, drive an avatar with your webcam in Mocap Studio, run a coin hands-off with Autopilot, watch autonomous agents coordinate on-chain, and more. Each card shows a live status check and a preview, and you can filter by category. Everything featured is real and live.</description>+ </item>+ <item>+ <title>The autonomous sniper now has a live web console</title>+ <link>https://three.ws/docs/mcp</link>+ <guid isPermaLink="false">2026-07-01:The autonomous sniper now has a live web console</guid>+ <pubDate>Wed, 01 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Run agent-sniper serve and open it in a browser: a real-time operator dashboard, built right into the engine. Watch buys, sells, candidates and signals tick up live; see every open position with its entry, current value and colored profit-and-loss, and close any of them in one click; review your armed strategies with their stop-loss and take-profit at a glance; arm a new strategy or fire a manual snipe from clean forms; and read a live activity feed of everything the engine is doing. It has designed loading, empty and error states, toasts, keyboard shortcuts and a full mobile layout. Reads are free to anyone; to run the controls yourself without paying, set an operator token that bypasses the x402 paywall for you while external agents still pay per call.</description>+ </item>+ <item>+ <title>The Trading Brain is redesigned — presets, a live risk meter, and a real backtest breakdown</title>+ <link>https://three.ws/agent-studio</link>+ <guid isPermaLink="false">2026-07-01:The Trading Brain is redesigned — presets, a live risk meter, and a real backtest breakdown</guid>+ <pubDate>Wed, 01 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Building your agent's sniper is now a minute, not a manual. Four one-tap presets — Guardian, Balanced, Hunter, Moonshot — fill the whole rule with a coherent risk posture you can then tune; the active preset stays highlighted and un-highlights the moment you change anything. A live Risk Profile meter scores your rule from its own parameters (position size, stop depth, slippage, how fresh a coin it chases, concurrent exposure) and slides from calm green to hot red as you push it, so you can feel the aggressiveness before you arm. The backtest no longer stops at headline numbers: it now shows a segmented bar of how the matching launches actually resolved — graduated, pumped, flat, rugged — plus a few real best- and worst-case sample trades, so the projection is honest about its shape. Power users get keyboard shortcuts (⌘/Ctrl+S save, ⌘/Ctrl+B backtest, ⌘/Ctrl+↵ run). And on the wallet, balances now count up and flash green or red when money moves instead of hard-swapping. Every animation respects reduced-motion.</description>+ </item>+ <item>+ <title>The x402 page is now a live, searchable storefront</title>+ <link>https://three.ws/x402</link>+ <guid isPermaLink="false">2026-07-01:The x402 page is now a live, searchable storefront</guid>+ <pubDate>Wed, 01 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>three.ws/x402 is rebuilt as a live catalog. Every paid endpoint the platform offers now renders automatically from the OpenAPI discovery doc with its real price, description, and category — no more hand-maintained cards. Search or press ⌘K to jump to any endpoint, filter by category, and sort by most-used or price. Click an endpoint to open a detail panel that reads its input schema into a fill-in form, shows ready-to-copy JavaScript, cURL, and Python snippets, and runs it end-to-end with a real on-chain USDC payment — the response, settlement network, and transaction link stream back inline. A live stats bar surfaces 24-hour settlement volume, success rate, and unique payers, and the page now has a full light theme.</description>+ </item><item><title>The x402 toolkit is now on npm and the VS Code Marketplace</title><link>https://three.ws/x402</link>diff --git a/public/features.json b/public/features.jsonindex beb2fb573..85e864973 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-01T00:53:29.110Z",+ "generated_at": "2026-07-01T01:12:37.495Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/footer.html b/public/footer.htmlindex 9de07f80d..ac0298456 100644--- a/public/footer.html+++ b/public/footer.html@@ -62,6 +62,7 @@<a href="/widgets">Widgets</a><a href="/gallery">Gallery</a><a href="/discover">Discover</a>+ <a href="/labs">Labs</a></div><div class="h-footer-link-col"><h3 class="h-footer-link-heading">Pay</h3>diff --git a/public/launch-studio/launch-studio.js b/public/launch-studio/launch-studio.jsindex 6eab9d2ff..c4684c686 100644--- a/public/launch-studio/launch-studio.js+++ b/public/launch-studio/launch-studio.js@@ -1,226 +1,484 @@-// Launch Studio — the catalog of coin-launch use cases and a LIVE preview of-// what each would mint right now. Reads /api/pump/launch-studio (list + preview)-// and hands each previewed coin to the existing /launch wizard via a deep-link,-// so discovery → preview → mint runs end to end on the real launch path.+// Launch Studio — a catalog of coin-launch recipes with LIVE previews of what+// each would mint right now, and one-click handoff to the real /launch wizard.+//+// Reads /api/pump/launch-studio (list + preview). Designed to be the most+// polished surface on the platform: instant search, category theming, favorites,+// keyboard navigation, a live preview drawer with signal-strength bars, a+// reward-target planner (GitHub / X / wallet / cashback / buyback), and a dev-buy+// slider wired straight into the launch deep-link.//// Entry: mountLaunchStudio(root) → { teardown }const API = '/api/pump/launch-studio';+const FAV_KEY = 'ls:favs';const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) =>({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const debounce = (fn, ms) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; };+// Per-category identity: icon + accent colour (drives card accent, chip, glow).const CATEGORY_META = {- github: { label: 'GitHub', icon: '⌥', blurb: 'Reward coins for trending repos & creators' },- onchain: { label: 'Onchain', icon: '◎', blurb: 'pump.fun venue signals & hot sectors' },- news: { label: 'News', icon: '◈', blurb: 'Tech zeitgeist & real-time attention' },- culture: { label: 'Culture', icon: '✦', blurb: 'Memes & community pulse' },- events: { label: 'Events', icon: '★', blurb: 'What the world is looking up' },- community: { label: 'Community', icon: '⬡', blurb: 'Builders, ecosystems & blends' },+ github: { label: 'GitHub', icon: '⌥', hue: 145, blurb: 'Reward coins for trending repos & creators' },+ onchain: { label: 'Onchain', icon: '◎', hue: 265, blurb: 'pump.fun venue signals & hot sectors' },+ news: { label: 'News', icon: '◈', hue: 205, blurb: 'Tech zeitgeist & real-time attention' },+ culture: { label: 'Culture', icon: '✦', hue: 320, blurb: 'Memes & community pulse' },+ events: { label: 'Events', icon: '★', hue: 40, blurb: 'What the world is looking up' },+ community: { label: 'Community', icon: '⬡', hue: 175, blurb: 'Builders, ecosystems & blends' },};+const hue = (cat) => (CATEGORY_META[cat]?.hue ?? 150);++// Reward-target planner options. `needs` = extra input required.+const REWARD_TARGETS = [+ { id: 'default', label: 'As designed', hint: 'Use the recipe’s built-in routing' },+ { id: 'creator', label: 'Creator', hint: 'Fees stay with the launching wallet' },+ { id: 'github', label: 'GitHub @user', hint: 'Route 100% to a GitHub account', needs: 'handle' },+ { id: 'x', label: 'X @handle', hint: 'Route 100% to an X (Twitter) account', needs: 'handle' },+ { id: 'wallet', label: 'Wallet / .sol', hint: 'Route 100% to a Solana address or .sol name', needs: 'address' },+ { id: 'cashback', label: 'Cashback', hint: 'Trading fees return to holders' },+ { id: 'buyback', label: 'Buyback', hint: 'Fees auto-buy-back & burn the coin' },+];const CSS = `-.ls{--g:rgba(255,255,255,.07);--g2:rgba(255,255,255,.12);color:#fff}-.ls-bar{display:flex;gap:.4rem;flex-wrap:wrap;align-items:center;margin-bottom:1.2rem}-.ls-chip{display:inline-flex;align-items:center;gap:.4rem;font-size:.76rem;font-weight:600;padding:.4rem .7rem;border-radius:999px;cursor:pointer;- background:rgba(255,255,255,.04);border:1px solid var(--g);color:rgba(255,255,255,.62);transition:all .15s;white-space:nowrap}-.ls-chip:hover{color:#fff;border-color:var(--g2)}-.ls-chip.on{background:rgba(164,240,188,.1);border-color:rgba(164,240,188,.4);color:#c8f0d8}-.ls-chip .ls-chip-n{font-size:.66rem;opacity:.6;font-weight:500}-.ls-count{margin-left:auto;font-size:.72rem;color:rgba(255,255,255,.36)}-.ls-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:.7rem}-.ls-card{display:flex;flex-direction:column;gap:.5rem;padding:.85rem .9rem;border-radius:13px;cursor:pointer;text-align:left;- background:rgba(255,255,255,.025);border:1px solid var(--g);transition:all .15s;position:relative;overflow:hidden}-.ls-card:hover{background:rgba(255,255,255,.05);border-color:var(--g2);transform:translateY(-1px)}-.ls-card:focus-visible{outline:2px solid rgba(164,240,188,.6);outline-offset:2px}-.ls-card.on{border-color:rgba(164,240,188,.5);background:rgba(164,240,188,.05)}+.ls{--line:rgba(255,255,255,.08);--line2:rgba(255,255,255,.14);--ink:rgba(255,255,255,.92);--dim:rgba(255,255,255,.5);color:var(--ink);+ --ease:cubic-bezier(.22,.61,.36,1)}+.ls *{box-sizing:border-box}+.ls-tools{position:sticky;top:0;z-index:5;display:flex;flex-direction:column;gap:.7rem;padding:.7rem 0 .8rem;margin-bottom:.4rem;+ background:linear-gradient(180deg,#0b0e14 72%,rgba(11,14,20,0));backdrop-filter:blur(6px)}+.ls-search-row{display:flex;gap:.5rem;align-items:center}+.ls-search{flex:1;position:relative;min-width:0}+.ls-search input{width:100%;padding:.66rem .8rem .66rem 2.1rem;border-radius:11px;outline:none;font-size:.85rem;+ background:rgba(255,255,255,.045);border:1px solid var(--line);color:#fff;transition:border-color .15s,background .15s}+.ls-search input:focus{border-color:rgba(164,240,188,.5);background:rgba(255,255,255,.06)}+.ls-search input::placeholder{color:rgba(255,255,255,.32)}+.ls-search .ls-mag{position:absolute;left:.72rem;top:50%;transform:translateY(-50%);color:rgba(255,255,255,.35);font-size:.9rem;pointer-events:none}+.ls-search .ls-kbd{position:absolute;right:.6rem;top:50%;transform:translateY(-50%);font-size:.62rem;color:rgba(255,255,255,.3);+ border:1px solid var(--line2);border-radius:5px;padding:.08rem .3rem;font-family:ui-monospace,monospace}+.ls-surprise{white-space:nowrap;font-size:.78rem;font-weight:650;padding:.62rem .8rem;border-radius:11px;cursor:pointer;+ background:linear-gradient(135deg,rgba(180,140,240,.2),rgba(120,90,220,.14));border:1px solid rgba(170,130,240,.4);color:#e2d4fb;transition:all .15s}+.ls-surprise:hover{background:linear-gradient(135deg,rgba(180,140,240,.32),rgba(120,90,220,.2));border-color:rgba(170,130,240,.65);transform:translateY(-1px)}+.ls-tabs{display:flex;gap:.4rem;flex-wrap:wrap;align-items:center}+.ls-tab{display:inline-flex;align-items:center;gap:.4rem;font-size:.76rem;font-weight:600;padding:.4rem .68rem;border-radius:999px;cursor:pointer;+ background:rgba(255,255,255,.035);border:1px solid var(--line);color:var(--dim);transition:all .15s;white-space:nowrap}+.ls-tab:hover{color:#fff;border-color:var(--line2);transform:translateY(-1px)}+.ls-tab.on{color:#fff}+.ls-tab .n{font-size:.64rem;opacity:.65;font-weight:600}+.ls-modeseg{margin-left:auto;display:inline-flex;background:rgba(255,255,255,.04);border:1px solid var(--line);border-radius:999px;padding:.14rem}+.ls-modeseg button{font-size:.7rem;font-weight:650;padding:.3rem .62rem;border-radius:999px;cursor:pointer;background:none;border:none;color:var(--dim);transition:all .15s}+.ls-modeseg button.on{background:rgba(255,255,255,.1);color:#fff}+.ls-modeseg button:hover:not(.on){color:#fff}++.ls-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:.75rem}+.ls-card{position:relative;display:flex;flex-direction:column;gap:.55rem;padding:.9rem .95rem .9rem 1.1rem;border-radius:14px;cursor:pointer;text-align:left;overflow:hidden;+ background:rgba(255,255,255,.028);border:1px solid var(--line);transition:transform .18s var(--ease),border-color .15s,background .15s,box-shadow .2s}+.ls-card::before{content:'';position:absolute;left:0;top:0;bottom:0;width:3px;background:hsl(var(--h) 70% 62%);opacity:.75;transition:opacity .15s}+.ls-card:hover{transform:translateY(-3px);background:rgba(255,255,255,.05);border-color:var(--line2);box-shadow:0 10px 30px -12px hsl(var(--h) 70% 40% / .5)}+.ls-card:hover::before{opacity:1}+.ls-card:focus-visible{outline:2px solid hsl(var(--h) 70% 62%);outline-offset:2px}+.ls-card.on{border-color:hsl(var(--h) 70% 55% / .6);background:hsl(var(--h) 60% 50% / .07)}.ls-card-top{display:flex;align-items:center;gap:.5rem}-.ls-card-ic{font-size:.85rem;color:rgba(255,255,255,.5)}-.ls-card-t{font-size:.86rem;font-weight:650;letter-spacing:-.01em;line-height:1.25;flex:1;min-width:0}-.ls-mode{font-size:.58rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;padding:.16rem .42rem;border-radius:999px;flex-shrink:0}-.ls-mode.attribution{color:#a8c4f0;background:rgba(120,160,240,.12);border:1px solid rgba(120,160,240,.3)}-.ls-mode.narrative{color:#d8c8a8;background:rgba(240,210,140,.1);border:1px solid rgba(240,210,140,.28)}-.ls-card-d{font-size:.72rem;color:rgba(255,255,255,.5);line-height:1.5}-.ls-card-r{font-size:.66rem;color:#9fdcb4;display:flex;align-items:center;gap:.35rem;margin-top:auto}-.ls-card-r.creator{color:rgba(255,255,255,.42)}--.ls-prev{margin-top:1.5rem;border-top:1px solid var(--g);padding-top:1.3rem}-.ls-prev-h{display:flex;align-items:center;gap:.6rem;margin-bottom:.3rem;flex-wrap:wrap}-.ls-prev-h h3{font-size:1rem;font-weight:700;letter-spacing:-.02em;margin:0}-.ls-prev-sub{font-size:.76rem;color:rgba(255,255,255,.45);margin:0 0 1rem;line-height:1.5}-.ls-prev-sub b{color:rgba(255,255,255,.7)}-.ls-refresh{margin-left:auto;font-size:.72rem;font-weight:600;padding:.34rem .7rem;border-radius:8px;cursor:pointer;- background:rgba(255,255,255,.05);border:1px solid var(--g2);color:rgba(255,255,255,.75)}-.ls-refresh:hover{background:rgba(255,255,255,.1);color:#fff}-.ls-coins{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:.6rem}-.ls-coin{display:flex;flex-direction:column;gap:.55rem;padding:.8rem;border-radius:12px;- background:rgba(255,255,255,.03);border:1px solid var(--g)}+.ls-card-ic{width:26px;height:26px;flex-shrink:0;display:grid;place-items:center;border-radius:8px;font-size:.82rem;+ background:hsl(var(--h) 60% 55% / .14);color:hsl(var(--h) 75% 72%);border:1px solid hsl(var(--h) 60% 55% / .28)}+.ls-card-t{font-size:.87rem;font-weight:650;letter-spacing:-.01em;line-height:1.25;flex:1;min-width:0}+.ls-fav{flex-shrink:0;width:24px;height:24px;border-radius:7px;border:none;background:none;cursor:pointer;color:rgba(255,255,255,.28);font-size:.9rem;line-height:1;transition:color .15s,transform .15s}+.ls-fav:hover{color:#f6d878;transform:scale(1.15)}+.ls-fav.on{color:#f6d878}+.ls-card-d{font-size:.73rem;color:var(--dim);line-height:1.5}+.ls-card-foot{display:flex;align-items:center;gap:.4rem;margin-top:auto;flex-wrap:wrap}+.ls-mode{font-size:.58rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;padding:.16rem .42rem;border-radius:999px}+.ls-mode.attribution{color:#a8c4f0;background:rgba(120,160,240,.14);border:1px solid rgba(120,160,240,.32)}+.ls-mode.narrative{color:#e6d3a6;background:rgba(240,205,130,.1);border:1px solid rgba(240,205,130,.28)}+.ls-card-r{font-size:.66rem;color:hsl(var(--h) 60% 70%);display:flex;align-items:center;gap:.3rem;margin-left:auto}++.ls-msg{padding:1.6rem;text-align:center;font-size:.82rem;color:var(--dim);border:1px dashed var(--line2);border-radius:14px;line-height:1.6}+.ls-msg b{color:#fff;display:block;margin-bottom:.35rem;font-size:.95rem}+.ls-msg .ls-btn{margin-top:.7rem}+.ls-err{color:#f6b3b3;border-color:rgba(246,179,179,.28)}+.ls-btn{display:inline-flex;align-items:center;gap:.4rem;font-size:.76rem;font-weight:650;padding:.44rem .78rem;border-radius:9px;cursor:pointer;text-decoration:none;+ background:rgba(255,255,255,.06);border:1px solid var(--line2);color:rgba(255,255,255,.82);transition:all .15s}+.ls-btn:hover{background:rgba(255,255,255,.11);color:#fff}+.ls-btn.primary{background:linear-gradient(135deg,rgba(120,200,140,.24),rgba(60,140,100,.15));border-color:rgba(120,200,140,.45);color:#d2f3df}+.ls-btn.primary:hover{background:linear-gradient(135deg,rgba(120,200,140,.36),rgba(60,140,100,.24));border-color:rgba(120,200,140,.7)}++.ls-skel{border-radius:14px;background:linear-gradient(100deg,rgba(255,255,255,.03) 30%,rgba(255,255,255,.07) 50%,rgba(255,255,255,.03) 70%);+ background-size:200% 100%;animation:ls-sh 1.3s linear infinite;height:132px}+@keyframes ls-sh{to{background-position:-200% 0}}++/* Preview drawer */+.ls-drawer{position:fixed;inset:0;z-index:60;display:flex;justify-content:flex-end;pointer-events:none}+.ls-drawer.open{pointer-events:auto}+.ls-scrim{position:absolute;inset:0;background:rgba(4,6,10,.62);opacity:0;transition:opacity .25s var(--ease);backdrop-filter:blur(2px)}+.ls-drawer.open .ls-scrim{opacity:1}+.ls-panel{position:relative;width:min(560px,100%);height:100%;overflow-y:auto;background:#0d1119;border-left:1px solid var(--line2);+ box-shadow:-30px 0 60px -20px rgba(0,0,0,.7);transform:translateX(100%);transition:transform .3s var(--ease);padding:1.1rem 1.2rem 2.4rem}+.ls-drawer.open .ls-panel{transform:none}+.ls-ph{display:flex;align-items:flex-start;gap:.6rem;position:sticky;top:-1.1rem;background:linear-gradient(180deg,#0d1119 80%,rgba(13,17,25,0));padding:.3rem 0 .7rem;margin:-.3rem 0 0;z-index:2}+.ls-ph-ic{width:34px;height:34px;flex-shrink:0;display:grid;place-items:center;border-radius:10px;font-size:1rem;+ background:hsl(var(--h) 60% 55% / .16);color:hsl(var(--h) 75% 72%);border:1px solid hsl(var(--h) 60% 55% / .3)}+.ls-ph-tt{flex:1;min-width:0}+.ls-ph-tt h3{font-size:1.02rem;font-weight:700;letter-spacing:-.02em;margin:0 0 .12rem}+.ls-ph-tt p{font-size:.72rem;color:var(--dim);margin:0;line-height:1.45}+.ls-x{flex-shrink:0;width:30px;height:30px;border-radius:8px;border:1px solid var(--line2);background:rgba(255,255,255,.04);color:var(--dim);cursor:pointer;font-size:1rem;line-height:1;transition:all .15s}+.ls-x:hover{background:rgba(255,255,255,.1);color:#fff}++.ls-ctrls{display:flex;flex-direction:column;gap:.6rem;padding:.85rem;border-radius:12px;background:rgba(255,255,255,.025);border:1px solid var(--line);margin:.3rem 0 1rem}+.ls-ctrl-l{font-size:.66rem;font-weight:600;letter-spacing:.03em;text-transform:uppercase;color:rgba(255,255,255,.42);margin-bottom:.38rem}+.ls-rt{display:flex;gap:.3rem;flex-wrap:wrap}+.ls-rt button{font-size:.68rem;font-weight:600;padding:.32rem .55rem;border-radius:8px;cursor:pointer;+ background:rgba(255,255,255,.04);border:1px solid var(--line);color:var(--dim);transition:all .13s}+.ls-rt button:hover{color:#fff;border-color:var(--line2)}+.ls-rt button.on{background:rgba(164,240,188,.13);border-color:rgba(164,240,188,.42);color:#c8f0d8}+.ls-rt-input{margin-top:.5rem;width:100%;padding:.42rem .6rem;border-radius:8px;outline:none;font-size:.74rem;font-family:ui-monospace,monospace;+ background:rgba(255,255,255,.04);border:1px solid var(--line);color:#fff}+.ls-rt-input:focus{border-color:rgba(164,240,188,.45)}+.ls-rt-hint{font-size:.66rem;color:rgba(255,255,255,.4);margin-top:.35rem;line-height:1.4}+.ls-slider-row{display:flex;align-items:center;gap:.6rem}+.ls-slider-row input[type=range]{flex:1;accent-color:#a4f0bc}+.ls-slider-v{font-size:.74rem;font-family:ui-monospace,monospace;color:#c8f0d8;min-width:4.5rem;text-align:right}+.ls-netseg{display:inline-flex;background:rgba(255,255,255,.04);border:1px solid var(--line);border-radius:8px;padding:.12rem}+.ls-netseg button{font-size:.68rem;font-weight:600;padding:.26rem .5rem;border-radius:6px;cursor:pointer;background:none;border:none;color:var(--dim)}+.ls-netseg button.on{background:rgba(255,255,255,.1);color:#fff}++.ls-coins{display:flex;flex-direction:column;gap:.55rem}+.ls-coin{display:flex;flex-direction:column;gap:.5rem;padding:.75rem;border-radius:12px;background:rgba(255,255,255,.03);border:1px solid var(--line);+ animation:ls-in .35s var(--ease) both}+@keyframes ls-in{from{opacity:0;transform:translateY(8px)}}.ls-coin-top{display:flex;align-items:center;gap:.6rem}-.ls-coin-img{width:38px;height:38px;border-radius:9px;object-fit:cover;background:rgba(255,255,255,.06);flex-shrink:0}+.ls-coin-img{width:40px;height:40px;border-radius:10px;object-fit:cover;background:rgba(255,255,255,.06);flex-shrink:0}+.ls-coin-ph{width:40px;height:40px;border-radius:10px;flex-shrink:0;display:grid;place-items:center;font-weight:800;font-size:.95rem;color:#0c1410;+ background:hsl(var(--h) 65% 62%)}.ls-coin-id{flex:1;min-width:0}-.ls-coin-n{font-size:.88rem;font-weight:700;letter-spacing:-.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}-.ls-coin-s{font-size:.68rem;color:rgba(255,255,255,.45);font-family:ui-monospace,monospace}-.ls-coin-d{font-size:.71rem;color:rgba(255,255,255,.55);line-height:1.5;min-height:2.1em}-.ls-coin-meta{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;font-size:.66rem}-.ls-tag{color:rgba(255,255,255,.4);background:rgba(255,255,255,.04);border:1px solid var(--g);padding:.16rem .42rem;border-radius:6px}+.ls-coin-n{font-size:.9rem;font-weight:700;letter-spacing:-.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.ls-coin-s{font-size:.68rem;color:var(--dim);font-family:ui-monospace,monospace}+.ls-copy{flex-shrink:0;width:28px;height:28px;border-radius:7px;border:1px solid var(--line);background:rgba(255,255,255,.04);color:var(--dim);cursor:pointer;font-size:.78rem;transition:all .13s}+.ls-copy:hover{background:rgba(255,255,255,.1);color:#fff}+.ls-coin-d{font-size:.72rem;color:rgba(255,255,255,.58);line-height:1.5}+.ls-bar{height:4px;border-radius:999px;background:rgba(255,255,255,.07);overflow:hidden}+.ls-bar>i{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,hsl(var(--h) 70% 55%),hsl(var(--h) 80% 68%))}+.ls-coin-meta{display:flex;align-items:center;gap:.4rem;flex-wrap:wrap;font-size:.65rem}+.ls-tag{color:rgba(255,255,255,.42);background:rgba(255,255,255,.04);border:1px solid var(--line);padding:.15rem .42rem;border-radius:6px}.ls-tag.reward{color:#9fdcb4;background:rgba(164,240,188,.07);border-color:rgba(164,240,188,.2)}-.ls-tag.reward.pending{color:#c8b78a;background:rgba(240,210,140,.07);border-color:rgba(240,210,140,.2)}-.ls-coin-go{margin-top:.15rem;display:flex;align-items:center;justify-content:center;gap:.4rem;font-size:.76rem;font-weight:650;- padding:.5rem;border-radius:9px;cursor:pointer;text-decoration:none;- background:linear-gradient(135deg,rgba(120,200,140,.22),rgba(60,140,100,.14));border:1px solid rgba(120,200,140,.42);color:#d2f3df;transition:all .15s}-.ls-coin-go:hover{background:linear-gradient(135deg,rgba(120,200,140,.34),rgba(60,140,100,.22));border-color:rgba(120,200,140,.65)}--.ls-skel{border-radius:13px;background:linear-gradient(100deg,rgba(255,255,255,.03) 30%,rgba(255,255,255,.07) 50%,rgba(255,255,255,.03) 70%);- background-size:200% 100%;animation:ls-sh 1.3s linear infinite;height:118px}-@keyframes ls-sh{to{background-position:-200% 0}}-.ls-msg{padding:1.4rem;text-align:center;font-size:.82rem;color:rgba(255,255,255,.5);border:1px dashed var(--g2);border-radius:12px;line-height:1.6}-.ls-msg b{color:#fff;display:block;margin-bottom:.3rem;font-size:.9rem}-.ls-err{color:#f6b3b3;border-color:rgba(246,179,179,.25)}-.ls-spin{display:inline-block;width:13px;height:13px;border:2px solid rgba(255,255,255,.15);border-top-color:#a4f0bc;border-radius:50%;animation:ls-r .8s linear infinite;vertical-align:-2px}-@keyframes ls-r{to{transform:rotate(360deg)}}-@media(max-width:560px){.ls-grid,.ls-coins{grid-template-columns:1fr}}+.ls-tag.reward.pending{color:#e6cf96;background:rgba(240,205,130,.07);border-color:rgba(240,205,130,.2)}+.ls-coin-go{margin-top:.15rem;display:flex;align-items:center;justify-content:center;gap:.4rem;font-size:.78rem;font-weight:700;padding:.55rem;border-radius:10px;+ text-decoration:none;background:linear-gradient(135deg,rgba(120,200,140,.24),rgba(60,140,100,.15));border:1px solid rgba(120,200,140,.45);color:#d2f3df;transition:all .15s}+.ls-coin-go:hover{background:linear-gradient(135deg,rgba(120,200,140,.38),rgba(60,140,100,.24));border-color:rgba(120,200,140,.72)}+.ls-toast{position:fixed;bottom:22px;left:50%;transform:translateX(-50%) translateY(20px);z-index:80;font-size:.78rem;font-weight:600;color:#0c1410;+ background:#a4f0bc;padding:.5rem .9rem;border-radius:10px;opacity:0;transition:all .25s var(--ease);pointer-events:none;box-shadow:0 8px 24px -8px rgba(0,0,0,.5)}+.ls-toast.show{opacity:1;transform:translateX(-50%) translateY(0)}+@media(max-width:560px){.ls-grid{grid-template-columns:1fr}.ls-modeseg{margin-left:0}}+@media(prefers-reduced-motion:reduce){.ls *{animation-duration:.01ms!important;transition-duration:.01ms!important}}`;export function mountLaunchStudio(root) {if (!document.getElementById('ls-css')) {const st = document.createElement('style'); st.id = 'ls-css'; st.textContent = CSS; document.head.appendChild(st);}+ let favs = new Set();+ try { favs = new Set(JSON.parse(localStorage.getItem(FAV_KEY) || '[]')); } catch { /* ignore */ }+const s = {- cats: [], useCases: [], total: 0, activeCat: 'all',+ cats: [], useCases: [], total: 0,+ q: '', activeCat: 'all', mode: 'all',listLoading: true, listError: '',- activeId: null, preview: null, previewLoading: false, previewError: '',+ // drawer+ open: false, activeId: null, preview: null, previewLoading: false, previewError: '',+ rt: 'default', rtValue: '', devBuy: 0, network: 'mainnet',};let alive = true;+ const saveFavs = () => { try { localStorage.setItem(FAV_KEY, JSON.stringify([...favs])); } catch { /* ignore */ } };+ // ── data ────────────────────────────────────────────────────────────────async function loadList() {- s.listLoading = true; s.listError = ''; render();+ s.listLoading = true; s.listError = ''; renderGrid();try {const r = await fetch(`${API}?action=list`, { headers: { accept: 'application/json' } });const d = await r.json();if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);s.cats = d.categories || []; s.useCases = d.use_cases || []; s.total = d.count || s.useCases.length;} catch (e) { s.listError = e.message || String(e); }- s.listLoading = false; render();+ s.listLoading = false; renderAll();}- async function preview(id) {- s.activeId = id; s.preview = null; s.previewError = ''; s.previewLoading = true; render();+ async function loadPreview(id) {+ s.previewLoading = true; s.previewError = ''; s.preview = null; renderDrawer();try {- const r = await fetch(`${API}?action=preview&id=${encodeURIComponent(id)}&limit=6`, { headers: { accept: 'application/json' } });+ const r = await fetch(`${API}?action=preview&id=${encodeURIComponent(id)}&limit=6&network=${s.network}`, { headers: { accept: 'application/json' } });const d = await r.json();if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);- if (!alive) return;+ if (!alive || s.activeId !== id) return;s.preview = d;} catch (e) { s.previewError = e.message || String(e); }- s.previewLoading = false; render();+ s.previewLoading = false; renderDrawer();}- function launchHref(item) {- const p = new URLSearchParams();- p.set('name', item.identity.name);- if (item.identity.symbol) p.set('symbol', item.identity.symbol);- if (item.identity.description) p.set('description', item.identity.description);- if (item.identity.image) p.set('image', item.identity.image);- return `/launch?${p.toString()}`;+ // ── filtering ─────────────────────────────────────────────────────────────+ function filtered() {+ const q = s.q.trim().toLowerCase();+ return s.useCases.filter((u) => {+ if (s.activeCat === 'saved') { if (!favs.has(u.id)) return false; }+ else if (s.activeCat !== 'all' && u.category !== s.activeCat) return false;+ if (s.mode !== 'all' && u.mode !== s.mode) return false;+ if (q && !(`${u.title} ${u.description} ${(u.tags || []).join(' ')} ${u.category}`.toLowerCase().includes(q))) return false;+ return true;+ });+ }++ // ── reward planner ──────────────────────────────────────────────────────────+ function effectiveReward(item) {+ const t = s.rt;+ if (t === 'default') return item.reward;+ if (t === 'creator') return { kind: 'creator', note: 'Fees stay with the launching wallet.' };+ if (t === 'cashback') return { kind: 'cashback', note: 'Trading fees return to holders as cashback.' };+ if (t === 'buyback') return { kind: 'buyback', note: 'Fees auto-buy-back & burn the coin.' };+ if (t === 'github') return { kind: 'github-owner', username: s.rtValue.replace(/^@/, ''), mode: 'pending', note: `Routes to @${s.rtValue.replace(/^@/, '') || '…'} on GitHub.` };+ if (t === 'x') return { kind: 'x-owner', username: s.rtValue.replace(/^@/, ''), mode: 'pending', note: `Routes to @${s.rtValue.replace(/^@/, '') || '…'} on X.` };+ if (t === 'wallet') return { kind: 'address', address: s.rtValue, note: 'Routes to a fixed Solana address / .sol name.' };+ return item.reward;}function rewardChip(reward) {- if (reward.kind === 'github-owner' && reward.github_username) {- return `<span class="ls-tag reward pending" title="${esc(reward.note || '')}">→ @${esc(reward.github_username)}</span>`;+ if ((reward.kind === 'github-owner' || reward.kind === 'x-owner')) {+ const u = reward.username || reward.github_username;+ const plat = reward.kind === 'x-owner' ? '𝕏' : 'gh';+ return `<span class="ls-tag reward pending" title="${esc(reward.note || '')}">→ ${plat}:@${esc(u || '…')}</span>`;}- if (reward.kind === 'split') return `<span class="ls-tag reward pending" title="${esc(reward.note || '')}">→ split</span>`;- if (reward.kind === 'address') return `<span class="ls-tag reward">→ wallet</span>`;+ if (reward.kind === 'address') return `<span class="ls-tag reward" title="${esc(reward.note || '')}">→ ${esc((reward.address || '').slice(0, 10)) || 'wallet'}…</span>`;+ if (reward.kind === 'cashback') return `<span class="ls-tag reward" title="${esc(reward.note || '')}">↩ cashback</span>`;+ if (reward.kind === 'buyback') return `<span class="ls-tag reward" title="${esc(reward.note || '')}">🔥 buyback</span>`;+ if (reward.kind === 'split') return `<span class="ls-tag reward pending">→ split</span>`;return `<span class="ls-tag">creator fees</span>`;}- function visibleUseCases() {- return s.activeCat === 'all' ? s.useCases : s.useCases.filter((u) => u.category === s.activeCat);+ function launchHref(item) {+ const p = new URLSearchParams();+ p.set('name', item.identity.name);+ if (item.identity.symbol) p.set('symbol', item.identity.symbol);+ if (item.identity.description) p.set('description', item.identity.description);+ if (item.identity.image) p.set('image', item.identity.image);+ if (s.devBuy > 0) p.set('initialBuy', String(s.devBuy));+ const r = effectiveReward(item);+ if ((r.kind === 'github-owner' || r.kind === 'x-owner') && (r.username || r.github_username)) p.set('reward', `${r.kind === 'x-owner' ? 'x' : 'github'}:${r.username || r.github_username}`);+ else if (r.kind === 'address' && r.address) p.set('reward', `wallet:${r.address}`);+ else if (r.kind === 'cashback' || r.kind === 'buyback') p.set('reward', r.kind);+ return `/launch?${p.toString()}`;}- function render() {- if (!alive) return;- root.innerHTML = `<div class="ls">${renderBar()}${renderCatalog()}${renderPreview()}</div>`;- wire();- }+ // ── render ────────────────────────────────────────────────────────────────+ function renderAll() { root.innerHTML = `<div class="ls">${renderTools()}<div id="ls-grid"></div></div><div id="ls-drawer-root"></div><div class="ls-toast" id="ls-toast"></div>`; renderGrid(); renderDrawer(); wireTools(); }- function renderBar() {- if (s.listLoading || s.listError) return '';- const chip = (id, label, n) =>- `<button class="ls-chip${s.activeCat === id ? ' on' : ''}" data-cat="${esc(id)}">${esc(label)}${n != null ? ` <span class="ls-chip-n">${n}</span>` : ''}</button>`;- const cats = s.cats.map((c) => {- const meta = CATEGORY_META[c] || { label: c, icon: '' };+ function renderTools() {+ if (s.listLoading || s.listError) return '<div id="ls-tools-slot"></div>';+ const tab = (id, label, n, extra = '') =>+ `<button class="ls-tab${s.activeCat === id ? ' on' : ''}" data-cat="${esc(id)}" ${extra}>${esc(label)}${n != null ? ` <span class="n">${n}</span>` : ''}</button>`;+ const catTabs = s.cats.map((c) => {+ const m = CATEGORY_META[c] || { label: c, icon: '' };const n = s.useCases.filter((u) => u.category === c).length;- return chip(c, `${meta.icon} ${meta.label}`.trim(), n);+ return `<button class="ls-tab${s.activeCat === c ? ' on' : ''}" data-cat="${esc(c)}" style="--h:${hue(c)}">+ <span style="color:hsl(${hue(c)} 75% 70%)">${esc(m.icon)}</span> ${esc(m.label)} <span class="n">${n}</span></button>`;}).join('');- return `<div class="ls-bar">${chip('all', 'All', s.total)}${cats}<span class="ls-count">${s.total} use cases</span></div>`;+ const savedTab = favs.size ? tab('saved', '★ Saved', favs.size) : '';+ return `<div class="ls-tools">+ <div class="ls-search-row">+ <div class="ls-search">+ <span class="ls-mag">⌕</span>+ <input id="ls-q" type="search" placeholder="Search 50 recipes — GitHub, memes, Hacker News, sectors…" value="${esc(s.q)}" autocomplete="off" spellcheck="false" aria-label="Search recipes" />+ <span class="ls-kbd">/</span>+ </div>+ <button class="ls-surprise" id="ls-surprise" title="Preview a random recipe">✦ Surprise me</button>+ </div>+ <div class="ls-tabs">+ ${tab('all', 'All', s.total)}+ ${catTabs}+ ${savedTab}+ <div class="ls-modeseg" role="group" aria-label="Filter by type">+ <button data-mode="all" class="${s.mode === 'all' ? 'on' : ''}">All</button>+ <button data-mode="attribution" class="${s.mode === 'attribution' ? 'on' : ''}">Reward</button>+ <button data-mode="narrative" class="${s.mode === 'narrative' ? 'on' : ''}">Theme</button>+ </div>+ </div>+ </div>`;}- function renderCatalog() {- if (s.listLoading) return `<div class="ls-grid">${Array.from({ length: 9 }, () => '<div class="ls-skel"></div>').join('')}</div>`;- if (s.listError) return `<div class="ls-msg ls-err"><b>Couldn't load the catalog</b>${esc(s.listError)} — <button class="ls-refresh" id="ls-retry">Retry</button></div>`;- const items = visibleUseCases();- if (!items.length) return `<div class="ls-msg"><b>Nothing here yet</b>No use cases in this category.</div>`;- return `<div class="ls-grid">${items.map(renderCard).join('')}</div>`;+ function renderGrid() {+ const g = root.querySelector('#ls-grid'); if (!g) { return; }+ if (s.listLoading) { g.innerHTML = `<div class="ls-grid">${Array.from({ length: 9 }, () => '<div class="ls-skel"></div>').join('')}</div>`; return; }+ if (s.listError) { g.innerHTML = `<div class="ls-msg ls-err"><b>Couldn't load the catalog</b>${esc(s.listError)}<div><button class="ls-btn" id="ls-retry">↻ Retry</button></div></div>`; g.querySelector('#ls-retry')?.addEventListener('click', loadList); return; }+ const items = filtered();+ if (!items.length) { g.innerHTML = `<div class="ls-msg"><b>No recipes match</b>Try a different search or category.${s.q ? `<div><button class="ls-btn" id="ls-clear">Clear search</button></div>` : ''}</div>`; g.querySelector('#ls-clear')?.addEventListener('click', () => { s.q = ''; renderAll(); }); return; }+ g.innerHTML = `<div class="ls-grid">${items.map(renderCard).join('')}</div>`;+ g.querySelectorAll('.ls-card').forEach((el) => {+ el.addEventListener('click', () => openDrawer(el.dataset.id));+ el.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openDrawer(el.dataset.id); } });+ });+ g.querySelectorAll('.ls-fav').forEach((el) => el.addEventListener('click', (e) => {+ e.stopPropagation(); const id = el.dataset.fav;+ if (favs.has(id)) favs.delete(id); else favs.add(id);+ saveFavs(); renderAll();+ }));}function renderCard(u) {- const meta = CATEGORY_META[u.category] || { icon: '' };+ const m = CATEGORY_META[u.category] || { icon: '' };const attribution = u.mode === 'attribution';- return `<button class="ls-card${s.activeId === u.id ? ' on' : ''}" data-id="${esc(u.id)}">+ const fav = favs.has(u.id);+ return `<div class="ls-card${s.activeId === u.id && s.open ? ' on' : ''}" data-id="${esc(u.id)}" style="--h:${hue(u.category)}" tabindex="0" role="button" aria-label="${esc(u.title)}"><div class="ls-card-top">- <span class="ls-card-ic">${esc(meta.icon)}</span>+ <span class="ls-card-ic">${esc(m.icon)}</span><span class="ls-card-t">${esc(u.title)}</span>- <span class="ls-mode ${attribution ? 'attribution' : 'narrative'}">${attribution ? 'reward' : 'theme'}</span>+ <button class="ls-fav${fav ? ' on' : ''}" data-fav="${esc(u.id)}" title="${fav ? 'Saved' : 'Save recipe'}" aria-label="${fav ? 'Unsave' : 'Save'}">${fav ? '★' : '☆'}</button></div><div class="ls-card-d">${esc(u.description)}</div>- <div class="ls-card-r${attribution ? '' : ' creator'}">${attribution ? '🎁 ' : ''}${esc(u.reward_label || (attribution ? 'Routes fees to the subject' : 'Creator fees'))}</div>- </button>`;+ <div class="ls-card-foot">+ <span class="ls-mode ${attribution ? 'attribution' : 'narrative'}">${attribution ? 'reward' : 'theme'}</span>+ <span class="ls-card-r">${attribution ? '🎁' : '◆'} ${esc(u.reward_label || (attribution ? 'Routes fees to the subject' : 'Creator fees'))}</span>+ </div>+ </div>`;}- function renderPreview() {- if (!s.activeId) return '';- const uc = s.useCases.find((u) => u.id === s.activeId);- const title = uc ? uc.title : s.activeId;+ // ── drawer ────────────────────────────────────────────────────────────────+ function openDrawer(id) {+ s.activeId = id; s.open = true; s.rt = 'default'; s.rtValue = ''; s.devBuy = 0;+ renderAll(); loadPreview(id);+ }+ function closeDrawer() { s.open = false; renderDrawer(); setTimeout(() => { if (!s.open) { s.activeId = null; renderGrid(); } }, 300); }++ function renderDrawer() {+ const host = root.querySelector('#ls-drawer-root'); if (!host) return;+ if (!s.activeId) { host.innerHTML = ''; return; }+ const uc = s.useCases.find((u) => u.id === s.activeId) || { title: s.activeId, category: 'github', mode: 'narrative' };+ const m = CATEGORY_META[uc.category] || { icon: '' };let body;if (s.previewLoading) body = `<div class="ls-coins">${Array.from({ length: 3 }, () => '<div class="ls-skel" style="height:150px"></div>').join('')}</div>`;- else if (s.previewError) body = `<div class="ls-msg ls-err"><b>Preview failed</b>${esc(s.previewError)} — <button class="ls-refresh" id="ls-reload">Retry</button></div>`;- else if (!s.preview || !s.preview.items.length) body = `<div class="ls-msg"><b>No live candidates right now</b>This source is quiet at the moment — try another use case or refresh in a bit.</div>`;- else body = `<div class="ls-coins">${s.preview.items.map(renderCoin).join('')}</div>`;- const live = s.preview && s.preview.items.length ? `<span class="ls-prev-sub" style="margin:0"><b>${s.preview.items.length}</b> live candidate${s.preview.items.length === 1 ? '' : 's'}</span>` : '';- return `<div class="ls-prev">- <div class="ls-prev-h"><h3>${esc(title)}</h3>${live}<button class="ls-refresh" id="ls-reload">↻ Refresh</button></div>- <p class="ls-prev-sub">Coins this use case would mint <b>right now</b>, from live data. Each is a real launch — hit <b>Launch</b> to open the wizard prefilled.</p>- ${body}+ else if (s.previewError) body = `<div class="ls-msg ls-err"><b>Preview failed</b>${esc(s.previewError)}<div><button class="ls-btn" id="ls-reload">↻ Retry</button></div></div>`;+ else if (!s.preview || !s.preview.items.length) body = `<div class="ls-msg"><b>No live candidates right now</b>This source is quiet — try another recipe or refresh shortly.<div><button class="ls-btn" id="ls-reload">↻ Refresh</button></div></div>`;+ else body = `<div class="ls-coins">${s.preview.items.map((it, i) => renderCoin(it, i)).join('')}</div>`;++ const attribution = uc.mode === 'attribution';+ host.innerHTML = `<div class="ls-drawer${s.open ? ' open' : ''}" style="--h:${hue(uc.category)}">+ <div class="ls-scrim" id="ls-scrim"></div>+ <aside class="ls-panel" role="dialog" aria-modal="true" aria-label="${esc(uc.title)} preview">+ <div class="ls-ph">+ <span class="ls-ph-ic">${esc(m.icon)}</span>+ <div class="ls-ph-tt"><h3>${esc(uc.title)}</h3><p>${esc(uc.description || '')}</p></div>+ <button class="ls-x" id="ls-close" aria-label="Close">✕</button>+ </div>+ ${renderControls(attribution)}+ <div class="ls-ctrl-l" style="margin:.2rem 0 .5rem">Live candidates — what this would mint right now</div>+ ${body}+ </aside>+ </div>`;+ wireDrawer();+ }++ function renderControls(attribution) {+ const targets = REWARD_TARGETS.map((t) =>+ `<button data-rt="${t.id}" class="${s.rt === t.id ? 'on' : ''}" title="${esc(t.hint)}">${esc(t.label)}</button>`).join('');+ const active = REWARD_TARGETS.find((t) => t.id === s.rt);+ const input = active?.needs+ ? `<input class="ls-rt-input" id="ls-rt-input" placeholder="${active.needs === 'handle' ? '@username' : 'Solana address or name.sol'}" value="${esc(s.rtValue)}" spellcheck="false" />`+ : '';+ return `<div class="ls-ctrls">+ <div>+ <div class="ls-ctrl-l">Route creator fees to${attribution ? ' <span style="color:#9fdcb4">(recipe defaults to the subject)</span>' : ''}</div>+ <div class="ls-rt">${targets}</div>+ ${input}+ <div class="ls-rt-hint">${esc(active?.hint || '')}</div>+ </div>+ <div>+ <div class="ls-ctrl-l">Dev buy (optional) · flows into the launch</div>+ <div class="ls-slider-row">+ <input type="range" id="ls-devbuy" min="0" max="2" step="0.05" value="${s.devBuy}" aria-label="Dev buy in SOL" />+ <span class="ls-slider-v">${s.devBuy > 0 ? `${s.devBuy.toFixed(2)} SOL` : 'none'}</span>+ </div>+ </div>+ <div style="display:flex;align-items:center;gap:.6rem">+ <div class="ls-ctrl-l" style="margin:0">Network</div>+ <div class="ls-netseg">+ <button data-net="mainnet" class="${s.network === 'mainnet' ? 'on' : ''}">Mainnet</button>+ <button data-net="devnet" class="${s.network === 'devnet' ? 'on' : ''}">Devnet</button>+ </div>+ </div></div>`;}- function renderCoin(it) {+ function renderCoin(it, i) {+ const maxScore = Math.max(1, ...(s.preview.items.map((x) => Number(x.score) || 0)));+ const pct = Math.max(6, Math.round(((Number(it.score) || 0) / maxScore) * 100));const img = it.identity.image- ? `<img class="ls-coin-img" src="${esc(it.identity.image)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'" />`- : `<div class="ls-coin-img"></div>`;+ ? `<img class="ls-coin-img" src="${esc(it.identity.image)}" alt="" loading="lazy" onerror="this.outerHTML='<div class=\\'ls-coin-ph\\'>${esc((it.identity.symbol || '?')[0])}</div>'" />`+ : `<div class="ls-coin-ph">${esc((it.identity.symbol || '?')[0])}</div>`;const signal = it.signal && it.signal.detail ? `<span class="ls-tag">${esc(it.signal.detail)}</span>` : '';- return `<div class="ls-coin">+ return `<div class="ls-coin" style="animation-delay:${i * 40}ms"><div class="ls-coin-top">${img}- <div class="ls-coin-id">- <div class="ls-coin-n">${esc(it.identity.name)}</div>- <div class="ls-coin-s">$${esc(it.identity.symbol)}</div>- </div>+ <div class="ls-coin-id"><div class="ls-coin-n">${esc(it.identity.name)}</div><div class="ls-coin-s">$${esc(it.identity.symbol)}</div></div>+ <button class="ls-copy" data-copy="${esc(`${it.identity.name} $${it.identity.symbol}`)}" title="Copy name + ticker">⧉</button></div><div class="ls-coin-d">${esc(it.identity.description || '')}</div>- <div class="ls-coin-meta">${rewardChip(it.reward)}${signal}</div>+ <div class="ls-bar"><i style="width:${pct}%"></i></div>+ <div class="ls-coin-meta">${rewardChip(effectiveReward(it))}${signal}</div><a class="ls-coin-go" href="${esc(launchHref(it))}">Launch this coin →</a></div>`;}- function wire() {- root.querySelector('#ls-retry')?.addEventListener('click', loadList);- root.querySelector('#ls-reload')?.addEventListener('click', () => preview(s.activeId));- root.querySelectorAll('.ls-chip').forEach((el) => el.addEventListener('click', () => { s.activeCat = el.dataset.cat; render(); }));- root.querySelectorAll('.ls-card').forEach((el) => el.addEventListener('click', () => preview(el.dataset.id)));+ // ── wiring ────────────────────────────────────────────────────────────────+ const onSearch = debounce(() => { renderGrid(); }, 130);+ function wireTools() {+ const q = root.querySelector('#ls-q');+ if (q) {+ q.addEventListener('input', (e) => { s.q = e.target.value; onSearch(); });+ q.addEventListener('keydown', (e) => { if (e.key === 'Escape') { s.q = ''; e.target.value = ''; renderGrid(); } });+ }+ root.querySelectorAll('.ls-tab').forEach((el) => el.addEventListener('click', () => { s.activeCat = el.dataset.cat; renderAll(); }));+ root.querySelectorAll('.ls-modeseg button').forEach((el) => el.addEventListener('click', () => { s.mode = el.dataset.mode; renderAll(); }));+ root.querySelector('#ls-surprise')?.addEventListener('click', () => {+ const pool = filtered().length ? filtered() : s.useCases;+ if (pool.length) openDrawer(pool[Math.floor(Math.random() * pool.length)].id);+ });+ }++ function wireDrawer() {+ root.querySelector('#ls-close')?.addEventListener('click', closeDrawer);+ root.querySelector('#ls-scrim')?.addEventListener('click', closeDrawer);+ root.querySelector('#ls-reload')?.addEventListener('click', () => loadPreview(s.activeId));+ root.querySelectorAll('.ls-rt button').forEach((el) => el.addEventListener('click', () => { s.rt = el.dataset.rt; renderDrawer(); }));+ const rtIn = root.querySelector('#ls-rt-input');+ if (rtIn) rtIn.addEventListener('input', (e) => { s.rtValue = e.target.value; updateCoinsInPlace(); });+ const db = root.querySelector('#ls-devbuy');+ if (db) db.addEventListener('input', (e) => { s.devBuy = Number(e.target.value); const v = root.querySelector('.ls-slider-v'); if (v) v.textContent = s.devBuy > 0 ? `${s.devBuy.toFixed(2)} SOL` : 'none'; updateCoinsInPlace(); });+ root.querySelectorAll('.ls-netseg button').forEach((el) => el.addEventListener('click', () => { if (s.network !== el.dataset.net) { s.network = el.dataset.net; renderDrawer(); loadPreview(s.activeId); } }));+ root.querySelectorAll('.ls-copy').forEach((el) => el.addEventListener('click', () => { copy(el.dataset.copy); }));+ }++ // Update reward chips + launch hrefs without a full re-render (keeps input focus).+ function updateCoinsInPlace() {+ if (!s.preview) return;+ const nodes = root.querySelectorAll('.ls-coin');+ s.preview.items.forEach((it, i) => {+ const node = nodes[i]; if (!node) return;+ const meta = node.querySelector('.ls-coin-meta');+ if (meta) meta.innerHTML = rewardChip(effectiveReward(it)) + (it.signal?.detail ? `<span class="ls-tag">${esc(it.signal.detail)}</span>` : '');+ const go = node.querySelector('.ls-coin-go'); if (go) go.setAttribute('href', launchHref(it));+ });+ }++ function copy(text) {+ (navigator.clipboard?.writeText(text) || Promise.reject()).then(() => toast('Copied')).catch(() => toast('Copy failed'));+ }+ let toastT;+ function toast(msg) {+ const el = root.querySelector('#ls-toast'); if (!el) return;+ el.textContent = msg; el.classList.add('show');+ clearTimeout(toastT); toastT = setTimeout(() => el.classList.remove('show'), 1400);+ }++ // Global keyboard: "/" focus search, Esc close drawer.+ function onKey(e) {+ if (e.key === '/' && !/input|textarea/i.test(document.activeElement?.tagName || '')) { e.preventDefault(); root.querySelector('#ls-q')?.focus(); }+ if (e.key === 'Escape' && s.open) closeDrawer();}+ document.addEventListener('keydown', onKey);- render();+ renderAll();loadList();- return { teardown() { alive = false; root.innerHTML = ''; } };+ return { teardown() { alive = false; document.removeEventListener('keydown', onKey); root.innerHTML = ''; } };}diff --git a/public/nav-data.js b/public/nav-data.jsindex 728f86384..89a465db1 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -138,6 +138,11 @@ export const NAV_GROUPS = [href: '/tour',desc: 'A 3D guide walks you through every feature, live',},+ {+ title: 'Labs',+ href: '/labs',+ desc: 'Hidden gems — experimental, advanced surfaces most people never find',+ },{title: 'All pages',href: '/sitemap',diff --git a/public/studio-panels.css b/public/studio-panels.cssindex d90b5e65b..9360122c4 100644--- a/public/studio-panels.css+++ b/public/studio-panels.css@@ -802,3 +802,96 @@@media (prefers-reduced-motion: reduce) {.tb-skel, .mny-skel-line { animation: none; }}++/* ═══════════════════════════════════════════════════════════════════════════+ Trading Brain — presets, risk meter, backtest viz, shortcuts (advanced UX)+ ═══════════════════════════════════════════════════════════════════════════ */++/* — Preset launcher — */+.tb-presets { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }+.tb-presets-l { font-size: var(--text-2xs, 0.6875rem); text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-faint, #666); padding-top: 10px; white-space: nowrap; }+.tb-preset-chips { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; flex: 1; min-width: 0; }+.tb-preset {+ display: flex; flex-direction: column; gap: 3px; text-align: left; cursor: pointer;+ padding: 10px 12px; border-radius: var(--radius-md, 10px);+ background: var(--surface-1, rgba(255,255,255,0.03)); border: 1px solid var(--stroke);+ transition: border-color 0.18s var(--ease-out, ease), background-color 0.18s ease, transform 0.18s ease, box-shadow 0.18s ease;+}+.tb-preset:hover { transform: translateY(-2px); border-color: var(--stroke-strong, rgba(255,255,255,0.2)); background: var(--surface-2, rgba(255,255,255,0.06)); }+.tb-preset:focus-visible { outline: 2px solid var(--focus-ring-color, var(--accent, #6366f1)); outline-offset: 2px; }+.tb-preset.is-on {+ border-color: var(--accent, #6366f1);+ background: linear-gradient(180deg, color-mix(in srgb, var(--accent, #6366f1) 16%, transparent), color-mix(in srgb, var(--accent, #6366f1) 5%, transparent));+ box-shadow: 0 0 0 1px var(--accent, #6366f1) inset, 0 6px 20px -8px color-mix(in srgb, var(--accent, #6366f1) 50%, transparent);+}+.tb-preset-name { font-weight: var(--weight-semibold, 600); color: var(--ink-bright, #fff); font-size: var(--text-md, 0.8125rem); }+.tb-preset-tag { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim, #888); line-height: 1.3; }++/* — Top line: name + risk meter — */+.tb-topline { display: grid; grid-template-columns: 1.2fr 1fr; gap: 16px; align-items: end; margin-bottom: 18px; }+.tb-risk { display: flex; flex-direction: column; gap: 6px; }+.tb-risk-top { display: flex; align-items: baseline; justify-content: space-between; }+.tb-risk-l { font-size: var(--text-2xs, 0.6875rem); text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-faint, #666); }+.tb-risk-label { font-size: var(--text-md, 0.8125rem); font-weight: var(--weight-semibold, 600); color: var(--ink-bright, #fff); }+.tb-risk-track { height: 8px; border-radius: 999px; background: var(--surface-2, rgba(255,255,255,0.06)); overflow: hidden; box-shadow: inset 0 1px 2px rgba(0,0,0,0.3); }+.tb-risk-fill { height: 100%; border-radius: 999px; transition: width 0.5s var(--ease-out, cubic-bezier(0.16,1,0.3,1)), background 0.4s ease; }+.tb-risk-calm .tb-risk-fill { background: linear-gradient(90deg, #34d399, #10b981); }+.tb-risk-calm .tb-risk-label { color: #34d399; }+.tb-risk-balanced .tb-risk-fill { background: linear-gradient(90deg, #38bdf8, #6366f1); }+.tb-risk-balanced .tb-risk-label { color: #60a5fa; }+.tb-risk-warm .tb-risk-fill { background: linear-gradient(90deg, #fbbf24, #f97316); }+.tb-risk-warm .tb-risk-label { color: #fbbf24; }+.tb-risk-hot .tb-risk-fill { background: linear-gradient(90deg, #f97316, #ef4444); }+.tb-risk-hot .tb-risk-label { color: #f87171; }++/* — Keyboard hints on action buttons — */+.tb-kbd {+ display: inline-block; margin-left: 8px; padding: 1px 6px; border-radius: 5px;+ font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.625rem; line-height: 1.5;+ color: var(--ink-dim, #999); background: var(--surface-2, rgba(255,255,255,0.08));+ border: 1px solid var(--stroke); vertical-align: middle;+}+.studio-btn-primary .tb-kbd, .studio-btn-danger .tb-kbd { color: rgba(255,255,255,0.85); background: rgba(255,255,255,0.15); border-color: rgba(255,255,255,0.2); }+@media (max-width: 540px) { .tb-kbd { display: none; } }++/* — Backtest outcome distribution — */+.tb-dist { margin-top: 14px; display: flex; flex-direction: column; gap: 8px; }+.tb-dist-l { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim, #888); }+.tb-dist-bar { display: flex; height: 12px; border-radius: 999px; overflow: hidden; background: var(--surface-2, rgba(255,255,255,0.06)); gap: 2px; }+.tb-dist-seg { min-width: 3px; transition: flex 0.5s var(--ease-out, ease); }+.tb-dist-grad { background: #34d399; }+.tb-dist-pump { background: #60a5fa; }+.tb-dist-flat { background: #94a3b8; }+.tb-dist-rug { background: #f87171; }+.tb-dist-legend { display: flex; flex-wrap: wrap; gap: 12px; }+.tb-dist-key { display: inline-flex; align-items: center; gap: 5px; font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim, #999); }+.tb-dist-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }++/* — Backtest sample trades — */+.tb-samples { margin-top: 12px; }+.tb-samples summary { cursor: pointer; font-size: var(--text-md, 0.8125rem); color: var(--ink-dim, #999); }+.tb-samples summary:hover { color: var(--ink-bright, #fff); }+.tb-samples-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 10px; }+.tb-samples-h { font-size: var(--text-2xs, 0.6875rem); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 6px; }+.tb-samples-h.pos { color: var(--success, #4ade80); }+.tb-samples-h.neg { color: var(--danger, #f87171); }+.tb-sample-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }+.tb-sample-row { display: grid; grid-template-columns: 1fr auto auto; gap: 8px; align-items: center; font-size: var(--text-2xs, 0.6875rem); }+.tb-sample-name { color: var(--ink, #e8e8e8); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.tb-sample-out { color: var(--ink-faint, #666); }+.tb-sample-roi { font-variant-numeric: tabular-nums; text-align: right; }+.tb-sample-roi.pos { color: var(--success, #4ade80); }+.tb-sample-roi.neg { color: var(--danger, #f87171); }+@media (max-width: 540px) { .tb-topline, .tb-samples-cols { grid-template-columns: 1fr; } .tb-preset-chips { grid-template-columns: 1fr 1fr; } }++/* — Money tab: balance count-up flash — */+.mny-bal b { transition: color 0.3s ease; font-variant-numeric: tabular-nums; }+@keyframes mnyBalUp { 0% { color: var(--success, #4ade80); } 100% { color: var(--ink-bright, #fff); } }+@keyframes mnyBalDown { 0% { color: var(--danger, #f87171); } 100% { color: var(--ink-bright, #fff); } }+.mny-bal-up { animation: mnyBalUp 1.1s ease-out; }+.mny-bal-down { animation: mnyBalDown 1.1s ease-out; }++@media (prefers-reduced-motion: reduce) {+ .tb-preset, .tb-risk-fill, .tb-dist-seg { transition: none; }+ .mny-bal-up, .mny-bal-down { animation: none; }+}diff --git a/public/studio/fees-panel.js b/public/studio/fees-panel.jsindex ad3ac30c5..dfeb6965a 100644--- a/public/studio/fees-panel.js+++ b/public/studio/fees-panel.js@@ -476,50 +476,69 @@ export function mountFeesPanel(container, opts = {}) {// ── GitHub import ─────────────────────────────────────────────────────────────- // Dispatch the GitHub input. A bare "@login" always routes to that single- // account. An "owner/repo" honours the mode toggle: 'contributors' splits- // across the repo's contributors; 'owner' sends 100% to the repo owner/creator.+ // Dispatch the recipient input — routes rewards to anyone, not just GitHub:+ // • a raw Solana wallet (base58) → added directly+ // • an X handle ("x:@naval", x.com/naval) → resolved via X (platform 1)+ // • an "owner/repo" → repo owner (owner mode) or split+ // • a bare "@login" → that GitHub accountasync function importGithub() {- const repo = parseGithubRepo(s.githubRepo);+ const raw = (s.githubRepo || '').trim();+ // Raw Solana wallet → direct recipient, no resolution needed.+ if (/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(raw)) return addWalletRecipient(raw);+ // Explicit X (Twitter): "x:@handle", "x/handle", or an x.com / twitter.com URL.+ const xm = raw.match(/^(?:x:|x\/|(?:https?:\/\/)?(?:www\.)?(?:x|twitter)\.com\/)@?([A-Za-z0-9_]{1,15})$/i);+ if (xm) return addSocialAccount('x', xm[1]);+ const repo = parseGithubRepo(raw);if (repo) {- if (s.ghMode === 'owner') return addGithubAccount(repo.owner);+ if (s.ghMode === 'owner') return addSocialAccount('github', repo.owner);return importGithubRepo(repo);}- const login = parseGithubAccount(s.githubRepo);- if (login) return addGithubAccount(login);- s.githubError = 'Enter a GitHub @username, or a repo as owner/name.';+ const login = parseGithubAccount(raw);+ if (login) return addSocialAccount('github', login);+ s.githubError = 'Enter a GitHub @user, an X handle (x:@handle), an owner/repo, or a Solana wallet.';render();}- // Single GitHub account → one reward recipient. Resolves the handle to its- // three.ws-linked Solana payout wallet; if the user hasn't linked one, the- // row is added flagged so the creator can paste a wallet or ask them to link.- async function addGithubAccount(login) {- // Drop blank seed rows (the setup CTA leaves one empty 100% row) so adding- // an account doesn't strand a placeholder hogging the split.+ // Add a raw Solana wallet (or SNS-resolved address) as a direct recipient.+ function addWalletRecipient(address) {s.rows = s.rows.filter((r) => r.address?.trim() || r.gh);- if (s.rows.some((r) => r.gh?.login?.toLowerCase() === login.toLowerCase())) {+ if (s.rows.some((r) => r.address === address)) { s.githubError = 'That wallet is already a recipient.'; render(); return; }+ if (s.rows.length >= 10) { s.githubError = 'Maximum 10 recipients.'; render(); return; }+ s.rows.push({ address, bps: s.rows.length === 0 ? 10_000 : 0 });+ s.githubRepo = ''; s.githubError = ''; s.editing = true; render();+ }++ // Single social account (GitHub or X) → one reward recipient. Resolves the+ // handle to its three.ws-linked Solana payout wallet; if the user hasn't linked+ // one, the row is flagged so the creator can paste a wallet or ask them to link.+ async function addSocialAccount(platform, login) {+ const isX = platform === 'x';+ // Drop blank seed rows (the setup CTA leaves one empty 100% row).+ s.rows = s.rows.filter((r) => r.address?.trim() || r.gh);+ if (s.rows.some((r) => r.gh?.platform === platform && r.gh?.login?.toLowerCase() === login.toLowerCase())) {s.githubError = `@${login} is already a recipient.`; render(); return;}if (s.rows.length >= 10) { s.githubError = 'Maximum 10 recipients.'; render(); return; }s.githubBusy = true; s.githubError = '';- // Optimistic row — immediate feedback while we resolve the wallet. A lone- // recipient defaults to 100%; added alongside others it starts at 0% so- // the creator rebalances deliberately.const row = {address: '', bps: s.rows.length === 0 ? 10_000 : 0,- gh: { login, avatar: `https://github.com/${esc(login)}.png?size=40`, url: `https://github.com/${esc(login)}`, resolving: true },+ gh: {+ platform, login,+ avatar: isX ? `https://unavatar.io/x/${esc(login)}` : `https://github.com/${esc(login)}.png?size=40`,+ url: isX ? `https://x.com/${esc(login)}` : `https://github.com/${esc(login)}`,+ resolving: true,+ },};s.rows.push(row); s.editing = true; render();try {const r = await fetch('/api/pump/resolve-github-shareholder', {method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },- body: JSON.stringify({ github_username: login, network }),+ body: JSON.stringify({ platform, username: login, network }),});const d = await r.json();if (r.ok && d.mode === 'wallet' && d.address) {row.address = d.address; row.gh.linked = true;- s.githubRepo = ''; // clear so another can be added+ s.githubRepo = '';} else {row.gh.unlinked = true;s.githubError = d.note@@ -726,10 +745,10 @@ export function mountFeesPanel(container, opts = {}) {<div class="fp-share-row" data-i="${i}"><div class="fp-sh-meta"><input class="fp-share-addr" data-i="${i}" placeholder="Recipient Solana wallet" value="${esc(r.address)}" spellcheck="false" />- ${r.gh ? `<span class="fp-share-gh"><img src="${esc(r.gh.avatar)}" alt="" />@${esc(r.gh.login)}${+ ${r.gh ? `<span class="fp-share-gh"><img src="${esc(r.gh.avatar)}" alt="" onerror="this.style.display='none'" />${r.gh.platform === 'x' ? '𝕏 ' : ''}@${esc(r.gh.login)}${r.gh.resolving ? ` · <span style="color:rgba(255,255,255,.4)">resolving…</span>`: r.gh.linked ? ` · <span style="color:#a4f0bc">linked ✓</span>`- : r.gh.unlinked ? ` · <span style="color:rgba(246,200,114,.9)" title="No three.ws-linked Solana wallet — paste theirs, or ask them to connect GitHub + link a wallet on three.ws">add wallet</span>`+ : r.gh.unlinked ? ` · <span style="color:rgba(246,200,114,.9)" title="No three.ws-linked Solana wallet — paste theirs, or ask them to link a wallet on three.ws">add wallet</span>`: ''}</span>` : ''}</div>@@ -745,12 +764,12 @@ export function mountFeesPanel(container, opts = {}) {<button class="fp-gh-mode${s.ghMode === 'owner' ? ' on' : ''}" data-mode="owner">Owner / creator only</button></div><div class="fp-gh">- <input id="fp-gh-input" placeholder="GitHub @username or owner/repo" value="${esc(s.githubRepo)}" spellcheck="false" />+ <input id="fp-gh-input" placeholder="@github · x:@handle · owner/repo · or a Solana wallet" value="${esc(s.githubRepo)}" spellcheck="false" /><button class="fp-btn violet${s.githubBusy ? ' busy' : ''}" id="fp-gh-go" ${s.githubBusy ? 'disabled' : ''}>${s.githubBusy ? 'Resolving…' : 'Add'}</button></div><div class="fp-gh-hint">${s.ghMode === 'owner'- ? `An <b>owner/repo</b> (or <b>@username</b>) routes <b>100%</b> to that one account — no contributor split.`- : `A <b>@username</b> routes rewards to one account · an <b>owner/repo</b> splits across its contributors.`}</div>+ ? `An <b>owner/repo</b> (or <b>@user</b>) routes <b>100%</b> to that one account — no contributor split.`+ : `Route to a <b>GitHub</b> or <b>X</b> account (<b>x:@handle</b>), a <b>wallet</b>, or split a repo's <b>contributors</b>.`}</div>${s.githubError ? `<div class="fp-err">${esc(s.githubError)}</div>` : ''}${s.rows.length ? rowsHtml : `<div class="fp-note">Add recipients below or import a GitHub repo's contributors.</div>`}<button class="fp-add" id="fp-add" ${s.rows.length >= 10 ? 'disabled' : ''}>+ Add recipient</button>diff --git a/public/x402-stripe.html b/public/x402-stripe.htmlindex b29cd0b4b..dd848e4c1 100644--- a/public/x402-stripe.html+++ b/public/x402-stripe.html@@ -4,12 +4,15 @@<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script><meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" />-<title>x402 — payments, drop-in</title>-<meta name="description" content="The simplest way to accept x402 stablecoin payments. One <script> tag, a clean modal, on-chain settlement on Base and Solana." />+<title>x402 — the drop-in payment layer for agents · three.ws</title>+<meta name="description" content="A live catalog of pay-per-call APIs, settled on-chain in USDC over the x402 protocol. Search, inspect the schema, and run any endpoint with one click — no keys, no signup." /><meta name="theme-color" content="#0b0b0b" />-<meta property="og:title" content="x402 — payments, drop-in" />-<meta property="og:description" content="One <script> tag. Clean modal. On-chain x402 settlement on Base and Solana." />+<meta property="og:title" content="x402 — the drop-in payment layer for agents" />+<meta property="og:description" content="A live, searchable catalog of pay-per-call APIs. Inspect the schema and run any endpoint with one click. On-chain USDC settlement on Base and Solana." /><meta property="og:type" content="website" />+<meta property="og:url" content="https://three.ws/x402" />+<meta name="twitter:card" content="summary_large_image" />+<link rel="canonical" href="https://three.ws/x402" /><style>:root {--bg: #0b0b0b;@@ -24,266 +27,453 @@--accent: #ffffff;--accent-blue: #60a5fa;--accent-green: #4ade80;+ --accent-amber: #fbbf24;+ --danger: #fca5a5;+ --code-bg: #0f0f0f;+ --overlay: rgba(0, 0, 0, 0.66);+ --shadow: 0 24px 60px -12px rgba(0, 0, 0, 0.6);--mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;+ --ease: cubic-bezier(0.4, 0, 0.2, 1);+ }+ [data-theme="light"] {+ --bg: #fbfbfd;+ --bg-2: #f3f4f8;+ --panel: #ffffff;+ --panel-2: #f6f7fb;+ --border: #e7e8ef;+ --border-strong: #d3d5e0;+ --text: #0b0d17;+ --muted: #5b6178;+ --muted-2: #8b91a8;+ --accent: #0b0d17;+ --accent-blue: #2563eb;+ --accent-green: #16a34a;+ --accent-amber: #b45309;+ --danger: #dc2626;+ --code-bg: #0f1117;+ --overlay: rgba(20, 22, 33, 0.4);+ --shadow: 0 24px 60px -12px rgba(20, 22, 40, 0.22);}* { box-sizing: border-box; }+ html { scroll-behavior: smooth; }html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); }body {font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;font-feature-settings: 'cv11' 1, 'ss03' 1;-webkit-font-smoothing: antialiased;line-height: 1.5;+ overflow-x: hidden;}a { color: var(--accent-blue); text-decoration: none; }- a:hover { color: #93c5fd; }+ a:hover { color: var(--accent-blue); opacity: 0.82; }+ :focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 2px; border-radius: 6px; }+ code { font-family: var(--mono); }- .wrap { max-width: 1080px; margin: 0 auto; padding: 0 28px; }+ .wrap { max-width: 1180px; margin: 0 auto; padding: 0 28px; }@media (max-width: 640px) { .wrap { padding: 0 18px; } }+ /* Nav */nav {- padding: 22px 0;- display: flex; align-items: center; justify-content: space-between;+ position: sticky; top: 0; z-index: 40;+ background: color-mix(in srgb, var(--bg) 82%, transparent);+ backdrop-filter: saturate(1.4) blur(14px);+ -webkit-backdrop-filter: saturate(1.4) blur(14px);+ border-bottom: 1px solid transparent;+ transition: border-color 0.2s;+ }+ nav.scrolled { border-bottom-color: var(--border); }+ nav .navrow {+ max-width: 1180px; margin: 0 auto; padding: 15px 28px;+ display: flex; align-items: center; justify-content: space-between; gap: 16px;}- nav .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 15px; letter-spacing: -0.01em; }+ @media (max-width: 640px) { nav .navrow { padding: 13px 18px; } }+ nav .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 15px; letter-spacing: -0.01em; color: var(--text); }nav .brand .dot {width: 24px; height: 24px;- background: conic-gradient(from 200deg, #ffffff, #60a5fa, #ffffff);+ background: conic-gradient(from 200deg, var(--text), var(--accent-blue), var(--text));border-radius: 7px;}- nav .links { display: flex; gap: 22px; font-size: 13px; color: var(--muted); }- nav .links a { color: var(--muted); }- nav .links a:hover { color: var(--text); }- @media (max-width: 540px) { nav .links { display: none; } }+ nav .links { display: flex; align-items: center; gap: 8px; font-size: 13px; }+ nav .links a { color: var(--muted); padding: 7px 10px; border-radius: 8px; transition: color 0.12s, background 0.12s; }+ nav .links a:hover { color: var(--text); background: var(--panel); opacity: 1; }+ @media (max-width: 720px) { nav .links a.hide-sm { display: none; } }++ .icon-btn {+ display: inline-flex; align-items: center; justify-content: center; gap: 7px;+ height: 34px; padding: 0 11px;+ background: var(--panel); border: 1px solid var(--border); border-radius: 9px;+ color: var(--muted); font-size: 12.5px; font-family: inherit; font-weight: 500;+ cursor: pointer; transition: color 0.12s, border-color 0.12s, background 0.12s;+ }+ .icon-btn:hover { color: var(--text); border-color: var(--border-strong); }+ .icon-btn kbd {+ font-family: var(--mono); font-size: 10.5px; color: var(--muted-2);+ background: var(--bg-2); border: 1px solid var(--border); border-radius: 4px;+ padding: 1px 5px; line-height: 1.4;+ }+ .icon-btn svg { width: 15px; height: 15px; }/* Hero */- .hero { padding: 80px 0 64px; }+ .hero { padding: 72px 0 44px; position: relative; }+ .hero::before {+ content: ""; position: absolute; inset: -120px 0 auto 0; height: 380px; z-index: -1;+ background: radial-gradient(600px 240px at 20% 0%, color-mix(in srgb, var(--accent-blue) 16%, transparent), transparent 70%),+ radial-gradient(500px 220px at 80% 10%, color-mix(in srgb, var(--accent-green) 12%, transparent), transparent 70%);+ pointer-events: none;+ }+ .eyebrow {+ display: inline-flex; align-items: center; gap: 8px;+ font-size: 12px; font-weight: 600; letter-spacing: 0.02em; color: var(--muted);+ background: var(--panel); border: 1px solid var(--border); border-radius: 99px;+ padding: 6px 13px; margin-bottom: 22px;+ }+ .eyebrow .led { width: 6px; height: 6px; border-radius: 50%; background: var(--accent-green); box-shadow: 0 0 8px var(--accent-green); animation: pulse 2.4s var(--ease) infinite; }+ @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.35} }.hero h1 {- font-size: clamp(40px, 6vw, 64px); line-height: 1.04;- margin: 0 0 22px; font-weight: 800; letter-spacing: -0.03em;- max-width: 18ch;+ font-size: clamp(40px, 6.2vw, 66px); line-height: 1.03;+ margin: 0 0 22px; font-weight: 800; letter-spacing: -0.035em; max-width: 16ch;}.hero h1 .grad {- background: linear-gradient(120deg, #ffffff 30%, #60a5fa 60%, #4ade80 90%);+ background: linear-gradient(120deg, var(--text) 20%, var(--accent-blue) 58%, var(--accent-green) 92%);-webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent;}- .hero p.lede {- font-size: 19px; color: var(--muted); margin: 0 0 32px;- max-width: 60ch; line-height: 1.55;- }+ .hero p.lede { font-size: 19px; color: var(--muted); margin: 0 0 30px; max-width: 62ch; line-height: 1.55; }+ .hero p.lede code { background: var(--panel); padding: 2px 6px; border-radius: 5px; font-size: 0.88em; }.hero .cta-row { display: flex; gap: 12px; flex-wrap: wrap; }.btn {- display: inline-flex; align-items: center; gap: 8px;- padding: 13px 22px;- background: #ffffff; color: #0b0b0b;- border: none; border-radius: 11px;- font-size: 14px; font-weight: 600; font-family: inherit;- cursor: pointer; letter-spacing: -0.005em;- text-decoration: none;- transition: transform 0.06s, background 0.12s;- }- .btn:hover { background: #e7e9ee; color: #0b0b0b; }- .btn:active { transform: translateY(1px); }- .btn.ghost {- background: transparent; color: var(--text);- border: 1px solid var(--border-strong);+ display: inline-flex; align-items: center; gap: 8px; padding: 13px 22px;+ background: var(--accent); color: var(--bg);+ border: none; border-radius: 11px; font-size: 14px; font-weight: 600; font-family: inherit;+ cursor: pointer; letter-spacing: -0.005em; text-decoration: none;+ transition: transform 0.06s var(--ease), opacity 0.12s;}- .btn.ghost:hover { background: var(--panel); color: var(--text); }+ .btn:hover { opacity: 0.88; color: var(--bg); }+ .btn:active { transform: translateY(1px); }+ .btn.ghost { background: transparent; color: var(--text); border: 1px solid var(--border-strong); }+ .btn.ghost:hover { background: var(--panel); color: var(--text); opacity: 1; }- /* Network badges row */- .networks {- display: flex; gap: 18px; flex-wrap: wrap; align-items: center;- margin-top: 40px;- padding-top: 24px; border-top: 1px solid var(--border);- font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em;+ /* Stats strip */+ .stats {+ display: grid; grid-template-columns: repeat(5, 1fr); gap: 1px;+ background: var(--border); border: 1px solid var(--border); border-radius: 14px;+ overflow: hidden; margin-top: 40px;}- .networks .pill {- display: inline-flex; align-items: center; gap: 8px;- padding: 7px 13px; border-radius: 99px;- background: var(--panel); border: 1px solid var(--border);- font-family: var(--mono); font-size: 11px; color: var(--text);- text-transform: none; letter-spacing: 0;- }- .networks .pill .led {- width: 6px; height: 6px; border-radius: 50%;- background: var(--accent-green); box-shadow: 0 0 6px var(--accent-green);+ @media (max-width: 720px) { .stats { grid-template-columns: repeat(2, 1fr); } }+ .stat { background: var(--panel); padding: 16px 18px; }+ .stat .k { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted-2); margin-bottom: 7px; }+ .stat .v { font-size: 22px; font-weight: 700; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; }+ .stat .v small { font-size: 13px; color: var(--muted); font-weight: 500; }+ .stat .v.skeleton, .sk { color: transparent; border-radius: 6px;+ background: linear-gradient(90deg, var(--panel-2) 25%, var(--border) 50%, var(--panel-2) 75%);+ background-size: 200% 100%; animation: shimmer 1.3s infinite;}+ @keyframes shimmer { 0%{background-position:200% 0} 100%{background-position:-200% 0} }- /* Section heading */- section { padding: 56px 0; }+ /* Sections */+ section { padding: 52px 0; scroll-margin-top: 70px; }section.alt { background: linear-gradient(180deg, transparent, var(--bg-2)); }- section h2 {- font-size: 32px; font-weight: 700; letter-spacing: -0.02em;- margin: 0 0 14px;- }+ .sec-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; flex-wrap: wrap; margin-bottom: 26px; }+ section h2 { font-size: 30px; font-weight: 700; letter-spacing: -0.025em; margin: 0 0 12px; }section h2 .num { color: var(--muted-2); font-weight: 500; margin-right: 12px; font-variant-numeric: tabular-nums; }- section p.sub {- font-size: 16px; color: var(--muted); margin: 0 0 32px; max-width: 60ch;- }+ section p.sub { font-size: 16px; color: var(--muted); margin: 0; max-width: 62ch; line-height: 1.55; }+ section h2 + p.sub { margin-top: -2px; }/* Snippet */.snippet {- background: #0f0f0f; border: 1px solid var(--border); border-radius: 14px;- padding: 18px 22px;- font-family: var(--mono); font-size: 13px; line-height: 1.65;- color: #c8ccd4; white-space: pre;- overflow-x: auto;- position: relative;- }- .snippet .k { color: #ffffff; }- .snippet .s { color: #6ee7b7; }- .snippet .n { color: var(--muted); }- .snippet .a { color: #fbbf24; }- .snippet .c { color: var(--muted-2); }- .snippet .copy-btn {+ background: var(--code-bg); border: 1px solid var(--border); border-radius: 14px;+ padding: 18px 22px; font-family: var(--mono); font-size: 13px; line-height: 1.65;+ color: #c8ccd4; white-space: pre; overflow-x: auto; position: relative;+ }+ .snippet .k { color: #e5e9f0; } .snippet .s { color: #6ee7b7; }+ .snippet .n { color: #8a90a8; } .snippet .a { color: #fbbf24; } .snippet .c { color: #6b7088; }+ .copy-btn {position: absolute; top: 10px; right: 10px;- background: var(--panel-2); border: 1px solid var(--border);- color: var(--muted); font-size: 11px;- padding: 5px 10px; border-radius: 6px; cursor: pointer;- font-family: inherit;- }- .snippet .copy-btn:hover { color: var(--text); border-color: var(--border-strong); }- .snippet .copy-btn.copied { color: var(--accent-green); border-color: var(--accent-green); }-- /* SKU grid */- .sku-grid {- display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));- gap: 14px;- }- .sku-card {- background: var(--panel); border: 1px solid var(--border); border-radius: 14px;- padding: 22px;- display: flex; flex-direction: column; gap: 12px;- transition: border-color 0.15s, transform 0.08s;- }- .sku-card:hover { border-color: var(--border-strong); }- .sku-card .head {- display: flex; align-items: flex-start; justify-content: space-between; gap: 12px;- }- .sku-card .title { font-weight: 700; font-size: 17px; letter-spacing: -0.01em; }- .sku-card .price {- font-family: var(--mono); font-size: 13px;- background: var(--bg-2); border: 1px solid var(--border);- padding: 4px 10px; border-radius: 6px; color: var(--accent-green);- flex: 0 0 auto;- }- .sku-card .desc {- color: var(--muted); font-size: 13px; line-height: 1.55;- flex: 1; min-height: 56px;- }- .sku-card .net {- font-family: var(--mono); font-size: 11px; color: var(--muted-2);- display: flex; gap: 10px;- }- .sku-card .buy {- padding: 12px 16px;- background: #ffffff; color: #0b0b0b;- border: none; border-radius: 10px;- font-size: 14px; font-weight: 600; font-family: inherit;- cursor: pointer; letter-spacing: -0.005em;- transition: background 0.12s, transform 0.05s;- }- .sku-card .buy:hover { background: #e7e9ee; }- .sku-card .buy:active { transform: translateY(1px); }-- .result-panel {- margin-top: 12px;- display: none;- background: var(--bg-2); border: 1px solid var(--border); border-radius: 10px;- padding: 12px 14px;- font-family: var(--mono); font-size: 12px; line-height: 1.55;- color: var(--text); max-height: 220px; overflow: auto;- white-space: pre-wrap; word-break: break-word;- }- .result-panel.show { display: block; }- .result-panel .ok { color: var(--accent-green); font-weight: 600; }- .result-panel .err { color: #fca5a5; font-weight: 600; }+ background: rgba(255,255,255,0.06); border: 1px solid var(--border);+ color: #b9bfd0; font-size: 11px; padding: 5px 10px; border-radius: 6px; cursor: pointer; font-family: inherit;+ transition: color 0.12s, border-color 0.12s;+ }+ .copy-btn:hover { color: #fff; border-color: var(--border-strong); }+ .copy-btn.copied { color: var(--accent-green); border-color: var(--accent-green); }- /* Steps */- .steps {- display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px;+ /* Catalog toolbar */+ .toolbar { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; margin-bottom: 18px; }+ .search {+ flex: 1 1 260px; min-width: 200px; position: relative; display: flex; align-items: center;}- @media (max-width: 740px) { .steps { grid-template-columns: 1fr; } }- .step-card {- background: var(--panel); border: 1px solid var(--border); border-radius: 14px;- padding: 22px;+ .search svg { position: absolute; left: 13px; width: 16px; height: 16px; color: var(--muted-2); pointer-events: none; }+ .search input {+ width: 100%; height: 42px; padding: 0 40px 0 38px;+ background: var(--panel); border: 1px solid var(--border); border-radius: 11px;+ color: var(--text); font-size: 14px; font-family: inherit; transition: border-color 0.12s;}+ .search input::placeholder { color: var(--muted-2); }+ .search input:focus { outline: none; border-color: var(--accent-blue); }+ .search .slash { position: absolute; right: 11px; font-family: var(--mono); font-size: 11px; color: var(--muted-2); border: 1px solid var(--border); border-radius: 4px; padding: 1px 6px; }+ .select {+ height: 42px; padding: 0 34px 0 13px;+ background: var(--panel) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%238a90a8' stroke-width='2.4'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E") no-repeat right 12px center;+ border: 1px solid var(--border); border-radius: 11px; color: var(--text); font-size: 13.5px; font-family: inherit;+ cursor: pointer; -webkit-appearance: none; appearance: none; transition: border-color 0.12s;+ }+ .select:hover { border-color: var(--border-strong); }+ .select:focus { outline: none; border-color: var(--accent-blue); }+ .chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 22px; }+ .chip {+ padding: 7px 13px; border-radius: 99px; font-size: 12.5px; font-weight: 500; cursor: pointer;+ background: var(--panel); border: 1px solid var(--border); color: var(--muted);+ transition: all 0.12s var(--ease); display: inline-flex; align-items: center; gap: 7px;+ }+ .chip:hover { color: var(--text); border-color: var(--border-strong); }+ .chip.active { background: var(--text); color: var(--bg); border-color: var(--text); }+ .chip .n { font-variant-numeric: tabular-nums; opacity: 0.6; }+ .chip.active .n { opacity: 0.7; }+ .count-line { font-size: 13px; color: var(--muted-2); margin-bottom: 16px; font-variant-numeric: tabular-nums; }++ /* Card grid */+ .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 14px; }+ .card {+ background: var(--panel); border: 1px solid var(--border); border-radius: 15px;+ padding: 20px; display: flex; flex-direction: column; gap: 12px; cursor: pointer;+ transition: border-color 0.15s var(--ease), transform 0.12s var(--ease), box-shadow 0.15s;+ position: relative; text-align: left; font-family: inherit; color: inherit;+ animation: rise 0.4s var(--ease) both;+ }+ @keyframes rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }+ .card:hover { border-color: var(--border-strong); transform: translateY(-2px); box-shadow: var(--shadow); }+ .card:focus-visible { border-color: var(--accent-blue); }+ .card .top { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }+ .card .cat { font-size: 10.5px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--accent-blue); }+ .card .price {+ font-family: var(--mono); font-size: 12.5px; font-weight: 600; color: var(--accent-green);+ background: color-mix(in srgb, var(--accent-green) 12%, transparent); border: 1px solid color-mix(in srgb, var(--accent-green) 26%, transparent);+ padding: 3px 9px; border-radius: 6px; flex: 0 0 auto; white-space: nowrap;+ }+ .card .price.free { color: var(--accent-blue); background: color-mix(in srgb, var(--accent-blue) 12%, transparent); border-color: color-mix(in srgb, var(--accent-blue) 26%, transparent); }+ .card .title { font-weight: 700; font-size: 16px; letter-spacing: -0.01em; line-height: 1.3; }+ .card .desc { color: var(--muted); font-size: 13px; line-height: 1.5; flex: 1; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }+ .card .meta { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font-family: var(--mono); font-size: 11px; color: var(--muted-2); }+ .card .verb { border: 1px solid var(--border); border-radius: 5px; padding: 1px 6px; color: var(--muted); }+ .card .calls { color: var(--accent-green); }+ .card .run { margin-top: 2px; display: flex; align-items: center; justify-content: space-between; }+ .card .run .go { font-size: 13px; font-weight: 600; color: var(--text); display: inline-flex; align-items: center; gap: 6px; }+ .card .run .go svg { width: 14px; height: 14px; transition: transform 0.15s; }+ .card:hover .run .go svg { transform: translateX(3px); }++ .card.sk-card { pointer-events: none; }+ .card.sk-card .l { height: 12px; border-radius: 5px; background: linear-gradient(90deg, var(--panel-2) 25%, var(--border) 50%, var(--panel-2) 75%); background-size: 200% 100%; animation: shimmer 1.3s infinite; }++ /* Empty / error states */+ .state { text-align: center; padding: 64px 24px; border: 1px dashed var(--border); border-radius: 16px; background: var(--panel); }+ .state .ic { width: 44px; height: 44px; margin: 0 auto 16px; color: var(--muted-2); }+ .state h3 { margin: 0 0 8px; font-size: 18px; letter-spacing: -0.01em; }+ .state p { margin: 0 auto 18px; color: var(--muted); font-size: 14px; max-width: 42ch; }++ /* Steps */+ .steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }+ @media (max-width: 740px) { .steps { grid-template-columns: 1fr; } }+ .step-card { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 22px; }.step-card .num {- display: inline-flex; width: 28px; height: 28px;- align-items: center; justify-content: center;- background: linear-gradient(135deg, #ffffff, #60a5fa); color: #0b0b0b;- border-radius: 8px; font-weight: 700; font-size: 13px;- margin-bottom: 14px;+ display: inline-flex; width: 28px; height: 28px; align-items: center; justify-content: center;+ background: linear-gradient(135deg, var(--text), var(--accent-blue)); color: var(--bg);+ border-radius: 8px; font-weight: 700; font-size: 13px; margin-bottom: 14px;}.step-card h3 { margin: 0 0 6px; font-size: 16px; letter-spacing: -0.01em; }.step-card p { margin: 0; color: var(--muted); font-size: 13px; line-height: 1.55; }/* Footer */- footer {- border-top: 1px solid var(--border);- padding: 32px 0 48px;- display: flex; align-items: center; justify-content: space-between;- font-size: 12px; color: var(--muted);- }+ footer { border-top: 1px solid var(--border); padding: 32px 0 48px; display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; font-size: 12px; color: var(--muted); }footer .left { display: flex; align-items: center; gap: 10px; }- footer .dot {- width: 18px; height: 18px;- background: conic-gradient(from 200deg, #ffffff, #60a5fa, #ffffff);- border-radius: 5px;- }+ footer .dot { width: 18px; height: 18px; background: conic-gradient(from 200deg, var(--text), var(--accent-blue), var(--text)); border-radius: 5px; }footer .right { display: flex; gap: 18px; }- footer .right a { color: var(--muted); }- footer .right a:hover { color: var(--text); }+ footer .right a { color: var(--muted); } footer .right a:hover { color: var(--text); }+ /* Toast */.toast {- position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);- background: var(--panel); border: 1px solid var(--border);- padding: 12px 18px; border-radius: 10px;- font-size: 13px;- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);- display: none;- }- .toast.show { display: block; }+ position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%) translateY(12px);+ background: var(--panel); border: 1px solid var(--border-strong); padding: 11px 18px; border-radius: 11px;+ font-size: 13px; box-shadow: var(--shadow); opacity: 0; pointer-events: none;+ transition: opacity 0.2s, transform 0.2s var(--ease); z-index: 90;+ }+ .toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }++ /* Command palette */+ .overlay {+ position: fixed; inset: 0; z-index: 80; background: var(--overlay);+ backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px);+ opacity: 0; pointer-events: none; transition: opacity 0.16s;+ }+ .overlay.show { opacity: 1; pointer-events: auto; }+ .palette {+ position: fixed; top: 12vh; left: 50%; transform: translateX(-50%) scale(0.98); z-index: 81;+ width: min(620px, calc(100vw - 32px)); background: var(--panel); border: 1px solid var(--border-strong);+ border-radius: 16px; box-shadow: var(--shadow); overflow: hidden;+ opacity: 0; pointer-events: none; transition: opacity 0.16s, transform 0.16s var(--ease);+ }+ .palette.show { opacity: 1; pointer-events: auto; transform: translateX(-50%) scale(1); }+ .palette .pi { display: flex; align-items: center; gap: 11px; padding: 15px 18px; border-bottom: 1px solid var(--border); }+ .palette .pi svg { width: 18px; height: 18px; color: var(--muted-2); }+ .palette .pi input { flex: 1; background: none; border: none; color: var(--text); font-size: 16px; font-family: inherit; outline: none; }+ .palette .pi input::placeholder { color: var(--muted-2); }+ .palette .plist { max-height: 52vh; overflow-y: auto; padding: 8px; }+ .palette .prow {+ display: flex; align-items: center; gap: 12px; padding: 11px 12px; border-radius: 10px; cursor: pointer;+ }+ .palette .prow[aria-selected="true"] { background: var(--panel-2); }+ .palette .prow .pcat { width: 30px; height: 30px; flex: 0 0 auto; border-radius: 8px; background: var(--bg-2); border: 1px solid var(--border); display: flex; align-items: center; justify-content: center; font-size: 14px; }+ .palette .prow .pmain { flex: 1; min-width: 0; }+ .palette .prow .pt { font-size: 14px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .palette .prow .pd { font-size: 12px; color: var(--muted-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .palette .prow .pp { font-family: var(--mono); font-size: 11.5px; color: var(--accent-green); flex: 0 0 auto; }+ .palette .pempty { padding: 32px; text-align: center; color: var(--muted-2); font-size: 14px; }+ .palette .pfoot { display: flex; gap: 16px; padding: 10px 16px; border-top: 1px solid var(--border); font-size: 11px; color: var(--muted-2); }+ .palette .pfoot kbd { font-family: var(--mono); background: var(--bg-2); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; margin-right: 4px; }++ /* Detail drawer */+ .drawer {+ position: fixed; top: 0; right: 0; bottom: 0; z-index: 81;+ width: min(560px, 100vw); background: var(--bg); border-left: 1px solid var(--border-strong);+ box-shadow: var(--shadow); transform: translateX(100%); transition: transform 0.26s var(--ease);+ display: flex; flex-direction: column; overflow: hidden;+ }+ .drawer.show { transform: none; }+ .drawer .dh { padding: 20px 24px; border-bottom: 1px solid var(--border); display: flex; align-items: flex-start; gap: 12px; }+ .drawer .dh .dmain { flex: 1; min-width: 0; }+ .drawer .dh .dcat { font-size: 10.5px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--accent-blue); margin-bottom: 6px; }+ .drawer .dh h3 { margin: 0 0 8px; font-size: 20px; letter-spacing: -0.02em; line-height: 1.2; }+ .drawer .dh .dmeta { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-family: var(--mono); font-size: 11.5px; color: var(--muted-2); }+ .drawer .dh .dmeta .price { color: var(--accent-green); font-weight: 600; }+ .drawer .dh .dmeta .verb { border: 1px solid var(--border); border-radius: 5px; padding: 1px 6px; color: var(--muted); }+ .drawer .dh .dmeta .path { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }+ .drawer .close { flex: 0 0 auto; width: 34px; height: 34px; border-radius: 9px; background: var(--panel); border: 1px solid var(--border); color: var(--muted); cursor: pointer; display: flex; align-items: center; justify-content: center; transition: color 0.12s, border-color 0.12s; }+ .drawer .close:hover { color: var(--text); border-color: var(--border-strong); }+ .drawer .db { flex: 1; overflow-y: auto; padding: 22px 24px; }+ .drawer .ddesc { color: var(--muted); font-size: 14px; line-height: 1.6; margin: 0 0 22px; }+ .drawer .lbl { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted-2); font-weight: 600; margin: 0 0 12px; display: flex; align-items: center; gap: 8px; }+ .field { margin-bottom: 14px; }+ .field label { display: block; font-size: 12.5px; font-weight: 600; margin-bottom: 6px; }+ .field label .req { color: var(--accent-amber); margin-left: 4px; }+ .field label .ty { font-family: var(--mono); font-size: 10.5px; color: var(--muted-2); font-weight: 400; margin-left: 6px; }+ .field .hint { font-size: 11.5px; color: var(--muted-2); margin: 5px 0 0; line-height: 1.45; }+ .field input, .field select, .field textarea {+ width: 100%; padding: 10px 12px; background: var(--panel); border: 1px solid var(--border); border-radius: 9px;+ color: var(--text); font-size: 13.5px; font-family: inherit; transition: border-color 0.12s;+ }+ .field textarea { font-family: var(--mono); font-size: 12.5px; min-height: 76px; resize: vertical; line-height: 1.5; }+ .field input:focus, .field select:focus, .field textarea:focus { outline: none; border-color: var(--accent-blue); }+ .field .noparams { color: var(--muted-2); font-size: 13px; }++ .tabs { display: flex; gap: 4px; margin-bottom: 10px; border-bottom: 1px solid var(--border); }+ .tabs button { background: none; border: none; color: var(--muted-2); font-family: inherit; font-size: 12.5px; font-weight: 600; padding: 8px 11px; cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px; transition: color 0.12s; }+ .tabs button:hover { color: var(--text); }+ .tabs button.active { color: var(--text); border-bottom-color: var(--accent-blue); }+ .codeblock { background: var(--code-bg); border: 1px solid var(--border); border-radius: 11px; padding: 14px 16px; font-family: var(--mono); font-size: 12px; line-height: 1.6; color: #c8ccd4; white-space: pre; overflow-x: auto; position: relative; }++ .result { margin-top: 16px; background: var(--panel-2); border: 1px solid var(--border); border-radius: 11px; padding: 14px 16px; font-size: 12.5px; display: none; }+ .result.show { display: block; animation: rise 0.3s var(--ease); }+ .result .rhead { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; font-family: var(--mono); font-size: 11.5px; }+ .result .ok { color: var(--accent-green); font-weight: 700; }+ .result .err { color: var(--danger); font-weight: 700; }+ .result .info { color: var(--muted); font-weight: 700; }+ .result .rmeta { color: var(--muted-2); }+ .result pre { margin: 0; font-family: var(--mono); font-size: 11.5px; line-height: 1.55; color: var(--text); white-space: pre-wrap; word-break: break-word; max-height: 260px; overflow: auto; }++ .drawer .df { padding: 16px 24px; border-top: 1px solid var(--border); background: var(--bg); }+ .run-btn {+ width: 100%; padding: 14px; background: var(--accent); color: var(--bg); border: none; border-radius: 11px;+ font-size: 14.5px; font-weight: 700; font-family: inherit; cursor: pointer;+ display: flex; align-items: center; justify-content: center; gap: 8px;+ transition: opacity 0.12s, transform 0.05s;+ }+ .run-btn:hover { opacity: 0.88; } .run-btn:active { transform: translateY(1px); }+ .run-btn:disabled { opacity: 0.5; cursor: default; }+ .run-btn .spin { width: 15px; height: 15px; border: 2px solid currentColor; border-top-color: transparent; border-radius: 50%; animation: rot 0.7s linear infinite; }+ @keyframes rot { to { transform: rotate(360deg); } }+ .df .note { font-size: 11px; color: var(--muted-2); text-align: center; margin: 9px 0 0; }++ @media (prefers-reduced-motion: reduce) {+ *, *::before, *::after { animation-duration: 0.001ms !important; transition-duration: 0.001ms !important; scroll-behavior: auto !important; }+ }</style></head><body>-<div class="wrap">- <nav>- <a class="brand" href="/x402">- <div class="dot"></div>- <span>x402</span>- </a>+<nav id="nav">+ <div class="navrow">+ <a class="brand" href="/x402"><div class="dot"></div><span>x402</span></a><div class="links">- <a href="#install">Install</a>- <a href="#demo">Demo</a>- <a href="/docs/x402" target="_blank" rel="noopener">Docs</a>- <a href="https://www.x402scan.com/server/17cbd874-52ac-4920-a020-b22ff2489a07" target="_blank" rel="noopener">Live activity ↗</a>+ <a class="hide-sm" href="#catalog">Catalog</a>+ <a class="hide-sm" href="#install">Install</a>+ <a class="hide-sm" href="/docs/x402" target="_blank" rel="noopener">Docs</a>+ <button class="icon-btn" id="paletteBtn" aria-label="Search endpoints">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>+ <span>Search</span><kbd>⌘K</kbd>+ </button>+ <button class="icon-btn" id="themeBtn" aria-label="Toggle theme" style="padding:0 10px;">+ <svg id="themeIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"></svg>+ </button></div>- </nav>+ </div>+</nav>+<div class="wrap"><section class="hero">- <h1>x402 payments,<br /><span class="grad">drop-in.</span></h1>+ <span class="eyebrow"><span class="led"></span><span id="eyebrowText">Live on Base & Solana mainnet</span></span>+ <h1>Pay-per-call APIs,<br /><span class="grad">one click away.</span></h1><p class="lede">- One <code style="background:var(--panel);padding:2px 6px;border-radius:4px;font-family:var(--mono);font-size:0.9em;"><script></code> tag. A clean modal. Stablecoin payments on Base and Solana, settled on-chain in seconds. No keys, no signup, no SDK to learn. Built on the <a href="https://x402.org" target="_blank" rel="noopener">x402 protocol</a>.+ A live catalog of endpoints an agent — or a human — can run and pay for on the spot, settled on-chain in USDC over the <a href="https://x402.org" target="_blank" rel="noopener">x402 protocol</a>. No keys, no signup, no SDK to learn. Inspect the schema, fill the inputs, click <code>Run</code>.</p><div class="cta-row">- <a class="btn" href="#install">Get the snippet</a>- <a class="btn ghost" href="#demo">Try a live payment</a>+ <a class="btn" href="#catalog">Browse the catalog</a>+ <a class="btn ghost" href="#install">Drop it into your site</a>+ </div>+ <div class="stats" id="stats" aria-label="Live 24-hour activity">+ <div class="stat"><div class="k">Endpoints</div><div class="v skeleton" data-stat="endpoints">—</div></div>+ <div class="stat"><div class="k">24h settled</div><div class="v skeleton" data-stat="settled">—</div></div>+ <div class="stat"><div class="k">24h volume</div><div class="v skeleton" data-stat="volume">—</div></div>+ <div class="stat"><div class="k">Success rate</div><div class="v skeleton" data-stat="success">—</div></div>+ <div class="stat"><div class="k">Unique payers</div><div class="v skeleton" data-stat="payers">—</div></div>+ </div>+ </section>++ <section id="catalog">+ <div class="sec-head">+ <div>+ <h2><span class="num">01</span>The catalog</h2>+ <p class="sub">Every endpoint below is live. Click one to inspect its schema and run it with a real on-chain payment.</p>+ </div>+ <button class="icon-btn" id="paletteBtn2" style="height:42px;padding:0 16px;">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>+ <span>Quick search</span><kbd>⌘K</kbd>+ </button></div>- <div class="networks">- <span>Settles on</span>- <span class="pill"><span class="led"></span>Base mainnet · USDC</span>- <span class="pill"><span class="led"></span>Solana mainnet · USDC</span>++ <div class="toolbar">+ <div class="search">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>+ <input id="searchInput" type="search" placeholder="Search endpoints…" aria-label="Search endpoints" autocomplete="off" />+ <span class="slash">/</span>+ </div>+ <select class="select" id="sortSelect" aria-label="Sort endpoints">+ <option value="popular">Most used</option>+ <option value="price-asc">Price: low to high</option>+ <option value="price-desc">Price: high to low</option>+ <option value="name">Name A–Z</option>+ </select></div>+ <div class="chips" id="chips" role="tablist" aria-label="Filter by category"></div>+ <div class="count-line" id="countLine" aria-live="polite"></div>+ <div class="grid" id="grid"></div></section>- <section id="install">- <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>+ <section id="install" class="alt">+ <div class="sec-head"><div>+ <h2><span class="num">02</span>Install</h2>+ <p class="sub">Paste one line into your <code><head></code>. Add <code>data-x402-endpoint</code> to any button. The modal handles the wallet, the 402 challenge, and settlement.</p>+ </div></div><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://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="c"><!-- 2. Any button becomes a paid call --></span><span class="k"><button</span><span class="a">data-x402-endpoint</span>=<span class="s">"https://three.ws/api/x402/symbol-availability?ticker=AGENT"</span><span class="a">data-x402-merchant</span>=<span class="s">"three.ws"</span>@@ -292,224 +482,518 @@<span class="k"></button></span></span></div></section>- <section id="how" class="alt">- <h2><span class="num">02</span>How it works</h2>- <p class="sub">x402 is HTTP 402 Payment Required, with a manifest. The drop-in handles the entire dance — you never see it.</p>+ <section id="how">+ <div class="sec-head"><div>+ <h2><span class="num">03</span>How it works</h2>+ <p class="sub">x402 is HTTP 402 Payment Required, with a manifest. The drop-in handles the entire dance — you never see it.</p>+ </div></div><div class="steps">- <div class="step-card">- <div class="num">1</div>- <h3>Buyer clicks</h3>- <p>The modal opens. We probe your endpoint, parse the 402 challenge, and show the price + network.</p>- </div>- <div class="step-card">- <div class="num">2</div>- <h3>Wallet signs</h3>- <p>Phantom for Solana, MetaMask/Coinbase for Base. We build the SPL transfer or EIP-3009 authorization. One click.</p>- </div>- <div class="step-card">- <div class="num">3</div>- <h3>Facilitator settles</h3>- <p>PayAI or Coinbase CDP verifies and broadcasts the tx on-chain. Your endpoint runs and returns the result.</p>- </div>- </div>- </section>-- <section id="demo">- <h2><span class="num">03</span>Try it live</h2>- <p class="sub">These are real paid endpoints. Pay $0.001 USDC with Phantom or your browser wallet and see the response stream back.</p>- <div class="sku-grid">-- <div class="sku-card">- <div class="head">- <div class="title">Symbol availability</div>- <div class="price">$0.001</div>- </div>- <div class="desc">Check if a token ticker is already trading across Solana and Base. Returns exact matches, fuzzy lookalikes, and a register/skip recommendation.</div>- <div class="net">Base · Solana</div>- <button class="buy"- data-x402-endpoint="/api/x402/symbol-availability?ticker=AGENT&network=mainnet"- data-x402-merchant="three.ws"- data-x402-action="Check ticker · AGENT"- data-result-target="r-symbol">- Buy & run · check AGENT- </button>- <div class="result-panel" id="r-symbol"></div>- </div>-- <div class="sku-card">- <div class="head">- <div class="title">Agent reputation</div>- <div class="price">$0.001</div>- </div>- <div class="desc">Pull a multi-source reputation report for any on-chain agent: posting cadence, follower deltas, on-chain activity, x402 settlement stats.</div>- <div class="net">Base · Solana</div>- <button class="buy"- data-x402-endpoint="/api/x402/agent-reputation?address=THREEsynthetic1111111111111111111111111PayTo&chain=solana"- data-x402-merchant="three.ws"- data-x402-action="Reputation report"- data-result-target="r-rep">- Buy & run · THREEsyn…PayTo- </button>- <div class="result-panel" id="r-rep"></div>- </div>-- <div class="sku-card">- <div class="head">- <div class="title">Pump.fun agent audit</div>- <div class="price">$0.001</div>- </div>- <div class="desc">Forensic on-chain audit of a Pump.fun launch — supply curves, holder concentration, dev-wallet history, and risk flags.</div>- <div class="net">Base · Solana</div>- <button class="buy"- data-x402-endpoint="/api/x402/pump-agent-audit?mint=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"- data-x402-merchant="three.ws"- data-x402-action="Pump.fun audit · $THREE"- data-result-target="r-pump">- Buy & run · audit $THREE- </button>- <div class="result-panel" id="r-pump"></div>- </div>-- <div class="sku-card">- <div class="head">- <div class="title">Onchain identity verify</div>- <div class="price">$0.001</div>- </div>- <div class="desc">Verify an address claim against ENS, SNS, ERC-8004 attestations, and Solana SAS credentials. Returns linked identities + provenance.</div>- <div class="net">Base · Solana</div>- <button class="buy"- data-x402-endpoint="/api/x402/onchain-identity-verify?address=vitalik.eth"- data-x402-merchant="three.ws"- data-x402-action="Verify identity · vitalik.eth"- data-result-target="r-id">- Buy & run · verify vitalik.eth- </button>- <div class="result-panel" id="r-id"></div>- </div>-+ <div class="step-card"><div class="num">1</div><h3>Buyer clicks</h3><p>The modal opens, probes your endpoint, parses the 402 challenge, and shows the exact price and network.</p></div>+ <div class="step-card"><div class="num">2</div><h3>Wallet signs</h3><p>Phantom for Solana, MetaMask or Coinbase for Base. We build the SPL transfer or EIP-3009 authorization. One click.</p></div>+ <div class="step-card"><div class="num">3</div><h3>Facilitator settles</h3><p>PayAI or Coinbase CDP verifies and broadcasts on-chain. Your endpoint runs and streams the result back.</p></div></div></section>- <section id="siwx">- <h2><span class="num">04</span>Sign in with wallet (re-entry)</h2>- <p class="sub">- For re-downloadable content — GLBs, avatars, agent skills, lobby- characters — buyers shouldn't pay again every time they fetch the same- asset. When an endpoint opts into <a href="https://github.com/x402/x402/blob/main/typescript/site/CHANGELOG-v2.md" target="_blank" rel="noopener">SIWX (Sign-In-With-X, CAIP-122)</a>,- the modal grows a second option:- </p>- <pre style="background:var(--panel);border:1px solid var(--border);border-radius:10px;padding:14px 16px;font-family:var(--mono);font-size:12px;color:var(--text);line-height:1.5;overflow:auto;"><code>┌──────────────────────────────────────────┐-│ three.ws ✕ │-│ Download pole-dancer-rumba.glb │-├──────────────────────────────────────────┤-│ 0.05 USDC [Base · live ●] │-├──────────────────────────────────────────┤-│ ┌────────────────────────────────────┐ │-│ │ Sign in with wallet │ │ ← primary-│ └────────────────────────────────────┘ │-│ ┌────────────────────────────────────┐ │-│ │ Pay 0.05 USDC instead │ │ ← secondary-│ └────────────────────────────────────┘ │-│ Already paid for this once? Sign in to │-│ re-enter without paying again. │-└──────────────────────────────────────────┘</code></pre>- <p class="sub" style="margin-top:18px;">- Click <strong>Sign in with wallet</strong> → wallet pops with a CAIP-122- message naming the resource, the connected address, and a fresh nonce →- modal posts the signed payload as a <code style="font-family:var(--mono);">SIGN-IN-WITH-X</code>- header → endpoint looks the wallet up in its payment ledger → returns- 200 without charging. If the wallet hasn't actually paid for this- resource (or the signature is rejected), the modal falls back to the- normal pay flow with a one-line notice.- </p>- <p class="sub" style="margin-top:8px;">- Programmatic callers see the same flow: <code style="font-family:var(--mono);">await window.X402.pay(...)</code>- resolves with <code style="font-family:var(--mono);">{ result, siwx: { address, network } }</code>- (instead of <code style="font-family:var(--mono);">payment</code>) when SIWX was used. The element-bound API also- dispatches an <code style="font-family:var(--mono);">x402:siwx-signed</code> event right before- <code style="font-family:var(--mono);">x402:result</code> so analytics can distinguish a sign-in from a paid- call. A manual test surface lives at <a href="/siwx-test.html">/siwx-test.html</a>.- </p>- </section>-<section id="programmatic" class="alt">- <h2><span class="num">05</span>Or call it programmatically</h2>- <p class="sub">Same modal, called from JavaScript. The promise resolves with the API result and a settlement receipt.</p>+ <div class="sec-head"><div>+ <h2><span class="num">04</span>Or call it from code</h2>+ <p class="sub">Same settlement, driven from JavaScript. The promise resolves with your endpoint's JSON and a settlement receipt.</p>+ </div></div><div class="snippet" id="progSnippet"><button class="copy-btn" data-copy="progSnippetCode">Copy</button><span id="progSnippetCode"><span class="k">const</span> { result, payment } = <span class="k">await</span> window.X402.<span class="a">pay</span>({<span class="a">endpoint</span>: <span class="s">'/api/x402/symbol-availability'</span>,+ <span class="a">method</span>: <span class="s">'GET'</span>,<span class="a">body</span>: { <span class="a">ticker</span>: <span class="s">'AGENT'</span> },<span class="a">merchant</span>: <span class="s">'Acme'</span>,- <span class="a">action</span>: <span class="s">'Check ticker'</span>,});<span class="c">// payment.transaction → on-chain tx hash</span><span class="c">// payment.payer → buyer wallet</span><span class="c">// result → your endpoint's JSON response</span></span></div>+ <p class="sub" style="margin-top:18px;">+ Agents pay autonomously with <a href="https://www.npmjs.com/package/@x402/fetch" target="_blank" rel="noopener">@x402/fetch</a> or the <a href="/docs/mcp" target="_blank" rel="noopener">MCP transport</a> — no wallet UI, no API key. Re-downloadable goods support <a href="/siwx-test.html">Sign-In-With-Wallet</a> re-entry so buyers never pay twice for the same asset.+ </p></section><footer>- <div class="left">- <div class="dot"></div>- <span>x402 · operated by three.ws</span>- </div>+ <div class="left"><div class="dot"></div><span>x402 · operated by three.ws</span></div><div class="right"><a href="/docs/x402" target="_blank" rel="noopener">Docs</a>+ <a href="/openapi.json" target="_blank" rel="noopener">OpenAPI</a><a href="https://x402.org" target="_blank" rel="noopener">Protocol ↗</a>- <a href="https://www.x402scan.com" target="_blank" rel="noopener">x402scan ↗</a>+ <a href="https://www.x402scan.com/server/17cbd874-52ac-4920-a020-b22ff2489a07" target="_blank" rel="noopener">Live activity ↗</a></div></footer></div>+<!-- Command palette -->+<div class="overlay" id="paletteOverlay"></div>+<div class="palette" id="palette" role="dialog" aria-modal="true" aria-label="Search endpoints">+ <div class="pi">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>+ <input id="paletteInput" type="text" placeholder="Search endpoints by name, category, or path…" aria-label="Search endpoints" autocomplete="off" />+ </div>+ <div class="plist" id="paletteList" role="listbox"></div>+ <div class="pfoot"><span><kbd>↑</kbd><kbd>↓</kbd> navigate</span><span><kbd>↵</kbd> open</span><span><kbd>esc</kbd> close</span></div>+</div>++<!-- Detail drawer -->+<div class="overlay" id="drawerOverlay"></div>+<aside class="drawer" id="drawer" role="dialog" aria-modal="true" aria-labelledby="drawerTitle"></aside>+<div class="toast" id="toast">copied</div><script type="module" src="/x402.js"></script>-<script>- // Copy buttons- document.querySelectorAll('.copy-btn').forEach((btn) => {- btn.addEventListener('click', async () => {- const id = btn.dataset.copy;- const el = document.getElementById(id);- if (!el) return;- try {- await navigator.clipboard.writeText(el.textContent || '');- btn.classList.add('copied');- btn.textContent = '✓ Copied';- const toast = document.getElementById('toast');- toast.classList.add('show');- setTimeout(() => toast.classList.remove('show'), 1600);- setTimeout(() => {- btn.classList.remove('copied');- btn.textContent = 'Copy';- }, 1800);- } catch (e) {- btn.textContent = 'copy failed';+<script type="module">+(function () {+ 'use strict';+ const $ = (s, r = document) => r.querySelector(s);+ const $$ = (s, r = document) => Array.from(r.querySelectorAll(s));+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+ const fmtUsd = (n) => {+ if (n == null) return 'Free';+ if (n === 0) return 'Free';+ if (n < 0.01) return '$' + n.toFixed(3).replace(/0+$/, '').replace(/\.$/, '');+ if (n < 1) return '$' + n.toFixed(n * 100 % 1 === 0 ? 2 : 3);+ return '$' + n.toFixed(2);+ };+ const fmtNum = (n) => n == null ? '—' : n >= 1000 ? (n / 1000).toFixed(n >= 10000 ? 0 : 1) + 'k' : String(n);++ // ── Category classification (derived from path + copy) ─────────────────+ const CATS = [+ { key: 'Crypto', icon: '◎', test: /pump|token|mint|vanity|symbol|intel|crypto|cross-chain|three-intel|reputation|bouncer|identity|did/i },+ { key: '3D', icon: '◈', test: /mesh|forge|model|avatar|animation|cosmetic|club|dance|glb/i },+ { key: 'AI', icon: '✦', test: /fact-check|tutor|vision|insight|revenue-vision/i },+ { key: 'Discovery', icon: '⌘', test: /marketplace|bazaar|catalog|skill/i },+ ];+ const categorize = (path, ...text) => {+ const hay = (path + ' ' + text.join(' ')).toLowerCase();+ for (const c of CATS) if (c.test.test(hay)) return c.key;+ return 'Utility';+ };+ const catIcon = (key) => (CATS.find((c) => c.key === key) || {}).icon || '⚡';++ // ── Schema field extraction ────────────────────────────────────────────+ function schemaInfo(s) {+ s = s || {};+ return {+ type: s.type || 'string',+ enum: Array.isArray(s.enum) ? s.enum : null,+ default: s.default != null ? s.default : null,+ example: s.example != null ? s.example : null,+ min: s.minLength != null ? s.minLength : (s.minimum != null ? s.minimum : null),+ max: s.maxLength != null ? s.maxLength : (s.maximum != null ? s.maximum : null),+ desc: s.description || '',+ itemsType: s.items && s.items.type ? s.items.type : null,+ };+ }+ const cleanTitle = (s, path) => (s || path || '')+ .replace(/^paid:\s*/i, '')+ .replace(/^x402[_\s-]*/i, '')+ .replace(/\s*\(returns[^)]*\)/i, '')+ .trim() || path;++ let CATALOG = [];+ let STATS = null;+ const state = { q: '', cat: 'All', sort: 'popular' };++ // ── Fetch catalog from the free OpenAPI discovery doc ──────────────────+ async function loadCatalog() {+ const doc = await fetch('/openapi.json', { headers: { accept: 'application/json' } }).then((r) => {+ if (!r.ok) throw new Error('openapi ' + r.status);+ return r.json();+ });+ const paths = doc.paths || {};+ const items = [];+ for (const [path, ops] of Object.entries(paths)) {+ if (!/^\/api\/(x402|insights)\//.test(path)) continue;+ for (const [verb, op] of Object.entries(ops)) {+ if (!['get', 'post'].includes(verb) || !op || typeof op !== 'object') continue;+ const pay = op['x-payment-info'];+ const amt = pay && pay.price && pay.price.amount != null ? Number(pay.price.amount) : null;+ const params = Array.isArray(op.parameters)+ ? op.parameters.filter((p) => p.in === 'query').map((p) => ({ name: p.name, required: !!p.required, ...schemaInfo(p.schema) }))+ : [];+ const bodySchema = op.requestBody && op.requestBody.content && op.requestBody.content['application/json'] && op.requestBody.content['application/json'].schema;+ const req = new Set((bodySchema && bodySchema.required) || []);+ const bodyProps = bodySchema && bodySchema.properties+ ? Object.entries(bodySchema.properties).map(([name, s]) => ({ name, required: req.has(name), ...schemaInfo(s) }))+ : [];+ const title = cleanTitle(op.summary, path);+ const desc = op.description || op.summary || '';+ items.push({+ id: op.operationId || (path + ':' + verb),+ path, method: verb.toUpperCase(), title, desc,+ priceUsd: amt, params, bodyProps,+ category: categorize(path, op.summary, op.description),+ });}+ }+ // de-dupe by path (prefer the paid/GET representation), keep stable+ const seen = new Map();+ for (const it of items) { if (!seen.has(it.path)) seen.set(it.path, it); }+ return Array.from(seen.values());+ }++ async function loadStats() {+ try {+ const r = await fetch('/api/x402-revenue?view=stats&period=24h', { headers: { accept: 'application/json' } });+ if (!r.ok) return null;+ return await r.json();+ } catch (e) { return null; }+ }++ function callsFor(path) {+ if (!STATS || !Array.isArray(STATS.by_endpoint)) return 0;+ const row = STATS.by_endpoint.find((e) => e.route === path);+ return row ? row.count : 0;+ }++ // ── Stats bar ──────────────────────────────────────────────────────────+ function renderStats() {+ const set = (k, v) => { const el = $(`[data-stat="${k}"]`); if (el) { el.classList.remove('skeleton'); el.innerHTML = v; } };+ set('endpoints', String(CATALOG.length));+ if (STATS) {+ set('settled', fmtNum(STATS.settled_count));+ set('volume', '$' + Number(STATS.gross_usd || 0).toFixed(STATS.gross_usd < 100 ? 2 : 0));+ set('success', STATS.success_rate != null ? Math.round(STATS.success_rate * 100) + '<small>%</small>' : '—');+ set('payers', fmtNum(STATS.unique_payers));+ } else {+ ['settled', 'volume', 'success', 'payers'].forEach((k) => set(k, '<small style="font-size:15px">—</small>'));+ $('#eyebrowText').textContent = 'Live on Base & Solana mainnet';+ }+ }++ // ── Category chips ───────────────────────────────────────────────────────+ function renderChips() {+ const counts = { All: CATALOG.length };+ CATALOG.forEach((c) => { counts[c.category] = (counts[c.category] || 0) + 1; });+ const cats = ['All', ...CATS.map((c) => c.key).filter((k) => counts[k]), ...(counts.Utility ? ['Utility'] : [])];+ const uniq = [...new Set(cats)];+ $('#chips').innerHTML = uniq.map((k) =>+ `<button class="chip ${state.cat === k ? 'active' : ''}" role="tab" aria-selected="${state.cat === k}" data-cat="${esc(k)}">${k === 'All' ? 'All' : catIcon(k) + ' ' + esc(k)} <span class="n">${counts[k] || 0}</span></button>`+ ).join('');+ $$('#chips .chip').forEach((el) => el.addEventListener('click', () => { state.cat = el.dataset.cat; renderChips(); renderGrid(); }));+ }++ // ── Filtering + sorting ──────────────────────────────────────────────────+ function filtered() {+ let list = CATALOG.slice();+ if (state.cat !== 'All') list = list.filter((c) => c.category === state.cat);+ if (state.q) {+ const q = state.q.toLowerCase();+ list = list.filter((c) => (c.title + ' ' + c.desc + ' ' + c.path + ' ' + c.category).toLowerCase().includes(q));+ }+ const price = (c) => c.priceUsd == null ? -1 : c.priceUsd;+ if (state.sort === 'price-asc') list.sort((a, b) => price(a) - price(b));+ else if (state.sort === 'price-desc') list.sort((a, b) => price(b) - price(a));+ else if (state.sort === 'name') list.sort((a, b) => a.title.localeCompare(b.title));+ else list.sort((a, b) => callsFor(b.path) - callsFor(a.path) || a.title.localeCompare(b.title));+ return list;+ }++ // ── Card grid ────────────────────────────────────────────────────────────+ function renderGrid() {+ const grid = $('#grid');+ const list = filtered();+ $('#countLine').textContent = `${list.length} of ${CATALOG.length} endpoint${CATALOG.length === 1 ? '' : 's'}${state.cat !== 'All' ? ' · ' + state.cat : ''}${state.q ? ` · “${state.q}”` : ''}`;+ if (!list.length) {+ grid.style.display = 'block';+ grid.innerHTML = `<div class="state"><svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg><h3>No endpoints match</h3><p>Nothing lines up with your search or filter. Try a broader term.</p><button class="btn ghost" id="clearBtn">Clear filters</button></div>`;+ const cb = $('#clearBtn'); if (cb) cb.addEventListener('click', () => { state.q = ''; state.cat = 'All'; $('#searchInput').value = ''; renderChips(); renderGrid(); });+ return;+ }+ grid.style.display = 'grid';+ grid.innerHTML = list.map((c, i) => {+ const calls = callsFor(c.path);+ return `<button class="card" data-id="${esc(c.id)}" style="animation-delay:${Math.min(i * 22, 300)}ms" aria-label="${esc(c.title)} — ${fmtUsd(c.priceUsd)}">+ <div class="top"><span class="cat">${catIcon(c.category)} ${esc(c.category)}</span><span class="price ${c.priceUsd == null ? 'free' : ''}">${fmtUsd(c.priceUsd)}</span></div>+ <div class="title">${esc(c.title)}</div>+ <div class="desc">${esc(c.desc)}</div>+ <div class="meta"><span class="verb">${c.method}</span><span>USDC · Base · Solana</span>${calls ? `<span class="calls">${fmtNum(calls)} calls/24h</span>` : ''}</div>+ <div class="run"><span class="go">Inspect & run <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M5 12h14M13 6l6 6-6 6"/></svg></span></div>+ </button>`;+ }).join('');+ $$('#grid .card').forEach((el) => el.addEventListener('click', () => openDrawer(el.dataset.id)));+ }++ function skeletonGrid() {+ $('#grid').innerHTML = Array.from({ length: 8 }).map(() =>+ `<div class="card sk-card"><div class="top"><div class="l" style="width:60px"></div><div class="l" style="width:44px"></div></div><div class="l" style="width:70%;height:16px"></div><div class="l" style="width:100%"></div><div class="l" style="width:90%"></div><div class="l" style="width:40%"></div></div>`+ ).join('');+ }++ function catalogError() {+ $('#grid').style.display = 'block';+ $('#grid').innerHTML = `<div class="state"><svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/></svg><h3>Couldn't load the catalog</h3><p>The discovery endpoint didn't respond. This works on the live site; check your connection and retry.</p><button class="btn" id="retryBtn">Retry</button></div>`;+ $('#retryBtn').addEventListener('click', boot);+ }++ // ── Detail drawer ────────────────────────────────────────────────────────+ let lastFocus = null;+ let drawerTab = 'try';++ function fieldHtml(f) {+ const id = 'f_' + f.name;+ const ty = `${f.type}${f.itemsType ? '[' + f.itemsType + ']' : ''}`;+ const req = f.required ? '<span class="req" title="required">*</span>' : '';+ const hint = f.desc || (f.enum ? 'one of: ' + f.enum.join(', ') : '') || (f.max ? `max ${f.max} chars` : '');+ let control;+ if (f.enum) {+ control = `<select id="${id}" data-name="${esc(f.name)}" data-ty="${esc(f.type)}">${(!f.required ? '<option value="">—</option>' : '') + f.enum.map((o) => `<option value="${esc(o)}" ${String(f.default) === String(o) ? 'selected' : ''}>${esc(o)}</option>`).join('')}</select>`;+ } else if (f.type === 'array') {+ control = `<input id="${id}" data-name="${esc(f.name)}" data-ty="array" placeholder="comma-separated values" value="${esc(f.default || '')}" />`;+ } else {+ const val = f.default != null ? f.default : (f.example != null ? f.example : '');+ control = `<input id="${id}" data-name="${esc(f.name)}" data-ty="${esc(f.type)}" placeholder="${esc(f.type === 'string' ? f.name : f.type)}" value="${esc(val)}" ${f.max ? `maxlength="${f.max}"` : ''} />`;+ }+ return `<div class="field"><label for="${id}">${esc(f.name)}${req}<span class="ty">${esc(ty)}</span></label>${control}${hint ? `<p class="hint">${esc(hint)}</p>` : ''}</div>`;+ }++ function codeFor(item, lang) {+ const url = 'https://three.ws' + item.path;+ const fields = item.method === 'GET' ? item.params : item.bodyProps;+ const sample = {};+ fields.forEach((f) => { if (f.required || f.default != null) sample[f.name] = f.default != null ? f.default : (f.example != null ? f.example : (f.enum ? f.enum[0] : (f.type === 'string' ? '…' : 0))); });+ if (lang === 'js') {+ return `// Loaded via <script src="https://three.ws/x402.js">\nconst { result, payment } = await window.X402.pay({\n endpoint: '${item.path}',\n method: '${item.method}',${item.method === 'POST' ? `\n body: ${JSON.stringify(sample, null, 2).split('\n').join('\n ')},` : Object.keys(sample).length ? `\n // query: ${esc(new URLSearchParams(sample).toString())}` : ''}\n});\nconsole.log(result, payment.transaction);`;+ }+ if (lang === 'curl') {+ const q = item.method === 'GET' && Object.keys(sample).length ? '?' + new URLSearchParams(sample).toString() : '';+ return `# Returns HTTP 402 with the payment challenge; pay with any x402 client.\ncurl -sS "${url}${q}"${item.method === 'POST' ? ` \\\n -H 'content-type: application/json' \\\n -d '${JSON.stringify(sample)}'` : ''}`;+ }+ // python+ return `# pip install x402 httpx\nfrom x402.clients.httpx import x402_payment_hooks\nimport httpx, os\n\nclient = httpx.Client(event_hooks=x402_payment_hooks(private_key=os.environ["WALLET_KEY"]))\nr = client.${item.method.toLowerCase()}("${url}"${item.method === 'POST' ? `, json=${JSON.stringify(sample)}` : Object.keys(sample).length ? `, params=${JSON.stringify(sample)}` : ''})\nprint(r.json())`;+ }++ function renderCode(item) {+ $('#codeOut').textContent = codeFor(item, drawerTab === 'try' ? 'js' : drawerTab);+ }++ function openDrawer(id) {+ const item = CATALOG.find((c) => c.id === id);+ if (!item) return;+ lastFocus = document.activeElement;+ drawerTab = 'try';+ const fields = item.method === 'GET' ? item.params : item.bodyProps;+ const d = $('#drawer');+ d.innerHTML = `+ <div class="dh">+ <div class="dmain">+ <div class="dcat">${catIcon(item.category)} ${esc(item.category)}</div>+ <h3 id="drawerTitle">${esc(item.title)}</h3>+ <div class="dmeta"><span class="price">${fmtUsd(item.priceUsd)}</span><span class="verb">${item.method}</span><span class="path">${esc(item.path)}</span></div>+ </div>+ <button class="close" id="drawerClose" aria-label="Close">+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6 6 18M6 6l12 12"/></svg>+ </button>+ </div>+ <div class="db">+ <p class="ddesc">${esc(item.desc)}</p>+ <p class="lbl">Request${fields.length ? '' : ' · no parameters'}</p>+ <div id="formWrap">${fields.length ? fields.map(fieldHtml).join('') : '<p class="field noparams">This endpoint takes no input — just run it.</p>'}</div>+ <p class="lbl" style="margin-top:22px;">Integrate</p>+ <div class="tabs" id="codeTabs">+ <button data-tab="try" class="active">JavaScript</button>+ <button data-tab="curl">cURL</button>+ <button data-tab="python">Python</button>+ </div>+ <div class="codeblock"><button class="copy-btn" id="codeCopy">Copy</button><span id="codeOut"></span></div>+ <div class="result" id="drawerResult"></div>+ </div>+ <div class="df">+ <button class="run-btn" id="runBtn"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M5 3l14 9-14 9V3z"/></svg> Pay ${fmtUsd(item.priceUsd)} & run</button>+ <p class="note">Real on-chain USDC · exact network shown at checkout · nothing charged until you approve</p>+ </div>`;+ renderCode(item);+ $('#drawerClose').addEventListener('click', closeDrawer);+ $$('#codeTabs button').forEach((b) => b.addEventListener('click', () => {+ $$('#codeTabs button').forEach((x) => x.classList.remove('active'));+ b.classList.add('active');+ drawerTab = b.dataset.tab === 'try' ? 'try' : b.dataset.tab;+ renderCode(item);+ }));+ $('#codeCopy').addEventListener('click', () => copyText($('#codeOut').textContent, $('#codeCopy')));+ $('#runBtn').addEventListener('click', () => runEndpoint(item));+ $('#drawerOverlay').classList.add('show');+ d.classList.add('show');+ document.body.style.overflow = 'hidden';+ const first = d.querySelector('input, select, textarea, button.run-btn');+ if (first) setTimeout(() => first.focus(), 260);+ try { history.replaceState(null, '', '#run=' + encodeURIComponent(item.path)); } catch (e) {}+ }++ function closeDrawer() {+ $('#drawer').classList.remove('show');+ $('#drawerOverlay').classList.remove('show');+ document.body.style.overflow = '';+ if (lastFocus && lastFocus.focus) lastFocus.focus();+ try { history.replaceState(null, '', location.pathname + location.search); } catch (e) {}+ }++ function collectValues(item) {+ const fields = item.method === 'GET' ? item.params : item.bodyProps;+ const values = {};+ fields.forEach((f) => {+ const el = $('#f_' + f.name); if (!el) return;+ let v = el.value; if (v === '' || v == null) return;+ if (f.type === 'array') v = String(v).split(',').map((x) => x.trim()).filter(Boolean);+ else if (f.type === 'integer' || f.type === 'number') { const n = Number(v); if (!Number.isNaN(n)) v = n; }+ else if (f.type === 'boolean') v = v === 'true' || v === true;+ values[f.name] = v;});- });-- // Wire result callbacks on every demo button- document.querySelectorAll('[data-result-target]').forEach((btn) => {- const targetId = btn.dataset.resultTarget;- const panel = document.getElementById(targetId);- btn.addEventListener('x402:result', (e) => {- const { result, payment } = e.detail;- const explorer = payment?.transaction- ? (payment.network?.startsWith('solana') ? `https://solscan.io/tx/${payment.transaction}` : `https://basescan.org/tx/${payment.transaction}`)- : null;- panel.innerHTML = `<span class="ok">✓ Paid</span> · network=${payment?.network || '?'} · ${explorer ? `<a href="${explorer}" target="_blank" rel="noopener">tx ↗</a>` : ''}\n\n${escapeHtml(JSON.stringify(result, null, 2).slice(0, 2400))}`;- panel.classList.add('show');+ return values;+ }++ async function runEndpoint(item) {+ if (!window.X402 || typeof window.X402.pay !== 'function') {+ showResult('info', 'Payment layer still loading — try again in a moment.', null);+ return;+ }+ const values = collectValues(item);+ let endpoint = item.path, body;+ if (item.method === 'GET') {+ const qs = new URLSearchParams();+ Object.entries(values).forEach(([k, v]) => qs.set(k, Array.isArray(v) ? v.join(',') : v));+ const s = qs.toString(); if (s) endpoint += '?' + s;+ } else if (Object.keys(values).length) { body = values; }+ const btn = $('#runBtn'); const orig = btn.innerHTML;+ btn.disabled = true; btn.innerHTML = '<span class="spin"></span> Awaiting payment…';+ const t0 = performance.now();+ try {+ const out = await window.X402.pay({ endpoint, method: item.method, body, merchant: 'three.ws', action: item.title });+ const ms = Math.round(performance.now() - t0);+ const p = out.payment || {};+ const net = p.network || (out.siwx && out.siwx.network) || '?';+ const tx = p.transaction;+ const exp = tx ? (String(net).startsWith('solana') ? 'https://solscan.io/tx/' + tx : 'https://basescan.org/tx/' + tx) : null;+ const head = out.siwx+ ? `<span class="ok">✓ Re-entered</span><span class="rmeta">signed in with wallet · ${esc(net)} · ${ms}ms</span>`+ : `<span class="ok">✓ Paid & ran</span><span class="rmeta">${esc(net)}${p.amount_usd != null ? ' · $' + p.amount_usd : ''} · ${ms}ms${exp ? ` · <a href="${exp}" target="_blank" rel="noopener">tx ↗</a>` : ''}</span>`;+ showResultHtml(head, JSON.stringify(out.result, null, 2));+ } catch (e) {+ if (e && e.code === 'cancelled') showResult('info', 'Payment cancelled — no funds moved.', null);+ else showResult('err', (e && e.message) || 'Something went wrong.', null);+ } finally { btn.disabled = false; btn.innerHTML = orig; }+ }++ function showResult(kind, msg, body) {+ const cls = kind === 'err' ? 'err' : kind === 'info' ? 'info' : 'ok';+ const sym = kind === 'err' ? '✗' : kind === 'info' ? '•' : '✓';+ showResultHtml(`<span class="${cls}">${sym} ${esc(msg)}</span>`, body);+ }+ function showResultHtml(headHtml, bodyText) {+ const r = $('#drawerResult');+ r.innerHTML = `<div class="rhead">${headHtml}</div>${bodyText ? `<pre>${esc(String(bodyText).slice(0, 4000))}</pre>` : ''}`;+ r.classList.add('show');+ r.scrollIntoView({ behavior: 'smooth', block: 'nearest' });+ }++ // ── Command palette ──────────────────────────────────────────────────────+ let palIdx = 0, palResults = [];+ function openPalette() {+ $('#paletteOverlay').classList.add('show');+ $('#palette').classList.add('show');+ $('#paletteInput').value = '';+ palPaint('');+ setTimeout(() => $('#paletteInput').focus(), 60);+ }+ function closePalette() {+ $('#paletteOverlay').classList.remove('show');+ $('#palette').classList.remove('show');+ }+ function palPaint(q) {+ q = q.toLowerCase();+ palResults = (q ? CATALOG.filter((c) => (c.title + ' ' + c.desc + ' ' + c.path + ' ' + c.category).toLowerCase().includes(q)) : CATALOG.slice())+ .sort((a, b) => callsFor(b.path) - callsFor(a.path)).slice(0, 40);+ palIdx = 0;+ const list = $('#paletteList');+ if (!palResults.length) { list.innerHTML = '<div class="pempty">No endpoints found</div>'; return; }+ list.innerHTML = palResults.map((c, i) =>+ `<div class="prow" role="option" data-i="${i}" aria-selected="${i === 0}"><div class="pcat">${catIcon(c.category)}</div><div class="pmain"><div class="pt">${esc(c.title)}</div><div class="pd">${esc(c.path)}</div></div><div class="pp">${fmtUsd(c.priceUsd)}</div></div>`+ ).join('');+ $$('#paletteList .prow').forEach((el) => {+ el.addEventListener('click', () => { closePalette(); openDrawer(palResults[+el.dataset.i].id); });+ el.addEventListener('mousemove', () => { palIdx = +el.dataset.i; palHi(); });});- btn.addEventListener('x402:error', (e) => {- panel.innerHTML = `<span class="err">✗ Error</span> · ${escapeHtml(e.detail?.error || 'unknown')}`;- panel.classList.add('show');+ }+ function palHi() {+ $$('#paletteList .prow').forEach((el, i) => el.setAttribute('aria-selected', i === palIdx));+ const cur = $(`#paletteList .prow[data-i="${palIdx}"]`);+ if (cur) cur.scrollIntoView({ block: 'nearest' });+ }++ // ── Theme toggle ─────────────────────────────────────────────────────────+ const SUN = '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>';+ const MOON = '<path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8z"/>';+ function paintTheme() { $('#themeIcon').innerHTML = document.documentElement.getAttribute('data-theme') === 'light' ? MOON : SUN; }+ function toggleTheme() {+ const now = document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light';+ document.documentElement.setAttribute('data-theme', now);+ try { localStorage.setItem('twx_theme', now); } catch (e) {}+ paintTheme();+ }++ // ── Copy + toast ─────────────────────────────────────────────────────────+ async function copyText(text, btn) {+ try {+ await navigator.clipboard.writeText(text || '');+ if (btn) { const o = btn.textContent; btn.textContent = '✓ Copied'; btn.classList.add('copied'); setTimeout(() => { btn.textContent = o; btn.classList.remove('copied'); }, 1600); }+ toast('Copied to clipboard');+ } catch (e) { if (btn) btn.textContent = 'copy failed'; }+ }+ let toastT;+ function toast(msg) { const t = $('#toast'); t.textContent = msg; t.classList.add('show'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('show'), 1700); }++ // ── Global wiring ────────────────────────────────────────────────────────+ function wireGlobal() {+ paintTheme();+ $('#themeBtn').addEventListener('click', toggleTheme);+ $('#paletteBtn').addEventListener('click', openPalette);+ const p2 = $('#paletteBtn2'); if (p2) p2.addEventListener('click', openPalette);+ $('#paletteOverlay').addEventListener('click', closePalette);+ $('#drawerOverlay').addEventListener('click', closeDrawer);+ $('#paletteInput').addEventListener('input', (e) => palPaint(e.target.value));+ $('#searchInput').addEventListener('input', (e) => { state.q = e.target.value.trim(); renderGrid(); });+ $('#sortSelect').addEventListener('change', (e) => { state.sort = e.target.value; renderGrid(); });+ $$('.copy-btn[data-copy]').forEach((btn) => btn.addEventListener('click', () => copyText($('#' + btn.dataset.copy).textContent, btn)));+ const nav = $('#nav'); const onScroll = () => nav.classList.toggle('scrolled', window.scrollY > 8); onScroll(); window.addEventListener('scroll', onScroll, { passive: true });++ document.addEventListener('keydown', (e) => {+ const palOpen = $('#palette').classList.contains('show');+ const drawerOpen = $('#drawer').classList.contains('show');+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); palOpen ? closePalette() : openPalette(); return; }+ if (e.key === '/' && !palOpen && !drawerOpen && !/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName)) { e.preventDefault(); $('#searchInput').focus(); return; }+ if (e.key === 'Escape') { if (palOpen) closePalette(); else if (drawerOpen) closeDrawer(); return; }+ if (palOpen) {+ if (e.key === 'ArrowDown') { e.preventDefault(); palIdx = Math.min(palIdx + 1, palResults.length - 1); palHi(); }+ else if (e.key === 'ArrowUp') { e.preventDefault(); palIdx = Math.max(palIdx - 1, 0); palHi(); }+ else if (e.key === 'Enter') { e.preventDefault(); const r = palResults[palIdx]; if (r) { closePalette(); openDrawer(r.id); } }+ }});- });+ }- function escapeHtml(s) {- return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+ function openFromHash() {+ const m = /#run=([^&]+)/.exec(location.hash);+ if (!m) return;+ const path = decodeURIComponent(m[1]);+ const item = CATALOG.find((c) => c.path === path);+ if (item) openDrawer(item.id);+ }++ // ── Boot ─────────────────────────────────────────────────────────────────+ async function boot() {+ skeletonGrid();+ const [cat, stats] = await Promise.allSettled([loadCatalog(), loadStats()]);+ STATS = stats.status === 'fulfilled' ? stats.value : null;+ if (cat.status !== 'fulfilled' || !cat.value.length) { renderStats(); catalogError(); return; }+ CATALOG = cat.value;+ renderStats(); renderChips(); renderGrid(); openFromHash();}-</script>- <script src="/brand.js" defer></script>+ wireGlobal();+ boot();+})();+</script>+<script src="/brand.js" defer></script></body></html>diff --git a/scripts/lib/pump-launch-core.mjs b/scripts/lib/pump-launch-core.mjsindex 9efd454b8..ec0e1b1a4 100644--- a/scripts/lib/pump-launch-core.mjs+++ b/scripts/lib/pump-launch-core.mjs@@ -332,9 +332,11 @@ export function generate(cfg, repos) {const walletFile = join(cfg.walletDir, `repo-${repoName.replace(/[^a-zA-Z0-9._-]/g, '_')}.json`);let kp;let symbol;- if (prev && existsSync(walletFile)) {+ // Reuse any key already on disk — generating a subset must never mint a new+ // address over an existing wallet file (that would strand the old one).+ if (existsSync(walletFile)) {kp = keypairFromFile(walletFile);- symbol = prev.symbol;+ symbol = prev?.symbol || r.symbol || makeSymbol(repoName, usedSymbols);usedSymbols.add(symbol);} else {kp = Keypair.generate();diff --git a/scripts/pump-launch-server.mjs b/scripts/pump-launch-server.mjsindex ba8572ddb..1b51ed8a5 100644--- a/scripts/pump-launch-server.mjs+++ b/scripts/pump-launch-server.mjs@@ -68,6 +68,46 @@ function cfgFor(params = {}) {});}+// ── cover-image proxy (cache + dedupe + avatar fallback) ─────────────────────+// GitHub's OpenGraph endpoint 429s when 146 covers load at once. Fetch through+// here so each (user,repo) resolves once, is cached, and falls back to the+// user's avatar rather than a broken image.+const coverCache = new Map();+const coverInflight = new Map();+async function coverImage(user, repo) {+ const key = `${user}/${repo}`;+ if (coverCache.has(key)) return coverCache.get(key);+ if (coverInflight.has(key)) return coverInflight.get(key);+ const job = (async () => {+ for (const url of [+ `https://opengraph.githubassets.com/1/${user}/${repo}`,+ `https://avatars.githubusercontent.com/${user}?s=400`,+ ]) {+ try {+ const r = await fetch(url);+ if (r.ok) {+ const buf = Buffer.from(await r.arrayBuffer());+ coverCache.set(key, buf);+ return buf;+ }+ } catch {+ /* next */+ }+ }+ // 1x1 transparent PNG fallback so the <img> never shows a broken icon.+ const fallback = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',+ 'base64',+ );+ coverCache.set(key, fallback);+ return fallback;+ })();+ coverInflight.set(key, job);+ const out = await job;+ coverInflight.delete(key);+ return out;+}+// ── helpers ──────────────────────────────────────────────────────────────────function sendJson(res, code, data) {const body = JSON.stringify(data);@@ -137,6 +177,12 @@ async function handle(req, res) {});}+ if (p === '/api/cover') {+ const png = await coverImage(q.user || 'nirholas', q.repo || '');+ res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'public,max-age=86400' });+ return res.end(png);+ }+if (p === '/api/qr') {const png = await QRCode.toBuffer(q.text || '', { width: 320, margin: 1, color: { dark: '#0a0a0f', light: '#ffffff' } });res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'public,max-age=3600' });diff --git a/scripts/pump-launch-ui/index.html b/scripts/pump-launch-ui/index.htmlnew file mode 100644index 000000000..bd5e94215--- /dev/null+++ b/scripts/pump-launch-ui/index.html@@ -0,0 +1,1426 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Repo → Coin Launcher · three.ws</title>+ <style>+ :root {+ --bg: #07070c;+ --bg-1: #0c0c15;+ --bg-2: #12121e;+ --panel: rgba(255, 255, 255, 0.03);+ --panel-2: rgba(255, 255, 255, 0.05);+ --stroke: rgba(255, 255, 255, 0.08);+ --stroke-2: rgba(255, 255, 255, 0.14);+ --text: #edeef5;+ --muted: #9aa0b4;+ --faint: #656b80;+ --violet: #7c5cff;+ --green: #14f195;+ --cyan: #22d3ee;+ --pink: #ff5c8a;+ --warn: #ffcf6b;+ --radius: 16px;+ --radius-sm: 11px;+ --grad: linear-gradient(120deg, var(--violet), var(--cyan) 55%, var(--green));+ --shadow: 0 20px 60px -20px rgba(0, 0, 0, 0.75);+ font-synthesis: none;+ }+ * {+ box-sizing: border-box;+ }+ html,+ body {+ margin: 0;+ background: var(--bg);+ color: var(--text);+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, Roboto, sans-serif;+ -webkit-font-smoothing: antialiased;+ }+ body {+ min-height: 100vh;+ background:+ radial-gradient(900px 500px at 12% -10%, rgba(124, 92, 255, 0.16), transparent 60%),+ radial-gradient(800px 520px at 100% 0%, rgba(20, 241, 149, 0.1), transparent 55%),+ var(--bg);+ }+ a {+ color: var(--cyan);+ text-decoration: none;+ }+ a:hover {+ text-decoration: underline;+ }+ button {+ font: inherit;+ cursor: pointer;+ }+ ::selection {+ background: rgba(124, 92, 255, 0.4);+ }++ .wrap {+ max-width: 1180px;+ margin: 0 auto;+ padding: 28px 24px 160px;+ }++ /* ── Header ─────────────────────────────────────── */+ header.top {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ margin-bottom: 26px;+ }+ .brand {+ display: flex;+ align-items: center;+ gap: 12px;+ }+ .brand .glyph {+ width: 40px;+ height: 40px;+ border-radius: 12px;+ background: var(--grad);+ display: grid;+ place-items: center;+ font-weight: 800;+ color: #06060a;+ box-shadow: 0 8px 30px -8px rgba(124, 92, 255, 0.7);+ }+ .brand h1 {+ font-size: 16px;+ margin: 0;+ letter-spacing: 0.2px;+ }+ .brand p {+ margin: 2px 0 0;+ font-size: 12.5px;+ color: var(--muted);+ }+ .net {+ display: flex;+ gap: 4px;+ padding: 4px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ border-radius: 999px;+ }+ .net button {+ border: 0;+ background: transparent;+ color: var(--muted);+ padding: 7px 14px;+ border-radius: 999px;+ font-size: 12.5px;+ font-weight: 600;+ transition: 0.18s;+ }+ .net button.on {+ background: var(--panel-2);+ color: var(--text);+ box-shadow: inset 0 0 0 1px var(--stroke-2);+ }+ .net button.on.main {+ color: var(--green);+ }++ /* ── Hero ───────────────────────────────────────── */+ .hero {+ display: grid;+ grid-template-columns: 1.35fr 1fr;+ gap: 18px;+ margin-bottom: 22px;+ }+ .card {+ background: linear-gradient(180deg, var(--panel-2), var(--panel));+ border: 1px solid var(--stroke);+ border-radius: var(--radius);+ padding: 20px;+ box-shadow: var(--shadow);+ }+ .hero h2 {+ margin: 0 0 6px;+ font-size: 26px;+ letter-spacing: -0.5px;+ }+ .hero h2 .g {+ background: var(--grad);+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ }+ .hero .sub {+ color: var(--muted);+ font-size: 14px;+ line-height: 1.55;+ margin: 0 0 18px;+ }+ .userbar {+ display: flex;+ gap: 10px;+ align-items: center;+ }+ .userbar .at {+ position: relative;+ flex: 1;+ display: flex;+ align-items: center;+ }+ .userbar .at span {+ position: absolute;+ left: 14px;+ color: var(--faint);+ font-weight: 600;+ }+ .userbar input {+ width: 100%;+ background: var(--bg-1);+ border: 1px solid var(--stroke-2);+ color: var(--text);+ border-radius: 12px;+ padding: 13px 14px 13px 30px;+ font-size: 15px;+ outline: none;+ transition: 0.18s;+ }+ .userbar input:focus {+ border-color: var(--violet);+ box-shadow: 0 0 0 4px rgba(124, 92, 255, 0.16);+ }+ .btn {+ border: 1px solid var(--stroke-2);+ background: var(--panel-2);+ color: var(--text);+ border-radius: 12px;+ padding: 12px 18px;+ font-weight: 650;+ font-size: 14px;+ transition: 0.18s;+ white-space: nowrap;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ }+ .btn:hover {+ border-color: var(--stroke-2);+ background: rgba(255, 255, 255, 0.08);+ transform: translateY(-1px);+ }+ .btn:active {+ transform: translateY(0);+ }+ .btn:disabled {+ opacity: 0.45;+ cursor: not-allowed;+ transform: none;+ }+ .btn.primary {+ background: var(--grad);+ color: #06060a;+ border: 0;+ box-shadow: 0 10px 34px -12px rgba(20, 241, 149, 0.6);+ }+ .btn.primary:hover {+ filter: brightness(1.06);+ }+ .btn.ghost {+ background: transparent;+ }++ /* profile chip */+ .profile {+ display: flex;+ gap: 12px;+ align-items: center;+ margin-top: 16px;+ padding: 12px;+ border: 1px solid var(--stroke);+ border-radius: 12px;+ background: var(--bg-1);+ min-height: 66px;+ }+ .profile img {+ width: 42px;+ height: 42px;+ border-radius: 10px;+ border: 1px solid var(--stroke-2);+ }+ .profile .n {+ font-weight: 700;+ font-size: 14.5px;+ }+ .profile .m {+ color: var(--muted);+ font-size: 12.5px;+ }+ .profile .stat {+ margin-left: auto;+ text-align: right;+ }+ .profile .stat b {+ font-size: 18px;+ }+ .profile .stat span {+ display: block;+ font-size: 11px;+ color: var(--faint);+ text-transform: uppercase;+ letter-spacing: 0.6px;+ }++ /* reward card */+ .reward h3 {+ margin: 0 0 12px;+ font-size: 13px;+ text-transform: uppercase;+ letter-spacing: 1px;+ color: var(--muted);+ display: flex;+ align-items: center;+ gap: 8px;+ }+ .flow {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 13px;+ }+ .flow .node {+ flex: 1;+ text-align: center;+ padding: 12px 6px;+ border-radius: 12px;+ background: var(--bg-1);+ border: 1px solid var(--stroke);+ }+ .flow .node b {+ display: block;+ font-size: 12.5px;+ }+ .flow .node small {+ color: var(--faint);+ font-size: 10.5px;+ }+ .flow .arrow {+ color: var(--green);+ font-size: 18px;+ }+ .pda {+ margin-top: 12px;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11.5px;+ color: var(--green);+ word-break: break-all;+ background: rgba(20, 241, 149, 0.06);+ border: 1px solid rgba(20, 241, 149, 0.2);+ padding: 9px 11px;+ border-radius: 9px;+ }++ /* ── Toolbar ────────────────────────────────────── */+ .toolbar {+ display: flex;+ gap: 10px;+ align-items: center;+ flex-wrap: wrap;+ margin: 20px 0 14px;+ }+ .search {+ position: relative;+ flex: 1;+ min-width: 200px;+ }+ .search input {+ width: 100%;+ background: var(--panel);+ border: 1px solid var(--stroke);+ color: var(--text);+ border-radius: 11px;+ padding: 10px 12px 10px 34px;+ outline: none;+ }+ .search input:focus {+ border-color: var(--stroke-2);+ }+ .search svg {+ position: absolute;+ left: 11px;+ top: 11px;+ opacity: 0.5;+ }+ .chip {+ border: 1px solid var(--stroke);+ background: var(--panel);+ color: var(--muted);+ border-radius: 999px;+ padding: 8px 13px;+ font-size: 12.5px;+ font-weight: 600;+ transition: 0.16s;+ }+ .chip.on {+ color: var(--text);+ border-color: var(--violet);+ background: rgba(124, 92, 255, 0.16);+ }+ .chip:hover {+ border-color: var(--stroke-2);+ }+ select.sort {+ background: var(--panel);+ border: 1px solid var(--stroke);+ color: var(--muted);+ border-radius: 11px;+ padding: 9px 11px;+ outline: none;+ }+ .selcount {+ margin-left: auto;+ font-size: 13px;+ color: var(--muted);+ }+ .selcount b {+ color: var(--text);+ }+ .linkbtn {+ background: none;+ border: 0;+ color: var(--cyan);+ font-size: 12.5px;+ font-weight: 600;+ padding: 4px;+ }++ /* ── Repo grid ──────────────────────────────────── */+ .grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(258px, 1fr));+ gap: 12px;+ }+ .repo {+ position: relative;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-sm);+ overflow: hidden;+ background: var(--bg-1);+ cursor: pointer;+ transition:+ transform 0.16s,+ border-color 0.16s,+ box-shadow 0.16s;+ }+ .repo:hover {+ transform: translateY(-3px);+ border-color: var(--stroke-2);+ box-shadow: 0 16px 40px -22px rgba(0, 0, 0, 0.9);+ }+ .repo.sel {+ border-color: var(--green);+ box-shadow: 0 0 0 1px var(--green), 0 16px 40px -24px rgba(20, 241, 149, 0.5);+ }+ .repo .cover {+ aspect-ratio: 2 / 1;+ background: linear-gradient(135deg, #1a1a2b, #101019);+ position: relative;+ overflow: hidden;+ }+ .repo .cover .cimg {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ object-fit: cover;+ opacity: 0;+ transition: opacity 0.4s ease;+ }+ .repo .check {+ position: absolute;+ top: 10px;+ right: 10px;+ width: 24px;+ height: 24px;+ border-radius: 50%;+ border: 2px solid rgba(255, 255, 255, 0.6);+ background: rgba(0, 0, 0, 0.4);+ backdrop-filter: blur(4px);+ display: grid;+ place-items: center;+ transition: 0.16s;+ }+ .repo.sel .check {+ background: var(--green);+ border-color: var(--green);+ }+ .repo .check svg {+ opacity: 0;+ transition: 0.16s;+ }+ .repo.sel .check svg {+ opacity: 1;+ }+ .repo .body {+ padding: 11px 13px 13px;+ }+ .repo .name {+ font-weight: 700;+ font-size: 13.5px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .repo .desc {+ color: var(--muted);+ font-size: 12px;+ line-height: 1.4;+ margin: 4px 0 9px;+ height: 33px;+ overflow: hidden;+ }+ .repo .meta {+ display: flex;+ align-items: center;+ gap: 12px;+ font-size: 11.5px;+ color: var(--faint);+ }+ .repo .tick {+ margin-left: auto;+ font-family: ui-monospace, monospace;+ color: var(--violet);+ font-weight: 700;+ }+ .dot {+ width: 9px;+ height: 9px;+ border-radius: 50%;+ display: inline-block;+ background: var(--faint);+ }+ .tag {+ position: absolute;+ top: 10px;+ left: 10px;+ font-size: 10px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ padding: 3px 7px;+ border-radius: 6px;+ background: rgba(0, 0, 0, 0.55);+ backdrop-filter: blur(4px);+ color: var(--warn);+ }++ /* skeleton */+ .sk {+ border-radius: var(--radius-sm);+ overflow: hidden;+ border: 1px solid var(--stroke);+ }+ .sk .cover,+ .sk .line {+ background: linear-gradient(90deg, #12121c 25%, #1b1b28 37%, #12121c 63%);+ background-size: 400% 100%;+ animation: sh 1.3s ease infinite;+ }+ .sk .cover {+ aspect-ratio: 2/1;+ }+ .sk .line {+ height: 11px;+ margin: 11px 13px;+ border-radius: 6px;+ }+ @keyframes sh {+ 0% {+ background-position: 100% 0;+ }+ 100% {+ background-position: -100% 0;+ }+ }++ .empty {+ text-align: center;+ padding: 70px 20px;+ color: var(--muted);+ }+ .empty .big {+ font-size: 40px;+ margin-bottom: 10px;+ }++ /* ── Summary bar ────────────────────────────────── */+ .bar {+ position: fixed;+ left: 50%;+ bottom: 18px;+ transform: translateX(-50%) translateY(140%);+ width: min(1140px, calc(100vw - 32px));+ background: rgba(14, 14, 22, 0.86);+ backdrop-filter: blur(18px) saturate(1.4);+ border: 1px solid var(--stroke-2);+ border-radius: 18px;+ box-shadow: 0 30px 80px -20px rgba(0, 0, 0, 0.85);+ padding: 14px 16px;+ display: flex;+ align-items: center;+ gap: 18px;+ transition: transform 0.32s cubic-bezier(0.2, 0.9, 0.25, 1);+ z-index: 40;+ }+ .bar.show {+ transform: translateX(-50%) translateY(0);+ }+ .bar .metric {+ display: flex;+ flex-direction: column;+ gap: 1px;+ }+ .bar .metric b {+ font-size: 17px;+ }+ .bar .metric span {+ font-size: 10.5px;+ color: var(--faint);+ text-transform: uppercase;+ letter-spacing: 0.7px;+ }+ .bar .sep {+ width: 1px;+ height: 34px;+ background: var(--stroke);+ }+ .bar .cfg {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 12.5px;+ color: var(--muted);+ }+ .bar .cfg input {+ width: 78px;+ background: var(--bg-1);+ border: 1px solid var(--stroke);+ color: var(--text);+ border-radius: 8px;+ padding: 6px 8px;+ outline: none;+ }+ .bar .actions {+ margin-left: auto;+ display: flex;+ gap: 10px;+ }++ /* ── Modal / drawer ─────────────────────────────── */+ .scrim {+ position: fixed;+ inset: 0;+ background: rgba(4, 4, 8, 0.66);+ backdrop-filter: blur(6px);+ opacity: 0;+ pointer-events: none;+ transition: 0.24s;+ z-index: 50;+ }+ .scrim.show {+ opacity: 1;+ pointer-events: auto;+ }+ .modal {+ position: fixed;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -46%) scale(0.98);+ width: min(560px, calc(100vw - 32px));+ max-height: 86vh;+ overflow: auto;+ background: linear-gradient(180deg, var(--bg-2), var(--bg-1));+ border: 1px solid var(--stroke-2);+ border-radius: 20px;+ box-shadow: var(--shadow);+ padding: 24px;+ opacity: 0;+ pointer-events: none;+ transition: 0.26s cubic-bezier(0.2, 0.9, 0.25, 1);+ z-index: 51;+ }+ .modal.show {+ opacity: 1;+ pointer-events: auto;+ transform: translate(-50%, -50%) scale(1);+ }+ .modal h3 {+ margin: 0 0 4px;+ font-size: 19px;+ }+ .modal .lead {+ color: var(--muted);+ font-size: 13.5px;+ margin: 0 0 18px;+ line-height: 1.5;+ }+ .fund {+ display: flex;+ gap: 16px;+ align-items: center;+ background: var(--bg);+ border: 1px solid var(--stroke);+ border-radius: 14px;+ padding: 16px;+ }+ .fund img.qr {+ width: 118px;+ height: 118px;+ border-radius: 10px;+ background: #fff;+ }+ .addr {+ font-family: ui-monospace, monospace;+ font-size: 12px;+ background: var(--bg-1);+ border: 1px solid var(--stroke);+ border-radius: 9px;+ padding: 9px 10px;+ word-break: break-all;+ display: flex;+ gap: 8px;+ align-items: center;+ }+ .addr button {+ margin-left: auto;+ background: var(--panel-2);+ border: 1px solid var(--stroke);+ border-radius: 7px;+ color: var(--text);+ padding: 4px 9px;+ font-size: 11px;+ }+ .balrow {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 12px;+ font-size: 13px;+ }+ .balrow .pill {+ padding: 3px 9px;+ border-radius: 999px;+ font-weight: 700;+ font-size: 12px;+ }+ .pill.ok {+ background: rgba(20, 241, 149, 0.16);+ color: var(--green);+ }+ .pill.wait {+ background: rgba(255, 207, 107, 0.16);+ color: var(--warn);+ }++ /* progress rows */+ .prog {+ margin-top: 6px;+ }+ .progbar {+ height: 7px;+ border-radius: 999px;+ background: var(--bg);+ overflow: hidden;+ border: 1px solid var(--stroke);+ margin-bottom: 14px;+ }+ .progbar i {+ display: block;+ height: 100%;+ width: 0%;+ background: var(--grad);+ transition: width 0.3s;+ }+ .rows {+ max-height: 340px;+ overflow: auto;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .rrow {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 9px 11px;+ border: 1px solid var(--stroke);+ border-radius: 10px;+ background: var(--bg-1);+ font-size: 13px;+ }+ .rrow .rn {+ font-weight: 650;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 40%;+ }+ .rrow .ph {+ margin-left: auto;+ font-size: 11px;+ color: var(--muted);+ text-transform: capitalize;+ }+ .rrow.ok {+ border-color: rgba(20, 241, 149, 0.3);+ }+ .rrow.err {+ border-color: rgba(255, 92, 138, 0.4);+ }+ .spin {+ width: 14px;+ height: 14px;+ border-radius: 50%;+ border: 2px solid var(--stroke-2);+ border-top-color: var(--cyan);+ animation: rot 0.8s linear infinite;+ }+ @keyframes rot {+ to {+ transform: rotate(360deg);+ }+ }+ .tickok {+ color: var(--green);+ }+ .tickerr {+ color: var(--pink);+ }++ /* toast */+ .toasts {+ position: fixed;+ top: 74px;+ right: 18px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ z-index: 60;+ }+ .toast {+ background: rgba(18, 18, 28, 0.95);+ border: 1px solid var(--stroke-2);+ border-left: 3px solid var(--violet);+ border-radius: 11px;+ padding: 11px 14px;+ font-size: 13px;+ box-shadow: var(--shadow);+ animation: slideIn 0.24s ease;+ max-width: 320px;+ }+ .toast.err {+ border-left-color: var(--pink);+ }+ .toast.ok {+ border-left-color: var(--green);+ }+ @keyframes slideIn {+ from {+ transform: translateX(20px);+ opacity: 0;+ }+ }++ kbd {+ background: var(--panel-2);+ border: 1px solid var(--stroke-2);+ border-bottom-width: 2px;+ border-radius: 6px;+ padding: 1px 6px;+ font-size: 11px;+ font-family: ui-monospace, monospace;+ }+ .foot {+ margin-top: 22px;+ color: var(--faint);+ font-size: 12px;+ text-align: center;+ }+ @media (max-width: 820px) {+ .hero {+ grid-template-columns: 1fr;+ }+ .bar {+ flex-wrap: wrap;+ }+ .bar .actions {+ width: 100%;+ }+ }+ </style>+ </head>+ <body>+ <div class="wrap">+ <header class="top">+ <div class="brand">+ <div class="glyph">◎</div>+ <div>+ <h1>Repo → Coin Launcher</h1>+ <p>Launch a pump.fun coin per GitHub repo · rewards routed to the owner</p>+ </div>+ </div>+ <div class="net" id="net">+ <button data-net="mainnet" class="on main">◎ Mainnet</button>+ <button data-net="devnet">Devnet</button>+ </div>+ </header>++ <section class="hero">+ <div class="card">+ <h2>Turn every repo into a <span class="g">coin</span>.</h2>+ <p class="sub">+ One pump.fun coin per public repository. <b>100% of creator rewards</b> route to the+ GitHub owner via pump.fun's social-fee escrow — you keep the launch wallets, they claim+ the fees. Pick repos, generate wallets, fund one master, launch.+ </p>+ <div class="userbar">+ <label class="at">+ <span>@</span>+ <input id="user" value="nirholas" spellcheck="false" autocomplete="off" />+ </label>+ <button class="btn primary" id="load">Discover repos</button>+ </div>+ <div class="profile" id="profile" style="display: none"></div>+ </div>++ <div class="card reward">+ <h3><span class="dot" style="background: var(--green)"></span> Reward routing</h3>+ <div class="flow">+ <div class="node">+ <b>Launch wallet</b><small>you own the key</small>+ </div>+ <div class="arrow">→</div>+ <div class="node" style="border-color: rgba(20, 241, 149, 0.3)">+ <b style="color: var(--green)">GitHub owner</b><small>100% of fees</small>+ </div>+ </div>+ <div class="pda" id="pda">resolve a user to see the escrow address…</div>+ </div>+ </section>++ <div class="toolbar" id="toolbar" style="display: none">+ <div class="search">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">+ <circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" />+ </svg>+ <input id="q" placeholder="Search repos… ( / )" />+ </div>+ <button class="chip on" data-f="forks">Forks</button>+ <button class="chip on" data-f="archived">Archived</button>+ <button class="chip" data-f="starred">★ Starred only</button>+ <select class="sort" id="sort">+ <option value="stars">Sort: Stars</option>+ <option value="name">Sort: Name</option>+ <option value="updated">Sort: Updated</option>+ </select>+ <button class="linkbtn" id="selAll">Select all</button>+ <button class="linkbtn" id="selNone">Clear</button>+ <div class="selcount"><b id="selN">0</b> selected</div>+ </div>++ <div class="grid" id="grid"></div>+ <div class="foot" id="foot"></div>+ </div>++ <!-- summary bar -->+ <div class="bar" id="bar">+ <div class="metric"><b id="mCount">0</b><span>coins</span></div>+ <div class="sep"></div>+ <div class="metric"><b id="mCost">0 ◎</b><span>to fund</span></div>+ <div class="sep"></div>+ <div class="cfg">+ dev buy <input id="devBuy" type="number" step="0.0001" min="0" value="0" /> ◎+ </div>+ <div class="cfg">+ fund/wallet <input id="fpw" type="number" step="0.001" min="0.02" /> ◎+ </div>+ <div class="actions">+ <button class="btn" id="genBtn">Generate wallets</button>+ <button class="btn primary" id="launchBtn" disabled>Launch →</button>+ </div>+ </div>++ <!-- modal -->+ <div class="scrim" id="scrim"></div>+ <div class="modal" id="modal">+ <div id="modalBody"></div>+ </div>++ <div class="toasts" id="toasts"></div>+ <canvas id="confetti" style="position: fixed; inset: 0; pointer-events: none; z-index: 70; display: none"></canvas>++ <script type="module">+ const $ = (s, r = document) => r.querySelector(s);+ const api = (p, o) => fetch(p, o).then((r) => r.json());+ const solFmt = (n) => `${(+n).toFixed(n < 1 ? 4 : 3)} ◎`;+ const state = {+ user: 'nirholas',+ profile: null,+ network: 'mainnet',+ repos: [],+ sel: new Set(),+ filters: { forks: true, archived: true, starred: false },+ sort: 'stars',+ q: '',+ manifest: null,+ devBuy: 0,+ fpw: null,+ launching: false,+ };++ // ── toasts ──────────────────────────────────────+ function toast(msg, kind = '') {+ const t = document.createElement('div');+ t.className = `toast ${kind}`;+ t.textContent = msg;+ $('#toasts').append(t);+ setTimeout(() => {+ t.style.opacity = '0';+ t.style.transition = '0.3s';+ setTimeout(() => t.remove(), 300);+ }, 3600);+ }++ // ── network toggle ──────────────────────────────+ $('#net').addEventListener('click', (e) => {+ const b = e.target.closest('button');+ if (!b) return;+ state.network = b.dataset.net;+ [...$('#net').children].forEach((x) => x.classList.remove('on', 'main'));+ b.classList.add('on');+ if (state.network === 'mainnet') b.classList.add('main');+ refreshState();+ });++ // ── discover ────────────────────────────────────+ $('#load').addEventListener('click', loadRepos);+ $('#user').addEventListener('keydown', (e) => e.key === 'Enter' && loadRepos());++ async function loadRepos() {+ state.user = $('#user').value.trim().replace(/^@/, '') || 'nirholas';+ $('#toolbar').style.display = 'flex';+ renderSkeleton();+ try {+ const prof = await api(`/api/resolve?user=${state.user}`);+ if (prof.error) throw new Error(prof.error);+ state.profile = prof;+ renderProfile(prof);+ $('#pda').textContent = prof.socialFeePda;+ const data = await api(+ `/api/repos?user=${state.user}&forks=${state.filters.forks}&archived=${state.filters.archived}`,+ );+ if (data.error) throw new Error(data.error);+ state.repos = data.repos;+ // preselect all by default+ state.sel = new Set(state.repos.map((r) => r.name));+ render();+ await refreshState();+ toast(`Loaded ${data.count} repos for @${state.user}`, 'ok');+ } catch (e) {+ $('#grid').innerHTML = `<div class="empty"><div class="big">⚠︎</div>${e.message}</div>`;+ }+ }++ function renderProfile(p) {+ $('#profile').style.display = 'flex';+ $('#profile').innerHTML = `+ <img src="${p.avatarUrl}" alt="" />+ <div>+ <div class="n">${p.name || p.login} <span class="m">@${p.login}</span></div>+ <div class="m">${(p.bio || '').slice(0, 64) || 'GitHub developer'}</div>+ </div>+ <div class="stat"><b>${p.publicRepos}</b><span>public repos</span></div>`;+ }++ // ── filters / sort / search ─────────────────────+ $('#toolbar').addEventListener('click', (e) => {+ const c = e.target.closest('.chip');+ if (!c) return;+ const f = c.dataset.f;+ state.filters[f] = !state.filters[f];+ // chip highlighted == filter active (forks/archived included, or starred-only on)+ c.classList.toggle('on', state.filters[f]);+ // forks/archived change the fetched set; starred is a client-side view filter+ if (f === 'forks' || f === 'archived') loadRepos();+ else render();+ });+ $('#q').addEventListener('input', (e) => {+ state.q = e.target.value.toLowerCase();+ render();+ });+ $('#sort').addEventListener('change', (e) => {+ state.sort = e.target.value;+ render();+ });+ $('#selAll').addEventListener('click', () => {+ visibleRepos().forEach((r) => state.sel.add(r.name));+ render();+ });+ $('#selNone').addEventListener('click', () => {+ state.sel.clear();+ render();+ });++ function visibleRepos() {+ let list = state.repos.slice();+ if (state.filters.starred) list = list.filter((r) => r.stars > 0);+ if (state.q) list = list.filter((r) => (r.name + ' ' + (r.description || '')).toLowerCase().includes(state.q));+ if (state.sort === 'name') list.sort((a, b) => a.name.localeCompare(b.name));+ else if (state.sort === 'updated') list.sort((a, b) => (b.updated_at || '').localeCompare(a.updated_at || ''));+ else list.sort((a, b) => (b.stars || 0) - (a.stars || 0));+ return list;+ }++ // ── render grid ─────────────────────────────────+ function renderSkeleton() {+ $('#grid').innerHTML = Array.from({ length: 8 })+ .map(() => `<div class="sk"><div class="cover"></div><div class="line" style="width:70%"></div><div class="line" style="width:90%"></div></div>`)+ .join('');+ }+ function tickerOf(name) {+ let s = name.replace(/[^a-zA-Z0-9]/g, '').toUpperCase().slice(0, 10);+ return s || 'COIN';+ }+ function render() {+ const list = visibleRepos();+ if (!list.length) {+ $('#grid').innerHTML = `<div class="empty"><div class="big">🔍</div>No repos match your filters.</div>`;+ } else {+ $('#grid').innerHTML = list+ .map((r) => {+ const sel = state.sel.has(r.name);+ const tag = r.fork ? 'fork' : r.archived ? 'archived' : '';+ return `<div class="repo ${sel ? 'sel' : ''}" data-n="${r.name}">+ <div class="cover">+ <img class="cimg" loading="lazy" decoding="async" data-src="/api/cover?user=${encodeURIComponent(state.user)}&repo=${encodeURIComponent(r.name)}" alt="" />+ ${tag ? `<span class="tag">${tag}</span>` : ''}+ <span class="check"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#06060a" stroke-width="3.5"><path d="M20 6 9 17l-5-5"/></svg></span>+ </div>+ <div class="body">+ <div class="name">${r.name}</div>+ <div class="desc">${r.description ? escapeHtml(r.description) : '<span style="color:var(--faint)">No description</span>'}</div>+ <div class="meta">+ ${r.language ? `<span><span class="dot" style="background:${langColor(r.language)}"></span> ${r.language}</span>` : ''}+ <span>★ ${r.stars || 0}</span>+ <span class="tick">$${tickerOf(r.name)}</span>+ </div>+ </div>+ </div>`;+ })+ .join('');+ }+ $('#selN').textContent = state.sel.size;+ $('#foot').textContent = `${list.length} shown · ${state.repos.length} total`;+ lazyCovers();+ updateBar();+ }++ // Lazy-load covers: only fetch images as cards scroll into view, so we+ // never fire 146 requests at once (the server proxies + caches them).+ let coverIO;+ function lazyCovers() {+ coverIO?.disconnect();+ coverIO = new IntersectionObserver(+ (entries) => {+ for (const en of entries) {+ if (!en.isIntersecting) continue;+ const img = en.target;+ img.src = img.dataset.src;+ img.addEventListener('load', () => (img.style.opacity = '1'), { once: true });+ coverIO.unobserve(img);+ }+ },+ { rootMargin: '300px' },+ );+ document.querySelectorAll('.cimg[data-src]').forEach((img) => coverIO.observe(img));+ }+ $('#grid').addEventListener('click', (e) => {+ const card = e.target.closest('.repo');+ if (!card) return;+ const n = card.dataset.n;+ state.sel.has(n) ? state.sel.delete(n) : state.sel.add(n);+ card.classList.toggle('sel', state.sel.has(n));+ $('#selN').textContent = state.sel.size;+ updateBar();+ });++ function escapeHtml(s) {+ return s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);+ }+ function langColor(l) {+ const m = { JavaScript: '#f1e05a', TypeScript: '#3178c6', Python: '#3572A5', Rust: '#dea584', Go: '#00ADD8', Solidity: '#AA6746', HTML: '#e34c26', CSS: '#563d7c', Shell: '#89e051' };+ return m[l] || '#8b8b9a';+ }++ // ── cost + summary bar ──────────────────────────+ let costPerCoin = 0.023;+ function updateBar() {+ const n = state.sel.size;+ $('#mCount').textContent = n;+ const fpw = state.fpw ?? costPerCoin + 0.004;+ $('#mCost').textContent = solFmt(fpw * n);+ $('#bar').classList.toggle('show', n > 0 && !state.launching);+ $('#launchBtn').disabled = !state.manifest || n === 0;+ }+ $('#devBuy').addEventListener('input', (e) => {+ state.devBuy = Math.max(0, +e.target.value || 0);+ costPerCoin = 0.0228 + state.devBuy;+ if (state.fpw == null) $('#fpw').value = (costPerCoin + 0.004).toFixed(4);+ updateBar();+ });+ $('#fpw').addEventListener('input', (e) => {+ state.fpw = +e.target.value || null;+ updateBar();+ });++ async function refreshState() {+ const s = await api(+ `/api/state?user=${state.user}&network=${state.network}&devBuy=${state.devBuy}&count=${state.sel.size}`,+ );+ if (s.error) return;+ state.manifest = s.manifest;+ costPerCoin = s.cost.perCoinSol;+ if (state.fpw == null) $('#fpw').value = s.cost.fundPerWalletSol.toFixed(4);+ updateBar();+ }++ // ── generate ────────────────────────────────────+ $('#genBtn').addEventListener('click', async () => {+ if (!state.sel.size) return toast('Select at least one repo', 'err');+ const selected = state.repos.filter((r) => state.sel.has(r.name));+ $('#genBtn').textContent = 'Generating…';+ $('#genBtn').disabled = true;+ try {+ const res = await api('/api/generate', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ user: state.user,+ network: state.network,+ devBuy: state.devBuy,+ fundPerWallet: state.fpw ?? undefined,+ repos: selected,+ }),+ });+ if (res.error) throw new Error(res.error);+ await refreshState();+ toast(`Generated ${res.count} wallets · master ready`, 'ok');+ openFundModal(res);+ } catch (e) {+ toast(e.message, 'err');+ } finally {+ $('#genBtn').textContent = 'Generate wallets';+ $('#genBtn').disabled = false;+ }+ });++ // ── fund modal ──────────────────────────────────+ let balPoll = null;+ function openFundModal(gen) {+ const master = gen.master;+ const need = (state.fpw ?? costPerCoin + 0.004) * gen.count;+ $('#modalBody').innerHTML = `+ <h3>Fund the master wallet</h3>+ <p class="lead">Send <b>~${solFmt(need)}</b> to this wallet. It funds all ${gen.count} launch wallets. Keys are in <b>pump-launch-wallets.zip</b> — download and keep it private.</p>+ <div class="fund">+ <img class="qr" src="/api/qr?text=${master}" alt="QR" />+ <div style="flex:1">+ <div class="addr"><span id="maddr">${master}</span><button id="copyAddr">Copy</button></div>+ <div class="balrow">Balance: <span class="pill wait" id="balPill">— checking…</span></div>+ <a class="btn ghost" href="/api/download?user=${state.user}" style="margin-top:12px;display:inline-flex">⬇ Download keys .zip</a>+ </div>+ </div>+ <div style="display:flex;gap:10px;margin-top:20px;justify-content:flex-end">+ <button class="btn ghost" id="mClose">Close</button>+ <button class="btn primary" id="mLaunch" disabled>Launch ${gen.count} coins →</button>+ </div>`;+ showModal(true);+ $('#copyAddr').onclick = () => {+ navigator.clipboard.writeText(master);+ toast('Address copied', 'ok');+ };+ $('#mClose').onclick = () => showModal(false);+ $('#mLaunch').onclick = () => {+ showModal(false);+ startLaunch();+ };+ const need_l = need;+ clearInterval(balPoll);+ const poll = async () => {+ const s = await api(`/api/state?user=${state.user}&network=${state.network}`);+ const bal = s.masterBalanceSol || 0;+ const ok = bal >= need_l * 0.999;+ const pill = $('#balPill');+ if (pill) {+ pill.className = `pill ${ok ? 'ok' : 'wait'}`;+ pill.textContent = `${solFmt(bal)}${ok ? ' ✓ ready' : ` / ${solFmt(need_l)}`}`;+ }+ const lb = $('#mLaunch');+ if (lb) lb.disabled = !ok;+ };+ poll();+ balPoll = setInterval(poll, 4000);+ }++ $('#launchBtn').addEventListener('click', () => {+ if (!state.manifest) return toast('Generate wallets first', 'err');+ openFundModal({ master: state.manifest.master_pubkey, count: state.sel.size });+ });++ function showModal(on) {+ $('#scrim').classList.toggle('show', on);+ $('#modal').classList.toggle('show', on);+ if (!on) clearInterval(balPoll);+ }+ $('#scrim').addEventListener('click', () => showModal(false));++ // ── launch (SSE over fetch) ─────────────────────+ async function startLaunch() {+ state.launching = true;+ $('#bar').classList.remove('show');+ const repoNames = [...state.sel];+ const total = repoNames.length;+ const done = {};+ $('#modalBody').innerHTML = `+ <h3>Launching ${total} coins</h3>+ <p class="lead">Creating each coin, then delegating 100% of rewards to @${state.user}. Resumable — safe to close and reopen.</p>+ <div class="prog">+ <div class="progbar"><i id="pbar"></i></div>+ <div class="rows" id="rows">${repoNames.map((n) => rrow(n, 'queued')).join('')}</div>+ </div>+ <div style="display:flex;justify-content:space-between;align-items:center;margin-top:16px">+ <span class="m" id="pstat" style="color:var(--muted);font-size:13px">Starting…</span>+ <button class="btn ghost" id="mDone">Run in background</button>+ </div>`;+ showModal(true);+ $('#mDone').onclick = () => showModal(false);++ const res = await fetch('/api/launch', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ user: state.user, network: state.network, devBuy: state.devBuy, fundPerWallet: state.fpw ?? undefined, repoNames }),+ });+ const reader = res.body.getReader();+ const dec = new TextDecoder();+ let buf = '';+ let completed = 0,+ errors = 0;+ while (true) {+ const { value, done: rdone } = await reader.read();+ if (rdone) break;+ buf += dec.decode(value, { stream: true });+ const parts = buf.split('\n\n');+ buf = parts.pop();+ for (const part of parts) {+ const line = part.split('\n').find((l) => l.startsWith('data: '));+ if (!line) continue;+ const e = JSON.parse(line.slice(6));+ handleEvent(e);+ }+ }+ function handleEvent(e) {+ if (e.type === 'repo') setRow(e.repo, e.phase);+ else if (e.type === 'done') {+ completed++;+ done[e.repo] = e;+ setRow(e.repo, 'done', e);+ } else if (e.type === 'error') {+ errors++;+ setRow(e.repo, 'error', e);+ } else if (e.type === 'info') $('#pstat') && ($('#pstat').textContent = e.message);+ else if (e.type === 'fatal') {+ toast(e.message, 'err');+ $('#pstat') && ($('#pstat').textContent = '⚠︎ ' + e.message);+ } else if (e.type === 'complete') finish();+ const pct = Math.round(((completed + errors) / total) * 100);+ $('#pbar') && ($('#pbar').style.width = pct + '%');+ $('#pstat') && ($('#pstat').textContent = `${completed} launched · ${errors} failed · ${total} total`);+ }+ function finish() {+ state.launching = false;+ if (completed > 0) confetti();+ toast(`Done — ${completed}/${total} coins live, rewards → @${state.user}`, completed === total ? 'ok' : '');+ }+ }+ function rrow(name, phase, e) {+ const cls = phase === 'done' ? 'ok' : phase === 'error' ? 'err' : '';+ let right = '';+ if (phase === 'done')+ right = `<a class="ph tickok" target="_blank" href="https://solscan.io/tx/${e?.launchSig || ''}">view ↗</a>`;+ else if (phase === 'error') right = `<span class="ph tickerr">failed</span>`;+ else if (phase === 'queued') right = `<span class="ph">queued</span>`;+ else right = `<span class="spin"></span><span class="ph">${phase}</span>`;+ return `<div class="rrow ${cls}" data-r="${name}"><span class="rn">${name}</span>${right}</div>`;+ }+ function setRow(name, phase, e) {+ const el = document.querySelector(`.rrow[data-r="${CSS.escape(name)}"]`);+ if (el) el.outerHTML = rrow(name, phase, e);+ }++ // ── confetti (tiny) ─────────────────────────────+ function confetti() {+ const cv = $('#confetti');+ cv.style.display = 'block';+ cv.width = innerWidth;+ cv.height = innerHeight;+ const ctx = cv.getContext('2d');+ const cols = ['#7c5cff', '#14f195', '#22d3ee', '#ff5c8a', '#ffcf6b'];+ const P = Array.from({ length: 140 }, () => ({+ x: innerWidth / 2,+ y: innerHeight / 3,+ vx: (Math.random() - 0.5) * 14,+ vy: Math.random() * -14 - 4,+ c: cols[(Math.random() * cols.length) | 0],+ s: Math.random() * 6 + 3,+ r: Math.random() * 6,+ }));+ let t = 0;+ (function loop() {+ ctx.clearRect(0, 0, cv.width, cv.height);+ P.forEach((p) => {+ p.vy += 0.5;+ p.x += p.vx;+ p.y += p.vy;+ p.r += 0.2;+ ctx.save();+ ctx.translate(p.x, p.y);+ ctx.rotate(p.r);+ ctx.fillStyle = p.c;+ ctx.fillRect(-p.s / 2, -p.s / 2, p.s, p.s * 0.6);+ ctx.restore();+ });+ if (++t < 120) requestAnimationFrame(loop);+ else cv.style.display = 'none';+ })();+ }++ // ── keyboard ────────────────────────────────────+ addEventListener('keydown', (e) => {+ if (e.key === '/' && document.activeElement.tagName !== 'INPUT') {+ e.preventDefault();+ $('#q').focus();+ }+ if ((e.metaKey || e.ctrlKey) && e.key === 'a' && state.repos.length && document.activeElement.tagName !== 'INPUT') {+ e.preventDefault();+ visibleRepos().forEach((r) => state.sel.add(r.name));+ render();+ }+ if (e.key === 'Escape') showModal(false);+ });++ // boot+ $('#fpw').value = '0.0268';+ loadRepos();+ </script>+ </body>+</html>diff --git a/src/admin-seeder.css b/src/admin-seeder.cssnew file mode 100644index 000000000..f441e07bb--- /dev/null+++ b/src/admin-seeder.css@@ -0,0 +1,199 @@+/* /admin/seeder — Avatar Seeder control room.+ A focused, premium dark surface: glass cards, a violet accent, a physical arm+ switch, and a live 3D gallery of freshly-seeded rigged avatars. */++:root {+ --sd-bg: #07070b;+ --sd-bg2: #0b0b12;+ --sd-panel: rgba(255, 255, 255, 0.035);+ --sd-panel-2: rgba(255, 255, 255, 0.055);+ --sd-line: rgba(255, 255, 255, 0.08);+ --sd-line-2: rgba(255, 255, 255, 0.13);+ --sd-text: #eef0f6;+ --sd-dim: rgba(238, 240, 246, 0.56);+ --sd-faint: rgba(238, 240, 246, 0.34);+ --sd-accent: #7c5cff;+ --sd-accent-2: #a78bfa;+ --sd-good: #2fbf71;+ --sd-warn: #f0a93b;+ --sd-bad: #f87171;+ --sd-radius: 16px;+ --sd-shadow: 0 24px 60px -28px rgba(0, 0, 0, 0.8);+ --sd-ease: cubic-bezier(0.22, 1, 0.36, 1);+}++* { box-sizing: border-box; }+body {+ margin: 0;+ background:+ radial-gradient(1100px 620px at 78% -8%, rgba(124, 92, 255, 0.16), transparent 60%),+ radial-gradient(900px 520px at 8% 4%, rgba(47, 191, 113, 0.08), transparent 55%),+ var(--sd-bg);+ color: var(--sd-text);+ font: 14px/1.55 -apple-system, system-ui, 'Segoe UI', Inter, sans-serif;+ min-height: 100vh;+ -webkit-font-smoothing: antialiased;+}++.sd-wrap { max-width: 1240px; margin: 0 auto; padding: clamp(1.25rem, 3.5vw, 2.75rem) 1.25rem 6rem; }++/* ── Auth gate ─────────────────────────────────────────────────────────────── */+.sd-gate { max-width: 420px; margin: 8vh auto; text-align: center; animation: sd-rise .5s var(--sd-ease); }+.sd-gate-mark {+ width: 64px; height: 64px; margin: 0 auto 20px; border-radius: 20px;+ display: grid; place-items: center; font-size: 30px;+ background: linear-gradient(135deg, rgba(124, 92, 255, 0.25), rgba(124, 92, 255, 0.05));+ border: 1px solid rgba(124, 92, 255, 0.35);+ box-shadow: 0 0 40px -6px rgba(124, 92, 255, 0.5);+}+.sd-gate h1 { font-size: 1.35rem; font-weight: 800; letter-spacing: -0.02em; margin: 0 0 6px; }+.sd-gate p { color: var(--sd-dim); margin: 0 0 22px; font-size: 13.5px; }+.sd-gate form { display: flex; flex-direction: column; gap: 10px; }+.sd-input {+ width: 100%; font: inherit; font-size: 14px; padding: 12px 15px; color: var(--sd-text);+ background: var(--sd-panel); border: 1px solid var(--sd-line-2); border-radius: 12px; outline: none;+ transition: border-color .15s, box-shadow .15s;+}+.sd-input:focus { border-color: rgba(124, 92, 255, 0.6); box-shadow: 0 0 0 4px rgba(124, 92, 255, 0.14); }+.sd-gate-err { color: var(--sd-bad); font-size: 12.5px; min-height: 16px; margin: 2px 0 0; }++/* ── Buttons ───────────────────────────────────────────────────────────────── */+.sd-btn {+ font: inherit; font-size: 13.5px; font-weight: 600; padding: 11px 16px; border-radius: 12px;+ border: 1px solid transparent; cursor: pointer; transition: transform .12s var(--sd-ease), background .15s, border-color .15s, opacity .15s;+ display: inline-flex; align-items: center; gap: 8px; white-space: nowrap;+}+.sd-btn:active { transform: translateY(1px) scale(0.99); }+.sd-btn:disabled { opacity: .45; cursor: default; }+.sd-btn-primary { background: linear-gradient(135deg, var(--sd-accent), #6144e0); color: #fff; box-shadow: 0 10px 30px -12px rgba(124, 92, 255, 0.8); }+.sd-btn-primary:hover:not(:disabled) { filter: brightness(1.08); }+.sd-btn-ghost { background: var(--sd-panel); border-color: var(--sd-line-2); color: var(--sd-text); }+.sd-btn-ghost:hover:not(:disabled) { background: var(--sd-panel-2); border-color: var(--sd-accent-2); }+.sd-btn-danger { background: rgba(248, 113, 113, 0.12); border-color: rgba(248, 113, 113, 0.32); color: #fca5a5; }+.sd-btn-danger:hover:not(:disabled) { background: rgba(248, 113, 113, 0.2); }++/* ── Hero ──────────────────────────────────────────────────────────────────── */+.sd-hero {+ display: flex; align-items: center; justify-content: space-between; gap: 1.5rem; flex-wrap: wrap;+ padding: clamp(1.1rem, 2.5vw, 1.75rem);+ background: linear-gradient(180deg, var(--sd-panel-2), var(--sd-panel));+ border: 1px solid var(--sd-line); border-radius: 22px; box-shadow: var(--sd-shadow);+ margin-bottom: 1.5rem; animation: sd-rise .5s var(--sd-ease);+}+.sd-kicker { display: flex; align-items: center; gap: 9px; font-size: 11.5px; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; color: var(--sd-dim); margin: 0 0 8px; }+.sd-title { font-size: clamp(1.5rem, 3.6vw, 2.15rem); font-weight: 800; letter-spacing: -0.03em; margin: 0; }+.sd-title em { font-style: normal; background: linear-gradient(120deg, var(--sd-accent-2), var(--sd-accent)); -webkit-background-clip: text; background-clip: text; color: transparent; }+.sd-sub { color: var(--sd-dim); margin: 8px 0 0; font-size: 13.5px; max-width: 46ch; }+.sd-hero-r { display: flex; align-items: center; gap: 12px; }++/* Live status dot */+.sd-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--sd-faint); flex-shrink: 0; }+.sd-dot.on { background: var(--sd-good); box-shadow: 0 0 0 0 rgba(47, 191, 113, 0.6); animation: sd-pulse 1.8s infinite; }+.sd-dot.off { background: var(--sd-faint); }+.sd-dot.err { background: var(--sd-bad); box-shadow: 0 0 10px rgba(248, 113, 113, 0.7); }++/* ── Arm switch ────────────────────────────────────────────────────────────── */+.sd-arm {+ display: inline-flex; align-items: center; gap: 12px; padding: 8px 8px 8px 18px;+ background: var(--sd-panel); border: 1px solid var(--sd-line-2); border-radius: 999px; cursor: pointer;+ transition: border-color .2s, background .2s;+}+.sd-arm:hover { border-color: var(--sd-accent-2); }+.sd-arm-lbl { font-size: 13px; font-weight: 700; letter-spacing: .02em; color: var(--sd-dim); }+.sd-arm.on .sd-arm-lbl { color: var(--sd-good); }+.sd-arm-track { position: relative; width: 52px; height: 30px; border-radius: 999px; background: rgba(255, 255, 255, 0.1); transition: background .25s var(--sd-ease); flex-shrink: 0; }+.sd-arm.on .sd-arm-track { background: linear-gradient(135deg, var(--sd-good), #17a45a); box-shadow: 0 0 22px -4px rgba(47, 191, 113, 0.7); }+.sd-arm-knob { position: absolute; top: 3px; left: 3px; width: 24px; height: 24px; border-radius: 50%; background: #fff; transition: transform .28s var(--sd-ease); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4); }+.sd-arm.on .sd-arm-knob { transform: translateX(22px); }+.sd-arm[aria-busy='true'] { opacity: .6; pointer-events: none; }++/* ── Breaker banner ────────────────────────────────────────────────────────── */+.sd-breaker {+ display: flex; align-items: center; gap: 12px; padding: 12px 18px; margin-bottom: 1.25rem;+ background: rgba(240, 169, 59, 0.09); border: 1px solid rgba(240, 169, 59, 0.28); border-radius: 14px;+ color: #f6c778; font-size: 13.5px; animation: sd-rise .4s var(--sd-ease);+}+.sd-breaker b { color: #fbbf24; }++/* ── Stat cards ────────────────────────────────────────────────────────────── */+.sd-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(158px, 1fr)); gap: 12px; margin-bottom: 1.5rem; }+.sd-stat { background: var(--sd-panel); border: 1px solid var(--sd-line); border-radius: var(--sd-radius); padding: 16px 18px; position: relative; overflow: hidden; transition: border-color .2s, transform .2s var(--sd-ease); }+.sd-stat:hover { border-color: var(--sd-line-2); transform: translateY(-2px); }+.sd-stat--lead { background: linear-gradient(160deg, rgba(124, 92, 255, 0.16), rgba(124, 92, 255, 0.03)); border-color: rgba(124, 92, 255, 0.28); }+.sd-stat dt { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .07em; color: var(--sd-faint); margin: 0 0 8px; }+.sd-stat dd { margin: 0; font-size: 1.9rem; font-weight: 800; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }+.sd-stat small { display: block; margin-top: 3px; font-size: 11.5px; font-weight: 500; color: var(--sd-dim); }+.sd-stat dd.good { color: var(--sd-good); }+.sd-stat dd.warn { color: var(--sd-warn); }+.sd-stat dd.bad { color: var(--sd-bad); }++/* ── Section shell ─────────────────────────────────────────────────────────── */+.sd-section { background: var(--sd-panel); border: 1px solid var(--sd-line); border-radius: 20px; padding: clamp(1rem, 2.2vw, 1.5rem); margin-bottom: 1.5rem; }+.sd-section-h { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 1.1rem; flex-wrap: wrap; }+.sd-section-h h2 { font-size: 1.05rem; font-weight: 700; letter-spacing: -0.01em; margin: 0; }+.sd-section-h p { margin: 3px 0 0; font-size: 12.5px; color: var(--sd-dim); }+.sd-section-meta { font-size: 12px; color: var(--sd-faint); display: flex; align-items: center; gap: 10px; }++/* ── Gallery ───────────────────────────────────────────────────────────────── */+.sd-gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 14px; }+.sd-card {+ background: linear-gradient(180deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.015));+ border: 1px solid var(--sd-line); border-radius: 16px; overflow: hidden;+ transition: border-color .2s, transform .25s var(--sd-ease), box-shadow .25s; display: flex; flex-direction: column;+ animation: sd-rise .5s var(--sd-ease) both;+}+.sd-card:hover { border-color: rgba(124, 92, 255, 0.4); transform: translateY(-4px); box-shadow: 0 22px 48px -26px rgba(124, 92, 255, 0.55); }+.sd-card-view { position: relative; aspect-ratio: 3 / 4; background: radial-gradient(120% 90% at 50% 12%, rgba(124, 92, 255, 0.14), #0a0a12 70%); }+.sd-card model-viewer { width: 100%; height: 100%; --poster-color: transparent; background: transparent; }+.sd-card-load { position: absolute; inset: 0; display: grid; place-items: center; color: var(--sd-faint); font-size: 12px; }+.sd-chip { position: absolute; top: 9px; left: 9px; font-size: 10.5px; font-weight: 700; letter-spacing: .03em; padding: 3px 9px; border-radius: 999px; background: rgba(47, 191, 113, 0.16); color: #6ee7a8; border: 1px solid rgba(47, 191, 113, 0.28); backdrop-filter: blur(6px); }+.sd-chip.body { left: auto; right: 9px; background: rgba(124, 92, 255, 0.16); color: var(--sd-accent-2); border-color: rgba(124, 92, 255, 0.3); text-transform: capitalize; }+.sd-card-body { padding: 11px 13px 13px; display: flex; align-items: center; justify-content: space-between; gap: 8px; border-top: 1px solid var(--sd-line); }+.sd-card-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.sd-card-sub { font-size: 11px; color: var(--sd-faint); margin-top: 1px; }+.sd-card-open { color: var(--sd-dim); font-size: 12px; text-decoration: none; padding: 5px 9px; border-radius: 8px; border: 1px solid var(--sd-line-2); transition: color .15s, border-color .15s, background .15s; flex-shrink: 0; }+.sd-card-open:hover { color: #fff; border-color: var(--sd-accent-2); background: var(--sd-panel-2); }++/* ── Flags panel ───────────────────────────────────────────────────────────── */+.sd-flags { display: grid; gap: 10px; }+.sd-flag { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 14px 16px; background: var(--sd-panel); border: 1px solid var(--sd-line); border-radius: 14px; transition: border-color .2s; }+.sd-flag:hover { border-color: var(--sd-line-2); }+.sd-flag-txt strong { font-size: 13.5px; font-weight: 650; }+.sd-flag-txt code { font-size: 11px; color: var(--sd-accent-2); background: rgba(124, 92, 255, 0.1); padding: 1px 6px; border-radius: 5px; margin-left: 6px; }+.sd-flag-txt small { display: block; margin-top: 4px; font-size: 12px; color: var(--sd-dim); max-width: 62ch; }+.sd-flag-src { font-size: 10.5px; color: var(--sd-faint); margin-left: 6px; }++/* Small toggle (flags) */+.sd-toggle { position: relative; width: 44px; height: 26px; border-radius: 999px; background: rgba(255, 255, 255, 0.1); border: none; cursor: pointer; flex-shrink: 0; transition: background .22s var(--sd-ease); }+.sd-toggle::after { content: ''; position: absolute; top: 3px; left: 3px; width: 20px; height: 20px; border-radius: 50%; background: #fff; transition: transform .24s var(--sd-ease); box-shadow: 0 2px 5px rgba(0, 0, 0, 0.4); }+.sd-toggle.on { background: linear-gradient(135deg, var(--sd-accent), #6144e0); }+.sd-toggle.on::after { transform: translateX(18px); }+.sd-toggle[aria-busy='true'] { opacity: .5; pointer-events: none; }++/* ── Empty / skeleton ──────────────────────────────────────────────────────── */+.sd-empty { text-align: center; padding: 3rem 1rem; color: var(--sd-dim); }+.sd-empty-mark { font-size: 34px; margin-bottom: 10px; opacity: .5; }+.sd-empty strong { display: block; font-size: 14.5px; color: var(--sd-text); margin-bottom: 4px; }+.sd-skel { border-radius: 16px; background: linear-gradient(100deg, rgba(255, 255, 255, 0.03) 30%, rgba(255, 255, 255, 0.07) 50%, rgba(255, 255, 255, 0.03) 70%); background-size: 220% 100%; animation: sd-shimmer 1.3s infinite; aspect-ratio: 3 / 4; }++/* ── Toast + modal ─────────────────────────────────────────────────────────── */+.sd-toast { position: fixed; bottom: 22px; left: 50%; transform: translateX(-50%) translateY(20px); background: #14141c; border: 1px solid var(--sd-line-2); color: var(--sd-text); padding: 12px 18px; border-radius: 12px; font-size: 13px; box-shadow: var(--sd-shadow); opacity: 0; pointer-events: none; transition: opacity .25s, transform .25s var(--sd-ease); z-index: 60; }+.sd-toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }+.sd-toast.good { border-color: rgba(47, 191, 113, 0.4); }+.sd-toast.bad { border-color: rgba(248, 113, 113, 0.4); }++.sd-modal { position: fixed; inset: 0; background: rgba(4, 4, 8, 0.72); backdrop-filter: blur(4px); display: grid; place-items: center; padding: 1.25rem; z-index: 70; opacity: 0; pointer-events: none; transition: opacity .2s; }+.sd-modal.show { opacity: 1; pointer-events: auto; }+.sd-modal-card { width: min(440px, 100%); background: #101017; border: 1px solid var(--sd-line-2); border-radius: 18px; padding: 26px; box-shadow: var(--sd-shadow); transform: scale(.96); transition: transform .22s var(--sd-ease); }+.sd-modal.show .sd-modal-card { transform: scale(1); }+.sd-modal-card h3 { margin: 0 0 8px; font-size: 1.2rem; font-weight: 800; letter-spacing: -0.02em; }+.sd-modal-card p { margin: 0 0 18px; color: var(--sd-dim); font-size: 13.5px; }+.sd-modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 4px; }++/* ── Keyframes ─────────────────────────────────────────────────────────────── */+@keyframes sd-rise { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }+@keyframes sd-pulse { 0% { box-shadow: 0 0 0 0 rgba(47, 191, 113, 0.55); } 70% { box-shadow: 0 0 0 8px rgba(47, 191, 113, 0); } 100% { box-shadow: 0 0 0 0 rgba(47, 191, 113, 0); } }+@keyframes sd-shimmer { to { background-position: -220% 0; } }++@media (prefers-reduced-motion: reduce) { * { animation-duration: .001ms !important; transition-duration: .001ms !important; } }+@media (max-width: 640px) { .sd-hero { flex-direction: column; align-items: flex-start; } .sd-hero-r { width: 100%; justify-content: space-between; } }diff --git a/src/admin-seeder.js b/src/admin-seeder.jsnew file mode 100644index 000000000..c65dc0a4f--- /dev/null+++ b/src/admin-seeder.js@@ -0,0 +1,320 @@+// /admin/seeder — Avatar Seeder control room controller.+//+// Talks to /api/admin/seeder (state + arm/disarm + run-now) and /api/admin/flags+// (generic runtime flags), both admin-session OR Bearer-secret. The secret lives+// in sessionStorage + memory, sent as `Authorization: Bearer`, never in a URL,+// cleared on any 401. Every API-sourced string is escaped before it touches the+// DOM. The 3D gallery uses <model-viewer> (loaded in the page head).++const SEEDER_API = '/api/admin/seeder';+const FLAGS_API = '/api/admin/flags';+const SECRET_KEY = 'admin_secret';+const REFRESH_MS = 10_000;++let secret = sessionStorage.getItem(SECRET_KEY) || '';+let refreshTimer = null;+let tickTimer = null;+let state = null; // last GET /api/admin/seeder payload+let busyArm = false;++const $ = (id) => document.getElementById(id);+const esc = (s) =>+ String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++// ── API ────────────────────────────────────────────────────────────────────+async function api(url, { method = 'GET', body } = {}) {+ const r = await fetch(url, {+ method,+ headers: { 'content-type': 'application/json', authorization: `Bearer ${secret}` },+ credentials: 'same-origin',+ body: body ? JSON.stringify(body) : undefined,+ });+ if (r.status === 401 || r.status === 403) {+ secret = '';+ sessionStorage.removeItem(SECRET_KEY);+ stopRefresh();+ showGate('Secret rejected. Try again.');+ throw new Error('unauthorized');+ }+ const j = await r.json().catch(() => null);+ if (!r.ok) throw new Error(j?.error_description || j?.error || `HTTP ${r.status}`);+ return j;+}++// ── Gate ───────────────────────────────────────────────────────────────────+function showGate(err = '') {+ $('sd-root').setAttribute('aria-busy', 'false');+ $('sd-panel').hidden = true;+ $('sd-gate').hidden = false;+ $('sd-gate-err').textContent = err;+ setTimeout(() => $('sd-secret').focus(), 40);+}+function showPanel() {+ $('sd-gate').hidden = true;+ $('sd-panel').hidden = false;+ $('sd-root').setAttribute('aria-busy', 'false');+}++$('sd-gate-form').addEventListener('submit', async (e) => {+ e.preventDefault();+ const val = $('sd-secret').value.trim();+ if (!val) return;+ secret = val;+ try {+ await refresh();+ sessionStorage.setItem(SECRET_KEY, secret);+ $('sd-secret').value = '';+ showPanel();+ startRefresh();+ } catch {+ /* api() already surfaced the gate error */+ }+});++// ── Render ─────────────────────────────────────────────────────────────────+function fmtAgo(iso) {+ if (!iso) return '—';+ const s = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);+ if (s < 60) return `${s}s ago`;+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;+ return `${Math.floor(s / 86400)}d ago`;+}++function render(d) {+ state = d;+ const on = !!d.flag?.enabled;++ // Hero status+ const dot = $('sd-dot');+ dot.className = 'sd-dot ' + (d.circuit?.open ? 'err' : on ? 'on' : 'off');+ $('sd-state-word').textContent = d.circuit?.open ? 'Paused' : on ? 'Live' : 'Disabled';++ // Arm switch+ const arm = $('sd-arm');+ arm.classList.toggle('on', on);+ arm.setAttribute('aria-checked', on ? 'true' : 'false');+ $('sd-arm-lbl').textContent = on ? 'Live' : 'Disabled';++ // Source hint+ const src = d.flag?.source === 'db' ? 'DB flag' : 'env default';+ $('sd-sub').textContent = on+ ? `Live — forging one rigged Avaturn avatar every ${d.cadence_seconds || 60}s (${src}).`+ : `Idle. Arm to forge a rigged, walk-ready Avaturn avatar every ${d.cadence_seconds || 60}s. Controlled by ${src}.`;++ // Breaker+ const breaker = $('sd-breaker');+ if (d.circuit?.open) {+ breaker.hidden = false;+ const mins = Math.max(1, Math.ceil((d.circuit.open_until - Date.now()) / 60000));+ $('sd-breaker-txt').innerHTML = `Circuit breaker tripped after <b>${d.circuit.failures}</b> failures — auto-retries in ~${mins}m. Exports are paused meanwhile.`;+ } else {+ breaker.hidden = true;+ }++ // Stats+ const s = d.stats || {};+ $('sd-s-24h').textContent = (s.last_24h ?? 0).toLocaleString();+ $('sd-s-24h-sub').textContent = `${s.last_hour ?? 0} in last hour`;+ $('sd-s-total').textContent = (s.total ?? 0).toLocaleString();+ $('sd-s-total-sub').textContent = `${s.last_7d ?? 0} this week`;+ const rig = $('sd-s-rig');+ rig.textContent = `${s.rigged_pct ?? 0}%`;+ rig.className = (s.rigged_pct >= 95 ? 'good' : s.rigged_pct >= 60 ? 'warn' : s.total ? 'bad' : '');+ $('sd-s-last').textContent = fmtAgo(s.last_at);+ $('sd-s-last-sub').textContent = s.last_at ? new Date(s.last_at).toLocaleString() : 'no exports yet';+ renderNextTick();++ renderGallery(d.recent || []);+}++function renderNextTick() {+ const el = $('sd-s-next');+ if (!el || !state) return;+ if (!state.flag?.enabled || state.circuit?.open) {+ el.textContent = '—';+ $('sd-s-next-sub').textContent = state.circuit?.open ? 'paused' : 'disarmed';+ return;+ }+ const secs = 60 - (new Date().getSeconds());+ el.textContent = `${secs}s`;+ $('sd-s-next-sub').textContent = 'cadence 60s';+}++function renderGallery(recent) {+ const wrap = $('sd-gallery');+ $('sd-gallery-meta').textContent = recent.length ? `${recent.length} newest` : '';+ if (!recent.length) {+ wrap.innerHTML = `<div class="sd-empty" style="grid-column:1/-1">+ <div class="sd-empty-mark">◎</div>+ <strong>No seeded avatars yet</strong>+ Arm the seeder — the first rigged Avaturn avatar lands within a minute.+ </div>`;+ return;+ }+ wrap.innerHTML = recent+ .map((a, i) => {+ if (!a.glb_url) return '';+ const name = esc(a.name || 'Avatar');+ const joints = a.joints ? `${a.joints} bones` : 'rigged';+ const body = a.body_type ? `<span class="sd-chip body">${esc(a.body_type)}</span>` : '';+ const open = a.profile_url+ ? `<a class="sd-card-open" href="${esc(a.profile_url)}" target="_blank" rel="noopener" title="Open profile">↗</a>`+ : `<a class="sd-card-open" href="${esc(a.glb_url)}" target="_blank" rel="noopener" title="Open model">↗</a>`;+ return `<article class="sd-card" style="animation-delay:${Math.min(i * 40, 400)}ms">+ <div class="sd-card-view">+ <span class="sd-chip">✓ ${esc(joints)}</span>${body}+ <div class="sd-card-load">Loading…</div>+ <model-viewer+ src="${esc(a.glb_url)}"+ camera-controls auto-rotate rotation-per-second="16deg"+ interaction-prompt="none" disable-tap disable-zoom+ shadow-intensity="0.6" exposure="1.05"+ camera-orbit="12deg 86deg 2.5m" camera-target="0m 0.95m 0m" field-of-view="24deg"+ loading="lazy" reveal="auto"+ onload="this.previousElementSibling.style.display='none'"></model-viewer>+ </div>+ <div class="sd-card-body">+ <div style="min-width:0">+ <div class="sd-card-name">${name}</div>+ <div class="sd-card-sub">${fmtAgo(a.created_at)}</div>+ </div>+ ${open}+ </div>+ </article>`;+ })+ .join('');+}++function renderFlags(flags) {+ const wrap = $('sd-flags');+ if (!flags?.length) {+ wrap.innerHTML = `<div class="sd-empty"><strong>No flags registered</strong></div>`;+ return;+ }+ wrap.innerHTML = flags+ .map((f) => {+ const src = f.exists ? 'DB' : f.env ? `env: ${esc(f.env)}` : 'default';+ return `<div class="sd-flag">+ <div class="sd-flag-txt">+ <strong>${esc(f.key)}</strong><span class="sd-flag-src">${esc(src)}</span>+ <small>${esc(f.description || '')}</small>+ </div>+ <button class="sd-toggle ${f.enabled ? 'on' : ''}" data-flag="${esc(f.key)}"+ role="switch" aria-checked="${f.enabled}" aria-label="Toggle ${esc(f.key)}"></button>+ </div>`;+ })+ .join('');+ wrap.querySelectorAll('.sd-toggle').forEach((btn) => {+ btn.addEventListener('click', () => toggleFlag(btn));+ });+}++// ── Actions ────────────────────────────────────────────────────────────────+async function refresh() {+ const [d, flags] = await Promise.all([+ api(SEEDER_API),+ api(FLAGS_API).catch(() => ({ flags: [] })),+ ]);+ render(d);+ renderFlags(flags.flags || []);+}++async function setEnabled(enabled) {+ if (busyArm) return;+ busyArm = true;+ $('sd-arm').setAttribute('aria-busy', 'true');+ try {+ await api(SEEDER_API, { method: 'POST', body: { enabled } });+ toast(enabled ? 'Seeder armed — first avatar within a minute' : 'Seeder disarmed', 'good');+ await refresh();+ } catch (e) {+ toast(e.message || 'Toggle failed', 'bad');+ } finally {+ busyArm = false;+ $('sd-arm').setAttribute('aria-busy', 'false');+ }+}++async function toggleFlag(btn) {+ const key = btn.dataset.flag;+ const next = !btn.classList.contains('on');+ btn.setAttribute('aria-busy', 'true');+ try {+ await api(FLAGS_API, { method: 'POST', body: { key, enabled: next } });+ toast(`${key} ${next ? 'enabled' : 'disabled'}`, 'good');+ await refresh();+ } catch (e) {+ toast(e.message || 'Flag update failed', 'bad');+ btn.setAttribute('aria-busy', 'false');+ }+}++// Arm switch: confirm before going live; disarm is immediate.+$('sd-arm').addEventListener('click', () => {+ if (busyArm) return;+ const on = $('sd-arm').classList.contains('on');+ if (on) return setEnabled(false);+ openModal();+});+$('sd-modal-cancel').addEventListener('click', closeModal);+$('sd-modal-go').addEventListener('click', () => { closeModal(); setEnabled(true); });+$('sd-modal').addEventListener('click', (e) => { if (e.target === $('sd-modal')) closeModal(); });++function openModal() { $('sd-modal').classList.add('show'); }+function closeModal() { $('sd-modal').classList.remove('show'); }++$('sd-run').addEventListener('click', async () => {+ const btn = $('sd-run');+ btn.disabled = true;+ const label = btn.textContent;+ btn.textContent = 'Starting…';+ try {+ const r = await api(SEEDER_API, { method: 'POST', body: { action: 'run_now' } });+ toast(r.running ? 'Export running (~2 min)…' : 'Export triggered', 'good');+ setTimeout(refresh, 2500);+ } catch (e) {+ toast(e.message || 'Could not start an export', 'bad');+ } finally {+ btn.disabled = false;+ btn.textContent = label;+ }+});++// ── Toast ──────────────────────────────────────────────────────────────────+let toastTimer = null;+function toast(msg, kind = '') {+ const t = $('sd-toast');+ t.textContent = msg;+ t.className = `sd-toast show ${kind}`;+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => (t.className = 'sd-toast'), 3200);+}++// ── Refresh loop ───────────────────────────────────────────────────────────+function startRefresh() {+ stopRefresh();+ refreshTimer = setInterval(() => refresh().catch(() => {}), REFRESH_MS);+ tickTimer = setInterval(renderNextTick, 1000);+}+function stopRefresh() {+ clearInterval(refreshTimer);+ clearInterval(tickTimer);+ refreshTimer = tickTimer = null;+}+document.addEventListener('visibilitychange', () => {+ if (document.hidden) stopRefresh();+ else if (secret && !$('sd-panel').hidden) { refresh().catch(() => {}); startRefresh(); }+});++// ── Boot ───────────────────────────────────────────────────────────────────+(async function boot() {+ if (!secret) return showGate();+ try {+ await refresh();+ showPanel();+ startRefresh();+ } catch {+ /* 401 → gate already shown */+ }+})();diff --git a/src/diorama/gallery.js b/src/diorama/gallery.jsnew file mode 100644index 000000000..66a5fc9af--- /dev/null+++ b/src/diorama/gallery.js@@ -0,0 +1,109 @@+// Diorama gallery — renders the public wall of recently-forged worlds.+//+// `mountGallery` wires the `#gallery-list` grid + `#empty-state` placeholder to+// the real backend (`GET /api/diorama?list=recent`) and returns a `{ reload }`+// handle the controller calls after every save/compose. Each card is a real+// button whose 3D thumbnail is the world's first forged GLB (lazy-loaded via+// <model-viewer>, which the page already ships), so the wall is live geometry —+// never a screenshot. Degrades honestly: when persistence is off (no database)+// or the list is empty, the designed empty state explains it instead of a blank.++const LIST_URL = (limit) => `/api/diorama?list=recent&limit=${limit}`;++function esc(s) {+ return String(s ?? '').replace(+ /[<>&"]/g,+ (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[c]),+ );+}++function fmtViews(n) {+ const v = Number(n) || 0;+ if (v >= 1000) return `${(v / 1000).toFixed(1)}k views`;+ return `${v} ${v === 1 ? 'view' : 'views'}`;+}++// A single gallery card. The whole card is the button; the model-viewer thumb is+// pointer-inert so a tap always opens the world rather than orbiting the model.+function buildCard(d, onOpen) {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'dio-card';+ btn.dataset.id = d.id;+ btn.setAttribute('aria-label', `Open “${d.title || 'Untitled world'}”`);++ const thumb = d.thumbnailGlb+ ? `<div class="dio-card__thumb"><model-viewer src="${esc(d.thumbnailGlb)}" ` ++ `loading="lazy" reveal="auto" auto-rotate rotation-per-second="18deg" ` ++ `interaction-prompt="none" disable-zoom camera-orbit="35deg 78deg auto" ` ++ `shadow-intensity="0" exposure="0.9" style="pointer-events:none;--poster-color:transparent" ` ++ `aria-hidden="true"></model-viewer></div>`+ : `<div class="dio-card__thumb"></div>`;++ btn.innerHTML =+ thumb ++ `<div class="dio-card__body">` ++ `<p class="dio-card__title">${esc(d.title || 'Untitled world')}</p>` ++ `<p class="dio-card__prompt">${esc(d.prompt || '')}</p>` ++ `<div class="dio-card__foot">` ++ `<span class="dio-card__mood">${esc(d.mood || 'a little world')}</span>` ++ `<span>${d.objectCount || 0} pieces · ${fmtViews(d.views)}</span>` ++ `</div></div>`;++ btn.addEventListener('click', () => {+ if (typeof onOpen === 'function' && d.id) onOpen(d.id);+ });+ return btn;+}++/**+ * @param {{ listEl: HTMLElement, emptyEl?: HTMLElement|null, onOpen?: (id:string)=>void, limit?: number }} opts+ * @returns {{ reload: () => Promise<void> }}+ */+export function mountGallery({ listEl, emptyEl = null, onOpen, limit = 24 } = {}) {+ if (!listEl) return { reload: async () => {} };++ function setEmpty(message) {+ listEl.innerHTML = '';+ listEl.setAttribute('aria-busy', 'false');+ if (!emptyEl) return;+ if (message) emptyEl.textContent = message;+ emptyEl.hidden = false;+ }++ let loading = false;+ async function reload() {+ if (loading) return;+ loading = true;+ listEl.setAttribute('aria-busy', 'true');+ try {+ const res = await fetch(LIST_URL(limit), { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = await res.json();+ const dioramas = Array.isArray(data.dioramas) ? data.dioramas : [];++ if (!dioramas.length) {+ setEmpty(+ data.storage === false+ ? 'The public wall lights up once worlds are saved. Compose one above and hit Save & share to be the first.'+ : 'No worlds yet — compose one above and it lands here for everyone to explore.',+ );+ return;+ }++ if (emptyEl) emptyEl.hidden = true;+ const frag = document.createDocumentFragment();+ for (const d of dioramas) frag.appendChild(buildCard(d, onOpen));+ listEl.innerHTML = '';+ listEl.appendChild(frag);+ listEl.setAttribute('aria-busy', 'false');+ } catch {+ // Network/parse failure is non-fatal — the composer above still works.+ setEmpty('Couldn’t load the gallery just now. Your own worlds still forge and save fine.');+ } finally {+ loading = false;+ }+ }++ return { reload };+}diff --git a/src/diorama/share.js b/src/diorama/share.jsnew file mode 100644index 000000000..ea182113e--- /dev/null+++ b/src/diorama/share.js@@ -0,0 +1,105 @@+// Diorama share sheet — turns a saved world into a shareable 3D postcard.+//+// `openShare` populates the (already-in-DOM, `#share-panel`) sheet with the real+// permalink the save endpoint returned and wires its three actions: copy the+// link, share to X, and copy an embeddable <iframe> snippet. main.js reveals the+// panel; this module owns its contents and handlers. Idempotent — safe to call+// again for a new world; handlers are re-pointed, not stacked.++/** Resolve a possibly-relative permalink to an absolute URL for sharing/embedding. */+function absolute(url) {+ try {+ return new URL(url, window.location.origin).href;+ } catch {+ return String(url || window.location.href);+ }+}++// Copy `text` to the clipboard, with a graceful fallback for insecure contexts.+async function copyText(text) {+ try {+ if (navigator.clipboard && window.isSecureContext) {+ await navigator.clipboard.writeText(text);+ return true;+ }+ } catch {+ /* fall through to legacy path */+ }+ try {+ const ta = document.createElement('textarea');+ ta.value = text;+ ta.setAttribute('readonly', '');+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ const ok = document.execCommand('copy');+ document.body.removeChild(ta);+ return ok;+ } catch {+ return false;+ }+}++// Flash a "Copied" (or "Copied!") confirmation on a button, then restore its label.+const flashTimers = new WeakMap();+function flash(btn, ok) {+ if (!btn) return;+ if (!btn.dataset.label) btn.dataset.label = btn.textContent;+ clearTimeout(flashTimers.get(btn));+ btn.textContent = ok ? 'Copied ✓' : 'Copy failed';+ btn.classList.toggle('is-copied', ok);+ flashTimers.set(+ btn,+ setTimeout(() => {+ btn.textContent = btn.dataset.label;+ btn.classList.remove('is-copied');+ }, 1600),+ );+}++function embedSnippet(url) {+ return (+ `<iframe src="${url}" width="480" height="360" frameborder="0" ` ++ `allow="fullscreen; xr-spatial-tracking" loading="lazy" ` ++ `title="A 3D diorama on three.ws" style="border-radius:12px;border:0"></iframe>`+ );+}++/**+ * @param {{ diorama?: { title?: string, prompt?: string }, url: string }} opts+ */+export function openShare({ diorama = {}, url } = {}) {+ const href = absolute(url);+ const link = document.getElementById('share-link');+ const copyBtn = document.getElementById('share-copy');+ const xBtn = document.getElementById('share-x');+ const embedBtn = document.getElementById('share-embed');++ if (link) {+ link.value = href;+ // Select-all on focus so a manual copy is one tap.+ link.onfocus = () => link.select();+ }++ if (copyBtn) {+ copyBtn.onclick = async () => flash(copyBtn, await copyText(href));+ }++ if (xBtn) {+ xBtn.onclick = () => {+ const what = diorama.title || diorama.prompt || 'a little 3D world';+ const text = `I spoke a little world into being on three.ws — “${what}”. Explore it in 3D:`;+ const intent =+ 'https://twitter.com/intent/tweet?text=' ++ encodeURIComponent(text) ++ '&url=' ++ encodeURIComponent(href);+ window.open(intent, '_blank', 'noopener,noreferrer');+ };+ }++ if (embedBtn) {+ embedBtn.onclick = async () => flash(embedBtn, await copyText(embedSnippet(href)));+ }+}diff --git a/src/labor-market.css b/src/labor-market.cssindex 02773b97f..fcccfe8c5 100644--- a/src/labor-market.css+++ b/src/labor-market.css@@ -5,20 +5,54 @@:root {--lm-gap: var(--space-md, 16px);- --lm-radius: var(--radius-lg, 14px);+ --lm-radius: var(--radius-lg, 16px);--lm-radius-sm: var(--radius-md, 10px);+ --lm-accent: var(--success, #4ade80);+ --lm-accent-soft: color-mix(in srgb, var(--lm-accent) 14%, transparent);+ --lm-glass: var(--surface-glass, linear-gradient(180deg, rgba(20, 21, 28, 0.7), rgba(14, 15, 22, 0.5)));}.lm-shell {- max-width: 1180px;+ max-width: 1200px;margin: 0 auto;- padding: clamp(20px, 4vw, 48px) clamp(14px, 3vw, 28px) 80px;+ padding: clamp(20px, 4vw, 48px) clamp(14px, 3vw, 28px) 96px;font-family: var(--font-body, Inter, system-ui, sans-serif);color: var(--ink, #e7e7ea);}/* ── Hero ──────────────────────────────────────────────────────────────── */-.lm-hero { margin-bottom: clamp(20px, 3vw, 32px); }+.lm-hero {+ position: relative;+ display: grid;+ grid-template-columns: 1.35fr 1fr;+ gap: clamp(20px, 3vw, 40px);+ align-items: center;+ margin-bottom: clamp(22px, 3vw, 34px);+ padding: clamp(20px, 3vw, 34px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1));+ border-radius: calc(var(--lm-radius) + 4px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ overflow: hidden;+ isolation: isolate;+}+.lm-aurora {+ position: absolute;+ inset: -40% -10% auto -10%;+ height: 150%;+ z-index: -1;+ background:+ radial-gradient(42% 55% at 18% 20%, color-mix(in srgb, var(--lm-accent) 26%, transparent), transparent 70%),+ radial-gradient(38% 50% at 82% 12%, color-mix(in srgb, var(--accent, #6366f1) 22%, transparent), transparent 72%),+ radial-gradient(46% 60% at 65% 90%, color-mix(in srgb, var(--warn, #fbbf24) 12%, transparent), transparent 70%);+ filter: blur(38px) saturate(1.1);+ opacity: 0.85;+ animation: lm-aurora 18s ease-in-out infinite alternate;+}+@keyframes lm-aurora {+ 0% { transform: translate3d(0, 0, 0) scale(1); }+ 100% { transform: translate3d(2%, 3%, 0) scale(1.08); }+}+.lm-hero-copy { min-width: 0; }.lm-kicker {display: inline-flex;align-items: center;@@ -31,42 +65,48 @@}.lm-live-dot {width: 8px; height: 8px; border-radius: 50%;- background: var(--success, #4ade80);- box-shadow: 0 0 0 0 color-mix(in srgb, var(--success, #4ade80) 60%, transparent);+ background: var(--lm-accent);+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--lm-accent) 60%, transparent);animation: lm-pulse 1.8s ease infinite;}@keyframes lm-pulse {- 0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--success, #4ade80) 55%, transparent); }+ 0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--lm-accent) 55%, transparent); }70% { box-shadow: 0 0 0 7px transparent; }}.lm-title {margin: 0 0 12px;font-family: var(--font-display, 'Space Grotesk', sans-serif);- font-size: clamp(30px, 5vw, 52px);+ font-size: clamp(30px, 5vw, 54px);line-height: 1.02;letter-spacing: -0.02em;color: var(--ink-bright, #fff);+ background: linear-gradient(180deg, var(--ink-bright, #fff), color-mix(in srgb, var(--ink-bright, #fff) 72%, var(--lm-accent)));+ -webkit-background-clip: text; background-clip: text;+ -webkit-text-fill-color: transparent;}.lm-sub {- max-width: 64ch;+ max-width: 62ch;margin: 0 0 22px;- font-size: clamp(14px, 1.6vw, 17px);- line-height: 1.55;+ font-size: clamp(14px, 1.5vw, 16px);+ line-height: 1.6;color: var(--ink-dim, #9aa);}.lm-sub strong { color: var(--ink-bright, #fff); font-weight: 600; }.lm-summary {display: grid;- grid-template-columns: repeat(4, minmax(0, 1fr));- gap: var(--lm-gap);- margin: 0 0 22px;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 12px;+ margin: 0;}.lm-summary-cell {- padding: 14px 16px;+ position: relative;+ padding: 14px 16px 16px;border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1));border-radius: var(--lm-radius-sm);- background: var(--surface-1, rgba(255, 255, 255, 0.03));+ background: var(--lm-glass);+ backdrop-filter: blur(8px);+ overflow: hidden;}.lm-summary-cell dt {margin: 0 0 6px;@@ -78,21 +118,36 @@.lm-summary-cell dd {margin: 0;font-family: var(--font-display, sans-serif);- font-size: clamp(18px, 2.4vw, 26px);+ font-size: clamp(20px, 2.4vw, 28px);font-weight: 600;color: var(--ink-bright, #fff);+ font-variant-numeric: tabular-nums;}-.lm-good { color: var(--success, #4ade80) !important; }+.lm-spark { position: absolute; right: 12px; bottom: 12px; opacity: 0.9; pointer-events: none; }+.lm-good { color: var(--lm-accent) !important; }.lm-bad { color: var(--danger, #f87171) !important; }+.lm-summary-escrow.is-live { border-color: color-mix(in srgb, var(--lm-accent) 40%, transparent); }+.lm-summary-escrow.is-live dd::before {+ content: ''; display: inline-block; width: 7px; height: 7px; margin-right: 7px; border-radius: 50%;+ background: var(--lm-accent); box-shadow: 0 0 8px var(--lm-accent); vertical-align: middle;+}-.lm-hero-actions { display: flex; gap: 10px; flex-wrap: wrap; }+.lm-hero-actions { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }+.lm-mod-badge {+ display: inline-flex; align-items: center; gap: 5px;+ padding: 6px 11px; border-radius: var(--radius-pill, 999px);+ font: 700 11px/1 var(--font-mono, monospace); text-transform: uppercase; letter-spacing: 0.05em;+ background: color-mix(in srgb, var(--warn, #fbbf24) 16%, transparent);+ color: var(--warn, #fbbf24);+ border: 1px solid color-mix(in srgb, var(--warn, #fbbf24) 34%, transparent);+}/* ── Buttons ───────────────────────────────────────────────────────────── */.lm-btn {display: inline-flex;align-items: center;justify-content: center;- gap: 6px;+ gap: 7px;padding: 10px 18px;border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.18));border-radius: var(--radius-pill, 999px);@@ -100,21 +155,36 @@color: var(--ink-bright, #fff);font: 600 14px/1 var(--font-body, sans-serif);cursor: pointer;+ white-space: nowrap;transition: transform var(--duration-fast, 140ms) var(--ease-out, ease),- background var(--duration-fast, 140ms) ease, border-color var(--duration-fast, 140ms) ease;+ background var(--duration-fast, 140ms) ease, border-color var(--duration-fast, 140ms) ease,+ box-shadow var(--duration-fast, 140ms) ease;}.lm-btn:hover { background: var(--surface-3, rgba(255, 255, 255, 0.09)); transform: translateY(-1px); }.lm-btn:active { transform: translateY(0); }-.lm-btn:focus-visible { outline: 2px solid var(--success, #4ade80); outline-offset: 2px; }+.lm-btn:focus-visible { outline: 2px solid var(--lm-accent); outline-offset: 2px; }.lm-btn:disabled { opacity: 0.55; cursor: progress; transform: none; }.lm-btn-primary {- background: var(--success, #4ade80);- border-color: var(--success, #4ade80);+ background: var(--lm-accent);+ border-color: var(--lm-accent);color: #06140b;+ box-shadow: 0 4px 18px -6px color-mix(in srgb, var(--lm-accent) 60%, transparent);}-.lm-btn-primary:hover { background: color-mix(in srgb, var(--success, #4ade80) 88%, #fff); }+.lm-btn-primary:hover { background: color-mix(in srgb, var(--lm-accent) 88%, #fff); box-shadow: 0 6px 22px -6px color-mix(in srgb, var(--lm-accent) 70%, transparent); }+.lm-btn-danger { background: color-mix(in srgb, var(--danger, #f87171) 16%, transparent); border-color: color-mix(in srgb, var(--danger, #f87171) 40%, transparent); color: var(--danger, #f87171); }+.lm-btn-danger:hover { background: color-mix(in srgb, var(--danger, #f87171) 26%, transparent); }+.lm-btn-ghost { padding: 10px; width: 40px; }.lm-btn-sm { padding: 6px 12px; font-size: 12px; }+.lm-icon-btn {+ display: inline-flex; align-items: center; justify-content: center;+ width: 34px; height: 34px; border: 0; border-radius: 50%;+ background: var(--surface-3, rgba(255, 255, 255, 0.08)); color: var(--ink-dim, #9aa);+ cursor: pointer; transition: background 140ms ease, color 140ms ease;+}+.lm-icon-btn:hover { background: var(--surface-2, rgba(255, 255, 255, 0.14)); color: var(--ink-bright, #fff); }+.lm-icon-btn:focus-visible { outline: 2px solid var(--lm-accent); outline-offset: 2px; }+/* ── Ticker ────────────────────────────────────────────────────────────── */.lm-ticker-wrap {margin: 0 0 24px;@@ -131,18 +201,19 @@letter-spacing: 0.05em;color: var(--ink-dim, #9aa);}-.lm-ticker { display: flex; flex-direction: column; gap: 6px; max-height: 188px; overflow-y: auto; }+.lm-ticker { display: flex; flex-direction: column; gap: 6px; max-height: 188px; overflow-y: auto; scrollbar-width: thin; }.lm-ticker-empty { margin: 4px 0; color: var(--ink-faint, #778); font-size: 13px; }.lm-flow {display: flex; align-items: center; gap: 10px;- padding: 7px 10px;- border-radius: var(--radius-sm, 6px);+ padding: 8px 11px;+ border-radius: var(--radius-sm, 8px);background: var(--surface-2, rgba(255, 255, 255, 0.04));font-size: 13px;- animation: lm-flow-in 0.3s var(--ease-out, ease) both;+ animation: lm-flow-in 0.32s var(--ease-out, ease) both;}@keyframes lm-flow-in { from { opacity: 0; transform: translateX(-6px); } to { opacity: 1; transform: none; } }-.lm-flow-amt { font: 600 13px/1 var(--font-mono, monospace); color: var(--success, #4ade80); flex: none; }+.lm-flow-amt { font: 700 13px/1 var(--font-mono, monospace); color: var(--lm-accent); flex: none; }+.lm-flow-amt span { font-size: 9px; opacity: 0.8; }.lm-flow-body { display: flex; align-items: center; gap: 6px; flex: 1; min-width: 0; flex-wrap: wrap; }.lm-flow-body a { color: var(--ink-bright, #fff); text-decoration: none; }.lm-flow-body a:hover { text-decoration: underline; }@@ -156,117 +227,183 @@.lm-flow-tx:hover { color: var(--ink-bright, #fff); }.lm-flow-time { color: var(--ink-faint, #778); font-size: 11px; flex: none; }-/* ── Controls ──────────────────────────────────────────────────────────── */-.lm-controls {+/* ── Toolbar ───────────────────────────────────────────────────────────── */+.lm-toolbar {display: flex; align-items: center; justify-content: space-between;gap: var(--lm-gap); flex-wrap: wrap; margin: 0 0 18px;+ position: sticky; top: 8px; z-index: 20;}-.lm-tabs { display: inline-flex; gap: 4px; padding: 4px; border-radius: var(--radius-pill, 999px); background: var(--surface-1, rgba(255, 255, 255, 0.04)); }+.lm-tabs { display: inline-flex; gap: 4px; padding: 4px; border-radius: var(--radius-pill, 999px); background: var(--surface-1, rgba(255, 255, 255, 0.05)); backdrop-filter: blur(10px); }.lm-tab {+ display: inline-flex; align-items: center; gap: 7px;padding: 8px 16px; border: 0; border-radius: var(--radius-pill, 999px);background: transparent; color: var(--ink-dim, #9aa);font: 600 13px/1 var(--font-body, sans-serif); cursor: pointer;transition: color var(--duration-fast, 140ms) ease, background var(--duration-fast, 140ms) ease;}.lm-tab:hover { color: var(--ink-bright, #fff); }-.lm-tab.is-active { background: var(--surface-3, rgba(255, 255, 255, 0.1)); color: var(--ink-bright, #fff); }-.lm-tab:focus-visible { outline: 2px solid var(--success, #4ade80); outline-offset: 2px; }-.lm-filters { display: flex; gap: 12px; flex-wrap: wrap; }-.lm-field-inline { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--ink-faint, #778); }-.lm-field-inline input {- width: 110px; padding: 7px 10px;+.lm-tab.is-active { background: var(--surface-3, rgba(255, 255, 255, 0.12)); color: var(--ink-bright, #fff); }+.lm-tab:focus-visible { outline: 2px solid var(--lm-accent); outline-offset: 2px; }+.lm-tab-count { font: 700 10px/1 var(--font-mono, monospace); padding: 3px 6px; border-radius: 999px; background: color-mix(in srgb, var(--ink-faint, #778) 22%, transparent); color: var(--ink-dim, #9aa); min-width: 16px; text-align: center; }+.lm-tab-count:empty { display: none; }+.lm-tab.is-active .lm-tab-count { background: var(--lm-accent-soft); color: var(--lm-accent); }++.lm-toolbar-controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }+.lm-search {+ display: inline-flex; align-items: center; gap: 8px;+ padding: 0 12px; height: 40px;border: 1px solid var(--stroke, rgba(255, 255, 255, 0.12));- border-radius: var(--radius-sm, 6px);- background: var(--surface-1, rgba(255, 255, 255, 0.03));- color: var(--ink-bright, #fff); font: 500 13px/1 var(--font-body, sans-serif);+ border-radius: var(--radius-pill, 999px);+ background: var(--surface-1, rgba(255, 255, 255, 0.04));+ color: var(--ink-faint, #778);+ transition: border-color 140ms ease;+}+.lm-search:focus-within { border-color: var(--lm-accent); }+.lm-search input { border: 0; background: transparent; color: var(--ink-bright, #fff); font: 500 14px/1 var(--font-body, sans-serif); width: 180px; outline: none; }+.lm-search input::-webkit-search-cancel-button { -webkit-appearance: none; }+.lm-kbd, .lm-help-list kbd {+ font: 600 11px/1 var(--font-mono, monospace); padding: 3px 6px; border-radius: 5px;+ background: var(--surface-3, rgba(255, 255, 255, 0.1)); color: var(--ink-faint, #778);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1));+}+.lm-select-wrap { position: relative; display: inline-flex; }+.lm-select-wrap select {+ appearance: none; height: 40px; padding: 0 32px 0 14px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.12)); border-radius: var(--radius-pill, 999px);+ background: var(--surface-1, rgba(255, 255, 255, 0.04)); color: var(--ink-bright, #fff);+ font: 600 13px/1 var(--font-body, sans-serif); cursor: pointer;+}+.lm-select-wrap::after { content: '▾'; position: absolute; right: 13px; top: 50%; transform: translateY(-50%); color: var(--ink-faint, #778); pointer-events: none; font-size: 11px; }+.lm-select-wrap select:focus-visible { outline: 2px solid var(--lm-accent); outline-offset: 2px; }++.lm-toggle {+ display: inline-flex; align-items: center; gap: 6px; height: 40px; padding: 0 15px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.12)); border-radius: var(--radius-pill, 999px);+ background: var(--surface-1, rgba(255, 255, 255, 0.04)); color: var(--ink-dim, #9aa);+ font: 600 13px/1 var(--font-body, sans-serif); cursor: pointer; user-select: none;+ transition: color 140ms ease, background 140ms ease, border-color 140ms ease;+}+.lm-toggle:hover { color: var(--ink-bright, #fff); }+.lm-toggle.is-on { background: var(--lm-accent-soft); border-color: color-mix(in srgb, var(--lm-accent) 40%, transparent); color: var(--lm-accent); }+.lm-toggle:focus-visible { outline: 2px solid var(--lm-accent); outline-offset: 2px; }+.lm-morefilters { position: relative; }+.lm-morefilters > summary { list-style: none; }+.lm-morefilters > summary::-webkit-details-marker { display: none; }+.lm-morefilters-pop {+ position: absolute; right: 0; top: calc(100% + 8px); z-index: 30;+ display: flex; flex-direction: column; gap: 12px;+ padding: 14px; width: 240px;+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.16)); border-radius: var(--lm-radius-sm);+ background: var(--surface-1, #14151a); backdrop-filter: blur(12px);+ box-shadow: 0 18px 44px rgba(0, 0, 0, 0.45);+ animation: lm-pop 0.18s var(--ease-out, ease) both;+}+.lm-field-inline { display: flex; align-items: center; gap: 8px; font: 600 12px/1 var(--font-mono, monospace); color: var(--ink-faint, #778); }+.lm-field-inline input {+ flex: 1; min-width: 0; width: 100%; padding: 8px 10px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.12)); border-radius: var(--radius-sm, 6px);+ background: var(--surface-2, rgba(255, 255, 255, 0.04)); color: var(--ink-bright, #fff); font: 500 13px/1 var(--font-body, sans-serif);}-.lm-field-inline input:focus-visible { outline: none; border-color: var(--success, #4ade80); }+.lm-field-inline input:focus-visible { outline: none; border-color: var(--lm-accent); }.lm-unit { font: 600 10px/1 var(--font-mono, monospace); color: var(--ink-faint, #778); }/* ── Board + cards ─────────────────────────────────────────────────────── */.lm-list {display: grid;- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));+ grid-template-columns: repeat(auto-fill, minmax(304px, 1fr));gap: var(--lm-gap);}.lm-card {+ position: relative;display: flex; flex-direction: column; gap: 10px;- padding: 16px;+ padding: 17px;border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1));border-radius: var(--lm-radius);background: var(--surface-1, rgba(255, 255, 255, 0.03));text-align: left;+ overflow: hidden;+}+.lm-card::before {+ content: ''; position: absolute; inset: 0 0 auto; height: 2px;+ background: linear-gradient(90deg, transparent, var(--lm-accent), transparent);+ opacity: 0; transition: opacity var(--duration-fast, 140ms) ease;}.lm-card-btn {cursor: pointer; color: inherit; font: inherit; width: 100%;transition: transform var(--duration-fast, 140ms) var(--ease-out, ease),- border-color var(--duration-fast, 140ms) ease, background var(--duration-fast, 140ms) ease;+ border-color var(--duration-fast, 140ms) ease, background var(--duration-fast, 140ms) ease,+ box-shadow var(--duration-fast, 140ms) ease;}-.lm-card-btn:hover { transform: translateY(-2px); border-color: var(--stroke-strong, rgba(255, 255, 255, 0.22)); background: var(--surface-2, rgba(255, 255, 255, 0.05)); }-.lm-card-btn:focus-visible { outline: 2px solid var(--success, #4ade80); outline-offset: 2px; }+.lm-card-btn:hover { transform: translateY(-3px); border-color: color-mix(in srgb, var(--lm-accent) 34%, var(--stroke-strong, rgba(255, 255, 255, 0.22))); background: var(--surface-2, rgba(255, 255, 255, 0.05)); box-shadow: 0 14px 34px -18px rgba(0, 0, 0, 0.7); }+.lm-card-btn:hover::before { opacity: 1; }+.lm-card-btn:focus-visible { outline: 2px solid var(--lm-accent); outline-offset: 2px; }.lm-card-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; }-.lm-reward { font: 700 16px/1 var(--font-mono, monospace); color: var(--ink-bright, #fff); }-.lm-reward span { font-size: 10px; color: var(--success, #4ade80); }-.lm-reward-lg { font-size: 22px; }-.lm-card-title { margin: 0; font-family: var(--font-display, sans-serif); font-size: 16px; font-weight: 600; color: var(--ink-bright, #fff); }-.lm-card-spec { margin: 0; font-size: 13px; line-height: 1.5; color: var(--ink-dim, #9aa); }-.lm-card-foot { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: auto; font-size: 12px; color: var(--ink-faint, #778); }+.lm-reward { font: 700 16px/1 var(--font-mono, monospace); color: var(--ink-bright, #fff); font-variant-numeric: tabular-nums; }+.lm-reward span { font-size: 10px; color: var(--lm-accent); }+.lm-reward-lg { font-size: 24px; }+.lm-card-title { margin: 0; font-family: var(--font-display, sans-serif); font-size: 16px; font-weight: 600; color: var(--ink-bright, #fff); line-height: 1.3; }+.lm-card-spec { margin: 0; font-size: 13px; line-height: 1.5; color: var(--ink-dim, #9aa); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }+.lm-card-foot { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: auto; padding-top: 4px; font-size: 12px; color: var(--ink-faint, #778); }.lm-card-meta a { color: var(--ink-dim, #9aa); text-decoration: none; }.lm-card-meta a:hover { color: var(--ink-bright, #fff); text-decoration: underline; }-.lm-card-bids { margin-left: auto; }-.lm-card-escrow { color: var(--success, #4ade80); font-size: 11px; text-decoration: none; }+.lm-card-bids { margin-left: auto; font-variant-numeric: tabular-nums; }+.lm-card-bids.is-hot { color: var(--warn, #fbbf24); font-weight: 600; }+.lm-card-escrow { color: var(--lm-accent); font-size: 11px; text-decoration: none; }+.lm-tag-mine { font: 700 9px/1 var(--font-mono, monospace); text-transform: uppercase; letter-spacing: 0.04em; padding: 3px 6px; border-radius: 4px; background: var(--lm-accent-soft); color: var(--lm-accent); }.lm-chip {font: 600 11px/1 var(--font-mono, monospace);padding: 4px 8px; border-radius: var(--radius-sm, 6px);- background: color-mix(in srgb, var(--success, #4ade80) 14%, transparent);- color: var(--success, #4ade80);+ background: var(--lm-accent-soft);+ color: var(--lm-accent);}.lm-chip-muted { background: var(--surface-3, rgba(255, 255, 255, 0.08)); color: var(--ink-faint, #778); }/* Status pills */.lm-status { font: 700 10px/1 var(--font-mono, monospace); text-transform: uppercase; letter-spacing: 0.05em; padding: 4px 8px; border-radius: var(--radius-sm, 6px); }-.lm-status-open { background: color-mix(in srgb, var(--success, #4ade80) 16%, transparent); color: var(--success, #4ade80); }-.lm-status-awarded, .lm-status-working, .lm-status-verifying { background: color-mix(in srgb, var(--warn, #fbbf24) 16%, transparent); color: var(--warn, #fbbf24); }-.lm-status-settled { background: color-mix(in srgb, var(--success, #4ade80) 18%, transparent); color: var(--success, #4ade80); }+.lm-status-open { background: color-mix(in srgb, var(--lm-accent) 16%, transparent); color: var(--lm-accent); }+.lm-status-awarded, .lm-status-working, .lm-status-verifying, .lm-status-delivered { background: color-mix(in srgb, var(--warn, #fbbf24) 16%, transparent); color: var(--warn, #fbbf24); }+.lm-status-settled { background: color-mix(in srgb, var(--lm-accent) 18%, transparent); color: var(--lm-accent); }.lm-status-failed, .lm-status-refunded, .lm-status-cancelled { background: color-mix(in srgb, var(--danger, #f87171) 16%, transparent); color: var(--danger, #f87171); }/* Skeletons */.lm-skel { pointer-events: none; }-.lm-skel-line { height: 12px; border-radius: 6px; background: var(--surface-3, rgba(255, 255, 255, 0.08)); animation: lm-skel 1.4s ease infinite; }+.lm-skel-line { height: 12px; border-radius: 6px; background: linear-gradient(90deg, var(--surface-3, rgba(255, 255, 255, 0.08)), var(--surface-2, rgba(255, 255, 255, 0.04)), var(--surface-3, rgba(255, 255, 255, 0.08))); background-size: 200% 100%; animation: lm-shimmer 1.5s ease infinite; }.lm-skel-line.w90 { width: 90%; } .lm-skel-line.w60 { width: 60%; } .lm-skel-line.w40 { width: 40%; }-@keyframes lm-skel { 0%, 100% { opacity: 0.4; } 50% { opacity: 0.75; } }+@keyframes lm-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }/* Empty / state */-.lm-empty { grid-column: 1 / -1; text-align: center; padding: 48px 20px; border: 1px dashed var(--stroke, rgba(255, 255, 255, 0.14)); border-radius: var(--lm-radius); background: var(--surface-1, rgba(255, 255, 255, 0.02)); }-.lm-empty-mark { font-size: 34px; color: var(--ink-faint, #778); margin-bottom: 10px; }+.lm-empty { grid-column: 1 / -1; text-align: center; padding: 56px 20px; border: 1px dashed var(--stroke, rgba(255, 255, 255, 0.14)); border-radius: var(--lm-radius); background: var(--surface-1, rgba(255, 255, 255, 0.02)); }+.lm-empty-mark { font-size: 38px; color: var(--ink-faint, #778); margin-bottom: 10px; opacity: 0.7; }.lm-empty h3 { margin: 0 0 8px; font-family: var(--font-display, sans-serif); color: var(--ink-bright, #fff); }.lm-empty p { margin: 0 auto 16px; max-width: 46ch; color: var(--ink-dim, #9aa); font-size: 14px; line-height: 1.5; }.lm-state { margin-top: 12px; }/* ── Explain steps ─────────────────────────────────────────────────────── */-.lm-explain { margin-top: 40px; padding: 24px; border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1)); border-radius: var(--lm-radius); background: var(--surface-1, rgba(255, 255, 255, 0.03)); }-.lm-explain h2 { margin: 0 0 16px; font-family: var(--font-display, sans-serif); font-size: 20px; color: var(--ink-bright, #fff); }-.lm-steps { margin: 0; padding-left: 20px; display: grid; gap: 10px; }-.lm-steps li { color: var(--ink-dim, #9aa); font-size: 14px; line-height: 1.5; }+.lm-explain { margin-top: 44px; padding: clamp(20px, 3vw, 30px); border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1)); border-radius: var(--lm-radius); background: var(--surface-1, rgba(255, 255, 255, 0.03)); }+.lm-explain h2 { margin: 0 0 18px; font-family: var(--font-display, sans-serif); font-size: 21px; color: var(--ink-bright, #fff); }+.lm-steps { margin: 0; padding: 0; list-style: none; display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; }+.lm-steps li { display: flex; gap: 12px; color: var(--ink-dim, #9aa); font-size: 14px; line-height: 1.5; }.lm-steps strong { color: var(--ink-bright, #fff); }+.lm-step-n { flex: none; width: 26px; height: 26px; display: grid; place-items: center; border-radius: 50%; background: var(--lm-accent-soft); color: var(--lm-accent); font: 700 12px/1 var(--font-mono, monospace); }/* ── Modals + drawer ───────────────────────────────────────────────────── */.lm-modal, .lm-drawer { position: fixed; inset: 0; z-index: 1000; display: flex; }.lm-modal { align-items: center; justify-content: center; padding: 16px; }.lm-drawer { justify-content: flex-end; }-.lm-modal-backdrop { position: absolute; inset: 0; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(3px); animation: lm-fade 0.18s ease both; }+.lm-modal-backdrop { position: absolute; inset: 0; background: rgba(0, 0, 0, 0.62); backdrop-filter: blur(4px); animation: lm-fade 0.18s ease both; }@keyframes lm-fade { from { opacity: 0; } to { opacity: 1; } }.lm-modal-card, .lm-drawer-card {position: relative; z-index: 1; background: var(--surface-1, #14151a);border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.16));- box-shadow: 0 24px 70px rgba(0, 0, 0, 0.5);+ box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55);}.lm-modal-card { width: min(540px, 100%); max-height: 90vh; overflow-y: auto; padding: 26px; border-radius: var(--lm-radius); animation: lm-pop 0.22s var(--ease-emphasized, cubic-bezier(0.2, 0.8, 0.2, 1)) both; }-.lm-drawer-card { width: min(560px, 100%); height: 100%; overflow-y: auto; padding: 28px; border-radius: var(--lm-radius) 0 0 var(--lm-radius); animation: lm-slide 0.26s var(--ease-emphasized, cubic-bezier(0.2, 0.8, 0.2, 1)) both; }+.lm-drawer-card { width: min(600px, 100%); height: 100%; overflow-y: auto; padding: 20px 28px 40px; border-radius: var(--lm-radius) 0 0 var(--lm-radius); animation: lm-slide 0.28s var(--ease-emphasized, cubic-bezier(0.2, 0.8, 0.2, 1)) both; }@keyframes lm-pop { from { opacity: 0; transform: scale(0.97) translateY(8px); } to { opacity: 1; transform: none; } }-@keyframes lm-slide { from { transform: translateX(40px); opacity: 0; } to { transform: none; opacity: 1; } }+@keyframes lm-slide { from { transform: translateX(44px); opacity: 0; } to { transform: none; opacity: 1; } }.lm-modal-x { position: absolute; top: 14px; right: 14px; width: 32px; height: 32px; border: 0; border-radius: 50%; background: var(--surface-3, rgba(255, 255, 255, 0.08)); color: var(--ink-bright, #fff); font-size: 20px; line-height: 1; cursor: pointer; }.lm-modal-x:hover { background: var(--surface-2, rgba(255, 255, 255, 0.14)); }+.lm-drawer-bar { position: sticky; top: -20px; z-index: 2; display: flex; justify-content: flex-end; gap: 8px; margin: -20px -28px 4px; padding: 12px 20px; background: linear-gradient(180deg, var(--surface-1, #14151a) 70%, transparent); }.lm-modal-card h2, .lm-drawer-card h2 { margin: 0 0 6px; font-family: var(--font-display, sans-serif); color: var(--ink-bright, #fff); }.lm-modal-sub { margin: 0 0 18px; color: var(--ink-dim, #9aa); font-size: 13px; line-height: 1.5; }.lm-noscroll { overflow: hidden; }@@ -285,27 +422,25 @@transition: border-color var(--duration-fast, 140ms) ease;}.lm-field textarea { resize: vertical; }-.lm-field input:focus-visible, .lm-field textarea:focus-visible, .lm-field select:focus-visible, .lm-form select:focus-visible { outline: none; border-color: var(--success, #4ade80); }+.lm-field input:focus-visible, .lm-field textarea:focus-visible, .lm-field select:focus-visible, .lm-form select:focus-visible { outline: none; border-color: var(--lm-accent); }.lm-field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }.lm-input-suffix { display: flex; align-items: center; gap: 0; border: 1px solid var(--stroke, rgba(255, 255, 255, 0.14)); border-radius: var(--radius-sm, 6px); background: var(--surface-2, rgba(255, 255, 255, 0.04)); overflow: hidden; }.lm-input-suffix input { border: 0; background: transparent; }.lm-input-suffix > span { padding: 0 10px; font: 600 11px/1 var(--font-mono, monospace); color: var(--ink-faint, #778); white-space: nowrap; }-.lm-input-suffix:focus-within { border-color: var(--success, #4ade80); }+.lm-input-suffix:focus-within { border-color: var(--lm-accent); }.lm-check { display: flex; align-items: flex-start; gap: 10px; font-size: 14px; color: var(--ink-bright, #fff); cursor: pointer; }-.lm-check input { width: 18px; height: 18px; accent-color: var(--success, #4ade80); margin-top: 1px; }+.lm-check input { width: 18px; height: 18px; accent-color: var(--lm-accent); margin-top: 1px; }.lm-check-sm { font-size: 13px; }.lm-form-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 4px; }.lm-form-msg { font-size: 13px; min-height: 1px; color: var(--ink-dim, #9aa); }-.lm-form-msg-ok { color: var(--success, #4ade80); }+.lm-form-msg-ok { color: var(--lm-accent); }.lm-form-msg-err { color: var(--danger, #f87171); }--/* Worker/poster reveal in policy form */.lm-worker-only, .lm-poster-only { display: none; }.lm-form.lm-show-worker .lm-worker-only { display: grid; }.lm-form.lm-show-poster .lm-poster-only { display: grid; }/* Drawer specifics */-.lm-drawer-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }+.lm-drawer-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }.lm-drawer-spec { margin: 0 0 14px; color: var(--ink-dim, #9aa); font-size: 14px; line-height: 1.6; white-space: pre-wrap; }.lm-drawer-tags { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 16px; font-size: 13px; }.lm-rationale { display: flex; gap: 8px; padding: 12px 14px; border-radius: var(--radius-sm, 6px); background: color-mix(in srgb, var(--warn, #fbbf24) 10%, transparent); border: 1px solid color-mix(in srgb, var(--warn, #fbbf24) 30%, transparent); color: var(--ink-bright, #fff); font-size: 13px; line-height: 1.5; margin-bottom: 18px; }@@ -316,44 +451,116 @@.lm-bids { display: grid; gap: 10px; }.lm-bids-empty { color: var(--ink-faint, #778); font-size: 13px; }.lm-bid { padding: 12px; border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1)); border-radius: var(--radius-sm, 6px); background: var(--surface-2, rgba(255, 255, 255, 0.03)); animation: lm-flow-in 0.3s var(--ease-out, ease) both; }-.lm-bid-win { border-color: color-mix(in srgb, var(--success, #4ade80) 50%, transparent); background: color-mix(in srgb, var(--success, #4ade80) 8%, transparent); }+.lm-bid-win { border-color: color-mix(in srgb, var(--lm-accent) 50%, transparent); background: color-mix(in srgb, var(--lm-accent) 8%, transparent); }.lm-bid-head { display: flex; align-items: center; gap: 8px; }.lm-bid-name { color: var(--ink-bright, #fff); text-decoration: none; font-weight: 600; }.lm-bid-name:hover { text-decoration: underline; }.lm-bid-price { margin-left: auto; font: 700 14px/1 var(--font-mono, monospace); color: var(--ink-bright, #fff); }.lm-tag-auto { font: 600 9px/1 var(--font-mono, monospace); text-transform: uppercase; padding: 3px 5px; border-radius: 4px; background: var(--surface-3, rgba(255, 255, 255, 0.1)); color: var(--ink-dim, #9aa); }-.lm-tag-win { font: 600 9px/1 var(--font-mono, monospace); text-transform: uppercase; padding: 3px 5px; border-radius: 4px; background: var(--success, #4ade80); color: #06140b; }+.lm-tag-win { font: 600 9px/1 var(--font-mono, monospace); text-transform: uppercase; padding: 3px 5px; border-radius: 4px; background: var(--lm-accent); color: #06140b; }.lm-bid-meta { display: flex; gap: 12px; margin: 8px 0; font: 500 11px/1 var(--font-mono, monospace); color: var(--ink-faint, #778); }.lm-bid-pitch { margin: 0 0 8px; font-size: 13px; line-height: 1.5; color: var(--ink-dim, #9aa); }++/* Bid distribution viz */+.lm-bidviz { display: grid; gap: 5px; margin: 0 0 14px; padding: 12px; border-radius: var(--radius-sm, 6px); background: var(--surface-2, rgba(255, 255, 255, 0.03)); }+.lm-bidviz-scale { display: flex; justify-content: space-between; font: 600 10px/1 var(--font-mono, monospace); color: var(--ink-faint, #778); margin-bottom: 3px; }+.lm-bidbar { height: 8px; border-radius: 4px; background: var(--surface-3, rgba(255, 255, 255, 0.06)); overflow: hidden; }+.lm-bidbar-fill { display: block; height: 100%; border-radius: 4px; background: color-mix(in srgb, var(--ink-dim, #9aa) 55%, transparent); animation: lm-bar 0.5s var(--ease-out, ease) both; }+.lm-bidbar.is-win .lm-bidbar-fill { background: var(--lm-accent); }+@keyframes lm-bar { from { transform: scaleX(0); transform-origin: left; } to { transform: scaleX(1); } }++/* Lifecycle stepper */+.lm-stepper { display: flex; align-items: flex-start; justify-content: space-between; gap: 2px; list-style: none; margin: 0 0 18px; padding: 0; counter-reset: step; }+.lm-step { position: relative; flex: 1; display: flex; flex-direction: column; align-items: center; gap: 7px; text-align: center; }+.lm-step::before { content: ''; position: absolute; top: 6px; left: -50%; width: 100%; height: 2px; background: var(--surface-3, rgba(255, 255, 255, 0.1)); z-index: 0; }+.lm-step:first-child::before { display: none; }+.lm-step-dot { position: relative; z-index: 1; width: 14px; height: 14px; border-radius: 50%; background: var(--surface-3, rgba(255, 255, 255, 0.12)); border: 2px solid var(--surface-1, #14151a); transition: background 240ms ease; }+.lm-step-label { font: 600 10px/1.2 var(--font-mono, monospace); text-transform: uppercase; letter-spacing: 0.03em; color: var(--ink-faint, #778); }+.lm-step.is-done .lm-step-dot { background: var(--lm-accent); }+.lm-step.is-done::before { background: var(--lm-accent); }+.lm-step.is-current .lm-step-dot { background: var(--lm-accent); box-shadow: 0 0 0 4px color-mix(in srgb, var(--lm-accent) 24%, transparent); }+.lm-step.is-current .lm-step-label { color: var(--ink-bright, #fff); }+.lm-stepper.is-failed .lm-step.is-current .lm-step-dot { background: var(--danger, #f87171); box-shadow: 0 0 0 4px color-mix(in srgb, var(--danger, #f87171) 24%, transparent); }+.lm-stepper.is-failed .lm-step.is-current .lm-step-label { color: var(--danger, #f87171); }++/* Job panel + moderator panel */.lm-jobpanel { margin-top: 20px; padding: 16px; border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1)); border-radius: var(--radius-sm, 6px); background: var(--surface-1, rgba(255, 255, 255, 0.03)); }.lm-jobpanel h4 { margin: 0 0 12px; font-family: var(--font-display, sans-serif); color: var(--ink-bright, #fff); }.lm-deliv summary { cursor: pointer; font-size: 13px; color: var(--ink-dim, #9aa); margin-bottom: 8px; }.lm-deliv pre { white-space: pre-wrap; word-break: break-word; font: 500 12px/1.5 var(--font-mono, monospace); color: var(--ink, #ccc); background: var(--surface-2, rgba(0, 0, 0, 0.2)); padding: 10px; border-radius: var(--radius-sm, 6px); max-height: 240px; overflow-y: auto; }.lm-verdict { font-size: 13px; padding: 8px 10px; border-radius: var(--radius-sm, 6px); margin: 10px 0; }-.lm-verdict.pass { background: color-mix(in srgb, var(--success, #4ade80) 12%, transparent); color: var(--success, #4ade80); }+.lm-verdict.pass { background: color-mix(in srgb, var(--lm-accent) 12%, transparent); color: var(--lm-accent); }.lm-verdict.fail { background: color-mix(in srgb, var(--danger, #f87171) 12%, transparent); color: var(--danger, #f87171); }.lm-verifier { opacity: 0.7; }.lm-settle-row { font-size: 13px; color: var(--ink-dim, #9aa); }-.lm-settle-row a { color: var(--success, #4ade80); text-decoration: none; }+.lm-settle-row a { color: var(--lm-accent); text-decoration: none; }.lm-settle-row a:hover { text-decoration: underline; }+.lm-modpanel { margin-top: 18px; padding: 16px; border: 1px solid color-mix(in srgb, var(--warn, #fbbf24) 30%, transparent); border-radius: var(--radius-sm, 6px); background: color-mix(in srgb, var(--warn, #fbbf24) 7%, transparent); }+.lm-modpanel h4 { display: flex; align-items: center; gap: 6px; margin: 0 0 6px; font-family: var(--font-display, sans-serif); color: var(--warn, #fbbf24); font-size: 14px; }+.lm-mod-note { margin: 0 0 12px; font-size: 12px; line-height: 1.5; color: var(--ink-dim, #9aa); }+.lm-mod-actions { display: flex; gap: 8px; flex-wrap: wrap; }.lm-inline-form { margin-top: 18px; padding: 16px; border: 1px solid var(--stroke, rgba(255, 255, 255, 0.12)); border-radius: var(--radius-sm, 6px); background: var(--surface-2, rgba(255, 255, 255, 0.03)); }.lm-inline-form h3, .lm-inline-form h4 { margin: 0 0 10px; font-family: var(--font-display, sans-serif); color: var(--ink-bright, #fff); font-size: 15px; }.lm-signin-hint { margin-top: 16px; padding: 12px; border-radius: var(--radius-sm, 6px); background: var(--surface-2, rgba(255, 255, 255, 0.04)); color: var(--ink-faint, #778); font-size: 13px; text-align: center; }.lm-drawer-loading { padding: 20px 0; }+/* Help overlay */+.lm-help-card { width: min(420px, 100%); }+.lm-help-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; }+.lm-help-list li { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--ink-dim, #9aa); }++/* ── Toasts ────────────────────────────────────────────────────────────── */+.lm-toasts { position: fixed; right: 18px; bottom: 18px; z-index: 2000; display: flex; flex-direction: column; gap: 10px; max-width: min(380px, calc(100vw - 36px)); pointer-events: none; }+.lm-toast {+ display: flex; align-items: center; gap: 10px;+ padding: 12px 14px; border-radius: var(--radius-sm, 10px);+ background: var(--surface-1, #14151a); border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.16));+ box-shadow: 0 14px 40px rgba(0, 0, 0, 0.5);+ color: var(--ink-bright, #fff); font-size: 13.5px; line-height: 1.4;+ pointer-events: auto; cursor: pointer;+ opacity: 0; transform: translateY(10px) scale(0.98);+ transition: opacity 0.24s ease, transform 0.24s var(--ease-emphasized, cubic-bezier(0.2, 0.8, 0.2, 1));+}+.lm-toast.is-in { opacity: 1; transform: none; }+.lm-toast.is-out { opacity: 0; transform: translateY(6px) scale(0.98); }+.lm-toast-icon { flex: none; width: 22px; height: 22px; display: grid; place-items: center; border-radius: 50%; font: 700 12px/1 var(--font-mono, monospace); }+.lm-toast-msg { flex: 1; min-width: 0; }+.lm-toast-link { flex: none; color: var(--lm-accent); text-decoration: none; font-weight: 600; font-size: 12px; }+.lm-toast-ok { border-left: 3px solid var(--lm-accent); }+.lm-toast-ok .lm-toast-icon { background: var(--lm-accent-soft); color: var(--lm-accent); }+.lm-toast-err { border-left: 3px solid var(--danger, #f87171); }+.lm-toast-err .lm-toast-icon { background: color-mix(in srgb, var(--danger, #f87171) 18%, transparent); color: var(--danger, #f87171); }+.lm-toast-warn { border-left: 3px solid var(--warn, #fbbf24); }+.lm-toast-warn .lm-toast-icon { background: color-mix(in srgb, var(--warn, #fbbf24) 18%, transparent); color: var(--warn, #fbbf24); }+.lm-toast-info { border-left: 3px solid var(--ink-faint, #778); }+.lm-toast-info .lm-toast-icon { background: var(--surface-3, rgba(255, 255, 255, 0.1)); color: var(--ink-dim, #9aa); }+/* ── Responsive ────────────────────────────────────────────────────────── */+@media (max-width: 900px) {+ .lm-hero { grid-template-columns: 1fr; }+}@media (max-width: 768px) {- .lm-summary { grid-template-columns: repeat(2, 1fr); }- .lm-controls { flex-direction: column; align-items: stretch; }- .lm-filters { justify-content: space-between; }+ .lm-toolbar { position: static; flex-direction: column; align-items: stretch; }+ .lm-tabs { justify-content: center; }+ .lm-toolbar-controls { justify-content: space-between; }+ .lm-search input { width: 100%; }+ .lm-search { flex: 1; }+ .lm-drawer-card { width: 100%; border-radius: var(--lm-radius) var(--lm-radius) 0 0; height: auto; max-height: 92vh; margin-top: auto; }+ .lm-drawer { align-items: flex-end; }}-@media (max-width: 420px) {+@media (max-width: 480px) {+ .lm-summary { grid-template-columns: 1fr 1fr; }.lm-field-row { grid-template-columns: 1fr; }.lm-drawer-card, .lm-modal-card { padding: 20px 16px; }+ .lm-drawer-bar { margin: -20px -16px 4px; padding: 12px 16px; }+ .lm-step-label { font-size: 9px; }+ .lm-toasts { left: 12px; right: 12px; max-width: none; }}@media (prefers-reduced-motion: reduce) {- .lm-live-dot, .lm-flow, .lm-bid, .lm-skel-line,- .lm-modal-backdrop, .lm-modal-card, .lm-drawer-card, .lm-card-btn { animation: none !important; transition: none !important; }+ .lm-aurora, .lm-live-dot, .lm-flow, .lm-bid, .lm-skel-line, .lm-bidbar-fill,+ .lm-modal-backdrop, .lm-modal-card, .lm-drawer-card, .lm-card-btn, .lm-toast,+ .lm-morefilters-pop { animation: none !important; transition: none !important; }.lm-card-btn:hover, .lm-btn:hover { transform: none; }+ .lm-toast { opacity: 1; transform: none; }}diff --git a/src/labor-market.js b/src/labor-market.jsindex 9e7f342a5..2cc6c10d2 100644--- a/src/labor-market.js+++ b/src/labor-market.js@@ -2,14 +2,16 @@//// A live feed of open bounties, in-flight jobs, and a real-time $THREE-flow// ticker, plus the owner flows that drive the machine economy: post a bounty-// (escrow $THREE on-chain), bid, award, deliver, settle, and opt an agent into-// autonomy. Watching the agents haggle — bids arriving with their score and-// rationale, then the award reasoning — is the point, so the bounty drawer makes-// the negotiation visible. Every number is real (no fake data); every action goes-// through the real /api/labor endpoints with CSRF on mutations.+// (escrow $THREE on-chain), bid, award, deliver, settle, opt an agent into+// autonomy, and — for moderators — force-resolve a stuck bounty without ever+// touching the escrow key. Watching the agents haggle is the point, so the+// bounty drawer makes the negotiation visible: bids with score + rationale, a+// lifecycle stepper, and the on-chain payout receipts. Every number is real (no+// fake data); every action goes through the real /api/labor endpoints with CSRF+// on mutations. Deep-linkable (#b/<id>), keyboard-driven, and toast-notified.import { apiFetch } from './api.js';-import { updateValue, setLiveDot } from './ui-juice.js';+import { updateValue, setLiveDot, sparkline, enterStagger, rippleOnce } from './ui-juice.js';const $ = (sel, root = document) => root.querySelector(sel);const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];@@ -18,12 +20,18 @@ const state = {tab: 'open',skill: '',minReward: '',+ search: '',+ sort: 'newest',+ mineOnly: false,feed: null,myAgents: [],+ myAgentIds: new Set(),authed: false,+ isModerator: false,escrowConfigured: false,pollTimer: null,openBountyId: null,+ seenSettlements: new Set(),};// ── Formatting ──────────────────────────────────────────────────────────────@@ -36,7 +44,6 @@ const fmtThree = (n) => {};const esc = (s) =>String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));-const shortAddr = (a) => (a ? `${a.slice(0, 4)}…${a.slice(-4)}` : '');const ago = (ts) => {if (!ts) return '';const s = Math.max(0, (Date.now() - new Date(ts).getTime()) / 1000);@@ -47,8 +54,40 @@ const ago = (ts) => {};const statusLabel = {open: 'Open', awarded: 'Awarded', working: 'Working', verifying: 'Verifying',- settled: 'Settled', refunded: 'Refunded', failed: 'Failed', cancelled: 'Cancelled',+ delivered: 'Delivered', settled: 'Settled', refunded: 'Refunded', failed: 'Failed', cancelled: 'Cancelled',};+const TERMINAL = new Set(['settled', 'refunded', 'failed', 'cancelled']);++// ── Toasts (self-contained, replaces alert()) ────────────────────────────────++function toast(message, kind = 'info', opts = {}) {+ const host = $('#lm-toasts');+ if (!host) return;+ const el = document.createElement('div');+ el.className = `lm-toast lm-toast-${kind}`;+ el.setAttribute('role', kind === 'err' ? 'alert' : 'status');+ const icon = kind === 'ok' ? '✓' : kind === 'err' ? '!' : kind === 'warn' ? '⚠' : '◆';+ el.innerHTML = `<span class="lm-toast-icon" aria-hidden="true">${icon}</span><span class="lm-toast-msg">${esc(message)}</span>`;+ if (opts.href) {+ const a = document.createElement('a');+ a.className = 'lm-toast-link';+ a.href = opts.href;+ a.target = '_blank';+ a.rel = 'noopener';+ a.textContent = opts.linkText || 'view ↗';+ el.appendChild(a);+ }+ host.appendChild(el);+ requestAnimationFrame(() => el.classList.add('is-in'));+ const ttl = opts.ttl ?? (kind === 'err' ? 6500 : 4200);+ const close = () => {+ el.classList.remove('is-in');+ el.classList.add('is-out');+ setTimeout(() => el.remove(), 280);+ };+ el.addEventListener('click', close);+ setTimeout(close, ttl);+}// ── Data ────────────────────────────────────────────────────────────────────@@ -67,28 +106,32 @@ async function loadFeed() {async function loadMyAgents() {try {const res = await apiFetch('/api/agents', { allowAnonymous: true });- if (!res.ok) {- state.authed = false;- return [];- }+ if (!res.ok) { state.authed = false; return []; }const j = await res.json();state.authed = true;state.myAgents = (j.agents || j.data?.agents || []).filter((a) => a && a.id);+ state.myAgentIds = new Set(state.myAgents.map((a) => a.id));return state.myAgents;- } catch {- state.authed = false;- return [];- }+ } catch { state.authed = false; return []; }}-const ownsAgent = (id) => state.myAgents.some((a) => a.id === id);+async function loadModerator() {+ try {+ const res = await apiFetch('/api/labor/release', { allowAnonymous: true });+ if (!res.ok) return;+ const j = await res.json();+ state.isModerator = !!j.data?.moderator;+ const badge = $('#lm-mod-badge');+ if (badge) badge.hidden = !state.isModerator;+ } catch { /* not a moderator */ }+}++const ownsAgent = (id) => state.myAgentIds.has(id);// ── Render: summary + ticker ────────────────────────────────────────────────function renderSummary() {const t = state.feed?.totals || {};- // Count the headline tiles from their previously-shown real values, flashing the- // direction as the market polls (the #lm-sum-* nodes persist across refreshes).updateValue($('#lm-sum-volume'), Number(t.volume_three || 0), fmtThree);updateValue($('#lm-sum-jobs'), Number(t.settled_jobs || 0), (n) => Math.round(n).toLocaleString());updateValue($('#lm-sum-open'), Number(t.open_bounties || 0), (n) => Math.round(n).toLocaleString());@@ -96,21 +139,41 @@ function renderSummary() {escrow.textContent = state.escrowConfigured ? 'Live' : 'Offline';escrow.classList.toggle('lm-bad', !state.escrowConfigured);escrow.classList.toggle('lm-good', state.escrowConfigured);+ $('.lm-summary-escrow')?.classList.toggle('is-live', state.escrowConfigured);setLiveDot($('#lm-live'), 'live', 'live');++ // Sparklines from the recent settlement stream (oldest → newest).+ const settle = [...(state.feed?.settlements || [])].reverse();+ if (settle.length >= 2) {+ let cum = 0;+ const volSeries = settle.map((s) => (cum += Number(s.worker_payout_three || 0)));+ $('#lm-spark-volume').innerHTML = sparkline(volSeries, { width: 92, height: 26, fill: true, stroke: 'var(--success)' });+ $('#lm-spark-jobs').innerHTML = sparkline(settle.map((_, i) => i + 1), { width: 92, height: 26, stroke: 'var(--success)' });+ }++ // Tab counts.+ setCount('open', state.feed?.open?.length);+ setCount('inflight', state.feed?.inflight?.length);+ setCount('settled', state.feed?.settlements?.length);+}++function setCount(tab, n) {+ const el = $(`.lm-tab-count[data-count="${tab}"]`);+ if (el) el.textContent = n != null ? String(n) : '';}function renderTicker() {const el = $('#lm-ticker');const rows = state.feed?.settlements || [];if (!rows.length) {- el.innerHTML = `<p class="lm-ticker-empty">No settlements yet, the first paid job will stream here.</p>`;+ el.innerHTML = `<p class="lm-ticker-empty">No settlements yet — the first paid job will stream here.</p>`;return;}el.innerHTML = rows.map((s) => `<div class="lm-flow">- <span class="lm-flow-amt">${fmtThree(s.worker_payout_three)} $THREE</span>+ <span class="lm-flow-amt">${fmtThree(s.worker_payout_three)} <span>$THREE</span></span><span class="lm-flow-body"><a href="/agent/${esc(s.poster_agent_id)}">${esc(s.poster_name)}</a><span class="lm-flow-arrow" aria-hidden="true">→</span>@@ -124,14 +187,34 @@ function renderTicker() {.join('');}+// Surface newly-arrived settlements as toasts (skip the very first paint).+function announceSettlements(firstPaint) {+ const rows = state.feed?.settlements || [];+ if (firstPaint) { rows.forEach((s) => state.seenSettlements.add(s.id || s.settlement_sig)); return; }+ for (const s of rows) {+ const key = s.id || s.settlement_sig;+ if (!key || state.seenSettlements.has(key)) continue;+ state.seenSettlements.add(key);+ toast(`${esc(s.worker_name || 'A worker')} earned ${fmtThree(s.worker_payout_three)} $THREE`, 'ok',+ s.settlement_explorer ? { href: s.settlement_explorer, linkText: 'tx ↗' } : {});+ }+}+// ── Render: board ───────────────────────────────────────────────────────────-function skeletonCards(n = 4) {- return Array.from({ length: n }, () => `<div class="lm-card lm-skel"><div class="lm-skel-line w60"></div><div class="lm-skel-line w90"></div><div class="lm-skel-line w40"></div></div>`).join('');+function skeletonCards(n = 6) {+ return Array.from({ length: n }, () => `<div class="lm-card lm-skel"><div class="lm-skel-line w40"></div><div class="lm-skel-line w90"></div><div class="lm-skel-line w60"></div></div>`).join('');+}++function chip(skill) {+ return skill+ ? `<span class="lm-chip">${esc(skill)}</span>`+ : `<span class="lm-chip lm-chip-muted">open skill</span>`;}function bountyCard(b) {- const skill = b.required_skill ? `<span class="lm-chip">${esc(b.required_skill)}</span>` : `<span class="lm-chip lm-chip-muted">open skill</span>`;+ const mine = ownsAgent(b.poster_agent_id);+ const hot = b.bid_count >= 3;return `<button class="lm-card lm-card-btn" data-bounty="${esc(b.id)}" aria-label="Open bounty ${esc(b.title)}"><div class="lm-card-top">@@ -139,54 +222,67 @@ function bountyCard(b) {<span class="lm-reward">${fmtThree(b.reward_three)} <span>$THREE</span></span></div><h3 class="lm-card-title">${esc(b.title)}</h3>- <p class="lm-card-spec">${esc((b.spec || '').slice(0, 140))}${(b.spec || '').length > 140 ? '…' : ''}</p>+ <p class="lm-card-spec">${esc((b.spec || '').slice(0, 150))}${(b.spec || '').length > 150 ? '…' : ''}</p><div class="lm-card-foot">- ${skill}+ ${chip(b.required_skill)}<span class="lm-card-meta">by <a href="/agent/${esc(b.poster_agent_id)}" onclick="event.stopPropagation()">${esc(b.poster_name)}</a></span>- <span class="lm-card-bids">${b.bid_count} bid${b.bid_count === 1 ? '' : 's'}</span>+ ${mine ? '<span class="lm-tag-mine">yours</span>' : ''}+ <span class="lm-card-bids ${hot ? 'is-hot' : ''}">${b.bid_count} bid${b.bid_count === 1 ? '' : 's'}</span>${b.escrow_explorer ? `<span class="lm-card-escrow" title="Reward escrowed on-chain">◆ escrowed</span>` : ''}</div></button>`;}function jobCard(j) {+ const mine = ownsAgent(j.worker_agent_id) || ownsAgent(j.poster_agent_id);return `- <div class="lm-card">+ <button class="lm-card lm-card-btn" data-bounty="${esc(j.bounty_id)}" aria-label="Open job ${esc(j.title || 'job')}"><div class="lm-card-top"><span class="lm-status lm-status-${esc(j.status)}">${statusLabel[j.status] || j.status}</span><span class="lm-reward">${fmtThree(j.price_three)} <span>$THREE</span></span></div><h3 class="lm-card-title">${esc(j.title || 'Job')}</h3><div class="lm-card-foot">- ${j.required_skill ? `<span class="lm-chip">${esc(j.required_skill)}</span>` : ''}- <span class="lm-card-meta"><a href="/agent/${esc(j.poster_agent_id)}">${esc(j.poster_name)}</a> → <a href="/agent/${esc(j.worker_agent_id)}">${esc(j.worker_name)}</a></span>+ ${chip(j.required_skill)}+ <span class="lm-card-meta"><a href="/agent/${esc(j.poster_agent_id)}" onclick="event.stopPropagation()">${esc(j.poster_name)}</a> → <a href="/agent/${esc(j.worker_agent_id)}" onclick="event.stopPropagation()">${esc(j.worker_name)}</a></span>+ ${mine ? '<span class="lm-tag-mine">yours</span>' : ''}<span class="lm-card-bids">${ago(j.created_at)}</span></div>- </div>`;+ </button>`;}function settledCard(s) {+ const mine = ownsAgent(s.worker_agent_id) || ownsAgent(s.poster_agent_id);return `- <div class="lm-card">+ <button class="lm-card lm-card-btn" data-bounty="${esc(s.bounty_id)}" aria-label="Open settlement ${esc(s.title || 'bounty')}"><div class="lm-card-top"><span class="lm-status lm-status-settled">Settled</span><span class="lm-reward">${fmtThree(s.worker_payout_three)} <span>$THREE</span></span></div><h3 class="lm-card-title">${esc(s.title || 'Bounty')}</h3><div class="lm-card-foot">- ${s.required_skill ? `<span class="lm-chip">${esc(s.required_skill)}</span>` : ''}- <span class="lm-card-meta"><a href="/agent/${esc(s.poster_agent_id)}">${esc(s.poster_name)}</a> → <a href="/agent/${esc(s.worker_agent_id)}">${esc(s.worker_name)}</a></span>+ ${chip(s.required_skill)}+ <span class="lm-card-meta"><a href="/agent/${esc(s.poster_agent_id)}" onclick="event.stopPropagation()">${esc(s.poster_name)}</a> → <a href="/agent/${esc(s.worker_agent_id)}" onclick="event.stopPropagation()">${esc(s.worker_name)}</a></span>+ ${mine ? '<span class="lm-tag-mine">yours</span>' : ''}${Number(s.royalty_three) > 0 ? `<span class="lm-card-bids">+${fmtThree(s.royalty_three)} royalty</span>` : ''}- ${s.settlement_explorer ? `<a class="lm-flow-tx" href="${esc(s.settlement_explorer)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">tx ↗</a>` : ''}</div>- </div>`;+ </button>`;}function emptyState(kind) {+ const filtered = state.search || state.skill || state.minReward || state.mineOnly;+ if (filtered) {+ return `<div class="lm-empty">+ <div class="lm-empty-mark" aria-hidden="true">⌕</div>+ <h3>Nothing matches your filters</h3>+ <p>No ${kind === 'open' ? 'open bounties' : kind === 'inflight' ? 'in-flight jobs' : 'settlements'} match. Try clearing the search or filters.</p>+ <button type="button" class="lm-btn lm-btn-sm" data-clear-filters>Clear filters</button>+ </div>`;+ }if (kind === 'open') {return `<div class="lm-empty"><div class="lm-empty-mark" aria-hidden="true">◆</div>- <h3>No open bounties${state.skill ? ` for "${esc(state.skill)}"` : ''}</h3>+ <h3>No open bounties yet</h3><p>Be the first employer in the machine economy. Post a task, escrow a $THREE reward, and let worker agents bid for it.</p><button type="button" class="lm-btn lm-btn-primary" data-post-cta>Post the first bounty</button></div>`;@@ -197,52 +293,122 @@ function emptyState(kind) {return `<div class="lm-empty"><div class="lm-empty-mark" aria-hidden="true">✓</div><h3>No settlements yet</h3><p>Completed, verified jobs and their on-chain $THREE payouts will land here.</p></div>`;}+// Apply client-side search / mine / sort on top of the server-filtered feed.+function visibleItems() {+ const f = state.feed;+ if (!f) return [];+ let items = state.tab === 'open' ? [...(f.open || [])] : state.tab === 'inflight' ? [...(f.inflight || [])] : [...(f.settlements || [])];++ if (state.mineOnly) {+ items = items.filter((it) => ownsAgent(it.poster_agent_id) || ownsAgent(it.worker_agent_id));+ }+ if (state.search) {+ const q = state.search.toLowerCase();+ items = items.filter((it) =>+ [it.title, it.spec, it.required_skill, it.poster_name, it.worker_name]+ .some((v) => String(v || '').toLowerCase().includes(q)));+ }+ const reward = (it) => Number(it.reward_three ?? it.price_three ?? it.worker_payout_three ?? 0);+ const created = (it) => new Date(it.created_at || it.settled_at || 0).getTime();+ if (state.sort === 'reward-desc') items.sort((a, b) => reward(b) - reward(a));+ else if (state.sort === 'reward-asc') items.sort((a, b) => reward(a) - reward(b));+ else if (state.sort === 'bids-desc') items.sort((a, b) => (b.bid_count || 0) - (a.bid_count || 0));+ else items.sort((a, b) => created(b) - created(a));+ return items;+}+function renderBoard() {const list = $('#lm-list');const board = $('.lm-board');- const f = state.feed;- if (!f) {- list.innerHTML = skeletonCards();- return;- }+ if (!state.feed) { list.innerHTML = skeletonCards(); return; }board.setAttribute('aria-busy', 'false');- let items = [];- if (state.tab === 'open') items = f.open || [];- else if (state.tab === 'inflight') items = f.inflight || [];- else items = f.settlements || [];- if (!items.length) {- list.innerHTML = emptyState(state.tab);- return;- }- if (state.tab === 'open') list.innerHTML = items.map(bountyCard).join('');- else if (state.tab === 'inflight') list.innerHTML = items.map(jobCard).join('');- else list.innerHTML = items.map(settledCard).join('');+ const items = visibleItems();+ if (!items.length) { list.innerHTML = emptyState(state.tab); return; }++ const render = state.tab === 'open' ? bountyCard : state.tab === 'inflight' ? jobCard : settledCard;+ list.innerHTML = items.map(render).join('');+ enterStagger($$('.lm-card-btn', list), { max: 12 });}-function renderAll() {+function renderAll(firstPaint = false) {renderSummary();renderTicker();renderBoard();+ announceSettlements(firstPaint);+}++// ── Lifecycle stepper + bid distribution (drawer visuals) ────────────────────++function stepper(b, job) {+ const steps = [+ { key: 'open', label: 'Posted' },+ { key: 'awarded', label: 'Awarded' },+ { key: 'working', label: 'Working' },+ { key: 'delivered', label: 'Delivered' },+ { key: 'settled', label: 'Settled' },+ ];+ // Map current status → step index.+ const s = job?.status || b.status;+ let idx = 0;+ if (b.status === 'open') idx = b.awarded_agent_id ? 1 : 0;+ if (['awarded'].includes(s)) idx = 1;+ if (s === 'working') idx = 2;+ if (['delivered', 'verifying'].includes(s)) idx = 3;+ if (s === 'settled') idx = 4;+ const failed = ['refunded', 'failed', 'cancelled'].includes(b.status) || ['refunded', 'failed'].includes(job?.status);+ if (failed) idx = 4;+ const endLabel = b.status === 'refunded' ? 'Refunded' : b.status === 'failed' ? 'Failed' : b.status === 'cancelled' ? 'Cancelled' : 'Settled';+ steps[4].label = endLabel;++ return `<ol class="lm-stepper ${failed ? 'is-failed' : ''}" aria-label="Bounty lifecycle">+ ${steps.map((st, i) => `+ <li class="lm-step ${i < idx ? 'is-done' : ''} ${i === idx ? 'is-current' : ''}">+ <span class="lm-step-dot" aria-hidden="true"></span>+ <span class="lm-step-label">${esc(st.label)}</span>+ </li>`).join('')}+ </ol>`;+}++function bidDistribution(b, bids) {+ if (!bids.length) return '';+ const reward = Number(b.reward_three) || 1;+ const bars = bids+ .slice()+ .sort((a, z) => Number(a.price_three) - Number(z.price_three))+ .map((bd) => {+ const pct = Math.max(4, Math.min(100, (Number(bd.price_three) / reward) * 100));+ const win = b.awarded_agent_id === bd.worker_agent_id;+ return `<div class="lm-bidbar ${win ? 'is-win' : ''}" title="${esc(bd.worker_name)} · ${fmtThree(bd.price_three)} $THREE">+ <span class="lm-bidbar-fill" style="width:${pct}%"></span>+ </div>`;+ })+ .join('');+ return `<div class="lm-bidviz" aria-hidden="true"><div class="lm-bidviz-scale"><span>0</span><span>${fmtThree(reward)} $THREE</span></div>${bars}</div>`;}// ── Bounty drawer (the negotiation, made visible) ───────────────────────────-async function openBounty(id) {+async function openBounty(id, { push = true } = {}) {state.openBountyId = id;+ if (push && location.hash !== `#b/${id}`) history.pushState({ bounty: id }, '', `#b/${id}`);const drawer = $('#lm-drawer');const body = $('#lm-drawer-body');drawer.hidden = false;document.body.classList.add('lm-noscroll');- body.innerHTML = `<div class="lm-drawer-loading">${skeletonCards(1)}</div>`;+ if (!body.dataset.for || body.dataset.for !== id) {+ body.innerHTML = `<div class="lm-drawer-loading">${skeletonCards(1)}</div>`;+ }try {const res = await apiFetch(`/api/labor/bounty?id=${encodeURIComponent(id)}`, { allowAnonymous: true });if (!res.ok) throw new Error('not found');const { data } = await res.json();+ body.dataset.for = id;body.innerHTML = drawerMarkup(data);wireDrawer(data);+ $('#lm-drawer-card')?.scrollTo?.({ top: 0 });} catch {- body.innerHTML = `<div class="lm-empty"><h3>Couldn't load this bounty</h3><p>It may have been removed. <button type="button" class="lm-btn" data-close>Close</button></p></div>`;+ body.innerHTML = `<div class="lm-empty"><h3>Couldn't load this bounty</h3><p>It may have been removed.</p><button type="button" class="lm-btn" data-close>Close</button></div>`;}}@@ -287,22 +453,36 @@ function drawerMarkup({ bounty: b, bids, job }) {<div class="lm-jobpanel"><h4>Job · ${statusLabel[job.status] || job.status}</h4>${job.deliverable?.output ? `<details class="lm-deliv"><summary>Deliverable</summary><pre>${esc(String(job.deliverable.output).slice(0, 2000))}</pre></details>` : ''}- ${verdict ? `<p class="lm-verdict ${verdict.pass ? 'pass' : 'fail'}">Verdict: <strong>${verdict.pass ? 'passed' : 'rejected'}</strong> · score ${Number(verdict.score).toFixed(2)} · ${esc(verdict.reason || '')} <span class="lm-verifier">(${esc(verdict.verifier || '')})</span></p>` : ''}+ ${verdict ? `<p class="lm-verdict ${verdict.pass ? 'pass' : 'fail'}">Verdict: <strong>${verdict.pass ? 'passed' : 'rejected'}</strong> · score ${Number(verdict.score).toFixed(2)} · ${esc(verdict.reason || '')} <span class="lm-verifier">(${esc(verdict.verifier || (verdict.moderator ? 'moderator' : ''))})</span></p>` : ''}${job.settlement_explorer ? `<p class="lm-settle-row">Paid <strong>${fmtThree(job.worker_payout_three)} $THREE</strong>${Number(job.royalty_three) > 0 ? ` · royalty ${fmtThree(job.royalty_three)}` : ''} <a href="${esc(job.settlement_explorer)}" target="_blank" rel="noopener">settlement ↗</a>${job.invocation_explorer ? ` · <a href="${esc(job.invocation_explorer)}" target="_blank" rel="noopener">invocation ↗</a>` : ''}</p>` : ''}${ownsAgent(job.worker_agent_id) && job.status === 'working' ? deliverForm(job.id) : ''}${(iOwnPoster || ownsAgent(job.worker_agent_id)) && ['delivered', 'verifying'].includes(job.status) ? `<button type="button" class="lm-btn lm-btn-primary" data-settle="${esc(job.id)}">Verify & settle now</button>` : ''}</div>`;}+ // Moderator override lane — only for admins, only while the escrow is live.+ const canModerate = state.isModerator && b.escrow_fund_sig && !TERMINAL.has(b.status);+ const modHtml = canModerate+ ? `<div class="lm-modpanel">+ <h4><svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path fill="currentColor" d="M12 1 3 5v6c0 5 3.8 9.4 9 11 5.2-1.6 9-6 9-11V5z"/></svg> Moderator override</h4>+ <p class="lm-mod-note">Force-resolve a stuck or disputed bounty. The escrow signs server-side — you never touch its key.</p>+ <div class="lm-mod-actions">+ ${job ? `<button type="button" class="lm-btn lm-btn-sm lm-btn-primary" data-mod="release">Release to worker</button>` : ''}+ <button type="button" class="lm-btn lm-btn-sm lm-btn-danger" data-mod="refund">Refund poster</button>+ </div>+ </div>`+ : '';+return `<div class="lm-drawer-head"><span class="lm-status lm-status-${esc(b.status)}">${statusLabel[b.status] || b.status}</span><span class="lm-reward lm-reward-lg">${reward} <span>$THREE</span></span></div><h2 id="lm-drawer-title">${esc(b.title)}</h2>+ ${stepper(b, job)}<p class="lm-drawer-spec">${esc(b.spec)}</p><div class="lm-drawer-tags">- ${b.required_skill ? `<span class="lm-chip">${esc(b.required_skill)}</span>` : '<span class="lm-chip lm-chip-muted">open skill</span>'}+ ${chip(b.required_skill)}<span class="lm-card-meta">by <a href="/agent/${esc(b.poster_agent_id)}">${esc(b.poster_name)}</a></span>${b.escrow_explorer ? `<a class="lm-card-escrow" href="${esc(b.escrow_explorer)}" target="_blank" rel="noopener" title="Reward escrowed on-chain">◆ escrow tx ↗</a>` : ''}</div>@@ -310,11 +490,13 @@ function drawerMarkup({ bounty: b, bids, job }) {<div class="lm-section"><h3>Bids <span class="lm-count">${bids.length}</span></h3>+ ${bidDistribution(b, bids)}<div class="lm-bids">${bidsHtml}</div></div>${canBid ? bidForm(b, myWorker) : state.authed ? '' : `<p class="lm-signin-hint">Sign in and own an agent to bid, award, or post.</p>`}- ${jobHtml}`;+ ${jobHtml}+ ${modHtml}`;}function bidForm(b, worker) {@@ -343,8 +525,17 @@ function deliverForm(jobId) {</form>`;}+async function postJson(url, body) {+ const res = await apiFetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });+ const j = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(j.error_description || j.error || `${url} failed`);+ return j;+}+function wireDrawer(data) {const body = $('#lm-drawer-body');+ const bountyId = data.bounty.id;+const bidForm = $('[data-bid-form]', body);if (bidForm) {bidForm.addEventListener('submit', async (e) => {@@ -354,47 +545,31 @@ function wireDrawer(data) {const etaMin = Number(fd.get('etaMin'));setMsg(msg, 'Placing bid…', '');try {- const res = await apiFetch('/api/labor/bid', {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- bountyId: fd.get('bountyId'),- workerAgentId: fd.get('workerAgentId'),- priceThree: Number(fd.get('priceThree')),- etaSeconds: etaMin > 0 ? etaMin * 60 : null,- pitch: fd.get('pitch') || null,- }),+ await postJson('/api/labor/bid', {+ bountyId: fd.get('bountyId'),+ workerAgentId: fd.get('workerAgentId'),+ priceThree: Number(fd.get('priceThree')),+ etaSeconds: etaMin > 0 ? etaMin * 60 : null,+ pitch: fd.get('pitch') || null,});- const j = await res.json();- if (!res.ok) throw new Error(j.error_description || j.error || 'bid failed');setMsg(msg, 'Bid placed.', 'ok');+ toast('Bid placed.', 'ok');await refresh();- openBounty(data.bounty.id);- } catch (err) {- setMsg(msg, err.message, 'err');- }+ openBounty(bountyId, { push: false });+ } catch (err) { setMsg(msg, err.message, 'err'); }});}$$('[data-award]', body).forEach((btn) =>btn.addEventListener('click', async () => {- btn.disabled = true;- btn.textContent = 'Awarding…';+ rippleOnce(btn);+ btn.disabled = true; btn.textContent = 'Awarding…';try {- const res = await apiFetch('/api/labor/award', {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ bountyId: data.bounty.id, bidId: btn.dataset.award }),- });- const j = await res.json();- if (!res.ok) throw new Error(j.error_description || j.error || 'award failed');+ await postJson('/api/labor/award', { bountyId, bidId: btn.dataset.award });+ toast('Bid awarded.', 'ok');await refresh();- openBounty(data.bounty.id);- } catch (err) {- btn.disabled = false;- btn.textContent = 'Award';- alert(err.message);- }+ openBounty(bountyId, { push: false });+ } catch (err) { btn.disabled = false; btn.textContent = 'Award'; toast(err.message, 'err'); }}),);@@ -405,50 +580,68 @@ function wireDrawer(data) {const msg = $('[data-deliver-msg]', deliverForm);setMsg(msg, 'Delivering & settling on-chain…', '');try {- const res = await apiFetch('/api/labor/deliver', {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ jobId: deliverForm.dataset.job, deliverable: { output: new FormData(deliverForm).get('output') } }),- });- const j = await res.json();- if (!res.ok) throw new Error(j.error_description || j.error || 'deliver failed');- setMsg(msg, j.settlement?.settled ? 'Settled, payout released.' : `Verdict: ${j.settlement?.status || 'recorded'}.`, 'ok');+ const j = await postJson('/api/labor/deliver', { jobId: deliverForm.dataset.job, deliverable: { output: new FormData(deliverForm).get('output') } });+ const settled = j.settlement?.settled;+ setMsg(msg, settled ? 'Settled — payout released.' : `Verdict: ${j.settlement?.status || 'recorded'}.`, settled ? 'ok' : '');+ toast(settled ? 'Delivered & settled — payout released.' : `Delivered. Verdict: ${j.settlement?.status || 'recorded'}.`, settled ? 'ok' : 'warn',+ j.settlement?.explorer ? { href: j.settlement.explorer, linkText: 'tx ↗' } : {});await refresh();- openBounty(data.bounty.id);- } catch (err) {- setMsg(msg, err.message, 'err');- }+ openBounty(bountyId, { push: false });+ } catch (err) { setMsg(msg, err.message, 'err'); }});}const settleBtn = $('[data-settle]', body);if (settleBtn) {settleBtn.addEventListener('click', async () => {- settleBtn.disabled = true;- settleBtn.textContent = 'Settling…';+ settleBtn.disabled = true; settleBtn.textContent = 'Settling…';try {- const res = await apiFetch('/api/labor/settle', {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ jobId: settleBtn.dataset.settle }),- });- const j = await res.json();- if (!res.ok) throw new Error(j.error_description || j.error || 'settle failed');+ const j = await postJson('/api/labor/settle', { jobId: settleBtn.dataset.settle });+ toast(j.settled ? 'Settled — payout released.' : `Verdict: ${j.status || 'recorded'}.`, j.settled ? 'ok' : 'warn');await refresh();- openBounty(data.bounty.id);- } catch (err) {- settleBtn.disabled = false;- settleBtn.textContent = 'Verify & settle now';- alert(err.message);- }+ openBounty(bountyId, { push: false });+ } catch (err) { settleBtn.disabled = false; settleBtn.textContent = 'Verify & settle now'; toast(err.message, 'err'); }});}++ $$('[data-mod]', body).forEach((btn) =>+ btn.addEventListener('click', async () => {+ const action = btn.dataset.mod;+ const verb = action === 'release' ? 'release the reward to the worker' : 'refund the poster';+ if (!confirm(`Moderator action: ${verb}?\n\nThis moves real $THREE from escrow and cannot be undone.`)) return;+ rippleOnce(btn);+ $$('[data-mod]', body).forEach((b) => (b.disabled = true));+ btn.textContent = action === 'release' ? 'Releasing…' : 'Refunding…';+ try {+ const j = await postJson('/api/labor/release', { bountyId, action });+ const sig = j.settlement_sig || j.refund_sig;+ toast(action === 'release' ? 'Released to worker.' : 'Refunded to poster.', 'ok',+ sig ? { href: `https://solscan.io/tx/${sig}`, linkText: 'tx ↗' } : {});+ await refresh();+ openBounty(bountyId, { push: false });+ } catch (err) {+ $$('[data-mod]', body).forEach((b) => (b.disabled = false));+ toast(err.message, 'err');+ }+ }),+ );}function closeDrawer() {$('#lm-drawer').hidden = true;+ $('#lm-drawer-body').dataset.for = '';state.openBountyId = null;document.body.classList.remove('lm-noscroll');+ if (location.hash.startsWith('#b/')) history.pushState(null, '', location.pathname + location.search);+}++async function copyBountyLink() {+ if (!state.openBountyId) return;+ const url = `${location.origin}/labor-market#b/${state.openBountyId}`;+ try {+ await navigator.clipboard.writeText(url);+ toast('Link copied to clipboard.', 'ok');+ } catch { toast(url, 'info'); }}// ── Post + policy modals ────────────────────────────────────────────────────@@ -461,24 +654,24 @@ function fillAgentSelects() {}function openModal(id) {- if (!state.authed) {+ if ((id === 'lm-post-modal' || id === 'lm-policy-modal') && !state.authed) {location.href = '/login?next=' + encodeURIComponent('/labor-market');return;}if (id === 'lm-post-modal' && !state.escrowConfigured) {- alert('Bounty escrow is not configured on this server yet.');+ toast('Bounty escrow is not online on this server yet.', 'warn');return;}- fillAgentSelects();+ if (id === 'lm-post-modal' || id === 'lm-policy-modal') fillAgentSelects();const m = $('#' + id);m.hidden = false;document.body.classList.add('lm-noscroll');- const first = m.querySelector('select, input, textarea');+ const first = m.querySelector('select, input, textarea, button.lm-btn-primary');if (first) setTimeout(() => first.focus(), 30);}function closeModal(m) {m.hidden = true;- document.body.classList.remove('lm-noscroll');+ if (!$$('.lm-modal').some((x) => !x.hidden) && $('#lm-drawer').hidden) document.body.classList.remove('lm-noscroll');}function setMsg(el, text, kind) {@@ -516,18 +709,16 @@ function wirePostForm() {throw new Error(j.error_description || j.error || 'post failed');}const auto = j.autopilot || {};- setMsg(msg, `Posted & escrowed. ${auto.bids ? `${auto.bids} auto-bid${auto.bids === 1 ? '' : 's'} arrived.` : ''} ${auto.settled === 'settled' ? 'Already settled!' : ''}`.trim(), 'ok');+ const extra = `${auto.bids ? `${auto.bids} auto-bid${auto.bids === 1 ? '' : 's'} arrived.` : ''} ${auto.settled === 'settled' ? 'Already settled!' : ''}`.trim();+ setMsg(msg, `Posted & escrowed. ${extra}`.trim(), 'ok');+ toast(`Bounty posted & escrowed.${extra ? ' ' + extra : ''}`, 'ok', j.bounty?.escrow_explorer ? { href: j.bounty.escrow_explorer, linkText: 'escrow tx ↗' } : {});form.reset();await refresh();setTimeout(() => {closeModal($('#lm-post-modal'));if (j.bounty?.id) openBounty(j.bounty.id);- }, 900);- } catch (err) {- setMsg(msg, err.message, 'err');- } finally {- btn.disabled = false;- }+ }, 700);+ } catch (err) { setMsg(msg, err.message, 'err'); } finally { btn.disabled = false; }});}@@ -562,28 +753,19 @@ function wirePolicyForm() {btn.disabled = true;setMsg(msg, 'Saving…', '');try {- const res = await apiFetch('/api/labor/policy', {- method: 'PUT',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- agentId: $('#lm-policy-agent').value,- workerEnabled: $('#lm-policy-worker').checked,- posterEnabled: $('#lm-policy-poster').checked,- autoAward: $('#lm-policy-autoaward').checked,- skills: $('#lm-policy-skills').value.split(',').map((s) => s.trim()).filter(Boolean),- maxBidThree: $('#lm-policy-maxbid').value ? Number($('#lm-policy-maxbid').value) : null,- minBids: Number($('#lm-policy-minbids').value) || 1,- }),+ await postJson('/api/labor/policy', {+ agentId: $('#lm-policy-agent').value,+ workerEnabled: $('#lm-policy-worker').checked,+ posterEnabled: $('#lm-policy-poster').checked,+ autoAward: $('#lm-policy-autoaward').checked,+ skills: $('#lm-policy-skills').value.split(',').map((s) => s.trim()).filter(Boolean),+ maxBidThree: $('#lm-policy-maxbid').value ? Number($('#lm-policy-maxbid').value) : null,+ minBids: Number($('#lm-policy-minbids').value) || 1,});- const j = await res.json();- if (!res.ok) throw new Error(j.error_description || j.error || 'save failed');setMsg(msg, 'Policy saved. This agent is now part of the economy.', 'ok');- setTimeout(() => closeModal($('#lm-policy-modal')), 900);- } catch (err) {- setMsg(msg, err.message, 'err');- } finally {- btn.disabled = false;- }+ toast('Autonomy policy saved.', 'ok');+ setTimeout(() => closeModal($('#lm-policy-modal')), 700);+ } catch (err) { setMsg(msg, err.message, 'err'); } finally { btn.disabled = false; }});}@@ -595,7 +777,7 @@ async function refresh() {renderAll();} catch {const list = $('#lm-list');- if (!state.feed) list.innerHTML = `<div class="lm-empty"><h3>Market unavailable</h3><p>Couldn't reach the labor market. <button type="button" class="lm-btn" data-retry>Retry</button></p></div>`;+ if (!state.feed) list.innerHTML = `<div class="lm-empty"><h3>Market unavailable</h3><p>Couldn't reach the labor market.</p><button type="button" class="lm-btn" data-retry>Retry</button></div>`;setLiveDot($('#lm-live'), state.feed ? 'connecting' : 'error', state.feed ? 'reconnecting' : 'offline');}}@@ -604,9 +786,7 @@ function startPolling() {stopPolling();state.pollTimer = setInterval(() => {if (document.hidden) return;- refresh().then(() => {- if (state.openBountyId) openBounty(state.openBountyId);- });+ refresh().then(() => { if (state.openBountyId) openBounty(state.openBountyId, { push: false }); });}, 8000);}function stopPolling() {@@ -618,27 +798,42 @@ function stopPolling() {function debounce(fn, ms) {let t;- return (...a) => {- clearTimeout(t);- t = setTimeout(() => fn(...a), ms);- };+ return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };+}++function selectTab(tab) {+ if (!tab) return;+ state.tab = tab;+ $$('.lm-tab').forEach((t) => {+ const active = t.dataset.tab === tab;+ t.classList.toggle('is-active', active);+ t.setAttribute('aria-selected', active ? 'true' : 'false');+ });+ $('#lm-sort-wrap').style.visibility = tab === 'open' ? 'visible' : 'hidden';+ renderBoard();+}++function anyOverlayOpen() {+ return $$('.lm-modal').some((m) => !m.hidden) || !$('#lm-drawer').hidden;}function init() {// Tabs- $$('.lm-tab').forEach((tab) =>- tab.addEventListener('click', () => {- $$('.lm-tab').forEach((t) => {- t.classList.toggle('is-active', t === tab);- t.setAttribute('aria-selected', t === tab ? 'true' : 'false');- });- state.tab = tab.dataset.tab;- $('#lm-filters').style.visibility = state.tab === 'open' ? 'visible' : 'hidden';- renderBoard();- }),- );+ $$('.lm-tab').forEach((tab) => tab.addEventListener('click', () => selectTab(tab.dataset.tab)));++ // Search+ $('#lm-search').addEventListener('input', debounce((e) => { state.search = e.target.value.trim(); renderBoard(); }, 160));+ // Sort+ $('#lm-sort').addEventListener('change', (e) => { state.sort = e.target.value; renderBoard(); });+ // Mine toggle+ $('#lm-mine-toggle').addEventListener('click', (e) => {+ state.mineOnly = !state.mineOnly;+ e.currentTarget.setAttribute('aria-pressed', String(state.mineOnly));+ e.currentTarget.classList.toggle('is-on', state.mineOnly);+ renderBoard();+ });- // Filters+ // Server-side filters (skill + min reward)const applyFilters = debounce(() => {state.skill = $('#lm-filter-skill').value.trim();state.minReward = $('#lm-filter-reward').value.trim();@@ -646,29 +841,67 @@ function init() {}, 350);$('#lm-filter-skill').addEventListener('input', applyFilters);$('#lm-filter-reward').addEventListener('input', applyFilters);+ $('#lm-filter-clear').addEventListener('click', () => {+ $('#lm-filter-skill').value = ''; $('#lm-filter-reward').value = '';+ $('#lm-search').value = ''; state.search = '';+ state.mineOnly = false; $('#lm-mine-toggle').setAttribute('aria-pressed', 'false'); $('#lm-mine-toggle').classList.remove('is-on');+ $('#lm-morefilters').open = false;+ applyFilters();+ });- // Card / drawer delegation+ // Card / drawer / empty-state delegation$('#lm-list').addEventListener('click', (e) => {const card = e.target.closest('[data-bounty]');- if (card) openBounty(card.dataset.bounty);- if (e.target.closest('[data-post-cta]')) openModal('lm-post-modal');- if (e.target.closest('[data-retry]')) refresh();+ if (card) return openBounty(card.dataset.bounty);+ if (e.target.closest('[data-post-cta]')) return openModal('lm-post-modal');+ if (e.target.closest('[data-retry]')) return refresh();+ if (e.target.closest('[data-clear-filters]')) return $('#lm-filter-clear').click();});// Hero + modal buttons$('#lm-post-open').addEventListener('click', () => openModal('lm-post-modal'));$('#lm-policy-open').addEventListener('click', () => openModal('lm-policy-modal'));- $$('[data-close]').forEach((el) =>- el.addEventListener('click', (e) => {- const modal = e.target.closest('.lm-modal');- if (modal) closeModal(modal);- else closeDrawer();- }),- );+ $('#lm-help-open').addEventListener('click', () => openModal('lm-help-modal'));+ $('#lm-drawer-copy').addEventListener('click', copyBountyLink);++ document.addEventListener('click', (e) => {+ const closer = e.target.closest('[data-close]');+ if (!closer) return;+ const modal = closer.closest('.lm-modal');+ if (modal) closeModal(modal);+ else closeDrawer();+ });++ // Keyboard shortcutsdocument.addEventListener('keydown', (e) => {- if (e.key !== 'Escape') return;- const openModalEl = $$('.lm-modal').find((m) => !m.hidden);- if (openModalEl) closeModal(openModalEl);+ if (e.key === 'Escape') {+ const openModalEl = $$('.lm-modal').find((m) => !m.hidden);+ if (openModalEl) return closeModal(openModalEl);+ if (!$('#lm-drawer').hidden) return closeDrawer();+ return;+ }+ const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName || '') || e.metaKey || e.ctrlKey || e.altKey;+ if (typing) return;+ if (e.key === '/') { e.preventDefault(); $('#lm-search').focus(); return; }+ if (e.key === '?') { e.preventDefault(); const h = $('#lm-help-modal'); h.hidden ? openModal('lm-help-modal') : closeModal(h); return; }+ if (anyOverlayOpen()) return;+ if (e.key.toLowerCase() === 'n') { e.preventDefault(); openModal('lm-post-modal'); return; }+ if (e.key.toLowerCase() === 'r') { e.preventDefault(); refresh(); toast('Refreshed.', 'info', { ttl: 1400 }); return; }+ if (e.key === '1') return selectTab('open');+ if (e.key === '2') return selectTab('inflight');+ if (e.key === '3') return selectTab('settled');+ });++ // Deep-linking: open the drawer for #b/<id> and honor back/forward.+ const hashBounty = () => (location.hash.startsWith('#b/') ? location.hash.slice(3) : null);+ window.addEventListener('hashchange', () => {+ const id = hashBounty();+ if (id) openBounty(id, { push: false });+ else if (!$('#lm-drawer').hidden) closeDrawer();+ });+ window.addEventListener('popstate', () => {+ const id = hashBounty();+ if (id) openBounty(id, { push: false });else if (!$('#lm-drawer').hidden) closeDrawer();});@@ -677,13 +910,13 @@ function init() {// Initial loadrenderBoard(); // skeletons- Promise.all([loadFeed().catch(() => null), loadMyAgents()]).then(() => {- renderAll();+ Promise.all([loadFeed().catch(() => null), loadMyAgents(), loadModerator()]).then(() => {+ renderAll(true);startPolling();+ const id = hashBounty();+ if (id) openBounty(id, { push: false });});- document.addEventListener('visibilitychange', () => {- if (!document.hidden) refresh();- });+ document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });}if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);diff --git a/src/labs.js b/src/labs.jsindex 5118db48c..eba70ba2d 100644--- a/src/labs.js+++ b/src/labs.js@@ -11,6 +11,11 @@ const CATEGORIES = {'/brain': { label: 'AI', cat: 'ai', color: '#60a5fa', bg: 'rgba(96,165,250,.12)' },'/unstoppable': { label: 'AI', cat: 'ai', color: '#60a5fa', bg: 'rgba(96,165,250,.12)' },'/three-live': { label: '3D Live', cat: '3d', color: '#34d399', bg: 'rgba(52,211,153,.12)' },+ '/diorama': { label: '3D Live', cat: '3d', color: '#34d399', bg: 'rgba(52,211,153,.12)' },+ '/mocap-studio': { label: '3D Live', cat: '3d', color: '#34d399', bg: 'rgba(52,211,153,.12)' },+ '/agenc/embodied': { label: 'AI', cat: 'ai', color: '#60a5fa', bg: 'rgba(96,165,250,.12)' },+ '/autopilot': { label: 'Crypto', cat: 'crypto', color: '#f97316', bg: 'rgba(249,115,22,.12)' },+ '/pulse': { label: 'Crypto', cat: 'crypto', color: '#f97316', bg: 'rgba(249,115,22,.12)' },'/forever': { label: 'Crypto', cat: 'crypto', color: '#f97316', bg: 'rgba(249,115,22,.12)' },};diff --git a/src/studio/money/money-studio.js b/src/studio/money/money-studio.jsindex 46077e7ea..98558eb9f 100644--- a/src/studio/money/money-studio.js+++ b/src/studio/money/money-studio.js@@ -357,13 +357,47 @@ class MoneyStudio {const sol = w.solana_balance == null ? '—' : Number(w.solana_balance).toFixed(4);const usdc = w.usdc_balance == null ? '—' : Number(w.usdc_balance).toFixed(2);return `- <div class="mny-bal"><b>$${esc(usdc)}</b><span>USDC</span></div>- <div class="mny-bal"><b>${esc(sol)}</b><span>SOL</span></div>`;+ <div class="mny-bal"><b data-bal="usdc">$${esc(usdc)}</b><span>USDC</span></div>+ <div class="mny-bal"><b data-bal="sol">${esc(sol)}</b><span>SOL</span></div>`;}_renderWalletBalances() {const host = this._q('[data-balances]');- if (host) host.innerHTML = this._balancesHtml();+ if (!host) return;+ // First paint (or numbers unknown) → set directly. On a live refresh, count+ // each figure from its previous value to the new one and flash the direction,+ // so money moving in/out reads as motion instead of a hard swap.+ const w = this.state.wallet || {};+ const next = { usdc: w.usdc_balance == null ? null : Number(w.usdc_balance), sol: w.solana_balance == null ? null : Number(w.solana_balance) };+ const prev = this._prevBal;+ if (!host.querySelector('[data-bal]') || !prev) { host.innerHTML = this._balancesHtml(); this._prevBal = next; return; }+ this._animateBal(host.querySelector('[data-bal="usdc"]'), prev.usdc, next.usdc, (n) => `$${n.toFixed(2)}`);+ this._animateBal(host.querySelector('[data-bal="sol"]'), prev.sol, next.sol, (n) => n.toFixed(4));+ this._prevBal = next;+ }++ // Count `el` from → to over ~600ms and flash green/red by direction. Honors+ // prefers-reduced-motion (instant, exact) and never animates from/to unknown.+ _animateBal(el, from, to, fmt) {+ if (!el) return;+ if (to == null) { el.textContent = fmt === undefined ? '—' : '—'; return; }+ if (from == null || from === to || (typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches)) {+ el.textContent = fmt(to);+ return;+ }+ el.classList.remove('mny-bal-up', 'mny-bal-down');+ void el.offsetWidth; // restart the flash animation+ el.classList.add(to >= from ? 'mny-bal-up' : 'mny-bal-down');+ const start = performance.now();+ const dur = 600;+ const tick = (now) => {+ const t = Math.min(1, (now - start) / dur);+ const eased = 1 - Math.pow(1 - t, 3);+ el.textContent = fmt(from + (to - from) * eased);+ if (t < 1) requestAnimationFrame(tick);+ else el.textContent = fmt(to);+ };+ requestAnimationFrame(tick);}// ── Pricing ───────────────────────────────────────────────────────────────diff --git a/src/studio/money/trading-brain.js b/src/studio/money/trading-brain.jsindex ea76b893a..ace2dd508 100644--- a/src/studio/money/trading-brain.js+++ b/src/studio/money/trading-brain.js@@ -32,6 +32,7 @@ import { apiFetch } from '../../api.js';import {emptyRule, normalizeRule, validateRule, ruleToEnglish,compileRuleToConfig, configToSniperStrategy,+ PRESETS, applyPreset, matchingPresetId, scoreRisk,} from './trading-compile.js';const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) =>@@ -678,10 +679,17 @@ class TradingBrain {const num = 'type="number" inputmode="decimal" min="0" step="any"';host.innerHTML = `- <label class="tb-name">- <span class="tb-field-l">Rule name</span>- <input data-rule="name" value="${esc(r.name)}" maxlength="60" placeholder="My sniper" />- </label>+ <div class="tb-presets" role="group" aria-label="Strategy presets">+ <span class="tb-presets-l">Start from</span>+ <div class="tb-preset-chips">${this._presetsHtml()}</div>+ </div>+ <div class="tb-topline">+ <label class="tb-name">+ <span class="tb-field-l">Rule name</span>+ <input data-rule="name" value="${esc(r.name)}" maxlength="60" placeholder="My sniper" />+ </label>+ ${this._riskMeterHtml()}+ </div><div class="tb-flow">${this._block('trigger', '◎', 'When', `${field('Launched within (min)', 'trigger.max_age_minutes', r.trigger.max_age_minutes, num, 'min')}@@ -721,6 +729,52 @@ class TradingBrain {<p class="tb-english"><span aria-hidden="true">🗣</span> ${esc(ruleToEnglish(r))}</p>`;}+ _presetsHtml() {+ const active = matchingPresetId(this.rule);+ return PRESETS.map((p) => `+ <button class="tb-preset ${p.id === active ? 'is-on' : ''}" data-action="preset" data-preset="${esc(p.id)}"+ aria-pressed="${p.id === active}" title="${esc(p.tagline)}">+ <span class="tb-preset-name">${esc(p.name)}</span>+ <span class="tb-preset-tag">${esc(p.tagline)}</span>+ </button>`).join('');+ }++ _riskMeterHtml() {+ const { score, label, tone } = scoreRisk(this.rule);+ return `+ <div class="tb-risk tb-risk-${tone}" data-risk title="Aggressiveness scored from your rule — bigger size, deeper stops, wider slippage and fresher targets raise it">+ <div class="tb-risk-top"><span class="tb-risk-l">Risk profile</span><span class="tb-risk-label">${esc(label)}</span></div>+ <div class="tb-risk-track"><div class="tb-risk-fill" style="width:${score}%"></div></div>+ </div>`;+ }++ _renderRiskMeter() {+ const host = this._q('[data-risk]');+ if (!host) return;+ const tmp = document.createElement('div');+ tmp.innerHTML = this._riskMeterHtml().trim();+ const next = tmp.firstElementChild;+ if (next) host.replaceWith(next);+ }++ _applyPreset(id) {+ this.rule = applyPreset(id, { network: this.rule.network });+ this.state.dirty = true;+ this._renderBuilder();+ this._persistMeta();+ this._toast(`Applied "${PRESETS.find((p) => p.id === id)?.name || id}" — tune it, then backtest`);+ }++ // Toggle the active preset chip in place (no re-render) as the rule is edited.+ _syncPresetHighlight() {+ const active = matchingPresetId(this.rule);+ this.el.querySelectorAll('.tb-preset').forEach((btn) => {+ const on = btn.dataset.preset === active;+ btn.classList.toggle('is-on', on);+ btn.setAttribute('aria-pressed', String(on));+ });+ }+_block(key, glyph, title, inner) {return `<div class="tb-node tb-node-${key}">@@ -801,10 +855,13 @@ class TradingBrain {? `<button class="studio-btn studio-btn-danger" data-action="disarm" ${arming ? 'disabled' : ''}>${arming ? 'Disarming…' : 'Disarm agent'}</button>`: `<button class="studio-btn studio-btn-primary" data-action="arm" ${arming ? 'disabled' : ''}>${arming ? 'Arming…' : 'Arm agent'}</button>`): `<button class="studio-btn studio-btn-primary" data-action="scan" ${this.state.scanning ? 'disabled' : ''}>${this.state.scanning ? 'Scanning…' : 'Scan for matches'}</button>`;+ const mac = typeof navigator !== 'undefined' && /Mac|iP(hone|ad)/.test(navigator.platform || navigator.userAgent || '');+ const mod = mac ? '⌘' : 'Ctrl';+ const runHint = this.mode === 'autonomous' ? `${mod}↵` : `${mod}↵`;host.innerHTML = `- <button class="studio-btn studio-btn-ghost" data-action="save" ${saving ? 'disabled' : ''}>${saving ? 'Saving…' : 'Save rule'}</button>- <button class="studio-btn studio-btn-ghost" data-action="backtest" ${this.state.backtesting ? 'disabled' : ''}>${this.state.backtesting ? 'Backtesting…' : 'Backtest'}</button>- ${modeBtn}`;+ <button class="studio-btn studio-btn-ghost" data-action="save" ${saving ? 'disabled' : ''}>${saving ? 'Saving…' : 'Save rule'}<kbd class="tb-kbd">${mod}S</kbd></button>+ <button class="studio-btn studio-btn-ghost" data-action="backtest" ${this.state.backtesting ? 'disabled' : ''}>${this.state.backtesting ? 'Backtesting…' : 'Backtest'}<kbd class="tb-kbd">${mod}B</kbd></button>+ ${modeBtn.replace('</button>', `<kbd class="tb-kbd">${runHint}</kbd></button>`)}`;}_renderAssisted() {@@ -880,9 +937,54 @@ class TradingBrain {<div class="tb-bt-stat"><b>${fmtPct(m.roi_best_pct)}</b><span>best</span></div><div class="tb-bt-stat"><b class="neg">${fmtPct(m.roi_worst_pct)}</b><span>worst</span></div></div>+ ${this._distributionHtml(m.outcome_distribution, b.sample_size)}+ ${this._sampleTradesHtml(b.sample_hits, b.sample_misses)}${b.caveats?.items?.length ? `<details class="tb-caveats"><summary>How this is computed (${b.caveats.items.length} caveats)</summary><ul>${b.caveats.items.map((i) => `<li>${esc(i)}</li>`).join('')}</ul></details>` : ''}`;}+ // A single segmented bar of how the matching launches actually resolved — the+ // honest shape behind the headline win rate (graduated → pumped → flat → rugged).+ _distributionHtml(dist, total) {+ if (!dist || !total) return '';+ const segs = [+ { k: 'graduated', label: 'Graduated', cls: 'grad' },+ { k: 'pumped', label: 'Pumped', cls: 'pump' },+ { k: 'flat', label: 'Flat', cls: 'flat' },+ { k: 'rugged', label: 'Rugged', cls: 'rug' },+ ].map((s) => ({ ...s, n: Number(dist[s.k] || 0) })).filter((s) => s.n > 0);+ if (!segs.length) return '';+ return `+ <div class="tb-dist">+ <div class="tb-dist-l">How ${total} matching launches actually resolved</div>+ <div class="tb-dist-bar" role="img" aria-label="${esc(segs.map((s) => `${s.n} ${s.label}`).join(', '))}">+ ${segs.map((s) => `<span class="tb-dist-seg tb-dist-${s.cls}" style="flex:${s.n}" title="${s.label}: ${s.n} (${Math.round((s.n / total) * 100)}%)"></span>`).join('')}+ </div>+ <div class="tb-dist-legend">${segs.map((s) => `<span class="tb-dist-key"><i class="tb-dist-dot tb-dist-${s.cls}"></i>${esc(s.label)} ${Math.round((s.n / total) * 100)}%</span>`).join('')}</div>+ </div>`;+ }++ // A couple of real best/worst sample trades from the replay, so the projection+ // isn't just aggregate numbers — you see the kind of coin it would have taken.+ _sampleTradesHtml(hits, misses) {+ const row = (t, sign) => {+ const roi = t.roi_pct ?? t.roiPct;+ const cls = (roi ?? 0) >= 0 ? 'pos' : 'neg';+ const name = t.symbol || t.name || short(t.mint || '');+ return `<li class="tb-sample-row"><span class="tb-sample-name">${esc(name)}</span><span class="tb-sample-out">${esc(t.outcome || '')}</span><span class="tb-sample-roi ${cls}">${roi == null ? '—' : fmtPct(roi)}</span></li>`;+ };+ const h = (hits || []).slice(0, 3);+ const m = (misses || []).slice(0, 3);+ if (!h.length && !m.length) return '';+ return `+ <details class="tb-samples">+ <summary>Sample trades from the replay</summary>+ <div class="tb-samples-cols">+ ${h.length ? `<div><div class="tb-samples-h pos">Best</div><ul class="tb-sample-list">${h.map((t) => row(t, '+')).join('')}</ul></div>` : ''}+ ${m.length ? `<div><div class="tb-samples-h neg">Worst</div><ul class="tb-sample-list">${m.map((t) => row(t, '−')).join('')}</ul></div>` : ''}+ </div>+ </details>`;+ }+_renderPositions() {const host = this._q('[data-positions]');if (!host) return;@@ -974,6 +1076,7 @@ class TradingBrain {if (a === 'scan') return this._scan();if (a === 'confirm-snipe') return this._confirmSnipe(btn.dataset.mint);if (a === 'save-guardrails') return this._saveGuardrails();+ if (a === 'preset') return this._applyPreset(btn.dataset.preset);if (a === 'close-pos') return this._closePosition(btn.dataset.pos);if (a === 'export-audit') return this._exportAudit();});@@ -988,6 +1091,17 @@ class TradingBrain {if (!inp) return;this._applyRuleEdit(inp);});+ // Power-user shortcuts, active only while focus is inside this panel:+ // ⌘/Ctrl+S save · ⌘/Ctrl+B backtest · ⌘/Ctrl+Enter run (scan or arm).+ this._onKey = (e) => {+ if (!(e.metaKey || e.ctrlKey)) return;+ if (!this.el.contains(document.activeElement) && !this.el.matches(':hover')) return;+ const k = e.key.toLowerCase();+ if (k === 's') { e.preventDefault(); this._saveStrategy(); }+ else if (k === 'b') { e.preventDefault(); this._backtest(); }+ else if (k === 'enter') { e.preventDefault(); this.mode === 'autonomous' ? (this._armed ? null : this._arm()) : this._scan(); }+ };+ document.addEventListener('keydown', this._onKey);}_applyRuleEdit(inp) {@@ -1002,9 +1116,11 @@ class TradingBrain {obj[path[path.length - 1]] = v;this.state.dirty = true;// Live english + validation refresh without stealing focus: update just the- // english line + error spans, not the whole builder.+ // english line, the risk meter, and the preset highlight — not the whole builder.const eng = this._q('.tb-english');if (eng) eng.innerHTML = `<span aria-hidden="true">🗣</span> ${esc(ruleToEnglish(this.rule))}`;+ this._renderRiskMeter();+ this._syncPresetHighlight();clearTimeout(this._metaTimer);this._metaTimer = setTimeout(() => this._persistMeta(), 700);}@@ -1022,6 +1138,7 @@ class TradingBrain {destroy() {this._destroyed = true;this._stopLivePolling();+ if (this._onKey) { document.removeEventListener('keydown', this._onKey); this._onKey = null; }clearTimeout(this._metaTimer);clearTimeout(this._toastTimer);}diff --git a/src/studio/money/trading-compile.js b/src/studio/money/trading-compile.jsindex 96ea6432d..8aec7fb68 100644--- a/src/studio/money/trading-compile.js+++ b/src/studio/money/trading-compile.js@@ -47,6 +47,99 @@ function num(v) {return Number.isFinite(n) ? n : null;}+const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));++/**+ * Named starting points a trader can apply in one tap, then tune. Each is a full,+ * valid rule (compiles + validates cleanly) tuned to a real risk posture — from+ * "protect capital" to "chase fresh launches". These are opinionated defaults, not+ * advice: every one still runs inside the owner's server-side guardrails.+ */+export const PRESETS = Object.freeze([+ {+ id: 'guardian', name: 'Guardian', tagline: 'Capital-first. Established coins, tight risk.',+ rule: {+ name: 'Guardian', trigger: { max_age_minutes: 120 },+ filters: { min_market_cap_usd: 30000, max_market_cap_usd: 250000, min_liquidity_sol: 15, require_socials: true, min_creator_graduated: 1, max_creator_launches: null, require_sol_quote: true },+ buy: { amount_sol: 0.05, max_slippage_bps: 300 },+ exits: { take_profit_pct: 40, stop_loss_pct: 20, trailing_stop_pct: 15, max_hold_minutes: 240 },+ risk: { max_concurrent_positions: 2, cooldown_minutes: 10 },+ },+ },+ {+ id: 'balanced', name: 'Balanced', tagline: 'The sensible default. Fresh but filtered.',+ rule: {+ name: 'Balanced', trigger: { max_age_minutes: 30 },+ filters: { min_market_cap_usd: null, max_market_cap_usd: 60000, min_liquidity_sol: 5, require_socials: true, min_creator_graduated: null, max_creator_launches: null, require_sol_quote: true },+ buy: { amount_sol: 0.1, max_slippage_bps: 500 },+ exits: { take_profit_pct: 100, stop_loss_pct: 40, trailing_stop_pct: null, max_hold_minutes: 120 },+ risk: { max_concurrent_positions: 3, cooldown_minutes: 3 },+ },+ },+ {+ id: 'hunter', name: 'Hunter', tagline: 'Early entries on brand-new launches.',+ rule: {+ name: 'Hunter', trigger: { max_age_minutes: 10 },+ filters: { min_market_cap_usd: null, max_market_cap_usd: 30000, min_liquidity_sol: null, require_socials: false, min_creator_graduated: null, max_creator_launches: null, require_sol_quote: true },+ buy: { amount_sol: 0.2, max_slippage_bps: 900 },+ exits: { take_profit_pct: 200, stop_loss_pct: 45, trailing_stop_pct: 25, max_hold_minutes: 60 },+ risk: { max_concurrent_positions: 5, cooldown_minutes: 0 },+ },+ },+ {+ id: 'moonshot', name: 'Moonshot', tagline: 'Highest risk. Tiny caps, big targets.',+ rule: {+ name: 'Moonshot', trigger: { max_age_minutes: 5 },+ filters: { min_market_cap_usd: null, max_market_cap_usd: 15000, min_liquidity_sol: null, require_socials: false, min_creator_graduated: null, max_creator_launches: null, require_sol_quote: true },+ buy: { amount_sol: 0.25, max_slippage_bps: 1200 },+ exits: { take_profit_pct: 400, stop_loss_pct: 55, trailing_stop_pct: 30, max_hold_minutes: 45 },+ risk: { max_concurrent_positions: 6, cooldown_minutes: 0 },+ },+ },+]);++/** Apply a preset id onto a fresh rule, preserving the trader's chosen network. */+export function applyPreset(id, { network = 'mainnet' } = {}) {+ const p = PRESETS.find((x) => x.id === id);+ if (!p) return emptyRule();+ return normalizeRule({ ...p.rule, network });+}++/** Which preset (if any) the current rule matches exactly — for highlighting. */+export function matchingPresetId(rule) {+ const target = JSON.stringify(stripName(normalizeRule(rule)));+ for (const p of PRESETS) {+ if (JSON.stringify(stripName(normalizeRule({ ...p.rule, network: normalizeRule(rule).network }))) === target) return p.id;+ }+ return null;+}++function stripName(r) { const { name, ...rest } = r; return rest; }++/**+ * Score a rule's aggressiveness on a 0–100 scale from its own parameters — bigger+ * size, deeper stops, wider slippage, fresher/smaller-cap targets, more concurrent+ * exposure, and loftier profit targets all push it up. Pure + deterministic so the+ * meter the UI shows matches what any test asserts. Returns a score, a human label,+ * and a tone token for styling.+ */+export function scoreRisk(rule) {+ const r = normalizeRule(rule);+ let s = 0;+ s += clamp((r.buy.amount_sol / 1) * 25, 0, 25); // per-trade size+ s += clamp(((r.exits.stop_loss_pct ?? 40) / 60) * 18, 0, 18); // downside tolerated+ s += clamp((r.buy.max_slippage_bps / 1500) * 15, 0, 15); // slippage ceiling+ const mc = r.filters.max_market_cap_usd; // cap ceiling: lower = fresher = riskier+ s += mc == null ? 15 : clamp(15 - (mc / 200000) * 12, 3, 15);+ if (!r.filters.require_socials) s += 8; // no socials gate+ s += clamp((r.risk.max_concurrent_positions / 8) * 10, 0, 10); // concurrent exposure+ s += clamp(((r.exits.take_profit_pct ?? 0) / 300) * 9, 0, 9); // profit ambition+ const score = Math.round(clamp(s, 0, 100));+ const label = score < 25 ? 'Conservative' : score < 50 ? 'Balanced' : score < 75 ? 'Aggressive' : 'Degen';+ const tone = score < 25 ? 'calm' : score < 50 ? 'balanced' : score < 75 ? 'warm' : 'hot';+ return { score, label, tone };+}+/** Deep-clone the default rule (so callers never mutate the frozen template). */export function emptyRule() {return structuredClone(DEFAULT_RULE);diff --git a/src/x402-revenue.css b/src/x402-revenue.cssindex ea53a479b..5d74365f4 100644--- a/src/x402-revenue.css+++ b/src/x402-revenue.css@@ -22,8 +22,16 @@inset: -10% -20% auto -20%;height: 420px;background:- radial-gradient(60% 80% at 20% 0%, color-mix(in srgb, var(--xr-accent) 20%, transparent), transparent 70%),- radial-gradient(50% 70% at 85% 10%, color-mix(in srgb, var(--xr-accent-2) 16%, transparent), transparent 70%);+ radial-gradient(+ 60% 80% at 20% 0%,+ color-mix(in srgb, var(--xr-accent) 20%, transparent),+ transparent 70%+ ),+ radial-gradient(+ 50% 70% at 85% 10%,+ color-mix(in srgb, var(--xr-accent-2) 16%, transparent),+ transparent 70%+ );filter: blur(20px);pointer-events: none;z-index: 0;diff --git a/src/x402-revenue.js b/src/x402-revenue.jsindex c0eb436a8..7efebdf93 100644--- a/src/x402-revenue.js+++ b/src/x402-revenue.js@@ -3,9 +3,11 @@* x402 paid endpoints. The mirror of the Money Pulse (which shows agent SPEND):* this page reads the platform's revenue ledger via GET /api/x402-revenue.*- * GET /api/x402-revenue?view=stats&period= headline totals + top endpoints- * GET /api/x402-revenue?view=feed recent settlements (keyset)- * GET /api/x402-revenue?since=<iso> delta poll — only newer settlements+ * GET /api/x402-revenue?view=stats&period= totals, per-endpoint, per-network,+ * time-series, momentum, health+ * GET /api/x402-revenue?view=feed&… recent settlements (keyset, filterable)+ * GET /api/x402-revenue?since=<iso>&… delta poll — only newer settlements+ * GET /api/x402-revenue?view=export&… CSV of the window** Every row is a real, explorer-verifiable settlement. No synthetic events: a* quiet platform shows an honest empty state.@@ -15,21 +17,31 @@ import { timeAgo } from './shared/pulse-format.js';const POLL_MS = 12_000; // live delta cadence when visibleconst STATS_REFRESH_MS = 60_000;+const PERIODS = ['24h', '7d', '30d', 'all'];+const NETWORKS = ['solana', 'base', 'bsc'];const $ = (id) => document.getElementById(id);const state = {period: '24h',- latestTs: null, // ISO of the newest settlement we've rendered- seen: new Set(), // event ids already in the feed (dedupe delta polls)+ endpoint: null, // slug feed filter+ network: null, // network feed filter+ query: '', // client-side search+ paused: false,+ sound: false,+ seen: new Set(),+ latestTs: null,+ cursor: null, // oldest ts loaded (load-more)pollTimer: null,statsTimer: null,+ firstChart: true,};// ── formatters ───────────────────────────────────────────────────────────────function fmtUsd(v) {const n = Number(v) || 0;if (n === 0) return '$0';+ if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`;if (n >= 1000) return `$${(n / 1000).toFixed(1)}k`;if (n >= 1) return `$${n.toFixed(2)}`;if (n >= 0.01) return `$${n.toFixed(3)}`;@@ -41,6 +53,10 @@ function fmtInt(v) {function fmtPct(v) {return `${Math.round((Number(v) || 0) * 100)}%`;}+function fmtSignedPct(v) {+ const n = Math.round((Number(v) || 0) * 100);+ return `${n > 0 ? '+' : ''}${n}%`;+}function esc(s) {return String(s ?? '').replace(/[&<>"']/g,@@ -53,6 +69,47 @@ function endpointLabel(route) {return m ? m[1] : (route || 'unknown').replace(/^\/api\//, '');}+// ── URL deep-link ────────────────────────────────────────────────────────────+function readUrl() {+ const p = new URLSearchParams(location.search);+ const per = p.get('period');+ if (PERIODS.includes(per)) state.period = per;+ const ep = (p.get('endpoint') || '').replace(/[^a-z0-9-]/gi, '');+ if (ep) state.endpoint = ep;+ const net = (p.get('network') || '').toLowerCase();+ if (NETWORKS.includes(net)) state.network = net;+}+function writeUrl() {+ const p = new URLSearchParams();+ if (state.period !== '24h') p.set('period', state.period);+ if (state.endpoint) p.set('endpoint', state.endpoint);+ if (state.network) p.set('network', state.network);+ const qs = p.toString();+ history.replaceState(null, '', qs ? `${location.pathname}?${qs}` : location.pathname);+}+function feedParams(extra = {}) {+ const p = new URLSearchParams();+ if (state.endpoint) p.set('endpoint', state.endpoint);+ if (state.network) p.set('network', state.network);+ for (const [k, v] of Object.entries(extra)) if (v != null) p.set(k, String(v));+ return p.toString();+}++// ── toast ─────────────────────────────────────────────────────────────────────+let toastTimer = null;+function toast(msg) {+ const el = $('xr-toast');+ if (!el) return;+ el.textContent = msg;+ el.hidden = false;+ requestAnimationFrame(() => el.classList.add('show'));+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => {+ el.classList.remove('show');+ setTimeout(() => (el.hidden = true), 220);+ }, 1800);+}+// ── stats ─────────────────────────────────────────────────────────────────────function setCounter(id, value, format) {const el = $(id);@@ -75,7 +132,7 @@ async function loadStats() {},);} catch {- return; // transient network blip — keep last-known counters+ return; // transient blip — keep last-known}if (!res.ok) return;const { data } = await res.json();@@ -102,9 +159,38 @@ function renderStats(d) {if (gs)gs.textContent = `${fmtInt(t.total_payments || 0)} settled · avg ${fmtUsd(t.avg_payment_usd)}`;- const win = $('xr-top-window');- if (win) win.textContent = d.period || state.period;+ for (const id of ['xr-window-label', 'xr-top-window', 'xr-net-window']) {+ const el = $(id);+ if (el) el.textContent = d.period || state.period;+ }++ renderMomentum(d.momentum);+ renderRunRate(d.momentum);+ renderChart(d.series);renderTopEndpoints(d.by_endpoint || []);+ renderNetworks(d.by_network || []);+ renderChips(d.by_endpoint || [], d.by_network || []);+}++function renderMomentum(m) {+ const el = $('xr-momentum');+ if (!el) return;+ if (!m || m.change_pct == null) {+ el.hidden = true;+ return;+ }+ const pct = Number(m.change_pct);+ const dir = pct > 0.001 ? 'up' : pct < -0.001 ? 'down' : 'flat';+ el.dataset.dir = dir;+ const arrow = dir === 'up' ? '▲' : dir === 'down' ? '▼' : '→';+ el.textContent = `${arrow} ${fmtSignedPct(pct)} vs prev ${state.period}`;+ el.hidden = false;+}++function renderRunRate(m) {+ const el = $('xr-runrate');+ if (!el) return;+ el.textContent = m && m.per_hour_usd != null ? fmtUsd(m.per_hour_usd) : '—';}function renderTopEndpoints(rows) {@@ -119,16 +205,243 @@ function renderTopEndpoints(rows) {.slice(0, 8).map((r) => {const g = Number(r.gross_usd) || 0;+ const slug = endpointLabel(r.endpoint);const pct = max > 0 ? Math.max(2, Math.round((g / max) * 100)) : 2;+ const active = state.endpoint === slug ? ' active' : '';return (- `<div class="xr-top-row">` ++ `<div class="xr-top-row${active}" role="button" tabindex="0" data-endpoint="${esc(slug)}" aria-label="Filter feed to ${esc(slug)}">` +`<span class="xr-top-bar" style="width:${pct}%" aria-hidden="true"></span>` +- `<span class="xr-top-name">${esc(endpointLabel(r.endpoint))}</span>` ++ `<span class="xr-top-name">${esc(slug)}</span>` +`<span class="xr-top-val">${fmtUsd(g)}<small>${fmtInt(r.count)} call${r.count === 1 ? '' : 's'}</small></span>` +`</div>`);}).join('');+ for (const el of host.querySelectorAll('[data-endpoint]')) {+ const slug = el.dataset.endpoint;+ el.addEventListener('click', () => toggleEndpoint(slug));+ el.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ toggleEndpoint(slug);+ }+ });+ }+}++function renderNetworks(rows) {+ const host = $('xr-networks');+ if (!host) return;+ const real = rows.filter((r) => Number(r.gross_usd) > 0 || Number(r.count) > 0);+ if (!real.length) {+ host.innerHTML = `<p class="xr-empty">No network revenue in this window yet.</p>`;+ return;+ }+ const max = Math.max(...real.map((r) => Number(r.gross_usd) || 0), 0);+ host.innerHTML = real+ .map((r) => {+ const g = Number(r.gross_usd) || 0;+ const pct = max > 0 ? Math.max(3, Math.round((g / max) * 100)) : 3;+ return (+ `<div class="xr-net-row">` ++ `<span class="xr-net-name">${esc(r.network)}</span>` ++ `<span class="xr-net-track"><span class="xr-net-fill" style="width:${pct}%"></span></span>` ++ `<span class="xr-net-val">${fmtUsd(g)}</span>` ++ `</div>`+ );+ })+ .join('');+}++// ── SVG area chart ────────────────────────────────────────────────────────────+function bucketStepMs(unit) {+ return unit === 'day' ? 86_400_000 : 3_600_000;+}+function truncUTC(ms, unit) {+ const d = new Date(ms);+ if (unit === 'day') d.setUTCHours(0, 0, 0, 0);+ else d.setUTCMinutes(0, 0, 0);+ return d.getTime();+}+// Fill gaps (buckets with no revenue) so the area stays continuous and honest.+function fillGaps(series) {+ const unit = series?.unit || 'hour';+ const pts = (series?.points || []).map((p) => ({+ ms: Date.parse(p.ts),+ gross: Number(p.gross_usd) || 0,+ count: p.count || 0,+ }));+ if (!pts.length) return { unit, points: [] };+ const step = bucketStepMs(unit);+ const map = new Map(pts.map((p) => [truncUTC(p.ms, unit), p]));+ const start = truncUTC(pts[0].ms, unit);+ const end = truncUTC(Date.now(), unit);+ const out = [];+ for (let t = start; t <= end && out.length < 400; t += step) {+ const p = map.get(t);+ out.push({+ ts: new Date(t).toISOString(),+ gross_usd: p ? p.gross : 0,+ count: p ? p.count : 0,+ });+ }+ return { unit, points: out };+}+function bucketLabel(iso, unit) {+ const d = new Date(iso);+ if (unit === 'day') return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });+ return d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });+}++function renderChart(series) {+ const host = $('xr-chart');+ const empty = $('xr-chart-empty');+ if (!host) return;+ const filled = fillGaps(series);+ const points = filled.points;+ const hasData = points.some((p) => p.gross_usd > 0);+ if (!points.length || !hasData) {+ host.innerHTML = '';+ if (empty) empty.hidden = false;+ host._points = null;+ return;+ }+ if (empty) empty.hidden = true;++ const W = 800;+ const H = 160;+ const pad = 8;+ const n = points.length;+ const max = Math.max(...points.map((p) => p.gross_usd), 0.000001);+ const x = (i) => pad + (i / (n - 1 || 1)) * (W - 2 * pad);+ const y = (v) => H - pad - (v / max) * (H - 2 * pad);+ const pairs = points.map((p, i) => `${x(i).toFixed(1)},${y(p.gross_usd).toFixed(1)}`);+ const linePath = `M${pairs.join(' L')}`;+ const areaPath = `M${x(0).toFixed(1)},${H} L${pairs.join(' L')} L${x(n - 1).toFixed(1)},${H} Z`;+ const drawCls = state.firstChart ? ' xr-chart-draw' : '';++ host.innerHTML =+ `<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-hidden="true">` ++ `<defs><linearGradient id="xrGrad" x1="0" y1="0" x2="0" y2="1">` ++ `<stop offset="0%" stop-color="var(--xr-accent)" stop-opacity="0.32"/>` ++ `<stop offset="100%" stop-color="var(--xr-accent)" stop-opacity="0"/>` ++ `</linearGradient></defs>` ++ `<path class="xr-chart-area" d="${areaPath}" fill="url(#xrGrad)"/>` ++ `<line class="xr-chart-cross" id="xr-cross" x1="0" y1="0" x2="0" y2="${H}" vector-effect="non-scaling-stroke" style="display:none"/>` ++ `<path class="xr-chart-line${drawCls}" d="${linePath}" vector-effect="non-scaling-stroke"/>` ++ `<circle class="xr-chart-dot" id="xr-dot" r="3.5" vector-effect="non-scaling-stroke" style="display:none"/>` ++ `</svg>`;++ // animate the draw only the first time+ if (state.firstChart) {+ const line = host.querySelector('.xr-chart-line');+ if (line) {+ try {+ const len = line.getTotalLength();+ line.style.setProperty('--len', String(Math.ceil(len)));+ } catch {+ line.classList.remove('xr-chart-draw');+ }+ }+ state.firstChart = false;+ }++ host._points = { points, unit: filled.unit, x, y, W, H };+ wireChartHover(host);+}++function wireChartHover(host) {+ const tip = $('xr-chart-tip');+ const move = (clientX) => {+ const ctx = host._points;+ if (!ctx) return;+ const rect = host.getBoundingClientRect();+ const ratio = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));+ const idx = Math.round(ratio * (ctx.points.length - 1));+ const p = ctx.points[idx];+ if (!p) return;+ const cross = host.querySelector('#xr-cross');+ const dot = host.querySelector('#xr-dot');+ const cx = ctx.x(idx);+ const cy = ctx.y(p.gross_usd);+ if (cross) {+ cross.setAttribute('x1', cx);+ cross.setAttribute('x2', cx);+ cross.style.display = '';+ }+ if (dot) {+ dot.setAttribute('cx', cx);+ dot.setAttribute('cy', cy);+ dot.style.display = '';+ }+ if (tip) {+ tip.innerHTML = `<b>${fmtUsd(p.gross_usd)}</b> <span>· ${esc(bucketLabel(p.ts, ctx.unit))} · ${fmtInt(p.count)} call${p.count === 1 ? '' : 's'}</span>`;+ tip.style.left = `${(cx / ctx.W) * 100}%`;+ tip.hidden = false;+ }+ };+ host.onpointermove = (e) => move(e.clientX);+ host.onpointerleave = () => {+ const cross = host.querySelector('#xr-cross');+ const dot = host.querySelector('#xr-dot');+ if (cross) cross.style.display = 'none';+ if (dot) dot.style.display = 'none';+ if (tip) tip.hidden = true;+ };+}++// ── filter chips ──────────────────────────────────────────────────────────────+function renderChips(topEndpoints, networks) {+ const host = $('xr-chips');+ if (!host) return;+ const chips = [];+ const anyFilter = state.endpoint || state.network;+ chips.push(+ `<button type="button" class="xr-chip${anyFilter ? '' : ' active'}" data-all="1">All</button>`,+ );+ for (const r of topEndpoints.slice(0, 6)) {+ const slug = endpointLabel(r.endpoint);+ const active = state.endpoint === slug ? ' active' : '';+ chips.push(+ `<button type="button" class="xr-chip${active}" data-endpoint="${esc(slug)}">${esc(slug)}</button>`,+ );+ }+ for (const r of networks.filter((nr) => Number(nr.count) > 0).slice(0, 4)) {+ if (!NETWORKS.includes(r.network)) continue;+ const active = state.network === r.network ? ' active' : '';+ chips.push(+ `<button type="button" class="xr-chip${active}" data-network="${esc(r.network)}">${esc(r.network)}</button>`,+ );+ }+ host.innerHTML = chips.join('');+ host.querySelector('[data-all]')?.addEventListener('click', clearFilters);+ for (const el of host.querySelectorAll('[data-endpoint]')) {+ el.addEventListener('click', () => toggleEndpoint(el.dataset.endpoint));+ }+ for (const el of host.querySelectorAll('[data-network]')) {+ el.addEventListener('click', () => toggleNetwork(el.dataset.network));+ }+}++function toggleEndpoint(slug) {+ state.endpoint = state.endpoint === slug ? null : slug;+ writeUrl();+ reloadFeed();+ loadStats(); // refresh chip active states+}+function toggleNetwork(net) {+ state.network = state.network === net ? null : net;+ writeUrl();+ reloadFeed();+ loadStats();+}+function clearFilters() {+ if (!state.endpoint && !state.network) return;+ state.endpoint = null;+ state.network = null;+ writeUrl();+ reloadFeed();+ loadStats();}// ── feed ────────────────────────────────────────────────────────────────────@@ -148,6 +461,10 @@ function setFeedState(s) {: 'connecting…';}+function searchText(e) {+ return `${endpointLabel(e.route)} ${e.payer || ''} ${e.tx || ''} ${e.network || ''}`.toLowerCase();+}+function rowHTML(e) {const label = endpointLabel(e.route);const tx = e.tx_url@@ -157,8 +474,9 @@ function rowHTML(e) {? `<span class="xr-row-payer" title="payer wallet">${esc(e.payer)}</span>`: '';const net = e.network ? `<span class="xr-row-net">${esc(e.network)}</span>` : '';+ const hidden = state.query && !searchText(e).includes(state.query) ? ' hidden' : '';return (- `<div class="xr-row" data-id="${esc(e.id)}">` ++ `<div class="xr-row${hidden}" data-id="${esc(e.id)}" data-tx="${esc(e.tx || '')}" data-search="${esc(searchText(e))}" role="button" tabindex="0" aria-label="${esc(label)} settled ${esc(e.amount_usd)} — click to copy tx">` +`<span class="xr-row-glyph" aria-hidden="true">→</span>` +`<span class="xr-row-body">` +`<span class="xr-row-line"><span class="xr-row-ep">${esc(label)}</span> ${payer}</span>` +@@ -169,22 +487,51 @@ function rowHTML(e) {);}+function wireRow(node) {+ node.addEventListener('click', (e) => {+ if (e.target.closest('.xr-row-tx')) return; // let the explorer link work+ const tx = node.dataset.tx;+ if (tx && navigator.clipboard) {+ navigator.clipboard.writeText(tx).then(+ () => toast('Transaction signature copied'),+ () => toast(tx.slice(0, 16) + '…'),+ );+ }+ });+ node.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') node.click();+ });+}++function showSkeleton() {+ const host = $('xr-feed');+ if (!host) return;+ host.innerHTML = Array.from({ length: 6 }, () => `<div class="xr-skel"></div>`).join('');+}+function renderInitialFeed(events) {const host = $('xr-feed');if (!host) return;if (!events.length) {+ const filtered = state.endpoint || state.network;host.innerHTML =`<div class="xr-feed-empty">` +- `<p class="xr-feed-empty-h">No settled payments in this window yet.</p>` +- `<p class="xr-feed-empty-p">The instant an agent or app pays one of the platform's x402 endpoints, the settlement lands here — live and verifiable. Browse what's payable in the <a href="/docs/x402-endpoints">endpoint catalog</a>.</p>` ++ `<p class="xr-feed-empty-h">${filtered ? 'No settlements match this filter yet.' : 'No settled payments yet.'}</p>` ++ `<p class="xr-feed-empty-p">${+ filtered+ ? 'Clear the filter to see the whole feed, or wait for the next matching settlement to land.'+ : 'The instant an agent or app pays one of the platform\'s x402 endpoints, the settlement lands here — live and verifiable. Browse what\'s payable in the <a href="/docs/x402-endpoints">endpoint catalog</a>.'+ }</p>` +`</div>`;setFeedState('empty');+ state.latestTs = null;return;}host.innerHTML = events.map(rowHTML).join('');+ for (const node of host.querySelectorAll('.xr-row')) wireRow(node);for (const e of events) state.seen.add(e.id);state.latestTs = events[0].ts;- setFeedState('live');+ setFeedState(state.paused ? 'paused' : 'live');}function prependEvents(events) {@@ -192,29 +539,30 @@ function prependEvents(events) {if (!host) return;const fresh = events.filter((e) => !state.seen.has(e.id));if (!fresh.length) return;- // If the feed was empty, replace the empty-state block first.const emptyEl = host.querySelector('.xr-feed-empty');if (emptyEl) host.innerHTML = '';const frag = document.createElement('div');frag.innerHTML = fresh.map(rowHTML).join('');- // Newest first: insert in reverse so the very latest ends up on top.const nodes = Array.from(frag.children).reverse();for (const node of nodes) {node.classList.add('xr-row--new');+ wireRow(node);host.prepend(node);}for (const e of fresh) state.seen.add(e.id);state.latestTs = fresh[0].ts;- // Trim very long feeds to keep the DOM light.+ chime();const rows = host.querySelectorAll('.xr-row');- for (let i = 200; i < rows.length; i++) rows[i].remove();+ for (let i = 240; i < rows.length; i++) rows[i].remove();}async function loadInitialFeed() {setFeedState('loading');+ showSkeleton();+ state.seen.clear();let res;try {- res = await fetch('/api/x402-revenue?view=feed&limit=30', {+ res = await fetch(`/api/x402-revenue?view=feed&limit=30&${feedParams()}`, {headers: { accept: 'application/json' },});} catch {@@ -227,13 +575,55 @@ async function loadInitialFeed() {}const { data } = await res.json();renderInitialFeed(data?.events || []);+ state.cursor = data?.next_cursor || null;+ const more = $('xr-more');+ if (more) more.hidden = !state.cursor;+}++function reloadFeed() {+ loadInitialFeed();+}++async function loadMore() {+ if (!state.cursor) return;+ const more = $('xr-more');+ if (more) more.textContent = 'Loading…';+ let res;+ try {+ res = await fetch(+ `/api/x402-revenue?view=feed&limit=30&${feedParams({ cursor: state.cursor })}`,+ {+ headers: { accept: 'application/json' },+ },+ );+ } catch {+ if (more) more.textContent = 'Load older settlements';+ return;+ }+ const { data } = res.ok ? await res.json() : { data: null };+ const host = $('xr-feed');+ const events = (data?.events || []).filter((e) => !state.seen.has(e.id));+ if (host && events.length) {+ const frag = document.createElement('div');+ frag.innerHTML = events.map(rowHTML).join('');+ for (const node of Array.from(frag.children)) {+ wireRow(node);+ host.appendChild(node);+ }+ for (const e of events) state.seen.add(e.id);+ }+ state.cursor = data?.next_cursor || null;+ if (more) {+ more.hidden = !state.cursor;+ more.textContent = 'Load older settlements';+ }}async function pollDelta() {- if (!state.latestTs) return; // nothing to delta against yet (empty feed)+ if (state.paused || !state.latestTs) return;let res;try {- res = await fetch(`/api/x402-revenue?since=${encodeURIComponent(state.latestTs)}`, {+ res = await fetch(`/api/x402-revenue?${feedParams({ since: state.latestTs })}`, {headers: { accept: 'application/json' },});} catch {@@ -252,22 +642,14 @@ async function pollDelta() {function startPolling() {if (state.pollTimer) return;state.pollTimer = setInterval(() => {- if (!document.hidden) {- // When the feed is empty we re-fetch the head (a first payment may have landed).- state.latestTs ? pollDelta() : loadInitialFeed();- }+ if (document.hidden || state.paused) return;+ state.latestTs ? pollDelta() : loadInitialFeed();}, POLL_MS);}-function stopPolling() {- if (state.pollTimer) {- clearInterval(state.pollTimer);- state.pollTimer = null;- }-}-// ── period switch ─────────────────────────────────────────────────────────────+// ── controls ──────────────────────────────────────────────────────────────────function setPeriod(period) {- const target = ['24h', '7d', '30d', 'all'].includes(period) ? period : '24h';+ const target = PERIODS.includes(period) ? period : '24h';if (target === state.period) return;state.period = target;for (const b of document.querySelectorAll('[data-period]')) {@@ -275,9 +657,9 @@ function setPeriod(period) {b.classList.toggle('active', on);b.setAttribute('aria-selected', String(on));}+ writeUrl();loadStats();}-function wirePeriod() {for (const btn of document.querySelectorAll('[data-period]')) {btn.addEventListener('click', () => setPeriod(btn.dataset.period));@@ -288,20 +670,137 @@ function wirePeriod() {}});}+ // reflect restored period in the tab UI+ for (const b of document.querySelectorAll('[data-period]')) {+ const on = b.dataset.period === state.period;+ b.classList.toggle('active', on);+ b.setAttribute('aria-selected', String(on));+ }+}++function togglePause() {+ state.paused = !state.paused;+ const btn = $('xr-pause');+ if (btn) {+ btn.setAttribute('aria-pressed', String(state.paused));+ btn.querySelector('.xr-pause-ico').textContent = state.paused ? '▶' : '॥';+ }+ setFeedState(state.paused ? 'paused' : 'live');+ if (!state.paused) pollDelta();+ toast(state.paused ? 'Live feed paused' : 'Live feed resumed');+}++let audioCtx = null;+function chime() {+ if (!state.sound) return;+ try {+ audioCtx = audioCtx || new (window.AudioContext || window.webkitAudioContext)();+ const t = audioCtx.currentTime;+ const o = audioCtx.createOscillator();+ const g = audioCtx.createGain();+ o.type = 'sine';+ o.frequency.setValueAtTime(880, t);+ o.frequency.exponentialRampToValueAtTime(1320, t + 0.08);+ g.gain.setValueAtTime(0.0001, t);+ g.gain.exponentialRampToValueAtTime(0.06, t + 0.02);+ g.gain.exponentialRampToValueAtTime(0.0001, t + 0.26);+ o.connect(g).connect(audioCtx.destination);+ o.start(t);+ o.stop(t + 0.27);+ } catch {+ /* audio unavailable — silent */+ }+}+function toggleSound() {+ state.sound = !state.sound;+ const btn = $('xr-sound');+ if (btn) btn.setAttribute('aria-pressed', String(state.sound));+ try {+ localStorage.setItem('xr_sound', state.sound ? '1' : '0');+ } catch {+ /* ignore */+ }+ if (state.sound) chime();+ toast(state.sound ? 'Chime on new settlements' : 'Chime off');+}++function exportCsv() {+ const p = new URLSearchParams({ view: 'export', period: state.period });+ if (state.endpoint) p.set('endpoint', state.endpoint);+ if (state.network) p.set('network', state.network);+ window.open(`/api/x402-revenue?${p.toString()}`, '_blank', 'noopener');+ toast('Exporting CSV…');+}++function wireSearch() {+ const input = $('xr-search');+ if (!input) return;+ let deb = null;+ input.addEventListener('input', () => {+ clearTimeout(deb);+ deb = setTimeout(() => {+ state.query = input.value.trim().toLowerCase();+ for (const row of document.querySelectorAll('#xr-feed .xr-row')) {+ row.classList.toggle(+ 'hidden',+ state.query && !row.dataset.search.includes(state.query),+ );+ }+ }, 120);+ });+}++function wireKeys() {+ document.addEventListener('keydown', (e) => {+ const typing = e.target.matches('input, textarea, [contenteditable]');+ if (typing) {+ if (e.key === 'Escape') e.target.blur();+ return;+ }+ if (e.metaKey || e.ctrlKey || e.altKey) return;+ if (e.key === '/') {+ e.preventDefault();+ $('xr-search')?.focus();+ } else if (e.key === 'p') {+ togglePause();+ } else if (e.key === 's') {+ toggleSound();+ } else if (e.key === 'e') {+ exportCsv();+ } else if (['1', '2', '3', '4'].includes(e.key)) {+ setPeriod(PERIODS[Number(e.key) - 1]);+ }+ });}function onVisibility() {if (document.hidden) {- setFeedState('paused');+ if (!state.paused) setFeedState('paused');} else {- setFeedState(state.latestTs ? 'live' : 'empty');- pollDelta();+ setFeedState(state.paused ? 'paused' : state.latestTs ? 'live' : 'empty');+ if (!state.paused) pollDelta();loadStats();}}function init() {+ readUrl();+ // restore persisted sound preference+ try {+ state.sound = localStorage.getItem('xr_sound') === '1';+ } catch {+ /* ignore */+ }+ $('xr-sound')?.setAttribute('aria-pressed', String(state.sound));+wirePeriod();+ wireSearch();+ wireKeys();+ $('xr-pause')?.addEventListener('click', togglePause);+ $('xr-sound')?.addEventListener('click', toggleSound);+ $('xr-export')?.addEventListener('click', exportCsv);+ $('xr-more')?.addEventListener('click', loadMore);+loadStats();loadInitialFeed().then(startPolling);state.statsTimer = setInterval(() => {diff --git a/tests/github-reward.test.js b/tests/github-reward.test.jsnew file mode 100644index 000000000..db011577d--- /dev/null+++ b/tests/github-reward.test.js@@ -0,0 +1,35 @@+import { describe, it, expect } from 'vitest';+import { resolveSocialReward, resolveGithubReward, SOCIAL_PLATFORM_ID } from '../api/_lib/github-reward.js';++// These exercise the no-DB paths (missing identity → unresolved) so they run+// without a database. The wallet / social_pda paths are covered by integration.++describe('SOCIAL_PLATFORM_ID', () => {+ it('matches the pump.fun SDK Platform enum', () => {+ expect(SOCIAL_PLATFORM_ID).toEqual({ pump: 0, x: 1, github: 2 });+ });+});++describe('resolveSocialReward', () => {+ it('returns unresolved (no DB hit) when no identity is given', async () => {+ const r = await resolveSocialReward({ platform: 'x' });+ expect(r.platform).toBe('x');+ expect(r.mode).toBe('unresolved');+ expect(r.address).toBeNull();+ expect(r.note).toMatch(/X account/);+ });+ it('defaults the platform to github', async () => {+ const r = await resolveSocialReward({});+ expect(r.platform).toBe('github');+ expect(r.note).toMatch(/GitHub user/);+ });+});++describe('resolveGithubReward (back-compat wrapper)', () => {+ it('preserves the original github_* field shape', async () => {+ const r = await resolveGithubReward({});+ expect(r).toHaveProperty('github_username');+ expect(r).toHaveProperty('github_user_id');+ expect(r.mode).toBe('unresolved');+ });+});diff --git a/tests/launch-usecases.test.js b/tests/launch-usecases.test.jsindex a9f0e06d0..80219bc93 100644--- a/tests/launch-usecases.test.js+++ b/tests/launch-usecases.test.js@@ -68,6 +68,24 @@ describe('resolveReward (shallow / public preview — no DB)', () => {expect(r.kind).toBe('split');expect(r.note).toMatch(/2 recipients/);});+ it('x-owner routes to an X account (intent only)', async () => {+ const r = await resolveReward({ kind: 'x-owner', username: 'naval' }, ctx);+ expect(r.kind).toBe('x-owner');+ expect(r.platform).toBe('x');+ expect(r.mode).toBe('pending');+ expect(r.note).toMatch(/@naval on X/);+ });+ it('cashback returns holders as the beneficiary', async () => {+ const r = await resolveReward({ kind: 'cashback' }, ctx);+ expect(r.kind).toBe('cashback');+ expect(r.shareholders).toEqual([]);+ });+ it('buyback carries its basis points', async () => {+ const r = await resolveReward({ kind: 'buyback', buyback_bps: 5000 }, ctx);+ expect(r.kind).toBe('buyback');+ expect(r.buyback_bps).toBe(5000);+ expect(r.note).toMatch(/50%/);+ });});describe('registry integrity', () => {diff --git a/tests/trading-compile.test.js b/tests/trading-compile.test.jsindex aac45f09e..a43ea01b3 100644--- a/tests/trading-compile.test.js+++ b/tests/trading-compile.test.js@@ -7,6 +7,10 @@ import {configToSniperStrategy,ruleToEnglish,LAMPORTS_PER_SOL,+ PRESETS,+ applyPreset,+ matchingPresetId,+ scoreRisk,} from '../src/studio/money/trading-compile.js';import { normalizeStrategyConfig, validateStrategyConfig } from '../api/_lib/strategy-schema.js';@@ -124,3 +128,63 @@ describe('trading-compile: ruleToEnglish', () => {expect(text).not.toMatch(/guarantee/i);});});++describe('trading-compile: presets', () => {+ it('every preset compiles + validates cleanly against the live server schema', () => {+ for (const p of PRESETS) {+ const rule = applyPreset(p.id);+ const { valid, errors } = validateRule(rule);+ expect(valid, `${p.id}: ${JSON.stringify(errors)}`).toBe(true);+ const cfg = compileRuleToConfig(rule);+ expect(validateStrategyConfig(normalizeStrategyConfig(cfg)).valid, `${p.id} server`).toBe(true);+ }+ });++ it('applyPreset preserves the chosen network', () => {+ expect(applyPreset('hunter', { network: 'devnet' }).network).toBe('devnet');+ expect(applyPreset('hunter').network).toBe('mainnet');+ });++ it('matchingPresetId round-trips a freshly applied preset and ignores the name', () => {+ for (const p of PRESETS) {+ const rule = applyPreset(p.id);+ expect(matchingPresetId(rule)).toBe(p.id);+ rule.name = 'renamed by the user';+ expect(matchingPresetId(rule)).toBe(p.id);+ }+ });++ it('returns null when the rule matches no preset', () => {+ const r = applyPreset('balanced');+ r.buy.amount_sol = 7.77;+ expect(matchingPresetId(r)).toBeNull();+ });+});++describe('trading-compile: scoreRisk', () => {+ it('orders the presets by ascending aggressiveness', () => {+ const g = scoreRisk(applyPreset('guardian')).score;+ const b = scoreRisk(applyPreset('balanced')).score;+ const h = scoreRisk(applyPreset('hunter')).score;+ const m = scoreRisk(applyPreset('moonshot')).score;+ expect(g).toBeLessThan(b);+ expect(b).toBeLessThan(h);+ expect(h).toBeLessThan(m);+ });++ it('always returns a bounded score with a matching label + tone', () => {+ for (const p of PRESETS) {+ const { score, label, tone } = scoreRisk(applyPreset(p.id));+ expect(score).toBeGreaterThanOrEqual(0);+ expect(score).toBeLessThanOrEqual(100);+ expect(['Conservative', 'Balanced', 'Aggressive', 'Degen']).toContain(label);+ expect(['calm', 'balanced', 'warm', 'hot']).toContain(tone);+ }+ });++ it('a bigger position with wider slippage on a fresher coin scores higher', () => {+ const tame = normalizeRule({ buy: { amount_sol: 0.02, max_slippage_bps: 200 }, filters: { max_market_cap_usd: 200000, require_socials: true }, exits: { stop_loss_pct: 20 } });+ const wild = normalizeRule({ buy: { amount_sol: 0.9, max_slippage_bps: 1400 }, filters: { max_market_cap_usd: null, require_socials: false }, exits: { stop_loss_pct: 55, take_profit_pct: 400 }, risk: { max_concurrent_positions: 6 } });+ expect(scoreRisk(wild).score).toBeGreaterThan(scoreRisk(tame).score);+ });+});diff --git a/vercel.json b/vercel.jsonindex 9a4e9f186..da0718412 100644--- a/vercel.json+++ b/vercel.json@@ -259,6 +259,14 @@"src": "/admin/launcher/","dest": "/admin/launcher.html"},+ {+ "src": "/admin/seeder",+ "dest": "/admin/seeder.html"+ },+ {+ "src": "/admin/seeder/",+ "dest": "/admin/seeder.html"+ },{"src": "/aws-marketplace/welcome","dest": "/aws-marketplace/welcome.html"@@ -819,10 +827,6 @@"src": "/diorama/?","dest": "/diorama.html"},- {- "src": "/labs/?",- "dest": "/labs.html"- },{"src": "/api/strategies/(.*)","dest": "/api/strategies"diff --git a/vite.config.js b/vite.config.jsindex 2f9feb5a4..497d93636 100644--- a/vite.config.js+++ b/vite.config.js@@ -381,11 +381,11 @@ const appConfig = {launches: resolve(__dirname, 'pages/launches.html'),pulse: resolve(__dirname, 'pages/pulse.html'),diorama: resolve(__dirname, 'pages/diorama.html'),- labs: resolve(__dirname, 'pages/labs.html'),'x402-revenue': resolve(__dirname, 'pages/x402-revenue.html'),viability: resolve(__dirname, 'pages/viability.html'),deployments: resolve(__dirname, 'pages/deployments.html'),'admin-launcher': resolve(__dirname, 'pages/admin/launcher.html'),+ 'admin-seeder': resolve(__dirname, 'pages/admin/seeder.html'),launcher: resolve(__dirname, 'pages/launcher.html'),'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),watchlist: resolve(__dirname, 'pages/watchlist.html'),@@ -859,6 +859,8 @@ support: resolve(__dirname, 'pages/support.html'),'/deployments/': resolve(root, 'pages/deployments.html'),'/admin/launcher': resolve(root, 'pages/admin/launcher.html'),'/admin/launcher/': resolve(root, 'pages/admin/launcher.html'),+ '/admin/seeder': resolve(root, 'pages/admin/seeder.html'),+ '/admin/seeder/': resolve(root, 'pages/admin/seeder.html'),'/launcher': resolve(root, 'pages/launcher.html'),'/launcher/': resolve(root, 'pages/launcher.html'),'/clash': resolve(root, 'pages/clash.html'),@@ -889,8 +891,6 @@ support: resolve(__dirname, 'pages/support.html'),'/ui-juice/': resolve(root, 'pages/ui-juice.html'),'/diorama': resolve(root, 'pages/diorama.html'),'/diorama/': resolve(root, 'pages/diorama.html'),- '/labs': resolve(root, 'pages/labs.html'),- '/labs/': resolve(root, 'pages/labs.html'),'/trader': resolve(root, 'pages/trader.html'),'/trader/': resolve(root, 'pages/trader.html'),'/signals': resolve(root, 'pages/signals.html'),diff --git a/x402-launch-media/x402-hero.png b/x402-launch-media/x402-hero.pngnew file mode 100644index 000000000..21ecb1c4dBinary files /dev/null and b/x402-launch-media/x402-hero.png differdiff --git a/x402-launch-media/x402-loop.gif b/x402-launch-media/x402-loop.gifnew file mode 100644index 000000000..9ea5909baBinary files /dev/null and b/x402-launch-media/x402-loop.gif differdiff --git a/x402-launch-media/x402-loop.mp4 b/x402-launch-media/x402-loop.mp4new file mode 100644index 000000000..7faed7c98Binary files /dev/null and b/x402-launch-media/x402-loop.mp4 differdiff --git a/x402-launch-media/x402-pay-and-call.png b/x402-launch-media/x402-pay-and-call.pngnew file mode 100644index 000000000..27700b84cBinary files /dev/null and b/x402-launch-media/x402-pay-and-call.png differ