Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: api endpoint updates
nirholased997c09ab64
diff --git a/api/_lib/feed.js b/api/_lib/feed.jsindex 7c6b7599c..e9cef9931 100644--- a/api/_lib/feed.js+++ b/api/_lib/feed.js@@ -31,6 +31,7 @@import { Redis } from '@upstash/redis';import { env } from './env.js';+import { insertNotification } from './notify.js';const FEED_KEY = 'feed:events';const MAX_EVENTS = 200; // capped list — the widget shows ~30; we keep headroom@@ -41,6 +42,25 @@ export const ALLOWED_TYPES = new Set(['level-up','world-join','jackpot',+ 'payment', // skill/service payment confirmed; { usdcAtomic, recipientLabel, txSig, explorerUrl }+]);++// Per-user notification types: stored in user_notifications (DB), never in the+// public feed:events list. Extend here so one place owns the full vocabulary.+export const USER_EVENT_TYPES = new Set([+ 'payment-earned', // agent owner received an x402 payment+ 'sale', // marketplace asset sale+ 'embed', // someone embedded the creator's agent+ 'remix', // someone remixed a creation+ 'reply', // new reply to an agent interaction+ // types already produced by purchase-confirm / buy-asset confirm flows+ 'skill_purchased',+ 'skill_purchase_confirmed',+ 'asset_purchased',+ 'asset_purchase_confirmed',+ 'asset_payment_mismatch',+ 'skill_payment_mismatch',+ 'referral_earned',]);let _redis = null;@@ -62,6 +82,25 @@ function eventId(ts) {return `${ts.toString(36)}-${_seq.toString(36)}`;}+// Publish a per-user notification event. Writes to user_notifications (DB),+// never to the public feed:events list. Preserves the shared event shape+// { id, type, ts, actor, ...typeSpecific } plus `read` flag and a `link` for+// click-through. Fire-and-forget: never throws.+//+// @param {string} userId — recipient's user id+// @param {object} event — { type (USER_EVENT_TYPES), actor, link, ...rest }+export function publishUserEvent(userId, event) {+ if (!userId || !event || !USER_EVENT_TYPES.has(event.type)) return;+ const ts = Number.isFinite(event.ts) ? event.ts : Date.now();+ const payload = {+ ...event,+ ts,+ id: event.id || eventId(ts),+ link: event.link || null,+ };+ insertNotification(userId, event.type, payload);+}+// Append an event to the feed. Returns the stored record (with id + ts filled// in) or null on a no-op (unknown type, Redis down, malformed input). Never// throws — every caller is fire-and-forget on a non-critical path.@@ -80,6 +119,28 @@ export async function publishFeedEvent(event) {}}+/**+ * Convenience wrapper: publish a 'payment' feed event from a confirmed skill/service payment.+ * All params best-effort; the event is fire-and-forget on a non-critical path.+ *+ * @param {object} opts+ * @param {string} opts.actor short display label (truncated wallet / agent name)+ * @param {number} [opts.usdcAtomic] payment amount in micro-USDC (1e6 scale)+ * @param {string} [opts.recipientLabel] "Luna's creator", "Oracle", etc.+ * @param {string} [opts.txSig] Solana tx signature+ * @param {string} [opts.explorerUrl] full Solscan/explorer URL+ */+export function pushPaymentEvent({ actor, usdcAtomic, recipientLabel, txSig, explorerUrl } = {}) {+ return publishFeedEvent({+ type: 'payment',+ actor: String(actor || 'user').slice(0, 32),+ usdcAtomic: usdcAtomic != null ? Number(usdcAtomic) : undefined,+ recipientLabel: recipientLabel ? String(recipientLabel).slice(0, 40) : undefined,+ txSig: txSig ? String(txSig).slice(0, 88) : undefined,+ explorerUrl: explorerUrl ? String(explorerUrl).slice(0, 200) : undefined,+ });+}+// Short-lived in-process read cache. The widget is mounted on every page and// polls this endpoint continuously, so without dedup each poll becomes a Redis// command — at platform scale that alone can exhaust the Upstash request quota.diff --git a/api/_lib/zauth.js b/api/_lib/zauth.jsindex 67e7af596..25834dd3a 100644--- a/api/_lib/zauth.js+++ b/api/_lib/zauth.js@@ -74,11 +74,49 @@ function buildMiddleware() {// starts immediately; the `drain()` helper below keeps the lambda// alive long enough for that POST to complete.const includeBodies = env.ZAUTH_INCLUDE_BODIES === '1';+ const evmKey = env.ZAUTH_REFUND_PRIVATE_KEY || undefined;+ const solKey = env.ZAUTH_SOLANA_PRIVATE_KEY || undefined;+ const refundEnabled = Boolean(evmKey || solKey);+const mw = zauthProvider(apiKey, {environment: resolveEnvironment(),shouldMonitor: shouldMonitorReq,debug: env.ZAUTH_DEBUG === '1',batching: { maxBatchSize: 1, maxBatchWaitMs: 0, retry: false },+ // Validate responses so the dashboard has health signal beyond status+ // codes. Our paid routes return JSON objects — reject empty collections+ // and bodies that only contain error fields.+ validation: {+ minResponseSize: 2,+ rejectEmptyCollections: true,+ errorFields: ['error', 'error_description'],+ },+ // Auto-refund callers who pay and receive a server error or empty body.+ // Enabled only when at least one refund keypair is present. Caps are+ // set above our highest tool price ($0.05) with conservative daily/+ // monthly ceilings; all three are overridable via env without a deploy.+ refund: {+ enabled: refundEnabled,+ privateKey: evmKey,+ solanaPrivateKey: solKey,+ maxRefundUsd: Number(process.env.ZAUTH_REFUND_MAX_USD) || 0.10,+ dailyCapUsd: Number(process.env.ZAUTH_REFUND_DAILY_CAP_USD) || 25.00,+ monthlyCapUsd: Number(process.env.ZAUTH_REFUND_MONTHLY_CAP_USD) || 250.00,+ triggers: {+ serverError: true,+ emptyResponse: true,+ timeout: true,+ schemaValidation: false,+ },+ onRefund: (r) => {+ console.log(+ `[zauth] refund executed: $${r.amountUsd} → ${r.recipient} on ${r.network} tx:${r.txHash}`,+ );+ },+ onRefundError: (e) => {+ console.error(`[zauth] refund failed for ${e.url}: ${e.error}`);+ },+ },// Privacy: the monitored routes are payment and MCP endpoints. Ship// status/timing/validation telemetry, but NOT the request/response// bodies (payment payloads, tool args) unless explicitly opted in.@@ -107,7 +145,7 @@ function buildMiddleware() {});trackZauthFetch();if (env.ZAUTH_DEBUG === '1' && !_bootLogged) {- console.log('[zauth] middleware initialized');+ console.log(`[zauth] middleware initialized (refunds:${refundEnabled ? 'on' : 'off'})`);_bootLogged = true;}return mw;@@ -143,6 +181,11 @@ export function status() {keyPrefix: apiKey ? apiKey.slice(0, 14) : null,environment: resolveEnvironment(),debug: env.ZAUTH_DEBUG === '1',+ refunds: {+ enabled: Boolean(env.ZAUTH_REFUND_PRIVATE_KEY || env.ZAUTH_SOLANA_PRIVATE_KEY),+ evm: Boolean(env.ZAUTH_REFUND_PRIVATE_KEY),+ solana: Boolean(env.ZAUTH_SOLANA_PRIVATE_KEY),+ },};}diff --git a/api/agent-detail-og.js b/api/agent-detail-og.jsnew file mode 100644index 000000000..05251c0fe--- /dev/null+++ b/api/agent-detail-og.js@@ -0,0 +1,145 @@+/**+ * SSR OG page for agent detail (/agents/:id)+ * -------------------------------------------+ * GET /api/agent-detail-og?id=<agentId>+ *+ * Wired via vercel.json: when a social crawler hits /agents/<uuid>,+ * a User-Agent "has" condition rewrites to this endpoint. Returns a minimal+ * HTML page with OG + Twitter Card + Farcaster Frame meta so shared agent+ * links unfurl with a real image and description.+ *+ * Real browsers never reach this route — the rewrite only fires for known+ * bot User-Agents. Mirrors the pattern in api/app-og.js.+ */++import { sql } from './_lib/db.js';+import { cors, wrap } from './_lib/http.js';+import { env } from './_lib/env.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;++ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('id');+ const origin = env.APP_ORIGIN || 'https://three.ws';++ if (!agentId || !UUID_RE.test(agentId)) {+ return passthrough(res, origin);+ }++ let agent;+ try {+ [agent] = await sql`+ SELECT i.id, i.name, i.description, i.skills,+ a.thumbnail_key AS avatar_thumbnail_key+ FROM agent_identities i+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL+ WHERE i.id = ${agentId} AND i.deleted_at IS NULL+ LIMIT 1+ `;+ } catch {+ return passthrough(res, origin);+ }++ if (!agent) return passthrough(res, origin);++ const title = agent.name || 'Agent';+ const baseDesc = agent.description || 'An AI agent on three.ws — with a body, a place, and an identity.';+ const skills = agent.skills || [];+ const skillSuffix = skills.length+ ? ` Skills: ${skills.slice(0, 4).join(', ')}${skills.length > 4 ? '…' : ''}.`+ : '';+ const desc = baseDesc + skillSuffix;++ const { publicUrl } = await import('./_lib/r2.js');+ const thumbnailUrl = agent.avatar_thumbnail_key ? publicUrl(agent.avatar_thumbnail_key) : null;+ const ogImage = thumbnailUrl || `${origin}/api/agent/${agentId}/og`;++ const pageUrl = `${origin}/agents/${agentId}`;++ res.statusCode = 200;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=600, stale-while-revalidate=3600');+ res.end(renderHtml({ agentId, title, desc, pageUrl, ogImage, origin }));+});++function passthrough(res, origin) {+ res.statusCode = 302;+ res.setHeader('location', `${origin}/agents`);+ res.setHeader('cache-control', 'no-cache');+ res.end();+}++function renderHtml({ agentId, title, desc, pageUrl, ogImage, origin }) {+ const t = esc(title);+ const d = esc(desc);+ const agentUrl = `/agents/${agentId}`;+ return `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="X-UA-Compatible" content="IE=edge">+ <title>${t} — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">+ <meta name="description" content="${d}">+ <meta name="theme-color" content="#06070a">++ <meta property="og:type" content="profile">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:title" content="${t} — three.ws">+ <meta property="og:description" content="${d}">+ <meta property="og:url" content="${esc(pageUrl)}">+ <meta property="og:image" content="${esc(ogImage)}">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:alt" content="${t} on three.ws">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="${t} — three.ws">+ <meta name="twitter:description" content="${d}">+ <meta name="twitter:image" content="${esc(ogImage)}">+ <meta name="twitter:creator" content="@trythreews">++ <meta property="fc:frame" content="vNext">+ <meta property="fc:frame:image" content="${esc(ogImage)}">+ <meta property="fc:frame:image:aspect_ratio" content="1.91:1">+ <meta property="fc:frame:button:1" content="Meet ${t}">+ <meta property="fc:frame:button:1:action" content="link">+ <meta property="fc:frame:button:1:target" content="${esc(pageUrl)}">++ <link rel="canonical" href="${esc(pageUrl)}">+ <link rel="shortcut icon" href="/favicon.ico">++ <style>+ html,body{margin:0;padding:0;background:#06070a;color:#e0e0e0;font-family:Inter,system-ui,sans-serif;height:100%}+ .shell{display:grid;place-items:center;min-height:100vh;text-align:center;padding:2rem;gap:1rem}+ .shell a{color:#e0e0e0;text-decoration:underline;text-underline-offset:3px}+ .spinner{width:28px;height:28px;border:2px solid rgba(255,255,255,0.1);border-top-color:rgba(255,255,255,0.6);border-radius:50%;animation:spin 0.9s linear infinite;margin:0 auto}+ @keyframes spin{to{transform:rotate(360deg)}}+ p{margin:0;color:rgba(255,255,255,0.5);font-size:14px}+ </style>+</head>+<body>+ <noscript>+ <div class="shell">+ <h1>${t}</h1>+ <p>${d}</p>+ <p><a href="${esc(pageUrl)}">View agent</a> · <a href="${esc(origin)}/agents">Browse agents</a></p>+ </div>+ </noscript>+ <div class="shell" aria-live="polite">+ <div class="spinner" aria-hidden="true"></div>+ <p>Loading ${t}…</p>+ </div>+ <script>(function(){window.location.replace(${JSON.stringify(agentUrl)});})()</script>+</body>+</html>`;+}++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}diff --git a/api/agents/payments/[action].js b/api/agents/payments/[action].jsindex 8c6e55c09..2f40f7364 100644--- a/api/agents/payments/[action].js+++ b/api/agents/payments/[action].js@@ -32,6 +32,7 @@ import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';import { randomToken } from '../../_lib/crypto.js';+import { insertNotification } from '../../_lib/notify.js';function rpcUrl(cluster) {return cluster === 'devnet'@@ -422,6 +423,22 @@ async function handlePayConfirm(req, res) {returning id, agent_id, amount, currency_mint, paid_at`;+ // Fire-and-forget: notify the agent owner that they received a payment.+ sql`select user_id from agent_identities where id = ${updated.agent_id} and deleted_at is null limit 1`+ .then(([row]) => {+ if (row?.user_id) {+ insertNotification(row.user_id, 'payment-earned', {+ agent_id: updated.agent_id,+ amount: updated.amount.toString(),+ currency_mint: updated.currency_mint,+ tx_signature: body.tx_signature,+ actor: user.display_name || user.username || 'a user',+ link: `/agent/${updated.agent_id}`,+ });+ }+ })+ .catch(() => {});+return json(res, 200, { ok: true, intent: updated });}diff --git a/api/dashboard/prefs.js b/api/dashboard/prefs.jsindex 04a83ae2d..6a922a735 100644--- a/api/dashboard/prefs.js+++ b/api/dashboard/prefs.js@@ -1,8 +1,9 @@/*** Dashboard Preferences* ---------------------- * GET /api/dashboard/prefs — returns the signed-in user's prefs JSON- * POST /api/dashboard/prefs — replaces the user's prefs JSON+ * GET /api/dashboard/prefs — returns the signed-in user's prefs JSON+ * POST /api/dashboard/prefs — replaces the user's prefs JSON body: { prefs: {...} }+ * PATCH /api/dashboard/prefs — merges partial prefs body: { prefs: {...} }** Backed by the user_prefs table. localStorage remains the primary client* store; this endpoint provides a durable backup so prefs follow the user@@ -26,8 +27,8 @@ const prefsBody = z.object({});export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET', 'POST'])) return;+ if (cors(req, res, { methods: 'GET,POST,PATCH,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST', 'PATCH'])) return;const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');@@ -39,19 +40,35 @@ export default wrap(async (req, res) => {return json(res, 200, { prefs: row?.prefs || {} });}- // POST — replace prefsconst rl = await limits.prefsWrite(auth.userId);if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');- const { prefs } = parse(prefsBody, await readJson(req));+ const { prefs: incoming } = parse(prefsBody, await readJson(req));- await sql`- INSERT INTO user_prefs (user_id, prefs, updated_at)- VALUES (${auth.userId}, ${JSON.stringify(prefs)}::jsonb, now())- ON CONFLICT (user_id) DO UPDATE SET- prefs = EXCLUDED.prefs,- updated_at = now()- `;+ if (req.method === 'PATCH') {+ // Merge: read existing prefs, shallow-merge incoming keys, write back.+ const [row] = await sql`SELECT prefs FROM user_prefs WHERE user_id = ${auth.userId}`;+ const merged = { ...(row?.prefs || {}), ...incoming };+ if (JSON.stringify(merged).length > MAX_BYTES) {+ return error(res, 400, 'prefs_too_large', `prefs exceed ${MAX_BYTES} bytes`);+ }+ await sql`+ INSERT INTO user_prefs (user_id, prefs, updated_at)+ VALUES (${auth.userId}, ${JSON.stringify(merged)}::jsonb, now())+ ON CONFLICT (user_id) DO UPDATE SET+ prefs = EXCLUDED.prefs,+ updated_at = now()+ `;+ } else {+ // POST — replace prefs entirely+ await sql`+ INSERT INTO user_prefs (user_id, prefs, updated_at)+ VALUES (${auth.userId}, ${JSON.stringify(incoming)}::jsonb, now())+ ON CONFLICT (user_id) DO UPDATE SET+ prefs = EXCLUDED.prefs,+ updated_at = now()+ `;+ }return json(res, 200, { ok: true });});diff --git a/api/feature-og.js b/api/feature-og.jsnew file mode 100644index 000000000..38fd1f25b--- /dev/null+++ b/api/feature-og.js@@ -0,0 +1,169 @@+// api/feature-og.js — Open Graph image for /features/<slug> landing pages.+// GET /api/feature-og?feature=forge&title=...&sub=...+//+// Returns a 1200×630 SVG card branded for the named feature.+// Self-contained SVG so all OG crawlers (Slack, X, Discord, iMessage) render it.++import { cors, wrap } from './_lib/http.js';++const CACHE = 'public, max-age=86400, s-maxage=604800';++const FEATURE_META = {+ forge: {+ label: 'Forge',+ route: '/forge',+ accent: '#a78bfa',+ icon: '⬡',+ tagline: 'Text → 3D Model',+ },+ scan: {+ label: 'Scan',+ route: '/scan',+ accent: '#6ee7ff',+ icon: '◎',+ tagline: 'Selfie → Rigged Avatar',+ },+ play: {+ label: 'Play',+ route: '/play',+ accent: '#4ade80',+ icon: '◈',+ tagline: 'Live 3D Coin Worlds',+ },+ walk: {+ label: 'Walk',+ route: '/walk',+ accent: '#fb923c',+ icon: '◉',+ tagline: '3D Avatar + AR',+ },+ studio: {+ label: 'Studio',+ route: '/studio',+ accent: '#f472b6',+ icon: '◧',+ tagline: 'Widget Builder',+ },+ marketplace: {+ label: 'Marketplace',+ route: '/marketplace',+ accent: '#facc15',+ icon: '◰',+ tagline: 'Agent Marketplace',+ },+ 'agent-exchange': {+ label: 'Agent Exchange',+ route: '/agent-exchange',+ accent: '#34d399',+ icon: '⟳',+ tagline: 'Agents Paying Each Other',+ },+ deploy: {+ label: 'Deploy',+ route: '/deploy',+ accent: '#60a5fa',+ icon: '◆',+ tagline: 'On-Chain Identity',+ },+};++function escapeXml(str) {+ return String(str)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++function wrap64(str, maxChars) {+ if (str.length <= maxChars) return [str, ''];+ const cut = str.lastIndexOf(' ', maxChars);+ if (cut <= 0) return [str.slice(0, maxChars), str.slice(maxChars).trim()];+ return [str.slice(0, cut), str.slice(cut + 1)];+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;++ const url = new URL(req.url, 'http://x');+ const slug = (url.searchParams.get('feature') || '').toLowerCase().replace(/[^a-z-]/g, '');+ const meta = FEATURE_META[slug] || {+ label: 'Features',+ route: '/features',+ accent: '#ffffff',+ icon: '◈',+ tagline: 'Explore the platform',+ };++ const titleParam = url.searchParams.get('title') || meta.label;+ const subParam = url.searchParams.get('sub') || meta.tagline;++ const [titleL1, titleL2] = wrap64(escapeXml(titleParam), 36);+ const [subL1, subL2] = wrap64(escapeXml(subParam), 58);++ const accent = escapeXml(meta.accent);+ const label = escapeXml(meta.label);+ const route = escapeXml(meta.route);+ const icon = escapeXml(meta.icon);++ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0%" stop-color="#050505"/>+ <stop offset="100%" stop-color="#0a0a0a"/>+ </linearGradient>+ <radialGradient id="glow" cx="75%" cy="20%" r="60%">+ <stop offset="0%" stop-color="${accent}" stop-opacity="0.12"/>+ <stop offset="100%" stop-color="${accent}" stop-opacity="0"/>+ </radialGradient>+ <radialGradient id="glow2" cx="10%" cy="90%" r="40%">+ <stop offset="0%" stop-color="${accent}" stop-opacity="0.06"/>+ <stop offset="100%" stop-color="${accent}" stop-opacity="0"/>+ </radialGradient>+ </defs>++ <!-- Background -->+ <rect width="1200" height="630" fill="url(#bg)"/>+ <rect width="1200" height="630" fill="url(#glow)"/>+ <rect width="1200" height="630" fill="url(#glow2)"/>++ <!-- Subtle grid -->+ <pattern id="grid" x="0" y="0" width="60" height="60" patternUnits="userSpaceOnUse">+ <path d="M 60 0 L 0 0 0 60" fill="none" stroke="rgba(255,255,255,0.025)" stroke-width="1"/>+ </pattern>+ <rect width="1200" height="630" fill="url(#grid)"/>++ <!-- Border -->+ <rect x="1" y="1" width="1198" height="628" fill="none" stroke="rgba(255,255,255,0.08)" stroke-width="2" rx="0"/>++ <!-- Brand -->+ <text x="64" y="88" font-family="system-ui, -apple-system, sans-serif" font-size="28" font-weight="800" fill="rgba(255,255,255,0.9)" letter-spacing="-0.5">three.ws</text>+ <text x="64" y="88" dx="160" font-family="system-ui, -apple-system, sans-serif" font-size="28" font-weight="400" fill="rgba(255,255,255,0.3)" letter-spacing="-0.5">/ features</text>++ <!-- Feature pill -->+ <rect x="62" y="112" width="${label.length * 10 + 40 + 24}" height="34" rx="17" fill="${accent}" fill-opacity="0.12" stroke="${accent}" stroke-opacity="0.3" stroke-width="1"/>+ <text x="${38 + 24}" y="135" font-family="ui-monospace, monospace" font-size="13" font-weight="700" fill="${accent}" letter-spacing="1.5" text-anchor="middle"+ transform="translate(${label.length * 5 + 38}, 0)">${label.toUpperCase()}</text>+ <text x="78" y="135" font-family="ui-monospace, monospace" font-size="13" font-weight="700" fill="${accent}">${icon}</text>++ <!-- Main heading -->+ <text x="64" y="270" font-family="system-ui, -apple-system, sans-serif" font-size="72" font-weight="900" fill="#ffffff" letter-spacing="-2">${titleL1}</text>+ ${titleL2 ? `<text x="64" y="352" font-family="system-ui, -apple-system, sans-serif" font-size="72" font-weight="900" fill="#ffffff" letter-spacing="-2">${titleL2}</text>` : ''}++ <!-- Sub -->+ <text x="64" y="${titleL2 ? 400 : 316}" font-family="system-ui, -apple-system, sans-serif" font-size="28" font-weight="400" fill="rgba(255,255,255,0.55)" letter-spacing="-0.3">${subL1}</text>+ ${subL2 ? `<text x="64" y="${titleL2 ? 436 : 352}" font-family="system-ui, -apple-system, sans-serif" font-size="28" font-weight="400" fill="rgba(255,255,255,0.55)" letter-spacing="-0.3">${subL2}</text>` : ''}++ <!-- CTA pill -->+ <rect x="62" y="548" width="200" height="44" rx="22" fill="${accent}"/>+ <text x="162" y="576" font-family="system-ui, -apple-system, sans-serif" font-size="18" font-weight="800" fill="#000" text-anchor="middle" letter-spacing="0.2">Open ${label} →</text>++ <!-- Route label -->+ <text x="1136" y="576" font-family="ui-monospace, monospace" font-size="16" fill="rgba(255,255,255,0.25)" text-anchor="end" letter-spacing="0.5">three.ws${route}</text>+</svg>`;++ res.statusCode = 200;+ res.setHeader('content-type', 'image/svg+xml');+ res.setHeader('cache-control', CACHE);+ res.end(svg);+});diff --git a/api/forge-og.js b/api/forge-og.jsnew file mode 100644index 000000000..b0eccbcbf--- /dev/null+++ b/api/forge-og.js@@ -0,0 +1,93 @@+/**+ * Forge creation OG image+ * -----------------------+ * GET /api/forge-og?id=<creation_id>+ *+ * Happy path: 302 to the creation's preview_image_url (the flux-generated+ * reference image) so social crawlers cache a real thumbnail. Fallback: a+ * server-rendered SVG card in the same style as api/agent-og.js so every+ * forge share link gets a real og:image.+ *+ * No client-key auth: if a creator has the ID they've chosen to share it.+ * UUIDs are unguessable by construction.+ */++import { sql } from './_lib/db.js';+import { cors, wrap } from './_lib/http.js';++const CACHE_CARD = 'public, max-age=3600, s-maxage=86400';+const CACHE_REDIR = 'public, max-age=3600';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;++ const url = new URL(req.url, 'http://x');+ const id = url.searchParams.get('id');++ if (!id || !UUID_RE.test(id)) return sendFallback(res);++ let row;+ try {+ [row] = await sql`+ SELECT id, prompt, preview_image_url+ FROM forge_creations+ WHERE id = ${id}+ LIMIT 1+ `;+ } catch {+ return sendFallback(res);+ }++ if (!row) return sendFallback(res);++ if (row.preview_image_url) {+ res.statusCode = 302;+ res.setHeader('location', row.preview_image_url);+ res.setHeader('cache-control', CACHE_REDIR);+ res.end();+ return;+ }++ sendCardSvg(res, 200, CACHE_CARD, {+ prompt: row.prompt || 'Forged creation',+ });+});++function sendFallback(res) {+ sendCardSvg(res, 404, 'public, max-age=60', { prompt: 'Forged with three.ws' });+}++function sendCardSvg(res, status, cacheControl, { prompt }) {+ res.statusCode = status;+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');+ res.setHeader('cache-control', cacheControl);+ res.end(renderCardSvg({ prompt }));+}++function renderCardSvg({ prompt }) {+ const safePrompt = escapeXml(truncate(prompt, 80));+ return `<?xml version="1.0" encoding="UTF-8"?>+<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="${safePrompt}">+ <rect width="1200" height="630" fill="#0b0d10"/>+ <text x="80" y="140" fill="#e5e5e5" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="52" font-weight="300">◳</text>+ <text x="80" y="300" fill="#e5e5e5" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="68" font-weight="300" letter-spacing="-2">${safePrompt}</text>+ <text x="80" y="380" fill="rgba(229,229,229,0.45)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="24" font-weight="400">Forged with text → 3D on three.ws</text>+ <text x="80" y="570" fill="rgba(229,229,229,0.3)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="20" font-weight="400" letter-spacing="4">three.ws / forge</text>+</svg>`;+}++function truncate(s, n) {+ s = String(s || '');+ return s.length <= n ? s : s.slice(0, n - 1) + '…';+}++function escapeXml(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;diff --git a/api/forge-share.js b/api/forge-share.jsnew file mode 100644index 000000000..6c784a923--- /dev/null+++ b/api/forge-share.js@@ -0,0 +1,139 @@+/**+ * SSR share page for forge creations+ * ------------------------------------+ * GET /api/forge-share?id=<creation_id>+ *+ * Wired via vercel.json: /forge/share/:id → /api/forge-share?id=$1+ *+ * Bakes Open Graph + Twitter Card + Farcaster Frame meta into the <head>+ * so social crawlers get a real preview. Real browsers are JS-redirected+ * to /forge?share=<id> so they can view the creation in the full forge UI.+ *+ * Mirrors the pattern in api/app-og.js and api/discover-detail.js.+ */++import { sql } from './_lib/db.js';+import { cors, wrap } from './_lib/http.js';+import { env } from './_lib/env.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;++ const url = new URL(req.url, 'http://x');+ const id = url.searchParams.get('id');+ const origin = env.APP_ORIGIN || 'https://three.ws';++ if (!id || !UUID_RE.test(id)) {+ return redirect(res, `${origin}/forge`);+ }++ let row;+ try {+ [row] = await sql`+ SELECT id, prompt, preview_image_url, status+ FROM forge_creations+ WHERE id = ${id}+ LIMIT 1+ `;+ } catch {+ return redirect(res, `${origin}/forge`);+ }++ if (!row) return redirect(res, `${origin}/forge`);++ const title = row.prompt ? truncate(row.prompt, 80) : 'Forged creation';+ const desc = `3D model forged from text on three.ws: "${title}"`;+ const pageUrl = `${origin}/forge/share/${id}`;+ const forgeUrl = `${origin}/forge?share=${id}`;+ const ogImage = row.preview_image_url || `${origin}/api/forge-og?id=${id}`;++ res.statusCode = 200;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=600, stale-while-revalidate=3600');+ res.end(renderHtml({ id, title, desc, pageUrl, forgeUrl, ogImage, origin }));+});++function redirect(res, to) {+ res.statusCode = 302;+ res.setHeader('location', to);+ res.setHeader('cache-control', 'no-cache');+ res.end();+}++function renderHtml({ id, title, desc, pageUrl, forgeUrl, ogImage, origin }) {+ const t = esc(title);+ const d = esc(desc);+ return `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="X-UA-Compatible" content="IE=edge">+ <title>${t} — three.ws Forge</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">+ <meta name="description" content="${d}">+ <meta name="theme-color" content="#0b0d10">++ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:title" content="${t} — three.ws Forge">+ <meta property="og:description" content="${d}">+ <meta property="og:url" content="${esc(pageUrl)}">+ <meta property="og:image" content="${esc(ogImage)}">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:alt" content="${t} forged on three.ws">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="${t} — three.ws Forge">+ <meta name="twitter:description" content="${d}">+ <meta name="twitter:image" content="${esc(ogImage)}">+ <meta name="twitter:creator" content="@trythreews">++ <meta property="fc:frame" content="vNext">+ <meta property="fc:frame:image" content="${esc(ogImage)}">+ <meta property="fc:frame:image:aspect_ratio" content="1.91:1">+ <meta property="fc:frame:button:1" content="Forge your own →">+ <meta property="fc:frame:button:1:action" content="link">+ <meta property="fc:frame:button:1:target" content="${esc(forgeUrl)}">++ <link rel="canonical" href="${esc(pageUrl)}">+ <link rel="shortcut icon" href="/favicon.ico">++ <style>+ html,body{margin:0;padding:0;background:#0b0d10;color:#e0e0e0;font-family:Inter,system-ui,sans-serif;height:100%}+ .shell{display:grid;place-items:center;min-height:100vh;text-align:center;padding:2rem;gap:1rem}+ .shell a{color:#e0e0e0;text-decoration:underline;text-underline-offset:3px}+ .spinner{width:28px;height:28px;border:2px solid rgba(255,255,255,0.1);border-top-color:rgba(255,255,255,0.6);border-radius:50%;animation:spin 0.9s linear infinite;margin:0 auto}+ @keyframes spin{to{transform:rotate(360deg)}}+ p{margin:0;color:rgba(255,255,255,0.5);font-size:14px}+ </style>+</head>+<body>+ <noscript>+ <div class="shell">+ <h1>${t}</h1>+ <p>${d}</p>+ <p><a href="${esc(forgeUrl)}">Open in Forge</a> · <a href="${esc(origin)}/forge">Browse Forge</a></p>+ </div>+ </noscript>+ <div class="shell" aria-live="polite">+ <div class="spinner" aria-hidden="true"></div>+ <p>Opening Forge…</p>+ </div>+ <script>(function(){window.location.replace(${JSON.stringify(forgeUrl)});})()</script>+</body>+</html>`;+}++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function truncate(s, n) {+ s = String(s || '');+ return s.length <= n ? s : s.slice(0, n - 1) + '…';+}diff --git a/api/notifications/read-all.js b/api/notifications/read-all.jsindex 106274a28..52e4147f3 100644--- a/api/notifications/read-all.js+++ b/api/notifications/read-all.js@@ -11,12 +11,12 @@ export default wrap(async (req, res) => {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');- const [{ count }] = await sql`+ const rows = await sql`update user_notificationsset read_at = now()where user_id = ${user.id} and read_at is nullreturning count(*) over ()::int as count`;- return json(res, 200, { marked_read: count ?? 0 });+ return json(res, 200, { marked_read: rows[0]?.count ?? 0 });});diff --git a/api/onramp/link.js b/api/onramp/link.jsnew file mode 100644index 000000000..fd4988e33--- /dev/null+++ b/api/onramp/link.js@@ -0,0 +1,101 @@+// GET /api/onramp/link?address=SOLANA_ADDR&amount=25+//+// Returns a URL the client should open (in a popup) to let the user buy USDC+// without leaving the app. Tries Coinbase Pay (hosted checkout) first, then+// falls back to a direct Coinbase buy-USDC URL.+//+// Requires:+// COINBASE_PAY_APP_ID (optional) — Coinbase Pay SDK App ID from+// https://pay.coinbase.com → Projects. When set, the+// returned URL is a pre-populated Coinbase Pay checkout+// targeting the user's Solana wallet. When absent, the+// URL falls back to Coinbase's general USDC buy page.+//+// The address param is NOT a secret (it's a Solana public key) and is only+// used as the deposit destination — it is safe to pass in a query string.++import { cors, json, error } from '../_lib/http.js';++const COINBASE_PAY_APP_ID = process.env.COINBASE_PAY_APP_ID;++// Solana USDC on mainnet+const USDC_SOLANA_ASSET = 'USDC';+const SOLANA_BLOCKCHAIN = 'solana';++// Length bounds for a Solana base58 public key+const SOL_ADDR_MIN = 32;+const SOL_ADDR_MAX = 44;+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;++function isValidSolanaAddress(addr) {+ if (!addr || typeof addr !== 'string') return false;+ if (addr.length < SOL_ADDR_MIN || addr.length > SOL_ADDR_MAX) return false;+ return BASE58_RE.test(addr);+}++/**+ * Build a Coinbase Pay hosted checkout URL.+ * Spec: https://docs.cdp.coinbase.com/onramp/docs/api-initializing+ *+ * @param {string} appId Coinbase Pay App ID+ * @param {string} destinationAddress Solana wallet address+ * @param {number} amount preset fiat amount in USD+ * @returns {string}+ */+function buildCoinbasePayUrl(appId, destinationAddress, amount) {+ const destinationWallets = JSON.stringify([+ {+ address: destinationAddress,+ blockchains: [SOLANA_BLOCKCHAIN],+ assets: [USDC_SOLANA_ASSET],+ },+ ]);+ const params = new URLSearchParams({+ appId,+ destinationWallets,+ presetFiatAmount: String(amount),+ fiatCurrency: 'USD',+ });+ return `https://pay.coinbase.com/buy/select-asset?${params}`;+}++/**+ * Fallback: Coinbase's general USDC buy page. The user lands on Coinbase,+ * selects their amount, and sends USDC to their own address. Still real;+ * not as frictionless as Coinbase Pay but 100% functional without an App ID.+ */+function buildCoinbaseFallbackUrl() {+ return 'https://www.coinbase.com/price/usd-coin';+}++export default function handler(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);+ const address = url.searchParams.get('address') || '';+ const amountRaw = url.searchParams.get('amount');+ const amount = Math.max(10, Math.min(500, Number(amountRaw) || 25));++ if (!isValidSolanaAddress(address)) {+ return error(res, 400, 'invalid_address', 'address must be a valid Solana public key');+ }++ let onrampUrl;+ let mode;++ if (COINBASE_PAY_APP_ID) {+ onrampUrl = buildCoinbasePayUrl(COINBASE_PAY_APP_ID, address, amount);+ mode = 'coinbase-pay';+ } else {+ onrampUrl = buildCoinbaseFallbackUrl();+ mode = 'coinbase-fallback';+ }++ return json(res, 200, {+ url: onrampUrl,+ mode,+ address,+ amount,+ });+}diff --git a/api/play-og.js b/api/play-og.jsindex 29e37ba0e..8a8d91f25 100644--- a/api/play-og.js+++ b/api/play-og.js@@ -6,9 +6,15 @@// Doubles as the guaranteed <img> fallback for content platforms that block// scripts/iframes (e.g. the AWS Builder Center editor): it is a plain image// served from our own domain, coin-specific, no embed component required.+//+// Rendered via @vercel/og's ImageResponse through the NODE runtime (not Edge).+// The Edge runtime returns FUNCTION_INVOCATION_FAILED in this deployment, so+// we run as a plain Vercel function and bridge the Web Response → Node+// ServerResponse, the same pattern proven in api/demo/coin/og.js.import { ImageResponse } from '@vercel/og';-export const config = { runtime: 'edge' };+const WIDTH = 1200;+const HEIGHT = 630;// Biome archetypes, matched to the seeded worlds described in /play.// Each coin's mint deterministically picks one, so the poster's palette@@ -42,6 +48,12 @@ function formatMarketCap(mc) {return `$${n.toFixed(0)}`;}+function originOf(req) {+ const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';+ const proto = req.headers['x-forwarded-proto'] || 'https';+ return `${proto}://${host}`;+}+async function fetchCoin(origin, mint) {if (!mint) return null;try {@@ -59,126 +71,161 @@ async function fetchCoin(origin, mint) {}}-export default async function handler(req) {- const url = new URL(req.url);- const origin = url.origin;- const mint = url.searchParams.get('coin') || url.searchParams.get('mint') || '';-- const coin = await fetchCoin(origin, mint);- const biome = pickBiome(mint);-- const ticker = coin?.symbol ? `$${String(coin.symbol).replace(/^\$/, '')}` : null;- const name = coin?.name || (mint ? 'this coin' : 'any coin');- // /api/pump/coin returns the raw pump.fun body — match the same field- // fallbacks the in-world client uses (coincommunities.js) so the share card- // actually populates instead of always rendering the blank/zero state.- const mcap = formatMarketCap(- coin?.usd_market_cap || coin?.market_cap_usd || coin?.market_cap || coin?.marketCap || 0,- );- const image = coin?.image_uri || coin?.image || coin?.imageUri || null;-- const heading = ticker ? `Walk into ${ticker}` : 'Walk into any coin';-- const metaChips = [- { label: biome.name },- mcap ? { label: `MCAP ${mcap}` } : null,- { label: 'Live 3D world' },- ].filter(Boolean);-- return new ImageResponse(- {- type: 'div',- props: {- style: {- width: '100%',- height: '100%',- display: 'flex',- flexDirection: 'column',- justifyContent: 'space-between',- padding: '64px 72px',- background: `radial-gradient(120% 120% at 80% 10%, ${biome.c2} 0%, ${biome.c1} 45%, #0a0a0a 100%)`,- color: 'white',- fontFamily: 'sans-serif',- },- children: [- // top row: brand + coin art- {- type: 'div',- props: {- style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' },- children: [- {- type: 'div',- props: {- style: { fontSize: 30, fontWeight: 800, letterSpacing: -1, opacity: 0.95 },- children: 'three.ws · /play',- },+function card({ biome, heading, subline, ticker, image, metaChips }) {+ return {+ type: 'div',+ props: {+ style: {+ width: '100%',+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ justifyContent: 'space-between',+ padding: '64px 72px',+ background: `radial-gradient(120% 120% at 80% 10%, ${biome.c2} 0%, ${biome.c1} 45%, #0a0a0a 100%)`,+ color: 'white',+ fontFamily: 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',+ },+ children: [+ // top row: brand + coin art+ {+ type: 'div',+ props: {+ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' },+ children: [+ {+ type: 'div',+ props: {+ style: { fontSize: 30, fontWeight: 800, letterSpacing: -1, opacity: 0.95 },+ children: 'three.ws · /play',},- image- ? {- type: 'img',- props: {- src: image,- width: 96,- height: 96,- style: { borderRadius: 96, border: '3px solid rgba(255,255,255,0.85)' },- },- }- : { type: 'div', props: { children: '' } },- ],- },+ },+ image+ ? {+ type: 'img',+ props: {+ src: image,+ width: 96,+ height: 96,+ style: { borderRadius: 96, border: '3px solid rgba(255,255,255,0.85)' },+ },+ }+ : { type: 'div', props: { children: '' } },+ ],},- // middle: heading + name- {- type: 'div',- props: {- style: { display: 'flex', flexDirection: 'column' },- children: [- {- type: 'div',- props: {- style: { fontSize: 84, fontWeight: 900, letterSpacing: -3, lineHeight: 1.0 },- children: heading,- },- },- {- type: 'div',- props: {- style: { fontSize: 34, marginTop: 14, opacity: 0.92, fontWeight: 600 },- children: ticker ? name : 'Turn any pump.fun coin into a live 3D world',- },+ },+ // middle: heading + name+ {+ type: 'div',+ props: {+ style: { display: 'flex', flexDirection: 'column' },+ children: [+ {+ type: 'div',+ props: {+ style: { fontSize: 84, fontWeight: 900, letterSpacing: -3, lineHeight: 1.0 },+ children: heading,},- ],- },- },- // bottom: chips- {- type: 'div',- props: {- style: { display: 'flex', gap: 16 },- children: metaChips.map((chip) => ({+ },+ {type: 'div',props: {- style: {- fontSize: 26,- fontWeight: 700,- padding: '12px 22px',- borderRadius: 999,- background: 'rgba(0,0,0,0.35)',- border: '1px solid rgba(255,255,255,0.25)',- },- children: chip.label,+ style: { fontSize: 34, marginTop: 14, opacity: 0.92, fontWeight: 600 },+ children: subline,},- })),- },+ },+ ],},- ],- },- },- {- width: 1200,- height: 630,- headers: { 'cache-control': 'public, max-age=300, s-maxage=600' },+ },+ // bottom: chips+ {+ type: 'div',+ props: {+ style: { display: 'flex', gap: 16 },+ children: metaChips.map((chip) => ({+ type: 'div',+ props: {+ style: {+ fontSize: 26,+ fontWeight: 700,+ padding: '12px 22px',+ borderRadius: 999,+ background: 'rgba(0,0,0,0.35)',+ border: '1px solid rgba(255,255,255,0.25)',+ },+ children: chip.label,+ },+ })),+ },+ },+ ],},- );+ };+}++function imageResponse(node) {+ return new ImageResponse(node, {+ width: WIDTH,+ height: HEIGHT,+ headers: { 'cache-control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=86400' },+ });+}++// Web Response (from @vercel/og) → Node ServerResponse. Headers first, then body.+async function sendImage(res, response) {+ for (const [key, value] of response.headers.entries()) res.setHeader(key, value);+ const ab = await response.arrayBuffer();+ res.statusCode = response.status;+ res.end(Buffer.from(ab));+}++export default async function handler(req, res) {+ if (req.method === 'OPTIONS') {+ res.setHeader('access-control-allow-origin', '*');+ res.setHeader('access-control-allow-methods', 'GET,OPTIONS');+ res.statusCode = 204;+ res.end();+ return;+ }++ const url = new URL(req.url, 'http://x');+ const origin = originOf(req);+ const mint = url.searchParams.get('coin') || url.searchParams.get('mint') || '';+ const biome = pickBiome(mint);++ try {+ const coin = await fetchCoin(origin, mint);+ const ticker = coin?.symbol ? `$${String(coin.symbol).replace(/^\$/, '')}` : null;+ const name = coin?.name || (mint ? 'this coin' : 'any coin');+ // /api/pump/coin returns the raw pump.fun body — match the same field+ // fallbacks the in-world client uses (coincommunities.js) so the share card+ // actually populates instead of always rendering the blank/zero state.+ const mcap = formatMarketCap(+ coin?.usd_market_cap || coin?.market_cap_usd || coin?.market_cap || coin?.marketCap || 0,+ );+ const image = coin?.image_uri || coin?.image || coin?.imageUri || null;+ const heading = ticker ? `Walk into ${ticker}` : 'Walk into any coin';+ const subline = ticker ? name : 'Turn any pump.fun coin into a live 3D world';+ const metaChips = [+ { label: biome.name },+ mcap ? { label: `MCAP ${mcap}` } : null,+ { label: 'Live 3D world' },+ ].filter(Boolean);++ await sendImage(res, imageResponse(card({ biome, heading, subline, ticker, image, metaChips })));+ } catch (err) {+ // Never fail open to a broken-image grey box — render the coin-agnostic+ // brand card so the share preview still looks intentional.+ console.error('[play-og] render failed:', err?.message || err);+ const fallback = card({+ biome,+ heading: 'Walk into any coin',+ subline: 'Turn any pump.fun coin into a live 3D world',+ ticker: null,+ image: null,+ metaChips: [{ label: biome.name }, { label: 'Live 3D world' }],+ });+ res.statusCode = 200;+ await sendImage(res, imageResponse(fallback));+ }}diff --git a/api/pump/search.js b/api/pump/search.jsnew file mode 100644index 000000000..c770f53a2--- /dev/null+++ b/api/pump/search.js@@ -0,0 +1,134 @@+// GET /api/pump/search?q=bonk&limit=8+// ------------------------------------+// Name/symbol search over Solana tokens for the site-wide command palette+// (public/search.js) and any other surface that needs to resolve a coin by+// query. Returns the same item shape as /api/pump/trending so consumers can+// share rendering code.+//+// Primary source is Birdeye token search (keeps BIRDEYE_API_KEY server-side).+// When Birdeye is unconfigured, rate-limited, or down, we fall back to+// pump.fun's public frontend search (no API key) — same response shape — so the+// palette degrades to live pump.fun data instead of a hard error. Only errors+// when both sources are unavailable.+//+// Response: { data: [ { mint, symbol, name, logo, price_usd, rank } ] }++import { cors, json, method, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { normalizeGatewayURL } from '../../src/ipfs.js';++const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;+const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';++// Process-local cache keyed by normalized query. Palette keystrokes are+// debounced client-side, but repeated queries (same token typed twice) and many+// tabs still benefit from a short TTL so we don't hammer the upstreams.+const _cache = new Map(); // key -> { value, expiresAt }+const TTL_MS = 30_000;+const CACHE_MAX = 100;++// Primary: Birdeye token search. Returns null (not throws) on any failure so the+// caller can transparently fall back to pump.fun.+async function searchBirdeye(q, limit) {+ if (!BIRDEYE_API_KEY) return null;+ const url =+ `https://public-api.birdeye.so/defi/v3/search` ++ `?chain=solana&target=token&search_mode=fuzzy&sort_by=marketcap&sort_type=desc` ++ `&offset=0&limit=${limit}&keyword=${encodeURIComponent(q)}`;+ let upstream;+ try {+ upstream = await fetch(url, {+ headers: { 'X-API-KEY': BIRDEYE_API_KEY, 'x-chain': 'solana', accept: 'application/json' },+ signal: AbortSignal.timeout(8000),+ });+ } catch {+ return null;+ }+ if (!upstream.ok) return null;+ const payload = await upstream.json().catch(() => null);+ // v3 search nests token matches under data.items[].result.+ const groups = payload?.data?.items;+ if (!Array.isArray(groups)) return null;+ const tokens = groups.flatMap((g) => (Array.isArray(g?.result) ? g.result : []));+ const data = tokens+ .map((t) => ({+ mint: t.address,+ symbol: t.symbol || '?',+ name: t.name || t.symbol || '',+ logo: t.logo_uri || t.logoURI || null,+ price_usd: typeof t.price === 'number' ? t.price : null,+ rank: null,+ }))+ .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);+ return data.length ? data : null;+}++// Fallback: pump.fun's public frontend search (no API key). Mapped into the+// exact same shape. pump.fun doesn't expose a clean per-token USD price here, so+// price_usd is left null rather than fabricated.+async function searchPumpFun(q, limit) {+ const url = new URL('/coins', PUMP_FRONTEND_BASE);+ url.searchParams.set('searchTerm', q);+ url.searchParams.set('offset', '0');+ url.searchParams.set('limit', String(limit));+ url.searchParams.set('sort', 'market_cap');+ url.searchParams.set('order', 'DESC');+ url.searchParams.set('includeNsfw', 'false');+ let upstream;+ try {+ upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });+ } catch {+ return null;+ }+ if (!upstream.ok) return null;+ const body = await upstream.json().catch(() => null);+ const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;+ if (!Array.isArray(coins)) return null;+ const data = coins+ .map((c, i) => ({+ mint: c.mint || c.address || '',+ symbol: c.symbol || '?',+ name: c.name || c.symbol || '',+ logo: normalizeGatewayURL(c.image_uri || c.image || '') || null,+ price_usd: null,+ rank: i + 1,+ }))+ .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);+ return data.length ? data : null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const params = new URL(req.url, 'http://x').searchParams;+ const q = (params.get('q') || '').trim().slice(0, 64);+ if (!q) return json(res, 200, { data: [] }, { 'cache-control': 'no-store' });++ const rawLimit = Number(params.get('limit') || '8');+ const limit = Math.min(20, Math.max(1, Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 8));++ const key = q.toLowerCase() + '|' + limit;+ const now = Date.now();+ const hit = _cache.get(key);+ if (hit && hit.expiresAt > now) {+ return json(res, 200, { data: hit.value }, { 'cache-control': 'public, max-age=15, s-maxage=30' });+ }++ let data = await searchBirdeye(q, limit);+ if (!data) data = await searchPumpFun(q, limit);+ if (!data) {+ // No matches found is a valid, common outcome — return an empty list, not+ // an error. We only surface an error if the upstreams threw above (handled+ // by wrap()). Cache the empty result briefly to soak repeat keystrokes.+ _cache.set(key, { value: [], expiresAt: now + TTL_MS });+ return json(res, 200, { data: [] }, { 'cache-control': 'public, max-age=15, s-maxage=30' });+ }++ if (_cache.size >= CACHE_MAX) _cache.clear();+ _cache.set(key, { value: data, expiresAt: now + TTL_MS });+ return json(res, 200, { data }, { 'cache-control': 'public, max-age=15, s-maxage=30' });+});diff --git a/api/pump/trending.js b/api/pump/trending.jsindex 5c1cc3f46..8553a6f8a 100644--- a/api/pump/trending.js+++ b/api/pump/trending.js@@ -1,81 +1,47 @@// GET /api/pump/trending?limit=25// --------------------------------// Server-side proxy for Birdeye's trending-tokens feed. Keeps BIRDEYE_API_KEY-// on the server — the browser never sees it. Returns the upstream error verbatim-// on failure so the UI can surface it; never falls back to a hardcoded list.+// Trending Solana tokens for the dashboard chart picker and every other live+// market surface (home card, communities, constellation, visualizer).+//+// Primary source is Birdeye (keeps BIRDEYE_API_KEY server-side). When Birdeye is+// unconfigured, rate-limited, or down, we fall back to pump.fun's public frontend+// feed — same response shape — so the market surfaces degrade to live pump.fun+// data instead of a hard error. Only errors when both sources are unavailable.//// Response: { data: [ { mint, symbol, name, logo, price_usd, rank } ] }import { cors, json, method, wrap, error } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';+import { normalizeGatewayURL } from '../../src/ipfs.js';const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;+const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';// Process-local cache. Trending shifts slowly; many tabs polling on nav into the-// dashboard would otherwise hammer Birdeye. Warm-starts share this map.+// dashboard would otherwise hammer the upstreams. Warm-starts share this map.let _cache = { value: null, expiresAt: 0, limit: 0 };const TTL_MS = 30_000;-export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;-- const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const raw = Number(new URL(req.url, 'http://x').searchParams.get('limit') || '25');- const limit = Math.min(50, Math.max(1, Number.isFinite(raw) ? Math.floor(raw) : 25));-- if (!BIRDEYE_API_KEY) {- return error(res, 503, 'not_configured', 'Trending data provider is not configured');- }-- const now = Date.now();- if (_cache.value && _cache.limit >= limit && _cache.expiresAt > now) {- return json(- res,- 200,- { data: _cache.value.slice(0, limit) },- {- 'cache-control': 'public, max-age=15, s-maxage=30',- },- );- }-+// Primary: Birdeye trending feed. Returns null (not throws) on any failure so the+// caller can transparently fall back.+async function fetchBirdeye(limit) {+ if (!BIRDEYE_API_KEY) return null;const url =`https://public-api.birdeye.so/defi/token_trending` +`?sort_by=rank&sort_type=asc&offset=0&limit=${limit}`;-let upstream;try {upstream = await fetch(url, {- headers: {- 'X-API-KEY': BIRDEYE_API_KEY,- 'x-chain': 'solana',- accept: 'application/json',- },+ headers: { 'X-API-KEY': BIRDEYE_API_KEY, 'x-chain': 'solana', accept: 'application/json' },signal: AbortSignal.timeout(8000),});- } catch (e) {- return error(res, 502, 'bad_gateway', `Birdeye unreachable: ${e.message}`);+ } catch {+ return null;}-- if (!upstream.ok) {- const body = await upstream.text().catch(() => '');- return error(- res,- 502,- 'upstream_error',- `Birdeye ${upstream.status}: ${body.slice(0, 200)}`,- );- }-+ if (!upstream.ok) return null;const payload = await upstream.json().catch(() => null);const tokens = payload?.data?.tokens;- if (!Array.isArray(tokens)) {- return error(res, 502, 'upstream_error', 'Birdeye returned an unexpected payload');- }-+ if (!Array.isArray(tokens)) return null;const data = tokens.map((t) => ({mint: t.address,@@ -86,8 +52,65 @@ export default wrap(async (req, res) => {rank: typeof t.rank === 'number' ? t.rank : null,})).filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);+ return data.length ? data : null;+}- _cache = { value: data, expiresAt: now + TTL_MS, limit };+// Fallback: pump.fun's public frontend feed (no API key). Mapped into the exact+// same shape so every consumer keeps working. pump.fun doesn't expose a clean+// per-token USD price here, so price_usd is left null rather than fabricated.+async function fetchPumpFun(limit) {+ const url = new URL('/coins', PUMP_FRONTEND_BASE);+ url.searchParams.set('offset', '0');+ url.searchParams.set('limit', String(limit));+ url.searchParams.set('sort', 'market_cap');+ url.searchParams.set('order', 'DESC');+ url.searchParams.set('includeNsfw', 'false');+ let upstream;+ try {+ upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });+ } catch {+ return null;+ }+ if (!upstream.ok) return null;+ const body = await upstream.json().catch(() => null);+ const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;+ if (!Array.isArray(coins)) return null;+ const data = coins+ .map((c, i) => ({+ mint: c.mint || c.address || '',+ symbol: c.symbol || '?',+ name: c.name || c.symbol || '',+ logo: normalizeGatewayURL(c.image_uri || c.image || '') || null,+ price_usd: null,+ rank: i + 1,+ }))+ .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);+ return data.length ? data : null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ const raw = Number(new URL(req.url, 'http://x').searchParams.get('limit') || '25');+ const limit = Math.min(50, Math.max(1, Number.isFinite(raw) ? Math.floor(raw) : 25));++ const now = Date.now();+ if (_cache.value && _cache.limit >= limit && _cache.expiresAt > now) {+ return json(res, 200, { data: _cache.value.slice(0, limit) }, {+ 'cache-control': 'public, max-age=15, s-maxage=30',+ });+ }++ let data = await fetchBirdeye(limit);+ if (!data) data = await fetchPumpFun(limit);+ if (!data) {+ return error(res, 502, 'upstream_error', 'Trending market data is temporarily unavailable');+ }++ _cache = { value: data, expiresAt: now + TTL_MS, limit };return json(res, 200, { data }, { 'cache-control': 'public, max-age=15, s-maxage=30' });});