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
Market data: deepen keyless failover for prices, charts, derivatives, and mood
nirholas1f6708a04290
diff --git a/api/_lib/hyperliquid.js b/api/_lib/hyperliquid.jsnew file mode 100644index 000000000..e90579f7f--- /dev/null+++ b/api/_lib/hyperliquid.js@@ -0,0 +1,92 @@+// Hyperliquid public info API (keyless): perpetual-futures market data from+// the largest perp DEX. One POST endpoint serves every read; this module wraps+// the `metaAndAssetCtxs` snapshot (mark price, funding, open interest, 24h+// notional volume per listed perp) and normalizes it to the exact ticker row+// shape /api/coin/derivatives emits, so it can stand in for CoinGecko's+// derivatives feed when that upstream is down.+//+// Verified reachable from US datacenter IPs (unlike Binance/Bybit/OKX, which+// geo-block them; see the note in api/_lib/sol-price.js). No key, no account.++const HL_INFO_URL = 'https://api.hyperliquid.xyz/info';++const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+};++/**+ * POST a query to the Hyperliquid info endpoint.+ * @param {object} body e.g. { type: 'metaAndAssetCtxs' }+ * @param {{ timeoutMs?: number }} [opts]+ */+export async function hlInfo(body, { timeoutMs = 8000 } = {}) {+ const res = await fetch(HL_INFO_URL, {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!res.ok) {+ const err = new Error(`hyperliquid ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++/**+ * Zip the `metaAndAssetCtxs` response ([meta, assetCtxs], index-aligned) into+ * derivatives ticker rows matching api/coin/derivatives.js:+ * { market, symbol, index_id, price, change_24h, funding_rate,+ * open_interest, volume_24h }+ *+ * Unit notes, pinned by tests:+ * - Hyperliquid funding is an HOURLY decimal rate; CoinGecko's derivatives+ * rows quote the venue's 8h funding as a percentage, so this converts to an+ * 8h-equivalent percent (rate * 8 * 100) to keep the column comparable.+ * - openInterest is in base-asset units; rows carry USD notional, so it is+ * multiplied by the mark price.+ * - Delisted assets and assets without a positive mark price are dropped.+ *+ * @param {[{ universe: Array<{name:string, isDelisted?:boolean}> }, Array<object>]} payload+ * @returns {Array<object>} rows sorted by 24h volume desc+ */+export function normalizeHyperliquidPerps(payload) {+ const universe = Array.isArray(payload?.[0]?.universe) ? payload[0].universe : [];+ const ctxs = Array.isArray(payload?.[1]) ? payload[1] : [];+ const rows = [];+ for (let i = 0; i < universe.length && i < ctxs.length; i++) {+ const asset = universe[i];+ const ctx = ctxs[i];+ if (!asset?.name || asset.isDelisted) continue;+ const price = num(ctx?.markPx);+ if (!(price > 0)) continue;+ const prevDay = num(ctx?.prevDayPx);+ const funding = num(ctx?.funding);+ const oiCoins = num(ctx?.openInterest);+ rows.push({+ market: 'Hyperliquid',+ symbol: `${asset.name}-USD`,+ index_id: asset.name,+ price,+ change_24h: prevDay > 0 ? ((price / prevDay) - 1) * 100 : null,+ funding_rate: funding != null ? funding * 8 * 100 : null,+ open_interest: oiCoins != null ? oiCoins * price : null,+ volume_24h: num(ctx?.dayNtlVlm),+ });+ }+ return rows.sort((a, b) => (b.volume_24h ?? 0) - (a.volume_24h ?? 0));+}++/**+ * Live Hyperliquid perp tickers in the /api/coin/derivatives row shape.+ * @returns {Promise<Array<object>>}+ * @throws when the API is unreachable or returns an empty universe.+ */+export async function fetchHyperliquidPerps() {+ const payload = await hlInfo({ type: 'metaAndAssetCtxs' });+ const rows = normalizeHyperliquidPerps(payload);+ if (!rows.length) throw new Error('hyperliquid returned no perps');+ return rows;+}diff --git a/api/_lib/market-fallbacks.js b/api/_lib/market-fallbacks.jsindex 095e1b389..fd30b9b7c 100644--- a/api/_lib/market-fallbacks.js+++ b/api/_lib/market-fallbacks.js@@ -42,6 +42,60 @@ const asPrice = (v) => {return Number.isFinite(n) && n > 0 ? n : null;};+// ── Exchange tickers for the headline assets ─────────────────────────────────+// US-datacenter-safe exchange APIs only: Binance, Bybit and OKX geo-block US+// datacenter IPs (Cloud Run us-central1 gets a "restricted location" error+// body, see the note in api/_lib/sol-price.js), which would make them+// permanently dead rungs. Kraken, Coinbase Exchange and Bitfinex all serve+// datacenter traffic. Only the CoinGecko ids the platform actually prices by+// id are mapped; an unmapped id just skips the exchange rungs.++export const EXCHANGE_PAIRS = {+ bitcoin: { kraken: 'XBTUSD', coinbase: 'BTC-USD', bitfinex: 'tBTCUSD' },+ ethereum: { kraken: 'ETHUSD', coinbase: 'ETH-USD', bitfinex: 'tETHUSD' },+ solana: { kraken: 'SOLUSD', coinbase: 'SOL-USD', bitfinex: 'tSOLUSD' },+};++// Kraken /0/public/Ticker: the result key is Kraken's internal pair name+// (XBTUSD comes back as XXBTZUSD), so take the first result entry rather than+// re-deriving their aliasing. `c` is [last trade price, lot volume].+export function parseKrakenTicker(raw) {+ const pair = Object.values(raw?.result || {})[0];+ return asPrice(pair?.c?.[0]);+}++/** Coinbase /v2/prices/:pair/spot → { data: { amount } }. */+export function parseCoinbaseSpot(raw) {+ return asPrice(raw?.data?.amount);+}++/** Bitfinex v2 ticker array: index 6 is LAST_PRICE. */+export function parseBitfinexTicker(raw) {+ return asPrice(Array.isArray(raw) ? raw[6] : null);+}++function exchangePriceProviders(id) {+ const pairs = EXCHANGE_PAIRS[id];+ if (!pairs) return [];+ return [+ {+ name: 'kraken',+ url: `https://api.kraken.com/0/public/Ticker?pair=${pairs.kraken}`,+ parse: async (r) => parseKrakenTicker(await r.json()),+ },+ {+ name: 'coinbase',+ url: `https://api.coinbase.com/v2/prices/${pairs.coinbase}/spot`,+ parse: async (r) => parseCoinbaseSpot(await r.json()),+ },+ {+ name: 'bitfinex',+ url: `https://api-pub.bitfinex.com/v2/ticker/${pairs.bitfinex}`,+ parse: async (r) => parseBitfinexTicker(await r.json()),+ },+ ];+}+// ── Spot USD price by CoinGecko id ───────────────────────────────────────────// For the endpoints that price a headline asset (ETH for /gas, BTC for// /exchanges) via CoinGecko /simple/price. Both those reads were single-source;@@ -50,7 +104,10 @@ const asPrice = (v) => {// or throws when both are down; callers price best-effort and tolerate a throw./**- * Live USD spot price for a CoinGecko coin id, CoinGecko → DefiLlama failover.+ * Live USD spot price for a CoinGecko coin id. CoinGecko → DefiLlama failover,+ * extended with Kraken → Coinbase → Bitfinex exchange tickers for the headline+ * assets in EXCHANGE_PAIRS, so BTC/ETH/SOL pricing survives even a+ * simultaneous aggregator outage.* @param {string} coingeckoId e.g. "ethereum", "bitcoin", "solana"* @returns {Promise<number>} positive USD price* @throws when every free source is down.@@ -71,6 +128,7 @@ export async function fetchCoinPriceUsd(coingeckoId) {url: `https://coins.llama.fi/prices/current/coingecko:${id}`,parse: async (r) => asPrice((await r.json())?.coins?.[`coingecko:${id}`]?.price),},+ ...exchangePriceProviders(id),],{ timeoutMs: 6000, label: `price:${id}` },);@@ -271,3 +329,85 @@ export async function fetchMarketsTable({ page, perPage, category }) {const { value, source } = await fetchFirst(providers, { timeoutMs: 10_000, label: 'markets-table' });return { rows: value, source };}++// ── Price-series (chart) failover ────────────────────────────────────────────+// Backs up CoinGecko /market_chart for the /coin/:id line chart, which renders+// close prices as [[timestamp_ms, price], ...]. Exchange candle endpoints+// (Kraken OHLC, Coinbase Exchange candles) cover the EXCHANGE_PAIRS majors:+// when CoinGecko is rate-limited, the BTC/ETH/SOL charts stay live instead of+// blanking. Long-tail coins have no exchange mapping and keep CoinGecko as+// their only source, exactly as before.++// Kraken OHLC interval (minutes) per chart window. Kraken returns up to 720+// candles per interval, so every window fits in one request: 5m covers 2.5d,+// 1h covers 30d, 4h covers 120d, 1d covers ~2y.+const KRAKEN_INTERVAL = { 1: 5, 7: 60, 30: 240, 90: 1440, 365: 1440 };++// Coinbase Exchange granularity (seconds) per window. Their API allows only+// {60,300,900,3600,21600,86400} and at most 300 candles per request, so the+// 365d window cannot be served in one call and is left to Kraken.+const COINBASE_GRANULARITY = { 1: 300, 7: 3600, 30: 21600, 90: 86400 };++/**+ * Kraken /0/public/OHLC → [[timestamp_ms, close], ...] clipped to the window.+ * Rows are [t_s, open, high, low, close, vwap, volume, count], oldest first.+ */+export function normalizeKrakenChart(raw, days, now = Date.now()) {+ const rows = Object.values(raw?.result || {}).find(Array.isArray);+ if (!Array.isArray(rows)) return null;+ const cutoff = now - days * 86_400_000;+ const out = rows+ .map((r) => [Number(r?.[0]) * 1000, Number(r?.[4])])+ .filter(([t, c]) => Number.isFinite(t) && t >= cutoff && Number.isFinite(c) && c > 0);+ return out.length ? out : null;+}++/**+ * Coinbase Exchange /products/:pair/candles → [[timestamp_ms, close], ...].+ * Rows are [t_s, low, high, open, close, volume], newest first.+ */+export function normalizeCoinbaseChart(raw, days, now = Date.now()) {+ if (!Array.isArray(raw)) return null;+ const cutoff = now - days * 86_400_000;+ const out = raw+ .map((r) => [Number(r?.[0]) * 1000, Number(r?.[4])])+ .filter(([t, c]) => Number.isFinite(t) && t >= cutoff && Number.isFinite(c) && c > 0)+ .sort((a, b) => a[0] - b[0]);+ return out.length ? out : null;+}++/**+ * Exchange-candle backup for the coin price chart. Returns [[timestamp_ms,+ * close], ...] oldest-first, or null when the id has no exchange mapping or+ * every exchange is down. Never throws: this only runs when CoinGecko already+ * failed, and the caller wants that original error if the backup misses too.+ * @param {string} id CoinGecko coin id (must be in EXCHANGE_PAIRS)+ * @param {number} days chart window: 1 | 7 | 30 | 90 | 365+ */+export async function fetchExchangeChart(id, days) {+ const pairs = EXCHANGE_PAIRS[id];+ if (!pairs || !KRAKEN_INTERVAL[days]) return null;+ const providers = [+ {+ name: 'kraken-ohlc',+ url: `https://api.kraken.com/0/public/OHLC?pair=${pairs.kraken}&interval=${KRAKEN_INTERVAL[days]}`,+ parse: async (r) => normalizeKrakenChart(await r.json(), days),+ },+ ];+ if (COINBASE_GRANULARITY[days]) {+ providers.push({+ name: 'coinbase-candles',+ url:+ `https://api.exchange.coinbase.com/products/${pairs.coinbase}/candles` ++ `?granularity=${COINBASE_GRANULARITY[days]}`,+ init: { headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' } },+ parse: async (r) => normalizeCoinbaseChart(await r.json(), days),+ });+ }+ try {+ const { value } = await fetchFirst(providers, { timeoutMs: 8000, label: `chart:${id}` });+ return value;+ } catch {+ return null;+ }+}diff --git a/api/_lib/market/token-market.js b/api/_lib/market/token-market.jsindex 583135d40..d243e41ce 100644--- a/api/_lib/market/token-market.js+++ b/api/_lib/market/token-market.js@@ -244,7 +244,19 @@ async function fromLlamaCoins(mint) {return shape({ price_usd: price, decimals: num(c?.decimals) ?? 6 }, 'llama');}-const SOURCES = [fromBirdeye, fromDexScreener, fromGeckoTerminal, fromLlamaCoins];+// Raydium v3 price API (keyless) — price-only like the Llama rung, and the+// narrowest coverage of the chain (only tokens with a Raydium pool resolve),+// so it sits last. Its value is independence: Raydium indexes its own AMM+// on-chain, so it keeps Solana majors and migrated pump.fun tokens priced+// through a simultaneous Birdeye/DexScreener/GeckoTerminal/Llama outage.+async function fromRaydium(mint) {+ const data = await fetchJson(`https://api-v3.raydium.io/mint/price?mints=${mint}`);+ const price = num(data?.data?.[mint]);+ if (!(price > 0)) return null;+ return shape({ price_usd: price }, 'raydium');+}++const SOURCES = [fromBirdeye, fromDexScreener, fromGeckoTerminal, fromLlamaCoins, fromRaydium];// Store a value in the per-instance L1 cache (with the bounded-size eviction the// fetch path uses) and return it. Shared by the live, L2-hit, and lock-loserdiff --git a/api/_lib/service-catalog/services/market-mood.js b/api/_lib/service-catalog/services/market-mood.jsindex 03fe162bc..cf2e9526e 100644--- a/api/_lib/service-catalog/services/market-mood.js+++ b/api/_lib/service-catalog/services/market-mood.js@@ -18,7 +18,7 @@ export default {acceptsBuilder: 'standard',serviceName: 'three.ws Market Mood',tags: ['sentiment', 'fear-greed', 'news', 'market-data'],- description: 'three.ws Market Mood Index — pay $0.002 USDC per call for a composite market-mood reading no single index gives you. Blends the Crypto Fear & Greed index (with its 24 h delta) with live lexicon sentiment scored across the newest headlines from 192 crypto publisher feeds into one 0–100 mood score and label, and returns both components so you can see when positioning (Fear & Greed) and narrative (news tone) disagree — the divergence signal. Includes the bullish and bearish headlines currently driving the news component, with links. Both components must be live or the call refuses before settlement.',+ description: 'three.ws Market Mood Index — pay $0.002 USDC per call for a composite market-mood reading no single index gives you. Blends the Crypto Fear & Greed index (with its 24 h delta) with live lexicon sentiment scored across the newest headlines from 192 crypto publisher feeds into one 0–100 mood score and label, and returns both components so you can see when positioning (Fear & Greed) and narrative (news tone) disagree — the divergence signal. Includes the bullish and bearish headlines currently driving the news component, with links, plus a best-effort volatility read: Deribit DVOL implied-volatility index values for BTC and ETH with their 24 h change (null if Deribit is unreachable; volatility never gates the call). Both mood components must be live or the call refuses before settlement.',input: {},inputSchema: {type: 'object',@@ -31,6 +31,11 @@ export default {components: {fear_greed: { value: 66, label: 'Greed', change_24h: 3 },news: { score: 0.18, label: 'positive', articles_scored: 120, positive: 41, negative: 22, neutral: 57 },+ volatility: {+ index: 'DVOL',+ btc: { value: 36.2, change_24h: -0.4 },+ eth: { value: 58.9, change_24h: 1.1 },+ },},drivers: {bullish: [{ title: 'Example bullish headline', source: 'Example Source', link: 'https://example.com/a' }],diff --git a/api/coin/derivatives.js b/api/coin/derivatives.jsindex e53a7c492..ad689bc98 100644--- a/api/coin/derivatives.js+++ b/api/coin/derivatives.js@@ -15,6 +15,7 @@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 { fetchHyperliquidPerps } from '../_lib/hyperliquid.js';let _cache = null; // { value, expiresAt }let _exCache = null; // { value, expiresAt }@@ -29,31 +30,44 @@ const num = (v) => {// Exported for the paid Market Data API (api/_lib/market-data/) — the x402// market-derivatives endpoint sells the same perp table this page renders.+//+// CoinGecko (cross-venue) is primary; when it is down or rate-limited the+// table falls back to Hyperliquid's keyless info API — one venue instead of+// dozens, but a live perp table (price/funding/OI/volume for ~200 assets)+// beats a 502. `source` says which upstream answered.export async function buildDerivativeTickers() {const now = Date.now();if (_cache && _cache.expiresAt > now) return _cache.value;- const raw = await geckoFetch('/derivatives?include_tickers=unexpired', { ttlMs: TTL_MS });- const rows = Array.isArray(raw) ? raw : [];+ let tickers = [];+ let source = 'coingecko';+ try {+ const raw = await geckoFetch('/derivatives?include_tickers=unexpired', { ttlMs: TTL_MS });+ const rows = Array.isArray(raw) ? raw : [];+ tickers = rows+ .filter((t) => t && t.contract_type === 'perpetual')+ .map((t) => ({+ market: t.market || 'Unknown',+ symbol: t.symbol || '',+ index_id: t.index_id || null,+ price: num(t.price),+ change_24h: num(t.price_percentage_change_24h),+ funding_rate: num(t.funding_rate),+ open_interest: num(t.open_interest),+ volume_24h: num(t.volume_24h),+ }))+ .sort((a, b) => (b.volume_24h ?? 0) - (a.volume_24h ?? 0))+ .slice(0, 100);+ } catch {+ // fall through to the Hyperliquid backup below+ }++ if (!tickers.length) {+ tickers = (await fetchHyperliquidPerps()).slice(0, 100);+ source = 'hyperliquid';+ }- const tickers = rows- .filter((t) => t && t.contract_type === 'perpetual')- .map((t) => ({- market: t.market || 'Unknown',- symbol: t.symbol || '',- index_id: t.index_id || null,- price: num(t.price),- change_24h: num(t.price_percentage_change_24h),- funding_rate: num(t.funding_rate),- open_interest: num(t.open_interest),- volume_24h: num(t.volume_24h),- }))- .sort((a, b) => (b.volume_24h ?? 0) - (a.volume_24h ?? 0))- .slice(0, 100);-- if (!tickers.length) throw new Error('empty derivatives payload');-- const value = { tickers, updated_at: now };+ const value = { tickers, source, updated_at: now };_cache = { value, expiresAt: now + TTL_MS };return value;}diff --git a/api/coin/ohlc.js b/api/coin/ohlc.jsindex 137c6cf6e..c73d57ba5 100644--- a/api/coin/ohlc.js+++ b/api/coin/ohlc.js@@ -4,10 +4,17 @@// 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.+//+// When CoinGecko fails (its keyless tier 429s under load), the headline assets+// fall back to exchange candles (Kraken OHLC, then Coinbase Exchange) via+// fetchExchangeChart, so the BTC/ETH/SOL charts stay live through a CoinGecko+// outage. A 404 (unknown coin) never falls back: that is an answer, not an+// outage.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';+import { fetchExchangeChart } from '../_lib/market-fallbacks.js';export const VALID_DAYS = new Set([1, 7, 30, 90, 365]);@@ -15,10 +22,18 @@ export const VALID_DAYS = new Set([1, 7, 30, 90, 365]);// market-chart endpoint sells the same price series this page renders.// Callers must validate id/days first; a 404 from upstream carries err.status.export async function buildPriceChart(id, days) {- const raw = await geckoFetch(`/coins/${id}/market_chart?vs_currency=usd&days=${days}`, {- ttlMs: 120_000,- timeoutMs: 10_000,- });+ let raw;+ try {+ raw = await geckoFetch(`/coins/${id}/market_chart?vs_currency=usd&days=${days}`, {+ ttlMs: 120_000,+ timeoutMs: 10_000,+ });+ } catch (err) {+ if (err?.status === 404) throw err;+ const backup = await fetchExchangeChart(id, days);+ if (backup) return { data: backup, days };+ throw err;+ }const data = (raw?.prices || []).filter((p) => Array.isArray(p) && Number.isFinite(p[0]) && Number.isFinite(p[1])).map(([t, v]) => [Math.round(t), v]);diff --git a/api/x402/market-mood.js b/api/x402/market-mood.jsindex c97c51008..c03bbbde5 100644--- a/api/x402/market-mood.js+++ b/api/x402/market-mood.js@@ -12,6 +12,11 @@// in-repo news engine (api/_lib/news.js). Both components must be live or// the handler throws BEFORE settlement — a mood score with a dead component// would be fabricated, and the buyer is never charged for one.+//+// A third, best-effort enrichment rides along: Deribit's DVOL implied-+// volatility index for BTC and ETH (keyless public API). Volatility is NOT+// part of the mood blend and never gates settlement; when Deribit is down the+// field is null and the paid contract is otherwise unchanged.import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';@@ -106,13 +111,57 @@ async function fetchNewsMood() {};}+/**+ * Deribit DVOL rows ([[timestamp_ms, open, high, low, close], ...], oldest+ * first) → { value, change_24h } from the newest and oldest closes, or null+ * when the window is empty.+ */+export function summarizeDvol(rows) {+ const closes = (Array.isArray(rows) ? rows : [])+ .map((r) => Number(r?.[4]))+ .filter(Number.isFinite);+ if (!closes.length) return null;+ const value = closes[closes.length - 1];+ return {+ value: Number(value.toFixed(2)),+ change_24h: closes.length > 1 ? Number((value - closes[0]).toFixed(2)) : null,+ };+}++async function fetchDvol(currency) {+ const end = Date.now();+ const start = end - 24 * 3_600_000;+ const r = await fetch(+ `https://www.deribit.com/api/v2/public/get_volatility_index_data?currency=${currency}` ++ `&start_timestamp=${start}&end_timestamp=${end}&resolution=3600`,+ { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) },+ );+ if (!r.ok) throw new Error(`dvol ${r.status}`);+ return summarizeDvol((await r.json())?.result?.data);+}++// Best-effort: per-currency failures collapse to null and never reject, so a+// Deribit outage cannot fail (or refund) a call whose paid components are live.+async function fetchVolatility() {+ const [btc, eth] = await Promise.all(+ ['BTC', 'ETH'].map((c) => fetchDvol(c).catch(() => null)),+ );+ if (!btc && !eth) return null;+ return { index: 'DVOL', btc, eth };+}+async function loadMood() {const now = Date.now();if (_cache && _cache.expiresAt > now) return _cache.value;// Both components are required — Promise.all rejects if either is down and// the caller refunds. A one-legged "composite" would be a fabricated signal.- const [fng, news] = await Promise.all([fetchFearGreed(), fetchNewsMood()]);+ // fetchVolatility never rejects (best-effort enrichment, null on outage).+ const [fng, news, volatility] = await Promise.all([+ fetchFearGreed(),+ fetchNewsMood(),+ fetchVolatility(),+ ]);// News score is -1..1; map to 0..100 and blend with Fear & Greed.const newsIndex = ((news.score + 1) / 2) * 100;@@ -141,6 +190,7 @@ async function loadMood() {negative: news.negative,neutral: news.neutral,},+ volatility,},drivers: news.drivers,};@@ -186,6 +236,27 @@ export const OUTPUT_SCHEMA = {neutral: { type: 'integer' },},},+ // Best-effort enrichment, not in `required`: null when Deribit is down.+ volatility: {+ type: ['object', 'null'],+ properties: {+ index: { type: 'string', enum: ['DVOL'] },+ btc: {+ type: ['object', 'null'],+ properties: {+ value: { type: 'number' },+ change_24h: { type: ['number', 'null'] },+ },+ },+ eth: {+ type: ['object', 'null'],+ properties: {+ value: { type: 'number' },+ change_24h: { type: ['number', 'null'] },+ },+ },+ },+ },},},drivers: {diff --git a/tests/hyperliquid.test.js b/tests/hyperliquid.test.jsnew file mode 100644index 000000000..06726297f--- /dev/null+++ b/tests/hyperliquid.test.js@@ -0,0 +1,92 @@+// Hyperliquid perp normalizer — unit tests.+//+// Pins the metaAndAssetCtxs → derivatives-ticker-row mapping (fixture shaped+// like the real API response) and the unit conversions the comparability of+// the /derivatives table depends on: hourly funding decimal → 8h-equivalent+// percent, and base-asset open interest → USD notional.++import { describe, it, expect } from 'vitest';+import { normalizeHyperliquidPerps } from '../api/_lib/hyperliquid.js';++const FIXTURE = [+ {+ universe: [+ { szDecimals: 5, name: 'BTC', maxLeverage: 40 },+ { szDecimals: 4, name: 'ETH', maxLeverage: 25 },+ { szDecimals: 1, name: 'MATIC', maxLeverage: 20, isDelisted: true },+ { szDecimals: 2, name: 'SOL', maxLeverage: 20 },+ ],+ },+ [+ {+ markPx: '64000',+ prevDayPx: '62500',+ funding: '0.0000125',+ openInterest: '10000',+ dayNtlVlm: '2500000000',+ },+ {+ markPx: '3200',+ prevDayPx: '3300',+ funding: '-0.00002',+ openInterest: '250000',+ dayNtlVlm: '900000000',+ },+ // delisted MATIC still occupies its index slot in the ctx array+ { markPx: '0.4', prevDayPx: '0.4', funding: '0', openInterest: '0', dayNtlVlm: '0' },+ {+ markPx: '150',+ prevDayPx: '150',+ funding: '0.0000125',+ openInterest: '2000000',+ dayNtlVlm: '3100000000',+ },+ ],+];++describe('normalizeHyperliquidPerps', () => {+ it('maps assets to derivatives ticker rows, volume-sorted, delisted dropped', () => {+ const rows = normalizeHyperliquidPerps(FIXTURE);+ expect(rows.map((r) => r.index_id)).toEqual(['SOL', 'BTC', 'ETH']);+ expect(rows.every((r) => r.market === 'Hyperliquid')).toBe(true);+ expect(rows[1].symbol).toBe('BTC-USD');+ });++ it('converts units: hourly funding → 8h percent, OI coins → USD notional', () => {+ const btc = normalizeHyperliquidPerps(FIXTURE).find((r) => r.index_id === 'BTC');+ expect(btc.price).toBe(64000);+ expect(btc.change_24h).toBeCloseTo(2.4, 5); // 64000/62500 - 1 = +2.4%+ expect(btc.funding_rate).toBeCloseTo(0.01, 6); // 0.0000125/h ≈ 0.01% per 8h+ expect(btc.open_interest).toBe(640_000_000); // 10k BTC × $64k+ expect(btc.volume_24h).toBe(2_500_000_000);+ });++ it('null-safes a partial ctx and keeps a negative funding sign', () => {+ const eth = normalizeHyperliquidPerps(FIXTURE).find((r) => r.index_id === 'ETH');+ expect(eth.change_24h).toBeCloseTo(-3.0303, 3);+ expect(eth.funding_rate).toBeCloseTo(-0.016, 6);++ const rows = normalizeHyperliquidPerps([+ { universe: [{ name: 'X' }] },+ [{ markPx: '2' }],+ ]);+ expect(rows).toEqual([+ {+ market: 'Hyperliquid',+ symbol: 'X-USD',+ index_id: 'X',+ price: 2,+ change_24h: null,+ funding_rate: null,+ open_interest: null,+ volume_24h: null,+ },+ ]);+ });++ it('returns [] on malformed or empty payloads (assets without a mark price dropped)', () => {+ expect(normalizeHyperliquidPerps(null)).toEqual([]);+ expect(normalizeHyperliquidPerps([{}, []])).toEqual([]);+ expect(normalizeHyperliquidPerps([{ universe: [{ name: 'Y' }] }, [{ markPx: '0' }]])).toEqual([]);+ });+});diff --git a/tests/market-fallbacks.test.js b/tests/market-fallbacks.test.jsindex e448b48bd..b597642b1 100644--- a/tests/market-fallbacks.test.js+++ b/tests/market-fallbacks.test.js@@ -14,6 +14,12 @@ import {normalizePaprikaGlobal,normalizeLoreGlobal,normalizeGeckoRow,+ parseKrakenTicker,+ parseCoinbaseSpot,+ parseBitfinexTicker,+ normalizeKrakenChart,+ normalizeCoinbaseChart,+ EXCHANGE_PAIRS,} from '../api/_lib/market-fallbacks.js';describe('global stats normalizers', () => {@@ -123,3 +129,72 @@ describe('markets table row normalizer', () => {expect(row.sparkline).toEqual([]);});});++describe('exchange spot ticker parsers', () => {+ it('Kraken ticker → last trade price under Kraken\'s internal pair alias', () => {+ // Querying XBTUSD comes back keyed XXBTZUSD; the parser must not depend+ // on knowing the alias.+ const raw = { error: [], result: { XXBTZUSD: { a: ['64000.1'], c: ['63980.5', '0.01'] } } };+ expect(parseKrakenTicker(raw)).toBeCloseTo(63980.5);+ });++ it('Coinbase spot → data.amount', () => {+ expect(parseCoinbaseSpot({ data: { base: 'BTC', currency: 'USD', amount: '64010.55' } })).toBeCloseTo(64010.55);+ });++ it('Bitfinex ticker array → LAST_PRICE at index 6', () => {+ const t = [63900, 12.5, 63901, 8.1, -120, -0.0019, 63975.2, 480.7, 64890, 63500];+ expect(parseBitfinexTicker(t)).toBeCloseTo(63975.2);+ });++ it('misses (null) on empty or malformed payloads', () => {+ expect(parseKrakenTicker({ error: ['EQuery:Unknown asset pair'], result: {} })).toBeNull();+ expect(parseCoinbaseSpot({})).toBeNull();+ expect(parseBitfinexTicker(['error'])).toBeNull();+ expect(parseBitfinexTicker(null)).toBeNull();+ });++ it('maps exactly the headline assets, all three exchanges each', () => {+ for (const id of ['bitcoin', 'ethereum', 'solana']) {+ expect(Object.keys(EXCHANGE_PAIRS[id]).sort()).toEqual(['bitfinex', 'coinbase', 'kraken']);+ }+ });+});++describe('exchange candle chart normalizers', () => {+ const now = 1_784_467_200_000; // fixed "now" so window clipping is deterministic+ const hour = 3_600_000;++ it('Kraken OHLC → [[ts_ms, close]] clipped to the window, oldest first', () => {+ const rows = [+ [(now - 30 * hour) / 1000, '100', '110', '95', '105', '102', '10', 5], // outside 1d window+ [(now - 20 * hour) / 1000, '105', '112', '101', '108', '106', '12', 6],+ [(now - 2 * hour) / 1000, '108', '115', '107', '111', '110', '9', 4],+ ];+ const out = normalizeKrakenChart({ result: { XXBTZUSD: rows, last: 12345 } }, 1, now);+ expect(out).toEqual([+ [now - 20 * hour, 108],+ [now - 2 * hour, 111],+ ]);+ });++ it('Coinbase candles → newest-first input re-sorted oldest first', () => {+ const raw = [+ [(now - 1 * hour) / 1000, 107, 112, 108, 111, 20], // [t, low, high, open, close, vol]+ [(now - 2 * hour) / 1000, 101, 109, 102, 108, 15],+ [(now - 50 * hour) / 1000, 90, 100, 92, 99, 30], // outside 1d window+ ];+ const out = normalizeCoinbaseChart(raw, 1, now);+ expect(out).toEqual([+ [now - 2 * hour, 108],+ [now - 1 * hour, 111],+ ]);+ });++ it('misses (null) when every candle is outside the window or malformed', () => {+ expect(normalizeKrakenChart({ result: {} }, 1, now)).toBeNull();+ expect(normalizeKrakenChart(null, 1, now)).toBeNull();+ expect(normalizeCoinbaseChart({ message: 'NotFound' }, 1, now)).toBeNull();+ expect(normalizeCoinbaseChart([[(now - 100 * hour) / 1000, 1, 2, 1, 2, 3]], 1, now)).toBeNull();+ });+});diff --git a/tests/market-mood-dvol.test.js b/tests/market-mood-dvol.test.jsnew file mode 100644index 000000000..690ff4b03--- /dev/null+++ b/tests/market-mood-dvol.test.js@@ -0,0 +1,51 @@+// Market Mood volatility enrichment — unit tests for the DVOL summarizer and+// the schema guarantee that volatility stays OPTIONAL (a Deribit outage must+// never make a paid response schema-invalid, because the component is+// best-effort and non-gating by contract).++import { describe, it, expect } from 'vitest';++// Discovery env must be set BEFORE the paid-endpoint stack loads — same stub+// set tests/market-data-api.test.js uses.+Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',+ X402_PAY_TO_SOLANA: 'So11111111111111111111111111111111111111112',+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ X402_ASSET_MINT_SOLANA: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ X402_ASSET_ADDRESS_ARBITRUM: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',+ X402_MAX_AMOUNT_REQUIRED: '1000',+ X402_FEE_PAYER_SOLANA: 'So11111111111111111111111111111111111111112',+});++const { summarizeDvol, OUTPUT_SCHEMA } = await import('../api/x402/market-mood.js');++describe('summarizeDvol', () => {+ it('takes the newest close and the 24h change from the oldest close', () => {+ const rows = [+ [1_784_380_000_000, 36.19, 36.38, 36.15, 36.34],+ [1_784_383_600_000, 36.34, 36.34, 36.25, 36.25],+ [1_784_387_200_000, 36.25, 36.35, 36.24, 35.91],+ ];+ expect(summarizeDvol(rows)).toEqual({ value: 35.91, change_24h: -0.43 });+ });++ it('a single row yields a value with a null change', () => {+ expect(summarizeDvol([[1, 36, 36, 36, 36.5]])).toEqual({ value: 36.5, change_24h: null });+ });++ it('misses (null) on empty or malformed windows', () => {+ expect(summarizeDvol([])).toBeNull();+ expect(summarizeDvol(null)).toBeNull();+ expect(summarizeDvol([[1, 2, 3, 4, 'x']])).toBeNull();+ });+});++describe('volatility stays optional in the paid contract', () => {+ it('is declared nullable and NOT required at either level', () => {+ const components = OUTPUT_SCHEMA.properties.components;+ expect(components.required).toEqual(['fear_greed', 'news']);+ expect(components.properties.volatility.type).toContain('null');+ expect(OUTPUT_SCHEMA.required).not.toContain('volatility');+ });+});