esplora-client
Version:
Tiny client library for Esplora-based Bitcoin APIs
39 lines • 2.03 kB
JavaScript
import fetch from "fetch-plus-plus";
/**
* Creates a new Esplora API client.
*
* @param options Client options.
* @param options.hostnames List of API hostnames.
* @param options.network Network name.
*/
export const esploraClient = function (options = {}) {
const { hostnames = ["mempool.space", "blockstream.info"], network = "mainnet", } = options;
const basePath = network === "mainnet" ? "api" : `${network}/api`;
const concatenateErrorMessage = (previousError, hostname) => (fetchError) => Promise.reject(new Error(`${previousError.message}, ${hostname}: ${fetchError.message}`));
const chainFetchCallsOnFailure = (path, opts) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(promiseChain, hostname) => promiseChain.catch((err) => fetch(`https://${hostname}/${basePath}/${path}`, opts).catch(concatenateErrorMessage(err, hostname)));
const fetchApi = (path, opts) => hostnames.reduce(chainFetchCallsOnFailure(path, opts), Promise.reject(new Error("All API calls failed")));
return {
bitcoin: {
addresses: {
getAddress: ({ address }) => fetchApi(`address/${address}`),
getAddressTxs: ({ address, after_txid, }) => fetchApi(`address/${address}/txs`, after_txid ? { queryString: { after_txid } } : undefined),
getAddressTxsUtxo: ({ address }) => fetchApi(`address/${address}/utxo`),
},
blocks: {
getBlocksTipHeight: () => fetchApi("blocks/tip/height"),
},
fees: {
getFeeEstimates: () => fetchApi("fee-estimates"),
getFeesRecommended: () => fetchApi("v1/fees/recommended"),
},
transactions: {
getTx: ({ txid }) => fetchApi(`tx/${txid}`),
getTxHex: ({ txid }) => fetchApi(`tx/${txid}/hex`),
postTx: ({ txhex }) => fetchApi("tx", { body: txhex, method: "POST" }),
},
},
};
};
//# sourceMappingURL=index.js.map