Skip to content

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

fix: harden holder snapshot, galaxy flows, cron, and error reporting

nirholas429292b3124e
diff --git a/.gitignore b/.gitignore
index 8ed46aeb2..64ce92c5e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -281,3 +281,4 @@ three-ws-prod-log-export-2026-06-24T04-15-25.json
pages/ibm/hello.html
three-ws-prod-log-export-2026-06-24T13-33-58.json
three-ws-prod-log-export-2026-06-25T07-22-45.json
+three-ws-prod-log-export-2026-06-25T19-38-22.json
diff --git a/api/_lib/coin/three-holders.js b/api/_lib/coin/three-holders.js
index 5f57ebcf5..abfb00687 100644
--- a/api/_lib/coin/three-holders.js
+++ b/api/_lib/coin/three-holders.js
@@ -139,7 +139,7 @@ export async function persistThreeHolderSnapshot(balances) {
* no fresh snapshot (table missing, never populated, or older than
* MAX_SNAPSHOT_AGE_MS) so the caller can fall back to a live scan.
*/
-export async function readThreeHolderSnapshot() {
+export async function readThreeHolderSnapshot({ allowStale = false } = {}) {
let meta;
try {
[meta] = await sql`select snapshot_at, holder_count from three_holder_snapshot_meta where id = 1`;
@@ -150,7 +150,10 @@ export async function readThreeHolderSnapshot() {
}
if (!meta?.snapshot_at) return null;
const ageMs = Date.now() - new Date(meta.snapshot_at).getTime();
- if (ageMs > MAX_SNAPSHOT_AGE_MS) return null;
+ // `allowStale` is the degraded path: when a cold-fallback live scan can't finish
+ // inside the request budget, serving an hours-old snapshot beats blocking to a
+ // 504. The freshness gate still applies to the normal read.
+ if (!allowStale && ageMs > MAX_SNAPSHOT_AGE_MS) return null;
const rows = await sql`select wallet, balance from three_holder_snapshot`;
const balances = new Map();
@@ -190,6 +193,12 @@ export async function threeHolderCount() {
// it auto-expires if the holder's lambda dies mid-scan.
const COLD_SCAN_LOCK_KEY = 'three:holders:coldscan';
const COLD_SCAN_LOCK_TTL = 90;
+// How long a public READ will wait on the cold-fallback DAS walk before degrading
+// to a stale snapshot. A full walk can take tens of seconds (well past the public
+// endpoints' function budget → 504); cap the wait so the request always returns
+// fast while the scan keeps running in the background to self-heal the snapshot.
+const COLD_SCAN_READ_BUDGET_MS = 18_000;
+const SCAN_DEADLINE = Symbol('threeHolderScanDeadline');
// In-process single-flight: coalesce concurrent cold scans within ONE warm
// lambda so a burst of cache-miss requests on the same instance shares one scan.
let _inflightColdScan = null;
@@ -212,9 +221,23 @@ let _inflightColdScan = null;
export async function threeHolderBalances() {
const snap = await readThreeHolderSnapshot();
if (snap) return snap;
- if (_inflightColdScan) return _inflightColdScan;
- _inflightColdScan = coldFallbackScan().finally(() => { _inflightColdScan = null; });
- return _inflightColdScan;
+ // Cold/stale snapshot: run at most one guarded scan, shared across callers. But
+ // never let the REQUEST block on it past the read budget — a full DAS walk can
+ // exceed the function's maxDuration and 504. The scan runs to completion in the
+ // background (self-healing the snapshot); this read degrades to the most recent
+ // stale snapshot, or an empty map only on a truly cold first deploy.
+ if (!_inflightColdScan) {
+ _inflightColdScan = coldFallbackScan().finally(() => { _inflightColdScan = null; });
+ }
+ const scan = _inflightColdScan;
+ let timer;
+ const budget = new Promise((resolve) => {
+ timer = setTimeout(() => resolve(SCAN_DEADLINE), COLD_SCAN_READ_BUDGET_MS);
+ });
+ const result = await Promise.race([scan.catch(() => SCAN_DEADLINE), budget]).finally(() => clearTimeout(timer));
+ if (result && result !== SCAN_DEADLINE) return result;
+ const stale = await readThreeHolderSnapshot({ allowStale: true }).catch(() => null);
+ return stale || new Map();
}
/**
diff --git a/api/cron/[name].js b/api/cron/[name].js
index bbe0137f4..9a1a8d77b 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -583,8 +583,15 @@ function idxRpcUrls(chainId) {
// is a guaranteed failed attempt + error log each run. With a key, rewrite
// to Ankr's authenticated form (…/<chain>/<KEY>); without one, drop it so
// failover lands on a working public node instead.
+ // PublicNode hard-403s from Vercel's egress range (see PUBLIC_RPCS note). On a
+ // Vercel deployment that endpoint is a guaranteed failed attempt — it both
+ // wastes a failover slot and is the source of the "RPC HTTP 403 from
+ // …publicnode.com" error storm — so drop it there. It stays in the rotation for
+ // self-hosted / non-Vercel runs where it answers normally.
+ const onVercel = !!process.env.VERCEL;
const fallbacks = (PUBLIC_RPCS[chainId] ?? [])
.map((url) => {
+ if (onVercel && url.includes('.publicnode.com')) return null;
if (!url.startsWith('https://rpc.ankr.com/')) return url;
return ankrKey ? `${url}/${ankrKey}` : null;
})
diff --git a/api/galaxy/flows.js b/api/galaxy/flows.js
index 7bd544225..94ffbb67e 100644
--- a/api/galaxy/flows.js
+++ b/api/galaxy/flows.js
@@ -30,7 +30,7 @@
// GET /api/galaxy/flows?network=mainnet|devnet&limit=<n>
import { sql } from '../_lib/db.js';
-import { cors, json, method, serverError, rateLimited } from '../_lib/http.js';
+import { cors, json, method, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { cacheGet, cacheSet } from '../_lib/cache.js';
import {
@@ -43,9 +43,42 @@ import {
} from '../_lib/galaxy-flows.js';
const FEED_TTL_S = 8; // first-page cache — it's a live feed, keep it short
+const LASTGOOD_TTL_S = 600; // last-good snapshot, served if a build is slow/fails
const DEFAULT_LIMIT = 80;
const MAX_LIMIT = 200;
+// The feed query fans across agent_custody_events + a JSONB-keyed counterparty
+// self-join; under load it can run long. Rather than hold the request until
+// Vercel's hard 30s ceiling (a 504 page the galaxy can't render), we cap the
+// build at a soft deadline and degrade to the last-good snapshot or an honestly
+// empty window — both valid 200s the map renders calmly.
+const BUILD_DEADLINE_MS = 22_000;
+
+class FeedDeadline extends Error {}
+
+// A valid, empty feed window — the same shape handleFeed returns — so a degraded
+// response is indistinguishable to the client from a genuinely quiet platform.
+function emptyFeed(network, type) {
+ return {
+ flows: [],
+ has_more: false,
+ next_cursor: null,
+ head_cursor: null,
+ network,
+ type,
+ summary: {
+ count: 0,
+ edges: 0,
+ flares: 0,
+ usd_total: 0,
+ by_kind: { tip: 0, trade: 0, snipe: 0, payment: 0, launch: 0 },
+ window_start: null,
+ window_end: null,
+ },
+ server_time: new Date().toISOString(),
+ };
+}
+
// A flow is only worth animating if it touches a star the viewer can actually
// see, but that gating happens client-side against the loaded snapshot — here we
// return the full public window so the scrubber has real history to replay.
@@ -208,6 +241,26 @@ export default async function handler(req, res) {
const cursor = url.searchParams.get('cursor');
const since = url.searchParams.get('since');
+ // Build the feed but never let a slow query run past the soft deadline. On a
+ // timeout or DB failure, fall back to the last-good snapshot for this
+ // view, and only then to an empty (but valid) window — so the galaxy degrades
+ // to last-known or calm-empty instead of surfacing a 504/502 the map can't use.
+ const lastGoodKey = `galaxy:flows:lastgood:${network}:${type}:${limit}`;
+ async function buildWithDeadline() {
+ let timer;
+ const deadline = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new FeedDeadline('feed build exceeded soft deadline')), BUILD_DEADLINE_MS);
+ });
+ try {
+ const body = await Promise.race([handleFeed({ network, type, limit, cursor, since }), deadline]);
+ // Retain a long-lived copy for the degraded path on a future slow build.
+ cacheSet(lastGoodKey, body, LASTGOOD_TTL_S).catch(() => {});
+ return body;
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
try {
// A first page (no cursor/since) is cached briefly to shield the DB from a
// herd of pollers. A delta poll (`since`) is never cached — it must be live.
@@ -216,17 +269,28 @@ export default async function handler(req, res) {
const cacheKey = `galaxy:flows:${network}:${type}:${limit}`;
let body = await cacheGet(cacheKey);
if (body === null) {
- body = await handleFeed({ network, type, limit, cursor, since });
+ body = await buildWithDeadline();
await cacheSet(cacheKey, body, FEED_TTL_S);
}
res.setHeader('cache-control', 'public, max-age=6');
return json(res, 200, { data: body });
}
- const body = await handleFeed({ network, type, limit, cursor, since });
+ const body = await buildWithDeadline();
return json(res, 200, { data: body });
} catch (e) {
- console.error('[api/galaxy/flows] failed', e?.message, e?.stack);
- return serverError(res, 502, 'galaxy_flows_failed', e);
+ const timedOut = e instanceof FeedDeadline;
+ console.error('[api/galaxy/flows] failed', timedOut ? 'soft-deadline' : e?.message, timedOut ? '' : e?.stack);
+ // Degrade gracefully: a delta poll (`since`) returns nothing new rather than
+ // erroring the live map; any view falls back to its last-good snapshot when
+ // one exists, else an empty window. All are valid 200s.
+ const lastGood = await cacheGet(lastGoodKey).catch(() => null);
+ if (lastGood) {
+ res.setHeader('cache-control', 'public, max-age=6');
+ res.setHeader('x-galaxy-flows-degraded', timedOut ? 'deadline' : 'error');
+ return json(res, 200, { data: lastGood });
+ }
+ res.setHeader('x-galaxy-flows-degraded', timedOut ? 'deadline-empty' : 'error-empty');
+ return json(res, 200, { data: emptyFeed(network, type) });
}
}
diff --git a/pages/three-live.html b/pages/three-live.html
index c57ad98f9..b1b7c5b81 100644
--- a/pages/three-live.html
+++ b/pages/three-live.html
@@ -296,6 +296,14 @@
const introEl = document.getElementById('pl-intro');
const toastEl = document.getElementById('pl-toast');
const el = (id) => document.getElementById(id);
+ // Null-tolerant writers. Privacy/anti-popup browser extensions strip
+ // fixed-position overlays (our HUD is a set of `.pl-overlay` nodes), which
+ // would otherwise make a per-frame `el(id).textContent = …` throw on a null
+ // node and kill the entire render loop — re-firing every animation frame and
+ // flooding error telemetry. These no-op when the node is gone; the WebGL
+ // scene keeps rendering regardless of what the page chrome looks like.
+ const setText = (node, value) => { if (node) node.textContent = value; };
+ const setTextById = (id, value) => { const n = el(id); if (n) n.textContent = value; };
// ── Scene ──────────────────────────────────────────────────────────────
const scene = new THREE.Scene();
@@ -512,13 +520,13 @@
while (recentTrades.length && now - recentTrades[0].t > FLOW_WINDOW_MS) recentTrades.shift();
let buys = 0, sells = 0, vol = 0;
for (const r of recentTrades) { if (r.isBuy) buys++; else sells++; vol += r.usd; }
- el('pl-buys').textContent = String(buys);
- el('pl-sells').textContent = String(sells);
- el('pl-vol60').textContent = vol > 0 ? fmtUsd(vol) : '$0';
+ setTextById('pl-buys', String(buys));
+ setTextById('pl-sells', String(sells));
+ setTextById('pl-vol60', vol > 0 ? fmtUsd(vol) : '$0');
const trades = buys + sells;
const busy = Math.min(1, trades / 30); // 30 trades/min ≈ "busy"
- activityFill.style.width = Math.round(busy * 100) + '%';
- activityReading.textContent = trades === 0 ? 'Quiet' : trades >= 24 ? 'Very busy' : trades >= 8 ? 'Active' : 'Steady';
+ if (activityFill) activityFill.style.width = Math.round(busy * 100) + '%';
+ setText(activityReading, trades === 0 ? 'Quiet' : trades >= 24 ? 'Very busy' : trades >= 8 ? 'Active' : 'Steady');
}
// ── HUD updates ─────────────────────────────────────────────────────────
@@ -539,9 +547,11 @@
if (n >= 1e3) return (n/1e3).toFixed(1) + 'K';
return String(Math.round(n));
}
- function setHero(state, text) { heroEl.dataset.state = state; if (text) statusText.textContent = text; }
+ function setHero(state, text) { if (heroEl) heroEl.dataset.state = state; if (text) setText(statusText, text); }
+ const heroState = () => (heroEl ? heroEl.dataset.state : '');
function pushTicker(isBuy, usd, who) {
+ if (!tickerList) return;
if (tickerEmpty) tickerEmpty.remove();
const li = document.createElement('li');
li.className = isBuy ? 'buy' : 'sell';
@@ -564,22 +574,22 @@
statsFailures = 0;
// Recover from a prior stats-error badge once figures load again. Don't stomp
// the live/quiet badge the trade stream owns — only clear the error state.
- if (heroEl.dataset.state === 'error') {
+ if (heroState() === 'error') {
setHero(recentTrades.length ? 'live' : 'connecting', recentTrades.length ? '$THREE · live' : '$THREE · connecting…');
}
- if (tk.price_usd != null) priceEl.textContent = fmtUsd(tk.price_usd);
+ if (tk.price_usd != null) setText(priceEl, fmtUsd(tk.price_usd));
const chg = Number(tk.price_change_24h);
- if (Number.isFinite(chg)) {
+ if (Number.isFinite(chg) && changeEl) {
changeEl.textContent = (chg >= 0 ? '+' : '') + chg.toFixed(2) + '% · 24h';
changeEl.className = 'chg ' + (chg > 0.01 ? 'up' : chg < -0.01 ? 'down' : 'flat');
}
- el('pl-mcap').textContent = fmtUsd(tk.market_cap);
- el('pl-vol').textContent = fmtUsd(tk.volume_24h);
- el('pl-holders').textContent = tk.holders != null ? fmtNum(tk.holders) : '—';
- el('pl-liq').textContent = fmtUsd(tk.liquidity);
- el('pl-agents').textContent = pr.total_agents != null ? fmtNum(pr.total_agents) : '—';
+ setTextById('pl-mcap', fmtUsd(tk.market_cap));
+ setTextById('pl-vol', fmtUsd(tk.volume_24h));
+ setTextById('pl-holders', tk.holders != null ? fmtNum(tk.holders) : '—');
+ setTextById('pl-liq', fmtUsd(tk.liquidity));
+ setTextById('pl-agents', pr.total_agents != null ? fmtNum(pr.total_agents) : '—');
const burned = (pr.total_agents || 0) * (pr.agent_deploy_burn || 0);
- el('pl-burned').textContent = burned ? fmtNum(burned) : '—';
+ setTextById('pl-burned', burned ? fmtNum(burned) : '—');
// market cap gently scales the core
if (tk.market_cap) {
const mc = Math.min(1, Math.log10(Number(tk.market_cap) + 1) / Math.log10(50_000_000));
@@ -591,7 +601,7 @@
// red and the status line says so, then keep retrying on the poll interval.
// Only flip the badge if a live trade stream isn't already proving the chain
// is reachable; in that case the stats endpoint alone hiccupped.
- if (heroEl.dataset.state !== 'live') setHero('error', '$THREE · stats unavailable');
+ if (heroState() !== 'live') setHero('error', '$THREE · stats unavailable');
showToast(statsFailures >= 2 ? 'Live stats still unavailable — retrying…' : 'Live stats unavailable — retrying…');
}
}
@@ -624,6 +634,7 @@
let toastTimer = null;
function showToast(msg) {
+ if (!toastEl) return;
toastEl.textContent = msg; toastEl.classList.add('is-visible');
clearTimeout(toastTimer); toastTimer = setTimeout(() => toastEl.classList.remove('is-visible'), 3200);
}
@@ -679,7 +690,7 @@
}
// idle/quiet state
- if (lastTradeAt && now - lastTradeAt > 25_000 && heroEl.dataset.state === 'live') setHero('quiet', '$THREE · market quiet');
+ if (lastTradeAt && now - lastTradeAt > 25_000 && heroState() === 'live') setHero('quiet', '$THREE · market quiet');
updateFlowCounters(now);
controls.update();
diff --git a/public/error-reporter.js b/public/error-reporter.js
index a12da5534..b4cd6365c 100644
--- a/public/error-reporter.js
+++ b/public/error-reporter.js
@@ -271,6 +271,23 @@
) {
return true;
}
+ // A promise rejected with a bare DOM Event rather than an Error — the reason
+ // IS the event object, so it carries no message and no stack, serializing to
+ // just `{"isTrusted":true}` with a constructor name of Event/ErrorEvent/
+ // ProgressEvent/etc. This is what surfaces when an element or stream's onerror
+ // is wired straight as a promise's reject callback (an <img>/<audio> failing to
+ // load, an EventSource/WebSocket erroring): the element owns its own onerror
+ // recovery and there is nothing in the event to act on. Guarded by "no stack"
+ // and the isTrusted shape so a genuine error that merely happens to be named
+ // with an Event suffix still reports.
+ if (
+ report.type === 'unhandledrejection' &&
+ !report.stack &&
+ /Event$/.test(report.name || '') &&
+ (!report.message || /^\{"isTrusted":(?:true|false)\}$/.test(report.message.trim()))
+ ) {
+ return true;
+ }
// A ReferenceError naming a known injected webview/extension bridge global.
if (
report.message &&
diff --git a/src/dashboard-next/api.js b/src/dashboard-next/api.js
index 554397367..8210ab078 100644
--- a/src/dashboard-next/api.js
+++ b/src/dashboard-next/api.js
@@ -81,8 +81,17 @@ export function getMe() {
return data || null;
})
.catch((err) => {
- if (err.status === 401) return null;
- throw err;
+ // A 401 is the normal "no live session" answer. We also treat any other
+ // non-success (404 from deploy-skew/cold-start routing, 5xx, or a network
+ // failure) as "session could not be confirmed" → null, rather than letting
+ // an ApiError escape: every dashboard page calls this first via
+ // requireUser(), and an unguarded throw here surfaced as an uncaught
+ // `ApiError http_404` rejection across all of them. Returning null routes
+ // the visitor through requireUser()'s /login redirect, which is
+ // self-healing — a still-valid session cookie bounces them straight back.
+ if (err && err.status === 401) return null;
+ console.warn('[dashboard] session check failed, treating as signed-out:', err?.status ?? err?.message ?? err);
+ return null;
});
}
return mePromise;