// Minimal Esplora (mempool.space) client: balances, UTXOs, fees, broadcast. // Only public addresses ever leave the browser. import { type BtcVault, type DerivedAddress, deriveAddress, NETWORKS } from './core.ts'; import type { Utxo } from './psbt.ts'; const GAP_LIMIT = 20; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** GET with retry + exponential backoff (public explorers rate-limit bursts). */ async function get(base: string, path: string, asText = false): Promise { let last: unknown; for (let attempt = 0; attempt < 5; attempt++) { if (attempt) await sleep(700 * 2 ** (attempt - 1)); try { const r = await fetch(base + path); if (r.status === 429 || r.status >= 500) { last = new Error(`${r.status}`); continue; } if (!r.ok) throw new Error(`${path}: ${r.status} ${await r.text().catch(() => '')}`); return (asText ? r.text() : r.json()) as Promise; } catch (e) { last = e; // network / CORS-blocked 429 → retry } } throw new Error(`Block explorer unavailable (${base}). Try again in a minute. ${last instanceof Error ? last.message : ''}`); } interface AddrStats { chain_stats: Stats; mempool_stats: Stats } interface Stats { funded_txo_sum: number; spent_txo_sum: number; tx_count: number } export interface AddressInfo extends DerivedAddress { used: boolean; balance: bigint; // confirmed + unconfirmed txCount: number; } export interface ScanResult { addresses: AddressInfo[]; utxos: Utxo[]; confirmed: bigint; unconfirmed: bigint; nextReceive: DerivedAddress; nextChange: DerivedAddress; } /** Walks receive (0) and change (1) chains until GAP_LIMIT unused addresses in a row. */ export async function scanVault(vault: BtcVault, onProgress?: (n: number) => void): Promise { const base = NETWORKS[vault.network].esplora; const addresses: AddressInfo[] = []; let count = 0; for (const change of [0, 1] as const) { let gap = 0, index = 0; while (gap < GAP_LIMIT) { const batch = Array.from({ length: 3 }, (_, k) => deriveAddress(vault, change, index + k)); const stats = await Promise.all(batch.map((a) => get(base, `/address/${a.address}`))); batch.forEach((a, k) => { const s = stats[k]; const txCount = s.chain_stats.tx_count + s.mempool_stats.tx_count; const balance = BigInt(s.chain_stats.funded_txo_sum - s.chain_stats.spent_txo_sum + s.mempool_stats.funded_txo_sum - s.mempool_stats.spent_txo_sum); const used = txCount > 0; gap = used ? 0 : gap + 1; if (used) addresses.push({ ...a, used, balance, txCount }); }); index += 3; onProgress?.((count += 3)); await sleep(120); } } // the first unused address after the last used one const firstFree = (change: 0 | 1) => { const used = addresses.filter((a) => a.change === change && a.used).map((a) => a.index); return deriveAddress(vault, change, used.length ? Math.max(...used) + 1 : 0); }; const utxos: Utxo[] = []; for (const a of addresses.filter((x) => x.balance > 0n)) { const list = await get<{ txid: string; vout: number; value: number; status: { confirmed: boolean } }[]>(base, `/address/${a.address}/utxo`); for (const u of list) utxos.push({ txid: u.txid, vout: u.vout, value: BigInt(u.value), confirmed: u.status.confirmed, addr: a }); } const confirmed = utxos.filter((u) => u.confirmed).reduce((s, u) => s + u.value, 0n); const unconfirmed = utxos.filter((u) => !u.confirmed).reduce((s, u) => s + u.value, 0n); return { addresses, utxos, confirmed, unconfirmed, nextReceive: firstFree(0), nextChange: firstFree(1) }; } export async function attachPrevTxs(vault: BtcVault, utxos: Utxo[]): Promise { const base = NETWORKS[vault.network].esplora; const cache = new Map(); const out: Utxo[] = []; for (const u of utxos) { if (!cache.has(u.txid)) cache.set(u.txid, await get(base, `/tx/${u.txid}/hex`, true)); out.push({ ...u, prevTxHex: cache.get(u.txid) }); } return out; } export async function feeRates(vault: BtcVault): Promise<{ fastestFee: number; halfHourFee: number; hourFee: number; economyFee: number }> { const base = NETWORKS[vault.network].esplora; try { return await get(base, '/v1/fees/recommended'); } catch { return { fastestFee: 10, halfHourFee: 5, hourFee: 3, economyFee: 1 }; } } export async function broadcast(vault: BtcVault, txHex: string): Promise { const r = await fetch(NETWORKS[vault.network].esplora + '/tx', { method: 'POST', body: txHex }); const text = await r.text(); if (!r.ok) throw new Error(`Broadcast rejected: ${text}`); return text.trim(); } export interface TxSummary { txid: string; confirmed: boolean; time?: number; delta: bigint } export async function history(vault: BtcVault, addresses: AddressInfo[]): Promise { const base = NETWORKS[vault.network].esplora; const mine = new Set(addresses.map((a) => a.address)); const txs = new Map(); for (const a of addresses.filter((x) => x.used)) { const list = await get(base, `/address/${a.address}/txs`); for (const t of list) txs.set(t.txid, t); } const out: TxSummary[] = []; for (const t of txs.values()) { let delta = 0n; for (const i of t.vin) if (i.prevout && mine.has(i.prevout.scriptpubkey_address)) delta -= BigInt(i.prevout.value); for (const o of t.vout) if (mine.has(o.scriptpubkey_address)) delta += BigInt(o.value); out.push({ txid: t.txid, confirmed: t.status.confirmed, time: t.status.block_time, delta }); } return out.sort((a, b) => (b.time ?? Infinity) - (a.time ?? Infinity)); }