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(data): keyless on-chain fundamentals, multichain stats, and Bitcoin reads via Coin Metrics, Blockchair, and Esplora
nirholasd9c3e1513e65
diff --git a/api/_lib/blockchair.js b/api/_lib/blockchair.jsnew file mode 100644index 000000000..53619be8b--- /dev/null+++ b/api/_lib/blockchair.js@@ -0,0 +1,188 @@+// Blockchair multichain explorer layer: https://api.blockchair.com (keyless+// within light limits: no API key needed for the stats endpoints used here).+//+// One normalized `getChainStats(chain)` per supported chain plus a fail-soft+// multi-chain aggregate. Same conventions as the DeFiLlama layer+// (api/_lib/market-data.js): per-instance LRU cache as a burst shield,+// jittered retry on 429/5xx via the shared resilience helper, camelCase+// normalized shapes. Blockchair wraps every payload as { data, context };+// `context.code` mirrors the HTTP status, so the HTTP status is authoritative.++import { createCache } from './mem-cache.js';+import { withRetry } from './resilience.js';++export const BLOCKCHAIR_BASE = 'https://api.blockchair.com';++/**+ * Chains this layer serves. Blockchair supports more; extend this allowlist+ * when a consumer needs another one (it exists so an arbitrary string can+ * never become a request path).+ */+export const BLOCKCHAIR_CHAINS = ['bitcoin', 'ethereum', 'litecoin', 'dogecoin', 'bitcoin-cash'];++export const BLOCKCHAIR_CACHE_TTL = {+ stats: 300_000, // 5 min; Blockchair itself caches stats for about a minute+};++const _cache = createCache({ max: 64 });++/** Drop every cached entry. Exposed for tests; not used in product code. */+export function clearBlockchairCache() {+ _cache.clear();+}++/** Retry only on 429/5xx or errors with no HTTP status (network/timeout). */+function shouldRetryFetch(err) {+ const status = err?.status;+ if (typeof status !== 'number') return true;+ return status === 429 || status >= 500;+}++/**+ * GET a Blockchair path as JSON, retrying with jittered exponential backoff on+ * 429/5xx. Throws an Error carrying `.status` on a non-retryable failure.+ *+ * @param {string} path must start with '/'+ * @param {{ maxRetries?: number, timeoutMs?: number }} [options]+ */+export function blockchairFetch(path, options = {}) {+ const { maxRetries = 2, timeoutMs = 10_000 } = options;+ return withRetry(+ async () => {+ const res = await fetch(`${BLOCKCHAIR_BASE}${path}`, {+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!res.ok) {+ const err = new Error(`Blockchair HTTP ${res.status} for ${path}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+ },+ {+ attempts: maxRetries + 1,+ initialDelayMs: 1_000,+ maxDelayMs: 30_000,+ shouldRetry: shouldRetryFetch,+ },+ );+}++/** Number or null; Blockchair mixes numbers with big-number strings. */+function toNum(value) {+ if (value === null || value === undefined || value === '') return null;+ const n = Number(value);+ return Number.isFinite(n) ? n : null;+}++/**+ * @typedef {Object} ChainStats+ * @property {string} chain+ * @property {number|null} blocks total blocks+ * @property {number|null} bestBlockHeight+ * @property {string|null} bestBlockHash+ * @property {string|null} bestBlockTime UTC "YYYY-MM-DD HH:MM:SS"+ * @property {number|null} transactions total transactions+ * @property {number|null} transactions24h+ * @property {number|null} blocks24h+ * @property {number|null} difficulty+ * @property {number|null} hashRate24h hashes/s (approximate above 2^53)+ * @property {number|null} mempoolTransactions+ * @property {number|null} mempoolTps+ * @property {number|null} circulation native base units (sats/wei; approximate above 2^53)+ * @property {number|null} marketPriceUsd+ * @property {number|null} marketPriceChange24hPct+ * @property {number|null} marketCapUsd+ * @property {number|null} marketDominancePct+ * @property {number|null} averageTransactionFeeUsd24h+ * @property {number|null} medianTransactionFeeUsd24h+ * @property {number|null} suggestedFeePerByteSat UTXO chains only+ * @property {Object<string, number>|null} suggestedFeeGweiOptions Ethereum only+ */++/**+ * Normalized explorer stats for one chain from Blockchair's+ * `/{chain}/stats` endpoint.+ *+ * @param {string} chain one of BLOCKCHAIR_CHAINS+ * @returns {Promise<ChainStats>}+ */+export async function getChainStats(chain) {+ const id = String(chain ?? '').trim().toLowerCase();+ if (!BLOCKCHAIR_CHAINS.includes(id)) {+ throw Object.assign(+ new Error(`unsupported chain "${chain}"; supported: ${BLOCKCHAIR_CHAINS.join(', ')}`),+ { status: 400 },+ );+ }+ const cacheKey = `bc:stats:${id}`;+ const cached = _cache.get(cacheKey);+ if (cached) return cached;++ const payload = await blockchairFetch(`/${id}/stats`);+ const d = payload?.data;+ if (!d || typeof d !== 'object') throw new Error(`unexpected Blockchair stats payload for ${id}`);++ const fees = d.suggested_transaction_fee_gwei_options;+ const result = {+ chain: id,+ blocks: toNum(d.blocks),+ bestBlockHeight: toNum(d.best_block_height),+ bestBlockHash: typeof d.best_block_hash === 'string' ? d.best_block_hash : null,+ bestBlockTime: typeof d.best_block_time === 'string' ? d.best_block_time : null,+ transactions: toNum(d.transactions),+ transactions24h: toNum(d.transactions_24h),+ blocks24h: toNum(d.blocks_24h),+ difficulty: toNum(d.difficulty),+ hashRate24h: toNum(d.hashrate_24h),+ mempoolTransactions: toNum(d.mempool_transactions),+ mempoolTps: toNum(d.mempool_tps),+ circulation: toNum(d.circulation ?? d.circulation_approximate),+ marketPriceUsd: toNum(d.market_price_usd),+ marketPriceChange24hPct: toNum(d.market_price_usd_change_24h_percentage),+ marketCapUsd: toNum(d.market_cap_usd),+ marketDominancePct: toNum(d.market_dominance_percentage),+ averageTransactionFeeUsd24h: toNum(d.average_transaction_fee_usd_24h),+ medianTransactionFeeUsd24h: toNum(d.median_transaction_fee_usd_24h),+ suggestedFeePerByteSat: toNum(d.suggested_transaction_fee_per_byte_sat),+ suggestedFeeGweiOptions:+ fees && typeof fees === 'object'+ ? Object.fromEntries(Object.entries(fees).map(([k, v]) => [k, toNum(v)]))+ : null,+ };++ _cache.set(cacheKey, result, { ttl: BLOCKCHAIR_CACHE_TTL.stats });+ return result;+}++/**+ * Stats for several chains in parallel. A failing chain is dropped with a+ * warning so one sick upstream shard never blanks the rest; throws only when+ * every requested chain failed.+ *+ * @param {string[]} [chains]+ * @returns {Promise<ChainStats[]>}+ */+export async function getMultiChainStats(chains = ['bitcoin', 'ethereum']) {+ const ids = [...new Set(chains.map((c) => String(c).trim().toLowerCase()).filter(Boolean))];+ if (ids.length === 0) {+ throw Object.assign(new Error('at least one chain is required'), { status: 400 });+ }++ const settled = await Promise.allSettled(ids.map((id) => getChainStats(id)));+ const result = [];+ settled.forEach((outcome, i) => {+ if (outcome.status === 'fulfilled') {+ result.push(outcome.value);+ } else {+ console.warn(`[blockchair] stats for ${ids[i]} failed: ${outcome.reason?.message || outcome.reason}`);+ }+ });++ if (result.length === 0) {+ const firstError = settled.find((s) => s.status === 'rejected');+ throw firstError?.reason ?? new Error('Blockchair returned no chain stats');+ }+ return result;+}diff --git a/api/_lib/coinmetrics.js b/api/_lib/coinmetrics.jsnew file mode 100644index 000000000..6fa8a8827--- /dev/null+++ b/api/_lib/coinmetrics.js@@ -0,0 +1,300 @@+// Coin Metrics Community API layer: on-chain fundamentals for the majors+// (BTC, ETH, SOL). Keyless: https://community-api.coinmetrics.io/v4 serves a+// community subset of Coin Metrics' network data with no API key, within light+// rate limits.+//+// Sits alongside the DeFiLlama layer (api/_lib/market-data.js), which imports+// `getAssetFundamentals` from here and exposes it as its fundamentals section+// (failing soft there). Same conventions as market-data.js: per-instance LRU+// cache as a burst shield, jittered retry on 429/5xx via the shared resilience+// helper, camelCase normalized shapes.+//+// Community-tier reality (verified against /catalog-v2/asset-metrics on+// 2026-08-05): CapRealUSD and FeeTotUSD are NOT served keyless; the tier+// carries FeeTotNtv (fees in native units) plus PriceUSD, so the USD fee figure+// is derived here as FeeTotNtv * PriceUSD for the same day. SOL has no on-chain+// metrics on the community tier at all, only reference-rate/market metrics, so+// its fundamentals row carries priceUsd/marketCapUsd/volume and nulls for the+// chain-activity fields. The full keyless roster per asset differs; requests go+// out with `ignore_forbidden_errors=true` so an unavailable metric degrades to+// absent instead of failing the whole call with a 403.++import { createCache } from './mem-cache.js';+import { withRetry } from './resilience.js';++export const COINMETRICS_BASE = 'https://community-api.coinmetrics.io/v4';++/** Default assets for the fundamentals snapshot. */+export const FUNDAMENTALS_ASSETS = ['btc', 'eth', 'sol'];++/**+ * Community-available metrics requested for the fundamentals snapshot.+ * Every name here is served keyless for at least one of the default assets;+ * `ignore_forbidden_errors=true` drops the rest per asset instead of erroring.+ */+export const FUNDAMENTALS_METRICS = [+ 'AdrActCnt', // active addresses (24h)+ 'TxCnt', // transaction count (24h)+ 'TxTfrCnt', // transfer count (24h)+ 'BlkCnt', // blocks mined (24h)+ 'FeeTotNtv', // total fees, native units (24h)+ 'HashRate', // mean hash rate+ 'SplyCur', // current supply+ 'IssTotUSD', // total issuance, USD (24h)+ 'CapMrktCurUSD', // market cap (current supply)+ 'CapMrktEstUSD', // market cap (estimated supply; SOL only has this one)+ 'CapMVRVCur', // MVRV ratio+ 'PriceUSD',+ 'ReferenceRateUSD',+ 'volume_reported_spot_usd_1d',+];++export const COINMETRICS_CACHE_TTL = {+ // Daily-frequency data; a new point lands once a day, 30 min is generous.+ fundamentals: 1_800_000,+ timeseries: 900_000,+};++const _cache = createCache({ max: 128 });++/** Drop every cached entry. Exposed for tests; not used in product code. */+export function clearCoinMetricsCache() {+ _cache.clear();+}++/** Retry only on 429/5xx or errors with no HTTP status (network/timeout). */+function shouldRetryFetch(err) {+ const status = err?.status;+ if (typeof status !== 'number') return true;+ return status === 429 || status >= 500;+}++/**+ * GET a Coin Metrics v4 path as JSON with query params, retrying with jittered+ * exponential backoff on 429/5xx. Throws an Error carrying `.status` (and the+ * upstream error message when the body has one) on a non-retryable failure.+ *+ * @param {string} path must start with '/'+ * @param {Record<string, string|number|boolean|undefined>} [params]+ * @param {{ maxRetries?: number, timeoutMs?: number }} [options]+ */+export function cmFetch(path, params = {}, options = {}) {+ const { maxRetries = 2, timeoutMs = 10_000 } = options;+ const url = new URL(`${COINMETRICS_BASE}${path}`);+ for (const [key, value] of Object.entries(params)) {+ if (value !== undefined && value !== null && value !== '') {+ url.searchParams.set(key, String(value));+ }+ }++ return withRetry(+ async () => {+ const res = await fetch(url.toString(), {+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!res.ok) {+ // The v4 API wraps failures as { error: { type, message } }.+ let message = `Coin Metrics HTTP ${res.status} for ${path}`;+ try {+ const body = await res.json();+ if (body?.error?.message) message = `Coin Metrics: ${body.error.message}`;+ } catch {+ // Non-JSON error body; the status-line message stands.+ }+ const err = new Error(message);+ err.status = res.status;+ throw err;+ }+ return res.json();+ },+ {+ attempts: maxRetries + 1,+ initialDelayMs: 1_000,+ maxDelayMs: 30_000,+ shouldRetry: shouldRetryFetch,+ },+ );+}++/** Coin Metrics returns numbers as strings; null/absent stays null. */+function toNum(value) {+ if (value === null || value === undefined || value === '') return null;+ const n = Number(value);+ return Number.isFinite(n) ? n : null;+}++/**+ * Raw daily timeseries for one asset. Returns rows ascending by time, each+ * `{ asset, time, <metric>: number|null }`. Metrics the community tier does+ * not serve for the asset are simply absent from the rows.+ *+ * @param {string} asset Coin Metrics asset id, e.g. 'btc'+ * @param {string[]} metrics+ * @param {{ frequency?: string, limit?: number }} [options]+ */+export async function getAssetMetrics(asset, metrics, options = {}) {+ if (!asset || typeof asset !== 'string') {+ throw Object.assign(new Error('asset is required'), { status: 400 });+ }+ if (!Array.isArray(metrics) || metrics.length === 0) {+ throw Object.assign(new Error('metrics are required'), { status: 400 });+ }+ const { frequency = '1d', limit = 4 } = options;+ const id = asset.trim().toLowerCase();+ const cacheKey = `cm:ts:${id}:${frequency}:${limit}:${metrics.join(',')}`;+ const cached = _cache.get(cacheKey);+ if (cached) return cached;++ const data = await cmFetch('/timeseries/asset-metrics', {+ assets: id,+ metrics: metrics.join(','),+ frequency,+ page_size: limit,+ paging_from: 'end',+ // An unavailable asset/metric combo degrades to absent instead of a 403+ // failing the whole call (SOL has no on-chain metrics keyless).+ ignore_forbidden_errors: true,+ });++ const rows = (Array.isArray(data?.data) ? data.data : []).map((row) => {+ const out = { asset: row.asset ?? id, time: String(row.time ?? '') };+ for (const metric of metrics) {+ if (metric in row) out[metric] = toNum(row[metric]);+ }+ return out;+ });++ _cache.set(cacheKey, rows, { ttl: COINMETRICS_CACHE_TTL.timeseries });+ return rows;+}++/**+ * @typedef {Object} AssetFundamentals+ * @property {string} asset Coin Metrics asset id ('btc')+ * @property {string|null} asOf ISO time of the newest data day used+ * @property {number|null} activeAddresses AdrActCnt+ * @property {number|null} txCount TxCnt+ * @property {number|null} transferCount TxTfrCnt+ * @property {number|null} blockCount BlkCnt+ * @property {number|null} feesNative FeeTotNtv+ * @property {number|null} feesUsd FeeTotNtv * PriceUSD (derived; the community tier has no FeeTotUSD)+ * @property {number|null} hashRate HashRate+ * @property {number|null} supply SplyCur+ * @property {number|null} issuanceUsd IssTotUSD+ * @property {number|null} marketCapUsd CapMrktCurUSD, falling back to CapMrktEstUSD+ * @property {number|null} mvrv CapMVRVCur+ * @property {number|null} priceUsd PriceUSD, falling back to ReferenceRateUSD+ * @property {number|null} volumeReportedUsd volume_reported_spot_usd_1d+ */++/**+ * Coalesce the latest non-null value for a metric across rows (newest last).+ * The current UTC day's row often carries nulls until end-of-day completion,+ * so a small lookback window is fetched and walked backwards.+ */+function latest(rows, metric) {+ for (let i = rows.length - 1; i >= 0; i--) {+ const v = rows[i]?.[metric];+ if (v !== null && v !== undefined) return { value: v, time: rows[i].time };+ }+ return { value: null, time: null };+}++/**+ * Latest on-chain fundamentals snapshot per asset, one request per asset+ * (the v4 API pages multi-asset responses asset-major, so per-asset requests+ * are the reliable way to get each asset's newest rows). A failing asset is+ * dropped with a warning; the call throws only when every asset failed, so a+ * partial upstream outage still yields partial data.+ *+ * @param {string[]} [assets]+ * @returns {Promise<AssetFundamentals[]>}+ */+export async function getAssetFundamentals(assets = FUNDAMENTALS_ASSETS) {+ const ids = [...new Set(assets.map((a) => String(a).trim().toLowerCase()).filter(Boolean))];+ if (ids.length === 0) {+ throw Object.assign(new Error('at least one asset is required'), { status: 400 });+ }+ const cacheKey = `cm:fundamentals:${ids.join(',')}`;+ const cached = _cache.get(cacheKey);+ if (cached) return cached;++ const settled = await Promise.allSettled(+ ids.map((id) => getAssetMetrics(id, FUNDAMENTALS_METRICS, { frequency: '1d', limit: 4 })),+ );++ const result = [];+ settled.forEach((outcome, i) => {+ if (outcome.status === 'rejected') {+ console.warn(`[coinmetrics] fundamentals for ${ids[i]} failed: ${outcome.reason?.message || outcome.reason}`);+ return;+ }+ const rows = outcome.value;+ if (!rows.length) return;++ const pick = (metric) => latest(rows, metric);+ const activeAddresses = pick('AdrActCnt');+ const txCount = pick('TxCnt');+ const transferCount = pick('TxTfrCnt');+ const blockCount = pick('BlkCnt');+ const feesNative = pick('FeeTotNtv');+ const hashRate = pick('HashRate');+ const supply = pick('SplyCur');+ const issuanceUsd = pick('IssTotUSD');+ const capCur = pick('CapMrktCurUSD');+ const capEst = pick('CapMrktEstUSD');+ const mvrv = pick('CapMVRVCur');+ const priceUsd = pick('PriceUSD');+ const refRateUsd = pick('ReferenceRateUSD');+ const volume = pick('volume_reported_spot_usd_1d');++ // Derive the USD fee total the community tier does not serve directly.+ // Pair fee and price from the SAME data day (metrics complete at+ // different times, so each latest-non-null can land on different days;+ // pricing one day's fees with another day's price would be fabricated).+ let feesUsd = null;+ for (let i = rows.length - 1; i >= 0; i--) {+ const fee = rows[i]?.FeeTotNtv;+ const price = rows[i]?.PriceUSD;+ if (fee !== null && fee !== undefined && price !== null && price !== undefined) {+ feesUsd = fee * price;+ break;+ }+ }++ const times = [+ activeAddresses, txCount, transferCount, blockCount, feesNative, hashRate,+ supply, issuanceUsd, capCur, capEst, mvrv, priceUsd, refRateUsd, volume,+ ]+ .map((p) => p.time)+ .filter(Boolean)+ .sort();++ result.push({+ asset: ids[i],+ asOf: times.length ? times[times.length - 1] : null,+ activeAddresses: activeAddresses.value,+ txCount: txCount.value,+ transferCount: transferCount.value,+ blockCount: blockCount.value,+ feesNative: feesNative.value,+ feesUsd,+ hashRate: hashRate.value,+ supply: supply.value,+ issuanceUsd: issuanceUsd.value,+ marketCapUsd: capCur.value ?? capEst.value,+ mvrv: mvrv.value,+ priceUsd: priceUsd.value ?? refRateUsd.value,+ volumeReportedUsd: volume.value,+ });+ });++ if (result.length === 0) {+ const firstError = settled.find((s) => s.status === 'rejected');+ throw firstError?.reason ?? new Error('Coin Metrics returned no fundamentals data');+ }++ _cache.set(cacheKey, result, { ttl: COINMETRICS_CACHE_TTL.fundamentals });+ return result;+}diff --git a/api/_lib/esplora.js b/api/_lib/esplora.jsnew file mode 100644index 000000000..b0d50fd46--- /dev/null+++ b/api/_lib/esplora.js@@ -0,0 +1,321 @@+// Blockstream Esplora layer: https://blockstream.info/api (keyless Bitcoin+// mainnet chain data: addresses, transactions, fee estimates, tip height).+//+// Esplora is the same API family mempool.space serves, so this doubles as the+// keyless fallback lane for anything Bitcoin-facing (the /forever inscription+// status path uses it to report real on-chain confirmation of reveal/commit+// txs). Same conventions as the DeFiLlama layer (api/_lib/market-data.js):+// per-instance LRU cache as a burst shield, jittered retry on 429/5xx via the+// shared resilience helper, camelCase normalized shapes. Esplora returns plain+// text for a few endpoints (tip height), so the fetch helper handles both.++import { createCache } from './mem-cache.js';+import { withRetry } from './resilience.js';++export const ESPLORA_BASE = 'https://blockstream.info/api';++export const ESPLORA_CACHE_TTL = {+ tip: 30_000, // a new block roughly every 10 min; 30 s keeps confirmations fresh+ fees: 60_000,+ address: 60_000,+ txUnconfirmed: 30_000,+ txConfirmed: 600_000, // a confirmed tx's content is immutable; only depth changes+};++const _cache = createCache({ max: 256 });++/** Drop every cached entry. Exposed for tests; not used in product code. */+export function clearEsploraCache() {+ _cache.clear();+}++const TXID_RE = /^[0-9a-f]{64}$/i;+// Mainnet address classes: base58 P2PKH/P2SH (1…, 3…) and bech32/bech32m+// segwit (bc1…). Format-level check only; Esplora is the validity authority.+const ADDRESS_RE = /^(bc1[02-9ac-hj-np-z]{11,87}|[13][a-km-zA-HJ-NP-Z1-9]{25,34})$/;++/** True when `s` looks like a Bitcoin mainnet address. */+export function isPlausibleBitcoinAddress(s) {+ return typeof s === 'string' && ADDRESS_RE.test(s);+}++/** True when `s` looks like a transaction id. */+export function isPlausibleTxid(s) {+ return typeof s === 'string' && TXID_RE.test(s);+}++/** Retry only on 429/5xx or errors with no HTTP status (network/timeout). */+function shouldRetryFetch(err) {+ const status = err?.status;+ if (typeof status !== 'number') return true;+ return status === 429 || status >= 500;+}++/**+ * GET an Esplora path, retrying with jittered exponential backoff on 429/5xx.+ * Esplora serves JSON for most endpoints but plain text for a few (tip+ * height, error bodies), so this parses by content. Throws an Error carrying+ * `.status` on a non-retryable failure (404 = unknown address/tx).+ *+ * @param {string} path must start with '/'+ * @param {{ maxRetries?: number, timeoutMs?: number }} [options]+ */+export function esploraFetch(path, options = {}) {+ const { maxRetries = 2, timeoutMs = 10_000 } = options;+ return withRetry(+ async () => {+ const res = await fetch(`${ESPLORA_BASE}${path}`, {+ headers: { accept: 'application/json, text/plain', 'user-agent': 'three.ws/1.0' },+ signal: AbortSignal.timeout(timeoutMs),+ });+ const text = await res.text();+ if (!res.ok) {+ // Esplora error bodies are short plain-text reasons ("Transaction not found").+ const reason = text.trim().slice(0, 200);+ const err = new Error(`Esplora HTTP ${res.status} for ${path}${reason ? `: ${reason}` : ''}`);+ err.status = res.status;+ throw err;+ }+ try {+ return JSON.parse(text);+ } catch {+ return text.trim();+ }+ },+ {+ attempts: maxRetries + 1,+ initialDelayMs: 1_000,+ maxDelayMs: 30_000,+ shouldRetry: shouldRetryFetch,+ },+ );+}++const toNum = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+};++/**+ * Current chain tip height.+ * @returns {Promise<number>}+ */+export async function getTipHeight() {+ const cacheKey = 'esplora:tip';+ const cached = _cache.get(cacheKey);+ if (cached !== undefined) return cached;++ const raw = await esploraFetch('/blocks/tip/height');+ const height = toNum(raw);+ if (height === null) throw new Error(`unexpected Esplora tip height payload: ${String(raw).slice(0, 80)}`);++ _cache.set(cacheKey, height, { ttl: ESPLORA_CACHE_TTL.tip });+ return height;+}++/**+ * @typedef {Object} FeeEstimates+ * @property {Object<string, number>} estimates confirmation target (blocks) → sat/vB+ * @property {number|null} fastest next-block target (1)+ * @property {number|null} halfHour 3-block target+ * @property {number|null} hour 6-block target+ * @property {number|null} economy 144-block (about a day) target+ */++/**+ * Pick the fee for a confirmation target: exact target when present,+ * otherwise the nearest available target at or above it (a slightly slower+ * target only ever quotes an equal-or-lower fee, so this never underquotes).+ */+function feeAt(estimates, target) {+ if (estimates[target] !== undefined) return estimates[target];+ const targets = Object.keys(estimates)+ .map(Number)+ .filter((t) => Number.isFinite(t))+ .sort((a, b) => a - b);+ for (const t of targets) {+ if (t >= target) return estimates[String(t)] ?? estimates[t];+ }+ return null;+}++/**+ * Fee estimates in sat/vB keyed by confirmation target, plus the familiar+ * fastest/halfHour/hour/economy tiers.+ * @returns {Promise<FeeEstimates>}+ */+export async function getFeeEstimates() {+ const cacheKey = 'esplora:fees';+ const cached = _cache.get(cacheKey);+ if (cached) return cached;++ const raw = await esploraFetch('/fee-estimates');+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ throw new Error('unexpected Esplora fee-estimates payload');+ }+ const estimates = {};+ for (const [target, rate] of Object.entries(raw)) {+ const n = toNum(rate);+ if (n !== null) estimates[target] = n;+ }++ const result = {+ estimates,+ fastest: feeAt(estimates, 1),+ halfHour: feeAt(estimates, 3),+ hour: feeAt(estimates, 6),+ economy: feeAt(estimates, 144),+ };++ _cache.set(cacheKey, result, { ttl: ESPLORA_CACHE_TTL.fees });+ return result;+}++/**+ * @typedef {Object} AddressInfo+ * @property {string} address+ * @property {number} balanceSats confirmed funded minus spent+ * @property {number} pendingBalanceSats net of mempool txos (can be negative)+ * @property {number} txCount confirmed transactions+ * @property {number} mempoolTxCount+ * @property {{fundedTxoCount: number, fundedTxoSum: number, spentTxoCount: number, spentTxoSum: number, txCount: number}} chainStats+ * @property {{fundedTxoCount: number, fundedTxoSum: number, spentTxoCount: number, spentTxoSum: number, txCount: number}} mempoolStats+ */++function mapStats(s) {+ return {+ fundedTxoCount: toNum(s?.funded_txo_count) ?? 0,+ fundedTxoSum: toNum(s?.funded_txo_sum) ?? 0,+ spentTxoCount: toNum(s?.spent_txo_count) ?? 0,+ spentTxoSum: toNum(s?.spent_txo_sum) ?? 0,+ txCount: toNum(s?.tx_count) ?? 0,+ };+}++/**+ * Confirmed + mempool stats for a Bitcoin address.+ * @param {string} address+ * @returns {Promise<AddressInfo>}+ */+export async function getAddress(address) {+ if (!isPlausibleBitcoinAddress(address)) {+ throw Object.assign(new Error('a Bitcoin mainnet address is required'), { status: 400 });+ }+ const cacheKey = `esplora:addr:${address}`;+ const cached = _cache.get(cacheKey);+ if (cached) return cached;++ const raw = await esploraFetch(`/address/${encodeURIComponent(address)}`);+ const chainStats = mapStats(raw?.chain_stats);+ const mempoolStats = mapStats(raw?.mempool_stats);++ const result = {+ address: raw?.address ?? address,+ balanceSats: chainStats.fundedTxoSum - chainStats.spentTxoSum,+ pendingBalanceSats: mempoolStats.fundedTxoSum - mempoolStats.spentTxoSum,+ txCount: chainStats.txCount,+ mempoolTxCount: mempoolStats.txCount,+ chainStats,+ mempoolStats,+ };++ _cache.set(cacheKey, result, { ttl: ESPLORA_CACHE_TTL.address });+ return result;+}++/**+ * @typedef {Object} TxStatus+ * @property {boolean} confirmed+ * @property {number|null} blockHeight+ * @property {string|null} blockHash+ * @property {number|null} blockTime unix seconds+ */++function mapStatus(status) {+ return {+ confirmed: Boolean(status?.confirmed),+ blockHeight: toNum(status?.block_height),+ blockHash: typeof status?.block_hash === 'string' ? status.block_hash : null,+ blockTime: toNum(status?.block_time),+ };+}++/**+ * Confirmation status of a transaction (small dedicated endpoint; use this+ * over getTransaction when only depth matters). Throws with .status = 404+ * for a txid the chain and mempool have never seen.+ *+ * @param {string} txid+ * @returns {Promise<TxStatus>}+ */+export async function getTransactionStatus(txid) {+ if (!isPlausibleTxid(txid)) {+ throw Object.assign(new Error('a 64-hex-char txid is required'), { status: 400 });+ }+ const id = txid.toLowerCase();+ const cacheKey = `esplora:txstatus:${id}`;+ const cached = _cache.get(cacheKey);+ if (cached) return cached;++ const raw = await esploraFetch(`/tx/${id}/status`);+ const result = mapStatus(raw);++ _cache.set(cacheKey, result, {+ ttl: result.confirmed ? ESPLORA_CACHE_TTL.txConfirmed : ESPLORA_CACHE_TTL.txUnconfirmed,+ });+ return result;+}++/**+ * @typedef {Object} TransactionInfo+ * @property {string} txid+ * @property {TxStatus} status+ * @property {number|null} fee sats+ * @property {number|null} size bytes+ * @property {number|null} weight weight units+ * @property {number|null} vsize ceil(weight / 4)+ * @property {number|null} feeRate sat/vB+ * @property {number} inputCount+ * @property {number} outputCount+ * @property {number} outputValueSats+ */++/**+ * Full transaction detail, lightly normalized.+ * @param {string} txid+ * @returns {Promise<TransactionInfo>}+ */+export async function getTransaction(txid) {+ if (!isPlausibleTxid(txid)) {+ throw Object.assign(new Error('a 64-hex-char txid is required'), { status: 400 });+ }+ const id = txid.toLowerCase();+ const cacheKey = `esplora:tx:${id}`;+ const cached = _cache.get(cacheKey);+ if (cached) return cached;++ const raw = await esploraFetch(`/tx/${id}`);+ const status = mapStatus(raw?.status);+ const weight = toNum(raw?.weight);+ const fee = toNum(raw?.fee);+ const vsize = weight !== null ? Math.ceil(weight / 4) : null;+ const vout = Array.isArray(raw?.vout) ? raw.vout : [];++ const result = {+ txid: raw?.txid ?? id,+ status,+ fee,+ size: toNum(raw?.size),+ weight,+ vsize,+ feeRate: fee !== null && vsize ? fee / vsize : null,+ inputCount: Array.isArray(raw?.vin) ? raw.vin.length : 0,+ outputCount: vout.length,+ outputValueSats: vout.reduce((sum, o) => sum + (toNum(o?.value) ?? 0), 0),+ };++ _cache.set(cacheKey, result, {+ ttl: status.confirmed ? ESPLORA_CACHE_TTL.txConfirmed : ESPLORA_CACHE_TTL.txUnconfirmed,+ });+ return result;+}diff --git a/api/_lib/market-data.js b/api/_lib/market-data.jsindex d2c77c3a3..c4f6af2a4 100644--- a/api/_lib/market-data.js+++ b/api/_lib/market-data.js@@ -17,6 +17,7 @@import { createCache } from './mem-cache.js';import { withRetry } from './resilience.js';+import { getAssetFundamentals, FUNDAMENTALS_ASSETS } from './coinmetrics.js';/*** @typedef {Object} Protocol@@ -98,6 +99,7 @@ export const CACHE_TTL = {yields: 900_000, // 15 minfearGreed: 1_800_000, // 30 mindexVolumes: 600_000, // 10 min+ fundamentals: 1_800_000, // 30 min (daily-frequency Coin Metrics data)};// True LRU with per-entry TTL. The previous Map evicted the oldest INSERTED@@ -395,3 +397,39 @@ export async function getFearGreed() {setCache(cacheKey, result, CACHE_TTL.fearGreed);return result;}++// ---------------------------------------------------------------------------+// On-chain fundamentals: Coin Metrics Community API (keyless), via+// api/_lib/coinmetrics.js. Daily network metrics for the majors: active+// addresses, tx/transfer counts, fees, hash rate, supply, market cap, MVRV.+// FAILS SOFT by design: fundamentals enrich a market snapshot, they never+// gate one, so a Coin Metrics outage degrades to an empty array here instead+// of rejecting the caller the way the DeFiLlama getters above do.+// ---------------------------------------------------------------------------++/**+ * Latest on-chain fundamentals per asset (default BTC, ETH, SOL). Each entry+ * is an AssetFundamentals shape (see api/_lib/coinmetrics.js): camelCase+ * metric values coalesced to the newest completed data day, with nulls for+ * metrics the community tier does not serve for that asset (SOL only has+ * market metrics keyless).+ *+ * @param {string[]} [assets]+ * @returns {Promise<import('./coinmetrics.js').AssetFundamentals[]>}+ */+export async function getFundamentals(assets = FUNDAMENTALS_ASSETS) {+ const cacheKey = `cm:market-data:fundamentals:${assets.join(',')}`;+ const cached = getCached(cacheKey);+ if (cached) return cached;++ let result;+ try {+ result = await getAssetFundamentals(assets);+ } catch (err) {+ console.warn(`[market-data] fundamentals unavailable: ${err?.message || err}`);+ return [];+ }++ setCache(cacheKey, result, CACHE_TTL.fundamentals);+ return result;+}diff --git a/api/forever/status.js b/api/forever/status.jsindex 916cbb9e6..1c69c4cb0 100644--- a/api/forever/status.js+++ b/api/forever/status.js@@ -2,15 +2,24 @@//// Returns the live status of an OrdinalsBot inscription order. Once paid +// inscribed, the response includes the inscription ID, the reveal txid, and-// public viewer URLs (mempool.space, ordinals.com).+// public viewer URLs (mempool.space, ordinals.com). When a reveal txid is+// known, the response also carries real Bitcoin chain confirmation for it,+// read keyless from Blockstream Esplora (api/_lib/esplora.js) so the user+// sees actual finality depth, not just OrdinalsBot's order state. That+// lookup fails soft: an Esplora outage degrades `inscription.onchain` to+// null and never breaks the status response.//// Response 200:// { orderId, state, paid, inscribed, charge?, inscription?, links }//+// inscription.onchain (when the reveal tx is known and reachable):+// { confirmed, confirmations, blockHeight, blockTime, source: "esplora" }+//// state ∈ "waiting-payment" | "payment-received" | "inscribing" |// "inscribed" | "failed"import { cors, error, json } from '../_lib/http.js';+import { getTransactionStatus, getTipHeight, isPlausibleTxid } from '../_lib/esplora.js';const ORDINALSBOT_BASE_URL =process.env.ORDINALSBOT_BASE_URL || 'https://api.ordinalsbot.com';@@ -76,6 +85,35 @@ function buildLinks({ inscriptionId, revealTxid, commitTxid, chargeAddress }) {return links;}+/**+ * Real chain confirmation for the reveal tx via Blockstream Esplora. Fails+ * soft on purpose: a 404 just means the tx has not been broadcast or indexed+ * yet (the OrdinalsBot state already covers that phase), and any other+ * upstream fault must never take the whole status endpoint down.+ */+async function fetchOnchainStatus(txid) {+ if (!isPlausibleTxid(txid)) return null;+ try {+ const [status, tip] = await Promise.all([getTransactionStatus(txid), getTipHeight()]);+ const confirmations =+ status.confirmed && Number.isFinite(status.blockHeight) && Number.isFinite(tip)+ ? Math.max(1, tip - status.blockHeight + 1)+ : 0;+ return {+ confirmed: status.confirmed,+ confirmations,+ blockHeight: status.blockHeight,+ blockTime: status.blockTime,+ source: 'esplora',+ };+ } catch (e) {+ if (e?.status !== 404) {+ console.warn(`[forever/status] esplora lookup for ${txid} failed: ${e?.message || e}`);+ }+ return null;+ }+}+async function fetchOrdinalsBotOrder(orderId) {const headers = {};if (process.env.ORDINALSBOT_API_KEY) {@@ -121,6 +159,8 @@ export default async function handler(req, res) {const commitTxid = pickCommitTxid(order);const charge = order.charge || {};const chargeAddress = charge.address || order.payAddress || null;+ // Only worth a lookup when the inscription block below will render it.+ const onchain = inscriptionId && revealTxid ? await fetchOnchainStatus(revealTxid) : null;return json(res, 200, {orderId,@@ -140,6 +180,7 @@ export default async function handler(req, res) {id: inscriptionId,revealTxid,commitTxid,+ onchain,}: null,links: buildLinks({ inscriptionId, revealTxid, commitTxid, chargeAddress }),diff --git a/tests/api/blockchair.test.js b/tests/api/blockchair.test.jsnew file mode 100644index 000000000..4e2536341--- /dev/null+++ b/tests/api/blockchair.test.js@@ -0,0 +1,152 @@+// api/_lib/blockchair.js: Blockchair multichain explorer layer.+//+// No live network: fetch is mocked with vi.stubGlobal so these exercise the+// module's real caching, allowlisting, and shape-mapping logic against+// payloads captured (trimmed) from the real api.blockchair.com on 2026-08-05.+// Live-network verification was run separately with real `node -e` calls.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ getChainStats,+ getMultiChainStats,+ clearBlockchairCache,+ BLOCKCHAIR_CHAINS,+ BLOCKCHAIR_BASE,+} from '../../api/_lib/blockchair.js';++function jsonResponse(status, body) {+ return { ok: status >= 200 && status < 300, status, statusText: String(status), json: async () => body };+}++let fetchMock;++beforeEach(() => {+ clearBlockchairCache();+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++const BITCOIN_STATS = {+ data: {+ blocks: 961223,+ transactions: 1411912353,+ circulation: 2006629291655096,+ blocks_24h: 142,+ transactions_24h: 606929,+ difficulty: 126231507121868.2,+ mempool_transactions: 7876,+ mempool_tps: 1.8166666666666667,+ best_block_height: 961222,+ best_block_hash: '000000000000000000012009d00d076443d9e33fa2299b68ff75471fd1880bc1',+ best_block_time: '2026-08-05 23:40:44',+ hashrate_24h: '891710846732260109258',+ average_transaction_fee_usd_24h: 0.39175778696063296,+ median_transaction_fee_usd_24h: 0.09239087,+ market_price_usd: 64609,+ market_price_usd_change_24h_percentage: 0.7,+ market_cap_usd: 1296529427283,+ market_dominance_percentage: 28.53,+ suggested_transaction_fee_per_byte_sat: 2,+ },+ context: { code: 200 },+};++const ETHEREUM_STATS = {+ data: {+ blocks: 25693055,+ transactions: 3652141935,+ circulation_approximate: '122374665718230000000000000',+ blocks_24h: 7173,+ transactions_24h: 2634319,+ difficulty: 0,+ mempool_transactions: 391,+ mempool_tps: 6.516666666666667,+ best_block_height: 25692153,+ best_block_hash: '43da7c17a8c3199c561e63620a80e59a4bc1748553b7aa8bed9ca052bb9495e1',+ best_block_time: '2026-08-05 23:56:11',+ hashrate_24h: '0',+ average_transaction_fee_usd_24h: 0.0974379280008165,+ median_transaction_fee_usd_24h: 0.008989736155474198,+ market_price_usd: 1907.8,+ market_price_usd_change_24h_percentage: 2,+ market_cap_usd: 230231886205,+ market_dominance_percentage: 9.99,+ suggested_transaction_fee_gwei_options: { sloth: 0, slow: 0, normal: 0, fast: 0, cheetah: 2 },+ },+ context: { code: 200 },+};++describe('getChainStats', () => {+ it('normalizes bitcoin stats to the camelCase shape', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(200, BITCOIN_STATS));+ const stats = await getChainStats('bitcoin');+ expect(stats).toMatchObject({+ chain: 'bitcoin',+ blocks: 961223,+ bestBlockHeight: 961222,+ bestBlockTime: '2026-08-05 23:40:44',+ transactions24h: 606929,+ mempoolTransactions: 7876,+ marketPriceUsd: 64609,+ marketCapUsd: 1296529427283,+ marketDominancePct: 28.53,+ suggestedFeePerByteSat: 2,+ suggestedFeeGweiOptions: null,+ });+ // The big-number hash rate string becomes a (necessarily approximate) number.+ expect(stats.hashRate24h).toBeCloseTo(8.917108467322601e20, -6);+ expect(fetchMock).toHaveBeenCalledWith(`${BLOCKCHAIR_BASE}/bitcoin/stats`, expect.any(Object));+ });++ it('normalizes ethereum stats including approximate circulation and gwei fee options', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(200, ETHEREUM_STATS));+ const stats = await getChainStats('ethereum');+ expect(stats.chain).toBe('ethereum');+ expect(stats.circulation).toBeCloseTo(1.2237466571823e26, -12);+ expect(stats.suggestedFeePerByteSat).toBeNull();+ expect(stats.suggestedFeeGweiOptions).toEqual({ sloth: 0, slow: 0, normal: 0, fast: 0, cheetah: 2 });+ });++ it('rejects a chain outside the allowlist without hitting the network', async () => {+ await expect(getChainStats('not-a-chain')).rejects.toThrow(/unsupported chain/);+ expect(fetchMock).not.toHaveBeenCalled();+ expect(BLOCKCHAIR_CHAINS).toContain('bitcoin');+ expect(BLOCKCHAIR_CHAINS).toContain('ethereum');+ });++ it('caches per chain within the TTL', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(200, BITCOIN_STATS));+ await getChainStats('bitcoin');+ await getChainStats('bitcoin');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});++describe('getMultiChainStats', () => {+ it('fetches chains in parallel and keeps successes when one fails', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ fetchMock.mockImplementation((url) => {+ if (String(url).includes('/bitcoin/')) return Promise.resolve(jsonResponse(200, BITCOIN_STATS));+ return Promise.resolve(jsonResponse(404, {}));+ });+ const result = await getMultiChainStats(['bitcoin', 'ethereum']);+ expect(result.map((s) => s.chain)).toEqual(['bitcoin']);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('ethereum'));+ warn.mockRestore();+ });++ it('rejects when every chain failed', async () => {+ fetchMock.mockResolvedValue(jsonResponse(404, {}));+ await expect(getMultiChainStats(['bitcoin', 'ethereum'])).rejects.toThrow(/HTTP 404/);+ });++ it('rejects an empty chain list without hitting the network', async () => {+ await expect(getMultiChainStats([])).rejects.toThrow(/at least one chain/);+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/coinmetrics.test.js b/tests/api/coinmetrics.test.jsnew file mode 100644index 000000000..41f72c2ed--- /dev/null+++ b/tests/api/coinmetrics.test.js@@ -0,0 +1,255 @@+// api/_lib/coinmetrics.js: Coin Metrics Community API layer, plus the+// fail-soft fundamentals wiring in api/_lib/market-data.js.+//+// No live network: fetch is mocked with vi.stubGlobal so these exercise the+// module's real caching, retry, coalescing, and shape-mapping logic against+// payloads captured from the real community API on 2026-08-05 (allowed under+// the no-mocks rule, which bars fake data in the product, not test doubles).+// Live-network verification was run separately with real `node -e` calls.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ getAssetMetrics,+ getAssetFundamentals,+ cmFetch,+ clearCoinMetricsCache,+ FUNDAMENTALS_METRICS,+ COINMETRICS_BASE,+} from '../../api/_lib/coinmetrics.js';+import { getFundamentals, clearMarketDataCache } from '../../api/_lib/market-data.js';++function jsonResponse(status, body) {+ return { ok: status >= 200 && status < 300, status, statusText: String(status), json: async () => body };+}++let fetchMock;++beforeEach(() => {+ clearCoinMetricsCache();+ clearMarketDataCache();+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-08-05T12:00:00.000Z'));+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++// Captured from the live community API (values as returned: numbers as+// strings, the current UTC day carrying nulls until end-of-day completion).+const BTC_ROWS = {+ data: [+ {+ asset: 'btc',+ time: '2026-08-03T00:00:00.000000000Z',+ AdrActCnt: '741819',+ BlkCnt: '150',+ CapMVRVCur: '1.202801204686642675',+ CapMrktCurUSD: '1273346363617.167523590440547882',+ FeeTotNtv: '3.9421898',+ HashRate: '941250341.229388156826514248312551951404',+ IssTotUSD: '29746897.55232684375',+ PriceUSD: '63460.0481116306',+ ReferenceRateUSD: '63445.6829658095',+ SplyCur: '20065323.01042797',+ TxCnt: '702879',+ TxTfrCnt: '1058121',+ },+ {+ asset: 'btc',+ time: '2026-08-04T00:00:00.000000000Z',+ AdrActCnt: '684692',+ BlkCnt: '141',+ CapMVRVCur: '1.21621443137356142',+ CapMrktCurUSD: '1287448909177.39337035991202835',+ FeeTotNtv: '3.26374575',+ HashRate: '884775320.936344932354661711723726951404',+ IssTotUSD: '28271148.106582396875',+ PriceUSD: '64161.470880187',+ ReferenceRateUSD: '63460.0481116306',+ SplyCur: '20065763.63533705',+ TxCnt: '619401',+ TxTfrCnt: '959665',+ },+ {+ asset: 'btc',+ time: '2026-08-05T00:00:00.000000000Z',+ AdrActCnt: null,+ BlkCnt: null,+ CapMVRVCur: null,+ CapMrktCurUSD: null,+ FeeTotNtv: null,+ HashRate: null,+ IssTotUSD: null,+ PriceUSD: null,+ ReferenceRateUSD: '64161.470880187',+ SplyCur: null,+ TxCnt: null,+ TxTfrCnt: null,+ },+ ],+};++// SOL has no on-chain metrics on the community tier: only reference+// rate/market metrics come back, the rest are absent from the rows entirely.+const SOL_ROWS = {+ data: [+ {+ asset: 'sol',+ time: '2026-08-04T00:00:00.000000000Z',+ CapMrktEstUSD: '42908375875.99746630027953975162',+ ReferenceRateUSD: '73.4220010898139',+ volume_reported_spot_usd_1d: '437308247.245655',+ },+ {+ asset: 'sol',+ time: '2026-08-05T00:00:00.000000000Z',+ CapMrktEstUSD: null,+ ReferenceRateUSD: '73.8281576996287',+ volume_reported_spot_usd_1d: null,+ },+ ],+};++function routeByAsset(url) {+ const u = String(url);+ if (u.includes('assets=btc')) return jsonResponse(200, BTC_ROWS);+ if (u.includes('assets=sol')) return jsonResponse(200, SOL_ROWS);+ return jsonResponse(403, { error: { type: 'forbidden', message: 'not available with supplied credentials' } });+}++describe('cmFetch', () => {+ it('builds the query and parses JSON on 200', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { data: [] }));+ await cmFetch('/timeseries/asset-metrics', { assets: 'btc', page_size: 4 });+ const url = String(fetchMock.mock.calls[0][0]);+ expect(url.startsWith(`${COINMETRICS_BASE}/timeseries/asset-metrics?`)).toBe(true);+ expect(url).toContain('assets=btc');+ expect(url).toContain('page_size=4');+ });++ it('retries on 429 then succeeds', async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse(429, {}))+ .mockResolvedValueOnce(jsonResponse(200, { data: [] }));+ const promise = cmFetch('/timeseries/asset-metrics', { assets: 'btc' });+ await vi.advanceTimersByTimeAsync(2100);+ await expect(promise).resolves.toEqual({ data: [] });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('surfaces the upstream error message on a non-retryable 403', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse(403, { error: { type: 'forbidden', message: 'metric not available' } }),+ );+ await expect(cmFetch('/timeseries/asset-metrics', { assets: 'btc' })).rejects.toThrow(+ /metric not available/,+ );+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});++describe('getAssetMetrics', () => {+ it('numbers the string values, keeps nulls, and requests ignore_forbidden_errors', async () => {+ fetchMock.mockImplementation((url) => Promise.resolve(routeByAsset(url)));+ const rows = await getAssetMetrics('btc', ['AdrActCnt', 'PriceUSD'], { limit: 3 });+ expect(rows).toHaveLength(3);+ expect(rows[0]).toMatchObject({ asset: 'btc', time: '2026-08-03T00:00:00.000000000Z', AdrActCnt: 741819 });+ expect(rows[2].AdrActCnt).toBeNull();+ const url = String(fetchMock.mock.calls[0][0]);+ expect(url).toContain('ignore_forbidden_errors=true');+ expect(url).toContain('paging_from=end');+ });++ it('caches per (asset, frequency, limit, metrics)', async () => {+ fetchMock.mockImplementation((url) => Promise.resolve(routeByAsset(url)));+ await getAssetMetrics('btc', ['AdrActCnt']);+ await getAssetMetrics('btc', ['AdrActCnt']);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('rejects a missing asset without hitting the network', async () => {+ await expect(getAssetMetrics('', ['AdrActCnt'])).rejects.toThrow(/asset/);+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('getAssetFundamentals', () => {+ it('coalesces the latest non-null value per metric past the incomplete current day', async () => {+ fetchMock.mockImplementation((url) => Promise.resolve(routeByAsset(url)));+ const [btc] = await getAssetFundamentals(['btc']);+ expect(btc.asset).toBe('btc');+ // On-chain metrics come from 08-04 (the 08-05 row is null), while the+ // reference rate is current through 08-05.+ expect(btc.activeAddresses).toBe(684692);+ expect(btc.txCount).toBe(619401);+ expect(btc.marketCapUsd).toBeCloseTo(1287448909177.39, 0);+ expect(btc.priceUsd).toBeCloseTo(64161.470880187, 6);+ expect(btc.asOf).toBe('2026-08-05T00:00:00.000000000Z');+ });++ it('derives feesUsd from the newest day carrying BOTH fee and price', async () => {+ fetchMock.mockImplementation((url) => Promise.resolve(routeByAsset(url)));+ const [btc] = await getAssetFundamentals(['btc']);+ expect(btc.feesNative).toBeCloseTo(3.26374575, 8);+ expect(btc.feesUsd).toBeCloseTo(3.26374575 * 64161.470880187, 4);+ });++ it('maps a market-metrics-only asset (SOL) to nulls plus estimated cap and reference rate', async () => {+ fetchMock.mockImplementation((url) => Promise.resolve(routeByAsset(url)));+ const [sol] = await getAssetFundamentals(['sol']);+ expect(sol.activeAddresses).toBeNull();+ expect(sol.txCount).toBeNull();+ expect(sol.feesUsd).toBeNull();+ expect(sol.marketCapUsd).toBeCloseTo(42908375875.997, 2);+ expect(sol.priceUsd).toBeCloseTo(73.8281576996287, 8);+ expect(sol.volumeReportedUsd).toBeCloseTo(437308247.245655, 4);+ });++ it('drops a failing asset but keeps the others', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ fetchMock.mockImplementation((url) => Promise.resolve(routeByAsset(url)));+ const result = await getAssetFundamentals(['btc', 'eth']); // eth routes to 403 here+ expect(result.map((r) => r.asset)).toEqual(['btc']);+ expect(warn).toHaveBeenCalled();+ warn.mockRestore();+ });++ it('rejects when every asset failed', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse(403, { error: { type: 'forbidden', message: 'nope' } }),+ );+ await expect(getAssetFundamentals(['btc', 'eth'])).rejects.toThrow(/nope/);+ });++ it('requests the full community fundamentals metric roster', async () => {+ fetchMock.mockImplementation((url) => Promise.resolve(routeByAsset(url)));+ await getAssetFundamentals(['btc']);+ const url = decodeURIComponent(String(fetchMock.mock.calls[0][0]));+ for (const metric of FUNDAMENTALS_METRICS) {+ expect(url).toContain(metric);+ }+ });+});++describe('market-data getFundamentals wiring', () => {+ it('passes through Coin Metrics fundamentals on success', async () => {+ fetchMock.mockImplementation((url) => Promise.resolve(routeByAsset(url)));+ const result = await getFundamentals(['btc', 'sol']);+ expect(result.map((r) => r.asset)).toEqual(['btc', 'sol']);+ });++ it('fails soft to an empty array when Coin Metrics is down', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ fetchMock.mockResolvedValue(+ jsonResponse(403, { error: { type: 'forbidden', message: 'down' } }),+ );+ await expect(getFundamentals(['btc'])).resolves.toEqual([]);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('fundamentals unavailable'));+ warn.mockRestore();+ });+});diff --git a/tests/api/esplora.test.js b/tests/api/esplora.test.jsnew file mode 100644index 000000000..0371ce1f3--- /dev/null+++ b/tests/api/esplora.test.js@@ -0,0 +1,256 @@+// api/_lib/esplora.js: Blockstream Esplora Bitcoin chain-data layer, plus+// its wiring into api/forever/status.js (real on-chain confirmation for+// inscription reveal txs, failing soft).+//+// No live network: fetch is mocked with vi.stubGlobal so these exercise the+// module's real caching, validation, and shape-mapping logic against payloads+// captured from the real blockstream.info/api on 2026-08-05. Live-network+// verification was run separately with real `node -e` calls.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { Readable } from 'node:stream';+import {+ getTipHeight,+ getFeeEstimates,+ getAddress,+ getTransaction,+ getTransactionStatus,+ isPlausibleBitcoinAddress,+ isPlausibleTxid,+ clearEsploraCache,+ ESPLORA_BASE,+} from '../../api/_lib/esplora.js';+import foreverStatusHandler from '../../api/forever/status.js';++// Esplora answers plain text for some endpoints, JSON for others; the module+// reads .text() and parses, so the stub only needs text().+function textResponse(status, body) {+ const text = typeof body === 'string' ? body : JSON.stringify(body);+ return { ok: status >= 200 && status < 300, status, statusText: String(status), text: async () => text };+}++let fetchMock;++beforeEach(() => {+ clearEsploraCache();+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++const ADDRESS = 'bc1qgdjqv0av3q56jvd82tkdjpy7gdp9ut8tlqmgrpmv24sq90ecnvqqjwvw97';+const TXID = 'c9f1953cdb5e3af87adaa960d2f6baae21e521061092c02a2946dcedcfb5f102';++const ADDRESS_FIXTURE = {+ address: ADDRESS,+ chain_stats: {+ funded_txo_count: 343,+ funded_txo_sum: 530775983879384,+ spent_txo_count: 296,+ spent_txo_sum: 517774975978040,+ tx_count: 335,+ },+ mempool_stats: { funded_txo_count: 0, funded_txo_sum: 0, spent_txo_count: 0, spent_txo_sum: 0, tx_count: 0 },+};++const FEES_FIXTURE = { 1: 2.232, 2: 2.232, 3: 2.006, 6: 1.223, 144: 0.292, 504: 0.1, 1008: 0.1 };++const TX_STATUS_FIXTURE = {+ confirmed: true,+ block_height: 961103,+ block_hash: '00000000000000000001b5a599a4d9dc6b333167c824eae917dac56a444aa097',+ block_time: 1785896637,+};++const TX_FIXTURE = {+ txid: TXID,+ version: 1,+ locktime: 961101,+ size: 700,+ weight: 1870,+ fee: 4690,+ status: TX_STATUS_FIXTURE,+ vin: [{ txid: 'a'.repeat(64), vout: 1 }],+ vout: [+ { scriptpubkey_address: 'bc1qexample', value: 2025623207327 },+ { scriptpubkey_address: 'bc1qchange', value: 265259169 },+ ],+};++describe('validators', () => {+ it('accepts mainnet address classes and rejects junk', () => {+ expect(isPlausibleBitcoinAddress(ADDRESS)).toBe(true);+ expect(isPlausibleBitcoinAddress('1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa')).toBe(true);+ expect(isPlausibleBitcoinAddress('3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')).toBe(true);+ expect(isPlausibleBitcoinAddress('not-an-address')).toBe(false);+ expect(isPlausibleBitcoinAddress('')).toBe(false);+ });++ it('accepts a 64-hex txid and rejects junk', () => {+ expect(isPlausibleTxid(TXID)).toBe(true);+ expect(isPlausibleTxid('xyz')).toBe(false);+ expect(isPlausibleTxid(null)).toBe(false);+ });+});++describe('getTipHeight', () => {+ it('parses the plain-text height and caches it', async () => {+ fetchMock.mockResolvedValueOnce(textResponse(200, '961224'));+ await expect(getTipHeight()).resolves.toBe(961224);+ await expect(getTipHeight()).resolves.toBe(961224);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock).toHaveBeenCalledWith(`${ESPLORA_BASE}/blocks/tip/height`, expect.any(Object));+ });+});++describe('getFeeEstimates', () => {+ it('maps confirmation targets to sat/vB and derives the familiar tiers', async () => {+ fetchMock.mockResolvedValueOnce(textResponse(200, FEES_FIXTURE));+ const fees = await getFeeEstimates();+ expect(fees.fastest).toBeCloseTo(2.232, 6);+ expect(fees.halfHour).toBeCloseTo(2.006, 6);+ expect(fees.hour).toBeCloseTo(1.223, 6);+ expect(fees.economy).toBeCloseTo(0.292, 6);+ expect(fees.estimates['504']).toBeCloseTo(0.1, 6);+ });++ it('falls back to the nearest slower target when the exact one is absent', async () => {+ fetchMock.mockResolvedValueOnce(textResponse(200, { 1: 5, 5: 2, 144: 0.5 }));+ const fees = await getFeeEstimates();+ expect(fees.halfHour).toBe(2); // target 3 absent, nearest at-or-above is 5+ expect(fees.hour).toBe(0.5); // target 6 absent, nearest at-or-above is 144+ });+});++describe('getAddress', () => {+ it('computes confirmed and pending balances from the txo sums', async () => {+ fetchMock.mockResolvedValueOnce(textResponse(200, ADDRESS_FIXTURE));+ const info = await getAddress(ADDRESS);+ expect(info.address).toBe(ADDRESS);+ expect(info.balanceSats).toBe(530775983879384 - 517774975978040);+ expect(info.pendingBalanceSats).toBe(0);+ expect(info.txCount).toBe(335);+ expect(info.chainStats.fundedTxoCount).toBe(343);+ });++ it('rejects an implausible address without hitting the network', async () => {+ await expect(getAddress('nope')).rejects.toThrow(/Bitcoin mainnet address/);+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('getTransaction / getTransactionStatus', () => {+ it('normalizes a confirmed tx with derived vsize and fee rate', async () => {+ fetchMock.mockResolvedValueOnce(textResponse(200, TX_FIXTURE));+ const tx = await getTransaction(TXID);+ expect(tx.txid).toBe(TXID);+ expect(tx.status.confirmed).toBe(true);+ expect(tx.status.blockHeight).toBe(961103);+ expect(tx.vsize).toBe(Math.ceil(1870 / 4));+ expect(tx.feeRate).toBeCloseTo(4690 / Math.ceil(1870 / 4), 6);+ expect(tx.inputCount).toBe(1);+ expect(tx.outputCount).toBe(2);+ expect(tx.outputValueSats).toBe(2025623207327 + 265259169);+ });++ it('maps the small status endpoint', async () => {+ fetchMock.mockResolvedValueOnce(textResponse(200, TX_STATUS_FIXTURE));+ const status = await getTransactionStatus(TXID);+ expect(status).toEqual({+ confirmed: true,+ blockHeight: 961103,+ blockHash: TX_STATUS_FIXTURE.block_hash,+ blockTime: 1785896637,+ });+ expect(fetchMock).toHaveBeenCalledWith(`${ESPLORA_BASE}/tx/${TXID}/status`, expect.any(Object));+ });++ it('throws with status 404 for an unseen txid, without retrying', async () => {+ fetchMock.mockResolvedValueOnce(textResponse(404, 'Transaction not found'));+ await expect(getTransactionStatus('f'.repeat(64))).rejects.toMatchObject({ status: 404 });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('rejects an implausible txid without hitting the network', async () => {+ await expect(getTransaction('short')).rejects.toThrow(/txid/);+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++// ── /api/forever/status wiring ──────────────────────────────────────────────++function makeReq(url) {+ const req = Readable.from([]);+ req.method = 'GET';+ req.url = url;+ req.headers = { host: 'localhost' };+ return req;+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ end(chunk) {+ if (chunk !== undefined) this.body += chunk;+ this.writableEnded = true;+ },+ };+}++const ORDER_FIXTURE = {+ id: 'order-1',+ status: 'completed',+ tx: { reveal: TXID, commit: 'b'.repeat(64) },+ files: [{ inscriptionId: `${TXID}i0` }],+ charge: { address: 'bc1qexamplechargeaddr', amount: 12345 },+};++describe('forever/status onchain enrichment', () => {+ it('adds real esplora confirmation depth to the inscription block', async () => {+ fetchMock.mockImplementation((url) => {+ const u = String(url);+ if (u.includes('ordinalsbot')) return Promise.resolve(textResponse(200, ORDER_FIXTURE));+ if (u.endsWith(`/tx/${TXID}/status`)) return Promise.resolve(textResponse(200, TX_STATUS_FIXTURE));+ if (u.endsWith('/blocks/tip/height')) return Promise.resolve(textResponse(200, '961224'));+ return Promise.resolve(textResponse(404, 'not found'));+ });++ const res = makeRes();+ await foreverStatusHandler(makeReq('/api/forever/status?id=order-1'), res);+ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.state).toBe('inscribed');+ expect(body.inscription.onchain).toEqual({+ confirmed: true,+ confirmations: 961224 - 961103 + 1,+ blockHeight: 961103,+ blockTime: 1785896637,+ source: 'esplora',+ });+ });++ it('fails soft to onchain: null when esplora cannot see the tx', async () => {+ fetchMock.mockImplementation((url) => {+ const u = String(url);+ if (u.includes('ordinalsbot')) return Promise.resolve(textResponse(200, ORDER_FIXTURE));+ return Promise.resolve(textResponse(404, 'Transaction not found'));+ });++ const res = makeRes();+ await foreverStatusHandler(makeReq('/api/forever/status?id=order-1'), res);+ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.inscription.id).toBe(`${TXID}i0`);+ expect(body.inscription.onchain).toBeNull();+ });+});