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
feat(chains): add a sortable turnover column (24h DEX volume over TVL) so /chains shows where capital is working, not just parked
nirholasbb7445ef235c
diff --git a/api/defi/chains.js b/api/defi/chains.jsindex 838346510..794b5f71c 100644--- a/api/defi/chains.js+++ b/api/defi/chains.js@@ -10,6 +10,7 @@ import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { createCache, cached } from '../_lib/mem-cache.js';import { fetchUpstream } from '../_lib/upstream-fetch.js';+import { buildDexVolumes, normalizeChainKey } from './dex-volumes.js';const UPSTREAM = 'https://api.llama.fi/v2/chains';const TTL_MS = 300_000;@@ -25,6 +26,24 @@ export async function buildChains() {return cached(_cache, CACHE_KEY, loadChains);}+// Turnover = 24h DEX volume / TVL: how hard a chain's capital is working. A+// chain with no TVL or no reported volume gets null (unavailable), never+// Infinity or a misleading zero.+export function turnover(volume24h, tvl) {+ if (!Number.isFinite(volume24h) || volume24h <= 0) return null;+ if (!Number.isFinite(tvl) || tvl <= 0) return null;+ return volume24h / tvl;+}++async function loadChainVolumes() {+ try {+ const dex = await buildDexVolumes();+ return dex?.chain_volumes24h || {};+ } catch {+ return {};+ }+}+async function loadChains() {const now = Date.now();@@ -32,6 +51,7 @@ async function loadChains() {headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },}, { timeoutMs: 10_000, attempts: 2 });const raw = await resp.json();+ const volumes = await loadChainVolumes();if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');let totalTvl = 0;@@ -47,11 +67,14 @@ async function loadChains() {const chains = eligible.slice(0, 100).map((c) => {const tvl = Number(c.tvl);+ const volume24h = volumes[normalizeChainKey(c.name ?? '')] ?? null;return {name: typeof c.name === 'string' ? c.name : 'Unknown',tvl,token_symbol: typeof c.tokenSymbol === 'string' && c.tokenSymbol ? c.tokenSymbol : null,share_pct: totalTvl > 0 ? (tvl / totalTvl) * 100 : 0,+ dex_volume_24h: volume24h,+ turnover: turnover(volume24h, tvl),};});diff --git a/api/defi/dex-volumes.js b/api/defi/dex-volumes.jsindex 53311ca7a..8b539b95b 100644--- a/api/defi/dex-volumes.js+++ b/api/defi/dex-volumes.js@@ -42,6 +42,33 @@ function normalizeChart(raw) {// Exported for the paid Market Data API (api/_lib/market-data/), the x402// market-dex-volumes endpoint sells the same DEX rankings this page renders.+// 24h DEX volume per chain, summed from each protocol's per-chain breakdown.+// Keyed by normalizeChainKey() so it joins against other feeds' chain names.+export function sumChainVolumes(protocols) {+ const out = {};+ for (const p of protocols) {+ const b = p?.breakdown24h;+ if (!b || typeof b !== 'object') continue;+ for (const [chain, perProto] of Object.entries(b)) {+ if (!perProto || typeof perProto !== 'object') continue;+ let sum = 0;+ for (const v of Object.values(perProto)) {+ const n = Number(v);+ if (Number.isFinite(n) && n > 0) sum += n;+ }+ if (sum <= 0) continue;+ const key = normalizeChainKey(chain);+ out[key] = (out[key] || 0) + sum;+ }+ }+ return out;+}++// "Arbitrum Nova" and "arbitrum_nova" are the same chain across feeds.+export function normalizeChainKey(name) {+ return String(name).toLowerCase().replace(/[^a-z0-9]/g, '');+}+export async function buildDexVolumes() {return cached(_cache, CACHE_KEY, loadDexVolumes);}@@ -90,6 +117,7 @@ async function loadDexVolumes() {change_7dover7d: finite(Number(raw.change_7dover7d)),chart: normalizeChart(raw.totalDataChart),protocols,+ chain_volumes24h: sumChainVolumes(raw.protocols),updated_at: now,};}diff --git a/src/chains.js b/src/chains.jsindex b99a00db6..03e2925ce 100644--- a/src/chains.js+++ b/src/chains.js@@ -91,6 +91,12 @@ const COLUMNS = [{ key: 'rank', label: '#', left: true, hide: 'hide-sm', num: true },{ key: 'name', label: 'Chain', left: true },{ key: 'tvl', label: 'TVL', num: true },+ {+ key: 'turnover',+ label: 'Turnover',+ num: true,+ tip: 'Turnover = 24h DEX volume divided by TVL. A high value means capital is trading actively; a low value means it is mostly parked. Shown as n/a when a chain reports no TVL or no DEX volume.',+ },{ key: 'share_pct', label: 'Dominance', num: true },{ key: 'bar', label: 'Share', left: true, hide: 'hide-md', sortless: true },];@@ -162,7 +168,7 @@ function renderTable() {const active = col.key === state.sortKey;const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';const sort = active ? (state.sortDir === 'asc' ? 'ascending' : 'descending') : 'none';- return `<th scope="col" tabindex="0" data-key="${col.key}" aria-sort="${sort}" class="${col.left ? 'left' : ''} ${col.hide || ''}">${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;+ return `<th scope="col" tabindex="0" data-key="${col.key}" aria-sort="${sort}"${col.tip ? ` title="${esc(col.tip)}"` : ''} class="${col.left ? 'left' : ''} ${col.hide || ''}">${esc(col.label)}${col.tip ? '<span class="tip" aria-hidden="true"> ⓘ</span>' : ''}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;}).join('');const body = sortedChains()@@ -182,6 +188,7 @@ function renderTable() {<td class="rank hide-sm cv-mono">${c.__rank}</td><td class="left name-cell">${href ? `<a href="${esc(href)}">${inner}</a>` : inner}</td><td class="price">${esc(formatUsd(c.tvl))}</td>+ <td class="pct cv-mono"${c.dex_volume_24h ? ` title="24h DEX volume ${esc(formatUsd(c.dex_volume_24h))}"` : ''}>${c.turnover == null ? 'n/a' : `${c.turnover.toFixed(c.turnover < 0.1 ? 3 : 2)}x`}</td><td class="pct cv-mono">${(c.share_pct || 0).toFixed(2)}%</td><td class="left hide-md chains-bar-cell"><span class="chains-bar" aria-hidden="true">diff --git a/tests/defi-chains.test.js b/tests/defi-chains.test.jsnew file mode 100644index 000000000..e2a18a9ac--- /dev/null+++ b/tests/defi-chains.test.js@@ -0,0 +1,55 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const fetchUpstream = vi.fn();+vi.mock('../api/_lib/upstream-fetch.js', () => ({ fetchUpstream: (...a) => fetchUpstream(...a) }));+vi.mock('../api/_lib/rate-limit.js', () => ({ limits: {}, clientIp: () => '0' }));++const { sumChainVolumes, normalizeChainKey } = await import('../api/defi/dex-volumes.js');+const { turnover, buildChains } = await import('../api/defi/chains.js');++const ok = (body) => ({ json: async () => body });++describe('turnover', () => {+ it('divides volume by TVL', () => expect(turnover(50, 100)).toBe(0.5));+ it('is null, never Infinity, when TVL is missing', () => {+ expect(turnover(50, 0)).toBeNull();+ expect(turnover(50, NaN)).toBeNull();+ });+ it('is null when no volume is reported', () => {+ expect(turnover(null, 100)).toBeNull();+ expect(turnover(0, 100)).toBeNull();+ });+});++describe('sumChainVolumes', () => {+ it('sums across protocols and normalizes chain keys', () => {+ const out = sumChainVolumes([+ { breakdown24h: { arbitrum_nova: { A: 10, B: 5 }, ethereum: { A: 100 } } },+ { breakdown24h: { ethereum: { C: 50 } } },+ {},+ ]);+ expect(out).toEqual({ arbitrumnova: 15, ethereum: 150 });+ expect(normalizeChainKey('Arbitrum Nova')).toBe('arbitrumnova');+ });+});++describe('buildChains', () => {+ beforeEach(() => fetchUpstream.mockReset());++ it('joins DEX volume into each chain as turnover', async () => {+ fetchUpstream.mockImplementation(async (url) =>+ String(url).includes('overview/dexs')+ ? ok({ total24h: 1, protocols: [{ breakdown24h: { ethereum: { A: 200 }, orphan: { A: 9 } } }] })+ : ok([+ { name: 'Ethereum', tvl: 1000 },+ { name: 'Base', tvl: 500 },+ ]),+ );+ const { chains } = await buildChains();+ const eth = chains.find((c) => c.name === 'Ethereum');+ const base = chains.find((c) => c.name === 'Base');+ expect(eth.turnover).toBeCloseTo(0.2);+ expect(eth.dex_volume_24h).toBe(200);+ expect(base.turnover).toBeNull();+ });+});