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.

build: fail fast when a Node-only import reaches the browser bundle

nirholasc43fed517a62
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5476af549..89bccb2ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,11 +16,15 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Category pages keep working when the market data provider rate-limits us** — Every coin category page (layer-1, AI tokens, meme tokens and the rest) is built from one upstream market data provider, because it is the only free source that knows which coins belong to which sector. Whenever that provider throttled us, those pages returned an error and showed nothing at all, while the main coins table stayed up because it has a second source to fall back on. Category pages now fall back to the most recent real data they successfully loaded, clearly marked as of when it was fetched, and switch back to live figures the moment the provider recovers. Nothing is invented: a category we have never loaded still reports the outage honestly rather than showing a made-up table. `[fix, improvement]`
- **Chat now forges and displays 3D models right in the conversation** — Ask the chat at three.ws/chat for a 3D model and it generates one with the free Forge lane, streams live progress in place, and then renders the finished model as an interactive viewer inside the thread: orbit and zoom it, play its animations, toggle the skeleton on rigged avatars, download the GLB, or open it in AR. Pasting a link to any .glb file now shows the model the same way, even when the file's host would normally block the browser from reading it. Previously 3D results only appeared inside a boxed-in web page you had to click into. (`/chat`) `[feature, improvement]`
- **Coin pages stay up when the market data provider rate-limits us** — The price chart, profile and exchange listings on a coin page all came from one provider, so whenever it throttled our requests the whole page went down at once, for hours. Each of those now has a live backup: charts fall back to exchange candles for the majors and an on-chain price oracle for every other coin, while the profile and market listings fall back to a second data provider. When a backup is answering, the page says so at the bottom instead of quietly leaving numbers blank, and columns the backup cannot fill are hidden rather than shown as a row of dashes. Two small honesty fixes came with it: a follower count of zero now means "not tracked" and is left out rather than stated as zero, and a price change the backup does not actually compute is no longer drawn as a flat 0.00%. (`/coins`) `[fix, improvement]`
+- **Command palette search now tolerates typos and ranks results properly** — The dashboard palette finds what you meant when you mistype (searching 'markteplace' now finds Marketplace) and orders results by how well they actually match, instead of lumping every loose match together at the same rank. Matched letters are highlighted at their real positions. (`/dashboard`) `[improvement]`
- **Concierge demo and the 3D home demo both work again** — The live widget on the Concierge page failed to start because the page ran its setup before the widget code had finished loading, leaving visitors with a dead demo on the page that sells it. The /demos/3d-home animated avatar demo never rendered its character either: the model uses compressed geometry and the page was loading it without the matching decoder. Both now load, animate, and respond as intended. (`/concierge`) `[fix]`
- **Ethereum name lookups work again** — Looking up an .eth name through the public name resolver had stopped working: every request sat there for about ten seconds and then came back as an error, while .sol names resolved fine. Two things were wrong. The Ethereum node we asked first had started refusing our requests outright, and because it was first in line every lookup wasted a full round trip on it before trying anywhere else. On top of that, the lookup itself was asking the network four or five separate questions in sequence when one would do. Nodes known to refuse us are now tried last instead of first, and a name lookup is a single question. An .eth name now resolves in about a quarter of a second, and a name that genuinely does not exist comes back as a clean not-found instead of a timeout. (`/crypto-api`) `[fix]`
- **Every x402 payment now settles against its own Solana transaction** — An audit of our payment facilitator found that about one in five recorded settlements shared an on-chain transaction with another settlement. Solana signatures are deterministic, so two payments of the same amount, from the same wallet, to the same endpoint, built in the same short window could compile to a byte-for-byte identical transaction. Only one of them could ever land on chain, and the facilitator was crediting the others against it. Settlement is now claimed atomically: one transaction settles at most one payment, a genuine retry is recognised and answered without double-charging, and anything else is refused rather than credited. The payment builder also draws from a signature space about four thousand times larger, at no extra fee, so identical transactions are no longer built in the first place. A new hourly audit watches the invariant and raises an alert if it is ever violated again. `[fix, infra, security]`
+- **Exported chat transcripts can no longer carry spreadsheet formulas** — When a widget owner exports their chat transcripts as a CSV, a visitor message that began with a character like = or @ could be treated as a live formula by Excel or Google Sheets when the file was opened. Exported text is now always neutralized so it opens as plain text. The audit-log export already did this; both exports now share one implementation so they cannot drift apart again. (`/widgets`) `[security, fix]`
- **Fact checks that used to time out now come back with their sources** — Some fact checks were taking so long that the request was cut off before anything came back, and the caller got an error instead of an answer. Two things caused it. The checker asks a language model to write search queries and then to judge each source it finds; if none of the model providers could answer, that step threw the whole check away, even though the checker had already gathered real sources and knew how to carry on without the model. And nothing kept an eye on the clock, so a slow run could outlast the time limit the request had to begin with. Both are fixed. A check now works to a time budget and hands each step whatever is left, so it always finishes with something to show. If a step genuinely cannot reach a model, the check falls back instead of failing: it searches the claim itself, returns the sources it found with their excerpts, and marks the verdict as insufficient rather than guessing. The response now says plainly which step fell back, and a result produced that way is deliberately not cached, so asking again re-runs the full check rather than replaying a bad day. (`/fact-check`) `[fix, improvement]`
+- **Hardened how agent and model text is displayed across the site** — Everywhere the site shows text written by an AI model or another person (agent chat replies, bounty briefs, the on-page concierge widget, saved memories, skill manifests), that text is now rendered through a single hardened pipeline that strips anything dangerous before it reaches the page. It also renders more of what you actually write: tables, nested lists, and strikethrough now display properly instead of appearing as raw symbols. Previously eight different parts of the site each interpreted this text their own way, with no shared safety net. `[security, improvement]`
- **Notification mute switches actually work now** — The per-category switches in settings let you turn the bell off for a kind of notification, but the bell ignored them and filled up anyway. They work now. One deliberate exception: account and security notices (withdrawals, payment problems, security alerts) always stay in your bell, because that is your record of what happened to your account and losing it silently would be worse than a little noise. You can still turn off their push, email and Telegram. Those always-on switches now show as locked in settings instead of pretending to be adjustable. (`/dashboard/settings`) `[fix, improvement]`
+- **Notifications stack instead of replacing each other** — Confirmation messages across the dashboard now queue up and stay readable when several happen at once, can be dismissed with a click, and are announced to screen readers. Before this, a second message would silently overwrite the first. (`/dashboard`) `[improvement]`
- **On-chain agent pages now load their registration details reliably** — ERC-8004 agent pages read each agent's registration document from wherever its owner published it. Most of those hosts do not permit direct browser access, so a large share of agents showed "Could not fetch registration JSON" instead of their name, description, avatar, and skills. Pages now fall back to fetching that document through three.ws, so those agents render in full. The fallback validates every address it connects to and caps the download, so a hostile registration link cannot reach anything private. (`/docs/erc8004`) `[fix]`
- **Ordinary new coins are no longer mistaken for honeypots** — Before any automated buy, the platform simulates a full buy-then-sell round trip on-chain to prove the coin can actually be sold again, and blocks anything that cannot be exited. That simulation runs from the buying agent's own wallet, so when the wallet was too small to fund the simulated purchase, the failure was being read as evidence that the coin was a trap. One underfunded agent produced 336 consecutive false honeypot verdicts in a single afternoon on perfectly normal launches. The safety probe now scales down to a size the wallet can actually simulate, since a real honeypot traps a seller at any size, and an out-of-funds failure is now reported as exactly that. Coins that genuinely cannot be sold are still blocked, and a wallet too empty to prove anything is still refused rather than waved through. `[fix, security]`
- **Payments that had already gone through no longer come back as failures** — When an agent pays three.ws for an API call, the payment is sent to Solana and then confirmed. If the node that answered replied in a shape our software could not read, the platform gave up and called the payment failed, even though in many cases it had already settled on-chain. The caller got an error for something they had genuinely paid for. The platform now asks the chain directly before declaring any payment failed, and skips that check only in the one case that proves the payment never reached the network at all. Separately, the most common payment failure used to reach our logs carrying no reason whatsoever, which made it impossible to diagnose or fix; the underlying cause is now recorded alongside it. `[fix]`
@@ -28,6 +32,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Production now watches every paid Solana connection, not just one** — three.ws reaches the Solana blockchain through several providers so that if one runs out of capacity the others carry the load. Until now the status page only watched one of them, which meant the platform could report a healthy connection while every paid provider was actually out of quota and all traffic had quietly fallen back to slower free servers. That state is hard to spot from the outside: it shows up as occasional slow pages and failed on-chain actions rather than a clean outage. The status page now reports the health of the whole set, and says plainly when everything paid has run out so it can be topped up before anyone notices. (`/status`) `[infra, improvement]`
- **Restyled models read properly in the feed** — When someone restyled a model, the activity feed just said they "shared something" with a generic icon. Restyles now say so, with their own icon, and a colorway variant is labelled as one instead of being lumped in with a hand-directed restyle. (`/feed`) `[fix]`
- **Solana RPC failover fixed: the paid reserve is no longer the primary lane** — The platform routes every Solana call through a chain of RPC providers so no single one becomes a bottleneck, with a paid endpoint held back as an emergency reserve. A configuration mistake had that reserve listed as the primary as well, and because the chain keeps the first entry for a repeated address, it quietly served all traffic and burned through its daily request cap while the free providers sat idle. The reserve is now held back as intended and the premium provider leads. Two safeguards prevent a repeat: the slowest public endpoint can no longer outrank a paid provider by being used as a default, and when one server discovers a provider is out of quota, the rest of the fleet now inherits that verdict immediately instead of each wasting another request against a cap that is already full. `[infra, fix]`
+- **Steadier market data during upstream rate limits and outages** — Market, coin, and price lookups now retry with randomized spacing rather than every request retrying in lockstep, which is what turned a brief upstream hiccup into a stampede. The in-memory caches behind those pages also keep the entries that are actually being used, instead of discarding the oldest one regardless of demand, so busy pages stay fast during a slowdown. (`/markets`) `[improvement, infra]`
- **Stopped two automated systems from passing the same SOL back and forth** — One background job tops up each trading agent wallet to a working balance. Another reclaims idle SOL from platform wallets back to the treasury so the agent economy can pay its network fees. Their thresholds disagreed, so they took turns moving the same funds in opposite directions: in one fifteen-minute window 0.24 SOL made that round trip six times, paying a network fee each leg, and the agents never held a balance long enough to trade. Both jobs now read a single shared policy with one rule, that a reclaim can never take a wallet below the level the top-up will immediately restore. The reclaim also now leaves every active trader enough to cover a complete trade, including the safety check that runs before it. `[fix, infra]`
- **The agent directory is now readable without JavaScript, and the homepage loads lighter** — Two things that made the site slower and harder to find. The Discover directory indexes over 150,000 agents but built its entire page in the browser, so search engines, link previews, and anyone on a slow or JavaScript-less connection saw an empty page. The server now sends the first page of agents and the live directory totals with the page itself, exactly matching what the browser then loads. Separately, the homepage was carrying a large duplicate copy of its own styling inline, plus two big scripts that blocked the page from drawing while they parsed. Those moved into files the browser caches once and reuses on every later visit, cutting the homepage document roughly in half. (`/discover`) `[improvement, infra]`
- **The fact checker stops timing out, and reads its sources properly** — Paid fact checks had started failing outright with a server error instead of returning a verdict. The cause was in how we try our AI providers: when the first provider accepted a request and then went quiet, we kept waiting on it (and on two more sign-ins to the same provider) until the whole time budget for the check was gone, so the providers that were healthy and ready to answer were never reached. We now stop re-trying a provider that has already gone quiet, and no single provider can eat more than a third of the remaining time while others are still waiting. Checks that used to die at 46 seconds now come back with a real, sourced answer. Alongside that, the checker reads evidence far better: its free Wikipedia source now returns the article's actual opening text instead of a 150-character fragment around a keyword, all three search angles are represented in the sources we examine rather than just the first, and a verdict is now decided by the sources that genuinely address the claim, so evidence that never mentions the claim returns an honest "not enough evidence" instead of a misleading "mixed". The published accuracy figure on the fact-check page has been cleared until a clean measurement can be taken, because the last one was recorded during the outage above and measured that outage rather than the product. (`/fact-check`) `[fix, improvement]`
diff --git a/api/_lib/coin-fallbacks.js b/api/_lib/coin-fallbacks.js
index 1262a8f0e..00beb3ec4 100644
--- a/api/_lib/coin-fallbacks.js
+++ b/api/_lib/coin-fallbacks.js
@@ -17,10 +17,26 @@
//
// DefiLlama is the reason the chart fallback is universal rather than
// majors-only: its coins oracle is addressed as `coingecko:<id>`, so no id
-// mapping is needed and every coin CoinGecko charts, DefiLlama charts too.
+// mapping is needed and every coin CoinGecko charts, DefiLlama charts too. It
+// also carries no meaningful rate limit, which is why it — not CoinPaprika —
+// takes the high-volume job.
+//
// CoinPaprika uses its own `<symbol>-<name-slug>` ids, so this module resolves
-// and caches that mapping — strictly, because serving the WRONG coin's profile
-// is worse than serving an error.
+// and caches that mapping. Resolution is deliberately conservative: an exact
+// slug/name match, or else a match proven by agreement between DefiLlama's
+// price for the requested CoinGecko id and the candidate's own price. Nothing
+// unproven is ever served, because answering with a different coin's market cap
+// is worse than answering with an error.
+//
+// **CoinPaprika's free tier allows sixty requests per HOUR** (25k/month), and
+// blocks for an hour past that. Every design choice here follows from it:
+// 1. Normalized payloads are cached in the SHARED cache, so during an outage
+// the fleet spends one round-trip per coin per cache window, not one per
+// request. This is what makes the budget survivable at all.
+// 2. Concurrent misses single-flight into one upstream call.
+// 3. The id mapping is cached for a week: a coin costs its resolution once.
+// 4. A budget rejection benches the source process-wide (api/_lib/coinpaprika.js),
+// so a spent hour costs zero further requests here or in any sibling caller.
//
// Every function here returns the exact shape its CoinGecko-backed caller
// already emits, so the page renders identically no matter which source
@@ -29,8 +45,11 @@
import { fetchFirst, fetchFirstOrNull } from '../../src/shared/failover-fetch.js';
import { cacheGet, cacheSet } from './cache.js';
+// The budget guard is process-wide and shared with the other CoinPaprika
+// callers (global stats, the paid market-heatmap endpoint) — see that module's
+// header for why the sixty-per-hour ceiling has to be tracked in one place.
+import { PAPRIKA_BASE, paprikaGet } from './coinpaprika.js';
-const PAPRIKA_BASE = 'https://api.coinpaprika.com/v1';
const LLAMA_COINS_BASE = 'https://coins.llama.fi';
const num = (v) => {
@@ -100,6 +119,84 @@ export function pickPaprikaId(raw, cgId) {
return str(matches[0].id);
}
+// ── Stage 2: symbol + price-verified resolution ──────────────────────────────
+// The slug match above resolves a bit over half the top coins. The rest fail
+// because the two catalogues simply name the same asset differently: one lists
+// it under its ticker, the other under a product name, or one carries a
+// disambiguating suffix the other doesn't. Roughly 44% of the top 50 miss on
+// slug alone. No amount of string cleverness bridges that safely, and guessing
+// is exactly what must not happen here.
+//
+// So identity is VERIFIED instead of guessed. DefiLlama's oracle is addressed by
+// CoinGecko id, so it hands back the authoritative symbol and live USD price for
+// the id we were asked about. Candidates are then drawn from CoinPaprika by that
+// symbol and accepted only when their price agrees with DefiLlama's within a
+// tight band. Two different coins that share a ticker having prices within 2% of
+// each other is vanishingly unlikely, so agreement is strong evidence of
+// identity — and unlike a name heuristic, it is evidence rather than a hunch.
+// Each probe costs one request from an hourly budget of sixty, so only the two
+// best-ranked candidates are ever checked. A coin with real market share is
+// essentially always among them, and the mapping is then cached for a week, so
+// the spend is once per coin rather than once per request.
+const PRICE_MATCH_TOLERANCE = 0.02;
+const MAX_VERIFY_CANDIDATES = 2;
+
+/** Do two prices agree closely enough to be the same asset? */
+export function pricesAgree(a, b, tolerance = PRICE_MATCH_TOLERANCE) {
+ if (!(a > 0) || !(b > 0)) return false;
+ return Math.abs(a - b) / Math.max(a, b) <= tolerance;
+}
+
+/** Authoritative symbol + USD price for a CoinGecko id, from DefiLlama. */
+async function llamaIdentity(cgId) {
+ const raw = await fetchFirstOrNull(
+ [
+ {
+ name: 'llama-identity',
+ url: `${LLAMA_COINS_BASE}/prices/current/coingecko:${encodeURIComponent(cgId)}`,
+ parse: async (r) => (await r.json())?.coins?.[`coingecko:${cgId}`] ?? null,
+ },
+ ],
+ { timeoutMs: 6000, label: `llama-id:${cgId}` },
+ );
+ const symbol = str(raw?.symbol)?.toUpperCase();
+ const price = pos(raw?.price);
+ return symbol && price ? { symbol, price } : null;
+}
+
+/**
+ * CoinPaprika candidates for a ticker symbol, best-ranked first. Exported so
+ * the ranking rule is testable without network access.
+ * @param {{currencies?: object[]}} raw /v1/search payload
+ * @param {string} symbol upper-case ticker
+ */
+export function symbolCandidates(raw, symbol) {
+ const rank = (c) => (num(c.rank) && num(c.rank) > 0 ? num(c.rank) : Number.MAX_SAFE_INTEGER);
+ return (raw?.currencies || [])
+ .filter((c) => str(c?.symbol)?.toUpperCase() === symbol && c?.is_active !== false && str(c?.id))
+ .sort((a, b) => rank(a) - rank(b))
+ .slice(0, MAX_VERIFY_CANDIDATES)
+ .map((c) => c.id);
+}
+
+/**
+ * Resolve by symbol, then prove the match on price. Returns a CoinPaprika id
+ * only when a candidate's live price agrees with DefiLlama's for the requested
+ * CoinGecko id; otherwise null, because an unproven match must not be served.
+ */
+async function resolveByPrice(cgId) {
+ const identity = await llamaIdentity(cgId);
+ if (!identity) return null;
+ const search = await paprikaGet(
+ `${PAPRIKA_BASE}/search/?q=${encodeURIComponent(identity.symbol)}&c=currencies&limit=20`,
+ );
+ for (const pid of symbolCandidates(search, identity.symbol)) {
+ const ticker = await paprikaGet(`${PAPRIKA_BASE}/tickers/${pid}?quotes=USD`);
+ if (pricesAgree(num(ticker?.quotes?.USD?.price), identity.price)) return pid;
+ }
+ return null;
+}
+
// The mapping is immutable in practice (a coin's ids don't change), so cache it
// hard: in-memory for the instance and in the shared cache for the fleet. A
// negative result is cached too, briefly — a coin CoinPaprika doesn't list
@@ -127,20 +224,12 @@ export async function resolvePaprikaId(cgId) {
_idMemo.set(id, resolved);
return resolved;
}
- const raw = await fetchFirstOrNull(
- [
- {
- name: 'coinpaprika-search',
- url: `${PAPRIKA_BASE}/search/?q=${encodeURIComponent(id)}&c=currencies&limit=20`,
- parse: async (r) => (await r.json()) ?? null,
- },
- ],
- { timeoutMs: 6000, label: `paprika-id:${id}` },
- );
+ const raw = await paprikaGet(`${PAPRIKA_BASE}/search/?q=${encodeURIComponent(id)}&c=currencies&limit=20`);
// Unreachable upstream: don't poison the cache with a negative that would
// outlive the outage. Only a real answer (hit or genuine miss) is stored.
if (!raw) return null;
- const pid = pickPaprikaId(raw, id);
+ // Stage 1 (free, no extra calls) then stage 2 (verified against price).
+ const pid = pickPaprikaId(raw, id) || (await resolveByPrice(id));
_idMemo.set(id, pid);
if (_idMemo.size > 2000) _idMemo.clear();
cacheSet(idKey(id), pid || '', pid ? ID_TTL_S : ID_MISS_TTL_S).catch(() => {});
@@ -152,6 +241,43 @@ export function resetPaprikaIdMemo() {
_idMemo.clear();
}
+// ── Payload cache ────────────────────────────────────────────────────────────
+// The single most important defence of the hourly budget. A CoinGecko outage
+// does not reduce traffic — every visitor to /coin/solana still arrives, and
+// without this each one would spend CoinPaprika requests until the hour's sixty
+// were gone, at which point the fallback is as dead as the thing it backs up.
+//
+// Caching the NORMALIZED payload (rather than the raw upstream bodies) means one
+// round-trip serves the whole fleet for the window, and the stored value is
+// exactly what the endpoint returns. The window is short because this is live
+// market data; it only has to be long enough to collapse a burst.
+//
+// Single-flight on top: N concurrent misses for the same coin — the shape of a
+// cold cache under load — await one upstream call instead of racing to spend N
+// requests on the same answer.
+const PAYLOAD_TTL_S = 120;
+const _inflight = new Map();
+
+async function cachedPayload(key, compute) {
+ const cached = await cacheGet(key).catch(() => null);
+ if (cached != null) return cached;
+ const pending = _inflight.get(key);
+ if (pending) return pending;
+ const p = (async () => {
+ try {
+ const value = await compute();
+ // A null is "couldn't answer", which must stay retryable: caching it
+ // would extend a transient miss across the whole window.
+ if (value != null) cacheSet(key, value, PAYLOAD_TTL_S).catch(() => {});
+ return value;
+ } finally {
+ _inflight.delete(key);
+ }
+ })();
+ _inflight.set(key, p);
+ return p;
+}
+
// ── Coin profile ─────────────────────────────────────────────────────────────
// Normalized to the exact object api/coin/detail.js `shape()` emits.
@@ -288,19 +414,17 @@ export function normalizePaprikaDetail(coin, ticker, cgId) {
* @returns {Promise<object|null>}
*/
export async function fetchFallbackCoinDetail(cgId) {
- const pid = await resolvePaprikaId(cgId);
- if (!pid) return null;
- const [coin, ticker] = await Promise.all([
- fetchFirstOrNull([{ name: 'coinpaprika-coin', url: `${PAPRIKA_BASE}/coins/${pid}` }], {
- timeoutMs: 8000,
- label: `paprika-coin:${pid}`,
- }),
- fetchFirstOrNull([{ name: 'coinpaprika-ticker', url: `${PAPRIKA_BASE}/tickers/${pid}?quotes=USD` }], {
- timeoutMs: 8000,
- label: `paprika-ticker:${pid}`,
- }),
- ]);
- return normalizePaprikaDetail(coin, ticker, cgId);
+ return cachedPayload(`gecko-fallback:detail:${cgId}`, async () => {
+ const pid = await resolvePaprikaId(cgId);
+ if (!pid) return null;
+ // The coin profile is near-static and the ticker is the live half; both are
+ // needed for one answer, so they go out together rather than in series.
+ const [coin, ticker] = await Promise.all([
+ paprikaGet(`${PAPRIKA_BASE}/coins/${pid}`),
+ paprikaGet(`${PAPRIKA_BASE}/tickers/${pid}?quotes=USD`),
+ ]);
+ return normalizePaprikaDetail(coin, ticker, cgId);
+ });
}
// ── Exchange listings ────────────────────────────────────────────────────────
@@ -354,30 +478,23 @@ export function normalizePaprikaMarket(m) {
* @returns {Promise<object[]|null>} null when unavailable
*/
export async function fetchFallbackTickers(cgId, { page = 1, perPage = 100 } = {}) {
- const pid = await resolvePaprikaId(cgId);
- if (!pid) return null;
- const raw = await fetchFirstOrNull(
- [
- {
- name: 'coinpaprika-markets',
- url: `${PAPRIKA_BASE}/coins/${pid}/markets?quotes=USD`,
- parse: async (r) => {
- const body = await r.json();
- return Array.isArray(body) && body.length ? body : null;
- },
- },
- ],
- { timeoutMs: 10_000, label: `paprika-markets:${pid}` },
- );
- if (!raw) return null;
- const rows = raw
- // CoinGecko's /tickers is a SPOT feed; CoinPaprika mixes perpetual and
- // futures venues into the same response (they out-volume spot and would
- // otherwise head the table). Keep the comparison honest.
- .filter((m) => String(m?.category || 'Spot').toLowerCase() === 'spot')
- .map(normalizePaprikaMarket)
- .filter((t) => t.exchange.name && t.price_usd != null)
- .sort((a, b) => (b.volume_usd ?? 0) - (a.volume_usd ?? 0));
+ // One upstream response holds every market, so the cache is keyed on the coin
+ // and paged in memory: browsing to page 2 costs no additional request.
+ const rows = await cachedPayload(`gecko-fallback:markets:${cgId}`, async () => {
+ const pid = await resolvePaprikaId(cgId);
+ if (!pid) return null;
+ const raw = await paprikaGet(`${PAPRIKA_BASE}/coins/${pid}/markets?quotes=USD`, 10_000);
+ if (!Array.isArray(raw) || !raw.length) return null;
+ return raw
+ // CoinGecko's /tickers is a SPOT feed; CoinPaprika mixes perpetual and
+ // futures venues into the same response (they out-volume spot and would
+ // otherwise head the table). Keep the comparison honest.
+ .filter((m) => String(m?.category || 'Spot').toLowerCase() === 'spot')
+ .map(normalizePaprikaMarket)
+ .filter((t) => t.exchange.name && t.price_usd != null)
+ .sort((a, b) => (b.volume_usd ?? 0) - (a.volume_usd ?? 0));
+ });
+ if (!rows) return null;
const start = (Math.max(1, page) - 1) * perPage;
return rows.slice(start, start + perPage);
}
diff --git a/data/changelog.json b/data/changelog.json
index 7b6f15426..7e3fe97e9 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,53 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-29",
+ "title": "Hardened how agent and model text is displayed across the site",
+ "summary": "Everywhere the site shows text written by an AI model or another person (agent chat replies, bounty briefs, the on-page concierge widget, saved memories, skill manifests), that text is now rendered through a single hardened pipeline that strips anything dangerous before it reaches the page. It also renders more of what you actually write: tables, nested lists, and strikethrough now display properly instead of appearing as raw symbols. Previously eight different parts of the site each interpreted this text their own way, with no shared safety net.",
+ "tags": [
+ "security",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-07-29",
+ "title": "Exported chat transcripts can no longer carry spreadsheet formulas",
+ "summary": "When a widget owner exports their chat transcripts as a CSV, a visitor message that began with a character like = or @ could be treated as a live formula by Excel or Google Sheets when the file was opened. Exported text is now always neutralized so it opens as plain text. The audit-log export already did this; both exports now share one implementation so they cannot drift apart again.",
+ "tags": [
+ "security",
+ "fix"
+ ],
+ "link": "/widgets"
+ },
+ {
+ "date": "2026-07-29",
+ "title": "Command palette search now tolerates typos and ranks results properly",
+ "summary": "The dashboard palette finds what you meant when you mistype (searching 'markteplace' now finds Marketplace) and orders results by how well they actually match, instead of lumping every loose match together at the same rank. Matched letters are highlighted at their real positions.",
+ "tags": [
+ "improvement"
+ ],
+ "link": "/dashboard"
+ },
+ {
+ "date": "2026-07-29",
+ "title": "Notifications stack instead of replacing each other",
+ "summary": "Confirmation messages across the dashboard now queue up and stay readable when several happen at once, can be dismissed with a click, and are announced to screen readers. Before this, a second message would silently overwrite the first.",
+ "tags": [
+ "improvement"
+ ],
+ "link": "/dashboard"
+ },
+ {
+ "date": "2026-07-29",
+ "title": "Steadier market data during upstream rate limits and outages",
+ "summary": "Market, coin, and price lookups now retry with randomized spacing rather than every request retrying in lockstep, which is what turned a brief upstream hiccup into a stampede. The in-memory caches behind those pages also keep the entries that are actually being used, instead of discarding the oldest one regardless of demand, so busy pages stay fast during a slowdown.",
+ "tags": [
+ "improvement",
+ "infra"
+ ],
+ "link": "/markets"
+ },
{
"date": "2026-07-29",
"title": "Chat now forges and displays 3D models right in the conversation",
diff --git a/docs/coin-pages.md b/docs/coin-pages.md
index 1c15adcc2..c75f0629a 100644
--- a/docs/coin-pages.md
+++ b/docs/coin-pages.md
@@ -119,14 +119,22 @@ through the shared [`failover-fetch`](../src/shared/failover-fetch.js) primitive
- **Coin profile** (`/api/coin/detail`) — CoinGecko `/coins/{id}` → CoinPaprika
([`api/_lib/coin-fallbacks.js`](../api/_lib/coin-fallbacks.js)). CoinPaprika
uses its own `<symbol>-<name-slug>` ids, so the module resolves the CoinGecko
- id against `/v1/search` and caches the mapping for a week. The match is
- deliberately strict — only an exact id-slug or name-slug hit counts — because
- answering with a *different* coin's market cap is worse than answering with an
- error. Fields this source doesn't carry (FDV, 24h high/low, developer stats,
- per-chain contract addresses) come back `null` and the page hides those
- sections. Circulating supply isn't published either, but market cap ÷ price
- recovers it exactly. The lookup by Solana mint (`?contract=`) has no fallback:
- CoinPaprika is addressed by coin id, not by mint.
+ id in two stages and caches the result for a week. First an exact id-slug or
+ name-slug match (`solana` → `sol-solana`), which covers a little over half the
+ top 50. The rest miss because the two catalogues list the same asset under
+ different names — one by ticker, the other by product name, or one with a
+ disambiguating suffix. For those, identity is **proven, not guessed**:
+ DefiLlama supplies the authoritative
+ symbol and price for the requested CoinGecko id, and a same-symbol candidate is
+ accepted only when its own price agrees within 2%. Two different coins sharing
+ a ticker and a price to within 2% is vanishingly unlikely, so agreement is
+ evidence; a name heuristic would only be a hunch, and serving a *different*
+ coin's market cap is worse than serving an error. Fields this source doesn't
+ carry (FDV, 24h high/low, developer stats, per-chain contract addresses) come
+ back `null` and the page hides those sections. Circulating supply isn't
+ published either, but market cap ÷ price recovers it exactly. The lookup by
+ Solana mint (`?contract=`) has no fallback: CoinPaprika is addressed by coin
+ id, not by mint.
- **Exchange listings** (`/api/coin/tickers`) — CoinGecko `/coins/{id}/tickers`
→ CoinPaprika `/coins/{id}/markets`. Derivatives venues are filtered out (the
CoinGecko endpoint it stands in for is spot-only, and perps would otherwise
@@ -163,6 +171,28 @@ Every fallback is free and keyless (Binance, Bybit and OKX are excluded — they
geo-block US datacenter IPs, so from Cloud Run they would be permanently dead
rungs).
+### Budgeting the CoinPaprika rungs
+
+**CoinPaprika's free tier allows 60 requests per hour** (25k/month) and returns
+`402 payment_required` with a one-hour block once that is spent. A fallback is
+hot exactly when CoinGecko is throttling, which is the worst possible moment to
+burn the only other profile source — so the per-coin rungs are budgeted rather
+than called per request:
+
+- **Normalized payloads are cached in the shared cache for 120s.** One round-trip
+ serves the whole fleet for the window, so 500 visitors to `/coin/solana` during
+ an outage cost one request, not 500. This is what makes the budget survivable.
+- **Concurrent misses single-flight.** A cold cache under load resolves to one
+ upstream call, not one per in-flight request.
+- **The id mapping is cached for a week**, so a coin costs its resolution once.
+- **Paging is served from the cached response** — CoinPaprika returns every market
+ in one payload, so "Load more exchanges" spends nothing.
+- **A 402/429 benches the source for an hour.** A spent budget then costs zero
+ further requests instead of one wasted round-trip per request until it resets.
+
+DefiLlama carries no comparable limit and is addressed by CoinGecko id, which is
+why it — not CoinPaprika — takes the high-volume chart job.
+
## The market tools
Four more surfaces extend Markets, all sharing the same design system
diff --git a/package.json b/package.json
index 485ca5b1f..b546a3aee 100644
--- a/package.json
+++ b/package.json
@@ -240,7 +240,7 @@
"deploy": "npm run build:all && npm run check:dist && vercel --local-config vercel.json --prod",
"build:info": "node scripts/write-build-info.mjs",
"build:info:snapshot": "node scripts/write-build-info.mjs --snapshot",
- "build:gcp": "npm run check:conflicts && npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build:chat && npm run build && npm run build:lib:full && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages",
+ "build:gcp": "npm run check:conflicts && npm run check:browser-graph && npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build:chat && npm run build && npm run build:lib:full && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages",
"ensure:avatar-studio": "test -f character-studio/build/index.html || npm run build:avatar-studio",
"deploy:gcp": "npm run check:dist && npm run check:pages && npm run db:check && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5 && npm run deploy:gcp:purge-cdn && npm run smoke:prod",
"deploy:gcp:full": "npm run build:gcp && npm run deploy:gcp",
@@ -268,7 +268,8 @@
"claude": "./scripts/claude.sh",
"typecheck": "tsc -p jsconfig.json",
"okx:bot": "node scripts/okx-bot-revive.mjs",
- "check:conflicts": "node scripts/check-merge-conflicts.mjs"
+ "check:conflicts": "node scripts/check-merge-conflicts.mjs",
+ "check:browser-graph": "node scripts/check-browser-graph.mjs"
},
"dependencies": {
"@0xsplits/splits-sdk": "^6.5.0",
diff --git a/public/changelog.json b/public/changelog.json
index 93fe863bf..402afbe89 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-29T06:15:54.723Z",
+ "generated_at": "2026-07-29T06:18:36.500Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -114,6 +114,16 @@
"improvement"
]
},
+ {
+ "date": "2026-07-29",
+ "type": "update",
+ "title": "Command palette search now tolerates typos and ranks results properly",
+ "summary": "The dashboard palette finds what you meant when you mistype (searching 'markteplace' now finds Marketplace) and orders results by how well they actually match, instead of lumping every loose match together at the same rank. Matched letters are highlighted at their real positions.",
+ "link": "/dashboard",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-07-29",
"type": "update",
@@ -146,6 +156,17 @@
"security"
]
},
+ {
+ "date": "2026-07-29",
+ "type": "update",
+ "title": "Exported chat transcripts can no longer carry spreadsheet formulas",
+ "summary": "When a widget owner exports their chat transcripts as a CSV, a visitor message that began with a character like = or @ could be treated as a live formula by Excel or Google Sheets when the file was opened. Exported text is now always neutralized so it opens as plain text. The audit-log export already did this; both exports now share one implementation so they cannot drift apart again.",
+ "link": "/widgets",
+ "tags": [
+ "security",
+ "fix"
+ ]
+ },
{
"date": "2026-07-29",
"type": "update",
@@ -157,6 +178,17 @@
"improvement"
]
},
+ {
+ "date": "2026-07-29",
+ "type": "update",
+ "title": "Hardened how agent and model text is displayed across the site",
+ "summary": "Everywhere the site shows text written by an AI model or another person (agent chat replies, bounty briefs, the on-page concierge widget, saved memories, skill manifests), that text is now rendered through a single hardened pipeline that strips anything dangerous before it reaches the page. It also renders more of what you actually write: tables, nested lists, and strikethrough now display properly instead of appearing as raw symbols. Previously eight different parts of the site each interpreted this text their own way, with no shared safety net.",
+ "link": null,
+ "tags": [
+ "security",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-29",
"type": "update",
@@ -168,6 +200,16 @@
"improvement"
]
},
+ {
+ "date": "2026-07-29",
+ "type": "update",
+ "title": "Notifications stack instead of replacing each other",
+ "summary": "Confirmation messages across the dashboard now queue up and stay readable when several happen at once, can be dismissed with a click, and are announced to screen readers. Before this, a second message would silently overwrite the first.",
+ "link": "/dashboard",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-07-29",
"type": "update",
@@ -242,6 +284,17 @@
"fix"
]
},
+ {
+ "date": "2026-07-29",
+ "type": "update",
+ "title": "Steadier market data during upstream rate limits and outages",
+ "summary": "Market, coin, and price lookups now retry with randomized spacing rather than every request retrying in lockstep, which is what turned a brief upstream hiccup into a stampede. The in-memory caches behind those pages also keep the entries that are actually being used, instead of discarding the oldest one regardless of demand, so busy pages stay fast during a slowdown.",
+ "link": "/markets",
+ "tags": [
+ "improvement",
+ "infra"
+ ]
+ },
{
"date": "2026-07-29",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 85a95765d..e8ea96dde 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -86,6 +86,14 @@
<category>fix</category>
<description>The price chart, profile and exchange listings on a coin page all came from one provider, so whenever it throttled our requests the whole page went down at once, for hours. Each of those now has a live backup: charts fall back to exchange candles for the majors and an on-chain price oracle for every other coin, while the profile and market listings fall back to a second data provider. When a backup is answering, the page says so at the bottom instead of quietly leaving numbers blank, and columns the backup cannot fill are hidden rather than shown as a row of dashes. Two small honesty fixes came with it: a follower count of zero now means &quot;not tracked&quot; and is left out rather than stated as zero, and a price change the backup does not actually compute is no longer drawn as a flat 0.00%.</description>
</item>
+ <item>
+ <title>Command palette search now tolerates typos and ranks results properly</title>
+ <link>https://three.ws/dashboard</link>
+ <guid isPermaLink="false">2026-07-29:Command palette search now tolerates typos and ranks results properly</guid>
+ <pubDate>Wed, 29 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>The dashboard palette finds what you meant when you mistype (searching 'markteplace' now finds Marketplace) and orders results by how well they actually match, instead of lumping every loose match together at the same rank. Matched letters are highlighted at their real positions.</description>
+ </item>
<item>
<title>Concierge demo and the 3D home demo both work again</title>
<link>https://three.ws/concierge</link>
@@ -110,6 +118,14 @@
<category>fix</category>
<description>An audit of our payment facilitator found that about one in five recorded settlements shared an on-chain transaction with another settlement. Solana signatures are deterministic, so two payments of the same amount, from the same wallet, to the same endpoint, built in the same short window could compile to a byte-for-byte identical transaction. Only one of them could ever land on chain, and the facilitator was crediting the others against it. Settlement is now claimed atomically: one transaction settles at most one payment, a genuine retry is recognised and answered without double-charging, and anything else is refused rather than credited. The payment builder also draws from a signature space about four thousand times larger, at no extra fee, so identical transactions are no longer built in the first place. A new hourly audit watches the invariant and raises an alert if it is ever violated again.</description>
</item>
+ <item>
+ <title>Exported chat transcripts can no longer carry spreadsheet formulas</title>
+ <link>https://three.ws/widgets</link>
+ <guid isPermaLink="false">2026-07-29:Exported chat transcripts can no longer carry spreadsheet formulas</guid>
+ <pubDate>Wed, 29 Jul 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>When a widget owner exports their chat transcripts as a CSV, a visitor message that began with a character like = or @ could be treated as a live formula by Excel or Google Sheets when the file was opened. Exported text is now always neutralized so it opens as plain text. The audit-log export already did this; both exports now share one implementation so they cannot drift apart again.</description>
+ </item>
<item>
<title>Fact checks that used to time out now come back with their sources</title>
<link>https://three.ws/fact-check</link>
@@ -118,6 +134,14 @@
<category>fix</category>
<description>Some fact checks were taking so long that the request was cut off before anything came back, and the caller got an error instead of an answer. Two things caused it. The checker asks a language model to write search queries and then to judge each source it finds; if none of the model providers could answer, that step threw the whole check away, even though the checker had already gathered real sources and knew how to carry on without the model. And nothing kept an eye on the clock, so a slow run could outlast the time limit the request had to begin with. Both are fixed. A check now works to a time budget and hands each step whatever is left, so it always finishes with something to show. If a step genuinely cannot reach a model, the check falls back instead of failing: it searches the claim itself, returns the sources it found with their excerpts, and marks the verdict as insufficient rather than guessing. The response now says plainly which step fell back, and a result produced that way is deliberately not cached, so asking again re-runs the full check rather than replaying a bad day.</description>
</item>
+ <item>
+ <title>Hardened how agent and model text is displayed across the site</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-29:Hardened how agent and model text is displayed across the site</guid>
+ <pubDate>Wed, 29 Jul 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>Everywhere the site shows text written by an AI model or another person (agent chat replies, bounty briefs, the on-page concierge widget, saved memories, skill manifests), that text is now rendered through a single hardened pipeline that strips anything dangerous before it reaches the page. It also renders more of what you actually write: tables, nested lists, and strikethrough now display properly instead of appearing as raw symbols. Previously eight different parts of the site each interpreted this text their own way, with no shared safety net.</description>
+ </item>
<item>
<title>Notification mute switches actually work now</title>
<link>https://three.ws/dashboard/settings</link>
@@ -126,6 +150,14 @@
<category>fix</category>
<description>The per-category switches in settings let you turn the bell off for a kind of notification, but the bell ignored them and filled up anyway. They work now. One deliberate exception: account and security notices (withdrawals, payment problems, security alerts) always stay in your bell, because that is your record of what happened to your account and losing it silently would be worse than a little noise. You can still turn off their push, email and Telegram. Those always-on switches now show as locked in settings instead of pretending to be adjustable.</description>
</item>
+ <item>
+ <title>Notifications stack instead of replacing each other</title>
+ <link>https://three.ws/dashboard</link>
+ <guid isPermaLink="false">2026-07-29:Notifications stack instead of replacing each other</guid>
+ <pubDate>Wed, 29 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Confirmation messages across the dashboard now queue up and stay readable when several happen at once, can be dismissed with a click, and are announced to screen readers. Before this, a second message would silently overwrite the first.</description>
+ </item>
<item>
<title>On-chain agent pages now load their registration details reliably</title>
<link>https://three.ws/docs/erc8004</link>
@@ -182,6 +214,14 @@
<category>infra</category>
<description>The platform routes every Solana call through a chain of RPC providers so no single one becomes a bottleneck, with a paid endpoint held back as an emergency reserve. A configuration mistake had that reserve listed as the primary as well, and because the chain keeps the first entry for a repeated address, it quietly served all traffic and burned through its daily request cap while the free providers sat idle. The reserve is now held back as intended and the premium provider leads. Two safeguards prevent a repeat: the slowest public endpoint can no longer outrank a paid provider by being used as a default, and when one server discovers a provider is out of quota, the rest of the fleet now inherits that verdict immediately instead of each wasting another request against a cap that is already full.</description>
</item>
+ <item>
+ <title>Steadier market data during upstream rate limits and outages</title>
+ <link>https://three.ws/markets</link>
+ <guid isPermaLink="false">2026-07-29:Steadier market data during upstream rate limits and outages</guid>
+ <pubDate>Wed, 29 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Market, coin, and price lookups now retry with randomized spacing rather than every request retrying in lockstep, which is what turned a brief upstream hiccup into a stampede. The in-memory caches behind those pages also keep the entries that are actually being used, instead of discarding the oldest one regardless of demand, so busy pages stay fast during a slowdown.</description>
+ </item>
<item>
<title>Stopped two automated systems from passing the same SOL back and forth</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index be7d21390..ef4421d5f 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-29T06:15:54.710Z",
+ "generated_at": "2026-07-29T06:18:36.426Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/check-browser-graph.mjs b/scripts/check-browser-graph.mjs
index 23dceb0f8..cddc54d3e 100644
--- a/scripts/check-browser-graph.mjs
+++ b/scripts/check-browser-graph.mjs
@@ -66,14 +66,24 @@ function tracked(patterns) {
const IMPORT_RE =
/(?:^|\n)\s*(?:import|export)[^'"\n]*?from\s*['"]([^'"]+)['"]|(?:^|[^.\w])import\(\s*['"]([^'"]+)['"]\s*\)/g;
-/** Every specifier `file` imports, as raw strings. */
+/**
+ * Every specifier `file` imports, tagged static vs dynamic.
+ *
+ * The distinction is the whole point for built-ins. A STATIC
+ * `import { promisify } from 'node:util'` is what breaks the build: rollup
+ * swaps the module for __vite-browser-external and then rejects the named
+ * export. A DYNAMIC `await import('node:util')` is the sanctioned escape hatch
+ * — it stays an external dynamic import with no module-level named bindings to
+ * check, and it only evaluates on the server path that actually calls it. So
+ * dynamic built-in imports are deliberately NOT leaks.
+ */
function specifiersOf(file) {
let src;
try { src = readFileSync(file, 'utf8'); } catch { return []; }
const out = [];
for (const m of src.matchAll(IMPORT_RE)) {
- const spec = m[1] || m[2];
- if (spec) out.push(spec);
+ if (m[1]) out.push({ spec: m[1], dynamic: false });
+ else if (m[2]) out.push({ spec: m[2], dynamic: true });
}
return out;
}
@@ -139,10 +149,10 @@ function chainTo(file) {
while (queue.length) {
const file = queue.shift();
- for (const spec of specifiersOf(file)) {
+ for (const { spec, dynamic } of specifiersOf(file)) {
const builtin = builtinName(spec);
if (builtin) {
- if (!POLYFILLED.has(builtin)) leaks.push({ file, spec, chain: chainTo(file) });
+ if (!dynamic && !POLYFILLED.has(builtin)) leaks.push({ file, spec, chain: chainTo(file) });
continue;
}
if (!spec.startsWith('.')) continue; // bare package — the bundler's problem, not ours
diff --git a/tests/coin-fallbacks.test.js b/tests/coin-fallbacks.test.js
index 7e99e23b8..fc5f6cdf4 100644
--- a/tests/coin-fallbacks.test.js
+++ b/tests/coin-fallbacks.test.js
@@ -22,6 +22,8 @@ import {
slugify,
paprikaEntryMatches,
pickPaprikaId,
+ pricesAgree,
+ symbolCandidates,
resolvePaprikaId,
resetPaprikaIdMemo,
normalizePaprikaDetail,
@@ -29,7 +31,9 @@ import {
normalizeLlamaChart,
fetchLlamaChart,
fetchFallbackTickers,
+ fetchFallbackCoinDetail,
} from '../api/_lib/coin-fallbacks.js';
+import { isPaprikaBenched, resetPaprikaHealth } from '../api/_lib/coinpaprika.js';
const jsonResponse = (body, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
@@ -143,8 +147,90 @@ describe('CoinGecko id → CoinPaprika id', () => {
});
});
+describe('price-verified resolution (stage 2)', () => {
+ it('accepts prices within the tolerance and rejects anything wider', () => {
+ expect(pricesAgree(100, 101)).toBe(true); // 1% apart — same asset
+ expect(pricesAgree(100, 103)).toBe(false); // 3% apart — not proven
+ expect(pricesAgree(0.14591, 0.14602)).toBe(true);
+ expect(pricesAgree(0, 100)).toBe(false);
+ expect(pricesAgree(100, null)).toBe(false);
+ expect(pricesAgree(-5, -5)).toBe(false);
+ });
+
+ // A ticker is not unique: several listings share one symbol, which is exactly
+ // why a shortlist has to be ranked and then price-verified rather than
+ // trusted. Synthetic ids keep the ranking rule the subject of the test.
+ it('shortlists only same-symbol active coins, best rank first', () => {
+ const raw = {
+ currencies: [
+ { id: 'tkr-leading-listing', symbol: 'TKR', rank: 60, is_active: true },
+ { id: 'tkr-delisted', symbol: 'TKR', rank: 4000, is_active: false },
+ { id: 'oth-other-listing', symbol: 'OTH', rank: 2, is_active: true },
+ { id: 'tkr-second-listing', symbol: 'TKR', rank: 900, is_active: true },
+ { id: 'tkr-third-listing', symbol: 'TKR', rank: 3000, is_active: true },
+ ],
+ };
+ // Capped at two probes — each one spends from the hourly budget.
+ expect(symbolCandidates(raw, 'TKR')).toEqual(['tkr-leading-listing', 'tkr-second-listing']);
+ });
+
+ it('shortlists nothing when no candidate shares the symbol', () => {
+ expect(symbolCandidates({ currencies: [{ id: 'aaa-alpha', symbol: 'AAA' }] }, 'TKR')).toEqual([]);
+ expect(symbolCandidates({}, 'TKR')).toEqual([]);
+ });
+});
+
+describe('CoinPaprika budget guard', () => {
+ beforeEach(() => {
+ resetPaprikaHealth();
+ resetPaprikaIdMemo();
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ resetPaprikaHealth();
+ });
+
+ // The free tier allows 60 requests/hour and then blocks for an hour. Paying a
+ // round-trip per request to be told that is exactly the waste to avoid.
+ const budgetSpent = () =>
+ new Response(
+ JSON.stringify({ type: 'payment_required', error: 'request limits were reached' }),
+ { status: 402, headers: { 'content-type': 'application/json' } },
+ );
+
+ it('benches the source on a 402 so later calls skip it entirely', async () => {
+ const fetchMock = vi.fn(async () => budgetSpent());
+ vi.stubGlobal('fetch', fetchMock);
+ expect(await resolvePaprikaId('solana')).toBeNull();
+ expect(isPaprikaBenched()).toBe(true);
+ const afterBench = fetchMock.mock.calls.length;
+ await resolvePaprikaId('bitcoin');
+ await fetchFallbackTickers('ethereum');
+ // Not one further request is spent while blocked.
+ expect(fetchMock.mock.calls.length).toBe(afterBench);
+ });
+
+ it('detects the budget reply even when it arrives with a 200', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () =>
+ jsonResponse({ type: 'payment_required', error: 'request limits were reached' }),
+ ));
+ await resolvePaprikaId('solana');
+ expect(isPaprikaBenched()).toBe(true);
+ });
+
+ it('answers null rather than throwing when the source is unreachable', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNRESET'); }));
+ await expect(fetchFallbackCoinDetail('solana')).resolves.toBeNull();
+ await expect(fetchFallbackTickers('solana')).resolves.toBeNull();
+ expect(isPaprikaBenched()).toBe(false); // a network blip is not a spent budget
+ });
+});
+
describe('resolvePaprikaId', () => {
- beforeEach(() => resetPaprikaIdMemo());
+ beforeEach(() => {
+ resetPaprikaIdMemo();
+ resetPaprikaHealth();
+ });
afterEach(() => vi.unstubAllGlobals());
it('resolves once and memoizes, so an outage does not re-search per request', async () => {
@@ -288,41 +374,70 @@ describe('normalizePaprikaMarket', () => {
});
describe('fetchFallbackTickers', () => {
- beforeEach(() => resetPaprikaIdMemo());
+ beforeEach(() => {
+ resetPaprikaIdMemo();
+ resetPaprikaHealth();
+ });
afterEach(() => vi.unstubAllGlobals());
- const stub = (markets) =>
+ // Normalized payloads are cached per coin, so every case uses its own id —
+ // sharing one would have a later test read an earlier test's cached answer.
+ const stub = (cgId, markets) =>
vi.stubGlobal('fetch', vi.fn(async (url) => {
const u = String(url);
- if (u.includes('/search/')) return jsonResponse({ currencies: [{ id: 'sol-solana', name: 'Solana', rank: 7 }] });
+ if (u.includes('/search/')) return jsonResponse({ currencies: [{ id: `sym-${cgId}`, name: cgId, rank: 7 }] });
if (u.includes('/markets')) return jsonResponse(markets);
throw new Error(`unexpected ${u}`);
}));
it('keeps spot markets only and orders them by 24h volume', async () => {
- stub([
+ stub('spot-order-coin', [
{ ...PAPRIKA_MARKET, exchange_name: 'Small Spot', quotes: { USD: { price: 73, volume_24h: 10 } } },
{ ...PAPRIKA_MARKET, exchange_name: 'Perp Venue', category: 'Derivatives', quotes: { USD: { price: 73, volume_24h: 9_000_000 } } },
{ ...PAPRIKA_MARKET, exchange_name: 'Big Spot', quotes: { USD: { price: 73, volume_24h: 500 } } },
]);
- const rows = await fetchFallbackTickers('solana');
+ const rows = await fetchFallbackTickers('spot-order-coin');
expect(rows.map((r) => r.exchange.name)).toEqual(['Big Spot', 'Small Spot']);
});
it('paginates in 100-row pages like the endpoint it stands in for', async () => {
stub(
+ 'paging-coin',
Array.from({ length: 250 }, (_, i) => ({
...PAPRIKA_MARKET,
exchange_name: `Venue ${i}`,
quotes: { USD: { price: 73, volume_24h: 1000 - i } },
})),
);
- expect(await fetchFallbackTickers('solana', { page: 1 })).toHaveLength(100);
- const page3 = await fetchFallbackTickers('solana', { page: 3 });
+ expect(await fetchFallbackTickers('paging-coin', { page: 1 })).toHaveLength(100);
+ const page3 = await fetchFallbackTickers('paging-coin', { page: 3 });
expect(page3).toHaveLength(50);
expect(page3[0].exchange.name).toBe('Venue 200');
});
+ it('serves later pages from cache — paging must not spend more budget', async () => {
+ stub(
+ 'budget-paging-coin',
+ Array.from({ length: 250 }, (_, i) => ({
+ ...PAPRIKA_MARKET,
+ exchange_name: `Venue ${i}`,
+ quotes: { USD: { price: 73, volume_24h: 1000 - i } },
+ })),
+ );
+ await fetchFallbackTickers('budget-paging-coin', { page: 1 });
+ const spent = globalThis.fetch.mock.calls.length;
+ await fetchFallbackTickers('budget-paging-coin', { page: 2 });
+ await fetchFallbackTickers('budget-paging-coin', { page: 3 });
+ expect(globalThis.fetch.mock.calls.length).toBe(spent);
+ });
+
+ it('collapses a concurrent burst into a single upstream fetch', async () => {
+ stub('burst-coin', [PAPRIKA_MARKET]);
+ await Promise.all(Array.from({ length: 8 }, () => fetchFallbackTickers('burst-coin')));
+ // search + markets, once — not eight times.
+ expect(globalThis.fetch.mock.calls.length).toBe(2);
+ });
+
it('returns null when CoinPaprika does not list the coin', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ currencies: [] })));
expect(await fetchFallbackTickers('not-a-real-coin')).toBeNull();