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
fix(api): give the permissions, stats and pump read paths real error envelopes
nirholas3b44abc9017d
diff --git a/api/permissions/[action].js b/api/permissions/[action].jsindex 45cb9a5fa..f61535ef1 100644--- a/api/permissions/[action].js+++ b/api/permissions/[action].js@@ -8,12 +8,13 @@* POST /api/permissions/revoke* GET /api/permissions/verify*- * Routed via vercel.json — see top of file path patterns.+ * Routed by the filesystem resolver in server/index.mjs: the trailing path+ * segment lands in req.query.action.*/import { createHash } from 'node:crypto';import { z } from 'zod';-import { ethers, Wallet, Contract, Interface, getAddress, isAddress } from 'ethers';+import { ethers, Wallet, Contract, Interface, isAddress } from 'ethers';import { evmFallbackProvider } from '../_lib/evm/rpc.js';import { sql } from '../_lib/db.js';@@ -351,11 +352,19 @@ async function handleList(req, res) {return error(res, 400, 'validation_error', 'chainId must be a positive integer');}- const limitParam = Math.min(- 200,- Math.max(1, parseInt(url.searchParams.get('limit') || '50', 10)),- );- const offset = Math.max(0, parseInt(url.searchParams.get('offset') || '0', 10));+ // Reject non-numeric paging here: an unparsed NaN reaches Postgres as `LIMIT+ // NaN::int` and surfaces as a 500 db_error, which reads like an outage for what+ // is plain caller error.+ const rawLimit = url.searchParams.get('limit');+ const rawOffset = url.searchParams.get('offset');+ if (rawLimit !== null && !/^\d+$/.test(rawLimit)) {+ return error(res, 400, 'validation_error', 'limit must be a non-negative integer');+ }+ if (rawOffset !== null && !/^\d+$/.test(rawOffset)) {+ return error(res, 400, 'validation_error', 'offset must be a non-negative integer');+ }+ const limitParam = Math.min(200, Math.max(1, parseInt(rawLimit || '50', 10)));+ const offset = Math.max(0, parseInt(rawOffset || '0', 10));// agentId-only path: public, no auth requiredif (agentId && !delegator) {@@ -888,9 +897,18 @@ async function handleRedeem(req, res) {}const spendReservationId = reserveRows[0].id;+ // Every exit from here on must release the reservation, or a request that never+ // reached the chain keeps consuming the delegation's period budget forever+ // ('pending' rows count toward the cap; only 'failed' is excluded).+ const releaseReservation = () =>+ sql`UPDATE usage_events SET status = 'failed' WHERE id = ${spendReservationId}`.catch(+ (err) => console.error('[permissions/redeem] reservation release failed', err?.message),+ );+// ── Build signer ───────────────────────────────────────────────────────const rpcUrl = getRpcUrl(chainId);if (!rpcUrl) {+ await releaseReservation();return error(res,502,@@ -905,6 +923,7 @@ async function handleRedeem(req, res) {// AGENT_RELAYER_KEY is never logged — only use it to construct the Walletsigner = new Wallet(env.AGENT_RELAYER_KEY, provider);} catch {+ await releaseReservation();return error(res, 500, 'internal_error', 'failed to initialise relayer signer');}@@ -921,7 +940,7 @@ async function handleRedeem(req, res) {} catch (err) {// The on-chain submit never landed — release the reservation so it stops// counting toward the period cap (mark 'failed', excluded from the sum).- await sql`UPDATE usage_events SET status = 'failed' WHERE id = ${spendReservationId}`.catch(() => {});+ await releaseReservation();if (err instanceof PermissionError && err.code === 'delegation_revoked') {// Auto-sync status in DBsql`UPDATE agent_delegations SET status = 'revoked' WHERE id = ${id}`.catch(() => {});@@ -1240,7 +1259,10 @@ async function verifyCheckDisabled(hash, chainId) {DELEGATION_MANAGER_ABI,provider,);- return manager.isDelegationDisabled(hash);+ // The on-chain method is `disabledDelegations(bytes32)`; that is the only name+ // DELEGATION_MANAGER_ABI declares, so calling anything else here resolves to+ // undefined on the Contract and turns every verify into a 502.+ return manager.disabledDelegations(hash);}function verifyWithTimeout(promise, ms) {diff --git a/api/platform/stats.js b/api/platform/stats.jsindex 802211433..acfb88f93 100644--- a/api/platform/stats.js+++ b/api/platform/stats.js@@ -5,26 +5,55 @@//// All figures are counts that don't expose individual user data.// Cache: 5 minutes CDN + 5 minutes server-side to avoid hammering the DB on-// every homepage hit.+// every homepage hit. A read that fails is never cached and never rounded down+// to zero: the response says `available: false` instead, the same contract+// /api/home-stats uses, so a database outage can't park a fabricated all-zero+// traction payload on the CDN for the next five minutes.import { sql } from '../_lib/db.js';+import { CHAIN_BY_ID } from '../_lib/erc8004-chains.js';import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';export const config = { runtime: 'nodejs' };const CACHE_TTL_MS = 5 * 60_000;+const FAILURE_TTL_SECONDS = 15;+let _cache = { value: null, expiresAt: 0 };+let _inflight = null;export function _resetStatsCache() {_cache = { value: null, expiresAt: 0 };+ _inflight = null;}-async function computeStats() {- const now = Date.now();- if (_cache.value && _cache.expiresAt > now) return _cache.value;+/**+ * Chains the platform can honestly claim: every mainnet that carries at least+ * one active ERC-8004 agent record, plus Solana (the home chain) whenever it+ * carries at least one attestation.+ *+ * Two rows are deliberately not counted. Testnet chain ids (Sepolia, Base+ * Sepolia, Amoy, Fuji…) are real index entries but not networks anyone+ * transacts on, and a chain id absent from the registry in+ * api/_lib/erc8004-chains.js is one we can't confirm is a mainnet at all. Both+ * would only inflate a number the homepage prints as traction.+ *+ * @param {Array<{ chain_id: number|string }>} chainRows distinct active chain ids+ * @param {Array<unknown>} solanaRows non-empty when Solana carries attestations+ * @returns {number}+ */+export function countChains(chainRows, solanaRows) {+ const mainnets = new Set();+ for (const row of chainRows ?? []) {+ const chain = CHAIN_BY_ID[Number(row.chain_id)];+ if (chain && !chain.testnet) mainnets.add(chain.id);+ }+ return mainnets.size + ((solanaRows?.length ?? 0) > 0 ? 1 : 0);+}- const [agents, views, chats, avatars, countries, widgets] = await Promise.allSettled([+async function queryStats() {+ const [agents, views, chats, avatars, countries, widgets, chains, solana] = await Promise.all([// Total published agents with wallets or 3D avatarssql`select count(*)::int as n@@ -33,12 +62,12 @@ async function computeStats() {`,// All-time widget view countsql`- select coalesce(count(*)::bigint, 0) as n+ select count(*)::bigint as nfrom widget_views`,// All-time chat conversation countsql`- select coalesce(count(*)::bigint, 0) as n+ select count(*)::bigint as nfrom widget_chat_threads`,// Total avatars uploaded (GLBs)@@ -59,26 +88,53 @@ async function computeStats() {from widgetswhere deleted_at is null`,+ // Chains carrying an indexed agent, classified against the chain registry+ sql`+ select distinct chain_id+ from erc8004_agents_index+ where active = true+ `,+ // Solana presence: one row is enough, so never count the whole table+ sql`+ select 1+ from solana_attestations+ limit 1+ `,]);- const safe = (res, fallback = 0) => {- if (res.status === 'rejected') return fallback;- return Number(res.value?.[0]?.n ?? fallback);- };+ const count = (rows) => Number(rows?.[0]?.n ?? 0);- const stats = {- agents: safe(agents),- views: safe(views),- chats: safe(chats),- avatars: safe(avatars),- countries: safe(countries),- widgets: safe(widgets),- chains: 6, // Solana + EVM + Base + Polygon + Arbitrum + Optimism+ return {+ available: true,+ agents: count(agents),+ views: count(views),+ chats: count(chats),+ avatars: count(avatars),+ countries: count(countries),+ widgets: count(widgets),+ chains: countChains(chains, solana),generated: new Date().toISOString(),};+}- _cache = { value: stats, expiresAt: now + CACHE_TTL_MS };- return stats;+async function computeStats() {+ if (_cache.value && _cache.expiresAt > Date.now()) return _cache.value;+ // Single-flight: the homepage fans in on every TTL expiry, and without this+ // each concurrent miss fires its own eight queries at the same instant.+ if (!_inflight) {+ _inflight = queryStats().then(+ (stats) => {+ _cache = { value: stats, expiresAt: Date.now() + CACHE_TTL_MS };+ _inflight = null;+ return stats;+ },+ (err) => {+ _inflight = null;+ throw err;+ },+ );+ }+ return _inflight;}export default wrap(async (req, res) => {@@ -88,7 +144,19 @@ export default wrap(async (req, res) => {const rl = await limits.publicIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const stats = await computeStats();+ let stats;+ try {+ stats = await computeStats();+ } catch (err) {+ console.warn('[platform-stats] db_unavailable', err?.message || err);+ return json(+ res,+ 200,+ { available: false, reason: 'db_unavailable' },+ { 'cache-control': `public, s-maxage=${FAILURE_TTL_SECONDS}` },+ );+ }+return json(res, 200, stats, {'cache-control': 'public, max-age=300, s-maxage=300, stale-while-revalidate=60',});diff --git a/api/pump/[action].js b/api/pump/[action].jsindex 803a9d95b..d43a67fc6 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -121,6 +121,23 @@ const RPC = {devnet: process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com',};+/**+ * Read and clamp a `?limit=` query param.+ *+ * `Number('abc')` is NaN, and NaN survives every Math.min/Math.max clamp, so the+ * naive `Math.min(Math.max(1, Number(param || 50)), max)` shape forwards a NaN+ * straight into SQL `limit`, into an upstream query string, and into the feed+ * slice. A single typo'd limit therefore answered 200 with an empty feed rather+ * than the default page. Anything non-numeric falls back to `fallback`; a real+ * number is floored and clamped into [1, max].+ */+function readLimit(url, fallback, max) {+ const param = url.searchParams.get('limit');+ const raw = param == null || param === '' ? NaN : Number(param);+ const n = Number.isFinite(raw) ? Math.floor(raw) : fallback;+ return Math.min(Math.max(1, n), max);+}+async function resolveAuth(req) {const session = await getSessionUser(req);if (session) {@@ -2189,7 +2206,7 @@ async function handlePaymentsList(req, res) {const url = new URL(req.url, `http://${req.headers.host}`);const mint = url.searchParams.get('mint');const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';- const limit = Math.min(Number(url.searchParams.get('limit') || 50), 500);+ const limit = readLimit(url, 50, 500);const wantsPending = url.searchParams.get('include_pending') === '1';// Pending payments expose unconfirmed invoices — require auth.@@ -3480,7 +3497,7 @@ async function handleChannelFeed(req, res) {const rl = await limits.mcpIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);- const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 50)), 200);+ const limit = readLimit(url, 50, 200);const kinds = url.searchParams.get('kinds') || null;// `signal` is one of the four kinds buildFeed knows and the only one that// carries agent attribution (which agent earned the reputation event, and how@@ -3549,7 +3566,7 @@ async function handleTrending(req, res) {return json(res, 200, TRENDING_CACHE.body);}const url = new URL(req.url, `http://${req.headers.host}`);- const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 50)), 100);+ const limit = readLimit(url, 50, 100);const upstream = new URL('/coins', PUMP_FRONTEND_BASE);upstream.searchParams.set('offset', '0');upstream.searchParams.set('limit', String(limit));@@ -3665,7 +3682,7 @@ async function handleCoinTrades(req, res) {const mint = (url.searchParams.get('mint') || '').trim();if (!MINT_RE.test(mint))return error(res, 400, 'invalid_mint', 'mint must be a base58 address');- const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 30)), 100);+ const limit = readLimit(url, 30, 100);const upstream = `${PUMP_SWAP_BASE}/v2/coins/${mint}/trades?limit=${limit}`;// "Recent trades" is a soft, continuously-polled feed (the homepage live card// re-fetches every ~4s). A transient pump.fun swap-API blip means "no new datadiff --git a/api/pump/dashboard.js b/api/pump/dashboard.jsindex 01e7acee9..094d51736 100644--- a/api/pump/dashboard.js+++ b/api/pump/dashboard.js@@ -4,6 +4,8 @@ import { json, error, wrap } from '../_lib/http.js';const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+// Process-local Birdeye response cache. Keeps the function instance from// hammering Birdeye when many tabs poll the same mint within a few seconds.// Vercel functions warm-start across requests, so this is meaningful even@@ -40,6 +42,11 @@ export default wrap(async (req, res) => {const agentId = new URL(req.url, 'http://x').searchParams.get('agent_id');if (!agentId) return error(res, 400, 'missing_agent_id', 'agent_id is required');+ // agent_id lands in a uuid-typed column. Without this guard Postgres raises+ // "invalid input syntax for type uuid" and the caller gets a 500 for what is+ // plainly their own typo.+ if (!UUID_RE.test(agentId))+ return error(res, 400, 'invalid_agent_id', 'agent_id must be a UUID');const [agent] = await sql`SELECT meta FROM agent_identitiesdiff --git a/api/pump/helius-stats.js b/api/pump/helius-stats.jsindex 749c836b4..4a5874336 100644--- a/api/pump/helius-stats.js+++ b/api/pump/helius-stats.js@@ -2,7 +2,9 @@// --------------------------// Lightweight network/feed health endpoint for the /pumpfun page. Returns:// - sol_price (USD, cached upstream)-// - helius { enabled, slot, blockTime, network } when HELIUS_API_KEY is set+// - helius { enabled, slot, network, endpoint } when Helius is reachable,+// plus `error` when the probe itself failed (so a dead RPC reads as dead+// rather than as a silent slot:null)// - feed { mints, graduations } counts from the in-process replay buffer//// Designed to be polled every ~5s by the page to drive the live network panel@@ -21,16 +23,29 @@ import { solPriceUsd, solPriceInfo, solChange24hPct } from '../_lib/sol-price.jslet _heliusCache = { value: null, at: 0 };+const isHeliusUrl = (u) => u.includes('helius-rpc.com') || u.includes('helius.dev');++// Which RPC this panel should actually probe, and what to honestly call it.+// SOLANA_RPC_URL is frequently a non-Helius provider (the shared failover chain+// points elsewhere), so keying "is this Helius?" off the presence of the API key+// alone reported a magicblock/quicknode endpoint as `endpoint: 'helius-rpc'` and+// then blanked its slot when that provider refused us. Resolve the URL FIRST,+// then let the URL decide the label.+export function resolveProbeTarget(env = process.env) {+ const apiKey = env.HELIUS_API_KEY || '';+ const configured = env.SOLANA_RPC_URL || '';+ if (configured && isHeliusUrl(configured)) return { url: configured, endpoint: 'helius-rpc' };+ // A Helius key with a non-Helius SOLANA_RPC_URL still means we HAVE Helius —+ // probe Helius itself rather than mislabeling the other provider.+ if (apiKey) return { url: `https://mainnet.helius-rpc.com/?api-key=${apiKey}`, endpoint: 'helius-rpc' };+ return { url: '', endpoint: null };+}+async function getHeliusInfo() {- const apiKey = process.env.HELIUS_API_KEY || '';- // Key-only configs (no SOLANA_RPC_URL) still get a working probe endpoint —- // otherwise enabled:true would pair with a guaranteed-unreachable empty URL.- const rpcUrl =- process.env.SOLANA_RPC_URL ||- (apiKey ? `https://mainnet.helius-rpc.com/?api-key=${apiKey}` : '');- const isHelius = !!apiKey || rpcUrl.includes('helius-rpc.com') || rpcUrl.includes('helius.dev');- if (!isHelius) return { enabled: false };+ const { url: rpcUrl, endpoint } = resolveProbeTarget();+ if (!rpcUrl) return { enabled: false };if (Date.now() - _heliusCache.at < 4_000 && _heliusCache.value) return _heliusCache.value;+ let value;try {const ctrl = new AbortController();const tid = setTimeout(() => ctrl.abort(), 1500);@@ -44,15 +59,23 @@ async function getHeliusInfo() {});clearTimeout(tid);const d = await r.json();- const slot = Number(d?.result) || null;- const value = { enabled: true, slot, network: 'mainnet', endpoint: 'helius-rpc' };- _heliusCache = { value, at: Date.now() };- return value;+ const slot = Number.isFinite(Number(d?.result)) ? Number(d.result) : null;+ // A JSON-RPC error body is a 200 at the HTTP layer. Reporting it as a bare+ // slot:null read as "quiet chain" for months; say what actually happened.+ value = slot != null+ ? { enabled: true, slot, network: 'mainnet', endpoint }+ : {+ enabled: true,+ slot: null,+ network: 'mainnet',+ endpoint,+ error: String(d?.error?.message || 'rpc_error').slice(0, 120),+ };} catch {- const value = { enabled: true, slot: null, network: 'mainnet', error: 'unreachable' };- _heliusCache = { value, at: Date.now() };- return value;+ value = { enabled: true, slot: null, network: 'mainnet', endpoint, error: 'unreachable' };}+ _heliusCache = { value, at: Date.now() };+ return value;}export default wrap(async (req, res) => {diff --git a/api/pump/intel.js b/api/pump/intel.jsindex 4a3f50dda..85eb4dac5 100644--- a/api/pump/intel.js+++ b/api/pump/intel.js@@ -18,10 +18,12 @@// Degrades gracefully (200 with degraded:true) if the engine tables don't exist// yet, so the dashboard can render its "engine warming up" state instead of 500ing.-import { cors, json, method, wrap } from '../_lib/http.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';import { sql, isDbUnavailableError } from '../_lib/db.js';const LAMPORTS_PER_SOL = 1_000_000_000;+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const VIEWS = new Set(['feed', 'leaderboard', 'learning', 'traders']);const num = (v) => {if (v == null) return null;@@ -428,6 +430,25 @@ export default wrap(async (req, res) => {const mint = (params.get('mint') || '').trim();const view = mint ? 'coin' : (params.get('view') || 'feed');+ // Caller mistakes are answered as caller mistakes. Everything below this point+ // reaching the `degraded` boundary means the ENGINE is down, which is what the+ // dashboard's "warming up" state is for — a typo must never be reported as an+ // outage, and an unknown view must never be silently served as the feed.+ if (mint && !MINT_RE.test(mint)) {+ return error(res, 400, 'invalid_mint', 'mint must be a base58 pump.fun address');+ }+ if (!mint && !VIEWS.has(view)) {+ return error(res, 400, 'invalid_view', `view must be one of: ${[...VIEWS].join(', ')}`);+ }+ const minQualityRaw = params.get('minQuality');+ let minQuality = null;+ if (minQualityRaw != null && minQualityRaw !== '') {+ minQuality = Number(minQualityRaw);+ if (!Number.isInteger(minQuality) || minQuality < 0 || minQuality > 100) {+ return error(res, 400, 'invalid_min_quality', 'minQuality must be an integer from 0 to 100');+ }+ }+try {let payload;switch (view) {@@ -449,7 +470,7 @@ export default wrap(async (req, res) => {network,limit: parseInt(params.get('limit') || '60', 10),category: params.get('category') || null,- minQuality: params.get('minQuality') ? parseInt(params.get('minQuality'), 10) : null,+ minQuality,verdict: params.get('verdict') || null,q: (params.get('q') || '').trim() || null,});diff --git a/api/pump/launch-og.js b/api/pump/launch-og.jsindex 4edfc912b..509694d8d 100644--- a/api/pump/launch-og.js+++ b/api/pump/launch-og.js@@ -171,7 +171,7 @@ export function renderCard(mint, d) {const mcText = mc ? fmtNum(mc) : '';const qColor = qualityColor(qualityScore);- const qText = qualityScore != null ? String(Math.round(qualityScore)) : '—';+ const qText = qualityScore != null ? String(Math.round(qualityScore)) : '-';let outcomePill = '';if (outcome?.graduated) {diff --git a/src/dashboard-next/pages/tokens.js b/src/dashboard-next/pages/tokens.jsindex faa9613be..7a20d34fc 100644--- a/src/dashboard-next/pages/tokens.js+++ b/src/dashboard-next/pages/tokens.js@@ -7,8 +7,13 @@// Real endpoints:// GET /api/agents { agents: [...] }// GET /api/pump/by-agent?agent_id=:id { token, stats }-// POST /api/pump/withdraw-prep body { agent_id, amount }-// POST /api/pump/withdraw-confirm body { tx }+//+// Withdrawal is driven by the <agent-token-widget> this page renders, not by+// this module, and it runs against the real schemas those endpoints accept:+// POST /api/pump/withdraw-prep+// body { mint, authority_wallet, receiver_ata, network } -> { tx_base64 }+// POST /api/pump/withdraw-confirm+// body { mint, network, tx_signature } -> { ok, slot, block_time }import { mountShell } from '../shell.js';import { requireUser, get, esc, ApiError } from '../api.js';