UNPKG

@bsv/sdk

Version:

BSV Blockchain Software Development Kit

68 lines 2.48 kB
import { defaultHttpClient } from '../http/DefaultHttpClient.js'; /** * Represents a chain tracker based on What's On Chain . */ export default class WhatsOnChain { network; apiKey; URL; httpClient; /** * 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 ?? 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; } } //# sourceMappingURL=WhatsOnChain.js.map