@bsv/wallet-toolbox
Version:
BRC100 conforming wallet, wallet storage and wallet signer components
1,771 lines (1,235 loc) • 231 kB
Markdown
# SERVICES: BSV Wallet Toolbox API Documentation
The documentation is split into various pages, this page covers the [Services](#class-services) and related API.
To function properly, a wallet makes use of a variety of services provided by the network:
1. Broadcast new transactions.
1. Verify the validity of unspent outputs.
1. Obtain mined transaction proofs.
2. Obtain block headers for proof validation.
3. Obtain exchange rates for UI and fee calculations.
These tasks are the responsibility of the [Services](#class-services) class.
[Return To Top](./README.md)
<!--#region ts2md-api-merged-here-->
### API
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
#### Interfaces
| | | |
| --- | --- | --- |
| [ArcConfig](#interface-arcconfig) | [ChaintracksClientApi](#interface-chaintracksclientapi) | [ChaintracksStorageNoDbOptions](#interface-chaintracksstoragenodboptions) |
| [ArcMinerGetTxData](#interface-arcminergettxdata) | [ChaintracksFetchApi](#interface-chaintracksfetchapi) | [ChaintracksStorageQueryApi](#interface-chaintracksstoragequeryapi) |
| [BitailsConfig](#interface-bitailsconfig) | [ChaintracksFsApi](#interface-chaintracksfsapi) | [ChaintracksWritableFileApi](#interface-chaintrackswritablefileapi) |
| [BitailsMerkleProof](#interface-bitailsmerkleproof) | [ChaintracksInfoApi](#interface-chaintracksinfoapi) | [ExchangeRatesIoApi](#interface-exchangeratesioapi) |
| [BulkFileDataManagerMergeResult](#interface-bulkfiledatamanagermergeresult) | [ChaintracksManagementApi](#interface-chaintracksmanagementapi) | [GetHeaderByteFileLinksResult](#interface-getheaderbytefilelinksresult) |
| [BulkFileDataManagerOptions](#interface-bulkfiledatamanageroptions) | [ChaintracksOptions](#interface-chaintracksoptions) | [HeightRangeApi](#interface-heightrangeapi) |
| [BulkHeaderFileInfo](#interface-bulkheaderfileinfo) | [ChaintracksPackageInfoApi](#interface-chaintrackspackageinfoapi) | [HeightRanges](#interface-heightranges) |
| [BulkHeaderFilesInfo](#interface-bulkheaderfilesinfo) | [ChaintracksReadableFileApi](#interface-chaintracksreadablefileapi) | [LiveBlockHeader](#interface-liveblockheader) |
| [BulkIngestorApi](#interface-bulkingestorapi) | [ChaintracksServiceClientOptions](#interface-chaintracksserviceclientoptions) | [LiveIngestorApi](#interface-liveingestorapi) |
| [BulkIngestorBaseOptions](#interface-bulkingestorbaseoptions) | [ChaintracksServiceOptions](#interface-chaintracksserviceoptions) | [LiveIngestorBaseOptions](#interface-liveingestorbaseoptions) |
| [BulkIngestorCDNOptions](#interface-bulkingestorcdnoptions) | [ChaintracksStorageApi](#interface-chaintracksstorageapi) | [LiveIngestorWhatsOnChainOptions](#interface-liveingestorwhatsonchainoptions) |
| [BulkIngestorWhatsOnChainOptions](#interface-bulkingestorwhatsonchainoptions) | [ChaintracksStorageBaseOptions](#interface-chaintracksstoragebaseoptions) | [ServiceCall](#interface-servicecall) |
| [BulkStorageApi](#interface-bulkstorageapi) | [ChaintracksStorageBulkFileApi](#interface-chaintracksstoragebulkfileapi) | [ServiceToCall](#interface-servicetocall) |
| [BulkStorageBaseOptions](#interface-bulkstoragebaseoptions) | [ChaintracksStorageIdbOptions](#interface-chaintracksstorageidboptions) | [WhatsOnChainServicesOptions](#interface-whatsonchainservicesoptions) |
| [BulkSyncResult](#interface-bulksyncresult) | [ChaintracksStorageIdbSchema](#interface-chaintracksstorageidbschema) | [WocChainInfo](#interface-wocchaininfo) |
| [ChaintracksApi](#interface-chaintracksapi) | [ChaintracksStorageIngestApi](#interface-chaintracksstorageingestapi) | [WocGetHeaderByteFileLinks](#interface-wocgetheaderbytefilelinks) |
| [ChaintracksAppendableFileApi](#interface-chaintracksappendablefileapi) | [ChaintracksStorageKnexOptions](#interface-chaintracksstorageknexoptions) | [WocGetHeadersHeader](#interface-wocgetheadersheader) |
| [ChaintracksChainTrackerOptions](#interface-chaintrackschaintrackeroptions) | [ChaintracksStorageMemoryOptions](#interface-chaintracksstoragememoryoptions) | [WocHeader](#interface-wocheader) |
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ArcConfig
Configuration options for the ARC broadcaster.
```ts
export interface ArcConfig {
apiKey?: string;
httpClient?: HttpClient;
deploymentId?: string;
callbackUrl?: string;
callbackToken?: string;
headers?: Record<string, string>;
}
```
###### Property apiKey
Authentication token for the ARC API
```ts
apiKey?: string
```
###### Property callbackToken
default access token for notification callback endpoint. It will be used as a Authorization header for the http callback
```ts
callbackToken?: string
```
###### Property callbackUrl
notification callback endpoint for proofs and double spend notification
```ts
callbackUrl?: string
```
###### Property deploymentId
Deployment id used annotating api calls in XDeployment-ID header - this value will be randomly generated if not set
```ts
deploymentId?: string
```
###### Property headers
additional headers to be attached to all tx submissions.
```ts
headers?: Record<string, string>
```
###### Property httpClient
The HTTP client used to make requests to the ARC API.
```ts
httpClient?: HttpClient
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ArcMinerGetTxData
```ts
export interface ArcMinerGetTxData {
status: number;
title: string;
blockHash: string;
blockHeight: number;
competingTxs: null | string[];
extraInfo: string;
merklePath: string;
timestamp: string;
txid: string;
txStatus: string;
}
```
See also: [blockHash](./services.md#function-blockhash)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BitailsConfig
```ts
export interface BitailsConfig {
apiKey?: string;
httpClient?: HttpClient;
}
```
###### Property apiKey
Authentication token for BitTails API
```ts
apiKey?: string
```
###### Property httpClient
The HTTP client used to make requests to the API.
```ts
httpClient?: HttpClient
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BitailsMerkleProof
```ts
export interface BitailsMerkleProof {
index: number;
txOrId: string;
target: string;
nodes: string[];
}
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkFileDataManagerMergeResult
```ts
export interface BulkFileDataManagerMergeResult {
unchanged: BulkHeaderFileInfo[];
inserted: BulkHeaderFileInfo[];
updated: BulkHeaderFileInfo[];
dropped: BulkHeaderFileInfo[];
}
```
See also: [BulkHeaderFileInfo](./services.md#interface-bulkheaderfileinfo)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkFileDataManagerOptions
```ts
export interface BulkFileDataManagerOptions {
chain: Chain;
maxPerFile: number;
maxRetained?: number;
fetch?: ChaintracksFetchApi;
fromKnownSourceUrl?: string;
}
```
See also: [Chain](./client.md#type-chain), [ChaintracksFetchApi](./services.md#interface-chaintracksfetchapi)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkHeaderFileInfo
Descriptive information about a single bulk header file.
```ts
export interface BulkHeaderFileInfo {
fileName: string;
firstHeight: number;
count: number;
prevChainWork: string;
lastChainWork: string;
prevHash: string;
lastHash: string | null;
fileHash: string | null;
chain?: Chain;
data?: Uint8Array;
validated?: boolean;
fileId?: number;
sourceUrl?: string;
}
```
See also: [Chain](./client.md#type-chain)
###### Property chain
Which chain: 'main' or 'test'
```ts
chain?: Chain
```
See also: [Chain](./client.md#type-chain)
###### Property count
count of how many headers the file contains. File size must be 80 * count.
```ts
count: number
```
###### Property fileHash
file contents single sha256 hash as base64 string
```ts
fileHash: string | null
```
###### Property fileId
optional, used for database storage
```ts
fileId?: number
```
###### Property fileName
filename and extension, no path
```ts
fileName: string
```
###### Property firstHeight
chain height of first header in file
```ts
firstHeight: number
```
###### Property lastChainWork
lastChainWork is the cummulative chain work including the last header in this file's data, as a hex string.
```ts
lastChainWork: string
```
###### Property lastHash
block hash of last header in the file in standard hex string block hash encoding
```ts
lastHash: string | null
```
###### Property prevChainWork
prevChainWork is the cummulative chain work up to the first header in this file's data, as a hex string.
```ts
prevChainWork: string
```
###### Property prevHash
previousHash of first header in file in standard hex string block hash encoding
```ts
prevHash: string
```
###### Property sourceUrl
optional, if valid `${sourceUrl}/${fileName}` is the source of this data.
```ts
sourceUrl?: string
```
###### Property validated
true iff these properties should be considered pre-validated, including a valid required fileHash of data (when not undefined).
```ts
validated?: boolean
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkHeaderFilesInfo
Describes a collection of bulk block header files.
```ts
export interface BulkHeaderFilesInfo {
rootFolder: string;
jsonFilename: string;
files: BulkHeaderFileInfo[];
headersPerFile: number;
}
```
See also: [BulkHeaderFileInfo](./services.md#interface-bulkheaderfileinfo)
###### Property files
Array of information about each bulk block header file.
```ts
files: BulkHeaderFileInfo[]
```
See also: [BulkHeaderFileInfo](./services.md#interface-bulkheaderfileinfo)
###### Property headersPerFile
Maximum number of headers in a single file in this collection of files.
```ts
headersPerFile: number
```
###### Property jsonFilename
Sub-path to this resource on rootFolder
```ts
jsonFilename: string
```
###### Property rootFolder
Where this file was fetched or read from.
```ts
rootFolder: string
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkIngestorApi
```ts
export interface BulkIngestorApi {
shutdown(): Promise<void>;
getPresentHeight(): Promise<number | undefined>;
fetchHeaders(before: HeightRanges, fetchRange: HeightRange, bulkRange: HeightRange, priorLiveHeaders: BlockHeader[]): Promise<BlockHeader[]>;
synchronize(presentHeight: number, before: HeightRanges, priorLiveHeaders: BlockHeader[]): Promise<BulkSyncResult>;
setStorage(storage: ChaintracksStorageApi, log: (...args: any[]) => void): Promise<void>;
storage(): ChaintracksStorageApi;
}
```
See also: [BlockHeader](./client.md#interface-blockheader), [BulkSyncResult](./services.md#interface-bulksyncresult), [ChaintracksStorageApi](./services.md#interface-chaintracksstorageapi), [HeightRange](./services.md#class-heightrange), [HeightRanges](./services.md#interface-heightranges)
###### Method fetchHeaders
A BulkIngestor fetches and updates storage with bulk headers in bulkRange.
If it can, it must also fetch live headers in fetch range that are not in bulkRange and return them as an array.
The storage methods `insertBulkFile`, `updateBulkFile`, and `addBulkHeaders` should be used to add bulk headers to storage.
```ts
fetchHeaders(before: HeightRanges, fetchRange: HeightRange, bulkRange: HeightRange, priorLiveHeaders: BlockHeader[]): Promise<BlockHeader[]>
```
See also: [BlockHeader](./client.md#interface-blockheader), [HeightRange](./services.md#class-heightrange), [HeightRanges](./services.md#interface-heightranges)
Returns
new live headers: headers in fetchRange but not in bulkRange
Argument Details
+ **before**
+ bulk and live range of headers before ingesting any new headers.
+ **fetchRange**
+ range of headers still needed, includes both missing bulk and live headers.
+ **bulkRange**
+ range of bulk headers still needed
+ **priorLiveHeaders**
+ any headers accumulated by prior bulk ingestor(s) that are too recent for bulk storage.
###### Method getPresentHeight
If the bulk ingestor is capable, return the approximate
present height of the actual chain being tracked.
Otherwise, return undefined.
May not assume that setStorage has been called.
```ts
getPresentHeight(): Promise<number | undefined>
```
###### Method setStorage
Called before first Synchronize with reference to storage.
Components requiring asynchronous setup can override base class implementation.
```ts
setStorage(storage: ChaintracksStorageApi, log: (...args: any[]) => void): Promise<void>
```
See also: [ChaintracksStorageApi](./services.md#interface-chaintracksstorageapi)
###### Method shutdown
Close and release all resources.
```ts
shutdown(): Promise<void>
```
###### Method synchronize
A BulkIngestor has two potential goals:
1. To source missing bulk headers and include them in bulk storage.
2. To source missing live headers to be forwarded to live storage.
```ts
synchronize(presentHeight: number, before: HeightRanges, priorLiveHeaders: BlockHeader[]): Promise<BulkSyncResult>
```
See also: [BlockHeader](./client.md#interface-blockheader), [BulkSyncResult](./services.md#interface-bulksyncresult), [HeightRanges](./services.md#interface-heightranges)
Returns
updated priorLiveHeaders including any accumulated by this ingestor
Argument Details
+ **presentHeight**
+ current height of the active chain tip, may lag the true value.
+ **before**
+ current bulk and live storage height ranges, either may be empty.
+ **priorLiveHeaders**
+ any headers accumulated by prior bulk ingestor(s) that are too recent for bulk storage.
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkIngestorBaseOptions
```ts
export interface BulkIngestorBaseOptions {
chain: Chain;
jsonResource: string | undefined;
}
```
See also: [Chain](./client.md#type-chain)
###### Property chain
The target chain: "main" or "test"
```ts
chain: Chain
```
See also: [Chain](./client.md#type-chain)
###### Property jsonResource
Required.
The name of the JSON resource to request from CDN which describes currently
available bulk block header resources.
```ts
jsonResource: string | undefined
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkIngestorCDNOptions
```ts
export interface BulkIngestorCDNOptions extends BulkIngestorBaseOptions {
jsonResource: string | undefined;
cdnUrl: string | undefined;
maxPerFile: number | undefined;
fetch: ChaintracksFetchApi;
}
```
See also: [BulkIngestorBaseOptions](./services.md#interface-bulkingestorbaseoptions), [ChaintracksFetchApi](./services.md#interface-chaintracksfetchapi)
###### Property cdnUrl
Required.
URL to CDN implementing the bulk ingestor CDN service protocol
```ts
cdnUrl: string | undefined
```
###### Property jsonResource
Required.
The name of the JSON resource to request from CDN which describes currently
available bulk block header resources.
```ts
jsonResource: string | undefined
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkIngestorWhatsOnChainOptions
```ts
export interface BulkIngestorWhatsOnChainOptions extends BulkIngestorBaseOptions, WhatsOnChainServicesOptions {
idleWait: number | undefined;
chain: Chain;
apiKey?: string;
timeout: number;
userAgent: string;
enableCache: boolean;
chainInfoMsecs: number;
fetch?: ChaintracksFetchApi;
}
```
See also: [BulkIngestorBaseOptions](./services.md#interface-bulkingestorbaseoptions), [Chain](./client.md#type-chain), [ChaintracksFetchApi](./services.md#interface-chaintracksfetchapi), [WhatsOnChainServicesOptions](./services.md#interface-whatsonchainservicesoptions)
###### Property apiKey
WhatsOnChain.com API Key
https://docs.taal.com/introduction/get-an-api-key
If unknown or empty, maximum request rate is limited.
https://developers.whatsonchain.com/#rate-limits
```ts
apiKey?: string
```
###### Property chain
Which chain is being tracked: main, test, or stn.
```ts
chain: Chain
```
See also: [Chain](./client.md#type-chain)
###### Property chainInfoMsecs
How long chainInfo is considered still valid before updating (msecs).
```ts
chainInfoMsecs: number
```
###### Property enableCache
Enable WhatsOnChain client cache option.
```ts
enableCache: boolean
```
###### Property idleWait
Maximum msecs of "normal" pause with no new data arriving.
```ts
idleWait: number | undefined
```
###### Property timeout
Request timeout for GETs to https://api.whatsonchain.com/v1/bsv
```ts
timeout: number
```
###### Property userAgent
User-Agent header value for requests to https://api.whatsonchain.com/v1/bsv
```ts
userAgent: string
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkStorageApi
Handles block header storage and retrieval older than the "live" portion of the chain.
Height is the primary and only indexing field required.
Only stores headers on the active chain; no orphans, no forks, no reorgs.
```ts
export interface BulkStorageApi {
shutdown(): Promise<void>;
getMaxHeight(): Promise<number>;
getHeightRange(): Promise<HeightRange>;
appendHeaders(minHeight: number, count: number, headers: Uint8Array): Promise<void>;
findHeaderForHeightOrUndefined(height: number): Promise<BlockHeader | undefined>;
findHeaderForHeight(height: number): Promise<BlockHeader>;
headersToBuffer(height: number, count: number): Promise<Uint8Array>;
exportBulkHeaders(rootFolder: string, jsonFilename: string, maxPerFile: number): Promise<void>;
setStorage(storage: ChaintracksStorageApi, log: (...args: any[]) => void): Promise<void>;
}
```
See also: [BlockHeader](./client.md#interface-blockheader), [ChaintracksStorageApi](./services.md#interface-chaintracksstorageapi), [HeightRange](./services.md#class-heightrange)
###### Method appendHeaders
Append new Block Headers to BulkStorage.
Requires that these headers directly extend existing headers.
maxHeight of existing plus one equals minHeight of `headers`.
hash of last existing equals previousHash of first in `headers`.
Checks that all `headers` are valid (hash, previousHash)
Duplicate headers must be ignored.
```ts
appendHeaders(minHeight: number, count: number, headers: Uint8Array): Promise<void>
```
Argument Details
+ **minHeight**
+ must match height of first header in buffer
+ **count**
+ times 80 must equal headers.length
+ **headers**
+ encoded as packed array of 80 byte serialized block headers
###### Method exportBulkHeaders
Exports current bulk headers, including all ingests, excluding live headers to static header files.
```ts
exportBulkHeaders(rootFolder: string, jsonFilename: string, maxPerFile: number): Promise<void>
```
Argument Details
+ **rootFolder**
+ Where the json and headers files will be written
+ **jsonFilename**
+ The name of the json file.
+ **maxPerFile**
+ The maximum headers per file.
###### Method findHeaderForHeight
Returns block header for a given block height on active chain.
Throws if not found.
```ts
findHeaderForHeight(height: number): Promise<BlockHeader>
```
See also: [BlockHeader](./client.md#interface-blockheader)
Argument Details
+ **hash**
+ block hash
###### Method findHeaderForHeightOrUndefined
Returns block header for a given block height on active chain.
```ts
findHeaderForHeightOrUndefined(height: number): Promise<BlockHeader | undefined>
```
See also: [BlockHeader](./client.md#interface-blockheader)
Argument Details
+ **hash**
+ block hash
###### Method getHeightRange
```ts
getHeightRange(): Promise<HeightRange>
```
See also: [HeightRange](./services.md#class-heightrange)
Returns
available bulk block header height range: `(0, getMaxHeight())`
###### Method getMaxHeight
```ts
getMaxHeight(): Promise<number>
```
Returns
the height of the most recent header in bulk storage or -1 if empty.
###### Method headersToBuffer
Adds headers in 80 byte serialized format to a buffer.
Only adds active headers.
returned array length divided by 80 is the actual number returned.
Returns the buffer.
```ts
headersToBuffer(height: number, count: number): Promise<Uint8Array>
```
Argument Details
+ **height**
+ of first header
+ **count**
+ of headers
###### Method setStorage
Called before first Synchronize with reference to storage.
Components requiring asynchronous setup can override base class implementation.
```ts
setStorage(storage: ChaintracksStorageApi, log: (...args: any[]) => void): Promise<void>
```
See also: [ChaintracksStorageApi](./services.md#interface-chaintracksstorageapi)
###### Method shutdown
Close and release all resources.
```ts
shutdown(): Promise<void>
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkStorageBaseOptions
```ts
export interface BulkStorageBaseOptions {
chain: Chain;
fs: ChaintracksFsApi;
}
```
See also: [Chain](./client.md#type-chain), [ChaintracksFsApi](./services.md#interface-chaintracksfsapi)
###### Property chain
The target chain: "main" or "test"
```ts
chain: Chain
```
See also: [Chain](./client.md#type-chain)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: BulkSyncResult
```ts
export interface BulkSyncResult {
liveHeaders: BlockHeader[];
liveRange: HeightRange;
done: boolean;
log: string;
}
```
See also: [BlockHeader](./client.md#interface-blockheader), [HeightRange](./services.md#class-heightrange)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksApi
Full Chaintracks API including startListening with callbacks
```ts
export interface ChaintracksApi extends ChaintracksClientApi {
startListening(listening?: () => void): Promise<void>;
}
```
See also: [ChaintracksClientApi](./services.md#interface-chaintracksclientapi)
###### Method startListening
Start or resume listening for new headers.
Calls `synchronize` to catch up on headers that were found while not listening.
Begins listening to any number of configured new header notification services.
Begins sending notifications to subscribed listeners only after processing any
previously found headers.
May be called if already listening or synchronizing to listen.
`listening` callback will be called after listening for new live headers has begun.
Alternatively, the `listening` API function which returns a Promise can be awaited.
```ts
startListening(listening?: () => void): Promise<void>
```
Argument Details
+ **listening**
+ callback indicates when listening for new headers has started.
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksAppendableFileApi
Supports access and appending data to new or existing named data storage.
New data is always appended to the end of existing data.
```ts
export interface ChaintracksAppendableFileApi extends ChaintracksReadableFileApi {
append(data: Uint8Array): Promise<void>;
}
```
See also: [ChaintracksReadableFileApi](./services.md#interface-chaintracksreadablefileapi)
###### Method append
```ts
append(data: Uint8Array): Promise<void>
```
Argument Details
+ **data**
+ data to add to the end of existing data.
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksChainTrackerOptions
```ts
export interface ChaintracksChainTrackerOptions {
maxRetries?: number;
}
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksClientApi
Chaintracks client API excluding events and callbacks
```ts
export interface ChaintracksClientApi extends ChainTracker {
getChain(): Promise<Chain>;
getInfo(): Promise<ChaintracksInfoApi>;
getPresentHeight(): Promise<number>;
getHeaders(height: number, count: number): Promise<string>;
findChainTipHeader(): Promise<BlockHeader>;
findChainTipHash(): Promise<string>;
findHeaderForHeight(height: number): Promise<BlockHeader | undefined>;
findHeaderForBlockHash(hash: string): Promise<BlockHeader | undefined>;
addHeader(header: BaseBlockHeader): Promise<void>;
startListening(): Promise<void>;
listening(): Promise<void>;
isListening(): Promise<boolean>;
isSynchronized(): Promise<boolean>;
subscribeHeaders(listener: HeaderListener): Promise<string>;
subscribeReorgs(listener: ReorgListener): Promise<string>;
unsubscribe(subscriptionId: string): Promise<boolean>;
isValidRootForHeight(root: string, height: number): Promise<boolean>;
currentHeight: () => Promise<number>;
}
```
See also: [BaseBlockHeader](./client.md#interface-baseblockheader), [BlockHeader](./client.md#interface-blockheader), [Chain](./client.md#type-chain), [ChaintracksInfoApi](./services.md#interface-chaintracksinfoapi), [HeaderListener](./services.md#type-headerlistener), [ReorgListener](./services.md#type-reorglistener)
###### Method addHeader
Submit a possibly new header for adding
If the header is invalid or a duplicate it will not be added.
This header will be ignored if the previous header has not already been inserted when this header
is considered for insertion.
```ts
addHeader(header: BaseBlockHeader): Promise<void>
```
See also: [BaseBlockHeader](./client.md#interface-baseblockheader)
Returns
immediately
###### Method findChainTipHash
Returns the block hash of the active chain tip.
```ts
findChainTipHash(): Promise<string>
```
###### Method findChainTipHeader
Returns the active chain tip header
```ts
findChainTipHeader(): Promise<BlockHeader>
```
See also: [BlockHeader](./client.md#interface-blockheader)
###### Method findHeaderForBlockHash
Returns block header for a given recent block hash or undefined.
```ts
findHeaderForBlockHash(hash: string): Promise<BlockHeader | undefined>
```
See also: [BlockHeader](./client.md#interface-blockheader)
###### Method findHeaderForHeight
Returns block header for a given block height on active chain.
```ts
findHeaderForHeight(height: number): Promise<BlockHeader | undefined>
```
See also: [BlockHeader](./client.md#interface-blockheader)
###### Method getChain
Confirms the chain
```ts
getChain(): Promise<Chain>
```
See also: [Chain](./client.md#type-chain)
###### Method getHeaders
Adds headers in 80 byte serialized format to an array.
Only adds active headers.
array length divided by 80 is the actual number returned.
```ts
getHeaders(height: number, count: number): Promise<string>
```
Returns
array of headers as serialized hex string
Argument Details
+ **height**
+ of first header
+ **count**
+ of headers, maximum
###### Method getInfo
```ts
getInfo(): Promise<ChaintracksInfoApi>
```
See also: [ChaintracksInfoApi](./services.md#interface-chaintracksinfoapi)
Returns
Summary of configuration and state.
###### Method getPresentHeight
Return the latest chain height from configured bulk ingestors.
```ts
getPresentHeight(): Promise<number>
```
###### Method isListening
Returns true if actively listening for new headers and client api is enabled.
```ts
isListening(): Promise<boolean>
```
###### Method isSynchronized
Returns true if `synchronize` has completed at least once.
```ts
isSynchronized(): Promise<boolean>
```
###### Method listening
Returns a Promise that will resolve when the previous call to startListening
enters the listening-for-new-headers state.
```ts
listening(): Promise<void>
```
###### Method startListening
Start or resume listening for new headers.
Calls `synchronize` to catch up on headers that were found while not listening.
Begins listening to any number of configured new header notification services.
Begins sending notifications to subscribed listeners only after processing any
previously found headers.
May be called if already listening or synchronizing to listen.
The `listening` API function which returns a Promise can be awaited.
```ts
startListening(): Promise<void>
```
###### Method subscribeHeaders
Subscribe to "header" events.
```ts
subscribeHeaders(listener: HeaderListener): Promise<string>
```
See also: [HeaderListener](./services.md#type-headerlistener)
Returns
identifier for this subscription
Throws
ERR_NOT_IMPLEMENTED if callback events are not supported
###### Method subscribeReorgs
Subscribe to "reorganization" events.
```ts
subscribeReorgs(listener: ReorgListener): Promise<string>
```
See also: [ReorgListener](./services.md#type-reorglistener)
Returns
identifier for this subscription
Throws
ERR_NOT_IMPLEMENTED if callback events are not supported
###### Method unsubscribe
Cancels all subscriptions with the given `subscriptionId` which was previously returned
by a `subscribe` method.
```ts
unsubscribe(subscriptionId: string): Promise<boolean>
```
Returns
true if a subscription was canceled
Argument Details
+ **subscriptionId**
+ value previously returned by subscribeToHeaders or subscribeToReorgs
Throws
ERR_NOT_IMPLEMENTED if callback events are not supported
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksFetchApi
Provides a simplified interface based on the
```ts
export interface ChaintracksFetchApi {
httpClient: HttpClient;
download(url: string): Promise<Uint8Array>;
fetchJson<R>(url: string): Promise<R>;
pathJoin(baseUrl: string, subpath: string): string;
}
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksFsApi
Supports file-like access to named data storage.
Only minimal functionality required by Chaintracks is supported.
```ts
export interface ChaintracksFsApi {
delete(path: string): Promise<void>;
writeFile(path: string, data: Uint8Array): Promise<void>;
readFile(path: string): Promise<Uint8Array>;
openReadableFile(path: string): Promise<ChaintracksReadableFileApi>;
openWritableFile(path: string): Promise<ChaintracksWritableFileApi>;
openAppendableFile(path: string): Promise<ChaintracksAppendableFileApi>;
pathJoin(...parts: string[]): string;
}
```
See also: [ChaintracksAppendableFileApi](./services.md#interface-chaintracksappendablefileapi), [ChaintracksReadableFileApi](./services.md#interface-chaintracksreadablefileapi), [ChaintracksWritableFileApi](./services.md#interface-chaintrackswritablefileapi)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksInfoApi
```ts
export interface ChaintracksInfoApi {
chain: Chain;
heightBulk: number;
heightLive: number;
storage: string;
bulkIngestors: string[];
liveIngestors: string[];
packages: ChaintracksPackageInfoApi[];
}
```
See also: [Chain](./client.md#type-chain), [ChaintracksPackageInfoApi](./services.md#interface-chaintrackspackageinfoapi)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksManagementApi
```ts
export interface ChaintracksManagementApi extends ChaintracksApi {
destroy(): Promise<void>;
validate(): Promise<boolean>;
exportBulkHeaders(toFolder: string, toFs: ChaintracksFsApi, sourceUrl?: string, toHeadersPerFile?: number, maxHeight?: number): Promise<void>;
}
```
See also: [ChaintracksApi](./services.md#interface-chaintracksapi), [ChaintracksFsApi](./services.md#interface-chaintracksfsapi)
###### Method destroy
close and release all resources
```ts
destroy(): Promise<void>
```
###### Method exportBulkHeaders
Exports current bulk headers, including all ingests, excluding live headers to static header files.
Useful for bulk ingestors such as those derived from BulkIngestorCDN.
```ts
exportBulkHeaders(toFolder: string, toFs: ChaintracksFsApi, sourceUrl?: string, toHeadersPerFile?: number, maxHeight?: number): Promise<void>
```
See also: [ChaintracksFsApi](./services.md#interface-chaintracksfsapi)
Argument Details
+ **toFolder**
+ Where the json and headers files will be written
+ **toFs**
+ The ChaintracksFsApi to use for writing files. If not provided, the default file system will be used.
+ **sourceUrl**
+ Optional source URL to include in the exported files. Set if exported files will be transferred to a CDN.
+ **toHeadersPerFile**
+ The maximum headers per file. Default is 100,000 (8MB)
+ **maxHeight**
+ The maximum height to export. Default is the current bulk storage max height.
###### Method validate
Verifies that all headers from the tip back to genesis can be retrieved, in order,
by height, and that they obey previousHash constraint.
Additional validations may be addeded.
This is a slow operation.
```ts
validate(): Promise<boolean>
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksOptions
```ts
export interface ChaintracksOptions {
chain: Chain;
storage?: ChaintracksStorageApi;
bulkIngestors: BulkIngestorApi[];
liveIngestors: LiveIngestorApi[];
addLiveRecursionLimit: number;
logging?: (...args: any[]) => void;
readonly: boolean;
}
```
See also: [BulkIngestorApi](./services.md#interface-bulkingestorapi), [Chain](./client.md#type-chain), [ChaintracksStorageApi](./services.md#interface-chaintracksstorageapi), [LiveIngestorApi](./services.md#interface-liveingestorapi)
###### Property addLiveRecursionLimit
Maximum number of missing headers to pursue when listening for new headers.
Normally, large numbers of missing headers are handled by bulk ingestors.
```ts
addLiveRecursionLimit: number
```
###### Property logging
Optional logging method
```ts
logging?: (...args: any[]) => void
```
###### Property readonly
If true, this chaintracks instance will only service read requests for existing data.
Shared storage only requires one readonly false instance to manage and update storage.
```ts
readonly: boolean
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksPackageInfoApi
```ts
export interface ChaintracksPackageInfoApi {
name: string;
version: string;
}
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksReadableFileApi
Supports access to named data storage (file like).
```ts
export interface ChaintracksReadableFileApi {
path: string;
close(): Promise<void>;
getLength(): Promise<number>;
read(length?: number, offset?: number): Promise<Uint8Array>;
}
```
###### Method getLength
Returns the length of the data storage in bytes.
```ts
getLength(): Promise<number>
```
###### Method read
```ts
read(length?: number, offset?: number): Promise<Uint8Array>
```
Argument Details
+ **length**
+ requested length to be returned, may return less than requested.
+ **offset**
+ starting offset in the existing data storage to read from, defaults to 0.
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksServiceClientOptions
```ts
export interface ChaintracksServiceClientOptions {
}
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksServiceOptions
```ts
export interface ChaintracksServiceOptions {
chain: Chain;
routingPrefix: string;
chaintracks?: Chaintracks;
services?: Services;
port?: number;
}
```
See also: [Chain](./client.md#type-chain), [Chaintracks](./services.md#class-chaintracks), [Services](./services.md#class-services)
###### Property chaintracks
Defaults to default configured Chaintracks instance with NoDb storage.
```ts
chaintracks?: Chaintracks
```
See also: [Chaintracks](./services.md#class-chaintracks)
###### Property routingPrefix
prepended to the path of each registered service endpoint
```ts
routingPrefix: string
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageApi
```ts
export interface ChaintracksStorageApi extends ChaintracksStorageQueryApi, ChaintracksStorageIngestApi {
log: (...args: any[]) => void;
bulkManager: BulkFileDataManager;
destroy(): Promise<void>;
}
```
See also: [BulkFileDataManager](./services.md#class-bulkfiledatamanager), [ChaintracksStorageIngestApi](./services.md#interface-chaintracksstorageingestapi), [ChaintracksStorageQueryApi](./services.md#interface-chaintracksstoragequeryapi)
###### Method destroy
Close and release all resources.
```ts
destroy(): Promise<void>
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageBaseOptions
```ts
export interface ChaintracksStorageBaseOptions {
chain: Chain;
liveHeightThreshold: number;
reorgHeightThreshold: number;
bulkMigrationChunkSize: number;
batchInsertLimit: number;
bulkFileDataManager: BulkFileDataManager | undefined;
}
```
See also: [BulkFileDataManager](./services.md#class-bulkfiledatamanager), [Chain](./client.md#type-chain)
###### Property batchInsertLimit
Maximum number of headers per call to batchInsert
```ts
batchInsertLimit: number
```
###### Property bulkFileDataManager
Controls in memory caching and retrieval of missing bulk header data.
```ts
bulkFileDataManager: BulkFileDataManager | undefined
```
See also: [BulkFileDataManager](./services.md#class-bulkfiledatamanager)
###### Property bulkMigrationChunkSize
How many excess "live" headers to accumulate before migrating them as a chunk to the
bulk header storage.
```ts
bulkMigrationChunkSize: number
```
###### Property chain
Which chain is being tracked: main, test, or stn.
```ts
chain: Chain
```
See also: [Chain](./client.md#type-chain)
###### Property liveHeightThreshold
How much of recent history is required to be kept in "live" block header storage.
Headers with height less than active chain tip height minus `liveHeightThreshold`
are not required to be kept in "live" storage and may be migrated to "bulk" storage.
As no forks, orphans, or reorgs can affect "bulk" block header storage, an
aggressively high number is recommended: At least an order of magnitude more than
the deepest actual reorg you can imagine.
```ts
liveHeightThreshold: number
```
###### Property reorgHeightThreshold
How much of recent history must be processed with full validation and reorg support.
Must be less than or equal to `liveHeightThreshold`.
Headers with height older than active chain tip height minus `reorgHeightThreshold`
may use batch processing when ingesting headers.
```ts
reorgHeightThreshold: number
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageBulkFileApi
```ts
export interface ChaintracksStorageBulkFileApi {
insertBulkFile(file: BulkHeaderFileInfo): Promise<number>;
updateBulkFile(fileId: number, file: BulkHeaderFileInfo): Promise<number>;
deleteBulkFile(fileId: number): Promise<number>;
getBulkFiles(): Promise<BulkHeaderFileInfo[]>;
getBulkFileData(fileId: number, offset?: number, length?: number): Promise<Uint8Array | undefined>;
}
```
See also: [BulkHeaderFileInfo](./services.md#interface-bulkheaderfileinfo)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageIdbOptions
```ts
export interface ChaintracksStorageIdbOptions extends ChaintracksStorageBaseOptions {
}
```
See also: [ChaintracksStorageBaseOptions](./services.md#interface-chaintracksstoragebaseoptions)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageIdbSchema
```ts
export interface ChaintracksStorageIdbSchema {
liveHeaders: {
key: number;
value: LiveBlockHeader;
indexes: {
hash: string;
previousHash: string;
previousHeaderId: number | null;
isActive: boolean;
activeTip: [
boolean,
boolean
];
height: number;
};
};
bulkHeaders: {
key: number;
value: BulkHeaderFileInfo;
indexes: {
firstHeight: number;
};
};
}
```
See also: [BulkHeaderFileInfo](./services.md#interface-bulkheaderfileinfo), [LiveBlockHeader](./services.md#interface-liveblockheader)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageIngestApi
```ts
export interface ChaintracksStorageIngestApi {
log: (...args: any[]) => void;
insertHeader(header: BlockHeader, prev?: LiveBlockHeader): Promise<InsertHeaderResult>;
pruneLiveBlockHeaders(activeTipHeight: number): Promise<void>;
migrateLiveToBulk(count: number): Promise<void>;
deleteOlderLiveBlockHeaders(maxHeight: number): Promise<number>;
makeAvailable(): Promise<void>;
migrateLatest(): Promise<void>;
dropAllData(): Promise<void>;
destroy(): Promise<void>;
}
```
See also: [BlockHeader](./client.md#interface-blockheader), [InsertHeaderResult](./services.md#type-insertheaderresult), [LiveBlockHeader](./services.md#interface-liveblockheader)
###### Method deleteOlderLiveBlockHeaders
Delete live headers with height less or equal to `maxHeight`
after they have been migrated to bulk storage.
```ts
deleteOlderLiveBlockHeaders(maxHeight: number): Promise<number>
```
Argument Details
+ **maxHeight**
+ delete all records with less or equal `height`
###### Method destroy
Release all resources. Makes the instance unusable.
```ts
destroy(): Promise<void>
```
###### Method insertHeader
Attempts to insert a block header into the chain.
Returns 'added' false and 'dupe' true if header's hash already exists in the live database
Returns 'added' false and 'dupe' false if header's previousHash wasn't found in the live database, or height doesn't increment previous' height.
Computes the header's chainWork from its bits and the previous header's chainWork.
Returns 'added' true if the header was added to the live database.
Returns 'isActiveTip' true if header's chainWork is greater than current active chain tip's chainWork.
If the addition of this header caused a reorg (did not directly extend old active chain tip):
Returns 'reorgDepth' the minimum height difference of the common ancestor to the two chain tips.
Returns 'priorTip' the old active chain tip.
If not a reorg:
Returns 'reorgDepth' of zero.
Returns 'priorTip' the active chain tip before this insert. May be unchanged.
Implementation must call `pruneLiveBlockHeaders` after adding new header.
```ts
insertHeader(header: BlockHeader, prev?: LiveBlockHeader): Promise<InsertHeaderResult>
```
See also: [BlockHeader](./client.md#interface-blockheader), [InsertHeaderResult](./services.md#type-insertheaderresult), [LiveBlockHeader](./services.md#interface-liveblockheader)
Argument Details
+ **header**
+ to insert
+ **prev**
+ if not undefined, the last bulk storage header with total bulk chainWork
###### Method makeAvailable
Async initialization method.
May be called prior to other async methods to control when initialization occurs.
```ts
makeAvailable(): Promise<void>
```
###### Method migrateLatest
Migrate storage schema to latest schema changes.
Typically invoked automatically by `makeAvailable`.
```ts
migrateLatest(): Promise<void>
```
###### Method migrateLiveToBulk
Migrates the oldest `count` LiveBlockHeaders to BulkStorage.
BulkStorage must be configured.
`count` must not exceed `bulkMigrationChunkSize`.
`count` must leave at least `liveHeightThreshold` LiveBlockHeaders.
```ts
migrateLiveToBulk(count: number): Promise<void>
```
Argument Details
+ **count**
+ Steps:
- Copy count oldest active LiveBlockHeaders from live database to buffer.
- Append the buffer of headers to BulkStorage
- Add the buffer's BlockHash, Height pairs to corresponding index table.
- Add the buffer's MerkleRoot, Height pairs to corresponding index table.
- Delete the records from the live database.
###### Method pruneLiveBlockHeaders
Must be called after the addition of new LiveBlockHeaders.
Checks the `StorageEngine` configuration options to see
if BulkStorage is configured and if there is at least one
`bulkMigrationChunkSize` woth of headers in excess of
`liveHeightThreshold` available.
If yes, then calls `migrateLiveToBulk` one or more times.
```ts
pruneLiveBlockHeaders(activeTipHeight: number): Promise<void>
```
Argument Details
+ **activeTipHeight**
+ height of active tip after adds
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageKnexOptions
```ts
export interface ChaintracksStorageKnexOptions extends ChaintracksStorageBaseOptions {
knex: Knex | undefined;
}
```
See also: [ChaintracksStorageBaseOptions](./services.md#interface-chaintracksstoragebaseoptions)
###### Property knex
Required.
Knex.js database interface initialized with valid connection configuration.
```ts
knex: Knex | undefined
```
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageMemoryOptions
```ts
export interface ChaintracksStorageMemoryOptions extends ChaintracksStorageKnexOptions {
sqliteClient: "sqlite3" | "better-sqlite3" | undefined;
}
```
See also: [ChaintracksStorageKnexOptions](./services.md#interface-chaintracksstorageknexoptions)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageNoDbOptions
```ts
export interface ChaintracksStorageNoDbOptions extends ChaintracksStorageBaseOptions {
}
```
See also: [ChaintracksStorageBaseOptions](./services.md#interface-chaintracksstoragebaseoptions)
Links: [API](#api), [Interfaces](#interfaces), [Classes](#classes), [Functions](#functions), [Types](#types), [Variables](#variables)
---
##### Interface: ChaintracksStorageQueryApi
```ts
export interface ChaintracksStorageQueryApi {
log: (...args: any[]) => void;
findChainTipHeader(): Promise<LiveBlockHeader>;
findChainTipHash(): Promise<string>;
findChainTipHeaderOrUndefined(): Promise<LiveBlockHeader | undefined>;
findChainTipWork(): Promise<string>;
findHeaderForHeight(height: number): Promise<LiveBlockHeader | BlockHeader>;
findHeaderForHeightOrUndefined(height: number): Promise<LiveBlockHeader | BlockHeader | undefined>;
findCommonAncestor(header1: LiveBlockHeader, header2: LiveBlockHeader): Promise<LiveBlockHeader>;
findReorgDepth(header1: LiveBlockHeader, header2: LiveBlockHeader): Promise<number>;
isMerkleRootActive(merkleRoot: string): Promise<boolean>;
getHeadersUint8Array(height: number, count: number): Promise<Uint8Array>;
getHeaders(height: number, count: number): Promise<BaseBlockHeader[]>;
getLiveHeaders(range: HeightRange): Promise<LiveBlockHeader[]>;
getBulkHeaders(range: HeightRange): Promise<Uint8Array>;
findLiveHeaderForHeight(height: number): Promise<LiveBlockHeader | null>;
findLiveHeaderForHeaderId(headerId: number): Promise<LiveBlockHeader>;
findLiveHeaderForBlockHash(hash: string): Promise<LiveBlockHeader | null>;
findLiveHeaderForMerkleRoot(merkleRoot: string): Promise<LiveBlockHeader | null>;