UNPKG

@mr-zwets/bchn-api-wrapper

Version:

a Typescript wrapper for interacting with the Bitcoin Cash Node (BCHN) API

101 lines (100 loc) 4.74 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { validateUrl } from "./utils/utils.js"; export class BchnRestClient { constructor(config) { var _a, _b; this.baseUrl = validateUrl(config.url); this.timeoutMs = (_a = config.timeoutMs) !== null && _a !== void 0 ? _a : 5000; this.logger = (_b = config.logger) !== null && _b !== void 0 ? _b : console; } fetchFromNode(endpoint, format) { return __awaiter(this, void 0, void 0, function* () { try { const response = yield fetch(`${this.baseUrl}/rest/${endpoint}`, { signal: AbortSignal.timeout(this.timeoutMs), }); if (!response.ok) { throw new Error(`Error fetching data from ${endpoint}: ${response.statusText}`); } if (format === 'json') { return yield response.json(); } else { return yield response.text(); // For 'bin' and 'hex', return raw text } } catch (error) { let errorMessage; // Check if the error is due to timeout or other fetch-related issues if (typeof error === 'string') { errorMessage = error; this.logger.error(error); } else if (error instanceof DOMException && error.name === 'TimeoutError') { // If error is an instance DOMException TimeoutError errorMessage = 'Request timed out'; this.logger.error(`Request to ${endpoint} timed out after ${this.timeoutMs} ms`); } else { this.logger.error(`Unknown error occurred during request to ${endpoint}`); throw new Error(`Unknown error: ${error}`); } // Always rethrow the error after logging throw new Error(errorMessage); } }); } // Get transaction details by transaction hash getTransaction(txid_1) { return __awaiter(this, arguments, void 0, function* (txid, format = 'json') { return this.fetchFromNode(`tx/${txid}.${format}`, format); }); } // getBlock Implementation getBlock(blockhash_1, includeTxDetails_1) { return __awaiter(this, arguments, void 0, function* (blockhash, includeTxDetails, format = 'json') { const path = includeTxDetails ? 'block' : 'block/notxdetails'; return this.fetchFromNode(`${path}/${blockhash}.${format}`, format); }); } // Get block headers starting from a specific block hash getBlockHeaders(count_1, blockhash_1) { return __awaiter(this, arguments, void 0, function* (count, blockhash, format = 'json') { return this.fetchFromNode(`headers/${count}/${blockhash}.${format}`, format); }); } // Get chain info (chain state details) getChainInfo() { return __awaiter(this, void 0, void 0, function* () { return this.fetchFromNode('chaininfo.json', 'json'); }); } // Query UTXO set based on specific outpoints (txid and vout) getUTXOs(checkmempool_1, outpoints_1) { return __awaiter(this, arguments, void 0, function* (checkmempool, outpoints, format = 'json') { const path = (checkmempool ? 'checkmempool/' : '') + outpoints.join('/'); const endpoint = `getutxos/${path}.${format}`; return this.fetchFromNode(endpoint, format); }); } // Get mempool information (basic) getMempoolInfo() { return __awaiter(this, void 0, void 0, function* () { return this.fetchFromNode('mempool/info.json', 'json'); }); } // Get mempool contents (transactions currently in the mempool) getMempoolContents() { return __awaiter(this, void 0, void 0, function* () { return this.fetchFromNode('mempool/contents.json', 'json'); }); } }