@mr-zwets/bchn-api-wrapper
Version:
a Typescript wrapper for interacting with the Bitcoin Cash Node (BCHN) API
114 lines (113 loc) • 5.43 kB
JavaScript
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";
/** REST client for read-only BCHN blockchain access via the REST interface. */
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);
}
});
}
/** Returns transaction details by txid. */
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);
});
}
/** Returns 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);
});
}
/** Returns current chain state (network, sync progress, best block). */
getChainInfo() {
return __awaiter(this, void 0, void 0, function* () {
return this.fetchFromNode('chaininfo.json', 'json');
});
}
/** Queries UTXO set for specific outpoints. Outpoints format: "txid-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);
});
}
/** Returns mempool statistics (size, bytes, fee rates). */
getMempoolInfo() {
return __awaiter(this, void 0, void 0, function* () {
return this.fetchFromNode('mempool/info.json', 'json');
});
}
/** Returns all transactions currently in the mempool. */
getMempoolContents() {
return __awaiter(this, void 0, void 0, function* () {
return this.fetchFromNode('mempool/contents.json', 'json');
});
}
/** Returns block with bytecode pattern data (v29.0.0+). */
getBlockWithPatterns(blockhash) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetchFromNode(`block/withpatterns/${blockhash}.json`, 'json');
});
}
/** Returns transaction with bytecode pattern data (v29.0.0+). */
getTransactionWithPatterns(txid) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetchFromNode(`tx/withpatterns/${txid}.json`, 'json');
});
}
}