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(derivatives): add Deribit options and perp data beside Hyperliquid, extend Jupiter lite surface

nirholas6b478b9011ba
diff --git a/api/_lib/deribit.js b/api/_lib/deribit.js
new file mode 100644
index 000000000..7184290f7
--- /dev/null
+++ b/api/_lib/deribit.js
@@ -0,0 +1,218 @@
+// Deribit public API (keyless): options + futures market data from the largest
+// crypto options venue. Every read here is a GET against
+// www.deribit.com/api/v2/public/* with no key and no account, wrapped into the
+// summary /api/coin/derivatives attaches next to its perp table: index prices,
+// perpetual tickers (mark, funding, open interest, 24h volume), and a per-asset
+// options aggregate (contract count, USD open interest, USD volume, put/call
+// ratio) that no other source on that endpoint provides.
+//
+// Verified reachable from US datacenter IPs (unlike Binance/Bybit/OKX, which
+// geo-block them; see the note in api/_lib/sol-price.js).
+//
+// Instrument map, pinned by the fixtures in tests/api/deribit.test.js:
+// - BTC and ETH trade as coin-settled (inverse) instruments under their own
+// currency: BTC-PERPETUAL, ETH-PERPETUAL, and BTC-*/ETH-* options.
+// - SOL trades USDC-settled (linear): SOL_USDC-PERPETUAL, and SOL_USDC-*
+// options listed under currency=USDC (currency=SOL returns nothing).
+
+const DERIBIT_BASE = 'https://www.deribit.com/api/v2/public';
+
+const num = (v) => {
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+};
+
+// One entry per perp we track: the venue instrument, the index asset it rides,
+// and whether it is linear (USDC-settled, open_interest in base units) or
+// inverse (coin-settled, open_interest already in USD).
+export const DERIBIT_PERPS = [
+ { instrument: 'BTC-PERPETUAL', asset: 'BTC', linear: false },
+ { instrument: 'ETH-PERPETUAL', asset: 'ETH', linear: false },
+ { instrument: 'SOL_USDC-PERPETUAL', asset: 'SOL', linear: true },
+];
+
+// Where each asset's options book lives: BTC/ETH under their own currency,
+// SOL under the shared USDC (linear) listing.
+export const DERIBIT_OPTION_BOOKS = [
+ { currency: 'BTC', asset: 'BTC' },
+ { currency: 'ETH', asset: 'ETH' },
+ { currency: 'USDC', asset: 'SOL' },
+];
+
+/**
+ * GET a public Deribit JSON-RPC method and unwrap the envelope.
+ * Deribit signals bad params with HTTP 200 + an `error` object, so both the
+ * HTTP status and the RPC envelope are checked.
+ * @param {string} rpcMethod e.g. 'ticker'
+ * @param {Record<string, string|number>} [params]
+ * @param {{ timeoutMs?: number }} [opts]
+ * @returns {Promise<any>} the envelope's `result`
+ */
+export async function deribitGet(rpcMethod, params = {}, { timeoutMs = 8000 } = {}) {
+ const u = new URL(`${DERIBIT_BASE}/${rpcMethod}`);
+ for (const [k, v] of Object.entries(params)) u.searchParams.set(k, String(v));
+ const res = await fetch(u, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!res.ok) {
+ const err = new Error(`deribit ${res.status}`);
+ err.status = res.status;
+ throw err;
+ }
+ const body = await res.json();
+ if (body?.error) {
+ throw new Error(`deribit rpc ${body.error.code}: ${body.error.message || 'error'}`);
+ }
+ return body?.result;
+}
+
+/**
+ * Map one `public/ticker` result onto the /api/coin/derivatives ticker row
+ * shape: { market, symbol, index_id, price, change_24h, funding_rate,
+ * open_interest, volume_24h }.
+ *
+ * Unit notes, pinned by tests:
+ * - `funding_8h` is a decimal 8h rate; rows quote 8h funding as a percentage,
+ * so it is multiplied by 100.
+ * - `stats.price_change` is already a 24h percentage.
+ * - Inverse perps report `open_interest` in USD; linear (USDC-settled) perps
+ * report base units, converted to USD via the mark price.
+ * - A ticker without a positive mark price yields null (instrument halted or
+ * payload malformed).
+ *
+ * @param {object} ticker raw `public/ticker` result
+ * @param {{ instrument: string, asset: string, linear: boolean }} cfg
+ * @returns {object|null}
+ */
+export function normalizeDeribitPerp(ticker, { instrument, asset, linear }) {
+ const price = num(ticker?.mark_price);
+ if (!(price > 0)) return null;
+ const funding = num(ticker?.funding_8h);
+ const oi = num(ticker?.open_interest);
+ return {
+ market: 'Deribit',
+ symbol: instrument,
+ index_id: asset,
+ price,
+ change_24h: num(ticker?.stats?.price_change),
+ funding_rate: funding != null ? funding * 100 : null,
+ open_interest: oi != null ? (linear ? oi * price : oi) : null,
+ volume_24h: num(ticker?.stats?.volume_usd),
+ };
+}
+
+/**
+ * Aggregate a `get_book_summary_by_currency?kind=option` payload into one
+ * options summary for `asset`: contract count, USD open interest, USD 24h
+ * volume, and the open-interest put/call ratio.
+ *
+ * Rows are filtered by `base_currency` so the shared USDC book yields a clean
+ * SOL aggregate. Option `open_interest` is in base-asset units and converted
+ * to USD via each row's `underlying_price`; `volume_usd` is summed as-is. The
+ * put/call split keys off the instrument-name suffix (-C / -P).
+ *
+ * @param {Array<object>} rows raw book-summary rows
+ * @param {string} asset base currency to keep, e.g. 'BTC'
+ * @returns {{ asset: string, contracts: number, open_interest: number,
+ * volume_24h: number, put_call_ratio: number|null }}
+ */
+export function summarizeDeribitOptions(rows, asset) {
+ let contracts = 0;
+ let oiUsd = 0;
+ let volUsd = 0;
+ let callOi = 0;
+ let putOi = 0;
+ for (const row of Array.isArray(rows) ? rows : []) {
+ if (row?.base_currency !== asset || typeof row?.instrument_name !== 'string') continue;
+ contracts += 1;
+ const oi = num(row.open_interest);
+ const underlying = num(row.underlying_price);
+ if (oi != null && underlying != null) {
+ oiUsd += oi * underlying;
+ if (row.instrument_name.endsWith('-C')) callOi += oi;
+ else if (row.instrument_name.endsWith('-P')) putOi += oi;
+ }
+ volUsd += num(row.volume_usd) ?? 0;
+ }
+ return {
+ asset,
+ contracts,
+ open_interest: oiUsd,
+ volume_24h: volUsd,
+ put_call_ratio: callOi > 0 ? putOi / callOi : null,
+ };
+}
+
+/**
+ * Live perp rows for every tracked instrument, volume-sorted. One dead
+ * instrument does not sink the rest (allSettled), but an empty result throws
+ * so callers can fail over.
+ * @returns {Promise<Array<object>>}
+ */
+export async function fetchDeribitPerps() {
+ const settled = await Promise.allSettled(
+ DERIBIT_PERPS.map((cfg) => deribitGet('ticker', { instrument_name: cfg.instrument })),
+ );
+ const rows = [];
+ for (let i = 0; i < settled.length; i++) {
+ if (settled[i].status !== 'fulfilled') continue;
+ const row = normalizeDeribitPerp(settled[i].value, DERIBIT_PERPS[i]);
+ if (row) rows.push(row);
+ }
+ if (!rows.length) throw new Error('deribit returned no perps');
+ return rows.sort((a, b) => (b.volume_24h ?? 0) - (a.volume_24h ?? 0));
+}
+
+/**
+ * USD index prices for the tracked assets: { BTC, ETH, SOL }, null for any
+ * index Deribit could not serve.
+ * @returns {Promise<Record<string, number|null>>}
+ */
+export async function fetchDeribitIndexes() {
+ const assets = ['BTC', 'ETH', 'SOL'];
+ const settled = await Promise.allSettled(
+ assets.map((a) => deribitGet('get_index_price', { index_name: `${a.toLowerCase()}_usd` })),
+ );
+ const out = {};
+ for (let i = 0; i < assets.length; i++) {
+ out[assets[i]] =
+ settled[i].status === 'fulfilled' ? num(settled[i].value?.index_price) : null;
+ }
+ return out;
+}
+
+/**
+ * Per-asset options aggregates for every tracked book. Books that fail or
+ * come back empty are dropped rather than reported as zeros.
+ * @returns {Promise<Array<object>>}
+ */
+export async function fetchDeribitOptionsSummaries() {
+ const settled = await Promise.allSettled(
+ DERIBIT_OPTION_BOOKS.map(({ currency }) =>
+ deribitGet('get_book_summary_by_currency', { currency, kind: 'option' }),
+ ),
+ );
+ const summaries = [];
+ for (let i = 0; i < settled.length; i++) {
+ if (settled[i].status !== 'fulfilled') continue;
+ const summary = summarizeDeribitOptions(settled[i].value, DERIBIT_OPTION_BOOKS[i].asset);
+ if (summary.contracts > 0) summaries.push(summary);
+ }
+ return summaries;
+}
+
+/**
+ * The full Deribit block /api/coin/derivatives attaches to its response:
+ * { indexes, perps, options }. Throws when the venue served nothing usable so
+ * the endpoint's soft-fail path can drop the block cleanly.
+ * @returns {Promise<{ indexes: Record<string, number|null>, perps: Array<object>, options: Array<object> }>}
+ */
+export async function fetchDeribitSummary() {
+ const [indexes, perps, options] = await Promise.all([
+ fetchDeribitIndexes(),
+ fetchDeribitPerps(),
+ fetchDeribitOptionsSummaries(),
+ ]);
+ return { indexes, perps, options };
+}
diff --git a/api/_lib/token/jupiter.js b/api/_lib/token/jupiter.js
index f29a93478..b0d1a6c2e 100644
--- a/api/_lib/token/jupiter.js
+++ b/api/_lib/token/jupiter.js
@@ -9,9 +9,27 @@
// BUY-ONLY by construction: nothing here sells $THREE. Every helper is a generic
// (inputMint → outputMint) swap primitive; the $THREE lanes only ever call it with
// outputMint = $THREE, and there is no sell path anywhere in the token/ tree.
+//
+// Beyond the swap lane, this module also wraps the rest of Jupiter's keyless
+// lite tier (read-only token intelligence, verified live 2026-08-06):
+// - /tokens/v2/search: rich per-mint info (price, mcap, liquidity, holderCount,
+// audit flags, launchpad). Jupiter serves no dedicated holders endpoint
+// (/ultra/v1/holders 404s); holderCount here is the keyless holder signal.
+// - /tokens/v2/{toptrending|toptraded|toporganicscore}/{interval}: ranked
+// discovery lists.
+// - /tokens/v2/recent: latest mints seen by Jupiter (fixed 30-row page;
+// upstream ignores a limit param, so trimming happens client-side).
+// - /ultra/v1/shield: per-mint safety warnings.
const JUP_QUOTE_URL = 'https://lite-api.jup.ag/swap/v1/quote';
const JUP_SWAP_URL = 'https://lite-api.jup.ag/swap/v1/swap';
+const JUP_TOKENS_URL = 'https://lite-api.jup.ag/tokens/v2';
+const JUP_SHIELD_URL = 'https://lite-api.jup.ag/ultra/v1/shield';
+
+// The category lists /tokens/v2 actually serves. A wrong category is not a
+// 404 upstream (it 200s with junk), so it is validated here instead.
+export const JUP_TOKEN_CATEGORIES = ['toporganicscore', 'toptraded', 'toptrending'];
+export const JUP_TOKEN_INTERVALS = ['5m', '1h', '6h', '24h'];
/**
* GET a Jupiter route + throw a coded error on a non-2xx / unparseable response,
@@ -76,3 +94,103 @@ export async function jupiterSwapTx({
}
return data.swapTransaction;
}
+
+/**
+ * Search tokens by symbol, name, or mint address. A mint query returns that
+ * token's full record: usdPrice, mcap, liquidity, holderCount, launchpad,
+ * audit flags, and per-window stats.
+ * @param {string} query symbol, name, or mint address
+ * @param {{ limit?: number }} [opts] upstream caps at 100
+ * @returns {Promise<Array<object>>} raw Jupiter token records
+ */
+export async function jupiterTokenSearch(query, { limit } = {}) {
+ if (!query) {
+ throw Object.assign(new Error('jupiterTokenSearch requires a query'), { code: 'bad_query' });
+ }
+ const u = new URL(`${JUP_TOKENS_URL}/search`);
+ u.searchParams.set('query', String(query));
+ if (limit) u.searchParams.set('limit', String(limit));
+ const data = await fetchJson(u.toString(), { headers: { accept: 'application/json' } });
+ return Array.isArray(data) ? data : [];
+}
+
+/**
+ * Ranked token discovery list: top trending, top traded, or top organic-score
+ * tokens over an interval.
+ * @param {string} category one of JUP_TOKEN_CATEGORIES
+ * @param {string} [interval] one of JUP_TOKEN_INTERVALS (default '24h')
+ * @param {{ limit?: number }} [opts] upstream caps at 100
+ * @returns {Promise<Array<object>>} raw Jupiter token records
+ */
+export async function jupiterTokenList(category, interval = '24h', { limit } = {}) {
+ if (!JUP_TOKEN_CATEGORIES.includes(category)) {
+ throw Object.assign(
+ new Error(`jupiterTokenList category must be one of ${JUP_TOKEN_CATEGORIES.join(', ')}`),
+ { code: 'bad_category' },
+ );
+ }
+ if (!JUP_TOKEN_INTERVALS.includes(interval)) {
+ throw Object.assign(
+ new Error(`jupiterTokenList interval must be one of ${JUP_TOKEN_INTERVALS.join(', ')}`),
+ { code: 'bad_interval' },
+ );
+ }
+ const u = new URL(`${JUP_TOKENS_URL}/${category}/${interval}`);
+ if (limit) u.searchParams.set('limit', String(limit));
+ const data = await fetchJson(u.toString(), { headers: { accept: 'application/json' } });
+ return Array.isArray(data) ? data : [];
+}
+
+/**
+ * The most recent mints Jupiter has seen. Upstream ignores a limit param and
+ * always returns its fixed page, so the cap is applied client-side.
+ * @param {{ limit?: number }} [opts]
+ * @returns {Promise<Array<object>>} raw Jupiter token records, newest first
+ */
+export async function jupiterRecentTokens({ limit } = {}) {
+ const data = await fetchJson(`${JUP_TOKENS_URL}/recent`, {
+ headers: { accept: 'application/json' },
+ });
+ const rows = Array.isArray(data) ? data : [];
+ return limit > 0 ? rows.slice(0, limit) : rows;
+}
+
+// Shield answers at most 30 mints per request and silently drops the rest
+// (verified live 2026-08-06: 60 unique mints in, warnings for exactly the
+// first 30 out), so jupiterShield chunks larger lists itself.
+const JUP_SHIELD_BATCH = 30;
+
+/**
+ * Jupiter Shield safety warnings per mint (freeze/mint authority, unverified
+ * status, rug signals, ...). An empty array for a mint means Shield has
+ * nothing to flag. Mints are deduped and fetched in batches of 30 so callers
+ * never hit the upstream truncation.
+ * @param {Array<string>|string} mints
+ * @returns {Promise<Record<string, Array<object>>>} mint -> warnings
+ */
+export async function jupiterShield(mints) {
+ const list = [...new Set((Array.isArray(mints) ? mints : [mints]).filter(Boolean).map(String))];
+ if (!list.length) {
+ throw Object.assign(new Error('jupiterShield requires at least one mint'), {
+ code: 'bad_mints',
+ });
+ }
+ const batches = [];
+ for (let i = 0; i < list.length; i += JUP_SHIELD_BATCH) {
+ batches.push(list.slice(i, i + JUP_SHIELD_BATCH));
+ }
+ const results = await Promise.all(
+ batches.map((batch) => {
+ const u = new URL(JUP_SHIELD_URL);
+ u.searchParams.set('mints', batch.join(','));
+ return fetchJson(u.toString(), { headers: { accept: 'application/json' } });
+ }),
+ );
+ const warnings = {};
+ for (const data of results) {
+ if (data && typeof data.warnings === 'object' && data.warnings !== null) {
+ Object.assign(warnings, data.warnings);
+ }
+ }
+ return warnings;
+}
diff --git a/api/coin/derivatives.js b/api/coin/derivatives.js
index ad689bc98..842a33720 100644
--- a/api/coin/derivatives.js
+++ b/api/coin/derivatives.js
@@ -7,6 +7,12 @@
// become null so the client renders an em dash instead of NaN. Cached 60s
// in-memory + CDN.
//
+// Alongside `tickers`, the response carries a `deribit` block (second
+// derivatives source, options-capable): index prices, perp tickers with
+// funding, and per-asset options aggregates from Deribit's keyless public
+// API. It fails soft: when Deribit is unreachable the block is null and the
+// perp table ships without it, mirroring the CoinGecko/Hyperliquid handling.
+//
// `?view=exchanges` returns the derivatives venues instead — CoinGecko
// `/derivatives/exchanges` ranked by open interest — feeding the Derivatives
// Exchanges section of the page; rows deep-link to /exchange/:id, where the
@@ -16,6 +22,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';
+import { fetchDeribitSummary } from '../_lib/deribit.js';
let _cache = null; // { value, expiresAt }
let _exCache = null; // { value, expiresAt }
@@ -39,6 +46,11 @@ export async function buildDerivativeTickers() {
const now = Date.now();
if (_cache && _cache.expiresAt > now) return _cache.value;
+ // Deribit rides alongside as a second source, fetched in parallel with the
+ // primary table and soft-failed to null: options data is a bonus, never a
+ // reason to 502 the perp table.
+ const deribitPromise = fetchDeribitSummary().catch(() => null);
+
let tickers = [];
let source = 'coingecko';
try {
@@ -67,7 +79,9 @@ export async function buildDerivativeTickers() {
source = 'hyperliquid';
}
- const value = { tickers, source, updated_at: now };
+ const deribit = await deribitPromise;
+
+ const value = { tickers, source, deribit, updated_at: now };
_cache = { value, expiresAt: now + TTL_MS };
return value;
}
diff --git a/tests/api/deribit.test.js b/tests/api/deribit.test.js
new file mode 100644
index 000000000..944f958f7
--- /dev/null
+++ b/tests/api/deribit.test.js
@@ -0,0 +1,281 @@
+// Deribit (api/_lib/deribit.js): unit + wiring tests.
+//
+// Pins the public/ticker → derivatives-ticker-row mapping and the unit
+// conversions the /derivatives comparability depends on: decimal 8h funding →
+// percent, and linear (USDC-settled) open interest in base units → USD
+// notional, while inverse open interest passes through as the USD it already
+// is. Also pins the options-book aggregation (base-currency filter, USD open
+// interest via underlying price, put/call split off the -C/-P suffix), the
+// JSON-RPC envelope handling (Deribit signals bad params with HTTP 200 + an
+// `error` object), and the /api/coin/derivatives soft-fail wiring.
+//
+// No live network: fixtures are trimmed real-shaped captures from
+// www.deribit.com/api/v2/public/* (verified 2026-08-05), and the envelope +
+// wiring cases run against a stubbed global fetch.
+
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import {
+ normalizeDeribitPerp,
+ summarizeDeribitOptions,
+ deribitGet,
+ DERIBIT_PERPS,
+ DERIBIT_OPTION_BOOKS,
+} from '../../api/_lib/deribit.js';
+
+const realFetch = global.fetch;
+afterEach(() => {
+ global.fetch = realFetch;
+ vi.restoreAllMocks();
+});
+
+// ── Fixtures: trimmed but real-shaped captures ───────────────────────────────
+const BTC_TICKER = {
+ instrument_name: 'BTC-PERPETUAL',
+ state: 'open',
+ mark_price: 64000,
+ index_price: 63990.5,
+ last_price: 64001.5,
+ open_interest: 730_000_000, // inverse contract: already USD notional
+ funding_8h: 0.0001,
+ current_funding: 0.00005,
+ stats: { high: 64970, low: 63856.5, price_change: 0.792, volume: 3583.7, volume_usd: 230_776_660 },
+};
+
+const SOL_TICKER = {
+ instrument_name: 'SOL_USDC-PERPETUAL',
+ state: 'open',
+ mark_price: 74,
+ index_price: 73.96,
+ open_interest: 200_000, // linear contract: base (SOL) units
+ funding_8h: -0.00004,
+ stats: { price_change: 0.3974, volume: 269_194.1, volume_usd: 19_916_271 },
+};
+
+// The shared USDC book mixes bases (SOL_USDC-*, XRP_USDC-*, ...); the
+// aggregate must keep only the requested one.
+const USDC_OPTION_BOOK = [
+ {
+ instrument_name: 'SOL_USDC-26MAR27-80-C',
+ base_currency: 'SOL',
+ quote_currency: 'USDC',
+ open_interest: 100,
+ underlying_price: 75,
+ volume_usd: 1000,
+ mark_iv: 58.13,
+ },
+ {
+ instrument_name: 'SOL_USDC-26MAR27-60-P',
+ base_currency: 'SOL',
+ quote_currency: 'USDC',
+ open_interest: 50,
+ underlying_price: 75,
+ volume_usd: 250,
+ },
+ {
+ instrument_name: 'XRP_USDC-26MAR27-1-C',
+ base_currency: 'XRP',
+ quote_currency: 'USDC',
+ open_interest: 9999,
+ underlying_price: 1,
+ volume_usd: 5,
+ },
+ // A dead strike: no open interest / volume yet, still a listed contract.
+ {
+ instrument_name: 'SOL_USDC-26MAR27-90-C',
+ base_currency: 'SOL',
+ quote_currency: 'USDC',
+ open_interest: 0,
+ underlying_price: 75,
+ volume_usd: 0,
+ },
+];
+
+const rpcOk = (result) => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ jsonrpc: '2.0', result, testnet: false }),
+});
+
+describe('DERIBIT instrument config', () => {
+ it('tracks BTC/ETH as inverse and SOL as USDC-linear, options books to match', () => {
+ expect(DERIBIT_PERPS.map((p) => p.asset)).toEqual(['BTC', 'ETH', 'SOL']);
+ expect(DERIBIT_PERPS.find((p) => p.asset === 'BTC')).toMatchObject({
+ instrument: 'BTC-PERPETUAL',
+ linear: false,
+ });
+ expect(DERIBIT_PERPS.find((p) => p.asset === 'SOL')).toMatchObject({
+ instrument: 'SOL_USDC-PERPETUAL',
+ linear: true,
+ });
+ // SOL options live under the shared USDC listing, not currency=SOL.
+ expect(DERIBIT_OPTION_BOOKS.find((b) => b.asset === 'SOL').currency).toBe('USDC');
+ });
+});
+
+describe('normalizeDeribitPerp', () => {
+ it('maps an inverse perp: USD open interest passes through, funding decimal → percent', () => {
+ const row = normalizeDeribitPerp(BTC_TICKER, DERIBIT_PERPS[0]);
+ expect(row).toEqual({
+ market: 'Deribit',
+ symbol: 'BTC-PERPETUAL',
+ index_id: 'BTC',
+ price: 64000,
+ change_24h: 0.792, // stats.price_change is already a percentage
+ funding_rate: 0.01, // 0.0001 decimal 8h → 0.01%
+ open_interest: 730_000_000,
+ volume_24h: 230_776_660,
+ });
+ });
+
+ it('maps a linear perp: base-unit open interest × mark price, negative funding keeps its sign', () => {
+ const row = normalizeDeribitPerp(SOL_TICKER, DERIBIT_PERPS[2]);
+ expect(row.index_id).toBe('SOL');
+ expect(row.open_interest).toBe(14_800_000); // 200k SOL × $74
+ expect(row.funding_rate).toBeCloseTo(-0.004, 9);
+ });
+
+ it('null-safes a partial ticker and rejects one without a positive mark price', () => {
+ const row = normalizeDeribitPerp({ mark_price: 2 }, DERIBIT_PERPS[1]);
+ expect(row).toEqual({
+ market: 'Deribit',
+ symbol: 'ETH-PERPETUAL',
+ index_id: 'ETH',
+ price: 2,
+ change_24h: null,
+ funding_rate: null,
+ open_interest: null,
+ volume_24h: null,
+ });
+ expect(normalizeDeribitPerp(null, DERIBIT_PERPS[0])).toBeNull();
+ expect(normalizeDeribitPerp({ mark_price: 0 }, DERIBIT_PERPS[0])).toBeNull();
+ });
+});
+
+describe('summarizeDeribitOptions', () => {
+ it('filters by base currency, converts OI to USD via underlying, splits put/call', () => {
+ const s = summarizeDeribitOptions(USDC_OPTION_BOOK, 'SOL');
+ expect(s).toEqual({
+ asset: 'SOL',
+ contracts: 3, // XRP row excluded, dead SOL strike still counted
+ open_interest: 11_250, // (100 + 50 + 0) coins × $75
+ volume_24h: 1250,
+ put_call_ratio: 0.5, // 50 put OI / 100 call OI
+ });
+ });
+
+ it('returns a zeroed aggregate (ratio null) for empty or malformed books', () => {
+ const empty = { asset: 'BTC', contracts: 0, open_interest: 0, volume_24h: 0, put_call_ratio: null };
+ expect(summarizeDeribitOptions([], 'BTC')).toEqual(empty);
+ expect(summarizeDeribitOptions(null, 'BTC')).toEqual(empty);
+ expect(summarizeDeribitOptions('Route not found', 'BTC')).toEqual(empty);
+ });
+
+ it('leaves the ratio null when no call OI exists (division guard)', () => {
+ const puts = [
+ { instrument_name: 'ETH-1JAN27-1500-P', base_currency: 'ETH', open_interest: 5, underlying_price: 2000, volume_usd: 10 },
+ ];
+ expect(summarizeDeribitOptions(puts, 'ETH').put_call_ratio).toBeNull();
+ });
+});
+
+describe('deribitGet JSON-RPC envelope', () => {
+ it('unwraps result and builds the public URL with params', async () => {
+ global.fetch = vi.fn().mockResolvedValue(rpcOk({ index_price: 64579.78 }));
+ const result = await deribitGet('get_index_price', { index_name: 'btc_usd' });
+ expect(result).toEqual({ index_price: 64579.78 });
+ const url = String(global.fetch.mock.calls[0][0]);
+ expect(url).toBe('https://www.deribit.com/api/v2/public/get_index_price?index_name=btc_usd');
+ });
+
+ it('throws on an RPC error even though the HTTP status is 200', async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ jsonrpc: '2.0',
+ error: { code: -32602, message: 'Invalid params' },
+ }),
+ });
+ await expect(deribitGet('ticker', { instrument_name: 'NOPE' })).rejects.toThrow(
+ /deribit rpc -32602/,
+ );
+ });
+
+ it('throws with the status on a non-2xx response', async () => {
+ global.fetch = vi.fn().mockResolvedValue({ ok: false, status: 503, json: async () => ({}) });
+ await expect(deribitGet('ticker', { instrument_name: 'BTC-PERPETUAL' })).rejects.toMatchObject(
+ { status: 503 },
+ );
+ });
+});
+
+// ── /api/coin/derivatives wiring ─────────────────────────────────────────────
+// Fresh module instances per case (vi.resetModules) because the builder holds
+// a 60s in-memory cache with no reset hook.
+
+const GECKO_ROWS = [
+ {
+ market: 'Binance (Futures)',
+ symbol: 'BTCUSDT',
+ index_id: 'BTC',
+ price: '64000',
+ price_percentage_change_24h: 1.2,
+ contract_type: 'perpetual',
+ funding_rate: 0.005,
+ open_interest: 5_000_000_000,
+ volume_24h: 20_000_000_000,
+ },
+];
+
+// Route every upstream the builder can touch; anything unexpected fails loud.
+const stubUpstreams = ({ deribitDown = false } = {}) => {
+ global.fetch = vi.fn(async (input) => {
+ const url = String(input);
+ if (url.includes('api.coingecko.com')) {
+ return { ok: true, status: 200, json: async () => GECKO_ROWS };
+ }
+ if (url.includes('deribit.com')) {
+ if (deribitDown) return { ok: false, status: 503, json: async () => ({}) };
+ const u = new URL(url);
+ if (url.includes('/ticker')) {
+ const name = u.searchParams.get('instrument_name');
+ return rpcOk(name === 'SOL_USDC-PERPETUAL' ? SOL_TICKER : { ...BTC_TICKER, instrument_name: name });
+ }
+ if (url.includes('/get_index_price')) return rpcOk({ index_price: 64579.78 });
+ if (url.includes('/get_book_summary_by_currency')) {
+ return rpcOk(u.searchParams.get('currency') === 'USDC' ? USDC_OPTION_BOOK : []);
+ }
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ });
+};
+
+describe('buildDerivativeTickers deribit block', () => {
+ it('attaches indexes, perps, and options next to the primary ticker table', async () => {
+ vi.resetModules();
+ stubUpstreams();
+ const { buildDerivativeTickers } = await import('../../api/coin/derivatives.js');
+ const value = await buildDerivativeTickers();
+
+ expect(value.source).toBe('coingecko');
+ expect(value.tickers).toHaveLength(1);
+ expect(value.deribit.indexes).toEqual({ BTC: 64579.78, ETH: 64579.78, SOL: 64579.78 });
+ expect(value.deribit.perps.map((r) => r.market)).toEqual(['Deribit', 'Deribit', 'Deribit']);
+ expect(value.deribit.perps.map((r) => r.index_id).sort()).toEqual(['BTC', 'ETH', 'SOL']);
+ // Empty BTC/ETH books are dropped; the USDC book yields the SOL aggregate.
+ expect(value.deribit.options).toEqual([
+ { asset: 'SOL', contracts: 3, open_interest: 11_250, volume_24h: 1250, put_call_ratio: 0.5 },
+ ]);
+ });
+
+ it('fails soft: an unreachable Deribit yields deribit:null, never a thrown table', async () => {
+ vi.resetModules();
+ stubUpstreams({ deribitDown: true });
+ const { buildDerivativeTickers } = await import('../../api/coin/derivatives.js');
+ const value = await buildDerivativeTickers();
+
+ expect(value.tickers).toHaveLength(1);
+ expect(value.source).toBe('coingecko');
+ expect(value.deribit).toBeNull();
+ });
+});
diff --git a/tests/api/jupiter-token-lite.test.js b/tests/api/jupiter-token-lite.test.js
new file mode 100644
index 000000000..02c862a4d
--- /dev/null
+++ b/tests/api/jupiter-token-lite.test.js
@@ -0,0 +1,152 @@
+// Jupiter keyless lite-tier token intelligence (api/_lib/token/jupiter.js).
+//
+// Pins the four read-only wrappers added next to the swap lane: token search,
+// the ranked category lists, the recent-mints feed, and Shield warnings.
+// Upstream quirks these tests exist to hold (verified against the REAL
+// lite-api.jup.ag on 2026-08-06):
+// - an unknown category 200s with junk instead of 404ing, so the wrapper must
+// validate category/interval itself;
+// - /tokens/v2/recent ignores its limit param and always returns the fixed
+// page, so trimming is client-side;
+// - /ultra/v1/shield answers at most 30 mints per request and silently drops
+// the rest, so the wrapper dedupes and batches.
+//
+// No live network: global.fetch is stubbed per case.
+
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import {
+ jupiterTokenSearch,
+ jupiterTokenList,
+ jupiterRecentTokens,
+ jupiterShield,
+ JUP_TOKEN_CATEGORIES,
+ JUP_TOKEN_INTERVALS,
+} from '../../api/_lib/token/jupiter.js';
+
+const realFetch = global.fetch;
+afterEach(() => {
+ global.fetch = realFetch;
+ vi.restoreAllMocks();
+});
+
+const ok = (body) => ({ ok: true, status: 200, json: async () => body });
+
+// Trimmed real-shaped /tokens/v2 record.
+const THREE_RECORD = {
+ id: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ name: 'three.ws',
+ symbol: 'three',
+ decimals: 6,
+ launchpad: 'pump.fun',
+ holderCount: 15830,
+ usdPrice: 0.001764119479092505,
+ mcap: 1763536.0054396437,
+ liquidity: 236617.60682663386,
+};
+
+describe('jupiterTokenSearch', () => {
+ it('queries /tokens/v2/search with query + limit and returns the raw records', async () => {
+ global.fetch = vi.fn().mockResolvedValue(ok([THREE_RECORD]));
+ const out = await jupiterTokenSearch('three.ws', { limit: 5 });
+ expect(out).toEqual([THREE_RECORD]);
+ const url = new URL(String(global.fetch.mock.calls[0][0]));
+ expect(url.origin + url.pathname).toBe('https://lite-api.jup.ag/tokens/v2/search');
+ expect(url.searchParams.get('query')).toBe('three.ws');
+ expect(url.searchParams.get('limit')).toBe('5');
+ });
+
+ it('requires a query and normalizes a non-array body to []', async () => {
+ await expect(jupiterTokenSearch('')).rejects.toMatchObject({ code: 'bad_query' });
+ global.fetch = vi.fn().mockResolvedValue(ok({ unexpected: true }));
+ expect(await jupiterTokenSearch('three')).toEqual([]);
+ });
+
+ it('surfaces upstream failures as coded jupiter errors', async () => {
+ global.fetch = vi.fn().mockResolvedValue({ ok: false, status: 429, json: async () => ({}) });
+ await expect(jupiterTokenSearch('three')).rejects.toMatchObject({
+ code: 'jupiter_error',
+ status: 429,
+ });
+ });
+});
+
+describe('jupiterTokenList', () => {
+ it('builds /tokens/v2/{category}/{interval} for every valid pair', async () => {
+ global.fetch = vi.fn().mockResolvedValue(ok([THREE_RECORD]));
+ const out = await jupiterTokenList('toptrending', '1h', { limit: 10 });
+ expect(out).toEqual([THREE_RECORD]);
+ const url = new URL(String(global.fetch.mock.calls[0][0]));
+ expect(url.pathname).toBe('/tokens/v2/toptrending/1h');
+ expect(url.searchParams.get('limit')).toBe('10');
+ });
+
+ it('defaults the interval to 24h', async () => {
+ global.fetch = vi.fn().mockResolvedValue(ok([]));
+ await jupiterTokenList('toptraded');
+ expect(new URL(String(global.fetch.mock.calls[0][0])).pathname).toBe('/tokens/v2/toptraded/24h');
+ });
+
+ it('rejects unknown categories/intervals locally (upstream 200s with junk)', async () => {
+ global.fetch = vi.fn();
+ await expect(jupiterTokenList('nope')).rejects.toMatchObject({ code: 'bad_category' });
+ await expect(jupiterTokenList('toptrending', '2d')).rejects.toMatchObject({
+ code: 'bad_interval',
+ });
+ expect(global.fetch).not.toHaveBeenCalled();
+ expect(JUP_TOKEN_CATEGORIES).toEqual(['toporganicscore', 'toptraded', 'toptrending']);
+ expect(JUP_TOKEN_INTERVALS).toEqual(['5m', '1h', '6h', '24h']);
+ });
+});
+
+describe('jupiterRecentTokens', () => {
+ it('trims the fixed upstream page client-side (upstream ignores limit)', async () => {
+ const page = Array.from({ length: 30 }, (_, i) => ({ id: `M${i}`, symbol: `S${i}` }));
+ global.fetch = vi.fn().mockResolvedValue(ok(page));
+ const out = await jupiterRecentTokens({ limit: 3 });
+ expect(out).toHaveLength(3);
+ expect(out[0].id).toBe('M0');
+ // No limit param is sent upstream; there is nothing there to honor it.
+ expect(new URL(String(global.fetch.mock.calls[0][0])).search).toBe('');
+ });
+
+ it('returns the whole page without a limit and [] on a malformed body', async () => {
+ global.fetch = vi.fn().mockResolvedValue(ok([{ id: 'A' }, { id: 'B' }]));
+ expect(await jupiterRecentTokens()).toHaveLength(2);
+ global.fetch = vi.fn().mockResolvedValue(ok(null));
+ expect(await jupiterRecentTokens()).toEqual([]);
+ });
+});
+
+describe('jupiterShield', () => {
+ it('dedupes mints and merges warnings from a single batch', async () => {
+ global.fetch = vi.fn().mockResolvedValue(
+ ok({ warnings: { A: [], B: [{ type: 'HAS_FREEZE_AUTHORITY', severity: 'warning' }] } }),
+ );
+ const out = await jupiterShield(['A', 'B', 'A']);
+ expect(Object.keys(out)).toEqual(['A', 'B']);
+ expect(out.B[0].type).toBe('HAS_FREEZE_AUTHORITY');
+ const url = new URL(String(global.fetch.mock.calls[0][0]));
+ expect(url.pathname).toBe('/ultra/v1/shield');
+ expect(url.searchParams.get('mints')).toBe('A,B');
+ });
+
+ it('splits >30 mints into 30-mint batches so upstream truncation never bites', async () => {
+ const mints = Array.from({ length: 70 }, (_, i) => `MINT${i}`);
+ global.fetch = vi.fn(async (input) => {
+ const batch = new URL(String(input)).searchParams.get('mints').split(',');
+ expect(batch.length).toBeLessThanOrEqual(30);
+ return ok({ warnings: Object.fromEntries(batch.map((m) => [m, []])) });
+ });
+ const out = await jupiterShield(mints);
+ expect(global.fetch).toHaveBeenCalledTimes(3); // 30 + 30 + 10
+ expect(Object.keys(out)).toHaveLength(70);
+ });
+
+ it('accepts a single mint string, requires at least one, and normalizes a bad body', async () => {
+ global.fetch = vi.fn().mockResolvedValue(ok({ warnings: { M: [] } }));
+ expect(await jupiterShield('M')).toEqual({ M: [] });
+ await expect(jupiterShield([])).rejects.toMatchObject({ code: 'bad_mints' });
+ global.fetch = vi.fn().mockResolvedValue(ok({}));
+ expect(await jupiterShield('M')).toEqual({});
+ });
+});