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
feat(evm): keyless gas price endpoint with a Blocknative, Owlracle, Etherscan failover chain
nirholas28be1950858d
diff --git a/.env.example b/.env.exampleindex 46ce0c6b6..ef90f1583 100644--- a/.env.example+++ b/.env.example@@ -309,6 +309,13 @@ WEB3_STORAGE_TOKEN=# Get one at https://birdeye.so — free tier allows ~100 req/min.BIRDEYE_API_KEY=+# ── EVM gas oracle chain (api/_lib/gas-oracles.js, GET /api/v1/gas) ────────+# Both optional: the keyless path fully works without them.+# Blocknative Gas API (https://www.blocknative.com/gas-platform); a key raises rate limits.+BLOCKNATIVE_API_KEY=+# Owlracle (https://owlracle.info); a key swaps the shared guest quota for a private one.+OWLRACLE_API_KEY=+# ── Pump.fun live feed integration (api/_lib/pumpfun-mcp.js) ──────────────# Upstream pumpfun-claims-bot MCP server URL. When set, /api/agents/pumpfun# and /api/agents/pumpfun-feed are enabled, the cron at /api/cron/pumpfun-signalsdiff --git a/api/_lib/gas-oracles.js b/api/_lib/gas-oracles.jsnew file mode 100644index 000000000..4f2592130--- /dev/null+++ b/api/_lib/gas-oracles.js@@ -0,0 +1,303 @@+// Keyless-first EVM gas price oracle chain.+//+// One question, three rungs, zero required credentials:+//+// 1. Blocknative Gas API (api.blocknative.com/gasprices/blockprices):+// probabilistic next-block estimates. Works KEYLESS at a lower rate+// limit; an optional BLOCKNATIVE_API_KEY raises it (sent as the raw+// `Authorization: <key>` header per Blocknative's docs, no Bearer+// prefix).+// 2. Owlracle (api.owlracle.info/v4/<network>/gas): history-derived speed+// tiers across many EVM networks. Keyless guest access with a shared+// guest quota (a burned quota answers 403, which fails soft here); an+// optional OWLRACLE_API_KEY (passed as the documented `apikey` query+// param) gets a private quota.+// 3. Etherscan V2 gas oracle (module=gastracker&action=gasoracle):+// Ethereum mainnet only. Uses the same ETHERSCAN_API_KEY /+// api.etherscan.io/v2/api pattern as x402/identity-claim-verify.js;+// also answers keyless at 1 req/5s, so the rung stays live either way.+//+// Every rung fails SOFT on its own timeout: a down/blocked/quota-starved+// provider costs one bounded fetch and the chain moves on. Rungs that do not+// serve the requested chain are skipped entirely (Etherscan is mainnet-only;+// Owlracle/Blocknative coverage is declared per chain below).+//+// The normalized shape every rung maps into:+// {+// chain, chainId, unit: 'gwei',+// baseFee, // current/suggested base fee, gwei (null if the source has none)+// tiers: { // cheapest → most aggressive+// safe: { maxFeePerGas, maxPriorityFeePerGas },+// standard: { maxFeePerGas, maxPriorityFeePerGas },+// fast: { maxFeePerGas, maxPriorityFeePerGas },+// },+// source, // 'blocknative' | 'owlracle' | 'etherscan'+// ts,+// }++import { env } from './env.js';++const BLOCKNATIVE_URL = 'https://api.blocknative.com/gasprices/blockprices';+const OWLRACLE_URL = 'https://api.owlracle.info/v4';+// Etherscan V2 unified multichain API, same base as x402/identity-claim-verify.js.+const ETHERSCAN_V2 = 'https://api.etherscan.io/v2/api';++// Per-rung fetch budget. Gas answers are only useful fresh, so a slow rung is+// treated as a dead rung: cheaper to fall through than to wait.+const RUNG_TIMEOUT_MS = 3500;++// Optional per-provider keys. These two are not yet declared in env.js (that+// file is shared config owned elsewhere); read them with the same trim-or-+// undefined semantics as env.js's cred()/opt() helpers so a dashboard paste+// with a trailing newline never poisons a header or query param.+function optionalKey(name) {+ const v = process.env[name];+ if (v == null) return undefined;+ const t = String(v).trim();+ return t || undefined;+}++// ── Chain registry ──────────────────────────────────────────────────────────+// Which rungs serve which chain, plus the identifier each provider expects.+// blocknative: EVM chainId passed as ?chainid= (only chains Blocknative's+// Gas API serves; it 4xx's fast on others, but declaring+// coverage keeps the chain honest and the logs quiet).+// owlracle: the network code in /v4/<network>/gas. Verified live:+// eth/base/bsc/poly/arb/opt answer keyless; avax/ftm/cro/+// linea/movr/one are valid networks behind the guest quota.+// etherscan: gastracker gas oracle, Ethereum mainnet only.+const CHAINS = {+ ethereum: { chainId: 1, blocknative: true, owlracle: 'eth', etherscan: true },+ base: { chainId: 8453, blocknative: true, owlracle: 'base' },+ bsc: { chainId: 56, blocknative: true, owlracle: 'bsc' },+ polygon: { chainId: 137, blocknative: true, owlracle: 'poly' },+ arbitrum: { chainId: 42161, blocknative: true, owlracle: 'arb' },+ optimism: { chainId: 10, blocknative: true, owlracle: 'opt' },+ avalanche: { chainId: 43114, blocknative: true, owlracle: 'avax' },+ linea: { chainId: 59144, blocknative: true, owlracle: 'linea' },+ fantom: { chainId: 250, owlracle: 'ftm' },+ cronos: { chainId: 25, owlracle: 'cro' },+ moonriver: { chainId: 1285, owlracle: 'movr' },+ harmony: { chainId: 1666600000, owlracle: 'one' },+};++// Accepted spellings → canonical chain key. Numeric chainIds resolve too, so+// callers holding an eip155 id never need a name table of their own.+const ALIASES = {+ eth: 'ethereum',+ mainnet: 'ethereum',+ bnb: 'bsc',+ binance: 'bsc',+ poly: 'polygon',+ matic: 'polygon',+ arb: 'arbitrum',+ op: 'optimism',+ opt: 'optimism',+ avax: 'avalanche',+ ftm: 'fantom',+ cro: 'cronos',+ movr: 'moonriver',+ one: 'harmony',+};++/**+ * Resolve a user-supplied chain string (name, alias, or numeric chainId,+ * optionally `eip155:`-prefixed) to a canonical chain key, or null.+ * @param {string|number} input+ * @returns {string|null}+ */+export function resolveGasChain(input) {+ const raw = String(input ?? '').trim().toLowerCase().replace(/^eip155:/, '');+ if (!raw) return null;+ if (CHAINS[raw]) return raw;+ if (ALIASES[raw]) return ALIASES[raw];+ if (/^\d+$/.test(raw)) {+ const id = Number(raw);+ for (const [key, meta] of Object.entries(CHAINS)) {+ if (meta.chainId === id) return key;+ }+ }+ return null;+}++/**+ * Supported chains with the oracle rungs that serve each; powers the+ * endpoint's discovery/error copy and keeps docs derivable, never hand-listed.+ * @returns {Array<{chain: string, chainId: number, sources: string[]}>}+ */+export function listGasChains() {+ return Object.entries(CHAINS).map(([chain, meta]) => ({+ chain,+ chainId: meta.chainId,+ sources: rungsFor(chain).map((r) => r.source),+ }));+}++// Round to 4 decimal places: gwei values below 0.0001 are noise for fee+// estimation, and it keeps L2 sub-gwei fees readable without float dust.+function gwei(n) {+ const v = Number(n);+ if (!Number.isFinite(v)) return null;+ return Math.round(v * 10_000) / 10_000;+}++function tier(maxFeePerGas, maxPriorityFeePerGas) {+ return { maxFeePerGas: gwei(maxFeePerGas), maxPriorityFeePerGas: gwei(maxPriorityFeePerGas) };+}++async function fetchJson(fetchImpl, url, { headers } = {}) {+ const res = await fetchImpl(url, {+ headers: { accept: 'application/json', ...headers },+ signal: AbortSignal.timeout(RUNG_TIMEOUT_MS),+ });+ if (!res.ok) throw new Error(`http_${res.status}`);+ return res.json();+}++// ── Rung 1: Blocknative ─────────────────────────────────────────────────────+// Response: { unit:'gwei', blockPrices: [{ baseFeePerGas, estimatedPrices:+// [{ confidence, price, maxPriorityFeePerGas, maxFeePerGas }, …] }] }.+// Confidence levels run 99/95/90/80/70; we map fast=highest, safe=lowest,+// standard=nearest to 90 so a trimmed-down response still yields three tiers.+async function fromBlocknative(chainKey, meta, fetchImpl) {+ const key = optionalKey('BLOCKNATIVE_API_KEY');+ const data = await fetchJson(fetchImpl, `${BLOCKNATIVE_URL}?chainid=${meta.chainId}`, {+ headers: key ? { authorization: key } : {},+ });+ const block = Array.isArray(data?.blockPrices) ? data.blockPrices[0] : null;+ const prices = Array.isArray(block?.estimatedPrices) ? block.estimatedPrices : [];+ const usable = prices.filter((p) => Number.isFinite(Number(p?.maxFeePerGas)));+ if (usable.length === 0) throw new Error('no_estimated_prices');++ const byConfDesc = [...usable].sort((a, b) => Number(b.confidence) - Number(a.confidence));+ const fast = byConfDesc[0];+ const safe = byConfDesc[byConfDesc.length - 1];+ const standard = [...usable].sort(+ (a, b) => Math.abs(Number(a.confidence) - 90) - Math.abs(Number(b.confidence) - 90),+ )[0];++ return {+ chain: chainKey,+ chainId: meta.chainId,+ unit: 'gwei',+ baseFee: gwei(block?.baseFeePerGas),+ tiers: {+ safe: tier(safe.maxFeePerGas, safe.maxPriorityFeePerGas),+ standard: tier(standard.maxFeePerGas, standard.maxPriorityFeePerGas),+ fast: tier(fast.maxFeePerGas, fast.maxPriorityFeePerGas),+ },+ source: 'blocknative',+ ts: Date.now(),+ };+}++// ── Rung 2: Owlracle ────────────────────────────────────────────────────────+// Response: { speeds: [{ acceptance, maxFeePerGas, maxPriorityFeePerGas,+// baseFee, estimatedFee }, …] } with speeds ascending by acceptance+// (slow → standard → fast → instant). We take the first three as+// safe/standard/fast; the acceptance:1 "instant" tier prices in outlier+// spikes and would overpay every routine transaction.+async function fromOwlracle(chainKey, meta, fetchImpl) {+ const key = optionalKey('OWLRACLE_API_KEY');+ const qs = key ? `?apikey=${encodeURIComponent(key)}` : '';+ const data = await fetchJson(fetchImpl, `${OWLRACLE_URL}/${meta.owlracle}/gas${qs}`);+ const speeds = (Array.isArray(data?.speeds) ? data.speeds : []).filter((s) =>+ Number.isFinite(Number(s?.maxFeePerGas)),+ );+ if (speeds.length === 0) throw new Error('no_speeds');++ const safe = speeds[0];+ const standard = speeds[Math.min(1, speeds.length - 1)];+ const fast = speeds[Math.min(2, speeds.length - 1)];+ const baseFee = [standard, safe, fast].map((s) => Number(s?.baseFee)).find(Number.isFinite);++ return {+ chain: chainKey,+ chainId: meta.chainId,+ unit: 'gwei',+ baseFee: gwei(baseFee),+ tiers: {+ safe: tier(safe.maxFeePerGas, safe.maxPriorityFeePerGas),+ standard: tier(standard.maxFeePerGas, standard.maxPriorityFeePerGas),+ fast: tier(fast.maxFeePerGas, fast.maxPriorityFeePerGas),+ },+ source: 'owlracle',+ ts: Date.now(),+ };+}++// ── Rung 3: Etherscan V2 gas oracle (Ethereum mainnet only) ─────────────────+// Response result: { SafeGasPrice, ProposeGasPrice, FastGasPrice,+// suggestBaseFee }: legacy-style TOTAL gas prices in gwei. The priority fee+// per tier is recovered as (total - suggestBaseFee), floored at 0. Works+// keyless at 1 req/5s; ETHERSCAN_API_KEY (already provisioned for the+// identity-claim verifier) lifts that.+async function fromEtherscan(chainKey, meta, fetchImpl) {+ const key = env.ETHERSCAN_API_KEY;+ const url =+ `${ETHERSCAN_V2}?chainid=${meta.chainId}&module=gastracker&action=gasoracle` ++ (key ? `&apikey=${encodeURIComponent(key)}` : '');+ const data = await fetchJson(fetchImpl, url);+ const r = data?.result;+ if (data?.status !== '1' || !r || !Number.isFinite(Number(r.SafeGasPrice))) {+ // Etherscan reports rate-limiting and bad params as status "0" with the+ // detail in `result` (a string); surface it as the failure reason.+ throw new Error(typeof r === 'string' ? r.slice(0, 120) : 'bad_gasoracle_response');+ }+ const baseFee = Number(r.suggestBaseFee);+ const t = (total) => {+ const totalNum = Number(total);+ const priority = Number.isFinite(baseFee) ? Math.max(0, totalNum - baseFee) : null;+ return tier(totalNum, priority);+ };+ return {+ chain: chainKey,+ chainId: meta.chainId,+ unit: 'gwei',+ baseFee: gwei(baseFee),+ tiers: { safe: t(r.SafeGasPrice), standard: t(r.ProposeGasPrice), fast: t(r.FastGasPrice) },+ source: 'etherscan',+ ts: Date.now(),+ };+}++function rungsFor(chainKey) {+ const meta = CHAINS[chainKey];+ const rungs = [];+ if (meta.blocknative) rungs.push({ source: 'blocknative', run: fromBlocknative });+ if (meta.owlracle) rungs.push({ source: 'owlracle', run: fromOwlracle });+ if (meta.etherscan) rungs.push({ source: 'etherscan', run: fromEtherscan });+ return rungs;+}++/**+ * Get a normalized gas estimate for a chain, trying Blocknative → Owlracle →+ * Etherscan (skipping rungs that do not serve the chain). Each rung fails+ * soft on error/timeout; the first success wins.+ *+ * @param {string|number} chain Chain name, alias, or numeric chainId.+ * @param {{ fetchImpl?: typeof fetch }} [opts] Injectable fetch for tests.+ * @returns {Promise<object>} the normalized estimate (shape at top of file)+ * @throws {Error} code 'unsupported_chain' for an unknown chain; code+ * 'gas_sources_unavailable' (with `.attempts` naming each rung's failure)+ * when every serving rung failed.+ */+export async function getGasEstimate(chain, { fetchImpl = fetch } = {}) {+ const chainKey = resolveGasChain(chain);+ if (!chainKey) {+ throw Object.assign(new Error(`unsupported chain: ${chain}`), { code: 'unsupported_chain' });+ }+ const meta = CHAINS[chainKey];+ const attempts = [];+ for (const rung of rungsFor(chainKey)) {+ try {+ return await rung.run(chainKey, meta, fetchImpl);+ } catch (err) {+ attempts.push({ source: rung.source, error: err?.message || String(err) });+ }+ }+ throw Object.assign(new Error(`all gas oracles failed for ${chainKey}`), {+ code: 'gas_sources_unavailable',+ attempts,+ });+}diff --git a/api/v1/_catalog.js b/api/v1/_catalog.jsindex 8d58520f8..833b4518e 100644--- a/api/v1/_catalog.js+++ b/api/v1/_catalog.js@@ -177,6 +177,19 @@ export const CATALOG = [chain: 'string — "ethereum" | "solana", optional hint validated against address (auto-detected from format when omitted)',},},+ {+ id: 'v1.gas',+ method: 'GET',+ path: '/api/v1/gas',+ auth: 'public',+ summary:+ 'Keyless EVM gas prices for 12 chains: normalized safe/standard/fast maxFee/maxPriorityFee ' ++ 'tiers plus baseFee (gwei), from a Blocknative -> Owlracle -> Etherscan failover chain, ' ++ 'cached 10s per chain.',+ params: {+ chain: 'string: chain name, alias, or numeric chainId (default ethereum); ?chains=1 lists supported chains',+ },+ },{id: 'v1.evm.swap-quote',method: 'GET',diff --git a/api/v1/gas.js b/api/v1/gas.jsnew file mode 100644index 000000000..6bfe00621--- /dev/null+++ b/api/v1/gas.js@@ -0,0 +1,70 @@+// GET /api/v1/gas: keyless-first EVM gas prices for agents, one call, any chain.+//+// "What should I pay for gas right now?" answered with real next-block data,+// no API key, no wallet. Wraps the shared oracle chain in+// api/_lib/gas-oracles.js: Blocknative → Owlracle → Etherscan V2 (mainnet+// only), each rung keyless-capable and failing soft on its own timeout, so+// one starved guest quota or blocked host never takes the answer down.+//+// GET /api/v1/gas?chain=base → normalized safe/standard/fast tiers+// GET /api/v1/gas → defaults to Ethereum mainnet+// GET /api/v1/gas?chains=1 → list supported chains + their sources+//+// Answers are cached server-side for one block-ish (10s) per chain, which is+// what actually protects the keyless upstream quotas: no matter how many+// clients ask, each chain costs at most ~6 upstream calls a minute.++import { defineEndpoint, fail } from '../_lib/gateway.js';+import { cacheWrap } from '../_lib/cache.js';+import { getGasEstimate, resolveGasChain, listGasChains } from '../_lib/gas-oracles.js';++const CACHE_TTL_SECONDS = 10;++export default defineEndpoint({+ name: 'v1.gas',+ method: 'GET',+ auth: 'public',+ handler: async ({ res, query }) => {+ // Discovery: the supported-chain table, derived from the oracle registry+ // so it can never drift from what getGasEstimate actually serves.+ if (query.chains === '1' || query.chains === 'true') {+ res.setHeader('cache-control', 'public, max-age=3600, s-maxage=3600');+ return { chains: listGasChains() };+ }++ const raw = typeof query.chain === 'string' && query.chain.trim() ? query.chain.trim() : 'ethereum';+ const chain = resolveGasChain(raw);+ if (!chain) {+ const supported = listGasChains().map((c) => c.chain).join(', ');+ fail(+ 400,+ 'unsupported_chain',+ `unknown chain "${raw}": pass a name, alias, or numeric chainId; supported: ${supported}`,+ );+ }++ try {+ const estimate = await cacheWrap(`gas:v1:${chain}`, CACHE_TTL_SECONDS, () =>+ getGasEstimate(chain),+ );+ // Public, cacheable read; set before returning so the gateway's+ // secure-by-default no-store doesn't override it.+ res.setHeader(+ 'cache-control',+ `public, max-age=${CACHE_TTL_SECONDS}, s-maxage=${CACHE_TTL_SECONDS}, stale-while-revalidate=30`,+ );+ return estimate;+ } catch (err) {+ if (err?.code === 'gas_sources_unavailable') {+ fail(+ 503,+ 'sources_unavailable',+ `every gas oracle serving ${chain} failed (${(err.attempts || [])+ .map((a) => `${a.source}: ${a.error}`)+ .join('; ')}); retry shortly`,+ );+ }+ throw err;+ }+ },+});diff --git a/tests/api/v1-gas.test.js b/tests/api/v1-gas.test.jsnew file mode 100644index 000000000..aed5a2203--- /dev/null+++ b/tests/api/v1-gas.test.js@@ -0,0 +1,413 @@+// GET /api/v1/gas + api/_lib/gas-oracles.js: keyless-first EVM gas oracle chain.+//+// The oracle chain tries Blocknative → Owlracle → Etherscan V2 (mainnet only),+// skipping rungs that do not serve the requested chain, each rung failing soft+// on its own timeout. These tests exercise the REAL provider mappers against+// captured live response shapes (Owlracle and Etherscan bodies captured from+// the real APIs on 2026-08-05; Blocknative per its documented blockprices+// contract) with fetch stubbed at the boundary (no test opens a socket), plus+// the endpoint contract: envelope, defaults, discovery, 400/429/503 paths.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { Readable } from 'node:stream';++// ── Captured / documented provider fixtures ─────────────────────────────────++// Blocknative blockprices: documented response shape (docs.blocknative.com),+// values in line with the live mainnet capture window below.+const BLOCKNATIVE_MAINNET = {+ system: 'ethereum',+ network: 'main',+ unit: 'gwei',+ maxPrice: 2,+ currentBlockNumber: 25692165,+ msSinceLastBlock: 4000,+ blockPrices: [+ {+ blockNumber: 25692166,+ estimatedTransactionCount: 120,+ baseFeePerGas: 0.104899732,+ estimatedPrices: [+ { confidence: 99, price: 0.34, maxPriorityFeePerGas: 0.228996727, maxFeePerGas: 0.371189757 },+ { confidence: 95, price: 0.14, maxPriorityFeePerGas: 0.0105, maxFeePerGas: 0.142193 },+ { confidence: 90, price: 0.13, maxPriorityFeePerGas: 0.008663652, maxFeePerGas: 0.131942596 },+ { confidence: 80, price: 0.12, maxPriorityFeePerGas: 0.006105707, maxFeePerGas: 0.117328939 },+ { confidence: 70, price: 0.11, maxPriorityFeePerGas: 0.005870803, maxFeePerGas: 0.110770535 },+ ],+ },+ ],+};++// Owlracle /v4/base/gas: captured live 2026-08-05. speeds ascend by+// acceptance: slow → standard → fast → instant.+const OWLRACLE_BASE = {+ timestamp: '2026-08-05T23:59:00.913Z',+ avgTime: 2,+ avgTx: 130.31,+ avgGas: 177672.5452001389,+ speeds: [+ { acceptance: 0.37, maxFeePerGas: 0.005500004, maxPriorityFeePerGas: 0.000500004, baseFee: 0.005, estimatedFee: 0.0018631094217399296 },+ { acceptance: 0.62, maxFeePerGas: 0.005500011, maxPriorityFeePerGas: 0.000500011, baseFee: 0.005, estimatedFee: 0.0018631117929683782 },+ { acceptance: 0.955, maxFeePerGas: 0.00575, maxPriorityFeePerGas: 0.00075, baseFee: 0.005, estimatedFee: 0.0019477947970591649 },+ { acceptance: 1, maxFeePerGas: 0.006, maxPriorityFeePerGas: 0.000981067, baseFee: 0.005018933, estimatedFee: 0.002032481527366085 },+ ],+};++// Etherscan V2 gastracker gasoracle: captured live 2026-08-05 (chainid=1).+const ETHERSCAN_MAINNET = {+ status: '1',+ message: 'OK',+ result: {+ LastBlock: '25692166',+ SafeGasPrice: '0.11201434',+ ProposeGasPrice: '0.112059969',+ FastGasPrice: '0.123265965',+ suggestBaseFee: '0.111877452',+ gasUsedRatio: '0.68,0.18,0.75,0.35,0.20',+ },+};++const jsonResponse = (body, status = 200) => ({+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+});++// Route a stubbed fetch by provider host. Records every call for assertions.+function providerFetch(routes) {+ const calls = [];+ const impl = async (url, opts = {}) => {+ calls.push({ url: String(url), opts });+ for (const [needle, responder] of Object.entries(routes)) {+ if (String(url).includes(needle)) return responder(String(url), opts);+ }+ throw new Error(`unrouted fetch: ${url}`);+ };+ impl.calls = calls;+ return impl;+}++const refused = () => Promise.reject(Object.assign(new Error('fetch failed'), { code: 'ECONNRESET' }));++beforeEach(() => {+ // The vitest setup loader pulls .env into process.env; pin every provider+ // key to a known state so URL/header assertions are deterministic.+ vi.stubEnv('BLOCKNATIVE_API_KEY', '');+ vi.stubEnv('OWLRACLE_API_KEY', '');+ vi.stubEnv('ETHERSCAN_API_KEY', '');+});+afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++// ── Chain resolution + registry ─────────────────────────────────────────────++describe('gas-oracles: chain resolution', () => {+ it('resolves names, aliases, numeric chainIds, and eip155 prefixes', async () => {+ const { resolveGasChain } = await import('../../api/_lib/gas-oracles.js');+ expect(resolveGasChain('ethereum')).toBe('ethereum');+ expect(resolveGasChain('eth')).toBe('ethereum');+ expect(resolveGasChain(' ETH ')).toBe('ethereum');+ expect(resolveGasChain('1')).toBe('ethereum');+ expect(resolveGasChain('8453')).toBe('base');+ expect(resolveGasChain('eip155:137')).toBe('polygon');+ expect(resolveGasChain('bnb')).toBe('bsc');+ expect(resolveGasChain('matic')).toBe('polygon');+ expect(resolveGasChain('op')).toBe('optimism');+ expect(resolveGasChain(42161)).toBe('arbitrum');+ expect(resolveGasChain('dogecoin')).toBe(null);+ expect(resolveGasChain('')).toBe(null);+ expect(resolveGasChain(undefined)).toBe(null);+ });++ it('declares chain-appropriate rungs: Etherscan mainnet-only, Owlracle everywhere', async () => {+ const { listGasChains } = await import('../../api/_lib/gas-oracles.js');+ const chains = listGasChains();+ const byName = Object.fromEntries(chains.map((c) => [c.chain, c]));++ expect(byName.ethereum.sources).toEqual(['blocknative', 'owlracle', 'etherscan']);+ expect(byName.base.sources).toEqual(['blocknative', 'owlracle']);+ expect(byName.fantom.sources).toEqual(['owlracle']);+ // The Etherscan gastracker rung serves Ethereum mainnet only.+ const withEtherscan = chains.filter((c) => c.sources.includes('etherscan'));+ expect(withEtherscan.map((c) => c.chain)).toEqual(['ethereum']);+ // Every chain keeps at least one keyless rung.+ for (const c of chains) expect(c.sources.length).toBeGreaterThan(0);+ });+});++// ── Provider mappers (real parsers, captured shapes) ────────────────────────++describe('gas-oracles: Blocknative rung', () => {+ it('maps blockprices to normalized tiers (fast=highest confidence, safe=lowest)', async () => {+ const { getGasEstimate } = await import('../../api/_lib/gas-oracles.js');+ const fetchImpl = providerFetch({+ 'api.blocknative.com': () => jsonResponse(BLOCKNATIVE_MAINNET),+ });+ const est = await getGasEstimate('ethereum', { fetchImpl });++ expect(est.source).toBe('blocknative');+ expect(est.chain).toBe('ethereum');+ expect(est.chainId).toBe(1);+ expect(est.unit).toBe('gwei');+ expect(est.baseFee).toBe(0.1049);+ expect(est.tiers.fast).toEqual({ maxFeePerGas: 0.3712, maxPriorityFeePerGas: 0.229 });+ expect(est.tiers.standard).toEqual({ maxFeePerGas: 0.1319, maxPriorityFeePerGas: 0.0087 });+ expect(est.tiers.safe).toEqual({ maxFeePerGas: 0.1108, maxPriorityFeePerGas: 0.0059 });+ expect(typeof est.ts).toBe('number');++ // Keyless call: chainid in the query, NO Authorization header.+ const call = fetchImpl.calls[0];+ expect(call.url).toContain('gasprices/blockprices?chainid=1');+ expect(call.opts.headers.authorization).toBeUndefined();+ });++ it('sends BLOCKNATIVE_API_KEY as a raw Authorization header when configured', async () => {+ vi.stubEnv('BLOCKNATIVE_API_KEY', 'bn-test-key');+ const { getGasEstimate } = await import('../../api/_lib/gas-oracles.js');+ const fetchImpl = providerFetch({+ 'api.blocknative.com': () => jsonResponse(BLOCKNATIVE_MAINNET),+ });+ await getGasEstimate('base', { fetchImpl });+ expect(fetchImpl.calls[0].url).toContain('chainid=8453');+ expect(fetchImpl.calls[0].opts.headers.authorization).toBe('bn-test-key');+ });+});++describe('gas-oracles: Owlracle rung', () => {+ it('falls through to Owlracle when Blocknative is unreachable, skipping the instant tier', async () => {+ const { getGasEstimate } = await import('../../api/_lib/gas-oracles.js');+ const fetchImpl = providerFetch({+ 'api.blocknative.com': refused,+ 'api.owlracle.info': () => jsonResponse(OWLRACLE_BASE),+ });+ const est = await getGasEstimate('base', { fetchImpl });++ expect(est.source).toBe('owlracle');+ expect(est.chain).toBe('base');+ expect(est.chainId).toBe(8453);+ expect(est.baseFee).toBe(0.005);+ expect(est.tiers.safe).toEqual({ maxFeePerGas: 0.0055, maxPriorityFeePerGas: 0.0005 });+ expect(est.tiers.standard).toEqual({ maxFeePerGas: 0.0055, maxPriorityFeePerGas: 0.0005 });+ expect(est.tiers.fast).toEqual({ maxFeePerGas: 0.0058, maxPriorityFeePerGas: 0.0008 });++ // Keyless guest path: /v4/<network>/gas with no apikey param.+ const owl = fetchImpl.calls.find((c) => c.url.includes('owlracle'));+ expect(owl.url).toContain('/v4/base/gas');+ expect(owl.url).not.toContain('apikey');+ });++ it('appends OWLRACLE_API_KEY as the documented apikey query param when configured', async () => {+ vi.stubEnv('OWLRACLE_API_KEY', 'owl-test-key');+ const { getGasEstimate } = await import('../../api/_lib/gas-oracles.js');+ const fetchImpl = providerFetch({+ 'api.blocknative.com': refused,+ 'api.owlracle.info': () => jsonResponse(OWLRACLE_BASE),+ });+ await getGasEstimate('bsc', { fetchImpl });+ const owl = fetchImpl.calls.find((c) => c.url.includes('owlracle'));+ expect(owl.url).toContain('/v4/bsc/gas?apikey=owl-test-key');+ });+});++describe('gas-oracles: Etherscan rung (mainnet final)', () => {+ it('recovers per-tier priority fees from the legacy total prices', async () => {+ const { getGasEstimate } = await import('../../api/_lib/gas-oracles.js');+ const fetchImpl = providerFetch({+ 'api.blocknative.com': refused,+ 'api.owlracle.info': () => jsonResponse({ error: { status: 403 } }, 403),+ 'api.etherscan.io': () => jsonResponse(ETHERSCAN_MAINNET),+ });+ const est = await getGasEstimate('ethereum', { fetchImpl });++ expect(est.source).toBe('etherscan');+ expect(est.baseFee).toBe(0.1119);+ // SafeGasPrice etc. are TOTAL gas prices; priority = total - suggestBaseFee.+ expect(est.tiers.safe).toEqual({ maxFeePerGas: 0.112, maxPriorityFeePerGas: 0.0001 });+ expect(est.tiers.standard).toEqual({ maxFeePerGas: 0.1121, maxPriorityFeePerGas: 0.0002 });+ expect(est.tiers.fast).toEqual({ maxFeePerGas: 0.1233, maxPriorityFeePerGas: 0.0114 });++ // The chain was walked in order: Blocknative, then Owlracle, then Etherscan.+ expect(fetchImpl.calls.map((c) => new URL(c.url).hostname)).toEqual([+ 'api.blocknative.com',+ 'api.owlracle.info',+ 'api.etherscan.io',+ ]);+ // Keyless: no apikey param when ETHERSCAN_API_KEY is unset.+ expect(fetchImpl.calls[2].url).toContain('chainid=1&module=gastracker&action=gasoracle');+ expect(fetchImpl.calls[2].url).not.toContain('apikey');+ });++ it('uses ETHERSCAN_API_KEY via the shared env helper when configured', async () => {+ vi.stubEnv('ETHERSCAN_API_KEY', 'etherscan-test-key');+ const { getGasEstimate } = await import('../../api/_lib/gas-oracles.js');+ const fetchImpl = providerFetch({+ 'api.blocknative.com': refused,+ 'api.owlracle.info': refused,+ 'api.etherscan.io': () => jsonResponse(ETHERSCAN_MAINNET),+ });+ await getGasEstimate('ethereum', { fetchImpl });+ expect(fetchImpl.calls[2].url).toContain('apikey=etherscan-test-key');+ });++ it('treats an Etherscan status:"0" body as a rung failure, surfacing its reason', async () => {+ const { getGasEstimate } = await import('../../api/_lib/gas-oracles.js');+ const fetchImpl = providerFetch({+ 'api.blocknative.com': refused,+ 'api.owlracle.info': refused,+ 'api.etherscan.io': () =>+ jsonResponse({ status: '0', message: 'NOTOK', result: 'Max calls per sec rate limit reached' }),+ });+ await expect(getGasEstimate('ethereum', { fetchImpl })).rejects.toMatchObject({+ code: 'gas_sources_unavailable',+ attempts: [+ { source: 'blocknative', error: 'fetch failed' },+ { source: 'owlracle', error: 'fetch failed' },+ { source: 'etherscan', error: 'Max calls per sec rate limit reached' },+ ],+ });+ });+});++describe('gas-oracles: chain-appropriate rung skipping + failure contract', () => {+ it('only calls Owlracle for a chain Blocknative/Etherscan do not serve', async () => {+ const { getGasEstimate } = await import('../../api/_lib/gas-oracles.js');+ const fetchImpl = providerFetch({ 'api.owlracle.info': refused });+ await expect(getGasEstimate('fantom', { fetchImpl })).rejects.toMatchObject({+ code: 'gas_sources_unavailable',+ attempts: [{ source: 'owlracle', error: 'fetch failed' }],+ });+ expect(fetchImpl.calls).toHaveLength(1);+ expect(fetchImpl.calls[0].url).toContain('/v4/ftm/gas');+ });++ it('rejects an unknown chain with unsupported_chain before any fetch', async () => {+ const { getGasEstimate } = await import('../../api/_lib/gas-oracles.js');+ const fetchImpl = providerFetch({});+ await expect(getGasEstimate('solana', { fetchImpl })).rejects.toMatchObject({+ code: 'unsupported_chain',+ });+ expect(fetchImpl.calls).toHaveLength(0);+ });+});++// ── Endpoint: GET /api/v1/gas ───────────────────────────────────────────────++// Gateway rate limit (shared /api/v1 budget): flip `quotaOk` per test.+let quotaOk = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ apiV1: async () =>+ quotaOk+ ? { success: true, limit: 120, remaining: 119, reset: Date.now() + 60_000 }+ : { success: false, limit: 120, remaining: 0, reset: Date.now() + 60_000 },+ },+ clientIp: () => '203.0.113.9',+}));++// Pass-through cache so each test hits the oracle chain deterministically+// (the real cacheWrap would pin the first test's answer for 10s).+vi.mock('../../api/_lib/cache.js', () => ({+ cacheWrap: (_key, _ttl, fn) => fn(),+}));++function makeReq(url) {+ const stream = Readable.from([]);+ stream.method = 'GET';+ stream.url = url;+ stream.headers = { host: 'three.ws' };+ 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(url) {+ const req = makeReq(url);+ const res = makeRes();+ const mod = await import('../../api/v1/gas.js');+ await mod.default(req, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++describe('GET /api/v1/gas', () => {+ beforeEach(() => {+ quotaOk = true;+ });++ it('returns normalized tiers for ?chain=base in the { data } envelope, edge-cacheable', async () => {+ vi.stubGlobal('fetch', providerFetch({+ 'api.blocknative.com': refused,+ 'api.owlracle.info': () => jsonResponse(OWLRACLE_BASE),+ }));+ const { res, body } = await dispatch('/api/v1/gas?chain=base');+ expect(res.statusCode).toBe(200);+ expect(body.data.chain).toBe('base');+ expect(body.data.chainId).toBe(8453);+ expect(body.data.source).toBe('owlracle');+ expect(body.data.tiers.fast.maxFeePerGas).toBe(0.0058);+ expect(res.getHeader('cache-control')).toMatch(/max-age=10/);+ });++ it('defaults to Ethereum mainnet when no chain is passed', async () => {+ vi.stubGlobal('fetch', providerFetch({+ 'api.blocknative.com': () => jsonResponse(BLOCKNATIVE_MAINNET),+ }));+ const { res, body } = await dispatch('/api/v1/gas');+ expect(res.statusCode).toBe(200);+ expect(body.data.chain).toBe('ethereum');+ expect(body.data.source).toBe('blocknative');+ });++ it('lists supported chains and their sources with ?chains=1', async () => {+ vi.stubGlobal('fetch', providerFetch({}));+ const { res, body } = await dispatch('/api/v1/gas?chains=1');+ expect(res.statusCode).toBe(200);+ const eth = body.data.chains.find((c) => c.chain === 'ethereum');+ expect(eth.sources).toEqual(['blocknative', 'owlracle', 'etherscan']);+ expect(body.data.chains.length).toBeGreaterThanOrEqual(10);+ });++ it('rejects an unknown chain with 400 naming the supported set', async () => {+ vi.stubGlobal('fetch', providerFetch({}));+ const { res, body } = await dispatch('/api/v1/gas?chain=solana');+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('unsupported_chain');+ expect(body.error_description).toContain('ethereum');+ expect(body.error_description).toContain('base');+ });++ it('returns 503 sources_unavailable (never 500) when every rung fails', async () => {+ vi.stubGlobal('fetch', providerFetch({+ 'api.blocknative.com': refused,+ 'api.owlracle.info': refused,+ 'api.etherscan.io': refused,+ }));+ const { res, body } = await dispatch('/api/v1/gas?chain=eth');+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('sources_unavailable');+ expect(body.error_description).toContain('blocknative');+ expect(body.error_description).toContain('owlracle');+ expect(body.error_description).toContain('etherscan');+ });++ it('returns 429 when the shared /api/v1 budget is exhausted', async () => {+ quotaOk = false;+ vi.stubGlobal('fetch', providerFetch({}));+ const { res, body } = await dispatch('/api/v1/gas?chain=base');+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ expect(res.getHeader('retry-after')).toBeTruthy();+ });+});