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(solana): shared read guards so a dead RPC serves a cached blockhash, skips network reads for known mints, and fails open on ATA probes
nirholasfea93dddf3bf
diff --git a/api/_lib/solana/read-guards.js b/api/_lib/solana/read-guards.jsnew file mode 100644index 000000000..6dd323adb--- /dev/null+++ b/api/_lib/solana/read-guards.js@@ -0,0 +1,342 @@+// Guarded Solana reads for the money paths.+//+// Every checkout, payout, and funding handler performs the same three reads+// before it can build a transaction: the mint's decimals, whether the+// recipient's ATA exists, and a recent blockhash. Each one used to be a bare+// web3.js call, so a single transport failure inside the RPC rotation+// (`TypeError: fetch failed` on getAccountInfo for the USDC mint, or+// `failed to get recent blockhash`) surfaced as an opaque `[api] unhandled` 500+// on a request that could have been served from what we already knew.+//+// These helpers were proven on the USDC checkout modal (api/x402-checkout.js)+// and are generalised here so every money path shares one posture:+//+// mintDecimals never touches the network for canonical mints, and+// tags a transport failure as a retryable 503+// ataExists fails OPEN to "missing" (the create is idempotent)+// getRecentBlockhash serves a cached blockhash inside its validity window+// when the chain cannot be read, per process and+// through the shared cache so other instances benefit+// readAccountInfoOrNull null on transport failure for decorative reads+// readBalanceOrNull null lamports on transport failure+// rpcUnavailableError the typed error every handler boundary can rely on+// respondRpcUnavailable 503 rpc_unavailable + Retry-After: 15 at the boundary++import { getMint } from '@solana/spl-token';+import { cacheGet, cacheSet } from '../cache.js';+import { isTransientRpcError } from './connection.js';+import { error as httpError } from '../http.js';++/** The $THREE mint (pump.fun launch, 6 decimals like every pump.fun mint). */+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// Decimals for canonical mints are immutable and universally known. Resolving+// them locally skips an RPC round-trip on every hot path (USDC is the default+// settlement asset) and immunizes transaction building against a flaky or+// rate-limited RPC returning 404 / fetch failed on getAccountInfo for the mint,+// the failure mode that 500'd every USDC checkout while the public endpoint was+// cooling.+export const WELL_KNOWN_MINT_DECIMALS = new Map([+ ['EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', 6], // USDC (mainnet)+ ['Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', 6], // USDT (mainnet)+ ['So11111111111111111111111111111111111111112', 9], // wrapped SOL+ [THREE_MINT, 6], // $THREE+]);++export const RPC_UNAVAILABLE = 'rpc_unavailable';+export const RPC_RETRY_AFTER_SECONDS = 15;++const MINT_DECIMALS_TTL_MS = 5 * 60 * 1000;+const MINT_DECIMALS_SHARED_TTL_S = 24 * 60 * 60;+// A blockhash is reused for this long before a fresh one is fetched. Well under+// the cluster's validity window, so a buyer signing against a reused hash still+// has the whole window to land the transaction.+const BLOCKHASH_TTL_MS = 8 * 1000;+// Cold-path fail-open window: a Solana blockhash stays valid on-chain for roughly+// 60-90s (150 blocks), so when the chain cannot be read we may still serve a+// cached one this much past its fetch time. Conservatively under the floor.+const BLOCKHASH_STALE_MAX_MS = 45 * 1000;+// Blocks of headroom kept below lastValidBlockHeight when the chain height is+// known: about 12s at 400ms per block, enough for the buyer to sign and send.+const BLOCKHASH_HEIGHT_MARGIN = 30;+const BLOCKHASH_SHARED_TTL_S = 60;++const mintDecimalsCache = new Map(); // mint -> { decimals, at }+const blockhashCache = new Map(); // `${key}:${commitment}` -> { blockhash, lastValidBlockHeight, at }+// The highest block height any successful read has reported, per key. Lets a+// stale blockhash be refused by height even when the live height read fails.+const lastKnownHeight = new Map(); // key -> { height, at }++function pubkeyString(pubkey) {+ return typeof pubkey === 'string' ? pubkey : pubkey.toBase58();+}++/** True when `err` is a token-program verdict (not a mint, wrong owner) rather than a transport failure. */+function isTokenProgramError(err) {+ return typeof err?.name === 'string' && err.name.startsWith('Token');+}++/** True when `err` is a transport / rotation failure the caller should retry. */+export function isRpcTransportError(err) {+ if (!err || isTokenProgramError(err)) return false;+ if (err.code === RPC_UNAVAILABLE) return true;+ if (err.name === 'TypeError' && /fetch failed/i.test(err.message || '')) return true;+ if (err.name === 'AbortError') return true;+ return isTransientRpcError(err);+}++/**+ * Wrap a transport failure as the typed, retryable error every boundary understands:+ * `{ status: 503, code: 'rpc_unavailable', retryable: true, expose: true }`. The+ * original error rides on `.cause`. Already-tagged errors are returned unchanged.+ */+export function rpcUnavailableError(cause, message = null) {+ if (cause && cause.code === RPC_UNAVAILABLE && cause.status === 503) return cause;+ const detail = cause?.message || String(cause || 'unknown');+ const err = new Error(message || `solana rpc unavailable: ${detail}`);+ err.status = 503;+ err.code = RPC_UNAVAILABLE;+ err.retryable = true;+ err.expose = true;+ err.retryAfter = RPC_RETRY_AFTER_SECONDS;+ err.cause = cause;+ return err;+}++/** True when `err` is the tagged rpc_unavailable error. */+export function isRpcUnavailable(err) {+ return Boolean(err) && err.code === RPC_UNAVAILABLE && err.status === 503;+}++/**+ * Re-throw a transport failure as rpc_unavailable and every other error untouched.+ * `await guardRpc(() => conn.getX())` is the one-liner for a read that must fail+ * closed but typed.+ */+export async function guardRpc(fn, message = null) {+ try {+ return await fn();+ } catch (err) {+ if (isRpcTransportError(err)) throw rpcUnavailableError(err, message);+ throw err;+ }+}++/**+ * Handler-boundary response for an RPC outage: 503 `rpc_unavailable` with+ * `Retry-After: 15`, the same shape whether the read died in this handler or+ * deeper in a lib. Returns true when the error was handled, false when it is+ * not an RPC failure (so the caller can fall through to its own handling).+ */+export function respondRpcUnavailable(res, err, extra = {}) {+ if (!isRpcUnavailable(err) && !isRpcTransportError(err)) return false;+ if (typeof res.setHeader === 'function') res.setHeader('retry-after', String(RPC_RETRY_AFTER_SECONDS));+ httpError(res, 503, RPC_UNAVAILABLE, 'solana rpc temporarily unavailable, retry shortly', {+ retryable: true,+ retry_after: RPC_RETRY_AFTER_SECONDS,+ ...extra,+ });+ return true;+}++/**+ * Decimals for `mintPubkey`. Canonical mints (USDC, USDT, wSOL, $THREE) resolve+ * from the local table and never touch the network; anything else is read once+ * through getMint and remembered per process and in the shared cache. A+ * transport failure is thrown as rpc_unavailable (503, retryable); a genuine+ * token-program verdict (the address is not a mint) propagates unchanged so the+ * caller can answer 4xx.+ */+export async function mintDecimals(conn, mintPubkey, { programId = undefined } = {}) {+ const mintStr = pubkeyString(mintPubkey);+ const known = WELL_KNOWN_MINT_DECIMALS.get(mintStr);+ if (known != null) return known;++ const hit = mintDecimalsCache.get(mintStr);+ if (hit && Date.now() - hit.at < MINT_DECIMALS_TTL_MS) return hit.decimals;++ const sharedKey = `solana:mint-decimals:${mintStr}`;+ try {+ const info = await getMint(conn, mintPubkey, undefined, programId);+ const decimals = Number(info.decimals);+ mintDecimalsCache.set(mintStr, { decimals, at: Date.now() });+ cacheSet(sharedKey, { decimals }, MINT_DECIMALS_SHARED_TTL_S).catch(() => {});+ return decimals;+ } catch (err) {+ if (!isRpcTransportError(err)) throw err;+ if (hit) return hit.decimals;+ const shared = await cacheGet(sharedKey).catch(() => null);+ if (shared && Number.isInteger(shared.decimals)) {+ mintDecimalsCache.set(mintStr, { decimals: shared.decimals, at: Date.now() });+ return shared.decimals;+ }+ throw rpcUnavailableError(err, `could not read mint ${mintStr}: ${err?.message || err}`);+ }+}++/**+ * Does an ATA (or any account) already exist on-chain? web3.js decodes+ * getAccountInfo's reply through a superstruct union, so a flaky or misconfigured+ * RPC returning a malformed 200 (truncated body, proxy error page, wrong-cluster+ * node) throws StructError instead of a clean null, and a socket failure throws+ * `TypeError: fetch failed`.+ *+ * FAILS OPEN: any probe failure reads as "missing". The only thing the answer+ * gates is an idempotent ATA-create instruction+ * (createAssociatedTokenAccountIdempotentInstruction), which is a no-op when the+ * account already exists, so assuming-missing is always safe: at worst the+ * transaction carries one redundant instruction. Never use this to gate a+ * non-idempotent create.+ */+export async function ataExists(conn, ata, commitment = undefined) {+ try {+ return (await conn.getAccountInfo(ata, commitment)) != null;+ } catch (err) {+ console.warn(+ `[solana-read-guards] getAccountInfo(${pubkeyString(ata)}) failed, assuming ATA missing: ${err?.message || err}`,+ );+ return false;+ }+}++/**+ * getAccountInfo that returns null on transport failure instead of throwing.+ * For decorative reads (a balance line, an "already funded" badge) where the+ * right answer to an outage is "unknown", not a 500. Pass `{ withCause: true }`+ * to receive `{ info, cause }` so the caller can tell "absent" from "unreadable";+ * by default a transport failure is indistinguishable from a missing account.+ * A token-program or argument error still throws: those are bugs, not weather.+ */+export async function readAccountInfoOrNull(conn, pubkey, { commitment = undefined, withCause = false } = {}) {+ try {+ const info = await conn.getAccountInfo(pubkey, commitment);+ return withCause ? { info, cause: null } : info;+ } catch (err) {+ if (!isRpcTransportError(err)) throw err;+ console.warn(`[solana-read-guards] getAccountInfo(${pubkeyString(pubkey)}) unreadable: ${err?.message || err}`);+ return withCause ? { info: null, cause: err } : null;+ }+}++/**+ * getBalance that returns null lamports on transport failure instead of throwing.+ * "Balance unknown" is the honest answer to an outage; callers skip the tick,+ * mark the line unverified, or show "as of" rather than treating null as zero.+ */+export async function readBalanceOrNull(conn, pubkey, commitment = 'confirmed') {+ try {+ return await conn.getBalance(pubkey, commitment);+ } catch (err) {+ if (!isRpcTransportError(err)) throw err;+ console.warn(`[solana-read-guards] getBalance(${pubkeyString(pubkey)}) unreadable: ${err?.message || err}`);+ return null;+ }+}++function noteHeight(key, height, at) {+ if (!Number.isFinite(height)) return;+ const prev = lastKnownHeight.get(key);+ if (!prev || height > prev.height) lastKnownHeight.set(key, { height, at });+}++/** The chain height right now, or null when it cannot be read within this call. */+async function readHeightOrNull(conn, commitment) {+ if (typeof conn?.getBlockHeight !== 'function') return null;+ try {+ const h = await conn.getBlockHeight(commitment);+ return Number.isFinite(h) ? h : null;+ } catch {+ return null;+ }+}++/**+ * Decide whether a cached blockhash may still be served. Height wins when we+ * have one (live or last-known); otherwise the age cap bounds the reuse.+ */+function cachedBlockhashUsable(hit, { now, key, liveHeight }) {+ if (!hit || !hit.blockhash) return false;+ const age = now - hit.at;+ if (age < 0 || age >= BLOCKHASH_STALE_MAX_MS) return false;+ const lastValid = Number(hit.lastValidBlockHeight);+ if (Number.isFinite(lastValid) && lastValid > 0) {+ const known = liveHeight ?? lastKnownHeight.get(key)?.height ?? null;+ if (known != null && known >= lastValid - BLOCKHASH_HEIGHT_MARGIN) return false;+ }+ return true;+}++/**+ * A recent blockhash plus its lastValidBlockHeight, keyed per network (or RPC+ * url) and commitment. Reuses a fresh one for BLOCKHASH_TTL_MS; when the chain+ * cannot be read, serves the last one fetched by this process or by any other+ * instance (shared cache) as long as it is still inside its validity window:+ * never past `lastValidBlockHeight` minus a safety margin when a height is+ * known, and never older than BLOCKHASH_STALE_MAX_MS regardless. A served+ * fallback carries `stale: true` and `as_of` so the caller can surface it.+ *+ * Safe by construction: a blockhash only bounds how long the signer has to land+ * the transaction, never the amount or recipient. A too-stale one simply fails+ * to confirm and prompts a clean retry, never a double charge.+ *+ * `now` is injectable so the staleness branches are unit-testable.+ */+export async function getRecentBlockhashInfo(conn, key, { now = Date.now, commitment = 'confirmed' } = {}) {+ const cacheKey = `${key}:${commitment}`;+ const sharedKey = `solana:blockhash:${cacheKey}`;+ const hit = blockhashCache.get(cacheKey);+ const t = now();+ if (hit && t - hit.at < BLOCKHASH_TTL_MS) {+ return { blockhash: hit.blockhash, lastValidBlockHeight: hit.lastValidBlockHeight, stale: false, as_of: hit.at };+ }+ try {+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash(commitment);+ const entry = { blockhash, lastValidBlockHeight: lastValidBlockHeight ?? null, at: now() };+ blockhashCache.set(cacheKey, entry);+ cacheSet(sharedKey, entry, BLOCKHASH_SHARED_TTL_S).catch(() => {});+ return { blockhash, lastValidBlockHeight: entry.lastValidBlockHeight, stale: false, as_of: entry.at };+ } catch (err) {+ const liveHeight = await readHeightOrNull(conn, commitment);+ if (liveHeight != null) noteHeight(cacheKey, liveHeight, now());+ let candidate = hit;+ if (!cachedBlockhashUsable(candidate, { now: now(), key: cacheKey, liveHeight })) {+ const shared = await cacheGet(sharedKey).catch(() => null);+ candidate = shared && cachedBlockhashUsable(shared, { now: now(), key: cacheKey, liveHeight }) ? shared : null;+ }+ if (candidate) {+ console.warn(+ `[solana-read-guards] getLatestBlockhash(${cacheKey}) failed; serving ${Math.round(+ (now() - candidate.at) / 1000,+ )}s-old cached blockhash inside its validity window: ${err?.message || err}`,+ );+ return {+ blockhash: candidate.blockhash,+ lastValidBlockHeight: candidate.lastValidBlockHeight ?? null,+ stale: true,+ as_of: candidate.at,+ };+ }+ if (isRpcTransportError(err)) throw rpcUnavailableError(err);+ throw err;+ }+}++/** The blockhash string alone; see getRecentBlockhashInfo for the full contract. */+export async function getRecentBlockhash(conn, key, opts = {}) {+ return (await getRecentBlockhashInfo(conn, key, opts)).blockhash;+}++/**+ * Cache key for a connection: the network name when the caller knows it,+ * otherwise the RPC url. Two callers on the same network share one blockhash.+ */+export function blockhashKey({ network = null, url = null } = {}) {+ return network || url || 'mainnet';+}++/** Test hook: forget every cached blockhash, height, and mint decimals. */+export function _resetReadGuardCaches() {+ mintDecimalsCache.clear();+ blockhashCache.clear();+ lastKnownHeight.clear();+}diff --git a/api/x402-checkout.js b/api/x402-checkout.jsindex 2cafc19f6..6d371a4b8 100644--- a/api/x402-checkout.js+++ b/api/x402-checkout.js@@ -34,13 +34,13 @@ import {getAssociatedTokenAddressSync,createAssociatedTokenAccountIdempotentInstruction,createTransferCheckedInstruction,- getMint,} from '@solana/spl-token';import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';import { parse } from './_lib/validate.js';import { limits, clientIp } from './_lib/rate-limit.js';import { NETWORK_SOLANA_MAINNET, NETWORK_SOLANA_DEVNET } from './_lib/x402-spec.js';import { confirmSolanaPayment } from './_lib/x402-solana-confirm.js';+import { ataExists, getRecentBlockhash, mintDecimals, respondRpcUnavailable } from './_lib/solana/read-guards.js';import { env } from './_lib/env.js';// Routed through env.* so the `api-mainnet.helius-rpc.com` misconfig is repaired@@ -48,42 +48,13 @@ import { env } from './_lib/env.js';const SOLANA_RPC = env.SOLANA_RPC_URL;const SOLANA_DEVNET_RPC = env.SOLANA_RPC_URL_DEVNET;-// Short-lived caches so repeated prepare calls don't re-issue identical RPC-// round-trips. Mint decimals are effectively immutable; a blockhash is valid for-// ~60-90s on Solana, so a few seconds of reuse cuts redundant traffic without-// handing out a stale-enough blockhash for the buyer's signed tx to fail.-const MINT_DECIMALS_TTL_MS = 5 * 60 * 1000;-const BLOCKHASH_TTL_MS = 8 * 1000;-// Cold-path fail-open window: a Solana blockhash stays valid on-chain for ~60-90s,-// so if a live fetch fails we may still serve a cached one this much past its fetch-// time rather than 500'ing the checkout. Conservatively under the cluster floor.-const BLOCKHASH_STALE_FALLBACK_MS = 60 * 1000;-const mintDecimalsCache = new Map(); // `${rpc}:${mint}` -> { decimals, at }-const blockhashCache = new Map(); // rpc -> { blockhash, at }--// Decimals for canonical mints are immutable and universally known. Resolving-// them locally skips an RPC round-trip on the hot checkout path (USDC is the-// default settlement asset) and immunizes prepare against a flaky/rate-limited-// RPC returning 404 for getAccountInfo on the mint — the failure mode that-// 500'd every USDC checkout when the public endpoint was cooling.-const WELL_KNOWN_MINT_DECIMALS = new Map([- ['EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', 6], // USDC (mainnet)- ['Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', 6], // USDT (mainnet)- ['So11111111111111111111111111111111111111112', 9], // wrapped SOL-]);--async function getMintDecimals(conn, rpc, mint) {- const mintStr = mint.toBase58();- const known = WELL_KNOWN_MINT_DECIMALS.get(mintStr);- if (known != null) return known;-- const key = `${rpc}:${mintStr}`;- const hit = mintDecimalsCache.get(key);- if (hit && Date.now() - hit.at < MINT_DECIMALS_TTL_MS) return hit.decimals;- const info = await getMint(conn, mint);- mintDecimalsCache.set(key, { decimals: info.decimals, at: Date.now() });- return info.decimals;-}+// The three RPC reads on the prepare hot path (mint decimals, ATA existence, a+// recent blockhash) go through the shared money-path guards: canonical mints+// resolve locally, an ATA probe fails open to "missing" (the create is+// idempotent), and a blockhash is served from cache inside its validity window+// when every RPC endpoint fails. See api/_lib/solana/read-guards.js. The two+// helpers stay exported from here because the checkout tests exercise them.+export { ataExists, getRecentBlockhash };// Build a PublicKey from a (schema-trimmed) address, converting web3.js's raw// "Non-base58 character" / "Invalid public key" throw into a structured 400.@@ -101,56 +72,6 @@ function toPubkey(value, field) {}}-// Resolve a recent blockhash for the payment tx. The one RPC call on the USDC-// checkout hot path that isn't already fail-open (getMintDecimals resolves-// canonical mints from a local map; ataExists fails open to "missing"), so a-// transient *total* failover outage — every endpoint in solanaConnection's chain-// failing within this single request — used to throw straight through wrap() as an-// opaque "internal error, quote ref … to support" 500 at the modal's Authorize-// step. Match the sibling fail-open posture: if the live fetch fails but we still-// hold a cached blockhash inside the cluster's ~60-90s validity window, serve it.-// Safe by construction — a blockhash only bounds how long the buyer has to land the-// signed tx, never the amount or recipient, and a too-stale one simply fails to-// confirm and prompts a clean retry, never a double charge. `now` is injectable so-// the staleness branches are unit-testable without a real clock.-export async function getRecentBlockhash(conn, rpc, { now = Date.now } = {}) {- const hit = blockhashCache.get(rpc);- if (hit && now() - hit.at < BLOCKHASH_TTL_MS) return hit.blockhash;- try {- const { blockhash } = await conn.getLatestBlockhash('confirmed');- blockhashCache.set(rpc, { blockhash, at: now() });- return blockhash;- } catch (err) {- if (hit && now() - hit.at < BLOCKHASH_STALE_FALLBACK_MS) {- console.warn(- `[x402-checkout] getLatestBlockhash failed across all RPC endpoints; serving ${Math.round(- (now() - hit.at) / 1000,- )}s-old cached blockhash so checkout still builds: ${err?.message || err}`,- );- return hit.blockhash;- }- throw err;- }-}--// Does an ATA already exist on-chain? web3.js decodes getAccountInfo's reply-// through a superstruct union, so a flaky/misconfigured RPC returning a malformed-// 200 (truncated body, proxy error page, wrong-cluster node) throws StructError-// instead of a clean null — which 500'd the whole checkout at the prepare step.-// Treat any probe failure as "missing": the only thing the answer gates is an-// *idempotent* ATA-create instruction, a no-op when the account already exists,-// so assuming-missing is always safe — same fail-open posture as getMintDecimals.-export async function ataExists(conn, ata) {- try {- return (await conn.getAccountInfo(ata)) != null;- } catch (err) {- console.warn(- `[x402-checkout] getAccountInfo(${ata.toBase58()}) failed, assuming ATA missing: ${err?.message || err}`,- );- return false;- }-}-// Solana addresses arrive inside the 402 challenge's `accept` entry, which is// built from operator-configured env (X402_PAY_TO_SOLANA / X402_FEE_PAYER_SOLANA).// Those values are pasted into dashboards and routinely carry a trailing newline@@ -256,7 +177,17 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const action = req.query?.action;- if (action === 'prepare') return handlePrepare(req, res);+ if (action === 'prepare') {+ try {+ return await handlePrepare(req, res);+ } catch (err) {+ // Every read on the prepare path is already fail-open or cache-backed, so+ // reaching here means the chain was unreadable with nothing cached. Answer+ // a typed 503 with Retry-After instead of an opaque internal_error.+ if (respondRpcUnavailable(res, err)) return;+ throw err;+ }+ }if (action === 'encode') return handleEncode(req, res);return error(res, 404, 'not_found', `unknown action: ${action ?? '(none)'}`);});@@ -314,7 +245,7 @@ async function handlePrepare(req, res) {TOKEN_PROGRAM_ID,ASSOCIATED_TOKEN_PROGRAM_ID,);- const mintDecimals = await getMintDecimals(conn, rpc, mint);+ const decimals = await mintDecimals(conn, mint);// Base payment needs ~60k CU; each donation adds a transfer (+ possibly an ATA// create), so budget headroom per tip. Unused CU isn't charged — this only@@ -343,7 +274,7 @@ async function handlePrepare(req, res) {receiverAta,buyerPubkey,amount,- mintDecimals,+ decimals,[],TOKEN_PROGRAM_ID,),@@ -365,7 +296,7 @@ async function handlePrepare(req, res) {);}ixs.push(- createTransferCheckedInstruction(senderAta, mint, tipAta, buyerPubkey, v.amount, mintDecimals, [], TOKEN_PROGRAM_ID),+ createTransferCheckedInstruction(senderAta, mint, tipAta, buyerPubkey, v.amount, decimals, [], TOKEN_PROGRAM_ID),);}}diff --git a/tests/solana-read-guards.test.js b/tests/solana-read-guards.test.jsnew file mode 100644index 000000000..b2dac06ca--- /dev/null+++ b/tests/solana-read-guards.test.js@@ -0,0 +1,166 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { PublicKey } from '@solana/web3.js';++vi.mock('@solana/spl-token', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, getMint: vi.fn() };+});++import { getMint } from '@solana/spl-token';+import {+ mintDecimals,+ ataExists,+ getRecentBlockhash,+ getRecentBlockhashInfo,+ readAccountInfoOrNull,+ readBalanceOrNull,+ rpcUnavailableError,+ isRpcUnavailable,+ respondRpcUnavailable,+ guardRpc,+ THREE_MINT,+ _resetReadGuardCaches,+} from '../api/_lib/solana/read-guards.js';++const USDC = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');+const ATA = new PublicKey('HgwbNyweQUiV5diWJ1a7ocxgzf3AYSLhTpphEYRLujtN');+const BH = 'GfVcyD4kkTrj4bKc7Wd9G4nf2k1zk8mF8YQ4i6N2bQrs';+const fetchFailed = () => Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNRESET' } });++beforeEach(() => {+ _resetReadGuardCaches();+ getMint.mockReset();+});++describe('mintDecimals', () => {+ it('never calls getMint for USDC or $THREE', async () => {+ const conn = {};+ expect(await mintDecimals(conn, USDC)).toBe(6);+ expect(await mintDecimals(conn, THREE_MINT)).toBe(6);+ expect(await mintDecimals(conn, 'So11111111111111111111111111111111111111112')).toBe(9);+ expect(getMint).not.toHaveBeenCalled();+ });++ it('reads an unknown mint once and remembers it', async () => {+ const mint = PublicKey.unique();+ getMint.mockResolvedValue({ decimals: 4 });+ expect(await mintDecimals({}, mint)).toBe(4);+ expect(await mintDecimals({}, mint)).toBe(4);+ expect(getMint).toHaveBeenCalledTimes(1);+ });++ it('tags a transport failure as a retryable 503 rpc_unavailable', async () => {+ getMint.mockRejectedValue(fetchFailed());+ const err = await mintDecimals({}, PublicKey.unique()).catch((e) => e);+ expect(err.status).toBe(503);+ expect(err.code).toBe('rpc_unavailable');+ expect(err.retryable).toBe(true);+ expect(err.expose).toBe(true);+ expect(isRpcUnavailable(err)).toBe(true);+ });++ it('lets a token-program verdict through untouched (the address is not a mint)', async () => {+ const notMint = Object.assign(new Error('TokenInvalidAccountOwnerError'), { name: 'TokenInvalidAccountOwnerError' });+ getMint.mockRejectedValue(notMint);+ const err = await mintDecimals({}, PublicKey.unique()).catch((e) => e);+ expect(err).toBe(notMint);+ expect(err.status).toBeUndefined();+ });+});++describe('ataExists', () => {+ it('reports existing / missing on a clean reply', async () => {+ expect(await ataExists({ getAccountInfo: async () => ({ data: Buffer.alloc(165) }) }, ATA)).toBe(true);+ expect(await ataExists({ getAccountInfo: async () => null }, ATA)).toBe(false);+ });++ it('fails open to missing when the RPC throws', async () => {+ const conn = { getAccountInfo: async () => { throw fetchFailed(); } };+ await expect(ataExists(conn, ATA)).resolves.toBe(false);+ });+});++describe('getRecentBlockhash', () => {+ const ok = (blockhash, lastValidBlockHeight) => ({ getLatestBlockhash: async () => ({ blockhash, lastValidBlockHeight }) });+ const dead = { getLatestBlockhash: async () => { throw new Error('failed to get recent blockhash: TypeError: fetch failed'); } };++ it('serves the cached blockhash inside the validity window when the chain fails', async () => {+ await getRecentBlockhash(ok(BH, 1000), 'mainnet', { now: () => 1000 });+ const info = await getRecentBlockhashInfo(dead, 'mainnet', { now: () => 1000 + 20_000 });+ expect(info.blockhash).toBe(BH);+ expect(info.stale).toBe(true);+ expect(info.as_of).toBe(1000);+ });++ it('refuses a cached blockhash past the age cap', async () => {+ await getRecentBlockhash(ok(BH, 1000), 'devnet', { now: () => 1000 });+ const err = await getRecentBlockhash(dead, 'devnet', { now: () => 1000 + 60_000 }).catch((e) => e);+ expect(err.code).toBe('rpc_unavailable');+ expect(err.status).toBe(503);+ expect(err.message).toMatch(/fetch failed/);+ });++ it('refuses a cached blockhash when the chain height has reached lastValidBlockHeight minus the margin', async () => {+ await getRecentBlockhash(ok(BH, 5000), 'height-net', { now: () => 1000 });+ const deadWithHeight = { ...dead, getBlockHeight: async () => 4990 };+ await expect(getRecentBlockhash(deadWithHeight, 'height-net', { now: () => 1000 + 5000 + 5000 })).rejects.toMatchObject({ code: 'rpc_unavailable' });+ });++ it('serves a cached blockhash when the chain height is still comfortably below lastValidBlockHeight', async () => {+ await getRecentBlockhash(ok(BH, 5000), 'height-ok', { now: () => 1000 });+ const deadWithHeight = { ...dead, getBlockHeight: async () => 4900 };+ expect(await getRecentBlockhash(deadWithHeight, 'height-ok', { now: () => 1000 + 20_000 })).toBe(BH);+ });++ it('throws typed when the cache is cold', async () => {+ await expect(getRecentBlockhash(dead, 'cold-net', { now: () => 1000 })).rejects.toMatchObject({ code: 'rpc_unavailable', retryable: true });+ });+});++describe('soft reads', () => {+ it('readAccountInfoOrNull returns null on transport failure and the cause when asked', async () => {+ const conn = { getAccountInfo: async () => { throw fetchFailed(); } };+ expect(await readAccountInfoOrNull(conn, ATA)).toBeNull();+ const r = await readAccountInfoOrNull(conn, ATA, { withCause: true });+ expect(r.info).toBeNull();+ expect(r.cause.message).toBe('fetch failed');+ });++ it('readBalanceOrNull returns null on transport failure and lamports otherwise', async () => {+ expect(await readBalanceOrNull({ getBalance: async () => 42 }, ATA)).toBe(42);+ expect(await readBalanceOrNull({ getBalance: async () => { throw fetchFailed(); } }, ATA)).toBeNull();+ });++ it('guardRpc rethrows non-transport errors untouched', async () => {+ const boom = new Error('bad argument');+ await expect(guardRpc(async () => { throw boom; })).rejects.toBe(boom);+ await expect(guardRpc(async () => { throw fetchFailed(); })).rejects.toMatchObject({ code: 'rpc_unavailable' });+ });+});++describe('respondRpcUnavailable', () => {+ function fakeRes() {+ const headers = {};+ return {+ headers,+ statusCode: 0,+ body: '',+ setHeader(k, v) { headers[k.toLowerCase()] = v; },+ getHeader(k) { return headers[k.toLowerCase()]; },+ end(b) { this.body = b; },+ };+ }++ it('answers 503 rpc_unavailable with Retry-After 15 for a tagged or raw transport error', () => {+ const res = fakeRes();+ expect(respondRpcUnavailable(res, rpcUnavailableError(fetchFailed()))).toBe(true);+ expect(res.statusCode).toBe(503);+ expect(res.headers['retry-after']).toBe('15');+ expect(JSON.parse(res.body).error).toBe('rpc_unavailable');+ expect(respondRpcUnavailable(fakeRes(), fetchFailed())).toBe(true);+ });++ it('leaves unrelated errors to the caller', () => {+ expect(respondRpcUnavailable(fakeRes(), new Error('validation'))).toBe(false);+ });+});