@bsv/sdk
Version:
BSV Blockchain Software Development Kit
67 lines • 2.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const DefaultHttpClient_js_1 = require("../http/DefaultHttpClient.js");
/**
* Represents a chain tracker based on What's On Chain .
*/
class WhatsOnChain {
/**
* Constructs an instance of the WhatsOnChain ChainTracker.
*
* @param {'main' | 'test' | 'stn'} network - The BSV network to use when calling the WhatsOnChain API.
* @param {WhatsOnChainConfig} config - Configuration options for the WhatsOnChain ChainTracker.
*/
constructor(network = 'main', config = {}) {
const { apiKey, httpClient } = config;
this.network = network;
this.URL = `https://api.whatsonchain.com/v1/bsv/${network}`;
this.httpClient = httpClient ?? (0, DefaultHttpClient_js_1.defaultHttpClient)();
this.apiKey = apiKey ?? '';
}
async isValidRootForHeight(root, height) {
const requestOptions = {
method: 'GET',
headers: this.getHttpHeaders()
};
const response = await this.httpClient.request(`${this.URL}/block/${height}/header`, requestOptions);
if (response.ok) {
const { merkleroot } = response.data;
return merkleroot === root;
}
else if (response.status === 404) {
return false;
}
else {
throw new Error(`Failed to verify merkleroot for height ${height} because of an error: ${JSON.stringify(response.data)} `);
}
}
async currentHeight() {
try {
const requestOptions = {
method: 'GET',
headers: this.getHttpHeaders()
};
const response = await this.httpClient.request(`${this.URL}/block/headers`, requestOptions);
if (response.ok) {
return response.data[0].height;
}
else {
throw new Error(`Failed to get current height because of an error: ${JSON.stringify(response.data)} `);
}
}
catch (error) {
throw new Error(`Failed to get current height because of an error: ${error instanceof Error ? error.message : String(error)}`);
}
}
getHttpHeaders() {
const headers = {
Accept: 'application/json'
};
if (typeof this.apiKey === 'string' && this.apiKey.trim() !== '') {
headers.Authorization = this.apiKey;
}
return headers;
}
}
exports.default = WhatsOnChain;
//# sourceMappingURL=WhatsOnChain.js.map