UNPKG

@bsv/wallet-toolbox-mobile

Version:

React Native and mobile-safe BRC-100 wallet, signer, and remote storage components

1,439 lines 432 kB
import { AbortActionArgs, AbortActionResult, AcquireCertificateArgs, AcquireCertificateResult, AtomicBEEF, AuthFetch, AuthenticatedResult, BEEF, Base64String, Beef, BeefParty, BigNumber, ChainTracker, CreateActionArgs, CreateActionResult, CreateHmacArgs, CreateHmacResult, CreateSignatureArgs, CreateSignatureResult, DescriptionString5to50Bytes, DiscoverByAttributesArgs, DiscoverByIdentityKeyArgs, DiscoverCertificatesResult, ErrorCodeString10To40Bytes, ErrorDescriptionString20To200Bytes, GetHeaderArgs, GetHeaderResult, GetHeightResult, GetNetworkResult, GetPublicKeyArgs, GetPublicKeyResult, GetVersionResult, HexString, HttpClient, InternalizeActionArgs, InternalizeActionResult, KeyDeriverApi, ListActionsArgs, ListActionsResult, ListCertificatesArgs, ListCertificatesResult, ListOutputsArgs, ListOutputsResult, LocalKVStore, LockingScript, LookupResolver, MakeWalletLogger, MerklePath, OriginatorDomainNameStringUnder250Bytes, OutpointString, P2PKH, PeerSession, PrivateKey, ProtoWallet, ProveCertificateArgs, ProveCertificateResult, PubKeyHex, PublicKey, RelinquishCertificateArgs, RelinquishCertificateResult, RelinquishOutputArgs, RelinquishOutputResult, RevealCounterpartyKeyLinkageArgs, RevealCounterpartyKeyLinkageResult, RevealSpecificKeyLinkageArgs, RevealSpecificKeyLinkageResult, SHIPBroadcaster, Script, ScriptTemplate, ScriptTemplateUnlock, SendWithResult, SignActionArgs, SignActionResult, SpendVerifierInterface, TXIDHexString, Telemetry, TelemetryConfig, TelemetrySpan, Transaction, TransactionInput, TrustSelf, UnlockingScript, Validation, Validation as Validation$1, VerifyHmacArgs, VerifyHmacResult, VerifySignatureArgs, VerifySignatureResult, WalletDecryptArgs, WalletDecryptResult, WalletEncryptArgs, WalletEncryptResult, WalletErrorObject, WalletInterface, WalletLoggerInterface, WalletLoggerLog, WalletNetwork, WalletProtocol, WhatsOnChainConfig } from "@bsv/sdk"; import { IDBPDatabase, IDBPTransaction } from "idb"; //#region ../src/sdk/WalletError.d.ts /** * Derived class constructors should use the derived class name as the value for `name`, * and an internationalizable constant string for `message`. * * If a derived class intends to wrap another WalletError, the public property should * be named `walletError` and will be recovered by `fromUnknown`. * * Optionaly, the derived class `message` can include template parameters passed in * to the constructor. See WERR_MISSING_PARAMETER for an example. * * To avoid derived class name colisions, packages should include a package specific * identifier after the 'WERR_' prefix. e.g. 'WERR_FOO_' as the prefix for Foo package error * classes. */ declare class WalletError extends Error implements WalletErrorObject { details?: Record<string, string> | undefined; isError: true; constructor(name: string, message: string, stack?: string, details?: Record<string, string> | undefined); /** * Error class compatible accessor for `code`. */ get code(): ErrorCodeString10To40Bytes; set code(v: ErrorCodeString10To40Bytes); /** * Error class compatible accessor for `description`. */ get description(): ErrorDescriptionString20To200Bytes; set description(v: ErrorDescriptionString20To200Bytes); /** * Recovers all public fields from WalletError derived error classes and relevant Error derived errors. * */ private static nonEmptyString; private static objectErrorFields; private static copyPublicErrorFields; static fromUnknown(err: unknown): WalletError; /** * @returns standard HTTP error status object with status property set to 'error'. */ asStatus(): { status: string; code: string; description: string; }; /** * Base class default JSON serialization. * Captures just the name and message properties. * * Override this method to safely (avoid deep, large, circular issues) serialize * derived class properties. * * @returns stringified JSON representation of the WalletError. */ protected toJson(): string; /** * Safely serializes a WalletError derived, WERR_REVIEW_ACTIONS (special case), Error or unknown error to JSON. * * Safely means avoiding deep, large, circular issues. * * @param error * @returns stringified JSON representation of the error such that it can be desirialized to a WalletError. */ static unknownToJson(error: unknown): string; } //#endregion //#region ../src/sdk/WalletErrorFromJson.d.ts /** * Reconstruct the correct derived WalletError from a JSON object created by `WalletError.unknownToJson`. * * This function is implemented as a separate function instead of a WalletError class static * to avoid circular dependencies. * * @param json * @returns a WalletError derived error object, typically for re-throw. */ declare function WalletErrorFromJson(json: object): WalletError; //#endregion //#region ../src/sdk/types.d.ts /** * Identifies a unique transaction output by its `txid` and index `vout` */ interface OutPoint { /** * Transaction double sha256 hash as big endian hex string */ txid: string; /** * zero based output index within the transaction */ vout: number; } type Chain = 'main' | 'test' | 'stn' | 'ttn' | 'tstn' | 'mock'; /** * Initial status (attempts === 0): * * nosend: transaction was marked 'noSend'. It is complete and signed. It may be sent by an external party. Proof should be sought as if 'unmined'. No error if it remains unknown by network. * * unprocessed: indicates req is about to be posted to network by non-acceptDelayedBroadcast application code, after posting status is normally advanced to 'sending' * * unsent: rawTx has not yet been sent to the network for processing. req is queued for delayed processing. * * sending: At least one attempt to send rawTx to transaction processors has occured without confirmation of acceptance. * * unknown: rawTx status is unknown but is believed to have been previously sent to the network. * * Attempts > 0 status, processing: * * unknown: Last status update received did not recognize txid or wasn't understood. * * nonfinal: rawTx has an un-expired nLockTime and is eligible for continuous updating by new transactions with additional outputs and incrementing sequence numbers. * * unmined: Last attempt has txid waiting to be mined, possibly just sent without callback * * callback: Waiting for proof confirmation callback from transaction processor. * * unconfirmed: Potential proof has not been confirmed by chaintracks * * Terminal status: * * doubleSpend: Transaction spends same input as another transaction. * * invalid: rawTx is structuraly invalid or was rejected by the network. Will never be re-attempted or completed. * * completed: proven_txs record added, and notifications are complete. * * unfail: asigned to force review of a currently invalid ProvenTxReq. */ type ProvenTxReqStatus = 'sending' | 'unsent' | 'nosend' | 'unknown' | 'nonfinal' | 'unprocessed' | 'unmined' | 'callback' | 'unconfirmed' | 'completed' | 'invalid' | 'doubleSpend' | 'unfail'; declare const ProvenTxReqTerminalStatus: ProvenTxReqStatus[]; declare const ProvenTxReqNonTerminalStatus: ProvenTxReqStatus[]; type TransactionStatus = 'completed' | 'failed' | 'unprocessed' | 'sending' | 'unproven' | 'unsigned' | 'nosend' | 'nonfinal' | 'unfail'; interface Paged { limit: number; offset?: number; } interface KeyPair { privateKey: string; publicKey: string; } interface StorageIdentity { /** * The identity key (public key) assigned to this storage */ storageIdentityKey: string; /** * The human readable name assigned to this storage. */ storageName: string; } interface EntityTimeStamp { created_at: Date; updated_at: Date; } interface ScriptTemplateUnlock$1 { sign: (tx: Transaction, inputIndex: number) => Promise<UnlockingScript>; estimateLength: (tx: Transaction, inputIndex: number) => Promise<number>; } interface WalletBalance { total: number; utxos: Array<{ satoshis: number; outpoint: string; }>; } interface ReqHistoryNote { when?: string; what: string; [key: string]: boolean | string | number | undefined; } /** * The transaction status that a client will receive when subscribing to transaction updates in the Monitor. */ interface ProvenTransactionStatus { txid: string; txIndex: number; blockHeight: number; blockHash: string; merklePath: number[]; merkleRoot: string; } /** * `listOutputs` special operation basket name value. * * Returns wallet's current change balance in the `totalOutputs` result property. * The `outputs` result property will always be an empty array. */ declare const specOpWalletBalance = "893b7646de0e1c9f741bd6e9169b76a8847ae34adef7bef1e6a285371206d2e8"; /** * `listOutputs` special operation basket name value. * * Lists only spendable wallet-managed BRC-29 change from the `default` * basket. Raw administrative `listOutputs({ basket: 'default' })` remains * intentionally unfiltered so legacy incompatible rows stay discoverable * for recovery instead of being hidden or silently mutated. */ declare const specOpWalletManagedUtxos = "284570a6213a74ba861c38b1cf790e1e400d9cf9324454b76ea98860b6031c1a"; /** * `listOutputs` special operation basket name value. * * Returns currently spendable wallet change outputs that fail to validate as unspent transaction outputs. * * Optional tag value 'release'. If present, updates invalid change outputs to not spendable. * * Optional tag value 'all'. If present, processes all spendable true outputs, independent of baskets, but basket must be defined. */ declare const specOpInvalidChange = "5a76fd430a311f8bc0553859061710a4475c19fed46e2ff95969aa918e612e57"; /** * `listOutputs` special operation basket name value. * * Updates the wallet's automatic change management parameters. * * Tag at index 0 is the new desired number of spendable change outputs to maintain. * * Tag at index 1 is the new target for minimum satoshis when creating new change outputs. */ declare const specOpSetWalletChangeParams = "a4979d28ced8581e9c1c92f1001cc7cb3aabf8ea32e10888ad898f0a509a3929"; /** * @param basket Output basket name value. * @returns true iff the `basket` name is a reserved `listOutputs` special operation identifier. */ declare function isListOutputsSpecOp(basket: string): boolean; /** * `listActions` special operation label name value. * * Processes only actions currently with status 'nosend' * * Optional label value 'abort'. If present, runs abortAction on all the actions returned. */ declare const specOpNoSendActions = "ac6b20a3bb320adafecd637b25c84b792ad828d3aa510d05dc841481f664277d"; /** * `listActions` special operation label name value. * * Processes only actions currently with status 'failed' * * Optional label value 'unfail'. If present, sets status to 'unfail', which queues them for attempted recovery by the Monitor. */ declare const specOpFailedActions = "97d4eb1e49215e3374cc2c1939a7c43a55e95c7427bf2d45ed63e3b4e0c88153"; /** * @param label Action / Transaction label name value. * @returns true iff the `label` name is a reserved `listActions` special operation identifier. */ declare function isListActionsSpecOp(label: string): boolean; /** * `createAction` special operation label name value. * * Causes WERR_REVIEW_ACTIONS throw with dummy properties. * */ declare const specOpThrowReviewActions = "a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a"; /** * @param label Action / Transaction label name value. * @returns true iff the `label` name is a reserved `createAction` special operation identifier. */ declare function isCreateActionSpecOp(label: string): boolean; //#endregion //#region ../src/sdk/WalletSigner.interfaces.d.ts /** */ interface WalletSigner$1 { isWalletSigner: true; chain: Chain; keyDeriver: KeyDeriverApi; } //#endregion //#region ../src/storage/schema/tables/TableSettings.d.ts interface TableSettings extends StorageIdentity, EntityTimeStamp { created_at: Date; updated_at: Date; /** * The identity key (public key) assigned to this storage */ storageIdentityKey: string; /** * The human readable name assigned to this storage. */ storageName: string; chain: Chain; dbtype: 'SQLite' | 'MySQL' | 'IndexedDB'; maxOutputScript: number; } //#endregion //#region ../src/storage/schema/tables/TableProvenTx.d.ts interface TableProvenTx extends EntityTimeStamp { created_at: Date; updated_at: Date; provenTxId: number; txid: string; height: number; index: number; merklePath: number[]; rawTx: number[]; blockHash: string; merkleRoot: string; } //#endregion //#region ../src/storage/schema/tables/TableProvenTxReq.d.ts interface TableProvenTxReq extends TableProvenTxReqDynamics { created_at: Date; updated_at: Date; provenTxReqId: number; provenTxId?: number; status: ProvenTxReqStatus; /** * Count of how many times a service has been asked about this txid */ attempts: number; /** * Set to true when a terminal status has been set and notification has occurred. */ notified: boolean; txid: string; /** * If valid, a unique string identifying a batch of transactions to be sent together for processing. */ batch?: string; /** * JSON string of processing history. * Parses to `ProvenTxReqHistoryApi`. */ history: string; /** * JSON string of data to drive notifications when this request completes. * Parses to `ProvenTxReqNotifyApi`. */ notify: string; rawTx: number[]; inputBEEF?: number[]; /** * Set to true the first time this req transitions to 'unmined' or 'callback' status, * indicating the transaction was successfully broadcast to the network. * Used to distinguish rebroadcast candidates from transactions that were never sent. * Defaults to false (added by migration 2026-04-30-001). */ wasBroadcast?: boolean; /** * Count of how many times this req has been reset to 'unsent' for rebroadcast * after proof check timeout. Used by the circuit-breaker (maxRebroadcastAttempts). * Defaults to 0 (added by migration 2026-04-30-001). */ rebroadcastAttempts?: number; } /** * Table properties that may change after initial record insertion. */ interface TableProvenTxReqDynamics extends EntityTimeStamp { updated_at: Date; provenTxId?: number; status: ProvenTxReqStatus; /** * Count of how many times a service has been asked about this txid */ attempts: number; /** * Set to true when a terminal status has been set and notification has occurred. */ notified: boolean; /** * If valid, a unique string identifying a batch of transactions to be sent together for processing. */ batch?: string; /** * JSON string of processing history. * Parses to `ProvenTxReqHistoryApi`. */ history: string; /** * JSON string of data to drive notifications when this request completes. * Parses to `ProvenTxReqNotifyApi`. */ notify: string; /** * Set to true the first time this req transitions to 'unmined' or 'callback' status. * Defaults to false (added by migration 2026-04-30-001). */ wasBroadcast?: boolean; /** * Count of rebroadcast cycles for this req. Used by the circuit-breaker. * Defaults to 0 (added by migration 2026-04-30-001). */ rebroadcastAttempts?: number; } //#endregion //#region ../src/storage/schema/tables/TableUser.d.ts interface TableUser extends EntityTimeStamp { created_at: Date; updated_at: Date; userId: number; /** * PubKeyHex uniquely identifying user. * Typically 66 hex digits. */ identityKey: string; /** * The storageIdentityKey value of the active wallet storage. */ activeStorage: string; } //#endregion //#region ../src/storage/schema/tables/TableCertificateField.d.ts interface TableCertificateField extends EntityTimeStamp { created_at: Date; updated_at: Date; userId: number; certificateId: number; fieldName: string; fieldValue: string; masterKey: Base64String; } //#endregion //#region ../src/storage/schema/tables/TableCertificate.d.ts interface TableCertificate extends EntityTimeStamp { created_at: Date; updated_at: Date; certificateId: number; userId: number; type: Base64String; serialNumber: Base64String; certifier: PubKeyHex; subject: PubKeyHex; verifier?: PubKeyHex; revocationOutpoint: OutpointString; signature: HexString; isDeleted: boolean; } interface TableCertificateX extends TableCertificate { fields?: TableCertificateField[]; } //#endregion //#region ../src/storage/schema/tables/TableOutputBasket.d.ts interface TableOutputBasket extends EntityTimeStamp { created_at: Date; updated_at: Date; basketId: number; userId: number; name: string; numberOfDesiredUTXOs: number; minimumDesiredUTXOValue: number; isDeleted: boolean; } //#endregion //#region ../src/storage/schema/tables/TableTransaction.d.ts interface TableTransaction extends EntityTimeStamp { created_at: Date; updated_at: Date; transactionId: number; userId: number; provenTxId?: number; status: TransactionStatus; /** * max length of 64, hex encoded */ reference: Base64String; /** * true if transaction originated in this wallet, change returns to it. * false for a transaction created externally and handed in to this wallet. */ isOutgoing: boolean; satoshis: number; description: string; /** * If not undefined, must match value in associated rawTransaction. */ version?: number; /** * Optional. Default is zero. * When the transaction can be processed into a block: * >= 500,000,000 values are interpreted as minimum required unix time stamps in seconds * < 500,000,000 values are interpreted as minimum required block height */ lockTime?: number; txid?: string; inputBEEF?: number[]; rawTx?: number[]; } declare const transactionColumnsWithoutRawTx: string[]; //#endregion //#region ../src/storage/schema/tables/TableCommission.d.ts interface TableCommission extends EntityTimeStamp { created_at: Date; updated_at: Date; commissionId: number; userId: number; transactionId: number; satoshis: number; keyOffset: string; isRedeemed: boolean; lockingScript: number[]; } //#endregion //#region ../src/storage/schema/tables/TableOutputTag.d.ts interface TableOutputTag extends EntityTimeStamp { created_at: Date; updated_at: Date; outputTagId: number; userId: number; tag: string; isDeleted: boolean; } //#endregion //#region ../src/storage/schema/tables/TableOutput.d.ts interface TableOutput extends EntityTimeStamp { created_at: Date; updated_at: Date; outputId: number; userId: number; transactionId: number; basketId?: number; spendable: boolean; change: boolean; outputDescription: DescriptionString5to50Bytes; vout: number; satoshis: number; providedBy: StorageProvidedBy; purpose: string; type: string; txid?: string; senderIdentityKey?: PubKeyHex; derivationPrefix?: Base64String; derivationSuffix?: Base64String; customInstructions?: string; spentBy?: number; sequenceNumber?: number; spendingDescription?: string; scriptLength?: number; scriptOffset?: number; lockingScript?: number[]; } interface TableOutputX extends TableOutput { basket?: TableOutputBasket; tags?: TableOutputTag[]; } declare const outputColumnsWithoutLockingScript: string[]; //#endregion //#region ../src/storage/schema/tables/TableOutputTagMap.d.ts interface TableOutputTagMap extends EntityTimeStamp { created_at: Date; updated_at: Date; outputTagId: number; outputId: number; isDeleted: boolean; } //#endregion //#region ../src/storage/schema/tables/TableTxLabel.d.ts interface TableTxLabel extends EntityTimeStamp { created_at: Date; updated_at: Date; txLabelId: number; userId: number; label: string; isDeleted: boolean; } //#endregion //#region ../src/storage/schema/tables/TableTxLabelMap.d.ts interface TableTxLabelMap extends EntityTimeStamp { created_at: Date; updated_at: Date; txLabelId: number; transactionId: number; isDeleted: boolean; } //#endregion //#region ../src/storage/schema/tables/TableMonitorEvent.d.ts interface TableMonitorEvent extends EntityTimeStamp { created_at: Date; updated_at: Date; id: number; event: string; details?: string; } //#endregion //#region ../src/storage/schema/tables/TableSyncState.d.ts interface TableSyncState extends EntityTimeStamp { created_at: Date; updated_at: Date; syncStateId: number; userId: number; storageIdentityKey: string; storageName: string; status: SyncStatus; init: boolean; refNum: string; syncMap: string; when?: Date; satoshis?: number; errorLocal?: string; errorOther?: string; } //#endregion //#region ../src/storage/schema/tables/TableActionBatch.d.ts type ActionBatchStatus = 'active' | 'prepared' | 'committed' | 'aborted' | 'expired'; interface TableActionBatch extends EntityTimeStamp { actionBatchId: number; userId: number; batchId: string; status: ActionBatchStatus; expiresAt: Date; hardExpiresAt: Date; manifestDigest?: string; /** JSON-encoded format-2 manifest retained between prepare and commit. */ manifest?: string; uploadDigests?: string; result?: string; } interface TableActionBatchOutput extends EntityTimeStamp { actionBatchId: number; outputId: number; } interface TableActionBatchBlob extends EntityTimeStamp { actionBatchBlobId: number; actionBatchId: number; digest: string; bytes: number[] | Uint8Array; } //#endregion //#region ../src/storage/schema/tables/TableAuthSession.d.ts /** * Durable representation of a BRC-103 peer session. * * The session nonce is the authoritative key. `lastUpdate` also acts as the * optimistic-write version so a delayed request from one replica cannot * overwrite newer authentication state written by another replica. */ interface TableAuthSession { sessionNonce: string; peerNonce?: string | null; peerIdentityKey?: string | null; isAuthenticated: boolean | number; lastUpdate: number | string; certificatesRequired?: boolean | number | null; certificatesValidated?: boolean | number | null; expiresAt: number | string; } declare function tableAuthSessionToPeerSession(row: TableAuthSession): PeerSession; //#endregion //#region ../src/services/providers/ARC.d.ts /** Configuration options for the ARC broadcaster. */ interface ArcConfig { /** Authentication token for the ARC API */ apiKey?: string; /** The HTTP client used to make requests to the ARC API. */ httpClient?: HttpClient; /** Deployment id used annotating api calls in XDeployment-ID header - this value will be randomly generated if not set */ deploymentId?: string; /** notification callback endpoint for proofs and double spend notification */ callbackUrl?: string; /** default access token for notification callback endpoint. It will be used as a Authorization header for the http callback */ callbackToken?: string; /** additional headers to be attached to all tx submissions. */ headers?: Record<string, string>; } /** * Represents an ARC transaction broadcaster. */ declare class ARC { readonly name: string; readonly URL: string; readonly apiKey: string | undefined; readonly deploymentId: string; readonly callbackUrl: string | undefined; readonly callbackToken: string | undefined; readonly headers: Record<string, string> | undefined; private readonly httpClient; /** * Constructs an instance of the ARC broadcaster. * * @param {string} URL - The URL endpoint for the ARC API. * @param {ArcConfig} config - Configuration options for the ARC broadcaster. */ constructor(URL: string, config?: ArcConfig, name?: string); /** * Constructs an instance of the ARC broadcaster. * * @param {string} URL - The URL endpoint for the ARC API. * @param {string} apiKey - The API key used for authorization with the ARC API. */ constructor(URL: string, apiKey?: string, name?: string); /** * Constructs a dictionary of the default & supplied request headers. */ private requestHeaders; private applySuccessfulPostRawTx; private applyFailedPostRawTx; private applyPostRawTxResponse; private applyPostRawTxCatch; /** * The ARC '/v1/tx' endpoint, as of 2025-02-17 supports all of the following hex string formats: * 1. Single serialized raw transaction. * 2. Single EF serialized raw transaction (untested). * 3. V1 serialized Beef (results returned reflect only the last transaction in the beef) * * The ARC '/v1/tx' endpoint, as of 2025-02-17 DOES NOT support the following hex string formats: * 1. V2 serialized Beef * * @param rawTx * @param txids * @returns */ postRawTx(rawTx: HexString, txids?: string[]): Promise<PostTxResultForTxid>; /** * ARC does not natively support a postBeef end-point aware of multiple txids of interest in the Beef. * * It does process multiple new transactions, however, which allows results for all txids of interest * to be collected by the `/v1/tx/${txid}` endpoint. * * @param beef * @param txids * @returns */ postBeef(beef: Beef, txids: string[]): Promise<PostBeefResult>; /** * This seems to only work for recently submitted txids...but that's all we need to complete postBeef! * @param txid * @returns */ getTxData(txid: string): Promise<ArcMinerGetTxData>; } interface ArcMinerGetTxData { status: number; title: string; blockHash: string; blockHeight: number; competingTxs: null | string[]; extraInfo: string; merklePath: string; timestamp: string; txid: string; txStatus: string; } //#endregion //#region ../src/services/chaintracker/chaintracks/Api/BlockHeaderApi.d.ts /** * The "live" portion of the block chain is recent history that can conceivably be subject to reorganizations. * The additional fields support tracking orphan blocks, chain forks, and chain reorgs. */ interface LiveBlockHeader extends BlockHeader { /** * The cumulative chainwork achieved by the addition of this block to the chain. * Chainwork only matters in selecting the active chain. */ chainWork: string; /** * True only if this header is currently a chain tip. e.g. There is no header that follows it by previousHash or previousHeaderId. */ isChainTip: boolean; /** * True only if this header is currently on the active chain. */ isActive: boolean; /** * As there may be more than one header with identical height values due to orphan tracking, * headers are assigned a unique headerId while part of the "live" portion of the block chain. */ headerId: number; /** * Every header in the "live" portion of the block chain is linked to an ancestor header through * both its previousHash and previousHeaderId properties. * * Due to forks, there may be multiple headers with identical `previousHash` and `previousHeaderId` values. * Of these, only one (the header on the active chain) will have `isActive` === true. */ previousHeaderId: number | null; } /** * Type guard function. * @publicbody */ declare function isLive(header: BlockHeader | LiveBlockHeader): header is LiveBlockHeader; /** Union of all block header variants */ type AnyBlockHeader = BaseBlockHeader | BlockHeader | LiveBlockHeader; /** * Type guard function. * @publicbody */ declare function isBaseBlockHeader(header: AnyBlockHeader): header is BaseBlockHeader; /** * Type guard function. * @publicbody */ declare function isBlockHeader(header: AnyBlockHeader): header is BlockHeader; /** * Type guard function. * @publicbody */ declare function isLiveBlockHeader(header: AnyBlockHeader): header is LiveBlockHeader; //#endregion //#region ../src/services/chaintracker/chaintracks/Api/ChaintracksClientApi.d.ts /** * @public */ type HeaderListener = (header: BlockHeader) => void; /** * @public */ type ReorgListener = (depth: number, oldTip: BlockHeader, newTip: BlockHeader, deactivatedHeaders?: BlockHeader[]) => void; /** * @public */ interface ChaintracksPackageInfoApi { name: string; version: string; } /** * @public */ interface ChaintracksInfoApi { chain: Chain; heightBulk: number; heightLive: number; storage: string; bulkIngestors: string[]; liveIngestors: string[]; packages: ChaintracksPackageInfoApi[]; /** Last observed source state. Additive and omitted by older services. */ sources?: ChaintracksSourceStatusApi[]; } /** @public */ interface ChaintracksSourceStatusApi { name: string; role: 'bulk' | 'live'; state: 'unknown' | 'healthy' | 'degraded'; lastSuccess?: string; lastFailure?: string; error?: string; } /** * Chaintracks client API excluding events and callbacks * @public */ interface ChaintracksClientApi extends ChainTracker { /** * Confirms the chain */ getChain(): Promise<Chain>; /** * @returns Summary of configuration and state. */ getInfo(): Promise<ChaintracksInfoApi>; /** * Return the latest chain height from configured bulk ingestors. */ getPresentHeight(): Promise<number>; /** * Adds headers in 80 byte serialized format to an array. * Only adds active headers. * array length divided by 80 is the actual number returned. * * @param height of first header * @param count of headers, maximum * @returns array of headers as serialized hex string */ getHeaders(height: number, count: number): Promise<string>; /** * Returns the active chain tip header */ findChainTipHeader(): Promise<BlockHeader>; /** * Returns the block hash of the active chain tip. */ findChainTipHash(): Promise<string>; /** * Returns block header for a given block height on active chain. */ findHeaderForHeight(height: number): Promise<BlockHeader | undefined>; /** * Returns block header for a given recent block hash or undefined. * @param hash */ findHeaderForBlockHash(hash: string): Promise<BlockHeader | undefined>; /** * 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. * * @param header * @returns immediately */ addHeader(header: BaseBlockHeader): Promise<void>; /** * 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. */ startListening(): Promise<void>; /** * Returns a Promise that will resolve when the previous call to startListening * enters the listening-for-new-headers state. */ listening(): Promise<void>; /** * Returns true if actively listening for new headers and client api is enabled. */ isListening(): Promise<boolean>; /** * Returns true if `synchronize` has completed at least once. */ isSynchronized(): Promise<boolean>; /** * Subscribe to "header" events. * @param listener * @returns identifier for this subscription * @throws ERR_NOT_IMPLEMENTED if callback events are not supported */ subscribeHeaders(listener: HeaderListener): Promise<string>; /** * Subscribe to "reorganization" events. * @param listener * @returns identifier for this subscription * @throws ERR_NOT_IMPLEMENTED if callback events are not supported */ subscribeReorgs(listener: ReorgListener): Promise<string>; /** * Cancels all subscriptions with the given `subscriptionId` which was previously returned * by a `subscribe` method. * @param subscriptionId value previously returned by subscribeToHeaders or subscribeToReorgs * @returns true if a subscription was canceled * @throws ERR_NOT_IMPLEMENTED if callback events are not supported */ unsubscribe(subscriptionId: string): Promise<boolean>; isValidRootForHeight(root: string, height: number): Promise<boolean>; currentHeight: () => Promise<number>; } /** * Full Chaintracks API including startListening with callbacks */ interface ChaintracksApi extends ChaintracksClientApi { /** * 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. * * @param listening callback indicates when listening for new headers has started. */ startListening(listening?: () => void): Promise<void>; } //#endregion //#region ../src/sdk/WalletServices.interfaces.d.ts /** * Defines standard interfaces to access functionality implemented by external transaction processing services. */ interface WalletServices { /** * The chain being serviced. */ chain: Chain; /** * @returns standard `ChainTracker` service which requires `options.chaintracks` be valid. */ getChainTracker: () => Promise<ChainTracker>; /** * @returns serialized block header for height on active chain * @param height */ getHeaderForHeight: (height: number) => Promise<number[]>; /** * @returns the height of the active chain */ getHeight: () => Promise<number>; /** * Approximate exchange rate US Dollar / BSV, USD / BSV * * This is the US Dollar price of one BSV */ getBsvExchangeRate: () => Promise<number>; /** * Approximate exchange rate currency per base. */ getFiatExchangeRate: (currency: FiatCurrencyCode, base?: FiatCurrencyCode) => Promise<number>; /** * Attempts to obtain the raw transaction bytes associated with a 32 byte transaction hash (txid). * * Cycles through configured transaction processing services attempting to get a valid response. * * On success: * Result txid is the requested transaction hash * Result rawTx will be an array containing raw transaction bytes. * Result name will be the responding service's identifying name. * Returns result without incrementing active service. * * On failure: * Result txid is the requested transaction hash * Result mapi will be the first mapi response obtained (service name and response), or null * Result error will be the first error thrown (service name and CwiError), or null * Increments to next configured service and tries again until all services have been tried. * * @param txid transaction hash for which raw transaction bytes are requested * @param useNext optional, forces skip to next service before starting service requests cycle. */ getRawTx: (txid: string, useNext?: boolean) => Promise<GetRawTxResult>; /** * Attempts to obtain the merkle proof associated with a 32 byte transaction hash (txid). * * Cycles through configured transaction processing services attempting to get a valid response. * * On success: * Result txid is the requested transaction hash * Result proof will be the merkle proof. * Result name will be the responding service's identifying name. * Returns result without incrementing active service. * * On failure: * Result txid is the requested transaction hash * Result mapi will be the first mapi response obtained (service name and response), or null * Result error will be the first error thrown (service name and CwiError), or null * Increments to next configured service and tries again until all services have been tried. * * @param txid transaction hash for which proof is requested * @param useNext optional, forces skip to next service before starting service requests cycle. */ getMerklePath: (txid: string, useNext?: boolean) => Promise<GetMerklePathResult>; /** * * @param beef * @param txids * @param chain * @returns */ postBeef: (beef: Beef, txids: string[], logger?: WalletLoggerInterface) => Promise<PostBeefResult[]>; /** * @param script Output script to be hashed for `getUtxoStatus` default `outputFormat` * @returns script hash in 'hashLE' format, which is the default. */ hashOutputScript: (script: string) => string; /** * For an array of one or more txids, returns for each wether it is a 'known', 'mined', or 'unknown' transaction. * * Primarily useful for determining if a recently broadcast transaction is known to the processing network. * * Also returns the current depth from chain tip if 'mined'. * * @param txids * @param useNext */ getStatusForTxids: (txids: string[], useNext?: boolean) => Promise<GetStatusForTxidsResult>; /** * Calls getUtxoStatus with the hash of the output's lockingScript, * and ensures that the output's outpoint matches an unspent use of that script. * * @param output * @returns true if the output appears to currently be spendable. */ isUtxo: (output: TableOutput) => Promise<boolean>; /** * Attempts to determine the UTXO status of a transaction output. * * Cycles through configured transaction processing services attempting to get a valid response. * * @param output transaction output identifier in format determined by `outputFormat`. * @param chain which chain to post to, all of rawTx's inputs must be unspent on this chain. * @param outputFormat optional, supported values: * 'hashLE' little-endian sha256 hash of output script * 'hashBE' big-endian sha256 hash of output script * 'script' entire transaction output script * undefined if length of `output` is 32 hex bytes then 'hashBE`, otherwise 'script'. * @param outpoint if valid, result isUtxo is true only if this txid and vout match an unspent occurance of output script. `${txid}.${vout}` format. * @param useNext optional, forces skip to next service before starting service requests cycle. */ getUtxoStatus: (output: string, outputFormat?: GetUtxoStatusOutputFormat, outpoint?: string, useNext?: boolean) => Promise<GetUtxoStatusResult>; getScriptHashHistory: (hash: string, useNext?: boolean, logger?: WalletLoggerInterface) => Promise<GetScriptHashHistoryResult>; /** * @returns a block header * @param hash block hash */ hashToHeader: (hash: string) => Promise<BlockHeader>; /** * @returns whether the locktime value allows the transaction to be mined at the current chain height * @param txOrLockTime either a bitcoin locktime value or hex, binary, un-encoded Transaction */ nLockTimeIsFinal: (txOrLockTime: string | number[] | Transaction | number) => Promise<boolean>; /** * Constructs a `Beef` for the given `txid` using only external data retrieval services. * * In most cases, the `getBeefForTransaction` method of the `StorageProvider` class should be * used instead to avoid redundantly retrieving data. * * @throws errors if txid does not correspond to a valid transaction as determined by the * configured services. * * @param txid */ getBeefForTxid: (txid: string) => Promise<Beef>; /** * @param reset if true, ends current interval and starts a new one. * @returns a history of service calls made to the configured services. */ getServicesCallHistory: (reset?: boolean) => ServicesCallHistory; } type ScriptHashFormat = 'hashLE' | 'hashBE' | 'script'; type GetUtxoStatusOutputFormat = 'hashLE' | 'hashBE' | 'script'; interface BsvExchangeRate { timestamp: Date; base: 'USD'; rate: number; } interface FiatExchangeRates { timestamp: Date; base: FiatCurrencyCode; rates: Record<string, number>; rateTimestamps?: Record<string, Date>; } type FiatCurrencyCode = 'USD' | 'EUR' | 'GBP' | 'JPY' | 'CNY' | 'INR' | 'AUD' | 'CAD' | 'CHF' | 'HKD' | 'SGD' | 'NZD' | 'SEK' | 'NOK' | 'MXN'; interface WalletServicesOptions { /** * 'main' or 'test': which BSV chain to use */ chain: Chain; /** Optional provider-neutral service and ChainTracks tracing. */ telemetry?: TelemetryConfig; /** * As of 2025-08-31 the `taalApiKey` is unused for default configured services. * See `arcConfig` instead. */ taalApiKey?: string; /** * Api key for use accessing Bitails API at * mainnet: `https://api.bitails.io/` * testnet: `https://test-api.bitails.io/` */ bitailsApiKey?: string; /** * Api key for use accessing WhatsOnChain API at * mainnet: `https://api.whatsonchain.com/v1/bsv/main` * testnet: `https://api.whatsonchain.com/v1/bsv/test` */ whatsOnChainApiKey?: string; /** * The initial approximate BSV/USD exchange rate. */ bsvExchangeRate: BsvExchangeRate; /** * Update interval for BSV/USD exchange rate. * Default is 15 minutes. */ bsvUpdateMsecs: number; /** * The initial approximate fiat exchange rates with USD as base. */ fiatExchangeRates: FiatExchangeRates; /** * Update interval for Fiat exchange rates. * Default is 24 hours. */ fiatUpdateMsecs: number; /** * MAPI callbacks are deprecated at this time. */ disableMapiCallback?: boolean; /** * API key for use accessing fiat exchange rates API at * `https://api.exchangeratesapi.io/v1/latest?access_key=${key}` * * Obtain your own api key here: * https://manage.exchangeratesapi.io/signup/free */ exchangeratesapiKey?: string; /** * Due to the default use of a free exchangeratesapiKey with low usage limits, * the `ChaintracksService` can act as a request rate multiplier. * * By default the following endpoint is used: * `https://mainnet-chaintracks.babbage.systems/getFiatExchangeRates` */ chaintracksFiatExchangeRatesUrl?: string; /** * Optional Chaintracks client API instance. * Default is a new instance of ChaintracksServiceClient configured to use: * mainnet: `https://mainnet-chaintracks.babbage.systems` * testnet: `https://testnet-chaintracks.babbage.systems` */ chaintracks?: ChaintracksClientApi; /** * TAAL ARC service provider endpoit to use * Default is: * mainnet: `https://arc.taal.com` * testnet: `https://arc-test.taal.com` */ arcUrl: string; /** * TAAL ARC service configuration options. * * apiKey Default value is undefined. * * deploymentId Default value: `wallet-toolbox-${randomBytesHex(16)}`. * * callbackUrl Default is undefined. * callbackToken Default is undefined. */ arcConfig: ArcConfig; /** * GorillaPool ARC service provider endpoit to use * Default is: * mainnet: `https://arc.gorillapool.io` * testnet: undefined */ arcGorillaPoolUrl?: string; /** * GorillaPool ARC service configuration options. * * apiKey Default is undefined. * * deploymentId Default value: `wallet-toolbox-${randomBytesHex(16)}`. * * callbackUrl Default is undefined. * callbackToken Default is undefined. */ arcGorillaPoolConfig?: ArcConfig; /** * Optional bsv-blockchain/arcade endpoint to use as the primary transaction broadcaster. * * When set, an Arcade broadcaster is registered ahead of the ARC providers (Arcade-first, * ARC fallback) and the Monitor's SSE/proof task (`TaskArcadeSSE`) targets this URL. * * Default is undefined (Arcade disabled; ARC providers used as before). * mainnet: `https://arcade-v2-us-1.bsvblockchain.tech` * teratest: `https://arcade-v2-ttn-us-1.bsvblockchain.tech` * tstn: supplied at runtime via the `TSTN_ARCADE_URL` environment variable (not public) */ arcadeUrl?: string; /** * Arcade service configuration options (used to construct the `Arcade` broadcaster). * * `callbackToken` must equal the Monitor's `callbackToken` so Arcade routes each * submitted transaction's status events to this wallet's SSE subscription. * * `callbackUrl` should be left undefined for the SSE (pull) flow — Arcade rejects * private/loopback webhook URLs. */ arcadeConfig?: ArcConfig; } interface GetStatusForTxidsResult { /** * The name of the service returning these results. */ name: string; status: 'success' | 'error'; /** * The first exception error that occurred during processing, if any. */ error?: WalletError; results: StatusForTxidResult[]; } interface StatusForTxidResult { txid: string; /** * roughly depth of block containing txid from chain tip. */ depth: number | undefined; /** * 'mined' if depth > 0 * 'known' if depth === 0 * 'unknown' if depth === undefined, txid may be old an purged or never processed. */ status: 'mined' | 'known' | 'unknown'; } /** * Properties on result returned from `WalletServices` function `getRawTx`. */ interface GetRawTxResult { /** * Transaction hash or rawTx (and of initial request) */ txid: string; /** * The name of the service returning the rawTx, or undefined if no rawTx */ name?: string; /** * Multiple proofs may be returned when a transaction also appears in * one or more orphaned blocks */ rawTx?: number[]; /** * The first exception error that occurred during processing, if any. */ error?: WalletError; } /** * Properties on result returned from `WalletServices` function `getMerkleProof`. */ interface GetMerklePathResult { /** * The name of the service returning the proof, or undefined if no proof */ name?: string; /** * Multiple proofs may be returned when a transaction also appears in * one or more orphaned blocks */ merklePath?: MerklePath; header?: BlockHeader; /** * The first exception error that occurred during processing, if any. */ error?: WalletError; notes?: ReqHistoryNote[]; } interface PostTxResultForTxid { txid: string; /** * 'success' - The transaction was accepted for processing */ status: 'success' | 'error'; /** * if true, the transaction was already known to this service. Usually treat as a success. * * Potentially stop posting to additional transaction processors. */ alreadyKnown?: boolean; /** * service indicated this broadcast double spends at least one input * `competingTxs` may be an array of txids that were first seen spends of at least one input. */ doubleSpend?: boolean; blockHash?: string; blockHeight?: number; merklePath?: MerklePath; competingTxs?: string[]; data?: object | string | PostTxResultForTxidError; notes?: ReqHistoryNote[]; /** * true iff service was unable to process a potentially valid transaction */ serviceError?: boolean; } interface PostTxResultForTxidError { status?: string; detail?: string; more?: object; } interface PostBeefResult extends PostTxsResult {} /** * Properties on array items of result returned from `WalletServices` function `postBeef`. */ interface PostTxsResult { /** * The name of the service to which the transaction was submitted for processing */ name: string; /** * 'success' all txids returned status of 'success' * 'error' one or more txids returned status of 'error'. See txidResults for details. */ status: 'success' | 'error'; error?: WalletError; txidResults: PostTxResultForTxid[]; /** * Service response object. Use service name and status to infer type of object. */ data?: object; notes?: ReqHistoryNote[]; } interface GetUtxoStatusDetails { /** * if isUtxo, the block height containing the matching unspent transaction output * * typically there will be only one, but future orphans can result in multiple values */ height?: number; /** * if isUtxo, the transaction hash (txid) of the transaction containing the matching unspent transaction output * * typically there will be only one, but future orphans can result in multiple values */ txid?: string; /** * if isUtxo, the output index in the transaction containing of the matching unspent transaction output * * typically there will be only one, but future orphans can result in multiple values */ index?: number; /** * if isUtxo, the amount of the matching unspent transaction output * * typically there will be only one, but future orphans can result in multiple values */ satoshis?: number; } interface GetUtxoStatusResult { /** * The name of the service to which the transaction was submitted for processing */ name: string; /** * 'success' - the operation was successful, non-error results are valid. * 'error' - the operation failed, error may have relevant information. */ status: 'success' | 'error'; /** * When status is 'error', provides code and description */ error?: WalletError; /** * true if the output is associated with at least one unspent transaction output */ isUtxo?: boolean; /** * Additional details about occurances of this output script as a utxo. * * Normally there will be one item in the array but due to the possibility of orphan races * there could be more than one block in which it is a valid utxo. */ details: GetUtxoStatusDetails[]; } interface GetScriptHashHistory { txid: string; height?: number; } interface GetScriptHashHistoryResult { /** * The name of the service to which the transaction was submitted for processing */ name: string; /** * 'success' - the operation was successful, non-error results are valid. * 'error' - the operation failed, error may have relevant info