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
Add comprehensive test coverage for pump bonding, subject reputation, identity verification, and pump launch listing
nichddaa0b678f85
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex c033c5d3b..1243977e0 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -25,6 +25,10 @@ bottom.| 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 || OKX.AI marketplace services | [api/okx/3d/[service].js](api/okx/3d/%5Bservice%5D.js) `→ /api/okx/3d/*` | Live | 3D services sold to other agents on OKX.AI (agent #2632): Agent Identity Studio flagship + decomposed studio services. Catalog source of truth: [api/_lib/okx-catalog.js](api/_lib/okx-catalog.js); pipeline: [api/_okx3d/](api/_okx3d); showcase: [pages/agent-identities.html](pages/agent-identities.html) `→ /agent-identities`; docs: [docs/okx-marketplace.md](docs/okx-marketplace.md) |+| Crypto Data API docs / landing | [pages/crypto.html](pages/crypto.html) `→ /crypto` | In-repo · docs surface | Screenshot-worthy public docs + funnel-top for the free, keyless Crypto Data API (`/api/crypto/*` — token snapshot, security, holders, launches, bonding, whales, symbol, wallet, trending). Renders hero, endpoint table, tabbed quickstart (curl/JS/Python), per-endpoint request/response reference and a live "Try it" console. Probes production at runtime and marks each endpoint Live vs Coming soon (degrades gracefully while sibling endpoints roll out). CTAs funnel to paid uniques: [/launcher](pages/launcher.html), [/vanity-wallet](public/vanity-wallet.html), [/forge](pages/forge.html). Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) |+| Free Crypto Data API + discovery | [api/crypto/index.js](api/crypto/index.js) `→ /api/crypto`, [api/crypto/openapi.js](api/crypto/openapi.js) `→ /api/crypto/openapi.json`, docs [docs/crypto-api.md](docs/crypto-api.md) `→ /docs/crypto-api` | Live · docs surface | Front door + OpenAPI 3.1 for the free, keyless Crypto Data API. Catalog assembler [api/_lib/crypto-catalog/index.js](api/_lib/crypto-catalog/index.js) globs `api/_lib/crypto-catalog/*.js` self-describing descriptors (currently `bonding`, `symbol`, `trending`, `wallet`, `whales`), skips malformed/throwing entries, never throws, valid-empty when zero; OpenAPI built from the same catalog via [api/_lib/crypto-catalog/openapi.js](api/_lib/crypto-catalog/openapi.js). Index does HTML/JSON content negotiation. Serverless-safe: `includeFiles: api/_lib/crypto-catalog/**` in [vercel.json](vercel.json) traces every descriptor into the bundle so the runtime `readdir` finds them. Endpoint handlers live in `api/crypto/*.js`. Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) |+| Free 3D API + docs | [api/3d/index.js](api/3d/index.js) `→ /api/3d`, [api/3d/openapi.js](api/3d/openapi.js) `→ /api/3d/openapi.json`, docs [public/3d.html](public/3d.html) `→ /3d` (alias `/docs/3d-api`) | Live · docs surface | Front door + OpenAPI 3.1 for the free, keyless 3D API. Catalog assembler [api/_lib/3d-catalog/index.js](api/_lib/3d-catalog/index.js) globs `api/_lib/3d-catalog/*.js` descriptors (currently `generate`, `inspect`), skips malformed, never throws; OpenAPI built from the same catalog via [api/_lib/3d-catalog/openapi.js](api/_lib/3d-catalog/openapi.js). Index does HTML/JSON content negotiation and advertises the paid ladder (Forge Pro, Rigged Avatars). Docs page: hero, live endpoint table, runnable quickstart with a live "Run inspect" console, embedded `<model-viewer>` GLB preview, and the free→paid ladder. Free endpoints: [api/3d/generate.js](api/3d/generate.js) (prompt 12), [api/3d/inspect.js](api/3d/inspect.js) (prompt 13). Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) |+| Sperax partnership + SperaxOS plugin | [pages/sperax.html](pages/sperax.html) `→ /sperax`, plugin [public/sperax/](public/sperax/README.md), manifest `→ /.well-known/sperax-plugin.json`, tools [api/chat-plugin/[tool].js](api/chat-plugin/%5Btool%5D.js) `→ /api/chat-plugin/*`, panel `→ /sperax/iframe/` | In-repo · Live | Partnership landing for the SperaxOS integration: three.ws ships as a standalone `plugin.delivery` plugin that gives a SperaxOS agent an embodied 3D avatar (speak/gesture/emote/render_agent), bound to an ERC-8004 identity, settling over Base x402. Launch offer: free AI credits for three.ws users on [chat.sperax.io](https://chat.sperax.io) — page explains what it is and how to claim. Blog: [/blog/three-ws-speraxusd-integration](blog/three-ws-speraxusd-integration.html) || Live Agents wall (mission control) | [pages/agents-live.html](pages/agents-live.html) + [src/agents-live.js](src/agents-live.js) `→ /agents-live` | In-repo · roster [api/agents/public.js](api/agents/public.js) (`sort=live`), per-agent SSE [api/agent-screen-stream.js](api/agent-screen-stream.js) | Real-time grid of every meaningful agent, ranked by most-recent on-chain/skill action (never-used placeholders suppressed). Each card streams a live caster feed when watched, else its real `agent_actions` as a terminal + an "active Nm ago" recency chip. Layers: showrunner spotlight ([src/showrunner.js](src/showrunner.js)), reputation arena ([src/agents-live-arena.js](src/agents-live-arena.js)), platform ticker ([src/theater-feed.js](src/theater-feed.js)) || X/Twitter automation toolkit | [nirholas/XActions](https://github.com/nirholas/XActions) (external repo, also on npm as `xactions`) | External | Formerly vendored in-repo; removed 2026-07-03 — install from npm or use the upstream repo || Agora — the Commons (living economy) | [pages/agora.html](pages/agora.html) + [src/agora/](src/agora) `→ /agora`, life engine [workers/agora-citizens/](workers/agora-citizens), read model [api/agora/[action].js](api/agora/[action].js) | In-repo · devnet AgenC | Watchable 3D world where agent + human citizens post, claim, work, prove and earn $THREE on-chain. **Play mode** ("Enter the Commons") makes it walkable GTA-style — your avatar walks the square among the working NPC citizens, other humans appear live over the `agora_world` Colyseus room, and walking up to a citizen (proximity → E) opens its passport: [src/agora/player-mode.js](src/agora/player-mode.js), pure math [src/agora/player-logic.js](src/agora/player-logic.js), room [multiplayer/src/rooms/AgoraRoom.js](multiplayer/src/rooms/AgoraRoom.js). **Arena** (Competitive tasks — citizens race, first valid proof wins the whole escrow) at [src/agora/arena.js](src/agora/arena.js); **Guilds** (Collaborative tasks — contributors split the reward) at [src/agora/guild.js](src/agora/guild.js), both live-driven by [api/agora/task](api/agora/[action].js). Spec: [docs/agora.md](docs/agora.md) |diff --git a/api/3d/generate.js b/api/3d/generate.jsnew file mode 100644index 000000000..e2afaefee--- /dev/null+++ b/api/3d/generate.js@@ -0,0 +1,271 @@+// POST /api/3d/generate + GET /api/3d/generate?job=<id>+//+// The FREE, keyless, agent-first front door to three.ws text→3D. An autonomous+// agent building a game, a scene, an NFT, or any visual can turn a text prompt+// into a real textured GLB in one call — no key, no account, no wallet. No other+// agent-payments platform gives away 3D generation; this is the magnet that+// funnels to paid Forge Pro (quality tiers) and Rigged Avatars.+//+// This route does NOT re-implement generation. It wraps the existing free draft+// lane (NVIDIA NIM TRELLIS → self-host TRELLIS/Hunyuan3D → HuggingFace Spaces)+// through the SAME /api/forge submit/poll pipeline the forge_free MCP tool and+// /api/v1/ai/text-to-3d already use (api/_mcp-studio/forge-client.js). Only the+// wire contract is new: a clean, minimal agent shape.+//+// POST { prompt, format?:'glb' }+// → 200 { status:'done', glbUrl, viewerUrl, ... } (draft finished inline)+// → 200 { status:'pending', job, poll, ... } (queued — poll below)+//+// GET ?job=<id>+// → 200 { status:'pending' } (still generating)+// → 200 { status:'done', glbUrl, viewerUrl } (GLB ready)+// → 200 { status:'error', error } (upstream failed; free = no charge)+//+// Free = the draft/NIM tier only, and we say so honestly: single-subject prompts,+// ~draft-fidelity geometry, no rigging. Higher quality + rigging live behind the+// paid Forge (/api/x402/forge) and Rigged Avatars, linked in every response.++import { cors, wrap, method, json, error, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { startForge, originFromReq, viewerUrl } from '../_mcp-studio/forge-client.js';++const PROMPT_MIN = 3; // the draft lane needs a subject to condition on+const PROMPT_MAX = 1000; // matches /api/forge's own prompt ceiling+const MAX_BODY_BYTES = 8_000;++// A forge job handle is either a signed f1.<b64url>.<b64url> token or a bare+// Replicate prediction id ([a-z0-9]{16,64}). Bound the poll param to that shape+// before forwarding — /api/forge does the authoritative validation, this just+// keeps obvious junk off the wire.+const JOB_HANDLE_RE = /^[A-Za-z0-9._-]{8,1024}$/;++// The upsell ladder every response carries: free draft here → paid Forge Pro+// quality tiers → rigged, animation-ready avatars. Not a paywall — a doorway.+const UPGRADE = Object.freeze({+ message:+ 'This is the free draft tier (NVIDIA NIM TRELLIS): single-subject, draft-fidelity geometry, no rigging. ' ++ 'For higher polygon budgets + PBR textures use paid Forge Pro; for animation-ready rigged characters use Rigged Avatars.',+ forgePro: '/api/x402/forge',+ riggedAvatars: '/api/forge?action=rig',+ docs: '/docs/3d-api',+});++// Shape a /api/forge draft-lane submit response into this route's agent contract.+// Pure + exported so the boundary is pinned in tests against real captured forge+// shapes (inline-done vs queued) without any network.+export function shapeSubmit(job, base) {+ const glbUrl = typeof job?.glb_url === 'string' ? job.glb_url : '';+ if (job?.status === 'done' && glbUrl) {+ return {+ status: 'done',+ glbUrl,+ viewerUrl: viewerUrl(base, glbUrl),+ format: 'glb',+ tier: 'draft',+ free: true,+ upgrade: UPGRADE,+ };+ }+ const token = job?.job_id ?? null;+ return {+ status: 'pending',+ job: token,+ poll: token ? `/api/3d/generate?job=${encodeURIComponent(token)}` : null,+ format: 'glb',+ tier: 'draft',+ free: true,+ upgrade: UPGRADE,+ };+}++// Shape a /api/forge poll response into { status:'pending'|'done'|'error', ... }.+// Pure + exported for the same reason as shapeSubmit.+export function shapePoll(data, base, jobId) {+ const glbUrl = typeof data?.glb_url === 'string' ? data.glb_url : '';+ if (data?.status === 'done' && glbUrl) {+ return {+ status: 'done',+ job: jobId,+ glbUrl,+ viewerUrl: viewerUrl(base, glbUrl),+ format: 'glb',+ tier: 'draft',+ free: true,+ };+ }+ if (data?.status === 'failed') {+ return {+ status: 'error',+ job: jobId,+ // Free lane: an upstream failure costs the caller nothing — say so and let+ // them simply retry. The message is already sanitized by /api/forge.+ error: data?.error || '3D generation hit a snag upstream — no charge; try again.',+ free: true,+ upgrade: UPGRADE,+ };+ }+ // queued / running / anything transient → still pending.+ return {+ status: 'pending',+ job: jobId,+ poll: `/api/3d/generate?job=${encodeURIComponent(jobId)}`,+ free: true,+ };+}++// Map a startForge lane failure to an honest boundary response. A well-formed+// prompt must NEVER 500: every code has a designed status + actionable message.+function failFromLane(res, err) {+ switch (err?.code) {+ case 'not_configured':+ return json(res, 503, {+ error: 'not_configured',+ message:+ err.message ||+ 'Free text→3D is not configured on this deployment — set NVIDIA_API_KEY (or a self-host TRELLIS / HuggingFace lane).',+ });+ case 'busy':+ // GPU lane saturated upstream — surface the retry hint the lane handed back.+ if (err.retryAfter) res.setHeader('retry-after', String(err.retryAfter));+ return json(res, 429, {+ error: 'rate_limited',+ message: err.message || 'The free 3D GPU lane is momentarily saturated — try again shortly.',+ retry_after: err.retryAfter || 10,+ });+ case 'timeout':+ res.setHeader('retry-after', '10');+ return json(res, 503, {+ error: 'lane_timeout',+ message: err.message || 'The 3D lane took too long to accept the job — try again.',+ retry_after: 10,+ });+ default:+ // Upstream provider blip — a free-lane failure, not a server fault. Answer+ // with a designed 502 (never a raw 500) so the agent can retry.+ return json(res, 502, {+ error: 'generation_failed',+ message: err?.message || 'The 3D lane could not start this job — try again.',+ });+ }+}++async function generate(req, res) {+ const ip = clientIp(req);++ let body;+ try {+ body = await readJson(req, MAX_BODY_BYTES);+ } catch (err) {+ return json(res, err?.status === 413 ? 413 : 400, {+ error: 'bad_request',+ message: err?.status === 413 ? 'Request body too large.' : 'Send a JSON body: { "prompt": "..." }.',+ });+ }++ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';+ if (prompt.length < PROMPT_MIN) {+ return json(res, 400, {+ error: 'invalid_prompt',+ message: `"prompt" is required — describe one subject in ${PROMPT_MIN}–${PROMPT_MAX} characters, e.g. "a small ceramic robot figurine".`,+ });+ }+ if (prompt.length > PROMPT_MAX) {+ return json(res, 400, {+ error: 'invalid_prompt',+ message: `"prompt" must be ${PROMPT_MAX} characters or fewer.`,+ });+ }++ // Only GLB is offered on the free lane. Accept the default and an explicit+ // 'glb'; reject anything else plainly rather than silently ignoring it.+ const format = body?.format == null ? 'glb' : String(body.format).toLowerCase();+ if (format !== 'glb') {+ return json(res, 400, {+ error: 'unsupported_format',+ message: 'The free lane returns GLB only. Omit "format" or pass "glb".',+ });+ }++ // Per-IP guard on the free GPU lane. Reuses the existing free-lane bucket+ // (mcp3d:generate:free) — the SAME counter /api/forge draws from — so this is a+ // generous shared ceiling protecting one GPU allocation, and the check here+ // rejects a flood before the self-call round-trip. The GLOBAL concurrency guard+ // (HuggingFace slot lease + platform submit throttle) lives inside /api/forge and+ // is inherited automatically by routing through it — no new limiter invented.+ const rl = await limits.mcp3dGenerateFree(ip);+ if (!rl.success) {+ return rateLimited(res, rl, 'Free 3D generation limit reached — try again shortly, or use paid Forge Pro (no per-IP cap).', {+ upgrade: UPGRADE,+ });+ }++ const base = originFromReq(req);+ let job;+ try {+ // Pin the free draft lane exactly: NVIDIA NIM TRELLIS, image path, draft tier.+ job = await startForge(base, { prompt, backend: 'nvidia', path: 'image', tier: 'draft' });+ } catch (err) {+ return failFromLane(res, err);+ }++ return json(res, 200, shapeSubmit(job, base));+}++async function poll(req, res, jobId) {+ if (!JOB_HANDLE_RE.test(jobId)) {+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id. Pass the "job" value from the generate response.' });+ }++ // Cheap, high-frequency poll — reuse the forge status limiter (per-instance,+ // flood-guard only) so a polling loop can't be turned into a hammer.+ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'Polling too fast — slow down and retry.');++ const base = originFromReq(req);+ let upstream;+ try {+ upstream = await fetch(`${base}/api/forge?job=${encodeURIComponent(jobId)}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(15_000),+ });+ } catch {+ // A transient network blip on the self-call is not a job failure — tell the+ // caller it's still pending so its poll loop retries.+ return json(res, 200, shapePoll({ status: 'running' }, base, jobId));+ }++ const data = await upstream.json().catch(() => ({}));+ if (upstream.status === 400) {+ return json(res, 400, { error: 'invalid_job', message: data?.message || 'Unknown or malformed job id.' });+ }+ if (upstream.status === 429) {+ const retryAfter = Number(data?.retry_after) || 5;+ res.setHeader('retry-after', String(retryAfter));+ return json(res, 429, { error: 'rate_limited', message: 'Polling is rate-limited — retry shortly.', retry_after: retryAfter });+ }+ if (!upstream.ok) {+ // Upstream hiccup mid-poll — keep the job alive as pending so the loop retries.+ return json(res, 200, shapePoll({ status: 'running' }, base, jobId));+ }++ return json(res, 200, shapePoll(data, base, jobId));+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ if (req.method === 'POST') return generate(req, res);++ const url = new URL(req.url, 'http://localhost');+ const jobId = (url.searchParams.get('job') || '').trim();+ if (!jobId) {+ return error(res, 400, 'missing_job', 'Pass ?job=<id> to poll a generation, or POST { prompt } to start one.');+ }+ return poll(req, res, jobId);+});++// The free NIM draft often finishes inside the submit window; startForge waits up+// to 90s for that inline completion. Give the function headroom beyond the default+// so a fast draft returns done in one call instead of forcing a poll.+export const config = { maxDuration: 120 };diff --git a/api/3d/index.js b/api/3d/index.jsnew file mode 100644index 000000000..45ca628b8--- /dev/null+++ b/api/3d/index.js@@ -0,0 +1,237 @@+// @ts-check+// GET /api/3d — the front door to the free, keyless three.ws 3D API.+//+// One URL an agent (or a human wiring one up) hits to discover the whole API:+// every free endpoint, its inputs/outputs, and a live example — plus the paid+// ladder it graduates to (Forge Pro quality tiers → Rigged Avatars). The list is+// assembled at request time from the catalog (api/_lib/3d-catalog), so a new+// sibling endpoint appears here the moment it ships — nothing wired by hand.+//+// Content negotiation: `Accept: text/html` gets a browsable page; everything+// else (the agent path) gets JSON. Free means free — keyless, no account, a+// generous per-IP limit that only blunts abuse.++import { wrap, cors, method, json, text, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { loadCatalog } from '../_lib/3d-catalog/index.js';++const VERSION = '1.0.0';++// The paid tiers the free lanes funnel into. Kept here (not in the catalog dir)+// because these are paid x402 routes, not free-bundle members — the catalog only+// holds free endpoints.+const PAID_TIERS = [+ {+ name: 'Forge Pro',+ path: '/api/x402/forge',+ price: 'from $0.05 USDC',+ why: 'Production text→3D / image→3D: higher polygon budgets, PBR textures, draft/standard/high quality tiers. Pay-per-call over x402, no key.',+ },+ {+ name: 'Rigged Avatar',+ path: '/api/forge?action=rig',+ price: 'from $0.05 USDC',+ why: 'Turn a static GLB into an animation-ready humanoid: auto-detected skeleton, skin weights, and the pre-baked idle/walk clip library.',+ },+];++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ // Cheap metadata read; generous ceiling, bounded so it can't be scraped in a+ // tight loop. Reuses the shared per-IP bucket sized for this surface.+ const ip = clientIp(req);+ const rl = await limits.apiIp(ip, { limit: 240, window: '5 m' });+ if (!rl.success) return rateLimited(res, rl, 'too many requests to the 3D API index');++ const endpoints = await loadCatalog();+ const origin = env.APP_ORIGIN;++ const payload = {+ name: 'three.ws 3D API',+ free: true,+ keyless: true,+ version: VERSION,+ endpoints,+ count: endpoints.length,+ // Zero entries is a valid state, not an error — say so plainly.+ ...(endpoints.length === 0+ ? { note: 'Free 3D endpoints are rolling out. They list here automatically as they ship.' }+ : {}),+ paidTiers: PAID_TIERS,+ openapi: '/api/3d/openapi.json',+ docs: '/docs/3d-api',+ ts: new Date().toISOString(),+ };++ // Public + CDN-cacheable: the catalog only changes on deploy, so a short edge+ // cache keeps this instant without hiding new endpoints for long.+ const cache = { 'cache-control': 'public, s-maxage=300, stale-while-revalidate=600' };++ if (String(req.headers.accept || '').includes('text/html')) {+ return text(res, 200, renderHtml(payload, origin), {+ ...cache,+ 'content-type': 'text/html; charset=utf-8',+ });+ }+ return json(res, 200, payload, cache);+});++/** Escape untrusted-ish strings before dropping them into HTML. */+function esc(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => /** @type {any} */ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++/**+ * Human-friendly index page. Self-contained, theme-aware, responsive. Lists+ * every free endpoint with its methods, path, summary, and a copy-ready curl —+ * then the paid ladder it funnels into.+ * @param {any} p payload+ * @param {string} origin+ */+function renderHtml(p, origin) {+ const rows = p.endpoints.length+ ? p.endpoints+ .map((e) => {+ const example =+ e.example && typeof e.example === 'object'+ ? esc(JSON.stringify(e.example, null, 2))+ : '';+ const methods = (e.methods || ['GET']).join(' · ');+ const isPost = (e.methods || []).includes('POST');+ const curl = isPost+ ? `curl -X POST ${esc(origin)}${esc(e.path)} -H 'content-type: application/json' -d '{ … }'`+ : `curl ${esc(origin)}${esc(e.path)}`;+ return `+ <article class="ep">+ <header>+ <span class="method">${esc(methods)}</span>+ <code class="path">${esc(e.path)}</code>+ </header>+ <h3>${esc(e.title)}</h3>+ ${e.summary ? `<p>${esc(e.summary)}</p>` : ''}+ ${e.useCase ? `<p class="use"><strong>Who uses it:</strong> ${esc(e.useCase)}</p>` : ''}+ <pre class="curl"><code>${esc(curl)}</code></pre>+ ${example ? `<details><summary>Example</summary><pre><code>${example}</code></pre></details>` : ''}+ </article>`;+ })+ .join('')+ : `<div class="empty">+ <h3>Free 3D endpoints are rolling out</h3>+ <p>This bundle lists every endpoint here automatically as it ships. Meanwhile, jump straight to the paid tiers below, or watch the <a href="/changelog">changelog</a>.</p>+ </div>`;++ const tiers = p.paidTiers+ .map(+ (t) => `+ <article class="tier">+ <header><h3>${esc(t.name)}</h3><span class="price">${esc(t.price)}</span></header>+ <code class="path">${esc(t.path)}</code>+ <p>${esc(t.why)}</p>+ </article>`,+ )+ .join('');++ return `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>three.ws 3D API — free text→3D + inspection for agents</title>+ <meta name="description" content="A free, keyless 3D API for AI agents: turn text into a GLB, inspect any glTF/GLB, and graduate to paid Forge Pro + Rigged Avatars. One URL to discover it all." />+ <style>+ :root {+ --bg: #ffffff; --fg: #0b0d12; --muted: #5b6472; --card: #f6f8fa;+ --border: #e4e8ee; --accent: #6d4aff; --code: #eef1f6; --pay: #b8860b;+ }+ @media (prefers-color-scheme: dark) {+ :root {+ --bg: #0b0d12; --fg: #e9edf4; --muted: #99a3b3; --card: #12151c;+ --border: #232935; --accent: #9d86ff; --code: #171b23; --pay: #e2b53c;+ }+ }+ * { box-sizing: border-box; }+ body {+ margin: 0; background: var(--bg); color: var(--fg);+ font: 15px/1.55 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ padding: 2.5rem 1.25rem 4rem;+ }+ main { max-width: 880px; margin: 0 auto; }+ .badges { display: flex; gap: .5rem; flex-wrap: wrap; margin: .75rem 0 0; }+ .badge {+ font-size: .72rem; font-weight: 600; text-transform: uppercase; letter-spacing: .04em;+ background: var(--accent); color: #fff; padding: .2rem .55rem; border-radius: 999px;+ }+ h1 { font-size: 1.9rem; margin: 0; letter-spacing: -.02em; }+ h2 { font-size: 1.2rem; margin: 2.6rem 0 .3rem; letter-spacing: -.01em; }+ .lede { color: var(--muted); margin: .6rem 0 0; }+ .meta { color: var(--muted); font-size: .85rem; margin-top: 1rem; }+ .meta a { color: var(--accent); }+ .grid { display: grid; gap: 1rem; margin-top: 1.2rem; }+ .ep, .tier {+ background: var(--card); border: 1px solid var(--border); border-radius: 14px;+ padding: 1.1rem 1.2rem; transition: border-color .15s ease;+ }+ .ep:hover, .tier:hover { border-color: var(--accent); }+ .ep header, .tier header { display: flex; align-items: center; gap: .6rem; }+ .method {+ font-size: .72rem; font-weight: 700; color: #fff; background: #2f8f4e;+ padding: .12rem .5rem; border-radius: 6px; letter-spacing: .03em; white-space: nowrap;+ }+ .path { font-size: .9rem; color: var(--fg); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }+ .ep h3, .tier h3 { margin: .7rem 0 .25rem; font-size: 1.05rem; }+ .tier h3 { margin: 0; }+ .tier .price { margin-left: auto; color: var(--pay); font-weight: 700; font-size: .82rem; }+ .tier code.path { display: inline-block; margin: .5rem 0 .3rem; }+ .ep p, .tier p { margin: 0 0 .7rem; color: var(--muted); }+ .ep p.use { font-size: .86rem; }+ pre {+ background: var(--code); border: 1px solid var(--border); border-radius: 8px;+ padding: .7rem .8rem; overflow-x: auto; margin: .4rem 0 0; font-size: .82rem;+ }+ pre code, code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }+ details { margin-top: .5rem; }+ summary { cursor: pointer; color: var(--accent); font-size: .85rem; }+ .empty {+ text-align: center; padding: 3rem 1rem; background: var(--card);+ border: 1px dashed var(--border); border-radius: 14px; color: var(--muted);+ }+ .empty a { color: var(--accent); }+ footer { margin-top: 2.5rem; color: var(--muted); font-size: .82rem; }+ footer a { color: var(--accent); }+ </style>+</head>+<body>+ <main>+ <h1>${esc(p.name)}</h1>+ <div class="badges">+ <span class="badge">Free</span>+ <span class="badge">Keyless</span>+ <span class="badge">v${esc(p.version)}</span>+ </div>+ <p class="lede">One URL to discover the whole API — every free endpoint, its inputs and outputs, a live example, and the paid tiers it graduates to. No account, no API key.</p>+ <p class="meta">+ ${p.count} free endpoint${p.count === 1 ? '' : 's'} ·+ <a href="/api/3d/openapi.json">OpenAPI 3.1</a> ·+ <a href="/docs/3d-api">Docs</a> ·+ <a href="/api/3d">JSON</a>+ </p>+ <h2>Free endpoints</h2>+ <section class="grid">+ ${rows}+ </section>+ <h2>Paid tiers</h2>+ <p class="lede">When a draft isn't enough — production quality and rigging, pay-per-call over x402.</p>+ <section class="grid">+ ${tiers}+ </section>+ <footer>Built for agents. <a href="/docs/3d-api">Read the docs →</a></footer>+ </main>+</body>+</html>`;+}diff --git a/api/3d/inspect.js b/api/3d/inspect.jsnew file mode 100644index 000000000..91b589f35--- /dev/null+++ b/api/3d/inspect.js@@ -0,0 +1,282 @@+// GET/POST /api/3d/inspect — FREE, keyless glTF/GLB inspection + validation.+//+// The agent use-case: an autonomous agent has a 3D asset (from any source — a+// marketplace, a generation API, a user upload) and, before it commits to using+// it, needs to answer three questions cheaply: is this a spec-valid glTF/GLB,+// how heavy is it (vertices / triangles / materials / textures / animations /+// extensions), and what's the shortest path to making it smaller and faster for+// web/mobile delivery? This endpoint answers all three in one call. It is free+// on purpose — a validation utility drives trust and funnels callers to the paid+// pipelines (Forge Pro quality tiers, Rigged Avatars, mesh optimization).+//+// Input:+// GET /api/3d/inspect?url=<https url of a .glb/.gltf>+// POST /api/3d/inspect body { "url": "<https url>" } (application/json)+// POST /api/3d/inspect raw .glb/.gltf bytes as the request body+//+// Output:+// { url, valid, stats:{ vertices, triangles, materials, textures, animations,+// extensions[], … }, sizeBytes, recommendations:[{ severity, issue, fix }],+// validation:{…}, ts }+//+// Reuses the same inspection core the paid /api/x402/model-check route uses+// (api/_lib/model-inspect.js → src/gltf-inspect.js) plus the official Khronos+// glTF-Validator (gltf-validator npm) for the spec-compliance verdict, and the+// SSRF-hardened, size-capped fetcher (api/_lib/fetch-model.js). Never returns a+// 500 on a well-formed request: every failure maps to a specific 4xx/502.++import { cors, wrap, error, json, rateLimited, readJson, readBody } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { fetchModel, FetchModelError } from '../_lib/fetch-model.js';+import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';+import { validateBytes } from 'gltf-validator';++// Free-tier size cap. A generous ceiling for real avatars/props while bounding+// the memory + compute a single anonymous call can spend. GLBs above this are+// almost always un-optimized source assets that the recommendations below would+// tell you to shrink anyway.+const MAX_BYTES = 32 * 1024 * 1024;++// Rank for ordering the recommendations list: most severe first. `suggestOptimizations`+// emits severities but does not order them, so we sort here.+const SEVERITY_RANK = { critical: 0, warn: 1, info: 2 };++// Map each optimization-suggestion id (from suggestOptimizations) to a concise,+// actionable fix. The suggestion's own `message` becomes the `issue` (what's+// wrong); this is the `fix` (what to do about it). Reusing the detector keeps the+// "which suggestions fire" logic in one place (shared with the paid route + the+// MCP tools) — this layer only reshapes it into the { severity, issue, fix }+// contract this endpoint advertises.+const RECOMMENDATION_FIX = {+ tri_budget:+ 'Decimate the mesh (gltf-transform simplify) or author LODs before shipping to the web.',+ draco: 'Apply KHR_draco_mesh_compression to the geometry buffers.',+ meshopt: 'Apply EXT_meshopt_compression to the vertex + index buffers (faster decode than Draco).',+ texture_oversized: 'Resize the flagged textures to ≤2048px unless hero-level detail is required.',+ texture_basisu:+ 'Transcode PNG/JPEG textures to KTX2 / Basis Universal (KHR_texture_basisu) for GPU-direct upload.',+ non_indexed: 'Re-index the primitives (gltf-transform weld) to remove duplicate vertices.',+ too_many_materials: 'Merge identical materials to cut draw calls.',+ texture_weight: 'Compress textures to KTX2 and resize them for web delivery.',+ file_size: 'Compress geometry (Draco/meshopt) and textures (KTX2); target under 10 MB.',+ anim_without_skin:+ 'Confirm the node-level animations are intentional; strip any orphan animation data.',+ ok: 'No action needed — the model is already well-suited for web delivery.',+};++// Reshape the raw inspectModel output into the advertised `stats` block. Keeps the+// prompt-13 core fields (vertices/triangles/materials/textures/animations/extensions)+// and adds a few more the agent almost always wants next (meshes, nodes, skins,+// bone/joint count, required extensions, container, generator).+export function buildStats(info) {+ const c = info.counts;+ return {+ vertices: c.totalVertices,+ triangles: c.totalTriangles,+ materials: c.materials,+ textures: c.textures,+ animations: c.animations,+ extensions: info.extensionsUsed,+ // Extra context — cheap to include, saves the caller a second call.+ meshes: c.meshes,+ nodes: c.nodes,+ scenes: c.scenes,+ skins: c.skins,+ joints: c.totalJoints,+ indexedPrimitives: c.indexedPrimitives,+ nonIndexedPrimitives: c.nonIndexedPrimitives,+ extensionsRequired: info.extensionsRequired,+ container: info.container,+ generator: info.generator,+ };+}++// Build the prioritized { severity, issue, fix } recommendation list, ordered most+// severe first. Reuses suggestOptimizations for detection.+export function buildRecommendations(info) {+ const suggestions = suggestOptimizations(info);+ return suggestions+ .map((s) => ({+ severity: s.severity,+ issue: s.estimate ? `${s.message} (${s.estimate})` : s.message,+ fix: RECOMMENDATION_FIX[s.id] || s.message,+ }))+ .sort((a, b) => (SEVERITY_RANK[a.severity] ?? 3) - (SEVERITY_RANK[b.severity] ?? 3));+}++// Run the Khronos glTF-Validator for the authoritative spec-compliance verdict.+// External resources (a .gltf's side-car .bin/textures) are NOT fetched — GLBs+// are self-contained, and fetching arbitrary side files would reopen the SSRF+// surface fetch-model.js closes. A validator failure never fails the whole call:+// inspectModel already proved the bytes parse, so we degrade to valid:true with a+// note rather than 500. Returns { valid, ...counts } or null when unavailable.+async function runValidator(bytes, filename) {+ try {+ const report = await validateBytes(bytes, {+ maxIssues: 100,+ uri: filename || 'model.glb',+ externalResourceFunction: (uri) =>+ Promise.reject(new Error(`external resource not fetched: ${uri}`)),+ });+ const issues = report?.issues || {};+ return {+ valid: (issues.numErrors ?? 0) === 0,+ validatorVersion: report?.validatorVersion || null,+ numErrors: issues.numErrors ?? 0,+ numWarnings: issues.numWarnings ?? 0,+ numInfos: issues.numInfos ?? 0,+ numHints: issues.numHints ?? 0,+ };+ } catch {+ return null;+ }+}++// Fetch a model by URL through the SSRF-hardened, size-capped fetcher and translate+// its typed errors into this endpoint's HTTP contract. Blocked/private/invalid URLs+// are the caller's fault → 400; upstream problems → 502 with a retry hint; oversize+// → 413.+async function fetchByUrl(url) {+ try {+ const { bytes, url: finalUrl } = await fetchModel(url, {+ maxBytes: MAX_BYTES,+ timeoutMs: 20_000,+ });+ return { bytes, url: finalUrl };+ } catch (err) {+ if (err instanceof FetchModelError) {+ if (err.code === 'file_too_large') {+ throw httpError(413, 'too_large', `model exceeds the ${MAX_BYTES}-byte free-tier cap`);+ }+ if (['invalid_url', 'scheme_not_allowed', 'private_address', 'host_pin_mismatch'].includes(err.code)) {+ throw httpError(400, 'invalid_url', err.message);+ }+ // upstream_error, too_many_redirects, dns_failed, dns_timeout, no_body, fetch_failed+ throw httpError(502, 'fetch_failed', `could not fetch model: ${err.message}`, {+ retry: 'the source URL did not return the model — check it is public and try again',+ });+ }+ throw httpError(502, 'fetch_failed', `could not fetch model: ${err?.message || err}`);+ }+}++function httpError(status, code, message, extra = {}) {+ const e = new Error(message);+ e.status = status;+ e.code = code;+ e.extra = extra;+ return e;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ if (req.method !== 'GET' && req.method !== 'POST') {+ res.setHeader('allow', 'GET, POST');+ return error(res, 405, 'method_not_allowed', 'use GET (?url=) or POST ({ url } or a raw model body)');+ }++ // Generous per-IP budget — this is a free, keyless utility. Reuses the generic+ // api:ip limiter with an explicit 60/min override, which getLimiter keys into+ // its own isolated bucket (no dedicated limiter needed, no shared-file edit).+ const ip = clientIp(req);+ const rl = await limits.apiIp(ip, { limit: 60, window: '1 m' });+ if (!rl.success) return rateLimited(res, rl, 'too many inspect requests');++ // Resolve the model bytes from one of the three accepted inputs.+ let bytes;+ let sourceUrl = null;+ let filename = 'model.glb';++ try {+ if (req.method === 'GET') {+ const url = String(req.query?.url || '').trim();+ if (!url) {+ return error(res, 400, 'missing_url', 'query param "url" is required (or POST a model body)');+ }+ const fetched = await fetchByUrl(url);+ bytes = fetched.bytes;+ sourceUrl = fetched.url;+ filename = urlFilename(sourceUrl);+ } else {+ const ct = String(req.headers['content-type'] || '').toLowerCase();+ if (ct.includes('application/json')) {+ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e.status === 415 ? 415 : 400, 'invalid_json', e.message || 'invalid JSON body');+ }+ const url = String(body?.url || '').trim();+ if (!url) {+ return error(res, 400, 'missing_url', 'POST JSON must include "url", or upload raw model bytes');+ }+ const fetched = await fetchByUrl(url);+ bytes = fetched.bytes;+ sourceUrl = fetched.url;+ filename = urlFilename(sourceUrl);+ } else {+ // Raw upload: the request body IS the model.+ let raw;+ try {+ raw = await readBody(req, MAX_BYTES);+ } catch (e) {+ if (e.status === 413) {+ return error(res, 413, 'too_large', `upload exceeds the ${MAX_BYTES}-byte free-tier cap`);+ }+ return error(res, 400, 'bad_body', e.message || 'could not read request body');+ }+ if (!raw || raw.byteLength === 0) {+ return error(res, 400, 'empty_body', 'no model bytes uploaded — send a .glb/.gltf body or a "url"');+ }+ // Copy into a tight, zero-offset buffer — `raw` is a Buffer backed by a+ // shared pool, and downstream parsers (glTF-Transform readBinary, the+ // validator) are happiest with a standalone Uint8Array.+ bytes = Uint8Array.from(raw);+ }+ }+ } catch (e) {+ // Typed errors from fetchByUrl (400/413/502) — never a 500.+ return error(res, e.status || 502, e.code || 'fetch_failed', e.message, e.extra || {});+ }++ // Parse structure. A parse failure here means the bytes are not a real glTF/GLB.+ let info;+ try {+ info = await inspectModel(bytes, { fileSize: bytes.byteLength });+ } catch (e) {+ return error(res, 400, 'invalid_model', `not a valid glTF/GLB: ${e.message || 'could not parse model'}`);+ }++ const validation = await runValidator(bytes, filename);+ const stats = buildStats(info);+ const recommendations = buildRecommendations(info);++ const payload = {+ url: sourceUrl,+ // `valid` reflects the Khronos validator's error count when it ran; when the+ // validator is unavailable the bytes still parsed, so it's structurally usable.+ valid: validation ? validation.valid : true,+ stats,+ sizeBytes: bytes.byteLength,+ recommendations,+ validation: validation || { valid: true, note: 'validator unavailable — structural parse succeeded' },+ ts: new Date().toISOString(),+ };++ // URL-sourced GETs are deterministic — let the CDN cache them briefly. Raw+ // uploads and POSTs are never cached.+ if (req.method === 'GET' && sourceUrl) {+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=300');+ } else {+ res.setHeader('cache-control', 'no-store');+ }+ return json(res, 200, payload);+});++function urlFilename(u) {+ try {+ return new URL(u).pathname.split('/').pop() || 'model.glb';+ } catch {+ return 'model.glb';+ }+}diff --git a/api/3d/openapi.js b/api/3d/openapi.jsnew file mode 100644index 000000000..5cbde6cc9--- /dev/null+++ b/api/3d/openapi.js@@ -0,0 +1,35 @@+// @ts-check+// GET /api/3d/openapi.json — the machine-readable spec for the free 3D API,+// generated live from the catalog (api/_lib/3d-catalog).+//+// Served at `/api/3d/openapi.json` via the rewrite in vercel.json; this file also+// answers `/api/3d/openapi` directly. An agent points its OpenAPI toolchain+// (openapi-generator, LangChain's OpenAPIToolkit, Swagger UI) at this URL and+// gets typed clients / callable tools for every endpoint — no key, no account.+// The doc is never hand-written: paths, params, request bodies, and response+// schemas all derive from the catalog entries, so it can't drift from `/api/3d`.++import { wrap, cors, method, json, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { loadCatalog } from '../_lib/3d-catalog/index.js';+import { buildOpenApiDoc } from '../_lib/3d-catalog/openapi.js';++const VERSION = '1.0.0';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const ip = clientIp(req);+ const rl = await limits.apiIp(ip, { limit: 240, window: '5 m' });+ if (!rl.success) return rateLimited(res, rl, 'too many requests to the 3D OpenAPI doc');++ const entries = await loadCatalog();+ const doc = buildOpenApiDoc(entries, { origin: env.APP_ORIGIN, version: VERSION });++ // Catalog changes only on deploy — safe to CDN-cache briefly.+ return json(res, 200, doc, {+ 'cache-control': 'public, s-maxage=300, stale-while-revalidate=600',+ });+});diff --git a/api/_lib/3d-catalog/generate.js b/api/_lib/3d-catalog/generate.jsnew file mode 100644index 000000000..08f5b101a--- /dev/null+++ b/api/_lib/3d-catalog/generate.js@@ -0,0 +1,81 @@+// 3D API catalog entry — free text→3D generation.+//+// Consumed by the /api/3d index + OpenAPI assembler (api/_lib/3d-catalog/index.js,+// prompt 14), which globs this directory. Same entry shape as the crypto catalog+// (slug / method / path / title / summary / inputSchema / outputSchema / example),+// so the two free APIs render identically. Stands alone with zero dependency on+// the assembler existing yet.++export default {+ slug: 'generate',+ method: 'POST',+ path: '/api/3d/generate',+ title: 'Text → 3D (free draft)',+ summary:+ 'Turn a text prompt into a real textured GLB model. Free, keyless, no account. ' ++ 'The draft/NIM tier (single-subject, draft-fidelity geometry, no rigging); ' ++ 'higher quality + rigging live behind paid Forge Pro and Rigged Avatars. ' ++ 'Returns the GLB inline when the draft finishes fast, otherwise a job token to poll ' ++ 'at GET /api/3d/generate?job=<id>.',+ free: true,+ keyless: true,+ inputSchema: {+ type: 'object',+ required: ['prompt'],+ properties: {+ prompt: {+ type: 'string',+ minLength: 3,+ maxLength: 1000,+ description: 'One subject to model, e.g. "a small ceramic robot figurine".',+ },+ format: {+ type: 'string',+ enum: ['glb'],+ default: 'glb',+ description: 'Output format. The free lane returns GLB only.',+ },+ },+ },+ outputSchema: {+ type: 'object',+ properties: {+ status: { type: 'string', enum: ['done', 'pending', 'error'] },+ glbUrl: { type: 'string', description: 'Durable URL to the generated GLB (when status=done).' },+ viewerUrl: { type: 'string', description: 'three.ws viewer link for the GLB (when status=done).' },+ job: { type: 'string', description: 'Opaque job token to poll (when status=pending).' },+ poll: { type: 'string', description: 'GET this URL to poll the job (when status=pending).' },+ error: { type: 'string', description: 'Actionable message (when status=error). Free lane: no charge.' },+ format: { type: 'string' },+ tier: { type: 'string' },+ free: { type: 'boolean' },+ },+ },+ poll: {+ method: 'GET',+ path: '/api/3d/generate?job={job}',+ description: 'Poll a queued generation. Returns { status:pending|done|error, glbUrl?, viewerUrl?, error? }.',+ },+ example: {+ request: {+ method: 'POST',+ path: '/api/3d/generate',+ body: { prompt: 'a small ceramic robot figurine' },+ },+ response: {+ status: 'pending',+ job: 'f1.eyJwIjoibnZpZGlhIiwiayI6InRleHQiLCJ0IjoibmltLXRhc2stMTIzIn0.c2ln',+ poll: '/api/3d/generate?job=f1.eyJwIjoibnZpZGlhIiwiayI6InRleHQiLCJ0IjoibmltLXRhc2stMTIzIn0.c2ln',+ format: 'glb',+ tier: 'draft',+ free: true,+ },+ },+ paidTiers: [+ { name: 'Forge Pro', path: '/api/x402/forge', why: 'Higher polygon budgets + PBR textures, quality tiers.' },+ { name: 'Rigged Avatars', path: '/api/forge?action=rig', why: 'Animation-ready skeleton + skin weights.' },+ ],+ useCase:+ 'An agent building a game, a scene, or an NFT needs a 3D model from a text prompt — free, no key, no account. ' ++ 'It calls this to draft geometry, then upgrades to Forge Pro / Rigged Avatars when it needs production quality.',+};diff --git a/api/_lib/3d-catalog/index.js b/api/_lib/3d-catalog/index.jsnew file mode 100644index 000000000..ab935ec0a--- /dev/null+++ b/api/_lib/3d-catalog/index.js@@ -0,0 +1,164 @@+// three.ws 3D API — catalog assembler.+//+// The free 3D API is a bundle of small keyless endpoints (inspect, generate, …).+// Rather than maintain one shared list that every sibling work-order would have+// to edit (and collide on), each endpoint drops ITS OWN descriptor file in this+// directory — `api/_lib/3d-catalog/<slug>.js` — and this assembler merges them.+//+// Serverless-safe enumeration+// ---------------------------+// Vercel's function bundler (node-file-trace) only bundles files it can see via+// STATIC imports. A computed `import('./' + file)` off a `readdirSync` result is+// invisible to the tracer, so the sibling descriptors would be missing from the+// deployed lambda. Two things make the runtime read work regardless:+// 1. `vercel.json` → `functions["api/3d/*.js"].includeFiles` ships the whole+// `api/_lib/3d-catalog/**` tree into every `/api/3d/*` lambda, so the files+// exist on disk at runtime.+// 2. we enumerate with `fs.readdirSync(__dirname)` and `import(pathToFileURL())`+// each `*.js` (except this index), which resolves against those bundled+// files.+// This is the documented Vercel escape hatch for data-dir reads; it's the same+// `includeFiles` mechanism other functions in this repo use (see vercel.json).+//+// Robustness: a malformed or throwing descriptor is skipped and logged — the+// assembler NEVER throws and NEVER lets one bad entry take down the whole index.+// With zero descriptors it returns `[]`, which the `/api/3d` index renders as a+// designed "rolling out" state rather than an error.++import { readdirSync } from 'node:fs';+import { pathToFileURL } from 'node:url';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++const __dirname = dirname(fileURLToPath(import.meta.url));++// Infrastructure modules that live in this directory but are NOT catalog+// entries — the assembler itself and the OpenAPI builder. Everything else that+// is a `*.js` file is treated as an endpoint descriptor.+const NON_ENTRY = new Set(['index.js', 'openapi.js']);++const str = (v) => (typeof v === 'string' ? v.trim() : '');+const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : null);++// A descriptor is valid only if it can answer the one question the index/OpenAPI+// generator needs of every entry: what route, which method, what does it do.+// Everything else is optional and defaulted; anything failing this is skipped.+//+// Sibling work-orders author these descriptors independently and have drifted on+// field names — one uses `slug`/`title`/`method`/`inputSchema`, another uses+// `id`/`name`/`methods`/`input`. Rather than reject a perfectly good entry over a+// naming difference, we accept BOTH conventions and canonicalize to one shape the+// index + OpenAPI generator consume. Only a genuinely unusable entry (no route,+// no name, no summary) is dropped.+function normalizeEntry(raw, source) {+ const entry = raw && typeof raw === 'object' && raw.default ? raw.default : raw;+ if (!entry || typeof entry !== 'object') return null;++ const slug = str(entry.slug) || str(entry.id);+ const path = str(entry.path);+ const summary = str(entry.summary) || str(entry.description);+ // Route + a human name + one line of what-it-does are the irreducible minimum.+ if (!slug || !path || !summary) return null;++ // Methods normalize to an uppercased array; a bad value defaults to GET so a+ // half-filled descriptor still surfaces rather than vanishing.+ const rawMethods = Array.isArray(entry.methods)+ ? entry.methods+ : entry.method+ ? [entry.method]+ : ['GET'];+ const methods = rawMethods+ .map((m) => String(m || '').toUpperCase().trim())+ .filter((m) => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(m));+ if (methods.length === 0) methods.push('GET');++ return {+ slug,+ path,+ methods,+ title: str(entry.title) || str(entry.name) || slug,+ summary,+ description: str(entry.description) || summary,+ free: entry.free !== false, // free by default — this is the free bundle+ keyless: entry.keyless !== false,+ category: str(entry.category) || '3d',+ useCase: str(entry.useCase) || str(entry.agentUseCase),+ // Accept both the flat `params`/`requestBody` (OpenAPI-ish) and the nested+ // `input` shapes; downstream generators read `inputSchema`/`outputSchema`.+ params: Array.isArray(entry.params) ? entry.params : [],+ requestBody: obj(entry.requestBody),+ input: obj(entry.input),+ inputSchema: obj(entry.inputSchema) || obj(entry.input?.schema),+ outputSchema: obj(entry.outputSchema) || obj(entry.output?.schema) || obj(entry.output),+ example: entry.example && typeof entry.example === 'object' ? entry.example : null,+ poll: obj(entry.poll),+ paidTiers: Array.isArray(entry.paidTiers) ? entry.paidTiers : [],+ rateLimit: str(entry.rateLimit) || null,+ tags: Array.isArray(entry.tags) ? entry.tags.map(String) : [],+ order: Number.isFinite(entry.order) ? entry.order : 100,+ source,+ };+}++// Per-directory cache. Keyed by resolved dir so the default (production) load is+// memoized across warm serverless invocations while tests pointing at fixture+// dirs each get their own slot. `fresh:true` bypasses it.+const cache = new Map();++// loadCatalog() — merge every descriptor in `dir` (defaults to this directory).+// Skips malformed/throwing entries, dedups by route, and NEVER throws — an empty+// catalog is a valid served state.+export async function loadCatalog({ dir = __dirname, fresh = false } = {}) {+ if (!fresh && cache.has(dir)) return cache.get(dir);++ let files = [];+ try {+ files = readdirSync(dir).filter(+ (f) =>+ f.endsWith('.js') &&+ !NON_ENTRY.has(f) &&+ !f.startsWith('_') &&+ !f.startsWith('.') &&+ !f.endsWith('.test.js'),+ );+ } catch (err) {+ // Directory unreadable (should never happen once bundled) — degrade to an+ // empty, valid catalog rather than throwing.+ console.warn(`[3d-catalog] could not read catalog dir ${dir}:`, err?.message || err);+ cache.set(dir, []);+ return cache.get(dir);+ }++ const entries = [];+ const seen = new Set();+ for (const file of files) {+ try {+ const mod = await import(pathToFileURL(join(dir, file)).href);+ const normalized = normalizeEntry(mod.default ?? mod.entry ?? mod, file);+ if (!normalized) {+ console.warn(`[3d-catalog] skipping malformed entry: ${file}`);+ continue;+ }+ // First descriptor to claim a route+method combo wins; a duplicate is+ // dropped rather than emitting two operations for one route.+ const key = `${normalized.methods.join(',')} ${normalized.path}`;+ if (seen.has(key)) {+ console.warn(`[3d-catalog] skipping duplicate route: ${key} (${file})`);+ continue;+ }+ seen.add(key);+ entries.push(normalized);+ } catch (err) {+ // One broken descriptor must never break the whole index.+ console.warn(`[3d-catalog] failed to load entry ${file}:`, err?.message || err);+ }+ }++ entries.sort((a, b) => a.order - b.order || a.slug.localeCompare(b.slug));+ cache.set(dir, entries);+ return cache.get(dir);+}++// Synchronous, side-effect-free normalizer export so tests can validate the+// skip-malformed contract without touching the filesystem.+export { normalizeEntry };diff --git a/api/_lib/3d-catalog/inspect.js b/api/_lib/3d-catalog/inspect.jsnew file mode 100644index 000000000..e73df0207--- /dev/null+++ b/api/_lib/3d-catalog/inspect.js@@ -0,0 +1,139 @@+// Catalog entry for the free 3D Inspect endpoint. The /api/3d index (prompt 14)+// globs api/_lib/3d-catalog/*.js and merges every default export into the public+// API catalog + the generated OpenAPI doc. Each entry is a self-describing,+// OpenAPI-friendly record: path, methods, input/output schemas, and a live+// example. Same entry shape as the crypto catalog — one file per endpoint so+// parallel agents never edit a shared list.++export default {+ id: 'inspect',+ name: '3D Model Inspect & Validate',+ path: '/api/3d/inspect',+ methods: ['GET', 'POST'],+ free: true,+ keyless: true,+ category: '3d',+ tags: ['3d', 'gltf', 'glb', 'validation', 'inspection', 'optimization'],+ summary:+ 'Validate a glTF/GLB and return structural stats plus a prioritized optimization plan.',+ description:+ 'Fetches a glTF (.gltf) or binary glTF (.glb) from a URL (or accepts a raw upload), runs ' ++ 'the Khronos glTF-Validator for the spec-compliance verdict, and reports structural stats ' ++ '(vertices, triangles, materials, textures, animations, extensions) plus a severity-ranked ' ++ 'list of make-it-smaller/faster recommendations. Free, keyless, no account.',+ useCase:+ 'An autonomous agent handling a 3D asset from any source validates it and sizes it up — ' ++ 'is it spec-valid, how heavy is it, what should it optimize — before committing to use it. ' ++ 'Free adoption funnels to the paid Forge Pro quality tiers, Rigged Avatars, and mesh ' ++ 'optimization pipelines.',+ input: {+ query: {+ url: {+ type: 'string',+ format: 'uri',+ required: false,+ description: 'Public https URL of a .glb or .gltf model (≤32 MiB).',+ },+ },+ body: {+ description:+ 'POST { "url": "…" } as application/json, OR upload raw .glb/.gltf bytes as the request body.',+ },+ },+ inputSchema: {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ url: {+ type: 'string',+ format: 'uri',+ description: 'Public https URL of a glTF (.gltf) or binary glTF (.glb) model. Max 32 MiB.',+ },+ },+ },+ outputSchema: {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['valid', 'stats', 'sizeBytes', 'recommendations', 'ts'],+ properties: {+ url: { type: ['string', 'null'], format: 'uri' },+ valid: { type: 'boolean' },+ sizeBytes: { type: 'integer' },+ stats: {+ type: 'object',+ required: ['vertices', 'triangles', 'materials', 'textures', 'animations', 'extensions'],+ properties: {+ vertices: { type: 'integer' },+ triangles: { type: 'integer' },+ materials: { type: 'integer' },+ textures: { type: 'integer' },+ animations: { type: 'integer' },+ extensions: { type: 'array', items: { type: 'string' } },+ meshes: { type: 'integer' },+ nodes: { type: 'integer' },+ scenes: { type: 'integer' },+ skins: { type: 'integer' },+ joints: { type: 'integer' },+ container: { type: 'string', enum: ['glb', 'gltf'] },+ generator: { type: ['string', 'null'] },+ },+ },+ recommendations: {+ type: 'array',+ items: {+ type: 'object',+ required: ['severity', 'issue', 'fix'],+ properties: {+ severity: { type: 'string', enum: ['critical', 'warn', 'info'] },+ issue: { type: 'string' },+ fix: { type: 'string' },+ },+ },+ },+ validation: {+ type: 'object',+ properties: {+ valid: { type: 'boolean' },+ validatorVersion: { type: ['string', 'null'] },+ numErrors: { type: 'integer' },+ numWarnings: { type: 'integer' },+ numInfos: { type: 'integer' },+ numHints: { type: 'integer' },+ },+ },+ ts: { type: 'string', format: 'date-time' },+ },+ },+ example: {+ request: 'GET /api/3d/inspect?url=https://three.ws/avatars/cesium-man.glb',+ response: {+ url: 'https://three.ws/avatars/cesium-man.glb',+ valid: true,+ sizeBytes: 495956,+ stats: {+ vertices: 3272,+ triangles: 4672,+ materials: 1,+ textures: 1,+ animations: 1,+ extensions: [],+ meshes: 1,+ nodes: 22,+ scenes: 1,+ skins: 1,+ joints: 19,+ container: 'glb',+ generator: 'COLLADA2GLTF',+ },+ recommendations: [+ {+ severity: 'info',+ issue: 'Model looks well-optimized for web delivery — no suggestions flagged.',+ fix: 'No action needed — the model is already well-suited for web delivery.',+ },+ ],+ validation: { valid: true, numErrors: 0, numWarnings: 0, numInfos: 0, numHints: 0 },+ ts: '2026-07-07T00:00:00.000Z',+ },+ },+};diff --git a/api/_lib/3d-catalog/openapi.js b/api/_lib/3d-catalog/openapi.jsnew file mode 100644index 000000000..34b0b0560--- /dev/null+++ b/api/_lib/3d-catalog/openapi.js@@ -0,0 +1,218 @@+// @ts-check+// Build a real OpenAPI 3.1 document FROM the free 3D API catalog entries.+//+// The catalog (see ./index.js) is the single source of truth; this renders it+// into the spec agents and tooling (Swagger UI, openapi-generator, LangChain's+// OpenAPI toolkit) consume. Every path, parameter, requestBody, and response+// schema comes from an entry's normalized `path` / `methods` / `inputSchema` /+// `outputSchema` — nothing is hand-maintained, so the spec can never drift from+// what `/api/3d` lists.+//+// Method-aware: entries carry a `methods` array. A GET emits the input schema as+// query/path `parameters`; a POST/PUT/PATCH emits it as a JSON `requestBody`.+// This mirrors the real endpoints — inspect is GET+POST, generate is POST.++/** @param {string} path @returns {Set<string>} names of `{templated}` segments */+function pathParamNames(path) {+ const names = new Set();+ const re = /\{([^}]+)\}/g;+ let m;+ while ((m = re.exec(path))) names.add(m[1]);+ return names;+}++/** Normalize one property descriptor into an OpenAPI Schema Object. */+function toSchema(prop) {+ if (!prop || typeof prop !== 'object') return { type: 'string' };+ const { description, example, required, ...schema } = prop;+ if (!schema.type && !schema.oneOf && !schema.anyOf && !schema.$ref) schema.type = 'string';+ return schema;+}++/**+ * Convert an entry's `inputSchema` into an OpenAPI `parameters` array (for GET).+ * Accepts either a JSON-Schema object or an array of OpenAPI parameter objects.+ * @param {any} inputSchema+ * @param {Set<string>} inPath+ * @returns {Array<object>}+ */+function toParameters(inputSchema, inPath) {+ if (!inputSchema) {+ return [...inPath].map((name) => ({+ name,+ in: 'path',+ required: true,+ schema: { type: 'string' },+ }));+ }++ if (Array.isArray(inputSchema)) {+ return inputSchema+ .filter((p) => p && typeof p === 'object' && typeof p.name === 'string')+ .map((p) => ({+ name: p.name,+ in: p.in || (inPath.has(p.name) ? 'path' : 'query'),+ required: p.required ?? inPath.has(p.name),+ ...(p.description ? { description: p.description } : {}),+ schema: p.schema || toSchema(p),+ ...(p.example !== undefined ? { example: p.example } : {}),+ }));+ }++ const properties =+ inputSchema.properties && typeof inputSchema.properties === 'object'+ ? inputSchema.properties+ : {};+ const required = new Set(Array.isArray(inputSchema.required) ? inputSchema.required : []);+ const params = Object.entries(properties).map(([name, prop]) => {+ const isPath = inPath.has(name);+ const p = /** @type {any} */ (prop || {});+ return {+ name,+ in: isPath ? 'path' : 'query',+ required: isPath || required.has(name),+ ...(p.description ? { description: p.description } : {}),+ schema: toSchema(p),+ ...(p.example !== undefined ? { example: p.example } : {}),+ };+ });+ for (const name of inPath) {+ if (!params.some((p) => p.name === name)) {+ params.push({ name, in: 'path', required: true, schema: { type: 'string' } });+ }+ }+ return params;+}++/** Build a JSON requestBody (for POST/PUT/PATCH) from an entry's inputSchema. */+function toRequestBody(inputSchema, requestBodyOverride) {+ if (requestBodyOverride && typeof requestBodyOverride === 'object') return requestBodyOverride;+ if (!inputSchema || typeof inputSchema !== 'object' || Array.isArray(inputSchema)) return null;+ const schema =+ inputSchema.type || inputSchema.properties || inputSchema.$ref+ ? inputSchema+ : { type: 'object', properties: inputSchema };+ return {+ required: Array.isArray(inputSchema.required) && inputSchema.required.length > 0,+ content: { 'application/json': { schema } },+ };+}++/** Build the response schema for an entry from its `outputSchema`. */+function toResponseSchema(outputSchema) {+ if (outputSchema && typeof outputSchema === 'object') {+ if (outputSchema.type || outputSchema.properties || outputSchema.$ref) return outputSchema;+ return { type: 'object', properties: outputSchema };+ }+ return { type: 'object', additionalProperties: true };+}++const BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);++/**+ * @param {Array<any>} entries normalized 3d-catalog entries+ * @param {{ origin?: string, version?: string }} [opts]+ * @returns {object} OpenAPI 3.1 document+ */+export function buildOpenApiDoc(entries, { origin = 'https://three.ws', version = '1.0.0' } = {}) {+ /** @type {Record<string, any>} */+ const paths = {};++ for (const e of entries) {+ const inPath = pathParamNames(e.path);+ const methods = Array.isArray(e.methods) && e.methods.length ? e.methods : ['GET'];+ if (!paths[e.path]) paths[e.path] = {};++ for (const method of methods) {+ const isBody = BODY_METHODS.has(method);+ const op = {+ operationId: methods.length > 1 ? `${e.slug}_${method.toLowerCase()}` : e.slug,+ summary: e.title || e.slug,+ ...(e.description || e.summary ? { description: e.description || e.summary } : {}),+ tags: ['3d'],+ ...(isBody+ ? {+ ...(toRequestBody(e.inputSchema, e.requestBody)+ ? { requestBody: toRequestBody(e.inputSchema, e.requestBody) }+ : {}),+ parameters: [...inPath].map((name) => ({+ name,+ in: 'path',+ required: true,+ schema: { type: 'string' },+ })),+ }+ : { parameters: toParameters(e.inputSchema, inPath) }),+ responses: {+ 200: {+ description: e.summary || `${e.title || e.slug} response`,+ content: {+ 'application/json': {+ schema: toResponseSchema(e.outputSchema),+ ...(e.example !== undefined && e.example !== null+ ? { example: e.example }+ : {}),+ },+ },+ },+ 400: { description: 'Invalid or missing input.' },+ 429: { description: 'Rate limited — retry after the `Retry-After` header.' },+ 502: { description: 'Upstream fetch or generation backend failed.' },+ },+ };+ paths[e.path][method.toLowerCase()] = op;+ }+ }++ return {+ openapi: '3.1.0',+ info: {+ title: 'three.ws 3D API',+ version,+ description:+ 'A free, keyless 3D API for AI agents — turn text into a real GLB model ' ++ 'and validate/optimize any glTF/GLB, all from one origin. No account, no ' ++ 'API key. Free draft generation and inspection funnel to paid Forge Pro ' ++ 'quality tiers and Rigged Avatars. See https://three.ws/docs/3d-api.',+ contact: { name: 'three.ws', url: 'https://three.ws', email: '[email protected]' },+ license: { name: 'Free to use', url: 'https://three.ws/docs/3d-api' },+ },+ servers: [{ url: origin, description: 'three.ws production' }],+ tags: [{ name: '3d', description: 'Free, keyless text→3D and glTF/GLB inspection endpoints.' }],+ paths,+ };+}++/**+ * Minimal structural assertion used by tests and by any caller that wants to+ * fail fast on a malformed doc. Returns an array of problems (empty = valid).+ * @param {any} doc+ * @returns {string[]}+ */+export function validateOpenApiDoc(doc) {+ const problems = [];+ if (!doc || typeof doc !== 'object') return ['document is not an object'];+ if (doc.openapi !== '3.1.0') problems.push(`openapi must be "3.1.0", got ${doc.openapi}`);+ if (!doc.info || typeof doc.info !== 'object') problems.push('info object missing');+ else {+ if (!doc.info.title) problems.push('info.title missing');+ if (!doc.info.version) problems.push('info.version missing');+ }+ if (!doc.paths || typeof doc.paths !== 'object') problems.push('paths object missing');+ else {+ for (const [p, item] of Object.entries(doc.paths)) {+ if (!p.startsWith('/')) problems.push(`path "${p}" must start with "/"`);+ for (const [verb, op] of Object.entries(/** @type {any} */ (item))) {+ if (!HTTP_VERBS.has(verb)) continue;+ const o = /** @type {any} */ (op);+ if (!o.responses || typeof o.responses !== 'object')+ problems.push(`${verb.toUpperCase()} ${p}: responses missing`);+ if (verb === 'get' && !Array.isArray(o.parameters))+ problems.push(`GET ${p}: parameters must be an array`);+ }+ }+ }+ return problems;+}++const HTTP_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options']);diff --git a/api/_lib/ai-image-lanes.js b/api/_lib/ai-image-lanes.jsnew file mode 100644index 000000000..c7b8639f0--- /dev/null+++ b/api/_lib/ai-image-lanes.js@@ -0,0 +1,221 @@+// Lane configuration, health, and response shaping for POST /api/v1/ai/image.+//+// The endpoint routes across the same free/subsidized text→image lanes the 3D+// forge uses (api/_mcp3d/text-to-image.js): NVIDIA NIM FLUX (free), Google+// Vertex/Gemini image (GCP credits), and a Replicate paid backstop. This module+// answers three questions the route needs without duplicating that lane logic:+//+// 1. Which lanes are configured right now? (drives the honest 503 before the+// GCP env lands, and the /api/v1/ai/image?health=1 probe)+// 2. Is a delivered result a provider safety refusal? (→ 422, never retried)+// 3. What provider label + nominal dimensions describe the result?+//+// It never generates an image itself — health probes are auth/reachability+// checks against each lane's cheap surface, so they cost nothing against quota.++import { getGcpAccessToken, gcpAuthConfigured } from './gcp-auth.js';+import { providersInCooldown } from './provider-health.js';++function readEnv(name) {+ if (typeof process !== 'undefined' && process.env?.[name]) return process.env[name];+ return null;+}++// Mirror of the private gate in text-to-image.js: the Vertex lane is active when+// GOOGLE_CLOUD_PROJECT is set unless VERTEX_IMAGEN_ENABLED explicitly disables it.+function vertexImagenEnabled() {+ const raw = readEnv('VERTEX_IMAGEN_ENABLED');+ if (raw == null) return true;+ return !/^(0|false|no|off)$/i.test(String(raw).trim());+}++// The circuit-breaker key text-to-image.js records a NIM FLUX failure under, so+// the health probe can report a cooling lane as degraded without its own probe.+const NIM_FLUX_COOLDOWN_KEY = 'forge-nim-flux';++// Env vars that gate at least one image lane. Named verbatim in the 503 body so+// the operator knows exactly what to set. NVIDIA / Vertex are the primary+// subsidized lanes; Replicate is the paid backstop.+export const IMAGE_LANE_ENV = Object.freeze({+ nim: ['NVIDIA_API_KEY'],+ vertex: ['GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON', 'GOOGLE_CLOUD_LOCATION'],+ replicate: ['REPLICATE_API_TOKEN'],+});++/**+ * Static (no-I/O) view of which lanes are wired from the current env. Matches+ * text-to-image.js's own config gate so "the endpoint works the moment a lane is+ * set" and "503 not_configured when none are" stay in lockstep with the router.+ */+export function imageLaneConfig() {+ const nim = Boolean(readEnv('NVIDIA_API_KEY'));+ const vertex = Boolean(readEnv('GOOGLE_CLOUD_PROJECT')) && vertexImagenEnabled();+ const replicate = Boolean(readEnv('REPLICATE_API_TOKEN'));+ return {+ nim,+ vertex,+ replicate,+ anyConfigured: nim || vertex || replicate,+ };+}++// Flat list of the env vars an operator must set to bring up an image lane —+// surfaced in the 503 body when nothing is configured.+export function missingLaneEnv() {+ return [...IMAGE_LANE_ENV.nim, ...IMAGE_LANE_ENV.vertex.slice(0, 2), ...IMAGE_LANE_ENV.replicate];+}++// ── Provider labelling + dimensions ──────────────────────────────────────────++// Canonical ~1MP pixel dimensions per aspect ratio, mirroring the NIM FLUX map.+// The lanes don't return the rendered size (Gemini takes an aspect ratio, not a+// width/height), so these are the nominal target dimensions for the request.+export const ASPECT_DIMENSIONS = Object.freeze({+ '1:1': [1024, 1024],+ '16:9': [1344, 768],+ '9:16': [768, 1344],+ '4:3': [1024, 768],+ '3:4': [768, 1024],+ '3:2': [1216, 832],+ '2:3': [832, 1216],+});++export const SUPPORTED_ASPECT_RATIOS = Object.freeze(Object.keys(ASPECT_DIMENSIONS));++export function dimensionsFor(aspectRatio) {+ const [width, height] = ASPECT_DIMENSIONS[aspectRatio] || ASPECT_DIMENSIONS['1:1'];+ return { width, height };+}++/**+ * Friendly provider label for a textToImage() result. Distinguishes NIM FLUX+ * from the Replicate flux backstop (both carry a black-forest-labs/flux* model+ * id) via the Replicate-only predictionId, and Vertex by its vertex-ai/ prefix.+ */+export function providerLabel(result) {+ const model = String(result?.model || '');+ if (model.startsWith('vertex-ai/')) return 'vertex';+ if (result?.predictionId) return 'replicate';+ if (model) return 'nvidia-nim';+ return 'unknown';+}++// ── Safety-refusal detection ─────────────────────────────────────────────────++// Gemini/Imagen block a prohibited prompt by returning candidates with a+// finishReason and no image part; text-to-image.js surfaces that as an error+// whose message carries the finishReason. These are the block enums Vertex emits.+const REFUSAL_FINISH_REASONS = /finishReason:\s*(SAFETY|IMAGE_SAFETY|PROHIBITED_CONTENT|RECITATION|BLOCKLIST|SPII|CONTENT_FILTERED|IMAGE_PROHIBITED_CONTENT)/i;+const REFUSAL_PHRASES = /\b(safety|content policy|prohibited content|blocked by|policy violation)\b/i;++/**+ * True when a thrown lane error is a provider safety refusal (content policy),+ * as opposed to a transient outage. A refusal is a terminal verdict about the+ * prompt — the caller must fix the prompt, so it is surfaced as 422 and never+ * retried. A rate-limit / unreachable / billing error is explicitly NOT a+ * refusal (those carry their own codes and are retryable).+ */+export function isProviderRefusal(err) {+ if (!err) return false;+ if (['rate_limited', 'provider_unreachable', 'billing', 'unconfigured'].includes(err.code)) return false;+ const msg = String(err.message || '');+ return REFUSAL_FINISH_REASONS.test(msg) || REFUSAL_PHRASES.test(msg);+}++/** Human-readable refusal reason pulled from the provider error, for the 422 body. */+export function refusalReason(err) {+ const msg = String(err?.message || '');+ const m = REFUSAL_FINISH_REASONS.exec(msg);+ if (m) return `Provider blocked this prompt (${m[1]}).`;+ return 'Provider declined this prompt for content-policy reasons.';+}++// ── Health probe ─────────────────────────────────────────────────────────────++const PROBE_TIMEOUT_MS = 3_000;++// NIM: no free "account" endpoint, so reachability is a plain GET to the API host+// (any answer <500 proves it is routable) folded with the shared FLUX cooldown+// breaker so a recently-failed lane reads as degraded without a probe.+async function probeNim() {+ if (!readEnv('NVIDIA_API_KEY')) return { configured: false, status: 'unconfigured' };+ let cooled = false;+ try {+ cooled = (await providersInCooldown([NIM_FLUX_COOLDOWN_KEY])).has(NIM_FLUX_COOLDOWN_KEY);+ } catch { /* cache miss → not cooling */ }+ if (cooled) return { configured: true, status: 'degraded', detail: 'recent failure cooldown' };+ try {+ const res = await fetch('https://ai.api.nvidia.com/v1/models', {+ headers: { authorization: `Bearer ${readEnv('NVIDIA_API_KEY')}` },+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ });+ return { configured: true, status: res.status < 500 ? 'ok' : 'down', httpStatus: res.status };+ } catch (err) {+ return { configured: true, status: 'down', detail: err?.message?.slice(0, 120) };+ }+}++// Vertex: mint a GCP access token. Success proves the service-account creds and+// the token endpoint work — the actual credit-burning generateContent call is+// never made, so this costs nothing against the image budget.+async function probeVertex() {+ const project = readEnv('GOOGLE_CLOUD_PROJECT');+ if (!project || !vertexImagenEnabled()) return { configured: false, status: 'unconfigured' };+ if (!gcpAuthConfigured()) {+ return {+ configured: true,+ status: 'down',+ detail: 'GCP_SERVICE_ACCOUNT_JSON not set',+ model: readEnv('VERTEX_IMAGEN_MODEL') || 'gemini-2.5-flash-image',+ };+ }+ try {+ await getGcpAccessToken();+ return {+ configured: true,+ status: 'ok',+ model: readEnv('VERTEX_IMAGEN_MODEL') || 'gemini-2.5-flash-image',+ location: readEnv('GOOGLE_CLOUD_LOCATION') || 'us-central1',+ };+ } catch (err) {+ return { configured: true, status: 'down', detail: err?.message?.slice(0, 120) };+ }+}++// Replicate: authenticated GET /v1/account — 200 proves a valid key + reachable+// host without creating a (billed) prediction.+async function probeReplicate() {+ const token = readEnv('REPLICATE_API_TOKEN');+ if (!token) return { configured: false, status: 'unconfigured' };+ try {+ const res = await fetch('https://api.replicate.com/v1/account', {+ headers: { authorization: `Bearer ${token}` },+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ });+ if (res.status === 200) return { configured: true, status: 'ok' };+ if (res.status === 401) return { configured: true, status: 'down', detail: 'invalid token' };+ return { configured: true, status: res.status < 500 ? 'ok' : 'down', httpStatus: res.status };+ } catch (err) {+ return { configured: true, status: 'down', detail: err?.message?.slice(0, 120) };+ }+}++/**+ * Per-lane configured/reachable health for the /api/v1/ai/image?health=1 probe.+ * Probes only configured lanes; unconfigured lanes report `unconfigured` with no+ * network call. `healthy` is true when at least one lane is reachable, so the+ * probe distinguishes "not wired yet" from "wired but every lane is down".+ */+export async function imageLaneHealth() {+ const [nim, vertex, replicate] = await Promise.all([probeNim(), probeVertex(), probeReplicate()]);+ const lanes = { nim, vertex, replicate };+ const anyConfigured = Object.values(lanes).some((l) => l.configured);+ const anyReachable = Object.values(lanes).some((l) => l.status === 'ok');+ return {+ endpoint: '/api/v1/ai/image',+ configured: anyConfigured,+ healthy: anyReachable,+ lanes,+ missing_env: anyConfigured ? [] : missingLaneEnv(),+ };+}diff --git a/api/_lib/ai-image-quota.js b/api/_lib/ai-image-quota.jsnew file mode 100644index 000000000..dd69c7e41--- /dev/null+++ b/api/_lib/ai-image-quota.js@@ -0,0 +1,140 @@+// Per-IP daily free-image quota for POST /api/v1/ai/image.+//+// The image endpoint is a free-tier funnel: the first N generations per IP per+// UTC day are served for free (payment bypassed), and callers past the quota+// fall through to the x402 pay-per-image lane. This module owns that counter.+//+// Semantics:+// • peekFreeQuota(ip) — READ ONLY. Answers "is this IP still under quota?"+// without spending a slot. Called at the access-control+// hook, before the image is generated.+// • consumeFreeQuota(ip) — spend one slot. Called ONLY after an image is+// actually delivered, so a validation error, a safety+// refusal, or an upstream outage never burns a free+// generation the caller didn't receive.+//+// The peek/consume split means the counter fails OPEN: under a burst two+// instances can both peek "allowed" before either consumes, letting a caller+// slip one or two extra free images. That is the correct bias for a free funnel+// (generous, never wrongly charges) — the paid lane and the x402 rail carry the+// money-critical guarantees, not this counter.+//+// Storage: an atomic Redis INCR on a day-stamped key (natural daily reset). When+// Redis is absent (local dev / tests) it degrades to a per-instance in-memory+// map — fine, because without Redis there is no cross-instance state to protect+// and the free tier is not a spend gate.++import { getRedis } from './redis.js';++const redis = getRedis();++// Default free allowance per IP per day. Env-overridable so ops can tune the+// funnel width without a redeploy.+const DEFAULT_FREE_PER_DAY = 5;++export function freePerDay() {+ const raw = process.env.X402_AI_IMAGE_FREE_PER_DAY;+ if (raw == null || String(raw).trim() === '') return DEFAULT_FREE_PER_DAY;+ const n = Number.parseInt(String(raw).trim(), 10);+ return Number.isFinite(n) && n >= 0 ? n : DEFAULT_FREE_PER_DAY;+}++// UTC day stamp (YYYY-MM-DD). Baking it into the key makes the quota reset at+// 00:00 UTC on its own — a new day is a new key, so the count starts at zero+// even before the old key's TTL lapses.+function utcDay(now = new Date()) {+ return now.toISOString().slice(0, 10);+}++function keyFor(ip, day = utcDay()) {+ return `aiimg:free:${ip || 'unknown'}:${day}`;+}++// Seconds until the next UTC midnight, floored to a minute so a key always+// outlives its own day. A generous +1h buffer covers clock skew between the+// counter write and the day rollover.+function ttlSeconds(now = new Date()) {+ const next = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1, 0, 0, 0));+ return Math.max(60, Math.ceil((next.getTime() - now.getTime()) / 1000) + 3600);+}++function resetAtIso(now = new Date()) {+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1, 0, 0, 0)).toISOString();+}++// ── In-memory fallback (no Redis) ────────────────────────────────────────────+// Keyed by the same day-stamped key so it also resets at the UTC boundary.+const memory = new Map();++function memGet(key) {+ const hit = memory.get(key);+ return hit ? hit.count : 0;+}++function memIncr(key, ttlMs) {+ const hit = memory.get(key);+ if (hit && hit.expiresAt > Date.now()) {+ hit.count += 1;+ return hit.count;+ }+ memory.set(key, { count: 1, expiresAt: Date.now() + ttlMs });+ return 1;+}++// ── Public API ───────────────────────────────────────────────────────────────++/**+ * Read-only view of an IP's free-image standing for today. Never mutates the+ * counter. Fails open (allowed: true) on any storage error — a Redis hiccup must+ * never wrongly demand payment for a call the free tier should have served.+ *+ * @param {string} ip+ * @returns {Promise<{allowed: boolean, used: number, limit: number, remaining: number, resetAt: string}>}+ */+export async function peekFreeQuota(ip) {+ const limit = freePerDay();+ const key = keyFor(ip);+ let used = 0;+ try {+ used = redis ? Number(await redis.get(key)) || 0 : memGet(key);+ } catch {+ used = 0; // storage unreachable → treat as fresh, fail open+ }+ const remaining = Math.max(0, limit - used);+ return { allowed: used < limit, used, limit, remaining, resetAt: resetAtIso() };+}++/**+ * Spend one free-image slot for an IP and return the post-increment view. Call+ * this only after an image was actually delivered. Atomic under Redis (INCR ++ * first-write EXPIRE); best-effort in-memory otherwise. Never throws — a failed+ * count must not fail an image the caller already received.+ *+ * @param {string} ip+ * @returns {Promise<{used: number, limit: number, remaining: number, resetAt: string}>}+ */+export async function consumeFreeQuota(ip) {+ const limit = freePerDay();+ const key = keyFor(ip);+ let used = 1;+ try {+ if (redis) {+ used = Number(await redis.incr(key));+ // Set the daily TTL exactly once, on the key's first write, so a busy IP+ // doesn't keep pushing the expiry out and never resetting.+ if (used === 1) await redis.expire(key, ttlSeconds());+ } else {+ used = memIncr(key, ttlSeconds() * 1000);+ }+ } catch {+ // Count lost — the image already shipped, so swallow and report a best guess.+ }+ const remaining = Math.max(0, limit - used);+ return { used, limit, remaining, resetAt: resetAtIso() };+}++// Test hook — the in-memory fallback persists across a module's lifetime; tests+// that exercise the no-Redis path need a clean slate.+export function __resetFreeQuota() {+ memory.clear();+}diff --git a/api/_lib/crypto-catalog/bonding.js b/api/_lib/crypto-catalog/bonding.jsnew file mode 100644index 000000000..cc6e48174--- /dev/null+++ b/api/_lib/crypto-catalog/bonding.js@@ -0,0 +1,75 @@+// Crypto Data API catalog entry — bonding-curve / graduation status.+// Globbed by api/_lib/crypto-catalog/index.js (prompt 10) into the /api/crypto+// front-door index + OpenAPI doc. Stands alone if that index doesn't exist yet.++export default {+ slug: 'bonding',+ method: 'GET',+ path: '/api/crypto/bonding',+ title: 'Bonding-Curve / Graduation Status',+ summary:+ 'Where a pump.fun token sits on its bonding curve — % to graduation, SOL in the ' ++ 'curve, and tokens left to buy — plus whether it has already graduated and ' ++ 'migrated to an AMM (Raydium / PumpSwap). The read an agent needs to time entries ' ++ 'and exits around graduation.',+ free: true,+ keyless: true,+ inputSchema: {+ type: 'object',+ required: ['mint'],+ properties: {+ mint: {+ type: 'string',+ description: 'pump.fun token mint (base58 Solana address).',+ },+ },+ },+ outputSchema: {+ type: 'object',+ required: ['mint', 'onCurve', 'graduated', 'ts', 'source'],+ properties: {+ mint: { type: 'string' },+ onCurve: { type: 'boolean', description: 'true while still on the bonding curve' },+ bondingProgressPct: {+ type: ['number', 'null'],+ minimum: 0,+ maximum: 100,+ description: 'share of the curve bought out (100 once graduated)',+ },+ solInCurve: {+ type: ['number', 'null'],+ description: 'real SOL reserves in the curve (null once graduated)',+ },+ tokensRemaining: {+ type: ['number', 'null'],+ description: 'tokens left to buy on the curve (null once graduated)',+ },+ marketCapUsd: { type: ['number', 'null'] },+ graduated: {+ type: 'boolean',+ description: 'completed the curve and migrated to an AMM',+ },+ migratedTo: {+ type: ['string', 'null'],+ enum: ['raydium', 'pumpswap', null],+ description: 'the AMM a graduated token migrated to',+ },+ ts: { type: 'string', format: 'date-time' },+ source: { type: 'string' },+ },+ },+ example: {+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ onCurve: true,+ bondingProgressPct: 70.67,+ solInCurve: 32.81,+ tokensRemaining: 232581073.73,+ marketCapUsd: 10095.72,+ graduated: false,+ migratedTo: null,+ ts: '2026-07-07T00:00:00.000Z',+ source: 'pumpfun',+ },+ related: ['/api/crypto/launches', '/api/crypto/whales'],+ tags: ['pump.fun', 'bonding-curve', 'graduation'],+};diff --git a/api/_lib/crypto-catalog/index.js b/api/_lib/crypto-catalog/index.jsnew file mode 100644index 000000000..cab3f1637--- /dev/null+++ b/api/_lib/crypto-catalog/index.js@@ -0,0 +1,161 @@+// @ts-check+// The Crypto Data API catalog assembler.+//+// Every endpoint in the free Crypto Data API bundle drops its OWN descriptor+// file in this directory (e.g. `token.js`, `holders.js`) and never edits a+// shared list, so parallel agents building sibling endpoints never collide.+// This module discovers whatever entry files exist at call time and merges+// their exported descriptors into one array — the single source of truth behind+// `GET /api/crypto` (the human/agent index) and `/api/crypto/openapi.json` (the+// machine-readable spec). Add an endpoint → it appears in both automatically.+//+// Why a runtime directory read instead of a hand-maintained barrel: a barrel+// would force every sibling prompt to edit one shared file, reintroducing the+// merge conflicts the per-file convention exists to avoid. Vercel's file tracer+// won't follow this dynamic `import()` on its own, so `api/crypto/index.js` and+// `api/crypto/openapi.js` pin `includeFiles: "api/_lib/crypto-catalog/**"` in+// vercel.json — that copies every entry file into the serverless bundle so the+// `readdir` below finds them in production exactly as it does in local dev and+// under vitest.+//+// Robustness contract (per the endpoint spec): a malformed or throwing entry is+// skipped and logged, never fatal. Zero entries is a valid state — the index+// returns an empty catalog, not an error.++import { readdirSync } from 'node:fs';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { dirname, join } from 'node:path';++const HERE = dirname(fileURLToPath(import.meta.url));++// Files in this directory that are the machinery, not catalog entries. Anything+// starting with `_` or `.` is also treated as non-entry (private/hidden).+const NON_ENTRY = new Set(['index.js', 'openapi.js']);++const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);++/**+ * A descriptor is usable iff it names a slug, an absolute path, and a real HTTP+ * method. Everything else is optional and defaulted in `normalize`.+ * @param {any} e+ */+function isValidEntry(e) {+ return Boolean(+ e &&+ typeof e === 'object' &&+ typeof e.slug === 'string' &&+ e.slug.trim() &&+ typeof e.path === 'string' &&+ e.path.startsWith('/') &&+ typeof e.method === 'string' &&+ HTTP_METHODS.has(e.method.toUpperCase()),+ );+}++/**+ * Coerce a raw descriptor into the stable public shape. Missing optional fields+ * become sensible defaults (never `undefined`, so the JSON shape is stable) and+ * unexpected extra keys are dropped so one entry can't pollute the catalog.+ *+ * Sibling endpoints converged on two spellings for their I/O contract, so both+ * are accepted: the JSON-Schema form (`inputSchema`/`outputSchema`, used by most+ * entries) and the terser param-map form (`input`/`output`). Either lands in the+ * canonical `inputSchema`/`outputSchema` fields; the OpenAPI generator handles+ * both representations. `methods` (an array) is honored for entries that answer+ * more than one verb (e.g. GET + POST), falling back to the single `method`.+ * @param {any} e+ */+function normalize(e) {+ const method = e.method.toUpperCase();+ const methods =+ Array.isArray(e.methods) && e.methods.length+ ? [...new Set(e.methods.map((m) => String(m).toUpperCase()).filter((m) => HTTP_METHODS.has(m)))]+ : [method];+ return {+ slug: e.slug.trim(),+ method,+ methods: methods.includes(method) ? methods : [method, ...methods],+ path: e.path,+ title: typeof e.title === 'string' && e.title.trim() ? e.title.trim() : e.slug.trim(),+ summary: typeof e.summary === 'string' ? e.summary : '',+ inputSchema: pickObject(e.inputSchema ?? e.input),+ outputSchema: pickObject(e.outputSchema ?? e.output),+ example: e.example === undefined ? null : e.example,+ };+}++/** Return the value iff it's a non-null object, else null. */+function pickObject(v) {+ return v && typeof v === 'object' ? v : null;+}++// Per-directory cache. Keyed by resolved dir so the default (production) load is+// memoized across serverless invocations while tests pointing at fixture dirs+// each get their own slot. `fresh:true` bypasses it.+/** @type {Map<string, Array<ReturnType<typeof normalize>>>} */+const cache = new Map();++/**+ * Assemble the catalog by globbing entry files in `dir`.+ * @param {{ dir?: string, fresh?: boolean }} [opts]+ * @returns {Promise<Array<ReturnType<typeof normalize>>>}+ */+export async function loadCatalog({ dir = HERE, fresh = false } = {}) {+ if (!fresh && cache.has(dir)) return cache.get(dir);++ let files = [];+ try {+ files = readdirSync(dir).filter(+ (f) =>+ f.endsWith('.js') &&+ !NON_ENTRY.has(f) &&+ !f.startsWith('_') &&+ !f.startsWith('.') &&+ !f.endsWith('.test.js'),+ );+ } catch (err) {+ // Directory unreadable (shouldn't happen given includeFiles, but never+ // throw from the assembler — an empty catalog is a valid served state).+ console.warn(`[crypto-catalog] could not read entry dir ${dir}: ${err.message}`);+ cache.set(dir, []);+ return [];+ }++ /** @type {Array<ReturnType<typeof normalize>>} */+ const entries = [];+ const seen = new Set();++ for (const file of files.sort()) {+ try {+ // eslint-disable-next-line no-await-in-loop+ const mod = await import(pathToFileURL(join(dir, file)).href);+ const raw = mod.default ?? mod.entry ?? mod.catalogEntry;+ if (!isValidEntry(raw)) {+ console.warn(+ `[crypto-catalog] skipping ${file}: no valid descriptor export (need { slug, method, path })`,+ );+ continue;+ }+ const entry = normalize(raw);+ const key = `${entry.method} ${entry.path}`;+ if (seen.has(key)) {+ console.warn(`[crypto-catalog] skipping ${file}: duplicate route ${key}`);+ continue;+ }+ seen.add(key);+ entries.push(entry);+ } catch (err) {+ console.warn(`[crypto-catalog] skipping ${file}: ${err?.message || err}`);+ }+ }++ // Deterministic order so the index, the OpenAPI paths, and tests are stable.+ entries.sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method));+ cache.set(dir, entries);+ return entries;+}++// Test/ops seam: drop a memoized directory so a fresh assembly re-reads disk.+export function clearCatalogCache() {+ cache.clear();+}diff --git a/api/_lib/crypto-catalog/openapi.js b/api/_lib/crypto-catalog/openapi.jsnew file mode 100644index 000000000..9370de56c--- /dev/null+++ b/api/_lib/crypto-catalog/openapi.js@@ -0,0 +1,264 @@+// @ts-check+// Build a real OpenAPI 3.1 document FROM the Crypto Data API catalog entries.+//+// The catalog (see ./index.js) is the single source of truth; this renders it+// into the spec agents and tooling (Swagger UI, openapi-generator, LangChain's+// OpenAPI toolkit, etc.) consume. Every path, parameter, and response schema+// comes from an entry's `path` / `inputSchema` / `outputSchema` — nothing is+// hand-maintained, so the spec can never drift from what `/api/crypto` lists.+//+// Input flexibility: a sibling entry may express `inputSchema` either as a+// JSON-Schema object (`{ type:'object', properties:{…}, required:[…] }`) or as+// an array of OpenAPI parameter objects. Both are handled; a param whose name+// appears in the path as `{name}` is emitted as a required path parameter, the+// rest as query parameters (the free endpoints are keyless GETs).++/**+ * @param {string} path e.g. "/api/crypto/token"+ * @returns {Set<string>} names of `{templated}` path segments+ */+function pathParamNames(path) {+ const names = new Set();+ const re = /\{([^}]+)\}/g;+ let m;+ while ((m = re.exec(path))) names.add(m[1]);+ return names;+}++/**+ * Normalize one property descriptor into an OpenAPI Schema Object.+ * @param {any} prop+ */+function toSchema(prop) {+ if (!prop || typeof prop !== 'object') return { type: 'string' };+ const { description, example, ...schema } = prop;+ if (!schema.type && !schema.oneOf && !schema.anyOf && !schema.$ref) schema.type = 'string';+ return schema;+}++/**+ * Does this object look like a bare param map — `{ name: {type, in, required,+ * description, example} }` — rather than a JSON-Schema object? Used to support+ * the terser entry style some siblings adopted (no `type:'object'`/`properties`+ * envelope, each key a parameter descriptor).+ * @param {any} obj+ */+function looksLikeParamMap(obj) {+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return false;+ if (obj.type || obj.properties || obj.$ref || obj.oneOf || obj.anyOf || obj.allOf) return false;+ const vals = Object.values(obj);+ return vals.length > 0 && vals.every((v) => v && typeof v === 'object');+}++/** Build one query/path parameter from a `{type,in,required,description,example}` descriptor. */+function paramFromDescriptor(name, desc, inPath) {+ /** @type {any} */+ const d = desc || {};+ const isPath = d.in === 'path' || inPath.has(name);+ const { in: _in, required: _req, description, example, ...rest } = d;+ return {+ name,+ in: isPath ? 'path' : d.in || 'query',+ required: isPath || d.required === true,+ ...(description ? { description } : {}),+ schema: toSchema(rest),+ ...(example !== undefined ? { example } : {}),+ };+}++/**+ * Convert an entry's input contract into an OpenAPI `parameters` array. Accepts+ * a JSON-Schema object, an OpenAPI parameter array, or a bare param map.+ * @param {any} inputSchema+ * @param {Set<string>} inPath+ * @returns {Array<object>}+ */+function toParameters(inputSchema, inPath) {+ if (!inputSchema) {+ // Still emit path params so a templated route documents its required ids.+ return [...inPath].map((name) => ({+ name,+ in: 'path',+ required: true,+ schema: { type: 'string' },+ }));+ }++ // Already an OpenAPI parameter array — pass through, defaulting `in`.+ if (Array.isArray(inputSchema)) {+ return inputSchema+ .filter((p) => p && typeof p === 'object' && typeof p.name === 'string')+ .map((p) => ({+ name: p.name,+ in: p.in || (inPath.has(p.name) ? 'path' : 'query'),+ required: p.required ?? inPath.has(p.name),+ ...(p.description ? { description: p.description } : {}),+ schema: p.schema || toSchema(p),+ ...(p.example !== undefined ? { example: p.example } : {}),+ }));+ }++ // Bare param map (no JSON-Schema envelope) → one param per key.+ let params;+ if (looksLikeParamMap(inputSchema)) {+ params = Object.entries(inputSchema).map(([name, desc]) =>+ paramFromDescriptor(name, desc, inPath),+ );+ } else {+ // JSON-Schema object → one parameter per property.+ const properties =+ inputSchema.properties && typeof inputSchema.properties === 'object'+ ? inputSchema.properties+ : {};+ const required = new Set(Array.isArray(inputSchema.required) ? inputSchema.required : []);+ params = Object.entries(properties).map(([name, prop]) => {+ const isPath = inPath.has(name);+ /** @type {any} */+ const p = prop || {};+ return {+ name,+ in: isPath ? 'path' : 'query',+ required: isPath || required.has(name),+ ...(p.description ? { description: p.description } : {}),+ schema: toSchema(p),+ ...(p.example !== undefined ? { example: p.example } : {}),+ };+ });+ }++ // A `{templated}` segment with no matching property still needs a param entry.+ for (const name of inPath) {+ if (!params.some((p) => p.name === name)) {+ params.push({ name, in: 'path', required: true, schema: { type: 'string' } });+ }+ }+ return params;+}++/**+ * Build the response schema for an entry from its `outputSchema`. Accepts a full+ * JSON-Schema object or a bare `{ field: … }` map whose values may be nested+ * schema objects OR plain-text descriptions (the terser sibling style) — the+ * latter are coerced to `{ description }` so the emitted schema stays valid.+ * @param {any} outputSchema+ */+function toResponseSchema(outputSchema) {+ if (outputSchema && typeof outputSchema === 'object' && !Array.isArray(outputSchema)) {+ if (outputSchema.type || outputSchema.properties || outputSchema.$ref) return outputSchema;+ const properties = {};+ for (const [k, v] of Object.entries(outputSchema)) {+ properties[k] =+ typeof v === 'string'+ ? { description: v }+ : v && typeof v === 'object'+ ? v+ : { description: String(v) };+ }+ return { type: 'object', properties };+ }+ // No declared schema: document a free-form JSON object rather than lie.+ return { type: 'object', additionalProperties: true };+}++/**+ * @param {Array<{slug:string,method:string,path:string,title?:string,summary?:string,inputSchema?:any,outputSchema?:any,example?:any}>} entries+ * @param {{ origin?: string, version?: string }} [opts]+ * @returns {object} OpenAPI 3.1 document+ */+export function buildOpenApiDoc(entries, { origin = 'https://three.ws', version = '1.0.0' } = {}) {+ /** @type {Record<string, any>} */+ const paths = {};++ for (const e of entries) {+ const inPath = pathParamNames(e.path);+ const parameters = toParameters(e.inputSchema, inPath);+ const responseExample =+ e.example !== undefined && e.example !== null ? { example: e.example } : {};+ // An entry may answer more than one verb (e.g. GET + POST on /symbol).+ const verbs = Array.isArray(e.methods) && e.methods.length ? e.methods : [e.method];+ for (const verb of verbs) {+ const op = {+ operationId: verbs.length > 1 ? `${e.slug}_${verb.toLowerCase()}` : e.slug,+ summary: e.title || e.slug,+ ...(e.summary ? { description: e.summary } : {}),+ tags: ['crypto'],+ parameters,+ responses: {+ 200: {+ description: e.summary || `${e.title || e.slug} response`,+ content: {+ 'application/json': {+ schema: toResponseSchema(e.outputSchema),+ ...responseExample,+ },+ },+ },+ 400: { description: 'Invalid or missing input.' },+ 429: { description: 'Rate limited — retry after the `Retry-After` header.' },+ 503: { description: 'Upstream data source temporarily unavailable.' },+ },+ };+ if (!paths[e.path]) paths[e.path] = {};+ paths[e.path][verb.toLowerCase()] = op;+ }+ }++ return {+ openapi: '3.1.0',+ info: {+ title: 'three.ws Crypto Data API',+ version,+ description:+ 'A free, keyless crypto data bundle for AI agents — token snapshots, ' ++ 'holders, security checks, bonding status, whale activity, wallet ' ++ 'portfolios, trending, and symbol availability, all from one origin. ' ++ 'No account, no API key. See https://three.ws/docs/crypto-api.',+ contact: { name: 'three.ws', url: 'https://three.ws', email: '[email protected]' },+ license: { name: 'Free to use', url: 'https://three.ws/docs/crypto-api' },+ },+ servers: [{ url: origin, description: 'three.ws production' }],+ tags: [+ {+ name: 'crypto',+ description: 'Free, keyless crypto market & on-chain data endpoints.',+ },+ ],+ paths,+ };+}++/**+ * Minimal structural assertion used by tests and by any caller that wants to+ * fail fast on a malformed doc. Returns an array of problems (empty = valid).+ * Not a full JSON-Schema validation of the OpenAPI meta-schema — it checks the+ * required top-level fields OpenAPI 3.1 mandates plus per-operation invariants.+ * @param {any} doc+ * @returns {string[]}+ */+export function validateOpenApiDoc(doc) {+ const problems = [];+ if (!doc || typeof doc !== 'object') return ['document is not an object'];+ if (doc.openapi !== '3.1.0') problems.push(`openapi must be "3.1.0", got ${doc.openapi}`);+ if (!doc.info || typeof doc.info !== 'object') problems.push('info object missing');+ else {+ if (!doc.info.title) problems.push('info.title missing');+ if (!doc.info.version) problems.push('info.version missing');+ }+ if (!doc.paths || typeof doc.paths !== 'object') problems.push('paths object missing');+ else {+ for (const [p, item] of Object.entries(doc.paths)) {+ if (!p.startsWith('/')) problems.push(`path "${p}" must start with "/"`);+ for (const [verb, op] of Object.entries(/** @type {any} */ (item))) {+ if (!HTTP_VERBS.has(verb)) continue;+ const o = /** @type {any} */ (op);+ if (!o.responses || typeof o.responses !== 'object')+ problems.push(`${verb.toUpperCase()} ${p}: responses missing`);+ if (!Array.isArray(o.parameters))+ problems.push(`${verb.toUpperCase()} ${p}: parameters must be an array`);+ }+ }+ }+ return problems;+}++const HTTP_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options']);diff --git a/api/_lib/crypto-catalog/symbol.js b/api/_lib/crypto-catalog/symbol.jsnew file mode 100644index 000000000..a36048f53--- /dev/null+++ b/api/_lib/crypto-catalog/symbol.js@@ -0,0 +1,86 @@+// Catalog entry for GET/POST /api/crypto/symbol — the free symbol-availability+// check. The /api/crypto index (prompt 10) globs every file in this directory+// and reflects it in the bundle listing + OpenAPI doc. This file stands alone:+// if the index doesn't exist yet, the endpoint still works.++export default {+ slug: 'symbol',+ method: 'GET',+ methods: ['GET', 'POST'],+ path: '/api/crypto/symbol',+ title: 'Symbol availability',+ summary:+ 'Check up to 20 candidate ticker symbols for exact and fuzzy (look-alike) ' ++ 'collisions across live token registries before launching a token. Free, ' ++ 'keyless. Feeds the paid Pump Launcher — clear the name here, mint there.',+ inputSchema: {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['symbols'],+ properties: {+ symbols: {+ type: 'array',+ items: { type: 'string', minLength: 1, maxLength: 32 },+ minItems: 1,+ maxItems: 20,+ description: 'Candidate tickers. GET accepts a comma-separated ?symbols=A,B,C.',+ },+ chain: {+ type: 'string',+ description: 'Optional chain filter (e.g. "solana"). Omit to check every indexed chain.',+ },+ },+ },+ outputSchema: {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['results', 'availableCount', 'takenCount', 'ts'],+ properties: {+ results: {+ type: 'array',+ items: {+ type: 'object',+ required: ['symbol', 'available', 'exactCollisions', 'fuzzyCollisions'],+ properties: {+ symbol: { type: 'string' },+ available: { type: ['boolean', 'null'], description: 'null when the source could not be reached' },+ exactCollisions: { type: 'array', items: { type: 'object' } },+ fuzzyCollisions: { type: 'array', items: { type: 'object' } },+ note: { type: 'string' },+ },+ },+ },+ availableCount: { type: 'number' },+ takenCount: { type: 'number' },+ degraded: { type: 'boolean' },+ chain: { type: ['string', 'null'] },+ ts: { type: 'string', format: 'date-time' },+ },+ },+ example: {+ request: 'GET /api/crypto/symbol?symbols=THREE,MOONZ,BLERGZ&chain=solana',+ response: {+ results: [+ {+ symbol: 'THREE',+ available: false,+ exactCollisions: [+ {+ symbol: 'three',+ name: 'three.ws',+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ chain: 'solana',+ },+ ],+ fuzzyCollisions: [],+ },+ { symbol: 'MOONZ', available: true, exactCollisions: [], fuzzyCollisions: [] },+ { symbol: 'BLERGZ', available: true, exactCollisions: [], fuzzyCollisions: [] },+ ],+ availableCount: 2,+ takenCount: 1,+ chain: 'solana',+ ts: '2026-07-07T00:00:00.000Z',+ },+ },+};diff --git a/api/_lib/crypto-catalog/wallet.js b/api/_lib/crypto-catalog/wallet.jsnew file mode 100644index 000000000..5c60b519d--- /dev/null+++ b/api/_lib/crypto-catalog/wallet.js@@ -0,0 +1,65 @@+// Catalog entry for GET /api/crypto/wallet — the free wallet-portfolio endpoint.+//+// The /api/crypto index (prompt 10) globs every file in this directory and merges+// the entries into the bundle's discovery doc + OpenAPI. Each entry is a plain,+// serializable descriptor: no imports, no side effects, safe to load anywhere.++export default {+ slug: 'wallet',+ method: 'GET',+ path: '/api/crypto/wallet',+ title: 'Wallet Portfolio',+ summary:+ 'Native balance, every SPL/token holding, and a rough USD valuation for any wallet — keyless. For treasury, copy-trade, and pre-trade counterparty checks.',+ inputSchema: {+ type: 'object',+ required: ['address'],+ properties: {+ address: {+ type: 'string',+ description: 'Wallet address to inspect (Solana base58 or EVM 0x).',+ },+ chain: {+ type: 'string',+ enum: ['solana', 'ethereum'],+ default: 'solana',+ description: 'Chain to read. Solana is keyless; Ethereum needs a provider key.',+ },+ },+ },+ outputSchema: {+ type: 'object',+ properties: {+ address: { type: 'string' },+ chain: { type: 'string' },+ native: {+ type: 'object',+ properties: {+ symbol: { type: 'string' },+ amount: { type: 'number' },+ usd: { type: ['number', 'null'] },+ },+ },+ tokens: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ mint: { type: 'string' },+ symbol: { type: ['string', 'null'] },+ name: { type: ['string', 'null'] },+ amount: { type: 'number' },+ usd: { type: ['number', 'null'] },+ logo: { type: ['string', 'null'] },+ },+ },+ },+ totalUsd: { type: 'number' },+ tokenCount: { type: 'integer' },+ truncated: { type: 'boolean' },+ ts: { type: 'string', format: 'date-time' },+ sources: { type: 'array', items: { type: 'string' } },+ },+ },+ example: '/api/crypto/wallet?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&chain=solana',+};diff --git a/api/_lib/crypto-catalog/whales.js b/api/_lib/crypto-catalog/whales.jsnew file mode 100644index 000000000..17fed3da8--- /dev/null+++ b/api/_lib/crypto-catalog/whales.js@@ -0,0 +1,86 @@+// Crypto Data API catalog entry — whale / large-buy activity.+// Globbed by api/_lib/crypto-catalog/index.js (prompt 10) into the /api/crypto+// front-door index + OpenAPI doc. Stands alone if that index doesn't exist yet.++export default {+ slug: 'whales',+ method: 'GET',+ path: '/api/crypto/whales',+ title: 'Whale / Large-Buy Activity',+ summary:+ 'Free read of large buys on pump.fun. Pass ?mint= for whale buys of a specific ' ++ 'token, or omit it for the top whale wallets active across the market. Returns a ' ++ 'deterministic bullish/bearish/neutral buy-pressure signal so an agent can tell ' ++ 'whether big money is moving in before it commits.',+ free: true,+ keyless: true,+ inputSchema: {+ type: 'object',+ properties: {+ mint: {+ type: 'string',+ description:+ 'Optional base58 Solana mint. Present → whale buys of that token; ' ++ 'omitted → top whale wallets active across pump.fun.',+ },+ minSol: {+ type: 'number',+ minimum: 0.1,+ default: 5,+ description: 'Minimum SOL in a single buy to qualify as a whale.',+ },+ limit: {+ type: 'integer',+ minimum: 1,+ maximum: 25,+ default: 10,+ description: 'Rows to return.',+ },+ },+ },+ outputSchema: {+ type: 'object',+ required: ['scope', 'whales', 'whaleCount', 'totalSolMoved', 'signal', 'ts', 'source'],+ properties: {+ scope: { type: 'string', enum: ['token', 'market'] },+ mint: { type: ['string', 'null'] },+ minSol: { type: 'number' },+ whales: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ wallet: { type: 'string' },+ solMoved: { type: 'number' },+ txHash: { type: ['string', 'null'] },+ ts: { type: ['string', 'null'], format: 'date-time' },+ },+ },+ },+ whaleCount: { type: 'integer', minimum: 0 },+ totalSolMoved: { type: 'number', minimum: 0 },+ signal: { type: 'string', enum: ['bullish', 'bearish', 'neutral'] },+ ts: { type: 'string', format: 'date-time' },+ source: { type: 'string' },+ note: { type: 'string' },+ },+ },+ example: {+ scope: 'token',+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ minSol: 5,+ whales: [+ {+ wallet: 'AbcDEF12345GHJKLMNopqrstuvwxyZabcdefghijk1',+ solMoved: 12.4,+ txHash: '5xTr4nSacT1oNsigNaTuReExampLe1111111111111111111111111111111111',+ ts: '2026-07-07T00:00:00.000Z',+ },+ ],+ whaleCount: 1,+ totalSolMoved: 12.4,+ signal: 'bullish',+ ts: '2026-07-07T00:00:00.000Z',+ source: 'pump.fun',+ },+};diff --git a/api/_lib/oracle/market.js b/api/_lib/oracle/market.jsindex 41f49546e..ca462552b 100644--- a/api/_lib/oracle/market.js+++ b/api/_lib/oracle/market.js@@ -25,6 +25,7 @@// coin page poll almost never fans out to six upstreams.import { cacheGet, cacheSet } from '../cache.js';+import { bondingProgressPct } from '../pump-bonding.js';const DEXSCREENER = 'https://api.dexscreener.com/latest/dex/tokens';const PUMP_V3 = 'https://frontend-api-v3.pump.fun';@@ -36,12 +37,6 @@ const COINGECKO = 'https://api.coingecko.com/api/v3';const FETCH_TIMEOUT_MS = 6000;const WSOL = 'So11111111111111111111111111111111111111112';-// pump.fun mints a fixed 1B supply (6 decimals). Of that, 793.1M tokens sit in-// the bonding curve at launch and the coin graduates once ~206.9M have been-// bought out of the curve. Used to derive graduation progress when neither-// pump.fun's `complete` flag nor GeckoTerminal's graduation % is available.-const PUMP_CURVE_INITIAL_REAL_TOKENS = 793_100_000 * 1e6;-const L1 = new Map(); // key -> { value, expires }const L1_TTL_MS = 20_000;const L2_TTL_S = 45;@@ -126,13 +121,9 @@ async function fromPumpFun(mint) {const d = await fetchJson(`${PUMP_V3}/coins-v2/${mint}`, { headers: { accept: 'application/json' } });if (!d || !d.mint) return null;const complete = Boolean(d.complete);- const realTokenReserves = num(d.real_token_reserves);// Graduation progress: 100 once complete; otherwise the share of the curve's- // initial token float that's been bought out.- let bondingPct = complete ? 100 : null;- if (bondingPct == null && realTokenReserves != null && realTokenReserves >= 0) {- bondingPct = clampPct((1 - realTokenReserves / PUMP_CURVE_INITIAL_REAL_TOKENS) * 100);- }+ // initial token float that's been bought out (shared curve math — pump-bonding.js).+ const bondingPct = complete ? 100 : bondingProgressPct(d.real_token_reserves);return {sources: ['pumpfun'],identity: {diff --git a/api/_lib/pump-bonding.js b/api/_lib/pump-bonding.jsnew file mode 100644index 000000000..2b5eba30e--- /dev/null+++ b/api/_lib/pump-bonding.js@@ -0,0 +1,197 @@+// Bonding-curve / graduation status for a single pump.fun token.+//+// One question an agent holding or watching a pump.fun coin needs mid-task:+// where is it on the bonding curve — how close to graduation, how much SOL is in+// the curve, and has it already migrated to an AMM (Raydium / PumpSwap)? Timing+// entries and exits around graduation is a core meme-trading move.+//+// This wraps the same public pump.fun frontend feed the rest of the codebase+// uses (PUMP_FRONTEND_BASE — see pump-launch-feed.js / oracle/market.js) and the+// SAME curve math already proven in oracle/market.js. It does NOT reimplement the+// curve: `bondingProgressPct` + `PUMP_CURVE_INITIAL_REAL_TOKENS` are the shared+// source of truth that oracle/market.js now imports from here too, so the free+// /api/crypto/bonding endpoint and the Oracle coin page can never drift.+//+// The pure mapping (`mapBondingStatus`) is separated from the network fetch+// (`fetchPumpCoin`) so the curve math is unit-testable with synthetic fixtures,+// no chain required.++import { isGraduated } from './pump-launch-feed.js';++export const PUMP_FRONTEND_BASE =+ process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';++const FETCH_TIMEOUT_MS = 6_000;+const UA = 'three.ws-crypto-api/1';++// pump.fun mints a fixed 1B supply (6 decimals). Of that, 793.1M tokens sit in+// the bonding curve at launch; the coin graduates once the curve's float has been+// bought out. `real_token_reserves` starts at this value and decreases toward the+// graduation floor, so `1 - real/initial` is the share of the curve completed.+export const PUMP_CURVE_INITIAL_REAL_TOKENS = 793_100_000 * 1e6;++const num = (v) => {+ if (v == null) return null;+ const n = typeof v === 'string' ? parseFloat(v) : Number(v);+ return Number.isFinite(n) ? n : null;+};++const clampPct = (n) => (n == null ? null : Math.max(0, Math.min(100, n)));++/**+ * Bonding-curve progress (0–100) from the curve's live real token reserves+ * (atomic, 6-dec units). 0 at launch, 100 when the curve's float is fully bought+ * out. Returns null when reserves are unknown.+ *+ * @param {number|string|null|undefined} realTokenReservesAtomic+ * @returns {number|null}+ */+export function bondingProgressPct(realTokenReservesAtomic) {+ const real = num(realTokenReservesAtomic);+ if (real == null || real < 0) return null;+ return clampPct((1 - real / PUMP_CURVE_INITIAL_REAL_TOKENS) * 100);+}++// USD market cap: prefer pump.fun's own `usd_market_cap`; else derive from the+// SOL-denominated cap and a SOL price when one is supplied.+function pickMarketCapUsd(coin, solPriceUsd) {+ const usd = num(coin?.usd_market_cap);+ if (usd != null) return usd;+ const sol = num(coin?.market_cap);+ if (sol != null && solPriceUsd > 0) return sol * solPriceUsd;+ return null;+}++/**+ * Is this coin object a genuine pump.fun *bonding-curve launch* (as opposed to an+ * external token pump.fun merely indexes)? pump.fun's frontend returns records for+ * well-known non-pump mints too — WSOL, USDC, cross-chain tokens — flagged+ * `indexed_by_pump`; those never had a bonding curve here and must be rejected as+ * "not a pump.fun mint". A native launch carries a bonding-curve account (the field+ * persists post-graduation) or live curve reserves; the `pump` mint suffix is a+ * last-resort corroborator.+ *+ * @param {object} coin+ * @returns {boolean}+ */+export function isPumpLaunch(coin) {+ if (!coin || !coin.mint) return false;+ if (coin.indexed_by_pump) return false;+ return (+ Boolean(coin.bonding_curve || coin.associated_bonding_curve) ||+ coin.real_token_reserves != null ||+ coin.virtual_token_reserves != null ||+ /pump$/i.test(coin.mint)+ );+}++// Which venue a graduated coin migrated to. pump.fun exposes `raydium_pool` for+// coins that graduated to Raydium and `pump_swap_pool` for the PumpSwap AMM+// (pump.fun's current default graduation venue). A `complete` coin with neither+// field surfaced still left the curve for PumpSwap — the default today — so we+// report that rather than null, which is what a trader needs to know.+function migrationVenue(coin) {+ if (coin?.raydium_pool) return 'raydium';+ if (coin?.pump_swap_pool) return 'pumpswap';+ return 'pumpswap';+}++/**+ * Map a raw pump.fun coin object → the bonding-curve status shape. Pure; no+ * network. On-curve coins carry live `solInCurve` / `tokensRemaining` / progress;+ * graduated coins report `graduated:true` + `migratedTo` with the curve fields+ * nulled (final) and progress pinned to 100.+ *+ * @param {object} coin Raw pump.fun frontend coin object.+ * @param {{ solPriceUsd?: number }} [opts]+ */+export function mapBondingStatus(coin, { solPriceUsd = 0 } = {}) {+ const graduated = isGraduated(coin);+ const marketCapUsd = pickMarketCapUsd(coin, solPriceUsd);++ if (graduated) {+ return {+ onCurve: false,+ graduated: true,+ migratedTo: migrationVenue(coin),+ bondingProgressPct: 100,+ solInCurve: null,+ tokensRemaining: null,+ marketCapUsd,+ source: 'pumpfun',+ };+ }++ const realTokenReserves = num(coin?.real_token_reserves);+ const realSolReserves = num(coin?.real_sol_reserves);+ return {+ onCurve: true,+ graduated: false,+ migratedTo: null,+ bondingProgressPct: bondingProgressPct(realTokenReserves),+ solInCurve: realSolReserves != null ? realSolReserves / 1e9 : null,+ tokensRemaining: realTokenReserves != null ? realTokenReserves / 1e6 : null,+ marketCapUsd,+ source: 'pumpfun',+ };+}++async function fetchOnce(url) {+ const ctrl = new AbortController();+ const tid = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);+ try {+ const r = await fetch(url, {+ signal: ctrl.signal,+ headers: { accept: 'application/json', 'user-agent': UA },+ });+ // 404 = this mint isn't a pump.fun-indexed coin; a hard distinction from a+ // transient upstream fault (5xx / network / timeout) so the caller can answer+ // 400 vs 503 correctly.+ if (r.status === 404) return { kind: 'not_found' };+ if (!r.ok) return { kind: 'upstream_down' };+ const j = await r.json().catch(() => null);+ // A returned record that isn't a native bonding-curve launch (an externally+ // indexed token) is "not a pump.fun mint", not a data-source fault.+ if (j && j.mint && isPumpLaunch(j)) return { kind: 'ok', coin: j };+ return { kind: 'not_found' };+ } catch {+ return { kind: 'upstream_down' };+ } finally {+ clearTimeout(tid);+ }+}++/**+ * Fetch a pump.fun coin object by mint. Tries the richer `coins-v2/<mint>` route+ * (carries the AMM pool fields) then falls back to `coins/<mint>`. Distinguishes+ * "not a pump.fun mint" (both routes 404 / empty) from "upstream temporarily+ * down" (network / timeout / 5xx) so the endpoint never turns a data-source blip+ * into a 400 or a 500.+ *+ * @param {string} mint+ * @returns {Promise<{ kind: 'ok', coin: object } | { kind: 'not_found' } | { kind: 'upstream_down' }>}+ */+export async function fetchPumpCoin(mint) {+ let sawUpstreamDown = false;+ for (const path of [`coins-v2/${encodeURIComponent(mint)}`, `coins/${encodeURIComponent(mint)}`]) {+ const r = await fetchOnce(`${PUMP_FRONTEND_BASE}/${path}`);+ if (r.kind === 'ok') return r;+ if (r.kind === 'upstream_down') sawUpstreamDown = true;+ // not_found → try the next route before concluding it's not a pump mint.+ }+ return { kind: sawUpstreamDown ? 'upstream_down' : 'not_found' };+}++/**+ * Resolve the full bonding-curve status for a mint: fetch + map.+ *+ * @param {string} mint+ * @returns {Promise<{ kind: 'ok', status: object, coin: object } | { kind: 'not_found' } | { kind: 'upstream_down' }>}+ */+export async function getBondingStatus(mint) {+ const res = await fetchPumpCoin(mint);+ if (res.kind !== 'ok') return res;+ // pump.fun's coin object already carries `usd_market_cap`, so no extra SOL-price+ // fetch is needed on the hot path; pass 0 and let mapBondingStatus prefer it.+ return { kind: 'ok', status: mapBondingStatus(res.coin, { solPriceUsd: 0 }), coin: res.coin };+}diff --git a/api/_lib/pump-whale-scan.js b/api/_lib/pump-whale-scan.jsnew file mode 100644index 000000000..dd57740c0--- /dev/null+++ b/api/_lib/pump-whale-scan.js@@ -0,0 +1,230 @@+// Whale / large-buy scanning over the public pump.fun feeds.+//+// Powers the FREE GET /api/crypto/whales endpoint. A "whale buy" is a single+// pump.fun trade of type=buy that moves at least `minSol` SOL. Two scopes:+//+// · token — whale BUYS of one specific mint (per-transaction rows).+// · market — the top whale WALLETS active across pump.fun right now, each row+// aggregating that wallet's qualifying buys (solMoved = sum, txHash+// + ts = its largest single qualifying buy).+//+// The buy/sell/neutral SIGNAL is a deterministic buy-pressure rule (documented+// in computeSignal + docs/crypto-api.md) — never an LLM. All fetches degrade to+// an empty result on upstream failure so the endpoint answers 200, never 500.+//+// Data source: pump.fun public swap-api (trades) + frontend-api-v3 (top coins).+// Both are keyless. Reuses the same hosts + trade shape as the paid+// api/x402/pump-agent-audit.js whale oracle, exposed here free and cleaner.++const PUMP_FRONTEND_BASE =+ process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';+const PUMP_SWAP_BASE = process.env.PUMP_SWAP_BASE || 'https://swap-api.pump.fun';++export const WHALE_MIN_SOL_DEFAULT = Number(process.env.PUMP_WHALE_SOL_THRESHOLD || 5);+export const WHALE_LIMIT_DEFAULT = 10;+export const WHALE_LIMIT_MAX = 25;++// How many top-market-cap coins to sample trades from in market scope. Kept+// small so one call stays within the pump.fun rate budget and our function+// timeout; each coin fetch runs concurrently.+const MARKET_COINS_SAMPLE = 8;+// Trades pulled per coin per sweep (pump swap-api caps this; 100 is plenty to+// surface recent whales without deep pagination).+const TRADES_PER_COIN = 100;++const SOURCE = 'pump.fun';++function parseNum(v) {+ const n = typeof v === 'string' ? parseFloat(v) : Number(v);+ return Number.isFinite(n) ? n : null;+}++// pump trade timestamps arrive as unix-seconds (or ms) numbers, or ISO strings.+// Normalize to an ISO string; null when unresolvable.+function normalizeTs(v) {+ if (v == null) return null;+ if (typeof v === 'string') {+ const t = Date.parse(v);+ return Number.isFinite(t) ? new Date(t).toISOString() : null;+ }+ const n = Number(v);+ if (!Number.isFinite(n) || n <= 0) return null;+ // < 1e12 → seconds, else milliseconds.+ const ms = n < 1e12 ? n * 1000 : n;+ return new Date(ms).toISOString();+}++// Pull a single normalized trade into { side, sol, wallet, txHash, ts }, or null+// if it can't be understood. Defensive against pump's field-name drift.+export function normalizeTrade(t) {+ if (!t || typeof t !== 'object') return null;+ const side = String(t.type ?? t.txType ?? t.side ?? '').toLowerCase();+ if (side !== 'buy' && side !== 'sell') return null;+ const sol = parseNum(t.amountSol ?? t.sol_amount ?? t.solAmount ?? t.amount_sol);+ if (sol == null || sol <= 0) return null;+ const wallet = t.userAddress ?? t.user ?? t.wallet ?? t.trader ?? null;+ if (!wallet) return null;+ const txHash = t.signature ?? t.txHash ?? t.tx ?? t.transaction ?? null;+ const ts = normalizeTs(t.timestamp ?? t.createdAt ?? t.created_at ?? t.ts);+ return { side, sol, wallet: String(wallet), txHash: txHash ? String(txHash) : null, ts };+}++// ── Deterministic buy-pressure signal ─────────────────────────────────────────+// Whales only ever appear here on qualifying trades, so the signal reads NET+// whale flow: SOL bought by whales minus SOL sold by whales, both over the+// `minSol` threshold. A net move of at least one whale-sized position decides+// direction; anything smaller (or no whale activity at all) is neutral.+//+// netFlow = whaleBuySol − whaleSellSol+// · no qualifying whale trades at all → neutral+// · netFlow ≥ +minSol (net accumulation) → bullish+// · netFlow ≤ −minSol (net distribution) → bearish+// · otherwise (balanced) → neutral+//+// Scales with the caller's minSol, so the rule means the same thing at any+// threshold. Pure + total-ordering deterministic — no randomness, no clock.+export function computeSignal({ whaleBuySol, whaleSellSol, buyCount, sellCount }, minSol) {+ const buys = Number(whaleBuySol) || 0;+ const sells = Number(whaleSellSol) || 0;+ if ((buyCount || 0) === 0 && (sellCount || 0) === 0) return 'neutral';+ const netFlow = buys - sells;+ if (netFlow >= minSol) return 'bullish';+ if (netFlow <= -minSol) return 'bearish';+ return 'neutral';+}++function round(n) {+ return Math.round((Number(n) || 0) * 1000) / 1000;+}++// ── Aggregation (pure — unit-tested directly) ────────────────────────────────+// From a flat list of normalized trades, split whale buys/sells over `minSol`+// and shape the endpoint response body for the given scope.+export function buildWhaleResult({ trades, scope, mint, minSol, limit }) {+ const norm = trades.map(normalizeTrade).filter(Boolean);++ const whaleBuys = norm.filter((t) => t.side === 'buy' && t.sol >= minSol);+ const whaleSells = norm.filter((t) => t.side === 'sell' && t.sol >= minSol);++ const whaleBuySol = whaleBuys.reduce((s, t) => s + t.sol, 0);+ const whaleSellSol = whaleSells.reduce((s, t) => s + t.sol, 0);++ let whales;+ if (scope === 'token') {+ // Per-buy rows, largest first.+ whales = whaleBuys+ .slice()+ .sort((a, b) => b.sol - a.sol)+ .slice(0, limit)+ .map((t) => ({ wallet: t.wallet, solMoved: round(t.sol), txHash: t.txHash, ts: t.ts }));+ } else {+ // Market scope: aggregate qualifying buys per wallet. Row solMoved = total+ // SOL that wallet moved; txHash/ts = its single largest qualifying buy.+ const byWallet = new Map();+ for (const t of whaleBuys) {+ const cur =+ byWallet.get(t.wallet) || { wallet: t.wallet, solMoved: 0, top: t };+ cur.solMoved += t.sol;+ if (t.sol > cur.top.sol) cur.top = t;+ byWallet.set(t.wallet, cur);+ }+ whales = Array.from(byWallet.values())+ .sort((a, b) => b.solMoved - a.solMoved)+ .slice(0, limit)+ .map((w) => ({+ wallet: w.wallet,+ solMoved: round(w.solMoved),+ txHash: w.top.txHash,+ ts: w.top.ts,+ }));+ }++ // whaleCount reflects the distinct whale entities in `whales` semantics:+ // per-buy count for token scope, distinct whale wallets for market scope.+ const whaleCount =+ scope === 'token'+ ? whaleBuys.length+ : new Set(whaleBuys.map((t) => t.wallet)).size;++ const signal = computeSignal(+ {+ whaleBuySol,+ whaleSellSol,+ buyCount: whaleBuys.length,+ sellCount: whaleSells.length,+ },+ minSol,+ );++ return {+ scope,+ mint: scope === 'token' ? mint : null,+ whales,+ whaleCount,+ totalSolMoved: round(whaleBuySol),+ signal,+ ts: new Date().toISOString(),+ source: SOURCE,+ };+}++// ── Upstream fetches (network boundary — always degrade, never throw) ─────────+async function fetchJson(url, timeoutMs) {+ try {+ const r = await fetch(url, {+ headers: { accept: 'application/json', 'user-agent': 'three.ws-crypto-whales/1' },+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!r.ok) return null;+ return await r.json().catch(() => null);+ } catch {+ return null;+ }+}++export async function fetchCoinTrades(mint, limit = TRADES_PER_COIN) {+ const body = await fetchJson(+ `${PUMP_SWAP_BASE}/v2/coins/${encodeURIComponent(mint)}/trades?limit=${limit}`,+ 6000,+ );+ if (Array.isArray(body)) return body;+ if (Array.isArray(body?.trades)) return body.trades;+ return [];+}++export async function fetchTopCoins(limit = 20) {+ const body = await fetchJson(+ `${PUMP_FRONTEND_BASE}/coins?offset=0&limit=${limit}&sort=market_cap&order=DESC&includeNsfw=false`,+ 7000,+ );+ const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : [];+ return coins.filter((c) => c && typeof c.mint === 'string' && c.mint.length >= 32);+}++// Token scope — whale buys of one specific mint. Upstream down → empty result.+export async function scanTokenWhales({ mint, minSol, limit }) {+ const trades = await fetchCoinTrades(mint, TRADES_PER_COIN);+ return {+ ...buildWhaleResult({ trades, scope: 'token', mint, minSol, limit }),+ degraded: trades.length === 0,+ };+}++// Market scope — top whale wallets across the top pump.fun coins right now.+// Upstream down → empty result (never throws).+export async function scanMarketWhales({ minSol, limit }) {+ const topCoins = await fetchTopCoins(20);+ if (!topCoins.length) {+ return {+ ...buildWhaleResult({ trades: [], scope: 'market', mint: null, minSol, limit }),+ degraded: true,+ };+ }+ const sample = topCoins.slice(0, MARKET_COINS_SAMPLE);+ const results = await Promise.allSettled(sample.map((c) => fetchCoinTrades(c.mint, TRADES_PER_COIN)));+ const trades = results.flatMap((r) => (r.status === 'fulfilled' ? r.value : []));+ return {+ ...buildWhaleResult({ trades, scope: 'market', mint: null, minSol, limit }),+ degraded: trades.length === 0,+ };+}diff --git a/api/_lib/token-market.js b/api/_lib/token-market.jsindex 7cd49b118..80bdcb17c 100644--- a/api/_lib/token-market.js+++ b/api/_lib/token-market.js@@ -76,6 +76,12 @@ export async function fetchTokenMarket(ca, opts = {}) {const info = p.info || {};const txns = p.txns || {};+ // Human label for the deepest pair (base/quote), plus its on-chain pair+ // address — the security reader (/api/v1/token/security) surfaces both as the+ // "largest_pair" fact; other callers ignore them.+ const pairLabel =+ base.symbol && quote.symbol ? `${base.symbol}/${quote.symbol}` : null;+return {mint: tok.address || ca,symbol: tok.symbol || null,@@ -84,6 +90,8 @@ export async function fetchTokenMarket(ca, opts = {}) {chain: p.chainId || null,dex: p.dexId || null,pair_url: p.url || null,+ pair_address: p.pairAddress || null,+ pair_label: pairLabel,price_usd: num(p.priceUsd),change_24h: p.priceChange?.h24 ?? null,market_cap_usd: num(p.marketCap) ?? num(p.fdv),diff --git a/api/_lib/trust/subject-reputation.js b/api/_lib/trust/subject-reputation.jsnew file mode 100644index 000000000..6b0e4e629--- /dev/null+++ b/api/_lib/trust/subject-reputation.js@@ -0,0 +1,744 @@+// Cross-chain Subject Reputation — a pre-transaction trust primitive for ANY+// counterparty, not just three.ws agents.+//+// The question this answers is the one every autonomous agent has right before it+// pays, trades, or delegates: "should I trust the thing on the other side?" That+// counterparty ("subject") might be minted anywhere — a Solana wallet, an EVM+// wallet, a pump.fun coin, an ERC-8004 on-chain agent, or a three.ws agent. This+// module auto-detects which, reads the REAL on-chain evidence available for that+// identifier, and collapses it into one deterministic 0–100 trust score with the+// evidence and caveats attached, so the buyer can decide.+//+// Two layers, cleanly split so the score is unit-testable without any network:+// • detectSubject() + scoreSignals() — pure, deterministic, no I/O.+// • loadSubjectReputation() — the live reads (Solana RPC, EVM RPC,+// the ERC-8004 reputation registry, DexScreener, and the three.ws on-chain+// index) that gather the signals, each read soft so a dead source degrades to+// a caveat instead of failing the whole call.+//+// Score rule (documented in docs/trust-primitives.md and mirrored here): six+// weighted trust dimensions, each normalized to 0..1, averaged over ONLY the+// dimensions readable for this subject, scaled to 0–100. No readable dimension →+// score:null, tier:'unknown' — never a fabricated number.++import { isUuid, isValidSolanaAddress, isValidEvmAddress } from '../validate.js';+import { CHAIN_BY_ID } from '../erc8004-chains.js';++// The canonical wrapped-SOL mint — used only to price a wallet's native SOL+// balance into USD for the holdings dimension.+const SOL_MINT = 'So11111111111111111111111111111111111111112';+const DEFAULT_EVM_CHAIN = 8453; // Base — where ERC-8004 sees the most agent activity.++export const SUBJECT_TYPES = [+ 'threews_agent',+ 'solana_wallet',+ 'solana_mint',+ 'evm_wallet',+ 'erc8004_agent',+ 'unknown',+];++// ── Detection (pure) ─────────────────────────────────────────────────────────++/**+ * Classify an arbitrary identifier into a subject type without any I/O. Solana+ * base58 strings can be either a wallet or a mint — the format alone can't tell,+ * so they resolve to the coarse family 'solana' here and loadSubjectReputation()+ * refines them to 'solana_wallet' / 'solana_mint' using the on-chain index.+ *+ * @param {string} raw the identifier to classify+ * @param {object} [opts]+ * @param {number|string} [opts.chain] chain id for bare EVM/ERC-8004 subjects+ * @returns {{ subjectType:string, subject:string, chainId?:number, agentId?:string, reason?:string }}+ */+export function detectSubject(raw, opts = {}) {+ const id = String(raw ?? '').trim();+ if (!id) return { subjectType: 'unknown', subject: '', reason: 'empty identifier' };++ // three.ws agent_id (UUID) — the platform's own agents.+ if (isUuid(id)) return { subjectType: 'threews_agent', subject: id.toLowerCase() };++ // ERC-8004 agent id in CAIP-flavoured form: erc8004:<chainId>:<agentId> or+ // eip155:<chainId>:<numericAgentId>. The last segment is numeric (a token id),+ // which is what distinguishes it from a CAIP-10 account (…:0x-address).+ const prefixed = id.match(/^(?:erc8004|eip155):(\d+):(\d+)$/i);+ if (prefixed) {+ const chainId = Number(prefixed[1]);+ return { subjectType: 'erc8004_agent', subject: `erc8004:${chainId}:${prefixed[2]}`, chainId, agentId: prefixed[2] };+ }++ // EVM wallet / contract address.+ if (isValidEvmAddress(id)) {+ const chainId = normChain(opts.chain) ?? DEFAULT_EVM_CHAIN;+ return { subjectType: 'evm_wallet', subject: id.toLowerCase(), chainId };+ }++ // A bare integer is an ERC-8004 agent id whose chain wasn't spelled out — take+ // it from ?chain= (default Base). Capped at 18 digits so a 32+ char all-numeric+ // string still falls through to the Solana branch below.+ if (/^\d{1,18}$/.test(id)) {+ const chainId = normChain(opts.chain) ?? DEFAULT_EVM_CHAIN;+ return { subjectType: 'erc8004_agent', subject: `erc8004:${chainId}:${id}`, chainId, agentId: id };+ }++ // Solana base58 — wallet or mint, refined by the loader.+ if (isValidSolanaAddress(id)) return { subjectType: 'solana', subject: id };++ return { subjectType: 'unknown', subject: id, reason: 'unrecognized identifier format' };+}++function normChain(c) {+ if (c == null || c === '') return null;+ const n = Number(c);+ return Number.isInteger(n) && n > 0 ? n : null;+}++// ── Scoring (pure, deterministic) ────────────────────────────────────────────++// Six trust dimensions. Each has a weight (its share of the 100-point scale when+// present) and a saturation cap (the value at which its normalized sub-score+// reaches 1.0). A subject is scored only over the dimensions that could actually+// be read for it — see scoreSignals().+export const DIMENSIONS = [+ { key: 'activity', weight: 25, cap: 200, label: 'on-chain activity (tx / payments)' },+ { key: 'age', weight: 15, cap: 365, label: 'account age (days)' },+ { key: 'counterparties', weight: 15, cap: 25, label: 'distinct counterparties' },+ { key: 'holdings', weight: 10, cap: 1000, label: 'holdings (USD)' },+ { key: 'reliability', weight: 15, label: 'settlement reliability' },+ { key: 'attestations', weight: 20, cap: 10, label: 'signed attestations / feedback' },+];+const DIM = Object.fromEntries(DIMENSIONS.map((d) => [d.key, d]));++// A banned/denylisted subject is capped here regardless of any positive signal —+// a known-bad counterparty is never "medium trust" because it has volume.+const BANNED_SCORE_CAP = 10;++const clamp01 = (n) => Math.min(1, Math.max(0, Number(n) || 0));+const isNum = (n) => typeof n === 'number' && Number.isFinite(n);+const numOrNull = (n) => (isNum(n) ? n : null);+const round2 = (n) => Math.round(n * 100) / 100;++/**+ * Collapse a signal bundle into a deterministic 0–100 trust score. Pure: the same+ * signals always yield the same score, so it is safe to unit-test and to compare+ * across time. Dimensions whose signal is absent (null/undefined) are dropped from+ * BOTH the numerator and denominator, so a subject with only two readable+ * dimensions is scored fairly against its own evidence rather than penalised for+ * chains we couldn't read.+ *+ * @param {object} sig+ * @param {number|null} [sig.activity] tx / confirmed-payment count+ * @param {number|null} [sig.ageDays] account/first-activity age in days+ * @param {number|null} [sig.counterparties] distinct payers / tippers / peers+ * @param {number|null} [sig.holdingsUsd] USD value held on-chain+ * @param {number|null} [sig.failureRate] 0..1 settlement failure rate+ * @param {number|null} [sig.attestationCount] signed attestations / feedback count+ * @param {number|null} [sig.attestationAvg] ERC-8004 average feedback [-100,100]+ * @param {boolean} [sig.banned] hard denylist hit+ * @returns {{ score:number|null, tier:string, dimensions:object, weight_considered:number }}+ */+export function scoreSignals(sig = {}) {+ const dimensions = {};+ let sumW = 0;+ let sumWN = 0;++ const add = (key, available, norm, extra = {}) => {+ const d = DIM[key];+ const n = available ? clamp01(norm) : 0;+ if (available) {+ sumW += d.weight;+ sumWN += d.weight * n;+ }+ dimensions[key] = {+ available,+ weight: d.weight,+ norm: available ? round2(n) : null,+ points: available ? Math.round(d.weight * n) : 0,+ ...extra,+ };+ };++ add('activity', isNum(sig.activity), (sig.activity || 0) / DIM.activity.cap, { value: numOrNull(sig.activity) });+ add('age', isNum(sig.ageDays), (sig.ageDays || 0) / DIM.age.cap, { days: numOrNull(sig.ageDays) });+ add('counterparties', isNum(sig.counterparties), (sig.counterparties || 0) / DIM.counterparties.cap, {+ value: numOrNull(sig.counterparties),+ });+ add('holdings', isNum(sig.holdingsUsd), (sig.holdingsUsd || 0) / DIM.holdings.cap, { usd: numOrNull(sig.holdingsUsd) });+ add('reliability', isNum(sig.failureRate), 1 - (sig.failureRate || 0), { failure_rate: numOrNull(sig.failureRate) });++ // Attestations: count saturates at 10; ERC-8004 feedback average (when present)+ // scales the contribution down for net-negative feedback, never up.+ const attAvail = isNum(sig.attestationCount);+ const qual = isNum(sig.attestationAvg)+ ? sig.attestationAvg >= 0+ ? 1+ : Math.max(0, (100 + sig.attestationAvg) / 100)+ : 1;+ add('attestations', attAvail, (Math.min(sig.attestationCount || 0, DIM.attestations.cap) / DIM.attestations.cap) * qual, {+ count: numOrNull(sig.attestationCount),+ avg_feedback: numOrNull(sig.attestationAvg),+ });++ let score = sumW > 0 ? Math.round((100 * sumWN) / sumW) : null;+ if (score != null && sig.banned) score = Math.min(score, BANNED_SCORE_CAP);++ return { score, tier: tierForScore(score), dimensions, weight_considered: sumW };+}++/**+ * Map a score to a coarse trust tier. Documented thresholds so callers can gate+ * on the tier without re-deriving the bands.+ * null → unknown · <30 → low · 30–59 → medium · 60–84 → high · ≥85 → elite+ */+export function tierForScore(score) {+ if (score == null) return 'unknown';+ if (score < 30) return 'low';+ if (score < 60) return 'medium';+ if (score < 85) return 'high';+ return 'elite';+}++// ── Live subject loaders ─────────────────────────────────────────────────────++// Every dimension a given subject type can never supply is turned into a caveat+// so the buyer knows the score reflects partial evidence, not a full audit.+const DIM_LABEL = Object.fromEntries(DIMENSIONS.map((d) => [d.key, d.label]));+function missingCaveats(sig, keys) {+ return keys+ .filter((k) => {+ if (k === 'reliability') return !isNum(sig.failureRate);+ if (k === 'attestations') return !isNum(sig.attestationCount);+ const map = { activity: 'activity', age: 'ageDays', counterparties: 'counterparties', holdings: 'holdingsUsd' };+ return !isNum(sig[map[k]]);+ })+ .map((k) => `${DIM_LABEL[k]} not readable for this subject`);+}++function finalize({ subject, subjectType, chainId, sig, evidence = [], caveats = [], raw = {}, ts }) {+ const { score, tier, dimensions, weight_considered } = scoreSignals(sig);+ const signals = { dimensions, weight_considered, ...(chainId ? { chain: chainId } : {}), ...raw };+ if (sig.banned) caveats = ['subject is on the three.ws denylist — score capped', ...caveats];+ return { subject, subjectType, score, tier, signals, evidence, caveats, ts };+}++function unknownResult(subject, reason, ts, subjectType = 'unknown') {+ return {+ subject,+ subjectType,+ score: null,+ tier: 'unknown',+ signals: { dimensions: {}, weight_considered: 0 },+ evidence: [],+ caveats: [reason || 'subject could not be identified or scanned'],+ ts,+ };+}++// soft(): resolve a read to a fallback on any error, recording the failure as a+// caveat so a degraded source is visible in the result rather than silent.+async function soft(promise, fallback, caveats, note) {+ try {+ return await promise;+ } catch (err) {+ if (caveats && note) caveats.push(`${note}: ${err?.message || 'read failed'}`);+ return fallback;+ }+}++/**+ * Reputation for ANY subject. Auto-detects the type, reads the real evidence, and+ * returns a uniform { subject, subjectType, score, tier, signals, evidence,+ * caveats, ts } object. Never throws for an unknown/unscannable subject and never+ * fabricates a score — those return score:null, tier:'unknown'.+ *+ * @param {string} identifier+ * @param {object} [opts] { chain } for bare EVM / ERC-8004 subjects+ */+export async function loadSubjectReputation(identifier, opts = {}) {+ const det = detectSubject(identifier, opts);+ const ts = new Date().toISOString();+ try {+ switch (det.subjectType) {+ case 'threews_agent':+ return await scoreThreewsAgent(det, ts);+ case 'erc8004_agent':+ return await scoreErc8004Agent(det, ts);+ case 'evm_wallet':+ return await scoreEvmWallet(det, ts);+ case 'solana':+ return await scoreSolanaSubject(det, ts);+ default:+ return unknownResult(det.subject, det.reason, ts);+ }+ } catch (err) {+ // Absolute backstop — a subject type is known but every read blew up. Degrade+ // to unknown with the reason rather than 500. Solana stays 'solana_wallet'+ // (the safe assumption) so the type field is still informative.+ const fallbackType = det.subjectType === 'solana' ? 'solana_wallet' : det.subjectType;+ return unknownResult(det.subject, `scan failed: ${err?.message || 'error'}`, ts, fallbackType);+ }+}++/** Score a batch of arbitrary subjects concurrently. Resilient per-item. */+export async function scoreSubjectBatch(identifiers = [], { concurrency = 6, chain } = {}) {+ const ids = identifiers.map((s) => String(s ?? '').trim()).filter(Boolean);+ const out = [];+ for (let i = 0; i < ids.length; i += concurrency) {+ const chunk = ids.slice(i, i + concurrency);+ const settled = await Promise.all(+ chunk.map((id) =>+ loadSubjectReputation(id, { chain }).catch((err) =>+ unknownResult(id, `scan failed: ${err?.message || 'error'}`, new Date().toISOString()),+ ),+ ),+ );+ out.push(...settled);+ }+ return out;+}++// ── three.ws agent ───────────────────────────────────────────────────────────++// Map a three.ws on-chain reputation snapshot (from the pump-agent index) into the+// shared signal vocabulary. Shared by the agent path and the Solana-wallet /+// solana-mint paths when they resolve to a three.ws agent.+function sigFromAgentRep(rep) {+ const p = rep.payments || {};+ const a = rep.attestations || {};+ const settled = (p.confirmed_count || 0) + (p.failed_count || 0);+ return {+ activity: p.confirmed_count || 0,+ counterparties: p.distinct_payers || 0,+ failureRate: settled > 0 ? Number(p.failure_rate) || 0 : null,+ attestationCount: (a.feedback_count || 0) + (a.validation_count || 0),+ };+}++async function scoreThreewsAgent(det, ts) {+ const { loadAgentReputation } = await import('./solana-bouncer.js');+ const { sql } = await import('../db.js');+ let rep;+ try {+ rep = await loadAgentReputation(det.subject);+ } catch (err) {+ if (err?.status === 404) return unknownResult(det.subject, 'no three.ws agent with this id', ts, 'threews_agent');+ throw err;+ }+ const caveats = [];+ // Age from the identity row (one light indexed read).+ const [row] = await soft(+ sql`select created_at from agent_identities where id = ${det.subject} limit 1`,+ [null],+ caveats,+ 'agent age read',+ );+ const ageDays = row?.created_at ? (Date.now() - new Date(row.created_at).getTime()) / 86_400_000 : null;++ const sig = { ...sigFromAgentRep(rep), ageDays };+ caveats.push(...missingCaveats(sig, ['holdings']));++ const evidence = [{ kind: 'threews_agent', ref: `/agent/${det.subject}` }];+ if (rep.wallet_address) evidence.push({ kind: 'solana_account', ref: `https://solscan.io/account/${rep.wallet_address}` });+ const firstMint = rep.mints?.[0]?.mint;+ if (firstMint) evidence.push({ kind: 'launched_coin', ref: `https://solscan.io/token/${firstMint}` });++ return finalize({+ subject: det.subject,+ subjectType: 'threews_agent',+ sig,+ evidence,+ caveats,+ raw: {+ name: rep.name || null,+ wallet_address: rep.wallet_address || null,+ deployed_mints: rep.deployed_mints || 0,+ payments: rep.payments,+ distributions: rep.distributions,+ buybacks: rep.buybacks,+ attestations: rep.attestations,+ },+ ts,+ });+}++// ── ERC-8004 agent ───────────────────────────────────────────────────────────++async function readErc8004(chainId, agentId) {+ const { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI, IDENTITY_REGISTRY_ABI } = await import('../../../src/erc8004/abi.js');+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment) throw Object.assign(new Error(`ERC-8004 not deployed on chain ${chainId}`), { code: 'no_deployment' });+ const { Contract } = await import('ethers');+ const { evmFallbackProvider } = await import('../evm/rpc.js');+ const provider = await evmFallbackProvider(chainId);++ const out = { average: null, count: 0, wallet: null };+ if (deployment.reputationRegistry) {+ const rep = new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider);+ const [avgX100, count] = await rep.getReputation(BigInt(agentId));+ const n = Number(count);+ out.count = n;+ out.average = n === 0 ? null : Number(avgX100) / 100;+ }+ if (deployment.identityRegistry) {+ try {+ const idreg = new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider);+ const w = await idreg.getAgentWallet(BigInt(agentId));+ if (w && /^0x[0-9a-fA-F]{40}$/.test(w) && !/^0x0{40}$/.test(w)) out.wallet = w.toLowerCase();+ } catch {+ /* getAgentWallet is optional — some registries don't bind a wallet */+ }+ }+ return out;+}++async function scoreErc8004Agent(det, ts) {+ const caveats = [];+ const reg = await soft(readErc8004(det.chainId, det.agentId), null, caveats, 'erc8004 registry read');+ if (!reg) {+ return {+ ...unknownResult(det.subject, `ERC-8004 registry unreadable on chain ${det.chainId}`, ts, 'erc8004_agent'),+ signals: { dimensions: {}, weight_considered: 0, chain: det.chainId },+ };+ }++ const sig = {+ attestationCount: reg.count,+ attestationAvg: reg.average,+ };++ // If the identity registry binds a wallet, fold that wallet's raw EVM activity+ // + holdings in — the agent's own on-chain footprint, not just its reviews.+ const evidence = [{ kind: 'erc8004_reputation', ref: `eip155:${det.chainId}:agent/${det.agentId}` }];+ let walletReads = null;+ if (reg.wallet) {+ walletReads = await soft(readEvmWallet(det.chainId, reg.wallet), null, caveats, 'erc8004 agent wallet read');+ if (walletReads) {+ sig.activity = walletReads.txCount;+ sig.holdingsUsd = walletReads.holdingsUsd;+ }+ const explorer = CHAIN_BY_ID[det.chainId]?.explorer;+ if (explorer) evidence.push({ kind: 'evm_account', ref: `${explorer}/address/${reg.wallet}` });+ } else {+ caveats.push('no wallet bound to this ERC-8004 agent — activity / holdings not scored');+ }++ caveats.push(...missingCaveats(sig, ['age', 'counterparties', 'reliability']));+ if (reg.count === 0) caveats.push('no ERC-8004 feedback on record yet');++ return finalize({+ subject: det.subject,+ subjectType: 'erc8004_agent',+ chainId: det.chainId,+ sig,+ evidence,+ caveats,+ raw: {+ agent_id: det.agentId,+ erc8004: { feedback_count: reg.count, avg_feedback: reg.average, wallet: reg.wallet },+ ...(walletReads ? { native_balance: walletReads.native, tx_count: walletReads.txCount } : {}),+ },+ ts,+ });+}++// ── EVM wallet ───────────────────────────────────────────────────────────────++// Cheap, keyless EVM reads: outbound tx count (nonce) for activity and native+// balance priced to USD for holdings. Age + counterparties need an indexer we+// don't require, so they stay unread (→ caveats).+async function readEvmWallet(chainId, address) {+ const { evmFallbackProvider } = await import('../evm/rpc.js');+ const provider = await evmFallbackProvider(chainId);+ const [nonce, balanceWei] = await Promise.all([+ provider.getTransactionCount(address),+ provider.getBalance(address),+ ]);+ const native = Number(balanceWei) / 1e18;+ const price = await evmNativePriceUsd(chainId);+ return { txCount: Number(nonce), native, holdingsUsd: price != null ? native * price : null };+}++// Native-asset USD price by chain, keyless via CoinGecko simple price. Best-effort+// — a miss just leaves holdings unpriced (dimension unavailable), never an error.+const CG_NATIVE_ID = {+ 1: 'ethereum', 8453: 'ethereum', 42161: 'ethereum', 10: 'ethereum', 59144: 'ethereum',+ 534352: 'ethereum', 324: 'ethereum', 5000: 'mantle', 56: 'binancecoin', 137: 'matic-network',+ 43114: 'avalanche-2', 100: 'xdai', 250: 'fantom', 42220: 'celo', 1284: 'moonbeam',+};+async function evmNativePriceUsd(chainId) {+ const cgId = CG_NATIVE_ID[chainId];+ if (!cgId) return null;+ try {+ const r = await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${cgId}&vs_currencies=usd`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(5000),+ });+ if (!r.ok) return null;+ const data = await r.json();+ return Number(data?.[cgId]?.usd) || null;+ } catch {+ return null;+ }+}++async function scoreEvmWallet(det, ts) {+ const caveats = [];+ const reads = await soft(readEvmWallet(det.chainId, det.subject), null, caveats, 'evm wallet read');+ if (!reads) {+ return {+ ...unknownResult(det.subject, `EVM chain ${det.chainId} unreadable for this wallet`, ts, 'evm_wallet'),+ signals: { dimensions: {}, weight_considered: 0, chain: det.chainId },+ };+ }+ const sig = { activity: reads.txCount, holdingsUsd: reads.holdingsUsd };+ caveats.push(...missingCaveats(sig, ['age', 'counterparties', 'reliability', 'attestations']));++ const explorer = CHAIN_BY_ID[det.chainId]?.explorer;+ const evidence = explorer ? [{ kind: 'evm_account', ref: `${explorer}/address/${det.subject}` }] : [];++ return finalize({+ subject: det.subject,+ subjectType: 'evm_wallet',+ chainId: det.chainId,+ sig,+ evidence,+ caveats,+ raw: { tx_count: reads.txCount, native_balance: reads.native, native_symbol: nativeSymbol(det.chainId) },+ ts,+ });+}++function nativeSymbol(chainId) {+ if (chainId === 56) return 'BNB';+ if (chainId === 137) return 'MATIC';+ if (chainId === 43114) return 'AVAX';+ if (chainId === 250) return 'FTM';+ if (chainId === 42220) return 'CELO';+ if (chainId === 1284) return 'GLMR';+ if (chainId === 5000) return 'MNT';+ return 'ETH';+}++// ── Solana subject (wallet or mint) ──────────────────────────────────────────++async function scoreSolanaSubject(det, ts) {+ const { sql } = await import('../db.js');++ // (1) A pump.fun mint three.ws indexed → score its owning agent's behavior.+ const mintRows = await sql`+ select agent_id, symbol, network from pump_agent_mints where mint = ${det.subject} limit 1+ `.catch(() => []);+ if (mintRows[0]?.agent_id) return scoreThreewsMint(det, mintRows[0], ts);++ // (2) A known three.ws agent wallet → score that agent (folding wallet reads).+ const agentRows = await sql`+ select id from agent_identities+ where (wallet_address = ${det.subject} or meta->>'solana_address' = ${det.subject})+ and deleted_at is null+ limit 1+ `.catch(() => []);+ const knownAgentId = agentRows[0]?.id || null;++ // (3) Not ours — is it a live token? DexScreener resolves mints; if it returns a+ // Solana pair, treat the subject as an external mint scored from its market.+ if (!knownAgentId) {+ const market = await dexscreenerToken(det.subject).catch(() => null);+ if (market) return scoreExternalMint(det, market, ts);+ }++ // (4) Fall through: score it as a raw Solana wallet (folding agent signals if known).+ return scoreSolanaWallet(det, { knownAgentId }, ts);+}++async function scoreThreewsMint(det, mintRow, ts) {+ const { loadAgentReputation } = await import('./solana-bouncer.js');+ const caveats = [];+ const rep = await soft(loadAgentReputation(mintRow.agent_id), null, caveats, 'agent reputation read');+ if (!rep) return unknownResult(det.subject, 'mint owner reputation unreadable', ts, 'solana_mint');++ const market = await dexscreenerToken(det.subject).catch(() => null);+ const sig = { ...sigFromAgentRep(rep) };+ if (market) {+ sig.ageDays = market.ageDays;+ sig.holdingsUsd = market.liquidityUsd; // pool liquidity = skin-in-the-game proxy for a coin+ }+ caveats.push(...missingCaveats(sig, ['age', 'holdings']));++ const evidence = [+ { kind: 'solana_token', ref: `https://solscan.io/token/${det.subject}` },+ { kind: 'threews_agent', ref: `/agent/${mintRow.agent_id}` },+ ];+ if (market) evidence.push({ kind: 'dexscreener', ref: `https://dexscreener.com/solana/${det.subject}` });++ return finalize({+ subject: det.subject,+ subjectType: 'solana_mint',+ sig,+ evidence,+ caveats,+ raw: {+ mint: det.subject,+ symbol: mintRow.symbol || rep.mints?.find((m) => m.mint === det.subject)?.symbol || null,+ owner_agent_id: mintRow.agent_id,+ owner_name: rep.name || null,+ payments: rep.payments,+ attestations: rep.attestations,+ ...(market ? { market: { liquidity_usd: market.liquidityUsd, volume_24h_usd: market.volumeUsd, txns_24h: market.txns24h } } : {}),+ },+ ts,+ });+}++async function scoreExternalMint(det, market, ts) {+ const caveats = [+ 'external mint — scored from live market signals (liquidity, activity, age), not agent behavior',+ ];+ const sig = {+ activity: market.txns24h,+ ageDays: market.ageDays,+ holdingsUsd: market.liquidityUsd,+ };+ caveats.push(...missingCaveats(sig, ['counterparties', 'reliability', 'attestations']));++ return finalize({+ subject: det.subject,+ subjectType: 'solana_mint',+ sig,+ evidence: [+ { kind: 'solana_token', ref: `https://solscan.io/token/${det.subject}` },+ { kind: 'dexscreener', ref: `https://dexscreener.com/solana/${det.subject}` },+ ],+ caveats,+ raw: {+ mint: det.subject,+ symbol: market.symbol || null,+ market: {+ price_usd: market.priceUsd,+ liquidity_usd: market.liquidityUsd,+ volume_24h_usd: market.volumeUsd,+ txns_24h: market.txns24h,+ pair_created_at: market.pairCreatedAt,+ },+ },+ ts,+ });+}++async function scoreSolanaWallet(det, { knownAgentId }, ts) {+ const caveats = [];+ const { solanaConnection } = await import('../solana/connection.js');+ const { PublicKey } = await import('@solana/web3.js');+ const { findBan, normalizeWallet } = await import('../club/cover-pass.js');++ let pk;+ try {+ pk = new PublicKey(det.subject);+ } catch {+ return unknownResult(det.subject, 'not a valid Solana address', ts, 'solana_wallet');+ }+ const conn = solanaConnection({ network: 'mainnet' });++ // Bounded signature scan: count (capped at 1000/page) → activity. Age is only+ // derivable when the scan reached the START of history (page NOT saturated) —+ // for a hyperactive wallet that fills the 1000-tx page, the oldest signature in+ // the page is merely the oldest *recent* tx, not the account's age, so we must+ // NOT treat it as age (doing so wrongly tanks an ancient, busy wallet's score).+ const sigs = await soft(conn.getSignaturesForAddress(pk, { limit: 1000 }), null, caveats, 'solana signatures read');+ let activity = null;+ let ageDays = null;+ if (Array.isArray(sigs)) {+ activity = sigs.length;+ if (sigs.length >= 1000) {+ caveats.push(+ 'activity is a lower bound and account age is not derivable — signature history exceeds the 1000-tx scan window',+ );+ } else {+ const oldest = sigs[sigs.length - 1]?.blockTime;+ if (oldest) ageDays = Math.max(0, (Date.now() - oldest * 1000) / 86_400_000);+ }+ }++ // Native SOL balance priced to USD → holdings.+ const lamports = await soft(conn.getBalance(pk), null, caveats, 'solana balance read');+ let holdingsUsd = null;+ let solAmount = null;+ if (isNum(lamports)) {+ solAmount = lamports / 1e9;+ const price = await soft(solPriceUsd(), null, caveats, 'SOL price read');+ if (isNum(price)) holdingsUsd = solAmount * price;+ }++ // Denylist → hard risk override.+ const ban = await soft(findBan(normalizeWallet(det.subject)), null, caveats, 'denylist read');++ const sig = { activity, ageDays, holdingsUsd, banned: Boolean(ban) };++ // Fold the agent's settled-payment behavior in when this wallet is a known+ // three.ws agent wallet — richer, third-party-attested signals.+ let agentRaw = null;+ if (knownAgentId) {+ const { loadAgentReputation } = await import('./solana-bouncer.js');+ const rep = await soft(loadAgentReputation(knownAgentId), null, caveats, 'agent reputation read');+ if (rep) {+ const arep = sigFromAgentRep(rep);+ sig.counterparties = arep.counterparties;+ sig.failureRate = arep.failureRate;+ sig.attestationCount = arep.attestationCount;+ if (!isNum(sig.activity)) sig.activity = arep.activity;+ agentRaw = { agent_id: knownAgentId, name: rep.name || null, payments: rep.payments, attestations: rep.attestations };+ }+ }+ caveats.push(...missingCaveats(sig, knownAgentId ? [] : ['counterparties', 'reliability', 'attestations']));++ const evidence = [{ kind: 'solana_account', ref: `https://solscan.io/account/${det.subject}` }];+ if (knownAgentId) evidence.push({ kind: 'threews_agent', ref: `/agent/${knownAgentId}` });++ return finalize({+ subject: det.subject,+ subjectType: 'solana_wallet',+ sig,+ evidence,+ caveats,+ raw: {+ sol_balance: solAmount,+ signature_count: activity,+ denylisted: Boolean(ban),+ ...(agentRaw ? { agent: agentRaw } : {}),+ },+ ts,+ });+}++// ── shared upstream reads ────────────────────────────────────────────────────++async function solPriceUsd() {+ const { solanaMintUsdPrice } = await import('../balances.js');+ const p = await solanaMintUsdPrice(SOL_MINT);+ return Number(p) || null;+}++// DexScreener token lookup → normalized market signals, or null if it's not a+// tradeable Solana token (i.e. probably a wallet, not a mint). Keyless, public.+async function dexscreenerToken(mint) {+ const r = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${mint}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(6000),+ });+ if (!r.ok) return null;+ const data = await r.json();+ const pairs = (data.pairs || []).filter((p) => p.chainId === 'solana' && p.baseToken?.address === mint);+ if (!pairs.length) return null;+ pairs.sort((a, b) => (b.liquidity?.usd ?? 0) - (a.liquidity?.usd ?? 0));+ const p = pairs[0];+ const txns = (p.txns?.h24?.buys ?? 0) + (p.txns?.h24?.sells ?? 0);+ const created = p.pairCreatedAt ? Number(p.pairCreatedAt) : null;+ return {+ symbol: p.baseToken?.symbol || null,+ priceUsd: parseFloat(p.priceUsd) || null,+ liquidityUsd: p.liquidity?.usd ?? null,+ volumeUsd: p.volume?.h24 ?? null,+ txns24h: txns,+ pairCreatedAt: created ? new Date(created).toISOString() : null,+ ageDays: created ? Math.max(0, (Date.now() - created) / 86_400_000) : null,+ };+}diff --git a/api/_lib/x402/identity-claim-verify.js b/api/_lib/x402/identity-claim-verify.jsnew file mode 100644index 000000000..f51f226f8--- /dev/null+++ b/api/_lib/x402/identity-claim-verify.js@@ -0,0 +1,554 @@+// Cross-platform on-chain identity-claim verifier.+// ---------------------------------------------------------------------------+// Given a CLAIM that some `identity` controls some `address` on a `chain`, this+// module returns cryptographic / on-chain EVIDENCE that the claim is real —+// never a bare yes/no. It works for ANY claimed identity↔address link, not just+// three.ws agents:+//+// identity may be an ENS name (vitalik.eth), an SNS name (bonfida.sol), an+// EVM wallet (0x…), a Solana wallet (base58), an ERC-8004+// agent id (eip155:8453:42 / 8453:42), or a three.ws+// agent_id (uuid).+// address is the mint / contract / wallet the identity asserts control+// of.+//+// The agent use-case: before Agent A pays / trades / delegates to a counterparty+// that says "I am the deployer of contract X" or "I own wallet W / name N", A+// calls this once and gets deploy-tx + signer + ownership / name-resolution+// proof. A cross-platform trust check.+//+// Verdict discipline (CLAUDE.md "no errors without solutions", no false+// positives):+// verified === true concrete on-chain evidence links identity→address+// verified === false we read the authoritative source and it links+// the address to someone ELSE (or nobody)+// verified === 'unverifiable' we could not read enough to decide (name did not+// resolve, explorer key absent, RPC down, address+// is an opaque EOA with nothing to compare). Comes+// with a `caveats[]` list of exactly what is+// missing. NEVER a false positive.+//+// Every network-touching resolver is injectable via `deps` (real defaults below)+// so the whole matrix is unit-testable without a live chain, and so a single+// upstream outage degrades one evidence source rather than failing the call.++// UUID v-any check, inlined so this trust primitive drags in no import-time+// dependency (every heavier resolver is lazy-imported on demand below).+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+function isUuid(value) {+ return typeof value === 'string' && UUID_RE.test(value);+}++const EVM_ADDR_RE = /^0x[0-9a-fA-F]{40}$/;+const EVM_TX_RE = /^0x[0-9a-fA-F]{64}$/;+const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const ENS_RE = /^[a-z0-9-]+(\.[a-z0-9-]+)*\.eth$/i;+// A dotted `.sol` name (bare label rejected — that would collide with a base58+// address ending in a real TLD is impossible since base58 has no dots).+const SNS_RE = /^[a-z0-9-]+(\.[a-z0-9-]+)*\.sol$/i;+// ERC-8004 id: `<chainId>:<agentId>` optionally CAIP-2-prefixed (`eip155:`).+const ERC8004_RE = /^(?:eip155:)?(\d+):(\d+)$/;++// CAIP-2 → EVM chainId for the chains we can resolve ENS / contract creation on.+// ENS itself only lives on Ethereum mainnet (1); the rest are for contract+// deploy / ownership reads.+const CAIP2_TO_EVM_CHAINID = {+ 'eip155:1': 1,+ 'eip155:10': 10,+ 'eip155:56': 56,+ 'eip155:100': 100,+ 'eip155:137': 137,+ 'eip155:8453': 8453,+ 'eip155:42161': 42161,+ 'eip155:43114': 43114,+ 'eip155:59144': 59144,+ 'eip155:534352': 534352,+ 'eip155:84532': 84532,+ 'eip155:11155111': 11155111,+};++// Etherscan V2 unified multichain API — one key covers every chain via `chainid`.+const ETHERSCAN_V2 = 'https://api.etherscan.io/v2/api';++function normEvm(addr) {+ return typeof addr === 'string' && EVM_ADDR_RE.test(addr) ? addr.toLowerCase() : null;+}+function eqEvm(a, b) {+ const na = normEvm(a);+ const nb = normEvm(b);+ return !!na && na === nb;+}+function eqSol(a, b) {+ return typeof a === 'string' && typeof b === 'string' && a === b && SOL_ADDR_RE.test(a);+}++function evmChainIdFor(chain) {+ if (!chain) return null;+ if (CAIP2_TO_EVM_CHAINID[chain] != null) return CAIP2_TO_EVM_CHAINID[chain];+ const m = /^eip155:(\d+)$/.exec(chain);+ return m ? Number(m[1]) : null;+}++function isSolanaChain(chain) {+ return typeof chain === 'string' && chain.startsWith('solana:');+}++/**+ * Classify the claimed identity string into a resolver family. `chain` is an+ * optional CAIP-2 hint that disambiguates address-shaped identities.+ * @returns {{ type: string, chainId?: number, agentId?: string }}+ */+export function classifyIdentity(identity, chain) {+ const id = String(identity || '').trim();+ if (!id) return { type: 'unknown' };+ if (isUuid(id)) return { type: 'threews_agent_id' };+ if (SNS_RE.test(id)) return { type: 'sns' };+ if (ENS_RE.test(id)) return { type: 'ens' };+ const erc = ERC8004_RE.exec(id);+ if (erc) return { type: 'erc8004', chainId: Number(erc[1]), agentId: erc[2] };+ if (EVM_ADDR_RE.test(id)) return { type: 'evm_address' };+ // A bare integer is an ERC-8004 agent id only when the chain hint is EVM.+ if (/^\d+$/.test(id) && evmChainIdFor(chain)) {+ return { type: 'erc8004', chainId: evmChainIdFor(chain), agentId: id };+ }+ if (SOL_ADDR_RE.test(id)) return { type: 'solana_address' };+ return { type: 'unknown' };+}++// ---------------------------------------------------------------------------+// Real resolvers (default deps). Each is defensive: it resolves to a value or+// null/❴reason❵ and never throws, so a degraded upstream becomes an+// 'unverifiable' verdict with a caveat rather than a 500.+// ---------------------------------------------------------------------------++async function realEvmProvider(chainId) {+ const { evmFallbackProvider } = await import('../evm/rpc.js');+ const { SERVER_CHAIN_META } = await import('../onchain.js');+ const primaryUrl = SERVER_CHAIN_META[chainId]?.rpc || null;+ return evmFallbackProvider(chainId, { primaryUrl });+}++function withTimeout(promise, ms, label) {+ return new Promise((resolve, reject) => {+ const t = setTimeout(() => reject(new Error(`${label || 'op'} timeout ${ms}ms`)), ms);+ Promise.resolve(promise).then(+ (v) => { clearTimeout(t); resolve(v); },+ (e) => { clearTimeout(t); reject(e); },+ );+ });+}++export const realDeps = {+ // ENS forward resolution (name → address). Mainnet only — ENS canonical+ // registry lives on chain 1.+ async resolveEns(name) {+ try {+ const provider = await realEvmProvider(1);+ const addr = await withTimeout(provider.resolveName(name), 5000, 'ens_resolve');+ return normEvm(addr);+ } catch { return null; }+ },+ // ENS reverse resolution (address → primary name) — extra corroborating evidence.+ async reverseEns(address) {+ try {+ const provider = await realEvmProvider(1);+ const name = await withTimeout(provider.lookupAddress(address), 5000, 'ens_reverse');+ return name || null;+ } catch { return null; }+ },+ async resolveSns(name) {+ try {+ const { resolveSnsName } = await import('../../../src/solana/sns.js');+ const addr = await withTimeout(resolveSnsName(name), 6000, 'sns_resolve');+ return addr && SOL_ADDR_RE.test(addr) ? addr : null;+ } catch { return null; }+ },+ async reverseSns(address) {+ try {+ const { reverseLookupAddress } = await import('../../../src/solana/sns.js');+ return (await withTimeout(reverseLookupAddress(address), 6000, 'sns_reverse')) || null;+ } catch { return null; }+ },+ // EVM bytecode presence — distinguishes a contract from an EOA.+ async getEvmCode(chainId, address) {+ try {+ const provider = await realEvmProvider(chainId);+ return await withTimeout(provider.getCode(address), 5000, 'eth_getCode');+ } catch { return null; }+ },+ // Contract creator + creation tx via Etherscan V2. Without a key we cannot+ // read the deployer keylessly — return a reason so the caller degrades to+ // 'unverifiable' rather than guessing.+ async getEvmContractCreation(chainId, address) {+ const key = process.env.ETHERSCAN_API_KEY;+ if (!key) return { deployer: null, txHash: null, reason: 'no_explorer_key' };+ try {+ const url = `${ETHERSCAN_V2}?chainid=${chainId}&module=contract&action=getcontractcreation&contractaddresses=${address}&apikey=${key}`;+ const res = await fetch(url, { signal: AbortSignal.timeout(6000), headers: { accept: 'application/json' } });+ if (!res.ok) return { deployer: null, txHash: null, reason: `explorer_http_${res.status}` };+ const data = await res.json();+ const row = Array.isArray(data?.result) ? data.result[0] : null;+ if (!row?.contractCreator) return { deployer: null, txHash: null, reason: 'no_creation_record' };+ return {+ deployer: normEvm(row.contractCreator),+ txHash: EVM_TX_RE.test(row.txHash || '') ? row.txHash : null,+ };+ } catch { return { deployer: null, txHash: null, reason: 'explorer_unreachable' }; }+ },+ // Optional `owner()` getter — many contracts (Ownable) expose it.+ async getEvmOwner(chainId, address) {+ try {+ const { Contract } = await import('ethers');+ const provider = await realEvmProvider(chainId);+ const c = new Contract(address, ['function owner() view returns (address)'], provider);+ const owner = await withTimeout(c.owner(), 5000, 'owner');+ return normEvm(owner);+ } catch { return null; }+ },+ // Solana mint/metadata authorities. Returns null when the account isn't a+ // mint (or doesn't exist) so a wallet-vs-wallet claim degrades cleanly.+ async getSolanaMintInfo(mint) {+ try {+ const { PublicKey } = await import('@solana/web3.js');+ const { getConnection } = await import('../pump.js');+ const connection = getConnection({ network: 'mainnet' });+ const pk = new PublicKey(mint);+ const parsed = await withTimeout(connection.getParsedAccountInfo(pk), 6000, 'sol_mint');+ const value = parsed?.value;+ if (!value) return null;+ const info = value.data?.parsed?.info;+ const isMint = value.data?.program === 'spl-token' && value.data?.parsed?.type === 'mint';+ if (!isMint || !info) return null;+ const out = {+ mintAuthority: info.mintAuthority || null,+ freezeAuthority: info.freezeAuthority || null,+ updateAuthority: null,+ };+ // Metaplex metadata update authority (the "creator" that controls the+ // token's name/URI). Decoded from the metadata PDA: key(1) + updateAuth(32).+ try {+ const bs58 = (await import('bs58')).default;+ const METADATA_PROGRAM = new PublicKey('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s');+ const [metaPda] = PublicKey.findProgramAddressSync(+ [Buffer.from('metadata'), METADATA_PROGRAM.toBuffer(), pk.toBuffer()],+ METADATA_PROGRAM,+ );+ const acc = await withTimeout(connection.getAccountInfo(metaPda), 6000, 'sol_meta');+ if (acc?.data && acc.data.length >= 33) {+ out.updateAuthority = bs58.encode(acc.data.subarray(1, 33));+ }+ } catch { /* metadata optional — mint authority alone is evidence */ }+ return out;+ } catch { return null; }+ },+ // three.ws canonical meta.onchain index row for a platform agent_id.+ async lookupThreewsIndex(agentId) {+ try {+ const { sql } = await import('../db.js');+ const [row] = await sql`+ select meta+ from agent_identities+ where id = ${agentId}+ and deleted_at is null+ limit 1+ `;+ return row?.meta || null;+ } catch { return null; }+ },+ // ERC-8004 Identity Registry ownerOf / getAgentWallet.+ async resolveErc8004(chainId, agentId) {+ try {+ const { resolveOnChainAgent } = await import('../onchain.js');+ const r = await resolveOnChainAgent({ chainId, agentId, fetchManifest: false, timeoutMs: 5000 });+ if (r?.error && !r.owner && !r.wallet) return { owner: null, wallet: null, reason: r.error };+ return { owner: r.owner || null, wallet: r.wallet || null, registry: r.registry || null, explorer: r.explorer || null };+ } catch (err) { return { owner: null, wallet: null, reason: err.message }; }+ },+};++// ---------------------------------------------------------------------------+// Verdict assembly+// ---------------------------------------------------------------------------++function result({ identity, address, chain, identity_type, verified, method, evidence, caveats }) {+ return {+ claim: { identity, address, chain: chain || null },+ identity_type,+ verified,+ method,+ evidence: evidence || [],+ caveats: caveats || [],+ ts: new Date().toISOString(),+ };+}++async function verifyEns({ identity, address, chain, deps }) {+ const evidence = [];+ const caveats = [];+ if (!EVM_ADDR_RE.test(address)) {+ caveats.push('an ENS name resolves to an EVM address; the claimed address is not a valid 0x… address');+ return { verified: 'unverifiable', method: 'ens-resolution', evidence, caveats };+ }+ const resolved = await deps.resolveEns(identity);+ if (!resolved) {+ caveats.push('ENS name did not resolve to any address (unregistered, no address record, or Ethereum RPC unavailable)');+ evidence.push({ kind: 'ens_resolution', ref: identity, detail: 'no address record found' });+ return { verified: 'unverifiable', method: 'ens-resolution', evidence, caveats };+ }+ evidence.push({ kind: 'ens_forward_resolution', ref: identity, detail: `resolves to ${resolved}` });+ const rev = await deps.reverseEns(address);+ if (rev) evidence.push({ kind: 'ens_reverse_resolution', ref: address, detail: `primary name ${rev}` });+ const match = eqEvm(resolved, address);+ if (!match) {+ caveats.push(`${identity} resolves to ${resolved}, which is not the claimed address`);+ }+ return { verified: match, method: 'ens-resolution', evidence, caveats };+}++async function verifySns({ identity, address, chain, deps }) {+ const evidence = [];+ const caveats = [];+ if (!SOL_ADDR_RE.test(address)) {+ caveats.push('an SNS (.sol) name resolves to a Solana address; the claimed address is not valid base58');+ return { verified: 'unverifiable', method: 'sns-resolution', evidence, caveats };+ }+ const resolved = await deps.resolveSns(identity);+ if (!resolved) {+ caveats.push('SNS name did not resolve (unregistered, no owner record, or Solana RPC unavailable)');+ evidence.push({ kind: 'sns_resolution', ref: identity, detail: 'no owner record found' });+ return { verified: 'unverifiable', method: 'sns-resolution', evidence, caveats };+ }+ evidence.push({ kind: 'sns_forward_resolution', ref: identity, detail: `resolves to ${resolved}` });+ const rev = await deps.reverseSns(address);+ if (rev) evidence.push({ kind: 'sns_reverse_resolution', ref: address, detail: `favorite domain ${rev}` });+ const match = eqSol(resolved, address);+ if (!match) caveats.push(`${identity} resolves to ${resolved}, which is not the claimed address`);+ return { verified: match, method: 'sns-resolution', evidence, caveats };+}++async function verifyEvmAddress({ identity, address, chain, deps }) {+ const evidence = [];+ const caveats = [];+ const chainId = evmChainIdFor(chain) || 1;+ if (!chain) caveats.push('no chain supplied; defaulted to Ethereum mainnet (eip155:1) for the contract read');++ if (!EVM_ADDR_RE.test(address)) {+ caveats.push('claimed address is not a valid EVM (0x…) address');+ return { verified: 'unverifiable', method: 'evm-control', evidence, caveats };+ }+ if (eqEvm(identity, address)) {+ evidence.push({ kind: 'same_address', ref: address, detail: 'identity and address are the same account' });+ return { verified: true, method: 'evm-same-address', evidence, caveats };+ }++ const code = await deps.getEvmCode(chainId, address);+ const isContract = typeof code === 'string' && code !== '0x' && code.length > 2;++ if (!isContract) {+ if (code == null) caveats.push(`could not read bytecode at ${address} on eip155:${chainId} (RPC unavailable)`);+ else caveats.push(`${address} is an externally-owned account (no bytecode); two distinct EOAs cannot be linked on-chain without a signature — supply an ENS/SNS name or an ERC-8004 id instead`);+ return { verified: 'unverifiable', method: 'evm-control', evidence, caveats };+ }+ evidence.push({ kind: 'evm_bytecode', ref: address, detail: `contract on eip155:${chainId}` });++ let matched = false;+ let readSomething = false;++ const creation = await deps.getEvmContractCreation(chainId, address);+ if (creation?.deployer) {+ readSomething = true;+ evidence.push({ kind: 'evm_deployer', ref: creation.deployer, detail: 'contract creator (deployer)' });+ if (creation.txHash) evidence.push({ kind: 'evm_deploy_tx', ref: creation.txHash, detail: 'contract creation transaction' });+ if (eqEvm(creation.deployer, identity)) matched = true;+ } else if (creation?.reason === 'no_explorer_key') {+ caveats.push('deployer lookup unavailable (no explorer API key configured); relied on owner() only');+ } else if (creation?.reason) {+ caveats.push(`deployer lookup degraded: ${creation.reason}`);+ }++ const owner = await deps.getEvmOwner(chainId, address);+ if (owner) {+ readSomething = true;+ evidence.push({ kind: 'evm_owner', ref: owner, detail: 'contract owner() getter' });+ if (eqEvm(owner, identity)) matched = true;+ }++ if (matched) return { verified: true, method: 'evm-contract-control', evidence, caveats };+ if (readSomething) {+ caveats.push(`${identity} is neither the deployer nor the owner of ${address}`);+ return { verified: false, method: 'evm-contract-control', evidence, caveats };+ }+ caveats.push('could not read deployer (no explorer key) or an owner() getter; control is undetermined');+ return { verified: 'unverifiable', method: 'evm-contract-control', evidence, caveats };+}++async function verifySolanaAddress({ identity, address, chain, deps }) {+ const evidence = [];+ const caveats = [];+ if (!SOL_ADDR_RE.test(address)) {+ caveats.push('claimed address is not valid base58 for Solana');+ return { verified: 'unverifiable', method: 'solana-control', evidence, caveats };+ }+ if (eqSol(identity, address)) {+ evidence.push({ kind: 'same_address', ref: address, detail: 'identity and address are the same account' });+ return { verified: true, method: 'solana-same-address', evidence, caveats };+ }++ const info = await deps.getSolanaMintInfo(address);+ if (!info) {+ caveats.push(`${address} is not a readable SPL mint (or RPC unavailable); two distinct Solana wallets cannot be linked on-chain without a signature — supply an SNS (.sol) name instead`);+ return { verified: 'unverifiable', method: 'solana-control', evidence, caveats };+ }++ let matched = false;+ if (info.mintAuthority) {+ evidence.push({ kind: 'solana_mint_authority', ref: info.mintAuthority, detail: 'SPL mint authority' });+ if (eqSol(info.mintAuthority, identity)) matched = true;+ }+ if (info.updateAuthority) {+ evidence.push({ kind: 'solana_update_authority', ref: info.updateAuthority, detail: 'Metaplex metadata update authority (creator)' });+ if (eqSol(info.updateAuthority, identity)) matched = true;+ }+ if (info.freezeAuthority) {+ evidence.push({ kind: 'solana_freeze_authority', ref: info.freezeAuthority, detail: 'SPL freeze authority' });+ if (eqSol(info.freezeAuthority, identity)) matched = true;+ }++ if (matched) return { verified: true, method: 'solana-mint-authority', evidence, caveats };+ if (!info.mintAuthority && !info.updateAuthority && !info.freezeAuthority) {+ caveats.push('all mint authorities are renounced/null; no on-chain authority links this mint to any wallet');+ return { verified: 'unverifiable', method: 'solana-mint-authority', evidence, caveats };+ }+ caveats.push(`${identity} is not the mint, freeze, or update authority of ${address}`);+ return { verified: false, method: 'solana-mint-authority', evidence, caveats };+}++async function verifyErc8004({ identity, address, chain, chainId, agentId, deps }) {+ const evidence = [];+ const caveats = [];+ const cid = chainId || evmChainIdFor(chain);+ if (!cid) {+ caveats.push('ERC-8004 id needs a chain: pass identity as `eip155:<chainId>:<agentId>` or supply chain=eip155:<chainId>');+ return { verified: 'unverifiable', method: 'erc8004-registry', evidence, caveats };+ }+ const r = await deps.resolveErc8004(cid, agentId);+ if (!r || (!r.owner && !r.wallet)) {+ caveats.push(`ERC-8004 agent #${agentId} on eip155:${cid} has no on-chain owner/wallet record${r?.reason ? ` (${r.reason})` : ''}`);+ return { verified: 'unverifiable', method: 'erc8004-registry', evidence, caveats };+ }+ const registryRef = r.registry ? `${r.registry}#${agentId}` : `eip155:${cid}#${agentId}`;+ let matched = false;+ if (r.owner) {+ evidence.push({ kind: 'erc8004_owner_of', ref: r.owner, detail: `Identity Registry ownerOf(${agentId})` });+ if (eqEvm(r.owner, address)) matched = true;+ }+ if (r.wallet) {+ evidence.push({ kind: 'erc8004_agent_wallet', ref: r.wallet, detail: `getAgentWallet(${agentId})` });+ if (eqEvm(r.wallet, address)) matched = true;+ }+ evidence.push({ kind: 'erc8004_registration', ref: registryRef, detail: 'ERC-8004 Identity Registry entry' });+ if (matched) return { verified: true, method: 'erc8004-registry', evidence, caveats };+ caveats.push(`ERC-8004 agent #${agentId} does not resolve to the claimed address`);+ return { verified: false, method: 'erc8004-registry', evidence, caveats };+}++async function verifyThreewsAgentId({ identity, address, chain, deps }) {+ const evidence = [];+ const caveats = [];+ const meta = await deps.lookupThreewsIndex(identity);+ if (!meta) {+ caveats.push('agent_id is not present in the three.ws registry (deleted, unknown, or DB unavailable)');+ return { verified: 'unverifiable', method: 'threews-onchain-index', evidence, caveats };+ }+ const onchain = meta.onchain || {};+ // Canonical deploy record — the tx_hash/owner here are real on-chain and+ // checkable on any explorer.+ const indexedMint = onchain.contract_or_mint || meta.sol_mint_address || null;+ const custodialWallet = onchain.owner || onchain.wallet || meta.solana_address || null;+ const matchAddr = (cand) =>+ cand && (isSolanaChain(onchain.chain) || SOL_ADDR_RE.test(String(cand)) ? eqSol(cand, address) : eqEvm(cand, address));++ if (indexedMint && matchAddr(indexedMint)) {+ if (onchain.tx_hash) evidence.push({ kind: 'threews_deploy_tx', ref: onchain.tx_hash, detail: `deploy tx on ${onchain.chain || 'chain'}` });+ if (custodialWallet) evidence.push({ kind: 'threews_owner', ref: custodialWallet, detail: 'recorded owner wallet' });+ if (onchain.metadata_uri) evidence.push({ kind: 'threews_metadata_uri', ref: onchain.metadata_uri, detail: 'on-chain metadata URI' });+ evidence.push({ kind: 'threews_onchain_index', ref: indexedMint, detail: `three.ws canonical deploy record${onchain.confirmed_at ? ` (confirmed ${onchain.confirmed_at})` : ''}` });+ return { verified: true, method: 'threews-onchain-index', evidence, caveats };+ }+ if (custodialWallet && matchAddr(custodialWallet)) {+ evidence.push({ kind: 'threews_custodial_wallet', ref: custodialWallet, detail: 'three.ws custodial wallet for this agent' });+ return { verified: true, method: 'threews-custodial-wallet', evidence, caveats };+ }+ if (!indexedMint && !custodialWallet) {+ caveats.push('agent exists but has no on-chain identity recorded yet (never deployed)');+ return { verified: 'unverifiable', method: 'threews-onchain-index', evidence, caveats };+ }+ if (indexedMint) evidence.push({ kind: 'threews_onchain_index', ref: indexedMint, detail: 'agent owns a different address than claimed' });+ caveats.push('the three.ws record for this agent does not link it to the claimed address');+ return { verified: false, method: 'threews-onchain-index', evidence, caveats };+}++/**+ * Verify a claim that `identity` controls `address` on `chain`.+ *+ * @param {{ identity: string, address: string, chain?: string }} claim+ * @param {object} [deps] resolver overrides (defaults to real on-chain sources)+ * @returns {Promise<{+ * claim: { identity: string, address: string, chain: string|null },+ * identity_type: string,+ * verified: boolean|'unverifiable',+ * method: string,+ * evidence: Array<{ kind: string, ref: string, detail: string }>,+ * caveats: string[],+ * ts: string,+ * }>}+ */+export async function verifyClaim({ identity, address, chain } = {}, deps = realDeps) {+ const id = String(identity || '').trim();+ const addr = String(address || '').trim();+ const chn = chain ? String(chain).trim() : null;++ const { type, chainId, agentId } = classifyIdentity(id, chn);++ let outcome;+ try {+ switch (type) {+ case 'ens':+ outcome = await verifyEns({ identity: id, address: addr, chain: chn, deps });+ break;+ case 'sns':+ outcome = await verifySns({ identity: id, address: addr, chain: chn, deps });+ break;+ case 'evm_address':+ outcome = await verifyEvmAddress({ identity: id, address: addr, chain: chn, deps });+ break;+ case 'solana_address':+ outcome = await verifySolanaAddress({ identity: id, address: addr, chain: chn, deps });+ break;+ case 'erc8004':+ outcome = await verifyErc8004({ identity: id, address: addr, chain: chn, chainId, agentId, deps });+ break;+ case 'threews_agent_id':+ outcome = await verifyThreewsAgentId({ identity: id, address: addr, chain: chn, deps });+ break;+ default:+ outcome = {+ verified: 'unverifiable',+ method: 'none',+ evidence: [],+ caveats: ['could not classify the identity — expected an ENS/SNS name, an EVM or Solana address, an ERC-8004 id (eip155:<chainId>:<agentId>), or a three.ws agent_id (uuid)'],+ };+ }+ } catch (err) {+ // Absolute backstop — a resolver that slipped past its own guard must still+ // degrade to unverifiable, never surface as a 500.+ outcome = {+ verified: 'unverifiable',+ method: 'error',+ evidence: [],+ caveats: [`verification degraded: ${err.message}`],+ };+ }++ return result({ identity: id, address: addr, chain: chn, identity_type: type, ...outcome });+}diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.jsindex 2dae53087..7ac76e356 100644--- a/api/_mcp3d/text-to-image.js+++ b/api/_mcp3d/text-to-image.js@@ -204,7 +204,7 @@ async function persistDataUriImage(result) {// comes back inline as base64, no poll. Caller guarantees NVIDIA_API_KEY is set.// Throws on any failure (timeout, throttle, malformed body) so the caller can// degrade to the paid lanes; never returns a half-result.-async function nimFluxImage(prompt, aspectRatio) {+async function nimFluxImage(prompt, aspectRatio, seed = 0) {const key = readEnv('NVIDIA_API_KEY');const [width, height] = NIM_DIMENSIONS[aspectRatio] || NIM_DIMENSIONS['1:1'];@@ -228,7 +228,7 @@ async function nimFluxImage(prompt, aspectRatio) {mode: 'base',width,height,- seed: 0,+ seed,steps: 4,}),signal: controller.signal,@@ -302,8 +302,12 @@ function enhanceFluxPrompt(raw) {// paid Replicate backstop on any failure — a broken or throttled preferred// provider must hand off, never take down the whole text→3D pipeline. The last// configured lane's error is surfaced only when nothing is left to try.-export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false } = {}) {+export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false, seed } = {}) {prompt = enhanceFluxPrompt(prompt);+ // Optional deterministic seed. Honored on the lanes that expose one (NIM FLUX,+ // Replicate flux); the Vertex/Gemini image API has no seed parameter, so a seed+ // is silently ignored there. Undefined preserves the prior default (seed 0).+ const hasSeed = Number.isInteger(seed) && seed >= 0;const token = readEnv('REPLICATE_API_TOKEN');const hasVertex = !!readEnv('GOOGLE_CLOUD_PROJECT') && vertexImagenEnabled();const hasFallback = hasVertex || !!token;@@ -319,7 +323,7 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false(skipNim || (await providersInCooldown([NIM_FLUX_COOLDOWN_KEY])).has(NIM_FLUX_COOLDOWN_KEY));if (readEnv('NVIDIA_API_KEY') && !nimCooling) {try {- return logImageProvider(await nimFluxImage(prompt, aspectRatio));+ return logImageProvider(await nimFluxImage(prompt, aspectRatio, hasSeed ? seed : 0));} catch (err) {// A degraded lane (timeout / unreachable / throttle / 5xx) cools down so the// next caller skips it; a clean 4xx (bad input) is not a lane-health fault.@@ -371,6 +375,8 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false// reconstructs into a far better mesh than a busy scene — steer flux// toward that without overriding a caller's own composition cues.go_fast: true,+ // Deterministic seed when the caller supplied one (flux accepts `seed`).+ ...(hasSeed ? { seed } : {}),};let endpoint;diff --git a/api/crypto/bonding.js b/api/crypto/bonding.jsnew file mode 100644index 000000000..61cd4f1a5--- /dev/null+++ b/api/crypto/bonding.js@@ -0,0 +1,102 @@+// GET /api/crypto/bonding — free, keyless bonding-curve / graduation status for a+// pump.fun token.+//+// Agent use-case: an agent holding or watching a pump.fun coin needs to know+// exactly where it sits on the bonding curve — % to graduation, SOL in the curve,+// and whether it has already migrated to Raydium / PumpSwap. Timing entries and+// exits around graduation is a core meme-trading move, and this is the one read+// that answers it. Pairs with /api/crypto/launches (discover fresh mints) and+// /api/crypto/whales.+//+// Part of the free Crypto Data API (/api/crypto/*). Plain-handler pattern: no+// account, no key, generous per-IP limit. Real data only — the pump.fun public+// frontend feed via api/_lib/pump-bonding.js.++import { cors, method, wrap, error, json, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getBondingStatus } from '../_lib/pump-bonding.js';++const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://localhost');+ const mint = (url.searchParams.get('mint') || '').trim();++ if (!mint) {+ return error(+ res,+ 400,+ 'missing_mint',+ 'query param `mint` is required — pass a pump.fun token mint, e.g. ?mint=<base58-mint>',+ );+ }+ if (!MINT_RE.test(mint)) {+ return error(+ res,+ 400,+ 'invalid_mint',+ '`mint` must be a base58 Solana address (32–44 chars)',+ { mint },+ );+ }++ const result = await getBondingStatus(mint);+ const ts = new Date().toISOString();++ // Not a pump.fun-indexed mint (never launched on pump.fun, or not a bonding-curve+ // token) — a client error, so 400 with a pointer to discovery.+ if (result.kind === 'not_found') {+ return error(+ res,+ 400,+ 'not_pumpfun_mint',+ `${mint} is not a pump.fun bonding-curve token — it never launched on pump.fun or isn't indexed. Discover live pump.fun mints at /api/crypto/launches.`,+ { mint },+ );+ }++ // pump.fun feed temporarily unreachable (network / timeout / 5xx). Never 500 —+ // answer 503 + Retry-After so the agent backs off and retries, per the free-API+ // contract.+ if (result.kind === 'upstream_down') {+ return json(+ res,+ 503,+ {+ error: 'upstream_unavailable',+ error_description: 'pump.fun data source is temporarily unreachable — retry shortly',+ mint,+ retry_after: 15,+ ts,+ },+ { 'cache-control': 'no-store', 'retry-after': '15' },+ );+ }++ const s = result.status;+ return json(+ res,+ 200,+ {+ mint,+ onCurve: s.onCurve,+ bondingProgressPct: s.bondingProgressPct,+ solInCurve: s.solInCurve,+ tokensRemaining: s.tokensRemaining,+ marketCapUsd: s.marketCapUsd,+ graduated: s.graduated,+ migratedTo: s.migratedTo,+ ts,+ source: s.source,+ },+ // Bonding-curve state moves fast; short CDN cache + SWR keeps a polling agent+ // responsive without hammering the pump.fun feed.+ { 'cache-control': 'public, s-maxage=15, stale-while-revalidate=30' },+ );+});diff --git a/api/crypto/index.js b/api/crypto/index.jsnew file mode 100644index 000000000..074e07010--- /dev/null+++ b/api/crypto/index.js@@ -0,0 +1,192 @@+// @ts-check+// GET /api/crypto — the front door to the free, keyless Crypto Data API bundle.+//+// One URL an agent (or a human wiring one up) hits to discover the entire API:+// every endpoint, its inputs/outputs, and a live example. This is what makes the+// bundle feel like one product instead of a handful of loose routes. The list is+// assembled at request time from the catalog (api/_lib/crypto-catalog), so a new+// sibling endpoint appears here the moment it ships — nothing to wire by hand.+//+// Content negotiation: `Accept: text/html` gets a browsable page; everything+// else (the agent path) gets JSON. Free means free — keyless, no account, a+// generous per-IP limit that only blunts abuse.++import { wrap, cors, method, json, text, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { loadCatalog } from '../_lib/crypto-catalog/index.js';++const VERSION = '1.0.0';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ // Cheap metadata read; generous ceiling, bounded so it can't be scraped in a+ // tight loop. Reuses the shared per-IP bucket sized for this surface.+ const ip = clientIp(req);+ const rl = await limits.apiIp(ip, { limit: 240, window: '5 m' });+ if (!rl.success) return rateLimited(res, rl, 'too many requests to the crypto API index');++ const endpoints = await loadCatalog();+ const origin = env.APP_ORIGIN;++ const payload = {+ name: 'three.ws Crypto Data API',+ free: true,+ keyless: true,+ version: VERSION,+ endpoints,+ count: endpoints.length,+ // Zero entries is a valid state, not an error — say so plainly.+ ...(endpoints.length === 0+ ? {+ note: 'Endpoints are coming soon. They list here automatically as they ship.',+ }+ : {}),+ openapi: '/api/crypto/openapi.json',+ docs: '/docs/crypto-api',+ ts: new Date().toISOString(),+ };++ // Public + CDN-cacheable: the catalog only changes on deploy, so a short edge+ // cache keeps this instant without hiding new endpoints for long.+ const cache = { 'cache-control': 'public, s-maxage=300, stale-while-revalidate=600' };++ if (String(req.headers.accept || '').includes('text/html')) {+ return text(res, 200, renderHtml(payload, origin), {+ ...cache,+ 'content-type': 'text/html; charset=utf-8',+ });+ }+ return json(res, 200, payload, cache);+});++/** Escape untrusted-ish strings before dropping them into HTML. */+function esc(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++/**+ * Human-friendly index page. Self-contained, theme-aware, responsive. Lists+ * every endpoint with its method, path, summary, and a copy-ready curl example.+ * @param {any} p payload+ * @param {string} origin+ */+function renderHtml(p, origin) {+ const rows = p.endpoints.length+ ? p.endpoints+ .map((e) => {+ const example =+ e.example && typeof e.example === 'object'+ ? esc(JSON.stringify(e.example, null, 2))+ : '';+ const curl = `curl ${esc(origin)}${esc(e.path)}`;+ return `+ <article class="ep">+ <header>+ <span class="method">${esc((e.methods && e.methods.length ? e.methods : [e.method]).join(' / '))}</span>+ <code class="path">${esc(e.path)}</code>+ </header>+ <h3>${esc(e.title)}</h3>+ ${e.summary ? `<p>${esc(e.summary)}</p>` : ''}+ <pre class="curl"><code>${esc(curl)}</code></pre>+ ${example ? `<details><summary>Example response</summary><pre><code>${example}</code></pre></details>` : ''}+ </article>`;+ })+ .join('')+ : `<div class="empty">+ <h3>Endpoints are coming soon</h3>+ <p>This bundle lists every endpoint here automatically as it ships. Check back shortly, or watch the <a href="/changelog">changelog</a>.</p>+ </div>`;++ return `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>three.ws Crypto Data API — free & keyless</title>+ <meta name="description" content="A free, keyless crypto data bundle for AI agents. One URL to discover every endpoint." />+ <style>+ :root {+ --bg: #ffffff; --fg: #0b0d12; --muted: #5b6472; --card: #f6f8fa;+ --border: #e4e8ee; --accent: #6d4aff; --code: #eef1f6;+ }+ @media (prefers-color-scheme: dark) {+ :root {+ --bg: #0b0d12; --fg: #e9edf4; --muted: #99a3b3; --card: #12151c;+ --border: #232935; --accent: #9d86ff; --code: #171b23;+ }+ }+ * { box-sizing: border-box; }+ body {+ margin: 0; background: var(--bg); color: var(--fg);+ font: 15px/1.55 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ padding: 2.5rem 1.25rem 4rem;+ }+ main { max-width: 860px; margin: 0 auto; }+ .badges { display: flex; gap: .5rem; flex-wrap: wrap; margin: .75rem 0 0; }+ .badge {+ font-size: .72rem; font-weight: 600; text-transform: uppercase; letter-spacing: .04em;+ background: var(--accent); color: #fff; padding: .2rem .55rem; border-radius: 999px;+ }+ h1 { font-size: 1.9rem; margin: 0; letter-spacing: -.02em; }+ .lede { color: var(--muted); margin: .6rem 0 0; }+ .meta { color: var(--muted); font-size: .85rem; margin-top: 1rem; }+ .meta a { color: var(--accent); }+ .grid { display: grid; gap: 1rem; margin-top: 2rem; }+ .ep {+ background: var(--card); border: 1px solid var(--border); border-radius: 14px;+ padding: 1.1rem 1.2rem; transition: border-color .15s ease, transform .15s ease;+ }+ .ep:hover { border-color: var(--accent); }+ .ep header { display: flex; align-items: center; gap: .6rem; }+ .method {+ font-size: .72rem; font-weight: 700; color: #fff; background: #2f8f4e;+ padding: .12rem .5rem; border-radius: 6px; letter-spacing: .03em;+ }+ .path { font-size: .9rem; color: var(--fg); }+ .ep h3 { margin: .7rem 0 .25rem; font-size: 1.05rem; }+ .ep p { margin: 0 0 .7rem; color: var(--muted); }+ pre {+ background: var(--code); border: 1px solid var(--border); border-radius: 8px;+ padding: .7rem .8rem; overflow-x: auto; margin: .4rem 0 0; font-size: .82rem;+ }+ pre code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }+ details { margin-top: .5rem; }+ summary { cursor: pointer; color: var(--accent); font-size: .85rem; }+ .empty {+ text-align: center; padding: 3rem 1rem; background: var(--card);+ border: 1px dashed var(--border); border-radius: 14px; color: var(--muted);+ }+ .empty a { color: var(--accent); }+ footer { margin-top: 2.5rem; color: var(--muted); font-size: .82rem; }+ </style>+</head>+<body>+ <main>+ <h1>${esc(p.name)}</h1>+ <div class="badges">+ <span class="badge">Free</span>+ <span class="badge">Keyless</span>+ <span class="badge">v${esc(p.version)}</span>+ </div>+ <p class="lede">One URL to discover the entire bundle — every endpoint, its inputs and outputs, and a live example. No account, no API key.</p>+ <p class="meta">+ ${p.count} endpoint${p.count === 1 ? '' : 's'} ·+ <a href="/api/crypto/openapi.json">OpenAPI 3.1</a> ·+ <a href="/docs/crypto-api">Docs</a> ·+ <a href="/api/crypto">JSON</a>+ </p>+ <section class="grid">+ ${rows}+ </section>+ <footer>Built for agents. <a href="/docs/crypto-api">Read the docs →</a></footer>+ </main>+</body>+</html>`;+}diff --git a/api/crypto/openapi.js b/api/crypto/openapi.jsnew file mode 100644index 000000000..a2cbf645f--- /dev/null+++ b/api/crypto/openapi.js@@ -0,0 +1,35 @@+// @ts-check+// GET /api/crypto/openapi.json — the machine-readable spec for the free Crypto+// Data API bundle, generated live from the catalog (api/_lib/crypto-catalog).+//+// Served at `/api/crypto/openapi.json` via the rewrite in vercel.json; this file+// also answers `/api/crypto/openapi` directly. An agent points its OpenAPI+// toolchain (openapi-generator, LangChain's OpenAPIToolkit, Swagger UI) at this+// URL and gets typed clients / callable tools for every endpoint — no key, no+// account. The doc is never hand-written: paths, params, and response schemas+// all derive from the catalog entries, so it can't drift from `/api/crypto`.++import { wrap, cors, method, json, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { loadCatalog } from '../_lib/crypto-catalog/index.js';+import { buildOpenApiDoc } from '../_lib/crypto-catalog/openapi.js';++const VERSION = '1.0.0';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const ip = clientIp(req);+ const rl = await limits.apiIp(ip, { limit: 240, window: '5 m' });+ if (!rl.success) return rateLimited(res, rl, 'too many requests to the crypto OpenAPI doc');++ const entries = await loadCatalog();+ const doc = buildOpenApiDoc(entries, { origin: env.APP_ORIGIN, version: VERSION });++ // Catalog changes only on deploy — safe to CDN-cache briefly.+ return json(res, 200, doc, {+ 'cache-control': 'public, s-maxage=300, stale-while-revalidate=600',+ });+});diff --git a/api/crypto/symbol.js b/api/crypto/symbol.jsnew file mode 100644index 000000000..4b0c81eaf--- /dev/null+++ b/api/crypto/symbol.js@@ -0,0 +1,242 @@+// GET /api/crypto/symbol?symbols=A,B,C&chain=solana+// POST /api/crypto/symbol { symbols: string[] (max 20), chain?: 'solana' }+//+// FREE, keyless symbol-availability check. Given up to 20 candidate ticker+// symbols, returns per-symbol exact + fuzzy collisions across live token+// registries so an agent can pick a name that won't be lost among clones+// BEFORE it commits to a launch.+//+// Agent use-case: an agent about to launch a token wants to check candidate+// tickers for collisions (exact name clashes + look-alikes that dilute search)+// before minting. A free batch check is the natural top-of-funnel for the paid+// Pump Launcher (/api/x402/pump-launch) — clear the name here, launch there.+//+// Data source: DexScreener's keyless search API (every chain it indexes),+// deduped by mint and scored locally with a pg_trgm-style trigram Jaccard+// similarity — the same exact-plus-fuzzy collision model the retired paid route+// (api/x402/symbol-availability.js) ran against three.ws's own mint index, but+// broadened to the whole market and made free. No key, no account.++import { wrap, cors, method, json, error, readJson, rateLimited, setRateLimitHeaders } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';++const DEXSCREENER_SEARCH = 'https://api.dexscreener.com/latest/dex/search';++// Cap the batch so one call can't fan out into an unbounded DexScreener sweep.+export const SYMBOL_CAP = 20;++// Fuzzy floor mirrors the paid route's SIMILARITY_THRESHOLD: a look-alike below+// this is noise, at/above it is worth warning about. Exact matches score 1.0.+const FUZZY_FLOOR = 0.4;++// Per-symbol collision lists are capped so a hot ticker (dozens of clones)+// returns the most-relevant matches, not a wall of near-duplicates.+const MAX_COLLISIONS = 10;++// Strip a leading `$` and surrounding whitespace so `$MOON`, `MOON`, and+// ` moon ` all resolve to the same candidate.+function normalizeSymbol(s) {+ return String(s ?? '').trim().replace(/^\$+/, '').trim();+}++// pg_trgm-style trigrams: lowercase, pad with two leading + one trailing space+// so word boundaries contribute to the score exactly like Postgres' show_trgm.+function trigrams(str) {+ const padded = ` ${str.toLowerCase()} `;+ const set = new Set();+ for (let i = 0; i + 3 <= padded.length; i++) set.add(padded.slice(i, i + 3));+ return set;+}++// Jaccard similarity over trigram sets — the same measure Postgres' pg_trgm+// `similarity()` uses (|intersection| / |union|), so the free route's fuzzy+// scoring matches what the paid route returned. 1.0 == identical, 0 == disjoint.+export function symbolSimilarity(a, b) {+ const A = String(a ?? '').toLowerCase();+ const B = String(b ?? '').toLowerCase();+ if (!A || !B) return 0;+ if (A === B) return 1;+ const ta = trigrams(A);+ const tb = trigrams(B);+ if (!ta.size || !tb.size) return 0;+ let inter = 0;+ for (const g of ta) if (tb.has(g)) inter++;+ const union = ta.size + tb.size - inter;+ return union ? inter / union : 0;+}++// Query DexScreener's keyless search for one symbol and reduce the returned+// pairs to unique base tokens (highest-liquidity pair wins per mint). Throws on+// a non-OK upstream so the caller can degrade that symbol gracefully.+async function searchTokens(symbol, chain, fetchImpl) {+ const url = `${DEXSCREENER_SEARCH}?q=${encodeURIComponent(symbol)}`;+ const r = await fetchImpl(url, {+ headers: { Accept: 'application/json' },+ signal: AbortSignal.timeout(6000),+ });+ if (!r.ok) throw new Error(`dexscreener search ${r.status}`);+ const data = await r.json();+ const pairs = Array.isArray(data?.pairs) ? data.pairs : [];+ const byMint = new Map();+ for (const p of pairs) {+ const base = p?.baseToken;+ if (!base?.symbol || !base?.address) continue;+ if (chain && String(p.chainId).toLowerCase() !== chain) continue;+ const liquidityUsd = Number(p?.liquidity?.usd) || 0;+ const prev = byMint.get(base.address);+ if (!prev || liquidityUsd > prev.liquidityUsd) {+ byMint.set(base.address, {+ symbol: base.symbol,+ name: base.name ?? null,+ mint: base.address,+ chain: p.chainId ?? null,+ liquidityUsd,+ });+ }+ }+ return [...byMint.values()];+}++// Classify one candidate symbol against the live registry.+async function checkOne(symbol, chain, fetchImpl) {+ let candidates;+ try {+ candidates = await searchTokens(symbol, chain, fetchImpl);+ } catch {+ // Registry source down for this symbol: degrade, never fail the batch.+ // `available: null` signals "could not verify" — distinct from a hard+ // available/taken — so a caller never reads an outage as a green light.+ return {+ symbol,+ available: null,+ exactCollisions: [],+ fuzzyCollisions: [],+ degraded: true,+ note: 'collision source unavailable — could not verify this symbol; retry shortly',+ };+ }++ const exact = [];+ const fuzzy = [];+ for (const c of candidates) {+ const score = symbolSimilarity(symbol, c.symbol);+ if (c.symbol.toLowerCase() === symbol.toLowerCase()) {+ exact.push({ symbol: c.symbol, name: c.name, mint: c.mint, chain: c.chain });+ } else if (score >= FUZZY_FLOOR) {+ fuzzy.push({+ symbol: c.symbol,+ name: c.name,+ mint: c.mint,+ chain: c.chain,+ similarity: Number(score.toFixed(3)),+ });+ }+ }+ fuzzy.sort((a, b) => b.similarity - a.similarity);++ return {+ symbol,+ available: exact.length === 0,+ exactCollisions: exact.slice(0, MAX_COLLISIONS),+ fuzzyCollisions: fuzzy.slice(0, MAX_COLLISIONS),+ };+}++// Core batch check — pure enough to unit-test with an injected `fetchImpl`.+// De-duplicates the input case-insensitively (checking "MOON" and "moon" twice+// wastes an upstream call and skews the counts).+export async function checkSymbols({ symbols, chain, fetchImpl = fetch }) {+ const seen = new Map();+ for (const raw of symbols) {+ const sym = normalizeSymbol(raw);+ if (!sym) continue;+ const key = sym.toLowerCase();+ if (!seen.has(key)) seen.set(key, sym);+ }+ const unique = [...seen.values()];++ const results = await Promise.all(unique.map((s) => checkOne(s, chain, fetchImpl)));++ const availableCount = results.filter((r) => r.available === true).length;+ const takenCount = results.filter((r) => r.available === false).length;+ const degraded = results.some((r) => r.degraded);++ return {+ results,+ availableCount,+ takenCount,+ ...(degraded+ ? { degraded: true, note: 'one or more symbols could not be verified against the collision source' }+ : {}),+ chain: chain ?? null,+ ts: new Date().toISOString(),+ };+}++// Read the requested symbol list + optional chain from either verb.+function parseInput(req, body, url) {+ if (req.method === 'POST') {+ const rawSymbols = Array.isArray(body?.symbols) ? body.symbols : [];+ const chain = body?.chain ? String(body.chain).trim().toLowerCase() : undefined;+ return { rawSymbols, chain };+ }+ const raw = url.searchParams.get('symbols') || '';+ const rawSymbols = raw.split(',');+ const c = url.searchParams.get('chain');+ const chain = c ? c.trim().toLowerCase() : undefined;+ return { rawSymbols, chain };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const ip = clientIp(req);+ const rl = await limits.publicIp(ip);+ if (!rl.success) return rateLimited(res, rl);++ let body = null;+ if (req.method === 'POST') {+ try {+ body = await readJson(req);+ } catch (err) {+ setRateLimitHeaders(res, rl);+ return error(res, err.status || 400, 'invalid_json', err.message || 'request body must be valid JSON');+ }+ }++ const url = new URL(req.url, 'http://x');+ const { rawSymbols, chain } = parseInput(req, body, url);++ const cleaned = rawSymbols.map(normalizeSymbol).filter(Boolean);++ setRateLimitHeaders(res, rl);++ if (cleaned.length === 0) {+ return error(+ res,+ 400,+ 'missing_symbols',+ `provide 1–${SYMBOL_CAP} ticker symbols via ?symbols=A,B,C (GET) or { "symbols": [...] } (POST)`,+ { cap: SYMBOL_CAP, example: { symbols: ['MOON', 'ROCKET', 'FROG'], chain: 'solana' } },+ );+ }+ if (cleaned.length > SYMBOL_CAP) {+ return error(+ res,+ 400,+ 'too_many_symbols',+ `at most ${SYMBOL_CAP} symbols per request — you sent ${cleaned.length}`,+ { cap: SYMBOL_CAP },+ );+ }++ const payload = await checkSymbols({ symbols: cleaned, chain });++ // Short shared-edge cache: identical candidate lists (agents batch-probing the+ // same trending tickers) served from the CDN without re-hitting DexScreener,+ // while staying fresh enough that a brand-new collision surfaces within ~30s.+ return json(res, 200, payload, {+ 'cache-control': 'public, s-maxage=30, stale-while-revalidate=60',+ });+});diff --git a/api/crypto/wallet.js b/api/crypto/wallet.jsnew file mode 100644index 000000000..b0571043b--- /dev/null+++ b/api/crypto/wallet.js@@ -0,0 +1,163 @@+// GET /api/crypto/wallet — free, keyless wallet portfolio for AI agents.+//+// Agent use-case: an autonomous agent needs to inspect a wallet — its own or a+// counterparty's — before it transacts. A treasury agent checks its runway, a+// copy-trade agent mirrors a leader's holdings, a pre-trade check inspects who+// it's about to deal with. One call returns native balance, every SPL token,+// and a rough USD valuation, so the agent doesn't have to juggle an RPC + a+// price API + a metadata source itself.+//+// Free-endpoint pattern (see prompts/x402-overhaul/00-CONTEXT.md): plain handler,+// `cors`/`wrap`/`error` from _lib/http.js, rate-limited by IP via _lib/rate-limit.js.+// No key, no account. The Solana path returns REAL balances even without a Helius+// key — it falls back to the public RPC `getTokenAccountsByOwner` walk and prices+// via Jupiter Lite + the pump.fun bonding curve (all keyless). Helius DAS is used+// only as a faster path when HELIUS_API_KEY is present.++import { cors, method, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getBalances, walletUsdTotal, heliusHealth } from '../_lib/balances.js';+import { isValidAddressForChain } from '../_lib/splits.js';++// Cap the token list so a wallet holding thousands of dust airdrops can't return+// a multi-megabyte payload. Tokens are sorted by USD value desc before the cap,+// so the most meaningful holdings always survive; `truncated` flags the rest.+const MAX_TOKENS = 200;++// Chain aliases → the internal chain key `getBalances` understands. Solana is the+// keyless flagship; the EVM path resolves Ethereum mainnet and needs ALCHEMY_API_KEY+// (degrades to 503 not_configured when absent, never a fake). Aliases keep the API+// forgiving without pretending to support a chain the balance layer can't read.+const CHAIN_ALIASES = {+ solana: 'solana',+ sol: 'solana',+ ethereum: 'evm',+ eth: 'evm',+ evm: 'evm',+ mainnet: 'evm',+};++// Round a USD figure to cents-ish precision without importing a bignum lib — these+// are display valuations, not settlement amounts. Keeps 6 significant sub-dollar+// digits so sub-cent token values ($0.0000123) don't collapse to 0.+function roundUsd(n) {+ if (!(Number(n) > 0)) return 0;+ return Number(n) < 1 ? Number(n.toPrecision(6)) : Math.round(n * 100) / 100;+}++// Map the rich internal balance shape to the stable public contract. Unpriced+// tokens (price 0 — Jupiter/pump.fun couldn't route them) keep their amount but+// report `usd: null`, never a fake 0 valuation and never dropped from the list.+function shapeToken(t) {+ const priced = Number(t.price) > 0;+ return {+ mint: t.mint,+ symbol: t.symbol || null,+ name: t.name || null,+ amount: t.amount,+ usd: priced ? roundUsd(t.usd) : null,+ logo: t.logo || null,+ };+}++// Which real upstreams a response drew on, reported honestly so an agent can+// reason about freshness. Solana balances come from Helius DAS when a key is+// configured and its quota breaker is closed, else the public RPC; USD comes+// from Jupiter Lite (with a pump.fun bonding-curve fallback baked into the+// balance layer). EVM balances/prices come from Alchemy + CoinGecko.+function sourcesFor(chain) {+ if (chain === 'solana') {+ const h = heliusHealth();+ const balanceSource = h.configured && h.available ? 'helius-das' : 'solana-rpc';+ return [balanceSource, 'jupiter-lite'];+ }+ return ['alchemy', 'coingecko'];+}++export default wrap(async function handler(req, res) {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const ip = clientIp(req);+ const [ipRl, globalRl] = await Promise.all([limits.cryptoDataIp(ip), limits.cryptoDataGlobal()]);+ if (!ipRl.success || !globalRl.success) {+ return error(res, 429, 'rate_limited', 'too many requests — slow down and retry shortly', {+ retryAfter: 60,+ });+ }++ const url = new URL(req.url, 'http://x');+ const address = (url.searchParams.get('address') || '').trim();+ const rawChain = (url.searchParams.get('chain') || 'solana').trim().toLowerCase();++ if (!address) {+ return error(res, 400, 'missing_address', 'pass ?address=<wallet> (a Solana or EVM address)', {+ example: '/api/crypto/wallet?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&chain=solana',+ });+ }++ const chain = CHAIN_ALIASES[rawChain];+ if (!chain) {+ return error(res, 400, 'unsupported_chain', `chain "${rawChain}" is not supported`, {+ supported: ['solana', 'ethereum'],+ });+ }++ // Validate the address for its family BEFORE any upstream call, so a typo is a+ // fast 400 rather than a wasted RPC round-trip that 404s deep in the balance layer.+ const validationChain = chain === 'solana' ? 'solana' : 'evm';+ if (!isValidAddressForChain(address, validationChain)) {+ return error(res, 400, 'invalid_address', `not a valid ${validationChain === 'solana' ? 'Solana' : 'EVM'} address`, {+ example: '/api/crypto/wallet?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&chain=solana',+ });+ }++ let balances;+ try {+ balances = await getBalances({ chain, address });+ } catch (err) {+ // EVM without an Alchemy key: honest 503 naming the gap, never a mock.+ if (err?.code === 'not_configured') {+ return error(res, 503, 'not_configured', 'this chain requires a provider key that is not set on this deployment — Solana works keyless', {+ chain: rawChain,+ });+ }+ // Every live RPC path failed and there was no cached snapshot to fall back on.+ // Surface a retryable 503 with Retry-After — never a 500 on a well-formed request.+ res.setHeader('retry-after', '15');+ return error(res, 503, 'upstream_unavailable', 'wallet data source is temporarily unavailable — retry shortly', {+ retryAfter: 15,+ });+ }++ const allTokens = Array.isArray(balances.tokens) ? balances.tokens : [];+ const truncated = allTokens.length > MAX_TOKENS;+ const tokens = allTokens.slice(0, MAX_TOKENS).map(shapeToken);++ const nativePriced = Number(balances.native?.price) > 0;+ const body = {+ address,+ chain: chain === 'solana' ? 'solana' : 'ethereum',+ native: {+ symbol: balances.native?.symbol || (chain === 'solana' ? 'SOL' : 'ETH'),+ amount: balances.native?.amount ?? 0,+ usd: nativePriced ? roundUsd(balances.native?.usd) : (balances.native?.amount ? null : 0),+ },+ tokens,+ totalUsd: roundUsd(walletUsdTotal(balances)),+ tokenCount: allTokens.length,+ truncated,+ ts: new Date().toISOString(),+ sources: sourcesFor(chain),+ };+ // A stale flag from the balance layer means every live path failed and we served+ // the wallet's last-known-good snapshot — pass that honesty through to the caller.+ if (balances.stale) body.stale = true;++ // Public read, safe to CDN-cache briefly: balances move, but a 30s edge cache+ // collapses a burst of agents polling the same wallet without serving stale data.+ res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=60');+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.end(JSON.stringify(body));+});diff --git a/api/crypto/whales.js b/api/crypto/whales.jsnew file mode 100644index 000000000..b47a55359--- /dev/null+++ b/api/crypto/whales.js@@ -0,0 +1,96 @@+// GET /api/crypto/whales — FREE whale / large-buy activity for AI agents.+//+// Agent use-case: a trading or sniper agent, mid-task, wants to know if big+// money is moving into a token (or the pump.fun market broadly) BEFORE it+// commits. A whale already in = price impact ahead; no whales = thin. This is a+// free, keyless read of large buys — high signal, no account, no payment.+//+// ?mint=<spl-mint> → whale BUYS of that token (per-transaction rows)+// (omit mint) → top whale WALLETS active across pump.fun right now+// ?minSol=<n> → single-buy SOL threshold to qualify as a whale (default 5)+// ?limit=<n> → rows to return (default 10, max 25)+//+// Response: { scope, mint, whales:[{ wallet, solMoved, txHash, ts }], whaleCount,+// totalSolMoved, signal:'bullish'|'bearish'|'neutral', ts, source }. The signal+// is a deterministic net-whale-flow rule (see api/_lib/pump-whale-scan.js+// computeSignal + docs/crypto-api.md), never an LLM.+//+// Never 500 on a well-formed request: no whales over threshold → 200 empty ++// neutral; feed down → 200 empty + a `note`. A paid, coarser version of this+// data lives at api/x402/pump-agent-audit.js; this is the free, cleaner read.++import { wrap, cors, method, json, error, rateLimited, setRateLimitHeaders } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import {+ scanTokenWhales,+ scanMarketWhales,+ WHALE_MIN_SOL_DEFAULT,+ WHALE_LIMIT_DEFAULT,+ WHALE_LIMIT_MAX,+} from '../_lib/pump-whale-scan.js';++// Base58 Solana mint pubkey (same shape the pump audit endpoint validates).+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ // Public read bucket — keyless, generous, per-IP flood guard.+ const rl = await limits.publicIp(clientIp(req));+ setRateLimitHeaders(res, rl);+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const mintRaw = String(url.searchParams.get('mint') || '').trim();++ // minSol: positive number, default 5. Clamp to a sane floor so a whale is+ // always a meaningfully large buy; reject non-numeric input.+ let minSol = WHALE_MIN_SOL_DEFAULT;+ if (url.searchParams.has('minSol')) {+ const raw = Number(url.searchParams.get('minSol'));+ if (!Number.isFinite(raw) || raw <= 0) {+ return error(res, 400, 'invalid_min_sol', 'minSol must be a positive number', {+ example: '/api/crypto/whales?minSol=5',+ });+ }+ minSol = Math.max(0.1, raw);+ }++ // limit: 1..25, default 10.+ let limit = WHALE_LIMIT_DEFAULT;+ if (url.searchParams.has('limit')) {+ const raw = Number(url.searchParams.get('limit'));+ if (!Number.isFinite(raw) || raw < 1) {+ return error(res, 400, 'invalid_limit', 'limit must be a positive integer (max 25)', {+ example: '/api/crypto/whales?limit=10',+ });+ }+ limit = Math.min(WHALE_LIMIT_MAX, Math.floor(raw));+ }++ // Token scope requires a valid base58 mint; a malformed mint is a client error.+ if (mintRaw && !BASE58_RE.test(mintRaw)) {+ return error(res, 400, 'invalid_mint', 'mint must be a base58 Solana pubkey', {+ example: '/api/crypto/whales?mint=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ });+ }++ const result = mintRaw+ ? await scanTokenWhales({ mint: mintRaw, minSol, limit })+ : await scanMarketWhales({ minSol, limit });++ const { degraded, ...body } = result;+ body.minSol = minSol;+ // Feed down (no trades reachable) → 200 empty + a note, per the never-500 rule.+ if (degraded) {+ body.note =+ 'pump.fun feed is temporarily unavailable — returning an empty whale set; retry shortly';+ }++ return json(res, 200, body, {+ // Whale activity turns over fast; a short shared-edge cache collapses+ // bursts of identical polls without making the read stale.+ 'cache-control': 'public, s-maxage=15, stale-while-revalidate=45',+ });+});diff --git a/api/v1/ai/image.js b/api/v1/ai/image.jsnew file mode 100644index 000000000..79f98363a--- /dev/null+++ b/api/v1/ai/image.js@@ -0,0 +1,352 @@+// POST /api/v1/ai/image — text→image for agents, over x402.+//+// Productizes the platform's text→image lanes (api/_mcp3d/text-to-image.js:+// NVIDIA NIM FLUX, Google Vertex/Gemini image, Replicate backstop) as a single+// versioned, bazaar-discoverable endpoint with a free daily quota funnel:+//+// • First N images/day per IP are FREE (payment bypassed). ← funnel+// • Past the quota, the call falls through to x402: $0.02 USDC/image. ← revenue+//+// A generated image is persisted to R2 by the lane itself and returned as a+// durable https URL. No API key, no account — an agent can try it wallet-free,+// then pay per image once it's past the free tier.+//+// GET /api/v1/ai/image → compact discovery doc (price, quota, lanes)+// GET /api/v1/ai/image?health=1 → per-lane configured/reachable, no quota burn+// POST /api/v1/ai/image → { prompt, aspect_ratio?, seed? } → image+//+// Honest degradation: with NO image lane configured the POST returns 503+// `not_configured` naming the env vars to set (NVIDIA_API_KEY /+// GOOGLE_CLOUD_PROJECT + GCP_SERVICE_ACCOUNT_JSON / REPLICATE_API_TOKEN); it+// starts serving the moment any one of them lands.++import { paidEndpoint } from '../../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../../_lib/x402-spec.js';+import { installAccessControl } from '../../_lib/x402/access-control.js';+import { withService, declareHttpDiscovery } from '../../_lib/x402/bazaar-helpers.js';+import { priceFor } from '../../_lib/x402-prices.js';+import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { clientIp } from '../../_lib/rate-limit.js';+import { textToImage } from '../../_mcp3d/text-to-image.js';+import {+ imageLaneConfig,+ imageLaneHealth,+ missingLaneEnv,+ dimensionsFor,+ providerLabel,+ isProviderRefusal,+ refusalReason,+ SUPPORTED_ASPECT_RATIOS,+} from '../../_lib/ai-image-lanes.js';+import { peekFreeQuota, consumeFreeQuota, freePerDay } from '../../_lib/ai-image-quota.js';++const ROUTE = '/api/v1/ai/image';+const PRICE_ATOMICS = priceFor('ai-image', '20000'); // $0.02 USDC per image above quota+const MAX_PROMPT = 2000;+const MIN_PROMPT = 3;+const MAX_SEED = 4_294_967_295; // uint32 — the widest seed the flux lanes accept++// ── Bazaar discovery (uniqueness first) ──────────────────────────────────────++const DESCRIPTION =+ 'Text-to-image for agents over x402 — pay $0.02 USDC per image, no API key, ' ++ 'no account; runs on NVIDIA NIM / Google Vertex lanes. The first 5 images per ' ++ 'day per IP are free, then each image is a single on-chain USDC micropayment. ' ++ 'Returns a durable https URL to the rendered PNG/JPEG.';++const INPUT_EXAMPLE = { prompt: 'a brass owl figurine on a plain white background', aspect_ratio: '1:1' };++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['prompt'],+ properties: {+ prompt: {+ type: 'string',+ minLength: MIN_PROMPT,+ maxLength: MAX_PROMPT,+ description: 'The image description to render.',+ },+ aspect_ratio: {+ type: 'string',+ enum: [...SUPPORTED_ASPECT_RATIOS],+ default: '1:1',+ description: 'Output aspect ratio. Defaults to 1:1.',+ },+ seed: {+ type: 'integer',+ minimum: 0,+ maximum: MAX_SEED,+ description: 'Optional deterministic seed (honored on the NIM / Replicate flux lanes; ignored by Vertex/Gemini, which has no seed parameter).',+ },+ },+};++const OUTPUT_EXAMPLE = {+ url: 'https://cdn.three.ws/forge/refs/6f1c0c2e-2a4d-4b6e-9b1a-3c5d7e9f0a1b.jpg',+ provider: 'nvidia-nim',+ model: 'black-forest-labs/flux.1-schnell',+ width: 1024,+ height: 1024,+ aspect_ratio: '1:1',+ seed: null,+ free: true,+ quota: { used: 1, limit: 5, remaining: 4, resetAt: '2026-07-08T00:00:00.000Z' },+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['url', 'provider', 'width', 'height'],+ properties: {+ url: { type: 'string', format: 'uri', description: 'Durable https URL to the rendered image.' },+ provider: { type: 'string', description: 'Lane that served the image: nvidia-nim | vertex | replicate.' },+ model: { type: 'string' },+ width: { type: 'integer' },+ height: { type: 'integer' },+ aspect_ratio: { type: 'string' },+ seed: { type: ['integer', 'null'] },+ free: { type: 'boolean', description: 'True when served from the free daily quota (no payment).' },+ quota: {+ type: 'object',+ properties: {+ used: { type: 'integer' },+ limit: { type: 'integer' },+ remaining: { type: 'integer' },+ resetAt: { type: 'string', format: 'date-time' },+ },+ },+ },+};++const BAZAAR = declareHttpDiscovery({+ method: 'POST',+ bodyType: 'json',+ input: INPUT_EXAMPLE,+ inputSchema: INPUT_SCHEMA,+ output: { example: OUTPUT_EXAMPLE, schema: OUTPUT_SCHEMA },+});++// ── Handler helpers ──────────────────────────────────────────────────────────++function badRequest(code, message) {+ return Object.assign(new Error(message), { status: 400, code });+}++// Validate + normalize the request body. Throws a 400 on any client fault, so a+// paid caller is never charged for a malformed request (the throw lands before+// settlement) and a free caller never spends a quota slot on one.+function parseImageRequest(rawBody) {+ let body;+ try {+ body = JSON.parse(rawBody || '{}');+ } catch {+ throw badRequest('invalid_json', 'Request body must be valid JSON.');+ }++ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';+ if (!prompt) throw badRequest('invalid_prompt', '"prompt" is required and must be a non-empty string.');+ if (prompt.length < MIN_PROMPT) throw badRequest('invalid_prompt', `"prompt" must be at least ${MIN_PROMPT} characters.`);+ if (prompt.length > MAX_PROMPT) throw badRequest('prompt_too_long', `"prompt" must be at most ${MAX_PROMPT} characters.`);++ let aspectRatio = '1:1';+ if (body?.aspect_ratio != null) {+ aspectRatio = String(body.aspect_ratio);+ if (!SUPPORTED_ASPECT_RATIOS.includes(aspectRatio)) {+ throw badRequest('invalid_aspect_ratio', `"aspect_ratio" must be one of: ${SUPPORTED_ASPECT_RATIOS.join(', ')}.`);+ }+ }++ let seed;+ if (body?.seed != null) {+ if (!Number.isInteger(body.seed) || body.seed < 0 || body.seed > MAX_SEED) {+ throw badRequest('invalid_seed', `"seed" must be an integer between 0 and ${MAX_SEED}.`);+ }+ seed = body.seed;+ }++ return { prompt, aspectRatio, seed };+}++// Map a text-to-image lane error onto a designed HTTP status. A safety refusal+// is a terminal verdict about the prompt (422, never retried); a rate-limit /+// outage / billing failure is transient (429 / 503). The paidEndpoint wrapper+// turns any throw here into an error response WITHOUT settling, so the buyer is+// never charged for a failed generation.+function mapLaneError(err) {+ if (isProviderRefusal(err)) {+ return Object.assign(new Error(refusalReason(err)), { status: 422, code: 'content_refused' });+ }+ if (err?.code === 'unconfigured') {+ return Object.assign(+ new Error(`No image lane is configured. Set one of: ${missingLaneEnv().join(', ')}.`),+ { status: 503, code: 'not_configured' },+ );+ }+ if (err?.code === 'rate_limited') {+ const retryAfter = Number.isFinite(err.retryAfter) ? err.retryAfter : 10;+ return Object.assign(new Error('Image generation is briefly busy — retry shortly.'), {+ status: 429,+ code: 'rate_limited',+ retryAfter,+ });+ }+ if (err?.code === 'provider_unreachable' || err?.code === 'billing') {+ return Object.assign(new Error('The image lane is temporarily unavailable — retry shortly.'), {+ status: 503,+ code: 'lane_unavailable',+ });+ }+ return Object.assign(new Error(err?.message || 'Image generation failed.'), {+ status: 502,+ code: 'generation_failed',+ });+}++// Generate one image and shape the response. Shared by the free-bypass path and+// the paid path — `free` distinguishes them so the response is honest about+// whether a payment happened, and the quota slot is spent ONLY on the free path+// and ONLY after a real image is delivered.+async function generateAndRespond({ prompt, aspectRatio, seed }, { free, ip }) {+ const config = imageLaneConfig();+ if (!config.anyConfigured) {+ throw Object.assign(+ new Error(`No image lane is configured. Set one of: ${missingLaneEnv().join(', ')}.`),+ { status: 503, code: 'not_configured' },+ );+ }++ let result;+ try {+ result = await textToImage(prompt, { aspectRatio, seed });+ } catch (err) {+ throw mapLaneError(err);+ }++ const url = result?.imageUrl;+ if (!url || !/^https?:\/\//.test(url)) {+ throw Object.assign(new Error('Image lane returned no usable image URL.'), {+ status: 502,+ code: 'generation_failed',+ });+ }++ const { width, height } = dimensionsFor(aspectRatio);+ let quota = null;+ if (free) quota = await consumeFreeQuota(ip);++ return {+ url,+ provider: providerLabel(result),+ model: result.model || null,+ width,+ height,+ aspect_ratio: aspectRatio,+ seed: Number.isInteger(seed) ? seed : null,+ free: Boolean(free),+ ...(quota ? { quota } : {}),+ };+}++async function readBody(req) {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ return Buffer.concat(chunks).toString('utf8');+}++// ── Paid endpoint (free-quota funnel → x402) ─────────────────────────────────++const paidImage = paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: PRICE_ATOMICS,+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws AI Image',+ tags: ['image', 'text-to-image', 'ai', 'agent', 'solana'],+ }),+ requiredScope: 'x402:bypass',+ // Free-tier funnel: an IP still under its daily quota bypasses payment. The+ // slot is only spent AFTER a real image ships (in generateAndRespond), so a+ // validation error / refusal / outage never burns a free generation. Peek is+ // read-only and fails open, so a Redis hiccup can't wrongly demand payment.+ accessControl: installAccessControl({+ requiredScope: 'x402:bypass',+ resolveCaller: async ({ req }) => {+ const ip = clientIp(req);+ const q = await peekFreeQuota(ip);+ if (q.allowed) {+ return { grantAccess: true, reason: 'ai_image_free_daily', callerId: `ip:${ip}` };+ }+ return null;+ },+ }),++ async handler({ req, bypass }) {+ const parsed = parseImageRequest(await readBody(req));+ const free = bypass?.reason === 'ai_image_free_daily';+ return generateAndRespond(parsed, { free, ip: clientIp(req) });+ },+});++// ── GET surfaces: discovery + health (both free, no quota burn) ──────────────++const health = wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;+ const report = await imageLaneHealth();+ return json(res, report.configured ? 200 : 503, { ...report, generated_at: new Date().toISOString() });+});++const discovery = wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;+ const config = imageLaneConfig();+ return json(res, 200, {+ route: ROUTE,+ method: 'POST',+ description: DESCRIPTION,+ free_tier: { images_per_day_per_ip: freePerDay(), then: 'x402 pay-per-image' },+ price_usdc: (Number(PRICE_ATOMICS) / 1e6).toFixed(6),+ price_atomics: String(PRICE_ATOMICS),+ networks: ['solana', 'base'],+ input: INPUT_SCHEMA,+ output_example: OUTPUT_EXAMPLE,+ lanes_configured: { nim: config.nim, vertex: config.vertex, replicate: config.replicate },+ health: `${ROUTE}?health=1`,+ });+});++// Single default export multiplexes the path: GET ?health=1 → health probe,+// other GET → discovery doc, everything else → the paid POST endpoint (which+// owns CORS/method enforcement, the free-quota bypass, and the 402 challenge).+export default function handler(req, res) {+ if (req.method === 'GET') {+ let hasHealth = false;+ try {+ hasHealth = new URL(req.url, 'http://localhost').searchParams.has('health');+ } catch { /* malformed url → treat as discovery */ }+ return hasHealth ? health(req, res) : discovery(req, res);+ }++ // Honest degradation: with NO image lane configured, answer every POST with a+ // clean 503 that NAMES the env vars to set — before the payment dance, so a+ // buyer is never challenged (or charged) for a good we cannot deliver. This+ // runs here rather than inside the paid handler because a handler throw for a+ // 5xx is sanitized to a generic "internal error" by the error boundary, which+ // would hide the actionable env-var list. The moment any lane env lands, this+ // check passes and the funnel (free quota → 402) takes over unchanged.+ if (req.method === 'POST' && !imageLaneConfig().anyConfigured) {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ return error(+ res,+ 503,+ 'not_configured',+ `No image lane is configured. Set one of: ${missingLaneEnv().join(', ')}.`,+ );+ }++ return paidImage(req, res);+}diff --git a/api/v1/token/security.js b/api/v1/token/security.jsnew file mode 100644index 000000000..8e9924a06--- /dev/null+++ b/api/v1/token/security.js@@ -0,0 +1,233 @@+// GET /api/v1/token/security — free, on-chain rug/risk facts for any Solana token.+//+// The one question every trading agent asks before touching a token: "is this a+// rug?" This endpoint answers it with FACTS, not an invented score — mint/freeze+// authority status, holder concentration, liquidity depth, and pair age, composed+// into one report the agent weighs itself.+//+// Sources (all keyless / already-configured, composed — never proxied raw):+// • Solana RPC (api/_lib/solana/connection.js failover chain):+// - getAccountInfo(mint, jsonParsed) → mintAuthority, freezeAuthority,+// supply, decimals (works for both spl-token and spl-token-2022 mints).+// - getTokenLargestAccounts(mint) → top-holder concentration.+// • DexScreener (api/_lib/token-market.js `fetchTokenMarket`) → liquidity USD,+// the deepest pair's label, and its creation time.+//+// Honest degradation: each section resolves independently. A partial upstream+// failure nulls only that section and names what answered in `sources`; the call+// succeeds if ANY section resolved and returns 503 only when every source failed.+// A well-formed Solana address that no source can resolve (no on-chain mint, no+// market) returns 404. EVM `0x…` input returns 400 — this endpoint is Solana-only.++import { defineEndpoint, fail } from '../../_lib/gateway.js';+import { rateLimited } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import { isValidSolanaAddress, isValidEvmAddress } from '../../_lib/validate.js';+import { fetchTokenMarket } from '../../_lib/token-market.js';+import { solanaRpcEndpoints, makeRotatingFetch } from '../../_lib/solana/connection.js';++const RPC_TIMEOUT_MS = 8000;+const DAY_MS = 86_400_000;++// One JSON-RPC call across the platform's failover chain. Resolves with the raw+// `{ result }` / `{ error }` envelope (a JSON-RPC error like "not a Token mint" is+// a soft "this section has no data", not a transport failure) and rejects only+// when every endpoint in the chain is down — which is how the caller tells an+// answered-but-empty source (→ degrade / 404) from a genuinely failed one (→ 503).+async function rpcCall(rpcFetch, method, params) {+ const resp = await rpcFetch(null, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ signal: AbortSignal.timeout(RPC_TIMEOUT_MS),+ });+ return resp.json();+}++// Round a base-unit part/total ratio to a 2-decimal percentage. Number() on the+// raw base-unit strings is exact enough for a percentage (supply tops out around+// 1e15, well under 2^53), and 2-decimal rounding absorbs any low-digit drift.+function pctOf(part, total) {+ if (!total || !Number.isFinite(total) || total <= 0) return null;+ const p = Number(part);+ if (!Number.isFinite(p)) return null;+ return Math.round((p / total) * 10000) / 100;+}++// Parse a getAccountInfo(jsonParsed) result into the authority/supply/decimals+// section. Returns null when the account isn't an initialized SPL/-2022 mint —+// either it doesn't exist (value === null) or it's some other account type. In+// SPL, a null authority means it was revoked (nobody can mint/freeze anymore).+export function parseMintAccount(result) {+ const value = result?.value;+ if (!value) return null;+ const parsed = value.data?.parsed;+ if (!parsed || parsed.type !== 'mint') return null;+ const info = parsed.info || {};+ const mintAuth = info.mintAuthority ?? null;+ const freezeAuth = info.freezeAuthority ?? null;+ return {+ mint_authority: { revoked: mintAuth === null, address: mintAuth },+ freeze_authority: { revoked: freezeAuth === null, address: freezeAuth },+ supply: typeof info.supply === 'string' ? info.supply : (info.supply ?? null),+ decimals: Number.isInteger(info.decimals) ? info.decimals : null,+ };+}++// Parse getTokenLargestAccounts + the mint supply into a concentration section.+// getTokenLargestAccounts returns up to the 20 largest token accounts; we report+// the cumulative share of the top 1 / 5 / 10 against total supply, and how many+// accounts we sampled. Percentages are null when supply is unknown (can't divide)+// but holders_sampled is still reported — an honest partial.+export function parseTopHolders(accounts, supplyRaw) {+ if (!Array.isArray(accounts) || accounts.length === 0) return null;+ const total = supplyRaw != null ? Number(supplyRaw) : null;+ const amt = (n) => accounts.slice(0, n).reduce((s, a) => s + Number(a?.amount || 0), 0);+ return {+ top1_pct: total ? pctOf(accounts[0]?.amount, total) : null,+ top5_pct: total ? pctOf(amt(5), total) : null,+ top10_pct: total ? pctOf(amt(10), total) : null,+ holders_sampled: accounts.length,+ };+}++// Project a fetchTokenMarket() result onto the liquidity section. null when the+// token has no indexed pair (DexScreener returned nothing).+export function parseLiquidity(market) {+ if (!market) return null;+ return {+ usd: market.liquidity_usd ?? null,+ largest_pair: market.pair_label ?? null,+ pair_created_at: market.pair_created_at ?? null,+ };+}++// Derive the factual flags. Every flag is a hard, observable condition — never a+// judgement — and is emitted ONLY when its inputs are present, so a null section+// never fabricates (or silently suppresses a real) signal.+export function buildFlags({ mint, holders, liquidity }, now) {+ const flags = [];+ if (mint) {+ if (mint.mint_authority.revoked === false) flags.push('mint_authority_active');+ if (mint.freeze_authority.revoked === false) flags.push('freeze_authority_active');+ }+ if (holders) {+ if (holders.top1_pct != null && holders.top1_pct > 20) flags.push('top1_holder_over_20pct');+ if (holders.top10_pct != null && holders.top10_pct > 80) flags.push('top10_holders_over_80pct');+ }+ if (liquidity) {+ if (liquidity.usd != null && liquidity.usd < 10_000) flags.push('liquidity_under_10k');+ if (liquidity.pair_created_at != null && now - liquidity.pair_created_at < DAY_MS) {+ flags.push('pair_younger_than_24h');+ }+ }+ return flags;+}++/**+ * Compose the full security report from the (already-resolved) upstream inputs.+ * Pure + exported so every section, flag, and the sources array can be pinned in+ * tests against captured real shapes without touching the network.+ *+ * @param {object} args+ * @param {string} args.address+ * @param {{ answered: boolean, result?: any }} args.account getAccountInfo outcome+ * @param {{ answered: boolean, result?: any }} args.largest getTokenLargestAccounts outcome+ * @param {{ answered: boolean, data?: any }} args.market fetchTokenMarket outcome+ * @param {number} [now]+ * @returns {{ resolved: boolean, allFailed: boolean, body: object }}+ */+export function buildSecurityReport({ address, account, largest, market }, now = Date.now()) {+ const mint = account.answered ? parseMintAccount(account.result) : null;+ const holders = largest.answered+ ? parseTopHolders(largest.result?.value, mint?.supply)+ : null;+ const liquidity = market.answered ? parseLiquidity(market.data) : null;++ const sources = [];+ if (mint || holders) sources.push('solana-rpc');+ if (liquidity) sources.push('dexscreener');++ const flags = buildFlags({ mint, holders, liquidity }, now);++ const body = {+ address,+ chain: 'solana',+ mint_authority: mint ? mint.mint_authority : { revoked: null, address: null },+ freeze_authority: mint ? mint.freeze_authority : { revoked: null, address: null },+ supply: mint ? mint.supply : null,+ decimals: mint ? mint.decimals : null,+ top_holders: holders || {+ top1_pct: null,+ top5_pct: null,+ top10_pct: null,+ holders_sampled: null,+ },+ liquidity: liquidity || { usd: null, largest_pair: null, pair_created_at: null },+ flags,+ sources,+ ts: now,+ };++ return {+ resolved: Boolean(mint || holders || liquidity),+ allFailed: !account.answered && !largest.answered && !market.answered,+ body,+ };+}++export default defineEndpoint({+ name: 'v1.token.security',+ method: 'GET',+ auth: 'public',+ handler: async ({ res, query, ip }) => {+ const address = typeof query.address === 'string' ? query.address.trim() : '';+ if (!address) fail(400, 'validation_error', '"address" query parameter is required');++ // EVM is a deliberate, honest 400 rather than a half-built passthrough: the+ // on-chain facts here (SPL mint/freeze authority, getTokenLargestAccounts) are+ // Solana concepts with no EVM equivalent in this reader.+ if (isValidEvmAddress(address)) {+ fail(400, 'unsupported_chain', 'this endpoint checks Solana tokens only (for now) — pass a base58 Solana mint address, not an EVM 0x… address');+ }+ if (!isValidSolanaAddress(address)) {+ fail(400, 'validation_error', '"address" must be a base58 Solana mint address');+ }++ // Public, keyless per-IP quota on top of the gateway's shared budget: the RPC+ // + DexScreener reads are cheap and edge-cached, but this caps a scripted+ // enumeration flood against the shared upstreams.+ const rl = await limits.tokenSecurityIp(ip);+ if (!rl.success) {+ return rateLimited(res, rl, 'token security checks are capped at 20/min per IP');+ }++ const rpcFetch = makeRotatingFetch(solanaRpcEndpoints('mainnet'));+ const [acct, largest, mkt] = await Promise.allSettled([+ rpcCall(rpcFetch, 'getAccountInfo', [address, { encoding: 'jsonParsed', commitment: 'confirmed' }]),+ rpcCall(rpcFetch, 'getTokenLargestAccounts', [address, { commitment: 'confirmed' }]),+ fetchTokenMarket(address),+ ]);++ const { resolved, allFailed, body } = buildSecurityReport({+ address,+ account: { answered: acct.status === 'fulfilled', result: acct.value?.result },+ largest: { answered: largest.status === 'fulfilled', result: largest.value?.result },+ market: { answered: mkt.status === 'fulfilled', data: mkt.value },+ });++ if (resolved) {+ // Public, cacheable read — 60s at the edge. Set before returning so the+ // gateway's secure-by-default no-store doesn't override it.+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=60, stale-while-revalidate=30');+ return body;+ }++ // Nothing resolved: distinguish "every source failed" (transient — retry)+ // from "sources answered but this isn't a resolvable token" (client input).+ if (allFailed) {+ fail(503, 'sources_unavailable', 'token security sources are unavailable right now — retry shortly');+ }+ fail(404, 'not_found', 'no on-chain mint or market could be resolved for this address — check the mint');+ },+});diff --git a/api/wk.js b/api/wk.jsindex 551e77ba1..fbc0e2905 100644--- a/api/wk.js+++ b/api/wk.js@@ -900,21 +900,27 @@ const REST_OUTPUT_EXAMPLES = Object.freeze({checked_at: '2026-06-28T00:00:00Z',},'/api/x402/agent-reputation': {- agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',- name: 'Helios',- wallet_address: 'AgEntWa11etExamp1eDoNotUse111111111111111111',- deployed_mints: 2,- payments: {- confirmed_count: 142,- confirmed_amount_atomics: '142000000',- distinct_payers: 87,- failed_count: 3,- failure_rate: 0.021,+ subject: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ subjectType: 'solana_mint',+ score: 71,+ tier: 'high',+ signals: {+ dimensions: {+ activity: { available: true, weight: 25, norm: 0.62, points: 16, value: 124 },+ age: { available: true, weight: 15, norm: 0.48, points: 7, days: 176 },+ counterparties: { available: true, weight: 15, norm: 0.72, points: 11, value: 18 },+ holdings: { available: true, weight: 10, norm: 1, points: 10, usd: 412000 },+ reliability: { available: true, weight: 15, norm: 0.98, points: 15, failure_rate: 0.02 },+ attestations: { available: true, weight: 20, norm: 0.6, points: 12, count: 6, avg_feedback: null },+ },+ weight_considered: 100,},- distributions: { confirmed: 12, failed: 1, success_rate: 0.923 },- buybacks: { confirmed: 5, failed: 0, total_burn_atomics: '500000000' },- attestations: { feedback_count: 14, validation_count: 8 },- indexed_at: '2026-05-14T17:00:00Z',+ evidence: [+ { kind: 'solana_token', ref: 'https://solscan.io/token/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' },+ { kind: 'threews_agent', ref: '/agent/7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55' },+ ],+ caveats: [],+ ts: '2026-07-07T00:00:00Z',},'/api/x402/agent-bouncer': {ok: true,@@ -941,17 +947,23 @@ const REST_OUTPUT_EXAMPLES = Object.freeze({fetchedAt: '2026-06-22T17:00:00.000Z',},'/api/x402/onchain-identity-verify': {- agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',- chain: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',- contract_or_mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',- verified: true,- evidence: {- family: 'solana',- tx_hash: '4kHTPp9ExampleSignatureDoNotUse...',- wallet: 'AgEntWa11etExamp1eDoNotUse111111111111111111',- confirmed_at: '2026-04-30T14:08:22Z',+ claim: {+ identity: 'vitalik.eth',+ address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',+ chain: 'eip155:1',},- indexed_at: '2026-05-14T17:00:00Z',+ identity_type: 'ens',+ verified: true,+ method: 'ens-resolution',+ evidence: [+ {+ kind: 'ens_forward_resolution',+ ref: 'vitalik.eth',+ detail: 'resolves to 0xd8da6bf26964af9d7eed9e03e53415d37aa96045',+ },+ ],+ caveats: [],+ ts: '2026-07-07T00:00:00.000Z',},'/api/x402/pump-agent-audit': {mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',@@ -1030,12 +1042,17 @@ const REST_OUTPUT_EXAMPLES = Object.freeze({suffix: null,ignoreCase: false,format: 'keypair',- secretKeyBase58: 'Hy5pQqgExampleSecretDoNotUse...',+ secretKeyBase58: '<example only — the live endpoint returns the ground secret key here>',+ mnemonic: null,+ wordCount: null,+ derivationPath: null,attempts: 160,durationMs: 6,expectedAttempts: 58,network: 'solana',explorerUrl: 'https://solscan.io/account/SoEXAMPLEdoNotUse1111111111111111111111111111',+ verifyUrl: 'https://three.ws/vanity/verify',+ serviceKeyUrl: 'https://three.ws/.well-known/three-vanity.json',},'/api/x402/vanity-verifiable': {protocol: 'three-vanity/v1',@@ -1052,6 +1069,21 @@ const REST_OUTPUT_EXAMPLES = Object.freeze({verifyUrl: 'https://three.ws/vanity/verify',serviceKeyUrl: 'https://three.ws/.well-known/three-vanity.json',},+ '/api/x402/vanity-premium': {+ address: 'PUMPEXAMPLEdoNotUse1111111111111111111111111',+ prefix: 'PUMP',+ suffix: null,+ patternLabel: 'PUMP…',+ rarityTier: 'rare',+ format: 'keypair',+ priceUsd: 12,+ secretKeyBase58: '<delivered once — ciphertext destroyed on delivery>',+ delivery: 'once',+ network: 'solana',+ explorerUrl: 'https://solscan.io/account/PUMPEXAMPLEdoNotUse1111111111111111111111111',+ custodyNotice:+ 'Platform-generated key delivered once — use as a token mint or sweep to self-generated custody, not as a treasury.',+ },'/api/x402/mint-to-mesh-batch': {count: 2,results: [@@ -1454,8 +1486,8 @@ async function handleX402Discovery(req, res) {tags: ['mcp', '3d', 'gltf', 'solana', 'agent'],}),agentReputation: withService({- serviceName: 'three.ws Agent Reputation',- tags: ['reputation', 'agent', 'solana', 'attestation', 'trust'],+ serviceName: 'Cross-chain Agent Reputation',+ tags: ['reputation', 'trust', 'cross-chain', 'agent', 'x402'],}),agentBouncer: withService({serviceName: 'three.ws Agent Bouncer',@@ -1493,6 +1525,10 @@ async function handleX402Discovery(req, res) {serviceName: 'three.ws Provable Vanity Grinder',tags: ['solana', 'vanity', 'keypair', 'wallet', 'verifiable', 'commit-reveal'],}),+ vanityPremium: withService({+ serviceName: 'three.ws Premium Vanity',+ tags: ['solana', 'vanity', 'wallet', 'address', 'premium'],+ }),permit2Demo: withService({serviceName: 'three.ws Permit2 Demo',tags: ['x402', 'permit2', 'eip2612', 'gasless', 'demo'],@@ -1579,6 +1615,7 @@ async function handleX402Discovery(req, res) {}),pipelineRembg: withService({serviceName: 'three.ws Pipeline - RemBG',+ tags: ['image', 'rembg', 'cutout', 'segmentation', 'pipeline'],}),billboard: withService({serviceName: 'three.ws Coin-World Billboard',@@ -1852,7 +1889,7 @@ async function handleX402Discovery(req, res) {url,method: 'GET',description:- "Agent Reputation — return a reputation snapshot for a three.ws agent (USDC paid in to its pump-agent tokens, distinct payers, deployed mints, distribution success rate, Solana attestation counts). Built from three.ws's proprietary index of pump_agent_payments, pump_distribute_runs, and solana_attestations.",+ 'Cross-chain Agent Reputation — get a deterministic 0–100 trust score for ANY counterparty (Solana wallet, EVM wallet, pump.fun mint, ERC-8004 agent id, or three.ws agent_id — auto-detected) before you pay, trade, or delegate to it. Scored from real on-chain evidence: transaction history, age, distinct counterparties, holdings, settlement reliability, prior settled agent payments, and ERC-8004 feedback. Unknown subjects return score:null, not a fabricated score.',mimeType: 'application/json',serviceName: routeMeta.agentReputation.serviceName,tags: routeMeta.agentReputation.tags,@@ -1861,11 +1898,14 @@ async function handleX402Discovery(req, res) {extensions: extensionsForAccepts(accepts, {method: 'GET',discoverable: true,- input: { agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55' },+ input: { subject: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' },inputSchema: {type: 'object',- required: ['agent_id'],- properties: { agent_id: { type: 'string', format: 'uuid' } },+ required: ['subject'],+ properties: {+ subject: { type: 'string' },+ chain: { type: ['integer', 'string'] },+ },},}),};@@ -1916,7 +1956,7 @@ async function handleX402Discovery(req, res) {url,method: 'GET',description:- 'On-Chain Identity Verifier — given a three.ws agent_id + CAIP-2 chain + contract/mint, verify ownership from the canonical meta.onchain index and return tx_hash/wallet/deploy time evidence when verified. Trust primitive before paying counterparty agents.',+ 'Cross-platform On-Chain Identity Verifier — prove any claim that an identity controls an address. `identity` can be an ENS name, an SNS (.sol) name, an EVM or Solana wallet, an ERC-8004 agent id, or a three.ws agent_id; `address` is the contract/mint/wallet it claims. Returns on-chain evidence (deploy tx + deployer, mint/update authority, ENS/SNS resolution, ERC-8004 registration, three.ws deploy record) with verified true/false/unverifiable. Trust primitive before paying counterparty agents.',mimeType: 'application/json',serviceName: routeMeta.onchainIdentity.serviceName,tags: routeMeta.onchainIdentity.tags,@@ -1926,17 +1966,24 @@ async function handleX402Discovery(req, res) {method: 'GET',discoverable: true,input: {- agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',- chain: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',- contract_or_mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',+ identity: 'vitalik.eth',+ address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',+ chain: 'eip155:1',},inputSchema: {type: 'object',- required: ['agent_id', 'chain', 'contract_or_mint'],+ required: ['identity', 'address'],properties: {- agent_id: { type: 'string', format: 'uuid' },- chain: { type: 'string', description: 'CAIP-2 chain ID' },- contract_or_mint: { type: 'string' },+ identity: {+ type: 'string',+ description:+ 'ENS/SNS name, EVM/Solana wallet, ERC-8004 id (eip155:8453:42), or three.ws agent_id (uuid)',+ },+ address: {+ type: 'string',+ description: 'the contract/mint/wallet the identity claims to control',+ },+ chain: { type: 'string', description: 'optional CAIP-2 chain hint' },},},}),@@ -1978,7 +2025,7 @@ async function handleX402Discovery(req, res) {url,method: 'POST',description:- 'Pump Launcher — deploy a brand-new pump.fun token in one paid call. Supply name + symbol and either a pre-pinned metadataUri or an imageUrl (we pin the image + descriptor to pump.fun IPFS). The server fronts the SOL deploy cost and signs the create-coin tx, so the buyer needs no SOL and no account. Creator rewards accrue to any Solana wallet you nominate; optional vanity prefix/suffix grinds a custom mint address. Returns mint + tx signature + pump.fun URL.',+ 'Pump Launcher — launch a pump.fun token autonomously in one paid call: no SOL, no wallet, no account. You pay USDC; the server fronts the ~0.022 SOL deploy cost, optionally grinds a vanity mint, and signs the bonding-curve create tx. Supply name + symbol and either a pre-pinned metadataUri or an imageUrl (we pin the image + descriptor to pump.fun IPFS). Creator rewards accrue to any Solana wallet you nominate; optional vanity prefix/suffix brands the mint address. Funnel: check the ticker is free first with the FREE GET /api/crypto/symbol, then confirm the deploy on the FREE GET /api/crypto/launches feed. Returns mint + tx signature + metadataUri + pump.fun URL.',mimeType: 'application/json',serviceName: routeMeta.pumpLaunch.serviceName,tags: routeMeta.pumpLaunch.tags,@@ -1996,15 +2043,20 @@ async function handleX402Discovery(req, res) {inputSchema: {type: 'object',required: ['name', 'symbol'],+ oneOf: [{ required: ['metadataUri'] }, { required: ['imageUrl'] }],properties: {- name: { type: 'string', maxLength: 32 },- symbol: { type: 'string', maxLength: 10 },+ name: { type: 'string', minLength: 1, maxLength: 32 },+ symbol: { type: 'string', minLength: 1, maxLength: 10 },metadataUri: { type: 'string', maxLength: 2048 },imageUrl: { type: 'string', maxLength: 2048 },description: { type: 'string', maxLength: 2000 },+ twitter: { type: 'string', maxLength: 2048 },+ telegram: { type: 'string', maxLength: 2048 },+ website: { type: 'string', maxLength: 2048 },creator: { type: 'string', minLength: 32, maxLength: 44 },vanityPrefix: { type: 'string', maxLength: 5 },vanitySuffix: { type: 'string', maxLength: 5 },+ vanityIgnoreCase: { type: 'boolean' },},},}),@@ -2104,7 +2156,7 @@ async function handleX402Discovery(req, res) {url,method: 'GET',description:- 'Vanity Grinder — generate a brand-new Solana keypair whose Base58 address starts with a chosen prefix and/or ends with a chosen suffix. Returns the public address and its secret key (Base58 + 64-byte array) so it imports into any Solana wallet. Ground fresh per request in a Rust/WASM ed25519 engine and never stored. Difficulty-tiered price ($0.01 for 1 char, $0.05 for 2, $0.25 for 3); combined pattern capped at 3 Base58 characters. Settlement runs only after a successful grind, so an exhausted budget costs nothing.',+ 'Vanity Grinder — put your brand on-chain: get a Solana address that starts with your ticker/prefix and/or ends with a chosen suffix, for a branded token MINT address, a recognizable agent/treasury wallet, or any wallet identifiable at a glance. The server grinds a brand-new keypair to match (no wallet, account, or SOL needed) and never stores it — the secret is served once over TLS and stripped from the replay cache. format=keypair (default) returns the address + secret key (Base58 + 64-byte array) importable into any Solana wallet, capped at 3 Base58 chars, priced $0.01 (1 char) / $0.05 (2) / $0.25 (3). format=mnemonic returns a BIP-39 seed phrase (12/24 words) whose derived key lands on the address, capped at 2 chars (~100× slower), priced $0.05 / $0.50. Optional sealTo=<X25519 pubkey> ECIES-seals the secret to you so plaintext never appears in the response or any log. Settlement runs only after a successful grind, so an exhausted budget costs nothing. Keyless — no API keys, no accounts.',mimeType: 'application/json',serviceName: routeMeta.vanity.serviceName,tags: routeMeta.vanity.tags,@@ -2113,7 +2165,7 @@ async function handleX402Discovery(req, res) {extensions: extensionsForAccepts(accepts, {method: 'GET',discoverable: true,- input: { prefix: 'So', suffix: '', ignoreCase: '0' },+ input: { prefix: 'So', suffix: '', ignoreCase: '0', format: 'keypair' },inputSchema: {type: 'object',anyOf: [{ required: ['prefix'] }, { required: ['suffix'] }],@@ -2122,13 +2174,13 @@ async function handleX402Discovery(req, res) {type: 'string',maxLength: 3,description:- 'Base58 characters the address must start with (excludes 0, O, I, l). Combined with suffix, max 3.',+ 'Base58 characters the address must start with (excludes 0, O, I, l). Combined with suffix, max 3 (keypair) or 2 (mnemonic).',},suffix: {type: 'string',maxLength: 3,description:- 'Base58 characters the address must end with. Combined with prefix, max 3.',+ 'Base58 characters the address must end with. Combined with prefix, max 3 (keypair) or 2 (mnemonic).',},ignoreCase: {type: 'string',@@ -2136,6 +2188,23 @@ async function handleX402Discovery(req, res) {description:'When 1/true, match case-insensitively (faster, less specific).',},+ format: {+ type: 'string',+ enum: ['keypair', 'mnemonic'],+ description:+ 'keypair (default): raw 64-byte Ed25519 secret key, up to 3 chars, $0.01–$0.25. mnemonic: BIP-39 seed phrase importable into any wallet, up to 2 chars, $0.05–$0.50.',+ },+ strength: {+ type: 'string',+ enum: ['128', '256'],+ description:+ 'Mnemonic mode only. 128 → 12 words (default), 256 → 24 words. Ignored for keypair.',+ },+ sealTo: {+ type: 'string',+ description:+ 'Optional. Your 32-byte X25519 public key (Base58/Base64url/hex). When set, the secret is ECIES-sealed to it and the plaintext is omitted from the response.',+ },},},}),@@ -2195,6 +2264,48 @@ async function handleX402Discovery(req, res) {}),};})(),+ (() => {+ // Premium vanity inventory: buy a PRE-GROUND long (4–5+ char)+ // brandable address from stock, delivered instantly once. Price+ // scales per item ($1–$50); the catalog advertises the $1 floor tier+ // ('1000000') while the live 402 quotes the exact price for the+ // requested address. Distinct from /api/x402/vanity (live <=3-char+ // grind) — this tier sells addresses too rare to grind on demand.+ const url = `${origin}/api/x402/vanity-premium`;+ const accepts = acceptsForPrice('1000000', url);+ return {+ path: '/api/x402/vanity-premium',+ url,+ method: 'GET',+ description:+ 'Premium Vanity Inventory — buy a PRE-GROUND Solana address with a long (4–5+ char) brandable prefix, delivered instantly from stock. Browse available patterns and prices with a plain GET; buy one with GET ?address=<base58> via x402 (USDC on Base or Solana). Price scales with grind difficulty ($1–$50). The key is delivered exactly ONCE and its stored ciphertext is destroyed on delivery (delete-after-reveal). Optional sealTo=<X25519 public key> seals the key to you so plaintext never appears in the response. CUSTODY: keys are platform-generated — use one as a token MINT address or sweep assets to self-generated custody, not as a long-term treasury. Distinct from the live /api/x402/vanity grinder (fresh <=3-char keypair per request) — this tier sells rarer addresses too slow to grind on demand.',+ mimeType: 'application/json',+ serviceName: routeMeta.vanityPremium.serviceName,+ tags: routeMeta.vanityPremium.tags,+ iconUrl: routeMeta.vanityPremium.iconUrl,+ accepts,+ extensions: extensionsForAccepts(accepts, {+ method: 'GET',+ discoverable: true,+ input: { address: '<base58 from the listing>' },+ inputSchema: {+ type: 'object',+ properties: {+ address: {+ type: 'string',+ description:+ 'A Base58 address from the premium inventory listing (GET with no address to browse). Buys that exact pre-ground address.',+ },+ sealTo: {+ type: 'string',+ description:+ 'Optional. Your 32-byte X25519 public key (Base58/Base64url/hex) to receive the key ECIES-sealed — plaintext never appears in the response.',+ },+ },+ },+ }),+ };+ })(),(() => {// Permit2-only demo: skip the EIP-3009 entry that acceptsForPrice// would push first, so SDK clients are forced through the gaslessdiff --git a/api/x402/agent-reputation.js b/api/x402/agent-reputation.jsindex 8cfc7d909..530a037ed 100644--- a/api/x402/agent-reputation.js+++ b/api/x402/agent-reputation.js@@ -1,27 +1,40 @@-// GET /api/x402/agent-reputation?agent_id=<uuid>+// GET /api/x402/agent-reputation?subject=<any identifier>//-// Paid endpoint cataloged by the CDP x402 Bazaar. For $0.01 USDC the server-// returns a reputation snapshot for a three.ws agent: total USDC paid in-// to its pump-agent tokens, distinct payer wallets, deployed mint count,-// distribution success rate, and Solana attestation counts.+// Cross-chain agent trust primitive, cataloged by the CDP x402 Bazaar. For $0.01+// USDC the server returns a deterministic 0–100 trust score for ANY counterparty+// an agent is about to transact with — regardless of which platform it was minted+// on. Pass a Solana wallet, an EVM wallet, a pump.fun mint, an ERC-8004 agent id,+// or a three.ws agent_id; the type is auto-detected and scored from the real+// on-chain evidence available for it.+//+// The use-case (a genuine pre-transaction primitive): before Agent A pays, trades,+// or delegates to Agent B, it calls this once to get B's trust score, tier, and+// the underlying evidence. Score is built from settled on-chain signals —+// transaction history, account age, distinct counterparties, holdings, settlement+// reliability, prior settled agent payments, and ERC-8004 feedback — never a+// subjective rating. Unknown/unscannable subjects return score:null, tier:'unknown'+// with an explicit caveat rather than a fabricated number.//// Why this is defensible: three.ws indexes every pump.fun agent-payments-// acceptPayment call (pump_agent_payments), every distributePayments cron-// run (pump_distribute_runs), and every signed Solana memo attestation-// (solana_attestations) for agents that registered through us. No other-// service has this combined index, so reputation queries here are the-// canonical source for any AI agent vetting a three.ws-registered agent.+// acceptPayment call (pump_agent_payments), every distributePayments cron run+// (pump_distribute_runs), and every signed Solana memo attestation+// (solana_attestations), and reads the ERC-8004 reputation registry and live+// Solana/EVM chain state on demand — one endpoint that scores across all of them.import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';-import { isUuid } from '../_lib/validate.js';-// Shared with /api/x402/agent-bouncer so the raw reputation snapshot and the-// admit/refuse verdict are computed from one source of truth.+// The generalized any-subject engine — auto-detect + deterministic scoring.+import {+ loadSubjectReputation,+ scoreSubjectBatch,+ SUBJECT_TYPES,+} from '../_lib/trust/subject-reputation.js';+// Sweep / leaderboard / decay operate over the three.ws indexed active-agent set —+// the only globally-sweepable subject universe we maintain.import {- loadAgentReputation,sweepAgentReputation,leaderboardAgentReputation,decayReportAgentReputation,@@ -31,117 +44,105 @@ import {const ROUTE = '/api/x402/agent-reputation';const DESCRIPTION =- 'three.ws Agent Reputation — given a three.ws agent_id, return a reputation ' +- 'snapshot synthesized from on-chain pump.fun agent-payments activity, ' +- 'distribute/buyback success history, and signed Solana memo attestations. ' +- 'Use to vet a counterparty before paying, trading, or composing skills. ' +- 'Reputation is built from real on-chain data three.ws indexes — not a ' +- 'subjective score. Pay-per-call in USDC on Base or Solana mainnet.';+ 'Cross-chain Agent Reputation — pay $0.01 USDC to get a deterministic 0–100 ' ++ 'trust score for ANY counterparty before you pay, trade, or delegate to it. ' ++ 'Accepts a Solana wallet, an EVM wallet, a pump.fun mint, an ERC-8004 agent id, ' ++ 'or a three.ws agent_id (auto-detected). Scored from real on-chain evidence — ' ++ 'transaction history, age, distinct counterparties, holdings, settlement ' ++ 'reliability, prior settled agent payments, and ERC-8004 feedback — with the ' ++ 'evidence and caveats returned. Unknown subjects return score:null, not a fake ' ++ 'score. Pay-per-call in USDC on Base or Solana mainnet.';-const INPUT_EXAMPLE = { agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55' };+const INPUT_EXAMPLE = { subject: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' };const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',- required: ['agent_id'],+ required: ['subject'],properties: {- agent_id: {+ subject: {type: 'string',- format: 'uuid',- description: 'three.ws agent_id (UUID). Returned by /api/agents and /api/agent-page.',+ description:+ 'Any counterparty identifier: a Solana wallet or mint, an EVM 0x address, ' ++ 'an ERC-8004 agent id (bare integer or erc8004:<chainId>:<id>), or a ' ++ 'three.ws agent_id (UUID). Type is auto-detected.',+ },+ chain: {+ type: ['integer', 'string'],+ description: 'EVM chain id for a bare EVM address or ERC-8004 agent id (default 8453 / Base).',},},};const OUTPUT_EXAMPLE = {- agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',- name: 'Helios',- wallet_address: 'THREEsynthetic1111111111111111111111111PayTo',- deployed_mints: 2,- mints: [- { mint: 'C3vQ...', network: 'mainnet', symbol: 'HELIO' },- { mint: 'F7kX...', network: 'mainnet', symbol: 'SUNUP' },- ],- payments: {- confirmed_count: 142,- confirmed_amount_atomics: '142000000',- distinct_payers: 87,- failed_count: 3,- failure_rate: 0.021,- },- distributions: {- confirmed: 12,- failed: 1,- success_rate: 0.923,- },- buybacks: {- confirmed: 5,- failed: 0,- total_burn_atomics: '500000000',+ subject: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ subjectType: 'solana_mint',+ score: 71,+ tier: 'high',+ signals: {+ dimensions: {+ activity: { available: true, weight: 25, norm: 0.62, points: 16, value: 124 },+ age: { available: true, weight: 15, norm: 0.48, points: 7, days: 176 },+ counterparties: { available: true, weight: 15, norm: 0.72, points: 11, value: 18 },+ holdings: { available: true, weight: 10, norm: 1, points: 10, usd: 412000 },+ reliability: { available: true, weight: 15, norm: 0.98, points: 15, failure_rate: 0.02 },+ attestations: { available: true, weight: 20, norm: 0.6, points: 12, count: 6, avg_feedback: null },+ },+ weight_considered: 100,},- attestations: {- feedback_count: 14,- validation_count: 8,- latest_attested_at: '2026-05-12T08:21:00Z',+ evidence: [+ { kind: 'solana_token', ref: 'https://solscan.io/token/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' },+ { kind: 'threews_agent', ref: '/agent/7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55' },+ ],+ caveats: [],+ ts: '2026-07-07T00:00:00Z',+};++const DIMENSION_SCHEMA = {+ type: 'object',+ properties: {+ available: { type: 'boolean' },+ weight: { type: 'number' },+ norm: { type: ['number', 'null'] },+ points: { type: 'number' },},- indexed_at: '2026-05-14T17:00:00Z',};const OUTPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',- required: ['agent_id', 'deployed_mints', 'payments', 'distributions', 'buybacks', 'attestations'],+ required: ['subject', 'subjectType', 'score', 'tier', 'signals', 'evidence', 'caveats', 'ts'],properties: {- agent_id: { type: 'string', format: 'uuid' },- name: { type: ['string', 'null'] },- wallet_address: { type: ['string', 'null'] },- deployed_mints: { type: 'integer', minimum: 0 },- mints: {- type: 'array',- items: {- type: 'object',- properties: {- mint: { type: 'string' },- network: { type: 'string' },- symbol: { type: ['string', 'null'] },- },- },- },- payments: {- type: 'object',- properties: {- confirmed_count: { type: 'integer' },- confirmed_amount_atomics: { type: 'string' },- distinct_payers: { type: 'integer' },- failed_count: { type: 'integer' },- failure_rate: { type: 'number' },- },- },- distributions: {+ subject: { type: 'string' },+ subjectType: { type: 'string', enum: SUBJECT_TYPES },+ score: { type: ['integer', 'null'], minimum: 0, maximum: 100 },+ tier: { type: 'string', enum: ['unknown', 'low', 'medium', 'high', 'elite'] },+ signals: {type: 'object',properties: {- confirmed: { type: 'integer' },- failed: { type: 'integer' },- success_rate: { type: 'number' },- },- },- buybacks: {- type: 'object',- properties: {- confirmed: { type: 'integer' },- failed: { type: 'integer' },- total_burn_atomics: { type: 'string' },+ dimensions: {+ type: 'object',+ properties: {+ activity: DIMENSION_SCHEMA,+ age: DIMENSION_SCHEMA,+ counterparties: DIMENSION_SCHEMA,+ holdings: DIMENSION_SCHEMA,+ reliability: DIMENSION_SCHEMA,+ attestations: DIMENSION_SCHEMA,+ },+ },+ weight_considered: { type: 'number' },},},- attestations: {- type: 'object',- properties: {- feedback_count: { type: 'integer' },- validation_count: { type: 'integer' },- latest_attested_at: { type: ['string', 'null'] },+ evidence: {+ type: 'array',+ items: {+ type: 'object',+ properties: { kind: { type: 'string' }, ref: { type: 'string' } },},},- indexed_at: { type: 'string', format: 'date-time' },+ caveats: { type: 'array', items: { type: 'string' } },+ ts: { type: 'string', format: 'date-time' },},};@@ -170,8 +171,8 @@ const singleEndpoint = paidEndpoint({description: DESCRIPTION,bazaar: BAZAAR,service: withService({- serviceName: 'three.ws Agent Reputation',- tags: ['reputation', 'agent', 'solana', 'attestation', 'trust'],+ serviceName: 'Cross-chain Agent Reputation',+ tags: ['reputation', 'trust', 'cross-chain', 'agent', 'x402'],}),requiredScope: 'x402:bypass',accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),@@ -184,20 +185,16 @@ const singleEndpoint = paidEndpoint({siwx: true,},async handler({ req }) {- const agentId = String(req.query?.agent_id || '').trim().toLowerCase();- if (!agentId) {- const err = new Error('query param "agent_id" is required');- err.status = 400;- err.code = 'missing_agent_id';- throw err;- }- if (!isUuid(agentId)) {- const err = new Error('agent_id must be a UUID');+ // Accept any counterparty identifier. `subject` is canonical; `agent_id` is+ // kept as an alias so existing three.ws-agent callers don't break.+ const subject = String(req.query?.subject || req.query?.agent_id || '').trim();+ if (!subject) {+ const err = new Error('query param "subject" is required');err.status = 400;- err.code = 'invalid_agent_id';+ err.code = 'missing_subject';throw err;}- return loadAgentReputation(agentId);+ return loadSubjectReputation(subject, { chain: req.query?.chain });},});@@ -212,15 +209,19 @@ const SWEEP_DEFAULT_LIMIT = 20;const SWEEP_MAX_LIMIT = 50;const LEADERBOARD_DEFAULT_LIMIT = 10;+const BATCH_MAX_SUBJECTS = 25;+const SWEEP_DESCRIPTION =- 'three.ws Agent Reputation (Sweep / Leaderboard / Decay Report) — ' ++ 'Cross-chain Agent Reputation (Batch / Sweep / Leaderboard / Decay) — ' ++ 'POST {"mode":"batch","subjects":[...]} to score up to 25 arbitrary counterparties ' ++ '(any wallet / mint / agent id, any chain) in one paid call. ' +'POST {"mode":"sweep","limit":N} to score the N most recently active three.ws agents. ' +'POST {"mode":"leaderboard","limit":N} to get the top N agents ranked by trust score (highest first). ' +'POST {"mode":"decay_report"} to get agents whose score dropped >10 points since the last snapshot. ' +`Sweep: fleet avg score + flagged agents (score < ${REPUTATION_FLAG_THRESHOLD}). ` +'Leaderboard: ranked list with { agent_id, score, rank }. ' +'Decay report: decayed_count, fastest_decline_agent, avg_decay. ' +- 'All scores are derived from real on-chain pump.fun activity — not subjective ratings.';+ 'All scores are derived from real on-chain evidence — not subjective ratings.';const SWEEP_INPUT_EXAMPLE = { mode: 'sweep', limit: 20 };@@ -230,8 +231,10 @@ const SWEEP_INPUT_SCHEMA = {properties: {mode: {type: 'string',- enum: ['sweep', 'leaderboard', 'decay_report'],- description: '"sweep" scores recent agents; "leaderboard" ranks by score desc; "decay_report" finds score declines >10 pts.',+ enum: ['batch', 'sweep', 'leaderboard', 'decay_report'],+ description:+ '"batch" scores an arbitrary subjects[] list; "sweep" scores recent three.ws agents; ' ++ '"leaderboard" ranks by score desc; "decay_report" finds score declines >10 pts.',},limit: {type: 'integer',@@ -239,6 +242,16 @@ const SWEEP_INPUT_SCHEMA = {maximum: SWEEP_MAX_LIMIT,description: `Agents to sweep/rank (sweep mode default ${SWEEP_DEFAULT_LIMIT}, leaderboard default ${LEADERBOARD_DEFAULT_LIMIT}, max ${SWEEP_MAX_LIMIT}).`,},+ subjects: {+ type: 'array',+ items: { type: 'string' },+ maxItems: BATCH_MAX_SUBJECTS,+ description: `batch mode: up to ${BATCH_MAX_SUBJECTS} counterparty identifiers to score (any chain, auto-detected).`,+ },+ chain: {+ type: ['integer', 'string'],+ description: 'batch mode: default EVM chain id for bare EVM / ERC-8004 subjects (default 8453).',+ },},};@@ -348,8 +361,8 @@ const sweepEndpoint = paidEndpoint({description: SWEEP_DESCRIPTION,bazaar: SWEEP_BAZAAR,service: withService({- serviceName: 'three.ws Agent Reputation (Active Sweep)',- tags: ['reputation', 'agent', 'solana', 'attestation', 'trust', 'monitoring'],+ serviceName: 'Agent Reputation (Batch / Sweep)',+ tags: ['reputation', 'trust', 'cross-chain', 'agent', 'monitoring'],}),requiredScope: 'x402:bypass',accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),@@ -367,6 +380,34 @@ const sweepEndpoint = paidEndpoint({err.code = 'invalid_json';throw err;}+ if (body.mode === 'batch') {+ if (!Array.isArray(body.subjects) || body.subjects.length === 0) {+ const err = new Error('batch mode requires a non-empty subjects[] array');+ err.status = 400;+ err.code = 'invalid_subjects';+ throw err;+ }+ if (body.subjects.length > BATCH_MAX_SUBJECTS) {+ const err = new Error(`subjects[] is limited to ${BATCH_MAX_SUBJECTS} per call`);+ err.status = 400;+ err.code = 'too_many_subjects';+ throw err;+ }+ const results = await scoreSubjectBatch(body.subjects, { chain: body.chain });+ const scored = results.filter((r) => r.score != null);+ const avg = scored.length+ ? Math.round(scored.reduce((s, r) => s + r.score, 0) / scored.length)+ : null;+ return {+ mode: 'batch',+ count: results.length,+ scored_count: scored.length,+ unknown_count: results.length - scored.length,+ avg_score: avg,+ subjects: results,+ generated_at: new Date().toISOString(),+ };+ }if (body.mode === 'decay_report') {return decayReportAgentReputation();}@@ -381,7 +422,7 @@ const sweepEndpoint = paidEndpoint({return leaderboardAgentReputation({ limit: Math.min(SWEEP_MAX_LIMIT, Math.floor(limit)) });}if (body.mode !== 'sweep') {- const err = new Error('mode must be "sweep", "leaderboard", or "decay_report"');+ const err = new Error('mode must be "batch", "sweep", "leaderboard", or "decay_report"');err.status = 400;err.code = 'invalid_mode';throw err;diff --git a/api/x402/model-check.js b/api/x402/model-check.jsindex 0eb47508a..c4028e2c5 100644--- a/api/x402/model-check.js+++ b/api/x402/model-check.js@@ -1,5 +1,9 @@// GET /api/x402/model-check?url=<glb-or-gltf>//+// DEPRECATED: model inspection is now FREE at GET/POST /api/3d/inspect+// (api/3d/inspect.js). Prefer that endpoint; retirement of this paid route is+// tracked by prompts/x402-overhaul/20.+//// Paid endpoint cataloged by the CDP x402 Bazaar (agentic.market) and the// pay-skills registry. For $0.001 USDC the server fetches the model bytes, runs// the glTF-Transform inspector, and returns structural stats + optimizationdiff --git a/api/x402/onchain-identity-verify.js b/api/x402/onchain-identity-verify.jsindex 71c8cb2f3..3ce4e3276 100644--- a/api/x402/onchain-identity-verify.js+++ b/api/x402/onchain-identity-verify.js@@ -1,97 +1,139 @@-// GET /api/x402/onchain-identity-verify?agent_id=<uuid>&chain=<caip2>&contract_or_mint=<addr>+// GET /api/x402/onchain-identity-verify?identity=<id>&address=<addr>&chain=<caip2>//-// Paid endpoint cataloged by the CDP x402 Bazaar. For $0.005 USDC the server-// returns a verdict on the claim "agent X owns mint/contract Y on chain Z" by-// looking it up in three.ws's unified meta.onchain index. Returns the on-chain-// evidence (tx hash, deploy time, wallet) when the claim verifies.+// Cross-platform on-chain identity-claim verifier. Paid endpoint cataloged by+// the CDP x402 Bazaar. For $0.005 USDC the server returns cryptographic /+// on-chain EVIDENCE that a claim "identity X controls address Y" is real — for+// ANY claimed identity↔address link, not just three.ws agents.//-// Why this is defensible: three.ws maintains a single unified jsonb index-// (agent_identities.meta.onchain) across Solana SPL mints, ERC-8004 EVM-// registries, and any future chain family — backed by deploy-time webhooks-// from three.ws's own /api/agents/onchain/confirm pipeline. AI agents pay-// to verify counterparty identity claims as a trust primitive: "does this-// agent really own the contract it claims?"+// `identity` may be an ENS name (vitalik.eth), an SNS name (bonfida.sol), an EVM+// wallet (0x…), a Solana wallet (base58), an ERC-8004 agent id+// (eip155:<chainId>:<agentId>), or a three.ws agent_id (uuid). `address` is the+// mint / contract / wallet the identity asserts control of.+//+// Agent use-case: before Agent A pays / trades / delegates to a counterparty+// that says "I am the deployer of contract X" or "I own wallet W / name N", A+// calls this once and gets deploy-tx + signer + ownership / name-resolution+// proof. It never asserts verified:true without concrete on-chain evidence;+// when it cannot read enough it returns verified:'unverifiable' with exactly+// what is missing — never a false positive.+//+// Evidence sources are REAL: ENS resolution (Ethereum RPC), SNS resolution+// (Solana RPC + Bonfida), EVM contract creation + deployer (Etherscan V2),+// contract owner() reads, Solana SPL mint/metadata authorities, the ERC-8004+// Identity Registry, and three.ws's canonical meta.onchain deploy index.+// See api/_lib/x402/identity-claim-verify.js for the full evidence model.import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';-import { sql } from '../_lib/db.js';import { priceFor } from '../_lib/x402-prices.js';-import { isUuid } from '../_lib/validate.js';+import { verifyClaim } from '../_lib/x402/identity-claim-verify.js';const ROUTE = '/api/x402/onchain-identity-verify';const DESCRIPTION =- 'three.ws On-Chain Identity Verifier — given a three.ws agent_id, a CAIP-2 ' +- 'chain ID, and a contract or mint address, verify whether the agent actually ' +- 'owns/deployed that address using the canonical meta.onchain unified index. ' +- 'Returns evidence (tx hash, wallet, deploy time, metadata URI) when verified. ' +- 'Use as a trust primitive before paying or trading with a counterparty agent.';+ 'Cross-platform On-Chain Identity Verifier — prove any claim that an identity ' ++ 'controls an address. `identity` can be an ENS name, an SNS (.sol) name, an EVM ' ++ 'or Solana wallet, an ERC-8004 agent id, or a three.ws agent_id; `address` is ' ++ 'the contract/mint/wallet it claims. Returns on-chain evidence (deploy tx + ' ++ 'deployer, mint/update authority, ENS/SNS resolution, ERC-8004 registration, ' ++ 'three.ws deploy record) with verified true/false/unverifiable. Use it as a ' ++ 'trust primitive before paying, trading, or delegating to a counterparty agent.';-const INPUT_EXAMPLE = {- agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',- chain: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',- contract_or_mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',+export const INPUT_EXAMPLE = {+ identity: 'vitalik.eth',+ address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',+ chain: 'eip155:1',};-const INPUT_SCHEMA = {+export const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',- required: ['agent_id', 'chain', 'contract_or_mint'],+ required: ['identity', 'address'],properties: {- agent_id: { type: 'string', format: 'uuid' },- chain: {+ identity: {type: 'string',description:- 'CAIP-2 chain ID. Examples: solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp, eip155:8453.',+ 'The claimed identity: an ENS name (vitalik.eth), SNS name (bonfida.sol), ' ++ 'EVM wallet (0x…), Solana wallet (base58), ERC-8004 id (eip155:8453:42), ' ++ 'or three.ws agent_id (uuid).',},- contract_or_mint: {+ address: {type: 'string',- description: 'SPL mint pubkey (base58) or EVM contract address (0x…).',+ description: 'The contract / mint / wallet the identity claims to control.',+ },+ chain: {+ type: 'string',+ description:+ 'Optional CAIP-2 chain hint. Examples: eip155:1, eip155:8453, ' ++ 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp. Inferred from the identity/address ' ++ 'shape when omitted.',},},};-const OUTPUT_EXAMPLE = {- agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',- chain: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',- contract_or_mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',- verified: true,- evidence: {- family: 'solana',- tx_hash: '4kHTPp9...',- wallet: 'THREEsynthetic1111111111111111111111111PayTo',- metadata_uri: 'https://arweave.net/...',- confirmed_at: '2026-04-30T14:08:22Z',+export const OUTPUT_EXAMPLE = {+ claim: {+ identity: 'vitalik.eth',+ address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',+ chain: 'eip155:1',},- indexed_at: '2026-05-14T17:00:00Z',+ identity_type: 'ens',+ verified: true,+ method: 'ens-resolution',+ evidence: [+ {+ kind: 'ens_forward_resolution',+ ref: 'vitalik.eth',+ detail: 'resolves to 0xd8da6bf26964af9d7eed9e03e53415d37aa96045',+ },+ ],+ caveats: [],+ ts: '2026-07-07T00:00:00.000Z',};-const OUTPUT_SCHEMA = {+export const OUTPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',- required: ['agent_id', 'chain', 'contract_or_mint', 'verified'],+ required: ['claim', 'verified', 'evidence', 'method', 'ts'],properties: {- agent_id: { type: 'string', format: 'uuid' },- chain: { type: 'string' },- contract_or_mint: { type: 'string' },- verified: { type: 'boolean' },- evidence: {- type: ['object', 'null'],+ claim: {+ type: 'object',+ required: ['identity', 'address'],properties: {- family: { type: 'string', enum: ['solana', 'evm'] },- tx_hash: { type: ['string', 'null'] },- wallet: { type: ['string', 'null'] },- metadata_uri: { type: ['string', 'null'] },- confirmed_at: { type: ['string', 'null'] },+ identity: { type: 'string' },+ address: { type: 'string' },+ chain: { type: ['string', 'null'] },+ },+ },+ identity_type: {+ type: 'string',+ enum: ['ens', 'sns', 'evm_address', 'solana_address', 'erc8004', 'threews_agent_id', 'unknown'],+ },+ verified: {+ description: 'true (proven), false (disproven), or "unverifiable" (insufficient on-chain data).',+ oneOf: [{ type: 'boolean' }, { type: 'string', const: 'unverifiable' }],+ },+ method: { type: 'string' },+ evidence: {+ type: 'array',+ items: {+ type: 'object',+ required: ['kind', 'ref', 'detail'],+ properties: {+ kind: { type: 'string' },+ ref: { type: 'string' },+ detail: { type: 'string' },+ },},},- indexed_at: { type: 'string', format: 'date-time' },+ caveats: { type: 'array', items: { type: 'string' } },+ ts: { type: 'string', format: 'date-time' },},};-const BAZAAR = {+export const BAZAAR = {discoverable: true,info: {input: {@@ -108,64 +150,6 @@ const BAZAAR = {}),};-const CAIP2_RE = /^[a-z0-9-]{3,}:[a-zA-Z0-9]{1,64}$/;--function normalizeAddress(addr, chain) {- if (chain.startsWith('eip155:')) return addr.toLowerCase();- return addr;-}--async function verifyIdentity({ agentId, chain, address }) {- const normalized = normalizeAddress(address, chain);- const [row] = await sql`- select- (meta->'onchain'->>'family') as family,- (meta->'onchain'->>'chain') as chain,- (meta->'onchain'->>'contract_or_mint') as contract_or_mint,- (meta->'onchain'->>'tx_hash') as tx_hash,- (meta->'onchain'->>'wallet') as wallet,- (meta->'onchain'->>'metadata_uri') as metadata_uri,- (meta->'onchain'->>'confirmed_at') as confirmed_at- from agent_identities- where id = ${agentId}- and deleted_at is null- and meta ? 'onchain'- and (meta->'onchain'->>'chain') = ${chain}- limit 1- `;-- if (!row) {- return {- agent_id: agentId,- chain,- contract_or_mint: address,- verified: false,- evidence: null,- indexed_at: new Date().toISOString(),- };- }-- const indexedAddr = normalizeAddress(row.contract_or_mint || '', chain);- const verified = indexedAddr === normalized;-- return {- agent_id: agentId,- chain,- contract_or_mint: address,- verified,- evidence: verified- ? {- family: row.family,- tx_hash: row.tx_hash || null,- wallet: row.wallet || null,- metadata_uri: row.metadata_uri || null,- confirmed_at: row.confirmed_at || null,- }- : null,- indexed_at: new Date().toISOString(),- };-}-export default paidEndpoint({route: ROUTE,method: 'GET',@@ -180,27 +164,27 @@ export default paidEndpoint({requiredScope: 'x402:bypass',accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),async handler({ req }) {- const agentId = String(req.query?.agent_id || '').trim().toLowerCase();- const chain = String(req.query?.chain || '').trim();- const address = String(req.query?.contract_or_mint || '').trim();- if (!agentId || !chain || !address) {- const err = new Error('query params agent_id, chain, contract_or_mint are required');+ // Accept the generalized params, and stay backward-compatible with the+ // original three.ws-only shape (agent_id + contract_or_mint).+ const identity = String(req.query?.identity || req.query?.agent_id || '').trim();+ const address = String(req.query?.address || req.query?.contract_or_mint || '').trim();+ const chain = String(req.query?.chain || '').trim() || undefined;++ if (!identity || !address) {+ const err = new Error('query params identity and address are required');err.status = 400;err.code = 'missing_params';throw err;}- if (!isUuid(agentId)) {- const err = new Error('agent_id must be a UUID');+ if (identity.length > 256 || address.length > 128) {+ const err = new Error('identity or address is unreasonably long');err.status = 400;- err.code = 'invalid_agent_id';+ err.code = 'invalid_input';throw err;}- if (!CAIP2_RE.test(chain)) {- const err = new Error('chain must be a CAIP-2 ID (e.g. eip155:8453 or solana:5eykt4Us...)');- err.status = 400;- err.code = 'invalid_chain';- throw err;- }- return verifyIdentity({ agentId, chain, address });++ // verifyClaim never throws — it degrades to verified:'unverifiable' with a+ // caveat, so this endpoint never 500s on a bad upstream.+ return verifyClaim({ identity, address, chain });},});diff --git a/api/x402/pump-launch.js b/api/x402/pump-launch.jsindex 8071f96f2..67eb1ef33 100644--- a/api/x402/pump-launch.js+++ b/api/x402/pump-launch.js@@ -40,16 +40,24 @@ const REQUIRED_SCOPE = 'x402:bypass';// Flat fee in USDC atomics (6 decimals). Default $5.00 comfortably covers the// ~0.022 SOL deploy cost the launcher fronts plus margin. Tune per unit// economics with X402_PRICE_PUMP_LAUNCH=<atomics>.-const PRICE_ATOMICS = priceFor('pump-launch', '5000000');+export const PRICE_ATOMICS = priceFor('pump-launch', '5000000');-const DESCRIPTION =- 'three.ws Pump Launcher — deploy a brand-new pump.fun token in one paid call. ' +- 'Supply a name, symbol, and either a pre-pinned metadataUri or an imageUrl ' +- '(we pin the image + descriptor to pump.fun IPFS for you). The server fronts ' +- 'the SOL deploy cost and signs the create-coin tx, so you need no SOL and no ' +- 'account — just USDC. Creator rewards accrue to any Solana wallet you nominate. ' +- 'Optional vanity prefix/suffix grinds a custom mint address. Returns the mint, ' +- 'tx signature, and pump.fun URL. Pay-per-call in USDC on Base or Solana mainnet.';+export const DESCRIPTION =+ 'three.ws Pump Launcher — launch a pump.fun token autonomously in ONE paid call: ' ++ 'no SOL, no wallet, no account. You pay USDC; the server fronts the ~0.022 SOL ' ++ 'deploy cost, optionally grinds a vanity mint, and signs the bonding-curve ' ++ 'create tx for you. ' ++ 'INPUTS: name + symbol (required); metadata as EITHER a pre-pinned "metadataUri" ' ++ 'OR an "imageUrl" we pin to pump.fun IPFS (with optional description / twitter / ' ++ 'telegram / website); "creator" = any Solana pubkey to receive pump.fun creator ' ++ 'rewards (defaults to the launcher); optional "vanityPrefix" / "vanitySuffix" ' ++ '(≤5 base58 chars each) to brand the mint address. ' ++ 'OUTPUT: mint address, tx signature, metadataUri, solscan explorer link, and the ' ++ 'pump.fun coin URL. ' ++ 'FUNNEL: check your ticker is free first with the FREE GET /api/crypto/symbol, ' ++ 'then confirm the deploy landed on the FREE GET /api/crypto/launches feed. ' ++ 'Idempotent per payment (a retried payment replays the same mint). ' ++ 'Pay in USDC on Base or Solana mainnet; the token deploys on Solana mainnet.';const INPUT_EXAMPLE = {name: 'Helios',@@ -60,36 +68,71 @@ const INPUT_EXAMPLE = {twitter: 'https://x.com/heliocoin',};-const INPUT_SCHEMA = {+export const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',+ // name + symbol are always required; exactly one of metadataUri / imageUrl+ // must also be supplied (enforced by the handler — a request with neither is+ // rejected 400 before payment settles).required: ['name', 'symbol'],+ oneOf: [{ required: ['metadataUri'] }, { required: ['imageUrl'] }],properties: {- name: { type: 'string', maxLength: 32, description: 'Token name.' },- symbol: { type: 'string', maxLength: 10, description: 'Token ticker.' },+ name: { type: 'string', minLength: 1, maxLength: 32, description: 'Token name, e.g. "Helios". 1–32 chars.' },+ symbol: {+ type: 'string',+ minLength: 1,+ maxLength: 10,+ description:+ 'Token ticker, e.g. "HELIO". 1–10 chars. Check availability first with the free ' ++ 'GET /api/crypto/symbol?ticker=<symbol> so you do not collide with a live coin.',+ },metadataUri: {type: 'string',format: 'uri',- description: 'Pre-pinned pump.fun metadata descriptor. Provide this OR imageUrl.',+ maxLength: 2048,+ description:+ 'Pre-pinned pump.fun metadata descriptor (JSON on IPFS). Provide this OR imageUrl. ' ++ 'When supplied it is used verbatim and no pinning happens server-side.',},imageUrl: {type: 'string',format: 'uri',+ maxLength: 2048,description:'https URL of the token image. When metadataUri is omitted, the image + a ' +- 'descriptor are pinned to pump.fun IPFS (png, jpeg, gif, webp; max 5 MB).',+ 'descriptor (name/symbol/description/socials) are pinned to pump.fun IPFS for ' ++ 'you (png, jpeg, gif, webp; max 5 MB).',+ },+ description: {+ type: 'string',+ maxLength: 2000,+ description: 'Coin description. Used only when we pin metadata for you (imageUrl path).',},- description: { type: 'string', maxLength: 2000 },- twitter: { type: 'string', maxLength: 2048 },- telegram: { type: 'string', maxLength: 2048 },- website: { type: 'string', maxLength: 2048 },+ twitter: { type: 'string', maxLength: 2048, description: 'Twitter/X URL for the pinned metadata (imageUrl path).' },+ telegram: { type: 'string', maxLength: 2048, description: 'Telegram URL for the pinned metadata (imageUrl path).' },+ website: { type: 'string', maxLength: 2048, description: 'Website URL for the pinned metadata (imageUrl path).' },creator: {type: 'string',- description: 'Solana pubkey to receive pump.fun creator rewards. Defaults to the launcher.',+ minLength: 32,+ maxLength: 44,+ description:+ 'Solana pubkey (base58) to receive pump.fun creator rewards. Defaults to the ' ++ 'launcher when omitted.',+ },+ vanityPrefix: {+ type: 'string',+ maxLength: 5,+ description: 'Base58 prefix to grind into the mint address (≤5 chars; longer = slower).',+ },+ vanitySuffix: {+ type: 'string',+ maxLength: 5,+ description: 'Base58 suffix to grind into the mint address (≤5 chars; longer = slower).',+ },+ vanityIgnoreCase: {+ type: 'boolean',+ description: 'Match vanityPrefix/Suffix case-insensitively (faster grind). Default false.',},- vanityPrefix: { type: 'string', maxLength: 5, description: 'Base58 prefix for the mint address.' },- vanitySuffix: { type: 'string', maxLength: 5, description: 'Base58 suffix for the mint address.' },- vanityIgnoreCase: { type: 'boolean' },},};@@ -109,7 +152,7 @@ const OUTPUT_EXAMPLE = {vanity_duration_ms: 190,};-const OUTPUT_SCHEMA = {+export const OUTPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',required: ['mint', 'signature', 'metadataUri', 'pumpfun_url'],@@ -130,7 +173,7 @@ const OUTPUT_SCHEMA = {},};-const BAZAAR = {+export const BAZAAR = {discoverable: true,info: {input: { type: 'http', method: 'POST', body: INPUT_EXAMPLE },@@ -147,7 +190,7 @@ const BAZAAR = {// Base58 (no 0/O/I/l) — used to bound vanity patterns before grinding.const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;-const bodySchema = z+export const bodySchema = z.object({name: z.string().trim().min(1).max(32),symbol: z.string().trim().min(1).max(10),diff --git a/api/x402/symbol-availability.js b/api/x402/symbol-availability.jsindex ac089f903..a3f78792b 100644--- a/api/x402/symbol-availability.js+++ b/api/x402/symbol-availability.js@@ -1,6 +1,11 @@// GET /api/x402/symbol-availability?ticker=<symbol>&network=<mainnet|devnet>// POST /api/x402/symbol-availability { symbols: string[], network?: string }//+// DEPRECATED: symbol-availability is now a FREE, keyless discovery utility at+// GET/POST /api/crypto/symbol (up to 20 symbols/call, exact + fuzzy collisions+// across live registries). Prefer that route; this paid endpoint is retired in+// prompts/x402-overhaul/20. See api/crypto/symbol.js.+//// GET: single-ticker collision check ($0.001 USDC) — original endpoint.// POST: batch scan of up to 10 symbols ($0.005 USDC) — returns// { scanned_count, available_count, taken_count, available_list,diff --git a/api/x402/vanity.js b/api/x402/vanity.jsindex 420994b18..ad7de55cc 100644--- a/api/x402/vanity.js+++ b/api/x402/vanity.js@@ -114,19 +114,22 @@ function priceAtomicsFor(format, combinedLength) {}const ROUTE_DESCRIPTION =- 'three.ws Solana Vanity Grinder — generate a brand-new Solana wallet whose ' +- 'Base58 address starts with your chosen prefix and/or ends with your chosen ' +- 'suffix. Two output formats: format=keypair (default) returns the public ' +- 'address and its secret key (Base58 + 64-byte array), ground in a Rust/WASM ' +- 'ed25519 engine — capped at 3 Base58 chars, priced $0.01–$0.25. format=mnemonic ' +- 'returns a BIP-39 seed phrase (12 or 24 words) whose derived key at ' +- "m/44'/501'/0'/0' lands on the vanity address, importable as a recovery phrase " +- 'into Phantom / Solflare / the Solana CLI — capped at 2 chars (~100× slower to ' +- 'grind), priced $0.05–$0.50. Nothing is ever stored; the secret exists only in ' +- 'the response, served once over TLS. Optional sealTo=<X25519 public key> seals the ' +- 'secret to you (ECIES) so the plaintext never appears in the response or any log — ' +- 'open it client-side with the matching private key. Pay-per-call in USDC on Base or ' +- 'Solana mainnet — no API keys, no accounts.';+ 'three.ws Solana Vanity Grinder — put your brand on-chain: get a Solana address ' ++ 'that starts with your ticker/prefix and/or ends with a chosen suffix. Use it as a ' ++ 'branded token MINT address, a recognizable agent or treasury wallet, or any wallet ' ++ 'you want identifiable at a glance. The server grinds a brand-new keypair to match — ' ++ 'no wallet, account, or SOL required. Two output formats: format=keypair (default) ' ++ 'returns the public address and its secret key (Base58 + 64-byte array), ground in a ' ++ 'Rust/WASM ed25519 engine — capped at 3 Base58 chars, priced $0.01 (1 char) / $0.05 ' ++ '(2) / $0.25 (3). format=mnemonic returns a BIP-39 seed phrase (12 or 24 words) whose ' ++ "derived key at m/44'/501'/0'/0' lands on the vanity address, importable as a recovery " ++ 'phrase into Phantom / Solflare / the Solana CLI — capped at 2 chars (~100× slower to ' ++ 'grind), priced $0.05 (1 char) / $0.50 (2). Security model: nothing is ever stored — ' ++ 'the secret exists only in the response, served once over TLS, and is stripped from the ' ++ 'replay/idempotency cache. Optional sealTo=<X25519 public key> seals the secret to you ' ++ '(ECIES; x25519-hkdf-sha256-aes256gcm) so the plaintext never appears in the response ' ++ 'or any log — open it client-side with the matching private key. Keyless and ' ++ 'account-free: pay-per-call in USDC on Base or Solana mainnet — no API keys, no signup.';// Base58 excludes 0/O/I/l. Note also that an address is 32 random bytes// Base58-encoded, so its LEADING characters are not uniformly distributed —diff --git a/data/pages.json b/data/pages.jsonindex f1700d252..44866568f 100644--- a/data/pages.json+++ b/data/pages.json@@ -1536,6 +1536,32 @@"changefreq": "weekly","added": "2026-04-27"},+ {+ "path": "/crypto",+ "title": "Crypto Data API",+ "description": "Free, keyless crypto data for AI agents in one API: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios and ticker-availability checks. No key, no account, no paywall.",+ "priority": 0.8,+ "changefreq": "weekly",+ "added": "2026-07-07",+ "showcase": true+ },+ {+ "path": "/3d",+ "title": "3D API",+ "description": "Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.",+ "priority": 0.8,+ "changefreq": "weekly",+ "added": "2026-07-07",+ "showcase": true+ },+ {+ "path": "/docs/crypto-api",+ "title": "Docs · Crypto Data API",+ "description": "Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.",+ "priority": 0.7,+ "changefreq": "weekly",+ "added": "2026-07-07"+ },{"path": "/docs/walk","title": "Docs · Walk Avatar",@@ -1602,6 +1628,12 @@"description": "Why autonomous agents need verifiable trust, and how three.ws delivers portable on-chain reputation.","added": "2026-06-22"},+ {+ "path": "/docs/trust-primitives",+ "title": "Docs · Trust Primitives",+ "description": "Cross-chain Agent Reputation — score any wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence before your agent pays, trades, or delegates.",+ "added": "2026-07-07"+ },{"path": "/docs/x402","title": "Docs · x402 Protocol",@@ -1620,6 +1652,12 @@"description": "Where settled x402 payments are recorded (x402_audit_log), how to read endpoint revenue, and how signed receipts work.","added": "2026-06-30"},+ {+ "path": "/docs/pump-launcher",+ "title": "Docs · Pump Launcher",+ "description": "Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.",+ "added": "2026-07-07"+ },{"path": "/docs/x402-buyer","title": "Docs · x402 Buyer Client",diff --git a/docs/agent-reputation.md b/docs/agent-reputation.mdindex 47adfa7fe..3b8682f0b 100644--- a/docs/agent-reputation.md+++ b/docs/agent-reputation.md@@ -116,7 +116,7 @@ The same on-chain data is exposed through every layer a reader might come from:| Reputation panel | agent profiles | The embedded vouch/score widget on `https://three.ws/a/<chainId>/<agentId>` || `GET /api/agents/<id>/reputation` | apps | One-call JSON: `average`, `count`, `total_stake_wei` || `agent_reputation` MCP tool | AI agents | Paid ($0.01 USDC) read of identity + score + stake + recent events; resolves a wallet to its agent automatically |-| `GET /api/x402/agent-reputation` | AI agents | Paid behavioral synthesis — payments, payout success, disputes, attestations |+| `GET /api/x402/agent-reputation` | AI agents | Paid ($0.01) cross-chain 0–100 trust score for **any** counterparty — Solana/EVM wallet, pump.fun mint, ERC-8004 agent id, or three.ws agent_id (auto-detected). See [Trust primitives](trust-primitives.md) || [Agent Passport](/agent-passport.html) | trust decisions | An A–D trust grade weighted toward credentialed and verified feedback || SDK `@three-ws/sdk/erc8004` | developers | `getReputation`, `getRecentReviews`, `getTotalStake` |diff --git a/docs/crypto-api.md b/docs/crypto-api.mdnew file mode 100644index 000000000..a13884a05--- /dev/null+++ b/docs/crypto-api.md@@ -0,0 +1,493 @@+# Crypto Data API++The three.ws **Crypto Data API** is a free, keyless bundle of read-only crypto+endpoints built for AI agents. No account, no API key, no payment — just HTTP+GET with a generous per-IP rate limit. Each endpoint answers one question an+autonomous agent has mid-task, from real on-chain and pump.fun data (no mocks).++Base URL: `https://three.ws`++> This bundle is the free loss-leader tier. Paid, deeper analytics live behind+> the x402 rail (see [`/.well-known/x402.json`](https://three.ws/.well-known/x402.json)).++---++## Discover the whole bundle in one call++The API is self-describing. An agent (or a human wiring one up) hits **one URL**+to learn every endpoint, its inputs and outputs, and a live example — no need to+read this page first.++| Discovery endpoint | Returns |+|--------------------|---------|+| [`GET /api/crypto`](https://three.ws/api/crypto) | The catalog: `{ name, free, keyless, version, endpoints[], docs, openapi, ts }`. Send `Accept: text/html` for a browsable page, anything else for JSON. |+| [`GET /api/crypto/openapi.json`](https://three.ws/api/crypto/openapi.json) | A real **OpenAPI 3.1** document generated from the same catalog — point Swagger UI, `openapi-generator`, or a framework's OpenAPI tool loader at it to get typed clients / callable tools for free. |++Both are generated from the catalog, so they can never drift from the live+endpoints — a new endpoint appears in both the moment it ships. Zero endpoints is+a valid state (empty `endpoints[]` + a "coming soon" note), never an error.++```bash+# One call, the whole map — pipe into jq to list paths+curl -s https://three.ws/api/crypto | jq '.endpoints[] | {method, path, title}'++# Generate a typed client from the spec+curl -s https://three.ws/api/crypto/openapi.json -o crypto.openapi.json+```++### Endpoints++Every endpoint is free, keyless, `GET` (a couple also accept `POST`), and rate-+limited per IP. This table is the canonical index; each endpoint's full contract+is documented in its section below and machine-readable in the OpenAPI doc.++| Endpoint | Verb(s) | What it answers |+|----------|---------|-----------------|+| [`/api/crypto/bonding`](https://three.ws/api/crypto/bonding) | `GET` | Where a pump.fun token sits on its bonding curve — % to graduation, SOL in the curve, and whether it has migrated to an AMM. |+| [`/api/crypto/symbol`](https://three.ws/api/crypto/symbol) | `GET` · `POST` | Whether up to 20 candidate tickers are taken — exact and fuzzy (look-alike) collisions across live registries. |+| [`/api/crypto/trending`](https://three.ws/api/crypto/trending) | `GET` | Solana tokens ranked by momentum (volume + buy pressure + spike + short-window price change) fused across sources. |+| [`/api/crypto/wallet`](https://three.ws/api/crypto/wallet) | `GET` | A wallet's native balance, every token it holds, and a rough USD valuation — keyless on Solana. |+| [`/api/crypto/whales`](https://three.ws/api/crypto/whales) | `GET` | Large buys on pump.fun for a token or market-wide, with a deterministic bullish/bearish/neutral buy-pressure signal. |++> Building an endpoint for this bundle? Drop a self-describing descriptor file in+> `api/_lib/crypto-catalog/` (`{ slug, method(s), path, title, summary,+> inputSchema, outputSchema, example }`) — the index and OpenAPI doc pick it up+> automatically, and it lists in the table above on the next deploy.++---++## `GET /api/crypto/bonding` — Bonding-curve / graduation status++**Use-case.** An agent holding or watching a pump.fun token needs to know exactly+where it is on the bonding curve — **% to graduation**, how much SOL is in the+curve, and whether it has already **migrated** to Raydium / PumpSwap. Timing+entries and exits around graduation is a core meme-trading move: a coin at 95% is+minutes from a supply/liquidity regime change; one that already graduated no longer+trades on the curve at all. Without this an agent would have to fetch the curve+account over RPC and do the reserve math itself — here it's one keyless GET.++Pair it with [`/api/crypto/launches`](https://three.ws/api/crypto/launches) to+discover fresh mints, then poll `bonding` on the ones worth watching.++### Request++| Param | Type | Notes |+|--------|--------|-------|+| `mint` | string | pump.fun token mint (base58 Solana address). Required. |++### Response++On-curve token (still filling the bonding curve):++```json+{+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "onCurve": true,+ "bondingProgressPct": 70.67,+ "solInCurve": 32.81,+ "tokensRemaining": 232581073.73,+ "marketCapUsd": 10095.72,+ "graduated": false,+ "migratedTo": null,+ "ts": "2026-07-07T00:00:00.000Z",+ "source": "pumpfun"+}+```++Graduated token (left the curve for an AMM):++```json+{+ "mint": "THREEsynthetic1111111111111111111111111111",+ "onCurve": false,+ "bondingProgressPct": 100,+ "solInCurve": null,+ "tokensRemaining": null,+ "marketCapUsd": 424807497.98,+ "graduated": true,+ "migratedTo": "pumpswap",+ "ts": "2026-07-07T00:00:00.000Z",+ "source": "pumpfun"+}+```++- **`onCurve`** — `true` while the token is still on the bonding curve; `false`+ once it has graduated.+- **`bondingProgressPct`** — `0`–`100`, the share of the curve's token float that+ has been bought out (`0` at launch, `100` once graduated). The math is the share+ of the curve's initial 793.1M-token float still unsold — the same `bondingProgressPct`+ the Oracle coin page uses, shared from+ [`api/_lib/pump-bonding.js`](../api/_lib/pump-bonding.js).+- **`solInCurve`** — real SOL reserves currently in the curve; `null` once graduated.+- **`tokensRemaining`** — tokens still buyable on the curve; `null` once graduated.+- **`graduated`** — `true` once the curve completed and the token migrated to an AMM.+- **`migratedTo`** — `"raydium"` or `"pumpswap"` for a graduated token; `null` while+ still on the curve.++### States++- **On the curve** → `200` with live `bondingProgressPct` / `solInCurve` /+ `tokensRemaining`.+- **Already graduated** → `200` with `graduated: true`, `migratedTo` set, and the+ curve fields `null` / final (`bondingProgressPct: 100`).+- **Not a pump.fun mint** (never launched on pump.fun, or an externally-indexed+ token like WSOL/USDC) → `400 not_pumpfun_mint` with a pointer to+ `/api/crypto/launches`.+- **Missing / non-base58 `mint`** → `400 missing_mint` / `400 invalid_mint` with a+ clear message.+- **pump.fun feed unavailable** → `503 upstream_unavailable` + `Retry-After`. Never `500`.+- **Rate-limited** → `429` with `RateLimit-*` + `Retry-After` headers.++### Examples++```bash+# How close is this token to graduating?+curl "https://three.ws/api/crypto/bonding?mint=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"++# Has it already migrated to an AMM?+curl "https://three.ws/api/crypto/bonding?mint=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" | jq '{graduated, migratedTo}'+```++---++## `GET /api/crypto/whales` — Whale / large-buy activity++**Use-case.** A trading or sniper agent, mid-decision, needs to know whether big+money is moving into a token — or the pump.fun market broadly — *before* it+commits. A whale already in means price impact is ahead; no whales means the book+is thin. This endpoint is a free, high-signal read of large buys.++### Request++| Param | Type | Default | Notes |+|----------|--------|---------|-------|+| `mint` | string | — | Optional base58 Solana mint. **Present** → whale buys of that token. **Omitted** → top whale wallets active across pump.fun. |+| `minSol` | number | `5` | Minimum SOL in a single buy to qualify as a whale (floored at `0.1`). |+| `limit` | int | `10` | Rows to return (max `25`). |++### Response++```json+{+ "scope": "token",+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "minSol": 5,+ "whales": [+ {+ "wallet": "AbcDEF12345GHJKLMNopqrstuvwxyZabcdefghijk1",+ "solMoved": 12.4,+ "txHash": "5xTr4nSacT1oNsigNaTuReExampLe…",+ "ts": "2026-07-07T00:00:00.000Z"+ }+ ],+ "whaleCount": 1,+ "totalSolMoved": 12.4,+ "signal": "bullish",+ "ts": "2026-07-07T00:00:00.000Z",+ "source": "pump.fun"+}+```++- **`scope`** — `token` when `mint` is supplied, else `market`.+- **`whales`** — in `token` scope, one row per qualifying **buy** (largest+ first). In `market` scope, one row per qualifying whale **wallet**, where+ `solMoved` is the sum of that wallet's qualifying buys and `txHash`/`ts` point+ at its single largest buy.+- **`whaleCount`** — qualifying buys (token scope) or distinct whale wallets+ (market scope).+- **`totalSolMoved`** — total SOL across all qualifying whale buys.+- **`signal`** — see the rule below.++### The signal rule (deterministic — no LLM)++The signal reads **net whale flow**: SOL bought by whales minus SOL sold by+whales, counting only trades at or above `minSol`. A net move of at least one+whale-sized position sets the direction, so the rule means the same thing at any+threshold:++```+netFlow = whaleBuySol − whaleSellSol++no qualifying whale trades at all → neutral+netFlow ≥ +minSol (net accumulation) → bullish+netFlow ≤ −minSol (net distribution) → bearish+otherwise (balanced) → neutral+```++The implementation is `computeSignal` in+[`api/_lib/pump-whale-scan.js`](../api/_lib/pump-whale-scan.js) and is covered by+`tests/crypto-whales.test.js`.++### States++- **No whales over threshold** → `200` with `whales: []`, `whaleCount: 0`, and+ `signal: "neutral"`. Not an error.+- **pump.fun feed unavailable** → `200` with an empty whale set and a `note`+ field. Never `500`.+- **Malformed `mint` / `minSol` / `limit`** → `400` with a clear message and an+ `example`.+- **Rate-limited** → `429` with `RateLimit-*` + `Retry-After` headers.++### Examples++```bash+# Whale buys of $THREE+curl "https://three.ws/api/crypto/whales?mint=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"++# Top whale wallets across pump.fun, raise the bar to 10 SOL, top 5+curl "https://three.ws/api/crypto/whales?minSol=10&limit=5"+```++---++## `GET /api/crypto/wallet` — Wallet portfolio++**Use-case.** An autonomous agent needs to inspect a wallet — its own or a+counterparty's — before it transacts. A **treasury agent** checks its own runway+(SOL + token value) before a spend; a **copy-trade agent** reads a leader wallet's+holdings to decide what to mirror; a **pre-trade counterparty check** inspects who+it's about to deal with (a fresh empty wallet, or a real holder?). Without this the+agent has to juggle an RPC (`getTokenAccountsByOwner`), a metadata source, and a+price API itself — here it's one keyless GET.++### Request++| Param | Type | Default | Notes |+|-----------|--------|----------|-------|+| `address` | string | — | Wallet address. Solana base58, or an EVM `0x` address. Required. |+| `chain` | string | `solana` | `solana` (keyless) or `ethereum` (needs a provider key on the deployment). |++Solana is the keyless flagship: balances come from Helius DAS when a key is+configured, and fall back to the **public Solana RPC** (`getTokenAccountsByOwner`)+with **Jupiter Lite** + the **pump.fun bonding curve** for pricing when it isn't —+so a real answer comes back with no key at all.++### Response++```json+{+ "address": "HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk",+ "chain": "solana",+ "native": { "symbol": "SOL", "amount": 2.5, "usd": 375.0 },+ "tokens": [+ {+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "symbol": "THREE",+ "name": "three.ws",+ "amount": 1000,+ "usd": 1.6,+ "logo": "https://.../three.png"+ },+ {+ "mint": "THREEsynthetic1111111111111111111111111111",+ "symbol": "SYNTH",+ "name": "Synthetic",+ "amount": 500,+ "usd": null,+ "logo": null+ }+ ],+ "totalUsd": 376.6,+ "tokenCount": 2,+ "truncated": false,+ "ts": "2026-07-07T00:00:00.000Z",+ "sources": ["solana-rpc", "jupiter-lite"]+}+```++- **`native.usd` / `tokens[].usd`** — USD valuation, or `null` when the asset+ couldn't be priced (a low-liquidity token no source can route). The balance is+ always reported; only the valuation is nullable.+- **`totalUsd`** — sum of every **priced** holding (unpriced ones contribute+ nothing, they don't corrupt the total).+- **`tokenCount`** — total tokens held, even when the returned list is capped.+- **`truncated`** — `true` when the wallet holds more than 200 tokens; the list is+ sorted by USD value descending and cut at 200, so the meaningful holdings survive.+- **`stale`** — present and `true` only when every live RPC path failed and the+ endpoint served the wallet's last-known-good snapshot instead of erroring.++### States++- **Invalid / missing `address`** → `400` (`invalid_address` / `missing_address`)+ with an `example`.+- **Unsupported `chain`** → `400 unsupported_chain` (lists supported chains).+- **Empty wallet** → `200` with `amount: 0`, `tokens: []`, `totalUsd: 0`. Not an error.+- **EVM chain, no provider key** → `503 not_configured` (Solana still works keyless).+- **Every upstream RPC down** → `503 upstream_unavailable` + `Retry-After`. Never `500`.+- **Rate-limited** → `429 rate_limited` with `retryAfter`.++### Example++```bash+curl "https://three.ws/api/crypto/wallet?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&chain=solana"+```++---++## `GET/POST /api/crypto/symbol` — Symbol availability++**Use-case.** An agent about to launch a token needs a ticker that won't be lost+among clones. Before it commits a mint, it batch-checks its shortlist here: an+**exact** collision means the name is already taken; a **fuzzy** collision (e.g.+`MOONZ` vs `MOONS`) means the brand gets diluted in aggregator search even when the+exact string is free. Clearing the name here for free is the natural first step+before minting through the paid **Pump Launcher** (`/api/x402/pump-launch`) — clear+the name, then launch.++Fuzzy scoring uses a pg_trgm-style trigram Jaccard similarity — the same+exact-plus-fuzzy model the earlier *paid* `symbol-availability` endpoint ran,+broadened from three.ws's own mint index to the whole market and made free.++### Request++Up to **20** symbols per call. GET takes a comma-separated list; POST takes a JSON+array.++| Param | Where | Type | Notes |+|-----------|-------|----------|-------|+| `symbols` | `?symbols=A,B,C` (GET) or body array (POST) | string[] | 1–20 tickers. A leading `$` is stripped; matching is case-insensitive. Required. |+| `chain` | `?chain=` (GET) or body (POST) | string | Optional. Restrict collisions to one chain (e.g. `solana`). Omit to check every indexed chain. |++### Response++```json+{+ "results": [+ {+ "symbol": "THREE",+ "available": false,+ "exactCollisions": [+ { "symbol": "three", "name": "three.ws", "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump", "chain": "solana" }+ ],+ "fuzzyCollisions": []+ },+ { "symbol": "MOONZ", "available": true, "exactCollisions": [], "fuzzyCollisions": [] }+ ],+ "availableCount": 1,+ "takenCount": 1,+ "chain": "solana",+ "ts": "2026-07-07T00:00:00.000Z"+}+```++- **`available`** — `true` when no exact collision exists, `false` when one does,+ and `null` when the collision source couldn't be reached for that symbol (the+ result carries a `note`, and the response sets `degraded: true`). An outage is+ never reported as a green light.+- **`fuzzyCollisions`** — each carries a `similarity` (0–1); sorted most-similar+ first, capped at 10.+- **`availableCount` / `takenCount`** — counts of `available === true` / `=== false`+ (unverifiable `null` symbols count as neither).++### States++- **No symbols** → `400 missing_symbols` with the cap and an `example`.+- **More than 20 symbols** → `400 too_many_symbols` with the cap.+- **Registry source down** → `200` with `degraded: true`; affected symbols get+ `available: null` + a `note`. Never `500`.+- **Rate-limited** → `429 rate_limited` with `RateLimit-*` + `Retry-After` headers.++### Examples++```bash+# GET — comma-separated shortlist, Solana only+curl "https://three.ws/api/crypto/symbol?symbols=THREE,MOONZ,BLERGZ&chain=solana"++# POST — same batch as JSON+curl -s -X POST https://three.ws/api/crypto/symbol \+ -H 'content-type: application/json' \+ -d '{"symbols":["THREE","MOONZ","BLERGZ"],"chain":"solana"}'+```++---++## `GET /api/crypto/trending` — Trending / hot tokens++**Use-case.** A *discovery agent* needs "what's hot right now" — tokens ranked by+momentum so it can surface opportunities, fire alerts, or shortlist candidates to+research, without scraping five sites and inventing its own score. One call+replaces polling pump.fun, a DEX aggregator, and a smart-money tracker and+reconciling their formats.++### Request++| Param | Type | Default | Notes |+|----------|------|---------|-------|+| `window` | enum | `1h` | `5m` \| `1h` \| `24h` — the trade window the momentum score measures. |+| `limit` | int | `20` | `1`–`50` (capped at 50). |+| `source` | enum | `all` | `pumpfun` restricts to the pump.fun board; `all` fuses every source. |++### Response++```json+{+ "window": "1h",+ "tokens": [+ {+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "symbol": "THREE",+ "name": "three.ws",+ "marketCapUsd": 412000,+ "volumeUsd": 32679.02,+ "change": 12.4,+ "score": 75.97,+ "url": "https://pump.fun/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"+ }+ ],+ "count": 1,+ "ts": "2026-07-07T00:22:11.083Z",+ "sources": ["pumpfun", "dexscreener"],+ "note": "Partial data: gmgn unavailable; ranked from pumpfun, dexscreener."+}+```++- **`tokens`** — ordered by `score` descending.+- **`change`** — price change **%** over the window; `null` where an upstream+ doesn't expose it (pump.fun's swap feed carries no per-window %).+- **`sources`** — which upstreams actually contributed to this ranking.+- **`note`** — present only when a source was down or the whole set is empty.++### The ranking signal++`score` is a **0–100 momentum score**, not a measure of raw size — a small coin+with a fresh volume spike and heavy buying outranks a large, quiet one. Each token+is reduced to up to four features, **normalized within its own source** so the very+different volume scales of pump.fun vs a DEX board don't distort the blend:++| Feature | Weight | Meaning |+|---------------|--------|---------|+| Volume share | 0.45 | `volumeUsd` relative to the busiest token in that source. |+| Buy dominance | 0.25 | Buy pressure above 50/50, from real trade/txn counts. |+| Volume spike | 0.20 | `volumeUsd ÷ median(peers)`, saturating at 3× — the same robust peer-median an anomaly verdict uses. |+| Price change | 0.10 | Positive % change over the window, saturating at +50%. |++The score is the weighted sum over the features actually present, divided by the+sum of the present weights — so a source that can't supply one signal is scored on+what it has rather than penalized. Signals are composed from the platform's+existing scoring primitives (`scorePressure`, `summarizeWindowUsd`, `median`); see+[`api/_lib/crypto-trending.js`](../api/_lib/crypto-trending.js).++**Sources fused (all keyless):**++- **pump.fun** — live board + per-coin swap trades (windowed USD volume + buy pressure).+- **DexScreener** — boosted-token board (24h volume, 1h/24h price change, buy/sell txns).+- **GMGN** — smart-money rank, *best-effort*: serverless egress IPs are frequently+ Cloudflare-blocked, so it usually contributes nothing and is simply omitted from+ `sources` — never an error.++### States++- **A source is down** → `200` with whatever ranked data is available, plus a `note`.+- **Everything down** → `200` with `tokens: []`, `sources: []`, and a retry note. Never `500`.+- **Bad `window`/`source`** → coerced to the default. **`limit` > 50** → capped at 50.+- **Rate-limited** → `429` with `RateLimit-*` + `Retry-After` headers.++### Examples++```bash+# Top 5 hottest tokens across all sources, last hour+curl -s "https://three.ws/api/crypto/trending?window=1h&limit=5&source=all"++# pump.fun only, 24h window+curl -s "https://three.ws/api/crypto/trending?window=24h&source=pumpfun"+```diff --git a/docs/pump-launcher.md b/docs/pump-launcher.mdnew file mode 100644index 000000000..0db36c41a--- /dev/null+++ b/docs/pump-launcher.md@@ -0,0 +1,138 @@+# Pump Launcher — deploy a pump.fun token in one paid call++`POST /api/x402/pump-launch` launches a brand-new [pump.fun](https://pump.fun)+token for an autonomous agent in a single paid request. The agent needs **no+SOL, no wallet, and no three.ws account** — it pays a flat USDC fee over the+[x402](x402.md) rail and the platform does the rest:++- fronts the ~0.022 SOL bonding-curve deploy cost from a funded launcher keypair,+- optionally grinds a **vanity mint address**,+- pins the token image + metadata to pump.fun IPFS (if you didn't pre-pin it),+- signs and broadcasts the create-coin transaction,+- routes pump.fun **creator rewards** to any Solana wallet the agent nominates.++## Which agent uses this, and why us++A launchpad bot, a "coin-per-X" automation (one coin per GitHub repo, per news+event, per Discord command), or an agent that mints a token as the payoff step of+a longer task. Every other path to a pump.fun launch needs a funded Solana wallet,+the SOL to pay rent + fees, and code that builds and signs the create instruction.+This endpoint collapses all of that into **one HTTP call priced in USDC** — the+one currency an agent operating on Base or Solana already holds. That's the pick:+no key management, no SOL treasury, no transaction assembly.++## Price++**$5.00** flat (USDC atomics `5000000`, 6 decimals). It comfortably covers the+~0.022 SOL the launcher fronts plus margin. Ops can override per unit-economics+with `X402_PRICE_PUMP_LAUNCH=<atomics>`. The live 402 challenge always quotes the+current figure — read it, don't hardcode.++## The free → paid funnel++The paid launch sits between two **free, keyless** [Crypto Data API](do-i-need-crypto.md)+endpoints. Use them to make the launch land well:++1. **Before you launch — check the ticker.**+ `GET /api/crypto/symbol?ticker=<SYMBOL>` reports whether a live pump.fun coin+ already trades that symbol and lists near-collisions. Free, no key. Pick a+ symbol that isn't already crowded before you spend $5.+2. **Launch** — `POST /api/x402/pump-launch` (this endpoint).+3. **After you launch — confirm it landed.**+ `GET /api/crypto/launches` is the live pump.fun launch feed; your new mint+ appears there once it's on-chain. Free, no key. Use it to verify the deploy+ and to surface the coin in a UI without polling an RPC.++Free data drives paid launches; paid launches show up in the free feed. That loop+is the point.++## Inputs++`name` and `symbol` are always required, plus **exactly one** of `metadataUri`+or `imageUrl`.++| Field | Required | Notes |+| --- | --- | --- |+| `name` | ✅ | Token name, 1–32 chars. |+| `symbol` | ✅ | Ticker, 1–10 chars. Check it first with `/api/crypto/symbol`. |+| `metadataUri` | one of | Pre-pinned pump.fun metadata descriptor (JSON on IPFS). Used verbatim; no server-side pinning. |+| `imageUrl` | one of | https URL of the token image. We pin the image + a descriptor to pump.fun IPFS for you (png/jpeg/gif/webp, ≤5 MB). |+| `description` | — | Coin description. Used only on the `imageUrl` (we-pin) path. |+| `twitter` / `telegram` / `website` | — | Socials embedded in the pinned metadata (`imageUrl` path). |+| `creator` | — | Solana pubkey (base58) to receive pump.fun creator rewards. Defaults to the launcher. |+| `vanityPrefix` / `vanitySuffix` | — | Base58 affix (≤5 chars each) to brand the mint address. Longer = exponentially slower grind. |+| `vanityIgnoreCase` | — | Match the vanity affixes case-insensitively (faster). Default `false`. |++### Example request++```bash+# 1. (free) is HELIO taken?+curl "https://three.ws/api/crypto/symbol?ticker=HELIO"++# 2. (paid, $5 USDC via x402) launch it — your x402 client handles the 402 dance+curl -X POST https://three.ws/api/x402/pump-launch \+ -H 'Content-Type: application/json' \+ -d '{+ "name": "Helios",+ "symbol": "HELIO",+ "imageUrl": "https://example.com/helios.png",+ "description": "A sun-themed community coin.",+ "creator": "wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV",+ "twitter": "https://x.com/heliocoin",+ "vanityPrefix": "HEL"+ }'++# 3. (free) confirm it landed on the live launch feed+curl "https://three.ws/api/crypto/launches"+```++See [x402 buyer client](x402-buyer.md) for how to satisfy the 402 challenge in+code (the `curl` above shows the shape, not the payment headers).++## Output++```json+{+ "mint": "HEL1oXyz…",+ "signature": "5xY…sig",+ "creator": "wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV",+ "name": "Helios",+ "symbol": "HELIO",+ "metadataUri": "https://ipfs.io/ipfs/Qm…",+ "network": "mainnet",+ "explorer": "https://solscan.io/tx/5xY…sig",+ "pumpfun_url": "https://pump.fun/coin/HEL1oXyz…",+ "vanity_prefix": "HEL",+ "vanity_suffix": null,+ "vanity_iterations": 4821,+ "vanity_duration_ms": 190+}+```++`mint`, `signature`, `metadataUri`, and `pumpfun_url` are guaranteed on success.++## Networks & settlement++Pay in **USDC on Base or Solana mainnet** (the 402 challenge advertises both). The+token itself always deploys on **Solana mainnet** — pump.fun is mainnet-only.++## Correctness guarantees++- **Validation before payment.** A missing `name`/`symbol`, a request with+ neither `metadataUri` nor `imageUrl`, or a malformed field is rejected `400`+ **before** settlement — a bad request never charges you.+- **Failed deploy costs nothing.** The launch runs after payment verification but+ **before** settlement. A bad image URL, IPFS failure, or RPC error throws before+ settle, so the buyer is not charged for a launch that didn't happen.+- **Idempotent per payment.** When your x402 client sends a payment identifier, a+ same-proof retry replays the **same** mint + signature instead of launching a+ second token.++## Related++- [x402 paid endpoints](x402-endpoints.md) — the full catalog and pricing.+- [Crypto Data API](do-i-need-crypto.md) — the free `symbol` and `launches`+ endpoints that bookend a launch.+- [Repo → Coin Launcher](pump-launch-repos.md) — the batch/CLI launcher that+ routes 100% of creator rewards to a GitHub identity (shares the same engine).+- [x402 protocol](x402.md) — challenge/settle mechanics.diff --git a/docs/start-here.md b/docs/start-here.mdindex 074c29580..b9a919cf1 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -67,6 +67,8 @@ If you're here to create and share agents rather than write code, follow this pa- **Meeting avatars in the worlds?** → Press <kbd>I</kbd> on anyone in `/play`, `/city`, a coin world, or `/agora` to see who they are — the [avatar inspector](./avatar-inspector.md) shows their reputation, wallet, and profile- **Trading?** → [The trading surfaces](./trading-surfaces.md) maps the solo stack (Radar, Coin Intelligence, Live Trade Feed, Watchlist, Mission Control); [trading arenas](./trading-arenas.md) covers tournaments, the theater, vaults, and swarms; [Oracle](./oracle.md) is the conviction engine underneath all of it- **Trusting an agent with money?** → [Custody you can verify](./custody.md) — spend limits, freeze, Merkle proof-of-custody, and social recovery; [claim your wallet](./trader-card.md) turns any pump.fun track record into a public, provable Trader Card. Every real-funds feature sits behind the [risk acknowledgment](./risk-acknowledgment.md) — read the [Risk Disclosure](https://three.ws/legal/risk) before committing anything+- **Vetting a counterparty before you pay it?** → [Trust primitives](./trust-primitives.md) — the cross-chain Agent Reputation endpoint scores ANY wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence, in one paid call, before your agent transacts+- **Want a branded on-chain address?** → [Vanity grinder](./vanity.md) — grind a Solana address that starts with your ticker (branded token mint or agent/treasury wallet) in one paid USDC call; keypair or importable mnemonic, nothing stored, optional sealed delivery, plus a provably-fair variant and a pre-ground premium inventory- **Going Pro?** → [Paid plans](./plan-checkout.md) — upgrade with a single on-chain payment in USDC, SOL, or $THREE (the platform coin takes 20% off); [hold-to-access](./hold-to-access.md) covers the separate hold-$THREE tier ladder- **Developer docs** → Read the [Introduction](./introduction.md) for the full technical picture- **Your agent needs a face?** → [OKX.AI marketplace services](./okx-marketplace.md) — the Agent Identity Studio and the pay-per-call 3D services other agents buy from us; demo identities at [/agent-identities](/agent-identities)diff --git a/docs/trust-primitives.md b/docs/trust-primitives.mdnew file mode 100644index 000000000..7ea6da63a--- /dev/null+++ b/docs/trust-primitives.md@@ -0,0 +1,233 @@+# Trust primitives++A trust primitive answers one question an autonomous agent has right before it acts:+**"Should I trust the thing on the other side of this transaction?"** Before Agent A+pays, trades with, or delegates to Agent B, it needs B's trustworthiness — from real+evidence, not a self-reported rating.++three.ws exposes this as a single paid endpoint that works on **any counterparty, on+any chain**, regardless of which platform that counterparty was minted on.++---++## Cross-chain Agent Reputation++**`GET /api/x402/agent-reputation?subject=<identifier>`** — $0.01 USDC per call+(Base or Solana mainnet, via [x402](./x402.md)).++Pass any counterparty identifier. The type is auto-detected and scored from whatever+real on-chain evidence exists for it:++| You pass | Detected as | Scored from |+|---|---|---|+| A Solana wallet (base58) | `solana_wallet` | signature history, account age, SOL balance, denylist, and — if it's a known three.ws agent wallet — its settled agent-payment record |+| A pump.fun / SPL mint (base58) | `solana_mint` | the owning agent's settled payments + attestations (three.ws mints) **or** live DexScreener market signals (external mints) |+| An EVM address (`0x…`) | `evm_wallet` | transaction count (nonce), native-asset holdings priced to USD |+| An ERC-8004 agent id (`42` or `erc8004:8453:42`) | `erc8004_agent` | the ERC-8004 reputation registry (feedback average × count) + the bound agent wallet's EVM activity/holdings |+| A three.ws `agent_id` (UUID) | `threews_agent` | the three.ws on-chain index: confirmed pump.fun agent-payments, distinct payers, failure rate, and signed Solana attestations |++`?chain=<id>` sets the EVM chain for a bare EVM address or ERC-8004 id (default `8453` / Base).+`agent_id=<uuid>` is still accepted as an alias for `subject` so existing callers don't break.++### Response++```json+{+ "subject": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "subjectType": "solana_mint",+ "score": 71,+ "tier": "high",+ "signals": {+ "dimensions": {+ "activity": { "available": true, "weight": 25, "norm": 0.62, "points": 16, "value": 124 },+ "age": { "available": true, "weight": 15, "norm": 0.48, "points": 7, "days": 176 },+ "counterparties": { "available": true, "weight": 15, "norm": 0.72, "points": 11, "value": 18 },+ "holdings": { "available": true, "weight": 10, "norm": 1.0, "points": 10, "usd": 412000 },+ "reliability": { "available": true, "weight": 15, "norm": 0.98, "points": 15, "failure_rate": 0.02 },+ "attestations": { "available": true, "weight": 20, "norm": 0.6, "points": 12, "count": 6, "avg_feedback": null }+ },+ "weight_considered": 100+ },+ "evidence": [+ { "kind": "solana_token", "ref": "https://solscan.io/token/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" },+ { "kind": "threews_agent", "ref": "/agent/7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55" }+ ],+ "caveats": [],+ "ts": "2026-07-07T00:00:00Z"+}+```++- **`score`** — 0–100, or `null` when the subject can't be scored (see below).+- **`tier`** — `unknown` · `low` · `medium` · `high` · `elite`.+- **`signals.dimensions`** — the per-dimension breakdown, so the score is auditable, not a black box.+- **`evidence`** — links you can follow to the raw on-chain source for each signal.+- **`caveats`** — every dimension that couldn't be read for this subject, spelled out.++---++## The score rule++The score is a **deterministic**, available-weighted average of six trust dimensions.+Given the same signals it always returns the same score — the scoring function is pure+and unit-tested (`tests/subject-reputation.test.js`); only the signal-gathering is live.++| Dimension | Weight | Saturates at | Real signal |+|---|---:|---|---|+| **activity** | 25 | 200 tx/payments | transaction / confirmed-payment count |+| **age** | 15 | 365 days | account age (first on-chain activity) |+| **counterparties** | 15 | 25 | distinct payers / peers |+| **holdings** | 10 | $1,000 | native + token value held on-chain (USD) |+| **reliability** | 15 | — | `1 − settlement failure rate` |+| **attestations** | 20 | 10 | signed Solana attestations / ERC-8004 feedback |++Each dimension is normalized to `0..1` (value ÷ saturation cap, clamped). The score is:++```+score = round( 100 × Σ(weightᵢ × normᵢ) / Σ(weightᵢ) ) over available dimensions only+```++**Only the dimensions that could actually be read are counted** — in both the numerator+and the denominator. A subject we can only read two dimensions for is scored fairly+against its own evidence, not penalised for chains we couldn't reach. Every unread+dimension becomes a caveat.++Two overrides:++- **ERC-8004 feedback quality** — a net-negative feedback average scales the attestation+ contribution *down* (never up); neutral/positive feedback counts in full.+- **Denylist** — a subject on the three.ws denylist is capped at score `10` regardless of+ any positive signal. A known-bad counterparty is never "medium trust" because it has volume.++### Tier bands++| Score | Tier |+|---|---|+| `null` | `unknown` |+| 0–29 | `low` |+| 30–59 | `medium` |+| 60–84 | `high` |+| ≥ 85 | `elite` |++### Never a fabricated score++- **Unknown / unscannable subject** → HTTP 200 with `score: null`, `tier: "unknown"`, and an+ explicit caveat. The endpoint never invents a number.+- **A data source is down** → the score degrades to whatever *is* readable, and the missing+ source is named in `caveats`. The call never 500s.++---++## Batch mode++**`POST /api/x402/agent-reputation`** with `{ "mode": "batch", "subjects": [...] }` scores up+to 25 arbitrary counterparties (any chain, auto-detected) in one paid call:++```json+{ "mode": "batch", "subjects": ["<solana_wallet>", "0x<evm>", "42"], "chain": 8453 }+```++Returns `{ mode, count, scored_count, unknown_count, avg_score, subjects: [ …full result each… ] }`.++The same POST route also serves three.ws-fleet monitoring over the platform's indexed+active-agent set: `mode: "sweep"` (fleet average + flagged low-trust agents),+`mode: "leaderboard"` (top N by score), and `mode: "decay_report"` (agents whose score+dropped >10 points). See the [x402 catalog](./x402.md).++---++## Who uses this, and why us++A payments agent about to settle an invoice, a trading agent about to route an order to a+market maker, or an orchestrator about to delegate a task all face the same decision: is+this counterparty safe? Competing reputation endpoints only know agents minted on their own+platform — useless the moment the counterparty is from somewhere else. This one reads Solana,+every major EVM chain, the ERC-8004 registry, and the three.ws on-chain index behind a single+call, so an agent can vet **whoever** it's about to transact with. That's why an outside agent+has a reason to pay for it.++---++## Cross-platform On-Chain Identity Verifier++Reputation answers *"should I trust them?"*. Identity answers the question that comes+first: *"are they who they say they are?"* Before Agent A pays a counterparty that+claims **"I am the deployer of contract X"** or **"I own wallet W / name N / agent id+42"**, it needs cryptographic proof the identity↔address link is real — not a+self-report.++**`GET /api/x402/onchain-identity-verify?identity=<id>&address=<addr>&chain=<caip2>`**+— $0.005 USDC per call (Base or Solana mainnet, via [x402](./x402.md)).++It verifies a **claim** that `identity` controls `address`, for **any** identity type,+on any chain — regardless of the platform the counterparty came from:++| `identity` you pass | Detected as | Verified from (real source) |+|---|---|---|+| An ENS name (`vitalik.eth`) | `ens` | ENS forward + reverse resolution (Ethereum RPC) |+| An SNS name (`bonfida.sol`) | `sns` | SNS resolution + favorite-domain reverse lookup (Solana RPC / Bonfida) |+| An EVM wallet (`0x…`) | `evm_address` | contract **deploy tx + deployer** (Etherscan V2) and/or the contract's `owner()` getter |+| A Solana wallet (base58) | `solana_address` | SPL **mint authority**, **freeze authority**, and Metaplex **update authority** of the claimed mint |+| An ERC-8004 id (`eip155:8453:42` or `8453:42`) | `erc8004` | Identity Registry `ownerOf(id)` + `getAgentWallet(id)` |+| A three.ws `agent_id` (UUID) | `threews_agent_id` | the canonical `meta.onchain` deploy record: deploy tx, owner wallet, metadata URI |++`chain` is an optional CAIP-2 hint (`eip155:1`, `eip155:8453`, `solana:5eykt4Us…`); it's+inferred from the identity/address shape when omitted. The legacy `agent_id` ++`contract_or_mint` params are still accepted as aliases so existing callers don't break.++### Response++```json+{+ "claim": { "identity": "vitalik.eth", "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "chain": "eip155:1" },+ "identity_type": "ens",+ "verified": true,+ "method": "ens-resolution",+ "evidence": [+ { "kind": "ens_forward_resolution", "ref": "vitalik.eth", "detail": "resolves to 0xd8da…6045" },+ { "kind": "ens_reverse_resolution", "ref": "0xd8dA…6045", "detail": "primary name vitalik.eth" }+ ],+ "caveats": [],+ "ts": "2026-07-07T00:00:00Z"+}+```++### The evidence model++`evidence[]` is a list of `{ kind, ref, detail }` — each `ref` is a concrete on-chain+handle (a tx hash, a wallet, a registry entry, a resolved name) you can follow to the raw+source. The verdict is **never** a bare boolean:++- **`verified: true`** — concrete on-chain evidence links the identity to the address (the+ name resolves to it, the identity deployed / owns the contract, holds the mint authority,+ or is the registered ERC-8004 owner). Always accompanied by ≥1 evidence item.+- **`verified: false`** — the authoritative source was read and links the address to+ **someone else** (or nobody). A disproof, backed by what was read.+- **`verified: "unverifiable"`** — not enough could be read to decide: the name didn't+ resolve, the explorer key is absent, the RPC was down, or the address is an opaque EOA with+ nothing on-chain to compare. `caveats[]` names exactly what's missing. **This is never a+ false positive** — an undetermined claim is never reported as true.++### Guarantees++- **No false positives.** `verified: true` requires concrete on-chain evidence; every "true"+ branch attaches the evidence that proves it.+- **Degrade, never fail.** A down explorer/RPC downgrades one evidence source to a caveat;+ bad input is a `400`; the endpoint never `500`s.+- **Two distinct EOAs can't be faked as linked.** With no contract, mint, or name to compare,+ a wallet-vs-wallet claim returns `unverifiable` and asks for a name / ERC-8004 id instead —+ it won't guess.++### Who uses this, and why us++A payments agent settling an invoice, a trading agent routing to a market maker, or an+orchestrator delegating a task all hit the same pre-flight check: *is this counterparty the+entity it claims to be?* Competing verifiers only know identities minted on their own+platform. This one reads ENS, SNS, every major EVM chain's contract-creation + ownership,+the ERC-8004 registry, and the three.ws on-chain index behind a single call — so an agent+can verify **whoever** it's about to transact with. Pair it with+[Cross-chain Agent Reputation](#cross-chain-agent-reputation): verify *who* they are, then+score *whether to trust* them.++---++See also: [x402 paid endpoints](./x402.md) · [Agent Bouncer](./api-reference.md) · [ERC-8004 identity](./erc8004.md)diff --git a/docs/vanity.md b/docs/vanity.mdnew file mode 100644index 000000000..c2422afd8--- /dev/null+++ b/docs/vanity.md@@ -0,0 +1,184 @@+# Vanity — brand a Solana address in one paid call++Three x402 endpoints that hand an agent a **branded Solana address** — one that+starts with your ticker/prefix and/or ends with a chosen suffix — with no wallet,+no account, and no SOL. Pay per call in USDC over the [x402](x402.md) rail and the+server grinds (or delivers from stock) a brand-new keypair that matches.++| Endpoint | What it is | Chars | Price | Pick it when |+| --- | --- | --- | --- | --- |+| [`/api/x402/vanity`](#tier-1--live-grinder) | Live grind, fresh keypair per request | ≤3 | $0.01–$0.50 | You want a custom address **now**, cheaply. |+| [`/api/x402/vanity-verifiable`](#tier-2--provably-fair-grinder) | Live grind **+ signed proof** it was ground fresh | ≤3 | $0.02–$0.40 | You need to **prove** no copy was kept (commit–reveal receipt). |+| [`/api/x402/vanity-premium`](#tier-3--premium-inventory) | Buy a **pre-ground** long address from stock | 4–5+ | $1–$50 | You want a rarer prefix too slow to grind on demand. |++All three are **keyless**: no API key, no signup. The Solana rail is the platform+default; Base mainnet is offered when a facilitator can settle it. The live 402+challenge always quotes the exact price for the pattern you asked for — read it,+don't hardcode.++## Which agent uses this, and why us++A **token-launch bot** that wants its mint address to start with the ticker+(`PUMP…`, `DOGE…`). A **treasury/agent-wallet provisioner** that wants every+managed wallet recognizable at a glance. A **naming/branding service** an agent+calls mid-task to get an on-brand address as the payoff step. Grinding a vanity+key yourself means running an ed25519 miner, managing the output key, and burning+CPU you'd rather not. This collapses it into **one HTTP call priced in USDC** —+the currency an agent on Base or Solana already holds — and the key is delivered+once, over TLS, and never stored.++> **What can you actually match?** Base58 excludes `0`, `O`, `I`, `l`. An address+> is 32 random bytes Base58-encoded, so its **leading** characters are not+> uniformly distributed — a given prefix can be markedly harder than the naive+> 58ⁿ estimate, while suffix characters are uniform. Each extra character+> multiplies expected work by ~58, which is why the char caps and price ladder+> climb steeply.++---++## Tier 1 — live grinder++`GET /api/x402/vanity?prefix=<base58>&suffix=<base58>` grinds a brand-new Solana+Ed25519 keypair in a Rust/WASM engine (~25k keypairs/sec) under a 45-second+budget and returns it. Settlement runs **only after a successful grind**, so an+exhausted budget (rare) costs nothing and can be retried.++### Formats++- **`format=keypair`** (default) — returns the public `address` plus its secret+ key in two forms: `secretKeyBase58` (import into Phantom / Solflare) and+ `secretKey` (a 64-byte int array — save as a Solana CLI keypair JSON). Combined+ pattern capped at **3 Base58 chars**.+- **`format=mnemonic`** — returns a **BIP-39 seed phrase** (`strength=128` → 12+ words, default; `strength=256` → 24 words) whose derived key at+ `m/44'/501'/0'/0'` (Phantom's default path) lands on the vanity address.+ Importable as a recovery phrase into any wallet. Seed-phrase grinding runs+ ~100× slower (PBKDF2-HMAC-SHA512 per attempt), so it is capped at **2 chars**.++### Price ladder++Difficulty-tiered by combined prefix+suffix length (USDC, 6 decimals):++| Combined length | `keypair` | `mnemonic` |+| --- | --- | --- |+| 1 char | $0.01 | $0.05 |+| 2 chars | $0.05 | $0.50 |+| 3 chars | $0.25 | — (capped at 2) |++Ops can override with `X402_PRICE_VANITY=<atomics>` for the base tier; the live+402 quotes the exact tier for the requested pattern.++### Inputs++| Param | Notes |+| --- | --- |+| `prefix` | Base58 chars the address must start with. Combined with `suffix`, ≤3 (keypair) or ≤2 (mnemonic). |+| `suffix` | Base58 chars the address must end with. |+| `ignoreCase` | `1`/`true` matches the pattern case-insensitively (faster, less specific). |+| `format` | `keypair` (default) or `mnemonic`. |+| `strength` | Mnemonic only: `128` (12 words, default) or `256` (24 words). |+| `sealTo` | Optional X25519 public key (Base58/Base64url/hex) — see [Security model](#security-model). |++### Example++```bash+# Grind an address starting with "So" (2-char keypair tier, $0.05).+# @x402/fetch handles the 402 → pay → retry handshake automatically.+curl "https://three.ws/api/x402/vanity?prefix=So"+```++```jsonc+{+ "address": "SoV3...", // starts with your prefix+ "prefix": "So",+ "suffix": null,+ "format": "keypair",+ "secretKeyBase58": "…", // the ground secret — capture it, it is never re-served+ "secretKey": [/* 64 bytes */],+ "mnemonic": null,+ "attempts": 3120,+ "durationMs": 140,+ "expectedAttempts": 3364,+ "network": "solana",+ "explorerUrl": "https://solscan.io/account/SoV3...",+ "certificate": { /* signed proof-of-grind, contains no secret */ },+ "verifyUrl": "https://three.ws/vanity/verify"+}+```++Longer than 3 chars? Grind it in the browser at [`/vanity`](https://three.ws/vanity)+or buy it from [premium inventory](#tier-3--premium-inventory).++### Security model++- **Nothing is ever stored.** The secret exists only in the response body, served+ once over TLS. The x402 replay/idempotency cache **strips** the plaintext secret+ from its stored copy — a replayed payment gets the public metadata plus an+ explicit "secret omitted, grind again" marker, never a spendable key.+- **`sealTo` (optional confidential delivery).** Supply your 32-byte X25519 public+ key and the secret is sealed to it with ECIES (`x25519-hkdf-sha256-aes256gcm`).+ The plaintext secret fields are then omitted entirely; you get a `sealedSecret`+ envelope you open client-side with the matching private key. The plaintext never+ appears in the response, a proxy log, or the cache.+- **Proof-of-grind certificate.** Every response carries a signed, offline-+ verifiable `certificate` (`three-pog/v1`) attesting the pattern, address,+ difficulty, and a freshness nonce — it contains **no secret**. Verify it at+ [`/vanity/verify`](https://three.ws/vanity/verify); the attestation public key is+ published at [`/.well-known/three-vanity.json`](https://three.ws/.well-known/three-vanity.json).++---++## Tier 2 — provably-fair grinder++`GET /api/x402/vanity-verifiable` is the trust-minimized sibling. Same pay-per-call+rails, but every key is ground under a **commit–reveal seed-mixing protocol**+(`three-vanity/v1`) and delivered with a **signed receipt** a buyer can verify+after the fact with open-source tooling — proving the key was generated fresh from+entropy the server committed to *before* it knew the result, that the buyer's own+`clientSeed` was mixed in, and that no copy was kept.++Because the verifier must reproduce the exact candidate stream, grinding walks a+deterministic pure-JS Ed25519 stream (slower than WASM), so it is capped at **3+chars** and priced $0.02–$0.40. `sealTo` is strongly recommended here. Verify with+`@three-ws/solana-agent`'s `verifyVanityReceipt()`, the CLI+(`scripts/verify-vanity-receipt.mjs`), or [`/vanity/verify`](https://three.ws/vanity/verify).++The full wire format is specified in [PROTOCOL-vanity.md](PROTOCOL-vanity.md).++---++## Tier 3 — premium inventory++`GET /api/x402/vanity-premium` is the **sell-from-stock** tier: long (4–5+ char)+brandable addresses ground ahead of time on batch CPU and held encrypted.++- **Browse** (free, no payment): `GET /api/x402/vanity-premium` with no `address`+ returns the available patterns, rarity tiers, and prices. Browsable in the UI at+ [`/vanity/premium`](https://three.ws/vanity/premium).+- **Buy**: `GET /api/x402/vanity-premium?address=<base58>` pays via x402. Price+ scales with grind difficulty ($1–$50). The key is delivered **exactly once** and+ its stored ciphertext is **destroyed on delivery** (delete-after-reveal) — three.ws+ cannot recover or re-send it. `sealTo` works here too.++> **Custody honesty (non-negotiable).** These keys were *generated by three.ws*,+> not by you. For anything of value, use a bought address as a **token mint+> address** or **sweep assets to a wallet you generated yourself** — do not use it+> as a long-term treasury. Every listing and delivery says this plainly.++---++## How agents discover these++All three are paid x402 resources published in the discovery document at+[`/.well-known/x402.json`](https://three.ws/.well-known/x402.json) (served by+`api/wk.js`), so the CDP Bazaar / agentic.market and x402scan crawlers index them.+Each entry ships a complete input schema — an agent can grind an address from the+schema alone. Run `node scripts/verify-x402-discovery.mjs` to confirm the live 402+challenges and the discovery doc stay in parity.++## Related++- [x402 endpoints overview](x402-endpoints.md)+- [three-vanity/v1 protocol spec](PROTOCOL-vanity.md)+- [Pump Launcher](pump-launcher.md) — accepts an optional vanity mint prefix/suffix+- Web grinder + verifier: [`/vanity`](https://three.ws/vanity), [`/vanity/verify`](https://three.ws/vanity/verify)diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.mdindex c9d9cad90..f0bd09026 100644--- a/docs/x402-endpoints.md+++ b/docs/x402-endpoints.md@@ -110,7 +110,7 @@ for to feed the oracle and sniper.| Endpoint | Default | Returns || ----------------------------------- | --------- | ------------------------------------------ |-| `/api/x402/agent-reputation` | $0.01 | On-chain agent reputation summary. |+| `/api/x402/agent-reputation` | $0.01 | Cross-chain 0–100 trust score for any wallet/mint/agent id ([trust primitives](trust-primitives.md)). || `/api/x402/agent-bouncer` | $0.01 | Access-gate decision for an agent/wallet. || `/api/x402/onchain-identity-verify` | $0.005 | Verifies an on-chain identity claim. || `/api/x402/skill-marketplace` | $0.001 | Skill listings + pricing. |@@ -122,6 +122,7 @@ for to feed the oracle and sniper.| Endpoint | Default | Returns || ----------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------- || `/api/x402/forge` | tiered | Text/image → 3D model (price by tier; GPU-bound). See [Avatar pipeline](avatar-pipeline.md). |+| `/api/x402/pipeline` | per stage | **One call, full 3D asset pipeline** — text or GLB in, rigged/optimized game-ready GLB out. Ordered chain of `generate → rig → remesh → gameready → stylize`; the 402 quote is the exact sum of the requested stages. Poll free at `/api/forge?job=<id>` for per-stage progress. See [3D pipeline](3d-pipeline.md). || `/api/x402/pipeline-rig` | $0.05 | **Pipeline — Rig.** Static GLB in → animation-ready rigged GLB out (skeleton + skin weights). One paid call, durable URL. See [3D pipeline](3d-pipeline.md). || `/api/x402/pipeline-remesh` | $0.03 | **Pipeline — Remesh.** Retopologize a GLB (triangle/quad/lowpoly, repair, decimate to a face budget) with texture re-baked. GLB in → GLB out. See [3D pipeline](3d-pipeline.md). || `/api/x402/pipeline-gameready` | $0.03 | **Pipeline — Game-Ready.** Retopologize to a poly budget + PBR re-bake for real-time engines. GLB in → engine-ready GLB out. See [3D pipeline](3d-pipeline.md). |@@ -137,9 +138,10 @@ for to feed the oracle and sniper.| Endpoint | Default | Returns || ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------- |-| `/api/x402/pump-launch` | $5.00 | Launch monitoring / a managed launch. |-| `/api/x402/vanity`, `/api/x402/vanity-verifiable` | per grind | Solana vanity address mining (verifiable variant returns proof). |-| `/api/x402/vanity-premium` | $1–$50 by rarity | **Premium inventory** — buy a pre-ground 4–5+ char brandable address from stock. GET lists available patterns + prices (free); `?address=…` buys via x402 and delivers the key **once** (ciphertext destroyed on delivery). Browsable at `/vanity/premium`. |+| [`/api/x402/pump-launch`](pump-launcher.md) | $5.00 | **Pump Launcher** — deploy a brand-new pump.fun token in one paid call. No SOL, no wallet, no account: the server fronts the deploy cost and signs the create tx; you pay USDC. Optional vanity mint. Full flow + funnel in [pump-launcher.md](pump-launcher.md). |+| [`/api/x402/vanity`](vanity.md) | $0.01–$0.50 | **Vanity Grinder** — grind a brand-new Solana address that starts with your ticker/prefix and/or ends with a suffix, for a branded token mint or agent/treasury wallet. Keypair or importable BIP-39 mnemonic; ≤3 chars; nothing stored; optional `sealTo` ECIES. Full doc: [vanity.md](vanity.md). |+| [`/api/x402/vanity-verifiable`](vanity.md#tier-2--provably-fair-grinder) | $0.02–$0.40 | **Provably-fair grinder** — same grind with a signed commit–reveal receipt proving the key was ground fresh and never kept. Spec: [PROTOCOL-vanity.md](PROTOCOL-vanity.md). |+| [`/api/x402/vanity-premium`](vanity.md#tier-3--premium-inventory) | $1–$50 by rarity | **Premium inventory** — buy a pre-ground 4–5+ char brandable address from stock. GET lists available patterns + prices (free); `?address=…` buys via x402 and delivers the key **once** (ciphertext destroyed on delivery). Browsable at `/vanity/premium`. || `/api/x402/pay-by-name` | per call | Resolve and pay an SNS/ENS name (see [Agent wallets](agent-wallets.md)). || `/api/x402/did` | per call | Decentralized identifier resolution. || `/api/x402/billboard` | $0.05 | Post to the on-platform billboard. |@@ -190,6 +192,7 @@ input and do not promote any specific token.## Related+- [Pump Launcher](pump-launcher.md) — the full launch flow, inputs/outputs, and the free `symbol` → launch → `launches` funnel.- [x402 protocol](x402.md) — the challenge/settle mechanics.- [x402 buyer client](x402-buyer.md) — how to pay these endpoints in code.- [x402 revenue & receipts](x402-revenue.md) — where settled payments are recorded and how to read endpoint revenue.diff --git a/pages/crypto.html b/pages/crypto.htmlnew file mode 100644index 000000000..27af15be8--- /dev/null+++ b/pages/crypto.html@@ -0,0 +1,726 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(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, viewport-fit=cover" />+ <title>Crypto Data API — Free, keyless crypto data for AI agents · three.ws</title>+ <meta+ name="description"+ content="One free, keyless API for the crypto data an AI agent needs mid-task: token snapshots, rug/security signals, holders, pump.fun launches, bonding-curve status, whale flow, trending, wallets and ticker checks. No key, no account, no paywall."+ />+ <meta name="robots" content="index, follow" />+ <link rel="canonical" href="https://three.ws/crypto" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Free crypto data for AI agents — one keyless API · three.ws" />+ <meta+ property="og:description"+ content="Token snapshots, rug checks, holders, pump.fun launches, bonding-curve status, whale flow, trending & wallets — free and keyless. Wire it into your agent in one fetch."+ />+ <meta property="og:url" content="https://three.ws/crypto" />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Free crypto data for AI agents — one keyless API · three.ws" />+ <meta+ name="twitter:description"+ content="Token snapshots, rug checks, holders, pump.fun launches, bonding & whale flow — free, keyless, one fetch."+ />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />++ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <script defer src="/footer-newsletter.js"></script>++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@type": "WebAPI",+ "name": "three.ws Crypto Data API",+ "description": "Free, keyless crypto data API for AI agents: token market snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios and ticker-availability checks.",+ "url": "https://three.ws/crypto",+ "documentation": "https://three.ws/crypto",+ "provider": { "@type": "Organization", "name": "three.ws", "url": "https://three.ws" },+ "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" }+ }+ </script>++ <style>+ /* ─────────────────────────────────────────────────────────────+ /crypto — Free Crypto Data API docs & landing.+ All values come from the design tokens in /tokens.css (loaded+ via /style.css). Nothing hardcoded that a token already names.+ ───────────────────────────────────────────────────────────── */+ .cx-main {+ max-width: 1100px;+ margin: 0 auto;+ padding: 0 var(--space-lg) var(--space-2xl);+ width: 100%;+ }+ .cx-main :where(h2) {+ font: var(--weight-bold) var(--text-2xl) / var(--leading-tight) var(--font-display);+ color: var(--ink-bright);+ margin: 0 0 var(--space-xs);+ letter-spacing: -0.01em;+ }+ .cx-section { padding-block: var(--space-2xl); border-top: 1px solid var(--stroke); }+ .cx-section:first-of-type { border-top: 0; }+ .cx-section-lede { color: var(--ink-dim); max-width: 62ch; margin: 0 0 var(--space-lg); line-height: var(--leading-normal); }++ /* ── Hero ─────────────────────────────────────────────────── */+ .cx-hero {+ position: relative;+ text-align: center;+ padding: clamp(var(--space-2xl), 8vw, 6rem) var(--space-lg) var(--space-2xl);+ max-width: 1100px;+ margin: 0 auto;+ overflow: hidden;+ }+ .cx-hero::before {+ content: "";+ position: absolute; inset: -40% 0 auto 0; height: 70%;+ background: radial-gradient(60% 100% at 50% 0%, var(--accent-soft), transparent 70%);+ pointer-events: none; z-index: -1;+ }+ .cx-hero .eyebrow { justify-content: center; display: inline-flex; align-items: center; gap: 0.5ch; margin-bottom: var(--space-md); }+ .cx-hero h1 {+ font: var(--weight-bold) clamp(2rem, 6vw, 3.4rem) / 1.05 var(--font-display);+ color: var(--ink-bright);+ letter-spacing: -0.02em;+ margin: 0 auto var(--space-md);+ max-width: 18ch;+ }+ .cx-hero h1 em { font-style: normal; color: var(--ink-dim); }+ .cx-hero-sub { color: var(--ink-dim); font-size: var(--text-lg); line-height: var(--leading-normal); max-width: 56ch; margin: 0 auto var(--space-lg); }+ .cx-hero-cta { display: flex; gap: var(--space-sm); justify-content: center; flex-wrap: wrap; }++ .cx-badges { display: flex; flex-wrap: wrap; gap: var(--space-2xs); justify-content: center; margin-top: var(--space-lg); }+ .cx-badge {+ display: inline-flex; align-items: center; gap: 0.5ch;+ font: var(--weight-medium) var(--text-xs) / 1 var(--font-mono);+ color: var(--ink-dim);+ background: var(--surface-1); border: 1px solid var(--stroke);+ padding: 0.5em 0.85em; border-radius: var(--radius-pill);+ }+ .cx-badge svg { width: 0.95em; height: 0.95em; opacity: 0.8; }++ .cx-live-pill {+ display: inline-flex; align-items: center; gap: 0.55ch;+ font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono);+ text-transform: uppercase; letter-spacing: 0.08em;+ padding: 0.5em 0.85em; border-radius: var(--radius-pill);+ background: var(--surface-2); border: 1px solid var(--stroke); color: var(--ink-dim);+ }+ .cx-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ink-faint); flex: none; }+ .cx-dot--live { background: var(--success); box-shadow: 0 0 0 0 var(--success); animation: cx-pulse 2s infinite; }+ @keyframes cx-pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--success) 55%, transparent); } 70% { box-shadow: 0 0 0 6px transparent; } 100% { box-shadow: 0 0 0 0 transparent; } }+ @media (prefers-reduced-motion: reduce) { .cx-dot--live { animation: none; } }++ /* ── Quickstart ───────────────────────────────────────────── */+ .cx-tabs { display: flex; gap: var(--space-3xs); flex-wrap: wrap; margin-bottom: var(--space-sm); }+ .cx-tab {+ font: var(--weight-medium) var(--text-sm) / 1 var(--font-mono);+ color: var(--ink-dim); background: transparent; border: 1px solid transparent;+ padding: 0.55em 0.9em; border-radius: var(--radius-md); cursor: pointer;+ transition: background var(--dur-fast, 120ms) ease, color var(--dur-fast, 120ms) ease;+ }+ .cx-tab:hover { color: var(--ink); background: var(--surface-1); }+ .cx-tab[aria-selected="true"] { color: var(--ink-bright); background: var(--surface-2); border-color: var(--stroke); }+ .cx-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }++ .cx-code {+ position: relative;+ background: var(--bg-1); border: 1px solid var(--stroke);+ border-radius: var(--radius-lg); overflow: hidden;+ }+ .cx-code pre {+ margin: 0; padding: var(--space-md) var(--space-md);+ overflow-x: auto; font: var(--weight-regular) var(--text-sm) / 1.6 var(--font-mono);+ color: var(--ink); tab-size: 2;+ }+ .cx-code code { font: inherit; color: inherit; background: none; white-space: pre; }+ .cx-copy {+ position: absolute; top: var(--space-2xs); right: var(--space-2xs);+ font: var(--weight-medium) var(--text-2xs) / 1 var(--font-mono);+ color: var(--ink-dim); background: var(--surface-2); border: 1px solid var(--stroke);+ padding: 0.5em 0.75em; border-radius: var(--radius-sm); cursor: pointer;+ display: inline-flex; align-items: center; gap: 0.5ch;+ transition: color var(--dur-fast, 120ms) ease, border-color var(--dur-fast, 120ms) ease;+ }+ .cx-copy:hover { color: var(--ink-bright); border-color: var(--stroke-strong); }+ .cx-copy:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .cx-copy.is-done { color: var(--success); border-color: color-mix(in srgb, var(--success) 40%, var(--stroke)); }++ .cx-tok { color: var(--ink-faint); }+ .cx-str { color: var(--success); }+ .cx-key { color: var(--accent); }+ .cx-num { color: var(--warn); }+ .cx-cmd { color: var(--ink-bright); font-weight: var(--weight-medium); }++ /* ── Endpoint table ───────────────────────────────────────── */+ .cx-table-wrap { border: 1px solid var(--stroke); border-radius: var(--radius-lg); overflow-x: auto; background: var(--surface-1); }+ table.cx-table { width: 100%; border-collapse: collapse; min-width: 640px; font-size: var(--text-sm); }+ .cx-table th {+ text-align: left; font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono);+ text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-faint);+ padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--stroke); white-space: nowrap;+ }+ .cx-table td { padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--stroke); vertical-align: top; }+ .cx-table tr:last-child td { border-bottom: 0; }+ .cx-table tbody tr { transition: background var(--dur-fast, 120ms) ease; }+ .cx-table tbody tr:hover { background: var(--surface-2); }+ .cx-table a.cx-ep-link { color: var(--ink-bright); font-weight: var(--weight-medium); text-decoration: none; }+ .cx-table a.cx-ep-link:hover { text-decoration: underline; }+ .cx-table .cx-purpose { color: var(--ink-dim); }+ .cx-meth {+ display: inline-block; font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono);+ color: var(--ink); background: var(--surface-2); border: 1px solid var(--stroke);+ padding: 0.35em 0.55em; border-radius: var(--radius-sm); margin-right: 0.5ch;+ }+ .cx-path { font: var(--weight-regular) var(--text-xs) / 1.4 var(--font-mono); color: var(--ink-dim); word-break: break-all; }+ .cx-free { color: var(--success); font-weight: var(--weight-semibold); }++ .cx-status {+ display: inline-flex; align-items: center; gap: 0.5ch; white-space: nowrap;+ font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono);+ text-transform: uppercase; letter-spacing: 0.06em;+ padding: 0.4em 0.7em; border-radius: var(--radius-pill); border: 1px solid var(--stroke);+ }+ .cx-status--live { color: var(--success); background: color-mix(in srgb, var(--success) 12%, transparent); border-color: color-mix(in srgb, var(--success) 35%, var(--stroke)); }+ .cx-status--soon { color: var(--ink-dim); background: var(--surface-2); }+ .cx-status--probing { color: var(--ink-faint); }++ /* ── Endpoint detail cards ────────────────────────────────── */+ .cx-eps { display: grid; gap: var(--space-lg); }+ .cx-ep {+ scroll-margin-top: 5rem;+ background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg);+ padding: var(--space-lg); display: grid; gap: var(--space-md);+ }+ .cx-ep-head { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--space-md); flex-wrap: wrap; }+ .cx-ep-title { font: var(--weight-bold) var(--text-xl) / 1.2 var(--font-display); color: var(--ink-bright); margin: 0 0 0.25rem; }+ .cx-ep-route { font: var(--weight-regular) var(--text-sm) / 1.4 var(--font-mono); color: var(--ink-dim); }+ .cx-ep-agent {+ background: var(--surface-2); border-left: 2px solid var(--accent);+ border-radius: var(--radius-sm); padding: var(--space-sm) var(--space-md);+ color: var(--ink); font-size: var(--text-sm); line-height: var(--leading-normal);+ }+ .cx-ep-agent b { color: var(--ink-bright); font-weight: var(--weight-semibold); }+ .cx-params { display: grid; gap: var(--space-2xs); font-size: var(--text-sm); }+ .cx-param { display: flex; gap: 0.75ch; align-items: baseline; flex-wrap: wrap; }+ .cx-param code { font: var(--weight-medium) var(--text-xs) / 1 var(--font-mono); color: var(--accent); background: var(--surface-2); padding: 0.3em 0.5em; border-radius: var(--radius-sm); }+ .cx-param .cx-req { color: var(--warn); font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); }+ .cx-param .cx-opt { color: var(--ink-faint); font: var(--weight-medium) var(--text-2xs)/1 var(--font-mono); }+ .cx-param span.cx-pdesc { color: var(--ink-dim); }++ .cx-io { display: grid; gap: var(--space-md); grid-template-columns: 1fr 1fr; }+ @media (max-width: 720px) { .cx-io { grid-template-columns: 1fr; } }+ .cx-io h4 { font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-faint); margin: 0 0 var(--space-2xs); }++ .cx-trybar { display: flex; align-items: center; gap: var(--space-sm); flex-wrap: wrap; }+ .cx-try-out { display: none; margin-top: var(--space-sm); }+ .cx-try-out.is-open { display: block; }+ .cx-try-note { font-size: var(--text-xs); color: var(--ink-faint); }++ /* ── CTA cards ────────────────────────────────────────────── */+ .cx-cta-grid { display: grid; gap: var(--space-md); grid-template-columns: repeat(3, 1fr); }+ @media (max-width: 860px) { .cx-cta-grid { grid-template-columns: 1fr; } }+ .cx-cta-card {+ display: flex; flex-direction: column; gap: var(--space-2xs);+ background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg);+ padding: var(--space-lg); text-decoration: none; color: inherit;+ transition: transform var(--dur-fast, 120ms) ease, border-color var(--dur-fast, 120ms) ease, background var(--dur-fast, 120ms) ease;+ }+ .cx-cta-card:hover { transform: translateY(-2px); border-color: var(--stroke-strong); background: var(--surface-2); }+ .cx-cta-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .cx-cta-tag { font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.08em; color: var(--accent); }+ .cx-cta-card h3 { font: var(--weight-bold) var(--text-lg)/1.2 var(--font-display); color: var(--ink-bright); margin: 0.15rem 0; }+ .cx-cta-card p { color: var(--ink-dim); font-size: var(--text-sm); line-height: var(--leading-normal); margin: 0; }+ .cx-cta-card .cx-cta-go { margin-top: auto; padding-top: var(--space-sm); color: var(--ink-bright); font: var(--weight-medium) var(--text-sm)/1 var(--font-body); display: inline-flex; align-items: center; gap: 0.4ch; }++ .cx-note {+ display: flex; gap: var(--space-sm); align-items: flex-start;+ background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md);+ padding: var(--space-md); color: var(--ink-dim); font-size: var(--text-sm); line-height: var(--leading-normal);+ }+ .cx-note b { color: var(--ink-bright); }+ .cx-anchor { color: inherit; text-decoration: none; }+ .cx-anchor:hover { color: var(--ink-bright); }+ </style>+ </head>+ <body>+ <a href="#cx-endpoints" class="h-skip-link">Skip to endpoints</a>++ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content">+ <!-- ── HERO ────────────────────────────────────────────────── -->+ <section class="cx-hero">+ <div class="eyebrow"><span class="cx-dot cx-dot--live"></span><span>Crypto Data API · Free forever</span></div>+ <h1>Free crypto data for AI agents — <em>one keyless API</em></h1>+ <p class="cx-hero-sub">+ The market snapshot, rug check, holder spread, launch feed and whale flow your agent+ needs mid-task — in a single <code>fetch</code>. No key, no account, no paywall.+ Solana & Base, real sources, honest nulls.+ </p>+ <div class="cx-hero-cta">+ <a class="btn btn--primary btn--lg" href="#cx-quickstart">Copy the quickstart</a>+ <a class="btn btn--secondary btn--lg" href="#cx-endpoints">Browse endpoints</a>+ </div>+ <div class="cx-badges">+ <span class="cx-badge">Free</span>+ <span class="cx-badge">Keyless — no account</span>+ <span class="cx-badge">Solana + Base</span>+ <span class="cx-badge">Real data · DexScreener · Solana RPC · pump.fun</span>+ <span class="cx-live-pill" id="cx-live-count"><span class="cx-dot"></span><span id="cx-live-count-text">Checking live status…</span></span>+ </div>+ </section>++ <div class="cx-main">+ <!-- ── QUICKSTART ─────────────────────────────────────── -->+ <section class="cx-section" id="cx-quickstart">+ <div class="eyebrow">Quickstart</div>+ <h2>One call, real data back</h2>+ <p class="cx-section-lede">+ Every endpoint is a plain HTTP GET. No auth header, no SDK required. Point your agent+ at the base URL <code>https://three.ws/api/crypto</code> and read JSON. Here's a token+ snapshot for <code>$THREE</code> — swap in any mint or pair address.+ </p>+ <div class="cx-tabs" role="tablist" aria-label="Quickstart language">+ <button class="cx-tab" role="tab" aria-selected="true" data-qtab="curl" id="qt-curl">curl</button>+ <button class="cx-tab" role="tab" aria-selected="false" data-qtab="js" id="qt-js">JavaScript</button>+ <button class="cx-tab" role="tab" aria-selected="false" data-qtab="py" id="qt-py">Python</button>+ </div>+ <div class="cx-code" id="cx-quickstart-code"><!-- filled by JS --></div>+ <p class="cx-try-note" style="margin-top:var(--space-sm)">+ Base URL: <code>https://three.ws/api/crypto</code> · discovery index:+ <a class="cx-anchor" href="/api/crypto" target="_blank" rel="noopener"><code>GET /api/crypto</code></a> ·+ machine spec: <a class="cx-anchor" href="/api/crypto/openapi.json" target="_blank" rel="noopener"><code>openapi.json</code></a>+ </p>+ </section>++ <!-- ── ENDPOINT TABLE ─────────────────────────────────── -->+ <section class="cx-section" id="cx-endpoints">+ <div class="eyebrow">Endpoints</div>+ <h2>Nine free reads, one bundle</h2>+ <p class="cx-section-lede">+ Each answers a question an agent actually has mid-trade. Status is probed live against+ production — endpoints still shipping show <b>Coming soon</b> and light up automatically+ once they deploy.+ </p>+ <div class="cx-table-wrap">+ <table class="cx-table">+ <thead>+ <tr><th>Endpoint</th><th>What it answers</th><th>Method & path</th><th>Price</th><th>Status</th></tr>+ </thead>+ <tbody id="cx-table-body"><!-- filled by JS --></tbody>+ </table>+ </div>+ </section>++ <!-- ── PER-ENDPOINT DETAIL ────────────────────────────── -->+ <section class="cx-section">+ <div class="eyebrow">Reference</div>+ <h2>Every endpoint, with a real example</h2>+ <p class="cx-section-lede">+ Response shapes below are the API's stable schema. Hit <b>Try it live</b> to run the real+ call from your browser — you'll see live JSON where an endpoint is deployed, or the+ designed “coming soon” state where it isn't yet.+ </p>+ <div class="cx-eps" id="cx-ep-cards"><!-- filled by JS --></div>+ </section>++ <!-- ── CTA ────────────────────────────────────────────── -->+ <section class="cx-section" id="cx-build">+ <div class="eyebrow">When you're ready to build</div>+ <h2>Free data in. Paid uniques out.</h2>+ <p class="cx-section-lede">+ The data API is the on-ramp. When your agent needs to <i>act</i> — mint a token, claim a+ vanity address, generate a 3D asset — these are the paid, best-in-class endpoints it graduates to.+ </p>+ <div class="cx-cta-grid">+ <a class="cx-cta-card" href="/launcher">+ <span class="cx-cta-tag">Pump Launcher</span>+ <h3>Launch a token</h3>+ <p>Your agent mints and launches a pump.fun coin end-to-end — metadata, image, curve — from one call.</p>+ <span class="cx-cta-go">Open the launcher →</span>+ </a>+ <a class="cx-cta-card" href="/vanity-wallet">+ <span class="cx-cta-tag">Vanity</span>+ <h3>Claim a vanity address</h3>+ <p>Grind a custom Solana address with your ticker or brand baked into it — verifiable, on demand.</p>+ <span class="cx-cta-go">Get a vanity wallet →</span>+ </a>+ <a class="cx-cta-card" href="/forge">+ <span class="cx-cta-tag">Forge</span>+ <h3>Generate a 3D model</h3>+ <p>Turn a token or a text prompt into a textured GLB your agent can wear, embed, or take into AR.</p>+ <span class="cx-cta-go">Open Forge →</span>+ </a>+ </div>+ <div class="cx-note" style="margin-top:var(--space-lg)">+ <span>💡</span>+ <span>+ Building an autonomous agent? Pair this with <a class="cx-anchor" href="/pay"><b>agent payments (x402)</b></a>+ so it can pay for the paid endpoints itself, and <a class="cx-anchor" href="/docs"><b>the SDKs & API reference</b></a>+ for the full platform surface.+ </span>+ </div>+ </section>+ </div>+ </main>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>++ <script type="module">+ /* ── The single source of truth for this page ─────────────────+ Table, quickstart, reference cards and the live probe all render+ from ENDPOINTS. Add a row here and the whole page updates. Response+ examples are the endpoints' documented stable schema (see+ prompts/x402-overhaul/01–10). ───────────────────────────────── */+ const BASE = '/api/crypto';+ const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump'; // $THREE — the platform coin+ const SAMPLE_WALLET = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++ const ENDPOINTS = [+ {+ slug: 'token', title: 'Token Snapshot', method: 'GET', path: '/api/crypto/token',+ purpose: 'Full market state for any mint/pair in one call',+ agent: 'A <b>trading or research agent</b> has a token address and needs its current market state before deciding to buy, alert, or ignore — price, liquidity, market cap, 24h change — without juggling DexScreener + an RPC + a price API itself.',+ probe: `${BASE}/token?address=${THREE}`,+ params: [+ ['address', true, 'Mint, pair, or contract address'],+ ['chain', false, 'solana | base | … — inferred from address shape when omitted'],+ ],+ example: {+ address: THREE, chain: 'solana', name: 'three.ws', symbol: 'THREE',+ priceUsd: 0.00421, change24h: 12.4, marketCapUsd: 4210000, liquidityUsd: 318000,+ volume24hUsd: 892000, fdvUsd: 4210000, pairCreatedAt: 1717977600000,+ dexId: 'raydium', url: 'https://dexscreener.com/solana/…', ts: 1720310400000,+ sources: ['dexscreener', 'solana-rpc'],+ },+ },+ {+ slug: 'security', title: 'Token Security', method: 'GET', path: '/api/crypto/security',+ purpose: 'Rug / honeypot signals: authorities, LP, concentration',+ agent: 'Before an agent <b>buys or LPs into a token</b>, it needs a fast “is this a rug?” read — mint & freeze authority, LP burned/locked, top-holder concentration. The single most-requested pre-trade check in crypto agent workflows.',+ probe: `${BASE}/security?address=${THREE}`,+ params: [+ ['address', true, 'Token mint'],+ ['chain', false, 'solana | base'],+ ],+ example: {+ address: THREE, chain: 'solana',+ checks: { mintAuthorityRevoked: true, freezeAuthorityRevoked: true, metadataMutable: false, lpBurnedOrLocked: true, liquidityUsd: 318000, topHolderPctFlag: 'low' },+ riskLevel: 'low', reasons: ['mint authority revoked', 'freeze authority revoked', 'LP burned'],+ ts: 1720310400000, sources: ['solana-rpc', 'dexscreener'],+ },+ },+ {+ slug: 'holders', title: 'Holders & Concentration', method: 'GET', path: '/api/crypto/holders',+ purpose: 'Holder count + top-10 concentration for exit-risk sizing',+ agent: 'An agent <b>sizing a position</b> needs holder distribution: how many holders, what % the top 10 hold, whether insiders still dominate. High concentration = exit risk. One free call instead of scraping an explorer.',+ probe: `${BASE}/holders?address=${THREE}&limit=10`,+ params: [+ ['address', true, 'Token mint'],+ ['chain', false, 'solana'],+ ['limit', false, 'Top-N holders to return — default 10, max 50'],+ ],+ example: {+ address: THREE, chain: 'solana', holderCount: 4820,+ top: [{ owner: '7xKq…9fA2', amount: '18400000', pct: 4.4 }, { owner: 'Bv3s…c1Rd', amount: '12100000', pct: 2.9 }],+ top10Pct: 21.7, concentration: 'medium', ts: 1720310400000, sources: ['helius', 'solana-rpc'],+ },+ },+ {+ slug: 'launches', title: 'Live pump.fun Launches', method: 'GET', path: '/api/crypto/launches',+ purpose: 'Freshest pump.fun launches with signal to filter',+ agent: 'A <b>sniper / discovery agent</b> polls the freshest pump.fun launches with enough signal to filter — name, symbol, mint, age, market cap, bonding-curve progress, dev wallet. Exactly the feed agents poll on a loop.',+ probe: `${BASE}/launches?limit=5`,+ params: [+ ['limit', false, 'How many launches — default 20, max 100'],+ ['minMarketCap', false, 'USD floor filter'],+ ['maxAgeMin', false, 'Only launches newer than N minutes'],+ ],+ example: {+ launches: [{ mint: 'THREEsynthetic1111111111111111111111111111', name: 'Example Coin', symbol: 'EXMPL', createdAt: 1720310100000, ageMinutes: 5, marketCapUsd: 12400, bondingProgressPct: 18.2, dev: '9wX…k2', url: 'https://pump.fun/…', imageUrl: 'https://…' }],+ count: 1, ts: 1720310400000, source: 'pump.fun',+ },+ },+ {+ slug: 'bonding', title: 'Bonding-Curve Status', method: 'GET', path: '/api/crypto/bonding',+ purpose: '% to graduation, SOL in curve, migration status',+ agent: 'An agent <b>timing an entry or exit around graduation</b> needs exactly where a pump.fun token sits on the bonding curve — % to graduation, SOL in curve, and whether it has migrated to Raydium/PumpSwap. A core meme-trading move.',+ probe: `${BASE}/bonding?mint=${THREE}`,+ params: [+ ['mint', true, 'pump.fun token mint'],+ ],+ example: {+ mint: 'THREEsynthetic1111111111111111111111111111', onCurve: true, bondingProgressPct: 62.4,+ solInCurve: 51.3, tokensRemaining: '31200000', marketCapUsd: 41800, graduated: false,+ migratedTo: null, ts: 1720310400000, source: 'pump.fun',+ },+ },+ {+ slug: 'whales', title: 'Whale Activity', method: 'GET', path: '/api/crypto/whales',+ purpose: 'Large-buy flow — is big money moving in?',+ agent: 'An agent wants to know if <b>big money is moving into a token</b> (or the pump.fun market broadly) before it commits — a whale already in means price impact ahead; no whales means thin. A free read of large buys is high-signal.',+ probe: `${BASE}/whales?minSol=5&limit=10`,+ params: [+ ['mint', false, 'Token mint — whale buys of that token; omit for market-wide top whales'],+ ['minSol', false, 'Minimum SOL per buy to count — default 5'],+ ['limit', false, 'Max whales — default 10, max 25'],+ ],+ example: {+ scope: 'market', mint: null,+ whales: [{ wallet: 'Dpr…8Ht', solMoved: 42.5, txHash: '5xN…', ts: 1720310360000 }],+ whaleCount: 1, totalSolMoved: 42.5, signal: 'bullish', ts: 1720310400000, source: 'pump.fun',+ },+ },+ {+ slug: 'symbol', title: 'Symbol Availability', method: 'GET', path: '/api/crypto/symbol',+ purpose: 'Ticker collision check — exact + fuzzy',+ agent: 'An agent <b>about to launch a token</b> checks candidate tickers for collisions (exact + fuzzy) before committing, so its brand isn\'t lost among clones. A natural top-of-funnel for the paid Pump Launcher.',+ probe: `${BASE}/symbol?symbols=THREE,MYCOIN`,+ params: [+ ['symbols', true, 'Comma-separated tickers (GET) or { symbols: string[] } (POST) — max 20'],+ ['chain', false, 'solana'],+ ],+ example: {+ results: [{ symbol: 'THREE', available: false, exactCollisions: 2, fuzzyCollisions: 5 }, { symbol: 'MYCOIN', available: true, exactCollisions: 0, fuzzyCollisions: 1 }],+ availableCount: 1, takenCount: 1, ts: 1720310400000,+ },+ },+ {+ slug: 'wallet', title: 'Wallet Portfolio', method: 'GET', path: '/api/crypto/wallet',+ purpose: 'Balances + rough USD value for any wallet',+ agent: 'A <b>treasury, copy-trade, or pre-trade counterparty check</b> agent inspects a wallet — its own or another\'s — before transacting: token balances, native SOL, rough USD value. Never needs a private key.',+ probe: `${BASE}/wallet?address=${SAMPLE_WALLET}`,+ params: [+ ['address', true, 'Wallet address'],+ ['chain', false, 'solana | base | …'],+ ],+ example: {+ address: SAMPLE_WALLET, chain: 'solana', native: { amount: 12.4, usd: 2108 },+ tokens: [{ mint: THREE, symbol: 'THREE', amount: '4200000', usd: 17682 }],+ totalUsd: 19790, tokenCount: 1, ts: 1720310400000, sources: ['solana-rpc', 'dexscreener'],+ },+ },+ {+ slug: 'trending', title: 'Trending Tokens', method: 'GET', path: '/api/crypto/trending',+ purpose: '“What\'s hot right now,” ranked by momentum',+ agent: 'A <b>discovery agent</b> wants “what\'s hot right now” — tokens ranked by momentum (volume spike, buy pressure, holder growth) so it can surface opportunities without scraping five sites.',+ probe: `${BASE}/trending?window=1h&limit=10`,+ params: [+ ['window', false, '5m | 1h | 24h — default 1h'],+ ['limit', false, 'Max tokens — default 20, max 50'],+ ['source', false, 'pumpfun | all'],+ ],+ example: {+ window: '1h',+ tokens: [{ mint: THREE, symbol: 'THREE', name: 'three.ws', marketCapUsd: 4210000, volumeUsd: 892000, change: 12.4, score: 87.2, url: 'https://dexscreener.com/solana/…' }],+ count: 1, ts: 1720310400000, sources: ['pump-trending-score', 'dexscreener'],+ },+ },+ ];++ /* ── Tiny helpers ─────────────────────────────────────────── */+ const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c]));+ const el = (tag, cls, html) => { const n = document.createElement(tag); if (cls) n.className = cls; if (html != null) n.innerHTML = html; return n; };++ // Minimal, dependency-free JSON syntax highlighter for the example blocks.+ function highlightJson(obj) {+ // esc() only escapes < > & — quotes stay literal, so match on real ".+ const json = JSON.stringify(obj, null, 2);+ return esc(json)+ .replace(/"([^"\n]+)"(\s*:)/g, '<span class="cx-key">"$1"</span>$2')+ .replace(/([:[]\s*)"([^"\n]*)"/g, '$1<span class="cx-str">"$2"</span>')+ .replace(/: (-?\d+\.?\d*)/g, ': <span class="cx-num">$1</span>')+ .replace(/([:[]\s*)(true|false|null)/g, '$1<span class="cx-tok">$2</span>');+ }++ function codeBlock(innerHtml) {+ const wrap = el('div', 'cx-code');+ const btn = el('button', 'cx-copy', copyIcon() + '<span>Copy</span>');+ btn.type = 'button';+ const pre = el('pre'); const code = el('code'); code.innerHTML = innerHtml; pre.appendChild(code);+ wrap.append(btn, pre);+ btn.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(code.textContent);+ btn.classList.add('is-done'); btn.querySelector('span').textContent = 'Copied';+ setTimeout(() => { btn.classList.remove('is-done'); btn.querySelector('span').textContent = 'Copy'; }, 1600);+ } catch { btn.querySelector('span').textContent = 'Press ⌘C'; }+ });+ return wrap;+ }+ const copyIcon = () => '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';++ /* ── Quickstart (tabbed) ──────────────────────────────────── */+ const QS = {+ curl: `<span class="cx-cmd">curl</span> <span class="cx-str">"https://three.ws/api/crypto/token?address=${THREE}"</span>`,+ js:+`<span class="cx-tok">// No key, no SDK — just fetch.</span>+<span class="cx-key">const</span> res = <span class="cx-key">await</span> fetch(+ <span class="cx-str">"https://three.ws/api/crypto/token?address=${THREE}"</span>+);+<span class="cx-key">const</span> token = <span class="cx-key">await</span> res.json();++<span class="cx-tok">// → { symbol: "THREE", priceUsd, change24h, liquidityUsd, marketCapUsd, ... }</span>+<span class="cx-key">if</span> (token.change24h > <span class="cx-num">10</span> && token.liquidityUsd > <span class="cx-num">50000</span>) {+ console.log(<span class="cx-str">\`\${token.symbol} pumping — liq $\${token.liquidityUsd}\`</span>);+}`,+ py:+`<span class="cx-tok"># No key, no client library — just requests.</span>+<span class="cx-key">import</span> requests++r = requests.get(+ <span class="cx-str">"https://three.ws/api/crypto/token"</span>,+ params={<span class="cx-str">"address"</span>: <span class="cx-str">"${THREE}"</span>},+)+token = r.json()++<span class="cx-key">if</span> token[<span class="cx-str">"change24h"</span>] > <span class="cx-num">10</span> <span class="cx-key">and</span> token[<span class="cx-str">"liquidityUsd"</span>] > <span class="cx-num">50000</span>:+ print(<span class="cx-str">f"{token['symbol']} pumping — liq \${token['liquidityUsd']}"</span>)`,+ };++ function renderQuickstart(kind) {+ // Re-query each call: the previous node is replaced (and detached),+ // so a stale reference would make replaceWith() a silent no-op.+ const cur = document.getElementById('cx-quickstart-code');+ const next = codeBlock(QS[kind]);+ next.id = 'cx-quickstart-code';+ cur.replaceWith(next);+ }+ renderQuickstart('curl');+ document.querySelectorAll('.cx-tab').forEach((tab) => {+ tab.addEventListener('click', () => {+ document.querySelectorAll('.cx-tab').forEach((t) => t.setAttribute('aria-selected', String(t === tab)));+ renderQuickstart(tab.dataset.qtab);+ });+ });++ /* ── Endpoint table ───────────────────────────────────────── */+ const tbody = document.getElementById('cx-table-body');+ for (const ep of ENDPOINTS) {+ const tr = el('tr');+ tr.innerHTML =+ `<td><a class="cx-ep-link" href="#ep-${ep.slug}">${esc(ep.title)}</a></td>` ++ `<td class="cx-purpose">${ep.purpose}</td>` ++ `<td><span class="cx-meth">${ep.method}</span><span class="cx-path">${esc(ep.path)}</span></td>` ++ `<td class="cx-free">Free</td>` ++ `<td><span class="cx-status cx-status--probing" data-status="${ep.slug}"><span class="cx-dot"></span>Checking…</span></td>`;+ tbody.appendChild(tr);+ }++ /* ── Reference cards ──────────────────────────────────────── */+ const cardsHost = document.getElementById('cx-ep-cards');+ for (const ep of ENDPOINTS) {+ const card = el('article', 'cx-ep'); card.id = `ep-${ep.slug}`;+ const params = ep.params.map(([name, req, desc]) =>+ `<div class="cx-param"><code>${esc(name)}</code>${req ? '<span class="cx-req">required</span>' : '<span class="cx-opt">optional</span>'}<span class="cx-pdesc">${desc}</span></div>`+ ).join('');++ const curl = `<span class="cx-cmd">curl</span> <span class="cx-str">"https://three.ws${esc(ep.probe.replace(BASE, '/api/crypto'))}"</span>`;++ card.innerHTML =+ `<div class="cx-ep-head">+ <div>+ <h3 class="cx-ep-title"><a class="cx-anchor" href="#ep-${ep.slug}">${esc(ep.title)}</a></h3>+ <div class="cx-ep-route"><span class="cx-meth">${ep.method}</span>${esc(ep.path)} · <span class="cx-free">Free</span></div>+ </div>+ <span class="cx-status cx-status--probing" data-status="${ep.slug}"><span class="cx-dot"></span>Checking…</span>+ </div>+ <div class="cx-ep-agent"><b>Who uses it:</b> ${ep.agent}</div>+ <div class="cx-params">${params}</div>`;++ const io = el('div', 'cx-io');+ const reqCol = el('div'); reqCol.appendChild(el('h4', null, 'Request'));+ reqCol.appendChild(codeBlock(curl));+ const resCol = el('div'); resCol.appendChild(el('h4', null, 'Response'));+ resCol.appendChild(codeBlock(highlightJson(ep.example)));+ io.append(reqCol, resCol);+ card.appendChild(io);++ // Try-it-live+ const tryBar = el('div', 'cx-trybar');+ const tryBtn = el('button', 'btn btn--secondary btn--sm', 'Try it live');+ tryBtn.type = 'button';+ const tryNote = el('span', 'cx-try-note', `GET ${ep.probe}`);+ tryBar.append(tryBtn, tryNote);+ const out = el('div', 'cx-try-out');+ card.append(tryBar, out);++ tryBtn.addEventListener('click', () => runTry(ep, tryBtn, out));+ cardsHost.appendChild(card);+ }++ async function runTry(ep, btn, out) {+ btn.disabled = true; out.classList.add('is-open');+ out.innerHTML = '<div class="skeleton skeleton--text" style="width:60%"></div><div class="skeleton skeleton--text" style="width:85%;margin-top:.5rem"></div><div class="skeleton skeleton--text" style="width:40%;margin-top:.5rem"></div>';+ try {+ const res = await fetch(ep.probe, { headers: { accept: 'application/json' } });+ if (res.status === 404) {+ out.innerHTML = '';+ out.appendChild(el('div', 'cx-note', '<span>🚧</span><span><b>Coming soon.</b> This endpoint isn\'t deployed yet — the schema above is its stable contract. This button starts returning live JSON the moment it ships; the status badge flips to Live automatically.</span>'));+ } else {+ let body; const text = await res.text();+ try { body = JSON.parse(text); } catch { body = text; }+ out.innerHTML = '';+ out.appendChild(el('h4', null, `Live response · HTTP ${res.status}`));+ out.appendChild(codeBlock(typeof body === 'string' ? esc(body) : highlightJson(body)));+ }+ } catch (err) {+ out.innerHTML = '';+ out.appendChild(el('div', 'cx-note', `<span>⚠️</span><span><b>Network error.</b> Couldn't reach the endpoint (${esc(err.message)}). Retry, or hit it directly with the curl above.</span>`));+ } finally {+ btn.disabled = false;+ }+ }++ /* ── Live probe: classify each endpoint (non-404 = deployed) ── */+ async function probe(ep) {+ try {+ const res = await fetch(ep.probe, { headers: { accept: 'application/json' } });+ return res.status !== 404; // 200/400/429/503 all mean the route exists+ } catch { return null; } // network/CORS — unknown+ }++ function setStatus(slug, state) {+ document.querySelectorAll(`[data-status="${slug}"]`).forEach((n) => {+ n.classList.remove('cx-status--probing', 'cx-status--live', 'cx-status--soon');+ if (state === true) { n.classList.add('cx-status--live'); n.innerHTML = '<span class="cx-dot cx-dot--live"></span>Live'; }+ else if (state === false) { n.classList.add('cx-status--soon'); n.innerHTML = '<span class="cx-dot"></span>Coming soon'; }+ else { n.classList.add('cx-status--soon'); n.innerHTML = '<span class="cx-dot"></span>Unknown'; }+ });+ }++ (async () => {+ const results = await Promise.all(ENDPOINTS.map(async (ep) => {+ const ok = await probe(ep);+ setStatus(ep.slug, ok);+ return ok;+ }));+ const live = results.filter((r) => r === true).length;+ const total = ENDPOINTS.length;+ const pill = document.getElementById('cx-live-count');+ const txt = document.getElementById('cx-live-count-text');+ const dot = pill.querySelector('.cx-dot');+ if (live > 0) { dot.classList.add('cx-dot--live'); txt.textContent = `${live} of ${total} endpoints live`; }+ else { txt.textContent = `${total} endpoints · rolling out`; }+ })();+ </script>+ </body>+</html>diff --git a/pages/sperax.html b/pages/sperax.htmlindex 314e77515..ea5e0e079 100644--- a/pages/sperax.html+++ b/pages/sperax.html@@ -19,9 +19,36 @@</script><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />- <title>Sperax · three.ws</title>- <meta name="description" content="Sperax on three.ws." />- <meta name="robots" content="noindex" />+ <title>Sperax × three.ws — Free AI credits on SperaxOS · three.ws</title>+ <meta+ name="description"+ content="three.ws is live inside SperaxOS. Connect your three.ws agent to chat.sperax.io to give it an embodied 3D body — and claim free AI credits as part of the partnership. Here's what the integration is and how to claim."+ />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/sperax" />+ <meta property="og:title" content="Sperax × three.ws — Free AI credits on SperaxOS" />+ <meta+ property="og:description"+ content="three.ws is live inside SperaxOS. Connect your agent to chat.sperax.io for an embodied 3D body — and claim free AI credits as part of the partnership."+ />+ <meta property="og:locale" content="en_US" />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Sperax+%C3%97+three.ws&d=three.ws+is+live+inside+SperaxOS.+Connect+your+agent+to+chat.sperax.io+for+an+embodied+3D+body+%E2%80%94+and+claim+free+AI+credits.&p=%2Fsperax"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content="Sperax × three.ws — free AI credits on SperaxOS" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Sperax × three.ws — Free AI credits on SperaxOS" />+ <meta+ name="twitter:description"+ content="Connect your three.ws agent to SperaxOS for an embodied 3D body — and claim free AI credits as part of the partnership."+ />+ <meta name="theme-color" content="#0a0a0a" /><link rel="canonical" href="https://three.ws/sperax" /><link rel="icon" href="/favicon.ico" sizes="any" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" />@@ -32,22 +59,681 @@<link rel="stylesheet" href="/footer.css" /><link rel="stylesheet" href="/fonts/fonts.css" /><link rel="stylesheet" href="/mobile.css" />+ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebPage",+ "name": "Sperax × three.ws — Free AI credits on SperaxOS",+ "description": "three.ws is live inside SperaxOS. Connect your three.ws agent to chat.sperax.io for an embodied 3D body — and claim free AI credits as part of the partnership.",+ "url": "https://three.ws/sperax",+ "isPartOf": { "@type": "WebSite", "name": "three.ws", "url": "https://three.ws" }+ },+ {+ "@type": "FAQPage",+ "mainEntity": [+ {+ "@type": "Question",+ "name": "How do I claim the free credits?",+ "acceptedAnswer": {+ "@type": "Answer",+ "text": "Install the three.ws plugin inside SperaxOS at chat.sperax.io, then bind it to your three.ws Agent ID from your dashboard. Credits apply to your SperaxOS account once your agent is connected."+ }+ },+ {+ "@type": "Question",+ "name": "Do I need a three.ws account?",+ "acceptedAnswer": {+ "@type": "Answer",+ "text": "Yes. You need a three.ws agent so the plugin has an identity to bind to. Your Agent ID is a UUID or @handle you copy from your three.ws dashboard."+ }+ },+ {+ "@type": "Question",+ "name": "Which chain does this settle on?",+ "acceptedAnswer": {+ "@type": "Answer",+ "text": "SperaxOS is EVM-native and settles agent payments via x402 over USDC on Base, which matches the three.ws Base x402 rail. The avatar panel itself is chain-agnostic and renders regardless of which chain your agent transacts on."+ }+ }+ ]+ }+ ]+ }+ </script><style>- .sperax-wrap {- max-width: 1040px;+ .spx {+ --spx-max: 1040px;+ }+ .spx main {+ max-width: var(--spx-max);margin: 0 auto;- padding: clamp(1.25rem, 4vw, 3rem) 1.25rem 4rem;- min-height: 40vh;+ padding: clamp(1.25rem, 4vw, 3rem) 1.25rem 5rem;+ }++ /* ── Hero ─────────────────────────────────────────────── */+ .spx-hero {+ position: relative;+ text-align: center;+ padding: clamp(2.5rem, 7vw, 5rem) 0 clamp(2rem, 5vw, 3.5rem);+ }+ .spx-lockup {+ display: inline-flex;+ align-items: center;+ gap: 0.75rem;+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--ink-dim);+ margin-bottom: 1.25rem;+ }+ .spx-lockup img {+ width: 22px;+ height: 22px;+ border-radius: 6px;+ display: block;+ }+ .spx-lockup .x {+ opacity: 0.5;+ }+ .spx-hero h1 {+ font-family: var(--font-display);+ font-weight: 600;+ font-size: clamp(2rem, 6vw, 3.4rem);+ line-height: 1.05;+ letter-spacing: -0.02em;+ margin: 0 auto 1rem;+ max-width: 16ch;+ color: var(--ink-bright);+ }+ .spx-hero p.lede {+ font-size: clamp(1rem, 2.4vw, 1.25rem);+ line-height: 1.55;+ color: var(--ink-dim);+ max-width: 56ch;+ margin: 0 auto 2rem;+ }+ .spx-cta-row {+ display: flex;+ flex-wrap: wrap;+ gap: 0.75rem;+ justify-content: center;+ }+ .spx-btn {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ font-family: var(--font-body);+ font-size: 0.95rem;+ font-weight: 550;+ line-height: 1;+ padding: 0.85rem 1.4rem;+ border-radius: var(--radius-pill);+ border: 1px solid transparent;+ cursor: pointer;+ text-decoration: none;+ transition:+ transform 0.15s ease,+ background 0.15s ease,+ border-color 0.15s ease,+ box-shadow 0.15s ease;+ }+ .spx-btn:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: var(--focus-ring-offset);+ }+ .spx-btn-primary {+ background: var(--ink-bright);+ color: var(--bg-0);+ box-shadow: var(--shadow-2);+ }+ .spx-btn-primary:hover {+ transform: translateY(-1px);+ box-shadow: var(--shadow-3);+ }+ .spx-btn-primary:active {+ transform: translateY(0);+ }+ .spx-btn-secondary {+ background: var(--surface-2);+ color: var(--ink);+ border-color: var(--stroke-strong);+ }+ .spx-btn-secondary:hover {+ background: var(--surface-3);+ border-color: var(--stroke-strong);+ transform: translateY(-1px);+ }+ .spx-btn-secondary:active {+ transform: translateY(0);+ }++ /* ── Offer banner ─────────────────────────────────────── */+ .spx-offer {+ position: relative;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 1rem 1.5rem;+ justify-content: center;+ text-align: center;+ margin: 0 auto clamp(2.5rem, 6vw, 4rem);+ padding: clamp(1.25rem, 3vw, 1.75rem) clamp(1.25rem, 4vw, 2.5rem);+ border-radius: var(--radius-lg);+ border: 1px solid rgba(52, 211, 153, 0.32);+ background:+ radial-gradient(120% 140% at 50% 0%, rgba(52, 211, 153, 0.12), transparent 70%),+ var(--surface-1);+ }+ .spx-offer .tag {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: #34d399;+ padding: 0.25rem 0.7rem;+ border-radius: var(--radius-pill);+ border: 1px solid rgba(52, 211, 153, 0.32);+ background: rgba(52, 211, 153, 0.1);+ }+ .spx-offer p {+ margin: 0;+ font-size: 1.02rem;+ line-height: 1.5;+ color: var(--ink);+ max-width: 60ch;+ }+ .spx-offer strong {+ color: var(--ink-bright);+ }++ /* ── Section scaffolding ──────────────────────────────── */+ .spx-section {+ margin: clamp(3rem, 8vw, 5rem) 0;+ }+ .spx-eyebrow {+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--ink-dim);+ margin: 0 0 0.6rem;+ }+ .spx-section h2 {+ font-family: var(--font-display);+ font-weight: 600;+ font-size: clamp(1.5rem, 3.6vw, 2.1rem);+ letter-spacing: -0.015em;+ line-height: 1.15;+ margin: 0 0 0.85rem;+ color: var(--ink-bright);+ max-width: 24ch;+ }+ .spx-section > p.intro {+ font-size: 1.05rem;+ line-height: 1.6;+ color: var(--ink-dim);+ max-width: 62ch;+ margin: 0 0 2rem;+ }++ /* ── Steps ────────────────────────────────────────────── */+ .spx-steps {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+ gap: 1rem;+ counter-reset: step;+ }+ .spx-step {+ position: relative;+ padding: 1.5rem 1.4rem 1.4rem;+ border-radius: var(--radius-lg);+ border: 1px solid var(--stroke);+ background: var(--surface-glass);+ }+ .spx-step::before {+ counter-increment: step;+ content: counter(step);+ display: grid;+ place-items: center;+ width: 34px;+ height: 34px;+ margin-bottom: 1rem;+ font-family: var(--font-mono);+ font-size: 0.95rem;+ color: var(--bg-0);+ background: var(--ink-bright);+ border-radius: var(--radius-pill);+ }+ .spx-step h3 {+ font-size: 1.05rem;+ font-weight: 600;+ margin: 0 0 0.4rem;+ color: var(--ink-bright);+ }+ .spx-step p {+ margin: 0;+ font-size: 0.94rem;+ line-height: 1.55;+ color: var(--ink-dim);+ }+ .spx-step a {+ color: var(--ink);+ text-decoration: underline;+ text-underline-offset: 2px;+ text-decoration-color: var(--stroke-strong);+ }+ .spx-step a:hover {+ text-decoration-color: currentColor;+ }+ .spx-step code {+ font-family: var(--font-mono);+ font-size: 0.85em;+ background: var(--surface-3);+ border-radius: var(--radius-sm);+ padding: 0.1em 0.4em;+ }++ /* ── Capability grid ──────────────────────────────────── */+ .spx-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+ gap: 1rem;+ }+ .spx-card {+ padding: 1.4rem;+ border-radius: var(--radius-lg);+ border: 1px solid var(--stroke);+ background: var(--surface-1);+ transition:+ border-color 0.15s ease,+ transform 0.15s ease;+ }+ .spx-card:hover {+ border-color: var(--stroke-strong);+ transform: translateY(-2px);+ }+ .spx-card .ico {+ font-size: 1.4rem;+ line-height: 1;+ margin-bottom: 0.85rem;+ }+ .spx-card h3 {+ font-size: 1rem;+ font-weight: 600;+ margin: 0 0 0.4rem;+ color: var(--ink-bright);+ }+ .spx-card h3 code {+ font-family: var(--font-mono);+ font-size: 0.8em;+ color: var(--ink-dim);+ font-weight: 400;+ }+ .spx-card p {+ margin: 0;+ font-size: 0.92rem;+ line-height: 1.55;+ color: var(--ink-dim);+ }++ /* ── Flow diagram ─────────────────────────────────────── */+ .spx-flow {+ border-radius: var(--radius-lg);+ border: 1px solid var(--stroke);+ background: var(--surface-glass);+ padding: clamp(1.25rem, 3vw, 2rem);+ overflow-x: auto;+ }+ .spx-flow pre {+ margin: 0;+ font-family: var(--font-mono);+ font-size: 0.82rem;+ line-height: 1.7;+ color: var(--ink-dim);+ white-space: pre;+ }+ .spx-flow pre b {+ color: var(--ink-bright);+ font-weight: 600;+ }++ /* ── Chain note ───────────────────────────────────────── */+ .spx-note {+ display: flex;+ gap: 1rem;+ align-items: flex-start;+ padding: 1.25rem 1.4rem;+ border-radius: var(--radius-lg);+ border: 1px solid var(--stroke);+ background: var(--surface-1);+ }+ .spx-note .ico {+ font-size: 1.25rem;+ line-height: 1.4;+ }+ .spx-note p {+ margin: 0;+ font-size: 0.95rem;+ line-height: 1.6;+ color: var(--ink-dim);+ }+ .spx-note strong {+ color: var(--ink);+ }++ /* ── FAQ ──────────────────────────────────────────────── */+ .spx-faq {+ display: grid;+ gap: 0.6rem;+ }+ .spx-faq details {+ border-radius: var(--radius-md);+ border: 1px solid var(--stroke);+ background: var(--surface-1);+ overflow: hidden;+ }+ .spx-faq summary {+ cursor: pointer;+ list-style: none;+ padding: 1rem 1.2rem;+ font-weight: 550;+ font-size: 0.98rem;+ color: var(--ink-bright);+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: 1rem;+ }+ .spx-faq summary::-webkit-details-marker {+ display: none;+ }+ .spx-faq summary::after {+ content: '+';+ font-family: var(--font-mono);+ color: var(--ink-dim);+ transition: transform 0.2s ease;+ }+ .spx-faq details[open] summary::after {+ transform: rotate(45deg);+ }+ .spx-faq summary:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: -2px;+ }+ .spx-faq details p {+ margin: 0;+ padding: 0 1.2rem 1.1rem;+ font-size: 0.94rem;+ line-height: 1.6;+ color: var(--ink-dim);+ }+ .spx-faq details a {+ color: var(--ink);+ text-decoration: underline;+ text-underline-offset: 2px;+ }++ /* ── Final CTA ────────────────────────────────────────── */+ .spx-final {+ text-align: center;+ margin: clamp(3.5rem, 9vw, 6rem) 0 0;+ padding: clamp(2.5rem, 6vw, 4rem) 1.5rem;+ border-radius: var(--radius-lg);+ border: 1px solid var(--stroke);+ background:+ radial-gradient(120% 140% at 50% 0%, var(--accent-soft), transparent 65%),+ var(--surface-1);+ }+ .spx-final h2 {+ font-family: var(--font-display);+ font-weight: 600;+ font-size: clamp(1.6rem, 4vw, 2.4rem);+ letter-spacing: -0.015em;+ margin: 0 auto 0.85rem;+ max-width: 20ch;+ color: var(--ink-bright);+ }+ .spx-final p {+ color: var(--ink-dim);+ font-size: 1.05rem;+ line-height: 1.55;+ max-width: 48ch;+ margin: 0 auto 1.75rem;+ }++ @media (prefers-reduced-motion: reduce) {+ .spx-btn,+ .spx-card,+ .spx-faq summary::after {+ transition: none;+ }+ .spx-btn:hover,+ .spx-card:hover {+ transform: none;+ }}</style></head>- <body>+ <body class="spx"><a href="#main-content" class="h-skip-link">Skip to main content</a><header><div id="nav-container"></div></header><script src="/nav.js"></script>- <main id="main-content" class="sperax-wrap">- <!-- Content coming soon -->+ <main id="main-content">+ <!-- ── Hero ─────────────────────────────────────────── -->+ <section class="spx-hero" aria-labelledby="spx-title">+ <span class="spx-lockup">+ <img src="/favicon.svg" alt="" aria-hidden="true" />+ three.ws+ <span class="x" aria-hidden="true">×</span>+ <img src="/sperax/icon-256.svg" alt="" aria-hidden="true" />+ Sperax+ </span>+ <h1 id="spx-title">three.ws is live inside SperaxOS</h1>+ <p class="lede">+ Give your SperaxOS agent a body — a rigged 3D avatar that speaks, gestures, and+ reacts to on-chain events in real time. To launch the partnership, Sperax is+ handing three.ws users <strong>free AI credits</strong> on+ <a href="https://chat.sperax.io" rel="noopener">chat.sperax.io</a>.+ </p>+ <div class="spx-cta-row">+ <a class="spx-btn spx-btn-primary" href="https://chat.sperax.io" rel="noopener">+ Claim your credits on SperaxOS →+ </a>+ <a class="spx-btn spx-btn-secondary" href="/blog/three-ws-speraxusd-integration">+ Read the integration+ </a>+ </div>+ </section>++ <!-- ── Offer banner ─────────────────────────────────── -->+ <div class="spx-offer" role="note">+ <span class="tag">◆ Launch offer</span>+ <p>+ Connect a three.ws agent to SperaxOS and+ <strong>free AI credits</strong> land on your SperaxOS account — enough to put+ your embodied agent to work across the Sperax DeFi stack before you spend a cent.+ </p>+ </div>++ <!-- ── How to claim ─────────────────────────────────── -->+ <section class="spx-section" aria-labelledby="spx-claim">+ <p class="spx-eyebrow">Claim in three steps</p>+ <h2 id="spx-claim">From zero to an embodied agent in a minute</h2>+ <p class="intro">+ The integration ships as a standalone SperaxOS plugin — no SDK to vendor, no+ bundle to submit. Install it, point it at your three.ws identity, and the credits+ follow.+ </p>+ <ol class="spx-steps" style="list-style: none; padding: 0; margin: 0">+ <li class="spx-step">+ <h3>Add the plugin</h3>+ <p>+ In SperaxOS, open <strong>Plugins → Add Plugin → Custom Plugin</strong> and+ paste the manifest URL:+ <code>https://three.ws/.well-known/sperax-plugin.json</code>+ </p>+ </li>+ <li class="spx-step">+ <h3>Bind your agent</h3>+ <p>+ Set your <strong>Agent ID</strong> — a UUID or <code>@handle</code> you copy+ from <a href="/dashboard">your three.ws dashboard</a>. The avatar binds to+ that on-chain identity when the panel opens.+ </p>+ </li>+ <li class="spx-step">+ <h3>Credits apply</h3>+ <p>+ With your agent connected, your <strong>free AI credits</strong> are active+ on <a href="https://chat.sperax.io" rel="noopener">chat.sperax.io</a>. Start+ chatting — the avatar speaks, gestures, and emotes as it works.+ </p>+ </li>+ </ol>+ </section>++ <!-- ── What you get ─────────────────────────────────── -->+ <section class="spx-section" aria-labelledby="spx-caps">+ <p class="spx-eyebrow">What the avatar does</p>+ <h2 id="spx-caps">A face for DeFi, driven by the model</h2>+ <p class="intro">+ Your agent's LLM calls four tools. Each one drives the visible avatar in the chat+ panel and returns a concise result the model reads back into the conversation —+ so the body language always matches what's happening on-chain.+ </p>+ <div class="spx-grid">+ <article class="spx-card">+ <div class="ico" aria-hidden="true">🧍</div>+ <h3>Render <code>render_agent</code></h3>+ <p>+ Mount or swap the 3D avatar to a specific three.ws agent — bound to its+ ERC-8004 identity.+ </p>+ </article>+ <article class="spx-card">+ <div class="ico" aria-hidden="true">🗣️</div>+ <h3>Speak <code>speak</code></h3>+ <p>+ Say a line out loud with emotional valence — greetings, narrating an action,+ reacting to you.+ </p>+ </article>+ <article class="spx-card">+ <div class="ico" aria-hidden="true">👋</div>+ <h3>Gesture <code>gesture</code></h3>+ <p>+ Punctuate a message with a physical gesture: wave, nod, point, or shrug.+ </p>+ </article>+ <article class="spx-card">+ <div class="ico" aria-hidden="true">💗</div>+ <h3>Emote <code>emote</code></h3>+ <p>+ Blend an emotion into the continuous Empathy Layer — concern as a position+ nears liquidation, celebration when a yield target hits.+ </p>+ </article>+ </div>+ </section>++ <!-- ── How it works ─────────────────────────────────── -->+ <section class="spx-section" aria-labelledby="spx-how">+ <p class="spx-eyebrow">Under the hood</p>+ <h2 id="spx-how">Two halves per tool call</h2>+ <p class="intro">+ The host frames a hosted iframe for the visible avatar and, in parallel, POSTs the+ tool arguments to the three.ws gateway for the model-facing result. Both run on+ every call.+ </p>+ <div class="spx-flow" role="img" aria-label="Diagram: a SperaxOS tool call fans out to the avatar iframe and the three.ws gateway endpoint">+<pre><b>SperaxOS host</b>+ │ 1. LLM calls a tool (speak / gesture / emote / render_agent)+ │+ ├─ 2a. frames <b>/sperax/iframe/</b> and posts the call+ │ └─▶ <agent-3d> animates the avatar in the chat panel+ │+ └─ 2b. gateway POSTs the arguments to the tool endpoint+ └─▶ <b>/api/chat-plugin/speak</b> → { ok: true, spoken: "…" }</pre>+ </div>+ </section>++ <!-- ── Chain note ───────────────────────────────────── -->+ <section class="spx-section" aria-labelledby="spx-chain">+ <p class="spx-eyebrow">Payments</p>+ <h2 id="spx-chain">Base x402, natively</h2>+ <div class="spx-note">+ <span class="ico" aria-hidden="true">⛓️</span>+ <p>+ SperaxOS is EVM-native and settles agent payments via <strong>x402 over USDC on+ Base</strong> (<code>x402.sperax.io</code>) — the same Base x402 rail three.ws+ already runs. The avatar panel is chain-agnostic: it renders and animates+ regardless of which chain your bound agent transacts on.+ </p>+ </div>+ </section>++ <!-- ── FAQ ──────────────────────────────────────────── -->+ <section class="spx-section" aria-labelledby="spx-faq-h">+ <p class="spx-eyebrow">Questions</p>+ <h2 id="spx-faq-h">Good to know</h2>+ <div class="spx-faq">+ <details>+ <summary>Do I need a three.ws account?</summary>+ <p>+ Yes — the plugin binds to a three.ws agent, so it needs an identity to render.+ Your Agent ID is a UUID or <code>@handle</code> you copy from+ <a href="/dashboard">your dashboard</a>. Don't have one?+ <a href="/create">Create an agent</a> first, then come back.+ </p>+ </details>+ <details>+ <summary>Does the plugin cost anything or need an API key?</summary>+ <p>+ No. The only setting is your public Agent ID — there's no API key to paste. The+ free credits cover your usage on SperaxOS while the launch offer runs.+ </p>+ </details>+ <details>+ <summary>Which chain does this settle on?</summary>+ <p>+ SperaxOS settles agent payments via x402 over USDC on Base, matching three.ws's+ Base x402 rail. The avatar itself renders regardless of chain — see+ <a href="#spx-chain">Base x402, natively</a> above.+ </p>+ </details>+ <details>+ <summary>Where's the technical detail?</summary>+ <p>+ The full plugin reference — manifest, tools, and local testing — lives in the+ <a href="/sperax/manifest.json" rel="noopener">manifest</a> and the integration+ write-up at+ <a href="/blog/three-ws-speraxusd-integration">three.ws Ships Inside SperaxUSD</a>.+ </p>+ </details>+ </div>+ </section>++ <!-- ── Final CTA ────────────────────────────────────── -->+ <section class="spx-final" aria-labelledby="spx-final-h">+ <h2 id="spx-final-h">Give your agent a body</h2>+ <p>+ Install the plugin, connect your three.ws identity, and claim your free credits on+ SperaxOS.+ </p>+ <div class="spx-cta-row">+ <a class="spx-btn spx-btn-primary" href="https://chat.sperax.io" rel="noopener">+ Open SperaxOS →+ </a>+ <a class="spx-btn spx-btn-secondary" href="/dashboard">Get your Agent ID</a>+ </div>+ </section></main><script src="/brand.js" defer></script>diff --git a/prompts/x402-overhaul/PROGRESS.md b/prompts/x402-overhaul/PROGRESS.mdindex dd8127d3d..332bc97ef 100644--- a/prompts/x402-overhaul/PROGRESS.md+++ b/prompts/x402-overhaul/PROGRESS.md@@ -222,10 +222,59 @@ three.ws agents. Same route, same paid model ($0.01 USDC, Base/Solana).disambiguation), score determinism/bounds, available-weighted normalization,denylist cap, negative-feedback scaling, unknown path, batch resilience.-**Real scores captured** (live reads):+**Real scores captured** (live reads, run through an isolated sandbox because six+concurrent agents' parallel `npm install`/`ci` runs were continuously wiping the+shared `node_modules` — same install-storm the Prompt 10 note describes):```-<!-- pasted after clean node_modules reinstall completes -->+# EVM wallet — vitalik.eth on chain 1 (live Ethereum RPC via evmFallbackProvider)+subject 0xd8da6bf26964af9d7eed9e03e53415d37aa96045 subjectType evm_wallet+score 100 tier elite tx_count 5898 native_balance 6.62 ETH holdings_usd 11919.25+weight_considered 35 (activity+holdings readable; age/counterparties/reliability/attestations caveated)++# Solana mint — $THREE, external market path (live DexScreener)+subject FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump subjectType solana_mint+score 76 tier high txns_24h 40043 liquidity_usd 206145.02 volume_24h 407599.22 age 68.7d+weight_considered 50 caveat: external mint — scored from market signals, not agent behavior++# Solana wallet — a hyperactive exchange wallet (live public Solana RPC)+subject 5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9 subjectType solana_wallet+score 100 tier elite signature_count 1000 (cap hit) sol_balance 928818.6 denylisted false+weight_considered 25 caveat: activity is a lower bound AND age not derivable (history > 1000-tx scan window)+# ↑ surfaced + fixed a real bug: for a wallet that fills the 1000-sig page, the oldest+# signature is NOT the account age — age is now marked unavailable when the page saturates.++# ERC-8004 agent — id 1 on Base (live Base RPC)+subject erc8004:8453:1 subjectType erc8004_agent+score null tier unknown caveat: "ERC-8004 registry unreadable on chain 8453"+# Canonical ERC-8004 mainnet registries have no bytecode on Base yet (getReputation+# reverts "missing revert data"), so the endpoint correctly degrades to unknown — never a fake score.++# Garbage subject → subjectType unknown, score null, caveat "unrecognized identifier format"+```++**Tests — `npx vitest run` (window caught between the concurrent install storm):**++```+tests/subject-reputation.test.js + tests/x402-agent-reputation-sweep.test.js+ Test Files 2 passed (2) Tests 50 passed (50)+# incl. the existing sweep/leaderboard/decay suite → confirms the POST modes still work.+tests/agent-bouncer.test.js + tests/wallet-reputation.test.js + tests/subject-reputation.test.js+ Test Files 3 passed (3) Tests 61 passed (61)+```++**`scripts/verify-x402-discovery.mjs` (local built doc, X402_PAY_TO_* set):**++```+--- summary ---+ ✓ clean: 74+ ▲ warnings: 0+ ✗ will be DROPPED by CDP/indexers: 0+OVERALL_EXIT=0+# /api/x402/agent-reputation entry:+# serviceName "Cross-chain Agent Reputation" (28 chars); tags [reputation,trust,cross-chain,agent,x402]+# bazaar.discoverable true; info.input.queryParams {subject:…}; output.example.subjectType solana_mint;+# schema present → bazaar.info validates against bazaar.schema (CDP-strict check passes).```**Adjacent gaps noticed (for other prompts):**@@ -966,24 +1015,111 @@ The endpoint's full decision logic was exercised end-to-end against the live feevia a node harness (the handler's own import chain pulls `db.js`→`@neondatabase`,which the shared node_modules was mid-corruption on — see blocker).-**Tests:** `tests/pump-bonding.test.js` (curve math incl. clamp/null; on-curve &-graduated mapping; raydium/pumpswap venue; `isPumpLaunch` native-vs-indexed) and-`tests/crypto-bonding-endpoint.test.js` (missing/invalid/not-found→400,-upstream-down→503, on-curve + graduated 200 shapes, 429). All assertions were-verified green by re-running the identical logic directly under `node` (below).--**Blocker (environment, not code):** `npm test`/vitest could not be run — the-shared worktree's `node_modules` is being continuously corrupted by concurrent-agents' `npm install` operations on a corrupted npm cache (persistent `ENOENT-rename` / `ENOTEMPTY` races; `@vitest/utils` left version-mismatched vs core). This-is the documented "concurrent agents share this worktree" trap, not a defect in-the code or tests. All logic was instead validated by direct `node --input-type=-module` execution against live pump.fun data (curve math, all mapping branches,-`isPumpLaunch`, and the endpoint decision logic all pass). Re-run `npm test` once-the workspace install settles.+**Tests: green (24/24).** `tests/pump-bonding.test.js` (curve math incl. clamp/null;+on-curve & graduated mapping; raydium/pumpswap venue; `isPumpLaunch` native-vs-+indexed) and `tests/crypto-bonding-endpoint.test.js` (missing/invalid/not-found→400,+upstream-down→503, on-curve + graduated 200 shapes, 429). The oracle suite+(`tests/oracle`, 109 tests) also stays green, confirming the `market.js` curve-math+refactor is behavior-preserving.++```+Test Files 2 passed (2) Tests 24 passed (24) # bonding+Test Files 11 passed (11) Tests 109 passed (109) # tests/oracle (refactor safe)+```++**Environment note (resolved):** for most of this session the shared worktree's+`node_modules` was unrunnable — concurrent agents' simultaneous `npm install`s on a+corrupted npm cache left the vitest tree version-mismatched (`ENOENT rename` /+`ENOTEMPTY` races; `@vitest/utils` core-vs-utils drift). Logic was validated in the+interim by direct `node --input-type=module` runs against live pump.fun data; once a+full `npm install` reconciled the tree, the vitest suite ran clean (above).**Adjacent gaps noticed (for other streams):**- `/api/crypto/whales` (06) is referenced in this endpoint's `related` + docs but isowned by prompt 06; already shipped by a sibling (present in the catalog).- `data/pages.json` `/docs/crypto-api` + the `STRUCTURE.md` crypto rows were alreadyadded by the index prompt (10) and list `bonding` — left as-is, no edit needed.++---++## Prompt 18 — Elevate the Vanity Grinder listing (flagship) — 2026-07-07++**What shipped (listing quality; grinding/signing behavior untouched):**+- **Primary route `api/x402/vanity.js`** — rewrote `ROUTE_DESCRIPTION` to LEAD WITH+ the use-case (branded token MINT address, recognizable agent/treasury wallet),+ then both formats (keypair vs importable BIP-39 mnemonic), the char caps + full+ price ladder ($0.01/$0.05/$0.25 keypair, $0.05/$0.50 mnemonic), the security model+ (nothing stored; served once over TLS; secret stripped from the replay cache;+ optional `sealTo` ECIES x25519-hkdf-sha256-aes256gcm), and the keyless/no-account+ pledge. Input/output discovery schemas were already complete (format, strength,+ sealTo, certificate, verifyUrl) — verified, left intact.+- **`api/wk.js` discovery mirror** — the `/api/x402/vanity` entry was stale: its+ description omitted `format=mnemonic` and `sealTo`, and its inputSchema listed only+ prefix/suffix/ignoreCase. Brought it into parity with the live handler (added+ `format`, `strength`, `sealTo` to the schema; mnemonic tier + price ladder + sealTo+ to the description; enriched the REST output example with mnemonic/verify fields).+- **`api/x402/vanity-premium.js` was MISSING from discovery entirely** — a paid+ `send402` route that was neither cataloged nor in the parity test's EXCLUSIONS, so+ it was invisible to x402scan/Bazaar and made `x402-discovery-parity` red. Added a+ full resource entry (`routeMeta.vanityPremium` + IIFE, $1 floor tier, address/sealTo+ schema, custody-honesty copy, cross-ref to the live grinder) and a REST output+ example. All three vanity tiers now index.+- **De-confliction:** the three routes now read distinctly — `vanity` (live ≤3-char+ grind), `vanity-verifiable` (same grind + signed commit–reveal receipt),+ `vanity-premium` (pre-ground 4–5+ char inventory, sell-from-stock). No merge/removal+ (correctly deferred per prompt).+- **Docs:** new `docs/vanity.md` (use-cases, all three tiers, formats, price ladder,+ security model, discovery); linked from `docs/x402-endpoints.md` (sharpened the three+ vanity rows) and `docs/start-here.md`. `data/changelog.json` entry (tag+ `improvement`, link `/docs/vanity`).++**Price ladder check:** vanity endpoints price via local `PRICE_BY_LENGTH` maps, NOT+`_lib/x402-prices.js` (which has no vanity slug), so there is no drift to fix there.+The catalog↔handler drift that existed was in `api/wk.js` (fixed above). The catalog+advertises the 1-char entry tiers (`10000`/`20000`/`1000000`) while each live 402+quotes the exact pattern price — matches the handlers.++**Real grind captured (1-char prefix, live WASM engine, 2026-07-07):**+```+prefix "z" →+ address : zt5phCsuqGdMJmuGtJjjJoMEEQNBdWwLsPbq6w1gpad (startsWith "z" ✓)+ secretKey: 64 bytes; attempts ~20000; durationMs ~278+Validity proof (Node crypto, no external deps):+ b58(secretKey[32:64]) == address → true+ ed25519 pubkey re-derived from secretKey[0:32] == pubkey → true+```+The grinder (`src/solana/vanity/grinder-node.js`) imports only local WASM ++validation — zero node_modules deps — so this ran cleanly despite the corrupted+shared tree.++**Verify script — PASSES (built in an isolated git worktree with a clean install,+since the shared node_modules was mid-corruption; my edited `api/wk.js` overlaid):**+```+x402 discovery check — /tmp/wt-catalog.json+service: three.ws resources: 74+--- summary ---+ ✓ clean: 74+ ▲ warnings: 0+ ✗ will be DROPPED by CDP/indexers: 0+```+All three vanity routes present & clean: `/api/x402/vanity` (10000),+`/api/x402/vanity-verifiable` (20000), `/api/x402/vanity-premium` (1000000, newly+indexed). Vanity tests green in the worktree: `x402-vanity-sealed-envelope`,+`vanity-mnemonic`, `vanity-wasm-grinder`, `vanity-premium-inventory` → 41 passed,+1 skipped.++**Blocker (environment, not code):** same documented "concurrent agents share this+worktree" trap — 13–17 simultaneous `npm install` runs from sibling agents kept the+shared `node_modules` in perpetual `ENOENT rename`/corruption, so `node scripts/+build-x402-catalog.mjs` and `npx vitest` could not run in-tree. Worked around by+`git worktree add` + a clean isolated install; all verification above ran there.++**Adjacent gaps noticed (for other streams):**+- `/api/x402/pipeline` (committed by another agent, e004f2670 — the 3D asset-chain+ endpoint) is a paid `send402` route MISSING from the `api/wk.js` discovery catalog,+ so `x402-discovery-parity` flags it. Out of scope for prompt 18 — its owner needs to+ add a `resources[]` mirror (or an EXCLUSIONS entry). This is the only remaining+ parity miss after the vanity fix.+- Consolidation of the three vanity routes (if ever wanted) is a prompt 21/22 call, as+ this prompt noted — descriptions now make each one's distinct purpose explicit, so no+ urgency.diff --git a/public/3d.html b/public/3d.htmlnew file mode 100644index 000000000..9f9437498--- /dev/null+++ b/public/3d.html@@ -0,0 +1,359 @@+<!doctype html>+<html lang="en">+<head>+ <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>three.ws 3D API — free text→3D + inspection for AI agents</title>+ <meta name="description" content="A free, keyless 3D API for AI agents: turn a text prompt into a real GLB, validate and optimize any glTF/GLB, and graduate to paid Forge Pro quality tiers and Rigged Avatars. One URL to discover it all — no account, no API key." />+ <meta name="theme-color" content="#0b0b0b" />+ <meta property="og:title" content="three.ws 3D API — free text→3D + inspection for AI agents" />+ <meta property="og:description" content="Free, keyless 3D for agents: text→3D draft generation + glTF/GLB inspection, with a clean OpenAPI 3.1 doc and a paid ladder to production quality." />+ <meta property="og:type" content="website" />+ <meta property="og:url" content="https://three.ws/3d" />+ <link rel="canonical" href="https://three.ws/3d" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <script+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"+ integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw"+ crossorigin="anonymous"+ type="module"+ ></script>+ <script src="/model-viewer-meshopt.js"></script>+ <style>+ .ws3d { max-width: 980px; margin: 0 auto; padding: 0 var(--space-md) var(--space-2xl); }+ .ws3d a { color: var(--accent); text-decoration: none; }+ .ws3d a:hover { text-decoration: underline; }++ /* Hero */+ .hero { padding: var(--space-2xl) 0 var(--space-lg); }+ .hero .badges { display: flex; gap: var(--space-2xs); flex-wrap: wrap; margin-bottom: var(--space-sm); }+ .pill {+ font-family: var(--font-mono); font-size: var(--text-2xs); font-weight: var(--weight-semibold);+ text-transform: uppercase; letter-spacing: .06em;+ padding: .25rem .6rem; border-radius: var(--radius-pill);+ background: var(--accent-soft); color: var(--ink-bright); border: 1px solid var(--stroke);+ }+ .pill.live { display: inline-flex; align-items: center; gap: .4rem; }+ .pill.live .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ink-faint); transition: background var(--duration-base) var(--ease-standard); }+ .pill.live.up .dot { background: var(--success); box-shadow: 0 0 8px var(--success); }+ .pill.live.down .dot { background: var(--warn); }+ .hero h1 { font-family: var(--font-display); font-size: var(--text-3xl); line-height: var(--leading-tight); margin: 0 0 var(--space-sm); letter-spacing: -.02em; }+ .hero p.lede { font-size: var(--text-lg); color: var(--ink-dim); max-width: 62ch; margin: 0 0 var(--space-lg); }+ .hero .cta { display: flex; gap: var(--space-2xs); flex-wrap: wrap; }+ .btn {+ display: inline-flex; align-items: center; gap: .4rem;+ font-weight: var(--weight-semibold); font-size: var(--text-ui);+ padding: .6rem 1rem; border-radius: var(--radius-md);+ border: 1px solid var(--stroke); background: var(--surface-1); color: var(--ink-bright);+ cursor: pointer; transition: transform var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);+ }+ .btn:hover { border-color: var(--stroke-strong); transform: translateY(-1px); text-decoration: none; }+ .btn:active { transform: translateY(0); }+ .btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .btn.primary { background: var(--ink-bright); color: var(--bg-0); border-color: var(--ink-bright); }++ /* Stat strip */+ .stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--space-sm); margin: var(--space-lg) 0; }+ .stat { background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg); padding: var(--space-md); }+ .stat .n { font-family: var(--font-display); font-size: var(--text-2xl); color: var(--ink-bright); }+ .stat .l { font-size: var(--text-xs); color: var(--ink-dim); text-transform: uppercase; letter-spacing: .05em; }++ section.block { margin-top: var(--space-2xl); }+ section.block > h2 { font-family: var(--font-display); font-size: var(--text-xl); margin: 0 0 var(--space-xs); letter-spacing: -.01em; }+ section.block > p.sub { color: var(--ink-dim); margin: 0 0 var(--space-md); max-width: 64ch; }++ /* Endpoint table */+ .table-wrap { overflow-x: auto; border: 1px solid var(--stroke); border-radius: var(--radius-lg); }+ table.ep { width: 100%; border-collapse: collapse; font-size: var(--text-sm); min-width: 640px; }+ table.ep th, table.ep td { text-align: left; padding: .7rem .9rem; border-bottom: 1px solid var(--stroke); vertical-align: top; }+ table.ep th { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim); background: var(--surface-1); }+ table.ep tr:last-child td { border-bottom: none; }+ table.ep code { font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-bright); }+ .verb { font-family: var(--font-mono); font-size: var(--text-2xs); font-weight: var(--weight-bold); padding: .1rem .4rem; border-radius: var(--radius-sm); background: var(--accent-soft); color: var(--ink-bright); }+ .tier-tag { font-size: var(--text-2xs); color: var(--success); font-weight: var(--weight-semibold); }++ /* Code + run */+ pre.code { background: var(--bg-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); overflow-x: auto; font-family: var(--font-mono); font-size: var(--text-xs); line-height: 1.6; margin: 0; }+ pre.code code { color: var(--ink); }+ .runbar { display: flex; align-items: center; gap: var(--space-2xs); margin: var(--space-sm) 0 var(--space-2xs); flex-wrap: wrap; }+ .runbar .status { font-size: var(--text-xs); color: var(--ink-dim); }+ .out { margin-top: var(--space-2xs); }+ .out pre.code { max-height: 340px; overflow: auto; }++ /* Viewer */+ .viewer-card { display: grid; grid-template-columns: 1.2fr 1fr; gap: var(--space-lg); align-items: center; background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg); padding: var(--space-lg); }+ model-viewer { width: 100%; height: 320px; background: radial-gradient(circle at 50% 30%, var(--surface-2), var(--bg-1)); border-radius: var(--radius-md); --poster-color: transparent; }+ .viewer-card h3 { margin: 0 0 var(--space-2xs); font-family: var(--font-display); }+ .viewer-card p { color: var(--ink-dim); margin: 0 0 var(--space-sm); font-size: var(--text-sm); }++ /* Ladder */+ .ladder { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--space-sm); }+ .rung { background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg); padding: var(--space-md); display: flex; flex-direction: column; }+ .rung.free { border-color: var(--success); }+ .rung .cap { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim); }+ .rung h3 { font-family: var(--font-display); margin: .3rem 0; font-size: var(--text-lg); }+ .rung .price { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink-bright); margin-bottom: var(--space-2xs); }+ .rung.free .price { color: var(--success); }+ .rung ul { margin: var(--space-2xs) 0 var(--space-sm); padding-left: 1.1rem; color: var(--ink-dim); font-size: var(--text-sm); }+ .rung ul li { margin: .2rem 0; }+ .rung .go { margin-top: auto; }++ .faq { display: grid; gap: var(--space-sm); }+ .faq details { background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); }+ .faq summary { cursor: pointer; font-weight: var(--weight-semibold); color: var(--ink-bright); }+ .faq p { color: var(--ink-dim); margin: var(--space-2xs) 0 0; font-size: var(--text-sm); }++ footer.foot { margin-top: var(--space-2xl); padding-top: var(--space-lg); border-top: 1px solid var(--stroke); color: var(--ink-dim); font-size: var(--text-sm); }++ @media (max-width: 760px) {+ .stats, .ladder { grid-template-columns: 1fr; }+ .viewer-card { grid-template-columns: 1fr; }+ .hero h1 { font-size: var(--text-2xl); }+ }+ </style>+</head>+<body>+ <script src="/nav.js"></script>++ <main id="main-content" class="ws3d">+ <!-- Hero -->+ <header class="hero">+ <div class="badges">+ <span class="pill">Free</span>+ <span class="pill">Keyless</span>+ <span class="pill">OpenAPI 3.1</span>+ <span class="pill live" id="liveBadge" title="Live status of the API"><span class="dot"></span><span id="liveText">checking…</span></span>+ </div>+ <h1>three.ws 3D API</h1>+ <p class="lede">Give your AI agent a 3D toolchain. Turn a text prompt into a real textured GLB, validate and optimize any glTF/GLB — <strong>free, keyless, no account</strong>. When a draft isn't enough, the same API graduates to production Forge Pro tiers and animation-ready Rigged Avatars.</p>+ <div class="cta">+ <a class="btn primary" href="#quickstart">Quickstart</a>+ <a class="btn" href="/api/3d/openapi.json">OpenAPI spec →</a>+ <a class="btn" href="/api/3d">JSON index →</a>+ </div>+ </header>++ <!-- Live stats -->+ <div class="stats" aria-label="API at a glance">+ <div class="stat"><div class="n" id="statEndpoints">—</div><div class="l">Free endpoints</div></div>+ <div class="stat"><div class="n">$0</div><div class="l">Cost to start</div></div>+ <div class="stat"><div class="n">0</div><div class="l">API keys required</div></div>+ </div>++ <!-- Who it's for -->+ <section class="block">+ <h2>Who this is for</h2>+ <p class="sub">An autonomous agent building a game, a scene, an NFT, or a marketplace asset needs 3D — and needs to trust what it gets. This API answers both mid-task: <strong>make me a model from this description</strong>, and <strong>is this model any good, and how do I make it smaller?</strong> No other agent-payments platform gives away 3D generation and inspection.</p>+ </section>++ <!-- Endpoints -->+ <section class="block" id="endpoints">+ <h2>Endpoints</h2>+ <p class="sub">Assembled live from the API catalog. Every row is free and keyless.</p>+ <div class="table-wrap">+ <table class="ep">+ <thead>+ <tr><th>Method</th><th>Path</th><th>What it does</th><th>Tier</th></tr>+ </thead>+ <tbody id="epRows">+ <tr><td colspan="4" style="color:var(--ink-dim)">Loading catalog…</td></tr>+ </tbody>+ </table>+ </div>+ </section>++ <!-- Quickstart -->+ <section class="block" id="quickstart">+ <h2>Quickstart</h2>+ <p class="sub">Copy, run, done. No key, no header, no account. These call the live production API.</p>++ <h3 style="font-family:var(--font-display);font-size:var(--text-md);margin:var(--space-md) 0 var(--space-2xs)">1 · Discover the whole API</h3>+ <pre class="code"><code>curl https://three.ws/api/3d</code></pre>++ <h3 style="font-family:var(--font-display);font-size:var(--text-md);margin:var(--space-md) 0 var(--space-2xs)">2 · Inspect a model (validate + optimization report)</h3>+ <pre class="code"><code>curl "https://three.ws/api/3d/inspect?url=https://three.ws/avatars/cesium-man.glb"</code></pre>+ <div class="runbar">+ <button class="btn" id="runInspect" type="button">Run it live ▶</button>+ <span class="status" id="inspectStatus"></span>+ </div>+ <div class="out"><pre class="code"><code id="inspectOut">// Response appears here — a real call to /api/3d/inspect.</code></pre></div>++ <h3 style="font-family:var(--font-display);font-size:var(--text-md);margin:var(--space-md) 0 var(--space-2xs)">3 · Generate a model from text (free draft)</h3>+ <pre class="code"><code>curl -X POST https://three.ws/api/3d/generate \+ -H 'content-type: application/json' \+ -d '{ "prompt": "a small ceramic robot figurine" }'+# → { "status": "pending", "job": "…", "poll": "/api/3d/generate?job=…" }+# poll the job:+curl "https://three.ws/api/3d/generate?job=<id>"+# → { "status": "done", "glbUrl": "https://…/model.glb", "viewerUrl": "https://three.ws/…" }</code></pre>++ <h3 style="font-family:var(--font-display);font-size:var(--text-md);margin:var(--space-md) 0 var(--space-2xs)">Point any OpenAPI toolchain at it</h3>+ <pre class="code"><code># LangChain, openapi-generator, Swagger UI, etc.+curl https://three.ws/api/3d/openapi.json</code></pre>+ </section>++ <!-- Viewer -->+ <section class="block">+ <h2>See the output</h2>+ <p class="sub">Everything the API touches is a real, standards-compliant GLB — the same format your engine, viewer, or marketplace already speaks. Drag to orbit.</p>+ <div class="viewer-card">+ <model-viewer+ src="/avatars/cesium-man.glb"+ alt="A rigged 3D character model rendered from a GLB file"+ camera-controls+ auto-rotate+ shadow-intensity="1"+ exposure="1.05"+ ar+ touch-action="pan-y"+ ></model-viewer>+ <div>+ <h3>Real GLB, not a screenshot</h3>+ <p>This is a live glTF binary rendered in your browser. The free <code>/api/3d/inspect</code> endpoint reports exactly what's inside one of these — vertices, triangles, materials, textures, animations, extensions — and a prioritized plan to make it smaller and faster.</p>+ <a class="btn" href="/api/3d/inspect?url=https://three.ws/avatars/cesium-man.glb">Inspect this model →</a>+ </div>+ </div>+ </section>++ <!-- Free → paid ladder -->+ <section class="block">+ <h2>Free → paid ladder</h2>+ <p class="sub">Start free. Upgrade only when a draft isn't enough. Paid tiers settle per-call in USDC over <a href="/pay">x402</a> — still no account, still no key.</p>+ <div class="ladder">+ <div class="rung free">+ <span class="cap">Tier 0 · Free</span>+ <h3>Draft + Inspect</h3>+ <div class="price">$0 · keyless</div>+ <ul>+ <li>Text→3D draft (NIM TRELLIS): single subject, GLB, no rigging</li>+ <li>glTF/GLB validation + optimization report</li>+ <li>Generous per-IP rate limit</li>+ </ul>+ <div class="go"><a class="btn" href="/api/3d">Use it →</a></div>+ </div>+ <div class="rung">+ <span class="cap">Tier 1 · Paid</span>+ <h3>Forge Pro</h3>+ <div class="price">from $0.05 USDC</div>+ <ul>+ <li>Higher polygon budgets + PBR textures</li>+ <li>draft / standard / high quality tiers</li>+ <li>Text→3D and image→3D pipelines</li>+ </ul>+ <div class="go"><a class="btn" href="/forge">Open Forge →</a></div>+ </div>+ <div class="rung">+ <span class="cap">Tier 2 · Paid</span>+ <h3>Rigged Avatars</h3>+ <div class="price">from $0.05 USDC</div>+ <ul>+ <li>Auto skeleton + skin weights</li>+ <li>Pre-baked idle / walk clip library</li>+ <li>Animation-ready humanoid GLB</li>+ </ul>+ <div class="go"><a class="btn" href="/create/prompt">Rig one →</a></div>+ </div>+ </div>+ </section>++ <!-- FAQ -->+ <section class="block">+ <h2>Notes</h2>+ <div class="faq">+ <details>+ <summary>Is it really free and keyless?</summary>+ <p>Yes. No account, no API key, no wallet. Free endpoints have a generous per-IP rate limit that only blunts abuse. The free draft generation tier runs on a shared GPU lane — it's honest about being a prototyping tier (draft geometry, GLB only, no rigging).</p>+ </details>+ <details>+ <summary>What formats are supported?</summary>+ <p>Output is binary glTF (GLB) — the web-standard 3D container every engine and viewer reads. Inspection accepts <code>.glb</code> and <code>.gltf</code> from any public URL, up to the documented size cap.</p>+ </details>+ <details>+ <summary>How do agents pay for the pro tiers?</summary>+ <p>Programmatically, over <a href="/pay">x402</a> (HTTP 402 + USDC on Base or Solana). No key exchange — an agent just retries the request with a payment header. See the paid <a href="/bazaar">x402 Bazaar</a> for the full catalog.</p>+ </details>+ </div>+ </section>++ <footer class="foot">+ Built for agents. Machine-readable spec: <a href="/api/3d/openapi.json">/api/3d/openapi.json</a> · Discovery: <a href="/api/3d">/api/3d</a> · Paid catalog: <a href="/bazaar">x402 Bazaar</a>+ </footer>+ </main>++ <script src="/brand.js" defer></script>+ <script type="module">+ // Live wiring. Everything degrades gracefully: in local dev, /api/* proxies+ // to production, so these calls hit the real endpoints. If a call fails+ // (offline, pre-deploy), we fall back to the known real catalog shape so the+ // page is never broken — but we mark the live badge honestly.+ const $ = (s) => document.querySelector(s);+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++ // Real, known catalog shape — the fallback if the live index can't be reached.+ const FALLBACK = [+ { methods: ['POST'], path: '/api/3d/generate', title: 'Text → 3D (free draft)', summary: 'Turn a text prompt into a real textured GLB. Draft tier, GLB only, no rigging.', free: true },+ { methods: ['GET', 'POST'], path: '/api/3d/inspect', title: '3D Model Inspect & Validate', summary: 'Validate a glTF/GLB and return structural stats + a prioritized optimization plan.', free: true },+ ];++ function renderRows(endpoints) {+ const rows = (endpoints && endpoints.length ? endpoints : FALLBACK).map((e) => {+ const verbs = (e.methods || ['GET']).map((m) => `<span class="verb">${esc(m)}</span>`).join(' ');+ return `<tr>+ <td>${verbs}</td>+ <td><code>${esc(e.path)}</code></td>+ <td>${esc(e.title || e.slug || '')}${e.summary ? `<br><span style="color:var(--ink-dim)">${esc(e.summary)}</span>` : ''}</td>+ <td><span class="tier-tag">Free</span></td>+ </tr>`;+ }).join('');+ $('#epRows').innerHTML = rows;+ $('#statEndpoints').textContent = String((endpoints && endpoints.length) || FALLBACK.length);+ }++ function setLive(up) {+ const b = $('#liveBadge');+ b.classList.toggle('up', up);+ b.classList.toggle('down', !up);+ $('#liveText').textContent = up ? 'live' : 'offline';+ }++ // 1) Discover the catalog for the endpoint table + stat.+ (async () => {+ try {+ const r = await fetch('/api/3d', { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error('status ' + r.status);+ const data = await r.json();+ renderRows(data.endpoints);+ setLive(true);+ } catch {+ renderRows(null); // real fallback shape+ setLive(false);+ }+ })();++ // 2) Run inspect live on demand.+ const GLB = 'https://three.ws/avatars/cesium-man.glb';+ $('#runInspect').addEventListener('click', async () => {+ const btn = $('#runInspect');+ const out = $('#inspectOut');+ const status = $('#inspectStatus');+ btn.disabled = true;+ status.textContent = 'calling /api/3d/inspect …';+ const t0 = performance.now();+ try {+ const r = await fetch('/api/3d/inspect?url=' + encodeURIComponent(GLB), { headers: { accept: 'application/json' } });+ const ms = Math.round(performance.now() - t0);+ const data = await r.json();+ out.textContent = JSON.stringify(data, null, 2);+ status.textContent = `${r.status} · ${ms} ms`;+ } catch (err) {+ out.textContent = '// Live call failed (the API may not be deployed to this environment yet).\n// The endpoint is https://three.ws/api/3d/inspect?url=<glb>\n// ' + esc(err.message);+ status.textContent = 'offline';+ } finally {+ btn.disabled = false;+ }+ });+ </script>+</body>+</html>diff --git a/public/features.json b/public/features.jsonindex 33059eb42..bd93ee6a7 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-06T21:07:37.673Z",+ "generated_at": "2026-07-07T01:01:47.616Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1867,6 +1867,36 @@"tags": [],"showcase": false},+ {+ "path": "/crypto",+ "title": "Crypto Data API",+ "description": "Free, keyless crypto data for AI agents in one API: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios and ticker-availability checks. No key, no account, no paywall.",+ "added": "2026-07-07",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": true+ },+ {+ "path": "/3d",+ "title": "3D API",+ "description": "Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.",+ "added": "2026-07-07",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": true+ },+ {+ "path": "/docs/crypto-api",+ "title": "Docs · Crypto Data API",+ "description": "Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.",+ "added": "2026-07-07",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/docs/walk","title": "Docs · Walk Avatar",@@ -1957,6 +1987,16 @@"tags": [],"showcase": false},+ {+ "path": "/docs/trust-primitives",+ "title": "Docs · Trust Primitives",+ "description": "Cross-chain Agent Reputation — score any wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence before your agent pays, trades, or delegates.",+ "added": "2026-07-07",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/docs/x402","title": "Docs · x402 Protocol",@@ -1987,6 +2027,16 @@"tags": [],"showcase": false},+ {+ "path": "/docs/pump-launcher",+ "title": "Docs · Pump Launcher",+ "description": "Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.",+ "added": "2026-07-07",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/docs/x402-buyer","title": "Docs · x402 Buyer Client",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 7f73fa2e2..a98784d88 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -1144,6 +1144,24 @@ URL: https://three.ws/docsFull documentation: SDKs, API reference, embedding, agent system, smart contracts.+### Crypto Data API++URL: https://three.ws/crypto++Free, keyless crypto data for AI agents in one API: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios and ticker-availability checks. No key, no account, no paywall.++### 3D API++URL: https://three.ws/3d++Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.++### Docs · Crypto Data API++URL: https://three.ws/docs/crypto-api++Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.+### Docs · Walk AvatarURL: https://three.ws/docs/walk@@ -1198,6 +1216,12 @@ URL: https://three.ws/docs/agent-reputationWhy autonomous agents need verifiable trust, and how three.ws delivers portable on-chain reputation.+### Docs · Trust Primitives++URL: https://three.ws/docs/trust-primitives++Cross-chain Agent Reputation — score any wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence before your agent pays, trades, or delegates.+### Docs · x402 ProtocolURL: https://three.ws/docs/x402@@ -1216,6 +1240,12 @@ URL: https://three.ws/docs/x402-revenueWhere settled x402 payments are recorded (x402_audit_log), how to read endpoint revenue, and how signed receipts work.+### Docs · Pump Launcher++URL: https://three.ws/docs/pump-launcher++Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.+### Docs · x402 Buyer ClientURL: https://three.ws/docs/x402-buyerdiff --git a/public/llms.txt b/public/llms.txtindex e28ac2046..871d0ca36 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -211,6 +211,9 @@ Sign-in, dashboard, billing.Docs, tutorials, and reference.- [Docs](https://three.ws/docs): Full documentation: SDKs, API reference, embedding, agent system, smart contracts.+- [Crypto Data API](https://three.ws/crypto): Free, keyless crypto data for AI agents in one API: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios and ticker-availability checks. No key, no account, no paywall.+- [3D API](https://three.ws/3d): Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.+- [Docs · Crypto Data API](https://three.ws/docs/crypto-api): Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.- [Docs · Walk Avatar](https://three.ws/docs/walk): Developer and user documentation for the three.ws walking-avatar system: the /walk page, iframe embeds, the JavaScript SDK, the postMessage event contract, companion mode, analytics, and the Chrome extension.- [Docs · Start Here](https://three.ws/docs/start-here): Plain-language introduction to three.ws for creators and non-developers — what it is, who it’s for, and where to begin.- [Docs · Make Your First Agent](https://three.ws/docs/make-your-agent): Step-by-step guide to creating a 3D AI agent in the browser with no code required.@@ -220,9 +223,11 @@ Docs, tutorials, and reference.- [Docs · Agent System](https://three.ws/docs/agent-system): How agents, avatars, skills, and memories fit together.- [Docs · ERC-8004](https://three.ws/docs/erc8004): Reference for the on-chain agent identity standard.- [Docs · Agent Reputation](https://three.ws/docs/agent-reputation): Why autonomous agents need verifiable trust, and how three.ws delivers portable on-chain reputation.+- [Docs · Trust Primitives](https://three.ws/docs/trust-primitives): Cross-chain Agent Reputation — score any wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence before your agent pays, trades, or delegates.- [Docs · x402 Protocol](https://three.ws/docs/x402): How three.ws implements x402 HTTP 402 paid agent skills — the challenge, verify, and settle mechanics.- [Docs · x402 Paid Endpoints](https://three.ws/docs/x402-endpoints): The catalog of three.ws's own paid HTTP endpoints — what each charges, the price-override scheme, and what it returns.- [Docs · x402 Revenue & Receipts](https://three.ws/docs/x402-revenue): Where settled x402 payments are recorded (x402_audit_log), how to read endpoint revenue, and how signed receipts work.+- [Docs · Pump Launcher](https://three.ws/docs/pump-launcher): Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.- [Docs · x402 Buyer Client](https://three.ws/docs/x402-buyer): How to settle a 402 challenge and pay three.ws's paid endpoints from code.- [Docs · Autonomous x402 Loop](https://three.ws/docs/autonomous-x402): The scheduled buyer that pays x402 endpoints on a cadence to feed the oracle and sniper — real USDC, real settlements.- [Docs · Circulation Engine](https://three.ws/docs/circulation-engine): The autonomous agent-to-agent activity loop — a pool of real platform agents tipping, paying, trading, and launching with one another.diff --git a/public/nav-data.js b/public/nav-data.jsindex fdef8ec4c..f656b25c9 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -421,6 +421,16 @@ export const NAV_GROUPS = [{label: 'Developers',items: [+ {+ title: 'Crypto Data API',+ href: '/crypto',+ desc: 'Free, keyless crypto data for agents — snapshots, rug checks, launches, whales',+ },+ {+ title: '3D API',+ href: '/3d',+ desc: 'Free, keyless text→3D + glTF/GLB inspection for agents — with a paid pro ladder',+ },{title: 'Avatar SDK',href: '/avatar-sdk',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 5f77fa900..81786db2d 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 382 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 387 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 382 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 387 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -1410,7 +1410,7 @@<section class="sm-section" id="learn"><header>- <h2>Learn<span class="sm-count" data-count>53</span></h2>+ <h2>Learn<span class="sm-count" data-count>58</span></h2><p class="sm-section-desc">Docs, tutorials, and reference.</p></header><ul class="sm-list">@@ -1421,6 +1421,27 @@<span class="sm-desc">Full documentation: SDKs, API reference, embedding, agent system, smart contracts.</span></a></li>+ <li>+ <a href="/crypto">+ <span class="sm-title">Crypto Data API</span>+ <span class="sm-path">/crypto</span>+ <span class="sm-desc">Free, keyless crypto data for AI agents in one API: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios and ticker-availability checks. No key, no account, no paywall.</span>+ </a>+ </li>+ <li>+ <a href="/3d">+ <span class="sm-title">3D API</span>+ <span class="sm-path">/3d</span>+ <span class="sm-desc">Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.</span>+ </a>+ </li>+ <li>+ <a href="/docs/crypto-api">+ <span class="sm-title">Docs · Crypto Data API</span>+ <span class="sm-path">/docs/crypto-api</span>+ <span class="sm-desc">Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.</span>+ </a>+ </li><li><a href="/docs/walk"><span class="sm-title">Docs · Walk Avatar</span>@@ -1484,6 +1505,13 @@<span class="sm-desc">Why autonomous agents need verifiable trust, and how three.ws delivers portable on-chain reputation.</span></a></li>+ <li>+ <a href="/docs/trust-primitives">+ <span class="sm-title">Docs · Trust Primitives</span>+ <span class="sm-path">/docs/trust-primitives</span>+ <span class="sm-desc">Cross-chain Agent Reputation — score any wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence before your agent pays, trades, or delegates.</span>+ </a>+ </li><li><a href="/docs/x402"><span class="sm-title">Docs · x402 Protocol</span>@@ -1505,6 +1533,13 @@<span class="sm-desc">Where settled x402 payments are recorded (x402_audit_log), how to read endpoint revenue, and how signed receipts work.</span></a></li>+ <li>+ <a href="/docs/pump-launcher">+ <span class="sm-title">Docs · Pump Launcher</span>+ <span class="sm-path">/docs/pump-launcher</span>+ <span class="sm-desc">Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.</span>+ </a>+ </li><li><a href="/docs/x402-buyer"><span class="sm-title">Docs · x402 Buyer Client</span>diff --git a/tests/3d-catalog.test.js b/tests/3d-catalog.test.jsnew file mode 100644index 000000000..06b31a91a--- /dev/null+++ b/tests/3d-catalog.test.js@@ -0,0 +1,188 @@+// Tests for the free 3D API discovery layer (prompt 14): the catalog assembler+// (globs entry files, accepts both descriptor naming styles, skips malformed,+// dedups routes, never throws), the OpenAPI 3.1 generator, and the GET /api/3d+// index handler's HTML-vs-JSON content negotiation.++import { describe, it, expect } from 'vitest';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++import { loadCatalog, normalizeEntry } from '../api/_lib/3d-catalog/index.js';+import { buildOpenApiDoc, validateOpenApiDoc } from '../api/_lib/3d-catalog/openapi.js';+import threeIndex from '../api/3d/index.js';++const HERE = dirname(fileURLToPath(import.meta.url));+const FIXTURES = resolve(HERE, '_fixtures/3d-catalog');++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ setHeader(k, v) {+ this._headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._headers[k.toLowerCase()];+ },+ end(b) {+ this._body = b || '';+ },+ get headersSent() {+ return false;+ },+ get writableEnded() {+ return false;+ },+ get json() {+ try {+ return JSON.parse(this._body);+ } catch {+ return null;+ }+ },+ };+}++function mockReq({ accept = 'application/json' } = {}) {+ return {+ method: 'GET',+ url: '/api/3d',+ headers: { accept, origin: 'http://localhost:3000' },+ socket: { remoteAddress: '127.0.0.1' },+ };+}++describe('3d-catalog assembler', () => {+ it('merges valid entries in BOTH naming styles, skips malformed/throwing, dedups routes', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const slugs = entries.map((e) => e.slug).sort();++ // generate.js (slug/method) + inspect.js (id/name/methods) both survive;+ // broken-shape.js, broken-throws.js are dropped, and zz-dup-inspect.js is+ // deduped away (same GET,POST /api/3d/inspect route as inspect.js).+ expect(slugs).toEqual(['generate', 'inspect']);+ expect(entries.find((e) => e.slug === 'never')).toBeUndefined();+ expect(entries.find((e) => e.slug === 'inspect-dupe')).toBeUndefined();+ });++ it('accepts the id/name/methods descriptor style without dropping it', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const inspect = entries.find((e) => e.slug === 'inspect');+ expect(inspect).toBeTruthy();+ expect(inspect.title).toBe('3D Model Inspect & Validate'); // from `name`+ expect(inspect.methods).toEqual(['GET', 'POST']);+ expect(inspect.summary).toBeTruthy(); // from `description`+ });++ it('normalizes: methods upper-cased array, optional fields defaulted (never undefined)', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const gen = entries.find((e) => e.slug === 'generate');+ expect(gen.methods).toEqual(['POST']); // fixture declares lowercase "post"+ expect(gen.path).toBe('/api/3d/generate');+ expect(gen.free).toBe(true);+ expect(gen.keyless).toBe(true);+ expect(Array.isArray(gen.tags)).toBe(true);+ expect(gen.paidTiers).toBeInstanceOf(Array);+ });++ it('normalizeEntry drops entries with no route/name/summary', () => {+ expect(normalizeEntry(null, 'x')).toBeNull();+ expect(normalizeEntry({ slug: 'a', summary: 'b' }, 'x')).toBeNull(); // no path+ expect(normalizeEntry({ path: '/x', summary: 'b' }, 'x')).toBeNull(); // no slug/id+ expect(normalizeEntry({ slug: 'a', path: '/x' }, 'x')).toBeNull(); // no summary+ });++ it('returns a valid EMPTY catalog for a directory with no entries', async () => {+ const empty = mkdtempSync(join(tmpdir(), '3d-catalog-empty-'));+ const entries = await loadCatalog({ dir: empty, fresh: true });+ expect(entries).toEqual([]);+ });++ it('never throws on an unreadable directory', async () => {+ const missing = join(tmpdir(), 'does-not-exist-3d-' + 'xyz');+ await expect(loadCatalog({ dir: missing, fresh: true })).resolves.toEqual([]);+ });+});++describe('3d-catalog OpenAPI generator', () => {+ it('produces a structurally valid OpenAPI 3.1 doc from the entries', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const doc = buildOpenApiDoc(entries, { origin: 'https://three.ws', version: '1.0.0' });++ expect(validateOpenApiDoc(doc)).toEqual([]);+ expect(doc.openapi).toBe('3.1.0');+ expect(doc.info.title).toBe('three.ws 3D API');+ expect(doc.info.version).toBe('1.0.0');+ expect(doc.servers[0].url).toBe('https://three.ws');++ // generate is POST → operation under `post`.+ expect(doc.paths['/api/3d/generate'].post.operationId).toBe('generate');+ // inspect answers GET + POST → both verbs present, distinct operationIds.+ expect(doc.paths['/api/3d/inspect'].get.operationId).toBe('inspect_get');+ expect(doc.paths['/api/3d/inspect'].post.operationId).toBe('inspect_post');+ });++ it('emits a JSON requestBody for POST and query parameters for GET', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const doc = buildOpenApiDoc(entries);++ // POST generate → requestBody from inputSchema, marked required (prompt).+ const post = doc.paths['/api/3d/generate'].post;+ expect(post.requestBody).toBeTruthy();+ expect(post.requestBody.required).toBe(true);+ expect(post.requestBody.content['application/json'].schema.properties.prompt).toBeTruthy();++ // GET inspect → `url` as a query parameter.+ const get = doc.paths['/api/3d/inspect'].get;+ const url = get.parameters.find((p) => p.name === 'url');+ expect(url.in).toBe('query');+ });++ it('validates an empty-catalog doc (no paths) as still well-formed', () => {+ const doc = buildOpenApiDoc([], { origin: 'https://three.ws' });+ expect(validateOpenApiDoc(doc)).toEqual([]);+ expect(doc.paths).toEqual({});+ });++ it('flags a malformed doc', () => {+ expect(validateOpenApiDoc({ openapi: '3.0.0' }).length).toBeGreaterThan(0);+ expect(validateOpenApiDoc(null)).toEqual(['document is not an object']);+ });+});++describe('GET /api/3d content negotiation', () => {+ it('returns JSON by default with the discovery envelope + paid ladder', async () => {+ const req = mockReq({ accept: 'application/json' });+ const res = mockRes();+ await threeIndex(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toMatch(/application\/json/);+ const body = res.json;+ expect(body.name).toBe('three.ws 3D API');+ expect(body.free).toBe(true);+ expect(body.keyless).toBe(true);+ expect(Array.isArray(body.endpoints)).toBe(true);+ expect(Array.isArray(body.paidTiers)).toBe(true);+ expect(body.paidTiers.map((t) => t.name)).toContain('Forge Pro');+ expect(body.paidTiers.map((t) => t.name)).toContain('Rigged Avatar');+ expect(body.docs).toBe('/docs/3d-api');+ expect(body.openapi).toBe('/api/3d/openapi.json');+ expect(typeof body.ts).toBe('string');+ });++ it('returns HTML when the client asks for text/html', async () => {+ const req = mockReq({ accept: 'text/html' });+ const res = mockRes();+ await threeIndex(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toMatch(/text\/html/);+ expect(res._body).toContain('<!doctype html>');+ expect(res._body).toContain('three.ws 3D API');+ expect(res._body).toContain('Paid tiers');+ });+});diff --git a/tests/_fixtures/3d-catalog/broken-shape.js b/tests/_fixtures/3d-catalog/broken-shape.jsnew file mode 100644index 000000000..0e406daa3--- /dev/null+++ b/tests/_fixtures/3d-catalog/broken-shape.js@@ -0,0 +1,2 @@+// Fixture: malformed (no slug/id, no path). Must be SKIPPED, not fatal.+export default { method: 'GET', title: 'I forgot my slug and path' };diff --git a/tests/_fixtures/3d-catalog/broken-throws.js b/tests/_fixtures/3d-catalog/broken-throws.jsnew file mode 100644index 000000000..934711813--- /dev/null+++ b/tests/_fixtures/3d-catalog/broken-throws.js@@ -0,0 +1,4 @@+// Fixture: throws at import time. Must be SKIPPED, not fatal.+throw new Error('boom: this entry blows up on import');+// eslint-disable-next-line no-unreachable+export default { slug: 'never', method: 'GET', path: '/api/3d/never', summary: 'x' };diff --git a/tests/_fixtures/3d-catalog/generate.js b/tests/_fixtures/3d-catalog/generate.jsnew file mode 100644index 000000000..938124cbf--- /dev/null+++ b/tests/_fixtures/3d-catalog/generate.js@@ -0,0 +1,11 @@+// Fixture: valid entry, slug/method/inputSchema style.+export default {+ slug: 'generate',+ method: 'post',+ path: '/api/3d/generate',+ title: 'Text → 3D (free draft)',+ summary: 'Turn a text prompt into a GLB.',+ inputSchema: { type: 'object', required: ['prompt'], properties: { prompt: { type: 'string' } } },+ outputSchema: { type: 'object', properties: { status: { type: 'string' } } },+ example: { request: { prompt: 'a robot' }, response: { status: 'pending' } },+};diff --git a/tests/_fixtures/3d-catalog/inspect.js b/tests/_fixtures/3d-catalog/inspect.jsnew file mode 100644index 000000000..af850ecb8--- /dev/null+++ b/tests/_fixtures/3d-catalog/inspect.js@@ -0,0 +1,11 @@+// Fixture: valid entry in the ALTERNATE naming style (id/name/methods/input).+// Proves the assembler accepts both conventions instead of dropping this entry.+export default {+ id: 'inspect',+ name: '3D Model Inspect & Validate',+ path: '/api/3d/inspect',+ methods: ['GET', 'POST'],+ description: 'Validate a glTF/GLB and return stats + recommendations.',+ inputSchema: { type: 'object', properties: { url: { type: 'string', format: 'uri' } } },+ outputSchema: { type: 'object', required: ['valid'], properties: { valid: { type: 'boolean' } } },+};diff --git a/tests/_fixtures/3d-catalog/zz-dup-inspect.js b/tests/_fixtures/3d-catalog/zz-dup-inspect.jsnew file mode 100644index 000000000..07a7f617f--- /dev/null+++ b/tests/_fixtures/3d-catalog/zz-dup-inspect.js@@ -0,0 +1,2 @@+// Fixture: duplicate route of inspect (GET,POST /api/3d/inspect). Deduped away.+export default { slug: 'inspect-dupe', methods: ['GET', 'POST'], path: '/api/3d/inspect', summary: 'dupe' };diff --git a/tests/_fixtures/crypto-catalog/broken-shape.js b/tests/_fixtures/crypto-catalog/broken-shape.jsnew file mode 100644index 000000000..af6051228--- /dev/null+++ b/tests/_fixtures/crypto-catalog/broken-shape.js@@ -0,0 +1,5 @@+// Fixture: malformed entry (missing slug + path). Must be SKIPPED, not fatal.+export default {+ method: 'GET',+ title: 'I forgot my slug and path',+};diff --git a/tests/_fixtures/crypto-catalog/broken-throws.js b/tests/_fixtures/crypto-catalog/broken-throws.jsnew file mode 100644index 000000000..df88dd4f9--- /dev/null+++ b/tests/_fixtures/crypto-catalog/broken-throws.js@@ -0,0 +1,4 @@+// Fixture: an entry file that throws at import time. Must be SKIPPED, not fatal.+throw new Error('boom: this entry blows up on import');+// eslint-disable-next-line no-unreachable+export default { slug: 'never', method: 'GET', path: '/api/crypto/never' };diff --git a/tests/_fixtures/crypto-catalog/holders.js b/tests/_fixtures/crypto-catalog/holders.jsnew file mode 100644index 000000000..937f0fc1a--- /dev/null+++ b/tests/_fixtures/crypto-catalog/holders.js@@ -0,0 +1,15 @@+// Fixture: a well-formed entry exported as a named `entry` (the assembler+// accepts default, `entry`, or `catalogEntry`). Uses a templated path param and+// an array-style inputSchema to exercise both OpenAPI conversion branches.+export const entry = {+ slug: 'holders',+ method: 'GET',+ path: '/api/crypto/holders/{mint}',+ title: 'Top Holders',+ summary: 'Holder distribution for a mint.',+ inputSchema: [+ { name: 'mint', in: 'path', required: true, schema: { type: 'string' } },+ { name: 'limit', schema: { type: 'integer' }, description: 'Rows to return' },+ ],+ outputSchema: { type: 'object', properties: { holders: { type: 'array' } } },+};diff --git a/tests/_fixtures/crypto-catalog/paramstyle.js b/tests/_fixtures/crypto-catalog/paramstyle.jsnew file mode 100644index 000000000..c4ddc56e0--- /dev/null+++ b/tests/_fixtures/crypto-catalog/paramstyle.js@@ -0,0 +1,27 @@+// Fixture: the terser sibling style — `input`/`output` (aliases for+// inputSchema/outputSchema), a bare param map, string-valued output fields, and+// a multi-verb `methods` array. Exercises the assembler's aliasing + the+// OpenAPI generator's param-map and string-property coercion.+export default {+ slug: 'paramstyle',+ method: 'GET',+ methods: ['GET', 'POST'],+ path: '/api/crypto/paramstyle/{mint}',+ title: 'Param-Map Style',+ summary: 'Exercises the terse input/output descriptor form.',+ input: {+ mint: {+ type: 'string',+ required: true,+ in: 'path',+ description: 'Token mint',+ example: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ },+ verbose: { type: 'boolean', description: 'Include extra fields' },+ },+ output: {+ mint: 'string',+ ok: 'boolean — always true on success',+ },+ example: '/api/crypto/paramstyle/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+};diff --git a/tests/_fixtures/crypto-catalog/token.js b/tests/_fixtures/crypto-catalog/token.jsnew file mode 100644index 000000000..e438c3944--- /dev/null+++ b/tests/_fixtures/crypto-catalog/token.js@@ -0,0 +1,24 @@+// Fixture: a well-formed catalog entry exported as `default`.+export default {+ slug: 'token',+ method: 'get',+ path: '/api/crypto/token',+ title: 'Token Snapshot',+ summary: 'Current market state for a token in one call.',+ inputSchema: {+ type: 'object',+ properties: {+ address: { type: 'string', description: 'Mint / pair / contract address' },+ chain: { type: 'string', description: 'solana | base | …' },+ },+ required: ['address'],+ },+ outputSchema: {+ type: 'object',+ properties: {+ address: { type: 'string' },+ priceUsd: { type: ['number', 'null'] },+ },+ },+ example: { address: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', priceUsd: 0.0001 },+};diff --git a/tests/_fixtures/crypto-catalog/zz-dup-token.js b/tests/_fixtures/crypto-catalog/zz-dup-token.jsnew file mode 100644index 000000000..68ed77f65--- /dev/null+++ b/tests/_fixtures/crypto-catalog/zz-dup-token.js@@ -0,0 +1,9 @@+// Fixture: a second entry claiming the SAME route as token.js. The first one+// wins (sorted by filename); this duplicate is skipped so the catalog never+// advertises the same GET path twice.+export default {+ slug: 'token-dupe',+ method: 'GET',+ path: '/api/crypto/token',+ title: 'Duplicate of token',+};diff --git a/tests/api/3d-generate.test.js b/tests/api/3d-generate.test.jsnew file mode 100644index 000000000..63eea24e6--- /dev/null+++ b/tests/api/3d-generate.test.js@@ -0,0 +1,287 @@+// Tests for POST /api/3d/generate + GET /api/3d/generate?job=<id> — the free,+// keyless, agent-first text→3D front door that wraps the /api/forge draft lane.+//+// The rate limiter is mocked (switchable per test) and the network is stubbed via+// global fetch, so the suite runs fully offline while exercising the real handler,+// real originFromReq, real viewerUrl, and the real shape helpers against the REAL+// captured /api/forge draft-lane shapes (inline-done, queued, poll-done, failed).++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { Readable } from 'node:stream';++// Switchable free-lane quota — flip `freeOk` per test. mcp3dStatus (poll flood+// guard) always passes; it isn't the thing under test.+let freeOk = true;+let freeResult = { success: true, limit: 60, remaining: 59, reset: Date.now() + 3_600_000 };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcp3dGenerateFree: async () =>+ freeOk ? { success: true, limit: 60, remaining: 59, reset: Date.now() + 3_600_000 } : freeResult,+ mcp3dStatus: async () => ({ success: true, limit: 240, remaining: 239, reset: Date.now() + 60_000 }),+ },+ clientIp: () => '203.0.113.7',+}));++const ORIGINAL_FETCH = globalThis.fetch;+const ENV_KEYS = ['STUDIO_API_BASE', 'PUBLIC_APP_ORIGIN', 'APP_ORIGIN'];+const saved = {};++beforeEach(() => {+ freeOk = true;+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+});+afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ globalThis.fetch = ORIGINAL_FETCH;+ vi.restoreAllMocks();+});++function makeReq({ method = 'POST', url = '/api/3d/generate', body = null, host = 'three.ws' } = {}) {+ const raw = body == null ? '' : JSON.stringify(body);+ const stream = Readable.from(raw ? [Buffer.from(raw)] : []);+ stream.method = method;+ stream.url = url;+ stream.headers = { 'content-type': 'application/json', host };+ return stream;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) {+ this._h[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._h[k.toLowerCase()];+ },+ end(body) {+ this._body = body;+ this.writableEnded = true;+ },+ };+}++async function dispatch(req, res) {+ const mod = await import('../../api/3d/generate.js');+ await mod.default(req, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++function jsonResponse(obj, { status = 200 } = {}) {+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: { get: () => 'application/json' },+ json: async () => obj,+ text: async () => JSON.stringify(obj),+ };+}++// ── Real captured /api/forge draft-lane shapes (NVIDIA NIM TRELLIS) ───────────+const SUBMIT_DONE = {+ job_id: null,+ creation_id: 'a1b2c3d4-0000-4000-8000-000000000001',+ status: 'done',+ glb_url: 'https://cdn.three.ws/forge/anon/a1b2c3d4.glb',+ durable: true,+ backend: 'nvidia',+ tier: 'draft',+ path: 'image',+};+const SUBMIT_QUEUED = {+ job_id: 'f1.eyJwIjoibnZpZGlhIiwiayI6InRleHQiLCJ0IjoibmltLXRhc2stMTIzIn0.c2lnbmF0dXJl',+ creation_id: 'a1b2c3d4-0000-4000-8000-000000000002',+ status: 'queued',+};+const POLL_DONE = { job_id: SUBMIT_QUEUED.job_id, status: 'done', glb_url: 'https://cdn.three.ws/forge/anon/done.glb', durable: true };+const POLL_RUNNING = { job_id: SUBMIT_QUEUED.job_id, status: 'running' };+const POLL_FAILED = { job_id: SUBMIT_QUEUED.job_id, status: 'failed', error: 'the generator hit a snag' };++describe('shape helpers — lane boundary contract', () => {+ it('shapeSubmit maps the inline-done shape to a done payload with a viewer URL', async () => {+ const { shapeSubmit } = await import('../../api/3d/generate.js');+ const out = shapeSubmit(SUBMIT_DONE, 'https://three.ws');+ expect(out.status).toBe('done');+ expect(out.glbUrl).toBe(SUBMIT_DONE.glb_url);+ expect(out.viewerUrl).toBe('https://three.ws/viewer?src=' + encodeURIComponent(SUBMIT_DONE.glb_url));+ expect(out.format).toBe('glb');+ expect(out.tier).toBe('draft');+ expect(out.free).toBe(true);+ });++ it('shapeSubmit maps the queued shape to a pending payload with the poll URL', async () => {+ const { shapeSubmit } = await import('../../api/3d/generate.js');+ const out = shapeSubmit(SUBMIT_QUEUED, 'https://three.ws');+ expect(out.status).toBe('pending');+ expect(out.job).toBe(SUBMIT_QUEUED.job_id);+ expect(out.poll).toBe('/api/3d/generate?job=' + encodeURIComponent(SUBMIT_QUEUED.job_id));+ expect(out.free).toBe(true);+ });++ it('shapePoll maps done/running/failed forge poll shapes', async () => {+ const { shapePoll } = await import('../../api/3d/generate.js');+ const done = shapePoll(POLL_DONE, 'https://three.ws', SUBMIT_QUEUED.job_id);+ expect(done.status).toBe('done');+ expect(done.glbUrl).toBe(POLL_DONE.glb_url);+ expect(done.viewerUrl).toContain('/viewer?src=');++ const pending = shapePoll(POLL_RUNNING, 'https://three.ws', SUBMIT_QUEUED.job_id);+ expect(pending.status).toBe('pending');+ expect(pending.poll).toContain('/api/3d/generate?job=');++ const err = shapePoll(POLL_FAILED, 'https://three.ws', SUBMIT_QUEUED.job_id);+ expect(err.status).toBe('error');+ expect(err.error).toBe(POLL_FAILED.error);+ expect(err.free).toBe(true);+ });+});++describe('POST /api/3d/generate — validation', () => {+ it('rejects an empty prompt with 400', async () => {+ const { res, body } = await dispatch(makeReq({ body: { prompt: '' } }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('invalid_prompt');+ });++ it('rejects a too-short prompt with 400', async () => {+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'ab' } }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('invalid_prompt');+ });++ it('rejects an oversized prompt with 400', async () => {+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'x'.repeat(1001) } }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('invalid_prompt');+ });++ it('rejects an unsupported format with 400', async () => {+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine', format: 'obj' } }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('unsupported_format');+ });+});++describe('POST /api/3d/generate — rate limit', () => {+ it('returns 429 with an upgrade pointer when the free lane cap is hit', async () => {+ freeOk = false;+ freeResult = { success: false, limit: 60, remaining: 0, reset: Date.now() + 600_000 };+ globalThis.fetch = vi.fn(async () => {+ throw new Error('lane should not be called when rate-limited');+ });+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine' } }), makeRes());+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ expect(res.getHeader('retry-after')).toBeTruthy();+ expect(body.upgrade.forgePro).toBe('/api/x402/forge');+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });+});++describe('POST /api/3d/generate — response contract', () => {+ it('returns { status: done, glbUrl, viewerUrl } when the lane finishes inline', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse(SUBMIT_DONE));+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine' } }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.status).toBe('done');+ expect(body.glbUrl).toBe(SUBMIT_DONE.glb_url);+ expect(body.viewerUrl).toBe('https://three.ws/viewer?src=' + encodeURIComponent(SUBMIT_DONE.glb_url));+ // The lane was submitted with the pinned free NVIDIA draft params.+ const [, opts] = globalThis.fetch.mock.calls[0];+ expect(JSON.parse(opts.body)).toMatchObject({ prompt: 'a small ceramic robot figurine', backend: 'nvidia', path: 'image', tier: 'draft' });+ });++ it('returns { status: pending, job, poll } when the lane queues the job', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse(SUBMIT_QUEUED));+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine' } }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.status).toBe('pending');+ expect(body.job).toBe(SUBMIT_QUEUED.job_id);+ expect(body.poll).toBe('/api/3d/generate?job=' + encodeURIComponent(SUBMIT_QUEUED.job_id));+ });++ it('surfaces a 503 not_configured when the lane is unconfigured', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse({ message: '3D generation is not configured' }, { status: 503 }));+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine' } }), makeRes());+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('not_configured');+ });++ it('maps an upstream 429 (GPU lane saturated) to 429 + retry-after', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse({ message: 'busy', retry_after: 12 }, { status: 429 }));+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine' } }), makeRes());+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ expect(res.getHeader('retry-after')).toBe('12');+ });+});++describe('GET /api/3d/generate?job= — poll lifecycle', () => {+ it('400s when no job param is present', async () => {+ const { res, body } = await dispatch(makeReq({ method: 'GET', url: '/api/3d/generate' }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('missing_job');+ });++ it('400s on a malformed job handle', async () => {+ const { res, body } = await dispatch(makeReq({ method: 'GET', url: '/api/3d/generate?job=%20%20' }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('invalid_job');+ });++ it('returns pending while the job runs', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse(POLL_RUNNING));+ const { res, body } = await dispatch(makeReq({ method: 'GET', url: `/api/3d/generate?job=${SUBMIT_QUEUED.job_id}` }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.status).toBe('pending');+ expect(body.poll).toContain('/api/3d/generate?job=');+ });++ it('returns done with glbUrl + viewerUrl when the job finishes', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse(POLL_DONE));+ const { res, body } = await dispatch(makeReq({ method: 'GET', url: `/api/3d/generate?job=${SUBMIT_QUEUED.job_id}` }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.status).toBe('done');+ expect(body.glbUrl).toBe(POLL_DONE.glb_url);+ expect(body.viewerUrl).toContain('/viewer?src=');+ });++ it('returns status:error (no charge) when the job failed upstream', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse(POLL_FAILED));+ const { res, body } = await dispatch(makeReq({ method: 'GET', url: `/api/3d/generate?job=${SUBMIT_QUEUED.job_id}` }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.status).toBe('error');+ expect(body.error).toBe(POLL_FAILED.error);+ expect(body.free).toBe(true);+ });++ it('treats a transient poll network error as pending', async () => {+ globalThis.fetch = vi.fn(async () => {+ throw new Error('network blip');+ });+ const { res, body } = await dispatch(makeReq({ method: 'GET', url: `/api/3d/generate?job=${SUBMIT_QUEUED.job_id}` }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.status).toBe('pending');+ });+});++describe('catalog entry', () => {+ it('exports a well-formed entry the /api/3d index can merge', async () => {+ const entry = (await import('../../api/_lib/3d-catalog/generate.js')).default;+ expect(entry.slug).toBe('generate');+ expect(entry.method).toBe('POST');+ expect(entry.path).toBe('/api/3d/generate');+ expect(entry.free).toBe(true);+ expect(entry.inputSchema.required).toContain('prompt');+ expect(entry.example.request.path).toBe('/api/3d/generate');+ });+});diff --git a/tests/api/3d-inspect.test.js b/tests/api/3d-inspect.test.jsnew file mode 100644index 000000000..274d24933--- /dev/null+++ b/tests/api/3d-inspect.test.js@@ -0,0 +1,222 @@+// GET/POST /api/3d/inspect — the free, keyless glTF/GLB inspection + validation+// endpoint. The rate limiter is mocked (switchable per test) so the suite runs+// fully offline; the real handler, real inspectModel core, and the real Khronos+// glTF-Validator all run against a real bundled GLB uploaded as the request body+// (no network). URL-fetch paths are covered by asserting the input-validation+// contract (bad/missing input never 500s).++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Readable } from 'node:stream';+import { readFileSync, existsSync } from 'node:fs';+import { resolve } from 'node:path';+import { inspectModel } from '../../src/gltf-inspect.js';+import { buildStats, buildRecommendations } from '../../api/3d/inspect.js';++// Switchable per-IP quota — flip `rlOk` per test.+let rlOk = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ apiIp: async () =>+ rlOk+ ? { success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 }+ : { success: false, limit: 60, remaining: 0, reset: Date.now() + 60_000 },+ },+ clientIp: () => '203.0.113.7',+}));++beforeEach(() => {+ rlOk = true;+});++const avatar = (name) => resolve(process.cwd(), 'public/avatars', name);+const REAL_GLB = ['cesium-man.glb', 'fox.glb', 'mannequin.glb'].map(avatar).find(existsSync);++function makeReq({ method = 'GET', url = '/api/3d/inspect', headers = {}, body = null } = {}) {+ const chunks = body == null ? [] : [Buffer.isBuffer(body) ? body : Buffer.from(body)];+ const stream = Readable.from(chunks);+ stream.method = method;+ stream.url = url;+ stream.headers = { host: 'three.ws', ...headers };+ // Parse ?query= like Vercel does, so the handler's req.query works.+ const qIdx = url.indexOf('?');+ stream.query = qIdx >= 0 ? Object.fromEntries(new URLSearchParams(url.slice(qIdx + 1))) : {};+ return stream;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) {+ this._h[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._h[k.toLowerCase()];+ },+ end(body) {+ this._body = body;+ this.writableEnded = true;+ },+ };+}++async function dispatch(req, res) {+ const mod = await import('../../api/3d/inspect.js');+ await mod.default(req, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++describe('buildStats / buildRecommendations (pure helpers)', () => {+ it.runIf(REAL_GLB)('extracts real stats from a bundled GLB', async () => {+ const info = await inspectModel(new Uint8Array(readFileSync(REAL_GLB)));+ const stats = buildStats(info);+ expect(stats.vertices).toBeGreaterThan(0);+ expect(stats.triangles).toBeGreaterThan(0);+ expect(stats.materials).toBeGreaterThanOrEqual(0);+ expect(Array.isArray(stats.extensions)).toBe(true);+ expect(['glb', 'gltf']).toContain(stats.container);+ });++ it('orders recommendations by severity (critical → warn → info)', () => {+ // A synthetic heavy model that trips multiple severities: an oversized 8K PNG+ // texture (warn), a huge non-indexed vertex buffer (info: draco/meshopt/+ // non_indexed), and a 30 MB file size (warn).+ const info = {+ fileSize: 30 * 1024 * 1024,+ container: 'glb',+ generator: 'test',+ extensionsUsed: [],+ extensionsRequired: [],+ counts: {+ scenes: 1,+ nodes: 1,+ meshes: 1,+ materials: 1,+ textures: 1,+ animations: 0,+ skins: 0,+ totalJoints: 0,+ totalVertices: 200_000,+ totalTriangles: 66_000,+ indexedPrimitives: 0,+ nonIndexedPrimitives: 1,+ },+ primitiveModes: [4],+ textures: [{ name: 'big', mimeType: 'image/png', width: 8192, height: 8192, byteSize: 30 * 1024 * 1024 }],+ materials: [{ name: 'm', alphaMode: 'OPAQUE' }],+ };+ const recs = buildRecommendations(info);+ expect(recs.length).toBeGreaterThan(1);+ // Each carries the { severity, issue, fix } contract.+ for (const r of recs) {+ expect(r).toHaveProperty('severity');+ expect(typeof r.issue).toBe('string');+ expect(typeof r.fix).toBe('string');+ expect(r.fix.length).toBeGreaterThan(0);+ }+ // Non-decreasing severity rank => sorted most-severe-first.+ const rank = { critical: 0, warn: 1, info: 2 };+ const ranks = recs.map((r) => rank[r.severity] ?? 3);+ for (let i = 1; i < ranks.length; i++) expect(ranks[i]).toBeGreaterThanOrEqual(ranks[i - 1]);+ });++ it('always returns at least one recommendation (the "ok" fallback)', () => {+ const info = {+ fileSize: 1000,+ container: 'glb',+ generator: null,+ extensionsUsed: [],+ extensionsRequired: [],+ counts: {+ scenes: 1, nodes: 1, meshes: 1, materials: 1, textures: 0, animations: 0, skins: 0,+ totalJoints: 0, totalVertices: 100, totalTriangles: 33, indexedPrimitives: 1, nonIndexedPrimitives: 0,+ },+ primitiveModes: [4],+ textures: [],+ materials: [{ name: 'm', alphaMode: 'OPAQUE' }],+ };+ const recs = buildRecommendations(info);+ expect(recs.length).toBeGreaterThanOrEqual(1);+ });+});++describe('POST /api/3d/inspect — raw upload (real GLB, offline)', () => {+ it.runIf(REAL_GLB)('inspects an uploaded GLB and returns the full contract', async () => {+ const bytes = readFileSync(REAL_GLB);+ const { res, body } = await dispatch(+ makeReq({ method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: bytes }),+ makeRes(),+ );+ expect(res.statusCode).toBe(200);+ expect(body.url).toBeNull(); // raw upload has no source URL+ expect(typeof body.valid).toBe('boolean');+ expect(body.sizeBytes).toBe(bytes.byteLength);+ expect(body.stats.vertices).toBeGreaterThan(0);+ expect(body.stats.triangles).toBeGreaterThan(0);+ expect(Array.isArray(body.stats.extensions)).toBe(true);+ expect(Array.isArray(body.recommendations)).toBe(true);+ expect(body.recommendations.length).toBeGreaterThanOrEqual(1);+ expect(typeof body.ts).toBe('string');+ expect(res.getHeader('cache-control')).toBe('no-store');+ });++ it('rejects an empty upload with 400 (never 500)', async () => {+ const { res, body } = await dispatch(+ makeReq({ method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: null }),+ makeRes(),+ );+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('empty_body');+ });++ it('rejects non-model bytes with 400 invalid_model (never 500)', async () => {+ const { res, body } = await dispatch(+ makeReq({+ method: 'POST',+ headers: { 'content-type': 'application/octet-stream' },+ body: Buffer.from('this is definitely not a glb file'),+ }),+ makeRes(),+ );+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('invalid_model');+ });+});++describe('input validation', () => {+ it('GET with no url → 400 missing_url', async () => {+ const { res, body } = await dispatch(makeReq({ method: 'GET', url: '/api/3d/inspect' }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('missing_url');+ });++ it('POST JSON with no url → 400 missing_url', async () => {+ const { res, body } = await dispatch(+ makeReq({+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ noturl: 1 }),+ }),+ makeRes(),+ );+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('missing_url');+ });++ it('unsupported method → 405', async () => {+ const { res } = await dispatch(makeReq({ method: 'DELETE' }), makeRes());+ expect(res.statusCode).toBe(405);+ });++ it('rate-limited → 429', async () => {+ rlOk = false;+ const { res, body } = await dispatch(+ makeReq({ method: 'GET', url: '/api/3d/inspect?url=https://three.ws/x.glb' }),+ makeRes(),+ );+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ });+});diff --git a/tests/api/crypto-symbol.test.js b/tests/api/crypto-symbol.test.jsnew file mode 100644index 000000000..7f35b7d11--- /dev/null+++ b/tests/api/crypto-symbol.test.js@@ -0,0 +1,216 @@+// Tests for the free symbol-availability check (api/crypto/symbol.js).+//+// The core collision logic (checkSymbols) takes an injected `fetchImpl`, so we+// exercise exact vs fuzzy matching, available/taken counts, and graceful+// degradation against real-shaped DexScreener search payloads — no live network.+// Handler-level tests drive the default export with mock req/res to prove cap+// enforcement, empty-list handling, and the happy-path response shape.+//+// Fixtures use made-up tickers + synthetic mints, except $THREE (three.ws's own+// coin, CA FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump).++import { describe, it, expect, vi, afterEach } from 'vitest';+import { Readable } from 'node:stream';+import handler, { checkSymbols, symbolSimilarity, SYMBOL_CAP } from '../../api/crypto/symbol.js';++// ── Fixtures: trimmed DexScreener /latest/dex/search shapes, keyed by query ───+function pair(symbol, name, mint, { chainId = 'solana', liq = 12000 } = {}) {+ return {+ chainId,+ dexId: 'pumpswap',+ baseToken: { address: mint, name, symbol },+ quoteToken: { address: 'So11111111111111111111111111111111111111112', symbol: 'SOL' },+ liquidity: { usd: liq },+ };+}++const FIXTURES = {+ // exact collision — same ticker already live+ three: [pair('three', 'three.ws', 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')],+ // fuzzy only — "MOONZ" vs "MOONS" (trigram Jaccard ≈ 0.5) + an unrelated token+ moonz: [+ pair('MOONS', 'Moons', 'MoonsSynthetic1111111111111111111111111111'),+ pair('LAMBO', 'Lambo', 'LamboSynthetic1111111111111111111111111111'),+ ],+ // clean — nothing similar comes back+ blergz: [pair('WIDGET', 'Widget', 'WidgetSynthetic11111111111111111111111111')],+ // two pairs for the same mint at different liquidity → dedupe keeps richest+ zorp: [+ pair('ZORP', 'Zorp', 'ZorpSynthetic11111111111111111111111111111', { liq: 500 }),+ pair('ZORP', 'Zorp', 'ZorpSynthetic11111111111111111111111111111', { liq: 90000 }),+ ],+ // lives only on base — used to prove the chain filter+ crosschain: [pair('CROSSCHAIN', 'Cross', 'CrossSynthetic111111111111111111111111111', { chainId: 'base' })],+};++function fakeFetch(url) {+ const q = (new URL(url).searchParams.get('q') || '').toLowerCase();+ const pairs = FIXTURES[q] ?? [];+ return Promise.resolve({ ok: true, status: 200, json: async () => ({ schemaVersion: '1.0.0', pairs }) });+}++function downFetch() {+ return Promise.resolve({ ok: false, status: 502, json: async () => ({}) });+}++// ── req/res mocks ─────────────────────────────────────────────────────────+function makeReq({ method = 'GET', url = '/api/crypto/symbol', headers = {}, body = null } = {}) {+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ base.method = method;+ base.url = url;+ base.headers = { host: 'localhost', ...(body ? { 'content-type': 'application/json' } : {}), ...headers };+ base.socket = { remoteAddress: '203.0.113.7' };+ return base;+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(chunk) {+ if (chunk !== undefined) this.body += chunk;+ this.writableEnded = true;+ this.headersSent = true;+ },+ };+}++async function invoke(reqOpts) {+ const req = makeReq(reqOpts);+ const res = makeRes();+ await handler(req, res);+ return { res, status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };+}++afterEach(() => vi.unstubAllGlobals());++// ── Trigram similarity ─────────────────────────────────────────────────────+describe('symbolSimilarity', () => {+ it('scores identical tickers 1.0 (case-insensitive)', () => {+ expect(symbolSimilarity('MOON', 'moon')).toBe(1);+ });+ it('scores look-alikes above the fuzzy floor', () => {+ expect(symbolSimilarity('MOONZ', 'MOONS')).toBeGreaterThanOrEqual(0.4);+ });+ it('scores unrelated tickers near zero', () => {+ expect(symbolSimilarity('MOON', 'LAMBO')).toBeLessThan(0.4);+ });+ it('returns 0 for empty input', () => {+ expect(symbolSimilarity('', 'MOON')).toBe(0);+ });+});++// ── Core collision logic ───────────────────────────────────────────────────+describe('checkSymbols', () => {+ it('flags an exact collision as taken', async () => {+ const out = await checkSymbols({ symbols: ['THREE'], fetchImpl: fakeFetch });+ const r = out.results[0];+ expect(r.available).toBe(false);+ expect(r.exactCollisions).toHaveLength(1);+ expect(r.exactCollisions[0].mint).toBe('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');+ expect(out.takenCount).toBe(1);+ expect(out.availableCount).toBe(0);+ });++ it('reports a fuzzy look-alike but leaves the symbol available', async () => {+ const out = await checkSymbols({ symbols: ['MOONZ'], fetchImpl: fakeFetch });+ const r = out.results[0];+ expect(r.available).toBe(true);+ expect(r.exactCollisions).toHaveLength(0);+ expect(r.fuzzyCollisions.map((c) => c.symbol)).toContain('MOONS');+ // The unrelated LAMBO token is below the floor and excluded.+ expect(r.fuzzyCollisions.map((c) => c.symbol)).not.toContain('LAMBO');+ expect(r.fuzzyCollisions[0].similarity).toBeGreaterThanOrEqual(0.4);+ });++ it('returns available with no collisions for a clean ticker', async () => {+ const out = await checkSymbols({ symbols: ['BLERGZ'], fetchImpl: fakeFetch });+ expect(out.results[0]).toMatchObject({ available: true, exactCollisions: [], fuzzyCollisions: [] });+ expect(out.availableCount).toBe(1);+ });++ it('computes available/taken counts across a mixed batch', async () => {+ const out = await checkSymbols({ symbols: ['THREE', 'MOONZ', 'BLERGZ'], fetchImpl: fakeFetch });+ expect(out.availableCount).toBe(2);+ expect(out.takenCount).toBe(1);+ expect(out.results).toHaveLength(3);+ });++ it('de-duplicates the input case-insensitively', async () => {+ const out = await checkSymbols({ symbols: ['THREE', 'three', ' $three '], fetchImpl: fakeFetch });+ expect(out.results).toHaveLength(1);+ });++ it('dedupes multiple pairs for one mint (keeps the record)', async () => {+ const out = await checkSymbols({ symbols: ['ZORP'], fetchImpl: fakeFetch });+ expect(out.results[0].exactCollisions).toHaveLength(1);+ });++ it('filters collisions by chain when requested', async () => {+ const onBase = await checkSymbols({ symbols: ['CROSSCHAIN'], chain: 'base', fetchImpl: fakeFetch });+ expect(onBase.results[0].available).toBe(false);+ const onSolana = await checkSymbols({ symbols: ['CROSSCHAIN'], chain: 'solana', fetchImpl: fakeFetch });+ expect(onSolana.results[0].available).toBe(true);+ });++ it('degrades to 200 with a note when the registry is down — never a false green light', async () => {+ const out = await checkSymbols({ symbols: ['THREE'], fetchImpl: downFetch });+ const r = out.results[0];+ expect(r.available).toBeNull();+ expect(r.degraded).toBe(true);+ expect(r.note).toMatch(/unavailable/i);+ expect(out.degraded).toBe(true);+ // Unverifiable symbols count as neither available nor taken.+ expect(out.availableCount).toBe(0);+ expect(out.takenCount).toBe(0);+ });+});++// ── Handler: validation + happy path ───────────────────────────────────────+describe('GET/POST /api/crypto/symbol', () => {+ it('400s an empty symbol list with the cap and an example', async () => {+ const { status, body } = await invoke({ url: '/api/crypto/symbol' });+ expect(status).toBe(400);+ expect(body.error).toBe('missing_symbols');+ expect(body.cap).toBe(SYMBOL_CAP);+ expect(body.example.symbols).toBeInstanceOf(Array);+ });++ it('400s an oversized list with the cap', async () => {+ const symbols = Array.from({ length: SYMBOL_CAP + 1 }, (_, i) => `SYM${i}`);+ const { status, body } = await invoke({ method: 'POST', body: { symbols } });+ expect(status).toBe(400);+ expect(body.error).toBe('too_many_symbols');+ expect(body.cap).toBe(SYMBOL_CAP);+ });++ it('serves a real GET batch with rate-limit headers', async () => {+ vi.stubGlobal('fetch', fakeFetch);+ const { status, body, res } = await invoke({ url: '/api/crypto/symbol?symbols=THREE,MOONZ,BLERGZ' });+ expect(status).toBe(200);+ expect(body.availableCount).toBe(2);+ expect(body.takenCount).toBe(1);+ expect(typeof body.ts).toBe('string');+ expect(res.headers['ratelimit-limit']).toBeDefined();+ });++ it('accepts a POST body with a chain filter', async () => {+ vi.stubGlobal('fetch', fakeFetch);+ const { status, body } = await invoke({+ method: 'POST',+ body: { symbols: ['THREE'], chain: 'solana' },+ });+ expect(status).toBe(200);+ expect(body.chain).toBe('solana');+ expect(body.results[0].available).toBe(false);+ });+});diff --git a/tests/api/crypto-wallet.test.js b/tests/api/crypto-wallet.test.jsnew file mode 100644index 000000000..b712ec635--- /dev/null+++ b/tests/api/crypto-wallet.test.js@@ -0,0 +1,208 @@+// GET /api/crypto/wallet — free wallet-portfolio endpoint.+//+// The balance layer (api/_lib/balances.js) has its own live-RPC + circuit-breaker+// tests; here we pin the ENDPOINT contract: input validation, the mapping from the+// rich internal balance shape to the stable public schema, USD valuation with a+// missing price, the keyless-RPC source label, the empty wallet, truncation, and+// every error state (bad input, unsupported chain, EVM-not-configured, upstream+// down). getBalances + heliusHealth are mocked so no network is touched; the pure+// mapping is what we assert. Fixtures use $THREE (CA in 00-CONTEXT) and a synthetic+// mint — never a real third-party mint.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const getBalancesMock = vi.fn();+const heliusHealthMock = vi.fn(() => ({ configured: false, available: true, degraded: false }));++vi.mock('../../api/_lib/balances.js', () => ({+ getBalances: (...a) => getBalancesMock(...a),+ heliusHealth: () => heliusHealthMock(),+ // Faithful reimplementation of the real reducer (native + Σ token usd).+ walletUsdTotal: (b) =>+ (b?.native?.usd ?? 0) + (b?.tokens ?? []).reduce((s, t) => s + (t.usd ?? 0), 0),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ cryptoDataIp: vi.fn(async () => ({ success: true })),+ cryptoDataGlobal: vi.fn(async () => ({ success: true })),+ },+ clientIp: () => '127.0.0.1',+}));++const { default: handler } = await import('../../api/crypto/wallet.js');+const { limits } = await import('../../api/_lib/rate-limit.js');++const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const SYNTH = 'THREEsynthetic1111111111111111111111111111';+const WALLET = 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk';++function makeReq(url) {+ return { url, method: 'GET', headers: { host: 'x' } };+}+function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; },+ };+}+async function call(url) {+ const res = makeRes();+ await handler(makeReq(url), res);+ let body = null;+ try { body = JSON.parse(res._body); } catch {}+ return { res, body };+}++beforeEach(() => {+ getBalancesMock.mockReset();+ heliusHealthMock.mockReturnValue({ configured: false, available: true, degraded: false });+ limits.cryptoDataIp.mockResolvedValue({ success: true });+ limits.cryptoDataGlobal.mockResolvedValue({ success: true });+});++describe('GET /api/crypto/wallet — validation', () => {+ it('400s with an example when address is missing', async () => {+ const { res, body } = await call('/api/crypto/wallet');+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('missing_address');+ expect(body.example).toContain('/api/crypto/wallet?address=');+ expect(getBalancesMock).not.toHaveBeenCalled();+ });++ it('400s on a syntactically invalid Solana address before any upstream call', async () => {+ const { res, body } = await call('/api/crypto/wallet?address=not-a-real-address&chain=solana');+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('invalid_address');+ expect(getBalancesMock).not.toHaveBeenCalled();+ });++ it('400s on an unsupported chain', async () => {+ const { res, body } = await call(`/api/crypto/wallet?address=${WALLET}&chain=dogechain`);+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('unsupported_chain');+ expect(body.supported).toContain('solana');+ });+});++describe('GET /api/crypto/wallet — balance parsing + USD valuation', () => {+ it('maps native + tokens and prices them, unpriced tokens report usd:null', async () => {+ getBalancesMock.mockResolvedValueOnce({+ chain: 'solana',+ address: WALLET,+ native: { symbol: 'SOL', name: 'Solana', amount: 2.5, price: 150, usd: 375 },+ tokens: [+ { mint: THREE, symbol: 'THREE', name: 'three.ws', decimals: 6, amount: 1000, price: 0.0016, usd: 1.6, logo: 'https://img/three.png' },+ // Unpriced: Jupiter/pump.fun couldn't route it → price 0. Still listed.+ { mint: SYNTH, symbol: 'SYNTH', name: 'Synthetic', decimals: 6, amount: 500, price: 0, usd: 0, logo: null },+ ],+ });++ const { res, body } = await call(`/api/crypto/wallet?address=${WALLET}&chain=solana`);+ expect(res.statusCode).toBe(200);+ expect(body.address).toBe(WALLET);+ expect(body.chain).toBe('solana');++ expect(body.native).toEqual({ symbol: 'SOL', amount: 2.5, usd: 375 });++ expect(body.tokens).toHaveLength(2);+ const three = body.tokens.find((t) => t.mint === THREE);+ expect(three).toMatchObject({ mint: THREE, symbol: 'THREE', amount: 1000, usd: 1.6 });++ const synth = body.tokens.find((t) => t.mint === SYNTH);+ expect(synth.usd).toBeNull(); // unpriced → null, never a fake 0+ expect(synth.amount).toBe(500); // ...but still listed with its amount++ // totalUsd = native 375 + THREE 1.6 (+ unpriced 0)+ expect(body.totalUsd).toBe(376.6);+ expect(body.tokenCount).toBe(2);+ expect(body.truncated).toBe(false);+ expect(typeof body.ts).toBe('string');+ });++ it('keyless path (no Helius key) reports solana-rpc + jupiter-lite as sources', async () => {+ heliusHealthMock.mockReturnValue({ configured: false, available: true, degraded: false });+ getBalancesMock.mockResolvedValueOnce({+ chain: 'solana', address: WALLET,+ native: { symbol: 'SOL', amount: 1, price: 150, usd: 150 }, tokens: [],+ });+ const { body } = await call(`/api/crypto/wallet?address=${WALLET}`);+ expect(body.sources).toEqual(['solana-rpc', 'jupiter-lite']);+ });++ it('uses helius-das as the source when a key is configured and healthy', async () => {+ heliusHealthMock.mockReturnValue({ configured: true, available: true, degraded: false });+ getBalancesMock.mockResolvedValueOnce({+ chain: 'solana', address: WALLET,+ native: { symbol: 'SOL', amount: 1, price: 150, usd: 150 }, tokens: [],+ });+ const { body } = await call(`/api/crypto/wallet?address=${WALLET}`);+ expect(body.sources).toEqual(['helius-das', 'jupiter-lite']);+ });++ it('empty wallet → 200 with zeros and an empty token array', async () => {+ getBalancesMock.mockResolvedValueOnce({+ chain: 'solana', address: WALLET,+ native: { symbol: 'SOL', amount: 0, price: 150, usd: 0 }, tokens: [],+ });+ const { res, body } = await call(`/api/crypto/wallet?address=${WALLET}`);+ expect(res.statusCode).toBe(200);+ expect(body.native).toEqual({ symbol: 'SOL', amount: 0, usd: 0 });+ expect(body.tokens).toEqual([]);+ expect(body.totalUsd).toBe(0);+ expect(body.tokenCount).toBe(0);+ expect(body.truncated).toBe(false);+ });++ it('caps the token list at 200 and flags truncated, keeping tokenCount honest', async () => {+ const many = Array.from({ length: 250 }, (_, i) => ({+ mint: `${SYNTH.slice(0, 40)}${String(i).padStart(2, '0')}`,+ symbol: `T${i}`, name: `Token ${i}`, decimals: 6,+ amount: 250 - i, price: 1, usd: 250 - i, logo: null,+ }));+ getBalancesMock.mockResolvedValueOnce({+ chain: 'solana', address: WALLET,+ native: { symbol: 'SOL', amount: 0, price: 150, usd: 0 }, tokens: many,+ });+ const { body } = await call(`/api/crypto/wallet?address=${WALLET}`);+ expect(body.tokens).toHaveLength(200);+ expect(body.truncated).toBe(true);+ expect(body.tokenCount).toBe(250); // full count preserved even when the list is capped+ });++ it('passes a stale flag through when the balance layer served last-known-good', async () => {+ getBalancesMock.mockResolvedValueOnce({+ chain: 'solana', address: WALLET, stale: true,+ native: { symbol: 'SOL', amount: 1, price: 150, usd: 150 }, tokens: [],+ });+ const { body } = await call(`/api/crypto/wallet?address=${WALLET}`);+ expect(body.stale).toBe(true);+ });+});++describe('GET /api/crypto/wallet — error states', () => {+ it('429s when the rate limiter rejects', async () => {+ limits.cryptoDataIp.mockResolvedValueOnce({ success: false });+ const { res, body } = await call(`/api/crypto/wallet?address=${WALLET}`);+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ });++ it('503 not_configured for an EVM chain with no provider key', async () => {+ getBalancesMock.mockRejectedValueOnce(Object.assign(new Error('not_configured: ALCHEMY_API_KEY'), { code: 'not_configured' }));+ const { res, body } = await call('/api/crypto/wallet?address=0x1111111111111111111111111111111111111111&chain=ethereum');+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('not_configured');+ });++ it('503 retryable when every upstream RPC path fails', async () => {+ getBalancesMock.mockRejectedValueOnce(Object.assign(new Error('upstream 502'), { status: 502 }));+ const { res, body } = await call(`/api/crypto/wallet?address=${WALLET}`);+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('upstream_unavailable');+ expect(res.getHeader('retry-after')).toBe('15');+ });+});diff --git a/tests/api/v1-ai-image.test.js b/tests/api/v1-ai-image.test.jsnew file mode 100644index 000000000..1d5c14934--- /dev/null+++ b/tests/api/v1-ai-image.test.js@@ -0,0 +1,257 @@+/**+ * Tests for POST /api/v1/ai/image (api/v1/ai/image.js).+ *+ * The endpoint is a free-quota funnel over the platform's text→image lanes: the+ * first N images/day per IP are free (payment bypassed), then callers fall+ * through to the x402 pay-per-image lane. What's tested here is the endpoint's+ * own logic — validation, the free→402 fall-through, the honest no-lane 503, and+ * safety-refusal mapping — with the payment rail and the text→image lane stubbed+ * at their module boundaries (each has its own suite). The provider boundaries+ * (lane success shape, Vertex refusal shape) use the REAL captured shapes from+ * api/_mcp3d/text-to-image.js and api/_mcp3d/vertex-imagen.js.+ */++import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';++beforeAll(() => {+ Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ X402_ADVERTISE_BASE: 'true',+ });+});++// Stub payment verify/settle — the 402 challenge, buildRequirements, and bazaar+// schema stay real; only the facilitator round-trips are faked.+vi.mock('../../api/_lib/x402-spec.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ verifyPayment: vi.fn(async () => ({ ok: true, requirement: { network: 'base', amount: '20000' }, payer: '0xpayer' })),+ settlePayment: vi.fn(async () => ({ settled: true, transaction: '0xtx', network: 'base' })),+ encodePaymentResponseHeader: vi.fn(() => 'stub-payment-response'),+ };+});++// Deterministic client IP; keep the real limiters (permissive in-memory in test).+vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {+ const actual = await importActual();+ return { ...actual, clientIp: () => '203.0.113.9' };+});++// Text→image lane — controlled per test. Default: a real NIM FLUX success shape+// (see nimFluxImage return, api/_mcp3d/text-to-image.js).+const laneState = vi.hoisted(() => ({+ impl: async () => ({ imageUrl: 'https://cdn.example/forge/refs/abc.jpg', model: 'black-forest-labs/flux.1-schnell' }),+}));+vi.mock('../../api/_mcp3d/text-to-image.js', () => ({+ textToImage: (...args) => laneState.impl(...args),+}));++// Free-quota module — controlled per test.+const quotaState = vi.hoisted(() => ({ allowed: true, consumed: 0 }));+vi.mock('../../api/_lib/ai-image-quota.js', () => ({+ freePerDay: () => 5,+ peekFreeQuota: vi.fn(async () => ({+ allowed: quotaState.allowed,+ used: quotaState.allowed ? 0 : 5,+ limit: 5,+ remaining: quotaState.allowed ? 5 : 0,+ resetAt: '2026-07-08T00:00:00.000Z',+ })),+ consumeFreeQuota: vi.fn(async () => {+ quotaState.consumed += 1;+ return { used: quotaState.consumed, limit: 5, remaining: 5 - quotaState.consumed, resetAt: '2026-07-08T00:00:00.000Z' };+ }),+ __resetFreeQuota: () => {},+}));++const { default: handler } = await import('../../api/v1/ai/image.js');+const { CATALOG } = await import('../../api/v1/_catalog.js');++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(name, value) { this.headers[String(name).toLowerCase()] = value; },+ getHeader(name) { return this.headers[String(name).toLowerCase()]; },+ end(body) { this.body = body ?? null; },+ };+}++function makeReq({ method = 'POST', url = '/api/v1/ai/image', headers = {}, body = null } = {}) {+ const payload = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);+ return {+ method,+ url,+ headers: { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9', ...headers },+ async *[Symbol.asyncIterator]() { if (payload) yield Buffer.from(payload, 'utf8'); },+ };+}++const LANE_ENV = ['NVIDIA_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON', 'REPLICATE_API_TOKEN', 'VERTEX_IMAGEN_ENABLED', 'X402_PRICE_AI_IMAGE'];+const savedEnv = {};+beforeEach(() => {+ for (const k of LANE_ENV) savedEnv[k] = process.env[k];+ quotaState.allowed = true;+ quotaState.consumed = 0;+ laneState.impl = async () => ({ imageUrl: 'https://cdn.example/forge/refs/abc.jpg', model: 'black-forest-labs/flux.1-schnell' });+ // A configured lane by default so the happy paths run.+ process.env.NVIDIA_API_KEY = 'nvapi-test';+});+afterEach(() => {+ for (const k of LANE_ENV) {+ if (savedEnv[k] === undefined) delete process.env[k];+ else process.env[k] = savedEnv[k];+ }+ vi.restoreAllMocks();+});++describe('catalog registration', () => {+ it('registers v1.ai.image as a public POST route', () => {+ const entry = CATALOG.find((e) => e.id === 'v1.ai.image');+ expect(entry).toBeTruthy();+ expect(entry.method).toBe('POST');+ expect(entry.path).toBe('/api/v1/ai/image');+ expect(entry.auth).toBe('public');+ });+});++describe('validation (free path, fresh IP)', () => {+ it('rejects an empty prompt with 400 and no charge', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { prompt: '' } }), res);+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.body).error).toBe('invalid_prompt');+ });++ it('rejects an oversized prompt with 400', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { prompt: 'x'.repeat(2001) } }), res);+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.body).error).toBe('prompt_too_long');+ });++ it('rejects an unsupported aspect_ratio with 400', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { prompt: 'a brass owl', aspect_ratio: '5:1' } }), res);+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.body).error).toBe('invalid_aspect_ratio');+ });++ it('rejects a non-integer seed with 400', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { prompt: 'a brass owl', seed: 1.5 } }), res);+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.body).error).toBe('invalid_seed');+ });++ it('does not spend a quota slot on a validation error', async () => {+ const { consumeFreeQuota } = await import('../../api/_lib/ai-image-quota.js');+ const res = makeRes();+ await handler(makeReq({ body: { prompt: '' } }), res);+ expect(consumeFreeQuota).not.toHaveBeenCalled();+ });+});++describe('free path success', () => {+ it('serves an image free, shapes { url, provider, width, height }, and spends a slot', async () => {+ const { consumeFreeQuota } = await import('../../api/_lib/ai-image-quota.js');+ const res = makeRes();+ await handler(makeReq({ body: { prompt: 'a brass owl figurine', aspect_ratio: '16:9', seed: 42 } }), res);+ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.url).toBe('https://cdn.example/forge/refs/abc.jpg');+ expect(body.provider).toBe('nvidia-nim');+ expect(body.width).toBe(1344);+ expect(body.height).toBe(768);+ expect(body.aspect_ratio).toBe('16:9');+ expect(body.seed).toBe(42);+ expect(body.free).toBe(true);+ expect(consumeFreeQuota).toHaveBeenCalledTimes(1);+ });++ it('forwards the seed to the lane', async () => {+ const spy = vi.fn(async () => ({ imageUrl: 'https://cdn.example/x.jpg', model: 'black-forest-labs/flux.1-schnell' }));+ laneState.impl = spy;+ const res = makeRes();+ await handler(makeReq({ body: { prompt: 'a brass owl', seed: 7 } }), res);+ expect(spy).toHaveBeenCalledWith('a brass owl', expect.objectContaining({ aspectRatio: '1:1', seed: 7 }));+ });+});++describe('quota fall-through to x402', () => {+ it('emits a 402 quoting $0.02 once the free quota is exhausted', async () => {+ quotaState.allowed = false;+ const res = makeRes();+ await handler(makeReq({ body: { prompt: 'a brass owl figurine' } }), res);+ expect(res.statusCode).toBe(402);+ const body = JSON.parse(res.body);+ expect((body.accepts || []).map((a) => a.amount)).toContain('20000');+ });+});++describe('no-lane honesty', () => {+ it('returns 503 not_configured naming the env vars when no lane is set', async () => {+ delete process.env.NVIDIA_API_KEY; // no lane configured at all+ const res = makeRes();+ await handler(makeReq({ body: { prompt: 'a brass owl figurine' } }), res);+ expect(res.statusCode).toBe(503);+ const body = JSON.parse(res.body);+ expect(body.error).toBe('not_configured');+ expect(body.error_description).toContain('NVIDIA_API_KEY');+ expect(body.error_description).toContain('GOOGLE_CLOUD_PROJECT');+ });+});++describe('provider safety refusal', () => {+ it('maps a Vertex/Gemini content block to 422 without retrying', async () => {+ // Real captured refusal shape: generateViaGemini throws this exact message+ // when candidates carry a finishReason and no image part.+ laneState.impl = async () => {+ throw new Error('Vertex Gemini returned no image data (finishReason: IMAGE_SAFETY)');+ };+ const res = makeRes();+ await handler(makeReq({ body: { prompt: 'something blocked' } }), res);+ expect(res.statusCode).toBe(422);+ expect(JSON.parse(res.body).error).toBe('content_refused');+ });+});++describe('GET surfaces', () => {+ it('serves a discovery doc with free-tier + price on plain GET', async () => {+ const res = makeRes();+ await handler(makeReq({ method: 'GET' }), res);+ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.route).toBe('/api/v1/ai/image');+ expect(body.free_tier.images_per_day_per_ip).toBe(5);+ expect(body.price_usdc).toBe('0.020000');+ });++ it('reports per-lane health on GET ?health=1 without a lane configured → 503', async () => {+ delete process.env.NVIDIA_API_KEY;+ const res = makeRes();+ await handler(makeReq({ method: 'GET', url: '/api/v1/ai/image?health=1' }), res);+ expect(res.statusCode).toBe(503);+ const body = JSON.parse(res.body);+ expect(body.configured).toBe(false);+ expect(body.lanes.nim.status).toBe('unconfigured');+ expect(body.missing_env).toContain('NVIDIA_API_KEY');+ });++ it('probes a configured Replicate lane as reachable on GET ?health=1', async () => {+ delete process.env.NVIDIA_API_KEY;+ process.env.REPLICATE_API_TOKEN = 'r8_test';+ globalThis.fetch = vi.fn(async () => new Response('{}', { status: 200 }));+ const res = makeRes();+ await handler(makeReq({ method: 'GET', url: '/api/v1/ai/image?health=1' }), res);+ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.configured).toBe(true);+ expect(body.healthy).toBe(true);+ expect(body.lanes.replicate.status).toBe('ok');+ });+});diff --git a/tests/api/v1-token-security.test.js b/tests/api/v1-token-security.test.jsnew file mode 100644index 000000000..4f2a104b5--- /dev/null+++ b/tests/api/v1-token-security.test.js@@ -0,0 +1,357 @@+// GET /api/v1/token/security — free on-chain rug/risk facts for a Solana token.+//+// The endpoint composes three real upstreams into one report agents weigh+// themselves: getAccountInfo (mint/freeze authority, supply, decimals),+// getTokenLargestAccounts (holder concentration), and DexScreener (liquidity+// depth + pair age). The tests pin the contract that matters:+// • the full report against captured REAL-shaped $THREE fixtures,+// • each factual flag's trigger condition (pure builder),+// • partial-upstream failure → per-section nulls + an honest `sources` array,+// • EVM 0x… input → 400, an unresolvable mint → 404, every source down → 503,+// • the per-IP rate limit → 429,+// • the /api/v1 catalog entry is present with the uniqueness-first summary.+//+// The rate limiter is mocked and the network is stubbed via global fetch (real+// Response objects, so the RPC failover chain + fetchTokenMarket run unchanged),+// so the suite runs fully offline while exercising the real handler.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { Readable } from 'node:stream';++// $THREE — the only mint that ever appears in these fixtures (per the $THREE rule).+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// Switchable per-IP quota result — flip `quotaOk` per test. apiV1 (the gateway's+// shared burst guard) always passes; it isn't the thing under test.+let quotaOk = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ apiV1: async () => ({ success: true, limit: 120, remaining: 119, reset: Date.now() + 60_000 }),+ tokenSecurityIp: async () =>+ quotaOk+ ? { success: true, limit: 20, remaining: 19, reset: Date.now() + 60_000 }+ : { success: false, limit: 20, remaining: 0, reset: Date.now() + 60_000 },+ },+ clientIp: () => '203.0.113.7',+}));++const ORIGINAL_FETCH = globalThis.fetch;++beforeEach(() => {+ quotaOk = true;+});+afterEach(() => {+ globalThis.fetch = ORIGINAL_FETCH;+ vi.restoreAllMocks();+});++// ── Captured REAL upstream shapes for $THREE (curled 2026-07) ──────────────────+// getAccountInfo(jsonParsed): a spl-token-2022 mint with BOTH authorities revoked.+const ACCOUNT_INFO_THREE = {+ jsonrpc: '2.0',+ id: 1,+ result: {+ context: { apiVersion: '4.1.0', slot: 431265387 },+ value: {+ data: {+ parsed: {+ info: {+ decimals: 6,+ freezeAuthority: null,+ isInitialized: true,+ mintAuthority: null,+ supply: '999683523471616',+ },+ type: 'mint',+ },+ program: 'spl-token-2022',+ space: 411,+ },+ executable: false,+ lamports: 46804176073,+ owner: 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',+ space: 411,+ },+ },+};++// getTokenLargestAccounts: the 10 largest token accounts (real top-8 amounts + 2).+const LARGEST_THREE = {+ jsonrpc: '2.0',+ id: 1,+ result: {+ context: { apiVersion: '4.1.0', slot: 431265459 },+ value: [+ { address: '5jeRNm8Rx8CrbhbiyNWE4wStfrtfrVpXU76cK9jovyGd', amount: '65966857333250', decimals: 6, uiAmount: 65966857.33325 },+ { address: 'CRRtkr9sSgDxhirY7KVYJMjjgyxSP2BqgC3NED6PkEte', amount: '21891366278164', decimals: 6, uiAmount: 21891366.278164 },+ { address: 'GipFNVyMfKWRD4A53CYD8eSDqntTv9X9LneaJ6zKjxFT', amount: '21562197571639', decimals: 6, uiAmount: 21562197.571639 },+ { address: 'ErJ5BUo1jzr5Z4khfKP3ZUUDDfyNnv3oFn8zDa5pXSik', amount: '18906305767556', decimals: 6, uiAmount: 18906305.767556 },+ { address: 'AMCFm1nhxqBkzbvpsg8xL3BuAWuAkWY6qfdFjRZJn1dD', amount: '18864076135934', decimals: 6, uiAmount: 18864076.135934 },+ { address: 'Cm9EortGHm7Fv53E2XxfKxSPuRG8KTHzdx2JsH3o4ZQ1', amount: '18757358726434', decimals: 6, uiAmount: 18757358.726434 },+ { address: 'DsRx83xQmYse1nkjwiZsKrMoteLT3UBXSgZNuRdbVCn5', amount: '18627604005087', decimals: 6, uiAmount: 18627604.005087 },+ { address: '2AdZHcsXgz7eAf4FK4ghr9UTsuMQMJMtWgFPD38iYHwz', amount: '17614659953367', decimals: 6, uiAmount: 17614659.953367 },+ { address: '8LEGhAhdYHPkbxTr5mdcmYeBSynthPlaceholder001', amount: '15000000000000', decimals: 6, uiAmount: 15000000 },+ { address: '9MFHbBidZIPlcyUs6ndanZfCSynthPlaceholder002', amount: '12000000000000', decimals: 6, uiAmount: 12000000 },+ ],+ },+};++// DexScreener /tokens/<mint>: the deepest pair (three/SOL on pumpswap) first.+const DEXSCREENER_THREE = {+ schemaVersion: '1.0.0',+ pairs: [+ {+ chainId: 'solana',+ dexId: 'pumpswap',+ url: 'https://dexscreener.com/solana/5byl7mzolabynwmpzkpkjf4mgkz7febzranos19pre2z',+ pairAddress: '5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z',+ baseToken: { address: THREE, name: 'three.ws', symbol: 'three' },+ quoteToken: { address: 'So11111111111111111111111111111111111111112', name: 'Wrapped SOL', symbol: 'SOL' },+ priceUsd: '0.001492',+ txns: { h24: { buys: 28926, sells: 11565 } },+ volume: { h24: 418360.79 },+ priceChange: { h24: -1.23 },+ liquidity: { usd: 196695.93, base: 65955621, quote: 1198.7522 },+ fdv: 1492140,+ marketCap: 1492140,+ pairCreatedAt: 1777446541000,+ info: { imageUrl: 'https://cdn.dexscreener.com/x.png' },+ },+ ],+};++// A real WHATWG Response so the RPC failover chain (resp.text/clone) and+// fetchTokenMarket (r.ok/r.json) both run against genuine transport objects.+function jsonResponse(obj, { status = 200 } = {}) {+ return new Response(JSON.stringify(obj), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++// Route the stub by URL (DexScreener vs Solana RPC) and, for RPC, by method.+function makeFetch({ account, largest, dex } = {}) {+ return vi.fn(async (url, init) => {+ const u = String(url);+ if (u.includes('dexscreener.com')) {+ return dex ?? jsonResponse(DEXSCREENER_THREE);+ }+ const method = JSON.parse(init?.body || '{}').method;+ if (method === 'getAccountInfo') return account ?? jsonResponse(ACCOUNT_INFO_THREE);+ if (method === 'getTokenLargestAccounts') return largest ?? jsonResponse(LARGEST_THREE);+ return jsonResponse({ jsonrpc: '2.0', id: 1, result: null });+ });+}++function makeReq({ url = `/api/v1/token/security?address=${THREE}`, host = 'three.ws' } = {}) {+ const stream = Readable.from([]);+ stream.method = 'GET';+ stream.url = url;+ stream.headers = { host };+ return stream;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; this.writableEnded = true; },+ };+}++async function dispatch(req, res) {+ const mod = await import('../../api/v1/token/security.js');+ await mod.default(req, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++// ── Full report against captured real shapes ──────────────────────────────────+describe('GET /api/v1/token/security — full report', () => {+ it('composes authorities, concentration, and liquidity for $THREE', async () => {+ globalThis.fetch = makeFetch();+ const { res, body } = await dispatch(makeReq(), makeRes());+ expect(res.statusCode).toBe(200);+ const d = body.data;+ expect(d.address).toBe(THREE);+ expect(d.chain).toBe('solana');+ // Both authorities revoked (null on chain) → revoked:true, address:null.+ expect(d.mint_authority).toEqual({ revoked: true, address: null });+ expect(d.freeze_authority).toEqual({ revoked: true, address: null });+ expect(d.supply).toBe('999683523471616');+ expect(d.decimals).toBe(6);+ // Concentration: top-1 ≈ 6.6% of supply, 10 accounts sampled.+ expect(d.top_holders.holders_sampled).toBe(10);+ expect(d.top_holders.top1_pct).toBeCloseTo(6.6, 1);+ expect(d.top_holders.top10_pct).toBeGreaterThan(d.top_holders.top1_pct);+ // Liquidity: deepest pair label + creation time from DexScreener.+ expect(d.liquidity.usd).toBeCloseTo(196695.93, 2);+ expect(d.liquidity.largest_pair).toBe('three/SOL');+ expect(d.liquidity.pair_created_at).toBe(1777446541000);+ // A healthy, established token trips no factual flags.+ expect(d.flags).toEqual([]);+ expect(d.sources).toEqual(['solana-rpc', 'dexscreener']);+ expect(typeof d.ts).toBe('number');+ // Public read is edge-cacheable for 60s.+ expect(res.getHeader('cache-control')).toMatch(/s-maxage=60/);+ });+});++// ── Each factual flag's trigger (pure builder) ────────────────────────────────+describe('buildSecurityReport — flag triggers', () => {+ const NOW = 1_780_000_000_000;++ function mintResult({ mintAuthority = null, freezeAuthority = null, supply = '1000000', decimals = 6 } = {}) {+ return { value: { data: { parsed: { type: 'mint', info: { mintAuthority, freezeAuthority, supply, decimals } } } } };+ }++ it('flags active mint + freeze authorities', async () => {+ const { buildSecurityReport } = await import('../../api/v1/token/security.js');+ const { body } = buildSecurityReport({+ address: THREE,+ account: { answered: true, result: mintResult({ mintAuthority: 'MintAuth1111111111111111111111111111111111', freezeAuthority: 'FrzAuth11111111111111111111111111111111111' }) },+ largest: { answered: false },+ market: { answered: false },+ }, NOW);+ expect(body.flags).toContain('mint_authority_active');+ expect(body.flags).toContain('freeze_authority_active');+ expect(body.mint_authority).toEqual({ revoked: false, address: 'MintAuth1111111111111111111111111111111111' });+ });++ it('flags a top-1 holder over 20%', async () => {+ const { buildSecurityReport } = await import('../../api/v1/token/security.js');+ const { body } = buildSecurityReport({+ address: THREE,+ account: { answered: true, result: mintResult({ supply: '1000000' }) },+ largest: { answered: true, result: { value: [{ amount: '300000' }, { amount: '10000' }] } },+ market: { answered: false },+ }, NOW);+ expect(body.top_holders.top1_pct).toBe(30);+ expect(body.flags).toContain('top1_holder_over_20pct');+ });++ it('flags top-10 holders over 80%', async () => {+ const { buildSecurityReport } = await import('../../api/v1/token/security.js');+ const value = Array.from({ length: 10 }, () => ({ amount: '90000' })); // 900k of 1M = 90%+ const { body } = buildSecurityReport({+ address: THREE,+ account: { answered: true, result: mintResult({ supply: '1000000' }) },+ largest: { answered: true, result: { value } },+ market: { answered: false },+ }, NOW);+ expect(body.top_holders.top10_pct).toBe(90);+ expect(body.flags).toContain('top10_holders_over_80pct');+ });++ it('flags liquidity under $10k and a pair younger than 24h', async () => {+ const { buildSecurityReport } = await import('../../api/v1/token/security.js');+ const { body } = buildSecurityReport({+ address: THREE,+ account: { answered: false },+ largest: { answered: false },+ market: { answered: true, data: { liquidity_usd: 4200, pair_label: 'three/SOL', pair_created_at: NOW - 3_600_000 } },+ }, NOW);+ expect(body.flags).toContain('liquidity_under_10k');+ expect(body.flags).toContain('pair_younger_than_24h');+ expect(body.liquidity.usd).toBe(4200);+ });+});++// ── Partial-upstream failure: per-section nulls + honest sources ──────────────+describe('buildSecurityReport — partial degradation', () => {+ it('nulls the liquidity section and drops dexscreener from sources when DexScreener fails', async () => {+ const { buildSecurityReport } = await import('../../api/v1/token/security.js');+ const { resolved, allFailed, body } = buildSecurityReport({+ address: THREE,+ account: { answered: true, result: ACCOUNT_INFO_THREE.result },+ largest: { answered: true, result: LARGEST_THREE.result },+ market: { answered: false },+ }, 1_780_000_000_000);+ expect(resolved).toBe(true);+ expect(allFailed).toBe(false);+ expect(body.liquidity).toEqual({ usd: null, largest_pair: null, pair_created_at: null });+ expect(body.sources).toEqual(['solana-rpc']);+ expect(body.supply).toBe('999683523471616');+ });++ it('nulls the on-chain section and keeps only dexscreener when RPC fails', async () => {+ const { buildSecurityReport } = await import('../../api/v1/token/security.js');+ const { body } = buildSecurityReport({+ address: THREE,+ account: { answered: false },+ largest: { answered: false },+ market: { answered: true, data: { liquidity_usd: 196695.93, pair_label: 'three/SOL', pair_created_at: 1777446541000 } },+ }, 1_780_000_000_000);+ expect(body.mint_authority).toEqual({ revoked: null, address: null });+ expect(body.freeze_authority).toEqual({ revoked: null, address: null });+ expect(body.supply).toBeNull();+ expect(body.top_holders).toEqual({ top1_pct: null, top5_pct: null, top10_pct: null, holders_sampled: null });+ expect(body.sources).toEqual(['dexscreener']);+ });+});++// ── HTTP boundary: input validation + status codes ────────────────────────────+describe('GET /api/v1/token/security — boundaries', () => {+ it('rejects an EVM 0x… address with a Solana-only 400', async () => {+ globalThis.fetch = makeFetch();+ const url = '/api/v1/token/security?address=0x1234567890abcdef1234567890abcdef12345678';+ const { res, body } = await dispatch(makeReq({ url }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('unsupported_chain');+ expect(body.error_description).toMatch(/Solana/i);+ // Never touched an upstream on a rejected input.+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('rejects a missing address with 400', async () => {+ globalThis.fetch = makeFetch();+ const { res, body } = await dispatch(makeReq({ url: '/api/v1/token/security' }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('returns 404 when no source can resolve the mint', async () => {+ globalThis.fetch = makeFetch({+ account: jsonResponse({ jsonrpc: '2.0', id: 1, result: { context: {}, value: null } }),+ largest: jsonResponse({ jsonrpc: '2.0', id: 1, result: { context: {}, value: [] } }),+ dex: jsonResponse({ schemaVersion: '1.0.0', pairs: [] }),+ });+ const { res, body } = await dispatch(makeReq(), makeRes());+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('returns 503 when every source is down', async () => {+ globalThis.fetch = vi.fn(async () => { throw new Error('network down'); });+ const { res, body } = await dispatch(makeReq(), makeRes());+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('sources_unavailable');+ });++ it('returns 429 when the per-IP quota is exhausted', async () => {+ globalThis.fetch = makeFetch();+ quotaOk = false;+ const { res, body } = await dispatch(makeReq(), makeRes());+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ expect(res.getHeader('retry-after')).toBeTruthy();+ // The upstreams are never hit once the quota is spent.+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });+});++// ── Catalog registration ──────────────────────────────────────────────────────+describe('/api/v1 catalog', () => {+ it('registers the token security endpoint with the uniqueness-first summary', async () => {+ const { CATALOG } = await import('../../api/v1/_catalog.js');+ const entry = CATALOG.find((e) => e.id === 'v1.token.security');+ expect(entry).toBeTruthy();+ expect(entry.method).toBe('GET');+ expect(entry.path).toBe('/api/v1/token/security');+ expect(entry.auth).toBe('public');+ expect(entry.summary).toMatch(/^Rug-check any Solana token in one free call/);+ });+});diff --git a/tests/crypto-bonding-endpoint.test.js b/tests/crypto-bonding-endpoint.test.jsnew file mode 100644index 000000000..23b44cc19--- /dev/null+++ b/tests/crypto-bonding-endpoint.test.js@@ -0,0 +1,142 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Test the endpoint's COMPOSITION + branching (input validation, not-found →+// 400, upstream-down → 503, success shape), not the network beneath it.+vi.mock('../api/_lib/http.js', () => ({+ wrap: (fn) => fn,+ cors: () => false,+ method: () => true,+ rateLimited: (res) => {+ res._json = { status: 429, body: { error: 'rate_limited' } };+ return res;+ },+ error: (res, status, code, message, extra = {}) => {+ res._json = { status, body: { error: code, error_description: message, ...extra } };+ return res;+ },+ json: (res, status, body) => {+ res._json = { status, body };+ return res;+ },+}));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '1.2.3.4',+}));+vi.mock('../api/_lib/pump-bonding.js', () => ({+ getBondingStatus: vi.fn(),+}));++import handler from '../api/crypto/bonding.js';+import { getBondingStatus } from '../api/_lib/pump-bonding.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++function fakeRes() {+ return { setHeader() {}, end() {}, statusCode: 200 };+}+function call(url) {+ const res = fakeRes();+ return handler({ method: 'GET', url, headers: {} }, res).then(() => res);+}++beforeEach(() => {+ getBondingStatus.mockReset();+});++describe('GET /api/crypto/bonding', () => {+ it('400s when mint is missing (no upstream call)', async () => {+ const res = await call('/api/crypto/bonding');+ expect(res._json.status).toBe(400);+ expect(res._json.body.error).toBe('missing_mint');+ expect(getBondingStatus).not.toHaveBeenCalled();+ });++ it('400s on a non-base58 mint before any upstream call', async () => {+ const res = await call('/api/crypto/bonding?mint=not-a-real-mint!!');+ expect(res._json.status).toBe(400);+ expect(res._json.body.error).toBe('invalid_mint');+ expect(getBondingStatus).not.toHaveBeenCalled();+ });++ it('400s a valid-looking but non-pump.fun mint with a discovery pointer', async () => {+ getBondingStatus.mockResolvedValue({ kind: 'not_found' });+ const res = await call(`/api/crypto/bonding?mint=${THREE_MINT}`);+ expect(res._json.status).toBe(400);+ expect(res._json.body.error).toBe('not_pumpfun_mint');+ expect(res._json.body.error_description).toContain('/api/crypto/launches');+ });++ it('503s (never 500) when the pump.fun feed is down, with retry hint', async () => {+ getBondingStatus.mockResolvedValue({ kind: 'upstream_down' });+ const res = await call(`/api/crypto/bonding?mint=${THREE_MINT}`);+ expect(res._json.status).toBe(503);+ expect(res._json.body.error).toBe('upstream_unavailable');+ expect(res._json.body.retry_after).toBe(15);+ });++ it('200s an on-curve coin with the documented shape', async () => {+ getBondingStatus.mockResolvedValue({+ kind: 'ok',+ status: {+ onCurve: true,+ graduated: false,+ migratedTo: null,+ bondingProgressPct: 62.5,+ solInCurve: 40,+ tokensRemaining: 297_412_500,+ marketCapUsd: 48000,+ source: 'pumpfun',+ },+ });+ const res = await call(`/api/crypto/bonding?mint=${THREE_MINT}`);+ expect(res._json.status).toBe(200);+ const b = res._json.body;+ expect(b).toMatchObject({+ mint: THREE_MINT,+ onCurve: true,+ graduated: false,+ migratedTo: null,+ bondingProgressPct: 62.5,+ solInCurve: 40,+ tokensRemaining: 297_412_500,+ marketCapUsd: 48000,+ source: 'pumpfun',+ });+ expect(typeof b.ts).toBe('string');+ });++ it('200s a graduated coin with graduated:true + migratedTo and nulled curve fields', async () => {+ getBondingStatus.mockResolvedValue({+ kind: 'ok',+ status: {+ onCurve: false,+ graduated: true,+ migratedTo: 'pumpswap',+ bondingProgressPct: 100,+ solInCurve: null,+ tokensRemaining: null,+ marketCapUsd: 71000,+ source: 'pumpfun',+ },+ });+ const res = await call(`/api/crypto/bonding?mint=${THREE_MINT}`);+ expect(res._json.status).toBe(200);+ expect(res._json.body).toMatchObject({+ graduated: true,+ onCurve: false,+ migratedTo: 'pumpswap',+ bondingProgressPct: 100,+ solInCurve: null,+ tokensRemaining: null,+ });+ });++ it('429s when the per-IP limiter denies', async () => {+ const { limits } = await import('../api/_lib/rate-limit.js');+ limits.publicIp.mockResolvedValueOnce({ success: false });+ const res = await call(`/api/crypto/bonding?mint=${THREE_MINT}`);+ expect(res._json.status).toBe(429);+ expect(getBondingStatus).not.toHaveBeenCalled();+ });+});diff --git a/tests/crypto-catalog.test.js b/tests/crypto-catalog.test.jsnew file mode 100644index 000000000..c52d32e8b--- /dev/null+++ b/tests/crypto-catalog.test.js@@ -0,0 +1,192 @@+// Tests for the free Crypto Data API discovery layer: the catalog assembler+// (globs entry files, skips malformed, dedups), the OpenAPI 3.1 generator, and+// the GET /api/crypto index handler's HTML-vs-JSON content negotiation.++import { describe, it, expect } from 'vitest';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++import { loadCatalog } from '../api/_lib/crypto-catalog/index.js';+import { buildOpenApiDoc, validateOpenApiDoc } from '../api/_lib/crypto-catalog/openapi.js';+import cryptoIndex from '../api/crypto/index.js';++const HERE = dirname(fileURLToPath(import.meta.url));+const FIXTURES = resolve(HERE, '_fixtures/crypto-catalog');++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ setHeader(k, v) {+ this._headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._headers[k.toLowerCase()];+ },+ end(b) {+ this._body = b || '';+ },+ get headersSent() {+ return false;+ },+ get writableEnded() {+ return false;+ },+ get json() {+ try {+ return JSON.parse(this._body);+ } catch {+ return null;+ }+ },+ };+}++function mockReq({ accept = 'application/json' } = {}) {+ return {+ method: 'GET',+ url: '/api/crypto',+ headers: { accept, origin: 'http://localhost:3000' },+ socket: { remoteAddress: '127.0.0.1' },+ };+}++describe('crypto-catalog assembler', () => {+ it('merges every valid entry, skips malformed, skips throwing, dedups routes', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const slugs = entries.map((e) => e.slug).sort();++ // token.js (default export), holders.js (named export), and paramstyle.js+ // (input/output aliases) survive; broken-shape.js, broken-throws.js, and+ // dup-token.js are all dropped.+ expect(slugs).toEqual(['holders', 'paramstyle', 'token']);+ expect(entries.find((e) => e.slug === 'token-dupe')).toBeUndefined();+ expect(entries.find((e) => e.slug === 'never')).toBeUndefined();+ });++ it('accepts the terse input/output aliases and a multi-verb methods array', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const p = entries.find((e) => e.slug === 'paramstyle');+ expect(p.inputSchema).toBeTruthy(); // `input` aliased into inputSchema+ expect(p.outputSchema).toBeTruthy(); // `output` aliased into outputSchema+ expect(p.methods).toEqual(['GET', 'POST']);+ });++ it('normalizes entries: method upper-cased, optional fields defaulted', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const token = entries.find((e) => e.slug === 'token');+ expect(token.method).toBe('GET'); // fixture declares lowercase "get"+ expect(token.path).toBe('/api/crypto/token');+ expect(typeof token.title).toBe('string');+ // holders declares no example → defaulted to null, never undefined.+ const holders = entries.find((e) => e.slug === 'holders');+ expect(holders.example).toBeNull();+ });++ it('returns a valid EMPTY catalog for a directory with no entries', async () => {+ const empty = mkdtempSync(join(tmpdir(), 'crypto-catalog-empty-'));+ const entries = await loadCatalog({ dir: empty, fresh: true });+ expect(entries).toEqual([]);+ });++ it('never throws on an unreadable directory', async () => {+ const missing = join(tmpdir(), 'does-not-exist-' + 'xyz');+ await expect(loadCatalog({ dir: missing, fresh: true })).resolves.toEqual([]);+ });+});++describe('crypto-catalog OpenAPI generator', () => {+ it('produces a structurally valid OpenAPI 3.1 doc from the entries', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const doc = buildOpenApiDoc(entries, { origin: 'https://three.ws', version: '1.0.0' });++ expect(validateOpenApiDoc(doc)).toEqual([]);+ expect(doc.openapi).toBe('3.1.0');+ expect(doc.info.title).toBeTruthy();+ expect(doc.info.version).toBe('1.0.0');+ expect(doc.servers[0].url).toBe('https://three.ws');++ // Each entry became a path + operation keyed by its lowercased method.+ expect(doc.paths['/api/crypto/token'].get.operationId).toBe('token');+ expect(doc.paths['/api/crypto/holders/{mint}'].get).toBeTruthy();+ });++ it('converts inputSchema into query + path parameters', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const doc = buildOpenApiDoc(entries);++ // token: object inputSchema → `address` (required query) + `chain` (query).+ const tokenParams = doc.paths['/api/crypto/token'].get.parameters;+ const address = tokenParams.find((p) => p.name === 'address');+ expect(address.in).toBe('query');+ expect(address.required).toBe(true);+ expect(tokenParams.find((p) => p.name === 'chain').required).toBe(false);++ // holders: `{mint}` becomes a required path param even from an array schema.+ const holdersParams = doc.paths['/api/crypto/holders/{mint}'].get.parameters;+ const mint = holdersParams.find((p) => p.name === 'mint');+ expect(mint.in).toBe('path');+ expect(mint.required).toBe(true);++ // paramstyle: bare param-map input → params; `{mint}` path param honored.+ const psGet = doc.paths['/api/crypto/paramstyle/{mint}'].get.parameters;+ expect(psGet.find((p) => p.name === 'mint').in).toBe('path');+ expect(psGet.find((p) => p.name === 'verbose').in).toBe('query');+ });++ it('emits one operation per verb for multi-verb entries', async () => {+ const entries = await loadCatalog({ dir: FIXTURES, fresh: true });+ const doc = buildOpenApiDoc(entries);+ const item = doc.paths['/api/crypto/paramstyle/{mint}'];+ expect(item.get).toBeTruthy();+ expect(item.post).toBeTruthy();+ expect(item.get.operationId).toBe('paramstyle_get');+ // String-valued output fields coerce to valid schema objects.+ const schema = item.get.responses['200'].content['application/json'].schema;+ expect(schema.properties.ok.description).toContain('always true');+ });++ it('validates an empty-catalog doc (no paths) as still well-formed', () => {+ const doc = buildOpenApiDoc([], { origin: 'https://three.ws' });+ expect(validateOpenApiDoc(doc)).toEqual([]);+ expect(doc.paths).toEqual({});+ });++ it('flags a malformed doc', () => {+ expect(validateOpenApiDoc({ openapi: '3.0.0' }).length).toBeGreaterThan(0);+ expect(validateOpenApiDoc(null)).toEqual(['document is not an object']);+ });+});++describe('GET /api/crypto content negotiation', () => {+ it('returns JSON by default with the discovery envelope', async () => {+ const req = mockReq({ accept: 'application/json' });+ const res = mockRes();+ await cryptoIndex(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toMatch(/application\/json/);+ const body = res.json;+ expect(body.name).toBe('three.ws Crypto Data API');+ expect(body.free).toBe(true);+ expect(body.keyless).toBe(true);+ expect(Array.isArray(body.endpoints)).toBe(true);+ expect(body.docs).toBe('/docs/crypto-api');+ expect(body.openapi).toBe('/api/crypto/openapi.json');+ expect(typeof body.ts).toBe('string');+ });++ it('returns HTML when the client asks for text/html', async () => {+ const req = mockReq({ accept: 'text/html' });+ const res = mockRes();+ await cryptoIndex(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toMatch(/text\/html/);+ expect(res._body).toContain('<!doctype html>');+ expect(res._body).toContain('three.ws Crypto Data API');+ });+});diff --git a/tests/crypto-whales.test.js b/tests/crypto-whales.test.jsnew file mode 100644index 000000000..e5b703a7a--- /dev/null+++ b/tests/crypto-whales.test.js@@ -0,0 +1,118 @@+import { describe, it, expect } from 'vitest';+import {+ normalizeTrade,+ computeSignal,+ buildWhaleResult,+} from '../api/_lib/pump-whale-scan.js';++// Synthetic pump.fun trades — no real third-party mints/wallets (CLAUDE.md).+// Wallets are placeholder base58-ish strings; the aggregation only keys on them.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++function buy(wallet, sol, extra = {}) {+ return { type: 'buy', amountSol: sol, userAddress: wallet, signature: `sig-${wallet}-${sol}`, timestamp: 1783382400, ...extra };+}+function sell(wallet, sol, extra = {}) {+ return { type: 'sell', amountSol: sol, userAddress: wallet, signature: `sig-${wallet}-${sol}`, timestamp: 1783382400, ...extra };+}++describe('normalizeTrade', () => {+ it('parses a buy with defensive field names', () => {+ const t = normalizeTrade({ txType: 'BUY', sol_amount: '3.5', user: 'WalletA', tx: 'abc', createdAt: 1783382400 });+ expect(t).toEqual({ side: 'buy', sol: 3.5, wallet: 'WalletA', txHash: 'abc', ts: '2026-07-07T00:00:00.000Z' });+ });++ it('normalizes millisecond timestamps and ISO strings', () => {+ expect(normalizeTrade(buy('W', 5, { timestamp: 1783382400000 })).ts).toBe('2026-07-07T00:00:00.000Z');+ expect(normalizeTrade(buy('W', 5, { timestamp: '2026-07-07T00:00:00Z' })).ts).toBe('2026-07-07T00:00:00.000Z');+ });++ it('rejects non-buy/sell, zero-amount, and wallet-less trades', () => {+ expect(normalizeTrade({ type: 'transfer', amountSol: 5, userAddress: 'W' })).toBeNull();+ expect(normalizeTrade({ type: 'buy', amountSol: 0, userAddress: 'W' })).toBeNull();+ expect(normalizeTrade({ type: 'buy', amountSol: 5 })).toBeNull();+ expect(normalizeTrade(null)).toBeNull();+ });+});++describe('computeSignal — deterministic net-whale-flow rule', () => {+ const minSol = 5;+ it('neutral when there is no whale activity at all', () => {+ expect(computeSignal({ whaleBuySol: 0, whaleSellSol: 0, buyCount: 0, sellCount: 0 }, minSol)).toBe('neutral');+ });+ it('bullish when net whale flow ≥ +minSol (accumulation)', () => {+ expect(computeSignal({ whaleBuySol: 30, whaleSellSol: 10, buyCount: 4, sellCount: 1 }, minSol)).toBe('bullish');+ });+ it('bearish when net whale flow ≤ −minSol (distribution)', () => {+ expect(computeSignal({ whaleBuySol: 6, whaleSellSol: 20, buyCount: 1, sellCount: 3 }, minSol)).toBe('bearish');+ });+ it('neutral when net flow is within ±minSol (balanced)', () => {+ expect(computeSignal({ whaleBuySol: 12, whaleSellSol: 10, buyCount: 2, sellCount: 2 }, minSol)).toBe('neutral');+ });+ it('scales with minSol — same net flow flips as threshold changes', () => {+ const flow = { whaleBuySol: 12, whaleSellSol: 4, buyCount: 2, sellCount: 1 }; // net +8+ expect(computeSignal(flow, 5)).toBe('bullish'); // 8 ≥ 5+ expect(computeSignal(flow, 10)).toBe('neutral'); // 8 < 10+ });+});++describe('buildWhaleResult — threshold filter', () => {+ it('keeps only buys at/above minSol', () => {+ const trades = [buy('W1', 10), buy('W2', 4.9), buy('W3', 5)];+ const r = buildWhaleResult({ trades, scope: 'token', mint: THREE_MINT, minSol: 5, limit: 10 });+ expect(r.whaleCount).toBe(2);+ expect(r.whales.map((w) => w.solMoved).sort()).toEqual([5, 10]);+ expect(r.totalSolMoved).toBe(15);+ });+});++describe('buildWhaleResult — token scope (per-buy rows)', () => {+ it('returns one row per qualifying buy, largest first, carrying tx + ts', () => {+ const trades = [buy('W1', 6), buy('W1', 20), buy('W2', 8)];+ const r = buildWhaleResult({ trades, scope: 'token', mint: THREE_MINT, minSol: 5, limit: 10 });+ expect(r.scope).toBe('token');+ expect(r.mint).toBe(THREE_MINT);+ expect(r.whales.map((w) => w.solMoved)).toEqual([20, 8, 6]); // per-buy, not aggregated+ expect(r.whaleCount).toBe(3);+ expect(r.whales[0].txHash).toBeTruthy();+ expect(r.whales[0].ts).toBe('2026-07-07T00:00:00.000Z');+ });++ it('respects the limit', () => {+ const trades = [buy('W1', 6), buy('W2', 7), buy('W3', 8)];+ const r = buildWhaleResult({ trades, scope: 'token', mint: THREE_MINT, minSol: 5, limit: 2 });+ expect(r.whales).toHaveLength(2);+ expect(r.whaleCount).toBe(3); // count reflects all qualifiers, list is capped+ });+});++describe('buildWhaleResult — market scope (per-wallet aggregation)', () => {+ it('aggregates a wallet across coins; solMoved sums, txHash = largest buy', () => {+ const trades = [buy('Whale', 6), buy('Whale', 20), buy('Other', 8)];+ const r = buildWhaleResult({ trades, scope: 'market', mint: null, minSol: 5, limit: 10 });+ expect(r.scope).toBe('market');+ expect(r.mint).toBeNull();+ const whale = r.whales.find((w) => w.wallet === 'Whale');+ expect(whale.solMoved).toBe(26); // 6 + 20 summed+ expect(whale.txHash).toBe('sig-Whale-20'); // representative = largest buy+ expect(r.whaleCount).toBe(2); // distinct wallets, not buys+ });+});++describe('buildWhaleResult — empty case', () => {+ it('no whales over threshold → empty + neutral, not an error', () => {+ const trades = [buy('W1', 1), sell('W2', 2)];+ const r = buildWhaleResult({ trades, scope: 'market', mint: null, minSol: 5, limit: 10 });+ expect(r.whales).toEqual([]);+ expect(r.whaleCount).toBe(0);+ expect(r.totalSolMoved).toBe(0);+ expect(r.signal).toBe('neutral');+ expect(r.source).toBe('pump.fun');+ });++ it('empty trade list → empty + neutral', () => {+ const r = buildWhaleResult({ trades: [], scope: 'token', mint: THREE_MINT, minSol: 5, limit: 10 });+ expect(r.whales).toEqual([]);+ expect(r.signal).toBe('neutral');+ });+});diff --git a/tests/pump-bonding.test.js b/tests/pump-bonding.test.jsnew file mode 100644index 000000000..c3fb6e241--- /dev/null+++ b/tests/pump-bonding.test.js@@ -0,0 +1,144 @@+import { describe, it, expect } from 'vitest';+import {+ bondingProgressPct,+ mapBondingStatus,+ isPumpLaunch,+ PUMP_CURVE_INITIAL_REAL_TOKENS,+} from '../api/_lib/pump-bonding.js';++// Synthetic pump.fun coin objects. No real third-party mint — $THREE's CA is the+// platform's own coin; the reserves are illustrative curve states.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++describe('bondingProgressPct — curve math', () => {+ it('is 0 at launch (full curve float unsold)', () => {+ expect(bondingProgressPct(PUMP_CURVE_INITIAL_REAL_TOKENS)).toBe(0);+ });++ it('is 50 when half the float has been bought out', () => {+ expect(bondingProgressPct(PUMP_CURVE_INITIAL_REAL_TOKENS / 2)).toBeCloseTo(50, 6);+ });++ it('is 100 when the curve float is fully sold', () => {+ expect(bondingProgressPct(0)).toBe(100);+ });++ it('accepts string reserves (feed returns strings)', () => {+ expect(bondingProgressPct(String(PUMP_CURVE_INITIAL_REAL_TOKENS / 4))).toBeCloseTo(75, 6);+ });++ it('clamps out-of-range reserves into 0–100', () => {+ // More reserves than the initial float would compute negative → clamp to 0.+ expect(bondingProgressPct(PUMP_CURVE_INITIAL_REAL_TOKENS * 2)).toBe(0);+ });++ it('returns null when reserves are unknown/invalid', () => {+ expect(bondingProgressPct(null)).toBeNull();+ expect(bondingProgressPct(undefined)).toBeNull();+ expect(bondingProgressPct('not-a-number')).toBeNull();+ expect(bondingProgressPct(-5)).toBeNull();+ });+});++describe('isPumpLaunch — native launch vs externally-indexed token', () => {+ it('accepts a coin with a bonding-curve account', () => {+ expect(isPumpLaunch({ mint: THREE_MINT, bonding_curve: 'BcAcct1111' })).toBe(true);+ });++ it('accepts a coin with live curve reserves', () => {+ expect(isPumpLaunch({ mint: THREE_MINT, virtual_token_reserves: '1073000000000000' })).toBe(true);+ });++ it('accepts a `pump`-suffixed mint as a corroborator', () => {+ expect(isPumpLaunch({ mint: THREE_MINT })).toBe(true); // ends in "pump"+ });++ it('rejects an externally-indexed token even if it carries a bonding_curve field', () => {+ // pump.fun indexes WSOL/USDC/cross-chain tokens with indexed_by_pump — not launches.+ expect(isPumpLaunch({ mint: 'So11111111111111111111111111111111111111112', indexed_by_pump: true, bonding_curve: 'x' })).toBe(false);+ });++ it('rejects a bare non-pump mint with no curve signal', () => {+ expect(isPumpLaunch({ mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' })).toBe(false);+ expect(isPumpLaunch(null)).toBe(false);+ expect(isPumpLaunch({})).toBe(false);+ });+});++describe('mapBondingStatus — on-curve branch', () => {+ const coin = {+ mint: THREE_MINT,+ complete: false,+ real_token_reserves: String(PUMP_CURVE_INITIAL_REAL_TOKENS / 4), // 75% bought out+ real_sol_reserves: String(42 * 1e9), // 42 SOL in the curve+ usd_market_cap: 51234.5,+ };++ it('reports live curve fields and progress', () => {+ const s = mapBondingStatus(coin);+ expect(s.onCurve).toBe(true);+ expect(s.graduated).toBe(false);+ expect(s.migratedTo).toBeNull();+ expect(s.bondingProgressPct).toBeCloseTo(75, 6);+ expect(s.solInCurve).toBeCloseTo(42, 6);+ expect(s.tokensRemaining).toBeCloseTo(PUMP_CURVE_INITIAL_REAL_TOKENS / 4 / 1e6, 6);+ expect(s.marketCapUsd).toBe(51234.5);+ expect(s.source).toBe('pumpfun');+ });++ it('derives USD market cap from SOL cap when usd_market_cap is absent', () => {+ const s = mapBondingStatus(+ { ...coin, usd_market_cap: undefined, market_cap: 100 },+ { solPriceUsd: 150 },+ );+ expect(s.marketCapUsd).toBe(15000);+ });++ it('leaves curve fields null when reserves are missing (never throws)', () => {+ const s = mapBondingStatus({ mint: THREE_MINT, complete: false });+ expect(s.onCurve).toBe(true);+ expect(s.bondingProgressPct).toBeNull();+ expect(s.solInCurve).toBeNull();+ expect(s.tokensRemaining).toBeNull();+ });+});++describe('mapBondingStatus — graduated branch', () => {+ it('nulls the curve fields, pins progress to 100, reports the venue (complete flag)', () => {+ const s = mapBondingStatus({+ mint: THREE_MINT,+ complete: true,+ real_token_reserves: '0',+ real_sol_reserves: '0',+ usd_market_cap: 69000,+ });+ expect(s.graduated).toBe(true);+ expect(s.onCurve).toBe(false);+ expect(s.bondingProgressPct).toBe(100);+ expect(s.solInCurve).toBeNull();+ expect(s.tokensRemaining).toBeNull();+ expect(s.migratedTo).toBe('pumpswap'); // default AMM when no explicit pool field+ expect(s.marketCapUsd).toBe(69000);+ });++ it('detects Raydium migration from raydium_pool', () => {+ const s = mapBondingStatus({+ mint: THREE_MINT,+ complete: true,+ raydium_pool: 'RayPoolPlaceholder1111111111111111111111111',+ });+ expect(s.graduated).toBe(true);+ expect(s.migratedTo).toBe('raydium');+ });++ it('detects PumpSwap migration from pump_swap_pool even without the complete flag', () => {+ const s = mapBondingStatus({+ mint: THREE_MINT,+ complete: false,+ pump_swap_pool: 'PumpSwapPoolPlaceholder11111111111111111111',+ });+ expect(s.graduated).toBe(true);+ expect(s.onCurve).toBe(false);+ expect(s.migratedTo).toBe('pumpswap');+ });+});diff --git a/tests/subject-reputation.test.js b/tests/subject-reputation.test.jsnew file mode 100644index 000000000..a61487076--- /dev/null+++ b/tests/subject-reputation.test.js@@ -0,0 +1,229 @@+// Unit tests for the cross-chain subject reputation engine.+//+// Two pure layers are pinned here without any network: subject-type detection+// (does an arbitrary identifier route to the right chain/loader?) and the+// deterministic scoring formula (same signals → same score, available-weighted,+// never a fabricated number for an unscannable subject).++import { describe, it, expect } from 'vitest';+import {+ detectSubject,+ scoreSignals,+ tierForScore,+ scoreSubjectBatch,+ DIMENSIONS,+ SUBJECT_TYPES,+} from '../api/_lib/trust/subject-reputation.js';++// $THREE — the platform coin, used as a real Solana-mint fixture.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+// A synthetic-but-shape-valid Solana wallet + a well-known EVM address form.+const SOL_WALLET = 'THREEsynthetic1111111111111111111111111111';+const EVM_WALLET = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e';+const UUID = '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55';++// ── Subject-type detection ────────────────────────────────────────────────────++describe('detectSubject — type routing', () => {+ it('routes a UUID to the three.ws agent path', () => {+ const d = detectSubject(UUID);+ expect(d.subjectType).toBe('threews_agent');+ expect(d.subject).toBe(UUID);+ });++ it('lowercases a mixed-case UUID', () => {+ const d = detectSubject(UUID.toUpperCase());+ expect(d.subjectType).toBe('threews_agent');+ expect(d.subject).toBe(UUID);+ });++ it('routes an EVM 0x address to the EVM wallet path with the default chain', () => {+ const d = detectSubject(EVM_WALLET);+ expect(d.subjectType).toBe('evm_wallet');+ expect(d.subject).toBe(EVM_WALLET.toLowerCase());+ expect(d.chainId).toBe(8453);+ });++ it('honors an explicit chain for an EVM address', () => {+ const d = detectSubject(EVM_WALLET, { chain: 1 });+ expect(d.subjectType).toBe('evm_wallet');+ expect(d.chainId).toBe(1);+ });++ it('routes a Solana base58 string to the coarse solana family', () => {+ const d = detectSubject(THREE_MINT);+ expect(d.subjectType).toBe('solana');+ expect(d.subject).toBe(THREE_MINT);+ });++ it('routes a Solana wallet-shaped string to the solana family', () => {+ expect(detectSubject(SOL_WALLET).subjectType).toBe('solana');+ });++ it('routes a bare integer to an ERC-8004 agent id on the default chain', () => {+ const d = detectSubject('42');+ expect(d.subjectType).toBe('erc8004_agent');+ expect(d.chainId).toBe(8453);+ expect(d.agentId).toBe('42');+ expect(d.subject).toBe('erc8004:8453:42');+ });++ it('routes a prefixed erc8004:<chain>:<id> identifier', () => {+ const d = detectSubject('erc8004:42161:1337');+ expect(d.subjectType).toBe('erc8004_agent');+ expect(d.chainId).toBe(42161);+ expect(d.agentId).toBe('1337');+ });++ it('routes an eip155:<chain>:<numericId> identifier to erc8004', () => {+ const d = detectSubject('eip155:8453:7');+ expect(d.subjectType).toBe('erc8004_agent');+ expect(d.chainId).toBe(8453);+ expect(d.agentId).toBe('7');+ });++ it('does not mistake a CAIP-10 account (…:0xaddr) for an erc8004 agent id', () => {+ // The last segment is an address, not a numeric token id → falls through to unknown.+ const d = detectSubject(`eip155:8453:${EVM_WALLET}`);+ expect(d.subjectType).toBe('unknown');+ });++ it('returns unknown for empty and garbage identifiers', () => {+ expect(detectSubject('').subjectType).toBe('unknown');+ expect(detectSubject(' ').subjectType).toBe('unknown');+ expect(detectSubject('not a real id !!').subjectType).toBe('unknown');+ });++ it('every detected subjectType is a declared type', () => {+ for (const id of [UUID, EVM_WALLET, THREE_MINT, '42', 'erc8004:1:1', 'garbage']) {+ const t = detectSubject(id).subjectType;+ // 'solana' is the coarse family refined by the loader; the rest are terminal.+ expect([...SUBJECT_TYPES, 'solana']).toContain(t);+ }+ });+});++// ── Scoring formula ───────────────────────────────────────────────────────────++describe('scoreSignals — determinism & bounds', () => {+ const rich = {+ activity: 200,+ ageDays: 365,+ counterparties: 25,+ holdingsUsd: 1000,+ failureRate: 0,+ attestationCount: 10,+ };++ it('is deterministic — identical signals yield identical scores', () => {+ const a = scoreSignals(rich);+ const b = scoreSignals({ ...rich });+ expect(a.score).toBe(b.score);+ expect(a.tier).toBe(b.tier);+ });++ it('a fully-saturated subject scores 100 / elite', () => {+ const r = scoreSignals(rich);+ expect(r.score).toBe(100);+ expect(r.tier).toBe('elite');+ expect(r.weight_considered).toBe(100);+ });++ it('an all-zero subject with every dimension present scores 0 / low', () => {+ const r = scoreSignals({+ activity: 0,+ ageDays: 0,+ counterparties: 0,+ holdingsUsd: 0,+ failureRate: 1,+ attestationCount: 0,+ });+ expect(r.score).toBe(0);+ expect(r.tier).toBe('low');+ });++ it('returns score:null / tier:unknown when NO dimension is readable', () => {+ const r = scoreSignals({});+ expect(r.score).toBeNull();+ expect(r.tier).toBe('unknown');+ expect(r.weight_considered).toBe(0);+ });++ it('normalizes over ONLY the available dimensions (partial evidence is not penalised)', () => {+ // Only activity is present and fully saturated → score should be 100, not+ // diluted by the missing dimensions.+ const r = scoreSignals({ activity: 200 });+ expect(r.score).toBe(100);+ expect(r.weight_considered).toBe(DIMENSIONS.find((d) => d.key === 'activity').weight);+ });++ it('more activity strictly increases the score', () => {+ const low = scoreSignals({ activity: 10, counterparties: 2 }).score;+ const high = scoreSignals({ activity: 150, counterparties: 2 }).score;+ expect(high).toBeGreaterThan(low);+ });++ it('a denylist hit caps the score at 10 regardless of positive signals', () => {+ const clean = scoreSignals(rich).score;+ const banned = scoreSignals({ ...rich, banned: true }).score;+ expect(clean).toBe(100);+ expect(banned).toBeLessThanOrEqual(10);+ expect(tierForScore(banned)).toBe('low');+ });++ it('negative ERC-8004 feedback scales the attestation contribution down, never up', () => {+ const neutral = scoreSignals({ attestationCount: 10, attestationAvg: 100 });+ const negative = scoreSignals({ attestationCount: 10, attestationAvg: -100 });+ expect(negative.score).toBeLessThan(neutral.score);+ expect(negative.dimensions.attestations.points).toBe(0);+ });++ it('reliability reflects the failure rate', () => {+ const reliable = scoreSignals({ failureRate: 0 }).score;+ const flaky = scoreSignals({ failureRate: 0.5 }).score;+ expect(reliable).toBeGreaterThan(flaky);+ });++ it('exposes a per-dimension breakdown with availability + points', () => {+ const r = scoreSignals({ activity: 100 });+ expect(r.dimensions.activity.available).toBe(true);+ expect(r.dimensions.age.available).toBe(false);+ expect(r.dimensions.age.points).toBe(0);+ expect(typeof r.dimensions.activity.points).toBe('number');+ });+});++describe('tierForScore — documented bands', () => {+ it('maps the score bands to the right tiers', () => {+ expect(tierForScore(null)).toBe('unknown');+ expect(tierForScore(0)).toBe('low');+ expect(tierForScore(29)).toBe('low');+ expect(tierForScore(30)).toBe('medium');+ expect(tierForScore(59)).toBe('medium');+ expect(tierForScore(60)).toBe('high');+ expect(tierForScore(84)).toBe('high');+ expect(tierForScore(85)).toBe('elite');+ expect(tierForScore(100)).toBe('elite');+ });+});++// ── Batch scoring (unknown subjects are graceful, never thrown) ────────────────++describe('scoreSubjectBatch — resilience', () => {+ it('returns an unknown result for garbage subjects without throwing', async () => {+ const out = await scoreSubjectBatch(['not a real id !!', 'also bad %%%']);+ expect(out).toHaveLength(2);+ for (const r of out) {+ expect(r.score).toBeNull();+ expect(r.tier).toBe('unknown');+ expect(Array.isArray(r.caveats)).toBe(true);+ expect(r.caveats.length).toBeGreaterThan(0);+ }+ });++ it('skips empty / whitespace entries', async () => {+ const out = await scoreSubjectBatch(['', ' ', 'garbage!!']);+ expect(out).toHaveLength(1);+ expect(out[0].subjectType).toBe('unknown');+ });+});diff --git a/tests/x402-onchain-identity-verify.test.js b/tests/x402-onchain-identity-verify.test.jsnew file mode 100644index 000000000..99e4850fe--- /dev/null+++ b/tests/x402-onchain-identity-verify.test.js@@ -0,0 +1,313 @@+import { describe, it, expect } from 'vitest';+import Ajv2020 from 'ajv/dist/2020.js';+import addFormats from 'ajv-formats';++import { classifyIdentity, verifyClaim } from '../api/_lib/x402/identity-claim-verify.js';+import {+ BAZAAR,+ INPUT_SCHEMA,+ INPUT_EXAMPLE,+ OUTPUT_SCHEMA,+ OUTPUT_EXAMPLE,+} from '../api/x402/onchain-identity-verify.js';++// Real EVM addresses/names used only as fixtures — no mainnet mint hardcoded.+const VITALIK = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';+const OTHER_EVM = '0x1111111111111111111111111111111111111111';+const SOL_WALLET = 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk';+const SOL_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump'; // $THREE+const OTHER_SOL = 'THREEsynthetic1111111111111111111111111PayTo';++// Fully-stubbed deps so the whole verdict matrix is exercised offline.+function stubDeps(over = {}) {+ return {+ resolveEns: async () => null,+ reverseEns: async () => null,+ resolveSns: async () => null,+ reverseSns: async () => null,+ getEvmCode: async () => '0x',+ getEvmContractCreation: async () => ({ deployer: null, txHash: null, reason: 'no_explorer_key' }),+ getEvmOwner: async () => null,+ getSolanaMintInfo: async () => null,+ lookupThreewsIndex: async () => null,+ resolveErc8004: async () => ({ owner: null, wallet: null }),+ ...over,+ };+}++describe('classifyIdentity', () => {+ it('detects each identity type', () => {+ expect(classifyIdentity('7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55').type).toBe('threews_agent_id');+ expect(classifyIdentity('vitalik.eth').type).toBe('ens');+ expect(classifyIdentity('bonfida.sol').type).toBe('sns');+ expect(classifyIdentity(VITALIK).type).toBe('evm_address');+ expect(classifyIdentity(SOL_WALLET).type).toBe('solana_address');+ expect(classifyIdentity('eip155:8453:42')).toMatchObject({ type: 'erc8004', chainId: 8453, agentId: '42' });+ expect(classifyIdentity('8453:42')).toMatchObject({ type: 'erc8004', chainId: 8453, agentId: '42' });+ // bare integer only becomes erc8004 with an EVM chain hint+ expect(classifyIdentity('42').type).toBe('unknown');+ expect(classifyIdentity('42', 'eip155:8453')).toMatchObject({ type: 'erc8004', agentId: '42' });+ expect(classifyIdentity('¯\\_(ツ)_/¯').type).toBe('unknown');+ });+});++describe('ENS claims', () => {+ it('verifies true when the name resolves to the claimed address', async () => {+ const r = await verifyClaim(+ { identity: 'vitalik.eth', address: VITALIK, chain: 'eip155:1' },+ stubDeps({ resolveEns: async () => VITALIK.toLowerCase(), reverseEns: async () => 'vitalik.eth' }),+ );+ expect(r.verified).toBe(true);+ expect(r.identity_type).toBe('ens');+ expect(r.evidence.some((e) => e.kind === 'ens_forward_resolution')).toBe(true);+ expect(r.evidence.some((e) => e.kind === 'ens_reverse_resolution')).toBe(true);+ });++ it('verifies false when the name resolves to a different address', async () => {+ const r = await verifyClaim(+ { identity: 'vitalik.eth', address: OTHER_EVM },+ stubDeps({ resolveEns: async () => VITALIK.toLowerCase() }),+ );+ expect(r.verified).toBe(false);+ expect(r.caveats.length).toBeGreaterThan(0);+ });++ it('is unverifiable (never true) when the name does not resolve', async () => {+ const r = await verifyClaim({ identity: 'ghost.eth', address: VITALIK }, stubDeps());+ expect(r.verified).toBe('unverifiable');+ expect(r.verified).not.toBe(true);+ });+});++describe('SNS claims', () => {+ it('verifies true when the .sol name resolves to the claimed wallet', async () => {+ const r = await verifyClaim(+ { identity: 'bonfida.sol', address: SOL_WALLET },+ stubDeps({ resolveSns: async () => SOL_WALLET, reverseSns: async () => 'bonfida.sol' }),+ );+ expect(r.verified).toBe(true);+ expect(r.method).toBe('sns-resolution');+ });++ it('is unverifiable when the .sol name does not resolve', async () => {+ const r = await verifyClaim({ identity: 'nope.sol', address: SOL_WALLET }, stubDeps());+ expect(r.verified).toBe('unverifiable');+ });+});++describe('EVM contract control', () => {+ it('verifies true when the deployer matches', async () => {+ const r = await verifyClaim(+ { identity: VITALIK, address: OTHER_EVM, chain: 'eip155:8453' },+ stubDeps({+ getEvmCode: async () => '0x6080604052',+ getEvmContractCreation: async () => ({ deployer: VITALIK.toLowerCase(), txHash: `0x${'a'.repeat(64)}` }),+ }),+ );+ expect(r.verified).toBe(true);+ expect(r.evidence.some((e) => e.kind === 'evm_deploy_tx')).toBe(true);+ expect(r.evidence.some((e) => e.kind === 'evm_deployer')).toBe(true);+ });++ it('verifies true when owner() matches even without a deployer lookup', async () => {+ const r = await verifyClaim(+ { identity: VITALIK, address: OTHER_EVM, chain: 'eip155:8453' },+ stubDeps({+ getEvmCode: async () => '0x6080',+ getEvmOwner: async () => VITALIK.toLowerCase(),+ }),+ );+ expect(r.verified).toBe(true);+ expect(r.evidence.some((e) => e.kind === 'evm_owner')).toBe(true);+ });++ it('verifies false when a contract is read but neither deployer nor owner matches', async () => {+ const r = await verifyClaim(+ { identity: VITALIK, address: OTHER_EVM, chain: 'eip155:8453' },+ stubDeps({+ getEvmCode: async () => '0x6080',+ getEvmContractCreation: async () => ({ deployer: OTHER_EVM, txHash: `0x${'b'.repeat(64)}` }),+ getEvmOwner: async () => OTHER_EVM,+ }),+ );+ expect(r.verified).toBe(false);+ });++ it('is unverifiable for a contract when nothing could be read (no key, no owner)', async () => {+ const r = await verifyClaim(+ { identity: VITALIK, address: OTHER_EVM, chain: 'eip155:8453' },+ stubDeps({ getEvmCode: async () => '0x6080' }),+ );+ expect(r.verified).toBe('unverifiable');+ });++ it('is unverifiable when the address is an EOA (two distinct wallets cannot be linked)', async () => {+ const r = await verifyClaim(+ { identity: VITALIK, address: OTHER_EVM, chain: 'eip155:8453' },+ stubDeps({ getEvmCode: async () => '0x' }),+ );+ expect(r.verified).toBe('unverifiable');+ });++ it('verifies true trivially when identity and address are the same account', async () => {+ const r = await verifyClaim({ identity: VITALIK, address: VITALIK }, stubDeps());+ expect(r.verified).toBe(true);+ expect(r.method).toBe('evm-same-address');+ });+});++describe('Solana mint control', () => {+ it('verifies true when the identity is the mint authority', async () => {+ const r = await verifyClaim(+ { identity: SOL_WALLET, address: SOL_MINT },+ stubDeps({ getSolanaMintInfo: async () => ({ mintAuthority: SOL_WALLET, freezeAuthority: null, updateAuthority: null }) }),+ );+ expect(r.verified).toBe(true);+ expect(r.evidence.some((e) => e.kind === 'solana_mint_authority')).toBe(true);+ });++ it('verifies true when the identity is the metadata update authority', async () => {+ const r = await verifyClaim(+ { identity: SOL_WALLET, address: SOL_MINT },+ stubDeps({ getSolanaMintInfo: async () => ({ mintAuthority: OTHER_SOL, freezeAuthority: null, updateAuthority: SOL_WALLET }) }),+ );+ expect(r.verified).toBe(true);+ });++ it('verifies false when no authority matches', async () => {+ const r = await verifyClaim(+ { identity: SOL_WALLET, address: SOL_MINT },+ stubDeps({ getSolanaMintInfo: async () => ({ mintAuthority: OTHER_SOL, freezeAuthority: null, updateAuthority: OTHER_SOL }) }),+ );+ expect(r.verified).toBe(false);+ });++ it('is unverifiable when the address is not a readable mint', async () => {+ const r = await verifyClaim({ identity: SOL_WALLET, address: OTHER_SOL }, stubDeps());+ expect(r.verified).toBe('unverifiable');+ });++ it('is unverifiable when authorities are all renounced', async () => {+ const r = await verifyClaim(+ { identity: SOL_WALLET, address: SOL_MINT },+ stubDeps({ getSolanaMintInfo: async () => ({ mintAuthority: null, freezeAuthority: null, updateAuthority: null }) }),+ );+ expect(r.verified).toBe('unverifiable');+ });+});++describe('ERC-8004 claims', () => {+ it('verifies true when ownerOf matches the claimed address', async () => {+ const r = await verifyClaim(+ { identity: 'eip155:8453:42', address: VITALIK },+ stubDeps({ resolveErc8004: async () => ({ owner: VITALIK.toLowerCase(), wallet: null, registry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432' }) }),+ );+ expect(r.verified).toBe(true);+ expect(r.evidence.some((e) => e.kind === 'erc8004_owner_of')).toBe(true);+ expect(r.evidence.some((e) => e.kind === 'erc8004_registration')).toBe(true);+ });++ it('verifies false when the registered owner/wallet differ', async () => {+ const r = await verifyClaim(+ { identity: 'eip155:8453:42', address: VITALIK },+ stubDeps({ resolveErc8004: async () => ({ owner: OTHER_EVM, wallet: OTHER_EVM }) }),+ );+ expect(r.verified).toBe(false);+ });++ it('is unverifiable when the registry has no record', async () => {+ const r = await verifyClaim({ identity: 'eip155:8453:42', address: VITALIK }, stubDeps());+ expect(r.verified).toBe('unverifiable');+ });+});++describe('three.ws agent_id claims', () => {+ const AGENT = '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55';++ it('verifies true against the canonical deploy record', async () => {+ const r = await verifyClaim(+ { identity: AGENT, address: SOL_MINT },+ stubDeps({+ lookupThreewsIndex: async () => ({+ sol_mint_address: SOL_MINT,+ onchain: {+ chain: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ family: 'solana',+ contract_or_mint: SOL_MINT,+ tx_hash: '4kHTPp9synthetic',+ owner: SOL_WALLET,+ metadata_uri: 'https://arweave.net/synthetic',+ confirmed_at: '2026-04-30T14:08:22Z',+ },+ }),+ }),+ );+ expect(r.verified).toBe(true);+ expect(r.evidence.some((e) => e.kind === 'threews_deploy_tx')).toBe(true);+ });++ it('verifies false when the agent owns a different mint than claimed', async () => {+ const r = await verifyClaim(+ { identity: AGENT, address: OTHER_SOL },+ stubDeps({+ lookupThreewsIndex: async () => ({+ onchain: { chain: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', contract_or_mint: SOL_MINT, tx_hash: 'x' },+ }),+ }),+ );+ expect(r.verified).toBe(false);+ });++ it('is unverifiable when the agent_id is unknown', async () => {+ const r = await verifyClaim({ identity: AGENT, address: SOL_MINT }, stubDeps());+ expect(r.verified).toBe('unverifiable');+ });+});++describe('no-evidence discipline', () => {+ it('an unclassifiable identity is unverifiable, never true', async () => {+ const r = await verifyClaim({ identity: 'not-an-identity', address: VITALIK }, stubDeps());+ expect(r.verified).toBe('unverifiable');+ expect(r.identity_type).toBe('unknown');+ });++ it('every branch that returns true carries at least one evidence item', async () => {+ const cases = [+ verifyClaim({ identity: 'vitalik.eth', address: VITALIK }, stubDeps({ resolveEns: async () => VITALIK.toLowerCase() })),+ verifyClaim({ identity: SOL_WALLET, address: SOL_MINT }, stubDeps({ getSolanaMintInfo: async () => ({ mintAuthority: SOL_WALLET }) })),+ ];+ for (const r of await Promise.all(cases)) {+ if (r.verified === true) expect(r.evidence.length).toBeGreaterThan(0);+ }+ });+});++describe('discovery schema (CDP validation the verify script runs)', () => {+ const ajv = new Ajv2020({ allErrors: true, strict: false });+ addFormats(ajv);++ it('bazaar.info validates against bazaar.schema', () => {+ const validate = ajv.compile(BAZAAR.schema);+ const ok = validate(BAZAAR.info);+ if (!ok) console.error(validate.errors);+ expect(ok).toBe(true);+ });++ it('input example validates against the input schema', () => {+ const validate = ajv.compile(INPUT_SCHEMA);+ expect(validate(INPUT_EXAMPLE)).toBe(true);+ });++ it('output example validates against the output schema', () => {+ const validate = ajv.compile(OUTPUT_SCHEMA);+ const ok = validate(OUTPUT_EXAMPLE);+ if (!ok) console.error(validate.errors);+ expect(ok).toBe(true);+ });++ it('a live unverifiable result also validates against the output schema', async () => {+ const validate = ajv.compile(OUTPUT_SCHEMA);+ const r = await verifyClaim({ identity: 'ghost.eth', address: VITALIK }, stubDeps());+ expect(validate(r)).toBe(true);+ });+});diff --git a/tests/x402-pump-launch-listing.test.js b/tests/x402-pump-launch-listing.test.jsnew file mode 100644index 000000000..20142e112--- /dev/null+++ b/tests/x402-pump-launch-listing.test.js@@ -0,0 +1,140 @@+// Pump Launcher (/api/x402/pump-launch) — listing quality + input validation.+//+// This endpoint deploys a real pump.fun token for real SOL, so these tests+// deliberately NEVER invoke the paid handler or broadcast anything. They lock+// down the things that make the listing sellable and safe to call blind:+// 1. the discovery listing sells the use-case and links the free funnel,+// 2. the advertised price matches the handler's default ($5.00),+// 3. input validation rejects the bad shapes (missing name/symbol, and a body+// with neither metadataUri nor imageUrl) BEFORE any launch could happen,+// 4. the documented input example satisfies the published INPUT_SCHEMA — i.e.+// the schema is complete enough for an agent to call blind.+//+// The bazaar.info ⇄ bazaar.schema self-validation (CDP-acceptance) is covered+// end-to-end by `npm run verify:x402` against the discovery doc, so it is not+// re-checked here.+//+// The handler transitively imports the Neon client, the Solana launcher, and the+// CDP x402 SDK — none of which this test needs. We mock those heavy leaf modules+// so the test exercises only the pure listing metadata + the zod body schema.++import { describe, it, expect, vi } from 'vitest';+import Ajv2020 from 'ajv/dist/2020.js';+import addFormats from 'ajv-formats';++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));+vi.mock('../api/_lib/http.js', () => ({ readJson: vi.fn() }));+vi.mock('../api/_lib/pump-launch.js', () => ({+ loadLauncherKeypair: vi.fn(),+ uploadPumpMetadata: vi.fn(),+ launchPumpToken: vi.fn(),+}));+vi.mock('../api/_lib/x402-paid-endpoint.js', () => ({ paidEndpoint: (cfg) => cfg }));+vi.mock('../api/_lib/x402-spec.js', () => ({ buildBazaarSchema: () => ({}) }));+vi.mock('../api/_lib/x402/access-control.js', () => ({ installAccessControl: () => ({}) }));+vi.mock('../api/_lib/x402/bazaar-helpers.js', () => ({ withService: (x) => x }));++const { DESCRIPTION, PRICE_ATOMICS, INPUT_SCHEMA, OUTPUT_SCHEMA, BAZAAR, bodySchema } = await import(+ '../api/x402/pump-launch.js'+);++const ajv = new Ajv2020({ allErrors: true, strict: false });+addFormats(ajv);++describe('pump-launch listing — description sells the use-case + funnel', () => {+ it('leads with the no-SOL / no-account use-case', () => {+ expect(DESCRIPTION).toMatch(/pump\.fun/i);+ expect(DESCRIPTION).toMatch(/no SOL/i);+ expect(DESCRIPTION).toMatch(/no (wallet|account)/i);+ expect(DESCRIPTION).toMatch(/USDC/);+ });++ it('names every input and the output shape', () => {+ for (const field of ['name', 'symbol', 'metadataUri', 'imageUrl', 'creator', 'vanity']) {+ expect(DESCRIPTION).toMatch(new RegExp(field, 'i'));+ }+ expect(DESCRIPTION).toMatch(/mint/i);+ expect(DESCRIPTION).toMatch(/signature/i);+ });++ it('wires the free → paid funnel to /api/crypto/symbol and /api/crypto/launches', () => {+ expect(DESCRIPTION).toContain('/api/crypto/symbol');+ expect(DESCRIPTION).toContain('/api/crypto/launches');+ });+});++describe('pump-launch listing — price parity', () => {+ it('advertises the $5.00 default (5000000 USDC atomics)', () => {+ // Matches the mirror in api/wk.js (acceptsForPrice('5000000', …)) so the+ // live 402 and the discovery doc never drift.+ expect(PRICE_ATOMICS).toBe('5000000');+ });+});++describe('pump-launch listing — schema completeness (call it blind)', () => {+ it('requires name + symbol and exactly one of metadataUri / imageUrl', () => {+ expect(INPUT_SCHEMA.required).toEqual(expect.arrayContaining(['name', 'symbol']));+ expect(INPUT_SCHEMA.oneOf).toEqual([+ { required: ['metadataUri'] },+ { required: ['imageUrl'] },+ ]);+ });++ it('guarantees the load-bearing outputs', () => {+ expect(OUTPUT_SCHEMA.required).toEqual(+ expect.arrayContaining(['mint', 'signature', 'metadataUri', 'pumpfun_url']),+ );+ });++ it('the published input example satisfies INPUT_SCHEMA', () => {+ const validate = ajv.compile(INPUT_SCHEMA);+ const example = BAZAAR.info.input.body;+ const ok = validate(example);+ expect(validate.errors, JSON.stringify(validate.errors)).toBeNull();+ expect(ok).toBe(true);+ });+});++describe('pump-launch listing — input validation rejects bad shapes before launch', () => {+ const valid = {+ name: 'Helios',+ symbol: 'HELIO',+ imageUrl: 'https://example.com/helios.png',+ };++ it('accepts a minimal valid body (name + symbol + imageUrl)', () => {+ expect(bodySchema.safeParse(valid).success).toBe(true);+ });++ it('accepts a valid body with metadataUri instead of imageUrl', () => {+ const { imageUrl, ...rest } = valid;+ expect(+ bodySchema.safeParse({ ...rest, metadataUri: 'https://ipfs.io/ipfs/QmExample' }).success,+ ).toBe(true);+ });++ it('rejects a missing name', () => {+ const { name, ...rest } = valid;+ expect(bodySchema.safeParse(rest).success).toBe(false);+ });++ it('rejects a missing symbol', () => {+ const { symbol, ...rest } = valid;+ expect(bodySchema.safeParse(rest).success).toBe(false);+ });++ it('rejects a body with neither metadataUri nor imageUrl', () => {+ const r = bodySchema.safeParse({ name: 'Helios', symbol: 'HELIO' });+ expect(r.success).toBe(false);+ expect(JSON.stringify(r.error.issues)).toMatch(/metadataUri or imageUrl/);+ });++ it('rejects a non-base58 vanity prefix', () => {+ expect(bodySchema.safeParse({ ...valid, vanityPrefix: '0OIl' }).success).toBe(false);+ });+});diff --git a/vercel.json b/vercel.jsonindex e4c09619e..54a9937e7 100644--- a/vercel.json+++ b/vercel.json@@ -45,6 +45,14 @@"includeFiles": "{node_modules/@img/sharp-libvips-linux-x64/**,node_modules/@img/sharp-linux-x64/**}","maxDuration": 300},+ "{api/crypto/index,api/crypto/openapi}.js": {+ "includeFiles": "api/_lib/crypto-catalog/**",+ "maxDuration": 30+ },+ "{api/3d/index,api/3d/openapi}.js": {+ "includeFiles": "api/_lib/3d-catalog/**",+ "maxDuration": 30+ },"api/widgets/[id]/knowledge-process.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 300@@ -224,6 +232,22 @@"src": "/viability/","dest": "/viability.html"},+ {+ "src": "/crypto",+ "dest": "/crypto.html"+ },+ {+ "src": "/crypto/",+ "dest": "/crypto.html"+ },+ {+ "src": "/3d",+ "dest": "/3d.html"+ },+ {+ "src": "/3d/",+ "dest": "/3d.html"+ },{"src": "/gallery-picker","dest": "/gallery-picker.html"@@ -364,6 +388,18 @@"src": "/openapi\\.json","dest": "/api/openapi-json"},+ {+ "src": "/api/crypto/openapi\\.json",+ "dest": "/api/crypto/openapi"+ },+ {+ "src": "/api/3d/openapi\\.json",+ "dest": "/api/3d/openapi"+ },+ {+ "src": "/docs/3d-api/?",+ "dest": "/3d.html"+ },{"src": "/api/features\\.json","dest": "/api/features"diff --git a/vite.config.js b/vite.config.jsindex d9cd44b7d..781f7de2c 100644--- a/vite.config.js+++ b/vite.config.js@@ -448,6 +448,7 @@ const appConfig = {'pump-dashboard': resolve(__dirname, 'pages/pump-dashboard.html'),autopilot: resolve(__dirname, 'pages/autopilot.html'),'pump-visualizer': resolve(__dirname, 'pages/pump-visualizer.html'),+ crypto: resolve(__dirname, 'pages/crypto.html'),three: resolve(__dirname, 'pages/three.html'),'three-live': resolve(__dirname, 'pages/three-live.html'),'three-token': resolve(__dirname, 'pages/three-token.html'),