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(defi): share one upstream fetch across concurrent DeFi market requests
nirholascd9170e99064
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2b3422aa5..2f6516d61 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,10 +13,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Every agent persona is now a signed, IPFS-pinned manifest anyone can verify**: Saving an agent's persona now compiles its full configuration (system prompt, voice, body, skills, on-chain identity) into a canonical manifest, signs it with the platform's ed25519 attester identity, and pins the signed envelope to IPFS. The CID lands on the agent record, so the prompt an agent actually runs is no longer a claim you have to trust: it is a document anyone can fetch from a public gateway and check. A new public endpoint, /api/manifest-verify, verifies the signature against the platform's signing key and diffs the pinned manifest against the agent's live configuration, naming every field that moved since the pin. The standalone verifier script does the same from the command line with nothing but the CID, so buyers of a forked agent can prove what behavior they are getting without asking three.ws for anything. The wire format is specified in the Agent Manifest spec's signed-envelope section. (`/agent/4c0e4d18-0544-4c95-a0db-a16896b029be`) `[feature, security]`- **Run your own inference node: the open inference network operator client is here**: Phase 4 of the roadmap (decouple agent inference from any single provider) takes its first concrete step: anyone can now run a node. The new node-operator client is a self-contained daemon that registers with the platform, claims inference jobs, executes them with a real open model (distilgpt2 via ONNX, CPU by default with a one-flag GPU image), and returns every result signed with the node's own Solana key so anyone can verify it. The proof runs end to end locally: register, claim a job, and return a cryptographically verified result, with a built-in selftest that proves the whole loop on a fresh checkout. Operators bring their own hardware; the network supplies the jobs and the on-chain receipts. This is the first piece of the bet that agent inference settles permissionlessly, closer to how blockchains settle blocks than to how today's AI APIs settle bills. (`/docs/inference-node-operator`) `[feature, infra]`- **Seed your agent's memory from your X account, with your explicit consent**: Your agent can now learn how you write from your own X account, and only after you say yes. Connect X in Settings, and the consent screen tells you exactly what is read (your profile and up to 100 of your recent original public posts), what is stored (a handful of short distilled facts about what you talk about and how you talk, never your posts themselves and never links), and what is never touched (messages, likes, bookmarks, your follower list, your credentials). Agree and the agent's next replies already speak from those facts; change your mind and revoking, or disconnecting X, deletes every memory the seed created. (`/docs/x-memory-seeding`) `[feature]`+- **The DeFi market pages stop hammering their data source when they get busy**: The /defi, /chains, /yields, /stablecoins, /fees, /dex-volumes and /hacks pages, plus the protocol, chain and stablecoin detail pages, all read live data from DeFiLlama and hold it in memory for a few minutes. The moment that held copy expired, every request that arrived at once went and fetched its own fresh copy instead of sharing one. Ten simultaneous visitors to the DEX volume board meant ten downloads of the same two megabytes, and the protocol leaderboard's feed is closer to eight. That burst lands precisely when the page is busiest, and when the source pushed back, the page showed an error even though the data behind it was perfectly good. Now the first request through fetches, and everyone else waiting shares that one result. A chain profile also reuses a single copy of the protocol list rather than pulling it again for every chain. If a fetch does fail, the failure is no longer held on to, so the next visitor gets a real retry instead of the same error for the rest of the window. One cosmetic fix rode along: a pool whose name is missing on /yields now reads "Unknown" instead of a bare dash. (`/defi`) `[fix, improvement]`- **The Forge can now federate GPU work to the Livepeer decentralized compute network**: Text-to-3D jobs start by painting a reference image, and that GPU step can now run on the Livepeer network instead of our own lanes, behind a flag, with the same request shape and the same verification our own workers get (safety screening plus byte-level image checks before anything is stored). It ships dark: our measured probe found Livepeer's free public gateway dead at the DNS edge, so the lane goes live only after a funded Studio key lands and clears a 20-job latency, cost, and success comparison run by the new bench script. The full record and the expansion criteria are in the operator docs. `[feature, infra]`- **The free trending and whale feeds stop going blank under their own traffic**: Ask the trending feed for the 5-minute, 1-hour and 24-hour view back to back and the last two used to come back empty, blaming an upstream outage that was not happening. The cause was our own request volume: each call pulled the trade history of twenty pump.fun coins, and three calls in a row hit pump.fun's rate limiter, which then refused everything for a while. Both feeds now read pump.fun through one shared, short-lived cache, so every window and every caller reuses a single set of pulls instead of re-fetching the same coins, and a repeat call answers in milliseconds. When the limiter does bite, the whale feed serves the last successful pull and marks it stale instead of pretending the market is empty. A token nobody is trading now also reports an honest empty result rather than a false feed-down warning. (`/docs/crypto-api`) `[fix, improvement]`- **The photo-to-avatar lane is now sized for the 10,000 avatars per day launch target**: The service that turns your selfies into a rigged 3D avatar was measured under real load and one number mattered: it was configured so the autoscaler could never see how busy it was. The service answers each request in milliseconds and does the real work in the background, so the scaling signal looked idle while its processors ground away, and no amount of extra quota would ever have added capacity. The configuration is fixed, and the lane then proved the roadmap's launch target for real: a sustained ten-minute run at the full 10,000-avatars-per-day rate finished every job, with the typical avatar ready in about six seconds and the slowest in under nine. The capacity is there when launch day brings the crowd. `[improvement, infra]`- **The public custody anchor lookup answers a bad epoch instead of erroring out**: Anyone can look up the on-chain anchor for a Proof-of-Custody epoch at /api/custody/anchor. Ask it for an epoch number too large to be a real round and it used to fail with an internal server error, which reads like the custody service is down rather than like a typo in the request. It now answers a plain "that is not a valid epoch" for malformed input, keeps 404 for an epoch that has not happened yet, and reads the newest epoch with a single lookup instead of pulling the whole integrity aggregate it then threw away. (`/integrity`) `[fix, improvement]`+- **Token holder and safety checks stop failing when the free data lanes are busy**: The free crypto API's holder distribution read (/api/crypto/holders) and the holder half of its token safety check (/api/crypto/security) both ask the Solana network for a token's largest accounts. Most of the public nodes we fall back on either refuse that question, answer it with an internal error, or accept it and never reply, and the router treated the last two as real answers, so the call gave up instead of trying the next node. It now moves on from an internal error, charges a silent no-reply to that one question rather than benching an otherwise healthy node, and has one more free node in the rotation that answers it. In a live check the holder read went from succeeding on roughly one call in three to eight out of eight. The error messages across the free crypto endpoints were reworded to match the rest of the platform's plain style at the same time. (`/docs/crypto-api`) `[fix, infra]`- **Your agent can now learn your Farcaster voice, and only after you prove the account is yours**: Memory seeding already worked from GitHub and X; Farcaster now joins them, with consent built into the protocol itself. Farcaster has no login button we could use, so instead the account's own public record does the work: every Farcaster account publishes the wallets it controls, and you prove ownership by signing a one-time challenge with one of those wallets, Solana first. Nothing is read, let alone stored, before that signature checks out. The grant is read-only and narrow: your public profile and up to 100 recent casts, distilled into identity, facts, and your strongest posts, so the agent talks the way you talk. Changing your mind is one click: revoking the grant deletes every memory it produced, including anything an earlier grant left behind. The whole flow lives in the agent persona editor, and it works with no API key configured because the reader falls back to a public Farcaster hub. (`/docs/farcaster-memory-seeding`) `[feature, security]`## 2026-08-11diff --git a/api/defi/README.md b/api/defi/README.mdindex 0665dc7fa..7d627710b 100644--- a/api/defi/README.md+++ b/api/defi/README.md@@ -6,7 +6,7 @@ Why this layer exists instead of calling DeFiLlama from the browser:- **Payload shaping.** The raw upstream feeds are enormous (the yields `/pools` feed alone is a multi-MB dump of ~15k pools; a protocol profile carries 2k+ daily TVL points). Every handler returns only the fields its page renders, downsamples chart series server-side, and coerces non-finite numbers to `null` (never NaN in the UI).- **Data hygiene.** DeFiLlama mixes centralized-exchange custody rows (category "CEX") into `/protocols`; the TVL leaderboard excludes them so Binance/OKX reserves never dwarf actual protocols. Synthetic per-chain TVL keys (`-borrowed`, `-staking`, `-pool2`, `-vesting`) are stripped from chain breakdowns so nothing double-counts. APY sorting enforces a $10k TVL floor so dust pools advertising five-digit APYs on three digits of liquidity never outrank real venues.-- **Caching and dedup.** In-memory caches (5 to 10 min per feed, bounded maps for per-slug/per-id lookups), in-flight request dedup on the heavy yields fetch, and CDN `s-maxage` with `stale-while-revalidate` keep upstream load at a handful of requests per instance per TTL regardless of traffic.+- **Caching and dedup.** Every feed is read through [`api/_lib/mem-cache.js`](../_lib/mem-cache.js): an LRU cache with a per-entry TTL (5 to 10 min per feed) and **single-flight de-duplication**, so concurrent misses on the same key share one upstream call instead of stampeding it. That last part is load-bearing here, not a micro-optimization: the feeds run from ~2 MB (dexs) to ~8 MB (protocols), and before it was applied uniformly, 10 concurrent cold requests to `/api/defi/dex-volumes` issued 10 identical upstream fetches. A burst like that arrives exactly when an entry expires under load, which is when the upstream is least willing to absorb it, and a refused burst reaches users as a 502 on a page whose data is fine. Per-slug and per-id lookups (`protocol`, `stablecoin`, `chain`) are LRU-bounded, so a crawl across many keys evicts the coldest entry rather than clearing every warm one. A failed load is never cached, so a transient outage cannot pin an endpoint for a whole TTL. `chain.js` additionally shares one copy of the protocols feed across every chain profile built in its TTL. On top of that, CDN `s-maxage` with `stale-while-revalidate` keeps upstream load at a handful of requests per instance per TTL regardless of traffic.- **One implementation for free and paid.** The exported builder functions below are reused verbatim by the paid x402 Market Data API ([`api/_lib/market-data/fetch.js`](../_lib/market-data/fetch.js)), so the data agents pay for can never drift from what the site shows.All endpoints are `GET`, CORS-open, and rate-limited per client IP via [`../_lib/rate-limit.js`](../_lib/rate-limit.js) (the shared `marketDataIp` limiter). Errors follow the platform shape from [`../_lib/http.js`](../_lib/http.js); upstream failures return `502 upstream_error`, never synthetic numbers.diff --git a/api/defi/chain.js b/api/defi/chain.jsindex 5ad24297e..f582461b9 100644--- a/api/defi/chain.js+++ b/api/defi/chain.js@@ -1,6 +1,6 @@// GET /api/defi/chain?name=<chain>// ----------------------------------------------------------------------------// Rich profile for one blockchain — powers the /chain/:name detail page.+// Rich profile for one blockchain. Powers the /chain/:name detail page.// Fans out across DeFiLlama's keyless feeds (no API key) and stitches them into// a single payload the page renders:// · /v2/chains → this chain's TVL, native token, chainId,@@ -15,10 +15,10 @@// Only the /v2/chains lookup is load-bearing (it resolves the canonical name and// the headline stats); every other feed is best-effort via Promise.allSettled,// so a chain that has no DEX/stablecoin/fees coverage still renders. DeFiLlama-// chain names are case-sensitive ("Ethereum", not "ethereum") — the request name+// chain names are case-sensitive ("Ethereum", not "ethereum"). The request name// is matched case-insensitively against /v2/chains and everything downstream uses// the canonical casing. Cached ~5 min in-memory per chain + CDN. DeFiLlama is the-// data source — see the page's attribution line.+// data source. See the page's attribution line.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -168,7 +168,7 @@ function shapeDex(raw) {const total24h = finite(Number(raw.total24h));const total7d = finite(Number(raw.total7d));// A chain listed on the DEX overview but with no activity returns total24h:- // null — nothing to show, so collapse to null and let the page hide the card.+ // null, nothing to show, so collapse to null and let the page hide the card.if (total24h == null && total7d == null) return null;const chart = Array.isArray(raw.totalDataChart) ? raw.totalDataChart : [];const series = [];@@ -264,7 +264,7 @@ export default wrap(async (req, res) => {res,400,'bad_name',- 'name must be a blockchain name (1–40 chars: letters, digits, spaces, or . _ -)',+ 'name must be a blockchain name (1 to 40 chars: letters, digits, spaces, or . _ -)',);}@@ -276,7 +276,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'Chain data is unavailable right now — retry shortly',+ 'Chain data is unavailable right now. Retry shortly',);}@@ -295,7 +295,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'Chain data is unavailable right now — retry shortly',+ 'Chain data is unavailable right now. Retry shortly',);}});diff --git a/api/defi/chains.js b/api/defi/chains.jsindex ffafdfd97..0cd77ac7c 100644--- a/api/defi/chains.js+++ b/api/defi/chains.js@@ -4,7 +4,7 @@// /v2/chains feed (no API key), normalizes each chain to name + TVL + native// token, computes each chain's share of total TVL, and returns the top 100 by// TVL plus the whole-market total. Cached 5 min in-memory + CDN. DeFiLlama is-// the data source — see the page's attribution line.+// the data source. See the page's attribution line.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -81,7 +81,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'Cross-chain TVL data is unavailable right now — retry shortly',+ 'Cross-chain TVL data is unavailable right now. Retry shortly',);}});diff --git a/api/defi/dex-volumes.js b/api/defi/dex-volumes.jsindex 8a769f847..ceacac064 100644--- a/api/defi/dex-volumes.js+++ b/api/defi/dex-volumes.js@@ -7,7 +7,7 @@// `share_pct` is its slice of the whole-market summed 24h volume, and its `slug`// resolves at api.llama.fi/protocol/{slug} (verified) so the page can deep-link// to a protocol detail page. Cached 10 min in-memory + CDN. DeFiLlama is the-// data source — see the page's attribution line.+// data source. See the page's attribution line.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -57,7 +57,7 @@ async function loadDexVolumes() {const eligible = raw.protocols.filter((p) => Number.isFinite(Number(p?.total24h)));// Denominator for `share_pct` spans every DEX with a positive 24h volume, not- // just the top 100 we return — so a DEX's share reflects the whole market.+ // just the top 100 we return, so a DEX's share reflects the whole market.let marketTotal24h = 0;for (const p of eligible) {const v = Number(p.total24h);@@ -72,7 +72,7 @@ async function loadDexVolumes() {return {name: typeof p.displayName === 'string' && p.displayName ? p.displayName: typeof p.name === 'string' ? p.name : 'Unknown',- // `slug` is DeFiLlama's canonical protocol key — it resolves at+ // `slug` is DeFiLlama's canonical protocol key. It resolves at// /protocol/{slug} (verified against uniswap-v3 and peers).slug: typeof p.slug === 'string' && p.slug ? p.slug : null,logo: typeof p.logo === 'string' ? p.logo : null,@@ -111,7 +111,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'DEX volume data is unavailable right now — retry shortly',+ 'DEX volume data is unavailable right now. Retry shortly',);}});diff --git a/api/defi/fees.js b/api/defi/fees.jsindex 03c748fe7..6855a9024 100644--- a/api/defi/fees.js+++ b/api/defi/fees.js@@ -2,13 +2,13 @@// ---------------------------------------------------------------------------// Protocol fees & revenue for the /fees page. Fetches DeFiLlama's keyless// /overview/fees dimension feed (no API key). `type=fees` (default) pulls the-// dailyFees series — the total users pay to use a protocol — and `type=revenue`-// pulls dailyRevenue — the slice the protocol itself keeps. Returns whole-market+// dailyFees series (the total users pay to use a protocol) and `type=revenue`+// pulls dailyRevenue, the slice the protocol itself keeps. Returns whole-market// 24h/7d/30d totals, the aggregate daily chart (downsampled to ≤200 points), and// the top 100 protocols by 24h. Each protocol's `slug` resolves at// api.llama.fi/protocol/{slug} (verified) so the page can deep-link to a// protocol detail page. Cached 10 min in-memory + CDN. DeFiLlama is the data-// source — see the page's attribution line.+// source. See the page's attribution line.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -71,7 +71,7 @@ async function loadFees(type) {return {name: typeof p.displayName === 'string' && p.displayName ? p.displayName: typeof p.name === 'string' ? p.name : 'Unknown',- // `slug` is DeFiLlama's canonical protocol key — it resolves at+ // `slug` is DeFiLlama's canonical protocol key. It resolves at// /protocol/{slug} (verified against tether / circle-usdc / uniswap-v3).slug: typeof p.slug === 'string' && p.slug ? p.slug : null,logo: typeof p.logo === 'string' ? p.logo : null,@@ -118,7 +118,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'Protocol fee data is unavailable right now — retry shortly',+ 'Protocol fee data is unavailable right now. Retry shortly',);}});diff --git a/api/defi/hacks.js b/api/defi/hacks.jsindex 77f8c26cc..a28c5d4ec 100644--- a/api/defi/hacks.js+++ b/api/defi/hacks.js@@ -5,10 +5,10 @@// renders, computes whole-dataset headline stats, then applies an optional// case-insensitive search over name+technique+classification and paginates.// The raw upstream is cached ~10 min in-memory + CDN. DeFiLlama's hacks-// database is the data source — see the page's attribution line.+// database is the data source. See the page's attribution line.//// Amount unit: DeFiLlama reports `amount` in raw USD (verified at build time-// against incidents of known magnitude — the largest bridge exploits land at+// against incidents of known magnitude, the largest bridge exploits land at// hundreds of millions to billions, matching their public post-mortems), so no// scaling is applied. `returnedFunds` uses the same unit. `chain` is an array// of chain names (or null); it is normalized to an array.@@ -37,7 +37,7 @@ function normalizeChains(chain) {}// Fetch + normalize the whole upstream feed once, cache it. Returns the full-// sorted, normalized incident list plus the dataset-wide headline stats — the+// sorted, normalized incident list plus the dataset-wide headline stats. The// per-request search/pagination happens on top of this cached whole.async function loadDataset() {return cached(_cache, CACHE_KEY, buildDataset);@@ -114,7 +114,7 @@ function clampInt(raw, fallback, min, max) {return Math.min(max, Math.max(min, n));}-// Exported for the paid Market Data API (api/_lib/market-data/) — the x402+// Exported for the paid Market Data API (api/_lib/market-data/), the x402// market-hacks endpoint sells the same exploit database this page renders.export async function queryHacks({ search = '', limit = DEFAULT_LIMIT, offset = 0 } = {}) {const dataset = await loadDataset();@@ -172,7 +172,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'DeFi hacks data is unavailable right now — retry shortly',+ 'DeFi hacks data is unavailable right now. Retry shortly',);}});diff --git a/api/defi/protocol.js b/api/defi/protocol.jsindex ec3fd0c1a..6c261ddd1 100644--- a/api/defi/protocol.js+++ b/api/defi/protocol.js@@ -1,19 +1,19 @@// GET /api/defi/protocol?slug=<slug>// ----------------------------------------------------------------------------// Rich profile for one DeFi protocol — powers the /protocol/:slug detail page.+// Rich profile for one DeFi protocol. Powers the /protocol/:slug detail page.// Proxies DeFiLlama's keyless endpoints (no API key) and slims the multi-MB// upstream payload to exactly what the page renders:-// · /protocol/{slug} (required) — TVL history, per-chain TVL, raises,-// hallmarks, mcap, metadata-// · /summary/fees/{slug} (optional) — 24h/7d/30d/all-time fees + revenue-// (dailyFees + dailyRevenue passes)-// · /summary/dexs/{slug} (optional) — DEX trading volume+// · /protocol/{slug} (required): TVL history, per-chain TVL, raises,+// hallmarks, mcap, metadata+// · /summary/fees/{slug} (optional): 24h/7d/30d/all-time fees + revenue+// (dailyFees + dailyRevenue passes)+// · /summary/dexs/{slug} (optional): DEX trading volume// The fees/dexs summaries also carry richer metadata (category, audits,// methodology, forkedFrom, parentProtocol) than the bare /protocol payload for// aggregator ("parent") protocols, so missing metadata is enriched from them.// The full daily TVL history (often 2k+ points) is downsampled server-side to// ≤400 points so the SVG chart stays light. Cached 5 min in-memory per slug +-// CDN. DeFiLlama is the data source — see the page's attribution line.+// CDN. DeFiLlama is the data source. See the page's attribution line.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -40,10 +40,10 @@ const num = (v) => {const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);const httpUrl = (v) => (typeof v === 'string' && /^https?:\/\//.test(v.trim()) ? v.trim() : null);-// Synthetic per-chain suffixes DeFiLlama appends to `currentChainTvls` — these+// Synthetic per-chain suffixes DeFiLlama appends to `currentChainTvls`. These// are not real TVL a chain holds (they double-count borrowed collateral, staked// governance tokens, LP-side liquidity, or locked vesting), so a "TVL by chain"-// view must exclude them or every chain appears 2–3× with inflated numbers.+// view must exclude them or every chain appears 2 to 3 times with inflated numbers.const SYNTH_SUFFIX = /-(borrowed|staking|pool2|vesting)$/i;// …and the whole-protocol aggregates of those same categories.const AGGREGATE_KEYS = new Set(['borrowed', 'staking', 'pool2', 'vesting']);@@ -61,7 +61,7 @@ async function fetchJson(url) {return resp.json();}-// Optional upstream — a 4xx (many protocols have no fees/dexs feed) or any other+// Optional upstream: a 4xx (many protocols have no fees/dexs feed) or any other// failure collapses to null so the section is simply hidden, never an error.async function fetchOptional(url) {try {@@ -251,7 +251,7 @@ export default wrap(async (req, res) => {const params = new URL(req.url, 'http://x').searchParams;const slug = (params.get('slug') || '').trim().toLowerCase();if (!SLUG_RE.test(slug)) {- return error(res, 400, 'bad_slug', 'slug must be a DeFiLlama protocol slug (1–80 chars: letters, digits, . or -)');+ return error(res, 400, 'bad_slug', 'slug must be a DeFiLlama protocol slug (1 to 80 chars: letters, digits, . or -)');}try {@@ -261,10 +261,10 @@ export default wrap(async (req, res) => {});} catch (err) {// DeFiLlama answers an unknown slug with 400 "Protocol not found" (and 404- // for some paths) — both mean "no such protocol" to the client.+ // for some paths), and both mean "no such protocol" to the client.if (err?.status === 404 || err?.status === 400) {return error(res, 404, 'not_found', `no DeFi protocol found for "${slug}"`);}- return error(res, 502, 'upstream_error', 'DeFi protocol data is unavailable right now — retry shortly');+ return error(res, 502, 'upstream_error', 'DeFi protocol data is unavailable right now. Retry shortly');}});diff --git a/api/defi/protocols.js b/api/defi/protocols.jsindex d8927414b..a6575fb79 100644--- a/api/defi/protocols.js+++ b/api/defi/protocols.js@@ -3,7 +3,7 @@// Top DeFi protocols by TVL for the /defi page. Fetches DeFiLlama's keyless// /protocols feed (no API key), normalizes each entry to the fields the page// renders, and returns the top 100 by TVL plus whole-market totals. Cached-// 5 min in-memory + CDN. DeFiLlama is the data source — see the page's+// 5 min in-memory + CDN. DeFiLlama is the data source. See the page's// attribution line.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';@@ -61,7 +61,7 @@ async function loadProtocols() {const protocols = eligible.slice(0, 100).map((p) => {const chains = Array.isArray(p.chains) ? p.chains.filter((c) => typeof c === 'string') : [];return {- // DeFiLlama protocol slug — the /protocol/:slug detail page keys off it.+ // DeFiLlama protocol slug. The /protocol/:slug detail page keys off it.slug: typeof p.slug === 'string' ? p.slug : null,name: typeof p.name === 'string' ? p.name : 'Unknown',logo: typeof p.logo === 'string' ? p.logo : null,@@ -101,7 +101,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'DeFi protocol data is unavailable right now — retry shortly',+ 'DeFi protocol data is unavailable right now. Retry shortly',);}});diff --git a/api/defi/stablecoin.js b/api/defi/stablecoin.jsindex 3e00155c1..af2e2914e 100644--- a/api/defi/stablecoin.js+++ b/api/defi/stablecoin.js@@ -1,6 +1,6 @@// GET /api/defi/stablecoin?id=<n>// ----------------------------------------------------------------------------// Rich profile for ONE stablecoin — powers the /stablecoin/:id detail page.+// Rich profile for ONE stablecoin. Powers the /stablecoin/:id detail page.// Proxies the free, keyless DeFiLlama per-coin endpoint// (https://stablecoins.llama.fi/stablecoin/{id}) and reshapes its firehose into// a lean payload: identity + peg metadata, current per-chain circulation with@@ -8,7 +8,7 @@// circulating history of the top chains. Circulating is denominated in the// asset's own peg unit (the on-chain market cap). A USD-family asset's price is// turned into a peg-deviation figure so the page can grade peg health. Cached-// 5m in-memory keyed by id + CDN s-maxage — the source refreshes on the order of+// 5m in-memory keyed by id + CDN s-maxage. The source refreshes on the order of// minutes, not seconds. Mirrors api/defi/stablecoins.js (list) and the// api/coin/exchange.js detail-handler pattern.@@ -52,7 +52,7 @@ function pegDisplay(pegType) {return pegType.startsWith('pegged') ? pegType.slice(6) : pegType;}-// DeFiLlama's source data carries a persistent typo — "crytpo-backed" — for a+// DeFiLlama's source data carries a persistent typo ("crytpo-backed") for a// slice of assets. Normalize it so the page's fiat/crypto/algorithmic grouping// never sees two spellings of the same mechanism.function normalizeMechanism(m) {@@ -140,8 +140,8 @@ function shape(raw, id) {const pegType = str(raw.pegType);const price = num(raw.price);// Peg deviation is only meaningful for USD-family assets, whose peg unit is- // $1.00. A EUR/GBP/etc. price is quoted in USD (~1.08, ~1.27) — comparing it- // to 1.0 would be nonsense — so it stays null for non-USD pegs.+ // $1.00. A EUR/GBP/etc. price is quoted in USD (~1.08, ~1.27), and comparing it+ // to 1.0 would be nonsense, so it stays null for non-USD pegs.const pegDeviationPct =pegType === 'peggedUSD' && price != null ? (price - 1) * 100 : null;@@ -201,7 +201,7 @@ export default wrap(async (req, res) => {const id = (new URL(req.url, 'http://x').searchParams.get('id') || '').trim();if (!ID_RE.test(id)) {- return error(res, 400, 'bad_id', 'id must be a DeFiLlama stablecoin id (1–6 digits)');+ return error(res, 400, 'bad_id', 'id must be a DeFiLlama stablecoin id (1 to 6 digits)');}try {@@ -217,7 +217,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'stablecoin data is unavailable right now — retry shortly',+ 'stablecoin data is unavailable right now. Retry shortly',);}});diff --git a/api/defi/stablecoins.js b/api/defi/stablecoins.jsindex 986b628b8..b4d752bb0 100644--- a/api/defi/stablecoins.js+++ b/api/defi/stablecoins.js@@ -6,7 +6,7 @@// its on-chain market cap. We surface price (for peg-health), peg mechanism,// and the chains it lives on. Aggregate market cap sums every finite asset,// then the list is sorted by size and capped at the top 100. Cached 5m-// in-memory + CDN — the source refreshes on the order of minutes, not seconds.+// in-memory + CDN. The source refreshes on the order of minutes, not seconds.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -42,7 +42,7 @@ function shape(assets) {const chains = Array.isArray(a.chains) ? a.chains.filter((c) => typeof c === 'string') : [];rows.push({- // DeFiLlama's numeric asset id ("1", "2", …) — the /stablecoin/:id+ // DeFiLlama's numeric asset id ("1", "2", …). The /stablecoin/:id// detail page keys off it; null when upstream omits it.id: a.id != null ? String(a.id) : null,name: typeof a.name === 'string' ? a.name : 'Unknown',@@ -103,7 +103,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'stablecoin data is unavailable right now — retry shortly',+ 'stablecoin data is unavailable right now. Retry shortly',);}});diff --git a/api/defi/yields.js b/api/defi/yields.jsindex 2aeda3a39..1b8bd063e 100644--- a/api/defi/yields.js+++ b/api/defi/yields.js@@ -1,8 +1,8 @@-// GET /api/defi/yields — DeFi yield pools for the /yields explorer.+// GET /api/defi/yields: DeFi yield pools for the /yields explorer.// ---------------------------------------------------------------------------// Two modes over DeFiLlama's keyless yields API (yields.llama.fi)://-// List — GET /api/defi/yields?chain=&project=&stablecoin=&search=&minTvl=+// List: GET /api/defi/yields?chain=&project=&stablecoin=&search=&minTvl=// &sort=tvl|apy&limit=&offset=// Fetches /pools (a multi-MB payload of ~15k pools), slims each pool// to the fields the page renders, caches the slimmed set in-memory@@ -10,11 +10,11 @@// also carries filter-agnostic facets (top chains + projects by pool// TVL) for the page's dropdowns and whole-dataset stats.//-// Chart — GET /api/defi/yields?pool=<uuid>+// Chart: GET /api/defi/yields?pool=<uuid>// Fetches /chart/{pool} (per-pool APY + TVL history) and downsamples// it to ≤300 points. Unknown pools 404 rather than 502.//-// DeFiLlama is the data source — see the page's attribution line.+// DeFiLlama is the data source. See the page's attribution line.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -78,7 +78,7 @@ function median(sorted) {}// Top-N (chain|project) facets by summed pool TVL, with pool counts, over the-// FULL dataset — the dropdowns must offer every major venue regardless of the+// FULL dataset. The dropdowns must offer every major venue regardless of the// caller's current filters.function buildFacets(pools, key, topN) {const agg = new Map(); // name → { tvl, count }@@ -159,7 +159,7 @@ function clampInt(v, { def, min, max }) {return Math.max(min, Math.min(max, n));}-// Exported for the paid Market Data API (api/_lib/market-data/) — the x402+// Exported for the paid Market Data API (api/_lib/market-data/), the x402// market-yields endpoint sells the same filtered pool explorer this page renders.export async function queryYieldPools({chain = '',@@ -189,7 +189,7 @@ export async function queryYieldPools({.filter((p) => p.tvl_usd >= APY_MIN_TVL && p.apy != null).sort((a, b) => b.apy - a.apy);}- // sort === 'tvl' needs no work — the cache is already TVL desc.+ // sort === 'tvl' needs no work, the cache is already TVL desc.return {pools: rows.slice(offset, offset + limit),@@ -221,7 +221,11 @@ async function listMode(req, res, params) {// ── Chart mode ──────────────────────────────────────────────────────────────-const _charts = new Map(); // pool uuid → { value, expiresAt }+// Per-pool chart cache, LRU-bounded so browsing many pools evicts the coldest+// entry, with single-flight de-dup on concurrent misses for the same pool. A+// pool with no history caches its `null` too, so a uuid that upstream does not+// know is answered from memory instead of re-asking on every request.+const _charts = createCache({ max: CHART_CACHE_MAX, ttlMs: CHART_TTL_MS });// Even stride over the series, always keeping the last point (the chart cares// most about where the line ends).@@ -234,40 +238,33 @@ function downsample(points, max) {}async function loadChart(pool) {- const now = Date.now();- const hit = _charts.get(pool);- if (hit && hit.expiresAt > now) return hit.value;+ return cached(_charts, pool, async () => {+ const now = Date.now();- const resp = await fetch(`${CHART_UPSTREAM}${pool}`, {- headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },- signal: AbortSignal.timeout(15_000),- });- // DeFiLlama answers an unknown pool id with a non-200 or an empty data set;- // both mean "no history for this pool", not an outage.- if (resp.status === 404 || resp.status === 400) return null;- if (!resp.ok) throw new Error(`llama chart ${resp.status}`);- const raw = await resp.json();- if (!Array.isArray(raw?.data)) throw new Error('unexpected upstream shape');-- const points = [];- for (const d of raw.data) {- const t = Date.parse(d?.timestamp);- if (!Number.isFinite(t)) continue;- points.push({ t, apy: finite(Number(d.apy)), tvl_usd: finite(Number(d.tvlUsd)) });- }- if (!points.length) return null;+ const resp = await fetch(`${CHART_UPSTREAM}${pool}`, {+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(15_000),+ });+ // DeFiLlama answers an unknown pool id with a non-200 or an empty data set;+ // both mean "no history for this pool", not an outage.+ if (resp.status === 404 || resp.status === 400) return null;+ if (!resp.ok) throw new Error(`llama chart ${resp.status}`);+ const raw = await resp.json();+ if (!Array.isArray(raw?.data)) throw new Error('unexpected upstream shape');- const value = { pool, points: downsample(points, CHART_MAX_POINTS), updated_at: now };- if (_charts.size >= CHART_CACHE_MAX) {- // Drop the stalest entry so a browse across many pools stays bounded.- const oldest = [..._charts.entries()].sort((a, b) => a[1].expiresAt - b[1].expiresAt)[0];- if (oldest) _charts.delete(oldest[0]);- }- _charts.set(pool, { value, expiresAt: now + CHART_TTL_MS });- return value;+ const points = [];+ for (const d of raw.data) {+ const t = Date.parse(d?.timestamp);+ if (!Number.isFinite(t)) continue;+ points.push({ t, apy: finite(Number(d.apy)), tvl_usd: finite(Number(d.tvlUsd)) });+ }+ if (!points.length) return null;++ return { pool, points: downsample(points, CHART_MAX_POINTS), updated_at: now };+ });}-// Exported for the paid Market Data API — validates + loads a single pool's+// Exported for the paid Market Data API, validates + loads a single pool's// APY/TVL history; throws {status, code} instead of writing to a response.export async function queryYieldChart(pool) {if (!UUID_RE.test(pool || '')) {@@ -322,7 +319,7 @@ export default wrap(async (req, res) => {res,502,'upstream_error',- 'DeFi yield data is unavailable right now — retry shortly',+ 'DeFi yield data is unavailable right now. Retry shortly',);}});diff --git a/prompts/swarm-100/api-defi-01.md b/prompts/swarm-100/api-defi-01.mddeleted file mode 100644index bd9baaf08..000000000--- a/prompts/swarm-100/api-defi-01.md+++ /dev/null@@ -1,110 +0,0 @@-# API audit: api/defi batch 01 (10 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/defi/chain.js-- api/defi/chains.js-- api/defi/dex-volumes.js-- api/defi/fees.js-- api/defi/hacks.js-- api/defi/protocol.js-- api/defi/protocols.js-- api/defi/stablecoin.js-- api/defi/stablecoins.js-- api/defi/yields.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-defi-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/public/changelog.json b/public/changelog.jsonindex ae32dba0e..771bb4a10 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-12T20:41:12.178Z",+ "generated_at": "2026-08-12T20:49:10.329Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -79,6 +79,17 @@"feature"]},+ {+ "date": "2026-08-12",+ "type": "update",+ "title": "The DeFi market pages stop hammering their data source when they get busy",+ "summary": "The /defi, /chains, /yields, /stablecoins, /fees, /dex-volumes and /hacks pages, plus the protocol, chain and stablecoin detail pages, all read live data from DeFiLlama and hold it in memory for a few minutes. The moment that held copy expired, every request that arrived at once went and fetched its own fresh copy instead of sharing one. Ten simultaneous visitors to the DEX volume board meant ten downloads of the same two megabytes, and the protocol leaderboard's feed is closer to eight. That burst lands precisely when the page is busiest, and when the source pushed back, the page showed an error even though the data behind it was perfectly good. Now the first request through fetches, and everyone else waiting shares that one result. A chain profile also reuses a single copy of the protocol list rather than pulling it again for every chain. If a fetch does fail, the failure is no longer held on to, so the next visitor gets a real retry instead of the same error for the rest of the window. One cosmetic fix rode along: a pool whose name is missing on /yields now reads \"Unknown\" instead of a bare dash.",+ "link": "/defi",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-08-12","type": "update",@@ -123,6 +134,17 @@"improvement"]},+ {+ "date": "2026-08-12",+ "type": "update",+ "title": "Token holder and safety checks stop failing when the free data lanes are busy",+ "summary": "The free crypto API's holder distribution read (/api/crypto/holders) and the holder half of its token safety check (/api/crypto/security) both ask the Solana network for a token's largest accounts. Most of the public nodes we fall back on either refuse that question, answer it with an internal error, or accept it and never reply, and the router treated the last two as real answers, so the call gave up instead of trying the next node. It now moves on from an internal error, charges a silent no-reply to that one question rather than benching an otherwise healthy node, and has one more free node in the rotation that answers it. In a live check the holder read went from succeeding on roughly one call in three to eight out of eight. The error messages across the free crypto endpoints were reworded to match the rest of the platform's plain style at the same time.",+ "link": "/docs/crypto-api",+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-08-12","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex d9f2a7dc5..f3b318218 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -62,6 +62,14 @@<category>feature</category><description>Your agent can now learn how you write from your own X account, and only after you say yes. Connect X in Settings, and the consent screen tells you exactly what is read (your profile and up to 100 of your recent original public posts), what is stored (a handful of short distilled facts about what you talk about and how you talk, never your posts themselves and never links), and what is never touched (messages, likes, bookmarks, your follower list, your credentials). Agree and the agent's next replies already speak from those facts; change your mind and revoking, or disconnecting X, deletes every memory the seed created.</description></item>+ <item>+ <title>The DeFi market pages stop hammering their data source when they get busy</title>+ <link>https://three.ws/defi</link>+ <guid isPermaLink="false">2026-08-12:The DeFi market pages stop hammering their data source when they get busy</guid>+ <pubDate>Wed, 12 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The /defi, /chains, /yields, /stablecoins, /fees, /dex-volumes and /hacks pages, plus the protocol, chain and stablecoin detail pages, all read live data from DeFiLlama and hold it in memory for a few minutes. The moment that held copy expired, every request that arrived at once went and fetched its own fresh copy instead of sharing one. Ten simultaneous visitors to the DEX volume board meant ten downloads of the same two megabytes, and the protocol leaderboard's feed is closer to eight. That burst lands precisely when the page is busiest, and when the source pushed back, the page showed an error even though the data behind it was perfectly good. Now the first request through fetches, and everyone else waiting shares that one result. A chain profile also reuses a single copy of the protocol list rather than pulling it again for every chain. If a fetch does fail, the failure is no longer held on to, so the next visitor gets a real retry instead of the same error for the rest of the window. One cosmetic fix rode along: a pool whose name is missing on /yields now reads "Unknown" instead of a bare dash.</description>+ </item><item><title>The Forge can now federate GPU work to the Livepeer decentralized compute network</title><link>https://three.ws/changelog</link>@@ -94,6 +102,14 @@<category>fix</category><description>Anyone can look up the on-chain anchor for a Proof-of-Custody epoch at /api/custody/anchor. Ask it for an epoch number too large to be a real round and it used to fail with an internal server error, which reads like the custody service is down rather than like a typo in the request. It now answers a plain "that is not a valid epoch" for malformed input, keeps 404 for an epoch that has not happened yet, and reads the newest epoch with a single lookup instead of pulling the whole integrity aggregate it then threw away.</description></item>+ <item>+ <title>Token holder and safety checks stop failing when the free data lanes are busy</title>+ <link>https://three.ws/docs/crypto-api</link>+ <guid isPermaLink="false">2026-08-12:Token holder and safety checks stop failing when the free data lanes are busy</guid>+ <pubDate>Wed, 12 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The free crypto API's holder distribution read (/api/crypto/holders) and the holder half of its token safety check (/api/crypto/security) both ask the Solana network for a token's largest accounts. Most of the public nodes we fall back on either refuse that question, answer it with an internal error, or accept it and never reply, and the router treated the last two as real answers, so the call gave up instead of trying the next node. It now moves on from an internal error, charges a silent no-reply to that one question rather than benching an otherwise healthy node, and has one more free node in the rotation that answers it. In a live check the holder read went from succeeding on roughly one call in three to eight out of eight. The error messages across the free crypto endpoints were reworded to match the rest of the platform's plain style at the same time.</description>+ </item><item><title>Your agent can now learn your Farcaster voice, and only after you prove the account is yours</title><link>https://three.ws/docs/farcaster-memory-seeding</link>diff --git a/tests/api/defi-cache-dedup.test.js b/tests/api/defi-cache-dedup.test.jsnew file mode 100644index 000000000..9835ac5d2--- /dev/null+++ b/tests/api/defi-cache-dedup.test.js@@ -0,0 +1,280 @@+// The api/defi/ builders must collapse a burst of concurrent cold requests into+// ONE upstream call.+//+// Every handler under api/defi/ proxies a DeFiLlama feed and caches the shaped+// result in memory. Before this guard, only yields.js de-duplicated concurrent+// misses; the rest checked "is the cache warm?" and, if not, each request fired+// its own fetch. Measured against a local server, 10 concurrent cold requests+// to /api/defi/dex-volumes issued 10 upstream fetches of the same ~2 MB payload+// (the /protocols feed behind /api/defi/protocols and every chain profile is+// ~8 MB). That is the classic cache stampede: it multiplies egress by the+// concurrency, and it arrives in bursts precisely when the entry expires under+// load, which is when the upstream is least willing to absorb it. A refused+// burst surfaces to users as a 502 on a page that has perfectly good data.+//+// The rules under test, per builder:+// 1. N concurrent cold calls issue exactly one upstream fetch and every+// caller gets the same shaped value.+// 2. A warm cache issues no further fetches.+// 3. A FAILED load is never cached: the next call retries the upstream. A+// cached rejection would pin an endpoint to a transient outage for the+// whole TTL.+//+// The upstream HTTP boundary is stubbed here (that is the only external+// dependency); everything below it is the real shipped code path.++import { describe, it, expect, vi, afterEach } from 'vitest';+import { readFileSync, readdirSync } from 'node:fs';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';++const DEFI_DIR = fileURLToPath(new URL('../../api/defi', import.meta.url));++const reply = (body, status = 200) =>+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });++// Fixture payloads shaped like the real DeFiLlama responses, trimmed to the+// fields each builder reads.+const FIXTURES = {+ protocols: [+ { name: 'Alpha', slug: 'alpha', tvl: 1_000, category: 'Dexes', chains: ['Solana'], symbol: 'AL' },+ { name: 'Custody', slug: 'custody', tvl: 9_000_000, category: 'CEX', chains: ['Solana'] },+ ],+ chains: [+ { name: 'Solana', tvl: 500, tokenSymbol: 'SOL', chainId: null },+ { name: 'Examplechain', tvl: 1_500, tokenSymbol: 'EXC', chainId: 1 },+ ],+ dexs: {+ total24h: 42,+ total7d: 99,+ change_7dover7d: 1.5,+ totalDataChart: [[1_700_000_000, 42]],+ protocols: [{ name: 'Alpha', displayName: 'Alpha', slug: 'alpha', total24h: 42, chains: ['Solana'] }],+ },+ fees: {+ total24h: 7,+ total7d: 21,+ total30d: 90,+ change_1d: -1,+ totalDataChart: [[1_700_000_000, 7]],+ protocols: [{ name: 'Alpha', displayName: 'Alpha', slug: 'alpha', total24h: 7, chains: ['Solana'] }],+ },+ stablecoins: {+ peggedAssets: [+ {+ id: 1,+ name: 'Example USD',+ symbol: 'EXUSD',+ pegType: 'peggedUSD',+ pegMechanism: 'fiat-backed',+ price: 1,+ circulating: { peggedUSD: 1_000 },+ chains: ['Solana'],+ },+ ],+ },+ hacks: [{ date: 1_700_000_000, name: 'Bridge exploit', amount: 100, bridgeHack: true, chain: ['Solana'] }],+ yields: {+ data: [+ {+ pool: '747c1d2a-c668-4682-b9f9-296708a3dd90',+ chain: 'Solana',+ project: 'alpha',+ symbol: 'SOL-EXUSD',+ tvlUsd: 50_000,+ apy: 5,+ },+ ],+ },+};++// Each case names the module, the exported builder, and the payload its single+// upstream call answers with.+const CASES = [+ { file: 'protocols', build: (m) => m.buildProtocols(), payload: FIXTURES.protocols },+ { file: 'chains', build: (m) => m.buildChains(), payload: FIXTURES.chains },+ { file: 'dex-volumes', build: (m) => m.buildDexVolumes(), payload: FIXTURES.dexs },+ { file: 'fees', build: (m) => m.buildFees('fees'), payload: FIXTURES.fees },+ { file: 'stablecoins', build: (m) => m.buildStablecoins(), payload: FIXTURES.stablecoins },+ { file: 'hacks', build: (m) => m.queryHacks({}), payload: FIXTURES.hacks },+ { file: 'yields', build: (m) => m.queryYieldPools({}), payload: FIXTURES.yields },+];++// Module-scope caches persist for the life of a module instance, so every test+// re-imports its subject to start from a genuinely cold cache. The `.js` stays+// in the static part of the specifier so vite can resolve the candidate set.+async function coldImport(name) {+ vi.resetModules();+ return import(`../../api/defi/${name}.js`);+}++afterEach(() => vi.unstubAllGlobals());++describe('api/defi builders de-duplicate concurrent cold loads', () => {+ for (const { file, build, payload } of CASES) {+ it(`${file}: 10 concurrent cold calls issue one upstream fetch`, async () => {+ const fetchMock = vi.fn(async () => reply(payload));+ vi.stubGlobal('fetch', fetchMock);++ const mod = await coldImport(file);+ const results = await Promise.all(Array.from({ length: 10 }, () => build(mod)));++ expect(fetchMock).toHaveBeenCalledTimes(1);+ // Every caller gets the same resolved value, not a partial or a copy+ // built from a second round trip.+ for (const r of results) expect(r).toEqual(results[0]);+ });++ it(`${file}: a warm cache issues no further fetches`, async () => {+ const fetchMock = vi.fn(async () => reply(payload));+ vi.stubGlobal('fetch', fetchMock);++ const mod = await coldImport(file);+ await build(mod);+ expect(fetchMock).toHaveBeenCalledTimes(1);++ await build(mod);+ await build(mod);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ 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);+ });+ vi.stubGlobal('fetch', fetchMock);++ const mod = await coldImport(file);+ await expect(build(mod)).rejects.toThrow();++ // The retry must reach the upstream again rather than replay the failure+ // from cache for the rest of the TTL.+ const recovered = await build(mod);+ expect(recovered).toBeTruthy();+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+ }++ it('fees.js caches the fees and revenue series independently', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ seen.push(String(input));+ return reply(FIXTURES.fees);+ }),+ );++ const mod = await coldImport('fees');+ const [fees, revenue] = await Promise.all([mod.buildFees('fees'), mod.buildFees('revenue')]);++ expect(seen).toHaveLength(2);+ expect(seen.some((u) => u.includes('dailyFees'))).toBe(true);+ expect(seen.some((u) => u.includes('dailyRevenue'))).toBe(true);+ expect(fees.type).toBe('fees');+ expect(revenue.type).toBe('revenue');++ // An unrecognized type is the fees series, and shares the fees cache slot+ // rather than opening a third one.+ await mod.buildFees('nonsense');+ expect(seen).toHaveLength(2);+ });++ it('chain.js shares one protocols feed across different chain profiles', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ const url = String(input);+ seen.push(url);+ if (url.includes('/v2/chains')) return reply(FIXTURES.chains);+ if (url.endsWith('/protocols')) return reply(FIXTURES.protocols);+ if (url.includes('historicalChainTvl')) return reply([{ date: 1_700_000_000, tvl: 500 }]);+ // The remaining feeds are best-effort; an absent one must not fail the+ // profile, so answer them as upstream does for a chain with no coverage.+ return reply({}, 404);+ }),+ );++ const mod = await coldImport('chain');+ const handler = mod.default;+ await Promise.all([invoke(handler, '/api/defi/chain?name=Solana'), invoke(handler, '/api/defi/chain?name=Examplechain')]);++ // Two distinct chain profiles, but the ~8 MB protocols feed is fetched once.+ const protocolsCalls = seen.filter((u) => u.endsWith('/protocols'));+ expect(protocolsCalls).toHaveLength(1);+ });+});++describe('api/defi pool rows carry a readable symbol', () => {+ it('falls back to a real label when upstream omits the symbol', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () =>+ reply({ data: [{ pool: 'b1e5f0a2-0000-4000-8000-000000000001', chain: 'Solana', project: 'alpha', tvlUsd: 1 }] }),+ ),+ );++ const mod = await coldImport('yields');+ const { pools } = await mod.queryYieldPools({});++ // This value renders verbatim as the pool's name on /yields, so it must be+ // a word, not a punctuation glyph standing in for one.+ expect(pools[0].symbol).toBe('Unknown');+ });+});++describe('api/defi honors the dash ban', () => {+ // Written as escapes on purpose: spelling the two glyphs literally would put+ // them in this file and make the repo-wide rule check fail on its own guard.+ const BANNED_DASH = new RegExp('[\\u2014\\u2013]');++ it('contains no em-dash or en-dash characters', () => {+ const offenders = [];+ for (const name of readdirSync(DEFI_DIR)) {+ if (!name.endsWith('.js') && !name.endsWith('.md')) continue;+ const src = readFileSync(join(DEFI_DIR, name), 'utf8');+ src.split('\n').forEach((line, i) => {+ if (BANNED_DASH.test(line)) offenders.push(`api/defi/${name}:${i + 1}`);+ });+ }+ expect(offenders).toEqual([]);+ });+});++// Minimal request/response pair for driving a handler's default export, matching+// the node-style (req, res) contract the api/ handlers are written against.+async function invoke(handler, url) {+ const chunks = [];+ const res = {+ statusCode: 200,+ headers: {},+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ removeHeader(k) {+ delete this.headers[k.toLowerCase()];+ },+ writeHead(status, headers) {+ this.statusCode = status;+ for (const [k, v] of Object.entries(headers || {})) this.setHeader(k, v);+ return this;+ },+ write(chunk) {+ chunks.push(chunk);+ return true;+ },+ end(chunk) {+ if (chunk) chunks.push(chunk);+ return this;+ },+ };+ await handler({ method: 'GET', url, headers: { host: 'three.ws' }, socket: {} }, res);+ return { status: res.statusCode, body: chunks.join('') };+}