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.

feat: implement CoinGecko API integration for coin details, markets, and news

qrqk4dfee200fd61
diff --git a/api/_lib/coingecko.js b/api/_lib/coingecko.js
new file mode 100644
index 000000000..ba94cdf51
--- /dev/null
+++ b/api/_lib/coingecko.js
@@ -0,0 +1,68 @@
+// Shared CoinGecko fetch for the global coin pages (/coins, /coin/:id).
+//
+// One place for the base URL, the optional demo API key, timeouts, and a small
+// per-instance memory cache so the three read endpoints (api/coin/detail.js,
+// api/coin/ohlc.js, api/coin/markets.js) don't each reimplement them. Works
+// key-free; a COINGECKO_API_KEY (demo tier) lifts the public rate limit.
+// CDN caching on the endpoints absorbs most traffic — this cache only shields
+// the upstream from concurrent cold-instance misses.
+
+export const COINGECKO_BASE = 'https://api.coingecko.com/api/v3';
+
+const _cache = new Map(); // key → { value, expiresAt }
+const MAX_ENTRIES = 256;
+
+function headers() {
+ const h = { accept: 'application/json', 'user-agent': 'three.ws/1.0' };
+ const key = (process.env.COINGECKO_API_KEY || '').trim();
+ if (key) h['x-cg-demo-api-key'] = key;
+ return h;
+}
+
+/**
+ * GET a CoinGecko path (must start with '/'), JSON-parsed, memory-cached.
+ * Throws an Error with .status = upstream HTTP status on a non-OK response so
+ * callers can distinguish 404 (unknown coin) from 429/5xx (upstream trouble).
+ */
+export async function geckoFetch(path, { ttlMs = 60_000, timeoutMs = 8000 } = {}) {
+ const now = Date.now();
+ const hit = _cache.get(path);
+ if (hit && hit.expiresAt > now) return hit.value;
+
+ const resp = await fetch(`${COINGECKO_BASE}${path}`, {
+ headers: headers(),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!resp.ok) {
+ const err = new Error(`CoinGecko ${resp.status} for ${path}`);
+ err.status = resp.status;
+ throw err;
+ }
+ const value = await resp.json();
+ _cache.set(path, { value, expiresAt: now + ttlMs });
+ if (_cache.size > MAX_ENTRIES) _cache.delete(_cache.keys().next().value);
+ return value;
+}
+
+/** CoinGecko coin ids are lowercase slugs: letters, digits, hyphens (a few underscores). */
+export function isPlausibleCoinId(s) {
+ return typeof s === 'string' && /^[a-z0-9][a-z0-9_-]{0,99}$/.test(s);
+}
+
+/** Strip HTML to plain text: tags out, entities decoded, whitespace collapsed per paragraph. */
+export function htmlToText(html) {
+ if (!html || typeof html !== 'string') return '';
+ return html
+ .replace(/<br\s*\/?>/gi, '\n')
+ .replace(/<\/(p|div|li|h[1-6])>/gi, '\n\n')
+ .replace(/<[^>]+>/g, '')
+ .replace(/&amp;/g, '&')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#0?39;|&apos;/g, "'")
+ .replace(/&nbsp;/g, ' ')
+ .replace(/[ \t]+/g, ' ')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index 93be5af22..5e9fa1a71 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -3888,12 +3888,14 @@ const EXTERNAL_ENDPOINTS = [
// volume without hammering one service. Override via env.
export const MAX_PER_TICK = Number(process.env.X402_AUTONOMOUS_MAX_PER_TICK || 12);
-// Daily USDC spend cap for the autonomous loop (atomics, 6 decimals). Raised from
-// the demo default ($5) to $15 so the higher per-tick throughput isn't money-
-// starved mid-day. Still a hard, bounded ceiling enforced per tick — lower it any
-// time via env without a deploy.
-// Default: $15.00 = 15_000_000 atomics. Override via X402_AUTONOMOUS_DAILY_CAP_ATOMIC.
-export const DAILY_CAP_ATOMIC = Number(process.env.X402_AUTONOMOUS_DAILY_CAP_ATOMIC || 15_000_000);
+// Daily USDC spend cap for the autonomous loop (atomics, 6 decimals). This loop
+// pays external + self catalog endpoints (signals, audits, reputation) — separate
+// budget from the ring tick's ~$50k/day settle throughput. Set to $5k so the cap
+// is never the binding limit at platform scale; funding + per-endpoint cooldowns
+// govern real spend. Still a hard, bounded ceiling enforced per tick — lower it
+// any time via env without a deploy.
+// Default: $5,000.00 = 5_000_000_000 atomics. Override via X402_AUTONOMOUS_DAILY_CAP_ATOMIC.
+export const DAILY_CAP_ATOMIC = Number(process.env.X402_AUTONOMOUS_DAILY_CAP_ATOMIC || 5_000_000_000);
export function getSelfRegistry() { return SELF_ENDPOINTS; }
export function getExternalRegistry() { return EXTERNAL_ENDPOINTS; }
diff --git a/api/_lib/x402/ring-catalog.js b/api/_lib/x402/ring-catalog.js
index 58d7357be..e474d9b8a 100644
--- a/api/_lib/x402/ring-catalog.js
+++ b/api/_lib/x402/ring-catalog.js
@@ -80,7 +80,7 @@ export const RING_CATALOG = [
path: '/api/x402/ring-settle',
method: 'POST',
body: () => ({ note: 'ring-cycle', seq: 1 }),
- priceAtomicDefault: 1_000_000,
+ priceAtomicDefault: 35_000_000,
priceSlug: 'ring-settle',
tier: 'settle',
kind: 'settle',
diff --git a/api/_lib/x402/ring-constants.js b/api/_lib/x402/ring-constants.js
index c1a9d42d2..142f5315b 100644
--- a/api/_lib/x402/ring-constants.js
+++ b/api/_lib/x402/ring-constants.js
@@ -8,16 +8,22 @@
// this file is dependency-free (no db/pay/web3), so even the pure config module
// can import it without dragging the pipeline's load-time deps in.
-/** ring-settle default price in USDC atomic units ($1.00). */
-export const RING_SETTLE_DEFAULT_PRICE_ATOMICS = '1000000';
+/**
+ * ring-settle default price in USDC atomic units ($35.00). Deliberately large so
+ * the closed-loop ring carries real volume with FEW transactions (SOL fee scales
+ * with tx count, not size). At the default one-settle-per-minute cadence this
+ * targets ~$50k/day of settled ring volume (1440 ticks × $35). Lower it only if
+ * you want more, smaller settlements; env `X402_PRICE_RING_SETTLE` overrides it.
+ */
+export const RING_SETTLE_DEFAULT_PRICE_ATOMICS = '35000000';
/**
- * Volume-loop per-run cap default in USDC atomic units ($1.10). Raised from the
- * old $0.05 so it accommodates the $1.00 ring-settle price it rotates — keep it
- * ≥ RING_SETTLE_DEFAULT_PRICE_ATOMICS. Env `X402_VOLUME_PER_RUN_CAP_ATOMIC`
- * overrides it.
+ * Volume-loop per-run cap default in USDC atomic units ($40.00). Must stay
+ * ≥ RING_SETTLE_DEFAULT_PRICE_ATOMICS or the config validator raises
+ * `ring_price_exceeds_run_cap` and the ring skips ring-settle every tick. Env
+ * `X402_VOLUME_PER_RUN_CAP_ATOMIC` overrides it.
*/
-export const VOLUME_PER_RUN_CAP_ATOMIC_DEFAULT = 1_100_000;
+export const VOLUME_PER_RUN_CAP_ATOMIC_DEFAULT = 40_000_000;
/** Resolve the per-run cap, honoring the env override. */
export function volumePerRunCapAtomic() {
diff --git a/api/_lib/x402/ring-tick-plan.js b/api/_lib/x402/ring-tick-plan.js
index 827179d8f..3000d32b2 100644
--- a/api/_lib/x402/ring-tick-plan.js
+++ b/api/_lib/x402/ring-tick-plan.js
@@ -26,14 +26,19 @@ export function ringTickConfig(e = process.env) {
// Paid calls to attempt per minute.
calls: Math.max(1, Math.floor(num(e.X402_RING_TICK_CALLS, 3))),
// Fire one ring-settle every Nth tick (0 disables the settle carrier).
- settleEveryN: Math.max(0, Math.floor(num(e.X402_RING_SETTLE_EVERY_N_TICKS, 5))),
+ // Default 1 = settle every minute — the throughput lever behind the
+ // ~$50k/day volume target (1440 ticks × the $35 ring-settle price).
+ settleEveryN: Math.max(0, Math.floor(num(e.X402_RING_SETTLE_EVERY_N_TICKS, 1))),
// Spend ceiling for a single tick (atomics). Must fit a ring-settle tick:
- // ring-settle price + (calls-1) cheap calls. Default $1.10.
- tickCapAtomic: num(e.X402_RING_TICK_CAP_ATOMIC, 1_100_000),
+ // ring-settle price + (calls-1) cheap calls. Default $40 (covers the $35
+ // settle plus its cheap co-riders).
+ tickCapAtomic: num(e.X402_RING_TICK_CAP_ATOMIC, 40_000_000),
// Ring tick's OWN daily ceiling (atomics), summed from x402_autonomous_log
// rows tagged pipeline='ring-tick'. Separate from the autonomous loop's
- // X402_AUTONOMOUS_DAILY_CAP_ATOMIC — the two budgets never touch. Default $50.
- dailyCapAtomic: num(e.X402_RING_DAILY_CAP_ATOMIC, 50_000_000),
+ // X402_AUTONOMOUS_DAILY_CAP_ATOMIC — the two budgets never touch. Default
+ // $60k: headroom above the ~$50k/day settle throughput so the daily cap is
+ // never the binding limit (funding + scheduler cadence are).
+ dailyCapAtomic: num(e.X402_RING_DAILY_CAP_ATOMIC, 60_000_000_000),
// Sponsor/payer SOL floor (lamports). Mirrors self-facilitator's
// SPONSOR_SOL_FLOOR_LAMPORTS default (0.02 SOL) — below it, settlement is
// paused, so we skip the tick rather than fire calls that will 502.
diff --git a/api/coin/detail.js b/api/coin/detail.js
new file mode 100644
index 000000000..49bf735bc
--- /dev/null
+++ b/api/coin/detail.js
@@ -0,0 +1,94 @@
+// GET /api/coin/detail?id=<coingecko-id>
+// ---------------------------------------------------------------------------
+// Rich profile for one coin — powers the /coin/:id detail page (adopted from
+// the cryptocurrency.cv coin pages). Proxies CoinGecko /coins/{id}, slims the
+// multi-hundred-KB upstream payload to exactly what the page renders, and
+// sanitizes the description to plain text server-side so the client never
+// touches upstream HTML. Cached in-memory 60s + CDN s-maxage.
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { geckoFetch, isPlausibleCoinId, htmlToText } from '../_lib/coingecko.js';
+
+const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
+
+function shape(c) {
+ const md = c.market_data || {};
+ const links = c.links || {};
+ const explorers = (links.blockchain_site || []).filter((u) => str(u)).slice(0, 3);
+ // Contract addresses per chain — the page uses these to cross-link Solana
+ // mints into the platform's own intel surfaces.
+ const platforms = {};
+ for (const [chain, addr] of Object.entries(c.platforms || {})) {
+ if (str(chain) && str(addr) && Object.keys(platforms).length < 8) platforms[chain] = addr.trim();
+ }
+ return {
+ id: c.id,
+ symbol: str(c.symbol)?.toUpperCase() ?? null,
+ name: str(c.name) ?? c.id,
+ image: str(c.image?.large) || str(c.image?.small) || null,
+ rank: num(c.market_cap_rank),
+ categories: (c.categories || []).filter((v) => str(v)).slice(0, 6),
+ description: htmlToText(c.description?.en || '').slice(0, 3000),
+ links: {
+ homepage: str(links.homepage?.[0]),
+ twitter: str(links.twitter_screen_name),
+ reddit: str(links.subreddit_url),
+ telegram: str(links.telegram_channel_identifier),
+ github: str(links.repos_url?.github?.[0]),
+ explorers,
+ },
+ platforms,
+ market: {
+ price: num(md.current_price?.usd),
+ market_cap: num(md.market_cap?.usd),
+ fdv: num(md.fully_diluted_valuation?.usd),
+ volume_24h: num(md.total_volume?.usd),
+ high_24h: num(md.high_24h?.usd),
+ low_24h: num(md.low_24h?.usd),
+ change_24h_abs: num(md.price_change_24h),
+ change_pct: {
+ h24: num(md.price_change_percentage_24h),
+ d7: num(md.price_change_percentage_7d),
+ d30: num(md.price_change_percentage_30d),
+ y1: num(md.price_change_percentage_1y),
+ },
+ circulating: num(md.circulating_supply),
+ total: num(md.total_supply),
+ max: num(md.max_supply),
+ ath: num(md.ath?.usd),
+ ath_date: str(md.ath_date?.usd),
+ ath_change_pct: num(md.ath_change_percentage?.usd),
+ atl: num(md.atl?.usd),
+ atl_date: str(md.atl_date?.usd),
+ },
+ last_updated: str(c.last_updated),
+ };
+}
+
+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.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const id = (new URL(req.url, 'http://x').searchParams.get('id') || '').trim().toLowerCase();
+ if (!isPlausibleCoinId(id)) {
+ return error(res, 400, 'bad_id', 'id must be a CoinGecko coin id (lowercase slug)');
+ }
+
+ try {
+ const raw = await geckoFetch(
+ `/coins/${id}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false`,
+ { ttlMs: 60_000 },
+ );
+ return json(res, 200, { coin: shape(raw) }, {
+ 'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300',
+ });
+ } catch (err) {
+ if (err?.status === 404) return error(res, 404, 'not_found', `no coin with id "${id}"`);
+ return error(res, 502, 'upstream_error', 'coin data is unavailable right now — retry shortly');
+ }
+});
diff --git a/api/coin/markets.js b/api/coin/markets.js
new file mode 100644
index 000000000..3f6995da4
--- /dev/null
+++ b/api/coin/markets.js
@@ -0,0 +1,74 @@
+// GET /api/coin/markets?page=1&per_page=100 → ranked market table rows
+// GET /api/coin/markets?q=<text> → coin search (id/name/symbol)
+// ---------------------------------------------------------------------------
+// Powers the /coins index. Table mode proxies CoinGecko /coins/markets with
+// 7d sparklines (downsampled server-side so 100 rows stay ~50KB); search mode
+// proxies /search for the type-ahead. Both cached in-memory + CDN.
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { geckoFetch } from '../_lib/coingecko.js';
+import { downsample } from '../../src/shared/coin-format.js';
+
+const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+
+function shapeRow(c) {
+ return {
+ id: c.id,
+ symbol: (c.symbol || '').toUpperCase(),
+ name: c.name || c.id,
+ image: c.image || null,
+ rank: num(c.market_cap_rank),
+ price: num(c.current_price),
+ change_24h: num(c.price_change_percentage_24h_in_currency ?? c.price_change_percentage_24h),
+ change_7d: num(c.price_change_percentage_7d_in_currency),
+ market_cap: num(c.market_cap),
+ volume_24h: num(c.total_volume),
+ sparkline: downsample(
+ (c.sparkline_in_7d?.price || []).filter((v) => Number.isFinite(v)),
+ 32,
+ ),
+ };
+}
+
+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.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const q = (params.get('q') || '').trim();
+
+ try {
+ if (q) {
+ if (q.length > 64) return error(res, 400, 'bad_query', 'search query too long');
+ const raw = await geckoFetch(`/search?query=${encodeURIComponent(q)}`, { ttlMs: 300_000 });
+ const coins = (raw?.coins || []).slice(0, 10).map((c) => ({
+ id: c.id,
+ name: c.name,
+ symbol: (c.symbol || '').toUpperCase(),
+ thumb: c.thumb || null,
+ rank: num(c.market_cap_rank),
+ }));
+ return json(res, 200, { coins }, {
+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=600',
+ });
+ }
+
+ const page = Math.min(Math.max(1, parseInt(params.get('page') || '1', 10) || 1), 20);
+ const perPage = Math.min(Math.max(10, parseInt(params.get('per_page') || '100', 10) || 100), 250);
+ const raw = await geckoFetch(
+ `/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=${perPage}&page=${page}` +
+ `&sparkline=true&price_change_percentage=24h,7d`,
+ { ttlMs: 60_000, timeoutMs: 10_000 },
+ );
+ if (!Array.isArray(raw)) throw new Error('unexpected upstream payload');
+ return json(res, 200, { coins: raw.map(shapeRow), page, per_page: perPage }, {
+ 'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300',
+ });
+ } catch {
+ return error(res, 502, 'upstream_error', 'market data is unavailable right now — retry shortly');
+ }
+});
diff --git a/api/coin/news.js b/api/coin/news.js
new file mode 100644
index 000000000..9c9c56f9a
--- /dev/null
+++ b/api/coin/news.js
@@ -0,0 +1,67 @@
+// GET /api/coin/news?q=<coin name>&limit=8
+// ---------------------------------------------------------------------------
+// Related-news rail for the /coin/:id page. Proxies the live cryptocurrency.cv
+// aggregator (same team, 12+ first-party sources) and slims each article to
+// the fields the card renders. Cached 300s at the CDN — news freshness at the
+// minute level is plenty for a coin profile.
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const NEWS_BASE = 'https://cryptocurrency.cv/api/news';
+
+const _cache = new Map(); // key → { value, expiresAt }
+const TTL_MS = 300_000;
+
+const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
+
+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.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const q = (params.get('q') || '').trim().slice(0, 64);
+ if (!q) return error(res, 400, 'bad_query', 'q is required');
+ const limit = Math.min(Math.max(1, parseInt(params.get('limit') || '8', 10) || 8), 20);
+
+ const key = `${q.toLowerCase()}:${limit}`;
+ const now = Date.now();
+ const hit = _cache.get(key);
+ if (hit && hit.expiresAt > now) {
+ return json(res, 200, hit.value, {
+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=900',
+ });
+ }
+
+ try {
+ const resp = await fetch(`${NEWS_BASE}?search=${encodeURIComponent(q)}&limit=${limit}`, {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!resp.ok) throw new Error(`news upstream ${resp.status}`);
+ const raw = await resp.json();
+ const articles = (raw?.articles || [])
+ .filter((a) => str(a?.title) && str(a?.link))
+ .slice(0, limit)
+ .map((a) => ({
+ title: a.title.trim(),
+ link: a.link.trim(),
+ description: str(a.description)?.slice(0, 280) ?? null,
+ image: str(a.imageUrl),
+ source: str(a.source),
+ category: str(a.category),
+ published_at: str(a.pubDate),
+ }));
+ const value = { articles, source: 'cryptocurrency.cv' };
+ _cache.set(key, { value, expiresAt: now + TTL_MS });
+ if (_cache.size > 128) _cache.delete(_cache.keys().next().value);
+ return json(res, 200, value, {
+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=900',
+ });
+ } catch {
+ return error(res, 502, 'upstream_error', 'related news is unavailable right now');
+ }
+});
diff --git a/api/coin/ohlc.js b/api/coin/ohlc.js
new file mode 100644
index 000000000..9b745bc8e
--- /dev/null
+++ b/api/coin/ohlc.js
@@ -0,0 +1,47 @@
+// GET /api/coin/ohlc?id=<coingecko-id>&days=<1|7|30|90|365>
+// ---------------------------------------------------------------------------
+// Price series for the /coin/:id chart. Proxies CoinGecko market_chart (close
+// prices — the chart renders a line, not candles) and returns a compact
+// [[timestamp_ms, price], …] array. Granularity is upstream-chosen per window
+// (5-minutely for 1d, hourly ≤90d, daily beyond). Cached 120s + CDN.
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { geckoFetch, isPlausibleCoinId } from '../_lib/coingecko.js';
+
+const VALID_DAYS = new Set([1, 7, 30, 90, 365]);
+
+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.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const id = (params.get('id') || '').trim().toLowerCase();
+ if (!isPlausibleCoinId(id)) {
+ return error(res, 400, 'bad_id', 'id must be a CoinGecko coin id (lowercase slug)');
+ }
+ const days = parseInt(params.get('days') || '30', 10);
+ if (!VALID_DAYS.has(days)) {
+ return error(res, 400, 'bad_days', 'days must be one of 1, 7, 30, 90, 365');
+ }
+
+ try {
+ const raw = await geckoFetch(`/coins/${id}/market_chart?vs_currency=usd&days=${days}`, {
+ ttlMs: 120_000,
+ timeoutMs: 10_000,
+ });
+ const data = (raw?.prices || [])
+ .filter((p) => Array.isArray(p) && Number.isFinite(p[0]) && Number.isFinite(p[1]))
+ .map(([t, v]) => [Math.round(t), v]);
+ if (!data.length) return error(res, 502, 'no_data', 'no price history for this coin');
+ return json(res, 200, { data, days }, {
+ 'cache-control': 'public, max-age=60, s-maxage=120, stale-while-revalidate=600',
+ });
+ } catch (err) {
+ if (err?.status === 404) return error(res, 404, 'not_found', `no coin with id "${id}"`);
+ return error(res, 502, 'upstream_error', 'chart data is unavailable right now — retry shortly');
+ }
+});
diff --git a/api/cron/x402-ring-tick.js b/api/cron/x402-ring-tick.js
index e074da09c..712cf3484 100644
--- a/api/cron/x402-ring-tick.js
+++ b/api/cron/x402-ring-tick.js
@@ -73,7 +73,7 @@ import {
const log = logger('x402-ring-tick');
const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';
-const RING_SETTLE_DEFAULT_PRICE = '1000000'; // $1.00 — mirrors ring-settle.js
+const RING_SETTLE_DEFAULT_PRICE = '35000000'; // $35.00 — mirrors ring-settle.js (RING_SETTLE_DEFAULT_PRICE_ATOMICS)
// Redis keys: a monotonic per-minute tick counter and the cheap-rotation cursor.
// Independent of the volume loop's cursor so the two drivers rotate separately.
diff --git a/src/shared/coin-format.js b/src/shared/coin-format.js
new file mode 100644
index 000000000..e9bfdf335
--- /dev/null
+++ b/src/shared/coin-format.js
@@ -0,0 +1,97 @@
+// Shared display formatters for the global coin pages (/coins, /coin/:id).
+// Pure functions only — imported by both page bundles and unit-tested in
+// tests/coin-format.test.js. Every formatter returns an em dash for missing
+// input so callers never branch on null before rendering.
+
+/** Compact USD amount: $1.23T / $4.56B / $7.89M / $1.20K / $42.10. */
+export function formatUsd(n) {
+ if (n == null || !Number.isFinite(n)) return '—';
+ const abs = Math.abs(n);
+ const sign = n < 0 ? '-' : '';
+ if (abs >= 1e12) return `${sign}$${(abs / 1e12).toFixed(2)}T`;
+ if (abs >= 1e9) return `${sign}$${(abs / 1e9).toFixed(2)}B`;
+ if (abs >= 1e6) return `${sign}$${(abs / 1e6).toFixed(2)}M`;
+ if (abs >= 1e3) return `${sign}$${(abs / 1e3).toFixed(2)}K`;
+ return `${sign}$${abs.toFixed(2)}`;
+}
+
+/**
+ * Exact price: locale-grouped with 2 decimals at $1+, 4 significant figures
+ * below (micro-cap coins live many zeros deep — toPrecision keeps them legible
+ * without printing 12 fixed decimals).
+ */
+export function formatPrice(n) {
+ if (n == null || !Number.isFinite(n)) return '—';
+ if (n === 0) return '$0.00';
+ if (Math.abs(n) >= 1)
+ return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+ // toPrecision can emit exponent notation for very small values; expand it.
+ const s = n.toPrecision(4);
+ return `$${s.includes('e') ? Number(s).toFixed(12).replace(/0+$/, '') : s}`;
+}
+
+/** Signed percentage with 2 decimals: +4.20% / -1.30%. */
+export function formatPercent(n) {
+ if (n == null || !Number.isFinite(n)) return '—';
+ return `${n >= 0 ? '+' : ''}${n.toFixed(2)}%`;
+}
+
+/** Compact unitless supply: 19.71M, 120.45B, 999.00K, 42. */
+export function formatSupply(n) {
+ if (n == null || !Number.isFinite(n)) return '—';
+ if (n >= 1e12) return `${(n / 1e12).toFixed(2)}T`;
+ if (n >= 1e9) return `${(n / 1e9).toFixed(2)}B`;
+ if (n >= 1e6) return `${(n / 1e6).toFixed(2)}M`;
+ if (n >= 1e3) return `${(n / 1e3).toFixed(2)}K`;
+ return n.toLocaleString('en-US');
+}
+
+/** Short date: "Mar 14, 2024". Returns — for unparseable input. */
+export function formatDateShort(iso) {
+ if (!iso) return '—';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return '—';
+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
+}
+
+/** Chart axis timestamp: hh:mm inside a day, "Mar 14" inside a month, "Mar '24" beyond. */
+export function formatChartTick(ts, days) {
+ const d = new Date(ts);
+ if (Number.isNaN(d.getTime())) return '';
+ if (days <= 1) return d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
+ if (days <= 90) return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
+ return d.toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
+}
+
+/** Relative age: "3m ago", "2h ago", "5d ago". Falls back to a short date past 14 days. */
+export function timeAgo(iso, now = Date.now()) {
+ if (!iso) return '';
+ const t = new Date(iso).getTime();
+ if (Number.isNaN(t)) return '';
+ const s = Math.max(0, Math.floor((now - t) / 1000));
+ if (s < 60) return 'just now';
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
+ if (s < 14 * 86400) return `${Math.floor(s / 86400)}d ago`;
+ return formatDateShort(iso);
+}
+
+/** HTML-escape for interpolating remote strings into innerHTML templates. */
+export function escapeHtml(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+/**
+ * Downsample a numeric series to at most `max` points, always keeping the
+ * final point (sparklines care most about where the line ends).
+ */
+export function downsample(series, max) {
+ if (!Array.isArray(series) || series.length <= max) return series || [];
+ const step = (series.length - 1) / (max - 1);
+ const out = [];
+ for (let i = 0; i < max; i++) out.push(series[Math.round(i * step)]);
+ return out;
+}
diff --git a/tests/x402-ring-tick.test.js b/tests/x402-ring-tick.test.js
index f871f24c4..d0da146cb 100644
--- a/tests/x402-ring-tick.test.js
+++ b/tests/x402-ring-tick.test.js
@@ -169,9 +169,10 @@ describe('ringTickConfig', () => {
const c = ringTickConfig();
expect(c.enabled).toBe(true);
expect(c.calls).toBe(3);
- expect(c.settleEveryN).toBe(5);
- expect(c.tickCapAtomic).toBe(1_100_000);
- expect(c.dailyCapAtomic).toBe(50_000_000);
+ // settle every tick — the ~$50k/day throughput default (1440 ticks × $35 settle).
+ expect(c.settleEveryN).toBe(1);
+ expect(c.tickCapAtomic).toBe(40_000_000);
+ expect(c.dailyCapAtomic).toBe(60_000_000_000);
});
it('X402_RING_TICK_ENABLED=false disables it; other values keep it on', () => {