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.

feat: provider failover and last-known-good fallbacks for Helius DAS paths

miniaturizationa5264bde9f83
diff --git a/api/_lib/coin/cohorts-live.js b/api/_lib/coin/cohorts-live.js
index 18583074d..463457d00 100644
--- a/api/_lib/coin/cohorts-live.js
+++ b/api/_lib/coin/cohorts-live.js
@@ -29,6 +29,29 @@ import { cacheGet, cacheSet } from '../cache.js';
// largest reduction in Helius credit spend with no change to what users see.
const LIVE_HOLDER_TTL_SECONDS = 180;
+// Last-known-good copy kept far longer than the fresh window. It is read ONLY
+// when a live Helius DAS walk fails (429 / quota exhausted / outage), so a Helius
+// problem degrades the cohorts panel to slightly-stale real data instead of a
+// hard 503. getTokenAccounts is Helius-proprietary (the rotating multi-provider
+// RPC chain can't serve it), so this stale tier is the failover for this path.
+const LIVE_HOLDER_STALE_TTL_SECONDS = 7 * 24 * 60 * 60; // 7d
+
+// BigInt can't ride through JSON, so the cached shape stores units as decimal
+// strings. These two helpers are the single source of truth for that conversion.
+function serializeHolderSet(holders, totalUnits) {
+ return {
+ holders: holders.map((h) => ({ wallet: h.wallet, units: h.units.toString() })),
+ totalUnits: totalUnits.toString(),
+ };
+}
+
+function deserializeHolderSet(cached) {
+ return {
+ holders: cached.holders.map((h) => ({ wallet: h.wallet, units: BigInt(h.units) })),
+ totalUnits: BigInt(cached.totalUnits),
+ };
+}
+
// Cohorts derivable from current balances alone (the rest need snapshot history).
const LIVE_COHORT_IDS = new Set(['holders', 'whales']);
@@ -86,39 +109,48 @@ function whaleCutoff(holders, topPct) {
*/
export async function liveHolderSet({ mint, network = 'mainnet' }) {
const cacheKey = `live-holders:${network}:${mint}`;
+ const staleKey = `live-holders-stale:${network}:${mint}`;
- // JSON can't carry BigInt, so the cached shape stores units as decimal
- // strings; rehydrate to BigInt on read so callers are oblivious to the cache.
+ // Fresh hit — within the short window, serve straight from cache.
const cached = await cacheGet(cacheKey).catch(() => null);
if (cached && Array.isArray(cached.holders)) {
- return {
- holders: cached.holders.map((h) => ({ wallet: h.wallet, units: BigInt(h.units) })),
- totalUnits: BigInt(cached.totalUnits),
- };
+ return { ...deserializeHolderSet(cached), stale: false };
}
- const balances = await fetchHolderBalances({ mint, network });
- const holders = [...balances.entries()]
- .map(([wallet, units]) => ({ wallet, units }))
- .filter((h) => h.units > 0n)
- .sort((a, b) => (b.units > a.units ? 1 : b.units < a.units ? -1 : 0));
- const totalUnits = holders.reduce((sum, h) => sum + h.units, 0n);
-
- // Don't cache empty results (an unconfigured key or transient RPC failure
- // returns an empty map) — caching a 0-holder set would mask recovery for the
- // whole TTL. A genuinely empty mint is harmless to re-walk; it's one cheap call.
- if (holders.length > 0) {
- await cacheSet(
- cacheKey,
- {
- holders: holders.map((h) => ({ wallet: h.wallet, units: h.units.toString() })),
- totalUnits: totalUnits.toString(),
- },
- LIVE_HOLDER_TTL_SECONDS,
- ).catch(() => {});
+ try {
+ const balances = await fetchHolderBalances({ mint, network });
+ const holders = [...balances.entries()]
+ .map(([wallet, units]) => ({ wallet, units }))
+ .filter((h) => h.units > 0n)
+ .sort((a, b) => (b.units > a.units ? 1 : b.units < a.units ? -1 : 0));
+ const totalUnits = holders.reduce((sum, h) => sum + h.units, 0n);
+
+ // Don't cache empty results (an unconfigured key or transient RPC failure
+ // returns an empty map) — caching a 0-holder set would mask recovery for the
+ // whole TTL. A genuinely empty mint is harmless to re-walk; one cheap call.
+ if (holders.length > 0) {
+ const payload = serializeHolderSet(holders, totalUnits);
+ // Fresh cache collapses page-view bursts; the long-lived stale copy is the
+ // failover snapshot, refreshed on every successful walk.
+ await cacheSet(cacheKey, payload, LIVE_HOLDER_TTL_SECONDS).catch(() => {});
+ await cacheSet(staleKey, payload, LIVE_HOLDER_STALE_TTL_SECONDS).catch(() => {});
+ }
+
+ return { holders, totalUnits, stale: false };
+ } catch (err) {
+ // Helius DAS is unreachable (429 / quota / outage). Fall back to the last
+ // known-good snapshot so the cohorts panel degrades to stale-but-real data
+ // instead of failing. Only rethrow if we have nothing to serve.
+ const lastGood = await cacheGet(staleKey).catch(() => null);
+ if (lastGood && Array.isArray(lastGood.holders)) {
+ console.warn(
+ '[cohorts-live] Helius DAS failed for %s — serving last-known-good holder set',
+ mint,
+ );
+ return { ...deserializeHolderSet(lastGood), stale: true };
+ }
+ throw err;
}
-
- return { holders, totalUnits };
}
/**
diff --git a/api/coin/[mint]/cohorts.js b/api/coin/[mint]/cohorts.js
index 0425fa681..38d9dd995 100644
--- a/api/coin/[mint]/cohorts.js
+++ b/api/coin/[mint]/cohorts.js
@@ -118,10 +118,12 @@ async function serveLiveCohorts(req, res, { mint, agentToken }) {
// ── Overview: definitions + counts + concentration (public) ──────────────
if (!cohortId) {
const { holderCount, counts, concentration } = liveCohortCounts(set, params);
- res.setHeader('Cache-Control', OVERVIEW_CACHE);
+ // A stale set came from the failover snapshot (Helius was unreachable) — use a
+ // shorter cache so the panel re-attempts live data sooner, and label it.
+ res.setHeader('Cache-Control', set.stale ? 'public, max-age=15, s-maxage=30' : OVERVIEW_CACHE);
return json(res, 200, {
coin: coinInfo,
- source: 'live',
+ source: set.stale ? 'live-stale' : 'live',
lastSnapshotAt: null,
holderCount,
concentration,
@@ -162,7 +164,7 @@ async function serveLiveCohorts(req, res, { mint, agentToken }) {
return json(res, 200, {
coin: coinInfo,
- source: 'live',
+ source: set.stale ? 'live-stale' : 'live',
cohort: cohortId,
sampled,
sample: sample ?? null,
diff --git a/api/nft/resolve.js b/api/nft/resolve.js
index bd53b4e87..ff3669484 100644
--- a/api/nft/resolve.js
+++ b/api/nft/resolve.js
@@ -9,6 +9,10 @@ import { cacheGet, cacheSet } from '../_lib/cache.js';
// upstream every time. Cache the resolved descriptor by chain:id so a given
// asset is fetched from the provider at most once per TTL.
const RESOLVE_TTL_SECONDS = 6 * 60 * 60; // 6h
+// Last-known-good copy kept far longer, read ONLY when the upstream provider is
+// unreachable. NFT metadata is effectively immutable, so serving a long-stale
+// descriptor during a Helius/Alchemy outage is correct — far better than a 502.
+const RESOLVE_STALE_TTL_SECONDS = 30 * 24 * 60 * 60; // 30d
export default wrap(async (req, res) => {
if (cors(req, res)) return;
@@ -27,6 +31,7 @@ export default wrap(async (req, res) => {
if (!id) return error(res, 400, 'bad_request', 'id required');
const cacheKey = `nft-resolve:${chain}:${id}`;
+ const staleKey = `nft-resolve-stale:${chain}:${id}`;
const cached = await cacheGet(cacheKey).catch(() => null);
if (cached) return json(res, 200, cached);
@@ -36,16 +41,43 @@ export default wrap(async (req, res) => {
const ceiling = await limits.heliusDasGlobal();
if (!ceiling.success) return rateLimited(res, ceiling);
+ // Persist a resolved descriptor to both the fresh and long-lived stale tiers.
+ const store = async (result) => {
+ await cacheSet(cacheKey, result, RESOLVE_TTL_SECONDS).catch(() => {});
+ await cacheSet(staleKey, result, RESOLVE_STALE_TTL_SECONDS).catch(() => {});
+ return result;
+ };
+ // Provider unreachable → serve the last-known-good descriptor if we have one,
+ // else fall through to the caller's error. Immutable metadata makes this safe.
+ const serveStaleOr = async (onMiss) => {
+ const lastGood = await cacheGet(staleKey).catch(() => null);
+ if (lastGood) {
+ console.warn('[nft/resolve] upstream unreachable — serving last-known-good for %s', cacheKey);
+ return json(res, 200, { ...lastGood, stale: true });
+ }
+ return onMiss();
+ };
+
if (chain === 'solana') {
- const resp = await fetch(env.SOLANA_RPC_URL, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getAsset', params: { id } }),
- });
+ let resp;
+ try {
+ resp = await fetch(env.SOLANA_RPC_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getAsset', params: { id } }),
+ });
+ } catch (err) {
+ console.error('[nft/resolve] Helius network error', err?.message);
+ return serveStaleOr(() =>
+ serverError(res, 502, 'upstream_error', new Error('Helius unreachable')),
+ );
+ }
if (!resp.ok) {
- const txt = await resp.text();
+ const txt = await resp.text().catch(() => '');
console.error('[nft/resolve] Helius error', resp.status, txt);
- return serverError(res, 502, 'upstream_error', new Error(`Helius error ${resp.status}`));
+ return serveStaleOr(() =>
+ serverError(res, 502, 'upstream_error', new Error(`Helius error ${resp.status}`)),
+ );
}
const data = await resp.json();
if (data.error) {
@@ -60,14 +92,13 @@ export default wrap(async (req, res) => {
asset?.content?.links?.image ||
files.find((f) => f.mime && f.mime.startsWith('image/'))?.uri ||
null;
- const result = {
+ const result = await store({
name,
image: imageUrl,
model: modelFile?.uri || null,
mime: modelFile?.mime || null,
source: 'helius',
- };
- await cacheSet(cacheKey, result, RESOLVE_TTL_SECONDS).catch(() => {});
+ });
return json(res, 200, result);
}
@@ -84,14 +115,24 @@ export default wrap(async (req, res) => {
const apiKey = env.ALCHEMY_API_KEY;
const url = `https://eth-mainnet.g.alchemy.com/nft/v3/${apiKey}/getNFTMetadata?contractAddress=${encodeURIComponent(contractAddress)}&tokenId=${encodeURIComponent(tokenId)}`;
- const resp = await fetch(url);
+ let resp;
+ try {
+ resp = await fetch(url);
+ } catch (err) {
+ console.error('[nft/resolve] Alchemy network error', err?.message);
+ return serveStaleOr(() =>
+ serverError(res, 502, 'upstream_error', new Error('Alchemy unreachable')),
+ );
+ }
if (!resp.ok) {
- const txt = await resp.text();
+ const txt = await resp.text().catch(() => '');
if (resp.status === 404) {
return error(res, 404, 'not_found', `Alchemy error ${resp.status}: ${txt}`);
}
console.error('[nft/resolve] Alchemy error', resp.status, txt);
- return serverError(res, 502, 'upstream_error', new Error(`Alchemy error ${resp.status}`));
+ return serveStaleOr(() =>
+ serverError(res, 502, 'upstream_error', new Error(`Alchemy error ${resp.status}`)),
+ );
}
const data = await resp.json();
const name = data.name || data.contract?.name || id;
@@ -106,7 +147,6 @@ export default wrap(async (req, res) => {
mime = animationUrl.toLowerCase().endsWith('.gltf') ? 'model/gltf+json' : 'model/gltf-binary';
}
- const result = { name, image: imageUrl, model, mime, source: 'alchemy' };
- await cacheSet(cacheKey, result, RESOLVE_TTL_SECONDS).catch(() => {});
+ const result = await store({ name, image: imageUrl, model, mime, source: 'alchemy' });
return json(res, 200, result);
});
diff --git a/api/tx/explain.js b/api/tx/explain.js
index dfc8d1fb1..dcb14f65e 100644
--- a/api/tx/explain.js
+++ b/api/tx/explain.js
@@ -4,6 +4,58 @@ import { wrap, cors, error, json, readJson, method, rateLimited } from '../_lib/
import { limits, clientIp } from '../_lib/rate-limit.js';
import { llmComplete, llmConfigured } from '../_lib/llm.js';
import { cacheGet, cacheSet } from '../_lib/cache.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
+
+// Reduce a raw parsed transaction to the same shape Helius's enhanced endpoint
+// returns, so the fallback path is transparent to the LLM summary and the UI.
+// Native transfers come from lamport balance deltas; token transfers from the
+// pre/post SPL token balances in the tx meta. No `description`/`type` (those are
+// Helius value-adds) — the LLM summary fills that role downstream.
+function parsedTxToExplain(tx) {
+ if (!tx) return null;
+ const meta = tx.meta || {};
+ const keys = (tx.transaction?.message?.accountKeys || []).map((k) =>
+ typeof k === 'string' ? k : k?.pubkey?.toString?.() ?? String(k?.pubkey ?? ''),
+ );
+
+ const nativeTransfers = [];
+ const pre = meta.preBalances || [];
+ const post = meta.postBalances || [];
+ for (let i = 0; i < keys.length; i++) {
+ const delta = (post[i] ?? 0) - (pre[i] ?? 0);
+ if (delta !== 0) nativeTransfers.push({ account: keys[i], amount: delta });
+ }
+
+ const byKey = (arr) => {
+ const m = new Map();
+ for (const b of arr || []) m.set(`${b.accountIndex}:${b.mint}`, b);
+ return m;
+ };
+ const preTok = byKey(meta.preTokenBalances);
+ const postTok = byKey(meta.postTokenBalances);
+ const tokenTransfers = [];
+ for (const k of new Set([...preTok.keys(), ...postTok.keys()])) {
+ const p = preTok.get(k);
+ const q = postTok.get(k);
+ const delta = BigInt(q?.uiTokenAmount?.amount ?? '0') - BigInt(p?.uiTokenAmount?.amount ?? '0');
+ if (delta === 0n) continue;
+ const ref = q || p;
+ tokenTransfers.push({
+ mint: ref.mint,
+ owner: ref.owner || null,
+ rawTokenAmount: { tokenAmount: delta.toString(), decimals: ref.uiTokenAmount?.decimals ?? null },
+ });
+ }
+
+ return {
+ tokenTransfers,
+ nativeTransfers,
+ description: '',
+ type: '',
+ feePayer: keys[0] || '',
+ source: 'rpc-fallback',
+ };
+}
// A confirmed transaction is immutable, but the Helius enhanced-tx (/v0) and
// Alchemy RPC calls behind this endpoint — plus the LLM summary — were recomputed
@@ -60,52 +112,103 @@ export default wrap(async (req, res) => {
let txData;
if (chain === 'solana') {
- const resp = await fetch(
- `https://api.helius.xyz/v0/transactions/?api-key=${env.HELIUS_API_KEY}`,
- {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ transactions: [sig] }),
- },
- );
- if (!resp.ok) {
- console.error('[tx/explain] Helius error', resp.status, await resp.text().catch(() => ''));
- return error(res, 502, 'upstream_error', 'transaction lookup failed upstream');
+ // Primary: Helius enhanced /v0 (rich description + type). On any upstream
+ // failure, fall back to getParsedTransaction over the rotating multi-provider
+ // RPC chain (Helius → Alchemy → Ankr → PublicNode → public) and reconstruct
+ // the transfer shape ourselves — so a Helius outage still explains the tx.
+ let enhanced = null;
+ try {
+ const resp = await fetch(
+ `https://api.helius.xyz/v0/transactions/?api-key=${env.HELIUS_API_KEY}`,
+ {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ transactions: [sig] }),
+ },
+ );
+ if (resp.ok) {
+ const data = await resp.json();
+ if (Array.isArray(data) && data.length > 0) enhanced = data[0];
+ } else {
+ console.warn('[tx/explain] Helius enhanced %s — falling back to RPC', resp.status);
+ }
+ } catch (err) {
+ console.warn('[tx/explain] Helius enhanced unreachable — falling back to RPC:', err?.message);
}
- const data = await resp.json();
- if (!Array.isArray(data) || data.length === 0) {
- return error(res, 404, 'not_found', 'Transaction not found');
+
+ if (enhanced) {
+ txData = {
+ tokenTransfers: enhanced.tokenTransfers || [],
+ nativeTransfers: enhanced.nativeTransfers || [],
+ description: enhanced.description || '',
+ type: enhanced.type || '',
+ feePayer: enhanced.feePayer || '',
+ };
+ } else {
+ let parsed = null;
+ try {
+ const conn = solanaConnection({ network: 'mainnet' });
+ parsed = await conn.getParsedTransaction(sig, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ } catch (err) {
+ console.error('[tx/explain] RPC fallback failed:', err?.message);
+ return error(res, 502, 'upstream_error', 'transaction lookup failed upstream');
+ }
+ if (!parsed) {
+ return error(res, 404, 'not_found', 'Transaction not found');
+ }
+ txData = parsedTxToExplain(parsed);
}
- const tx = data[0];
- txData = {
- tokenTransfers: tx.tokenTransfers || [],
- nativeTransfers: tx.nativeTransfers || [],
- description: tx.description || '',
- type: tx.type || '',
- feePayer: tx.feePayer || '',
- };
} else {
- const rpcUrl = `https://eth-mainnet.g.alchemy.com/v2/${env.ALCHEMY_API_KEY}`;
- const rpc = (id, methodName, params) =>
- fetch(rpcUrl, {
+ // EVM failover chain: keyed Alchemy first, then an optional configured RPC,
+ // then keyless public nodes — so an Alchemy outage or quota cap still
+ // resolves the tx. Try each until one responds cleanly.
+ const evmEndpoints = [
+ env.ALCHEMY_API_KEY ? `https://eth-mainnet.g.alchemy.com/v2/${env.ALCHEMY_API_KEY}` : null,
+ env.MAINNET_RPC_URL || null,
+ 'https://ethereum-rpc.publicnode.com',
+ 'https://eth.llamarpc.com',
+ ].filter(Boolean);
+
+ const rpcAt = (url) => (id, methodName, params) =>
+ fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id, method: methodName, params }),
});
- const [txResp, receiptResp] = await Promise.all([
- rpc(1, 'eth_getTransactionByHash', [sig]),
- rpc(2, 'eth_getTransactionReceipt', [sig]),
- ]);
-
- if (!txResp.ok || !receiptResp.ok) {
- return error(res, 502, 'upstream_error', 'Alchemy RPC request failed');
+ let txJson = null;
+ let receiptJson = null;
+ let lastErr = 'no endpoints configured';
+ for (const url of evmEndpoints) {
+ try {
+ const rpc = rpcAt(url);
+ const [txResp, receiptResp] = await Promise.all([
+ rpc(1, 'eth_getTransactionByHash', [sig]),
+ rpc(2, 'eth_getTransactionReceipt', [sig]),
+ ]);
+ if (!txResp.ok || !receiptResp.ok) {
+ lastErr = `status ${txResp.status}/${receiptResp.status}`;
+ continue;
+ }
+ const [tj, rj] = await Promise.all([txResp.json(), receiptResp.json()]);
+ if (tj.error) {
+ lastErr = tj.error?.message || 'rpc error';
+ continue;
+ }
+ // Clean response (result may legitimately be null for an unknown tx).
+ txJson = tj;
+ receiptJson = rj;
+ break;
+ } catch (err) {
+ lastErr = err?.message || 'network error';
+ }
}
- const [txJson, receiptJson] = await Promise.all([txResp.json(), receiptResp.json()]);
-
- if (txJson.error) {
- console.error('[tx/explain] Alchemy RPC error', txJson.error?.message);
+ if (!txJson) {
+ console.error('[tx/explain] all EVM RPC endpoints failed:', lastErr);
return error(res, 502, 'upstream_error', 'transaction lookup failed upstream');
}
if (!txJson.result) {
@@ -113,7 +216,7 @@ export default wrap(async (req, res) => {
}
const tx = txJson.result;
- const receipt = receiptJson.result;
+ const receipt = receiptJson?.result;
const logs = [];
for (const log of receipt?.logs || []) {
if (log.topics[0] !== ERC20_TRANSFER_TOPIC) continue;