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(prices,qr): quote tokens and BTC across four feeds each, and give both deposit QRs a backup service plus a readable fallback

nirholasb3c42db1f4df
diff --git a/public/forever.js b/public/forever.js
index d88b548e3..969631339 100644
--- a/public/forever.js
+++ b/public/forever.js
@@ -113,36 +113,79 @@ els.feeRate.addEventListener('change', renderFeeEstimate);
updateCounters();
renderFeeEstimate();
-// ── btc/usd price (single fetch, best-effort) ───────────────────
+// ── btc/usd price (best-effort, four feeds) ─────────────────────
+// CoinGecko alone, un-timed, meant a rate-limited or slow CoinGecko silently
+// dropped the fiat fee estimate for everyone. Four keyless CORS-enabled feeds
+// are tried in order, each under its own deadline, so the estimate survives any
+// one of them being down. This file ships as a raw public/ copy (it is not a
+// Vite input), so the chain is inline rather than imported from src/shared.
+const BTC_FEEDS = [
+ {
+ url: 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd',
+ pick: (d) => d?.bitcoin?.usd,
+ },
+ {
+ url: 'https://api.coinbase.com/v2/prices/BTC-USD/spot',
+ pick: (d) => d?.data?.amount,
+ },
+ {
+ url: 'https://api.kraken.com/0/public/Ticker?pair=XBTUSD',
+ pick: (d) => d?.result?.XXBTZUSD?.c?.[0],
+ },
+ {
+ url: 'https://coins.llama.fi/prices/current/coingecko:bitcoin',
+ pick: (d) => d?.coins?.['coingecko:bitcoin']?.price,
+ },
+];
+
async function fetchBtcPrice() {
- try {
- const r = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd');
- if (!r.ok) return;
- const d = await r.json();
- const p = d?.bitcoin?.usd;
- if (typeof p === 'number') {
- BTC_USD = p;
- renderFeeEstimate();
+ for (const feed of BTC_FEEDS) {
+ try {
+ const r = await fetch(feed.url, { signal: AbortSignal.timeout(4000) });
+ if (!r.ok) continue;
+ const p = Number(feed.pick(await r.json()));
+ if (Number.isFinite(p) && p > 0) {
+ BTC_USD = p;
+ renderFeeEstimate();
+ return;
+ }
+ } catch {
+ // Try the next feed; the estimate is a nicety, never a blocker.
}
- } catch {
- // Price is decoration; not required for the flow.
}
}
fetchBtcPrice();
// ── QR rendering ────────────────────────────────────────────────
-// Uses Google's chart server as a zero-dep QR generator. The payload is the
-// BIP-21 URI so any Bitcoin wallet can scan it directly. Fallback to a plain
-// address QR if BIP-21 construction fails.
+// Two zero-dep QR services, tried in order. The payload is the BIP-21 URI so
+// any Bitcoin wallet can scan it directly. If both services are unreachable the
+// box shows the payment URI as selectable text instead of a broken-image icon:
+// the user is mid-payment and must never be left with nothing to act on.
+const QR_SERVICES = [
+ (data, px) => `https://api.qrserver.com/v1/create-qr-code/?size=${px}x${px}&margin=0&data=${encodeURIComponent(data)}`,
+ (data, px) => `https://quickchart.io/qr?size=${px}&margin=1&text=${encodeURIComponent(data)}`,
+];
+
function renderQR(payload) {
els.qrBox.innerHTML = '';
const img = document.createElement('img');
img.alt = 'Bitcoin payment QR';
- img.src =
- 'https://api.qrserver.com/v1/create-qr-code/?size=400x400&margin=0&data=' +
- encodeURIComponent(payload);
img.loading = 'eager';
img.decoding = 'async';
+ let attempt = 0;
+ const tryNext = () => {
+ if (attempt < QR_SERVICES.length) {
+ img.src = QR_SERVICES[attempt++](payload, 400);
+ return;
+ }
+ const fallback = document.createElement('p');
+ fallback.className = 'qr-fallback';
+ fallback.style.cssText = 'word-break:break-all;font:500 12px/1.5 ui-monospace,monospace;user-select:all;';
+ fallback.textContent = payload;
+ img.replaceWith(fallback);
+ };
+ img.addEventListener('error', tryNext);
+ tryNext();
els.qrBox.appendChild(img);
}
diff --git a/src/agent-edit.js b/src/agent-edit.js
index 5ea7d2b5e..ea022e804 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -2294,10 +2294,35 @@ $('send-confirm').addEventListener('click', async () => {
}
});
+// Ordered QR services: qrserver first, quickchart as the backup. On the final
+// failure the <img> is hidden so the copyable address text stands alone.
+const QR_SERVICES = [
+ (data, px) => `https://api.qrserver.com/v1/create-qr-code/?size=${px}x${px}&data=${encodeURIComponent(data)}`,
+ (data, px) => `https://quickchart.io/qr?size=${px}&margin=1&text=${encodeURIComponent(data)}`,
+];
+
+function setQrSrc(img, data, px) {
+ if (!img) return;
+ let attempt = 0;
+ const tryNext = () => {
+ if (attempt < QR_SERVICES.length) {
+ img.hidden = false;
+ img.src = QR_SERVICES[attempt++](data, px);
+ return;
+ }
+ img.hidden = true;
+ };
+ img.onerror = tryNext;
+ tryNext();
+}
+
$('wallet-fund-btn').addEventListener('click', () => {
if (!walletInfo?.solAddr) { alert('Solana wallet not provisioned yet.'); return; }
$('fund-address').textContent = walletInfo.solAddr;
- $('fund-qr').src = `https://api.qrserver.com/v1/create-qr-code/?size=240x240&data=${encodeURIComponent(walletInfo.solAddr)}`;
+ // Two QR services, tried in order. The address is already rendered as text
+ // above, so an outage of both leaves the modal usable rather than showing a
+ // broken-image icon where the deposit QR belongs.
+ setQrSrc($('fund-qr'), walletInfo.solAddr, 240);
$('fund-modal').hidden = false;
});
$('fund-close').addEventListener('click', () => { $('fund-modal').hidden = true; });
diff --git a/src/credits.js b/src/credits.js
index 12ee6c71e..88c24aea4 100644
--- a/src/credits.js
+++ b/src/credits.js
@@ -10,7 +10,7 @@
import { getAdapter } from './onchain/adapters/index.js';
import { resolveTokenProgramId } from './shared/spl-token-program.js';
-import { solToUsd } from './shared/usd-price.js';
+import { solToUsd, getTokenPriceUsd } from './shared/usd-price.js';
const SOL_MINT = 'So11111111111111111111111111111111111111112';
@@ -231,12 +231,11 @@ async function loadPrices() {
const p = await solToUsd(1);
if (p > 0) state.prices[mint] = p;
} else {
- const r = await fetch(`https://lite-api.jup.ag/price/v3?ids=${mint}`);
- if (r.ok) {
- const d = await r.json();
- const p = Number(d?.[mint]?.usdPrice ?? d?.[mint]?.price);
- if (p > 0) state.prices[mint] = p;
- }
+ // Same shared chain as SOL, per mint: Jupiter -> DexScreener ->
+ // GeckoTerminal -> DefiLlama, each bounded. A single un-timed Jupiter
+ // call used to leave the estimate blank whenever Jupiter was slow.
+ const p = await getTokenPriceUsd(mint);
+ if (p > 0) state.prices[mint] = p;
}
} catch {
/* estimate is a nicety */
diff --git a/src/shared/usd-price.js b/src/shared/usd-price.js
index ff5beea7c..ef108fa10 100644
--- a/src/shared/usd-price.js
+++ b/src/shared/usd-price.js
@@ -72,6 +72,116 @@ export async function getSolPriceUsd() {
}
}
+// Per-mint price feeds, all keyless and CORS-enabled, mirroring the server-side
+// chain in api/_lib/market/token-market.js. Jupiter knows pump.fun bonding
+// curves, DexScreener and GeckoTerminal index the pools directly, so a token
+// that is missing from one is usually present in another.
+function tokenFeeds(mint) {
+ return [
+ {
+ name: 'jupiter',
+ url: `https://lite-api.jup.ag/price/v3?ids=${mint}`,
+ parse: async (r) => {
+ const d = await r.json();
+ return asPrice(d?.[mint]?.usdPrice ?? d?.[mint]?.price);
+ },
+ },
+ {
+ name: 'dexscreener',
+ url: `https://api.dexscreener.com/latest/dex/tokens/${mint}`,
+ parse: async (r) => {
+ const pairs = (await r.json())?.pairs;
+ if (!Array.isArray(pairs) || !pairs.length) return null;
+ // Deepest pool is the honest quote; a thin pool can print anything.
+ const best = pairs.reduce((a, b) => ((Number(b?.liquidity?.usd) || 0) > (Number(a?.liquidity?.usd) || 0) ? b : a));
+ return asPrice(best?.priceUsd);
+ },
+ },
+ {
+ name: 'geckoterminal',
+ url: `https://api.geckoterminal.com/api/v2/networks/solana/tokens/${mint}`,
+ parse: async (r) => asPrice((await r.json())?.data?.attributes?.price_usd),
+ },
+ {
+ name: 'llama',
+ url: `https://coins.llama.fi/prices/current/solana:${mint}`,
+ parse: async (r) => asPrice((await r.json())?.coins?.[`solana:${mint}`]?.price),
+ },
+ ];
+}
+
+const _tokenPrices = new Map(); // mint -> { price, at }
+
+/**
+ * Live USD price of one whole SPL token, across four independent feeds.
+ * Returns null (never throws, never guesses) when every feed misses, so a
+ * caller shows the raw token amount rather than a wrong dollar figure.
+ *
+ * @param {string} mint
+ * @returns {Promise<number|null>}
+ */
+export async function getTokenPriceUsd(mint) {
+ if (!mint) return null;
+ if (mint === SOL_MINT) return getSolPriceUsd().catch(() => null);
+ const hit = _tokenPrices.get(mint);
+ if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.price;
+ try {
+ const { value } = await fetchFirst(tokenFeeds(mint), { timeoutMs: 4000, label: `token-price:${mint.slice(0, 6)}` });
+ _tokenPrices.set(mint, { price: value, at: Date.now() });
+ return value;
+ } catch {
+ // Keep serving the last real price through a blip rather than blanking the
+ // estimate; the caller's own copy says the rate is applied at settlement.
+ return hit?.price ?? null;
+ }
+}
+
+// BTC/USD, same shape as the SOL chain. Used by the inscription flow's fee
+// estimate, which previously hung on a single un-timed CoinGecko call.
+const BTC_FEEDS = [
+ {
+ name: 'coingecko',
+ url: 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd',
+ parse: async (r) => asPrice((await r.json())?.bitcoin?.usd),
+ },
+ {
+ name: 'coinbase',
+ url: 'https://api.coinbase.com/v2/prices/BTC-USD/spot',
+ parse: async (r) => asPrice((await r.json())?.data?.amount),
+ },
+ {
+ name: 'kraken',
+ url: 'https://api.kraken.com/0/public/Ticker?pair=XBTUSD',
+ parse: async (r) => asPrice((await r.json())?.result?.XXBTZUSD?.c?.[0]),
+ },
+ {
+ name: 'llama',
+ url: 'https://coins.llama.fi/prices/current/coingecko:bitcoin',
+ parse: async (r) => asPrice((await r.json())?.coins?.['coingecko:bitcoin']?.price),
+ },
+];
+
+let _btcPrice = 0;
+let _btcPriceAt = 0;
+
+/**
+ * Live BTC/USD across four feeds. Returns null when all of them miss, so a
+ * caller can hide a fiat estimate instead of printing a stale or invented one.
+ *
+ * @returns {Promise<number|null>}
+ */
+export async function getBtcPriceUsd() {
+ if (Date.now() - _btcPriceAt < CACHE_TTL_MS && _btcPrice > 0) return _btcPrice;
+ try {
+ const { value } = await fetchFirst(BTC_FEEDS, { timeoutMs: 4000, label: 'btc-price-client' });
+ _btcPrice = value;
+ _btcPriceAt = Date.now();
+ return _btcPrice;
+ } catch {
+ return _btcPrice > 0 ? _btcPrice : null;
+ }
+}
+
/** USDC → USD (1:1, pegged stablecoin). */
export function usdcToUsd(amount) {
return Number(amount);