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 information.
   */
  status: 'success' | 'error';
  /**
   * When status is 'error', provides code and description
   */
  error?: WalletError;
  /**
   * Transaction txid (and height if mined) that consumes the script hash. May not be a complete history.
   */
  history: GetScriptHashHistory[];
}
/**
 * These are fields of 80 byte serialized header in order whose double sha256 hash is a block's hash value
 * and the next block's previousHash value.
 *
 * All block hash values and merkleRoot values are 32 byte hex string values with the byte order reversed from the serialized byte order.
 */
interface BaseBlockHeader {
  /**
   * Block header version value. Serialized length is 4 bytes.
   */
  version: number;
  /**
   * Hash of previous block's block header. Serialized length is 32 bytes.
   */
  previousHash: string;
  /**
   * Root hash of the merkle tree of all transactions in this block. Serialized length is 32 bytes.
   */
  merkleRoot: string;
  /**
   * Block header time value. Serialized length is 4 bytes.
   */
  time: number;
  /**
   * Block header bits value. Serialized length is 4 bytes.
   */
  bits: number;
  /**
   * Block header nonce value. Serialized length is 4 bytes.
   */
  nonce: number;
}
/**
 * A `BaseBlockHeader` extended with its computed hash and height in its chain.
 */
interface BlockHeader extends BaseBlockHeader {
  /**
   * Height of the header, starting from zero.
   */
  height: number;
  /**
   * The double sha256 hash of the serialized `BaseBlockHeader` fields.
   */
  hash: string;
}
type GetUtxoStatusService = (output: string, outputFormat?: GetUtxoStatusOutputFormat, outpoint?: string) => Promise<GetUtxoStatusResult>;
type GetStatusForTxidsService = (txids: string[]) => Promise<GetStatusForTxidsResult>;
type GetScriptHashHistoryService = (hash: string) => Promise<GetScriptHashHistoryResult>;
type GetMerklePathService = (txid: string, services: WalletServices) => Promise<GetMerklePathResult>;
type GetRawTxService = (txid: string, chain: Chain) => Promise<GetRawTxResult>;
type PostTxsService = (beef: Beef, txids: string[], services: WalletServices) => Promise<PostTxsResult>;
type PostBeefService = (beef: Beef, txids: string[]) => Promise<PostBeefResult>;
type UpdateFiatExchangeRateService = (targetCurrencies: string[], options: WalletServicesOptions) => Promise<FiatExchangeRates>;
/**
 * Type for the service call history returned by Services.getServicesCallHistory.
 */
interface ServicesCallHistory {
  version: number;
  getMerklePath: ServiceCallHistory;
  getRawTx: ServiceCallHistory;
  postBeef: ServiceCallHistory;
  getUtxoStatus: ServiceCallHistory;
  getStatusForTxids: ServiceCallHistory;
  getScriptHashHistory: ServiceCallHistory;
  updateFiatExchangeRates: ServiceCallHistory;
}
/**
 * Minimum data tracked for each service call.
 */
interface ServiceCall$1 {
  /**
   * string value must be Date's toISOString format.
   */
  when: Date | string;
  msecs: number;
  /**
   * true iff service provider successfully processed the request
   * false iff service provider failed to process the request which includes thrown errors.
   */
  success: boolean;
  /**
   * Simple text summary of result. e.g. `not a valid utxo` or `valid utxo`
   */
  result?: string;
  /**
   * Error code and message iff success is false and a exception was thrown.
   */
  error?: {
    message: string;
    code: string;
  };
}
/**
 * Counts of service calls over a time interval.
 */
interface ServiceCallHistoryCounts {
  /**
   * count of calls returning success true.
   */
  success: number;
  /**
   * count of calls returning success false.
   */
  failure: number;
  /**
   * of failures (success false), count of calls with valid error code and message.
   */
  error: number;
  /**
   * Counts are of calls over interval `since` to `until`.
   * string value must be Date's toISOString format.
   */
  since: Date | string;
  /**
   * Counts are of calls over interval `since` to `until`.
   * string value must be Date's toISOString format.
   */
  until: Date | string;
}
/**
 * History of service calls for a single service, single provider.
 */
interface ProviderCallHistory {
  providerName: string;
  serviceName: string;
  /**
   * Most recent service calls.
   * Array length is limited by Services configuration.
   */
  calls: ServiceCall$1[];
  /**
   * Counts since creation of Services instance.
   */
  totalCounts: ServiceCallHistoryCounts;
  /**
   * Entry [0] is always the current interval being extended by new calls.
   * when `getServiceCallHistory` with `reset` true is called, a new interval with zero counts is added to the start of array.
   * Array length is limited by Services configuration.
   */
  resetCounts: ServiceCallHistoryCounts[];
}
/**
 * History of service calls for a single service, all providers.
 */
interface ServiceCallHistory {
  serviceName: string;
  historyByProvider: Record<string, ProviderCallHistory>;
}
//#endregion
//#region ../src/sdk/ActionBatch.interfaces.d.ts
type ActionBatchPackEncoding = 'identity' | 'gzip' | 'brotli';
/** Internal Wallet Toolbox capabilities. These do not extend the BRC-100 wallet interface. */
interface StorageCapabilities {
  actionBatch?: {
    version: 1;
    maxInlineBytes: number;
    maxBlobBytes: number;
    maxConcurrentUploads: number;
    leaseMs: number;
    hardLifetimeMs: number;
    /** Large first actions may omit bytes that will be uploaded at commit. */
    compactBegin?: boolean;
    /**
     * Compact manifests derive source and output scripts from the transaction
     * graph instead of transferring duplicate script strings and blobs.
     */
    manifestVersion?: 2;
    /** A prepared compact manifest may be committed by its semantic digest. */
    commitByDigest?: boolean;
    /** Multiple logical blobs may share one authenticated binary request. */
    packedUploads?: {
      version: 1;
      maxPackBytes: number;
      maxItems: number;
      encodings: ActionBatchPackEncoding[];
      /** Packs may be uploaded before the final manifest is prepared. */
      eager: boolean;
    };
  };
}
interface ActionBatchFundingOutput extends TableOutput {
  sourceTransaction?: number[] | Uint8Array;
}
interface BeginActionBatchArgs {
  batchId: string;
  firstAction: Validation.ValidCreateActionArgs;
  /**
   * Exact output-script byte lengths when a large first action is sent in
   * compact form with empty script fields. This internal storage extension
   * avoids sending scripts and input proof data before chunked upload begins.
   */
  firstActionOutputScriptLengths?: number[];
}
interface BeginActionBatchResult {
  batchId: string;
  expiresAt: string;
  hardExpiresAt: string;
  changeBasket: TableOutputBasket;
  feeModel: StorageFeeModel;
  commissionSatoshis: number;
  commissionPubKeyHex?: string;
  availableChangeCount: number;
  reservedOutputs: ActionBatchFundingOutput[];
  explicitOutputs: ActionBatchFundingOutput[];
  inputBeef?: number[] | Uint8Array;
}
interface ExtendActionBatchArgs {
  batchId: string;
  targetSatoshis: number;
  requestedOutputs: number;
  explicitOutpoints: Array<{
    txid: string;
    vout: number;
  }>;
  includeSourceTransactions: boolean;
}
interface ExtendActionBatchResult {
  expiresAt: string;
  reservedOutputs: ActionBatchFundingOutput[];
  explicitOutputs: ActionBatchFundingOutput[];
  inputBeef?: number[] | Uint8Array;
}
interface RenewActionBatchResult {
  expiresAt: string;
}
interface ActionBatchCommitMetadata {
  description: string;
  labels: string[];
  isNoSend: boolean;
  isDelayed: boolean;
  inputs: Validation.ValidCreateActionInput[];
  outputs: Validation.ValidCreateActionOutput[];
}
interface ActionBatchCommitInput extends Omit<StorageCreateTransactionSdkInput, 'sourceLockingScript'> {
  /**
   * Version-1 manifests carry this value. Version-2 manifests derive it from
   * the proven source output and therefore omit it.
   */
  sourceLockingScript?: string;
}
interface ActionBatchCommitPlan extends Omit<StorageCreateActionResult, 'inputs'> {
  inputs: ActionBatchCommitInput[];
}
interface ActionBatchCommitAction {
  reference: string;
  txid: TXIDHexString;
  rawTx?: number[] | Uint8Array;
  rawTxDigest?: string;
  /** Content-addressed locking scripts aligned to plan.outputs for compact workspaces. */
  lockingScriptDigests?: Array<string | undefined>;
  /** Version 2 derives the scripts identified above from rawTx. */
  deriveLockingScripts?: boolean;
  plan: ActionBatchCommitPlan;
  metadata: ActionBatchCommitMetadata;
  commissionKeyOffset?: string;
}
interface ActionBatchManifest {
  /** Omitted for the original manifest format. */
  format?: 2;
  batchId: string;
  digest: string;
  actions: ActionBatchCommitAction[];
  /** Content-addressed blobs carried in the commit request when the batch is below the inline limit. */
  inlineBlobs?: Record<string, number[] | Uint8Array>;
  /** Physical chunk digests for logical blobs larger than the provider's advertised blob limit. */
  blobChunks?: Record<string, string[]>;
  dependencyBeef?: number[] | Uint8Array;
  dependencyBeefDigest?: string;
  sendWith: TXIDHexString[];
  isDelayed: boolean;
}
interface PrepareActionBatchCommitResult {
  missingDigests: string[];
  maxBlobBytes: number;
  maxConcurrentUploads: number;
}
interface PutActionBatchBlobArgs {
  batchId: string;
  digest: string;
  bytes: number[] | Uint8Array;
}
interface ActionBatchPackItem {
  digest: string;
  bytes: number[] | Uint8Array;
}
interface PutActionBatchPackArgs {
  batchId: string;
  items: ActionBatchPackItem[];
  maxPackBytes: number;
  maxItems: number;
  preferredEncodings?: ActionBatchPackEncoding[];
}
interface CommitActionBatchByDigestArgs {
  batchId: string;
  digest: string;
}
interface CommitActionBatchResult extends StorageProcessActionResults {
  batchId: string;
  manifestDigest: string;
  committedTxids: TXIDHexString[];
  alreadyCommitted: boolean;
}
interface AbortActionBatchResult {
  aborted: boolean;
}
//#endregion
//#region ../src/sdk/WalletStorage.interfaces.d.ts
/**
 * This is the `WalletStorage` interface implemented by a class such as `WalletStorageManager`,
 * which manges an active and set of backup storage providers.
 *
 * Access and conrol is not directly managed. Typically each request is made with an associated identityKey
 * and it is left to the providers: physical access or remote channel authentication.
 */
interface WalletStorage {
  /**
   * @returns false
   */
  isStorageProvider: () => boolean;
  isAvailable: () => boolean;
  makeAvailable: () => Promise<TableSettings>;
  migrate: (storageName: string, storageIdentityKey: string) => Promise<string>;
  destroy: () => Promise<void>;
  setServices: (v: WalletServices) => void;
  getServices: () => WalletServices;
  getSettings: () => TableSettings;
  getAuth: () => Promise<AuthId>;
  findOrInsertUser: (identityKey: string) => Promise<{
    user: TableUser;
    isNew: boolean;
  }>;
  abortAction: (args: AbortActionArgs) => Promise<AbortActionResult>;
  createAction: (args: Validation.ValidCreateActionArgs) => Promise<StorageCreateActionResult>;
  processAction: (args: StorageProcessActionArgs) => Promise<StorageProcessActionResults>;
  getCapabilities: () => Promise<StorageCapabilities>;
  beginActionBatch: (args: BeginActionBatchArgs) => Promise<BeginActionBatchResult>;
  extendActionBatch: (args: ExtendActionBatchArgs) => Promise<ExtendActionBatchResult>;
  renewActionBatch: (batchId: string) => Promise<RenewActionBatchResult>;
  prepareActionBatchCommit: (manifest: ActionBatchManifest) => Promise<PrepareActionBatchCommitResult>;
  putActionBatchBlob: (args: PutActionBatchBlobArgs) => Promise<void>;
  putActionBatchPack?: (args: PutActionBatchPackArgs) => Promise<void>;
  commitActionBatch: (manifest: ActionBatchManifest) => Promise<CommitActionBatchResult>;
  commitActionBatchByDigest?: (args: CommitActionBatchByDigestArgs) => Promise<CommitActionBatchResult>;
  abortActionBatch: (batchId: string) => Promise<AbortActionBatchResult>;
  internalizeAction: (args: InternalizeActionArgs) => Promise<InternalizeActionResult>;
  findCertificates: (args: FindCertificatesArgs) => Promise<TableCertificateX[]>;
  findOutputBaskets: (args: FindOutputBasketsArgs) => Promise<TableOutputBasket[]>;
  findOutputs: (args: FindOutputsArgs) => Promise<TableOutput[]>;
  findProvenTxReqs: (args: FindProvenTxReqsArgs) => Promise<TableProvenTxReq[]>;
  listActions: (args: Validation.ValidListActionsArgs) => Promise<ListActionsResult>;
  listCertificates: (args: Validation.ValidListCertificatesArgs) => Promise<ListCertificatesResult>;
  listOutputs: (args: Validation.ValidListOutputsArgs) => Promise<ListOutputsResult>;
  insertCertificate: (certificate: TableCertificateX) => Promise<number>;
  relinquishCertificate: (args: RelinquishCertificateArgs) => Promise<number>;
  relinquishOutput: (args: RelinquishOutputArgs) => Promise<number>;
  getStores: () => WalletStorageInfo[];
}
/**
 * Snapshot of the current state of a storage provider configured for an `WalletStorageManager`.
 */
interface WalletStorageInfo {
  isActive: boolean;
  isEnabled: boolean;
  isBackup: boolean;
  isConflicting: boolean;
  userId: number;
  storageIdentityKey: string;
  storageName: string;
  storageClass: string;
  endpointURL?: string;
}
/**
 * This is the `WalletStorage` interface implemented with authentication checking and
 * is the actual minimal interface implemented by storage and remoted storage providers.
 */
interface WalletStorageProvider extends WalletStorageSync {
  /**
   * @returns true if this object's interface can be extended to the full `StorageProvider` interface
   */
  isStorageProvider: () => boolean;
  setServices: (v: WalletServices) => void;
}
interface WalletStorageSync extends WalletStorageWriter {
  findOrInsertSyncStateAuth: (auth: AuthId, storageIdentityKey: string, storageName: string) => Promise<{
    syncState: TableSyncState;
    isNew: boolean;
  }>;
  /**
   * Updagte the `activeStorage` property of the authenticated user by their `userId`.
   * @param auth
   * @param newActiveStorageIdentityKey
   */
  setActive: (auth: AuthId, newActiveStorageIdentityKey: string) => Promise<number>;
  getSyncChunk: (args: RequestSyncChunkArgs) => Promise<SyncChunk>;
  processSyncChunk: (args: RequestSyncChunkArgs, chunk: SyncChunk) => Promise<ProcessSyncChunkResult>;
}
/**
 * This is the minimal interface required for a WalletStorageProvider to export data to another provider.
 */
interface WalletStorageSyncReader {
  makeAvailable: () => Promise<TableSettings>;
  getSyncChunk: (args: RequestSyncChunkArgs) => Promise<SyncChunk>;
}
interface WalletStorageWriter extends WalletStorageReader {
  makeAvailable: () => Promise<TableSettings>;
  migrate: (storageName: string, storageIdentityKey: string) => Promise<string>;
  destroy: () => Promise<void>;
  findOrInsertUser: (identityKey: string) => Promise<{
    user: TableUser;
    isNew: boolean;
  }>;
  abortAction: (auth: AuthId, args: AbortActionArgs) => Promise<AbortActionResult>;
  createAction: (auth: AuthId, args: Validation.ValidCreateActionArgs) => Promise<StorageCreateActionResult>;
  processAction: (auth: AuthId, args: StorageProcessActionArgs) => Promise<StorageProcessActionResults>;
  getCapabilities: () => Promise<StorageCapabilities>;
  beginActionBatch: (auth: AuthId, args: BeginActionBatchArgs) => Promise<BeginActionBatchResult>;
  extendActionBatch: (auth: AuthId, args: ExtendActionBatchArgs) => Promise<ExtendActionBatchResult>;
  renewActionBatch: (auth: AuthId, batchId: string) => Promise<RenewActionBatchResult>;
  prepareActionBatchCommit: (auth: AuthId, manifest: ActionBatchManifest) => Promise<PrepareActionBatchCommitResult>;
  putActionBatchBlob: (auth: AuthId, args: PutActionBatchBlobArgs) => Promise<void>;
  putActionBatchPack?: (auth: AuthId, args: PutActionBatchPackArgs) => Promise<void>;
  commitActionBatch: (auth: AuthId, manifest: ActionBatchManifest) => Promise<CommitActionBatchResult>;
  commitActionBatchByDigest?: (auth: AuthId, args: CommitActionBatchByDigestArgs) => Promise<CommitActionBatchResult>;
  abortActionBatch: (auth: AuthId, batchId: string) => Promise<AbortActionBatchResult>;
  internalizeAction: (auth: AuthId, args: InternalizeActionArgs) => Promise<StorageInternalizeActionResult>;
  insertCertificateAuth: (auth: AuthId, certificate: TableCertificateX) => Promise<number>;
  relinquishCertificate: (auth: AuthId, args: RelinquishCertificateArgs) => Promise<number>;
  relinquishOutput: (auth: AuthId, args: RelinquishOutputArgs) => Promise<number>;
}
interface WalletStorageReader {
  isAvailable: () => boolean;
  getServices: () => WalletServices;
  getSettings: () => TableSettings;
  findCertificatesAuth: (auth: AuthId, args: FindCertificatesArgs) => Promise<TableCertificateX[]>;
  findOutputBasketsAuth: (auth: AuthId, args: FindOutputBasketsArgs) => Promise<TableOutputBasket[]>;
  findOutputsAuth: (auth: AuthId, args: FindOutputsArgs) => Promise<TableOutput[]>;
  findProvenTxReqs: (args: FindProvenTxReqsArgs) => Promise<TableProvenTxReq[]>;
  listActions: (auth: AuthId, vargs: Validation.ValidListActionsArgs) => Promise<ListActionsResult>;
  listCertificates: (auth: AuthId, vargs: Validation.ValidListCertificatesArgs) => Promise<ListCertificatesResult>;
  listOutputs: (auth: AuthId, vargs: Validation.ValidListOutputsArgs) => Promise<ListOutputsResult>;
}
interface AuthId {
  identityKey: string;
  userId?: number;
  isActive?: boolean;
}
interface FindSincePagedArgs {
  since?: Date;
  paged?: Paged;
  trx?: TrxToken;
  /**
   * Support for orderDescending is implemented in StorageKnex for basic table find methods,
   * excluding certificate_fields table, map tables, and settings (singleton row table).
   */
  orderDescending?: boolean;
}
interface FindForUserSincePagedArgs extends FindSincePagedArgs {
  userId: number;
}
interface FindPartialSincePagedArgs<T extends object> extends FindSincePagedArgs {
  partial: Partial<T>;
}
interface FindCertificatesArgs extends FindSincePagedArgs {
  partial: Partial<TableCertificate>;
  certifiers?: string[];
  types?: string[];
  includeFields?: boolean;
}
interface FindOutputBasketsArgs extends FindSincePagedArgs {
  partial: Partial<TableOutputBasket>;
}
interface FindOutputsArgs extends FindSincePagedArgs {
  partial: Partial<TableOutput>;
  noScript?: boolean;
  txStatus?: TransactionStatus[];
}
type StorageProvidedBy = 'you' | 'storage' | 'you-and-storage';
interface StorageCreateTransactionSdkInput {
  vin: number;
  sourceTxid: string;
  sourceVout: number;
  sourceSatoshis: number;
  sourceLockingScript: string;
  /**
   *
   */
  sourceTransaction?: number[] | Uint8Array;
  unlockingScriptLength: number;
  providedBy: StorageProvidedBy;
  type: string;
  spendingDescription?: string;
  derivationPrefix?: string;
  derivationSuffix?: string;
  senderIdentityKey?: string;
}
interface StorageCreateTransactionSdkOutput extends Validation.ValidCreateActionOutput {
  vout: number;
  providedBy: StorageProvidedBy;
  purpose?: string;
  derivationSuffix?: string;
}
interface StorageCreateActionResult {
  inputBeef?: number[] | Uint8Array;
  inputs: StorageCreateTransactionSdkInput[];
  outputs: StorageCreateTransactionSdkOutput[];
  noSendChangeOutputVouts?: number[];
  derivationPrefix: string;
  version: number;
  lockTime: number;
  reference: string;
}
interface StorageProcessActionArgs {
  isNewTx: boolean;
  isSendWith: boolean;
  isNoSend: boolean;
  isDelayed: boolean;
  reference?: string;
  txid?: string;
  rawTx?: number[] | Uint8Array;
  sendWith: string[];
  logger?: WalletLoggerInterface;
}
interface StorageInternalizeActionResult extends InternalizeActionResult {
  /** true if internalizing outputs on an existing storage transaction */
  isMerge: boolean;
  /** txid of transaction being internalized */
  txid: string;
  /** net change in change balance for user due to this internalization */
  satoshis: number;
  /** valid iff not isMerge and txid was unknown to storage and non-delayed broadcast was not success */
  sendWithResults?: SendWithResult[];
  /** valid iff not isMerge and txid was unknown to storage and non-delayed broadcast was not success */
  notDelayedResults?: ReviewActionResult[];
}
/**
 * Indicates status of a new Action following a `createAction` or `signAction` in immediate mode:
 * When `acceptDelayedBroadcast` is falses.
 *
 * 'success': The action has been broadcast and accepted by the bitcoin processing network.
 * 'doubleSpend': The action has been confirmed to double spend one or more inputs, and by the "first-seen-rule" is the losing transaction.
 * 'invalidTx': The action was rejected by the processing network as an invalid bitcoin transaction.
 * 'serviceError': The broadcast services are currently unable to reach the bitcoin network. The action is now queued for delayed retries.
 */
type ReviewActionResultStatus = 'success' | 'doubleSpend' | 'serviceError' | 'invalidTx';
interface ReviewActionResult {
  txid: TXIDHexString;
  status: ReviewActionResultStatus;
  /**
   * Any competing txids reported for this txid, valid when status is 'doubleSpend'.
   */
  competingTxs?: string[];
  /**
   * Merged beef of competingTxs, valid when status is 'doubleSpend'.
   */
  competingBeef?: BEEF;
}
interface StorageProcessActionResults {
  sendWithResults?: SendWithResult[];
  notDelayedResults?: ReviewActionResult[];
  log?: string;
}
interface ProvenOrRawTx {
  proven?: TableProvenTx;
  rawTx?: number[];
  inputBEEF?: BEEF;
}
interface PurgeParams {
  purgeCompleted: boolean;
  purgeFailed: boolean;
  purgeSpent: boolean;
  /**
   * Minimum age in msecs for transient completed transaction data purge.
   * Default is 14 days.
   */
  purgeCompletedAge?: number;
  /**
   * Minimum age in msecs for failed transaction data purge.
   * Default is 14 days.
   */
  purgeFailedAge?: number;
  /**
   * Minimum age in msecs for failed transaction data purge.
   * Default is 14 days.
   */
  purgeSpentAge?: number;
}
interface PurgeResults {
  count: number;
  log: string;
}
interface StorageProvenOrReq {
  proven?: TableProvenTx;
  req?: TableProvenTxReq;
  isNew?: boolean;
}
/**
 * Specifies the available options for computing transaction fees.
 */
interface StorageFeeModel {
  /**
   * Available models. Currently only "sat/kb" is supported.
   */
  model: 'sat/kb';
  /**
   * When "fee.model" is "sat/kb", this is an integer representing the number of satoshis per kb of block space
   * the transaction will pay in fees.
   *
   * If undefined, the default value is used.
   */
  value?: number;
}
interface StorageGetBeefOptions {
  /** if 'known', txids known to local storage as valid are included as txidOnly */
  trustSelf?: 'known';
  /** list of txids to be included as txidOnly if referenced. Validity is known to caller. */
  knownTxids?: string[];
  /** optional. If defined, raw transactions and merkle paths required by txid are merged to this instance and returned. Otherwise a new Beef is constructed and returned. */
  mergeToBeef?: Beef | number[] | Uint8Array;
  /** Maximum independent ancestor lookups to perform concurrently. Defaults to 8. */
  maxConcurrency?: number;
  /** optional. Default is false. `storage` is used for raw transaction and merkle proof lookup */
  ignoreStorage?: boolean;
  /** optional. Default is false. `getServices` is used for raw transaction and merkle proof lookup */
  ignoreServices?: boolean;
  /** optional. Default is false. If true, raw transactions with proofs missing from `storage` and obtained from `getServices` are not inserted to `storage`. */
  ignoreNewProven?: boolean;
  /** optional. Default is zero. Ignores available merkle paths until recursion detpth equals or exceeds value  */
  minProofLevel?: number;
  /** optional. If valid, any merkleRoot that fails to validate will result in an exception without merging to `mergeToBeef`. */
  chainTracker?: ChainTracker;
  /** optional. Default is false. If chainTracker is valid and an invalid proof is found: if true, pursues deeper beef. If false, throws WERR_INVALID_MERKLE_ROOT. */
  skipInvalidProofs?: boolean;
}
interface StorageSyncReaderOptions {
  chain: Chain;
}
interface FindCertificateFieldsArgs extends FindSincePagedArgs {
  partial: Partial<TableCertificateField>;
}
interface FindCommissionsArgs extends FindSincePagedArgs {
  partial: Partial<TableCommission>;
}
interface FindOutputTagMapsArgs extends FindSincePagedArgs {
  partial: Partial<TableOutputTagMap>;
  tagIds?: number[];
}
interface FindOutputTagsArgs extends FindSincePagedArgs {
  partial: Partial<TableOutputTag>;
}
interface FindProvenTxReqsArgs extends FindSincePagedArgs {
  partial: Partial<TableProvenTxReq>;
  status?: ProvenTxReqStatus[];
  txids?: string[];
}
interface FindProvenTxsArgs extends FindSincePagedArgs {
  partial: Partial<TableProvenTx>;
  txids?: string[];
}
interface FindStaleMerkleRootsArgs {
  height: number;
  /**
   * The current valid merkle root for the given height.
   * Any proven transaction with a different merkle root at this height is considered to have a stale proof.
   */
  merkleRoot: string;
  trx?: TrxToken;
}
interface FindSyncStatesArgs extends FindSincePagedArgs {
  partial: Partial<TableSyncState>;
}
interface FindTransactionsArgs extends FindSincePagedArgs {
  partial: Partial<TableTransaction>;
  status?: TransactionStatus[];
  from?: Date;
  to?: Date;
  noRawTx?: boolean;
}
interface FindTxLabelMapsArgs extends FindSincePagedArgs {
  partial: Partial<TableTxLabelMap>;
  labelIds?: number[];
}
interface FindTxLabelsArgs extends FindSincePagedArgs {
  partial: Partial<TableTxLabel>;
}
interface FindUsersArgs extends FindSincePagedArgs {
  partial: Partial<TableUser>;
}
interface FindMonitorEventsArgs extends FindSincePagedArgs {
  partial: Partial<TableMonitorEvent>;
}
/**
 * Place holder for the transaction control object used by actual storage provider implementation.
 */
interface TrxToken {}
interface UpdateProvenTxReqWithNewProvenTxArgs {
  provenTxReqId: number;
  txid: string;
  attempts: number;
  status: ProvenTxReqStatus;
  history: string;
  height: number;
  index: number;
  blockHash: string;
  merkleRoot: string;
  merklePath: number[];
}
interface UpdateProvenTxReqWithNewProvenTxResult {
  status: ProvenTxReqStatus;
  history: string;
  provenTxId: number;
  /** Final durable notification state, when supplied by the storage implementation. */
  notified?: boolean;
  /** Final durable notification payload, when supplied by the storage implementation. */
  notify?: string;
  log?: string;
}
/**
 * success: Last sync of this user from this storage was successful.
 *
 * error: Last sync protocol operation for this user to this storage threw and error.
 *
 * identified: Configured sync storage has been identified but not sync'ed.
 *
 * unknown: Sync protocol state is unknown.
 */
type SyncStatus = 'success' | 'error' | 'identified' | 'updated' | 'unknown';
type SyncProtocolVersion = '0.1.0';
interface RequestSyncChunkArgs {
  /**
   * The storageIdentityKey of the storage supplying the update SyncChunk data.
   */
  fromStorageIdentityKey: string;
  /**
   * The storageIdentityKey of the storage consuming the update SyncChunk data.
   */
  toStorageIdentityKey: string;
  /**
   * The identity of whose data is being requested
   */
  identityKey: string;
  /**
   * The max updated_at time received from the storage service receiving the request.
   * Will be undefiend if this is the first request or if no data was previously sync'ed.
   *
   * `since` must include items if 'updated_at' is greater or equal. Thus, when not undefined, a sync request should always return at least one item already seen.
   */
  since?: Date;
  /**
   * A rough limit on how large the response should be.
   * The item that exceeds the limit is included and ends adding more items.
   */
  maxRoughSize: number;
  /**
   * The maximum number of items (records) to be returned.
   */
  maxItems: number;
  /**
   * For each entity in dependency order, the offset at which to start returning items
   * from `since`.
   *
   * The entity order is:
   * 0 ProvenTxs
   * 1 ProvenTxReqs
   * 2 OutputBaskets
   * 3 TxLabels
   * 4 OutputTags
   * 5 Transactions
   * 6 TxLabelMaps
   * 7 Commissions
   * 8 Outputs
   * 9 OutputTagMaps
   * 10 Certificates
   * 11 CertificateFields
   */
  offsets: Array<{
    name: string;
    offset: number;
  }>;
}
/**
 * Result received from remote `WalletStorage` in response to a `RequestSyncChunkArgs` request.
 *
 * Each property is undefined if there was no attempt to update it. Typically this is caused by size and count limits on this result.
 *
 * If all properties are empty arrays the sync process has received all available new and updated items.
 */
interface SyncChunk {
  fromStorageIdentityKey: string;
  toStorageIdentityKey: string;
  userIdentityKey: string;
  user?: TableUser;
  provenTxs?: TableProvenTx[];
  provenTxReqs?: TableProvenTxReq[];
  outputBaskets?: TableOutputBasket[];
  txLabels?: TableTxLabel[];
  outputTags?: TableOutputTag[];
  transactions?: TableTransaction[];
  txLabelMaps?: TableTxLabelMap[];
  commissions?: TableCommission[];
  outputs?: TableOutput[];
  outputTagMaps?: TableOutputTagMap[];
  certificates?: TableCertificate[];
  certificateFields?: TableCertificateField[];
}
interface ProcessSyncChunkResult {
  done: boolean;
  maxUpdated_at: Date | undefined;
  updates: number;
  inserts: number;
  error?: WalletError;
}
/**
 * Returned results from WalletStorageManager reproveHeader method.
 */
interface ReproveHeaderResult {
  /**
   * Human readable log of the reproveHeader process.
   */
  log: string;
  /**
   * List of proven_txs records that were updated with new proof data.
   */
  updated: Array<{
    was: TableProvenTx;
    update: Partial<TableProvenTx>;
    logUpdate: string;
  }>;
  /**
   * List of proven_txs records that were checked but currently available proof is unchanged.
   */
  unchanged: TableProvenTx[];
  /**
   * List of proven_txs records that were checked but currently proof data is unavailable.
   */
  unavailable: TableProvenTx[];
}
/**
 * Returned results from WalletStorageManager reproveProven method.
 */
interface ReproveProvenResult {
  /**
   * Human readable log of the reproveProven process.
   */
  log: string;
  /**
   * Valid if proof data for proven_txs record is available and has changed.
   */
  updated?: {
    update: Partial<TableProvenTx>;
    logUpdate: string;
  };
  /**
   * True if proof data for proven_txs record was found to be unchanged.
   */
  unchanged: boolean;
  /**
   * True if proof data for proven_txs record is currently unavailable.
   */
  unavailable: boolean;
}
//#endregion
//#region ../src/sdk/WERR_errors.d.ts
/**
 * Not implemented.
 */
declare class WERR_NOT_IMPLEMENTED extends WalletError {
  constructor(message?: string);
}
/**
 * An internal error has occurred.
 *
 * This is an example of an error with an optional custom `message`.
 */
declare class WERR_INTERNAL extends WalletError {
  constructor(message?: string);
}
/**
 * The ${parameter} parameter is invalid.
 *
 * This is an example of an error object with a custom property `parameter` and templated `message`.
 */
declare class WERR_INVALID_OPERATION extends WalletError {
  constructor(message?: string);
}
/**
 * Unable to broadcast transaction at this time.
 */
declare class WERR_BROADCAST_UNAVAILABLE extends WalletError {
  constructor(_message?: string);
}
/**
 * The ${parameter} parameter is invalid.
 *
 * This is an example of an error object with a custom property `parameter` and templated `message`.
 */
declare class WERR_INVALID_PARAMETER extends WalletError {
  parameter: string;
  constructor(parameter: string, mustBe?: string);
  toJson(): string;
}
/**
 * Invalid merkleRoot ${merkleRoot} for block ${blockHash} at height ${blockHeight}${txid ? ` for txid ${txid}` : ''}.
 *
 * Typically thrown when a chain tracker fails to validate a merkle root.
 */
declare class WERR_INVALID_MERKLE_ROOT extends WalletError {
  blockHash: string;
  blockHeight: number;
  merkleRoot: string;
  txid?: string | undefined;
  constructor(blockHash: string, blockHeight: number, merkleRoot: string, txid?: string | undefined);
  toJson(): string;
}
/**
 * The required ${parameter} parameter is missing.
 *
 * This is an example of an error object with a custom property `parameter`
 */
declare class WERR_MISSING_PARAMETER extends WalletError {
  parameter: string;
  constructor(parameter: string);
  toJson(): string;
}
/**
 * The request is invalid.
 */
declare class WERR_BAD_REQUEST extends WalletError {
  constructor(message?: string);
}
/**
 * Configured network chain is invalid or does not match across services.
 */
declare class WERR_NETWORK_CHAIN extends WalletError {
  constructor(message?: string);
}
/**
 * Access is denied due to an authorization error.
 */
declare class WERR_UNAUTHORIZED extends WalletError {
  constructor(message?: string);
}
/**
 * WalletStorageManager is not accessing user's active storage or there are conflicting active stores configured.
 */
declare class WERR_NOT_ACTIVE extends WalletError {
  constructor(message?: string);
}
/**
 * Insufficient funds in the available inputs to cover the cost of the required outputs
 * and the transaction fee (${moreSatoshisNeeded} more satoshis are needed,
 * for a total of ${totalSatoshisNeeded}), plus whatever would be required in order
 * to pay the fee to unlock and spend the outputs used to provide the additional satoshis.
 */
declare class WERR_INSUFFICIENT_FUNDS extends WalletError {
  totalSatoshisNeeded: number;
  moreSatoshisNeeded: number;
  /**
   * @param totalSatoshisNeeded Total satoshis required to fund transactions after net of required inputs and outputs.
   * @param moreSatoshisNeeded Shortfall on total satoshis required to fund transactions after net of required inputs and outputs.
   */
  constructor(totalSatoshisNeeded: number, moreSatoshisNeeded: number);
  toJson(): string;
}
declare class WERR_INVALID_PUBLIC_KEY extends WalletError {
  key: string;
  /**
   * @param key The invalid public key that caused the error.
   * @param environment Optional environment flag to control whether the key is included in the message.
   */
  constructor(key: string, network?: WalletNetwork);
  protected toJson(): string;
}
/**
 * When a `createAction` or `signAction` is completed in undelayed mode (`acceptDelayedBroadcast`: false),
 * any unsuccessful result will return the results by way of this exception to ensure attention is
 * paid to processing errors.
 */
declare class WERR_REVIEW_ACTIONS extends WalletError {
  reviewActionResults: ReviewActionResult[];
  sendWithResults: SendWithResult[];
  txid?: TXIDHexString | undefined;
  tx?: AtomicBEEF | undefined;
  noSendChange?: OutpointString[] | undefined;
  /**
   * All parameters correspond to their comparable `createAction` or `signAction` results
   * with the exception of `reviewActionResults`;
   * which contains more details, particularly for double spend results.
   */
  constructor(reviewActionResults: ReviewActionResult[], sendWithResults: SendWithResult[], txid?: TXIDHexString | undefined, tx?: AtomicBEEF | undefined, noSendChange?: OutpointString[] | undefined);
  toJson(): string;
}
/**
 * IF YOU ADD NEW ERRORS, ALSO UPDATE THE WalletError.fromJson METHOD IN src/sdk/WalletError.ts
 */
//#endregion
//#region ../src/sdk/CertOpsWallet.d.ts
interface CertOpsWallet {
  getPublicKey: (args: GetPublicKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes) => Promise<GetPublicKeyResult>;
  encrypt: (args: WalletEncryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes) => Promise<WalletEncryptResult>;
  decrypt: (args: WalletDecryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes) => Promise<WalletDecryptResult>;
}
//#endregion
//#region ../src/sdk/PrivilegedKeyManager.d.ts
/**
 * PrivilegedKeyManager
 *
 * This class manages a privileged (i.e., very sensitive) private key, obtained from
 * an external function (`keyGetter`), which might be backed by HSMs, secure enclaves,
 * or other secure storage. The manager retains the key in memory only for a limited
 * duration (`retentionPeriod`), uses XOR-based chunk-splitting obfuscation, and
 * includes decoy data to raise the difficulty of discovering the real key in memory.
 *
 * IMPORTANT: While these measures raise the bar for attackers, JavaScript environments
 * do not provide perfect in-memory secrecy.
 */
declare class PrivilegedKeyManager implements ProtoWallet {
  /**
   * Function that will retrieve the PrivateKey from a secure environment,
   * e.g., an HSM or secure enclave. The reason for key usage is passed in
   * to help with user consent, auditing, and access policy checks.
   */
  private readonly keyGetter;
  /**
   * Time (in ms) for which the obfuscated key remains in memory
   * before being automatically destroyed.
   */
  private readonly retentionPeriod;
  /**
   * A list of dynamically generated property names used to store
   * real key chunks (XORed with random pads).
   */
  private chunkPropNames;
  /**
   * A list of dynamically generated property names used to store
   * the random pads that correspond to the real key chunks.
   */
  private chunkPadPropNames;
  /**
   * A list of decoy property names that will be removed
   * when the real key is destroyed.
   */
  private decoyPropNamesDestroy;
  /**
   * A list of decoy property names that remain in memory
   * even after the real key is destroyed (just to cause confusion).
   */
  private readonly decoyPropNamesRemain;
  /**
   * Handle to the timer that will remove the key from memory
   * after the retention period. If the key is refreshed again
   * within that period, the timer is cleared and re-set.
   */
  private destroyTimer;
  /**
   * Number of chunks to split the 32-byte key into.
   * Adjust to increase or decrease obfuscation complexity.
   */
  private readonly CHUNK_COUNT;
  /**
   * @param keyGetter - Asynchronous function that retrieves the PrivateKey from a secure environment.
   * @param retentionPeriod - Time in milliseconds to retain the obfuscated key in memory before zeroizing.
   */
  constructor(keyGetter: (reason: string) => Promise<PrivateKey>, retentionPeriod?: number);
  /**
   * Safely destroys the in-memory obfuscated key material by zeroizing
   * and deleting related fields. Also destroys some (but not all) decoy
   * properties to further confuse an attacker.
   */
  destroyKey(): void;
  /**
   * Re/sets the destruction timer that removes the key from memory
   * after `retentionPeriod` ms. If a timer is already running, it
   * is cleared and re-set. This ensures the key remains in memory
   * for exactly the desired window after its most recent acquisition.
   */
  private scheduleKeyDestruction;
  /**
   * XOR-based obfuscation on a per-chunk basis.
   * This function takes two equal-length byte arrays
   * and returns the XOR combination.
   */
  private xorBytes;
  /**
   * Splits the 32-byte key into `this.CHUNK_COUNT` smaller chunks
   * (mostly equal length; the last chunk picks up leftover bytes
   * if 32 is not evenly divisible).
   */
  private splitKeyIntoChunks;
  /**
   * Reassembles the chunks from the dynamic properties, XORs them
   * with their corresponding pads, and returns a single 32-byte
   * Uint8Array representing the raw key.
   */
  private reassembleKeyFromChunks;
  /**
   * Generates a random property name to store key chunks or decoy data.
   */
  private generateRandomPropName;
  /**
   * Forces a PrivateKey to be represented as exactly 32 bytes, left-padding
   * with zeros if its numeric value has fewer than 32 bytes.
   */
  private get32ByteRepresentation;
  /**
   * Returns the privileged key needed to perform cryptographic operations.
   * Uses in-memory chunk-based obfuscation if the key was already fetched.
   * Otherwise, it calls out to `keyGetter`, splits the 32-byte representation
   * of the key, XORs each chunk with a random pad, and stores them under
   * dynamic property names. Also populates new decoy properties.
   *
   * @param reason - The reason for why the key is needed, passed to keyGetter.
   * @returns The PrivateKey object needed for cryptographic operations.
   */
  private getPrivilegedKey;
  getPublicKey(args: GetPublicKeyArgs): Promise<{
    publicKey: PubKeyHex;
  }>;
  revealCounterpartyKeyLinkage(args: RevealCounterpartyKeyLinkageArgs): Promise<RevealCounterpartyKeyLinkageResult>;
  revealSpecificKeyLinkage(args: RevealSpecificKeyLinkageArgs): Promise<RevealSpecificKeyLinkageResult>;
  encrypt(args: WalletEncryptArgs): Promise<WalletEncryptResult>;
  decrypt(args: WalletDecryptArgs): Promise<WalletDecryptResult>;
  createHmac(args: CreateHmacArgs): Promise<CreateHmacResult>;
  verifyHmac(args: VerifyHmacArgs): Promise<VerifyHmacResult>;
  createSignature(args: CreateSignatureArgs): Promise<CreateSignatureResult>;
  verifySignature(args: VerifySignatureArgs): Promise<VerifySignatureResult>;
}
declare namespace index_d_exports {
  export { AbortActionBatchResult, ActionBatchCommitAction, ActionBatchCommitInput, ActionBatchCommitMetadata, ActionBatchCommitPlan, ActionBatchFundingOutput, ActionBatchManifest, ActionBatchPackEncoding, ActionBatchPackItem, AuthId, BaseBlockHeader, BeginActionBatchArgs, BeginActionBatchResult, BlockHeader, BsvExchangeRate, CertOpsWallet, Chain, CommitActionBatchByDigestArgs, CommitActionBatchResult, EntityTimeStamp, ExtendActionBatchArgs, ExtendActionBatchResult, FiatCurrencyCode, FiatExchangeRates, FindCertificateFieldsArgs, FindCertificatesArgs, FindCommissionsArgs, FindForUserSincePagedArgs, FindMonitorEventsArgs, FindOutputBasketsArgs, FindOutputTagMapsArgs, FindOutputTagsArgs, FindOutputsArgs, FindPartialSincePagedArgs, FindProvenTxReqsArgs, FindProvenTxsArgs, FindSincePagedArgs, FindStaleMerkleRootsArgs, FindSyncStatesArgs, FindTransactionsArgs, FindTxLabelMapsArgs, FindTxLabelsArgs, FindUsersArgs, GetMerklePathResult, GetMerklePathService, GetRawTxResult, GetRawTxService, GetScriptHashHistory, GetScriptHashHistoryResult, GetScriptHashHistoryService, GetStatusForTxidsResult, GetStatusForTxidsService, GetUtxoStatusDetails, GetUtxoStatusOutputFormat, GetUtxoStatusResult, GetUtxoStatusService, KeyPair, OutPoint, Paged, PostBeefResult, PostBeefService, PostTxResultForTxid, PostTxResultForTxidError, PostTxsResult, PostTxsService, PrepareActionBatchCommitResult, PrivilegedKeyManager, ProcessSyncChunkResult, ProvenOrRawTx, ProvenTransactionStatus, ProvenTxReqNonTerminalStatus, ProvenTxReqStatus, ProvenTxReqTerminalStatus, ProviderCallHistory, PurgeParams, PurgeResults, PutActionBatchBlobArgs, PutActionBatchPackArgs, RenewActionBatchResult, ReproveHeaderResult, ReproveProvenResult, ReqHistoryNote, RequestSyncChunkArgs, ReviewActionResult, ReviewActionResultStatus, ScriptHashFormat, ScriptTemplateUnlock$1 as ScriptTemplateUnlock, ServiceCall$1 as ServiceCall, ServiceCallHistory, ServiceCallHistoryCounts, ServicesCallHistory, StatusForTxidResult, StorageCapabilities, StorageCreateActionResult, StorageCreateTransactionSdkInput, StorageCreateTransactionSdkOutput, StorageFeeModel, StorageGetBeefOptions, StorageIdentity, StorageInternalizeActionResult, StorageProcessActionArgs, StorageProcessActionResults, StorageProvenOrReq, StorageProvidedBy, StorageSyncReaderOptions, SyncChunk, SyncProtocolVersion, SyncStatus, TransactionStatus, TrxToken, UpdateFiatExchangeRateService, UpdateProvenTxReqWithNewProvenTxArgs, UpdateProvenTxReqWithNewProvenTxResult, Validation$1 as Validation, WERR_BAD_REQUEST, WERR_BROADCAST_UNAVAILABLE, WERR_INSUFFICIENT_FUNDS, WERR_INTERNAL, WERR_INVALID_MERKLE_ROOT, WERR_INVALID_OPERATION, WERR_INVALID_PARAMETER, WERR_INVALID_PUBLIC_KEY, WERR_MISSING_PARAMETER, WERR_NETWORK_CHAIN, WERR_NOT_ACTIVE, WERR_NOT_IMPLEMENTED, WERR_REVIEW_ACTIONS, WERR_UNAUTHORIZED, WalletBalance, WalletError, WalletErrorFromJson, WalletServices, WalletServicesOptions, WalletSigner$1 as WalletSigner, WalletStorage, WalletStorageInfo, WalletStorageProvider, WalletStorageReader, WalletStorageSync, WalletStorageSyncReader, WalletStorageWriter, isCreateActionSpecOp, isListActionsSpecOp, isListOutputsSpecOp, specOpFailedActions, specOpInvalidChange, specOpNoSendActions, specOpSetWalletChangeParams, specOpThrowReviewActions, specOpWalletBalance, specOpWalletManagedUtxos };
}
//#endregion
//#region ../src/utility/stampLog.d.ts
/**
 * If a log is being kept, add a time stamped line.
 * @param log  Optional time stamped log to extend, or an object with a log property to update
 * @param lineToAdd Content to add to line.
 * @returns undefined or log extended by time stamped `lineToAdd` and new line.
 */
declare function stampLog(log: string | undefined | {
  log?: string;
}, lineToAdd: string): string | undefined;
/**
 * Replaces individual timestamps with delta msecs.
 * Looks for two network crossings and adjusts clock for clock skew if found.
 * Assumes log built by repeated calls to `stampLog`
 * @param log Each logged event starts with ISO time stamp, space, rest of line, terminated by `\n`.
 * @returns reformated multi-line event log
 */
declare function stampLogFormat(log?: string): string;
//#endregion
//#region ../src/utility/ScriptTemplateBRC29.d.ts
declare const brc29ProtocolID: WalletProtocol;
interface ScriptTemplateParamsBRC29 {
  derivationPrefix?: string;
  derivationSuffix?: string;
  keyDeriver: KeyDeriverApi;
}
/**
 * Simple Authenticated BSV P2PKH Payment Protocol
 * https://brc.dev/29
 */
declare class ScriptTemplateBRC29 implements ScriptTemplate {
  params: ScriptTemplateParamsBRC29;
  p2pkh: P2PKH;
  constructor(params: ScriptTemplateParamsBRC29);
  getKeyID(): string;
  getKeyDeriver(privKey: PrivateKey | HexString): KeyDeriverApi;
  lock(lockerPrivKey: string, unlockerPubKey: string): LockingScript;
  unlock(unlockerPrivKey: PrivateKey | HexString, lockerPubKey: PublicKey | string, sourceSatoshis?: number, lockingScript?: Script): ScriptTemplateUnlock;
  unlockWithDerivedPrivateKey(derivedPrivateKey: PrivateKey, sourceSatoshis?: number, lockingScript?: Script): ScriptTemplateUnlock;
  /**
   * P2PKH unlock estimateLength is a constant
   */
  unlockLength: number;
}
//#endregion
//#region ../src/utility/parseTxScriptOffsets.d.ts
interface TxScriptOffsets {
  inputs: Array<{
    vin: number;
    offset: number;
    length: number;
  }>;
  outputs: Array<{
    vout: number;
    offset: number;
    length: number;
  }>;
}
declare function parseTxScriptOffsets(rawTx: number[] | Uint8Array): TxScriptOffsets;
//#endregion
//#region ../src/utility/tscProofToMerklePath.d.ts
interface TscMerkleProofApi {
  height: number;
  index: number;
  nodes: string[];
}
declare function convertProofToMerklePath(txid: string, proof: TscMerkleProofApi): MerklePath;
//#endregion
//#region ../src/utility/utilityHelpers.d.ts
declare function getIdentityKey(wallet: CertOpsWallet): Promise<PubKeyHex>;
declare function toWalletNetwork(chain: Chain): WalletNetwork;
/**
 * Maps a Chain to a network preset suitable for LookupResolver / SHIPBroadcaster.
 * Unlike `toWalletNetwork`, this returns `'local'` for `mock` chain.
 */
declare function toLookupNetworkPreset(chain: Chain): 'mainnet' | 'testnet' | 'local';
declare function makeAtomicBeef(tx: Transaction, beef: number[] | Beef): number[];
/**
 * Coerce a bsv transaction encoded as a hex string, serialized array, or Transaction to Transaction
 * If tx is already a Transaction, just return it.
 * @publicbody
 */
declare function asBsvSdkTx(tx: HexString | number[] | Transaction): Transaction;
/**
 * Coerce a bsv script encoded as a hex string, serialized array, or Script to Script
 * If script is already a Script, just return it.
 * @publicbody
 */
declare function asBsvSdkScript(script: HexString | number[] | Script): Script;
/**
 * @param privKey bitcoin private key in 32 byte hex string form
 * @returns @bsv/sdk PrivateKey
 */
declare function asBsvSdkPrivateKey(privKey: string): PrivateKey;
/**
 * @param pubKey bitcoin public key in standard compressed key hex string form
 * @returns @bsv/sdk PublicKey
 */
declare function asBsvSdkPublickKey(pubKey: string): PublicKey;
/**
 * Helper function.
 *
 * Verifies that a possibly optional value has a value.
 */
declare function verifyTruthy<T>(v: T | null | undefined, description?: string): T;
/**
 * Helper function.
 *
 * Verifies that a hex string is trimmed and lower case.
 */
declare function verifyHexString(v: string): string;
/**
 * Helper function.
 *
 * Verifies that an optional or null hex string is undefined or a trimmed lowercase string.
 */
declare function verifyOptionalHexString(v?: string | null): string | undefined;
/**
 * Helper function.
 *
 * Verifies that an optional or null number has a numeric value.
 */
declare function verifyNumber(v: number | null | undefined): number;
/**
 * Helper function.
 *
 * Verifies that an optional or null number has a numeric value.
 */
declare function verifyInteger(v: number | null | undefined): number;
/**
 * Helper function.
 *
 * Verifies that a database record identifier is an integer greater than zero.
 */
declare function verifyId(id: number | undefined | null): number;
/**
 * Helper function.
 *
 * @throws WERR_BAD_REQUEST if results has length greater than one.
 *
 * @returns results[0] or undefined if length is zero.
 */
declare function verifyOneOrNone<T>(results: T[]): T | undefined;
/**
 * Helper function.
 *
 * @throws WERR_BAD_REQUEST if results has length other than one.
 *
 * @returns results[0].
 */
declare function verifyOne<T>(results: T[], errorDescrition?: string): T;
/**
 * Returns an await'able Promise that resolves in the given number of msecs.
 * @param msecs number of milliseconds to wait before resolving the promise.
 * Must be greater than zero and less than 2 minutes (120,000 msecs)
 * @publicbody
 */
declare function wait(msecs: number): Promise<void>;
/**
 * @returns count cryptographically secure random bytes as array of bytes
 */
declare function randomBytes(count: number): number[];
/**
 * @returns count cryptographically secure random bytes as hex encoded string
 */
declare function randomBytesHex(count: number): string;
/**
 * @returns count cryptographically secure random bytes as base64 encoded string
 */
declare function randomBytesBase64(count: number): string;
declare function validateSecondsSinceEpoch(time: number): Date;
/**
 * Compares lengths and direct equality of values.
 * @param arr1
 * @param arr2
 * @returns
 */
declare function arraysEqual(arr1: number[], arr2: number[]): boolean;
declare function optionalArraysEqual(arr1?: number[], arr2?: number[]): boolean;
declare function maxDate(d1?: Date, d2?: Date): Date | undefined;
/**
 * Calculate the SHA256 hash of an array of bytes
 * @returns sha256 hash of buffer contents.
 * @publicbody
 */
declare function sha256Hash(data: number[] | Uint8Array): number[];
/**
 * Calculate the SHA256 hash of the SHA256 hash of an array of bytes.
 * @param data an array of bytes
 * @returns double sha256 hash of data, byte 0 of hash first.
 * @publicbody
 */
declare function doubleSha256LE(data: number[] | Uint8Array): number[];
/**
 * Calculate the SHA256 hash of the SHA256 hash of an array of bytes.
 * @param data is an array of bytes.
 * @returns reversed (big-endian) double sha256 hash of data, byte 31 of hash first.
 * @publicbody
 */
declare function doubleSha256BE(data: number[] | Uint8Array): number[];
/**
 * Logging function to handle logging based on running in jest "single test" mode,
 *
 * @param {string} message - The main message to log.
 * @param {...any} optionalParams - Additional parameters to log (optional).
 */
declare const logger: (message: string, ...optionalParams: any[]) => void;
//#endregion
//#region ../src/utility/utilityHelpers.noBuffer.d.ts
/** Byte array, string, or Uint8Array accepted by buffer-coercion helpers */
type ByteInput = string | number[] | Uint8Array;
/** Encoding identifier for buffer-coercion helpers */
type ByteEncoding = 'hex' | 'utf8' | 'base64';
/**
 * Convert a value to an encoded string if currently an encoded string or number[] or Uint8Array.
 * @param val string or number[] or Uint8Array. If string, encoding must be hex. If number[], each value must be 0..255.
 * @param enc optional encoding type if val is string, defaults to 'hex'. Can be 'hex', 'utf8', or 'base64'.
 * @param returnEnc optional encoding type for returned string if different from `enc`, defaults to 'hex'. Can be 'hex', 'utf8', or 'base64'.
 * @returns hex encoded string representation of val.
 * @publicbody
 */
declare function asString(val: ByteInput, enc?: ByteEncoding, returnEnc?: ByteEncoding): string;
/**
 * Convert a value to number[] if currently an encoded string or number[] or Uint8Array.
 * @param val string or number[] or Uint8Array. If string, encoding must be hex. If number[], each value must be 0..255.
 * @param enc optional encoding type if val is string, defaults to 'hex'. Can be 'hex', 'utf8', or 'base64'.
 * @returns number[] array of byte values representation of val.
 * @publicbody
 */
declare function asArray(val: ByteInput, enc?: ByteEncoding): number[];
/**
 * Convert a value to Uint8Array if currently an encoded string or number[] or Uint8Array.
 * @param val string or number[] or Uint8Array. If string, encoding must be hex. If number[], each value must be 0..255.
 * @param enc optional encoding type if val is string, defaults to 'hex'. Can be 'hex', 'utf8', or 'base64'.
 * @returns Uint8Array representation of val.
 * @publicbody
 */
declare function asUint8Array(val: ByteInput, enc?: ByteEncoding): Uint8Array;
//#endregion
//#region ../src/utility/brc114ActionTimeLabels.d.ts
interface ParsedBrc114ActionTimeLabels {
  from?: number;
  to?: number;
  timeFilterRequested: boolean;
  remainingLabels: string[];
}
declare function parseBrc114ActionTimeLabels(labels: string[] | undefined): ParsedBrc114ActionTimeLabels;
declare function makeBrc114ActionTimeLabel(unixMillis: number): string;
//#endregion
//#region ../src/storage/schema/entities/EntityBase.d.ts
type EntityStorage = StorageProvider;
declare abstract class EntityBase<T> {
  api: T;
  constructor(api: T);
  /**
   * Standard property for entity database Id
   */
  abstract get id(): number;
  /**
   * Name of derived entity class
   */
  abstract get entityName(): string;
  /**
   * Schema table name of entity
   */
  abstract get entityTable(): string;
  /**
   * On construction, an entity may decode properties of the `api` object,
   * such as JSON stringified objects.
   *
   * The `updateApi` method must re-encode the current state of those decoded properties
   * into the `api` object.
   *
   * Used by the `toApi` method to return an updated `api` object.
   */
  abstract updateApi(): void;
  /**
   * Tests for equality or 'merge' / 'convergent' equality if syncMap is provided.
   *
   * 'convergent' equality must satisfy (A sync B) equals (B sync A)
   *
   * @param ei
   * @param syncMap
   */
  abstract equals(ei: T, syncMap?: SyncMap): boolean;
  /**
   * Perform a 'merge' / 'convergent' equality migration of state
   * to this new local entity which was constructed
   * as a copy of the external object.
   *
   * @param userId local userId
   * @param syncMap
   */
  abstract mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  /**
   * Perform a 'merge' / 'convergent' equality migration of state
   * from external `ei` to this existing local EntityUser
   *
   * @param ei
   * @param syncMap
   * @returns true iff entity state changed and was updated to storage
   */
  abstract mergeExisting(storage: EntityStorage, since: Date | undefined, ei: T, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
  /**
   * An entity may decode properties of the underlying Api object on construction.
   *
   * The `toApi` method forces an `updateApi` before returning the underlying,
   * now updated, Api object.
   *
   * @returns The underlying Api object with any entity decoded properties updated.
   */
  toApi(): T;
}
interface EntitySyncMap {
  entityName: string;
  /**
   * Maps foreign ids to local ids
   * Some entities don't have idMaps (CertificateField, TxLabelMap and OutputTagMap)
   */
  idMap: Record<number, number>;
  /**
   * the maximum updated_at value seen for this entity over chunks received
   * during this udpate cycle.
   */
  maxUpdated_at?: Date;
  /**
   * The cummulative count of items of this entity type received over all the `SyncChunk`s
   * since the `since` was last updated.
   *
   * This is the `offset` value to use for the next SyncChunk request.
   */
  count: number;
}
interface SyncMap {
  provenTx: EntitySyncMap;
  outputBasket: EntitySyncMap;
  transaction: EntitySyncMap;
  provenTxReq: EntitySyncMap;
  txLabel: EntitySyncMap;
  txLabelMap: EntitySyncMap;
  output: EntitySyncMap;
  outputTag: EntitySyncMap;
  outputTagMap: EntitySyncMap;
  certificate: EntitySyncMap;
  certificateField: EntitySyncMap;
  commission: EntitySyncMap;
}
declare function createSyncMap(): SyncMap;
interface SyncError {
  code: string;
  description: string;
  stack?: string;
}
//#endregion
//#region ../src/storage/schema/entities/EntityProvenTxReq.d.ts
declare class EntityProvenTxReq extends EntityBase<TableProvenTxReq> {
  static readonly wasBroadcastStatuses: ProvenTxReqStatus[];
  static fromStorageTxid(storage: EntityStorage, txid: string, trx?: TrxToken): Promise<EntityProvenTxReq | undefined>;
  static fromStorageId(storage: EntityStorage, id: number, trx?: TrxToken): Promise<EntityProvenTxReq>;
  static fromTxid(txid: string, rawTx: number[] | Uint8Array, inputBEEF?: number[] | Uint8Array): EntityProvenTxReq;
  history: ProvenTxReqHistory;
  notify: ProvenTxReqNotify;
  packApiHistory(): void;
  packApiNotify(): void;
  unpackApiHistory(): void;
  unpackApiNotify(): void;
  get apiHistory(): string;
  get apiNotify(): string;
  set apiHistory(v: string);
  set apiNotify(v: string);
  updateApi(): void;
  unpackApi(): void;
  refreshFromStorage(storage: EntityStorage | WalletStorageManager, trx?: TrxToken): Promise<void>;
  constructor(api?: TableProvenTxReq);
  /**
   * Returns history to only what followed since date.
   */
  historySince(since: Date): ProvenTxReqHistory;
  historyPretty(since?: Date, _indent?: number): string;
  prettyNote(note: ReqHistoryNote): string;
  getHistorySummary(): ProvenTxReqHistorySummaryApi;
  parseHistoryNote(note: ReqHistoryNote, summary?: ProvenTxReqHistorySummaryApi): string;
  addNotifyTransactionId(id: number): void;
  /**
   * Adds a note to history.
   * Notes with identical property values to an existing note are ignored.
   * @param note Note to add
   * @param noDupes if true, only newest note with same `what` value is retained.
   */
  addHistoryNote(note: ReqHistoryNote, noDupes?: boolean): void;
  /**
   * Updates database record with current state of this EntityUser
   * @param storage
   * @param trx
   */
  updateStorage(storage: EntityStorage, trx?: TrxToken): Promise<void>;
  /**
   * Update storage with changes to non-static properties:
   *   updated_at
   *   provenTxId
   *   status
   *   history
   *   notify
   *   notified
   *   attempts
   *   batch
   *
   * @param storage
   * @param trx
   */
  updateStorageDynamicProperties(storage: WalletStorageManager | StorageProvider, trx?: TrxToken): Promise<void>;
  insertOrMerge(storage: EntityStorage, trx?: TrxToken): Promise<EntityProvenTxReq>;
  /**
   * See `ProvenTxReqStatusApi`
   */
  get status(): ProvenTxReqStatus;
  set status(v: ProvenTxReqStatus);
  get provenTxReqId(): number;
  set provenTxReqId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get txid(): string;
  set txid(v: string);
  get inputBEEF(): number[] | undefined;
  set inputBEEF(v: number[] | undefined);
  get rawTx(): number[];
  set rawTx(v: number[]);
  get attempts(): number;
  set attempts(v: number);
  get provenTxId(): number | undefined;
  set provenTxId(v: number | undefined);
  get notified(): boolean;
  set notified(v: boolean);
  get batch(): string | undefined;
  set batch(v: string | undefined);
  get wasBroadcast(): boolean;
  set wasBroadcast(v: boolean);
  get rebroadcastAttempts(): number;
  set rebroadcastAttempts(v: number);
  applyProofTimeout(maxRebroadcastAttempts?: number): {
    action: 'invalid' | 'rebroadcast';
    rebroadcastAttempts: number;
  };
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  /**
   * 'convergent' equality must satisfy (A sync B) equals (B sync A)
   */
  equals(ei: TableProvenTxReq, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableProvenTxReq, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityProvenTxReq;
    eiId: number;
  }>;
  mapNotifyTransactionIds(syncMap: SyncMap): void;
  mergeNotifyTransactionIds(ei: TableProvenTxReq, syncMap?: SyncMap): void;
  mergeHistory(ei: TableProvenTxReq, syncMap?: SyncMap, noDupes?: boolean): void;
  static isTerminalStatus(status: ProvenTxReqStatus): boolean;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  /**
   * When merging `ProvenTxReq`, care is taken to avoid short-cirtuiting notification: `status` must not transition to `completed` without
   * passing through `notifying`. Thus a full convergent merge passes through these sequence steps:
   * 1. Remote storage completes before local storage.
   * 2. The remotely completed req and ProvenTx sync to local storage.
   * 3. The local storage transitions to `notifying`, after merging the remote attempts and history.
   * 4. The local storage notifies, transitioning to `completed`.
   * 5. Having been updated, the local req, but not ProvenTx sync to remote storage, but do not merge because the earlier `completed` wins.
   * 6. Convergent equality is achieved (completing work - history and attempts are equal)
   *
   * On terminal failure: `doubleSpend` trumps `invalid` as it contains more data.
   */
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableProvenTxReq, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
interface ProvenTxReqHistorySummaryApi {
  setToCompleted: boolean;
  setToCallback: boolean;
  setToUnmined: boolean;
  setToDoubleSpend: boolean;
  setToSending: boolean;
  setToUnconfirmed: boolean;
}
interface ProvenTxReqHistory {
  /**
   * Keys are Date().toISOString()
   * Values are a description of what happened.
   */
  notes?: ReqHistoryNote[];
}
interface ProvenTxReqNotify {
  transactionIds?: number[];
}
//#endregion
//#region ../src/storage/methods/processAction.d.ts
interface GetReqsAndBeefDetail {
  txid: string;
  req?: TableProvenTxReq;
  proven?: TableProvenTx;
  status: 'readyToSend' | 'alreadySent' | 'error' | 'unknown';
  error?: string;
}
interface GetReqsAndBeefResult {
  beef: Beef;
  details: GetReqsAndBeefDetail[];
  /** Internal fast path: this exact BEEF instance already passed validation. */
  verified?: boolean;
}
//#endregion
//#region ../src/storage/schema/entities/EntitySyncState.d.ts
declare class EntitySyncState extends EntityBase<TableSyncState> {
  constructor(api?: TableSyncState);
  validateSyncMap(sm: SyncMap): void;
  static fromStorage(storage: WalletStorageSync, userIdentityKey: string, remoteSettings: TableSettings): Promise<EntitySyncState>;
  /**
   * Handles both insert and update based on id value: zero indicates insert.
   * @param storage
   * @param notSyncMap if not new and true, excludes updating syncMap in storage.
   * @param trx
   */
  updateStorage(storage: EntityStorage, notSyncMap?: boolean, trx?: TrxToken): Promise<void>;
  updateApi(notSyncMap?: boolean): void;
  set created_at(v: Date);
  get created_at(): Date;
  set updated_at(v: Date);
  get updated_at(): Date;
  set userId(v: number);
  get userId(): number;
  set storageIdentityKey(v: string);
  get storageIdentityKey(): string;
  set storageName(v: string);
  get storageName(): string;
  set init(v: boolean);
  get init(): boolean;
  set refNum(v: string);
  get refNum(): string;
  set status(v: SyncStatus);
  get status(): SyncStatus;
  set when(v: Date | undefined);
  get when(): Date | undefined;
  set satoshis(v: number | undefined);
  get satoshis(): number | undefined;
  get apiErrorLocal(): string | undefined;
  get apiErrorOther(): string | undefined;
  get apiSyncMap(): string;
  get id(): number;
  set id(id: number);
  get entityName(): string;
  get entityTable(): string;
  static mergeIdMap(fromMap: Record<number, number>, toMap: Record<number, number>): void;
  /**
   * Merge additions to the syncMap
   * @param iSyncMap
   */
  mergeSyncMap(iSyncMap: SyncMap): void;
  errorLocal: SyncError | undefined;
  errorOther: SyncError | undefined;
  syncMap: SyncMap;
  /**
   * Eliminate any properties besides code and description
   */
  private errorToString;
  equals(ei: TableSyncState, syncMap?: SyncMap | undefined): boolean;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableSyncState, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
  makeRequestSyncChunkArgs(forIdentityKey: string, forStorageIdentityKey: string, maxRoughSize?: number, maxItems?: number): RequestSyncChunkArgs;
  static syncChunkSummary(c: SyncChunk): string;
  processSyncChunk(writer: EntityStorage, args: RequestSyncChunkArgs, chunk: SyncChunk): Promise<{
    done: boolean;
    maxUpdated_at: Date | undefined;
    updates: number;
    inserts: number;
  }>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityProvenTx.d.ts
declare class EntityProvenTx extends EntityBase<TableProvenTx> {
  /**
   * Given a txid and optionally its rawTx, create a new ProvenTx object.
   *
   * rawTx is fetched if not provided.
   *
   * Only succeeds (proven is not undefined) if a proof is confirmed for rawTx,
   * and hash of rawTx is confirmed to match txid
   *
   * The returned ProvenTx and ProvenTxReq objects have not been added to the storage database,
   * this is optional and can be done by the caller if appropriate.
   *
   * @param txid
   * @param services
   * @param rawTx
   * @returns
   */
  static fromTxid(txid: string, services: WalletServices, rawTx?: number[]): Promise<ProvenTxFromTxidResult>;
  constructor(api?: TableProvenTx);
  updateApi(): void;
  /**
   * @returns desirialized `MerklePath` object, value is cached.
   */
  getMerklePath(validateRoots?: boolean): MerklePath;
  _mp?: MerklePath;
  _mpUnchecked?: MerklePath;
  get provenTxId(): number;
  set provenTxId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get txid(): string;
  set txid(v: string);
  get height(): number;
  set height(v: number);
  get index(): number;
  set index(v: number);
  get merklePath(): number[];
  set merklePath(v: number[]);
  get rawTx(): number[];
  set rawTx(v: number[]);
  get blockHash(): string;
  set blockHash(v: string);
  get merkleRoot(): string;
  set merkleRoot(v: string);
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableProvenTx, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableProvenTx, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityProvenTx;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableProvenTx, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
  /**
   * How high attempts can go before status is forced to invalid
   */
  static readonly getProofAttemptsLimit = 8;
  /**
   * How many hours we have to try for a poof
   */
  static readonly getProofMinutes = 60;
  private static applyProofTimeoutIfExpired;
  private static createFromProof;
  private static recordProofError;
  /**
   * Try to create a new ProvenTx from a ProvenTxReq and GetMerkleProofResultApi
   *
   * Otherwise it returns undefined and updates req.status to either 'unknown', 'invalid', or 'unconfirmed'
   *
   * @param req
   * @param gmpResult
   * @returns
   */
  static fromReq(req: EntityProvenTxReq, gmpResult: GetMerklePathResult, countsAsAttempt: boolean, maxRebroadcastAttempts?: number): Promise<EntityProvenTx | undefined>;
}
interface ProvenTxFromTxidResult {
  proven?: EntityProvenTx;
  rawTx?: number[];
}
//#endregion
//#region ../src/storage/schema/entities/MergeEntity.d.ts
/**
 * @param API one of the storage table interfaces.
 * @param DE the corresponding entity class
 */
declare class MergeEntity<API extends EntityTimeStamp, DE extends EntityBase<API>> {
  stateArray: API[] | undefined;
  find: (storage: EntityStorage, userId: number, ei: API, syncMap: SyncMap, trx?: TrxToken) => Promise<{
    found: boolean;
    eo: DE;
    eiId: number;
  }>;
  /** id map for primary id of API and DE object. */
  esm: EntitySyncMap;
  idMap: Record<number, number>;
  constructor(stateArray: API[] | undefined, find: (storage: EntityStorage, userId: number, ei: API, syncMap: SyncMap, trx?: TrxToken) => Promise<{
    found: boolean;
    eo: DE;
    eiId: number;
  }>,
  /** id map for primary id of API and DE object. */
  esm: EntitySyncMap);
  updateSyncMap(map: Record<number, number>, inId: number, outId: number): void;
  /**
   * @param since date of current sync chunk
   */
  merge(since: Date | undefined, storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<{
    inserts: number;
    updates: number;
  }>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityOutputBasket.d.ts
declare class EntityOutputBasket extends EntityBase<TableOutputBasket> {
  constructor(api?: TableOutputBasket);
  get basketId(): number;
  set basketId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get userId(): number;
  set userId(v: number);
  get name(): string;
  set name(v: string);
  get numberOfDesiredUTXOs(): number;
  set numberOfDesiredUTXOs(v: number);
  get minimumDesiredUTXOValue(): number;
  set minimumDesiredUTXOValue(v: number);
  get isDeleted(): boolean;
  set isDeleted(v: boolean);
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  updateApi(): void;
  equals(ei: TableOutputBasket, syncMap?: SyncMap): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableOutputBasket, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityOutputBasket;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableOutputBasket, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityUser.d.ts
declare class EntityUser extends EntityBase<TableUser> {
  constructor(api?: TableUser);
  updateApi(): void;
  get userId(): number;
  set userId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get identityKey(): string;
  set identityKey(v: string);
  get activeStorage(): string;
  set activeStorage(v: string);
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableUser, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableUser, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityUser;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableUser, syncMap?: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityTxLabelMap.d.ts
declare class EntityTxLabelMap extends EntityBase<TableTxLabelMap> {
  constructor(api?: TableTxLabelMap);
  updateApi(): void;
  get txLabelId(): number;
  set txLabelId(v: number);
  get transactionId(): number;
  set transactionId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get isDeleted(): boolean;
  set isDeleted(v: boolean);
  get id(): number;
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableTxLabelMap, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableTxLabelMap, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityTxLabelMap;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableTxLabelMap, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityTxLabel.d.ts
declare class EntityTxLabel extends EntityBase<TableTxLabel> {
  constructor(api?: TableTxLabel);
  updateApi(): void;
  get txLabelId(): number;
  set txLabelId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get label(): string;
  set label(v: string);
  get userId(): number;
  set userId(v: number);
  get isDeleted(): boolean;
  set isDeleted(v: boolean);
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableTxLabel, syncMap?: SyncMap): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableTxLabel, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityTxLabel;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableTxLabel, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityOutputTag.d.ts
declare class EntityOutputTag extends EntityBase<TableOutputTag> {
  constructor(api?: TableOutputTag);
  updateApi(): void;
  get outputTagId(): number;
  set outputTagId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get tag(): string;
  set tag(v: string);
  get userId(): number;
  set userId(v: number);
  get isDeleted(): boolean;
  set isDeleted(v: boolean);
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableOutputTag, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableOutputTag, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityOutputTag;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableOutputTag, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityOutputTagMap.d.ts
declare class EntityOutputTagMap extends EntityBase<TableOutputTagMap> {
  constructor(api?: TableOutputTagMap);
  updateApi(): void;
  get outputTagId(): number;
  set outputTagId(v: number);
  get outputId(): number;
  set outputId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get isDeleted(): boolean;
  set isDeleted(v: boolean);
  get id(): number;
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableOutputTagMap, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableOutputTagMap, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityOutputTagMap;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableOutputTagMap, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityCommission.d.ts
declare class EntityCommission extends EntityBase<TableCommission> {
  constructor(api?: TableCommission);
  updateApi(): void;
  get commissionId(): number;
  set commissionId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get transactionId(): number;
  set transactionId(v: number);
  get userId(): number;
  set userId(v: number);
  get isRedeemed(): boolean;
  set isRedeemed(v: boolean);
  get keyOffset(): string;
  set keyOffset(v: string);
  get lockingScript(): number[];
  set lockingScript(v: number[]);
  get satoshis(): number;
  set satoshis(v: number);
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableCommission, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableCommission, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityCommission;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableCommission, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityCertificate.d.ts
declare class EntityCertificate extends EntityBase<TableCertificate> {
  constructor(api?: TableCertificate);
  updateApi(): void;
  get certificateId(): number;
  set certificateId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get userId(): number;
  set userId(v: number);
  get type(): string;
  set type(v: string);
  get subject(): string;
  set subject(v: string);
  get verifier(): string | undefined;
  set verifier(v: string | undefined);
  get serialNumber(): string;
  set serialNumber(v: string);
  get certifier(): string;
  set certifier(v: string);
  get revocationOutpoint(): string;
  set revocationOutpoint(v: string);
  get signature(): string;
  set signature(v: string);
  get isDeleted(): boolean;
  set isDeleted(v: boolean);
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableCertificate, syncMap?: SyncMap): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableCertificate, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityCertificate;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableCertificate, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityCertificateField.d.ts
declare class EntityCertificateField extends EntityBase<TableCertificateField> {
  constructor(api?: TableCertificateField);
  updateApi(): void;
  get userId(): number;
  set userId(v: number);
  get certificateId(): number;
  set certificateId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get fieldName(): string;
  set fieldName(v: string);
  get fieldValue(): string;
  set fieldValue(v: string);
  get masterKey(): string;
  set masterKey(v: string);
  get id(): number;
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableCertificateField, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableCertificateField, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityCertificateField;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableCertificateField, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityTransaction.d.ts
declare class EntityTransaction extends EntityBase<TableTransaction> {
  /**
   * @returns @bsv/sdk Transaction object from parsed rawTx.
   * If rawTx is undefined, returns undefined.
   */
  getBsvTx(): Transaction | undefined;
  /**
   * @returns array of @bsv/sdk TransactionInput objects from parsed rawTx.
   * If rawTx is undefined, an empty array is returned.
   */
  getBsvTxIns(): TransactionInput[];
  /**
   * Returns an array of "known" inputs to this transaction which belong to the same userId.
   * Uses both spentBy and rawTx inputs (if available) to locate inputs from among user's outputs.
   * Not all transaction inputs correspond to prior storage outputs.
   */
  getInputs(storage: EntityStorage, trx?: TrxToken): Promise<TableOutput[]>;
  constructor(api?: TableTransaction);
  updateApi(): void;
  get transactionId(): number;
  set transactionId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get version(): number | undefined;
  set version(v: number | undefined);
  get lockTime(): number | undefined;
  set lockTime(v: number | undefined);
  get isOutgoing(): boolean;
  set isOutgoing(v: boolean);
  get status(): TransactionStatus;
  set status(v: TransactionStatus);
  get userId(): number;
  set userId(v: number);
  get provenTxId(): number | undefined;
  set provenTxId(v: number | undefined);
  get satoshis(): number;
  set satoshis(v: number);
  get txid(): string | undefined;
  set txid(v: string | undefined);
  get reference(): string;
  set reference(v: string);
  get inputBEEF(): number[] | undefined;
  set inputBEEF(v: number[] | undefined);
  get description(): string;
  set description(v: string);
  get rawTx(): number[] | undefined;
  set rawTx(v: number[] | undefined);
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableTransaction, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableTransaction, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityTransaction;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableTransaction, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
  getProvenTx(storage: EntityStorage, trx?: TrxToken): Promise<EntityProvenTx | undefined>;
}
//#endregion
//#region ../src/storage/schema/entities/EntityOutput.d.ts
declare class EntityOutput extends EntityBase<TableOutput> {
  constructor(api?: TableOutput);
  updateApi(): void;
  get outputId(): number;
  set outputId(v: number);
  get created_at(): Date;
  set created_at(v: Date);
  get updated_at(): Date;
  set updated_at(v: Date);
  get userId(): number;
  set userId(v: number);
  get transactionId(): number;
  set transactionId(v: number);
  get basketId(): number | undefined;
  set basketId(v: number | undefined);
  get spentBy(): number | undefined;
  set spentBy(v: number | undefined);
  get vout(): number;
  set vout(v: number);
  get satoshis(): number;
  set satoshis(v: number);
  get outputDescription(): string;
  set outputDescription(v: string);
  get spendable(): boolean;
  set spendable(v: boolean);
  get change(): boolean;
  set change(v: boolean);
  get txid(): string | undefined;
  set txid(v: string | undefined);
  get type(): string;
  set type(v: string);
  get providedBy(): StorageProvidedBy;
  set providedBy(v: StorageProvidedBy);
  get purpose(): string;
  set purpose(v: string);
  get spendingDescription(): string | undefined;
  set spendingDescription(v: string | undefined);
  get derivationPrefix(): string | undefined;
  set derivationPrefix(v: string | undefined);
  get derivationSuffix(): string | undefined;
  set derivationSuffix(v: string | undefined);
  get senderIdentityKey(): string | undefined;
  set senderIdentityKey(v: string | undefined);
  get customInstructions(): string | undefined;
  set customInstructions(v: string | undefined);
  get lockingScript(): number[] | undefined;
  set lockingScript(v: number[] | undefined);
  get scriptLength(): number | undefined;
  set scriptLength(v: number | undefined);
  get scriptOffset(): number | undefined;
  set scriptOffset(v: number | undefined);
  get id(): number;
  set id(v: number);
  get entityName(): string;
  get entityTable(): string;
  equals(ei: TableOutput, syncMap?: SyncMap | undefined): boolean;
  static mergeFind(storage: EntityStorage, userId: number, ei: TableOutput, syncMap: SyncMap, trx?: TrxToken): Promise<{
    found: boolean;
    eo: EntityOutput;
    eiId: number;
  }>;
  mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: TrxToken): Promise<void>;
  mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableOutput, syncMap: SyncMap, trx?: TrxToken): Promise<boolean>;
}
//#endregion
//#region ../src/storage/methods/attemptToPostReqsToNetwork.d.ts
/**
 * Indicates status of a new Action following a `createAction` or `signAction` in immediate mode:
 * When `acceptDelayedBroadcast` is falses.
 *
 * 'success': The action has been broadcast and accepted by the bitcoin processing network.
 * 'doubleSpend': The action has been confirmed to double spend one or more inputs, and by the "first-seen-rule" is the losing transaction.
 * 'invalidTx': The action was rejected by the processing network as an invalid bitcoin transaction.
 * 'serviceError': The broadcast services are currently unable to reach the bitcoin network. The action is now queued for delayed retries.
 *
 * 'invalid': The action was in an invalid state for processing, this status should never be seen by user code.
 * 'unknown': An internal processing error has occured, this status should never be seen by user code.
 *
 */
type PostReqsToNetworkDetailsStatus = 'success' | 'doubleSpend' | 'unknown' | 'invalid' | 'serviceError' | 'invalidTx';
interface PostReqsToNetworkDetails {
  txid: string;
  req: EntityProvenTxReq;
  status: PostReqsToNetworkDetailsStatus;
  /**
   * Any competing double spend txids reported for this txid
   */
  competingTxs?: string[];
}
interface PostReqsToNetworkResult {
  status: 'success' | 'error';
  beef: Beef;
  details: PostReqsToNetworkDetails[];
  log: string;
}
//#endregion
//#region ../src/storage/StorageReader.d.ts
type StorageDate = Date | string;
type DateInput = Date | string | number;
type OptionalDateInput = DateInput | null | undefined;
/**
 * The `StorageReader` abstract class is the base of the concrete wallet storage provider classes.
 *
 * It is the minimal interface required to read all wallet state records and is the base class for sync readers.
 *
 * The next class in the heirarchy is the `StorageReaderWriter` which supports sync readers and writers.
 *
 * The last class in the heirarchy is the `Storage` class which supports all active wallet operations.
 *
 * The ability to construct a properly configured instance of this class implies authentication.
 * As such there are no user specific authenticated access checks implied in the implementation of any of these methods.
 */
declare abstract class StorageReader implements WalletStorageSyncReader {
  chain: Chain;
  readonly telemetry: Telemetry;
  _settings?: TableSettings;
  whenLastAccess?: Date;
  get dbtype(): DBType | undefined;
  constructor(options: StorageReaderOptions);
  isAvailable(): boolean;
  makeAvailable(): Promise<TableSettings>;
  getSettings(): TableSettings;
  isStorageProvider(): boolean;
  abstract destroy(): Promise<void>;
  abstract transaction<T>(scope: (trx: TrxToken) => Promise<T>, trx?: TrxToken): Promise<T>;
  abstract readSettings(trx?: TrxToken): Promise<TableSettings>;
  abstract findCertificateFields(args: FindCertificateFieldsArgs): Promise<TableCertificateField[]>;
  abstract findCertificates(args: FindCertificatesArgs): Promise<TableCertificateX[]>;
  abstract findCommissions(args: FindCommissionsArgs): Promise<TableCommission[]>;
  abstract findMonitorEvents(args: FindMonitorEventsArgs): Promise<TableMonitorEvent[]>;
  abstract findOutputBaskets(args: FindOutputBasketsArgs): Promise<TableOutputBasket[]>;
  abstract findOutputs(args: FindOutputsArgs): Promise<TableOutput[]>;
  abstract findOutputTags(args: FindOutputTagsArgs): Promise<TableOutputTag[]>;
  abstract findSyncStates(args: FindSyncStatesArgs): Promise<TableSyncState[]>;
  abstract findTransactions(args: FindTransactionsArgs): Promise<TableTransaction[]>;
  abstract findTxLabels(args: FindTxLabelsArgs): Promise<TableTxLabel[]>;
  abstract findUsers(args: FindUsersArgs): Promise<TableUser[]>;
  abstract countCertificateFields(args: FindCertificateFieldsArgs): Promise<number>;
  abstract countCertificates(args: FindCertificatesArgs): Promise<number>;
  abstract countCommissions(args: FindCommissionsArgs): Promise<number>;
  abstract countMonitorEvents(args: FindMonitorEventsArgs): Promise<number>;
  abstract countOutputBaskets(args: FindOutputBasketsArgs): Promise<number>;
  abstract countOutputs(args: FindOutputsArgs): Promise<number>;
  abstract countOutputTags(args: FindOutputTagsArgs): Promise<number>;
  abstract countSyncStates(args: FindSyncStatesArgs): Promise<number>;
  abstract countTransactions(args: FindTransactionsArgs): Promise<number>;
  abstract countTxLabels(args: FindTxLabelsArgs): Promise<number>;
  abstract countUsers(args: FindUsersArgs): Promise<number>;
  abstract getProvenTxsForUser(args: FindForUserSincePagedArgs): Promise<TableProvenTx[]>;
  abstract getProvenTxReqsForUser(args: FindForUserSincePagedArgs): Promise<TableProvenTxReq[]>;
  abstract getTxLabelMapsForUser(args: FindForUserSincePagedArgs): Promise<TableTxLabelMap[]>;
  abstract getOutputTagMapsForUser(args: FindForUserSincePagedArgs): Promise<TableOutputTagMap[]>;
  findUserByIdentityKey(key: string): Promise<TableUser | undefined>;
  getSyncChunk(args: RequestSyncChunkArgs): Promise<SyncChunk>;
  /**
   * Force dates to strings on SQLite and Date objects on MySQL
   * @param date
   * @returns
   */
  validateEntityDate(date: DateInput): StorageDate;
  /**
   *
   * @param date
   * @param useNowAsDefault if true and date is null or undefiend, set to current time.
   * @returns
   */
  validateOptionalEntityDate(date: OptionalDateInput, useNowAsDefault?: boolean): StorageDate | undefined;
  validateDate(date: DateInput): Date;
  validateOptionalDate(date: OptionalDateInput): Date | undefined;
  validateDateForWhere(date: DateInput): DateInput;
}
interface StorageReaderOptions {
  chain: Chain;
  /** Optional provider-neutral storage and database tracing. */
  telemetry?: TelemetryConfig;
}
type DBType = 'SQLite' | 'MySQL' | 'IndexedDB';
//#endregion
//#region ../src/storage/StorageReaderWriter.d.ts
declare abstract class StorageReaderWriter extends StorageReader {
  abstract dropAllData(): Promise<void>;
  abstract migrate(storageName: string, storageIdentityKey: string): Promise<string>;
  abstract findOutputTagMaps(args: FindOutputTagMapsArgs): Promise<TableOutputTagMap[]>;
  abstract findProvenTxReqs(args: FindProvenTxReqsArgs): Promise<TableProvenTxReq[]>;
  abstract findProvenTxs(args: FindProvenTxsArgs): Promise<TableProvenTx[]>;
  abstract findTxLabelMaps(args: FindTxLabelMapsArgs): Promise<TableTxLabelMap[]>;
  abstract findStaleMerkleRoots(args: FindStaleMerkleRootsArgs): Promise<string[]>;
  abstract countOutputTagMaps(args: FindOutputTagMapsArgs): Promise<number>;
  abstract countProvenTxReqs(args: FindProvenTxReqsArgs): Promise<number>;
  abstract countProvenTxs(args: FindProvenTxsArgs): Promise<number>;
  abstract countTxLabelMaps(args: FindTxLabelMapsArgs): Promise<number>;
  abstract insertCertificate(certificate: TableCertificate, trx?: TrxToken): Promise<number>;
  abstract insertCertificateField(certificateField: TableCertificateField, trx?: TrxToken): Promise<void>;
  abstract insertCommission(commission: TableCommission, trx?: TrxToken): Promise<number>;
  abstract insertMonitorEvent(event: TableMonitorEvent, trx?: TrxToken): Promise<number>;
  abstract insertOutput(output: TableOutput, trx?: TrxToken): Promise<number>;
  abstract insertOutputBasket(basket: TableOutputBasket, trx?: TrxToken): Promise<number>;
  abstract insertOutputTag(tag: TableOutputTag, trx?: TrxToken): Promise<number>;
  abstract insertOutputTagMap(tagMap: TableOutputTagMap, trx?: TrxToken): Promise<void>;
  abstract insertProvenTx(tx: TableProvenTx, trx?: TrxToken): Promise<number>;
  abstract insertProvenTxReq(tx: TableProvenTxReq, trx?: TrxToken): Promise<number>;
  abstract insertSyncState(syncState: TableSyncState, trx?: TrxToken): Promise<number>;
  abstract insertTransaction(tx: TableTransaction, trx?: TrxToken): Promise<number>;
  abstract insertTxLabel(label: TableTxLabel, trx?: TrxToken): Promise<number>;
  abstract insertTxLabelMap(labelMap: TableTxLabelMap, trx?: TrxToken): Promise<void>;
  abstract insertUser(user: TableUser, trx?: TrxToken): Promise<number>;
  abstract updateCertificate(id: number, update: Partial<TableCertificate>, trx?: TrxToken): Promise<number>;
  abstract updateCertificateField(certificateId: number, fieldName: string, update: Partial<TableCertificateField>, trx?: TrxToken): Promise<number>;
  abstract updateCommission(id: number, update: Partial<TableCommission>, trx?: TrxToken): Promise<number>;
  abstract updateMonitorEvent(id: number, update: Partial<TableMonitorEvent>, trx?: TrxToken): Promise<number>;
  abstract updateOutput(id: number, update: Partial<TableOutput>, trx?: TrxToken): Promise<number>;
  abstract updateOutputBasket(id: number, update: Partial<TableOutputBasket>, trx?: TrxToken): Promise<number>;
  abstract updateOutputTag(id: number, update: Partial<TableOutputTag>, trx?: TrxToken): Promise<number>;
  abstract updateOutputTagMap(outputId: number, tagId: number, update: Partial<TableOutputTagMap>, trx?: TrxToken): Promise<number>;
  abstract updateProvenTx(id: number, update: Partial<TableProvenTx>, trx?: TrxToken): Promise<number>;
  abstract updateProvenTxReq(id: number | number[], update: Partial<TableProvenTxReq>, trx?: TrxToken): Promise<number>;
  abstract updateSyncState(id: number, update: Partial<TableSyncState>, trx?: TrxToken): Promise<number>;
  abstract updateTransaction(id: number | number[], update: Partial<TableTransaction>, trx?: TrxToken): Promise<number>;
  abstract updateTxLabel(id: number, update: Partial<TableTxLabel>, trx?: TrxToken): Promise<number>;
  abstract updateTxLabelMap(transactionId: number, txLabelId: number, update: Partial<TableTxLabelMap>, trx?: TrxToken): Promise<number>;
  abstract updateUser(id: number, update: Partial<TableUser>, trx?: TrxToken): Promise<number>;
  setActive(auth: AuthId, newActiveStorageIdentityKey: string): Promise<number>;
  findCertificateById(id: number, trx?: TrxToken): Promise<TableCertificate | undefined>;
  findCommissionById(id: number, trx?: TrxToken): Promise<TableCommission | undefined>;
  findOutputById(id: number, trx?: TrxToken, noScript?: boolean): Promise<TableOutput | undefined>;
  findOutputBasketById(id: number, trx?: TrxToken): Promise<TableOutputBasket | undefined>;
  findProvenTxById(id: number, trx?: TrxToken | undefined): Promise<TableProvenTx | undefined>;
  findProvenTxReqById(id: number, trx?: TrxToken | undefined): Promise<TableProvenTxReq | undefined>;
  findSyncStateById(id: number, trx?: TrxToken): Promise<TableSyncState | undefined>;
  findTransactionById(id: number, trx?: TrxToken, noRawTx?: boolean): Promise<TableTransaction | undefined>;
  findTxLabelById(id: number, trx?: TrxToken): Promise<TableTxLabel | undefined>;
  findOutputTagById(id: number, trx?: TrxToken): Promise<TableOutputTag | undefined>;
  findUserById(id: number, trx?: TrxToken): Promise<TableUser | undefined>;
  findOrInsertUser(identityKey: string, trx?: TrxToken): Promise<{
    user: TableUser;
    isNew: boolean;
  }>;
  findOrInsertTransaction(newTx: TableTransaction, trx?: TrxToken): Promise<{
    tx: TableTransaction;
    isNew: boolean;
  }>;
  findOrInsertOutputBasket(userId: number, name: string, trx?: TrxToken): Promise<TableOutputBasket>;
  findOrInsertTxLabel(userId: number, label: string, trx?: TrxToken): Promise<TableTxLabel>;
  findOrInsertTxLabelMap(transactionId: number, txLabelId: number, trx?: TrxToken): Promise<TableTxLabelMap>;
  findOrInsertOutputTag(userId: number, tag: string, trx?: TrxToken): Promise<TableOutputTag>;
  findOrInsertOutputTagMap(outputId: number, outputTagId: number, trx?: TrxToken): Promise<TableOutputTagMap>;
  findOrInsertSyncStateAuth(auth: AuthId, storageIdentityKey: string, storageName: string): Promise<{
    syncState: TableSyncState;
    isNew: boolean;
  }>;
  findOrInsertProvenTxReq(newReq: TableProvenTxReq, trx?: TrxToken): Promise<{
    req: TableProvenTxReq;
    isNew: boolean;
  }>;
  findOrInsertProvenTx(newProven: TableProvenTx, trx?: TrxToken): Promise<{
    proven: TableProvenTx;
    isNew: boolean;
  }>;
  abstract processSyncChunk(args: RequestSyncChunkArgs, chunk: SyncChunk): Promise<ProcessSyncChunkResult>;
  tagOutput(partial: Partial<TableOutput>, tag: string, trx?: TrxToken): Promise<void>;
}
interface StorageReaderWriterOptions extends StorageReaderOptions {}
//#endregion
//#region ../src/storage/methods/availableManagedChange.d.ts
type ManagedChangeInputCandidate = Pick<TableOutput, 'outputId' | 'transactionId' | 'satoshis' | 'txid' | 'vout'>;
//#endregion
//#region ../src/storage/StorageProvider.d.ts
declare abstract class StorageProvider extends StorageReaderWriter implements WalletStorageProvider {
  isDirty: boolean;
  _services?: WalletServices;
  feeModel: StorageFeeModel;
  commissionSatoshis: number;
  commissionPubKeyHex?: PubKeyHex;
  maxRecursionDepth?: number;
  readonly scriptVerifier?: SpendVerifierInterface;
  static defaultOptions(): {
    feeModel: StorageFeeModel;
    commissionSatoshis: number;
    commissionPubKeyHex: undefined;
  };
  static createStorageBaseOptions(chain: Chain): StorageProviderOptions;
  constructor(options: StorageProviderOptions);
  abstract reviewStatus(args: {
    agedLimit: Date;
    trx?: TrxToken;
  }): Promise<{
    log: string;
  }>;
  abstract purgeData(params: PurgeParams, trx?: TrxToken): Promise<PurgeResults>;
  abstract allocateChangeInput(userId: number, basketId: number, targetSatoshis: number, exactSatoshis: number | undefined, excludeSending: boolean, transactionId: number): Promise<TableOutput | undefined>;
  /** Mark a planned set of change inputs spent within the caller's transaction. */
  markChangeInputsSpent(outputIds: number[], transactionId: number, trx: TrxToken): Promise<number>;
  /**
   * Insert outputs that do not need their generated ids returned to the
   * caller. Engines with a multi-row insert override this common-path helper;
   * the fallback preserves existing storage implementations unchanged.
   */
  insertOutputs(outputs: TableOutput[], trx?: TrxToken): Promise<void>;
  /** Return unreserved wallet-managed outputs eligible for automatic funding. */
  findAvailableManagedChangeInputs(userId: number, basketId: number, excludeSending: boolean, trx?: TrxToken): Promise<TableOutput[]>;
  /** Read only the fields needed by the in-memory funding planner. */
  findAvailableManagedChangeInputCandidates(userId: number, basketId: number, excludeSending: boolean, trx?: TrxToken): Promise<ManagedChangeInputCandidate[]>;
  /** Read the current status of a set of source transactions without loading raw transaction bytes. */
  findTransactionStatusesByIds(userId: number, transactionIds: number[], trx?: TrxToken): Promise<Map<number, TransactionStatus>>;
  /**
   * Lock and return the selected funding rows whose source transaction and
   * action-batch reservation state still permit allocation.
   */
  findFundingOutputsForUpdate(userId: number, outputIds: number[], statuses: TransactionStatus[], trx: TrxToken): Promise<Record<number, TableOutput>>;
  abstract getProvenOrRawTx(txid: string, trx?: TrxToken): Promise<ProvenOrRawTx>;
  /**
   * Resolve several transaction proofs in one storage operation when the
   * backend supports it. The default preserves compatibility for custom
   * providers; SQL and IndexedDB providers override this hot path.
   */
  getProvenOrRawTxs(txids: string[], trx?: TrxToken): Promise<Map<string, ProvenOrRawTx>>;
  abstract getRawTxOfKnownValidTransaction(txid?: string, offset?: number, length?: number, trx?: TrxToken): Promise<number[] | undefined>;
  abstract getLabelsForTransactionId(transactionId?: number, trx?: TrxToken): Promise<TableTxLabel[]>;
  abstract getTagsForOutputId(outputId: number, trx?: TrxToken): Promise<TableOutputTag[]>;
  abstract listActions(auth: AuthId, args: Validation.ValidListActionsArgs): Promise<ListActionsResult>;
  abstract listOutputs(auth: AuthId, args: Validation.ValidListOutputsArgs): Promise<ListOutputsResult>;
  abstract countChangeInputs(userId: number, basketId: number, excludeSending: boolean): Promise<number>;
  insertActionBatch(_batch: TableActionBatch, _trx?: TrxToken): Promise<number>;
  findActionBatch(_userId: number, _batchId: string, _trx?: TrxToken): Promise<TableActionBatch | undefined>;
  findActionBatchForUpdate(userId: number, batchId: string, trx: TrxToken): Promise<TableActionBatch | undefined>;
  findExpiredActionBatches(_now: Date, _trx?: TrxToken): Promise<TableActionBatch[]>;
  updateActionBatch(_actionBatchId: number, _update: Partial<TableActionBatch>, _trx?: TrxToken): Promise<number>;
  deleteActionBatch(_actionBatchId: number, _trx?: TrxToken): Promise<void>;
  reserveActionBatchOutputs(_reservations: TableActionBatchOutput[], _trx?: TrxToken): Promise<void>;
  findActionBatchOutputIds(_actionBatchId: number, _trx?: TrxToken): Promise<number[]>;
  findReservedActionBatchOutputIds(_outputIds: number[], _trx?: TrxToken): Promise<number[]>;
  deleteActionBatchOutputReservations(_actionBatchId: number, _trx?: TrxToken): Promise<void>;
  putActionBatchBlobRecord(_blob: TableActionBatchBlob, _trx?: TrxToken): Promise<void>;
  findActionBatchBlobRecord(_actionBatchId: number, _digest: string, _trx?: TrxToken): Promise<TableActionBatchBlob | undefined>;
  findActionBatchBlobRecords(actionBatchId: number, digests: string[], trx?: TrxToken): Promise<TableActionBatchBlob[]>;
  putActionBatchBlobRecords(blobs: TableActionBatchBlob[], trx?: TrxToken): Promise<void>;
  deleteActionBatchBlobRecords(_actionBatchId: number, _trx?: TrxToken): Promise<void>;
  getCapabilities(): Promise<StorageCapabilities>;
  protected supportsActionBatchPersistence(): boolean;
  /** Custom providers may require physical expiry cleanup before reservations are queried. */
  protected requiresActionBatchCleanupBeforeCreateAction(): boolean;
  beginActionBatch(auth: AuthId, args: BeginActionBatchArgs): Promise<BeginActionBatchResult>;
  extendActionBatch(auth: AuthId, args: ExtendActionBatchArgs): Promise<ExtendActionBatchResult>;
  renewActionBatch(auth: AuthId, batchId: string): Promise<RenewActionBatchResult>;
  prepareActionBatchCommit(auth: AuthId, manifest: ActionBatchManifest): Promise<PrepareActionBatchCommitResult>;
  putActionBatchBlob(auth: AuthId, args: PutActionBatchBlobArgs): Promise<void>;
  putActionBatchPack(auth: AuthId, args: PutActionBatchPackArgs): Promise<void>;
  commitActionBatch(auth: AuthId, manifest: ActionBatchManifest): Promise<CommitActionBatchResult>;
  commitActionBatchByDigest(auth: AuthId, args: CommitActionBatchByDigestArgs): Promise<CommitActionBatchResult>;
  abortActionBatch(auth: AuthId, batchId: string): Promise<AbortActionBatchResult>;
  findOutputsByIds(outputIds: number[], trx?: TrxToken): Promise<Record<number, TableOutput>>;
  findStaleMerkleRoots(args: FindStaleMerkleRootsArgs): Promise<string[]>;
  findOutputsByOutpoints(userId: number, outpoints: Array<{
    txid: string;
    vout: number;
  }>, trx?: TrxToken): Promise<Record<string, TableOutput>>;
  findOutputsByOutpointsForUpdate(userId: number, outpoints: Array<{
    txid: string;
    vout: number;
  }>, trx: TrxToken, _noScript?: boolean): Promise<Record<string, TableOutput>>;
  findOrInsertOutputBasketsBulk(userId: number, names: string[], trx?: TrxToken): Promise<Record<string, TableOutputBasket>>;
  findOrInsertOutputTagsBulk(userId: number, tags: string[], trx?: TrxToken): Promise<Record<string, TableOutputTag>>;
  findOrInsertTxLabelsBulk(userId: number, labels: string[], trx?: TrxToken): Promise<Record<string, TableTxLabel>>;
  sumSpendableSatoshisInBasket(userId: number, basketId: number, excludeSending: boolean, trx?: TrxToken): Promise<number>;
  abstract findCertificatesAuth(auth: AuthId, args: FindCertificatesArgs): Promise<TableCertificateX[]>;
  abstract findOutputBasketsAuth(auth: AuthId, args: FindOutputBasketsArgs): Promise<TableOutputBasket[]>;
  abstract findOutputsAuth(auth: AuthId, args: FindOutputsArgs): Promise<TableOutput[]>;
  abstract insertCertificateAuth(auth: AuthId, certificate: TableCertificateX): Promise<number>;
  abstract adminStats(adminIdentityKey: string): Promise<AdminStatsResult>;
  recentlyActiveUsers(limit?: number, trx?: TrxToken): Promise<TableUser[]>;
  isStorageProvider(): boolean;
  setServices(v: WalletServices): void;
  getServices(): WalletServices;
  private findAbortableTransaction;
  private checkAbortChainProtection;
  private invalidateAbortedTransaction;
  abortAction(auth: AuthId, args: AbortActionArgs): Promise<AbortActionResult>;
  internalizeAction(auth: AuthId, args: InternalizeActionArgs): Promise<StorageInternalizeActionResult>;
  /**
   * Given an array of transaction txids with current ProvenTxReq ready-to-share status,
   * lookup their ProvenTxReqApi req records.
   * For the txids with reqs and status still ready to send construct a single merged beef.
   *
   * @param txids
   * @param knownTxids
   * @param trx
   */
  getReqsAndBeefToShareWithWorld(txids: string[], knownTxids: string[], trx?: TrxToken): Promise<GetReqsAndBeefResult>;
  mergeReqToBeefToShareExternally(req: TableProvenTxReq, mergeToBeef: Beef, knownTxids: string[], trx?: TrxToken): Promise<void>;
  /**
   * Checks if txid is a known valid ProvenTx and returns it if found.
   * Next checks if txid is a current ProvenTxReq and returns that if found.
   * If `newReq` is provided and an existing ProvenTxReq isn't found,
   * use `newReq` to create a new ProvenTxReq.
   *
   * This is safe "findOrInsert" operation using retry if unique index constraint
   * is violated by a race condition insert.
   *
   * @param txid
   * @param newReq
   * @param trx
   * @returns
   */
  private upsertProvenTxReq;
  getProvenOrReq(txid: string, newReq?: TableProvenTxReq, trx?: TrxToken): Promise<StorageProvenOrReq>;
  updateTransactionsStatus(transactionIds: number[], status: TransactionStatus, trx?: TrxToken): Promise<void>;
  private releaseInputsAllocatedToFailedTransaction;
  private markFailedTransactionOutputsNotSpendable;
  /**
   * For all `status` values besides 'failed', just updates the transaction records status property.
   *
   * For 'status' of 'failed', attempts to make outputs previously allocated as inputs to this transaction usable again
   * and makes outputs generated by this transaction non-spendable.
   *
   * @param status
   * @param transactionId
   * @param userId
   * @param reference
   * @param trx
   */
  updateTransactionStatus(status: TransactionStatus, transactionId?: number, userId?: number, reference?: string, trx?: TrxToken): Promise<void>;
  createAction(auth: AuthId, args: Validation.ValidCreateActionArgs): Promise<StorageCreateActionResult>;
  processAction(auth: AuthId, args: StorageProcessActionArgs): Promise<StorageProcessActionResults>;
  attemptToPostReqsToNetwork(reqs: EntityProvenTxReq[], trx?: TrxToken, logger?: WalletLoggerInterface): Promise<PostReqsToNetworkResult>;
  listCertificates(auth: AuthId, args: Validation.ValidListCertificatesArgs): Promise<ListCertificatesResult>;
  verifyKnownValidTransaction(txid: string, trx?: TrxToken): Promise<boolean>;
  /**
   * Pulls data from storage to build a valid beef for a txid.
   *
   * Optionally merges the data into an existing beef.
   * Optionally requires a minimum number of proof levels.
   *
   * @param txid
   * @param mergeToBeef
   * @param trustSelf
   * @param knownTxids
   * @param trx
   * @param requiredLevels
   * @returns
   */
  getValidBeefForKnownTxid(txid: string, mergeToBeef?: Beef, trustSelf?: TrustSelf, knownTxids?: string[], trx?: TrxToken, requiredLevels?: number): Promise<Beef>;
  /**
   * Handles the proven-tx branch of getValidBeefForTxid.
   *
   * Returns the beef if the proof was merged and we can stop, or `undefined` to
   * signal that the caller should fall through to the rawTx path.  May also
   * populate `r.rawTx` so the rawTx path can proceed without re-fetching.
   */
  private handleProvenTxBranch;
  getValidBeefForTxid(...[txid, mergeToBeef, trustSelf, knownTxids, trx, requiredLevels, chainTracker, skipInvalidProofs]: [txid: string, mergeToBeef?: Beef, trustSelf?: TrustSelf, knownTxids?: string[], trx?: TrxToken, requiredLevels?: number, chainTracker?: ChainTracker, skipInvalidProofs?: boolean]): Promise<Beef | undefined>;
  getBeefForTransaction(txid: string, options: StorageGetBeefOptions): Promise<Beef>;
  getBeefForTransactions(txids: string[], options: StorageGetBeefOptions): Promise<Beef>;
  findMonitorEventById(id: number, trx?: TrxToken): Promise<TableMonitorEvent | undefined>;
  relinquishCertificate(auth: AuthId, args: RelinquishCertificateArgs): Promise<number>;
  relinquishOutput(auth: AuthId, args: RelinquishOutputArgs): Promise<number>;
  processSyncChunk(args: RequestSyncChunkArgs, chunk: SyncChunk): Promise<ProcessSyncChunkResult>;
  /**
   * Handles storage changes when a valid MerklePath and mined block header are found for a ProvenTxReq txid.
   *
   * Performs the following storage updates (typically):
   * 1. Lookup the exising `ProvenTxReq` record for its rawTx
   * 2. Insert a new ProvenTx record using properties from `args` and rawTx, yielding a new provenTxId
   * 3. Update ProvenTxReq record with status 'completed' and new provenTxId value (and history of status changed)
   * 4. Unpack notify transactionIds from req and update each transaction's status to 'completed', provenTxId value.
   * 5. Update ProvenTxReq history again to record that transactions have been notified.
   * 6. Return results...
   *
   * Alterations of "typically" to handle:
   */
  updateProvenTxReqWithNewProvenTx(args: UpdateProvenTxReqWithNewProvenTxArgs): Promise<UpdateProvenTxReqWithNewProvenTxResult>;
  /**
   * Reconcile completed proof requests whose transaction fan-out previously
   * failed or whose durable notification state drifted.
   *
   * This is called by TaskReviewStatus so a completed request with
   * `notified = false` is retried and can become eligible for normal purge.
   */
  reconcileCompletedProvenTxReqs(): Promise<{
    log: string;
  }>;
  private prepareProofRecoveryOutputVerdicts;
  private restoreProofRecoveryInputs;
  private restoreProofRecoveryOutputs;
  private restoreTransactionForProof;
  /**
   * Restore every failed local copy of a transaction before proof completion.
   * Also heals the request's notification set from the authoritative txid
   * lookup so TaskUnFail cannot omit a local copy after notification drift.
   */
  unfailTransactionsForProof(req: EntityProvenTxReq, indent?: number, requestUpdate?: Pick<TableProvenTxReqDynamics, 'status' | 'attempts'>): Promise<string>;
  private reconcileProvenTxReqTransactions;
  /**
   * For each spendable output in the 'default' basket of the authenticated user,
   * verify that the output script, satoshis, vout and txid match that of an output
   * still in the mempool of at least one service provider.
   *
   * @returns object with invalidSpendableOutputs array. A good result is an empty array.
   */
  confirmSpendableOutputs(): Promise<{
    invalidSpendableOutputs: TableOutput[];
  }>;
  private checkOutputIsUtxo;
  updateProvenTxReqDynamics(id: number, update: Partial<TableProvenTxReqDynamics>, trx?: TrxToken): Promise<number>;
  extendOutput(o: TableOutput, includeBasket?: boolean, includeTags?: boolean, trx?: TrxToken): Promise<TableOutputX>;
  validateOutputScript(o: TableOutput, trx?: TrxToken): Promise<void>;
}
interface StorageProviderOptions extends StorageReaderWriterOptions {
  chain: Chain;
  feeModel: StorageFeeModel;
  /**
   * Transactions created by this Storage can charge a fee per transaction.
   * A value of zero disables commission fees.
   */
  commissionSatoshis: number;
  /**
   * If commissionSatoshis is greater than zero, must be a valid public key hex string.
   * The actual locking script for each commission will use a public key derived
   * from this key by information stored in the commissions table.
   */
  commissionPubKeyHex?: PubKeyHex;
  /**
   * Optional verifier for server-side action-batch script checks. This Wallet
   * Toolbox extension leaves the BRC-100 wallet interface unchanged.
   */
  scriptVerifier?: SpendVerifierInterface;
}
declare function validateStorageFeeModel(v?: StorageFeeModel): StorageFeeModel;
interface StorageAdminStats {
  requestedBy: string;
  when: string;
  usersDay: number;
  usersWeek: number;
  usersMonth: number;
  usersTotal: number;
  transactionsDay: number;
  transactionsWeek: number;
  transactionsMonth: number;
  transactionsTotal: number;
  txCompletedDay: number;
  txCompletedWeek: number;
  txCompletedMonth: number;
  txCompletedTotal: number;
  txFailedDay: number;
  txFailedWeek: number;
  txFailedMonth: number;
  txFailedTotal: number;
  txAbandonedDay: number;
  txAbandonedWeek: number;
  txAbandonedMonth: number;
  txAbandonedTotal: number;
  txUnprocessedDay: number;
  txUnprocessedWeek: number;
  txUnprocessedMonth: number;
  txUnprocessedTotal: number;
  txSendingDay: number;
  txSendingWeek: number;
  txSendingMonth: number;
  txSendingTotal: number;
  txUnprovenDay: number;
  txUnprovenWeek: number;
  txUnprovenMonth: number;
  txUnprovenTotal: number;
  txUnsignedDay: number;
  txUnsignedWeek: number;
  txUnsignedMonth: number;
  txUnsignedTotal: number;
  txNosendDay: number;
  txNosendWeek: number;
  txNosendMonth: number;
  txNosendTotal: number;
  txNonfinalDay: number;
  txNonfinalWeek: number;
  txNonfinalMonth: number;
  txNonfinalTotal: number;
  txUnfailDay: number;
  txUnfailWeek: number;
  txUnfailMonth: number;
  txUnfailTotal: number;
  satoshisDefaultDay: number;
  satoshisDefaultWeek: number;
  satoshisDefaultMonth: number;
  satoshisDefaultTotal: number;
  satoshisOtherDay: number;
  satoshisOtherWeek: number;
  satoshisOtherMonth: number;
  satoshisOtherTotal: number;
  basketsDay: number;
  basketsWeek: number;
  basketsMonth: number;
  basketsTotal: number;
  labelsDay: number;
  labelsWeek: number;
  labelsMonth: number;
  labelsTotal: number;
  tagsDay: number;
  tagsWeek: number;
  tagsMonth: number;
  tagsTotal: number;
}
interface AdminStatsResult extends StorageAdminStats {
  servicesStats?: ServicesCallHistory;
  monitorStats?: ServicesCallHistory;
}
//#endregion
//#region ../src/storage/WalletStorageManager.d.ts
declare class ManagedStorage {
  storage: WalletStorageProvider;
  isAvailable: boolean;
  isStorageProvider: boolean;
  settings?: TableSettings;
  user?: TableUser;
  constructor(storage: WalletStorageProvider);
}
/**
 * The `WalletStorageManager` class delivers authentication checking storage access to the wallet.
 *
 * If manages multiple `StorageBase` derived storage services: one actice, the rest as backups.
 *
 * Of the storage services, one is 'active' at any one time.
 * On startup, and whenever triggered by the wallet, `WalletStorageManager` runs a syncrhonization sequence:
 *
 * 1. While synchronizing, all other access to storage is blocked waiting.
 * 2. The active service is confirmed, potentially triggering a resolution process if there is disagreement.
 * 3. Changes are pushed from the active storage service to each inactive, backup service.
 *
 * Some storage services do not support multiple writers. `WalletStorageManager` manages wait-blocking write requests
 * for these services.
 */
declare class WalletStorageManager implements WalletStorage {
  /**
   * All configured stores including current active, backups, and conflicting actives.
   */
  _stores: ManagedStorage[];
  /**
   * True if makeAvailable has been run and access to managed stores (active) is allowed
   */
  _isAvailable: boolean;
  /**
   * The current active store which is only enabled if the store's user record activeStorage property matches its settings record storageIdentityKey property
   */
  _active?: ManagedStorage;
  /**
   * Stores to which state is pushed by updateBackups.
   */
  _backups?: ManagedStorage[];
  /**
   * Stores whose user record activeStorage property disagrees with the active store's user record activeStorage property.
   */
  _conflictingActives?: ManagedStorage[];
  /**
   * identityKey is always valid, userId and isActive are valid only if _isAvailable
   */
  _authId: AuthId;
  /**
   * Configured services if any. If valid, shared with stores (which may ignore it).
   */
  _services?: WalletServices;
  /**
   * Creates a new WalletStorageManager with the given identityKey and optional active and backup storage providers.
   *
   * @param identityKey The identity key of the user for whom this wallet is being managed.
   * @param active An optional active storage provider. If not provided, no active storage will be set.
   * @param backups An optional array of backup storage providers. If not provided, no backups will be set.
   */
  constructor(identityKey: string, active?: WalletStorageProvider, backups?: WalletStorageProvider[]);
  isStorageProvider(): boolean;
  isAvailable(): boolean;
  /**
   * The active storage is "enabled" only if its `storageIdentityKey` matches the user's currently selected `activeStorage`,
   * and only if there are no stores with conflicting `activeStorage` selections.
   *
   * A wallet may be created without including the user's currently selected active storage. This allows readonly access to their wallet data.
   *
   * In addition, if there are conflicting `activeStorage` selections among backup storage providers then the active remains disabled.
   */
  get isActiveEnabled(): boolean;
  /**
   * @returns true if at least one WalletStorageProvider has been added.
   */
  canMakeAvailable(): boolean;
  /**
   * This async function must be called after construction and before
   * any other async function can proceed.
   *
   * Runs through `_stores` validating all properties and partitioning across `_active`, `_backups`, `_conflictingActives`.
   *
   * @throws WERR_INVALID_PARAMETER if canMakeAvailable returns false.
   *
   * @returns {TableSettings} from the active storage.
   */
  private ensureStoreAvailable;
  private selectActiveFromStore;
  makeAvailable(): Promise<TableSettings>;
  private verifyActive;
  getAuth(mustBeActive?: boolean): Promise<AuthId>;
  getUserId(): Promise<number>;
  getActive(): WalletStorageProvider;
  getActiveSettings(): TableSettings;
  getActiveUser(): TableUser;
  getActiveStore(): string;
  getActiveStoreName(): string;
  getBackupStores(): string[];
  getConflictingStores(): string[];
  getAllStores(): string[];
  private readonly readerLocks;
  private readonly writerLocks;
  private readonly syncLocks;
  private readonly spLocks;
  private getActiveLock;
  private releaseActiveLock;
  private getActiveForReader;
  private releaseActiveForReader;
  private getActiveForWriter;
  private releaseActiveForWriter;
  private getActiveForSync;
  private releaseActiveForSync;
  private getActiveForStorageProvider;
  private releaseActiveForStorageProvider;
  runAsWriter<R>(writer: (active: WalletStorageWriter) => Promise<R>): Promise<R>;
  runAsReader<R>(reader: (active: WalletStorageReader) => Promise<R>): Promise<R>;
  /**
   *
   * @param sync the function to run with sync access lock
   * @param activeSync from chained sync functions, active storage already held under sync access lock.
   * @returns
   */
  runAsSync<R>(sync: (active: WalletStorageSync) => Promise<R>, activeSync?: WalletStorageSync): Promise<R>;
  runAsStorageProvider<R>(sync: (active: StorageProvider) => Promise<R>): Promise<R>;
  /**
   *
   * @returns true if the active `WalletStorageProvider` also implements `StorageProvider`
   */
  isActiveStorageProvider(): boolean;
  addWalletStorageProvider(provider: WalletStorageProvider): Promise<void>;
  setServices(v: WalletServices): void;
  getServices(): WalletServices;
  getSettings(): TableSettings;
  migrate(storageName: string, storageIdentityKey: string): Promise<string>;
  destroy(): Promise<void>;
  findOrInsertUser(identityKey: string): Promise<{
    user: TableUser;
    isNew: boolean;
  }>;
  abortAction(args: AbortActionArgs): Promise<AbortActionResult>;
  createAction(vargs: Validation.ValidCreateActionArgs): Promise<StorageCreateActionResult>;
  internalizeAction(args: InternalizeActionArgs): Promise<StorageInternalizeActionResult>;
  relinquishCertificate(args: RelinquishCertificateArgs): Promise<number>;
  relinquishOutput(args: RelinquishOutputArgs): Promise<number>;
  processAction(args: StorageProcessActionArgs): Promise<StorageProcessActionResults>;
  getCapabilities(): Promise<StorageCapabilities>;
  beginActionBatch(args: BeginActionBatchArgs): Promise<BeginActionBatchResult>;
  extendActionBatch(args: ExtendActionBatchArgs): Promise<ExtendActionBatchResult>;
  renewActionBatch(batchId: string): Promise<RenewActionBatchResult>;
  prepareActionBatchCommit(manifest: ActionBatchManifest): Promise<PrepareActionBatchCommitResult>;
  putActionBatchBlob(args: PutActionBatchBlobArgs): Promise<void>;
  putActionBatchPack(args: PutActionBatchPackArgs): Promise<void>;
  commitActionBatch(manifest: ActionBatchManifest): Promise<CommitActionBatchResult>;
  commitActionBatchByDigest(args: CommitActionBatchByDigestArgs): Promise<CommitActionBatchResult>;
  abortActionBatch(batchId: string): Promise<AbortActionBatchResult>;
  insertCertificate(certificate: TableCertificate): Promise<number>;
  listActions(vargs: Validation.ValidListActionsArgs): Promise<ListActionsResult>;
  listCertificates(args: Validation.ValidListCertificatesArgs): Promise<ListCertificatesResult>;
  listOutputs(vargs: Validation.ValidListOutputsArgs): Promise<ListOutputsResult>;
  findCertificates(args: FindCertificatesArgs): Promise<TableCertificateX[]>;
  findOutputBaskets(args: FindOutputBasketsArgs): Promise<TableOutputBasket[]>;
  findOutputs(args: FindOutputsArgs): Promise<TableOutput[]>;
  findProvenTxReqs(args: FindProvenTxReqsArgs): Promise<TableProvenTxReq[]>;
  /**
   * For each proven_txs record currently sourcing its transaction merkle proof from the given deactivated header,
   * attempt to reprove the transaction against the current chain,
   * updating the proven_txs record if a new valid proof is found.
   *
   * @param deactivatedHash An orphaned header than may have served as a proof source for proven_txs records.
   * @returns
   */
  reproveHeader(deactivatedHash: string): Promise<ReproveHeaderResult>;
  /**
   * For all proven_txs records at the given height currently tied to the given stale merkleRoot,
   * attempt to reprove them against the current chain and update proof data if new valid proofs are found.
   *
   * This is intended for backup auditing of recent heights after the primary reorg event path has run.
   */
  reproveHeightMerkleRoot(height: number, staleMerkleRoot: string): Promise<ReproveHeaderResult>;
  /**
   * Attempt to reprove the transaction against the current chain,
   * If a new valid proof is found and noUpdate is not true,
   * update the proven_txs record with new block and merkle proof data.
   * If noUpdate is true, the update to be applied is available in the returned result.
   *
   * @param ptx proven_txs record to reprove
   * @param noUpdate
   * @returns
   */
  private evaluateNewMerkleLeaf;
  reproveProven(ptx: TableProvenTx, noUpdate?: boolean): Promise<ReproveProvenResult>;
  syncFromReader(identityKey: string, reader: WalletStorageSyncReader, activeSync?: WalletStorageSync, log?: string): Promise<{
    inserts: number;
    updates: number;
    log: string;
  }>;
  syncToWriter(auth: AuthId, writer: WalletStorageProvider, activeSync?: WalletStorageSync, log?: string, progLog?: (s: string) => string): Promise<{
    inserts: number;
    updates: number;
    log: string;
  }>;
  updateBackups(activeSync?: WalletStorageSync, progLog?: (s: string) => string): Promise<string>;
  /**
   * Updates backups and switches to new active storage provider from among current backup providers.
   *
   * Also resolves conflicting actives.
   *
   * @param storageIdentityKey of current backup storage provider that is to become the new active provider.
   */
  setActive(storageIdentityKey: string, progLog?: (s: string) => string): Promise<string>;
  getStoreEndpointURL(store: ManagedStorage): string | undefined;
  getStores(): WalletStorageInfo[];
}
interface VerifyAndRepairBeefResult {
  isStructurallyValid: boolean;
  originalRoots: Record<number, string>;
  invalidRoots: Record<number, {
    root: string;
    reproveResults: ReproveHeaderResult;
  }>;
  verifiedBeef?: Beef;
}
//#endregion
//#region ../src/storage/StorageSyncReader.d.ts
/**
 * The `StorageSyncReader` non-abstract class must be used when authentication checking access to the methods of a `StorageBaseReader` is required.
 *
 * Constructed from an `auth` object that must minimally include the authenticated user's identityKey,
 * and the `StorageBaseReader` to be protected.
 */
declare class StorageSyncReader implements WalletStorageSyncReader {
  auth: AuthId;
  storage: StorageReader;
  constructor(auth: AuthId, storage: StorageReader);
  makeAvailable(): Promise<TableSettings>;
  destroy(): Promise<void>;
  getSyncChunk(args: RequestSyncChunkArgs): Promise<SyncChunk>;
}
//#endregion
//#region ../src/storage/remoting/StorageClientBase.d.ts
interface StorageClientOptions {
  /**
   * Send compact tagged binary request values after the server advertises
   * support. Leave disabled during rolling deployments where an endpoint may
   * still route requests to legacy server instances.
   */
  binaryRequests?: boolean;
  /**
   * Optional vendor-neutral tracing. Disabled unless an enabled sink is
   * supplied. Request parameters and response payloads are never emitted.
   */
  telemetry?: TelemetryConfig;
}
/**
 * Abstract base class shared by `StorageClient` and `StorageMobile`.
 *
 * Contains all `WalletStorageProvider` method implementations and entity-validation
 * helpers. Subclasses only need to provide `rpcCall`, which differs between
 * the full (logger-aware) and mobile (lightweight) variants.
 */
declare abstract class StorageClientBase implements WalletStorageProvider {
  readonly endpointUrl: string;
  protected readonly authClient: AuthFetch;
  protected nextId: number;
  protected serverSupportsBinary: boolean;
  protected readonly binaryRequests: boolean;
  protected readonly telemetry: Telemetry;
  settings?: TableSettings;
  constructor(wallet: WalletInterface, endpointUrl: string, options?: StorageClientOptions);
  protected traceRpcCall<T>(method: string, params: unknown[], callback: (span?: TelemetrySpan) => Promise<T>): Promise<T>;
  protected traceRpcStep<T>(name: string, parent: TelemetrySpan | undefined, callback: (span?: TelemetrySpan) => Promise<T> | T, attributes?: Readonly<Record<string, unknown>>): Promise<T>;
  /**
   * The `StorageClient` implements the `WalletStorageProvider` interface.
   * It does not implement the lower level `StorageProvider` interface.
   *
   * @returns false
   */
  isStorageProvider(): boolean;
  /**
   * Make a JSON-RPC call to the remote server.
   * Implemented differently by each subclass (with or without logger support).
   * @param method The WalletStorage method name to call.
   * @param params The array of parameters to pass to the method in order.
   */
  protected abstract rpcCall<T>(method: string, params: unknown[]): Promise<T>;
  /**
   * @returns true once storage `TableSettings` have been retreived from remote storage.
   */
  isAvailable(): boolean;
  /**
   * @returns remote storage `TableSettings` if they have been retreived by `makeAvailable`.
   * @throws WERR_INVALID_OPERATION if `makeAvailable` has not yet been called.
   */
  getSettings(): TableSettings;
  /**
   * Must be called prior to making use of storage.
   * Retreives `TableSettings` from remote storage provider.
   * @returns remote storage `TableSettings`
   */
  makeAvailable(): Promise<TableSettings>;
  /**
   * Called to cleanup resources when no further use of this object will occur.
   */
  destroy(): Promise<void>;
  /**
   * Requests schema migration to latest.
   * Typically remote storage will ignore this request.
   * @param storageName Unique human readable name for remote storage if it does not yet exist.
   * @param storageIdentityKey Unique identity key for remote storage if it does not yet exist.
   * @returns current schema migration identifier
   */
  migrate(storageName: string, _storageIdentityKey: string): Promise<string>;
  /**
   * Remote storage does not offer `Services` to remote clients.
   * @throws WERR_INVALID_OPERATION
   */
  getServices(): WalletServices;
  /**
   * Ignored. Remote storage cannot share `Services` with remote clients.
   */
  setServices(_v: WalletServices): void;
  /**
   * Storage level processing for wallet `internalizeAction`.
   * Updates internalized outputs in remote storage.
   * Triggers proof validation of containing transaction.
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args Original wallet `internalizeAction` arguments.
   * @returns `internalizeAction` results
   */
  internalizeAction(auth: AuthId, args: InternalizeActionArgs): Promise<StorageInternalizeActionResult>;
  /**
   * Storage level processing for wallet `createAction`.
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args Validated extension of original wallet `createAction` arguments.
   * @returns `StorageCreateActionResults` supporting additional wallet processing to yield `createAction` results.
   */
  createAction(auth: AuthId, args: Validation.ValidCreateActionArgs): Promise<StorageCreateActionResult>;
  /**
   * Storage level processing for wallet `createAction` and `signAction`.
   *
   * Handles remaining storage tasks once a fully signed transaction has been completed. This is common to both `createAction` and `signAction`.
   *
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args `StorageProcessActionArgs` convey completed signed transaction to storage.
   * @returns `StorageProcessActionResults` supporting final wallet processing to yield `createAction` or `signAction` results.
   */
  processAction(auth: AuthId, args: StorageProcessActionArgs): Promise<StorageProcessActionResults>;
  getCapabilities(): Promise<StorageCapabilities>;
  beginActionBatch(auth: AuthId, args: BeginActionBatchArgs): Promise<BeginActionBatchResult>;
  extendActionBatch(auth: AuthId, args: ExtendActionBatchArgs): Promise<ExtendActionBatchResult>;
  renewActionBatch(auth: AuthId, batchId: string): Promise<RenewActionBatchResult>;
  prepareActionBatchCommit(auth: AuthId, manifest: ActionBatchManifest): Promise<PrepareActionBatchCommitResult>;
  putActionBatchBlob(auth: AuthId, args: PutActionBatchBlobArgs): Promise<void>;
  putActionBatchPack(_auth: AuthId, args: PutActionBatchPackArgs): Promise<void>;
  commitActionBatch(auth: AuthId, manifest: ActionBatchManifest): Promise<CommitActionBatchResult>;
  commitActionBatchByDigest(auth: AuthId, args: CommitActionBatchByDigestArgs): Promise<CommitActionBatchResult>;
  abortActionBatch(auth: AuthId, batchId: string): Promise<AbortActionBatchResult>;
  /**
   * Aborts an action by `reference` string.
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args original wallet `abortAction` args.
   * @returns `abortAction` result.
   */
  abortAction(auth: AuthId, args: AbortActionArgs): Promise<AbortActionResult>;
  /**
   * Used to both find and initialize a new user by identity key.
   * It is up to the remote storage whether to allow creation of new users by this method.
   * @param identityKey of the user.
   * @returns `TableUser` for the user and whether a new user was created.
   */
  findOrInsertUser(identityKey: string): Promise<{
    user: TableUser;
    isNew: boolean;
  }>;
  /**
   * Used to both find and insert a `TableSyncState` record for the user to track wallet data replication across storage providers.
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param storageName the name of the remote storage being sync'd
   * @param storageIdentityKey the identity key of the remote storage being sync'd
   * @returns `TableSyncState` and whether a new record was created.
   */
  findOrInsertSyncStateAuth(auth: AuthId, storageIdentityKey: string, storageName: string): Promise<{
    syncState: TableSyncState;
    isNew: boolean;
  }>;
  /**
   * Inserts a new certificate with fields and keyring into remote storage.
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param certificate the certificate to insert.
   * @returns record Id of the inserted `TableCertificate` record.
   */
  insertCertificateAuth(auth: AuthId, certificate: TableCertificateX): Promise<number>;
  /**
   * Storage level processing for wallet `listActions`.
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args Validated extension of original wallet `listActions` arguments.
   * @returns `listActions` results.
   */
  listActions(auth: AuthId, vargs: Validation.ValidListActionsArgs): Promise<ListActionsResult>;
  /**
   * Storage level processing for wallet `listOutputs`.
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args Validated extension of original wallet `listOutputs` arguments.
   * @returns `listOutputs` results.
   */
  listOutputs(auth: AuthId, vargs: Validation.ValidListOutputsArgs): Promise<ListOutputsResult>;
  /**
   * Storage level processing for wallet `listCertificates`.
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args Validated extension of original wallet `listCertificates` arguments.
   * @returns `listCertificates` results.
   */
  listCertificates(auth: AuthId, vargs: Validation.ValidListCertificatesArgs): Promise<ListCertificatesResult>;
  /**
   * Find user certificates, optionally with fields.
   *
   * This certificate retrieval method supports internal wallet operations.
   * Field values are stored and retrieved encrypted.
   *
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args `FindCertificatesArgs` determines which certificates to retrieve and whether to include fields.
   * @returns array of certificates matching args.
   */
  findCertificatesAuth(auth: AuthId, args: FindCertificatesArgs): Promise<TableCertificateX[]>;
  /**
   * Find output baskets.
   *
   * This retrieval method supports internal wallet operations.
   *
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args `FindOutputBasketsArgs` determines which baskets to retrieve.
   * @returns array of output baskets matching args.
   */
  findOutputBasketsAuth(auth: AuthId, args: FindOutputBasketsArgs): Promise<TableOutputBasket[]>;
  /**
   * Find outputs.
   *
   * This retrieval method supports internal wallet operations.
   *
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args `FindOutputsArgs` determines which outputs to retrieve.
   * @returns array of outputs matching args.
   */
  findOutputsAuth(auth: AuthId, args: FindOutputsArgs): Promise<TableOutput[]>;
  /**
   * Find requests for transaction proofs.
   *
   * This retrieval method supports internal wallet operations.
   *
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args `FindProvenTxReqsArgs` determines which proof requests to retrieve.
   * @returns array of proof requests matching args.
   */
  findProvenTxReqs(args: FindProvenTxReqsArgs): Promise<TableProvenTxReq[]>;
  /**
   * Relinquish a certificate.
   *
   * For storage supporting replication records must be kept of deletions. Therefore certificates are marked as deleted
   * when relinquished, and no longer returned by `listCertificates`, but are still retained by storage.
   *
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args original wallet `relinquishCertificate` args.
   */
  relinquishCertificate(auth: AuthId, args: RelinquishCertificateArgs): Promise<number>;
  /**
   * Relinquish an output.
   *
   * Relinquishing an output removes the output from whatever basket was tracking it.
   *
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param args original wallet `relinquishOutput` args.
   */
  relinquishOutput(auth: AuthId, args: RelinquishOutputArgs): Promise<number>;
  /**
   * Process a "chunk" of replication data for the user.
   *
   * The normal data flow is for the active storage to push backups as a sequence of data chunks to backup storage providers.
   *
   * @param args a copy of the replication request args that initiated the sequence of data chunks.
   * @param chunk the current data chunk to process.
   * @returns whether processing is done, counts of inserts and udpates, and related progress tracking properties.
   */
  processSyncChunk(args: RequestSyncChunkArgs, chunk: SyncChunk): Promise<ProcessSyncChunkResult>;
  /**
   * Request a "chunk" of replication data for a specific user and storage provider.
   *
   * The normal data flow is for the active storage to push backups as a sequence of data chunks to backup storage providers.
   * Also supports recovery where non-active storage can attempt to merge available data prior to becoming active.
   *
   * @param args that identify the non-active storage which will receive replication data and constrains the replication process.
   * @returns the next "chunk" of replication data
   */
  getSyncChunk(args: RequestSyncChunkArgs): Promise<SyncChunk>;
  /**
   * Handles the data received when a new transaction proof is found in response to an outstanding request for proof data:
   *
   *   - Creates a new `TableProvenTx` record.
   *   - Notifies all user transaction records of the new status.
   *   - Updates the proof request record to 'completed' status which enables delayed deletion.
   *
   * @param args proof request and new transaction proof data
   * @returns results of updates
   */
  updateProvenTxReqWithNewProvenTx(args: UpdateProvenTxReqWithNewProvenTxArgs): Promise<UpdateProvenTxReqWithNewProvenTxResult>;
  /**
   * Ensures up-to-date wallet data replication to all configured backup storage providers,
   * then promotes one of the configured backups to active,
   * demoting the current active to new backup.
   *
   * @param auth Identifies client by identity key and the storage identity key of their currently active storage.
   * This must match the `AuthFetch` identity securing the remote conneciton.
   * @param newActiveStorageIdentityKey which must be a currently configured backup storage provider.
   */
  setActive(auth: AuthId, newActiveStorageIdentityKey: string): Promise<number>;
  /** @see {@link validateDate} */
  validateDate(date: Date | string | number): Date;
  /**
   * Helper to force uniform behavior across database engines.
   * Use to process all individual records with time stamps retreived from database.
   * @see {@link validateEntity}
   */
  validateEntity<T extends EntityTimeStamp>(entity: T, dateFields?: string[]): T;
  /**
   * Helper to force uniform behavior across database engines.
   * Use to process all arrays of records with time stamps retreived from database.
   * @returns input `entities` array with contained values validated.
   * @see {@link validateEntities}
   */
  validateEntities<T extends EntityTimeStamp>(entities: T[], dateFields?: string[]): T[];
}
//#endregion
//#region ../src/storage/remoting/StorageMobile.d.ts
/**
 * `StorageClient` (mobile variant) implements the `WalletStorageProvider` interface which allows it to
 * serve as a BRC-100 wallet's active storage.
 *
 * Internally, it uses JSON-RPC over HTTPS to make requests of a remote server.
 * Typically this server uses the `StorageServer` class to implement the service.
 *
 * This mobile variant omits the full logger support present in `StorageClient` to keep
 * the bundle lean for mobile / browser environments.
 *
 * For details of the API implemented, follow the "See also" link for the `WalletStorageProvider` interface.
 */
declare class StorageClient extends StorageClientBase {
  constructor(wallet: WalletInterface, endpointUrl: string, options?: StorageClientOptions);
  /**
   * Make a JSON-RPC call to the remote server.
   * @param method The WalletStorage method name to call.
   * @param params The array of parameters to pass to the method in order.
   */
  protected rpcCall<T>(method: string, params: unknown[]): Promise<T>;
}
//#endregion
//#region ../src/storage/portable/index.d.ts
type JsonPrimitive = string | number | boolean;
type JsonValue = JsonPrimitive | JsonValue[] | {
  [key: string]: JsonValue;
};
type PortableRow = Record<string, JsonValue>;
interface BRC38Tables {
  provenTxs: PortableRow[];
  provenTxReqs: PortableRow[];
  outputBaskets: PortableRow[];
  transactions: PortableRow[];
  commissions: PortableRow[];
  outputs: PortableRow[];
  outputTags: PortableRow[];
  outputTagMaps: PortableRow[];
  txLabels: PortableRow[];
  txLabelMaps: PortableRow[];
  certificates: PortableRow[];
  certificateFields: PortableRow[];
  syncStates: PortableRow[];
}
interface BRC38WalletData {
  brc: 38;
  title: 'User Wallet Data Format';
  formatVersion: 1;
  exportedAt: string;
  sourceStorage: PortableRow;
  user: PortableRow;
  tables: BRC38Tables;
}
interface BRC38ImportOptions {
  mode: 'merge' | 'restore';
}
interface BRC38ImportResult {
  mode: 'merge' | 'restore';
  identityKey: string;
  userId: number;
  inserts: number;
  updates: number;
}
interface BRC39Options {
  iterations?: number;
  memoryKiB?: number;
  parallelism?: number;
}
declare function exportBRC38(storage: StorageProvider, identityKey: string): Promise<BRC38WalletData>;
declare function exportBRC38Json(storage: StorageProvider, identityKey: string): Promise<string>;
declare function parseBRC38Json(json: string): BRC38WalletData;
declare function importBRC38(storage: StorageProvider, documentOrJson: BRC38WalletData | string, options: BRC38ImportOptions): Promise<BRC38ImportResult>;
declare function exportBRC39(storage: StorageProvider, identityKey: string, password: string, options?: BRC39Options): Promise<number[]>;
declare function importBRC39(storage: StorageProvider, bytes: number[] | Uint8Array, password: string, options: BRC38ImportOptions): Promise<BRC38ImportResult>;
declare function encryptBRC39(documentOrJson: BRC38WalletData | string, password: string, options?: BRC39Options): Promise<number[]>;
declare function decryptBRC39(bytes: number[] | Uint8Array, password: string): Promise<BRC38WalletData>;
//#endregion
//#region ../src/storage/methods/ListActionsSpecOp.d.ts
interface ListActionsSpecOp {
  name: string;
  /**
   * undefined to intercept no labels from vargs,
   * empty array to intercept all labels,
   * or an explicit array of labels to intercept.
   */
  labelsToIntercept?: string[];
  setStatusFilter?: () => TransactionStatus[];
  postProcess?: (s: StorageProvider, auth: AuthId, vargs: Validation.ValidListActionsArgs, specOpLabels: string[], txs: Array<Partial<TableTransaction>>) => Promise<void>;
}
declare function partitionActionLabels(ordinaryLabels: string[]): {
  specOp: ListActionsSpecOp | undefined;
  specOpLabels: string[];
  labels: string[];
};
declare const getLabelToSpecOp: () => Record<string, ListActionsSpecOp>;
//#endregion
//#region ../src/storage/methods/ListOutputsSpecOp.d.ts
interface ListOutputsSpecOp {
  name: string;
  useBasket?: string;
  ignoreLimit?: boolean;
  includeOutputScripts?: boolean;
  includeSpent?: boolean;
  /**
   * If true, and supported by storage, maximum performance optimization, computing balance done in the query itself.
   */
  totalOutputsIsSumOfSatoshis?: boolean;
  /** Restrict the operation to wallet-managed, BRC-29-signable change. */
  managedChangeOnly?: boolean;
  resultFromTags?: (s: StorageProvider, auth: AuthId, vargs: Validation.ValidListOutputsArgs, specOpTags: string[]) => Promise<ListOutputsResult>;
  resultFromOutputs?: (s: StorageProvider, auth: AuthId, vargs: Validation.ValidListOutputsArgs, specOpTags: string[], outputs: TableOutput[]) => Promise<ListOutputsResult>;
  filterOutputs?: (s: StorageProvider, auth: AuthId, vargs: Validation.ValidListOutputsArgs, specOpTags: string[], outputs: TableOutput[]) => Promise<TableOutput[]>;
  /**
   * undefined to intercept no tags from vargs,
   * empty array to intercept all tags,
   * or an explicit array of tags to intercept.
   */
  tagsToIntercept?: string[];
  /**
   * How many positional tags to intercept.
   */
  tagsParamsCount?: number;
}
/**
 * Check basket and tags arguments passed to listOutputs to determine if they trigger a special operation execution mode.
 * @param basket
 * @param tags
 * @returns
 */
declare function getListOutputsSpecOp(basket: string, tags: string[]): {
  specOp: ListOutputsSpecOp | undefined;
  basket?: string;
  tags: string[];
};
//#endregion
//#region ../src/services/chaintracker/chaintracks/util/HeightRange.d.ts
interface HeightRangeApi {
  minHeight: number;
  maxHeight: number;
}
interface HeightRanges {
  bulk: HeightRange;
  live: HeightRange;
}
/**
 * Represents a range of block heights.
 *
 * Operations support integrating contiguous batches of headers,
 */
declare class HeightRange implements HeightRangeApi {
  minHeight: number;
  maxHeight: number;
  constructor(minHeight: number, maxHeight: number);
  /**
   * All ranges where maxHeight is less than minHeight are considered empty.
   * The canonical empty range is (0, -1).
   */
  static readonly empty: HeightRange;
  /**
   * @returns true iff minHeight is greater than maxHeight.
   */
  get isEmpty(): boolean;
  /**
   * @param headers an array of objects with a non-negative integer `height` property.
   * @returns range of height values from the given headers, or the empty range if there are no headers.
   */
  static from(headers: BlockHeader[]): HeightRange;
  /**
   * @returns the number of heights in the range, or 0 if the range is empty.
   */
  get length(): number;
  /**
   * @returns an easy to read string representation of the height range.
   */
  toString(): string;
  /**
   * @param range HeightRange or single height value.
   * @returns true if `range` is entirely within this range.
   */
  contains(range: HeightRange | number): boolean;
  /**
   * Return the intersection with another height range.
   *
   * Intersection with an empty range is always empty.
   *
   * The result is always a single, possibly empty, range.
   * @param range
   * @returns
   */
  intersect(range: HeightRange): HeightRange;
  /**
   * Return the union with another height range.
   *
   * Only valid if the two ranges overlap or touch, or one is empty.
   *
   * Throws an error if the union would create two disjoint ranges.
   *
   * @param range
   * @returns
   */
  union(range: HeightRange): HeightRange;
  /**
   * Returns `range` subtracted from this range.
   *
   * Throws an error if the subtraction would create two disjoint ranges.
   *
   * @param range
   * @returns
   */
  subtract(range: HeightRange): HeightRange;
  /**
   * If `range` is not empty and this is not empty, returns a new range minHeight
   * replaced by to range.maxHeight + 1.
   *
   * Otherwise returns a copy of this range.
   *
   * This returns the portion of this range that is strictly above `range`.
   */
  above(range: HeightRange): HeightRange;
  /**
   * Return a copy of this range.
   */
  copy(): HeightRange;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Api/ChaintracksFsApi.d.ts
/**
 * Supports access to named data storage (file like).
 */
interface ChaintracksReadableFileApi {
  path: string;
  close(): Promise<void>;
  /**
   * Returns the length of the data storage in bytes.
   */
  getLength(): Promise<number>;
  /**
   *
   * @param length requested length to be returned, may return less than requested.
   * @param offset starting offset in the existing data storage to read from, defaults to 0.
   */
  read(length?: number, offset?: number): Promise<Uint8Array>;
}
/**
 * Supports access and appending data to new or existing named data storage.
 * New data is always appended to the end of existing data.
 */
interface ChaintracksAppendableFileApi extends ChaintracksReadableFileApi {
  /**
   * @param data data to add to the end of existing data.
   */
  append(data: Uint8Array): Promise<void>;
}
/**
 * Supports creation or re-creation of named data storage from position 0.
 * Any pre-existing data is initially removed.
 * Does not support reading existing data.
 */
interface ChaintracksWritableFileApi {
  path: string;
  close(): Promise<void>;
  /**
   * @param data data to add to the end of existing data.
   */
  append(data: Uint8Array): Promise<void>;
}
/**
 * Supports file-like access to named data storage.
 *
 * Only minimal functionality required by Chaintracks is supported.
 */
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;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Api/ChaintracksFetchApi.d.ts
/**
 * Provides a simplified interface based on the @bsv/sdk `HttpClient` class
 * with just the methods necesary for most Chaintracks operations.
 *
 * The primary purpose is to isolate and centralize external package dependency.
 *
 * Specific ingestors are free to use other means for access.
 *
 * The `ChaintracksFetch` class implements this interface.
 */
interface ChaintracksFetchApi {
  httpClient: HttpClient;
  download(url: string): Promise<Uint8Array>;
  fetchJson<R>(url: string): Promise<R>;
  pathJoin(baseUrl: string, subpath: string): string;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/util/BulkFileDataReader.d.ts
declare class BulkFileDataReader {
  readonly manager: BulkFileDataManager;
  readonly range: HeightRange;
  readonly maxBufferSize: number;
  nextHeight: number;
  constructor(manager: BulkFileDataManager, range: HeightRange, maxBufferSize: number);
  /**
   * Returns the Buffer of block headers from the given `file` for the given `range`.
   * If `range` is undefined, the file's full height range is read.
   * The returned Buffer will only contain headers in `file` and in `range`
   * @param file
   * @param range
   */
  private readBufferFromFile;
  /**
   * @returns an array containing the next `maxBufferSize` bytes of headers from the files.
   */
  read(): Promise<Uint8Array | undefined>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/util/BulkFileDataManager.d.ts
interface BulkFileDataManagerOptions {
  chain: Chain;
  maxPerFile: number;
  maxRetained?: number;
  fetch?: ChaintracksFetchApi;
  fromKnownSourceUrl?: string;
}
/**
 * Manages bulk file data (typically 8MB chunks of 100,000 headers each).
 *
 * If not cached in memory,
 * optionally fetches data by `sourceUrl` from CDN on demand,
 * optionally finds data by `fileId` in a database on demand,
 * and retains a limited number of files in memory,
 * subject to the optional `maxRetained` limit.
 */
declare class BulkFileDataManager {
  static createDefaultOptions(chain: Chain): BulkFileDataManagerOptions;
  private log;
  private bfds;
  private fileHashToIndex;
  private readonly lock;
  private storage?;
  readonly chain: Chain;
  readonly maxPerFile: number;
  readonly fetch?: ChaintracksFetchApi;
  readonly maxRetained?: number;
  readonly fromKnownSourceUrl?: string;
  constructor(options: BulkFileDataManagerOptions | Chain);
  deleteBulkFiles(): Promise<void>;
  private deleteBulkFilesNoLock;
  /**
   * If `bfds` are going to be backed by persistent storage,
   * must be called before making storage available.
   *
   * Synchronizes bfds and storage files, after which this manager maintains sync.
   * There should be no changes to bulk files by direct access to storage bulk file methods.
   */
  setStorage(storage: ChaintracksStorageBulkFileApi, log: (...args: any[]) => void): Promise<void>;
  private setStorageNoLock;
  heightRangesFromBulkFiles(files: BulkHeaderFileInfo[]): {
    all: HeightRange;
    cdn: HeightRange;
    incremental: HeightRange;
  };
  createReader(range?: HeightRange, maxBufferSize?: number): Promise<BulkFileDataReader>;
  updateFromUrl(cdnUrl: string): Promise<void>;
  merge(files: BulkHeaderFileInfo[]): Promise<BulkFileDataManagerMergeResult>;
  private mergeNoLock;
  private mergeIncremental;
  toLogString(what?: BulkFileDataManagerMergeResult | BulkFileData[] | BulkHeaderFileInfo[]): string;
  mergeIncrementalBlockHeaders(newBulkHeaders: BlockHeader[], incrementalChainWork?: string): Promise<void>;
  getBulkFiles(keepData?: boolean): Promise<BulkHeaderFileInfo[]>;
  getHeightRange(): Promise<HeightRange>;
  getDataFromFile(file: BulkHeaderFileInfo, offset?: number, length?: number): Promise<Uint8Array | undefined>;
  private getDataFromFileNoLock;
  findHeaderForHeightOrUndefined(height: number): Promise<BlockHeader | undefined>;
  getFileForHeight(height: number): Promise<BulkHeaderFileInfo | undefined>;
  private getBfdForHeight;
  private getLastBfd;
  getLastFile(fromEnd?: number): Promise<BulkHeaderFileInfo | undefined>;
  private getLastFileNoLock;
  private getDataByFileHash;
  private getDataByFileId;
  private validateFileInfo;
  private validateBfdData;
  private validateBfdHeaders;
  ReValidate(): Promise<void>;
  private ReValidateNoLock;
  private validateBfdForAdd;
  private add;
  private replaceBfdAtIndex;
  /**
   * Updating an existing file occurs in two specific contexts:
   *
   * 1. CDN Update: CDN files of a specific `maxPerFile` series typically ends in a partial file
   * which may periodically add more headers until the next file is started.
   * If the CDN update is the second to last file (followed by an incremental file),
   * then the incremental file is updated or deleted and also returned as the result (with a count of zero if deleted).
   *
   * 2. Incremental Update: The last bulk file is almost always an "incremental" file
   * which is not limited by "maxPerFile" and holds all non-CDN bulk headers.
   * If is updated with new bulk headers which come either from non CDN ingestors or from live header migration to bulk.
   *
   * Updating preserves the following properties:
   *
   * - Any existing headers following this update are preserved and must form an unbroken chain.
   * - There can be at most one incremental file and it must be the last file.
   * - The update start conditions (height, prevHash, prevChainWork) must match an existing file which may be either CDN or internal.
   * - The update fileId must match, it may be undefind.
   * - The fileName does not need to match.
   * - The incremental file must always have fileName "incremental" and sourceUrl must be undefined.
   * - The update count must be greater than 0.
   * - The update count must be greater than current count for CDN to CDN update.
   *
   * @param update new validated BulkFileData to update.
   * @param hbf corresponding existing BulkFileData to update.
   */
  private update;
  private resolveUpdatePlan;
  private resolveLastFileUpdate;
  private resolvePenultimateFileUpdate;
  private persistUpdate;
  private recordUpdateResults;
  private dropLastBulkFile;
  /**
   * Remove work (and headers) from `truncate` that now exists in `update`.
   * There are two scenarios:
   * 1. `replaced` is undefined: update is a CDN file that splits an incremental file that must be truncated.
   * 2. `replaced` is valid: update is a CDN update that replaced an existing CDN file and splits an incremental file that must be truncated.
   * @param update the new CDN update file.
   * @param truncate the incremental file to be truncated (losing work which now exists in `update`).
   * @param replaced the existing CDN file that was replaced by `update` (if any).
   */
  private shiftWork;
  /**
   *
   * @param bfd
   * @returns
   */
  private ensureData;
  private ensureMaxRetained;
  exportHeadersToFs(toFs: ChaintracksFsApi, toHeadersPerFile: number, toFolder: string, sourceUrl?: string, maxHeight?: number): Promise<void>;
}
interface BulkFileData extends BulkHeaderFileInfo {
  mru: number;
  fileHash: string;
}
declare function selectBulkHeaderFiles(files: BulkHeaderFileInfo[], chain: Chain, maxPerFile: number): BulkHeaderFileInfo[];
interface BulkFileDataManagerMergeResult {
  unchanged: BulkHeaderFileInfo[];
  inserted: BulkHeaderFileInfo[];
  updated: BulkHeaderFileInfo[];
  dropped: BulkHeaderFileInfo[];
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Storage/ChaintracksStorageBase.d.ts
/**
 * Required interface methods of a Chaintracks Storage Engine implementation.
 */
declare abstract class ChaintracksStorageBase implements ChaintracksStorageQueryApi, ChaintracksStorageIngestApi {
  static createStorageBaseOptions(chain: Chain): ChaintracksStorageBaseOptions;
  log: (...args: any[]) => void;
  chain: Chain;
  liveHeightThreshold: number;
  reorgHeightThreshold: number;
  bulkMigrationChunkSize: number;
  batchInsertLimit: number;
  isAvailable: boolean;
  hasMigrated: boolean;
  bulkManager: BulkFileDataManager;
  constructor(options: ChaintracksStorageBaseOptions);
  shutdown(): Promise<void>;
  makeAvailable(): Promise<void>;
  migrateLatest(): Promise<void>;
  dropAllData(): Promise<void>;
  abstract deleteLiveBlockHeaders(): Promise<void>;
  abstract deleteOlderLiveBlockHeaders(maxHeight: number): Promise<number>;
  abstract findChainTipHeader(): Promise<LiveBlockHeader>;
  abstract findChainTipHeaderOrUndefined(): Promise<LiveBlockHeader | undefined>;
  abstract findLiveHeaderForBlockHash(hash: string): Promise<LiveBlockHeader | null>;
  abstract findLiveHeaderForHeaderId(headerId: number): Promise<LiveBlockHeader>;
  abstract findLiveHeaderForHeight(height: number): Promise<LiveBlockHeader | null>;
  abstract findLiveHeaderForMerkleRoot(merkleRoot: string): Promise<LiveBlockHeader | null>;
  abstract findLiveHeightRange(): Promise<HeightRange>;
  abstract findMaxHeaderId(): Promise<number>;
  abstract liveHeadersForBulk(count: number): Promise<LiveBlockHeader[]>;
  abstract getLiveHeaders(range: HeightRange): Promise<LiveBlockHeader[]>;
  /**
   * @param header Header to attempt to add to live storage.
   * @returns details of conditions found attempting to insert header
   */
  abstract insertHeader(header: BlockHeader): Promise<InsertHeaderResult>;
  abstract destroy(): Promise<void>;
  getBulkHeaders(range: HeightRange): Promise<Uint8Array>;
  getHeadersUint8Array(height: number, count: number): Promise<Uint8Array>;
  getHeaders(height: number, count: number): Promise<BaseBlockHeader[]>;
  deleteBulkBlockHeaders(): Promise<void>;
  getAvailableHeightRanges(): Promise<{
    bulk: HeightRange;
    live: HeightRange;
  }>;
  private lastActiveMinHeight;
  pruneLiveBlockHeaders(activeTipHeight: number): Promise<void>;
  findChainTipHash(): Promise<string>;
  findChainTipWork(): Promise<string>;
  findChainWorkForBlockHash(hash: string): Promise<string>;
  findBulkFilesHeaderForHeightOrUndefined(height: number): Promise<BlockHeader | undefined>;
  findHeaderForHeightOrUndefined(height: number): Promise<LiveBlockHeader | BlockHeader | undefined>;
  findHeaderForHeight(height: number): Promise<LiveBlockHeader | BlockHeader>;
  isMerkleRootActive(merkleRoot: string): Promise<boolean>;
  findCommonAncestor(header1: LiveBlockHeader, header2: LiveBlockHeader): Promise<LiveBlockHeader>;
  findReorgDepth(header1: LiveBlockHeader, header2: LiveBlockHeader): Promise<number>;
  private nowMigratingLiveToBulk;
  migrateLiveToBulk(count: number, ignoreLimits?: boolean): Promise<void>;
  addBulkHeaders(headers: BlockHeader[], bulkRange: HeightRange, priorLiveHeaders: BlockHeader[]): Promise<BlockHeader[]>;
  private getMinimumBulkHeaderHeight;
  private buildBulkHeaderChains;
  private addHeaderToBulkChains;
  private addBulkHeadersFromBestChain;
  private addLiveHeadersToBulk;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/util/BulkHeaderFile.d.ts
/**
 * Descriptive information about a single bulk header file.
 */
interface BulkHeaderFileInfo {
  /**
   * filename and extension, no path
   */
  fileName: string;
  /**
   * chain height of first header in file
   */
  firstHeight: number;
  /**
   * count of how many headers the file contains. File size must be 80 * count.
   */
  count: number;
  /**
   * prevChainWork is the cummulative chain work up to the first header in this file's data, as a hex string.
   */
  prevChainWork: string;
  /**
   * lastChainWork is the cummulative chain work including the last header in this file's data, as a hex string.
   */
  lastChainWork: string;
  /**
   * previousHash of first header in file in standard hex string block hash encoding
   */
  prevHash: string;
  /**
   * block hash of last header in the file in standard hex string block hash encoding
   */
  lastHash: string | null;
  /**
   * file contents single sha256 hash as base64 string
   */
  fileHash: string | null;
  /**
   * Which chain: 'main' or 'test'
   */
  chain?: Chain;
  data?: Uint8Array;
  /**
   * true iff these properties should be considered pre-validated, including a valid required fileHash of data (when not undefined).
   */
  validated?: boolean;
  /**
   * optional, used for database storage
   */
  fileId?: number;
  /**
   * optional, if valid `${sourceUrl}/${fileName}` is the source of this data.
   */
  sourceUrl?: string;
}
declare abstract class BulkHeaderFile implements BulkHeaderFileInfo {
  chain?: Chain;
  count: number;
  data?: Uint8Array<ArrayBufferLike>;
  fileHash: string | null;
  fileId?: number;
  fileName: string;
  firstHeight: number;
  lastChainWork: string;
  lastHash: string | null;
  prevChainWork: string;
  prevHash: string;
  sourceUrl?: string;
  validated?: boolean;
  constructor(info: BulkHeaderFileInfo);
  abstract readDataFromFile(length: number, offset: number): Promise<Uint8Array | undefined>;
  get heightRange(): HeightRange;
  ensureData(): Promise<Uint8Array>;
  /**
   * Whenever reloading data from a backing store, validated fileHash must be re-verified
   * @returns the sha256 hash of the file's data as base64 string.
   */
  computeFileHash(): Promise<string>;
  releaseData(): Promise<void>;
  toCdnInfo(): BulkHeaderFileInfo;
  toStorageInfo(): BulkHeaderFileInfo;
}
declare class BulkHeaderFileFs extends BulkHeaderFile {
  fs: ChaintracksFsApi;
  rootFolder: string;
  constructor(info: BulkHeaderFileInfo, fs: ChaintracksFsApi, rootFolder: string);
  readDataFromFile(length: number, offset: number): Promise<Uint8Array | undefined>;
  ensureData(): Promise<Uint8Array>;
}
declare class BulkHeaderFileStorage extends BulkHeaderFile {
  storage: ChaintracksStorageBase;
  fetch?: ChaintracksFetchApi | undefined;
  constructor(info: BulkHeaderFileInfo, storage: ChaintracksStorageBase, fetch?: ChaintracksFetchApi | undefined);
  readDataFromFile(length: number, offset: number): Promise<Uint8Array | undefined>;
  ensureData(): Promise<Uint8Array>;
}
/**
 * Describes a collection of bulk block header files.
 */
interface BulkHeaderFilesInfo {
  /**
   * Where this file was fetched or read from.
   */
  rootFolder: string;
  /**
   * Sub-path to this resource on rootFolder
   */
  jsonFilename: string;
  /**
   * Array of information about each bulk block header file.
   */
  files: BulkHeaderFileInfo[];
  /**
   * Maximum number of headers in a single file in this collection of files.
   */
  headersPerFile: number;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Api/ChaintracksStorageApi.d.ts
interface ChaintracksStorageBaseOptions {
  /**
   * Which chain is being tracked: main, test, or stn.
   */
  chain: Chain;
  /**
   * 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.
   */
  liveHeightThreshold: number;
  /**
   * 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.
   */
  reorgHeightThreshold: number;
  /**
   * How many excess "live" headers to accumulate before migrating them as a chunk to the
   * bulk header storage.
   */
  bulkMigrationChunkSize: number;
  /**
   * Maximum number of headers per call to batchInsert
   */
  batchInsertLimit: number;
  /**
   * Controls in memory caching and retrieval of missing bulk header data.
   */
  bulkFileDataManager: BulkFileDataManager | undefined;
}
interface ChaintracksStorageQueryApi {
  log: (...args: any[]) => void;
  /**
   * Returns the active chain tip header
   * Throws an error if there is no tip.
   */
  findChainTipHeader(): Promise<LiveBlockHeader>;
  /**
   * Returns the block hash of the active chain tip.
   */
  findChainTipHash(): Promise<string>;
  /**
   * Returns the active chain tip header or undefined if there is no tip.
   */
  findChainTipHeaderOrUndefined(): Promise<LiveBlockHeader | undefined>;
  /**
   * Returns the chainWork value of the active chain tip
   */
  findChainTipWork(): Promise<string>;
  /**
   * Returns block header for a given block height on active chain.
   * @param hash block hash
   */
  findHeaderForHeight(height: number): Promise<LiveBlockHeader | BlockHeader>;
  /**
   * Returns block header for a given block height on active chain.
   * @param hash block hash
   */
  findHeaderForHeightOrUndefined(height: number): Promise<LiveBlockHeader | BlockHeader | undefined>;
  /**
   * Given two chain tip headers in a chain reorg scenario,
   * return their common ancestor header.
   * @param header1 First header in live part of the chain.
   * @param header2 Second header in live part of the chain.
   */
  findCommonAncestor(header1: LiveBlockHeader, header2: LiveBlockHeader): Promise<LiveBlockHeader>;
  /**
   * This is an original API. Proposed deprecation in favor of `findCommonAncestor`
   * Given two headers that are both chain tips in a reorg scenario, returns
   * the depth of the reorg (the greater of the heights of the two provided
   * headers, minus the height of their last common ancestor)
   */
  findReorgDepth(header1: LiveBlockHeader, header2: LiveBlockHeader): Promise<number>;
  /**
   * Returns true if the given merkleRoot is found in a block header on the active chain.
   * @param merkleRoot of block header
   */
  isMerkleRootActive(merkleRoot: string): Promise<boolean>;
  /**
   * Returns serialized headers as a Uint8Array.
   * Only adds bulk and active live headers.
   *
   * @param height is the minimum header height to return, must be >= zero.
   * @param count height + count - 1 is the maximum header height to return.
   * @returns serialized headers as a Uint8Array.
   */
  getHeadersUint8Array(height: number, count: number): Promise<Uint8Array>;
  /**
   * Returns an array of deserialized headers.
   * Only adds bulk and active live headers.
   *
   * @param height is the minimum header height to return, must be >= zero.
   * @param count height + count - 1 is the maximum header height to return.
   * @returns array of deserialized headers
   */
  getHeaders(height: number, count: number): Promise<BaseBlockHeader[]>;
  /**
   * Returns active `LiveBlockHeaders` with height in the given range.
   *
   * @param range
   * @returns array of active `LiveBlockHeaders`
   */
  getLiveHeaders(range: HeightRange): Promise<LiveBlockHeader[]>;
  /**
   * Returns serialized bulk headers in the given range.
   *
   * @param range
   * @returns serialized headers as a Uint8Array.
   */
  getBulkHeaders(range: HeightRange): Promise<Uint8Array>;
  /**
   * Returns block header for a given block height on active chain.
   * @param hash block hash
   */
  findLiveHeaderForHeight(height: number): Promise<LiveBlockHeader | null>;
  /**
   * Returns block header for a given headerId.
   * Only from the "live" portion of the chain.
   * @param headerId
   */
  findLiveHeaderForHeaderId(headerId: number): Promise<LiveBlockHeader>;
  /**
   * Returns block header for a given block hash.
   * Only from the "live" portion of the chain.
   * Returns null if not found.
   * @param hash block hash
   */
  findLiveHeaderForBlockHash(hash: string): Promise<LiveBlockHeader | null>;
  /**
   * Returns block header for a given merkleRoot.
   * Only from the "live" portion of the chain.
   * @param merkleRoot
   */
  findLiveHeaderForMerkleRoot(merkleRoot: string): Promise<LiveBlockHeader | null>;
  /**
   * Returns the height range of both bulk and live storage.
   * Verifies that the ranges meet these requirements:
   * - Both may be empty.
   * - If bulk is empty, live must be empty or start with height zero.
   * - If bulk is not empty it must start with height zero.
   * - If bulk is not empty and live is not empty, live must start with the height after bulk.
   */
  getAvailableHeightRanges(): Promise<{
    bulk: HeightRange;
    live: HeightRange;
  }>;
  /**
   * @returns The current minimum and maximum height active LiveBlockHeaders in the "live" database.
   */
  findLiveHeightRange(): Promise<HeightRange>;
  /**
   * @returns The maximum headerId value used by existing records or -1 if there are none.
   */
  findMaxHeaderId(): Promise<number>;
  /**
   * Which chain is being tracked: "main" or "test".
   */
  chain: Chain;
  /**
   * How much of recent history is required to be kept in "live" block header storage.
   *
   * Headers with height older than active chain tip height minus `liveHeightThreshold`
   * are not required to be kept in "live" storage and may be migrated to "bulk" storage.
   */
  liveHeightThreshold: number;
  /**
   * How much of recent history must be processed with full validation and reorg support.
   *
   * May be less than `liveHeightThreshold`.
   *
   * Headers with height older than active chain tip height minus ``
   * may use batch processing when ingesting headers.
   */
  reorgHeightThreshold: number;
  /**
   * How many excess "live" headers to accumulate before migrating them as a chunk to the
   * bulk header storage.
   */
  bulkMigrationChunkSize: number;
  /**
   * Maximum number of headers per call to batchInsert
   */
  batchInsertLimit: number;
}
type InsertHeaderResult = {
  /**
   * true only if the new header was inserted
   */
  added: boolean;
  /**
   * true only if the header was not inserted because a matching hash already exists in the database.
   */
  dupe: boolean;
  /**
   * true only if the new header became the active chain tip.
   */
  isActiveTip: boolean;
  /**
   * zero if the insertion of the new header did not cause a reorg.
   * If isActiveTip is true, and priorTip is not the new headers previous header,
   * then the minimum height difference from the common active ancestor to this header (new tip) and priorTip.
   */
  reorgDepth: number;
  /**
   * If `added` is true, this header was the active chain tip before the insert. It may or may not still be the active chain tip after the insert.
   */
  priorTip: LiveBlockHeader | undefined;
  /**
   * If a reorg has occurred, these headers where active and are now deactivated.
   */
  deactivatedHeaders: LiveBlockHeader[];
  /**
   * header's previousHash was not found in database
   */
  noPrev: boolean;
  /**
   * header matching previousHash does not have height - 1
   */
  badPrev: boolean;
  /**
   * an active ancestor was not found in live storage or prev header.
   */
  noActiveAncestor: boolean;
  /**
   * a current chain tip was not found in live storage or prev header.
   */
  noTip: boolean;
};
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>;
}
interface ChaintracksStorageIngestApi {
  log: (...args: any[]) => void;
  /**
   * 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.
   *
   * @param header to insert
   * @param prev if not undefined, the last bulk storage header with total bulk chainWork
   */
  insertHeader(header: BlockHeader, prev?: LiveBlockHeader): Promise<InsertHeaderResult>;
  /**
   * 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.
   * @param activeTipHeight height of active tip after adds
   */
  pruneLiveBlockHeaders(activeTipHeight: number): Promise<void>;
  /**
   * Migrates the oldest `count` LiveBlockHeaders to BulkStorage.
   * BulkStorage must be configured.
   * `count` must not exceed `bulkMigrationChunkSize`.
   * `count` must leave at least `liveHeightThreshold` LiveBlockHeaders.
   *
   * @param 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.
   */
  migrateLiveToBulk(count: number): Promise<void>;
  /**
   * Delete live headers with height less or equal to `maxHeight`
   * after they have been migrated to bulk storage.
   *
   * @param maxHeight delete all records with less or equal `height`
   */
  deleteOlderLiveBlockHeaders(maxHeight: number): Promise<number>;
  /**
   * Async initialization method.
   *
   * May be called prior to other async methods to control when initialization occurs.
   */
  makeAvailable(): Promise<void>;
  /**
   * Migrate storage schema to latest schema changes.
   *
   * Typically invoked automatically by `makeAvailable`.
   */
  migrateLatest(): Promise<void>;
  dropAllData(): Promise<void>;
  /**
   * Release all resources. Makes the instance unusable.
   */
  destroy(): Promise<void>;
}
interface ChaintracksStorageApi extends ChaintracksStorageQueryApi, ChaintracksStorageIngestApi {
  log: (...args: any[]) => void;
  bulkManager: BulkFileDataManager;
  /**
   * Close and release all resources.
   */
  destroy(): Promise<void>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Api/BulkIngestorApi.d.ts
interface BulkIngestorBaseOptions {
  /**
   * The target chain.
   */
  chain: Chain;
  /**
   * Required.
   *
   * The name of the JSON resource to request from CDN which describes currently
   * available bulk block header resources.
   */
  jsonResource: string | undefined;
}
interface BulkIngestorApi {
  /**
   * Close and release all resources.
   */
  shutdown(): Promise<void>;
  /**
   * 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.
   */
  getPresentHeight(): Promise<number | undefined>;
  /**
   * 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.
   *
   * @param before bulk and live range of headers before ingesting any new headers.
   * @param fetchRange range of headers still needed, includes both missing bulk and live headers.
   * @param bulkRange range of bulk headers still needed
   * @param priorLiveHeaders any headers accumulated by prior bulk ingestor(s) that are too recent for bulk storage.
   * @returns new live headers: headers in fetchRange but not in bulkRange
   */
  fetchHeaders(before: HeightRanges, fetchRange: HeightRange, bulkRange: HeightRange, priorLiveHeaders: BlockHeader[]): Promise<BlockHeader[]>;
  /**
   * 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.
   *
   * @param presentHeight current height of the active chain tip, may lag the true value.
   * @param before current bulk and live storage height ranges, either may be empty.
   * @param priorLiveHeaders any headers accumulated by prior bulk ingestor(s) that are too recent for bulk storage.
   * @returns updated priorLiveHeaders including any accumulated by this ingestor
   */
  synchronize(presentHeight: number, before: HeightRanges, priorLiveHeaders: BlockHeader[]): Promise<BulkSyncResult>;
  /**
   * Called before first Synchronize with reference to storage.
   * Components requiring asynchronous setup can override base class implementation.
   * @param storage
   */
  setStorage(storage: ChaintracksStorageApi, log: (...args: any[]) => void): Promise<void>;
  storage(): ChaintracksStorageApi;
}
interface BulkSyncResult {
  liveHeaders: BlockHeader[];
  liveRange: HeightRange;
  done: boolean;
  log: string;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Api/LiveIngestorApi.d.ts
interface LiveIngestorApi {
  /**
   * Close and release all resources.
   */
  shutdown(): Promise<void>;
  getHeaderByHash(hash: string): Promise<BlockHeader | undefined>;
  /**
   * Called before first Synchronize with reference to storage.
   * Components requiring asynchronous setup can override base class implementation.
   * @param storage
   */
  setStorage(storage: ChaintracksStorageApi, log: (...args: any[]) => void): Promise<void>;
  storage(): ChaintracksStorageApi;
  startListening(liveHeaders: BlockHeader[]): Promise<void>;
  stopListening(): void;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Api/ChaintracksApi.d.ts
interface ChaintracksOptions {
  chain: Chain;
  storage?: ChaintracksStorageApi;
  bulkIngestors: BulkIngestorApi[];
  liveIngestors: LiveIngestorApi[];
  /**
   * Maximum number of missing headers to pursue when listening for new headers.
   * Normally, large numbers of missing headers are handled by bulk ingestors.
   */
  addLiveRecursionLimit: number;
  /**
   * Optional logging method
   */
  logging?: (...args: any[]) => void;
  /**
   * 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.
   */
  readonly: boolean;
}
interface ChaintracksManagementApi extends ChaintracksApi {
  /**
   * close and release all resources
   */
  destroy(): Promise<void>;
  /**
   * 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.
   */
  validate(): Promise<boolean>;
  /**
   * Exports current bulk headers, including all ingests, excluding live headers to static header files.
   *
   * Useful for bulk ingestors such as those derived from BulkIngestorCDN.
   *
   * @param toFolder Where the json and headers files will be written
   * @param toFs The ChaintracksFsApi to use for writing files. If not provided, the default file system will be used.
   * @param sourceUrl Optional source URL to include in the exported files. Set if exported files will be transferred to a CDN.
   * @param toHeadersPerFile The maximum headers per file. Default is 100,000 (8MB)
   * @param maxHeight The maximum height to export. Default is the current bulk storage max height.
   */
  exportBulkHeaders(toFolder: string, toFs: ChaintracksFsApi, sourceUrl?: string, toHeadersPerFile?: number, maxHeight?: number): Promise<void>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Api/BulkStorageApi.d.ts
interface BulkStorageBaseOptions {
  /**
   * The target chain: "main" or "test"
   */
  chain: Chain;
  fs: ChaintracksFsApi;
}
/**
 * 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.
 */
interface BulkStorageApi {
  /**
   * Close and release all resources.
   */
  shutdown(): Promise<void>;
  /**
   * @returns the height of the most recent header in bulk storage or -1 if empty.
   */
  getMaxHeight(): Promise<number>;
  /**
   * @returns available bulk block header height range: `(0, getMaxHeight())`
   */
  getHeightRange(): Promise<HeightRange>;
  /**
   * 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.
   *
   * @param minHeight must match height of first header in buffer
   * @param count times 80 must equal headers.length
   * @param headers encoded as packed array of 80 byte serialized block headers
   */
  appendHeaders(minHeight: number, count: number, headers: Uint8Array): Promise<void>;
  /**
   * Returns block header for a given block height on active chain.
   * @param hash block hash
   */
  findHeaderForHeightOrUndefined(height: number): Promise<BlockHeader | undefined>;
  /**
   * Returns block header for a given block height on active chain.
   * Throws if not found.
   * @param hash block hash
   */
  findHeaderForHeight(height: number): Promise<BlockHeader>;
  /**
   * 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.
   *
   * @param height of first header
   * @param count of headers
   */
  headersToBuffer(height: number, count: number): Promise<Uint8Array>;
  /**
   * Exports current bulk headers, including all ingests, excluding live headers to static header files.
   * @param rootFolder Where the json and headers files will be written
   * @param jsonFilename The name of the json file.
   * @param maxPerFile The maximum headers per file.
   */
  exportBulkHeaders(rootFolder: string, jsonFilename: string, maxPerFile: number): Promise<void>;
  /**
   * Called before first Synchronize with reference to storage.
   * Components requiring asynchronous setup can override base class implementation.
   * @param storage
   */
  setStorage(storage: ChaintracksStorageApi, log: (...args: any[]) => void): Promise<void>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Chaintracks.d.ts
declare class Chaintracks implements ChaintracksManagementApi {
  options: ChaintracksOptions;
  static createOptions(chain: Chain): ChaintracksOptions;
  log: (...args: any[]) => void;
  readonly chain: Chain;
  readonly readonly: boolean;
  private readonly promises;
  private readonly callbacks;
  private readonly storage;
  private readonly bulkIngestors;
  private readonly liveIngestors;
  private readonly baseHeaders;
  private readonly liveHeaders;
  private readonly addLiveRecursionLimit;
  private available;
  private startupError;
  private subscriberCallbacksEnabled;
  private stopMainThread;
  private lastPresentHeight;
  private lastPresentHeightMsecs;
  private readonly lastPresentHeightMaxAge;
  private readonly lock;
  private readonly sourceStatus;
  constructor(options: ChaintracksOptions);
  getChain(): Promise<Chain>;
  /**
   * Caches and returns most recently sourced value if less than one minute old.
   * @returns the current externally available chain height (via bulk ingestors).
   */
  getPresentHeight(): Promise<number>;
  currentHeight(): Promise<number>;
  subscribeHeaders(listener: HeaderListener): Promise<string>;
  subscribeReorgs(listener: ReorgListener): Promise<string>;
  unsubscribe(subscriptionId: string): Promise<boolean>;
  /**
   * Queues a potentially new, unknown header for consideration as an addition to the chain.
   * When the header is considered, if the prior header is unknown, recursive calls to the
   * bulk ingestors will be attempted to resolve the linkage up to a depth of `addLiveRecursionLimit`.
   *
   * Headers are considered in the order they were added.
   *
   * @param header
   */
  addHeader(header: BaseBlockHeader): Promise<void>;
  /**
   * If not already available, takes a writer lock to queue calls until available.
   * Becoming available starts by initializing ingestors and main thread,
   * and ends when main thread sets `available`.
   * Note that the main thread continues running and takes additional write locks
   * itself when already available.
   *
   * @returns when available for client requests
   */
  makeAvailable(): Promise<void>;
  startPromises(): Promise<void>;
  destroy(): Promise<void>;
  listening(): Promise<void>;
  private runLiveIngestor;
  private liveIngestorRestartWaitMsecs;
  isListening(): Promise<boolean>;
  isSynchronized(): Promise<boolean>;
  findHeaderForHeight(height: number): Promise<BlockHeader | undefined>;
  private findHeaderForHeightNoLock;
  findHeaderForBlockHash(hash: string): Promise<BlockHeader | undefined>;
  private findHeaderForBlockHashNoLock;
  isValidRootForHeight(root: string, height: number): Promise<boolean>;
  getInfo(): Promise<ChaintracksInfoApi>;
  private getInfoNoLock;
  getHeaders(height: number, count: number): Promise<string>;
  findChainTipHeader(): Promise<BlockHeader>;
  findChainTipHash(): Promise<string>;
  findLiveHeaderForBlockHash(hash: string): Promise<LiveBlockHeader | undefined>;
  findChainWorkForBlockHash(hash: string): Promise<string | undefined>;
  /**
   * @returns true iff all headers from height zero through current chainTipHeader height can be retreived and form a valid chain.
   */
  validate(): Promise<boolean>;
  exportBulkHeaders(toFolder: string, toFs: ChaintracksFsApi, sourceUrl?: string, toHeadersPerFile?: number, maxHeight?: number): Promise<void>;
  startListening(): Promise<void>;
  private syncBulkStorage;
  private syncBulkStorageNoLock;
  private runBulkSyncRound;
  private sourceName;
  private markSourceSuccess;
  private markSourceFailure;
  private getMissingBlockHeader;
  private invalidInsertHeaderResult;
  private addLiveHeader;
  private notifyHeaderListeners;
  private notifyReorgListeners;
  /**
   * Long running method terminated by setting `stopMainThread` false.
   *
   * The promise returned by this method is held in the `promises` array.
   *
   * When synchronized (bulk and live storage is valid up to most recent presentHeight),
   * this method will process headers from `baseHeaders` and `liveHeaders` arrays to extend the chain of headers.
   *
   * If a significant gap is detected between bulk+live and presentHeight, `syncBulkStorage` is called to re-establish sync.
   *
   * Periodically CDN bulk ingestor is invoked to check if incremental headers can be migrated to CDN backed files.
   */
  private mainThreadShiftLiveHeaders;
  /** Returns (potentially updated) lastBulkSync timestamp. */
  private runBulkSyncIfNeeded;
  private processNextQueuedHeader;
  private flushLiveHeaderProgress;
  private waitForQueuedHeaders;
  private processLiveHeaderQueue;
  private formatIhrLog;
  private processOneLiveHeader;
  private processOneBaseHeader;
  private checkAndEnableSubscribers;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/ChaintracksServiceClient.d.ts
interface ChaintracksServiceClientOptions {}
/**
 * Connects to a ChaintracksService to implement 'ChaintracksClientApi'
 *
 */
declare class ChaintracksServiceClient implements ChaintracksClientApi {
  chain: Chain;
  serviceUrl: string;
  static createChaintracksServiceClientOptions(): ChaintracksServiceClientOptions;
  options: ChaintracksServiceClientOptions;
  constructor(chain: Chain, serviceUrl: string, options?: ChaintracksServiceClientOptions);
  subscribeHeaders(_listener: HeaderListener): Promise<string>;
  subscribeReorgs(_listener: ReorgListener): Promise<string>;
  unsubscribe(_subscriptionId: string): Promise<boolean>;
  currentHeight(): Promise<number>;
  isValidRootForHeight(root: string, height: number): Promise<boolean>;
  getJsonOrUndefined<T>(path: string): Promise<T | undefined>;
  getJson<T>(path: string): Promise<T>;
  postJsonVoid<T>(path: string, params: T): Promise<void>;
  addHeader(header: BaseBlockHeader): Promise<void>;
  startListening(): Promise<void>;
  listening(): Promise<void>;
  getChain(): Promise<Chain>;
  isListening(): Promise<boolean>;
  isSynchronized(): Promise<boolean>;
  getPresentHeight(): Promise<number>;
  getInfo(): Promise<ChaintracksInfoApi>;
  findChainTipHeader(): Promise<BlockHeader>;
  findChainTipHash(): Promise<string>;
  getHeaders(height: number, count: number): Promise<string>;
  findHeaderForHeight(height: number): Promise<BlockHeader | undefined>;
  findHeaderForBlockHash(hash: string): Promise<BlockHeader | undefined>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/GoChaintracksServiceClient.d.ts
interface GoChaintracksServiceClientOptions {
  /**
   * Path prefix for the go-chaintracks HTTP API.
   * Arcade exposes this at `/chaintracks/v2`.
   */
  apiPrefix?: string;
  fetch?: typeof fetch;
  /** Timeout for HTTP requests and the initial SSE handshake. */
  requestTimeoutMsecs?: number;
  /** Initial delay before reconnecting a closed or failed SSE stream. */
  reconnectWaitMsecs?: number;
  /** Maximum SSE reconnect delay. */
  reconnectWaitMaxMsecs?: number;
}
/**
 * Client for go-chaintracks compatible HTTP services, including Arcade's
 * `/chaintracks/v2` surface. Unlike the legacy ChaintracksServiceClient, this
 * can subscribe to tip/reorg SSE streams and therefore drive Monitor block
 * processing without a local WhatsOnChain polling ingestor.
 */
declare class GoChaintracksServiceClient implements ChaintracksClientApi {
  chain: Chain;
  private readonly baseUrl;
  private readonly fetcher;
  private readonly requestTimeoutMsecs;
  private readonly reconnectWaitMsecs;
  private readonly reconnectWaitMaxMsecs;
  private readonly subscriptions;
  private nextSubscriptionId;
  constructor(chain: Chain, serviceUrl: string, options?: GoChaintracksServiceClientOptions);
  currentHeight(): Promise<number>;
  isValidRootForHeight(root: string, height: number): Promise<boolean>;
  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>;
  private subscribe;
  private runSseWithReconnect;
  private waitForReconnect;
  private runSse;
  private processSseBuffer;
  private getJson;
  private getJsonOrUndefined;
  private getBinary;
  private fetchWithTimeout;
  private url;
  private normalizeChain;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/BulkIngestorBase.d.ts
declare abstract class BulkIngestorBase implements BulkIngestorApi {
  /**
   *
   * @param chain
   * @param localCachePath defaults to './data/ingest_headers/'
   * @returns
   */
  static createBulkIngestorBaseOptions(chain: Chain): BulkIngestorBaseOptions;
  chain: Chain;
  jsonFilename: string;
  log: (...args: any[]) => void;
  constructor(options: BulkIngestorBaseOptions);
  private storageEngine;
  setStorage(storage: ChaintracksStorageBase, log: (...args: any[]) => void): Promise<void>;
  shutdown(): Promise<void>;
  storageOrUndefined(): ChaintracksStorageApi | undefined;
  storage(): ChaintracksStorageBase;
  /**
   * information about locally cached bulk header files managed by this bulk ingestor
   */
  filesInfo: BulkHeaderFilesInfo | undefined;
  /**
   * At least one derived BulkIngestor must override this method to provide the current height of the active chain tip.
   * @returns undefined unless overridden
   */
  getPresentHeight(): Promise<number | undefined>;
  /**
   * 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.
   *
   * @param before bulk and live range of headers before ingesting any new headers.
   * @param fetchRange range of headers still needed, includes both missing bulk and live headers.
   * @param bulkRange range of bulk headers still needed
   * @param priorLiveHeaders any headers accumulated by prior bulk ingestor(s) that are too recent for bulk storage.
   * @returns new live headers: headers in fetchRange but not in bulkRange
   */
  abstract fetchHeaders(before: HeightRanges, fetchRange: HeightRange, bulkRange: HeightRange, priorLiveHeaders: BlockHeader[]): Promise<BlockHeader[]>;
  /**
   * 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.
   *
   * @param presentHeight current height of the active chain tip, may lag the true value.
   * @param before current bulk and live storage height ranges, either may be empty.
   * @param priorLiveHeaders any headers accumulated by prior bulk ingestor(s) that are too recent for bulk storage.
   * @returns updated priorLiveHeaders including any accumulated by this ingestor
   */
  synchronize(presentHeight: number, before: HeightRanges, priorLiveHeaders: BlockHeader[]): Promise<BulkSyncResult>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/LiveIngestorBase.d.ts
interface LiveIngestorBaseOptions {
  /**
   * The target chain: "main" or "test"
   */
  chain: Chain;
}
/**
 *
 */
declare abstract class LiveIngestorBase implements LiveIngestorApi {
  static createLiveIngestorBaseOptions(chain: Chain): LiveIngestorBaseOptions;
  chain: Chain;
  log: (...args: any[]) => void;
  constructor(options: LiveIngestorBaseOptions);
  /**
   * Release resources.
   * Override if required.
   */
  shutdown(): Promise<void>;
  private storageEngine?;
  /**
   * Allocate resources.
   * @param storage coordinating storage engine.
   */
  setStorage(storage: ChaintracksStorageApi, log: (...args: any[]) => void): Promise<void>;
  /**
   *
   * @returns coordinating storage engine.
   */
  storage(): ChaintracksStorageApi;
  /**
   * Called to retrieve a missing block header,
   * when the previousHash of a new header is unknown.
   *
   * @param hash block hash of missing header
   */
  abstract getHeaderByHash(hash: string): Promise<BlockHeader | undefined>;
  /**
   * Begin retrieving new block headers.
   *
   * New headers are pushed onto the liveHeaders array.
   *
   * Continue waiting for new headers.
   *
   * Return only when either `stopListening` or `shutdown` are called.
   *
   * Be prepared to resume listening after `stopListening` but not
   * after `shutdown`.
   *
   * @param liveHeaders
   */
  abstract startListening(liveHeaders: BlockHeader[]): Promise<void>;
  /**
   * Causes `startListening` to stop listening for new block headers and return.
   */
  abstract stopListening(): void;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/BulkIngestorCDN.d.ts
interface BulkIngestorCDNOptions extends BulkIngestorBaseOptions {
  /**
   * Required.
   *
   * The name of the JSON resource to request from CDN which describes currently
   * available bulk block header resources.
   */
  jsonResource: string | undefined;
  /**
   * Required.
   *
   * URL to CDN implementing the bulk ingestor CDN service protocol
   */
  cdnUrl: string | undefined;
  maxPerFile: number | undefined;
  fetch: ChaintracksFetchApi;
}
declare class BulkIngestorCDN extends BulkIngestorBase {
  /**
   *
   * @param chain
   * @param localCachePath defaults to './data/bulk_cdn_headers/'
   * @returns
   */
  static createBulkIngestorCDNOptions(chain: Chain, cdnUrl: string, fetch: ChaintracksFetchApi, maxPerFile?: number): BulkIngestorCDNOptions;
  fetch: ChaintracksFetchApi;
  jsonResource: string;
  cdnUrl: string;
  maxPerFile: number | undefined;
  availableBulkFiles: BulkHeaderFilesInfo | undefined;
  selectedFiles: BulkHeaderFileInfo[] | undefined;
  currentRange: HeightRange | undefined;
  constructor(options: BulkIngestorCDNOptions);
  getPresentHeight(): Promise<number | undefined>;
  getJsonHttpHeaders(): Record<string, string>;
  /**
   * A BulkFile CDN serves a JSON BulkHeaderFilesInfo resource which lists all the available binary bulk header files available and associated metadata.
   *
   * The term "CDN file" is used for a local bulk file that has a sourceUrl. (Not undefined)
   * The term "incremental file" is used for the local bulk file that holds all the non-CDN bulk headers and must chain to the live headers if there are any.
   *
   * Bulk ingesting from a CDN happens in one of three contexts:
   *
   * 1. Cold Start: No local bulk or live headers.
   * 2. Incremental: Available CDN files extend into an existing incremental file but not into the live headers.
   * 3. Replace: Available CDN files extend into live headers.
   *
   * Context Cold Start:
   * - The CDN files are selected in height order, starting at zero, always choosing the largest count less than the local maximum (maxPerFile).
   *
   * Context Incremental:
   * - Last existing CDN file is updated if CDN now has a higher count.
   * - Additional CDN files are added as in Cold Start.
   * - The existing incremental file is truncated or deleted.
   *
   * Context Replace:
   * - Existing live headers are truncated or deleted.
   * - Proceed as context Incremental.
   *
   * @param before bulk and live range of headers before ingesting any new headers.
   * @param fetchRange total range of header heights needed including live headers
   * @param bulkRange range of missing bulk header heights required.
   * @param priorLiveHeaders
   * @returns
   */
  fetchHeaders(before: HeightRanges, fetchRange: HeightRange, bulkRange: HeightRange, priorLiveHeaders: BlockHeader[]): Promise<BlockHeader[]>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/BulkIngestorCDNBabbage.d.ts
declare class BulkIngestorCDNBabbage extends BulkIngestorCDN {
  /**
   *
   * @param chain
   * @param rootFolder defaults to './data/bulk_cdn_babbage_headers/'
   * @returns
   */
  static createBulkIngestorCDNBabbageOptions(chain: Chain, fetch: ChaintracksFetchApi): BulkIngestorCDNOptions;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/WhatsOnChainIngestorWs.d.ts
interface StopListenerToken {
  stop: (() => void) | undefined;
}
//#endregion
//#region ../src/services/providers/SdkWhatsOnChain.d.ts
/**
 * Represents a chain tracker based on What's On Chain .
 */
declare class SdkWhatsOnChain implements ChainTracker {
  readonly network: string;
  readonly apiKey: string;
  protected readonly URL: string;
  protected readonly httpClient: HttpClient;
  /**
   * Constructs an instance of the WhatsOnChain ChainTracker.
   *
   * @param {'main' | 'test' | 'stn'} network - The BSV network to use when calling the WhatsOnChain API.
   * @param {WhatsOnChainConfig} config - Configuration options for the WhatsOnChain ChainTracker.
   */
  constructor(network?: 'main' | 'test' | 'stn' | 'ttn' | 'tstn', config?: WhatsOnChainConfig);
  isValidRootForHeight(root: string, height: number): Promise<boolean>;
  currentHeight(): Promise<number>;
  protected getHttpHeaders(): Record<string, string>;
}
//#endregion
//#region ../src/services/ServiceCollection.d.ts
declare class ServiceCollection<T> {
  serviceName: string;
  services: Array<{
    name: string;
    service: T;
  }>;
  _index: number;
  /**
   * Start of currentCounts interval. Initially instance construction time.
   */
  readonly since: Date;
  _historyByProvider: Record<string, ProviderCallHistory>;
  constructor(serviceName: string, services?: Array<{
    name: string;
    service: T;
  }>);
  add(s: {
    name: string;
    service: T;
  }): this;
  remove(name: string): void;
  get name(): string;
  get service(): T;
  getServiceToCall(i: number): ServiceToCall<T>;
  get serviceToCall(): ServiceToCall<T>;
  get allServicesToCall(): Array<ServiceToCall<T>>;
  /**
   * Used to de-prioritize a service call by moving it to the end of the list.
   * @param stc
   */
  moveServiceToLast(stc: ServiceToCall<T>): void;
  get allServices(): T[];
  get count(): number;
  get index(): number;
  reset(): void;
  next(): number;
  clone(): ServiceCollection<T>;
  _addServiceCall(providerName: string, call: ServiceCall): ProviderCallHistory;
  getDuration(since: Date | string): number;
  addServiceCallSuccess(stc: ServiceToCall<T>, result?: string): void;
  addServiceCallFailure(stc: ServiceToCall<T>, result?: string): void;
  addServiceCallError(stc: ServiceToCall<T>, error: WalletError): void;
  /**
   * @returns A copy of current service call history
   */
  getServiceCallHistory(reset?: boolean): ServiceCallHistory;
}
interface ServiceCall {
  /**
   * string value must be Date's toISOString format.
   */
  when: Date | string;
  msecs: number;
  /**
   * true iff service provider successfully processed the request
   * false iff service provider failed to process the request which includes thrown errors.
   */
  success: boolean;
  /**
   * Simple text summary of result. e.g. `not a valid utxo` or `valid utxo`
   */
  result?: string;
  /**
   * Error code and message iff success is false and a exception was thrown.
   */
  error?: {
    message: string;
    code: string;
  };
}
interface ServiceToCall<T> {
  providerName: string;
  serviceName: string;
  service: T;
  call: ServiceCall;
}
//#endregion
//#region ../src/services/providers/Arcade.d.ts
/**
 * Broadcaster for bsv-blockchain/arcade — the Teranode-native, ARC-compatible broadcaster.
 *
 * Arcade is intentionally a separate, self-contained class (not a subclass of {@link ARC}) so
 * the audited ARC transport is never altered. It is ARC-compatible on headers, configuration and
 * the `getTxData` response shape — but differs where it must:
 *
 *  - Endpoints are served at the root: `/tx` and `/tx/{txid}` (no `/v1` prefix).
 *  - A submit returns HTTP 202; HTTP 400 is a terminal validation failure (REJECTED) and is
 *    surfaced as an invalid-transaction status error rather than a transient service error.
 *  - Submission encoding is Extended Format (EF), not BEEF: Arcade's `/tx` parser rejects BEEF
 *    ("failed to parse transaction") and runs fee/script validation that needs per-input source
 *    data, which EF carries inline.
 */
declare class Arcade {
  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;
  /**
   * @param URL - The Arcade endpoint base URL.
   * @param config - Arcade configuration (shares ARC's {@link ArcConfig} shape).
   */
  constructor(URL: string, config?: ArcConfig, name?: string);
  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;
  /**
   * Submit a single transaction to Arcade's `POST /tx` endpoint.
   *
   * `rawTx` must be a single (raw or Extended Format) transaction hex — NOT BEEF. The canonical
   * txid is taken from `txids` when supplied (Arcade derives the same txid from the parsed tx).
   */
  postRawTx(rawTx: HexString, txids?: string[]): Promise<PostTxResultForTxid>;
  /**
   * Post each tx of interest as Extended Format (EF).
   *
   * EF needs each input's source output (satoshis + locking script). For a BEEF that carries every
   * direct parent transaction in full (e.g. the atomic BEEF produced by createAction), that data is
   * present and {@link Transaction.fromBEEF} can reconstruct EF. A BEEF is NOT guaranteed to contain
   * it, however: BEEF V2 `txidOnly` entries (or an otherwise pruned BEEF) can reference a direct
   * parent without its bytes, leaving no source output to embed — so BEEF -> EF is not always
   * possible. When EF cannot be built for a txid, it is recorded as a (non-terminal) service error
   * so cross-provider aggregation falls through to a BEEF-capable broadcaster, which can still
   * broadcast the (valid) transaction.
   */
  postBeef(beef: Beef, txids: string[]): Promise<PostBeefResult>;
  /** Look up a transaction's current status (and merkle path once mined) via `GET /tx/{txid}`. */
  getTxData(txid: string): Promise<ArcMinerGetTxData>;
  /**
   * `getMerklePath` provider: obtain a BUMP merkle proof for a mined transaction from Arcade.
   *
   * Arcade only has a proof for transactions it tracked (i.e. broadcast through it) that have
   * been mined while tracked; for anything else `GET /tx/{txid}` reports a non-mined status (or
   * 404) and this returns no `merklePath`, so {@link Services.getMerklePath} falls through to the
   * other providers (WhatsOnChain/Bitails).
   *
   * The proof is NOT trusted blindly: the canonical block header is resolved from the wallet's
   * own chaintracker via `services.hashToHeader(blockHash)` (which only knows real, mined blocks),
   * and the BUMP's computed merkle root must equal that header's `merkleRoot`. Only then is the
   * proof returned, with the canonical `header` that downstream proof completion requires.
   */
  getMerklePath(txid: string, services: WalletServices): Promise<GetMerklePathResult>;
}
//#endregion
//#region ../src/services/providers/Bitails.d.ts
interface BitailsConfig {
  /** Authentication token for BitTails API */
  apiKey?: string;
  /** The HTTP client used to make requests to the API. */
  httpClient?: HttpClient;
}
/**
 *
 */
declare class Bitails {
  readonly chain: Chain;
  readonly apiKey: string;
  readonly URL: string;
  readonly httpClient: HttpClient;
  constructor(chain?: Chain, config?: BitailsConfig);
  getHttpHeaders(): Record<string, string>;
  /**
   * Bitails does not natively support a postBeef end-point aware of multiple txids of interest in the Beef.
   *
   * Send rawTx in `txids` order from beef.
   *
   * @param beef
   * @param txids
   * @returns
   */
  postBeef(beef: Beef, txids: string[]): Promise<PostBeefResult>;
  /**
   * @param raws Array of raw transactions to broadcast as hex strings
   * @param txids Array of txids for transactions in raws for which results are requested, remaining raws are supporting only.
   * @returns
   */
  postRaws(raws: HexString[], txids?: string[]): Promise<PostBeefResult>;
  /**
   *
   * @param txid
   * @param services
   * @returns
   */
  getMerklePath(txid: string, services: WalletServices): Promise<GetMerklePathResult>;
}
//#endregion
//#region ../src/services/Services.d.ts
declare class Services implements WalletServices {
  static readonly getStatusForTxidsBatchLimit = 20;
  static createDefaultOptions(chain: Chain): WalletServicesOptions;
  options: WalletServicesOptions;
  whatsonchain: WhatsOnChain;
  arcTaal: ARC;
  arcGorillaPool?: ARC;
  /** Primary Arcade (bsv-blockchain/arcade) broadcaster, when `options.arcadeUrl` is set. */
  arcade?: Arcade;
  bitails?: Bitails;
  getMerklePathServices: ServiceCollection<GetMerklePathService>;
  getRawTxServices: ServiceCollection<GetRawTxService>;
  postBeefServices: ServiceCollection<PostBeefService>;
  getUtxoStatusServices: ServiceCollection<GetUtxoStatusService>;
  getStatusForTxidsServices: ServiceCollection<GetStatusForTxidsService>;
  getScriptHashHistoryServices: ServiceCollection<GetScriptHashHistoryService>;
  updateFiatExchangeRateServices: ServiceCollection<UpdateFiatExchangeRateService>;
  chain: Chain;
  readonly telemetry: Telemetry;
  constructor(optionsOrChain: Chain | WalletServicesOptions);
  private configureOptionalProviders;
  private initializeReadServices;
  private initializePostBeefServices;
  private initializeFiatRateServices;
  getServicesCallHistory(reset?: boolean): ServicesCallHistory;
  getChainTracker(): Promise<ChainTracker>;
  getBsvExchangeRate(): Promise<number>;
  getFiatExchangeRate(currency: FiatCurrencyCode, base?: FiatCurrencyCode): Promise<number>;
  getFiatExchangeRates(targetCurrencies: FiatCurrencyCode[]): Promise<FiatExchangeRates>;
  get getProofsCount(): number;
  get getRawTxsCount(): number;
  get postBeefServicesCount(): number;
  get getUtxoStatsCount(): number;
  getStatusForTxids(txids: string[], useNext?: boolean): Promise<GetStatusForTxidsResult>;
  private getStatusForTxidsBatched;
  /**
   * @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;
  isUtxo(output: TableOutput): Promise<boolean>;
  getUtxoStatus(output: string, outputFormat?: GetUtxoStatusOutputFormat, outpoint?: string, useNext?: boolean, logger?: WalletLoggerInterface): Promise<GetUtxoStatusResult>;
  private tryUtxoStatusProviders;
  getScriptHashHistory(hash: string, useNext?: boolean, logger?: WalletLoggerInterface): Promise<GetScriptHashHistoryResult>;
  postBeefMode: 'PromiseAll' | 'UntilSuccess';
  /**
   * Soft timeout used for each provider call in `UntilSuccess` mode.
   * This bounds request latency when a provider hangs before failover.
   */
  postBeefUntilSuccessSoftTimeoutMs: number;
  /**
   * Additional soft-timeout budget (ms) per KiB of serialized Beef payload.
   * Helps avoid false timeout failover on legitimately large submissions.
   */
  postBeefUntilSuccessSoftTimeoutPerKbMs: number;
  /**
   * Upper bound for adaptive soft-timeout in `UntilSuccess` mode.
   */
  postBeefUntilSuccessSoftTimeoutMaxMs: number;
  /**
   *
   * @param beef
   * @param chain
   * @returns
   */
  postBeef(beef: Beef, txids: string[], logger?: WalletLoggerInterface): Promise<PostBeefResult[]>;
  private getPostBeefSoftTimeoutMs;
  getRawTx(txid: string, useNext?: boolean): Promise<GetRawTxResult>;
  private applyRawTxResult;
  invokeChaintracksWithRetry<R>(method: () => Promise<R>, operation?: string): Promise<R>;
  private invokeChaintracksWithRetryCore;
  getHeaderForHeight(height: number): Promise<number[]>;
  getHeight(): Promise<number>;
  hashToHeader(hash: string): Promise<BlockHeader>;
  getMerklePath(txid: string, useNext?: boolean, logger?: WalletLoggerInterface): Promise<GetMerklePathResult>;
  updateFiatExchangeRates(targetCurrencies: FiatCurrencyCode[], updateMsecs?: number): Promise<FiatExchangeRates>;
  private collectStaleCurrencies;
  private fetchFiatRates;
  private mergeFiatRates;
  nLockTimeIsFinal(tx: string | number[] | Transaction | number): Promise<boolean>;
  getBeefForTxid(txid: string): Promise<Beef>;
}
declare function validateScriptHash(output: string, outputFormat?: GetUtxoStatusOutputFormat): string;
/**
 * Serializes a block header as an 80 byte array.
 * The exact serialized format is defined in the Bitcoin White Paper
 * such that computing a double sha256 hash of the array computes
 * the block hash for the header.
 * @returns 80 byte array
 * @publicbody
 */
declare function toBinaryBaseBlockHeader(header: BaseBlockHeader): number[];
//#endregion
//#region ../src/services/providers/WhatsOnChain.d.ts
interface WalletToolboxWhatsOnChainConfig extends WhatsOnChainConfig {
  /** Optional request-start gate used by ChainTracks' shared public-rate scheduler. */
  requestGate?: () => Promise<void>;
}
declare class WhatsOnChainNoServices extends SdkWhatsOnChain {
  private readonly requestGate?;
  constructor(chain?: Chain, config?: WalletToolboxWhatsOnChainConfig);
  private requestWithAnonymousAuthFallback;
  /**
   * POST
   * https://api.whatsonchain.com/v1/bsv/main/txs/status
   * Content-Type: application/json
   * data: "{\"txids\":[\"6815f8014db74eab8b7f75925c68929597f1d97efa970109d990824c25e5e62b\"]}"
   *
   * result for a mined txid:
   *     [{
   *        "txid":"294cd1ebd5689fdee03509f92c32184c0f52f037d4046af250229b97e0c8f1aa",
   *        "blockhash":"000000000000000004b5ce6670f2ff27354a1e87d0a01bf61f3307f4ccd358b5",
   *        "blockheight":612251,
   *        "blocktime":1575841517,
   *        "confirmations":278272
   *      }]
   *
   * result for a valid recent txid:
   *     [{"txid":"6815f8014db74eab8b7f75925c68929597f1d97efa970109d990824c25e5e62b"}]
   *
   * result for an unknown txid:
   *     [{"txid":"6815f8014db74eab8b7f75925c68929597f1d97efa970109d990824c25e5e62c","error":"unknown"}]
   */
  getStatusForTxids(txids: string[]): Promise<GetStatusForTxidsResult>;
  /**
   * 2025-02-16 throwing internal server error 500.
   * @param txid
   * @returns
   */
  getTxPropagation(txid: string): Promise<number>;
  /**
   * May return undefined for unmined transactions that are in the mempool.
   * @param txid
   * @returns raw transaction as hex string or undefined if txid not found in mined block.
   */
  getRawTx(txid: string): Promise<string | undefined>;
  getRawTxResult(txid: string): Promise<GetRawTxResult>;
  /**
   * WhatsOnChain does not natively support a postBeef end-point aware of multiple txids of interest in the Beef.
   *
   * Send rawTx in `txids` order from beef.
   *
   * @param beef
   * @param txids
   * @returns
   */
  postBeef(beef: Beef, txids: string[]): Promise<PostBeefResult>;
  /**
   * @param rawTx raw transaction to broadcast as hex string
   * @returns txid returned by transaction processor of transaction broadcast
   */
  postRawTx(rawTx: HexString): Promise<PostTxResultForTxid>;
  updateBsvExchangeRate(rate?: BsvExchangeRate, updateMsecs?: number): Promise<BsvExchangeRate>;
  getUtxoStatus(output: string, outputFormat?: GetUtxoStatusOutputFormat, outpoint?: string): Promise<GetUtxoStatusResult>;
  private applyUtxoStatusResponse;
  getScriptHashConfirmedHistory(hash: string): Promise<GetScriptHashHistoryResult>;
  getScriptHashUnconfirmedHistory(hash: string): Promise<GetScriptHashHistoryResult>;
  getScriptHashHistory(hash: string): Promise<GetScriptHashHistoryResult>;
  /**
      {
        "hash": "000000000000000004a288072ebb35e37233f419918f9783d499979cb6ac33eb",
        "confirmations": 328433,
        "size": 14421,
        "height": 575045,
        "version": 536928256,
        "versionHex": "2000e000",
        "merkleroot": "4ebcba09addd720991d03473f39dce4b9a72cc164e505cd446687a54df9b1585",
        "time": 1553416668,
        "mediantime": 1553414858,
        "nonce": 87914848,
        "bits": "180997ee",
        "difficulty": 114608607557.4425,
        "chainwork": "000000000000000000000000000000000000000000ddf5d385546872bab7dc01",
        "previousblockhash": "00000000000000000988156c7075dc9147a5b62922f1310862e8b9000d46dd9b",
        "nextblockhash": "00000000000000000112b36a37c10235fa0c991f680bc5482ba9692e0ae697db",
        "nTx": 0,
        "num_tx": 5
      }
     */
  getBlockHeaderByHash(hash: string): Promise<BlockHeader | undefined>;
  getChainInfo(): Promise<WocChainInfo>;
}
/**
 *
 */
declare class WhatsOnChain extends WhatsOnChainNoServices {
  services: Services;
  constructor(chain?: Chain, config?: WalletToolboxWhatsOnChainConfig, services?: Services);
  /**
   * @param txid
   * @returns
   */
  getMerklePath(txid: string, services: WalletServices): Promise<GetMerklePathResult>;
  private applyMerklePathResponse;
}
interface WocChainInfo {
  chain: string;
  blocks: number;
  headers: number;
  bestblockhash: string;
  difficulty: number;
  mediantime: number;
  verificationprogress: number;
  pruned: boolean;
  chainwork: string;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/WhatsOnChainServices.d.ts
/**
 * return true to ignore error, false to close service connection
 */
type ErrorHandler = (code: number, message: string) => boolean;
type EnqueueHandler = (header: BlockHeader) => void;
declare function parseFileLink(file: string): {
  range: {
    fromHeight: number;
    toHeight: number;
  } | 'latest';
  sourceUrl: string;
  fileName: string;
} | undefined;
interface WhatsOnChainServicesOptions {
  /**
   * Which chain is being tracked. The public WhatsOnChain fallback is only
   * configured automatically for mainnet and testnet.
   */
  chain: Chain;
  /**
   * Optional WhatsOnChain API key. ChainTracks works without one and limits
   * anonymous traffic to the documented public rate.
   * https://docs.whatsonchain.com/
   */
  apiKey?: string;
  /**
   * Request timeout for GETs to https://api.whatsonchain.com/v1/bsv
   */
  timeout: number;
  /**
   * User-Agent header value for requests to https://api.whatsonchain.com/v1/bsv
   */
  userAgent: string;
  /**
   * Enable WhatsOnChain client cache option.
   */
  enableCache: boolean;
  /**
   * How long chainInfo is considered still valid before updating (msecs).
   */
  chainInfoMsecs: number;
  /** Minimum interval between keyless API request starts. Defaults below 3 requests/second. */
  minRequestIntervalMsecs?: number;
}
declare class WhatsOnChainServices {
  options: WhatsOnChainServicesOptions;
  static createWhatsOnChainServicesOptions(chain: Chain): WhatsOnChainServicesOptions;
  static readonly chainInfo: Array<WocChainInfo | undefined>;
  static readonly chainInfoTime: Array<Date | undefined>;
  static readonly chainInfoMsecs: number[];
  static readonly chainInfoPromise: Partial<Record<Chain, Promise<WocChainInfo>>>;
  private static requestTail;
  private static nextRequestMsecs;
  chain: Chain;
  woc: WhatsOnChain;
  constructor(options: WhatsOnChainServicesOptions);
  getHeaderByHash(hash: string): Promise<BlockHeader | undefined>;
  getChainInfo(): Promise<WocChainInfo>;
  getChainTipHeight(): Promise<number>;
  getChainTipHash(): Promise<string>;
  /**
   * @param fetch
   * @returns returns the last 10 block headers including height, size, chainwork...
   */
  getHeaders(fetch?: ChaintracksFetchApi): Promise<WocGetHeadersHeader[]>;
  getHeaderByteFileLinks(neededRange: HeightRange, fetch?: ChaintracksFetchApi): Promise<GetHeaderByteFileLinksResult[]>;
  private waitForRateLimit;
}
interface WocGetHeaderByteFileLinks {
  files: string[];
}
interface WocGetHeadersHeader {
  hash: string;
  confirmations: number;
  size: number;
  height: number;
  version: number;
  versionHex: string;
  merkleroot: string;
  time: number;
  mediantime: number;
  nonce: number;
  bits: string;
  difficulty: number;
  chainwork: string;
  previousblockhash: string;
  nextblockhash: string;
  nTx: number;
  num_tx: number;
}
declare function wocGetHeadersHeaderToBlockHeader(h: WocGetHeadersHeader): BlockHeader;
interface GetHeaderByteFileLinksResult {
  sourceUrl: string;
  fileName: string;
  range: HeightRange;
  data: Uint8Array | undefined;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/BulkIngestorWhatsOnChainCdn.d.ts
interface BulkIngestorWhatsOnChainOptions extends BulkIngestorBaseOptions, WhatsOnChainServicesOptions {
  /**
   * Maximum msecs of "normal" pause with no new data arriving.
   */
  idleWait: number | undefined;
  /**
   * Which chain is being tracked: main, test, or stn.
   */
  chain: Chain;
  /**
   * 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
   */
  apiKey?: string;
  /**
   * Request timeout for GETs to https://api.whatsonchain.com/v1/bsv
   */
  timeout: number;
  /**
   * User-Agent header value for requests to https://api.whatsonchain.com/v1/bsv
   */
  userAgent: string;
  /**
   * Enable WhatsOnChain client cache option.
   */
  enableCache: boolean;
  /**
   * How long chainInfo is considered still valid before updating (msecs).
   */
  chainInfoMsecs: number;
  /**
   *
   */
  fetch?: ChaintracksFetchApi;
}
declare class BulkIngestorWhatsOnChainCdn extends BulkIngestorBase {
  /**
   *
   * @param chain
   * @param localCachePath defaults to './data/ingest_whatsonchain_headers'
   * @returns
   */
  static createBulkIngestorWhatsOnChainOptions(chain: Chain): BulkIngestorWhatsOnChainOptions;
  fetch: ChaintracksFetchApi;
  idleWait: number;
  woc: WhatsOnChainServices;
  stopOldListenersToken: StopListenerToken;
  constructor(options: BulkIngestorWhatsOnChainOptions);
  getPresentHeight(): Promise<number | undefined>;
  fetchHeaders(before: HeightRanges, fetchRange: HeightRange, bulkRange: HeightRange, priorLiveHeaders: BlockHeader[]): Promise<BlockHeader[]>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/BulkIngestorChaintracks.d.ts
interface BulkIngestorChaintracksOptions extends BulkIngestorBaseOptions {
  chain: Chain;
  chaintracks: ChaintracksClientApi;
  /** Maximum headers requested from the upstream service at once. */
  maxHeadersPerRequest?: number;
}
/**
 * Uses a go-chaintracks/Arcade-compatible service as a validated bulk source.
 * Retrieved bytes still pass through ChainTracks' local serialization, hash,
 * continuity, and genesis checks before storage.
 */
declare class BulkIngestorChaintracks extends BulkIngestorBase {
  private readonly chaintracks;
  private readonly maxHeadersPerRequest;
  private networkChecked;
  constructor(options: BulkIngestorChaintracksOptions);
  getPresentHeight(): Promise<number>;
  fetchHeaders(_before: HeightRanges, fetchRange: HeightRange, bulkRange: HeightRange, priorLiveHeaders: BlockHeader[]): Promise<BlockHeader[]>;
  private ensureNetwork;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/LiveIngestorWhatsOnChainPoll.d.ts
interface LiveIngestorWhatsOnChainOptions extends LiveIngestorBaseOptions, WhatsOnChainServicesOptions {
  /**
   * Maximum msces of "normal" time with no ping received from connected WoC service.
   */
  idleWait: number | undefined;
  /**
   * Which chain is being tracked: main, test, or stn.
   */
  chain: Chain;
  /**
   * 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
   */
  apiKey?: string;
  /**
   * Request timeout for GETs to https://api.whatsonchain.com/v1/bsv
   */
  timeout: number;
  /**
   * User-Agent header value for requests to https://api.whatsonchain.com/v1/bsv
   */
  userAgent: string;
  /**
   * Enable WhatsOnChain client cache option.
   */
  enableCache: boolean;
  /**
   * How long chainInfo is considered still valid before updating (msecs).
   */
  chainInfoMsecs: number;
  /**
   * Initial delay before retrying a failed polling request.
   */
  retryWait?: number;
  /**
   * Maximum delay before retrying repeated failed polling requests.
   */
  retryWaitMax?: number;
}
/**
 * Reports new headers by polling periodically.
 */
declare class LiveIngestorWhatsOnChainPoll extends LiveIngestorBase {
  static createLiveIngestorWhatsOnChainOptions(chain: Chain): LiveIngestorWhatsOnChainOptions;
  idleWait: number;
  retryWait: number;
  retryWaitMax: number;
  woc: WhatsOnChainServices;
  done: boolean;
  constructor(options: LiveIngestorWhatsOnChainOptions);
  getHeaderByHash(hash: string): Promise<BlockHeader | undefined>;
  startListening(liveHeaders: BlockHeader[]): Promise<void>;
  private getRetryWaitMsecs;
  private errorMessage;
  private waitUnlessStopped;
  stopListening(): void;
  shutdown(): Promise<void>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Ingest/LiveIngestorChaintracksSSE.d.ts
interface LiveIngestorChaintracksSSEOptions extends LiveIngestorBaseOptions {
  chaintracks: ChaintracksClientApi;
}
/**
 * Adapts a remote Chaintracks event stream, such as Arcade/go-chaintracks
 * `/chaintracks/v2/tip/stream`, into the local Chaintracks live-ingestor API.
 */
declare class LiveIngestorChaintracksSSE extends LiveIngestorBase {
  private readonly options;
  static createLiveIngestorChaintracksSSEOptions(chain: Chain, chaintracks: ChaintracksClientApi): LiveIngestorChaintracksSSEOptions;
  private subscriptionId?;
  private stopped;
  private resolveStopped?;
  constructor(options: LiveIngestorChaintracksSSEOptions);
  getHeaderByHash(hash: string): Promise<BlockHeader | undefined>;
  startListening(liveHeaders: BlockHeader[]): Promise<void>;
  stopListening(): void;
  shutdown(): Promise<void>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Storage/BulkStorageBase.d.ts
declare abstract class BulkStorageBase implements BulkStorageApi {
  static createBulkStorageBaseOptions(chain: Chain, fs: ChaintracksFsApi): BulkStorageBaseOptions;
  chain: Chain;
  fs: ChaintracksFsApi;
  log: (...args: any[]) => void;
  constructor(options: BulkStorageBaseOptions);
  shutdown(): Promise<void>;
  abstract appendHeaders(minHeight: number, count: number, newBulkHeaders: Uint8Array): Promise<void>;
  abstract getMaxHeight(): Promise<number>;
  abstract headersToBuffer(height: number, count: number): Promise<Uint8Array>;
  abstract findHeaderForHeightOrUndefined(height: number): Promise<BlockHeader | undefined>;
  findHeaderForHeight(height: number): Promise<BlockHeader>;
  getHeightRange(): Promise<HeightRange>;
  setStorage(storage: ChaintracksStorageBase, log: (...args: any[]) => void): Promise<void>;
  exportBulkHeaders(rootFolder: string, jsonFilename: string, maxPerFile: number): Promise<void>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Storage/ChaintracksStorageNoDb.d.ts
interface ChaintracksNoDbData {
  chain: Chain;
  liveHeaders: Map<number, LiveBlockHeader>;
  maxHeaderId: number;
  tipHeaderId: number;
  hashToHeaderId: Map<string, number>;
}
interface ChaintracksStorageNoDbOptions extends ChaintracksStorageBaseOptions {}
declare class ChaintracksStorageNoDb extends ChaintracksStorageBase {
  static readonly mainData: ChaintracksNoDbData;
  static readonly testData: ChaintracksNoDbData;
  static readonly stnData: ChaintracksNoDbData;
  static readonly ttnData: ChaintracksNoDbData;
  static readonly tstnData: ChaintracksNoDbData;
  constructor(options: ChaintracksStorageNoDbOptions);
  destroy(): Promise<void>;
  getData(): Promise<ChaintracksNoDbData>;
  deleteLiveBlockHeaders(): Promise<void>;
  deleteOlderLiveBlockHeaders(maxHeight: number): Promise<number>;
  findChainTipHeader(): Promise<LiveBlockHeader>;
  findChainTipHeaderOrUndefined(): Promise<LiveBlockHeader | undefined>;
  findLiveHeaderForBlockHash(hash: string): Promise<LiveBlockHeader | null>;
  findLiveHeaderForHeaderId(headerId: number): Promise<LiveBlockHeader>;
  findLiveHeaderForHeight(height: number): Promise<LiveBlockHeader | null>;
  findLiveHeaderForMerkleRoot(merkleRoot: string): Promise<LiveBlockHeader | null>;
  findLiveHeightRange(): Promise<HeightRange>;
  findMaxHeaderId(): Promise<number>;
  liveHeadersForBulk(count: number): Promise<LiveBlockHeader[]>;
  getLiveHeaders(range: HeightRange): Promise<LiveBlockHeader[]>;
  private insertFirstHeader;
  private findActiveAncestor;
  private applyReorganization;
  private prepareActiveTip;
  insertHeader(header: BlockHeader): Promise<InsertHeaderResult>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/Storage/ChaintracksStorageIdb.d.ts
interface ChaintracksStorageIdbOptions extends ChaintracksStorageBaseOptions {}
declare class ChaintracksStorageIdb extends ChaintracksStorageBase implements ChaintracksStorageBulkFileApi {
  dbName: string;
  db?: IDBPDatabase<ChaintracksStorageIdbSchema>;
  whenLastAccess?: Date;
  allStores: string[];
  constructor(options: ChaintracksStorageIdbOptions);
  makeAvailable(): Promise<void>;
  migrateLatest(): Promise<void>;
  destroy(): Promise<void>;
  deleteLiveBlockHeaders(): Promise<void>;
  /**
   * Delete live headers with height less or equal to `maxHeight`
   *
   * Set existing headers with previousHeaderId value set to the headerId value of
   * a header which is to be deleted to null.
   *
   * @param maxHeight delete all records with less or equal `height`
   * @returns number of deleted records
   */
  deleteOlderLiveBlockHeaders(maxHeight: number): Promise<number>;
  /**
   * @returns the active chain tip header
   * @throws an error if there is no tip.
   */
  findChainTipHeader(): Promise<LiveBlockHeader>;
  /**
   *
   * @returns the active chain tip header
   * @throws an error if there is no tip.
   */
  findChainTipHeaderOrUndefined(): Promise<LiveBlockHeader | undefined>;
  findLiveHeaderForBlockHash(hash: string): Promise<LiveBlockHeader | null>;
  findLiveHeaderForHeaderId(headerId: number): Promise<LiveBlockHeader>;
  findLiveHeaderForHeight(height: number): Promise<LiveBlockHeader | null>;
  findLiveHeaderForMerkleRoot(merkleRoot: string): Promise<LiveBlockHeader | null>;
  findLiveHeightRange(): Promise<HeightRange>;
  findMaxHeaderId(): Promise<number>;
  liveHeadersForBulk(count: number): Promise<LiveBlockHeader[]>;
  getLiveHeaders(range: HeightRange): Promise<LiveBlockHeader[]>;
  private insertFirstHeader;
  private findActiveAncestor;
  private applyReorganization;
  private prepareActiveTip;
  insertHeader(header: BlockHeader): Promise<InsertHeaderResult>;
  deleteBulkFile(fileId: number): Promise<number>;
  insertBulkFile(file: BulkHeaderFileInfo): Promise<number>;
  updateBulkFile(fileId: number, file: BulkHeaderFileInfo): Promise<number>;
  getBulkFiles(): Promise<BulkHeaderFileInfo[]>;
  getBulkFileData(fileId: number, offset?: number, length?: number): Promise<Uint8Array | undefined>;
  /**
   * IndexedDB does not do indices of boolean properties.
   * So true is stored as a 1, and false is stored as no property value (delete v['property'])
   *
   * This function restores these property values to true and false.
   *
   * @param header
   * @returns copy of header with updated properties
   */
  private repairStoredLiveHeader;
  private prepareStoredLiveHeader;
  insertLiveHeader(header: LiveBlockHeader): Promise<LiveBlockHeader>;
  initDB(): Promise<IDBPDatabase<ChaintracksStorageIdbSchema>>;
  toDbTrxReadOnly(stores: string[]): IDBPTransaction<ChaintracksStorageIdbSchema, string[], 'readonly'>;
  toDbTrxReadWrite(stores: string[]): IDBPTransaction<ChaintracksStorageIdbSchema, string[], 'readwrite'>;
}
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;
    };
  };
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/configureChaintracksIngestors.d.ts
interface ChaintracksSourceOptions {
  /** Preferred go-chaintracks or Arcade source. */
  chaintracks?: ChaintracksClientApi;
  /** Disable the credential-free public Arcade default. */
  disableChaintracks?: boolean;
  /** Maximum number of headers requested from the remote source at once. */
  remoteMaxHeadersPerRequest?: number;
  /** Disable the configured CDN source without changing its URL. */
  disableCdn?: boolean;
  /** Disable the keyless WhatsOnChain fallback on mainnet/testnet. */
  disableWhatsOnChain?: boolean;
}
type ChaintracksArgumentsTail = [whatsonchainApiKey?: string, maxPerFile?: number, maxRetained?: number, fetch?: ChaintracksFetchApi, cdnUrl?: string, liveHeightThreshold?: number, reorgHeightThreshold?: number, bulkMigrationChunkSize?: number, batchInsertLimit?: number, addLiveRecursionLimit?: number, sources?: ChaintracksSourceOptions];
type DefaultChaintracksArguments = [chain: Chain, ...options: ChaintracksArgumentsTail];
/**
 * Shared parameters for configuring Chaintracks ingestors.
 */
interface ChaintracksIngestorParams {
  chain: Chain;
  whatsonchainApiKey: string;
  maxPerFile: number;
  fetch: ChaintracksFetchApi;
  cdnUrl: string;
  addLiveRecursionLimit: number;
  sources: ChaintracksSourceOptions;
}
interface ResolvedDefaultChaintracksParams extends ChaintracksIngestorParams {
  maxRetained: number;
  liveHeightThreshold: number;
  reorgHeightThreshold: number;
  bulkMigrationChunkSize: number;
  batchInsertLimit: number;
}
interface CreatedChaintracks<TStorage extends ChaintracksOptions['storage']> {
  chain: Chain;
  maxPerFile: number;
  fetch: ChaintracksFetchApi;
  storage: TStorage;
  chaintracks: Chaintracks;
  available: Promise<void>;
}
declare function resolveDefaultChaintracksArguments(args: DefaultChaintracksArguments): ResolvedDefaultChaintracksParams;
declare function toDefaultChaintracksArguments(params: ResolvedDefaultChaintracksParams): DefaultChaintracksArguments;
declare function createDefaultBulkFileDataManager(params: ResolvedDefaultChaintracksParams): BulkFileDataManager;
declare function createDefaultChaintracksStorageOptions(params: ResolvedDefaultChaintracksParams): {
  chain: Chain;
  bulkFileDataManager: BulkFileDataManager;
  liveHeightThreshold: number;
  reorgHeightThreshold: number;
  bulkMigrationChunkSize: number;
  batchInsertLimit: number;
};
declare function startChaintracks<TStorage extends ChaintracksOptions['storage']>(params: ResolvedDefaultChaintracksParams, options: ChaintracksOptions): CreatedChaintracks<TStorage>;
declare function createAndStartDefaultChaintracks<TStorage extends ChaintracksOptions['storage']>(args: DefaultChaintracksArguments, createOptions: (...args: DefaultChaintracksArguments) => ChaintracksOptions): CreatedChaintracks<TStorage>;
/**
 * Builds the shared portion of ChaintracksOptions that all storage backends
 * (Knex, Idb, NoDb) have in common: the options shell and bulk/live ingestors.
 *
 * The caller is responsible for providing the storage implementation.
 */
declare function buildChaintracksOptionsWithIngestors(params: ChaintracksIngestorParams, storage: ChaintracksOptions['storage']): ChaintracksOptions;
//#endregion
//#region ../src/services/chaintracker/chaintracks/createDefaultNoDbChaintracksOptions.d.ts
declare function createDefaultNoDbChaintracksOptions(...args: DefaultChaintracksArguments): ChaintracksOptions;
//#endregion
//#region ../src/services/chaintracker/chaintracks/createNoDbChaintracks.d.ts
declare function createNoDbChaintracks(...args: DefaultChaintracksArguments): Promise<{
  chain: Chain;
  maxPerFile: number;
  fetch: ChaintracksFetchApi;
  storage: ChaintracksStorageNoDb;
  chaintracks: Chaintracks;
  available: Promise<void>;
}>;
//#endregion
//#region ../src/services/chaintracker/chaintracks/util/BulkFilesReader.d.ts
/**
 * Breaks available bulk headers stored in multiple files into a sequence of buffers with
 * limited maximum size.
 */
declare class BulkFilesReader {
  /**
   * Previously validated bulk header files which may pull data from backing storage on demand.
   */
  files: BulkHeaderFile[];
  /**
   * Subset of headers currently being "read".
   */
  range: HeightRange;
  /**
   * Maximum buffer size returned from `read()` in bytes.
   */
  maxBufferSize: number;
  /**
   * "Read pointer", the next height to be "read".
   */
  nextHeight: number | undefined;
  constructor(files: BulkHeaderFile[], range?: HeightRange, maxBufferSize?: number);
  protected setRange(range?: HeightRange): void;
  setMaxBufferSize(maxBufferSize: number | undefined): void;
  private getLastFile;
  get heightRange(): HeightRange;
  private getFileForHeight;
  readBufferForHeightOrUndefined(height: number): Promise<Uint8Array | undefined>;
  readBufferForHeight(height: number): Promise<Uint8Array>;
  readHeaderForHeight(height: number): Promise<BaseBlockHeader>;
  readHeaderForHeightOrUndefined(height: number): Promise<BaseBlockHeader | undefined>;
  /**
   * Returns the Buffer of block headers from the given `file` for the given `range`.
   * If `range` is undefined, the file's full height range is read.
   * The returned Buffer will only contain headers in `file` and in `range`
   * @param file
   * @param range
   */
  private readBufferFromFile;
  private nextFile;
  /**
   * @returns an array containing the next `maxBufferSize` bytes of headers from the files.
   */
  read(): Promise<Uint8Array | undefined>;
  /**
   * Reset the reading process and adjust the range to be read to a new subset of what's available...
   * @param range new range for subsequent `read` calls to return.
   * @param maxBufferSize optionally update largest buffer size for `read` to return
   */
  resetRange(range: HeightRange, maxBufferSize?: number): void;
  validateFiles(): Promise<void>;
  exportHeadersToFs(toFs: ChaintracksFsApi, toHeadersPerFile: number, toFolder: string): Promise<void>;
}
declare class BulkFilesReaderFs extends BulkFilesReader {
  fs: ChaintracksFsApi;
  constructor(fs: ChaintracksFsApi, files: BulkHeaderFileFs[], range?: HeightRange, maxBufferSize?: number);
  /**
   * Return a BulkFilesReader configured to access the intersection of `range` and available headers.
   * @param rootFolder
   * @param jsonFilename
   * @param range
   * @returns
   */
  static fromFs(fs: ChaintracksFsApi, rootFolder: string, jsonFilename: string, range?: HeightRange, maxBufferSize?: number): Promise<BulkFilesReaderFs>;
  static writeEmptyJsonFile(fs: ChaintracksFsApi, rootFolder: string, jsonFilename: string): Promise<string>;
  static readJsonFile(fs: ChaintracksFsApi, rootFolder: string, jsonFilename: string, failToEmptyRange?: boolean): Promise<BulkHeaderFilesInfo>;
}
declare class BulkFilesReaderStorage extends BulkFilesReader {
  constructor(storage: ChaintracksStorageBase, files: BulkHeaderFileStorage[], range?: HeightRange, maxBufferSize?: number);
  static fromStorage(storage: ChaintracksStorageBase, fetch?: ChaintracksFetchApi, range?: HeightRange, maxBufferSize?: number): Promise<BulkFilesReaderStorage>;
}
//#endregion
//#region ../src/services/chaintracker/chaintracks/util/ChaintracksFetch.d.ts
declare class ChaintracksFetchError extends Error {
  readonly url: string;
  readonly status: number;
  readonly statusText: string;
  readonly retryAfterMsecs?: number | undefined;
  constructor(message: string, url: string, status: number, statusText: string, retryAfterMsecs?: number | undefined);
  get retryable(): boolean;
}
/**
 * This class implements the ChaintracksFetchApi
 * using the @bsv/sdk `defaultHttpClient`.
 */
declare class ChaintracksFetch implements ChaintracksFetchApi {
  httpClient: HttpClient;
  download(url: string): Promise<Uint8Array>;
  fetchJson<R>(url: string): Promise<R>;
  pathJoin(baseUrl: string, subpath: string): string;
}
declare namespace blockHeaderUtilities_d_exports {
  export { addWork, blockHash, convertBitsToTarget, convertBitsToWork, convertBufferToUint32, convertUint32ToBuffer, deserializeBaseBlockHeader, deserializeBaseBlockHeaders, deserializeBlockHeader, deserializeBlockHeaders, genesisBuffer, genesisHeader, isMoreWork, readUInt32BE, readUInt32LE, serializeBaseBlockHeader, serializeBaseBlockHeaders, sha256HashOfBinaryFile, subWork, swapByteOrder, validateBufferOfHeaders, validateBulkFileData, validateGenesisHeader, validateHeaderDifficulty, validateHeaderFormat, workBNtoBuffer, writeUInt32BE, writeUInt32LE };
}
/**
 * Computes sha256 hash of file contents read as bytes with no encoding.
 * @param filepath Full filepath to file.
 * @param bufferSize Optional read buffer size to use. Defaults to 80,000 bytes. Currently ignored.
 * @returns `{hash, length}` where `hash` is base64 string form of file hash and `length` is file length in bytes.
 */
declare function sha256HashOfBinaryFile(fs: ChaintracksFsApi, filepath: string, _bufferSize?: number): Promise<{
  hash: string;
  length: number;
}>;
/**
 * Validates the contents of a bulk header file.
 * @param bf BulkHeaderFileInfo containing `data` to validate.
 * @param prevHash Required previous header hash.
 * @param prevChainWork Required previous chain work.
 * @param fetch Optional ChaintracksFetchApi instance for fetching data.
 * @returns Validated BulkHeaderFileInfo with `validated` set to true.
 */
declare function validateBulkFileData(bf: BulkHeaderFileInfo, prevHash: string, prevChainWork: string, fetch?: ChaintracksFetchApi): Promise<BulkHeaderFileInfo>;
/**
 * Validate headers contained in an array of bytes. The headers must be consecutive block headers, 80 bytes long,
 *  where the hash of each header equals the previousHash of the following header.
 * @param buffer Buffer of headers to be validated.
 * @param previousHash Expected previousHash of first header.
 * @param offset Optional starting offset within `buffer`.
 * @param count Optional number of headers to validate. Validates to end of buffer if missing.
 * @returns Header hash of last header validated or previousHash if there where none.
 */
declare function validateBufferOfHeaders(buffer: Uint8Array, previousHash: string, offset?: number, count?: number, previousChainWork?: string): {
  lastHeaderHash: string;
  lastChainWork: string | undefined;
};
/**
 * Verifies that buffer begins with valid genesis block header for the specified chain.
 * @param buffer
 * @param chain
 */
declare function validateGenesisHeader(buffer: Uint8Array, chain: Chain): void;
/**
 * @param work chainWork as a BigNumber
 * @returns Converted chainWork value from BN to hex string of 32 bytes.
 */
declare function workBNtoBuffer(work: BigNumber): string;
/**
 * Returns true if work1 is more work (greater than) work2
 */
declare function isMoreWork(work1: string, work2: string): boolean;
/**
 * Add two Buffer encoded chainwork values
 * @returns Sum of work1 + work2 as Buffer encoded chainWork value
 */
declare function addWork(work1: string, work2: string): string;
/**
 * Subtract Buffer encoded chainwork values
 * @returns work1 - work2 as Buffer encoded chainWork value
 */
declare function subWork(work1: string, work2: string): string;
/**
 * Computes "target" value for 4 byte Bitcoin block header "bits" value.
 * @param bits number or converted from Buffer using `readUint32LE`
 * @returns 32 byte Buffer with "target" value
 */
declare function convertBitsToTarget(bits: number | number[]): BigNumber;
/**
 * Computes "chainWork" value for 4 byte Bitcoin block header "bits" value.
 * @param bits number or converted from Buffer using `readUint32LE`
 * @returns 32 byte Buffer with "chainWork" value
 */
declare function convertBitsToWork(bits: number | number[]): string;
declare function deserializeBaseBlockHeaders(buffer: number[] | Uint8Array, offset?: number, count?: number | undefined): BaseBlockHeader[];
declare function deserializeBlockHeaders(firstHeight: number, buffer: number[] | Uint8Array, offset?: number, count?: number | undefined): BlockHeader[];
declare function validateHeaderFormat(header: BlockHeader): void;
/**
 * Ensures that a header has a valid proof-of-work
 * Requires chain is 'main'
 *
 * @param header The header to validate
 *
 * @returns true if the header is valid
 */
declare function validateHeaderDifficulty(hash: Buffer, bits: number): boolean;
/**
 * Computes double sha256 hash of bitcoin block header
 * bytes are reversed to bigendian order
 *
 * If header is a Buffer, it is required to 80 bytes long
 * and in standard block header serialized encoding.
 *
 * @returns doule sha256 hash of header bytes reversed
 * @publicbody
 */
declare function blockHash(header: BaseBlockHeader | number[] | Uint8Array): string;
/**
 * Serializes a block header as an 80 byte Buffer.
 * The exact serialized format is defined in the Bitcoin White Paper
 * such that computing a double sha256 hash of the buffer computes
 * the block hash for the header.
 * @returns 80 byte Buffer
 * @publicbody
 */
declare function serializeBaseBlockHeader(header: BaseBlockHeader, buffer?: number[], offset?: number): number[];
declare function serializeBaseBlockHeaders(headers: BlockHeader[]): Uint8Array;
/**
 * Deserialize a BaseBlockHeader from an 80 byte buffer
 * @publicbody
 */
declare function deserializeBaseBlockHeader(buffer: number[] | Uint8Array, offset?: number): BaseBlockHeader;
declare function deserializeBlockHeader(buffer: number[] | Uint8Array, height: number, offset?: number): BlockHeader;
/**
 * Returns the genesis block for the specified chain.
 * @publicbody
 */
declare function genesisHeader(chain: Chain): BlockHeader;
/**
 * Returns the genesis block for the specified chain.
 * @publicbody
 */
declare function genesisBuffer(chain: Chain): number[];
/**
 * Returns a copy of a Buffer with byte order reversed.
 * @returns new buffer with byte order reversed.
 * @publicbody
 */
declare function swapByteOrder(buffer: number[]): number[];
/**
 * @param num a number value in the Uint32 value range
 * @param littleEndian true for little-endian byte order in Buffer
 * @returns four byte buffer with Uint32 number encoded
 * @publicbody
 */
declare function convertUint32ToBuffer(n: number, littleEndian?: boolean): number[];
declare function writeUInt32LE(n: number, a: number[] | Uint8Array, offset: number): number;
declare function writeUInt32BE(n: number, a: number[] | Uint8Array, offset: number): number;
declare function readUInt32LE(a: number[] | Uint8Array, offset: number): number;
declare function readUInt32BE(a: number[] | Uint8Array, offset: number): number;
/**
 * @param buffer four byte buffer with Uint32 number encoded
 * @param littleEndian true for little-endian byte order in Buffer
 * @returns a number value in the Uint32 value range
 * @publicbody
 */
declare function convertBufferToUint32(buffer: number[] | Uint8Array, littleEndian?: boolean): number;
//#endregion
//#region ../src/CWIStyleWalletManager.d.ts
/**
 * Number of rounds used in PBKDF2 for deriving password keys.
 */
declare const PBKDF2_NUM_ROUNDS = 7777;
/**
 * Default Argon2id parameters for password-key derivation (UMP v3).
 */
declare const ARGON2ID_DEFAULT_ITERATIONS = 7;
declare const ARGON2ID_DEFAULT_MEMORY_KIB = 131072;
declare const ARGON2ID_DEFAULT_PARALLELISM = 1;
declare const ARGON2ID_DEFAULT_HASH_LENGTH = 32;
declare const ARGON2ID_MAX_ITERATIONS = 20;
declare const ARGON2ID_MAX_MEMORY_KIB = 262144;
declare const ARGON2ID_MAX_PARALLELISM = 16;
declare const KDF_MAX_HASH_LENGTH = 64;
declare const PBKDF2_MAX_ITERATIONS = 10000000;
declare const MAX_STATE_SNAPSHOT_BYTES: number;
/**
 * Unique Identifier for the default profile (16 zero bytes).
 */
declare const DEFAULT_PROFILE_ID: number[];
/**
 * Describes the structure of a user profile within the wallet.
 */
interface Profile {
  /**
   * User-defined name for the profile.
   */
  name: string;
  /**
   * Unique 16-byte identifier for the profile.
   */
  id: number[];
  /**
   * 32-byte random pad XOR'd with the root primary key to derive the profile's primary key.
   */
  primaryPad: number[];
  /**
   * 32-byte random pad XOR'd with the root privileged key to derive the profile's privileged key.
   */
  privilegedPad: number[];
  /**
   * Timestamp (seconds since epoch) when the profile was created.
   */
  createdAt: number;
}
/**
 * Describes the structure of a User Management Protocol (UMP) token.
 */
interface UMPToken {
  /**
   * Root Primary key encrypted by the XOR of the password and presentation keys.
   */
  passwordPresentationPrimary: number[];
  /**
   * Root Primary key encrypted by the XOR of the password and recovery keys.
   */
  passwordRecoveryPrimary: number[];
  /**
   * Root Primary key encrypted by the XOR of the presentation and recovery keys.
   */
  presentationRecoveryPrimary: number[];
  /**
   * Root Privileged key encrypted by the XOR of the password and primary keys.
   */
  passwordPrimaryPrivileged: number[];
  /**
   * Root Privileged key encrypted by the XOR of the presentation and recovery keys.
   */
  presentationRecoveryPrivileged: number[];
  /**
   * Hash of the presentation key.
   */
  presentationHash: number[];
  /**
   * PBKDF2 salt used in conjunction with the password to derive the password key.
   */
  passwordSalt: number[];
  /**
   * Hash of the recovery key.
   */
  recoveryHash: number[];
  /**
   * A copy of the presentation key encrypted with the root privileged key.
   */
  presentationKeyEncrypted: number[];
  /**
   * A copy of the recovery key encrypted with the root privileged key.
   */
  recoveryKeyEncrypted: number[];
  /**
   * A copy of the password key encrypted with the root privileged key.
   */
  passwordKeyEncrypted: number[];
  /**
   * Optional field containing the encrypted profile data.
   * JSON string -> Encrypted Bytes using root privileged key.
   */
  profilesEncrypted?: number[];
  /**
   * On-chain UMP protocol version (3 for tokens with KDF metadata).
   */
  umpVersion?: number;
  /**
   * Password-based key derivation function metadata.
   * Present for UMP v3 tokens; absent for legacy tokens.
   */
  passwordKdf?: {
    algorithm: 'pbkdf2-sha512' | 'argon2id';
    iterations: number;
    memoryKiB?: number;
    parallelism?: number;
    hashLength?: number;
  };
  /**
   * Describes the token's location on-chain, if it's already been published.
   */
  currentOutpoint?: OutpointString;
}
/**
 * Configuration options for KDF (Key Derivation Function) used in UMP tokens.
 */
interface KdfConfig {
  /**
   * Algorithm to use for new UMP tokens.
   */
  algorithm?: 'pbkdf2-sha512' | 'argon2id';
  /**
   * Number of iterations/rounds.
   */
  iterations?: number;
  /**
   * Memory size in KiB (Argon2id only).
   */
  memoryKiB?: number;
  /**
   * Degree of parallelism (Argon2id only).
   */
  parallelism?: number;
  /**
   * Hash output length in bytes.
   */
  hashLength?: number;
}
/**
 * Describes a system capable of finding and updating UMP tokens on the blockchain.
 */
interface UMPTokenInteractor {
  /**
   * Locates the latest valid copy of a UMP token (including its outpoint)
   * based on the presentation key hash.
   *
   * @param hash The hash of the presentation key.
   * @returns The UMP token if found; otherwise, undefined.
   * @throws Implementations should throw when no verified token or clean empty response is available.
   */
  findByPresentationKeyHash: (hash: number[]) => Promise<UMPToken | undefined>;
  /**
   * Locates the latest valid copy of a UMP token (including its outpoint)
   * based on the recovery key hash.
   *
   * @param hash The hash of the recovery key.
   * @returns The UMP token if found; otherwise, undefined.
   * @throws Implementations should throw when no verified token or clean empty response is available.
   */
  findByRecoveryKeyHash: (hash: number[]) => Promise<UMPToken | undefined>;
  /**
   * Creates (and optionally consumes the previous version of) a UMP token on-chain.
   *
   * @param wallet            The wallet that might be used to create a new token (MUST be operating under the DEFAULT profile).
   * @param adminOriginator   The domain name of the administrative originator.
   * @param token             The new UMP token to create.
   * @param oldTokenToConsume If provided, the old token that must be consumed in the same transaction.
   * @returns                 The newly created outpoint.
   */
  buildAndSend: (wallet: WalletInterface // This wallet MUST be the one built for the default profile
  , adminOriginator: OriginatorDomainNameStringUnder250Bytes, token: UMPToken, oldTokenToConsume?: UMPToken) => Promise<OutpointString>;
}
interface UMPTokenLookupDiagnostics {
  hostCount: number;
  completedHosts: number;
  successfulHosts: number;
  emptyHosts: number;
  failedHosts: number;
  rejectedHosts: number;
  freeformHosts: number;
  outputCount: number;
  correlationId?: string;
}
type UMPTokenLookupFailureReason = 'lookup-unavailable' | 'lookup-incomplete' | 'token-malformed' | 'token-ambiguous';
/**
 * Raised when a UMP lookup yields neither a verified token nor a clean empty response.
 *
 * Callers must offer retry/recovery rather than treating this error as a new
 * account. Diagnostics contain counts only and never hashes, keys, or tokens.
 */
declare class UMPTokenLookupError extends Error {
  readonly reason: UMPTokenLookupFailureReason;
  readonly diagnostics: UMPTokenLookupDiagnostics;
  readonly code = "WERR_UMP_LOOKUP_INDETERMINATE";
  constructor(reason: UMPTokenLookupFailureReason, diagnostics: UMPTokenLookupDiagnostics, options?: {
    cause?: unknown;
  });
}
/**
 * @class OverlayUMPTokenInteractor
 *
 * A concrete implementation of the UMPTokenInteractor interface that interacts
 * with Overlay Services and the UMP (User Management Protocol) topic. This class
 * is responsible for:
 *
 * 1) Locating UMP tokens via overlay lookups (ls_users).
 * 2) Creating and publishing new or updated UMP token outputs on-chain under
 *    the "tm_users" topic.
 * 3) Consuming (spending) an old token if provided.
 */
declare class OverlayUMPTokenInteractor implements UMPTokenInteractor {
  /**
   * A `LookupResolver` instance used to query overlay networks.
   */
  private readonly resolver;
  /**
   * A SHIP broadcaster that can be used to publish updated UMP tokens
   * under the `tm_users` topic to overlay service peers.
   */
  private readonly broadcaster;
  private readonly telemetry;
  /**
   * Construct a new OverlayUMPTokenInteractor.
   *
   * @param resolver     A LookupResolver instance for performing overlay queries (ls_users).
   * @param broadcaster  A SHIPBroadcaster instance for sharing new or updated tokens across the `tm_users` overlay.
   */
  constructor(resolver?: LookupResolver, broadcaster?: SHIPBroadcaster, telemetry?: TelemetryConfig);
  /**
   * Finds a UMP token on-chain by the given presentation key hash, if it exists.
   * Uses the ls_users overlay service to perform the lookup.
   *
   * @param hash The 32-byte SHA-256 hash of the presentation key.
   * @returns A UMPToken object (including currentOutpoint) if found, otherwise undefined.
   */
  findByPresentationKeyHash(hash: number[]): Promise<UMPToken | undefined>;
  /**
   * Finds a UMP token on-chain by the given recovery key hash, if it exists.
   * Uses the ls_users overlay service to perform the lookup.
   *
   * @param hash The 32-byte SHA-256 hash of the recovery key.
   * @returns A UMPToken object (including currentOutpoint) if found, otherwise undefined.
   */
  findByRecoveryKeyHash(hash: number[]): Promise<UMPToken | undefined>;
  private findToken;
  /**
   * Picks the newest rendition among distinct verified tokens, when possible.
   *
   * The on-chain UMP protocol expresses token updates by consumption: the
   * transaction creating a new rendition spends the previous rendition's
   * outpoint (there is no rendition counter field in the current format).
   * A candidate is therefore superseded when any other candidate's ancestry
   * (available from its BEEF) spends the candidate's outpoint.
   *
   * @returns The single unsuperseded candidate, or undefined when supersession
   * cannot be established for every stale candidate (e.g. forked tokens).
   */
  private resolveNewestToken;
  /**
   * Whether `tx` spends an input whose source output (available in the BEEF)
   * decodes as a UMP token sharing the candidate's presentation or recovery
   * hash — on-chain proof that the candidate is an update of a same-identity
   * predecessor rather than an independently minted token.
   */
  private consumesSameIdentityToken;
  /**
   * Accumulates every outpoint spent by `tx` and by the ancestor transactions
   * embedded in its BEEF, so supersession is detected even when intermediate
   * renditions are absent from the lookup answer. Iterative so arbitrarily
   * long update chains cannot exhaust the call stack.
   */
  private collectSpentOutpoints;
  private emptyLookupDiagnostics;
  private toLookupDiagnostics;
  private lookupDiagnosticAttributes;
  private captureLookupCompleted;
  private captureLookupFailure;
  /**
   * Creates or updates (replaces) a UMP token on-chain. If `oldTokenToConsume` is provided,
   * it is spent in the same transaction that creates the new token output. The new token is
   * then broadcast and published under the `tm_users` topic using a SHIP broadcast, ensuring
   * overlay participants see the updated token.
   *
   * @param wallet            The wallet used to build and sign the transaction (MUST be operating under the DEFAULT profile).
   * @param adminOriginator   The domain/FQDN of the administrative originator (wallet operator).
   * @param token             The new UMPToken to create on-chain.
   * @param oldTokenToConsume Optionally, an existing token to consume/spend in the same transaction.
   * @returns The outpoint of the newly created UMP token (e.g. "abcd1234...ef.0").
   */
  buildAndSend(wallet: WalletInterface // This wallet MUST be the one built for the default profile
  , adminOriginator: OriginatorDomainNameStringUnder250Bytes, token: UMPToken, oldTokenToConsume?: UMPToken): Promise<OutpointString>;
  /** Assembles the ordered number[][] fields array from a UMPToken. */
  private buildUMPTokenFields;
  /** Looks up the old token on the overlay; returns undefined resolved token if not found. */
  private resolveOldTokenInput;
  /** Creates the UMP action without dropping a required old-token input on failure. */
  private createUMPAction;
  /** Handles a fully-finalized (no signable tx) createAction result — broadcasts and returns outpoint. */
  private broadcastFinishedUMPAction;
  /** Signs the old-token input and broadcasts — used during UMP token renewal. */
  private signAndBroadcastWithOldToken;
  /** Signs without input spending and broadcasts — used when creating a brand-new UMP token. */
  private signAndBroadcastNewToken;
  private assertSuccessfulBroadcast;
  /**
   * Attempts to parse a LookupAnswer from the UMP lookup service. If successful,
   * extracts the token fields from the resulting transaction and constructs
   * a UMPToken object.
   *
   * @param answer The LookupAnswer returned by a query to ls_users.
   * @returns The parsed UMPToken or `undefined` if none found/decodable.
   */
  private parseLookupAnswer;
  private parseLookupAnswers;
  private parseLookupOutput;
  /**
   * Finds by outpoint for unlocking / spending previous tokens.
   * @param outpoint The outpoint we are searching by
   * @returns The result so that we can use it to unlock the transaction
   */
  private findByOutpoint;
}
/**
 * Manages a "CWI-style" wallet that uses a UMP token and a
 * multi-key authentication scheme (password, presentation key, and recovery key),
 * supporting multiple user profiles under a single account.
 */
declare class CWIStyleWalletManager implements WalletInterface {
  /**
   * Whether the user is currently authenticated (i.e., root keys are available).
   */
  authenticated: boolean;
  /**
   * Resolves once the optional snapshot (if provided to the constructor) has been
   * fully loaded and the wallet is ready to accept calls.
   * When no snapshot is provided this resolves immediately.
   * Await `ready` before calling wallet methods after constructing with a snapshot.
   */
  get ready(): Promise<void>;
  private _readyInit?;
  private readonly _initSnapshot?;
  /**
   * The domain name of the administrative originator (wallet operator / vendor, or your own).
   */
  private readonly adminOriginator;
  /**
   * The system that locates and publishes UMP tokens on-chain.
   */
  private readonly UMPTokenInteractor;
  /**
   * Privacy-bounded diagnostic channel for wallet state transitions.
   */
  protected readonly telemetry: Telemetry;
  /**
   * A function called to persist the newly generated recovery key.
   * It should generally trigger a UI prompt where the user is asked to write it down.
   */
  private readonly recoveryKeySaver;
  /**
   * Asks the user to enter their password, for a given reason.
   * The test function can be used to see if the password is correct before resolving.
   * Only resolve with the correct password or reject with an error.
   * Resolving with an incorrect password will throw an error.
   */
  private readonly passwordRetriever;
  /**
   * Optional function to fund a new Wallet after the new-user flow.
   */
  private readonly newWalletFunder?;
  /**
   * Builds the underlying wallet for a specific profile.
   */
  private readonly walletBuilder;
  /**
   * Current mode of authentication.
   */
  authenticationMode: 'presentation-key-and-password' | 'presentation-key-and-recovery-key' | 'recovery-key-and-password';
  /**
   * Indicates new user or existing user flow.
   */
  authenticationFlow: 'unknown' | 'new-user' | 'existing-user';
  /**
   * The current UMP token in use.
   */
  private currentUMPToken?;
  /**
   * Temporarily retained presentation key.
   */
  private presentationKey?;
  /**
   * Temporarily retained recovery key.
   */
  private recoveryKey?;
  /**
   * The user's *root* primary key, derived from authentication factors.
   */
  private rootPrimaryKey?;
  /**
   * The currently active profile ID (null or DEFAULT_PROFILE_ID means default profile).
   */
  private activeProfileId;
  /**
   * List of loaded non-default profiles.
   */
  private profiles;
  /**
   * The underlying wallet instance for the *active* profile.
   */
  private underlying?;
  /**
   * Privileged key manager associated with the *root* keys, aware of the active profile.
   */
  private rootPrivilegedKeyManager?;
  /**
   * KDF configuration for new UMP tokens. Defaults to Argon2id for v3 tokens.
   */
  private readonly kdfConfig;
  /**
   * Constructs a new CWIStyleWalletManager.
   *
   * @param adminOriginator   The domain name of the administrative originator.
   * @param walletBuilder     A function that can build an underlying wallet instance for a profile.
   * @param interactor        An instance of UMPTokenInteractor.
   * @param recoveryKeySaver  A function to persist a new recovery key.
   * @param passwordRetriever A function to request the user's password.
   * @param newWalletFunder   Optional function to fund a new wallet.
   * @param stateSnapshot     Optional previously saved state snapshot.
   * @param kdfConfig         Optional KDF configuration for new UMP tokens.
   */
  constructor(...[adminOriginator, walletBuilder, interactor, recoveryKeySaver, passwordRetriever, newWalletFunder, stateSnapshot, kdfConfig, telemetry]: [adminOriginator: OriginatorDomainNameStringUnder250Bytes, walletBuilder: (profilePrimaryKey: number[], profilePrivilegedKeyManager: PrivilegedKeyManager, profileId: number[]) => Promise<WalletInterface>, interactor: UMPTokenInteractor | undefined, recoveryKeySaver: (key: number[]) => Promise<true>, passwordRetriever: (reason: string, test: (passwordCandidate: string) => boolean | Promise<boolean>) => Promise<string>, newWalletFunder?: (presentationKey: number[], wallet: WalletInterface, adminOriginator: OriginatorDomainNameStringUnder250Bytes) => Promise<void>, stateSnapshot?: number[], kdfConfig?: KdfConfig, telemetry?: TelemetryConfig]);
  private _init;
  /**
   * Provides the presentation key.
   */
  providePresentationKey(key: number[]): Promise<void>;
  /**
   * Provides the password.
   */
  providePassword(password: string): Promise<void>;
  /** Handles the password step for an existing user — derives keys, sets up infrastructure. */
  private handleExistingUserPassword;
  /** Handles the password step for a new user — generates keys, builds UMP token, publishes on-chain. */
  private handleNewUserPassword;
  /**
   * Provides the recovery key.
   */
  provideRecoveryKey(recoveryKey: number[]): Promise<void>;
  /**
   * Saves the current wallet state (root key, UMP token, active profile) into an encrypted snapshot.
   * Version 2 format: [1 byte version=2] + [32 byte snapshot key] + [16 byte activeProfileId] + [encrypted payload]
   * Encrypted Payload: [32 byte rootPrimaryKey] + [varint token length + serialized UMP token]
   *
   * @returns Encrypted snapshot bytes.
   */
  saveSnapshot(): number[];
  /**
   * Loads a previously saved state snapshot. Restores root key, UMP token, profiles, and active profile.
   * Handles Version 1 (legacy) and Version 2 formats.
   *
   * @param snapshot Encrypted snapshot bytes.
   */
  loadSnapshot(snapshot: number[]): Promise<void>;
  syncUMPToken(): Promise<boolean>;
  /**
   * Destroys the wallet state, clearing keys, tokens, and profiles.
   */
  destroy(): void;
  /**
   * Lists all available profiles, including the default profile.
   * @returns Array of profile info objects, including an 'active' flag.
   */
  listProfiles(): Array<{
    id: number[];
    name: string;
    createdAt: number | null;
    active: boolean;
    identityKey: string;
  }>;
  /**
   * Adds a new profile with the given name.
   * Generates necessary pads and updates the UMP token.
   * Does not switch to the new profile automatically.
   *
   * @param name The desired name for the new profile.
   * @returns The ID of the newly created profile.
   */
  addProfile(name: string): Promise<number[]>;
  /**
   * Deletes a profile by its ID.
   * Cannot delete the default profile. If the active profile is deleted,
   * it switches back to the default profile.
   *
   * @param profileId The 16-byte ID of the profile to delete.
   */
  deleteProfile(profileId: number[]): Promise<void>;
  /**
   * Switches the active profile. This re-derives keys and rebuilds the underlying wallet.
   *
   * @param profileId The 16-byte ID of the profile to switch to (use DEFAULT_PROFILE_ID for default).
   */
  switchProfile(profileId: number[]): Promise<void>;
  /**
   * Changes the user's password. Re-wraps keys and updates the UMP token.
   */
  changePassword(newPassword: string): Promise<void>;
  /**
   * Retrieves the current recovery key. Requires privileged access.
   */
  getRecoveryKey(): Promise<number[]>;
  /**
   * Changes the user's recovery key. Prompts user to save the new key.
   */
  changeRecoveryKey(): Promise<void>;
  /**
   * Changes the user's presentation key.
   */
  changePresentationKey(newPresentationKey: number[]): Promise<void>;
  /**
   * Performs XOR operation on two byte arrays.
   */
  private XOR;
  /**
   * Helper to decrypt a specific factor (key) stored encrypted in the UMP token.
   * Requires the root privileged key manager.
   * @param factorName Name of the factor to decrypt ('passwordKey', 'presentationKey', 'recoveryKey', 'privilegedKey').
   * @param getRoot If true and factorName is 'privilegedKey', returns the root privileged key bytes directly.
   * @returns The decrypted key bytes.
   */
  private getFactor;
  /**
   * Recomputes UMP token fields with updated factors and profiles, then publishes the update.
   * This operation requires the *root* privileged key and the *default* profile wallet.
   */
  private updateAuthFactors;
  /**
   * Serializes a UMP token to binary format (Version 3 with KDF metadata, Version 2 with profiles).
   * V3 Layout: [1 byte version=3] + [11 * (varint len + bytes) for standard fields] + [1 byte profile_flag] + [IF flag=1 THEN varint len + profile bytes] + [1 byte kdf_flag] + [IF flag=1 THEN kdf metadata] + [varint len + outpoint bytes]
   */
  private serializeUMPToken;
  /**
   * Deserializes a UMP token from binary format (Handles Version 1, 2, and 3).
   */
  private deserializeUMPToken;
  /**
   * Sets up the root key infrastructure after authentication or loading from snapshot.
   * Initializes the root primary key, root privileged key manager, loads profiles,
   * and sets the authenticated flag. Does NOT switch profile initially.
   *
   * @param rootPrimaryKey      The user's root primary key (32 bytes).
   * @param ephemeralRootPrivilegedKey Optional root privileged key (e.g., during recovery flows).
   */
  private setupRootInfrastructure;
  private checkAuthAndUnderlying;
  getPublicKey(args: GetPublicKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetPublicKeyResult>;
  revealCounterpartyKeyLinkage(args: RevealCounterpartyKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealCounterpartyKeyLinkageResult>;
  revealSpecificKeyLinkage(args: RevealSpecificKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealSpecificKeyLinkageResult>;
  encrypt(args: WalletEncryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletEncryptResult>;
  decrypt(args: WalletDecryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletDecryptResult>;
  createHmac(args: CreateHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateHmacResult>;
  verifyHmac(args: VerifyHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifyHmacResult>;
  createSignature(args: CreateSignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateSignatureResult>;
  verifySignature(args: VerifySignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifySignatureResult>;
  createAction(args: CreateActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateActionResult>;
  signAction(args: SignActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<SignActionResult>;
  abortAction(args: AbortActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AbortActionResult>;
  listActions(args: ListActionsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListActionsResult>;
  internalizeAction(args: InternalizeActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<InternalizeActionResult>;
  listOutputs(args: ListOutputsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListOutputsResult>;
  relinquishOutput(args: RelinquishOutputArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishOutputResult>;
  acquireCertificate(args: AcquireCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AcquireCertificateResult>;
  listCertificates(args: ListCertificatesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListCertificatesResult>;
  proveCertificate(args: ProveCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ProveCertificateResult>;
  relinquishCertificate(args: RelinquishCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishCertificateResult>;
  discoverByIdentityKey(args: DiscoverByIdentityKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>;
  discoverByAttributes(args: DiscoverByAttributesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>;
  isAuthenticated(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>;
  waitForAuthentication(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>;
  getHeight(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeightResult>;
  getHeaderForHeight(args: GetHeaderArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeaderResult>;
  getNetwork(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetNetworkResult>;
  getVersion(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetVersionResult>;
}
//#endregion
//#region ../src/monitor/tasks/WalletMonitorTask.d.ts
/**
 * A monitor task performs some periodic or state triggered maintenance function
 * on the data managed by a wallet (Bitcoin UTXO manager, aka wallet)
 *
 * The monitor maintains a collection of tasks.
 *
 * It runs each task's non-asynchronous trigger to determine if the runTask method needs to run.
 *
 * Tasks that need to be run are run consecutively by awaiting their async runTask override method.
 *
 * The monitor then waits a fixed interval before repeating...
 *
 * Tasks may use the monitor_events table to persist their execution history.
 * This is done by accessing the wathman.storage object.
 */
declare abstract class WalletMonitorTask {
  monitor: Monitor;
  name: string;
  /**
   * Set by monitor each time runTask completes
   */
  lastRunMsecsSinceEpoch: number;
  storage: MonitorStorage;
  constructor(monitor: Monitor, name: string);
  /**
   * Override to handle async task setup configuration.
   *
   * Called before first call to `trigger`
   */
  asyncSetup(): Promise<void>;
  /**
   * Return true if `runTask` needs to be called now.
   */
  abstract trigger(nowMsecsSinceEpoch: number): {
    run: boolean;
  };
  abstract runTask(): Promise<string>;
}
//#endregion
//#region ../src/monitor/tasks/TaskPurge.d.ts
/**
 * The database stores a variety of data that may be considered transient.
 *
 * At one extreme, the data that must be preserved:
 *   - unspent outputs (UTXOs)
 *   - in-use metadata (labels, baskets, tags...)
 *
 * At the other extreme, everything can be preserved to fully log all transaction creation and processing actions.
 *
 * The following purge actions are available to support sustained operation:
 *   - Failed transactions, delete all associated data including:
 *       + Delete tag and label mapping records
 *       + Delete output records
 *       + Delete transaction records
 *       + Delete mapi_responses records
 *       + Delete proven_tx_reqs records
 *       + Delete commissions records
 *       + Update output records marked spentBy failed transactions
 *   - Completed transactions, delete transient data including:
 *       + transactions table set truncatedExternalInputs = null
 *       + transactions table set beef = null
 *       + transactions table set rawTx = null
 *       + Delete mapi_responses records
 *       + proven_tx_reqs table delete records
 */
interface TaskPurgeParams extends PurgeParams {}
//#endregion
//#region ../src/monitor/Monitor.d.ts
type MonitorStorage = WalletStorageManager;
type MonitorStartupTaskMode = 'none' | 'default' | 'multiuser' | 'alltoother';
interface MonitorOptions {
  chain: Chain;
  services: Services | WalletServices;
  storage: MonitorStorage;
  chaintracks: ChaintracksClientApi;
  chaintracksWithEvents?: ChaintracksClientApi;
  startupTaskMode?: MonitorStartupTaskMode;
  /**
   * How many msecs to wait after each getMerkleProof service request.
   */
  msecsWaitPerMerkleProofServiceReq: number;
  taskRunWaitMsecs: number;
  abandonedMsecs: number;
  unprovenAttemptsLimitTest: number;
  unprovenAttemptsLimitMain: number;
  /**
   * Maximum number of times a broadcast transaction may be reset to 'unsent' for
   * rebroadcast after proof check timeout (circuit breaker).
   *
   * Default 0 means unlimited — the tx is rebroadcast indefinitely until a proof
   * is found. Set to a positive integer to cap rebroadcast cycles; once the limit
   * is reached the req is marked 'invalid'.
   */
  maxRebroadcastAttempts: number;
  /**
   * Stable callback token for ARC SSE event streaming.
   * When set, TaskArcadeSSE will open an SSE connection to Arcade's
   * /events endpoint and receive real-time transaction status updates.
   * Must match the X-CallbackToken header sent during broadcast.
   */
  callbackToken?: string;
  /** Load persisted SSE lastEventId (e.g. from SQLite) for catchup on startup */
  loadLastSSEEventId?: () => Promise<string | undefined>;
  /** Save SSE lastEventId to persistent storage */
  saveLastSSEEventId?: (lastEventId: string) => Promise<void>;
  /** The react-native-sse EventSource class for SSE support in React Native */
  EventSourceClass?: any;
  /**
   * These are hooks for a wallet-toolbox client to get transaction updates.
   */
  onTransactionBroadcasted?: (broadcastResult: ReviewActionResult) => Promise<void>;
  onTransactionProven?: (txStatus: ProvenTransactionStatus) => Promise<void>;
  onTransactionStatusChanged?: (txid: string, newStatus: string) => Promise<void>;
}
/**
 * Background task to make sure transactions are processed, transaction proofs are received and propagated,
 * and potentially that reorgs update proofs that were already received.
 */
declare class Monitor {
  static createDefaultWalletMonitorOptions(chain: Chain, storage: MonitorStorage, services?: Services, chaintracks?: ChaintracksClientApi, startupTaskMode?: MonitorStartupTaskMode): MonitorOptions;
  options: MonitorOptions;
  services: Services | WalletServices;
  chain: Chain;
  storage: MonitorStorage;
  chaintracks: ChaintracksClientApi;
  chaintracksWithEvents?: ChaintracksClientApi;
  reorgSubscriptionPromise?: Promise<string>;
  headersSubscriptionPromise?: Promise<string>;
  onTransactionBroadcasted?: (broadcastResult: ReviewActionResult) => Promise<void>;
  onTransactionProven?: (txStatus: ProvenTransactionStatus) => Promise<void>;
  onTransactionStatusChanged?: (txid: string, newStatus: string) => Promise<void>;
  /**
   * Resolves once the optional Chaintracks subscriptions have been registered.
   * Await this before calling `startTasks()` if `chaintracksWithEvents` is provided
   * and you need subscriptions to be active before the first task loop runs.
   */
  get ready(): Promise<void>;
  private _readyInit?;
  constructor(options: MonitorOptions);
  private _init;
  private applyStartupTaskMode;
  destroy(): Promise<void>;
  static readonly oneSecond = 1000;
  static readonly oneMinute: number;
  static readonly oneHour: number;
  static readonly oneDay: number;
  static readonly oneWeek: number;
  /**
   * _tasks are typically run by the scheduler but may also be run by runTask.
   */
  _tasks: WalletMonitorTask[];
  /**
   * _otherTasks can be run by runTask but not by scheduler.
   */
  _otherTasks: WalletMonitorTask[];
  _tasksRunning: boolean;
  defaultPurgeParams: TaskPurgeParams;
  addAllTasksToOther(): void;
  /**
   * Default tasks with settings appropriate for a single user storage
   */
  addDefaultTasks(): void;
  /**
   * Tasks appropriate for multi-user storage
   */
  addMultiUserTasks(): void;
  addTask(task: WalletMonitorTask): void;
  removeTask(name: string): void;
  runTask(name: string): Promise<string>;
  runOnce(): Promise<void>;
  private setupTasksOnce;
  private tasksReadyToRun;
  private runScheduledTask;
  private logTaskError;
  _runAsyncSetup: boolean;
  _tasksRunningPromise?: PromiseLike<void>;
  resolveCompletion: ((value: void | PromiseLike<void>) => void) | undefined;
  startTasks(): Promise<void>;
  logEvent(event: string, details?: string): Promise<void>;
  stopTasks(): void;
  lastNewHeader: BlockHeader | undefined;
  lastNewHeaderWhen: Date | undefined;
  /**
   * Process new chain header event received from Chaintracks
   *
   * Kicks processing 'unconfirmed' and 'unmined' request processing.
   *
   * @param reqs
   */
  processNewBlockHeader(header: BlockHeader): void;
  /**
   * This is a function run from a TaskSendWaiting Monitor task.
   *
   * This allows the user of wallet-toolbox to 'subscribe' for transaction broadcast updates.
   *
   * @param broadcastResult
   */
  callOnBroadcastedTransaction(broadcastResult: ReviewActionResult): void;
  /**
   * This is a function run from a TaskCheckForProofs Monitor task.
   *
   * This allows the user of wallet-toolbox to 'subscribe' for transaction updates.
   *
   * @param txStatus
   */
  callOnProvenTransaction(txStatus: ProvenTransactionStatus): void;
  /**
   * Called by TaskArcadeSSE when an SSE status event is received from Arcade.
   */
  callOnTransactionStatusChanged(txid: string, newStatus: string): void;
  /**
   * Fetch pending transaction status events from Arcade on demand.
   * Call this on app open, balance refresh, transaction list view, etc.
   */
  fetchSSEEvents(): Promise<number>;
  deactivatedHeaders: DeactivedHeader[];
  /**
   * Process reorg event received from Chaintracks
   *
   * Reorgs can move recent transactions to new blocks at new index positions.
   * Affected transaction proofs become invalid and must be updated.
   *
   * It is possible for a transaction to become invalid.
   *
   * Coinbase transactions always become invalid.
   */
  processReorg(depth: number, oldTip: BlockHeader, newTip: BlockHeader, deactivatedHeaders?: BlockHeader[]): void;
  /**
   * Handler for new header events from Chaintracks.
   *
   * To minimize reorg processing, new headers are aged before processing via TaskNewHeader.
   * Therefore this handler is intentionally a no-op.
   *
   * @param header
   */
  processHeader(header: BlockHeader): void;
}
interface DeactivedHeader {
  /**
   * To control aging of notification before pursuing updated proof data.
   */
  whenMsecs: number;
  /**
   * Number of attempts made to process the header.
   * Supports returning deactivation notification to the queue if proof data is not yet available.
   */
  tries: number;
  /**
   * The deactivated block header.
   */
  header: BlockHeader;
}
//#endregion
//#region ../src/services/createDefaultWalletServicesOptions.d.ts
/**
 * Returns the credential-free default ChainTracks client for a supported
 * public network, or an operator-configured client for stn/tstn.
 */
declare function createDefaultChaintracksClient(chain: Exclude<Chain, 'mock'>): ChaintracksClientApi;
declare function createDefaultWalletServicesOptions(...[chain, arcCallbackUrl, arcCallbackToken, taalArcApiKey, gorillaPoolArcApiKey, bitailsApiKey, deploymentId, chaintracks, arcadeUrl, arcadeApiKey, arcadeCallbackToken]: [chain: Chain, arcCallbackUrl?: string, arcCallbackToken?: string, taalArcApiKey?: string, gorillaPoolArcApiKey?: string, bitailsApiKey?: string, deploymentId?: string, chaintracks?: ChaintracksClientApi,
/**
 * Optional Arcade endpoint. When provided (or when a default exists for the chain via
 * `arcadeDefaultUrl`), Arcade is registered as the primary broadcaster ahead of ARC.
 * Pass an empty string to explicitly disable the per-chain default.
 */
arcadeUrl?: string,
/** Server-level API key (Bearer) for the Arcade endpoint, if it requires auth. */
arcadeApiKey?: string,
/**
 * Stable SSE callback token. Must match the Monitor's `callbackToken` so Arcade routes
 * each broadcast transaction's status events to this wallet's `/events` subscription.
 */
arcadeCallbackToken?: string]): WalletServicesOptions;
/**
 * Default Arcade (bsv-blockchain/arcade) endpoint per chain.
 * Returns undefined when no public default is known for the chain.
 */
declare function arcadeDefaultUrl(chain: Chain): string | undefined;
declare function arcDefaultUrl(chain: Chain): string;
declare function arcGorillaPoolUrl(chain: Chain): string | undefined;
//#endregion
//#region ../src/services/providers/ArcSSEClient.d.ts
/**
 * Client for Arcade transaction status updates.
 *
 * Uses react-native-sse EventSource to connect to Arcade's
 * `GET /events?callbackToken=<token>` endpoint for real-time
 * status updates via SSE.
 *
 * Supports on-demand fetching via fetchEvents() for use on
 * app open, balance refresh, transaction list view, etc.
 * The EventSource stays connected between fetches for live updates.
 */
interface ArcSSEEvent {
  txid: string;
  txStatus: string;
  timestamp: string;
}
interface ArcSSEClientOptions {
  /** Base URL of the Arcade instance (e.g. "https://arcade-us-1.bsvb.tech") */
  baseUrl: string;
  /** Stable per-wallet token matching the X-CallbackToken sent on broadcast */
  callbackToken: string;
  /** Server-level API key for Authorization header (from ArcConfig.apiKey) */
  arcApiKey?: string;
  /** Called for each status event received */
  onEvent: (event: ArcSSEEvent) => void;
  /** Called when a connection error occurs */
  onError?: (error: Error) => void;
  /** Initial lastEventId for catchup */
  lastEventId?: string;
  /** Called whenever lastEventId changes, for persistence to storage */
  onLastEventIdChanged?: (lastEventId: string) => void;
  /** The react-native-sse EventSource class — passed in to avoid import from wallet-toolbox */
  EventSourceClass: any;
}
declare class ArcSSEClient {
  private readonly options;
  private _lastEventId;
  private es;
  private readonly url;
  private readonly displayUrl;
  private connected;
  private connecting;
  constructor(options: ArcSSEClientOptions);
  get lastEventId(): string | undefined;
  /**
   * Open the SSE connection. Events will be dispatched via onEvent as they arrive.
   */
  connect(): void;
  /** Close the connection and clean up */
  close(): void;
  /**
   * Ensure connection is open. If already connected, this is a no-op.
   * If not connected, opens a new connection with catchup from lastEventId.
   * Returns immediately — events arrive asynchronously via onEvent callback.
   */
  fetchEvents(): Promise<number>;
}
//#endregion
//#region ../src/signer/WalletSigner.d.ts
declare class WalletSigner {
  isWalletSigner: true;
  chain: Chain;
  keyDeriver: KeyDeriverApi;
  storage: WalletStorageManager;
  constructor(chain: Chain, keyDeriver: KeyDeriverApi, storage: WalletStorageManager);
}
//#endregion
//#region ../src/SimpleWalletManager.d.ts
/**
 * SimpleWalletManager is a slimmed-down wallet manager that only requires two things to authenticate:
 *  1. A primary key (32 bytes), which represents the core secret for the wallet.
 *  2. A privileged key manager (an instance of `PrivilegedKeyManager`), responsible for
 *     more sensitive operations.
 *
 * Once both pieces are provided (or if a snapshot containing the primary key is loaded,
 * and the privileged key manager is provided separately), the wallet becomes authenticated.
 *
 * After authentication, calls to the standard wallet methods (`createAction`, `signAction`, etc.)
 * are proxied to an underlying `WalletInterface` instance returned by a user-supplied `walletBuilder`.
 *
 * **Important**: This manager does not handle user password flows, recovery, or on-chain
 * token management. It is a straightforward wrapper that ensures the user has provided
 * both their main secret (primary key) and a privileged key manager before allowing usage.
 *
 * It also prevents calls from the special "admin originator" from being used externally.
 * (Any call that tries to use the admin originator as its originator, other than the manager itself,
 * will result in an error, ensuring that only internal operations can use that originator.)
 *
 * The manager can also save and load snapshots of its state. In this simplified version,
 * the snapshot only contains the primary key. If you load a snapshot, you still need to
 * re-provide the privileged key manager to complete authentication.
 */
declare class SimpleWalletManager implements WalletInterface {
  /**
   * Whether the user is currently authenticated (meaning both the primary key
   * and privileged key manager have been provided).
   */
  authenticated: boolean;
  /**
   * Resolves once the optional snapshot (if provided to the constructor) has been
   * fully loaded and the wallet is ready to accept calls.
   * When no snapshot is provided this resolves immediately.
   * Await `ready` before calling wallet methods after constructing with a snapshot.
   */
  get ready(): Promise<void>;
  private _readyInit?;
  private readonly _initSnapshot?;
  /**
   * The domain name of the administrative originator (wallet operator / vendor, or your own).
   */
  private readonly adminOriginator;
  /**
   * A function that, given the user's primary key and privileged key manager,
   * returns a new `WalletInterface` instance that handles the actual signing,
   * encryption, transaction building, etc.
   */
  private readonly walletBuilder;
  /**
   * The underlying wallet instance that is built once authenticated.
   */
  private underlying?;
  /**
   * The privileged key manager, responsible for sensitive tasks.
   */
  private underlyingPrivilegedKeyManager?;
  /**
   * The primary key (32 bytes) that unlocks the wallet functionality.
   */
  private primaryKey?;
  /**
   * Constructs a new `SimpleWalletManager`.
   *
   * @param adminOriginator The domain name of the administrative originator.
   * @param walletBuilder   A function that, given a primary key and privileged key manager,
   *                        returns a fully functional `WalletInterface`.
   * @param stateSnapshot   If provided, a previously saved snapshot of the wallet's state.
   *                        If the snapshot contains a primary key, it will be loaded immediately
   *                        (though you will still need to provide a privileged key manager to authenticate).
   */
  constructor(adminOriginator: OriginatorDomainNameStringUnder250Bytes, walletBuilder: (primaryKey: number[], privilegedKeyManager: PrivilegedKeyManager) => Promise<WalletInterface>, stateSnapshot?: number[]);
  private _init;
  /**
   * Provides the primary key (32 bytes) needed for authentication.
   * If a privileged key manager has already been provided, we attempt to build
   * the underlying wallet. Otherwise, we wait until the manager is also provided.
   *
   * @param key A 32-byte primary key.
   */
  providePrimaryKey(key: number[]): Promise<void>;
  /**
   * Provides the privileged key manager needed for sensitive tasks.
   * If a primary key has already been provided (or loaded from a snapshot),
   * we attempt to build the underlying wallet. Otherwise, we wait until the key is provided.
   *
   * @param manager An instance of `PrivilegedKeyManager`.
   */
  providePrivilegedKeyManager(manager: PrivilegedKeyManager): Promise<void>;
  /**
   * Internal method that checks if we have both the primary key and privileged manager.
   * If so, we build the underlying wallet instance and become authenticated.
   */
  private tryBuildUnderlying;
  /**
   * Destroys the underlying wallet, returning to a default (unauthenticated) state.
   *
   * This clears the primary key, the privileged key manager, and the `authenticated` flag.
   */
  destroy(): void;
  /**
   * Saves the current wallet state (including just the primary key)
   * into an encrypted snapshot. This snapshot can be stored and later
   * passed to `loadSnapshot` to restore the primary key (and partially authenticate).
   *
   * **Note**: The snapshot does NOT include the privileged key manager.
   * You must still provide that separately after loading the snapshot
   * in order to complete authentication.
   *
   * @remarks
   * Storing the snapshot (which contains the primary key) provides a significant
   * portion of the wallet's secret material. It must be protected carefully.
   *
   * @returns A byte array representing the encrypted snapshot.
   * @throws {Error} if no primary key is currently set.
   */
  saveSnapshot(): number[];
  /**
   * Loads a previously saved state snapshot (produced by `saveSnapshot`).
   * This will restore the primary key but will **not** restore the privileged key manager
   * (that must be provided separately to complete authentication).
   *
   * @param snapshot A byte array that was previously returned by `saveSnapshot`.
   * @throws {Error} If the snapshot format is invalid or decryption fails.
   */
  loadSnapshot(snapshot: number[]): Promise<void>;
  /**
   * Returns whether the user is currently authenticated (the wallet has a primary key
   * and a privileged key manager). If not authenticated, an error is thrown.
   *
   * @param _ Not used in this manager.
   * @param originator The originator domain, which must not be the admin originator.
   * @throws If not authenticated, or if the originator is the admin.
   */
  isAuthenticated(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>;
  /**
   * Blocks until the user is authenticated (by providing primaryKey and privileged manager).
   * If not authenticated yet, it waits until that occurs.
   *
   * @param _ Not used in this manager.
   * @param originator The originator domain, which must not be the admin originator.
   * @throws If the originator is the admin.
   */
  waitForAuthentication(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>;
  getPublicKey(args: GetPublicKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetPublicKeyResult>;
  revealCounterpartyKeyLinkage(args: RevealCounterpartyKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealCounterpartyKeyLinkageResult>;
  revealSpecificKeyLinkage(args: RevealSpecificKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealSpecificKeyLinkageResult>;
  encrypt(args: WalletEncryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletEncryptResult>;
  decrypt(args: WalletDecryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletDecryptResult>;
  createHmac(args: CreateHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateHmacResult>;
  verifyHmac(args: VerifyHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifyHmacResult>;
  createSignature(args: CreateSignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateSignatureResult>;
  verifySignature(args: VerifySignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifySignatureResult>;
  createAction(args: CreateActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateActionResult>;
  signAction(args: SignActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<SignActionResult>;
  abortAction(args: AbortActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AbortActionResult>;
  listActions(args: ListActionsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListActionsResult>;
  internalizeAction(args: InternalizeActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<InternalizeActionResult>;
  listOutputs(args: ListOutputsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListOutputsResult>;
  relinquishOutput(args: RelinquishOutputArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishOutputResult>;
  acquireCertificate(args: AcquireCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AcquireCertificateResult>;
  listCertificates(args: ListCertificatesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListCertificatesResult>;
  proveCertificate(args: ProveCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ProveCertificateResult>;
  relinquishCertificate(args: RelinquishCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishCertificateResult>;
  discoverByIdentityKey(args: DiscoverByIdentityKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>;
  discoverByAttributes(args: DiscoverByAttributesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>;
  getHeight(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeightResult>;
  getHeaderForHeight(args: GetHeaderArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeaderResult>;
  getNetwork(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetNetworkResult>;
  getVersion(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetVersionResult>;
  /**
   * A small helper that throws if the user is not authenticated or if the
   * provided originator is the admin (which is not permitted externally).
   */
  private ensureCanCall;
}
//#endregion
//#region ../src/wab-client/WABTransport.d.ts
type WABClientErrorCode = 'WAB_INVALID_CONFIGURATION' | 'WAB_INVALID_REQUEST' | 'WAB_NETWORK_ERROR' | 'WAB_TIMEOUT' | 'WAB_HTTP_ERROR' | 'WAB_ENDPOINT_MISMATCH' | 'WAB_REQUEST_TOO_LARGE' | 'WAB_RESPONSE_TOO_LARGE' | 'WAB_INVALID_RESPONSE';
interface WABClientErrorOptions {
  cause?: unknown;
  correlationId?: string;
  operation?: string;
  route?: string;
  endpointMarkerPresent?: boolean;
  responseCorrelationMatched?: boolean;
}
/**
 * A privacy-safe WAB transport failure. Response bodies and request payloads
 * are deliberately excluded from the error.
 */
declare class WABClientError extends Error {
  readonly code: WABClientErrorCode;
  readonly retryable: boolean;
  readonly status?: number | undefined;
  constructor(code: WABClientErrorCode, message: string, retryable: boolean, status?: number | undefined, options?: WABClientErrorOptions);
  readonly correlationId?: string;
  readonly operation?: string;
  readonly route?: string;
  readonly endpointMarkerPresent?: boolean;
  readonly responseCorrelationMatched?: boolean;
}
interface WABTransportOptions {
  /** Injectable fetch implementation for React Native, tests, and custom runtimes. */
  fetch?: typeof fetch;
  /** Hard wall-clock request timeout. Defaults to 10 seconds. */
  timeoutMs?: number;
  /** Maximum encoded JSON request size. Defaults to 1 MiB. */
  maxRequestBytes?: number;
  /** Maximum accepted JSON response size. Defaults to 1 MiB. */
  maxResponseBytes?: number;
  /** Optional privacy-bounded telemetry integration. */
  telemetry?: TelemetryConfig;
}
interface WABRequestOptions {
  method?: 'GET' | 'POST';
  body?: unknown;
  operation: string;
  correlationId?: string;
}
/**
 * Centralized, bounded transport used by every WAB client operation.
 *
 * Only fixed endpoint metadata is reported. Request bodies and response bodies
 * never cross the telemetry boundary.
 */
declare class WABTransport {
  readonly serverUrl: string;
  readonly serverOrigin: string;
  readonly telemetry: Telemetry;
  private readonly fetchClient;
  private readonly timeoutMs;
  private readonly maxRequestBytes;
  private readonly maxResponseBytes;
  constructor(serverUrl: string, options?: WABTransportOptions);
  createCorrelationId(): string;
  request<T>(path: string, options: WABRequestOptions): Promise<T>;
  private createRequestMetadata;
  private captureRequestStarted;
  private encodeRequestBody;
  private startRequestTimeout;
  private fetchResponse;
  private createResponseContext;
  private assertSuccessfulResponse;
  private readResponseText;
  private parseResponseObject;
  private captureRequestFailure;
  private readBoundedResponse;
  private rejectOversizedDeclaredResponse;
  private readBoundedArrayBuffer;
  private readBoundedStream;
  private decodeChunks;
  private responseTooLargeError;
  private cancelResponseBody;
  private cancelResponseReader;
  private captureFailure;
}
//#endregion
//#region ../src/wab-client/auth-method-interactors/AuthMethodInteractor.d.ts
interface AuthPayload {
  [key: string]: unknown;
}
interface StartAuthResponse {
  success: boolean;
  message?: string;
  data?: unknown;
}
interface CompleteAuthResponse {
  success: boolean;
  message?: string;
  presentationKey?: string;
  /** Preferred explicit continuity signal for newer WAB servers. */
  accountStatus?: 'new-user' | 'existing-user';
  /** Compatibility signal accepted from WAB deployments using a boolean. */
  existingUser?: boolean;
}
/**
 * Abstract client-side interactor for an Auth Method.
 *
 * Subclasses only need to set `methodType`; the HTTP calls to
 * `/auth/start` and `/auth/complete` are handled here.
 */
declare abstract class AuthMethodInteractor {
  abstract methodType: string;
  protected preparePayload(payload: AuthPayload): AuthPayload;
  /**
   * Shared POST helper for auth endpoints.
   */
  private postAuth;
  /**
   * Start the flow (e.g. request an OTP or create a session).
   */
  startAuth(serverUrl: string, presentationKey: string, payload: AuthPayload, transport?: WABTransport, correlationId?: string): Promise<StartAuthResponse>;
  /**
   * Complete the flow (e.g. confirm OTP).
   */
  completeAuth(serverUrl: string, presentationKey: string, payload: AuthPayload, transport?: WABTransport, correlationId?: string): Promise<CompleteAuthResponse>;
}
//#endregion
//#region ../src/wab-client/auth-method-interactors/PersonaIDInteractor.d.ts
declare class PersonaIDInteractor extends AuthMethodInteractor {
  methodType: string;
}
//#endregion
//#region ../src/wab-client/auth-method-interactors/TwilioPhoneInteractor.d.ts
/**
 * TwilioPhoneInteractor
 *
 * A client-side class that knows how to call the WAB server for Twilio-based phone verification.
 */
declare class TwilioPhoneInteractor extends AuthMethodInteractor {
  methodType: string;
  protected preparePayload(payload: AuthPayload): AuthPayload;
}
//#endregion
//#region ../src/wab-client/auth-method-interactors/DevConsoleInteractor.d.ts
/**
 * DevConsoleInteractor
 *
 * A client-side class that knows how to call the WAB server for DevConsole-based authentication.
 * This is a development-only auth method that generates OTP codes and logs them to the console.
 */
declare class DevConsoleInteractor extends AuthMethodInteractor {
  methodType: string;
}
//#endregion
//#region ../src/wab-client/WABClient.d.ts
interface WABClientOptions extends WABTransportOptions {}
interface WABServerInfo {
  supportedAuthMethods?: string[];
  [key: string]: unknown;
}
interface WABOperationResponse {
  success: boolean;
  message?: string;
  [key: string]: unknown;
}
interface WABFaucetResponse extends WABOperationResponse {
  paymentData?: {
    k?: string;
    tx?: number[];
    txid?: string;
  };
}
/**
 * Production-oriented WAB client with one security and observability boundary
 * for every endpoint.
 */
declare class WABClient {
  readonly transport: WABTransport;
  constructor(serverUrl: string, options?: WABClientOptions);
  getInfo(): Promise<WABServerInfo>;
  generateRandomPresentationKey(): string;
  startAuthMethod(authMethod: AuthMethodInteractor, presentationKey: string, payload: AuthPayload, correlationId?: string): Promise<StartAuthResponse>;
  completeAuthMethod(authMethod: AuthMethodInteractor, presentationKey: string, payload: AuthPayload, correlationId?: string): Promise<CompleteAuthResponse>;
  listLinkedMethods(presentationKey: string): Promise<WABOperationResponse>;
  unlinkMethod(presentationKey: string, authMethodId: number): Promise<WABOperationResponse>;
  requestFaucet(presentationKey: string): Promise<WABFaucetResponse>;
  deleteUser(presentationKey: string): Promise<WABOperationResponse>;
  startShareAuth(methodType: string, userIdHash: string, payload: AuthPayload): Promise<{
    success: boolean;
    message: string;
  }>;
  storeShare(methodType: string, payload: AuthPayload, shareB: string, userIdHash: string): Promise<{
    success: boolean;
    message: string;
    userId?: number;
  }>;
  retrieveShare(methodType: string, payload: AuthPayload, userIdHash: string): Promise<{
    success: boolean;
    shareB?: string;
    message: string;
  }>;
  updateShare(methodType: string, payload: AuthPayload, userIdHash: string, newShareB: string): Promise<{
    success: boolean;
    message: string;
    shareVersion?: number;
  }>;
  deleteShamirUser(methodType: string, payload: AuthPayload, userIdHash: string): Promise<{
    success: boolean;
    message: string;
  }>;
}
//#endregion
//#region ../src/WalletSettingsManager.d.ts
interface Certifier {
  name: string;
  description: string;
  identityKey: PubKeyHex;
  trust: number;
  iconUrl?: string;
  baseURL?: string;
}
interface TrustSettings {
  trustLevel: number;
  trustedCertifiers: Certifier[];
}
interface WalletTheme {
  mode: string;
}
interface WalletSettings {
  trustSettings: TrustSettings;
  theme?: WalletTheme;
  currency?: string;
  permissionMode?: string;
}
interface WalletSettingsManagerConfig {
  defaultSettings: WalletSettings;
}
declare const DEFAULT_SETTINGS: WalletSettings;
declare const TESTNET_DEFAULT_SETTINGS: WalletSettings;
/**
 * Manages wallet settings
 */
declare class WalletSettingsManager {
  private readonly wallet;
  private readonly config;
  kv: LocalKVStore;
  constructor(wallet: WalletInterface, config?: WalletSettingsManagerConfig);
  /**
   * Returns a user's wallet settings
   *
   * @returns - Wallet settings object
   */
  get(): Promise<WalletSettings>;
  /**
   * Creates (or updates) the user's settings token.
   *
   * @param settings - The wallet settings to be stored.
   */
  set(settings: WalletSettings): Promise<void>;
  /**
   * Deletes the user's settings token.
   */
  delete(): Promise<void>;
}
//#endregion
//#region ../src/signer/actionBatch/ActionBatchWorkspace.d.ts
type ActionBatchMode = 'auto' | 'legacy';
declare class ActionBatchController {
  private readonly wallet;
  readonly mode: ActionBatchMode;
  private workspace?;
  private readonly capabilities;
  private serial;
  constructor(wallet: Wallet, mode: ActionBatchMode);
  get hasWorkspace(): boolean;
  overlayListActions(persisted: ListActionsResult, args: Validation.ValidListActionsArgs): ListActionsResult;
  overlayListOutputs(persisted: ListOutputsResult, args: Validation.ValidListOutputsArgs): ListOutputsResult;
  private runExclusive;
  private negotiate;
  private begin;
  plan(args: Validation.ValidCreateActionArgs): Promise<StorageCreateActionResult | undefined>;
  process(prior: PendingSignAction | undefined, args: Validation.ValidProcessActionArgs): Promise<StorageProcessActionResults | undefined>;
  ownsReference(reference: string): boolean;
  abort(): Promise<boolean>;
  abortAction(referenceOrTxid: string): Promise<boolean>;
}
//#endregion
//#region ../src/Wallet.d.ts
/**
 * The preferred means of constructing a `Wallet` is with a `WalletArgs` instance.
 */
/**
 * Minimal interface the wallet uses to short-circuit identity discovery against the user's local
 * contacts before hitting the overlay. The result shape matches what `discoverByIdentityKey` /
 * `discoverByAttributes` return so callers don't have to special-case contact-sourced records.
 *
 * Implementations typically wrap `@bsv/sdk` `ContactsManager` or another on-device source. Reads
 * are expected to be very fast (single-digit ms against local SQLite is typical).
 */
interface ContactSource {
  /** Look up a contact by identity key. Return `null` (or undefined) if unknown. */
  findByIdentityKey: (identityKey: PubKeyHex) => Promise<ContactRecord | null | undefined>;
  /** Look up contacts matching a set of attributes. May be a no-op if attribute search is unsupported. */
  findByAttributes?: (attributes: Record<string, string> | string[]) => Promise<ContactRecord[]>;
}
/**
 * What a {@link ContactSource} returns. Carries enough to synthesize a minimal trusted
 * `DiscoverCertificatesResult` without touching the overlay.
 */
interface ContactRecord {
  identityKey: PubKeyHex;
  /** Optional certificate type (e.g. xCert / discordCert) so callers can render a badge. */
  type?: string;
  /** Optional decrypted fields. Whatever the app stored when saving the contact. */
  decryptedFields?: Record<string, string>;
  /** Optional certifier metadata; missing trust defaults to `Infinity` (contacts override overlay trust). */
  certifierInfo?: {
    name?: string;
    iconUrl?: string;
    description?: string;
    trust?: number;
  };
}
interface WalletArgs {
  chain: Chain;
  keyDeriver: KeyDeriverApi;
  storage: WalletStorageManager;
  services?: WalletServices;
  monitor?: Monitor;
  privilegedKeyManager?: PrivilegedKeyManager;
  settingsManager?: WalletSettingsManager;
  lookupResolver?: LookupResolver;
  /**
   * Optional contact source consulted before the overlay in `discoverByIdentityKey` /
   * `discoverByAttributes`. When a contact matches, the overlay call is skipped entirely.
   * Pass `forceRefresh: true` on the discover args to bypass both contacts and the overlay
   * cache.
   */
  contactSource?: ContactSource;
  /**
   * Optional. Provide a function conforming to the `MakeWalletLogger` type to enable wallet request logging.
   *
   * For simple requests using `Console` may be adequate, initialize with
   * `() => Console`
   *
   * Aggregate tracing and control over capturing all logged output in one place:
   * `(log?: string | WalletLoggerInterface) => new WalletLogger(log)`
   */
  makeLogger?: MakeWalletLogger;
  /**
   * Internal Wallet Toolbox optimization policy. `auto` (the default)
   * negotiates the optional action-batch storage capability; `legacy` always
   * uses per-action storage. This does not change the BRC-100 wallet interface.
   */
  actionBatchMode?: ActionBatchMode;
  /**
   * Optional high-performance script verifier used by Wallet Toolbox's
   * internal transaction checks. This is an implementation extension and does
   * not change the BRC-100 wallet interface.
   */
  scriptVerifier?: SpendVerifierInterface;
  /**
   * Optional provider-neutral tracing shared by wallet, lookup, storage, and
   * permission layers. Disabled unless an enabled sink is supplied.
   */
  telemetry?: TelemetryConfig;
}
declare class Wallet implements WalletInterface, ProtoWallet {
  chain: Chain;
  keyDeriver: KeyDeriverApi;
  storage: WalletStorageManager;
  settingsManager: WalletSettingsManager;
  lookupResolver: LookupResolver;
  services?: WalletServices;
  monitor?: Monitor;
  contactSource?: ContactSource;
  identityKey: string;
  /**
   * The wallet creates a `BeefParty` when it is created.
   * All the Beefs that pass through the wallet are merged into this beef.
   * Thus what it contains at any time is the union of all transactions and proof data processed.
   * The class `BeefParty` derives from `Beef`, adding the ability to track the source of merged data.
   *
   * This allows it to generate beefs to send to a particular “party” (storage or the user)
   * that includes “txid only proofs” for transactions they already know about.
   * Over time, this allows an active wallet to drastically reduce the amount of data transmitted.
   */
  beef: BeefParty;
  /**
   * If true, signableTransactions will include sourceTransaction for each input,
   * including those that do not require signature and those that were also contained
   * in the inputBEEF.
   */
  includeAllSourceTransactions: boolean;
  /**
   * If true, txids that are known to the wallet's party beef do not need to be returned from storage.
   */
  autoKnownTxids: boolean;
  /**
   * If true, beefs returned to the user may contain txidOnly transactions.
   */
  returnTxidOnly: boolean;
  trustSelf?: TrustSelf;
  userParty: string;
  proto: ProtoWallet;
  privilegedKeyManager?: PrivilegedKeyManager;
  makeLogger?: MakeWalletLogger;
  pendingSignActions: Record<string, PendingSignAction>;
  readonly actionBatch: ActionBatchController;
  readonly scriptVerifier?: SpendVerifierInterface;
  readonly telemetry: Telemetry;
  /**
   * For repeatability testing, set to an array of random numbers from [0..1).
   */
  randomVals?: number[];
  constructor(argsOrSigner: WalletArgs | WalletSigner, services?: WalletServices, monitor?: Monitor, privilegedKeyManager?: PrivilegedKeyManager, makeLogger?: MakeWalletLogger);
  destroy(): Promise<void>;
  getClientChangeKeyPair(): KeyPair;
  getIdentityKey(): Promise<PubKeyHex>;
  getPublicKey(args: GetPublicKeyArgs, _originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetPublicKeyResult>;
  revealCounterpartyKeyLinkage(args: RevealCounterpartyKeyLinkageArgs, _originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealCounterpartyKeyLinkageResult>;
  revealSpecificKeyLinkage(args: RevealSpecificKeyLinkageArgs, _originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealSpecificKeyLinkageResult>;
  encrypt(args: WalletEncryptArgs, _originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletEncryptResult>;
  decrypt(args: WalletDecryptArgs, _originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletDecryptResult>;
  createHmac(args: CreateHmacArgs, _originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateHmacResult>;
  verifyHmac(args: VerifyHmacArgs, _originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifyHmacResult>;
  createSignature(args: CreateSignatureArgs, _originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateSignatureResult>;
  verifySignature(args: VerifySignatureArgs, _originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifySignatureResult>;
  getServices(): WalletServices;
  /**
   * @returns the full list of txids whose validity this wallet claims to know.
   *
   * @param newKnownTxids Optional. Additional new txids known to be valid by the caller to be merged.
   */
  getKnownTxids(newKnownTxids?: string[]): string[];
  getStorageIdentity(): StorageIdentity;
  private validateAuthAndArgs;
  listActions(args: ListActionsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListActionsResult>;
  get storageParty(): string;
  listOutputs(args: ListOutputsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListOutputsResult>;
  listCertificates(args: ListCertificatesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListCertificatesResult>;
  private acquireDirectCertificateProtocol;
  private validateIssuedCertificateFields;
  private validateIssuedCertificate;
  private acquireIssuedCertificateProtocol;
  acquireCertificate(args: AcquireCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AcquireCertificateResult>;
  relinquishCertificate(args: RelinquishCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishCertificateResult>;
  proveCertificate(args: ProveCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ProveCertificateResult>;
  /** 2-minute cache of trust settings for identity resolution paths */
  private _trustSettingsCache?;
  /** 2-minute cache of queryOverlay() results keyed by normalized query */
  private readonly _overlayCache;
  discoverByIdentityKey(args: DiscoverByIdentityKeyArgs & {
    forceRefresh?: boolean;
  }, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>;
  discoverByAttributes(args: DiscoverByAttributesArgs & {
    forceRefresh?: boolean;
  }, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>;
  verifyReturnedTxidOnly(beef: Beef, knownTxids?: string[]): Beef;
  verifyReturnedTxidOnlyAtomicBEEF(beef: AtomicBEEF, knownTxids?: string[], parsedBeef?: Beef): AtomicBEEF;
  verifyReturnedTxidOnlyBEEF(beef: BEEF): BEEF;
  logMakeLogger(method: string, args: any): WalletLoggerInterface | undefined;
  logMethodStart(method: string, logger?: WalletLoggerInterface): void;
  logResult(r: any, logger?: WalletLoggerInterface): void;
  logWalletError(eu: unknown, logger?: WalletLoggerInterface): void;
  createAction(args: CreateActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateActionResult>;
  signAction(args: SignActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<SignActionResult>;
  internalizeAction(args: InternalizeActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<InternalizeActionResult>;
  abortAction(args: AbortActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AbortActionResult>;
  relinquishOutput(args: RelinquishOutputArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishOutputResult>;
  isAuthenticated(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>;
  waitForAuthentication(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>;
  getHeight(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeightResult>;
  getHeaderForHeight(args: GetHeaderArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeaderResult>;
  getNetwork(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetNetworkResult>;
  getVersion(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetVersionResult>;
  /**
   * Transfer all possible satoshis held by this wallet to `toWallet`.
   *
   * @param toWallet wallet which will receive this wallet's satoshis.
   */
  sweepTo(toWallet: Wallet): Promise<void>;
  /**
   * Uses `listOutputs` to iterate over chunks of up to 1000 outputs to
   * compute the sum of output satoshis.
   *
   * For `default`, only wallet-managed BRC-29 change is included. Raw
   * administrative `listOutputs({ basket: 'default' })` remains available to
   * discover legacy incompatible rows for recovery.
   *
   * @param {string} basket - Optional. Defaults to 'default', the wallet change basket.
   * @returns {WalletBalance} total sum of output satoshis and utxo details (satoshis and outpoints)
   */
  balanceAndUtxos(basket?: string): Promise<WalletBalance>;
  /**
   * Uses `listOutputs` special operation to compute the total value (of satoshis) for
   * all spendable outputs in the 'default' basket.
   *
   * @returns {number} sum of output satoshis
   */
  balance(args?: ListOutputsArgs): Promise<number>;
  /**
   * Uses `listOutputs` special operation to review the spendability via `Services` of
   * outputs currently considered spendable. Returns the outputs that fail to verify.
   *
   * Ignores the `limit` and `offset` properties.
   *
   * @param all Defaults to false. If false, only change outputs ('default' basket) are reviewed. If true, all spendable outputs are reviewed.
   * @param release Defaults to false. If true, sets outputs that fail to verify to un-spendable (spendable: false)
   * @param optionalArgs Optional. Additional tags will constrain the outputs processed.
   * @returns outputs which are/where considered spendable but currently fail to verify as spendable.
   */
  reviewSpendableOutputs(all?: boolean, release?: boolean, optionalArgs?: Partial<ListOutputsArgs>): Promise<ListOutputsResult>;
  /**
   * Uses `listOutputs` special operation to update the 'default' basket's automatic
   * change generation parameters.
   *
   * @param count target number of change UTXOs to maintain.
   * @param satoshis target value for new change outputs.
   */
  setWalletChangeParams(count: number, satoshis: number): Promise<void>;
  /**
   * Uses `listActions` special operation to return only actions with status 'nosend'.
   *
   * @param abort Defaults to false. If true, runs `abortAction` on each 'nosend' action.
   * @returns {ListActionsResult} start `listActions` result restricted to 'nosend' (or 'failed' if aborted) actions.
   */
  listNoSendActions(args: ListActionsArgs, abort?: boolean): Promise<ListActionsResult>;
  /**
   * Uses `listActions` special operation to return only actions with status 'failed'.
   *
   * @param unfail Defaults to false. If true, queues the action for attempted recovery.
   * @returns {ListActionsResult} start `listActions` result restricted to 'failed' status actions.
   */
  listFailedActions(args: ListActionsArgs, unfail?: boolean): Promise<ListActionsResult>;
}
interface PendingStorageInput {
  vin: number;
  derivationPrefix: string;
  derivationSuffix: string;
  unlockerPubKey?: string;
  sourceSatoshis: number;
  lockingScript: string;
}
interface PendingSignAction {
  reference: string;
  dcr: StorageCreateActionResult;
  args: Validation.ValidCreateActionArgs;
  tx: Transaction;
  amount: number;
  pdi: PendingStorageInput[];
}
/**
 * Throws a WERR_REVIEW_ACTIONS with a full set of properties to test data formats and propagation.
 */
declare function throwDummyReviewActions(): void;
//#endregion
//#region ../src/WalletLogger.d.ts
declare class WalletLogger implements WalletLoggerInterface {
  indent: number;
  logs: WalletLoggerLog[];
  isOrigin: boolean;
  isError: boolean;
  level?: WalletLoggerLevel;
  flushFormat?: 'json';
  constructor(log?: string | WalletLoggerInterface);
  private logAny;
  private toAdd;
  private stampLog;
  group(...label: any[]): void;
  groupEnd(): void;
  log(message?: any, ...optionalParams: any[]): void;
  error(message?: any, ...optionalParams: any[]): void;
  toWalletLoggerJson(): object;
  toLogString(): string;
  flush(): object | undefined;
  merge(log: WalletLoggerInterface): void;
}
declare function logWalletError(eu: unknown, logger?: WalletLoggerInterface, label?: string): void;
declare function logCreateActionArgs(args: CreateActionArgs): object;
/**
 * Optional. Logging levels that may influence what is logged.
 *
 * 'error' Only requests resulting in an exception should be logged.
 * 'warn' Also log requests that succeed but with an abnormal condition.
 * 'info' Also log normal successful requests.
 * 'debug' Add input parm and result details where possible.
 * 'trace' Instead of adding debug details, focus on execution path and timing.
 */
type WalletLoggerLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';
/**
 * Constructor properties available to `WalletLogger`
 */
interface WalletLoggerArgs {
  /**
   * Optional. Logging levels that may influence what is logged.
   *
   * 'error' Only requests resulting in an exception should be logged.
   * 'warn' Also log requests that succeed but with an abnormal condition.
   * 'info' Also log normal successful requests.
   * 'debug' Add input parm and result details where possible.
   * 'trace' Instead of adding debug details, focus on execution path and timing.
   */
  level?: 'error' | 'warn' | 'info' | 'debug' | 'trace';
  /**
   * Valid if an accumulating logger. Count of `group` calls without matching `groupEnd`.
   */
  indent?: number;
  /**
   * True if this is an accumulating logger and the logger belongs to the object servicing the initial request.
   */
  isOrigin?: boolean;
  /**
   * True if this is an accumulating logger and an error was logged.
   */
  isError?: boolean;
  /**
   * Optional array of accumulated logged data and errors.
   */
  logs?: WalletLoggerLog[];
}
//#endregion
//#region ../src/WalletAuthenticationManager.d.ts
interface WalletAuthenticationManagerOptions {
  telemetry?: TelemetryConfig;
  /** Maximum lifetime of a temporary WAB presentation key. Defaults to 10 minutes. */
  authSessionTtlMs?: number;
}
declare class WABAccountContinuityError extends Error {
  readonly code = "WERR_WAB_ACCOUNT_CONTINUITY";
  constructor(message?: string);
}
/**
 * WalletAuthenticationManager
 *
 * A wallet manager that integrates
 * with a WABClient for user authentication flows (e.g. Twilio phone).
 */
declare class WalletAuthenticationManager extends CWIStyleWalletManager {
  private readonly wabClient;
  private authMethod?;
  private authSession?;
  private readonly authSessionTtlMs;
  constructor(...[adminOriginator, walletBuilder, interactor, recoveryKeySaver, passwordRetriever, wabClient, authMethod, stateSnapshot, options]: [adminOriginator: string, walletBuilder: (primaryKey: number[], privilegedKeyManager: PrivilegedKeyManager) => Promise<WalletInterface>, interactor: UMPTokenInteractor | undefined, recoveryKeySaver: (key: number[]) => Promise<true>, passwordRetriever: (reason: string, test: (passwordCandidate: string) => boolean | Promise<boolean>) => Promise<string>, wabClient: WABClient, authMethod?: AuthMethodInteractor, stateSnapshot?: number[], options?: WalletAuthenticationManagerOptions]);
  /**
   * Sets (or switches) the chosen AuthMethodInteractor at runtime,
   * in case the user changes their mind or picks a new method in the UI.
   */
  setAuthMethod(method: AuthMethodInteractor): void;
  /**
   * Initiate the WAB-based flow, e.g. sending an SMS code or starting an ID check,
   * using the chosen AuthMethodInteractor.
   */
  startAuth(payload: AuthPayload): Promise<void>;
  /**
   * Completes the WAB-based flow, retrieving the final presentationKey from WAB if successful.
   */
  completeAuth(payload: AuthPayload): Promise<void>;
  cancelAuth(): void;
  destroy(): void;
  private inferAccountStatus;
  private constantTimeHexEqual;
  private generateTemporaryPresentationKey;
}
//#endregion
//#region ../src/WalletPermissionsManager.d.ts
/** Line item type for spending authorization requests. */
type LineItemType = 'input' | 'output' | 'fee';
/** Security level for DPACP protocol permissions. */
type SecurityLevel = 0 | 1 | 2;
/**
 * A permissions module handles request/response transformation for a specific P-protocol or P-basket scheme under BRC-98/99.
 * Modules are registered in the config mapped by their scheme ID.
 */
interface PermissionsModule {
  /**
   * Transforms the request before it's passed to the underlying wallet.
   * Can check and enforce permissions, throw errors, or modify any arguments as needed prior to invocation.
   *
   * @param req - The incoming request with method, args, and originator
   * @returns Transformed arguments that will be passed to the underlying wallet
   */
  onRequest: (req: {
    method: string;
    args: object;
    originator: string;
  }) => Promise<{
    args: object;
  }>;
  /**
   * Transforms the response from the underlying wallet before returning to caller.
   *
   * @param res - The response from the underlying wallet
   * @param context - Metadata about the original request (method, originator)
   * @returns Transformed response to return to the caller
   */
  onResponse: (res: any, context: {
    method: string;
    originator: string;
  }) => Promise<any>;
}
/**
 * Describes a group of permissions that can be requested together.
 * This structure is based on BRC-73.
 */
interface GroupedPermissions {
  description?: string;
  spendingAuthorization?: {
    amount: number;
    description: string;
  };
  protocolPermissions?: Array<{
    protocolID: WalletProtocol;
    counterparty?: string;
    description: string;
  }>;
  basketAccess?: Array<{
    basket: string;
    description: string;
  }>;
  certificateAccess?: Array<{
    type: string;
    fields: string[];
    verifierPublicKey: string;
    description: string;
  }>;
}
/**
 * The object passed to the UI when a grouped permission is requested.
 */
interface GroupedPermissionRequest {
  originator: string;
  requestID: string;
  permissions: GroupedPermissions;
}
/**
 * Signature for functions that handle a grouped permission request event.
 */
type GroupedPermissionEventHandler = (request: GroupedPermissionRequest) => void | Promise<void>;
interface CounterpartyPermissions {
  description?: string;
  protocols: Array<{
    protocolName: string;
    protocolID?: WalletProtocol;
    description?: string;
  }>;
}
interface CounterpartyPermissionRequest {
  originator: string;
  requestID: string;
  counterparty: PubKeyHex;
  counterpartyLabel?: string;
  permissions: CounterpartyPermissions;
}
type CounterpartyPermissionEventHandler = (request: CounterpartyPermissionRequest) => void | Promise<void>;
/**
 * Describes a single requested permission that the user must either grant or deny.
 *
 * Four categories of permission are supported, each with a unique protocol:
 *  1) protocol - "DPACP" (Domain Protocol Access Control Protocol)
 *  2) basket   - "DBAP"  (Domain Basket Access Protocol)
 *  3) certificate - "DCAP" (Domain Certificate Access Protocol)
 *  4) spending - "DSAP"  (Domain Spending Authorization Protocol)
 *
 * This model underpins "requests" made to the user for permission, which the user can
 * either grant or deny. The manager can then create on-chain tokens (PushDrop outputs)
 * if permission is granted. Denying requests cause the underlying operation to throw,
 * and no token is created. An "ephemeral" grant is also possible, denoting a one-time
 * authorization without an associated persistent on-chain token.
 */
interface PermissionRequest {
  type: 'protocol' | 'basket' | 'certificate' | 'spending';
  originator: string;
  displayOriginator?: string;
  usageType?: string;
  privileged?: boolean;
  protocolID?: WalletProtocol;
  counterparty?: string;
  basket?: string;
  certificate?: {
    verifier: string;
    certType: string;
    fields: string[];
  };
  spending?: {
    satoshis: number;
    lineItems?: Array<{
      type: LineItemType;
      description: string;
      satoshis: number;
    }>;
  };
  reason?: string;
  renewal?: boolean;
  previousToken?: PermissionToken;
}
/**
 * Signature for functions that handle a permission request event, e.g. "Please ask the user to allow basket X".
 */
type PermissionEventHandler = (request: PermissionRequest & {
  requestID: string;
}) => void | Promise<void>;
/**
 * Data structure representing an on-chain permission token.
 * It is typically stored as a single unspent PushDrop output in a special "internal" admin basket belonging to
 * the user, held in their underlying wallet.
 *
 * It can represent any of the four permission categories by having the relevant fields:
 *  - DPACP: originator, privileged, protocol, securityLevel, counterparty
 *  - DBAP:  originator, basketName
 *  - DCAP:  originator, privileged, verifier, certType, certFields
 *  - DSAP:  originator, authorizedAmount
 */
interface PermissionToken {
  /** The transaction ID where this token resides. */
  txid: string;
  /** The current transaction encapsulating the token. */
  tx: number[];
  /** The output index within that transaction. */
  outputIndex: number;
  /** The exact script hex for the locking script. */
  outputScript: string;
  /** The amount of satoshis assigned to the permission output (often 1). */
  satoshis: number;
  /** The originator domain or FQDN that is allowed to use this permission. */
  originator: string;
  /**
   * The raw, unnormalized originator string captured at the time the permission
   * token was created. This is preserved so we can continue to recognize legacy
   * permissions that were stored with different casing or explicit default ports.
   */
  rawOriginator?: string;
  /** The expiration time for this token in UNIX epoch seconds. (0 or omitted for spending authorizations, which are indefinite) */
  expiry: number;
  /** Whether this token grants privileged usage (for protocol or certificate). */
  privileged?: boolean;
  /** The protocol name, if this is a DPACP token. */
  protocol?: string;
  /** The security level (0,1,2) for DPACP. */
  securityLevel?: SecurityLevel;
  /** The counterparty, for DPACP. */
  counterparty?: string;
  /** The name of a basket, if this is a DBAP token. */
  basketName?: string;
  /** The certificate type, if this is a DCAP token. */
  certType?: string;
  /** The certificate fields that this token covers, if DCAP token. */
  certFields?: string[];
  /** The "verifier" public key string, if DCAP. */
  verifier?: string;
  /** For DSAP, the maximum authorized spending for the month. */
  authorizedAmount?: number;
}
/**
 * The set of callbacks that external code can bind to, e.g. to display UI prompts or logs
 * when a permission is requested.
 */
interface WalletPermissionsManagerCallbacks {
  onProtocolPermissionRequested?: PermissionEventHandler[];
  onBasketAccessRequested?: PermissionEventHandler[];
  onCertificateAccessRequested?: PermissionEventHandler[];
  onSpendingAuthorizationRequested?: PermissionEventHandler[];
  onGroupedPermissionRequested?: GroupedPermissionEventHandler[];
  onCounterpartyPermissionRequested?: CounterpartyPermissionEventHandler[];
}
/**
 * Configuration object for the WalletPermissionsManager. If a given option is `false`,
 * the manager will skip or alter certain permission checks or behaviors.
 *
 * By default, all of these are `true` unless specified otherwise. This is the most secure configuration.
 */
interface PermissionsManagerConfig {
  /**
   * Optional provider-neutral permission timing. Originators, permission-token
   * contents, manifests, descriptions, labels, and transaction data are never
   * emitted by the generic instrumentation.
   */
  telemetry?: TelemetryConfig;
  /**
   * A map of P-basket/protocol permission scheme modules.
   *
   * Keys are scheme IDs (e.g., "btms"), values are PermissionsModule instances.
   *
   * Each module handles basket/protocol names of the form: `p <schemeID> <rest...>`
   *
   * The WalletPermissionManager detects P-prefix baskets/protocols and delegates
   * request/response transformation to the corresponding module.
   *
   * If no module exists for a given schemeID, the wallet will reject access.
   */
  permissionModules?: Record<string, PermissionsModule>;
  /**
   * For `createSignature` and `verifySignature`,
   * require a "protocol usage" permission check?
   */
  seekProtocolPermissionsForSigning?: boolean;
  /**
   * For methods that perform encryption (encrypt/decrypt), require
   * a "protocol usage" permission check?
   */
  seekProtocolPermissionsForEncrypting?: boolean;
  /**
   * For methods that perform HMAC creation or verification (createHmac, verifyHmac),
   * require a "protocol usage" permission check?
   */
  seekProtocolPermissionsForHMAC?: boolean;
  /**
   * For revealing counterparty-level or specific key linkage revelation information,
   * should we require permission?
   */
  seekPermissionsForKeyLinkageRevelation?: boolean;
  /**
   * For revealing any user public key (getPublicKey) **other** than the identity key,
   * should we require permission?
   */
  seekPermissionsForPublicKeyRevelation?: boolean;
  /**
   * If getPublicKey is requested with `identityKey=true`, do we require permission?
   */
  seekPermissionsForIdentityKeyRevelation?: boolean;
  /**
   * If discoverByIdentityKey / discoverByAttributes are called, do we require permission
   * for "identity resolution" usage?
   */
  seekPermissionsForIdentityResolution?: boolean;
  /**
   * When we do internalizeAction with `basket insertion`, or include outputs in baskets
   * with `createAction, do we ask for basket permission?
   */
  seekBasketInsertionPermissions?: boolean;
  /**
   * When relinquishOutput is called, do we ask for basket permission?
   */
  seekBasketRemovalPermissions?: boolean;
  /**
   * When listOutputs is called, do we ask for basket permission?
   */
  seekBasketListingPermissions?: boolean;
  /**
   * When createAction is called with labels, do we ask for "label usage" permission?
   */
  seekPermissionWhenApplyingActionLabels?: boolean;
  /**
   * When listActions is called with labels, do we ask for "label usage" permission?
   */
  seekPermissionWhenListingActionsByLabel?: boolean;
  /**
   * If proving a certificate (proveCertificate) or revealing certificate fields,
   * do we require a "certificate access" permission?
   */
  seekCertificateDisclosurePermissions?: boolean;
  /**
   * If acquiring a certificate (acquireCertificate), do we require a permission check?
   */
  seekCertificateAcquisitionPermissions?: boolean;
  /**
   * If relinquishing a certificate (relinquishCertificate), do we require a permission check?
   */
  seekCertificateRelinquishmentPermissions?: boolean;
  /**
   * If listing a user's certificates (listCertificates), do we require a permission check?
   */
  seekCertificateListingPermissions?: boolean;
  /**
   * Should transaction descriptions, input descriptions, and output descriptions be encrypted
   * when before they are passed to the underlying wallet, and transparently decrypted when retrieved?
   */
  encryptWalletMetadata?: boolean;
  /**
   * If the originator tries to spend wallet funds (netSpent > 0 in createAction),
   * do we seek spending authorization?
   */
  seekSpendingPermissions?: boolean;
  /**
   * If true, triggers a grouped permission request flow based on the originator's `manifest.json`.
   */
  seekGroupedPermission?: boolean;
  /**
   * If false, permissions are checked without regard for whether we are in
   * privileged mode. Privileged status is ignored with respect to whether
   * permissions are granted. Internally, they are always sought and checked
   * with privileged=false, regardless of the actual value.
   */
  differentiatePrivilegedOperations?: boolean;
  /**
   * An allowlist mapping counterparty identity public keys (hex)
   * to protocol names that are automatically permitted
   * without prompting the user.
   */
  whitelistedCounterparties?: {
    [counterparty: PubKeyHex]: string[];
  };
}
/**
 * @class WalletPermissionsManager
 *
 * Wraps an underlying BRC-100 `Wallet` implementation with permissions management capabilities.
 * The manager intercepts calls from external applications (identified by originators), checks if the request is allowed,
 * and if not, orchestrates user permission flows. It creates or renews on-chain tokens in special
 * admin baskets to track these authorizations. Finally, it proxies the actual call to the underlying wallet.
 *
 * ### Key Responsibilities:
 *  - **Permission Checking**: Before standard wallet operations (e.g. `encrypt`),
 *    the manager checks if a valid permission token exists. If not, it attempts to request permission from the user.
 *  - **On-Chain Tokens**: When permission is granted, the manager stores it as an unspent "PushDrop" output.
 *    This can be spent later to revoke or renew the permission.
 *  - **Callbacks**: The manager triggers user-defined callbacks on permission requests (to show a UI prompt),
 *    on grants/denials, and on internal processes.
 *
 * ### Implementation Notes:
 *  - The manager follows the BRC-100 `createAction` + `signAction` pattern for building or spending these tokens.
 *  - Token revocation or renewal uses standard BRC-100 flows: we build a transaction that consumes
 *    the old token UTXO and outputs a new one (or none, if fully revoked).
 */
declare class WalletPermissionsManager implements WalletInterface {
  /** A reference to the BRC-100 wallet instance. */
  private readonly underlying;
  /** The "admin" domain or FQDN that is implicitly allowed to do everything. */
  private readonly adminOriginator;
  /**
   * Event callbacks that external code can subscribe to, e.g. to show a UI prompt
   * or log events. Each event can have multiple handlers.
   */
  private readonly callbacks;
  /**
   * We queue parallel requests for the same resource so that only one
   * user prompt is created for a single resource. If multiple calls come
   * in at once for the same "protocol:domain:privileged:counterparty" etc.,
   * they get merged.
   *
   * The key is a string derived from the operation; the value is an object with a reference to the
   * associated request and an array of pending promise resolve/reject pairs, one for each active
   * operation that's waiting on the particular resource described by the key.
   */
  private readonly activeRequests;
  /** Cache recently confirmed permissions to avoid repeated lookups. */
  private readonly permissionCache;
  private readonly recentGrants;
  /**
   * Token mints currently being written on-chain, keyed by permission cache
   * key. A granted permission is only cached once its token finishes minting
   * (network seconds); ensures arriving in that window await the in-flight
   * mint instead of re-prompting the user for a permission they just granted.
   * Stored promises never reject.
   */
  private readonly mintsInFlight;
  private readonly manifestCache;
  private readonly manifestFetchInProgress;
  private static readonly MANIFEST_CACHE_TTL_MS;
  private readonly groupedPermissionFlowTail;
  private readonly pactEstablishedCache;
  /**
   * Parsed BEEF bundles keyed by the raw BEEF array of a `listOutputs`
   * result, so token scans parse each bundle once instead of once per output.
   * `null` records a bundle that failed to parse. WeakMap-keyed so entries
   * are released with their results.
   */
  private readonly parsedBeefCache;
  /** Counts token-field decrypts so long scans can periodically yield. */
  private tokenFieldDecryptCount;
  /** How long a cached permission remains valid (5 minutes). */
  private static readonly CACHE_TTL_MS;
  /** Window during which freshly granted permissions are auto-allowed (except spending). */
  private static readonly RECENT_GRANT_COVER_MS;
  /** Default ports used when normalizing originator values. */
  private static readonly DEFAULT_PORTS;
  /**
   * Configuration that determines whether to skip or apply various checks and encryption.
   */
  private readonly config;
  private readonly telemetry;
  /**
   * Constructs a new Permissions Manager instance.
   *
   * @param underlyingWallet           The underlying BRC-100 wallet, where requests are forwarded after permission is granted
   * @param adminOriginator            The domain or FQDN that is automatically allowed everything
   * @param config                     A set of boolean flags controlling how strictly permissions are enforced
   */
  constructor(underlyingWallet: WalletInterface, adminOriginator: string, config?: PermissionsManagerConfig);
  /**
   * Delegates a wallet method call to a P-module if the basket or protocol name uses a P-scheme.
   * Handles the full request/response transformation flow.
   *
   * @param basketOrProtocolName - The basket or protocol name to check for p-module delegation
   * @param method - The wallet method name being called
   * @param args - The original args passed to the method
   * @param originator - The originator of the request
   * @param underlyingCall - Callback that executes the underlying wallet method with transformed args
   * @returns The transformed response, or null if not a P-basket/protocol (caller should continue normal flow)
   */
  private delegateToPModuleIfNeeded;
  /**
   * Adds a permission module for the given schemeID if needed, throwing if unsupported.
   */
  private addPModuleByScheme;
  /**
   * Splits labels into P and non-P lists, registering any P-modules encountered.
   *
   * P-labels follow BRC-111 format: `p <moduleId> <payload>`
   * - Must start with "p " (lowercase p + space)
   * - Module ID must be at least 1 character with no spaces
   * - Single space separates module ID from payload
   * - Payload must be at least 1 character
   *
   * @example Valid: "p btms token123", "p invoicing invoice 2026-02-02"
   * @example Invalid: "p btms" (no payload), "p btms " (empty payload), "p  data" (empty moduleId)
   *
   * @param labels - Array of label strings to process
   * @param pModulesByScheme - Map to populate with discovered p-modules
   * @returns Array of non-P labels for normal permission checks
   * @throws Error if p-label format is invalid or module is unsupported
   */
  private splitLabelsByPermissionModule;
  /**
   * Decrypts custom instructions in listOutputs results if encryption is configured.
   */
  private decryptListOutputsMetadata;
  /**
   * Decrypts metadata in listActions results if encryption is configured.
   */
  private decryptListActionsMetadata;
  private decryptSingleActionMetadata;
  private decryptActionOutputMetadata;
  /**
   * Binds a callback function to a named event, such as `onProtocolPermissionRequested`.
   *
   * @param eventName The name of the event to listen to
   * @param handler   A function that handles the event
   * @returns         A numeric ID you can use to unbind later
   */
  bindCallback(eventName: keyof WalletPermissionsManagerCallbacks, handler: PermissionEventHandler | GroupedPermissionEventHandler | CounterpartyPermissionEventHandler): number;
  /**
   * Unbinds a previously registered callback by either its numeric ID (returned by `bindCallback`)
   * or by exact function reference.
   *
   * @param eventName  The event name, e.g. "onProtocolPermissionRequested"
   * @param reference  Either the numeric ID or the function reference
   * @returns          True if successfully unbound, false otherwise
   */
  unbindCallback(eventName: keyof WalletPermissionsManagerCallbacks, reference: number | Function): boolean;
  /**
   * Internally triggers a named event, calling all subscribed listeners.
   * Each callback is awaited in turn (though errors are swallowed so that
   * one failing callback doesn't prevent the others).
   *
   * @param eventName The event name
   * @param param     The parameter object passed to all listeners
   */
  private callEvent;
  /**
   * Grants a previously requested permission.
   * This method:
   *  1) Resolves all pending promise calls waiting on this request
   *  2) Optionally creates or renews an on-chain PushDrop token (unless `ephemeral===true`)
   *
   * @param params      requestID to identify which request is granted, plus optional expiry
   *                    or `ephemeral` usage, etc.
   */
  grantPermission(params: {
    requestID: string;
    expiry?: number;
    ephemeral?: boolean;
    amount?: number;
  }): Promise<void>;
  /**
   * Denies a previously requested permission.
   * This method rejects all pending promise calls waiting on that request
   *
   * @param requestID    requestID identifying which request to deny
   */
  denyPermission(requestID: string): Promise<void>;
  /**
   * Grants a previously requested grouped permission.
   * @param params.requestID The ID of the request being granted.
   * @param params.granted A subset of the originally requested permissions that the user has granted.
   * @param params.expiry An optional expiry time (in seconds) for the new permission tokens.
   */
  grantGroupedPermission(params: {
    requestID: string;
    granted: Partial<GroupedPermissions>;
    expiry?: number;
  }): Promise<void>;
  /**
   * Denies a previously requested grouped permission.
   * @param requestID The ID of the request being denied.
   */
  /**
   * Validates that every entry in `granted` was part of the original `requested` set.
   * Throws an error on the first mismatch.
   */
  private validateGrantedPermissionsSubset;
  private denyActiveRequest;
  private settleActiveGrant;
  private persistPermissionGrant;
  denyGroupedPermission(requestID: string): Promise<void>;
  dismissGroupedPermission(requestID: string): Promise<void>;
  grantCounterpartyPermission(params: {
    requestID: string;
    granted: Partial<CounterpartyPermissions>;
    expiry?: number;
  }): Promise<void>;
  denyCounterpartyPermission(requestID: string): Promise<void>;
  /**
   * Ensures the originator has protocol usage permission.
   * If no valid (unexpired) permission token is found, triggers a permission request flow.
   */
  ensureProtocolPermission({ originator, privileged, protocolID, counterparty, reason, seekPermission, usageType }: {
    originator: string;
    privileged: boolean;
    protocolID: WalletProtocol;
    counterparty: string;
    reason?: string;
    seekPermission?: boolean;
    usageType: 'signing' | 'encrypting' | 'hmac' | 'publicKey' | 'identityKey' | 'linkageRevelation' | 'generic';
  }): Promise<boolean>;
  /**
   * Ensures the originator has basket usage permission for the specified basket.
   * If not, triggers a permission request flow.
   */
  ensureBasketAccess({ originator, basket, reason, seekPermission, usageType }: {
    originator: string;
    basket: string;
    reason?: string;
    seekPermission?: boolean;
    usageType: 'insertion' | 'removal' | 'listing';
  }): Promise<boolean>;
  /** Returns false when the basket usageType does NOT need a permission check (config-gated). */
  private isBasketUsageRequired;
  /**
   * Ensures the originator has a valid certificate permission.
   * This is relevant when revealing certificate fields in DCAP contexts.
   */
  ensureCertificateAccess({ originator, privileged, verifier, certType, fields, reason, seekPermission, usageType }: {
    originator: string;
    privileged: boolean;
    verifier: string;
    certType: string;
    fields: string[];
    reason?: string;
    seekPermission?: boolean;
    usageType: 'disclosure';
  }): Promise<boolean>;
  /**
   * Ensures the originator has spending authorization (DSAP) for a certain satoshi amount.
   * If the existing token limit is insufficient, attempts to renew. If no token, attempts to create one.
   */
  ensureSpendingAuthorization({ originator, satoshis, lineItems, reason, seekPermission }: {
    originator: string;
    satoshis: number;
    lineItems?: Array<{
      type: LineItemType;
      description: string;
      satoshis: number;
    }>;
    reason?: string;
    seekPermission?: boolean;
  }): Promise<boolean>;
  /**
   * Ensures the originator has label usage permission.
   * If no valid (unexpired) permission token is found, triggers a permission request flow.
   */
  ensureLabelAccess({ originator, label, reason, seekPermission, usageType }: {
    originator: string;
    label: string;
    reason?: string;
    seekPermission?: boolean;
    usageType: 'apply' | 'list';
  }): Promise<boolean>;
  /**
   * Returns true when the given usageType is configured to skip permission checks.
   */
  private isProtocolUsageTypeExempted;
  private isProtocolInCounterpartyPermissions;
  private validateCounterpartyPermissions;
  private fetchManifestPermissions;
  private fetchManifestGroupPermissions;
  private filterAlreadyGrantedPermissions;
  private hasAnyPermissionsToRequest;
  private hasGroupedPermissionRequestedHandlers;
  private hasCounterpartyPermissionRequestedHandlers;
  private hasPactEstablished;
  private markPactEstablished;
  private maybeRequestPact;
  private joinOrCreatePactRequest;
  private maybeRequestPeerGroupedLevel2ProtocolPermissions;
  private withGroupedPermissionFlowLock;
  private checkSpecificPermissionAfterGroupFlow;
  private isRequestIncludedInGroupPermissions;
  private maybeRequestGroupedPermissions;
  /**
   * Joins an existing grouped permission request (piggybacks on the existing promise), or creates
   * a new one and fires the onGroupedPermissionRequested event.
   */
  private joinOrCreateGroupedRequest;
  /**
   * A central method that triggers the permission request flow.
   * - It checks if there's already an active request for the same key
   * - If so, we wait on that existing request rather than creating a duplicative one
   * - Otherwise we create a new request queue, call the relevant "onXXXRequested" event,
   *   and return a promise that resolves once permission is granted or rejects if denied.
   */
  private requestPermissionFlow;
  private requestPermissionFlowCore;
  /** Returns true when an active-request queue already has pending waiters for this key. */
  private isPiggybacking;
  /** Appends to an existing request queue and waits for resolution. */
  private piggybackOnExistingQueue;
  /** Runs the grouped-permission flow (with or without a lock) and checks post-group satisfaction. */
  private resolveGroupedFlow;
  /** Creates a new active-request queue entry, fires the event, and returns the promise. */
  private enqueueAndFireEvent;
  /** Fires the appropriate onXXXRequested event based on the request type. */
  private firePermissionRequestEvent;
  private callPermissionEvent;
  /**
   * We will use a administrative "permission token encryption" protocol to store fields
   * in each permission's PushDrop script. This ensures that only the user's wallet
   * can decrypt them. In practice, this data is not super sensitive, but we still
   * follow the principle of least exposure.
   */
  private static readonly PERM_TOKEN_ENCRYPTION_PROTOCOL;
  /**
   * Similarly, we will use a "metadata encryption" protocol to preserve the confidentiality
   * of transaction descriptions and input/output descriptions from lower storage layers.
   */
  private static readonly METADATA_ENCRYPTION_PROTOCOL;
  /** We always use `keyID="1"` and `counterparty="self"` for these encryption ops. */
  private encryptPermissionTokenField;
  /**
   * Extracts a transaction from a `listOutputs` result's BEEF bundle, parsing
   * the bundle only once per result. Calling
   * `Transaction.fromBEEF(result.BEEF, txid)` per output re-parses the entire
   * bundle every time — O(n²) in the number of outputs — which can block the
   * caller's thread (in browser wallets, the UI) for seconds on large
   * permission baskets.
   */
  private transactionFromResultBeef;
  private decryptPermissionTokenField;
  /**
   * Encrypts wallet metadata if configured to do so, otherwise returns the original plaintext for storage.
   * @param plaintext The metadata to encrypt if configured to do so
   * @returns The encrypted metadata, or the original value if encryption was disabled.
   */
  private maybeEncryptMetadata;
  /**
   * Attempts to decrypt metadata. if decryption fails, assumes the value is already plaintext and returns it.
   * @param ciphertext The metadata to attempt decryption for.
   * @returns The decrypted metadata. If decryption fails, returns the original value instead.
   */
  private maybeDecryptMetadata;
  /** Helper to see if a token's expiry is in the past. */
  private isTokenExpired;
  /** Decrypts the standard 6 fields from a protocol (DPACP) PushDrop script. */
  private decryptProtocolTokenFields;
  private protocolTokenTags;
  private parseProtocolTokenOutput;
  private parseBasketTokenOutput;
  private parseCertificateTokenOutput;
  /** Parses outpoint string "txid.vout" into [txid, outputIndex]. */
  private parseOutpoint;
  /** Normalizes a txid string to lowercase. */
  private normalizeTxid;
  /** Reverses a 32-byte hex txid (for endian normalization). */
  private reverseHexTxid;
  /**
   * Returns true when an outpoint string (e.g. "txid.vout" or "txid:vout") refers to `token`.
   */
  private tokenMatchesOutpointString;
  /**
   * Finds the index of the tx input that spends the given permission token.
   * Handles multiple potential field names for TXID and vout.
   */
  private findInputIndexForToken;
  /** Looks for a DPACP permission token matching origin/domain, privileged, protocol, cpty. */
  private findProtocolToken;
  /** Finds ALL DPACP permission tokens matching origin/domain, privileged, protocol, cpty. Never filters by expiry. */
  private findAllProtocolTokens;
  /** Looks for a DBAP token matching (originator, basket). */
  private findBasketToken;
  /** Looks for a DCAP token matching (origin, privileged, verifier, certType, fields subset). */
  private findCertificateToken;
  /** Looks for a DSAP token matching origin, returning the first one found. */
  private findSpendingToken;
  /**
   * Returns the current month and year in UTC as a string in the format "YYYY-MM".
   *
   * @returns {string} The current month and year in UTC.
   */
  private getCurrentMonthYearUTC;
  /**
   * Returns spending for an originator in the current calendar month.
   */
  querySpentSince(token: PermissionToken): Promise<number>;
  /**
   * Creates a brand-new permission token as a single-output PushDrop script in the relevant admin basket.
   *
   * The main difference between each type of token is in the "fields" we store in the PushDrop script.
   *
   * @param r        The permission request
   * @param expiry   The expiry epoch time
   * @param amount   For DSAP, the authorized spending limit
   */
  private createPermissionOnChain;
  private mapWithConcurrency;
  private runBestEffortBatches;
  private runBestEffortChunk;
  private buildPermissionOutput;
  private createPermissionTokensBestEffort;
  private renewPermissionTokensBestEffort;
  private coalescePermissionTokens;
  /**
   * Renews a permission token by spending the old token as input and creating a new token output.
   * This invalidates the old token and replaces it with a new one.
   *
   * @param oldToken The old token to consume
   * @param r        The permission request being renewed
   * @param newExpiry The new expiry epoch time
   * @param newAmount For DSAP, the new authorized amount
   */
  private renewPermissionOnChain;
  /**
   * Builds the encrypted array of fields for a PushDrop permission token
   * (protocol / basket / certificate / spending).
   */
  private buildPushdropFields;
  /**
   * Helper to build an array of tags for the new output, matching the user request's
   * origin, basket, privileged, protocol name, etc.
   */
  private buildTagsForRequest;
  /**
   * Lists all protocol permission tokens (DPACP) with optional filters.
   * @param originator Optional originator domain to filter by
   * @param privileged Optional boolean to filter by privileged status
   * @param protocolName Optional protocol name to filter by
   * @param protocolSecurityLevel Optional protocol security level to filter by
   * @param counterparty Optional counterparty to filter by
   * @returns Array of permission tokens that match the filter criteria
   */
  listProtocolPermissions({ originator, privileged, protocolName, protocolSecurityLevel, counterparty }?: {
    originator?: string;
    privileged?: boolean;
    protocolName?: string;
    protocolSecurityLevel?: number;
    counterparty?: string;
  }): Promise<PermissionToken[]>;
  /** Builds the base tag array for protocol permission listing. */
  private buildProtocolFilterTags;
  /** Decodes and appends protocol permission tokens from a listOutputs result. */
  private collectProtocolTokens;
  /**
   * Returns true if the originator already holds a valid unexpired protocol permission.
   * This calls `ensureProtocolPermission` with `seekPermission=false`, so it won't prompt.
   */
  hasProtocolPermission(params: {
    originator: string;
    privileged: boolean;
    protocolID: WalletProtocol;
    counterparty: string;
  }): Promise<boolean>;
  /**
   * Lists basket permission tokens (DBAP) for a given originator or basket (or for all if not specified).
   * @param params.originator Optional originator to filter by
   * @param params.basket Optional basket name to filter by
   * @returns Array of permission tokens that match the filter criteria
   */
  listBasketAccess(params?: {
    originator?: string;
    basket?: string;
  }): Promise<PermissionToken[]>;
  /** Decodes and appends basket permission tokens from a listOutputs result. */
  private collectBasketTokens;
  /**
   * Returns `true` if the originator already holds a valid unexpired basket permission for `basket`.
   */
  hasBasketAccess(params: {
    originator: string;
    basket: string;
  }): Promise<boolean>;
  /**
   * Lists spending authorization tokens (DSAP) for a given originator (or all).
   */
  listSpendingAuthorizations(params: {
    originator?: string;
  }): Promise<PermissionToken[]>;
  /**
   * Returns `true` if the originator already holds a valid spending authorization token
   * with enough available monthly spend. We do not prompt (seekPermission=false).
   */
  hasSpendingAuthorization(params: {
    originator: string;
    satoshis: number;
  }): Promise<boolean>;
  /**
   * Lists certificate permission tokens (DCAP) with optional filters.
   * @param originator Optional originator domain to filter by
   * @param privileged Optional boolean to filter by privileged status
   * @param certType Optional certificate type to filter by
   * @param verifier Optional verifier to filter by
   * @returns Array of permission tokens that match the filter criteria
   */
  listCertificateAccess(params?: {
    originator?: string;
    privileged?: boolean;
    certType?: Base64String;
    verifier?: PubKeyHex;
  }): Promise<PermissionToken[]>;
  /** Decodes and appends certificate permission tokens from a listOutputs result. */
  private collectCertificateTokens;
  /**
   * Returns `true` if the originator already holds a valid unexpired certificate access
   * for the given certType/fields. Does not prompt the user.
   */
  hasCertificateAccess(params: {
    originator: string;
    privileged: boolean;
    verifier: string;
    certType: string;
    fields: string[];
  }): Promise<boolean>;
  revokePermissions(oldTokens: PermissionToken[]): Promise<PermissionToken[]>;
  revokeAllForOriginator(originator: string, opts?: {
    protocol?: boolean;
    basket?: boolean;
    certificate?: boolean;
    spending?: boolean;
  }): Promise<PermissionToken[]>;
  private revokePermissionTokensBestEffort;
  private revokePermissionTokensChunk;
  /**
   * Revokes a permission token by spending it with no replacement output.
   * The manager builds a BRC-100 transaction that consumes the token, effectively invalidating it.
   */
  revokePermission(oldToken: PermissionToken): Promise<void>;
  createAction(args: Parameters<WalletInterface['createAction']>[0], originator?: string): ReturnType<WalletInterface['createAction']>;
  /** Scans outputs to split P-scheme baskets from regular baskets; registers P-modules as a side effect. */
  private collectNonPBaskets;
  /** Enforces signAndProcess=false for non-admin originators; throws if admin override is missing. */
  private enforceSignAndProcess;
  /** Encrypts all description/instruction fields in args in-place; returns original (plaintext) copies. */
  private encryptActionMetadata;
  /** Calls underlying createAction, chaining P-module request/response transforms when needed. */
  private callCreateActionWithPModules;
  /**
   * Computes the net satoshis the originator is spending in a createAction call,
   * accounting for foreign (originator-provided) inputs and outputs plus the fee.
   * Also builds the line items list for the spending authorization request.
   */
  /**
   * Defense-in-depth verification that each caller-requested output (locking
   * script + amount) is present in the transaction returned for signing.
   *
   * The scripts in the signable transaction originate from storage. A malicious
   * or compromised remote storage provider could substitute a different
   * recipient script for a caller-specified output. The signer
   * (buildSignableTransaction) rejects this at the source; this is an
   * independent check at the permissions layer so the substitution is caught
   * regardless of how the signable transaction was produced.
   *
   * Outputs are matched as a multiset on (lockingScript, satoshis): the
   * transaction also contains change/commission outputs and the output order is
   * randomized by default, and a caller may legitimately request the same
   * script+amount more than once.
   *
   * @throws Error if any caller-requested output is absent from the transaction.
   */
  private verifyRequestedOutputsPresent;
  private computeNetSpend;
  signAction(...args: Parameters<WalletInterface['signAction']>): ReturnType<WalletInterface['signAction']>;
  abortAction(...args: Parameters<WalletInterface['abortAction']>): ReturnType<WalletInterface['abortAction']>;
  listActions(...args: Parameters<WalletInterface['listActions']>): ReturnType<WalletInterface['listActions']>;
  private collectInternalizeActionBaskets;
  private authorizeInternalizeActionBaskets;
  private authorizeInternalizeActionLabels;
  private encryptInternalizeActionModuleMetadata;
  private runInternalizeActionModules;
  internalizeAction(...args: Parameters<WalletInterface['internalizeAction']>): ReturnType<WalletInterface['internalizeAction']>;
  listOutputs(...args: Parameters<WalletInterface['listOutputs']>): ReturnType<WalletInterface['listOutputs']>;
  relinquishOutput(...args: Parameters<WalletInterface['relinquishOutput']>): ReturnType<WalletInterface['relinquishOutput']>;
  getPublicKey(...args: Parameters<WalletInterface['getPublicKey']>): ReturnType<WalletInterface['getPublicKey']>;
  revealCounterpartyKeyLinkage(...args: Parameters<WalletInterface['revealCounterpartyKeyLinkage']>): ReturnType<WalletInterface['revealCounterpartyKeyLinkage']>;
  revealSpecificKeyLinkage(...args: Parameters<WalletInterface['revealSpecificKeyLinkage']>): ReturnType<WalletInterface['revealSpecificKeyLinkage']>;
  encrypt(...args: Parameters<WalletInterface['encrypt']>): ReturnType<WalletInterface['encrypt']>;
  decrypt(...args: Parameters<WalletInterface['decrypt']>): ReturnType<WalletInterface['decrypt']>;
  createHmac(...args: Parameters<WalletInterface['createHmac']>): ReturnType<WalletInterface['createHmac']>;
  verifyHmac(...args: Parameters<WalletInterface['verifyHmac']>): ReturnType<WalletInterface['verifyHmac']>;
  createSignature(...args: Parameters<WalletInterface['createSignature']>): ReturnType<WalletInterface['createSignature']>;
  verifySignature(...args: Parameters<WalletInterface['verifySignature']>): ReturnType<WalletInterface['verifySignature']>;
  acquireCertificate(...args: Parameters<WalletInterface['acquireCertificate']>): ReturnType<WalletInterface['acquireCertificate']>;
  listCertificates(...args: Parameters<WalletInterface['listCertificates']>): ReturnType<WalletInterface['listCertificates']>;
  proveCertificate(...args: Parameters<WalletInterface['proveCertificate']>): ReturnType<WalletInterface['proveCertificate']>;
  relinquishCertificate(...args: Parameters<WalletInterface['relinquishCertificate']>): ReturnType<WalletInterface['relinquishCertificate']>;
  discoverByIdentityKey(...args: Parameters<WalletInterface['discoverByIdentityKey']>): ReturnType<WalletInterface['discoverByIdentityKey']>;
  discoverByAttributes(...args: Parameters<WalletInterface['discoverByAttributes']>): ReturnType<WalletInterface['discoverByAttributes']>;
  isAuthenticated(...args: Parameters<WalletInterface['isAuthenticated']>): ReturnType<WalletInterface['isAuthenticated']>;
  waitForAuthentication(...args: Parameters<WalletInterface['waitForAuthentication']>): ReturnType<WalletInterface['waitForAuthentication']>;
  getHeight(...args: Parameters<WalletInterface['getHeight']>): ReturnType<WalletInterface['getHeight']>;
  getHeaderForHeight(...args: Parameters<WalletInterface['getHeaderForHeight']>): ReturnType<WalletInterface['getHeaderForHeight']>;
  getNetwork(...args: Parameters<WalletInterface['getNetwork']>): ReturnType<WalletInterface['getNetwork']>;
  getVersion(...args: Parameters<WalletInterface['getVersion']>): ReturnType<WalletInterface['getVersion']>;
  /** Returns true if the specified origin is the admin originator. */
  private isAdminOriginator;
  /**
   * Checks if the given protocol is admin-reserved per BRC-100 rules:
   *
   *  - Must not start with `admin` (admin-reserved)
   *  - Must not start with `p ` (allows for future specially permissioned protocols)
   *
   * If it violates these rules and the caller is not admin, we consider it "admin-only."
   */
  private isAdminProtocol;
  /**
   * Checks if the given label is admin-reserved per BRC-100 rules:
   *
   *  - Must not start with `admin` (admin-reserved)
   *  - Must not start with `p ` (permissioned labels requiring a permission module)
   *
   * If it violates these rules and the caller is not admin, we consider it "admin-only."
   */
  private isAdminLabel;
  /**
   * Checks if the given basket is admin-reserved per BRC-100 rules:
   *
   *  - Must not start with `admin`
   *  - Must not be `default` (some wallets use this for internal operations)
   *  - Must not start with `p ` (future specially permissioned baskets)
   */
  private isAdminBasket;
  /**
   * Whether the permission is satisfied without consulting on-chain tokens:
   * cached, recently granted, or — when the user just granted it and its
   * token is still minting — after the in-flight mint settles. Spares the
   * user a duplicate prompt for a grant they already made moments ago.
   */
  private hasRecentOrPendingGrant;
  private hasRecentOrPendingGrantCore;
  /**
   * Returns true if we have a cached record that the permission identified by
   * `key` is valid and unexpired.
   */
  private isPermissionCached;
  /** Caches the fact that the permission for `key` is valid until `expiry`. */
  private cachePermission;
  /** Records that a non-spending permission was just granted so we can skip re-prompting briefly. */
  private markRecentGrant;
  /** Returns true if we are inside the short "cover window" immediately after granting permission. */
  private isRecentlyGranted;
  /** Normalizes and canonicalizes originator domains (e.g., lowercase + drop default ports). */
  private normalizeOriginator;
  private isWhitelistedCounterpartyProtocol;
  /**
   * Produces a normalized originator value along with the set of legacy
   * representations that should be considered when searching for existing
   * permission tokens (for backwards compatibility).
   */
  private prepareOriginator;
  /**
   * Builds a unique list of originator variants that should be searched when
   * looking up on-chain tokens (e.g., legacy raw + normalized forms).
   */
  private buildOriginatorLookupValues;
  /**
   * Builds a "map key" string so that identical requests (e.g. "protocol:domain:true:protoName:counterparty")
   * do not produce multiple user prompts.
   */
  private buildRequestKey;
  private buildActiveRequestKey;
}
//#endregion
export { ARGON2ID_DEFAULT_HASH_LENGTH, ARGON2ID_DEFAULT_ITERATIONS, ARGON2ID_DEFAULT_MEMORY_KIB, ARGON2ID_DEFAULT_PARALLELISM, ARGON2ID_MAX_ITERATIONS, ARGON2ID_MAX_MEMORY_KIB, ARGON2ID_MAX_PARALLELISM, ActionBatchStatus, AdminStatsResult, AnyBlockHeader, ArcSSEClient, ArcSSEClientOptions, ArcSSEEvent, AuthMethodInteractor, AuthPayload, BRC38ImportOptions, BRC38ImportResult, BRC38Tables, BRC38WalletData, BRC39Options, type BaseBlockHeader, type BlockHeader, BulkFileDataManager, BulkFileDataManagerMergeResult, BulkFileDataManagerOptions, BulkFileDataReader, BulkFilesReader, BulkFilesReaderFs, BulkFilesReaderStorage, BulkIngestorApi, BulkIngestorBase, BulkIngestorBaseOptions, BulkIngestorCDN, BulkIngestorCDNBabbage, BulkIngestorCDNOptions, BulkIngestorChaintracks, BulkIngestorChaintracksOptions, BulkIngestorWhatsOnChainCdn, BulkIngestorWhatsOnChainOptions, BulkStorageApi, BulkStorageBase, BulkStorageBaseOptions, BulkSyncResult, ByteEncoding, ByteInput, CWIStyleWalletManager, Certifier, type Chain, Chaintracks, ChaintracksApi, ChaintracksAppendableFileApi, ChaintracksArgumentsTail, ChaintracksClientApi, ChaintracksFetch, ChaintracksFetchApi, ChaintracksFetchError, ChaintracksFsApi, ChaintracksInfoApi, ChaintracksIngestorParams, ChaintracksManagementApi, ChaintracksOptions, ChaintracksPackageInfoApi, ChaintracksReadableFileApi, ChaintracksServiceClient, ChaintracksServiceClientOptions, ChaintracksSourceOptions, ChaintracksSourceStatusApi, ChaintracksStorageApi, ChaintracksStorageBase, ChaintracksStorageBaseOptions, ChaintracksStorageBulkFileApi, ChaintracksStorageIdb, ChaintracksStorageIdbOptions, ChaintracksStorageIdbSchema, ChaintracksStorageIngestApi, ChaintracksStorageNoDb, ChaintracksStorageNoDbOptions, ChaintracksStorageQueryApi, ChaintracksWritableFileApi, CompleteAuthResponse, ContactRecord, ContactSource, CounterpartyPermissionEventHandler, CounterpartyPermissionRequest, CounterpartyPermissions, CreatedChaintracks, DEFAULT_PROFILE_ID, DEFAULT_SETTINGS, DeactivedHeader, DefaultChaintracksArguments, DevConsoleInteractor, EnqueueHandler, EntityBase, EntityCertificate, EntityCertificateField, EntityCommission, EntityOutput, EntityOutputBasket, EntityOutputTag, EntityOutputTagMap, EntityProvenTx, EntityProvenTxReq, EntityStorage, EntitySyncMap, EntitySyncState, EntityTransaction, EntityTxLabel, EntityTxLabelMap, EntityUser, ErrorHandler, GetHeaderByteFileLinksResult, GoChaintracksServiceClient, GoChaintracksServiceClientOptions, GroupedPermissionEventHandler, GroupedPermissionRequest, GroupedPermissions, HeaderListener, HeightRange, HeightRangeApi, HeightRanges, InsertHeaderResult, KDF_MAX_HASH_LENGTH, KdfConfig, LineItemType, ListActionsSpecOp, ListOutputsSpecOp, LiveBlockHeader, LiveIngestorApi, LiveIngestorBase, LiveIngestorBaseOptions, LiveIngestorChaintracksSSE, LiveIngestorChaintracksSSEOptions, LiveIngestorWhatsOnChainOptions, LiveIngestorWhatsOnChainPoll, MAX_STATE_SNAPSHOT_BYTES, MergeEntity, Monitor, MonitorOptions, MonitorStartupTaskMode, MonitorStorage, OverlayUMPTokenInteractor, PBKDF2_MAX_ITERATIONS, PBKDF2_NUM_ROUNDS, ParsedBrc114ActionTimeLabels, PendingSignAction, PendingStorageInput, PermissionEventHandler, PermissionRequest, PermissionToken, PermissionsManagerConfig, PermissionsModule, PersonaIDInteractor, PrivilegedKeyManager, Profile, ProvenTxFromTxidResult, ProvenTxReqHistory, ProvenTxReqHistorySummaryApi, ProvenTxReqNotify, ReorgListener, ResolvedDefaultChaintracksParams, ScriptTemplateBRC29, ScriptTemplateParamsBRC29, SecurityLevel, Services, SimpleWalletManager, StartAuthResponse, StorageAdminStats, StorageClient, StorageProvider, StorageProviderOptions, StorageSyncReader, SyncError, SyncMap, TESTNET_DEFAULT_SETTINGS, TableActionBatch, TableActionBatchBlob, TableActionBatchOutput, TableAuthSession, TableCertificate, TableCertificateField, TableCertificateX, TableCommission, TableMonitorEvent, TableOutput, TableOutputBasket, TableOutputTag, TableOutputTagMap, TableOutputX, TableProvenTx, TableProvenTxReq, TableProvenTxReqDynamics, TableSettings, TableSyncState, TableTransaction, TableTxLabel, TableTxLabelMap, TableUser, TrustSettings, TscMerkleProofApi, TwilioPhoneInteractor, TxScriptOffsets, UMPToken, UMPTokenInteractor, UMPTokenLookupDiagnostics, UMPTokenLookupError, UMPTokenLookupFailureReason, VerifyAndRepairBeefResult, WABAccountContinuityError, WABClient, WABClientError, WABClientErrorCode, WABClientErrorOptions, WABClientOptions, WABFaucetResponse, WABOperationResponse, WABRequestOptions, WABServerInfo, WABTransport, WABTransportOptions, Wallet, WalletArgs, WalletAuthenticationManager, WalletAuthenticationManagerOptions, WalletLogger, WalletLoggerArgs, WalletLoggerLevel, WalletPermissionsManager, WalletPermissionsManagerCallbacks, WalletSettings, WalletSettingsManager, WalletSettingsManagerConfig, WalletSigner, WalletStorageManager, WalletTheme, WhatsOnChainServices, WhatsOnChainServicesOptions, WocGetHeaderByteFileLinks, WocGetHeadersHeader, arcDefaultUrl, arcGorillaPoolUrl, arcadeDefaultUrl, arraysEqual, asArray, asBsvSdkPrivateKey, asBsvSdkPublickKey, asBsvSdkScript, asBsvSdkTx, asString, asUint8Array, brc29ProtocolID, buildChaintracksOptionsWithIngestors, convertProofToMerklePath, createAndStartDefaultChaintracks, createDefaultBulkFileDataManager, createDefaultChaintracksClient, createDefaultChaintracksStorageOptions, createDefaultNoDbChaintracksOptions, createDefaultWalletServicesOptions, createNoDbChaintracks, createSyncMap, decryptBRC39, doubleSha256BE, doubleSha256LE, encryptBRC39, exportBRC38, exportBRC38Json, exportBRC39, getIdentityKey, getLabelToSpecOp, getListOutputsSpecOp, importBRC38, importBRC39, isBaseBlockHeader, isBlockHeader, isLive, isLiveBlockHeader, logCreateActionArgs, logWalletError, logger, makeAtomicBeef, makeBrc114ActionTimeLabel, maxDate, optionalArraysEqual, outputColumnsWithoutLockingScript, parseBRC38Json, parseBrc114ActionTimeLabels, parseFileLink, parseTxScriptOffsets, partitionActionLabels, randomBytes, randomBytesBase64, randomBytesHex, resolveDefaultChaintracksArguments, index_d_exports as sdk, selectBulkHeaderFiles, sha256Hash, stampLog, stampLogFormat, startChaintracks, tableAuthSessionToPeerSession, throwDummyReviewActions, toBinaryBaseBlockHeader, toDefaultChaintracksArguments, toLookupNetworkPreset, toWalletNetwork, transactionColumnsWithoutRawTx, blockHeaderUtilities_d_exports as utils, validateScriptHash, validateSecondsSinceEpoch, validateStorageFeeModel, verifyHexString, verifyId, verifyInteger, verifyNumber, verifyOne, verifyOneOrNone, verifyOptionalHexString, verifyTruthy, wait, wocGetHeadersHeaderToBlockHeader };
//# sourceMappingURL=index.mobile.d.mts.map