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(crypto): give a holder read enough budget to actually use the RPC failover chain

nirholas0c4aacf15947
diff --git a/api/_lib/crypto-token-holders.js b/api/_lib/crypto-token-holders.js
index ddea6ab79..3e2e9bc5c 100644
--- a/api/_lib/crypto-token-holders.js
+++ b/api/_lib/crypto-token-holders.js
@@ -21,7 +21,14 @@
import { parseMintAccount } from '../v1/token/security.js';
import { solanaRpcEndpoints, makeRotatingFetch } from './solana/connection.js';
-const RPC_TIMEOUT_MS = 8000;
+// Budget for ONE JSON-RPC read across the WHOLE failover chain, not per
+// endpoint. makeRotatingFetch bounds each attempt itself (10s) and composes the
+// caller's signal with AbortSignal.any, so a caller cap below that bound spends
+// the entire budget on the first endpoint and every rotation after it aborts
+// instantly: at 8s a read that hit one slow lane logged "all 9 endpoints failed
+// this request" and answered 503, while a retry seconds later succeeded. Sized
+// to cover a couple of real attempts, matching the wallet-activity lane.
+const RPC_TIMEOUT_MS = 25_000;
// Helius DAS getTokenAccounts pages at up to 1000 accounts; cap the walk so a
// mega-token (millions of accounts) can't burn the invocation. Within the cap
@@ -127,21 +134,19 @@ export async function heliusHolderWalk(mint, { fetchImpl = fetch } = {}) {
const accounts = [];
let complete = false;
for (let page = 1; page <= HELIUS_MAX_PAGES; page++) {
- const r = await fetchImpl(url, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 'holders',
- method: 'getTokenAccounts',
- params: { mint, page, limit: HELIUS_PAGE_LIMIT },
- }),
- signal: AbortSignal.timeout(RPC_TIMEOUT_MS),
- });
- if (!r.ok) throw new Error(`helius getTokenAccounts ${r.status}`);
- const json = await r.json();
- const batch = json?.result?.token_accounts;
- if (!Array.isArray(batch)) throw new Error('helius getTokenAccounts: malformed response');
+ let batch;
+ try {
+ batch = await heliusPage(url, mint, page, fetchImpl);
+ } catch (err) {
+ // A page that fails mid-walk does not invalidate the pages already in
+ // hand: 1000 accounts is far more than any top-N needs, and discarding
+ // them dropped the read onto the keyless lane, whose
+ // getTokenLargestAccounts most public RPCs refuse. Keep what we have and
+ // mark the walk incomplete so the holder COUNT is still withheld.
+ if (!accounts.length) throw err;
+ console.log(`[crypto-holders] helius walk stopped at page ${page}: ${err.message}`);
+ return { accounts, complete: false };
+ }
accounts.push(...batch.map((a) => ({ owner: a.owner || null, address: a.address, amount: a.amount })));
if (batch.length < HELIUS_PAGE_LIMIT) {
complete = true;
@@ -151,6 +156,36 @@ export async function heliusHolderWalk(mint, { fetchImpl = fetch } = {}) {
return { accounts, complete };
}
+// One page of the walk. Helius answers an exhausted plan with HTTP 200 and the
+// plain-text body "max usage reached", so parsing the body as JSON unconditionally
+// surfaced a bare SyntaxError with no hint that the key was the problem. Read the
+// text first and name what came back.
+async function heliusPage(url, mint, page, fetchImpl) {
+ const r = await fetchImpl(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 'holders',
+ method: 'getTokenAccounts',
+ params: { mint, page, limit: HELIUS_PAGE_LIMIT },
+ }),
+ signal: AbortSignal.timeout(RPC_TIMEOUT_MS),
+ });
+ const text = await r.text();
+ if (!r.ok) throw new Error(`helius getTokenAccounts ${r.status}: ${text.slice(0, 80)}`);
+ let json;
+ try {
+ json = JSON.parse(text);
+ } catch {
+ throw new Error(`helius getTokenAccounts: non-JSON response "${text.slice(0, 60)}"`);
+ }
+ if (json?.error) throw new Error(`helius getTokenAccounts: ${JSON.stringify(json.error).slice(0, 120)}`);
+ const batch = json?.result?.token_accounts;
+ if (!Array.isArray(batch)) throw new Error('helius getTokenAccounts: malformed response');
+ return batch;
+}
+
// Default network dependency bundle — injectable for tests.
export function realHolderDeps() {
const rpcFetch = makeRotatingFetch(solanaRpcEndpoints('mainnet'));
@@ -232,7 +267,12 @@ export async function composeTokenHolders({ address, limit = DEFAULT_LIMIT }, de
};
}
}
- } catch { /* keyed path failed — fall through to the keyless truth */ }
+ } catch (err) {
+ // Named, not swallowed: an exhausted Helius plan silently demoted every
+ // holder read to the keyless lane, which then 503'd roughly one call in
+ // three with nothing in the logs pointing at the cause.
+ console.log(`[crypto-holders] helius path unavailable, falling back to keyless RPC: ${err.message}`);
+ }
// Keyless: top-20 largest token accounts + owner resolution.
// `largestAnswered` requires a REAL array answer. A JSON-RPC error envelope
diff --git a/api/_lib/crypto-token-security.js b/api/_lib/crypto-token-security.js
index 3bcece464..5c3197c1c 100644
--- a/api/_lib/crypto-token-security.js
+++ b/api/_lib/crypto-token-security.js
@@ -29,7 +29,14 @@ import { isGraduated } from './pump-launch-feed.js';
import { solanaRpcEndpoints, makeRotatingFetch } from './solana/connection.js';
const METADATA_PROGRAM = new PublicKey('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s');
-const RPC_TIMEOUT_MS = 8000;
+// Budget for ONE JSON-RPC read across the WHOLE failover chain, not per
+// endpoint. makeRotatingFetch bounds each attempt itself (10s) and composes the
+// caller's signal with AbortSignal.any, so a caller cap below that bound spends
+// the entire budget on the first endpoint and every rotation after it aborts
+// instantly: at 8s a read that hit one slow lane logged "all 9 endpoints failed
+// this request" and answered 503, while a retry seconds later succeeded. Sized
+// to cover a couple of real attempts, matching the wallet-activity lane.
+const RPC_TIMEOUT_MS = 25_000;
// Concentration thresholds shared with the v1 reader's flags, so the two
// security surfaces can never disagree about what "concentrated" means.
diff --git a/api/v1/token/security.js b/api/v1/token/security.js
index 8e9924a06..50dbd6c14 100644
--- a/api/v1/token/security.js
+++ b/api/v1/token/security.js
@@ -26,7 +26,14 @@ import { isValidSolanaAddress, isValidEvmAddress } from '../../_lib/validate.js'
import { fetchTokenMarket } from '../../_lib/token-market.js';
import { solanaRpcEndpoints, makeRotatingFetch } from '../../_lib/solana/connection.js';
-const RPC_TIMEOUT_MS = 8000;
+// Budget for ONE JSON-RPC read across the WHOLE failover chain, not per
+// endpoint. makeRotatingFetch bounds each attempt itself (10s) and composes the
+// caller's signal with AbortSignal.any, so a caller cap below that bound spends
+// the entire budget on the first endpoint and every rotation after it aborts
+// instantly: at 8s a read that hit one slow lane logged "all 9 endpoints failed
+// this request" and answered 503, while a retry seconds later succeeded. Sized
+// to cover a couple of real attempts, matching the wallet-activity lane.
+const RPC_TIMEOUT_MS = 25_000;
const DAY_MS = 86_400_000;
// One JSON-RPC call across the platform's failover chain. Resolves with the raw
diff --git a/tests/crypto-token-holders.test.js b/tests/crypto-token-holders.test.js
index 0df8d6d0f..ec436d8aa 100644
--- a/tests/crypto-token-holders.test.js
+++ b/tests/crypto-token-holders.test.js
@@ -6,6 +6,7 @@ import {
top10PctOf,
deriveConcentration,
composeTokenHolders,
+ heliusHolderWalk,
CONCENTRATION_HIGH_PCT,
CONCENTRATION_MEDIUM_PCT,
} from '../api/_lib/crypto-token-holders.js';
@@ -213,3 +214,82 @@ describe('composeTokenHolders — states', () => {
expect(r.status).toBe('upstream_down');
});
});
+
+// The keyed walk is the preferred lane; when it silently dies every holder read
+// lands on the keyless one, whose getTokenLargestAccounts most public RPCs
+// refuse. These pin the failure shapes that took it down without a trace.
+describe('heliusHolderWalk failure shapes', () => {
+ const MINT = THREE;
+ const page = (n) => ({
+ ok: true,
+ status: 200,
+ text: async () => JSON.stringify({
+ result: { token_accounts: Array.from({ length: n }, (_, i) => ({ owner: W1, address: `a${i}`, amount: '1' })) },
+ }),
+ });
+
+ const withKey = async (fn) => {
+ const had = process.env.HELIUS_API_KEY;
+ process.env.HELIUS_API_KEY = 'test-key';
+ try {
+ return await fn();
+ } finally {
+ if (had === undefined) delete process.env.HELIUS_API_KEY;
+ else process.env.HELIUS_API_KEY = had;
+ }
+ };
+
+ it('returns null without a key so the caller uses the keyless lane', async () => {
+ const had = process.env.HELIUS_API_KEY;
+ delete process.env.HELIUS_API_KEY;
+ try {
+ expect(await heliusHolderWalk(MINT, { fetchImpl: async () => page(0) })).toBeNull();
+ } finally {
+ if (had !== undefined) process.env.HELIUS_API_KEY = had;
+ }
+ });
+
+ it('names an exhausted plan instead of throwing a bare JSON parse error', async () => {
+ await withKey(async () => {
+ const fetchImpl = async () => ({ ok: true, status: 200, text: async () => 'max usage reached' });
+ await expect(heliusHolderWalk(MINT, { fetchImpl })).rejects.toThrow(/non-JSON response .*max usage reached/);
+ });
+ });
+
+ it('names a JSON-RPC error envelope', async () => {
+ await withKey(async () => {
+ const fetchImpl = async () => ({ ok: true, status: 200, text: async () => JSON.stringify({ error: { code: -32603, message: 'nope' } }) });
+ await expect(heliusHolderWalk(MINT, { fetchImpl })).rejects.toThrow(/nope/);
+ });
+ });
+
+ it('keeps the pages already walked when a later page fails', async () => {
+ await withKey(async () => {
+ let call = 0;
+ const fetchImpl = async () => {
+ call++;
+ if (call === 1) return page(1000);
+ throw new Error('gateway timeout');
+ };
+ const out = await heliusHolderWalk(MINT, { fetchImpl });
+ expect(out.accounts).toHaveLength(1000);
+ // Incomplete, so the holder COUNT is still withheld rather than guessed.
+ expect(out.complete).toBe(false);
+ });
+ });
+
+ it('still throws when the very first page fails and there is nothing to keep', async () => {
+ await withKey(async () => {
+ const fetchImpl = async () => { throw new Error('gateway timeout'); };
+ await expect(heliusHolderWalk(MINT, { fetchImpl })).rejects.toThrow(/gateway timeout/);
+ });
+ });
+
+ it('marks a short page as a complete walk', async () => {
+ await withKey(async () => {
+ const out = await heliusHolderWalk(MINT, { fetchImpl: async () => page(3) });
+ expect(out.complete).toBe(true);
+ expect(out.accounts).toHaveLength(3);
+ });
+ });
+});