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.

3.9 KB
Raw Blame
// GET /api/defi/chains
// ---------------------------------------------------------------------------
// Cross-chain TVL leaderboard for the /chains page. Fetches DeFiLlama's keyless
// /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.

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;

// Single-entry cache with single-flight de-dup, so a burst of concurrent
// requests on a cold or just-expired entry shares one upstream fetch.
const _cache = createCache({ max: 1, ttlMs: TTL_MS });
const CACHE_KEY = 'chains';

// Exported for the paid Market Data API (api/_lib/market-data/), the x402
// market-chains endpoint sells the same cross-chain TVL board this page renders.
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();

	const resp = await fetchUpstream(UPSTREAM, {
		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;
	const eligible = [];
	for (const c of raw) {
		const tvl = Number(c?.tvl);
		if (!Number.isFinite(tvl) || tvl <= 0) continue;
		totalTvl += tvl;
		eligible.push(c);
	}

	eligible.sort((a, b) => Number(b.tvl) - Number(a.tvl));

	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),
		};
	});

	return {
		total_tvl: totalTvl,
		chain_count: eligible.length,
		chains,
		updated_at: now,
	};
}

// `cached()` serves its last-good copy (without re-populating the fresh slot)
// when the loader throws, so a fresh miss after a resolved value means the
// payload is stale. Label it so the page can say so instead of passing it off
// as live.
function staleHeaders() {
	return _cache.has(CACHE_KEY) ? {} : { 'x-three-stale': '1' };
}

export default wrap(async (req, res) => {
	if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
	if (!method(req, res, ['GET'])) return;

	const rl = await limits.marketDataIp(clientIp(req));
	if (!rl.success) return rateLimited(res, rl);

	try {
		const payload = await buildChains();
		return json(res, 200, payload, {
			'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
			...staleHeaders(),
		});
	} catch {
		return error(
			res,
			502,
			'upstream_error',
			'Cross-chain TVL data is unavailable right now. Retry shortly',
		);
	}
});