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(resilience): stop the new stale tiers from reaching the payment retry and the token security verdict
nirholasd5f735c2fedd
diff --git a/api/_lib/solana/read-guards.js b/api/_lib/solana/read-guards.jsindex 6dd323adb..cd5041ee3 100644--- a/api/_lib/solana/read-guards.js+++ b/api/_lib/solana/read-guards.js@@ -279,14 +279,22 @@ function cachedBlockhashUsable(hit, { now, key, liveHeight }) {* the transaction, never the amount or recipient. A too-stale one simply fails* to confirm and prompts a clean retry, never a double charge.*+ * `forceFresh` skips the reuse window and reads the chain, for the one caller+ * that must not reuse a hash: the post-402 payment retry. A refused attempt is+ * re-signed there, and re-signing the SAME blockhash with the same payer, payee+ * and amount recompiles byte-identical bytes, so the facilitator refuses it+ * again for the same reason. Only the fast path is skipped; the stale-fallback+ * branch below still applies, because a cached hash inside its validity window+ * beats failing the payment outright when the chain cannot be read at all.+ ** `now` is injectable so the staleness branches are unit-testable.*/-export async function getRecentBlockhashInfo(conn, key, { now = Date.now, commitment = 'confirmed' } = {}) {+export async function getRecentBlockhashInfo(conn, key, { now = Date.now, commitment = 'confirmed', forceFresh = false } = {}) {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) {+ if (!forceFresh && hit && t - hit.at < BLOCKHASH_TTL_MS) {return { blockhash: hit.blockhash, lastValidBlockHeight: hit.lastValidBlockHeight, stale: false, as_of: hit.at };}try {diff --git a/api/_lib/upstream-fetch.js b/api/_lib/upstream-fetch.jsindex 0940dd88c..96c38aa57 100644--- a/api/_lib/upstream-fetch.js+++ b/api/_lib/upstream-fetch.js@@ -70,6 +70,17 @@ export function safeUrl(url) {}}+// Body text for an error message, never throwing: a non-2xx is often an HTML+// error page or an empty body, and some Response-likes (test doubles, older+// fetch shims) have no text() at all.+async function readBodyText(res) {+ try {+ return typeof res.text === 'function' ? await res.text() : '';+ } catch {+ return '';+ }+}+function composeSignal(callerSignal, timeoutMs) {const timeout = AbortSignal.timeout(timeoutMs);if (!callerSignal) return timeout;@@ -125,8 +136,14 @@ export async function fetchUpstream(url, init = {}, opts = {}) {throw e;}if (okWhen(res)) return res;- const body = await res.text().catch(() => '');- const retryAfterMs = parseRetryAfter(res.headers.get('retry-after'));+ // Read the body and the Retry-After defensively. This is the ERROR path of+ // the one wrapper every third-party call in api/ goes through, so a throw+ // raised while describing a failure would replace the upstream's real+ // status with an opaque 503, and a 429 that reads as a 5xx changes what+ // callers do next (back off versus fail over). Anything Response-shaped+ // enough to have a status must still report that status.+ const body = await readBodyText(res);+ const retryAfterMs = parseRetryAfter(res.headers?.get?.('retry-after'));const e = new UpstreamError(`${shown}: http ${res.status}${body ? ` ${body.slice(0, BODY_EXCERPT)}` : ''}`, {status: res.status,url: shown,diff --git a/api/_lib/x402/pay.js b/api/_lib/x402/pay.jsindex 50794a780..ca2da905d 100644--- a/api/_lib/x402/pay.js+++ b/api/_lib/x402/pay.js@@ -302,7 +302,10 @@ async function currentBlockhash(conn, fallback, { forceFresh = false } = {}) {// The shared guard serves its own cached blockhash (per process and via the// shared cache) inside the validity window when every RPC lane is down, so// this only reaches the fallback when nothing usable exists anywhere.- const blockhash = await getRecentBlockhash(conn, SOLANA_RPC);+ // forceFresh has to travel INTO the guard as well: it keeps its own reuse+ // window, so skipping only this module's cache would still hand the retry+ // the very hash the facilitator just refused.+ const blockhash = await getRecentBlockhash(conn, SOLANA_RPC, { forceFresh });seedBlockhash(blockhash);return blockhash;} catch {diff --git a/api/v1/token/security.js b/api/v1/token/security.jsindex dea5c0c7c..5dc3234ff 100644--- a/api/v1/token/security.js+++ b/api/v1/token/security.js@@ -48,7 +48,17 @@ async function rpcCall(rpcFetch, method, params) {body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),signal: AbortSignal.timeout(RPC_TIMEOUT_MS),});- return resp.json();+ const body = await resp.json();+ // The rotation can answer an idempotent read from the last body a lane+ // returned when every lane is down, marking it with x-solana-rpc-stale. That+ // is the right trade for a balance chip; it is the wrong one here. Mint and+ // freeze authority and holder concentration are the whole point of a security+ // verdict, and a remembered copy of them presented as live would tell a+ // caller a token is clean at the exact moment we cannot see the chain.+ const stale = resp.headers?.get?.('x-solana-rpc-stale') != null;+ // A JSON-RPC envelope is always an object, but never let the marker itself be+ // the thing that throws on a malformed body.+ return body && typeof body === 'object' ? Object.assign(body, { __stale: stale }) : { result: undefined, __stale: stale };}// Round a base-unit part/total ratio to a 2-decimal percentage. Number() on the@@ -216,10 +226,15 @@ export default defineEndpoint({fetchTokenMarket(address),]);+ // A stale-served read counts as "did not answer": the caller gets the same+ // honest 503 it would get if the lane had simply refused, instead of a+ // security report quietly assembled out of remembered on-chain state.+ const answered = (settled) => settled.status === 'fulfilled' && !settled.value?.__stale;+const { resolved, allFailed, body } = buildSecurityReport({address,- account: { answered: acct.status === 'fulfilled', result: acct.value?.result },- largest: { answered: largest.status === 'fulfilled', result: largest.value?.result },+ account: { answered: answered(acct), result: answered(acct) ? acct.value?.result : undefined },+ largest: { answered: answered(largest), result: answered(largest) ? largest.value?.result : undefined },market: { answered: mkt.status === 'fulfilled', data: mkt.value },});diff --git a/tests/api/defi-cache-dedup.test.js b/tests/api/defi-cache-dedup.test.jsindex 9835ac5d2..1cd5bd0aa 100644--- a/tests/api/defi-cache-dedup.test.js+++ b/tests/api/defi-cache-dedup.test.js@@ -139,22 +139,26 @@ describe('api/defi builders de-duplicate concurrent cold loads', () => {});it(`${file}: a failed load is not cached and the next call retries`, async () => {- let attempt = 0;- const fetchMock = vi.fn(async () => {- attempt += 1;- // First round trip fails the way a throttled or broken upstream does.- return attempt === 1 ? reply({ error: 'upstream down' }, 503) : reply(payload);- });+ // The upstream stays down for the whole call, not just its first round+ // trip: fetchUpstream retries a transient 503 on its own now, so a+ // single blip followed by a good body is a SUCCESS by design and would+ // never reach the caller as an error. What must still hold is that the+ // failure itself is never cached.+ let down = true;+ const fetchMock = vi.fn(async () => (down ? reply({ error: 'upstream down' }, 503) : reply(payload)));vi.stubGlobal('fetch', fetchMock);const mod = await coldImport(file);await expect(build(mod)).rejects.toThrow();+ const afterFailure = fetchMock.mock.calls.length;+ expect(afterFailure).toBeGreaterThan(0);- // The retry must reach the upstream again rather than replay the failure- // from cache for the rest of the TTL.+ // The next call must reach the upstream again rather than replay the+ // failure from cache for the rest of the TTL.+ down = false;const recovered = await build(mod);expect(recovered).toBeTruthy();- expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock.mock.calls.length).toBeGreaterThan(afterFailure);});}diff --git a/tests/rider-pass.test.js b/tests/rider-pass.test.jsindex 307f81460..e0e268aad 100644--- a/tests/rider-pass.test.js+++ b/tests/rider-pass.test.js@@ -220,10 +220,13 @@ describe('GET /api/rider/check', () => {expect(res.payload).toMatchObject({ has_pass: false, holder_pass: false, paid_pass: false });});- it('answers 502 rather than a false negative when the RPC read fails', async () => {+ it('refuses rather than returning a false negative when the RPC read fails for a wallet it has never judged', async () => {+ // WALLET_B has no cached verdict, so there is nothing honest to answer+ // with: reporting "no pass" here would deny a real holder. The boundary+ // answers the typed 503 + Retry-After that rpc-degrade.js standardizes on.rpcState.fail = new Error('failed to fetch https://mainnet.helius-rpc.com/?api-key=secret');- const res = await callGet(checkHandler, '/api/rider/check', { address: WALLET_A });- expect(res.statusCode).toBe(502);+ const res = await callGet(checkHandler, '/api/rider/check', { address: WALLET_B });+ expect(res.statusCode).toBe(503);expect(res.payload.error).toBe('rpc_unavailable');// The RPC URL carries the Helius key; it must never reach the caller.expect(JSON.stringify(res.payload)).not.toMatch(/api-key/);diff --git a/tests/token-layer.test.js b/tests/token-layer.test.jsindex f5b73a0a3..8332c8d26 100644--- a/tests/token-layer.test.js+++ b/tests/token-layer.test.js@@ -11,8 +11,16 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';vi.mock('../api/_lib/cache.js', () => ({cacheGet: vi.fn(async () => null),+ cacheGetFresh: vi.fn(async () => null),cacheSet: vi.fn(async () => {}),cacheDel: vi.fn(async () => {}),+ // The market-data fallback chain single-flights through the shared lock and+ // reads through cacheWrap; without these the chain dies on a missing export+ // instead of on the upstream it is meant to be exercising.+ acquireLock: vi.fn(async () => true),+ releaseLock: vi.fn(async () => {}),+ cacheWrap: vi.fn(async (_key, _ttl, fn) => fn()),+ cacheWrapLastGood: vi.fn(async (_key, _ttl, fn) => fn()),}));vi.mock('../api/_lib/db.js', () => {@@ -46,11 +54,18 @@ const mockFetch = (url, opts = {}) => {if (!resp) throw new Error(`Unexpected fetch: ${url}`);if (resp.error) return Promise.reject(resp.error);const body = resp.body;+ // text() has to serialize the SAME body json() returns: the upstream fetch+ // wrapper reads text() and parses it, so a stub that answered with the status+ // string made every parsed body come back as the number 200.+ const asText = body === undefined+ ? String(resp.status ?? 200)+ : (typeof body === 'string' ? body : JSON.stringify(body));return Promise.resolve({ok: resp.ok ?? true,status: resp.status ?? 200,+ headers: new Headers(resp.headers || {}),json: async () => (typeof body === 'string' ? JSON.parse(body) : body),- text: async () => String(resp.status ?? 200),+ text: async () => asText,});};vi.stubGlobal('fetch', mockFetch);