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(browser): close the last single-source reads a user can actually hit

nirholasca24bfd01298
diff --git a/src/coin3d/main.js b/src/coin3d/main.js
index 10ebeeb2f..5b573a751 100644
--- a/src/coin3d/main.js
+++ b/src/coin3d/main.js
@@ -59,6 +59,7 @@ import {
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { fetchFirstOrNull } from '../shared/failover-fetch.js';
import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from '../shared/cinematic-render.js';
+import { resolveURI, IPFS_GATEWAYS } from '../ipfs.js';
const MCP_ENDPOINT = '/api/pump-fun-mcp';
// The one and only coin — featured on the no-mint landing.
@@ -274,7 +275,9 @@ async function resolveImage(d) {
function ipfsToHttp(url) {
if (typeof url !== 'string') return null;
- if (url.startsWith('ipfs://')) return `https://ipfs.io/ipfs/${url.slice(7)}`;
+ // Resolve through the shared gateway list so this page inherits every gateway
+ // the rest of the platform rotates through, instead of pinning one host.
+ if (url.startsWith('ipfs://')) return resolveURI(url);
return url;
}
@@ -283,9 +286,14 @@ function ipfsToHttp(url) {
// isn't a known gateway URL (nothing useful to retry).
function altIpfsGateway(url) {
if (typeof url !== 'string') return null;
- if (url.includes('ipfs.io/ipfs/')) return url.replace('ipfs.io/ipfs/', 'dweb.link/ipfs/');
- if (url.includes('dweb.link/ipfs/')) return url.replace('dweb.link/ipfs/', 'ipfs.io/ipfs/');
- return null;
+ // Find which shared gateway this URL currently uses and hand back the next
+ // one in the list, so a retry walks the whole chain rather than bouncing
+ // between the same two hosts.
+ const idx = IPFS_GATEWAYS.findIndex((gw) => url.startsWith(gw));
+ if (idx === -1) return null;
+ const cid = url.slice(IPFS_GATEWAYS[idx].length);
+ const next = IPFS_GATEWAYS[(idx + 1) % IPFS_GATEWAYS.length];
+ return next === IPFS_GATEWAYS[idx] ? null : `${next}${cid}`;
}
function numOrNull(v) {
diff --git a/src/garment-catalog.js b/src/garment-catalog.js
index ab8dbb64f..030f2bab8 100644
--- a/src/garment-catalog.js
+++ b/src/garment-catalog.js
@@ -117,14 +117,73 @@ let _catalogPromise = null;
* @param {typeof fetch} [opts.fetchImpl]
* @returns {Promise<{ garments: object[], rejected: Array<{id: string, errors: string[]}> }>}
*/
+// One bounded attempt plus two retries: the catalog is a small static file, so a
+// transient 5xx or a dropped connection is worth re-asking before falling back.
+async function fetchCatalogPayload(fetchImpl, url) {
+ let lastErr;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt > 0) await new Promise((r) => setTimeout(r, 300 * attempt));
+ try {
+ const res = await fetchImpl(url, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!res.ok) {
+ const err = new Error(`garment catalog fetch failed: ${res.status}`);
+ if (res.status < 500 && res.status !== 429) throw err;
+ lastErr = err;
+ continue;
+ }
+ return await res.json();
+ } catch (err) {
+ lastErr = err;
+ if (err?.message?.startsWith('garment catalog fetch failed')) throw err;
+ }
+ }
+ throw lastErr;
+}
+
+const CATALOG_CACHE_KEY = (url) => `three.ws:garment-catalog:${url}`;
+const CATALOG_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
+
+function readCatalogCache(url) {
+ try {
+ const raw = localStorage.getItem(CATALOG_CACHE_KEY(url));
+ if (!raw) return null;
+ const { at, payload } = JSON.parse(raw);
+ return Date.now() - at < CATALOG_CACHE_TTL_MS ? payload : null;
+ } catch {
+ return null;
+ }
+}
+
+function writeCatalogCache(url, payload) {
+ try {
+ localStorage.setItem(CATALOG_CACHE_KEY(url), JSON.stringify({ at: Date.now(), payload }));
+ } catch {
+ // A private window or a full quota is not a reason to fail the load.
+ }
+}
+
export function loadCatalog(opts = {}) {
if (_catalogPromise && !opts.force) return _catalogPromise;
const url = opts.url || GARMENT_CATALOG_URL;
const fetchImpl = opts.fetchImpl || fetch;
_catalogPromise = (async () => {
- const res = await fetchImpl(url, { headers: { accept: 'application/json' } });
- if (!res.ok) throw new Error(`garment catalog fetch failed: ${res.status}`);
- const { garments, rejected } = sanitizeCatalog(await res.json());
+ let payload;
+ try {
+ payload = await fetchCatalogPayload(fetchImpl, url);
+ writeCatalogCache(url, payload);
+ } catch (err) {
+ // The catalog is a static manifest on one bucket. A blip there used to
+ // empty the garment picker outright; the copy this browser last loaded
+ // is a far better answer than no garments at all.
+ const cached = readCatalogCache(url);
+ if (!cached) throw err;
+ console.warn(`[garment-catalog] fetch failed (${err?.message || err}); using the last catalog this browser loaded`);
+ payload = cached;
+ }
+ const { garments, rejected } = sanitizeCatalog(payload);
if (rejected.length) {
console.warn(
`[garment-catalog] dropped ${rejected.length} invalid manifest(s):`,
diff --git a/src/ipfs.js b/src/ipfs.js
index 7ea1fa5fe..4adc20b86 100644
--- a/src/ipfs.js
+++ b/src/ipfs.js
@@ -13,10 +13,12 @@
// requests to either now fail DNS (ERR_NAME_NOT_RESOLVED). pump.fun metadata
// still hands out cf-ipfs.com image URLs, so we keep this list dead-host-free
// and rewrite any lingering dead-gateway URL via normalizeGatewayURL().
-const IPFS_GATEWAYS = [
+export const IPFS_GATEWAYS = [
'https://dweb.link/ipfs/',
'https://ipfs.io/ipfs/',
'https://flk-ipfs.xyz/ipfs/',
+ 'https://w3s.link/ipfs/',
+ 'https://nftstorage.link/ipfs/',
];
const AR_GATEWAY = 'https://arweave.net/';
diff --git a/src/pump/pumpkit-whale.js b/src/pump/pumpkit-whale.js
index a15c325d8..e3e1e9fe2 100644
--- a/src/pump/pumpkit-whale.js
+++ b/src/pump/pumpkit-whale.js
@@ -8,7 +8,17 @@
import { getSolPriceUsd } from '../shared/usd-price.js';
-const RPC_MAINNET = 'https://api.mainnet-beta.solana.com';
+// api.mainnet-beta.solana.com refuses most browser origins outright, so the
+// whale feed used to be dead on arrival with nothing on screen saying why. Every
+// other browser Solana caller goes through our own proxy, which fronts the
+// keyed, rotating server chain; do the same here and keep the public endpoint
+// only for a non-browser caller that has no origin to proxy from.
+const RPC_MAINNET = (() => {
+ try {
+ if (typeof location !== 'undefined' && location.origin) return `${location.origin}/api/solana-rpc`;
+ } catch { /* fall through to the public endpoint */ }
+ return 'https://api.mainnet-beta.solana.com';
+})();
const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';
const LAMPORTS_PER_SOL = 1_000_000_000;
const NATIVE_SOL = 'So11111111111111111111111111111111111111112';
diff --git a/src/solana/jupiter-swap.js b/src/solana/jupiter-swap.js
index b752887e5..6ab2cc2ab 100644
--- a/src/solana/jupiter-swap.js
+++ b/src/solana/jupiter-swap.js
@@ -7,6 +7,7 @@
import { createJupiterApiClient } from '@jup-ag/api';
import { detectSolanaWallet, SOLANA_RPC } from '../erc8004/solana-deploy.js';
+import { fetchFirst } from '../shared/failover-fetch.js';
export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
export const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
@@ -14,6 +15,22 @@ export const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
// Jupiter consolidated quote-api.jup.ag/v6 and token.jup.ag onto lite-api.jup.ag;
// the old hosts now fail every request.
const JUPITER_API_URL = 'https://lite-api.jup.ag/swap/v1';
+// Every source above returns an array of token records; only these four fields
+// are read downstream, and a rung with none of them is treated as a miss so the
+// chain moves on rather than caching an empty picker.
+function normalizeTokenList(raw) {
+ const rows = Array.isArray(raw) ? raw : [];
+ const out = rows
+ .map((t) => ({
+ address: t?.address || t?.id || null,
+ symbol: t?.symbol || '',
+ name: t?.name || '',
+ decimals: Number.isFinite(t?.decimals) ? t.decimals : 0,
+ }))
+ .filter((t) => t.address && t.symbol);
+ return out.length ? out : null;
+}
+
const JUPITER_TOKENS_URL = 'https://lite-api.jup.ag/tokens/v2/tag?query=verified';
const FETCH_TIMEOUT_MS = 10_000;
const QUOTE_TTL_MS = 15_000;
@@ -131,9 +148,27 @@ const TOKEN_LIST_TTL = 5 * 60_000;
export async function getJupiterTopTokens() {
if (_tokenListCache && Date.now() - _tokenListTs < TOKEN_LIST_TTL) return _tokenListCache;
- const res = await fetch(JUPITER_TOKENS_URL, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
- if (!res.ok) throw new Error(`Jupiter token list fetch failed: ${res.status}`);
- _tokenListCache = await res.json();
+ // The token picker is unusable without a list, and Jupiter's lite host is one
+ // box: fall through to its own mirror and then to the Solana Labs registry,
+ // normalising each shape to the fields the picker reads.
+ const list = await fetchFirst([
+ {
+ name: 'jup-lite',
+ url: JUPITER_TOKENS_URL,
+ parse: async (r) => normalizeTokenList(await r.json()),
+ },
+ {
+ name: 'jup-tokens',
+ url: 'https://tokens.jup.ag/tokens?tags=verified',
+ parse: async (r) => normalizeTokenList(await r.json()),
+ },
+ {
+ name: 'solana-labs',
+ url: 'https://raw.githubusercontent.com/solana-labs/token-list/main/src/tokens/solana.tokenlist.json',
+ parse: async (r) => normalizeTokenList((await r.json())?.tokens),
+ },
+ ], { timeoutMs: FETCH_TIMEOUT_MS, label: 'jupiter-token-list' });
+ _tokenListCache = list;
_tokenListTs = Date.now();
return _tokenListCache;
}
diff --git a/src/token-pay.js b/src/token-pay.js
index 1faa71f24..f0b8ac12f 100644
--- a/src/token-pay.js
+++ b/src/token-pay.js
@@ -202,16 +202,31 @@ export async function payWithToken({
// 4. Settle (server verifies on-chain and records the payment)
onStatus('settling');
- const settleResp = await fetch('/api/token/settle', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({ quote_token: quote.quote_token, tx_signature: signature, network }),
- });
- const settled = await settleResp.json();
+ // The transaction is already signed, broadcast and confirmed by this point, so
+ // a settle call that dies at the transport layer must never surface as a bare
+ // unhandled rejection: the payer needs the signature in hand to reconcile.
+ let settleResp;
+ try {
+ settleResp = await fetch('/api/token/settle', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ quote_token: quote.quote_token, tx_signature: signature, network }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch (err) {
+ throw Object.assign(
+ new Error(`Payment sent (transaction ${signature}) but confirmation could not be reached: ${err?.message || err}. It will be reconciled; keep this signature.`),
+ { code: 'settle_unreachable', tx_signature: signature, paid: true },
+ );
+ }
+ // A gateway 502 answers with an HTML body, so parsing is allowed to fail
+ // without turning a real payment into "Unexpected token <".
+ const settled = await settleResp.json().catch(() => ({}));
if (!settleResp.ok) {
- throw Object.assign(new Error(settled.error_description || 'settlement failed'), {
- code: settled.error,
+ throw Object.assign(new Error(settled.error_description || `settlement failed (HTTP ${settleResp.status}); payment ${signature} will be reconciled`), {
+ code: settled.error || 'settle_failed',
+ paid: true,
tx_signature: signature,
});
}
diff --git a/src/validation-ui.js b/src/validation-ui.js
index 9f9599008..416b0627a 100644
--- a/src/validation-ui.js
+++ b/src/validation-ui.js
@@ -12,6 +12,7 @@
import { ensureWallet } from './erc8004/agent-registry.js';
import { recordValidation, hashReport } from './erc8004/validation-recorder.js';
import { fetchValidationState } from './shared/validation-badge.js';
+import { resolveURI } from './ipfs.js';
/**
* Latest on-chain verdict for an agent, shaped for renderRecord(). Returns null
@@ -384,12 +385,11 @@ export class ValidationDashboard {
}
}
+ // One hardcoded gateway is one outage away from every validation record
+ // rendering blank. resolveURI walks the shared gateway list in src/ipfs.js,
+ // which the rest of the platform already rotates through.
resolveIPFS(uri) {
- if (uri?.startsWith('ipfs://')) {
- const cid = uri.slice(7);
- return `https://dweb.link/ipfs/${cid}`;
- }
- return uri;
+ return resolveURI(uri);
}
escapeHtml(str) {
diff --git a/tests/garment-catalog.test.js b/tests/garment-catalog.test.js
index e36975ed3..a2b9a4ef8 100644
--- a/tests/garment-catalog.test.js
+++ b/tests/garment-catalog.test.js
@@ -120,13 +120,18 @@ describe('loadCatalog', () => {
});
it('does not cache a failed fetch', async () => {
+ // A dropped connection is retried before giving up, so the count is the
+ // attempt budget rather than one. What must hold is that the FAILURE is
+ // not cached: the next call fetches again and succeeds.
let calls = 0;
const failing = async () => { calls++; throw new Error('offline'); };
await expect(loadCatalog({ force: true, url: 'https://t.test/c.json', fetchImpl: failing }))
.rejects.toThrow('offline');
+ expect(calls).toBeGreaterThan(0);
+ const attemptsSpent = calls;
const ok = await loadCatalog({ url: 'https://t.test/c.json', fetchImpl: okFetch([validManifest()]) });
expect(ok.garments).toHaveLength(1);
- expect(calls).toBe(1);
+ expect(calls).toBe(attemptsSpent);
});
});