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(evm): keyless read-only swap quotes with ParaSwap, KyberSwap, and LI.FI failover

nirholas008b0c86c31f
diff --git a/api/_lib/evm/swap-quotes.js b/api/_lib/evm/swap-quotes.js
new file mode 100644
index 000000000..9a430dbe3
--- /dev/null
+++ b/api/_lib/evm/swap-quotes.js
@@ -0,0 +1,273 @@
+// Keyless EVM swap-QUOTE chain: ParaSwap, then KyberSwap, then LI.FI.
+//
+// Read-only price discovery ONLY. This module never builds transaction
+// calldata, never signs, and never sends anything on-chain: every rung calls a
+// public, keyless quote endpoint and returns numbers. The LI.FI quote endpoint
+// requires a `fromAddress` even for a price read, so a burn address is passed
+// as a placeholder; the tx payload LI.FI attaches to its response is discarded
+// on purpose.
+//
+// Chain order and why: ParaSwap's /prices endpoint is the most permissive
+// keyless rung (no per-request address requirement, decimals resolved
+// server-side), KyberSwap's aggregator routes endpoint is a fast second with
+// per-chain hosts under one API shape, and LI.FI (li.quest/v1/quote, the same
+// keyless host api/x402/cross-chain.js already probes for bridge health) is the
+// broadest but the most tightly rate-limited without a key, so it goes last.
+// First success wins; each rung fails soft on its own timeout
+// (AbortSignal.timeout, the pattern the cross-chain probes use) and the next
+// rung is tried. Only when every rung has failed does the chain throw, carrying
+// the per-provider attempt log for the caller's error message.
+//
+// Chains covered: Ethereum, Base, Polygon, Arbitrum, Optimism, BSC. Each
+// provider addresses chains differently (ParaSwap and LI.FI take the numeric
+// chain id, KyberSwap takes a per-chain host path segment), so `resolveChain`
+// maps one caller-facing name (plus common aliases and the raw chain id) to
+// every per-provider identifier.
+//
+// Native-coin quotes work through the providers' shared sentinel address
+// (0xeeee...eeee), which is a syntactically valid EVM address and passes
+// straight through.
+
+const PARASWAP_BASE = 'https://api.paraswap.io';
+const KYBER_BASE = 'https://aggregator-api.kyberswap.com';
+const LIFI_BASE = 'https://li.quest';
+
+// Per-rung budget. A rung that cannot answer in this window is treated as down
+// and the chain moves on; three rungs stay comfortably inside a 30s request.
+export const PROVIDER_TIMEOUT_MS = 7000;
+
+// LI.FI's quote endpoint validates fromAddress but a pure price read has no
+// caller wallet; the canonical burn address satisfies the validator without
+// implying any account. No transaction is ever built from this quote.
+const LIFI_QUOTE_ADDRESS = '0x000000000000000000000000000000000000dEaD';
+
+// One row per supported chain: caller-facing key, accepted aliases, numeric
+// chain id (ParaSwap `network`, LI.FI `fromChain`/`toChain`), and KyberSwap's
+// host path segment.
+const CHAINS = {
+ ethereum: { chainId: 1, kyber: 'ethereum', aliases: ['eth', 'mainnet'] },
+ base: { chainId: 8453, kyber: 'base', aliases: [] },
+ polygon: { chainId: 137, kyber: 'polygon', aliases: ['matic'] },
+ arbitrum: { chainId: 42161, kyber: 'arbitrum', aliases: ['arb'] },
+ optimism: { chainId: 10, kyber: 'optimism', aliases: ['op'] },
+ bsc: { chainId: 56, kyber: 'bsc', aliases: ['bnb', 'binance'] },
+};
+
+/** Caller-facing chain keys, for validation messages. */
+export const SUPPORTED_CHAINS = Object.keys(CHAINS);
+
+/**
+ * Map a chain name (key, alias, or numeric chain id as number/string) to its
+ * per-provider identifiers. Returns null for anything unsupported.
+ * @param {string|number} input
+ * @returns {{ key: string, chainId: number, kyber: string } | null}
+ */
+export function resolveChain(input) {
+ const raw = String(input ?? '').trim().toLowerCase();
+ if (!raw) return null;
+ for (const [key, def] of Object.entries(CHAINS)) {
+ if (raw === key || def.aliases.includes(raw) || raw === String(def.chainId)) {
+ return { key, chainId: def.chainId, kyber: def.kyber };
+ }
+ }
+ return null;
+}
+
+/** Trim an upstream error body to something safe for an attempt log. */
+function snippet(text) {
+ return String(text ?? '').replace(/\s+/g, ' ').trim().slice(0, 160);
+}
+
+/** Finite positive number or null; upstream USD fields arrive as strings. */
+function num(value) {
+ const n = Number(value);
+ return Number.isFinite(n) ? n : null;
+}
+
+/**
+ * Human price (buy tokens per 1 sell token) when both decimals are known.
+ * Number precision is fine here: this is a display/comparison figure, the
+ * exact raw buyAmount string stays authoritative.
+ */
+function humanPrice(sellAmount, buyAmount, sellDecimals, buyDecimals) {
+ if (!Number.isInteger(sellDecimals) || !Number.isInteger(buyDecimals)) return null;
+ const sell = Number(sellAmount) / 10 ** sellDecimals;
+ const buy = Number(buyAmount) / 10 ** buyDecimals;
+ if (!Number.isFinite(sell) || sell <= 0 || !Number.isFinite(buy) || buy < 0) return null;
+ return buy / sell;
+}
+
+async function fetchJson(url, timeoutMs, providerName) {
+ const res = await fetch(url, {
+ headers: { Accept: 'application/json', 'User-Agent': 'three-ws/1.0 (+https://three.ws)' },
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ const text = await res.text();
+ let data = null;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = null;
+ }
+ if (!res.ok) {
+ const detail = snippet(data?.error || data?.message || text) || 'no error body';
+ throw new Error(`${providerName} ${res.status}: ${detail}`);
+ }
+ if (data === null) throw new Error(`${providerName} returned a non-JSON body`);
+ return data;
+}
+
+// ---------------------------------------------------------------------------
+// Rung 1: ParaSwap /prices (keyless, decimals resolved server-side).
+// ---------------------------------------------------------------------------
+async function quoteParaswap({ chain, sellToken, buyToken, amount, timeoutMs }) {
+ const url = new URL('/prices', PARASWAP_BASE);
+ url.searchParams.set('srcToken', sellToken);
+ url.searchParams.set('destToken', buyToken);
+ url.searchParams.set('amount', amount);
+ url.searchParams.set('side', 'SELL');
+ url.searchParams.set('network', String(chain.chainId));
+
+ const data = await fetchJson(url, timeoutMs, 'paraswap');
+ const route = data?.priceRoute;
+ if (data?.error) throw new Error(`paraswap: ${snippet(data.error)}`);
+ if (!route?.destAmount) throw new Error('paraswap: no priceRoute in response');
+
+ const sellDecimals = Number.isInteger(route.srcDecimals) ? route.srcDecimals : null;
+ const buyDecimals = Number.isInteger(route.destDecimals) ? route.destDecimals : null;
+ return {
+ provider: 'paraswap',
+ chain: chain.key,
+ chainId: chain.chainId,
+ sellToken,
+ buyToken,
+ sellAmount: String(route.srcAmount ?? amount),
+ buyAmount: String(route.destAmount),
+ price: humanPrice(route.srcAmount ?? amount, route.destAmount, sellDecimals, buyDecimals),
+ estimatedGas: route.gasCost != null ? String(route.gasCost) : null,
+ gasUsd: num(route.gasCostUSD),
+ sellAmountUsd: num(route.srcUSD),
+ buyAmountUsd: num(route.destUSD),
+ venue: route.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange ?? null,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Rung 2: KyberSwap Aggregator routes (keyless, per-chain host segment).
+// ---------------------------------------------------------------------------
+async function quoteKyberswap({ chain, sellToken, buyToken, amount, timeoutMs }) {
+ const url = new URL(`/${chain.kyber}/api/v1/routes`, KYBER_BASE);
+ url.searchParams.set('tokenIn', sellToken);
+ url.searchParams.set('tokenOut', buyToken);
+ url.searchParams.set('amountIn', amount);
+
+ const data = await fetchJson(url, timeoutMs, 'kyberswap');
+ // Kyber wraps everything in { code, message, data }; code 0 is success.
+ if (data?.code !== 0) throw new Error(`kyberswap: ${snippet(data?.message) || `code ${data?.code}`}`);
+ const summary = data?.data?.routeSummary;
+ if (!summary?.amountOut) throw new Error('kyberswap: no routeSummary in response');
+
+ return {
+ provider: 'kyberswap',
+ chain: chain.key,
+ chainId: chain.chainId,
+ sellToken,
+ buyToken,
+ sellAmount: String(summary.amountIn ?? amount),
+ buyAmount: String(summary.amountOut),
+ // Kyber's summary carries no token decimals, so no human price; the USD
+ // legs below give callers the same comparison signal.
+ price: null,
+ estimatedGas: summary.gas != null ? String(summary.gas) : null,
+ gasUsd: num(summary.gasUsd),
+ sellAmountUsd: num(summary.amountInUsd),
+ buyAmountUsd: num(summary.amountOutUsd),
+ venue: summary.route?.[0]?.[0]?.exchange ?? null,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Rung 3: LI.FI /v1/quote (keyless with rate limits; same-chain = swap quote).
+// ---------------------------------------------------------------------------
+async function quoteLifi({ chain, sellToken, buyToken, amount, timeoutMs }) {
+ const url = new URL('/v1/quote', LIFI_BASE);
+ url.searchParams.set('fromChain', String(chain.chainId));
+ url.searchParams.set('toChain', String(chain.chainId));
+ url.searchParams.set('fromToken', sellToken);
+ url.searchParams.set('toToken', buyToken);
+ url.searchParams.set('fromAmount', amount);
+ url.searchParams.set('fromAddress', LIFI_QUOTE_ADDRESS);
+
+ const data = await fetchJson(url, timeoutMs, 'lifi');
+ const estimate = data?.estimate;
+ if (!estimate?.toAmount) throw new Error('lifi: no estimate in response');
+
+ const sellDecimals = data?.action?.fromToken?.decimals;
+ const buyDecimals = data?.action?.toToken?.decimals;
+ const gasCosts = Array.isArray(estimate.gasCosts) ? estimate.gasCosts : [];
+ const gasUnits = gasCosts.length ? gasCosts.reduce((sum, g) => sum + (num(g?.estimate) ?? 0), 0) : null;
+ const gasUsd = gasCosts.length ? gasCosts.reduce((sum, g) => sum + (num(g?.amountUSD) ?? 0), 0) : null;
+ return {
+ provider: 'lifi',
+ chain: chain.key,
+ chainId: chain.chainId,
+ sellToken,
+ buyToken,
+ sellAmount: String(estimate.fromAmount ?? amount),
+ buyAmount: String(estimate.toAmount),
+ price: humanPrice(
+ estimate.fromAmount ?? amount,
+ estimate.toAmount,
+ Number.isInteger(sellDecimals) ? sellDecimals : null,
+ Number.isInteger(buyDecimals) ? buyDecimals : null,
+ ),
+ estimatedGas: gasUnits != null && gasUnits > 0 ? String(gasUnits) : null,
+ gasUsd,
+ sellAmountUsd: num(estimate.fromAmountUSD),
+ buyAmountUsd: num(estimate.toAmountUSD),
+ venue: data?.tool ?? null,
+ };
+}
+
+// The chain, in priority order. Exported so tests and docs can assert the
+// order instead of restating it.
+export const QUOTE_PROVIDERS = [
+ { name: 'paraswap', quote: quoteParaswap },
+ { name: 'kyberswap', quote: quoteKyberswap },
+ { name: 'lifi', quote: quoteLifi },
+];
+
+/**
+ * Fetch the best available swap quote by walking the provider chain.
+ * First rung that answers wins; every failure (transport error, timeout,
+ * non-2xx, no-route body) fails soft into the next rung.
+ *
+ * @param {object} params
+ * @param {{ key: string, chainId: number, kyber: string }} params.chain From resolveChain().
+ * @param {string} params.sellToken 0x token address (0xeeee... for the native coin).
+ * @param {string} params.buyToken 0x token address.
+ * @param {string} params.amount Sell amount in RAW base units (integer string).
+ * @param {number} [params.timeoutMs] Per-rung budget, default PROVIDER_TIMEOUT_MS.
+ * @returns {Promise<{ quote: object, provider: string, attempts: Array<{provider: string, ok: boolean, latencyMs: number, error?: string}> }>}
+ * @throws {Error & { attempts: Array }} when every rung failed.
+ */
+export async function getSwapQuote({ chain, sellToken, buyToken, amount, timeoutMs = PROVIDER_TIMEOUT_MS }) {
+ const attempts = [];
+ for (const rung of QUOTE_PROVIDERS) {
+ const t0 = Date.now();
+ try {
+ const quote = await rung.quote({ chain, sellToken, buyToken, amount, timeoutMs });
+ attempts.push({ provider: rung.name, ok: true, latencyMs: Date.now() - t0 });
+ return { quote, provider: rung.name, attempts };
+ } catch (err) {
+ attempts.push({
+ provider: rung.name,
+ ok: false,
+ latencyMs: Date.now() - t0,
+ error: snippet(err?.message ?? err),
+ });
+ }
+ }
+ const summary = attempts.map((a) => `${a.provider}: ${a.error}`).join('; ');
+ throw Object.assign(new Error(`every quote provider failed (${summary})`), { attempts });
+}
diff --git a/api/v1/_catalog.js b/api/v1/_catalog.js
index 5537bd568..8d58520f8 100644
--- a/api/v1/_catalog.js
+++ b/api/v1/_catalog.js
@@ -177,6 +177,22 @@ export const CATALOG = [
chain: 'string — "ethereum" | "solana", optional hint validated against address (auto-detected from format when omitted)',
},
},
+ {
+ id: 'v1.evm.swap-quote',
+ method: 'GET',
+ path: '/api/v1/evm/swap-quote',
+ auth: 'public',
+ summary:
+ 'Read-only EVM swap quote with keyless failover across ParaSwap, KyberSwap, and LI.FI: ' +
+ 'best-effort output amount, price, and gas estimate on ethereum/base/polygon/arbitrum/' +
+ 'optimism/bsc. No calldata, no execution, no key; 30/min per IP.',
+ params: {
+ chain: 'string: chain name, alias, or numeric id (ethereum | base | polygon | arbitrum | optimism | bsc), required',
+ sellToken: 'string: 0x… token address to sell; 0xeeee…eeee for the native coin (required)',
+ buyToken: 'string: 0x… token address to buy (required)',
+ amount: 'string: sell amount in raw base units, integer string (required)',
+ },
+ },
{
id: 'v1.robinhood.chain',
method: 'GET',
diff --git a/api/v1/evm/swap-quote.js b/api/v1/evm/swap-quote.js
new file mode 100644
index 000000000..fc2ec662f
--- /dev/null
+++ b/api/v1/evm/swap-quote.js
@@ -0,0 +1,87 @@
+// GET /api/v1/evm/swap-quote - free, keyless EVM swap-quote aggregation.
+//
+// Read-only price discovery over the keyless provider chain in
+// api/_lib/evm/swap-quotes.js (ParaSwap, then KyberSwap, then LI.FI; first
+// success wins, each rung fails soft on its own timeout). This endpoint never
+// builds, signs, or sends a transaction: it returns the normalized best quote
+// and names the provider that served it.
+//
+// ?chain=base
+// &sellToken=0x4200000000000000000000000000000000000006 (WETH)
+// &buyToken=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 (USDC)
+// &amount=1000000000000000000 (raw base units)
+//
+// -> { data: { provider, quote, attempts } }
+//
+// chain accepts a name (ethereum|base|polygon|arbitrum|optimism|bsc), a common
+// alias (eth, matic, arb, op, bnb), or the numeric chain id. The native coin
+// quotes via the providers' shared 0xeeee...eeee sentinel address. A quote miss
+// on every rung is a 502 `quote_unavailable` naming each rung's failure, never
+// a 500. Successful quotes carry a short public cache window: prices move
+// block to block, so anything longer serves stale numbers.
+
+import { defineEndpoint, fail } from '../../_lib/gateway.js';
+import { rateLimited } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { isValidEvmAddress } from '../../_lib/validate.js';
+import { getSwapQuote, resolveChain, SUPPORTED_CHAINS } from '../../_lib/evm/swap-quotes.js';
+
+const HIT_CACHE_CONTROL = 'public, max-age=10, s-maxage=10';
+const RAW_AMOUNT_RE = /^[0-9]{1,78}$/;
+
+export default defineEndpoint({
+ name: 'v1.evm.swap-quote',
+ method: 'GET',
+ auth: 'public',
+ handler: async ({ res, query, ip }) => {
+ // Dedicated per-IP budget on top of the gateway's shared apiV1 guard:
+ // every cache miss fans out to up to three real upstreams, and the last
+ // rung (LI.FI) is keyless with its own tight rate limits, so this caps a
+ // scripted quote flood before it burns the shared lane.
+ const rl = await limits.apiIp(ip, { limit: 30, window: '1 m' });
+ if (!rl.success) return rateLimited(res, rl, 'swap quotes are capped at 30 requests/min per IP');
+
+ const chain = resolveChain(typeof query.chain === 'string' ? query.chain : '');
+ if (!chain) {
+ fail(
+ 400,
+ 'validation_error',
+ `chain must be one of ${SUPPORTED_CHAINS.join(', ')} (aliases like eth/matic/arb/op/bnb and numeric chain ids work too)`,
+ );
+ }
+
+ const sellToken = typeof query.sellToken === 'string' ? query.sellToken.trim() : '';
+ const buyToken = typeof query.buyToken === 'string' ? query.buyToken.trim() : '';
+ if (!isValidEvmAddress(sellToken)) {
+ fail(400, 'validation_error', 'sellToken must be a 0x token address (0xeeee...eeee for the native coin)');
+ }
+ if (!isValidEvmAddress(buyToken)) {
+ fail(400, 'validation_error', 'buyToken must be a 0x token address (0xeeee...eeee for the native coin)');
+ }
+ if (sellToken.toLowerCase() === buyToken.toLowerCase()) {
+ fail(400, 'validation_error', 'sellToken and buyToken must differ');
+ }
+
+ const amount = typeof query.amount === 'string' ? query.amount.trim() : '';
+ if (!RAW_AMOUNT_RE.test(amount) || BigInt(amount) <= 0n) {
+ fail(
+ 400,
+ 'validation_error',
+ 'amount must be a positive integer in the sell token\'s RAW base units (e.g. 1000000000000000000 for 1 WETH)',
+ );
+ }
+
+ let result;
+ try {
+ result = await getSwapQuote({ chain, sellToken, buyToken, amount });
+ } catch (err) {
+ const runs = Array.isArray(err?.attempts)
+ ? err.attempts.map((a) => `${a.provider}: ${a.error}`).join('; ')
+ : 'no provider reachable';
+ fail(502, 'quote_unavailable', `no provider returned a quote (${runs}) - retry shortly`);
+ }
+
+ res.setHeader('cache-control', HIT_CACHE_CONTROL);
+ return result;
+ },
+});
diff --git a/tests/api/v1-evm-swap-quote.test.js b/tests/api/v1-evm-swap-quote.test.js
new file mode 100644
index 000000000..22b420d03
--- /dev/null
+++ b/tests/api/v1-evm-swap-quote.test.js
@@ -0,0 +1,438 @@
+// Keyless EVM swap-quote chain (api/_lib/evm/swap-quotes.js) and its endpoint
+// (GET /api/v1/evm/swap-quote).
+//
+// Every rung of the quote chain must be REACHABLE, proven by failing the rungs
+// above it at the TRANSPORT level (a thrown fetch: ECONNRESET or an abort),
+// the way a provider actually dies. A chain tested only with parsed error
+// bodies looks healthy while the real failure mode walks straight past it;
+// tests/api/llm-free-chain-reachability.test.js documents the incident that
+// made this the house style for fallback chains.
+//
+// Fixtures are trimmed captures of REAL responses from the three live
+// endpoints (curl-verified 2026-08-05, WETH -> USDC on Base):
+// ParaSwap GET api.paraswap.io/prices -> { priceRoute }
+// KyberSwap GET aggregator-api.kyberswap.com/base/api/v1/routes
+// -> { code: 0, data: { routeSummary } }
+// LI.FI GET li.quest/v1/quote -> { estimate, action, tool }
+// No test opens a real socket: global fetch is stubbed per-host.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+const WETH_BASE = '0x4200000000000000000000000000000000000006';
+const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+const ONE_WETH = '1000000000000000000';
+
+const HOSTS = {
+ paraswap: 'api.paraswap.io',
+ kyberswap: 'aggregator-api.kyberswap.com',
+ lifi: 'li.quest',
+};
+
+// ── Real-shape fixtures (trimmed live captures) ─────────────────────────────
+
+const PARASWAP_BODY = {
+ priceRoute: {
+ blockNumber: 49592462,
+ network: 8453,
+ srcToken: WETH_BASE.toLowerCase(),
+ srcDecimals: 18,
+ srcAmount: ONE_WETH,
+ destToken: USDC_BASE.toLowerCase(),
+ destDecimals: 6,
+ destAmount: '1912283226',
+ bestRoute: [
+ { percent: 100, swaps: [{ swapExchanges: [{ exchange: 'CurveV1StableNg', percent: 100 }] }] },
+ ],
+ gasCostUSD: '0.003527',
+ gasCost: '302300',
+ side: 'SELL',
+ srcUSD: '1908.0400000000',
+ destUSD: '1911.5297864090',
+ },
+};
+
+const KYBER_BODY = {
+ code: 0,
+ message: 'successfully',
+ data: {
+ routeSummary: {
+ tokenIn: WETH_BASE.toLowerCase(),
+ amountIn: ONE_WETH,
+ amountInUsd: '1908.8696524460145',
+ tokenOut: USDC_BASE.toLowerCase(),
+ amountOut: '1906692387',
+ amountOutUsd: '1909.011824429036',
+ gas: '2615965',
+ gasUsd: '0.029961217202165626',
+ route: [[{ exchange: 'uniswap-v4-fairflow', poolType: 'uniswap-v4' }]],
+ },
+ },
+};
+
+const LIFI_BODY = {
+ type: 'lifi',
+ tool: 'fly',
+ action: {
+ fromToken: { address: WETH_BASE, chainId: 8453, symbol: 'WETH', decimals: 18 },
+ toToken: { address: USDC_BASE, chainId: 8453, symbol: 'USDC', decimals: 6 },
+ fromChainId: 8453,
+ toChainId: 8453,
+ },
+ estimate: {
+ tool: 'fly',
+ fromAmount: ONE_WETH,
+ toAmount: '1907503064',
+ toAmountMin: '1897965549',
+ fromAmountUSD: '1908.09',
+ toAmountUSD: '1900.79',
+ gasCosts: [{ type: 'SEND', estimate: '375000', amountUSD: '0.011' }],
+ },
+};
+
+// How a provider dies for real: the socket drops, or the attempt is aborted.
+function transportFailure(kind) {
+ if (kind === 'abort') return Object.assign(new Error('The operation was aborted'), { name: 'AbortError' });
+ return Object.assign(new Error('fetch failed: ECONNRESET'), { cause: { code: 'ECONNRESET' } });
+}
+
+const jsonResp = (body, status = 200) => ({
+ ok: status >= 200 && status < 300,
+ status,
+ text: async () => JSON.stringify(body),
+});
+
+// Per-host behavior for the stubbed fetch. Each entry is either a function
+// returning a response object or an Error instance to throw (transport death).
+let hostPlan = {};
+let fetchLog = [];
+
+function stubFetch() {
+ vi.stubGlobal('fetch', async (input) => {
+ const url = new URL(String(input));
+ fetchLog.push(url);
+ const plan = hostPlan[url.host];
+ if (!plan) throw new Error(`unexpected fetch to ${url.host} in test`);
+ const step = typeof plan === 'function' ? plan(url) : plan;
+ if (step instanceof Error) throw step;
+ return step;
+ });
+}
+
+// Switchable quotas, mirroring the v1-resolve test harness.
+let apiV1Ok = true;
+let quoteIpOk = true;
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ apiV1: async () =>
+ apiV1Ok
+ ? { success: true, limit: 120, remaining: 119, reset: Date.now() + 60_000 }
+ : { success: false, limit: 120, remaining: 0, reset: Date.now() + 60_000 },
+ apiIp: async () =>
+ quoteIpOk
+ ? { success: true, limit: 30, remaining: 29, reset: Date.now() + 60_000 }
+ : { success: false, limit: 30, remaining: 0, reset: Date.now() + 60_000 },
+ },
+ clientIp: () => '203.0.113.9',
+}));
+
+beforeEach(() => {
+ apiV1Ok = true;
+ quoteIpOk = true;
+ hostPlan = {};
+ fetchLog = [];
+ stubFetch();
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+async function lib() {
+ return import('../../api/_lib/evm/swap-quotes.js');
+}
+
+const baseParams = async () => {
+ const { resolveChain } = await lib();
+ return {
+ chain: resolveChain('base'),
+ sellToken: WETH_BASE,
+ buyToken: USDC_BASE,
+ amount: ONE_WETH,
+ timeoutMs: 1000,
+ };
+};
+
+// ── Chain identity ──────────────────────────────────────────────────────────
+describe('swap-quotes chain map', () => {
+ it('lists the rungs in the documented order: paraswap, kyberswap, lifi', async () => {
+ const { QUOTE_PROVIDERS } = await lib();
+ expect(QUOTE_PROVIDERS.map((p) => p.name)).toEqual(['paraswap', 'kyberswap', 'lifi']);
+ });
+
+ it('covers the six required chains and maps names, aliases, and ids per provider', async () => {
+ const { resolveChain, SUPPORTED_CHAINS } = await lib();
+ expect(SUPPORTED_CHAINS).toEqual(['ethereum', 'base', 'polygon', 'arbitrum', 'optimism', 'bsc']);
+ expect(resolveChain('ethereum')).toEqual({ key: 'ethereum', chainId: 1, kyber: 'ethereum' });
+ expect(resolveChain('eth')).toEqual({ key: 'ethereum', chainId: 1, kyber: 'ethereum' });
+ expect(resolveChain('BASE')).toEqual({ key: 'base', chainId: 8453, kyber: 'base' });
+ expect(resolveChain('matic')).toEqual({ key: 'polygon', chainId: 137, kyber: 'polygon' });
+ expect(resolveChain('arb')).toEqual({ key: 'arbitrum', chainId: 42161, kyber: 'arbitrum' });
+ expect(resolveChain('op')).toEqual({ key: 'optimism', chainId: 10, kyber: 'optimism' });
+ expect(resolveChain('bnb')).toEqual({ key: 'bsc', chainId: 56, kyber: 'bsc' });
+ expect(resolveChain(8453)).toEqual({ key: 'base', chainId: 8453, kyber: 'base' });
+ expect(resolveChain('56')).toEqual({ key: 'bsc', chainId: 56, kyber: 'bsc' });
+ expect(resolveChain('solana')).toBeNull();
+ expect(resolveChain('')).toBeNull();
+ });
+});
+
+// ── Rung 1 wins ─────────────────────────────────────────────────────────────
+describe('getSwapQuote: first success wins', () => {
+ it('returns a normalized ParaSwap quote and never touches the rungs below', async () => {
+ hostPlan[HOSTS.paraswap] = () => jsonResp(PARASWAP_BODY);
+ const { getSwapQuote } = await lib();
+ const { quote, provider, attempts } = await getSwapQuote(await baseParams());
+
+ expect(provider).toBe('paraswap');
+ expect(attempts).toEqual([{ provider: 'paraswap', ok: true, latencyMs: expect.any(Number) }]);
+ expect(fetchLog).toHaveLength(1);
+ expect(fetchLog[0].host).toBe(HOSTS.paraswap);
+ expect(fetchLog[0].pathname).toBe('/prices');
+ expect(fetchLog[0].searchParams.get('network')).toBe('8453');
+ expect(fetchLog[0].searchParams.get('side')).toBe('SELL');
+ expect(fetchLog[0].searchParams.get('amount')).toBe(ONE_WETH);
+
+ expect(quote).toEqual({
+ provider: 'paraswap',
+ chain: 'base',
+ chainId: 8453,
+ sellToken: WETH_BASE,
+ buyToken: USDC_BASE,
+ sellAmount: ONE_WETH,
+ buyAmount: '1912283226',
+ price: 1912.283226,
+ estimatedGas: '302300',
+ gasUsd: 0.003527,
+ sellAmountUsd: 1908.04,
+ buyAmountUsd: 1911.529786409,
+ venue: 'CurveV1StableNg',
+ });
+ });
+});
+
+// ── Transport-level failover, rung by rung ──────────────────────────────────
+describe('getSwapQuote: every rung is reachable through a transport-level failure', () => {
+ it('falls to KyberSwap when ParaSwap dies at the socket, on the per-chain host segment', async () => {
+ hostPlan[HOSTS.paraswap] = transportFailure('econnreset');
+ hostPlan[HOSTS.kyberswap] = () => jsonResp(KYBER_BODY);
+ const { getSwapQuote } = await lib();
+ const { quote, provider, attempts } = await getSwapQuote(await baseParams());
+
+ expect(provider).toBe('kyberswap');
+ expect(attempts.map((a) => [a.provider, a.ok])).toEqual([
+ ['paraswap', false],
+ ['kyberswap', true],
+ ]);
+ expect(attempts[0].error).toMatch(/ECONNRESET/);
+ const kyberUrl = fetchLog.find((u) => u.host === HOSTS.kyberswap);
+ expect(kyberUrl.pathname).toBe('/base/api/v1/routes');
+ expect(kyberUrl.searchParams.get('amountIn')).toBe(ONE_WETH);
+
+ expect(quote).toEqual({
+ provider: 'kyberswap',
+ chain: 'base',
+ chainId: 8453,
+ sellToken: WETH_BASE,
+ buyToken: USDC_BASE,
+ sellAmount: ONE_WETH,
+ buyAmount: '1906692387',
+ price: null,
+ estimatedGas: '2615965',
+ gasUsd: 0.029961217202165626,
+ sellAmountUsd: 1908.8696524460145,
+ buyAmountUsd: 1909.011824429036,
+ venue: 'uniswap-v4-fairflow',
+ });
+ });
+
+ it('falls to LI.FI when ParaSwap and KyberSwap both die (reset + abort)', async () => {
+ hostPlan[HOSTS.paraswap] = transportFailure('econnreset');
+ hostPlan[HOSTS.kyberswap] = transportFailure('abort');
+ hostPlan[HOSTS.lifi] = () => jsonResp(LIFI_BODY);
+ const { getSwapQuote } = await lib();
+ const { quote, provider, attempts } = await getSwapQuote(await baseParams());
+
+ expect(provider).toBe('lifi');
+ expect(attempts.map((a) => [a.provider, a.ok])).toEqual([
+ ['paraswap', false],
+ ['kyberswap', false],
+ ['lifi', true],
+ ]);
+ const lifiUrl = fetchLog.find((u) => u.host === HOSTS.lifi);
+ expect(lifiUrl.pathname).toBe('/v1/quote');
+ expect(lifiUrl.searchParams.get('fromChain')).toBe('8453');
+ expect(lifiUrl.searchParams.get('toChain')).toBe('8453');
+ // The quote read supplies the burn placeholder, never a user wallet.
+ expect(lifiUrl.searchParams.get('fromAddress')).toBe('0x000000000000000000000000000000000000dEaD');
+
+ expect(quote).toEqual({
+ provider: 'lifi',
+ chain: 'base',
+ chainId: 8453,
+ sellToken: WETH_BASE,
+ buyToken: USDC_BASE,
+ sellAmount: ONE_WETH,
+ buyAmount: '1907503064',
+ price: 1907.503064,
+ estimatedGas: '375000',
+ gasUsd: 0.011,
+ sellAmountUsd: 1908.09,
+ buyAmountUsd: 1900.79,
+ venue: 'fly',
+ });
+ });
+
+ it('fails soft past a ParaSwap HTTP error and a KyberSwap non-zero code body', async () => {
+ hostPlan[HOSTS.paraswap] = () => jsonResp({ error: 'No routes found with enough liquidity' }, 404);
+ hostPlan[HOSTS.kyberswap] = () => jsonResp({ code: 4005, message: 'route not found' });
+ hostPlan[HOSTS.lifi] = () => jsonResp(LIFI_BODY);
+ const { getSwapQuote } = await lib();
+ const { provider, attempts } = await getSwapQuote(await baseParams());
+
+ expect(provider).toBe('lifi');
+ expect(attempts[0].error).toMatch(/paraswap 404/);
+ expect(attempts[1].error).toMatch(/route not found/);
+ });
+
+ it('throws with the full attempt log when every rung is down', async () => {
+ hostPlan[HOSTS.paraswap] = transportFailure('econnreset');
+ hostPlan[HOSTS.kyberswap] = transportFailure('econnreset');
+ hostPlan[HOSTS.lifi] = transportFailure('abort');
+ const { getSwapQuote } = await lib();
+
+ const err = await getSwapQuote(await baseParams()).then(
+ () => null,
+ (e) => e,
+ );
+ expect(err).toBeTruthy();
+ expect(err.message).toMatch(/every quote provider failed/);
+ expect(err.attempts.map((a) => a.provider)).toEqual(['paraswap', 'kyberswap', 'lifi']);
+ expect(err.attempts.every((a) => a.ok === false)).toBe(true);
+ });
+});
+
+// ── The endpoint ────────────────────────────────────────────────────────────
+
+function makeReq({ url, host = 'three.ws' } = {}) {
+ const stream = Readable.from([]);
+ stream.method = 'GET';
+ stream.url = url;
+ stream.headers = { host };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; this.writableEnded = true; },
+ };
+}
+
+async function dispatch(req, res) {
+ const mod = await import('../../api/v1/evm/swap-quote.js');
+ await mod.default(req, res);
+ return { res, body: res._body ? JSON.parse(res._body) : null };
+}
+
+const quoteUrl = (over = {}) => {
+ const q = new URLSearchParams({
+ chain: 'base',
+ sellToken: WETH_BASE,
+ buyToken: USDC_BASE,
+ amount: ONE_WETH,
+ ...over,
+ });
+ for (const [k, v] of [...q]) if (v === '') q.delete(k);
+ return `/api/v1/evm/swap-quote?${q}`;
+};
+
+describe('GET /api/v1/evm/swap-quote', () => {
+ it('serves the normalized best quote, names the provider, and caches briefly', async () => {
+ hostPlan[HOSTS.paraswap] = () => jsonResp(PARASWAP_BODY);
+ const { res, body } = await dispatch(makeReq({ url: quoteUrl() }), makeRes());
+
+ expect(res.statusCode).toBe(200);
+ expect(body.data.provider).toBe('paraswap');
+ expect(body.data.quote.buyAmount).toBe('1912283226');
+ expect(body.data.quote.price).toBe(1912.283226);
+ expect(body.data.attempts).toHaveLength(1);
+ expect(res.getHeader('cache-control')).toMatch(/max-age=10/);
+ });
+
+ it('accepts a numeric chain id and quotes through the failover rung', async () => {
+ hostPlan[HOSTS.paraswap] = transportFailure('econnreset');
+ hostPlan[HOSTS.kyberswap] = () => jsonResp(KYBER_BODY);
+ const { res, body } = await dispatch(makeReq({ url: quoteUrl({ chain: '8453' }) }), makeRes());
+
+ expect(res.statusCode).toBe(200);
+ expect(body.data.provider).toBe('kyberswap');
+ expect(body.data.attempts.map((a) => a.ok)).toEqual([false, true]);
+ });
+
+ it('rejects an unsupported chain with 400 naming the supported set', async () => {
+ const { res, body } = await dispatch(makeReq({ url: quoteUrl({ chain: 'solana' }) }), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(body.error_description).toMatch(/ethereum, base, polygon, arbitrum, optimism, bsc/);
+ });
+
+ it('rejects a malformed token address with 400', async () => {
+ const { res, body } = await dispatch(makeReq({ url: quoteUrl({ sellToken: 'weth' }) }), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(body.error_description).toMatch(/sellToken/);
+ });
+
+ it('rejects identical sell and buy tokens with 400', async () => {
+ const url = quoteUrl({ buyToken: WETH_BASE.toLowerCase() });
+ const { res, body } = await dispatch(makeReq({ url }), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error_description).toMatch(/must differ/);
+ });
+
+ it('rejects a non-integer or zero amount with 400', async () => {
+ for (const amount of ['1.5', '0', '-3', 'abc', '']) {
+ const { res, body } = await dispatch(makeReq({ url: quoteUrl({ amount }) }), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(body.error_description).toMatch(/RAW base units/);
+ }
+ });
+
+ it('returns 502 quote_unavailable (never 500) naming each rung when all providers fail', async () => {
+ hostPlan[HOSTS.paraswap] = transportFailure('econnreset');
+ hostPlan[HOSTS.kyberswap] = transportFailure('abort');
+ hostPlan[HOSTS.lifi] = transportFailure('econnreset');
+ const { res, body } = await dispatch(makeReq({ url: quoteUrl() }), makeRes());
+
+ expect(res.statusCode).toBe(502);
+ expect(body.error).toBe('quote_unavailable');
+ expect(body.error_description).toMatch(/paraswap/);
+ expect(body.error_description).toMatch(/kyberswap/);
+ expect(body.error_description).toMatch(/lifi/);
+ });
+
+ it('returns 429 when the per-IP quote quota is exhausted, before any upstream call', async () => {
+ quoteIpOk = false;
+ const { res, body } = await dispatch(makeReq({ url: quoteUrl() }), makeRes());
+ expect(res.statusCode).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ expect(fetchLog).toHaveLength(0);
+ });
+});