The documentation is split into various pages, this page is the API of the @bsv/wallet-toolbox-client
package;
which is the subset of the @bsv/wallet-toolbox
that is compatible with browser deployment contexts.
Links: API, Interfaces, Classes, Functions, Types, Variables
Links: API, Interfaces, Classes, Functions, Types, Variables
Configuration options for the ARC broadcaster.
export interface ArcConfig {
apiKey?: string;
httpClient?: HttpClient;
deploymentId?: string;
callbackUrl?: string;
callbackToken?: string;
headers?: Record<string, string>;
}
Authentication token for the ARC API
apiKey?: string
default access token for notification callback endpoint. It will be used as a Authorization header for the http callback
callbackToken?: string
notification callback endpoint for proofs and double spend notification
callbackUrl?: string
Deployment id used annotating api calls in XDeployment-ID header - this value will be randomly generated if not set
deploymentId?: string
additional headers to be attached to all tx submissions.
headers?: Record<string, string>
The HTTP client used to make requests to the ARC API.
httpClient?: HttpClient
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ArcMinerGetTxData {
status: number;
title: string;
blockHash: string;
blockHeight: number;
competingTxs: null | string[];
extraInfo: string;
merklePath: string;
timestamp: string;
txid: string;
txStatus: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface AuthId {
identityKey: string;
userId?: number;
isActive?: boolean;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
AuthMethodInteractor
A base interface/class for client-side logic to interact with a server for a specific Auth Method’s flow (start, complete).
export interface AuthPayload {
[key: string]: any;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export interface BaseBlockHeader {
version: number;
previousHash: string;
merkleRoot: string;
time: number;
bits: number;
nonce: number;
}
Block header bits value. Serialized length is 4 bytes.
bits: number
Root hash of the merkle tree of all transactions in this block. Serialized length is 32 bytes.
merkleRoot: string
Block header nonce value. Serialized length is 4 bytes.
nonce: number
Hash of previous block’s block header. Serialized length is 32 bytes.
previousHash: string
Block header time value. Serialized length is 4 bytes.
time: number
Block header version value. Serialized length is 4 bytes.
version: number
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export interface BaseBlockHeader {
version: number;
previousHash: string;
merkleRoot: string;
time: number;
bits: number;
nonce: number;
}
Block header bits value. Serialized length is 4 bytes.
bits: number
Root hash of the merkle tree of all transactions in this block. Serialized length is 32 bytes.
merkleRoot: string
Block header nonce value. Serialized length is 4 bytes.
nonce: number
Hash of previous block’s block header. Serialized length is 32 bytes.
previousHash: string
Block header time value. Serialized length is 4 bytes.
time: number
Block header version value. Serialized length is 4 bytes.
version: number
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface BitailsConfig {
apiKey?: string;
httpClient?: HttpClient;
}
Authentication token for BitTails API
apiKey?: string
The HTTP client used to make requests to the API.
httpClient?: HttpClient
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface BitailsMerkleProof {
index: number;
txOrId: string;
target: string;
nodes: string[];
}
Links: API, Interfaces, Classes, Functions, Types, Variables
A BaseBlockHeader
extended with its computed hash and height in its chain.
export interface BlockHeader extends BaseBlockHeader {
height: number;
hash: string;
}
See also: BaseBlockHeader
The double sha256 hash of the serialized BaseBlockHeader
fields.
hash: string
Height of the header, starting from zero.
height: number
Links: API, Interfaces, Classes, Functions, Types, Variables
A BaseBlockHeader
extended with its computed hash and height in its chain.
export interface BlockHeader extends BaseBlockHeader {
height: number;
hash: string;
}
See also: BaseBlockHeader
The double sha256 hash of the serialized BaseBlockHeader
fields.
hash: string
Height of the header, starting from zero.
height: number
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface BsvExchangeRate {
timestamp: Date;
base: "USD";
rate: number;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface CertOpsWallet {
getPublicKey(args: GetPublicKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetPublicKeyResult>;
encrypt(args: WalletEncryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletEncryptResult>;
decrypt(args: WalletDecryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletDecryptResult>;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface Certifier {
name: string;
description: string;
identityKey: PubKeyHex;
trust: number;
iconUrl?: string;
baseURL?: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface CommitNewTxResults {
req: EntityProvenTxReq;
log?: string;
}
See also: EntityProvenTxReq
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface CompleteAuthResponse {
success: boolean;
message?: string;
presentationKey?: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface CreateActionResultX extends CreateActionResult {
txid?: TXIDHexString;
tx?: AtomicBEEF;
noSendChange?: OutpointString[];
sendWithResults?: SendWithResult[];
signableTransaction?: SignableTransaction;
notDelayedResults?: ReviewActionResult[];
}
See also: ReviewActionResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface EntitySyncMap {
entityName: string;
idMap: Record<number, number>;
maxUpdated_at?: Date;
count: number;
}
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
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
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface EntityTimeStamp {
created_at: Date;
updated_at: Date;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ExchangeRatesIoApi {
success: boolean;
timestamp: number;
base: "EUR" | "USD";
date: string;
rates: Record<string, number>;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ExtendedVerifiableCertificate extends IdentityCertificate {
certifierInfo: IdentityCertifier;
publiclyRevealedKeyring: Record<string, Base64String>;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FiatExchangeRates {
timestamp: Date;
base: "USD";
rates: Record<string, number>;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindCertificateFieldsArgs extends FindSincePagedArgs {
partial: Partial<TableCertificateField>;
}
See also: FindSincePagedArgs, TableCertificateField
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindCertificatesArgs extends FindSincePagedArgs {
partial: Partial<TableCertificate>;
certifiers?: string[];
types?: string[];
includeFields?: boolean;
}
See also: FindSincePagedArgs, TableCertificate
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindCommissionsArgs extends FindSincePagedArgs {
partial: Partial<TableCommission>;
}
See also: FindSincePagedArgs, TableCommission
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindForUserSincePagedArgs extends FindSincePagedArgs {
userId: number;
}
See also: FindSincePagedArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindMonitorEventsArgs extends FindSincePagedArgs {
partial: Partial<TableMonitorEvent>;
}
See also: FindSincePagedArgs, TableMonitorEvent
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindOutputBasketsArgs extends FindSincePagedArgs {
partial: Partial<TableOutputBasket>;
}
See also: FindSincePagedArgs, TableOutputBasket
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindOutputTagMapsArgs extends FindSincePagedArgs {
partial: Partial<TableOutputTagMap>;
tagIds?: number[];
}
See also: FindSincePagedArgs, TableOutputTagMap
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindOutputTagsArgs extends FindSincePagedArgs {
partial: Partial<TableOutputTag>;
}
See also: FindSincePagedArgs, TableOutputTag
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindOutputsArgs extends FindSincePagedArgs {
partial: Partial<TableOutput>;
noScript?: boolean;
txStatus?: TransactionStatus[];
}
See also: FindSincePagedArgs, TableOutput, TransactionStatus
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindPartialSincePagedArgs<T extends object> extends FindSincePagedArgs {
partial: Partial<T>;
}
See also: FindSincePagedArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindProvenTxReqsArgs extends FindSincePagedArgs {
partial: Partial<TableProvenTxReq>;
status?: ProvenTxReqStatus[];
txids?: string[];
}
See also: FindSincePagedArgs, ProvenTxReqStatus, TableProvenTxReq
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindProvenTxsArgs extends FindSincePagedArgs {
partial: Partial<TableProvenTx>;
}
See also: FindSincePagedArgs, TableProvenTx
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindSincePagedArgs {
since?: Date;
paged?: Paged;
trx?: TrxToken;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindSyncStatesArgs extends FindSincePagedArgs {
partial: Partial<TableSyncState>;
}
See also: FindSincePagedArgs, TableSyncState
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindTransactionsArgs extends FindSincePagedArgs {
partial: Partial<TableTransaction>;
status?: TransactionStatus[];
noRawTx?: boolean;
}
See also: FindSincePagedArgs, TableTransaction, TransactionStatus
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindTxLabelMapsArgs extends FindSincePagedArgs {
partial: Partial<TableTxLabelMap>;
labelIds?: number[];
}
See also: FindSincePagedArgs, TableTxLabelMap
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindTxLabelsArgs extends FindSincePagedArgs {
partial: Partial<TableTxLabel>;
}
See also: FindSincePagedArgs, TableTxLabel
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface FindUsersArgs extends FindSincePagedArgs {
partial: Partial<TableUser>;
}
See also: FindSincePagedArgs, TableUser
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GenerateChangeSdkChangeInput {
outputId: number;
satoshis: number;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GenerateChangeSdkChangeOutput {
satoshis: number;
lockingScriptLength: number;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GenerateChangeSdkInput {
satoshis: number;
unlockingScriptLength: number;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GenerateChangeSdkOutput {
satoshis: number;
lockingScriptLength: number;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GenerateChangeSdkParams {
fixedInputs: GenerateChangeSdkInput[];
fixedOutputs: GenerateChangeSdkOutput[];
feeModel: sdk.StorageFeeModel;
targetNetCount?: number;
changeInitialSatoshis: number;
changeFirstSatoshis: number;
changeLockingScriptLength: number;
changeUnlockingScriptLength: number;
randomVals?: number[];
noLogging?: boolean;
log?: string;
}
See also: GenerateChangeSdkInput, GenerateChangeSdkOutput, StorageFeeModel
Lowest amount value to assign to a change output. Drop the output if unable to satisfy. default 285
changeFirstSatoshis: number
Satoshi amount to initialize optional new change outputs.
changeInitialSatoshis: number
Fixed change locking script length.
For P2PKH template, 25 bytes
changeLockingScriptLength: number
Fixed change unlocking script length.
For P2PKH template, 107 bytes
changeUnlockingScriptLength: number
Target for number of new change outputs added minus number of funding change outputs consumed. If undefined, only a single change output will be added if excess fees must be recaptured.
targetNetCount?: number
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GenerateChangeSdkResult {
allocatedChangeInputs: GenerateChangeSdkChangeInput[];
changeOutputs: GenerateChangeSdkChangeOutput[];
size: number;
fee: number;
satsPerKb: number;
maxPossibleSatoshisAdjustment?: {
fixedOutputIndex: number;
satoshis: number;
};
}
See also: GenerateChangeSdkChangeInput, GenerateChangeSdkChangeOutput
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GenerateChangeSdkStorageChange extends GenerateChangeSdkChangeInput {
spendable: boolean;
}
See also: GenerateChangeSdkChangeInput
Links: API, Interfaces, Classes, Functions, Types, Variables
Properties on result returned from WalletServices
function getMerkleProof
.
export interface GetMerklePathResult {
name?: string;
merklePath?: MerklePath;
header?: BlockHeader;
error?: WalletError;
notes?: ReqHistoryNote[];
}
See also: BlockHeader, ReqHistoryNote, WalletError
The first exception error that occurred during processing, if any.
error?: WalletError
See also: WalletError
Multiple proofs may be returned when a transaction also appears in one or more orphaned blocks
merklePath?: MerklePath
The name of the service returning the proof, or undefined if no proof
name?: string
Links: API, Interfaces, Classes, Functions, Types, Variables
Properties on result returned from WalletServices
function getRawTx
.
export interface GetRawTxResult {
txid: string;
name?: string;
rawTx?: number[];
error?: WalletError;
}
See also: WalletError
The first exception error that occurred during processing, if any.
error?: WalletError
See also: WalletError
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[]
Transaction hash or rawTx (and of initial request)
txid: string
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GetReqsAndBeefDetail {
txid: string;
req?: TableProvenTxReq;
proven?: TableProvenTx;
status: "readyToSend" | "alreadySent" | "error" | "unknown";
error?: string;
}
See also: TableProvenTx, TableProvenTxReq
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GetReqsAndBeefResult {
beef: Beef;
details: GetReqsAndBeefDetail[];
}
See also: GetReqsAndBeefDetail
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GetScriptHashHistory {
txid: string;
height?: number;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GetScriptHashHistoryResult {
name: string;
status: "success" | "error";
error?: WalletError;
history: GetScriptHashHistory[];
}
See also: GetScriptHashHistory, WalletError
When status is ‘error’, provides code and description
error?: WalletError
See also: WalletError
Transaction txid (and height if mined) that consumes the script hash. May not be a complete history.
history: GetScriptHashHistory[]
See also: GetScriptHashHistory
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"
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GetStatusForTxidsResult {
name: string;
status: "success" | "error";
error?: WalletError;
results: StatusForTxidResult[];
}
See also: StatusForTxidResult, WalletError
The first exception error that occurred during processing, if any.
error?: WalletError
See also: WalletError
The name of the service returning these results.
name: string
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GetUtxoStatusDetails {
height?: number;
txid?: string;
index?: number;
satoshis?: number;
}
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 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
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
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface GetUtxoStatusResult {
name: string;
status: "success" | "error";
error?: WalletError;
isUtxo?: boolean;
details: GetUtxoStatusDetails[];
}
See also: GetUtxoStatusDetails, WalletError
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[]
See also: GetUtxoStatusDetails
When status is ‘error’, provides code and description
error?: WalletError
See also: WalletError
true if the output is associated with at least one unspent transaction output
isUtxo?: boolean
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"
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface KeyPair {
privateKey: string;
publicKey: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export interface LiveBlockHeader extends BlockHeader {
chainWork: string;
isChainTip: boolean;
isActive: boolean;
headerId: number;
previousHeaderId: number | null;
}
See also: BlockHeader
The cummulative chainwork achieved by the addition of this block to the chain. Chainwork only matters in selecting the active chain.
chainWork: string
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
True only if this header is currently on the active chain.
isActive: boolean
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
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
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface MonitorOptions {
chain: sdk.Chain;
services: Services;
storage: MonitorStorage;
chaintracks: ChaintracksServiceClient;
msecsWaitPerMerkleProofServiceReq: number;
taskRunWaitMsecs: number;
abandonedMsecs: number;
unprovenAttemptsLimitTest: number;
unprovenAttemptsLimitMain: number;
}
See also: Chain, MonitorStorage, Services
How many msecs to wait after each getMerkleProof service request.
msecsWaitPerMerkleProofServiceReq: number
Links: API, Interfaces, Classes, Functions, Types, Variables
Identifies a unique transaction output by its txid
and index vout
export interface OutPoint {
txid: string;
vout: number;
}
Transaction double sha256 hash as big endian hex string
txid: string
zero based output index within the transaction
vout: number
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface Paged {
limit: number;
offset?: number;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PendingSignAction {
reference: string;
dcr: sdk.StorageCreateActionResult;
args: sdk.ValidCreateActionArgs;
tx: BsvTransaction;
amount: number;
pdi: PendingStorageInput[];
}
See also: PendingStorageInput, StorageCreateActionResult, ValidCreateActionArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PendingStorageInput {
vin: number;
derivationPrefix: string;
derivationSuffix: string;
unlockerPubKey?: string;
sourceSatoshis: number;
lockingScript: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export interface PermissionRequest {
type: "protocol" | "basket" | "certificate" | "spending";
originator: string;
privileged?: boolean;
protocolID?: WalletProtocol;
counterparty?: string;
basket?: string;
certificate?: {
verifier: string;
certType: string;
fields: string[];
};
spending?: {
satoshis: number;
lineItems?: Array<{
type: "input" | "output" | "fee";
description: string;
satoshis: number;
}>;
};
reason?: string;
renewal?: boolean;
previousToken?: PermissionToken;
}
See also: PermissionToken
Links: API, Interfaces, Classes, Functions, Types, Variables
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:
export interface PermissionToken {
txid: string;
outputIndex: number;
outputScript: string;
satoshis: number;
originator: string;
expiry: number;
privileged?: boolean;
protocol?: string;
securityLevel?: 0 | 1 | 2;
counterparty?: string;
basketName?: string;
certType?: string;
certFields?: string[];
verifier?: string;
authorizedAmount?: number;
}
For DSAP, the maximum authorized spending for the month.
authorizedAmount?: number
The name of a basket, if this is a DBAP token.
basketName?: string
The certificate fields that this token covers, if DCAP token.
certFields?: string[]
The certificate type, if this is a DCAP token.
certType?: string
The counterparty, for DPACP.
counterparty?: string
The expiration time for this token in UNIX epoch seconds. (0 or omitted for spending authorizations, which are indefinite)
expiry: number
The originator domain or FQDN that is allowed to use this permission.
originator: string
The output index within that transaction.
outputIndex: number
The exact script hex for the locking script.
outputScript: string
Whether this token grants privileged usage (for protocol or certificate).
privileged?: boolean
The protocol name, if this is a DPACP token.
protocol?: string
The amount of satoshis assigned to the permission output (often 1).
satoshis: number
The security level (0,1,2) for DPACP.
securityLevel?: 0 | 1 | 2
The transaction ID where this token resides.
txid: string
The “verifier” public key string, if DCAP.
verifier?: string
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export interface PermissionsManagerConfig {
seekProtocolPermissionsForSigning?: boolean;
seekProtocolPermissionsForEncrypting?: boolean;
seekProtocolPermissionsForHMAC?: boolean;
seekPermissionsForKeyLinkageRevelation?: boolean;
seekPermissionsForPublicKeyRevelation?: boolean;
seekPermissionsForIdentityKeyRevelation?: boolean;
seekPermissionsForIdentityResolution?: boolean;
seekBasketInsertionPermissions?: boolean;
seekBasketRemovalPermissions?: boolean;
seekBasketListingPermissions?: boolean;
seekPermissionWhenApplyingActionLabels?: boolean;
seekPermissionWhenListingActionsByLabel?: boolean;
seekCertificateDisclosurePermissions?: boolean;
seekCertificateAcquisitionPermissions?: boolean;
seekCertificateRelinquishmentPermissions?: boolean;
seekCertificateListingPermissions?: boolean;
encryptWalletMetadata?: boolean;
seekSpendingPermissions?: boolean;
differentiatePrivilegedOperations?: 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
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
When we do internalizeAction with basket insertion
, or include outputs in baskets
with `createAction, do we ask for basket permission?
seekBasketInsertionPermissions?: boolean
When listOutputs is called, do we ask for basket permission?
seekBasketListingPermissions?: boolean
When relinquishOutput is called, do we ask for basket permission?
seekBasketRemovalPermissions?: boolean
If acquiring a certificate (acquireCertificate), do we require a permission check?
seekCertificateAcquisitionPermissions?: boolean
If proving a certificate (proveCertificate) or revealing certificate fields, do we require a “certificate access” permission?
seekCertificateDisclosurePermissions?: boolean
If listing a user’s certificates (listCertificates), do we require a permission check?
seekCertificateListingPermissions?: boolean
If relinquishing a certificate (relinquishCertificate), do we require a permission check?
seekCertificateRelinquishmentPermissions?: 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 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
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
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 createSignature
and verifySignature
,
require a “protocol usage” permission check?
seekProtocolPermissionsForSigning?: boolean
If the originator tries to spend wallet funds (netSpent > 0 in createAction), do we seek spending authorization?
seekSpendingPermissions?: boolean
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PostBeefResult extends PostTxsResult {
}
See also: PostTxsResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PostBeefResultForTxidApi {
txid: string;
status: "success" | "error";
alreadyKnown?: boolean;
blockHash?: string;
blockHeight?: number;
merklePath?: string;
}
if true, the transaction was already known to this service. Usually treat as a success.
Potentially stop posting to additional transaction processors.
alreadyKnown?: boolean
‘success’ - The transaction was accepted for processing
status: "success" | "error"
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PostReqsToNetworkDetails {
txid: string;
req: EntityProvenTxReq;
status: PostReqsToNetworkDetailsStatus;
competingTxs?: string[];
}
See also: EntityProvenTxReq, PostReqsToNetworkDetailsStatus
Any competing double spend txids reported for this txid
competingTxs?: string[]
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PostReqsToNetworkResult {
status: "success" | "error";
beef: Beef;
details: PostReqsToNetworkDetails[];
log: string;
}
See also: PostReqsToNetworkDetails
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PostTxResultForTxid {
txid: string;
status: "success" | "error";
alreadyKnown?: boolean;
doubleSpend?: boolean;
blockHash?: string;
blockHeight?: number;
merklePath?: MerklePath;
competingTxs?: string[];
data?: object | string | PostTxResultForTxidError;
notes?: ReqHistoryNote[];
serviceError?: boolean;
}
See also: PostTxResultForTxidError, ReqHistoryNote
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
true iff service was unable to process a potentially valid transaction
serviceError?: boolean
‘success’ - The transaction was accepted for processing
status: "success" | "error"
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PostTxResultForTxidError {
status?: string;
detail?: string;
more?: object;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
Properties on array items of result returned from WalletServices
function postBeef
.
export interface PostTxsResult {
name: string;
status: "success" | "error";
error?: WalletError;
txidResults: PostTxResultForTxid[];
data?: object;
notes?: ReqHistoryNote[];
}
See also: PostTxResultForTxid, ReqHistoryNote, WalletError
Service response object. Use service name and status to infer type of object.
data?: object
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"
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ProcessSyncChunkResult {
done: boolean;
maxUpdated_at: Date | undefined;
updates: number;
inserts: number;
error?: WalletError;
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
Describes the structure of a user profile within the wallet.
export interface Profile {
name: string;
id: number[];
primaryPad: number[];
privilegedPad: number[];
createdAt: number;
}
Timestamp (seconds since epoch) when the profile was created.
createdAt: number
Unique 16-byte identifier for the profile.
id: number[]
User-defined name for the profile.
name: string
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[]
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ProvenOrRawTx {
proven?: TableProvenTx;
rawTx?: number[];
inputBEEF?: number[];
}
See also: TableProvenTx
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ProvenTxFromTxidResult {
proven?: EntityProvenTx;
rawTx?: number[];
}
See also: EntityProvenTx
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ProvenTxReqHistory {
notes?: sdk.ReqHistoryNote[];
}
See also: ReqHistoryNote
Keys are Date().toISOString() Values are a description of what happened.
notes?: sdk.ReqHistoryNote[]
See also: ReqHistoryNote
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ProvenTxReqHistorySummaryApi {
setToCompleted: boolean;
setToCallback: boolean;
setToUnmined: boolean;
setToDoubleSpend: boolean;
setToSending: boolean;
setToUnconfirmed: boolean;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ProvenTxReqNotify {
transactionIds?: number[];
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PurgeParams {
purgeCompleted: boolean;
purgeFailed: boolean;
purgeSpent: boolean;
purgeCompletedAge?: number;
purgeFailedAge?: number;
purgeSpentAge?: number;
}
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
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface PurgeResults {
count: number;
log: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface RequestSyncChunkArgs {
fromStorageIdentityKey: string;
toStorageIdentityKey: string;
identityKey: string;
since?: Date;
maxRoughSize: number;
maxItems: number;
offsets: {
name: string;
offset: number;
}[];
}
The storageIdentityKey of the storage supplying the update SyncChunk data.
fromStorageIdentityKey: string
The identity of whose data is being requested
identityKey: string
The maximum number of items (records) to be returned.
maxItems: number
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
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: {
name: string;
offset: number;
}[]
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
The storageIdentityKey of the storage consuming the update SyncChunk data.
toStorageIdentityKey: string
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ReviewActionResult {
txid: TXIDHexString;
status: ReviewActionResultStatus;
competingTxs?: string[];
competingBeef?: number[];
}
See also: ReviewActionResultStatus
Merged beef of competingTxs, valid when status is ‘doubleSpend’.
competingBeef?: number[]
Any competing txids reported for this txid, valid when status is ‘doubleSpend’.
competingTxs?: string[]
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ScriptTemplateParamsBRC29 {
derivationPrefix?: string;
derivationSuffix?: string;
keyDeriver: KeyDeriverApi;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ScriptTemplateUnlock {
sign: (tx: Transaction, inputIndex: number) => Promise<UnlockingScript>;
estimateLength: (tx: Transaction, inputIndex: number) => Promise<number>;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface SignActionResultX extends SignActionResult {
txid?: TXIDHexString;
tx?: AtomicBEEF;
sendWithResults?: SendWithResult[];
notDelayedResults?: ReviewActionResult[];
}
See also: ReviewActionResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StartAuthResponse {
success: boolean;
message?: string;
data?: any;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StatusForTxidResult {
txid: string;
depth: number | undefined;
status: "mined" | "known" | "unknown";
}
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"
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageCreateActionResult {
inputBeef?: number[];
inputs: StorageCreateTransactionSdkInput[];
outputs: StorageCreateTransactionSdkOutput[];
noSendChangeOutputVouts?: number[];
derivationPrefix: string;
version: number;
lockTime: number;
reference: string;
}
See also: StorageCreateTransactionSdkInput, StorageCreateTransactionSdkOutput
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageCreateTransactionSdkInput {
vin: number;
sourceTxid: string;
sourceVout: number;
sourceSatoshis: number;
sourceLockingScript: string;
sourceTransaction?: number[];
unlockingScriptLength: number;
providedBy: StorageProvidedBy;
type: string;
spendingDescription?: string;
derivationPrefix?: string;
derivationSuffix?: string;
senderIdentityKey?: string;
}
See also: StorageProvidedBy
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageCreateTransactionSdkOutput extends ValidCreateActionOutput {
vout: number;
providedBy: StorageProvidedBy;
purpose?: string;
derivationSuffix?: string;
}
See also: StorageProvidedBy, ValidCreateActionOutput
Links: API, Interfaces, Classes, Functions, Types, Variables
Specifies the available options for computing transaction fees.
export interface StorageFeeModel {
model: "sat/kb";
value?: number;
}
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
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageGetBeefOptions {
trustSelf?: "known";
knownTxids?: string[];
mergeToBeef?: Beef | number[];
ignoreStorage?: boolean;
ignoreServices?: boolean;
ignoreNewProven?: boolean;
minProofLevel?: number;
}
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 false. getServices
is used for raw transaction and merkle proof lookup
ignoreServices?: boolean
optional. Default is false. storage
is used for raw transaction and merkle proof lookup
ignoreStorage?: boolean
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[]
optional. Default is zero. Ignores available merkle paths until recursion detpth equals or exceeds value
minProofLevel?: number
if ‘known’, txids known to local storage as valid are included as txidOnly
trustSelf?: "known"
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageIdentity {
storageIdentityKey: string;
storageName: string;
}
The identity key (public key) assigned to this storage
storageIdentityKey: string
The human readable name assigned to this storage.
storageName: string
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageInternalizeActionResult extends InternalizeActionResult {
isMerge: boolean;
txid: string;
satoshis: number;
}
true if internalizing outputs on an existing storage transaction
isMerge: boolean
net change in change balance for user due to this internalization
satoshis: number
txid of transaction being internalized
txid: string
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageProcessActionArgs {
isNewTx: boolean;
isSendWith: boolean;
isNoSend: boolean;
isDelayed: boolean;
reference?: string;
txid?: string;
rawTx?: number[];
sendWith: string[];
log?: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageProcessActionResults {
sendWithResults?: SendWithResult[];
notDelayedResults?: ReviewActionResult[];
log?: string;
}
See also: ReviewActionResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageProvenOrReq {
proven?: TableProvenTx;
req?: TableProvenTxReq;
}
See also: TableProvenTx, TableProvenTxReq
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageProviderOptions extends StorageReaderWriterOptions {
chain: sdk.Chain;
feeModel: sdk.StorageFeeModel;
commissionSatoshis: number;
commissionPubKeyHex?: PubKeyHex;
}
See also: Chain, StorageFeeModel, StorageReaderWriterOptions
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
Transactions created by this Storage can charge a fee per transaction. A value of zero disables commission fees.
commissionSatoshis: number
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageReaderOptions {
chain: sdk.Chain;
}
See also: Chain
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageReaderWriterOptions extends StorageReaderOptions {
}
See also: StorageReaderOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface StorageSyncReaderOptions {
chain: Chain;
}
See also: Chain
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export 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[];
}
See also: TableCertificate, TableCertificateField, TableCommission, TableOutput, TableOutputBasket, TableOutputTag, TableOutputTagMap, TableProvenTx, TableProvenTxReq, TableTransaction, TableTxLabel, TableTxLabelMap, TableUser
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface SyncError {
code: string;
description: string;
stack?: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export 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;
}
See also: EntitySyncMap
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableCertificate extends sdk.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;
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableCertificateField extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
userId: number;
certificateId: number;
fieldName: string;
fieldValue: string;
masterKey: Base64String;
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableCertificateX extends TableCertificate {
fields?: TableCertificateField[];
}
See also: TableCertificate, TableCertificateField
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableCommission extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
commissionId: number;
userId: number;
transactionId: number;
satoshis: number;
keyOffset: string;
isRedeemed: boolean;
lockingScript: number[];
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableMonitorEvent extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
id: number;
event: string;
details?: string;
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableOutput extends sdk.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: sdk.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[];
}
See also: EntityTimeStamp, StorageProvidedBy
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableOutputBasket extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
basketId: number;
userId: number;
name: string;
numberOfDesiredUTXOs: number;
minimumDesiredUTXOValue: number;
isDeleted: boolean;
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableOutputTag extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
outputTagId: number;
userId: number;
tag: string;
isDeleted: boolean;
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableOutputTagMap extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
outputTagId: number;
outputId: number;
isDeleted: boolean;
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableOutputX extends TableOutput {
basket?: TableOutputBasket;
tags?: TableOutputTag[];
}
See also: TableOutput, TableOutputBasket, TableOutputTag
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableProvenTx extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
provenTxId: number;
txid: string;
height: number;
index: number;
merklePath: number[];
rawTx: number[];
blockHash: string;
merkleRoot: string;
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableProvenTxReq extends TableProvenTxReqDynamics {
created_at: Date;
updated_at: Date;
provenTxReqId: number;
provenTxId?: number;
status: sdk.ProvenTxReqStatus;
attempts: number;
notified: boolean;
txid: string;
batch?: string;
history: string;
notify: string;
rawTx: number[];
inputBEEF?: number[];
}
See also: ProvenTxReqStatus, TableProvenTxReqDynamics
Count of how many times a service has been asked about this txid
attempts: number
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
Set to true when a terminal status has been set and notification has occurred.
notified: boolean
JSON string of data to drive notifications when this request completes.
Parses to ProvenTxReqNotifyApi
.
notify: string
Links: API, Interfaces, Classes, Functions, Types, Variables
Table properties that may change after initial record insertion.
export interface TableProvenTxReqDynamics extends sdk.EntityTimeStamp {
updated_at: Date;
provenTxId?: number;
status: sdk.ProvenTxReqStatus;
attempts: number;
notified: boolean;
batch?: string;
history: string;
notify: string;
}
See also: EntityTimeStamp, ProvenTxReqStatus
Count of how many times a service has been asked about this txid
attempts: number
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
Set to true when a terminal status has been set and notification has occurred.
notified: boolean
JSON string of data to drive notifications when this request completes.
Parses to ProvenTxReqNotifyApi
.
notify: string
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableSettings extends sdk.StorageIdentity, sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
storageIdentityKey: string;
storageName: string;
chain: sdk.Chain;
dbtype: "SQLite" | "MySQL";
maxOutputScript: number;
}
See also: Chain, EntityTimeStamp, StorageIdentity
The identity key (public key) assigned to this storage
storageIdentityKey: string
The human readable name assigned to this storage.
storageName: string
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableSyncState extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
syncStateId: number;
userId: number;
storageIdentityKey: string;
storageName: string;
status: sdk.SyncStatus;
init: boolean;
refNum: string;
syncMap: string;
when?: Date;
satoshis?: number;
errorLocal?: string;
errorOther?: string;
}
See also: EntityTimeStamp, SyncStatus
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableTransaction extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
transactionId: number;
userId: number;
provenTxId?: number;
status: sdk.TransactionStatus;
reference: Base64String;
isOutgoing: boolean;
satoshis: number;
description: string;
version?: number;
lockTime?: number;
txid?: string;
inputBEEF?: number[];
rawTx?: number[];
}
See also: EntityTimeStamp, TransactionStatus
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
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
max length of 64, hex encoded
reference: Base64String
If not undefined, must match value in associated rawTransaction.
version?: number
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableTxLabel extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
txLabelId: number;
userId: number;
label: string;
isDeleted: boolean;
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableTxLabelMap extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
txLabelId: number;
transactionId: number;
isDeleted: boolean;
}
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TableUser extends sdk.EntityTimeStamp {
created_at: Date;
updated_at: Date;
userId: number;
identityKey: string;
activeStorage: string;
}
See also: EntityTimeStamp
The storageIdentityKey value of the active wallet storage.
activeStorage: string
PubKeyHex uniquely identifying user. Typically 66 hex digits.
identityKey: string
Links: API, Interfaces, Classes, Functions, Types, Variables
The database stores a variety of data that may be considered transient.
At one extreme, the data that must be preserved:
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:
export interface TaskPurgeParams extends PurgeParams {
}
See also: PurgeParams
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TrustSettings {
trustLevel: number;
trustedCertifiers: Certifier[];
}
See also: Certifier
Links: API, Interfaces, Classes, Functions, Types, Variables
Place holder for the transaction control object used by actual storage provider implementation.
export interface TrxToken {
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TscMerkleProofApi {
height: number;
index: number;
nodes: string[];
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface TxScriptOffsets {
inputs: {
vin: number;
offset: number;
length: number;
}[];
outputs: {
vout: number;
offset: number;
length: number;
}[];
}
Links: API, Interfaces, Classes, Functions, Types, Variables
Describes the structure of a User Management Protocol (UMP) token.
export interface UMPToken {
passwordPresentationPrimary: number[];
passwordRecoveryPrimary: number[];
presentationRecoveryPrimary: number[];
passwordPrimaryPrivileged: number[];
presentationRecoveryPrivileged: number[];
presentationHash: number[];
passwordSalt: number[];
recoveryHash: number[];
presentationKeyEncrypted: number[];
recoveryKeyEncrypted: number[];
passwordKeyEncrypted: number[];
profilesEncrypted?: number[];
currentOutpoint?: OutpointString;
}
Describes the token’s location on-chain, if it’s already been published.
currentOutpoint?: OutpointString
A copy of the password key encrypted with the root privileged key.
passwordKeyEncrypted: number[]
Root Primary key encrypted by the XOR of the password and presentation keys.
passwordPresentationPrimary: number[]
Root Privileged key encrypted by the XOR of the password and primary keys.
passwordPrimaryPrivileged: number[]
Root Primary key encrypted by the XOR of the password and recovery keys.
passwordRecoveryPrimary: number[]
PBKDF2 salt used in conjunction with the password to derive the password key.
passwordSalt: number[]
Hash of the presentation key.
presentationHash: number[]
A copy of the presentation key encrypted with the root privileged key.
presentationKeyEncrypted: 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 presentation and recovery keys.
presentationRecoveryPrivileged: number[]
Optional field containing the encrypted profile data. JSON string -> Encrypted Bytes using root privileged key.
profilesEncrypted?: number[]
Hash of the recovery key.
recoveryHash: number[]
A copy of the recovery key encrypted with the root privileged key.
recoveryKeyEncrypted: number[]
Links: API, Interfaces, Classes, Functions, Types, Variables
Describes a system capable of finding and updating UMP tokens on the blockchain.
export interface UMPTokenInteractor {
findByPresentationKeyHash: (hash: number[]) => Promise<UMPToken | undefined>;
findByRecoveryKeyHash: (hash: number[]) => Promise<UMPToken | undefined>;
buildAndSend: (wallet: WalletInterface, adminOriginator: OriginatorDomainNameStringUnder250Bytes, token: UMPToken, oldTokenToConsume?: UMPToken) => Promise<OutpointString>;
}
See also: UMPToken
Creates (and optionally consumes the previous version of) a UMP token on-chain.
buildAndSend: (wallet: WalletInterface, adminOriginator: OriginatorDomainNameStringUnder250Bytes, token: UMPToken, oldTokenToConsume?: UMPToken) => Promise<OutpointString>
See also: UMPToken
Locates the latest valid copy of a UMP token (including its outpoint) based on the presentation key hash.
findByPresentationKeyHash: (hash: number[]) => Promise<UMPToken | undefined>
See also: UMPToken
Locates the latest valid copy of a UMP token (including its outpoint) based on the recovery key hash.
findByRecoveryKeyHash: (hash: number[]) => Promise<UMPToken | undefined>
See also: UMPToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface UpdateProvenTxReqWithNewProvenTxArgs {
provenTxReqId: number;
txid: string;
attempts: number;
status: ProvenTxReqStatus;
history: string;
height: number;
index: number;
blockHash: string;
merkleRoot: string;
merklePath: number[];
}
See also: ProvenTxReqStatus
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface UpdateProvenTxReqWithNewProvenTxResult {
status: ProvenTxReqStatus;
history: string;
provenTxId: number;
log?: string;
}
See also: ProvenTxReqStatus
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidAbortActionArgs extends ValidWalletSignerArgs {
reference: Base64String;
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidAcquireCertificateArgs extends ValidWalletSignerArgs {
acquisitionProtocol: AcquisitionProtocol;
type: Base64String;
serialNumber?: Base64String;
certifier: PubKeyHex;
revocationOutpoint?: OutpointString;
fields: Record<CertificateFieldNameUnder50Bytes, string>;
signature?: HexString;
certifierUrl?: string;
keyringRevealer?: KeyringRevealer;
keyringForSubject?: Record<CertificateFieldNameUnder50Bytes, Base64String>;
privileged: boolean;
privilegedReason?: DescriptionString5to50Bytes;
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidAcquireDirectCertificateArgs extends ValidWalletSignerArgs {
type: Base64String;
serialNumber: Base64String;
certifier: PubKeyHex;
revocationOutpoint: OutpointString;
fields: Record<CertificateFieldNameUnder50Bytes, string>;
signature: HexString;
subject: PubKeyHex;
keyringRevealer: KeyringRevealer;
keyringForSubject: Record<CertificateFieldNameUnder50Bytes, Base64String>;
privileged: boolean;
privilegedReason?: DescriptionString5to50Bytes;
}
See also: ValidWalletSignerArgs
validated to an empty string, must be provided by wallet and must match expectations of keyringForSubject
subject: PubKeyHex
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidAcquireIssuanceCertificateArgs extends ValidWalletSignerArgs {
type: Base64String;
certifier: PubKeyHex;
certifierUrl: string;
fields: Record<CertificateFieldNameUnder50Bytes, string>;
subject: PubKeyHex;
privileged: boolean;
privilegedReason?: DescriptionString5to50Bytes;
}
See also: ValidWalletSignerArgs
validated to an empty string, must be provided by wallet and must match expectations of keyringForSubject
subject: PubKeyHex
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidBasketInsertion {
basket: BasketStringUnder300Bytes;
customInstructions?: string;
tags: BasketStringUnder300Bytes[];
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidCreateActionArgs extends ValidProcessActionArgs {
description: DescriptionString5to2000Bytes;
inputBEEF?: BEEF;
inputs: sdk.ValidCreateActionInput[];
outputs: sdk.ValidCreateActionOutput[];
lockTime: number;
version: number;
labels: string[];
options: ValidCreateActionOptions;
isSignAction: boolean;
randomVals?: number[];
includeAllSourceTransactions: boolean;
}
See also: DescriptionString5to2000Bytes, ValidCreateActionInput, ValidCreateActionOptions, ValidCreateActionOutput, ValidProcessActionArgs
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
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidCreateActionInput {
outpoint: OutPoint;
inputDescription: DescriptionString5to2000Bytes;
sequenceNumber: PositiveIntegerOrZero;
unlockingScript?: HexString;
unlockingScriptLength: PositiveInteger;
}
See also: DescriptionString5to2000Bytes, OutPoint
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidCreateActionOptions extends ValidProcessActionOptions {
signAndProcess: boolean;
trustSelf?: TrustSelf;
knownTxids: TXIDHexString[];
noSendChange: OutPoint[];
randomizeOutputs: boolean;
}
See also: OutPoint, ValidProcessActionOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidCreateActionOutput {
lockingScript: HexString;
satoshis: SatoshiValue;
outputDescription: DescriptionString5to2000Bytes;
basket?: BasketStringUnder300Bytes;
customInstructions?: string;
tags: BasketStringUnder300Bytes[];
}
See also: DescriptionString5to2000Bytes
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidDiscoverByAttributesArgs extends ValidWalletSignerArgs {
attributes: Record<CertificateFieldNameUnder50Bytes, string>;
limit: PositiveIntegerDefault10Max10000;
offset: PositiveIntegerOrZero;
seekPermission: boolean;
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidDiscoverByIdentityKeyArgs extends ValidWalletSignerArgs {
identityKey: PubKeyHex;
limit: PositiveIntegerDefault10Max10000;
offset: PositiveIntegerOrZero;
seekPermission: boolean;
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidInternalizeActionArgs extends ValidWalletSignerArgs {
tx: AtomicBEEF;
outputs: InternalizeOutput[];
description: DescriptionString5to2000Bytes;
labels: LabelStringUnder300Bytes[];
seekPermission: BooleanDefaultTrue;
}
See also: DescriptionString5to2000Bytes, ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidInternalizeOutput {
outputIndex: PositiveIntegerOrZero;
protocol: "wallet payment" | "basket insertion";
paymentRemittance?: ValidWalletPayment;
insertionRemittance?: ValidBasketInsertion;
}
See also: ValidBasketInsertion, ValidWalletPayment
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidListActionsArgs extends ValidWalletSignerArgs {
labels: LabelStringUnder300Bytes[];
labelQueryMode: "any" | "all";
includeLabels: BooleanDefaultFalse;
includeInputs: BooleanDefaultFalse;
includeInputSourceLockingScripts: BooleanDefaultFalse;
includeInputUnlockingScripts: BooleanDefaultFalse;
includeOutputs: BooleanDefaultFalse;
includeOutputLockingScripts: BooleanDefaultFalse;
limit: PositiveIntegerDefault10Max10000;
offset: PositiveIntegerOrZero;
seekPermission: BooleanDefaultTrue;
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidListCertificatesArgs extends ValidWalletSignerArgs {
partial?: {
type?: Base64String;
serialNumber?: Base64String;
certifier?: PubKeyHex;
subject?: PubKeyHex;
revocationOutpoint?: OutpointString;
signature?: HexString;
};
certifiers: PubKeyHex[];
types: Base64String[];
limit: PositiveIntegerDefault10Max10000;
offset: PositiveIntegerOrZero;
privileged: BooleanDefaultFalse;
privilegedReason?: DescriptionString5to50Bytes;
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidListOutputsArgs extends ValidWalletSignerArgs {
basket: BasketStringUnder300Bytes;
tags: OutputTagStringUnder300Bytes[];
tagQueryMode: "all" | "any";
includeLockingScripts: boolean;
includeTransactions: boolean;
includeCustomInstructions: BooleanDefaultFalse;
includeTags: BooleanDefaultFalse;
includeLabels: BooleanDefaultFalse;
limit: PositiveIntegerDefault10Max10000;
offset: PositiveIntegerOrZero;
seekPermission: BooleanDefaultTrue;
knownTxids: string[];
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidProcessActionArgs extends ValidWalletSignerArgs {
options: sdk.ValidProcessActionOptions;
isSendWith: boolean;
isNewTx: boolean;
isRemixChange: boolean;
isNoSend: boolean;
isDelayed: boolean;
}
See also: ValidProcessActionOptions, ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidProcessActionOptions {
acceptDelayedBroadcast: BooleanDefaultTrue;
returnTXIDOnly: BooleanDefaultFalse;
noSend: BooleanDefaultFalse;
sendWith: TXIDHexString[];
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidProveCertificateArgs extends ValidWalletSignerArgs {
type?: Base64String;
serialNumber?: Base64String;
certifier?: PubKeyHex;
subject?: PubKeyHex;
revocationOutpoint?: OutpointString;
signature?: HexString;
fieldsToReveal: CertificateFieldNameUnder50Bytes[];
verifier: PubKeyHex;
privileged: boolean;
privilegedReason?: DescriptionString5to50Bytes;
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidRelinquishCertificateArgs extends ValidWalletSignerArgs {
type: Base64String;
serialNumber: Base64String;
certifier: PubKeyHex;
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidRelinquishOutputArgs extends ValidWalletSignerArgs {
basket: BasketStringUnder300Bytes;
output: OutpointString;
}
See also: ValidWalletSignerArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidSignActionArgs extends ValidProcessActionArgs {
spends: Record<PositiveIntegerOrZero, SignActionSpend>;
reference: Base64String;
options: sdk.ValidSignActionOptions;
}
See also: ValidProcessActionArgs, ValidSignActionOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidSignActionOptions extends ValidProcessActionOptions {
acceptDelayedBroadcast: boolean;
returnTXIDOnly: boolean;
noSend: boolean;
sendWith: TXIDHexString[];
}
See also: ValidProcessActionOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidWalletPayment {
derivationPrefix: Base64String;
derivationSuffix: Base64String;
senderIdentityKey: PubKeyHex;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidWalletSignerArgs {
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface ValidateGenerateChangeSdkParamsResult {
hasMaxPossibleOutput?: number;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface WalletArgs {
chain: sdk.Chain;
keyDeriver: KeyDeriver;
storage: WalletStorageManager;
services?: sdk.WalletServices;
monitor?: Monitor;
privilegedKeyManager?: sdk.PrivilegedKeyManager;
settingsManager?: WalletSettingsManager;
lookupResolver?: LookupResolver;
}
See also: Chain, Monitor, PrivilegedKeyManager, WalletServices, WalletSettingsManager, WalletStorageManager
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface WalletBalance {
total: number;
utxos: {
satoshis: number;
outpoint: string;
}[];
}
Links: API, Interfaces, Classes, Functions, Types, Variables
The set of callbacks that external code can bind to, e.g. to display UI prompts or logs when a permission is requested.
export interface WalletPermissionsManagerCallbacks {
onProtocolPermissionRequested?: PermissionEventHandler[];
onBasketAccessRequested?: PermissionEventHandler[];
onCertificateAccessRequested?: PermissionEventHandler[];
onSpendingAuthorizationRequested?: PermissionEventHandler[];
}
See also: PermissionEventHandler
Links: API, Interfaces, Classes, Functions, Types, Variables
Defines standard interfaces to access functionality implemented by external transaction processing services.
export interface WalletServices {
chain: Chain;
getChainTracker(): Promise<ChainTracker>;
getHeaderForHeight(height: number): Promise<number[]>;
getHeight(): Promise<number>;
getBsvExchangeRate(): Promise<number>;
getFiatExchangeRate(currency: "USD" | "GBP" | "EUR", base?: "USD" | "GBP" | "EUR"): Promise<number>;
getRawTx(txid: string, useNext?: boolean): Promise<GetRawTxResult>;
getMerklePath(txid: string, useNext?: boolean): Promise<GetMerklePathResult>;
postBeef(beef: Beef, txids: string[]): Promise<PostBeefResult[]>;
hashOutputScript(script: string): string;
getStatusForTxids(txids: string[], useNext?: boolean): Promise<GetStatusForTxidsResult>;
getUtxoStatus(output: string, outputFormat?: GetUtxoStatusOutputFormat, outpoint?: string, useNext?: boolean): Promise<GetUtxoStatusResult>;
getScriptHashHistory(hash: string, useNext?: boolean): Promise<GetScriptHashHistoryResult>;
hashToHeader(hash: string): Promise<BlockHeader>;
nLockTimeIsFinal(txOrLockTime: string | number[] | BsvTransaction | number): Promise<boolean>;
}
See also: BlockHeader, Chain, GetMerklePathResult, GetRawTxResult, GetScriptHashHistoryResult, GetStatusForTxidsResult, GetUtxoStatusOutputFormat, GetUtxoStatusResult, PostBeefResult
The chain being serviced.
chain: Chain
See also: Chain
Approximate exchange rate US Dollar / BSV, USD / BSV
This is the US Dollar price of one BSV
getBsvExchangeRate(): Promise<number>
getChainTracker(): Promise<ChainTracker>
Returns
standard ChainTracker
service which requires options.chaintracks
be valid.
Approximate exchange rate currency per base.
getFiatExchangeRate(currency: "USD" | "GBP" | "EUR", base?: "USD" | "GBP" | "EUR"): Promise<number>
getHeaderForHeight(height: number): Promise<number[]>
Returns
serialized block header for height on active chain
getHeight(): Promise<number>
Returns
the height of the active chain
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.
getMerklePath(txid: string, useNext?: boolean): Promise<GetMerklePathResult>
See also: GetMerklePathResult
Argument Details
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.
getRawTx(txid: string, useNext?: boolean): Promise<GetRawTxResult>
See also: GetRawTxResult
Argument Details
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’.
getStatusForTxids(txids: string[], useNext?: boolean): Promise<GetStatusForTxidsResult>
See also: GetStatusForTxidsResult
Attempts to determine the UTXO status of a transaction output.
Cycles through configured transaction processing services attempting to get a valid response.
getUtxoStatus(output: string, outputFormat?: GetUtxoStatusOutputFormat, outpoint?: string, useNext?: boolean): Promise<GetUtxoStatusResult>
See also: GetUtxoStatusOutputFormat, GetUtxoStatusResult
Argument Details
outputFormat
.output
is 32 hex bytes then ‘hashBE`, otherwise ‘script’.${txid}.${vout}
format.hashOutputScript(script: string): string
Returns
script hash in ‘hashLE’ format, which is the default.
Argument Details
getUtxoStatus
default outputFormat
hashToHeader(hash: string): Promise<BlockHeader>
See also: BlockHeader
Returns
a block header
Argument Details
nLockTimeIsFinal(txOrLockTime: string | number[] | BsvTransaction | number): Promise<boolean>
Returns
whether the locktime value allows the transaction to be mined at the current chain height
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface WalletServicesOptions {
chain: Chain;
taalApiKey?: string;
bitailsApiKey?: string;
whatsOnChainApiKey?: string;
bsvExchangeRate: BsvExchangeRate;
bsvUpdateMsecs: number;
fiatExchangeRates: FiatExchangeRates;
fiatUpdateMsecs: number;
disableMapiCallback?: boolean;
exchangeratesapiKey?: string;
chaintracksFiatExchangeRatesUrl?: string;
chaintracks?: ChaintracksServiceClient;
arcUrl: string;
arcConfig: ArcConfig;
}
See also: ArcConfig, BsvExchangeRate, Chain, FiatExchangeRates
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface WalletSettings {
trustSettings: TrustSettings;
theme?: WalletTheme;
currency?: string;
}
See also: TrustSettings, WalletTheme
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface WalletSettingsManagerConfig {
defaultSettings: WalletSettings;
}
See also: WalletSettings
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface WalletSigner {
isWalletSigner: true;
chain: Chain;
keyDeriver: KeyDeriverApi;
}
See also: Chain
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export interface WalletStorage {
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: ValidCreateActionArgs): Promise<StorageCreateActionResult>;
processAction(args: StorageProcessActionArgs): Promise<StorageProcessActionResults>;
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: ListActionsArgs): Promise<ListActionsResult>;
listCertificates(args: ValidListCertificatesArgs): Promise<ListCertificatesResult>;
listOutputs(args: ListOutputsArgs): Promise<ListOutputsResult>;
insertCertificate(certificate: TableCertificateX): Promise<number>;
relinquishCertificate(args: RelinquishCertificateArgs): Promise<number>;
relinquishOutput(args: RelinquishOutputArgs): Promise<number>;
}
See also: AuthId, FindCertificatesArgs, FindOutputBasketsArgs, FindOutputsArgs, FindProvenTxReqsArgs, StorageCreateActionResult, StorageProcessActionArgs, StorageProcessActionResults, TableCertificateX, TableOutput, TableOutputBasket, TableProvenTxReq, TableSettings, TableUser, ValidCreateActionArgs, ValidListCertificatesArgs, WalletServices, createAction, internalizeAction, listActions, listCertificates, listOutputs, processAction
isStorageProvider(): boolean
Returns
false
Links: API, Interfaces, Classes, Functions, Types, Variables
This is the WalletStorage
interface implemented with authentication checking and
is the actual minimal interface implemented by storage and remoted storage providers.
export interface WalletStorageProvider extends WalletStorageSync {
isStorageProvider(): boolean;
setServices(v: WalletServices): void;
}
See also: WalletServices, WalletStorageSync
isStorageProvider(): boolean
Returns
true if this object’s interface can be extended to the full StorageProvider
interface
Links: API, Interfaces, Classes, Functions, Types, Variables
export 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: ValidListActionsArgs): Promise<ListActionsResult>;
listCertificates(auth: AuthId, vargs: ValidListCertificatesArgs): Promise<ListCertificatesResult>;
listOutputs(auth: AuthId, vargs: ValidListOutputsArgs): Promise<ListOutputsResult>;
}
See also: AuthId, FindCertificatesArgs, FindOutputBasketsArgs, FindOutputsArgs, FindProvenTxReqsArgs, TableCertificateX, TableOutput, TableOutputBasket, TableProvenTxReq, TableSettings, ValidListActionsArgs, ValidListCertificatesArgs, ValidListOutputsArgs, WalletServices, listActions, listCertificates, listOutputs
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface WalletStorageSync extends WalletStorageWriter {
findOrInsertSyncStateAuth(auth: AuthId, storageIdentityKey: string, storageName: string): Promise<{
syncState: TableSyncState;
isNew: boolean;
}>;
setActive(auth: AuthId, newActiveStorageIdentityKey: string): Promise<number>;
getSyncChunk(args: RequestSyncChunkArgs): Promise<SyncChunk>;
processSyncChunk(args: RequestSyncChunkArgs, chunk: SyncChunk): Promise<ProcessSyncChunkResult>;
}
See also: AuthId, ProcessSyncChunkResult, RequestSyncChunkArgs, SyncChunk, TableSyncState, WalletStorageWriter, getSyncChunk
Updagte the activeStorage
property of the authenticated user by their userId
.
setActive(auth: AuthId, newActiveStorageIdentityKey: string): Promise<number>
See also: AuthId
Links: API, Interfaces, Classes, Functions, Types, Variables
This is the minimal interface required for a WalletStorageProvider to export data to another provider.
export interface WalletStorageSyncReader {
makeAvailable(): Promise<TableSettings>;
getSyncChunk(args: RequestSyncChunkArgs): Promise<SyncChunk>;
}
See also: RequestSyncChunkArgs, SyncChunk, TableSettings, getSyncChunk
Links: API, Interfaces, Classes, Functions, Types, Variables
export 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: ValidCreateActionArgs): Promise<StorageCreateActionResult>;
processAction(auth: AuthId, args: StorageProcessActionArgs): Promise<StorageProcessActionResults>;
internalizeAction(auth: AuthId, args: InternalizeActionArgs): Promise<InternalizeActionResult>;
insertCertificateAuth(auth: AuthId, certificate: TableCertificateX): Promise<number>;
relinquishCertificate(auth: AuthId, args: RelinquishCertificateArgs): Promise<number>;
relinquishOutput(auth: AuthId, args: RelinquishOutputArgs): Promise<number>;
}
See also: AuthId, StorageCreateActionResult, StorageProcessActionArgs, StorageProcessActionResults, TableCertificateX, TableSettings, TableUser, ValidCreateActionArgs, WalletStorageReader, createAction, internalizeAction, processAction
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface WalletTheme {
mode: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export interface XValidCreateActionOutput extends sdk.ValidCreateActionOutput {
vout: number;
providedBy: sdk.StorageProvidedBy;
purpose?: string;
derivationSuffix?: string;
keyOffset?: string;
}
See also: StorageProvidedBy, ValidCreateActionOutput
Links: API, Interfaces, Classes, Functions, Types, Variables
Links: API, Interfaces, Classes, Functions, Types, Variables
Represents an ARC transaction broadcaster.
export class ARC {
readonly URL: string;
readonly apiKey: string | undefined;
readonly deploymentId: string;
readonly callbackUrl: string | undefined;
readonly callbackToken: string | undefined;
readonly headers: Record<string, string> | undefined;
constructor(URL: string, config?: ArcConfig);
constructor(URL: string, apiKey?: string);
constructor(URL: string, config?: string | ArcConfig)
async postRawTx(rawTx: HexString, txids?: string[]): Promise<sdk.PostTxResultForTxid>
async postBeef(beef: Beef, txids: string[]): Promise<sdk.PostBeefResult>
async getTxData(txid: string): Promise<ArcMinerGetTxData>
}
See also: ArcConfig, ArcMinerGetTxData, PostBeefResult, PostTxResultForTxid
Constructs an instance of the ARC broadcaster.
constructor(URL: string, config?: ArcConfig)
See also: ArcConfig
Argument Details
Constructs an instance of the ARC broadcaster.
constructor(URL: string, apiKey?: string)
Argument Details
This seems to only work for recently submitted txids…but that’s all we need to complete postBeef!
async getTxData(txid: string): Promise<ArcMinerGetTxData>
See also: ArcMinerGetTxData
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.
async postBeef(beef: Beef, txids: string[]): Promise<sdk.PostBeefResult>
See also: PostBeefResult
The ARC ‘/v1/tx’ endpoint, as of 2025-02-17 supports all of the following hex string formats:
The ARC ‘/v1/tx’ endpoint, as of 2025-02-17 DOES NOT support the following hex string formats:
async postRawTx(rawTx: HexString, txids?: string[]): Promise<sdk.PostTxResultForTxid>
See also: PostTxResultForTxid
Links: API, Interfaces, Classes, Functions, Types, Variables
Abstract client-side interactor for an Auth Method
export abstract class AuthMethodInteractor {
public abstract methodType: string;
public abstract startAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<StartAuthResponse>;
public abstract completeAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<CompleteAuthResponse>;
}
See also: AuthPayload, CompleteAuthResponse, StartAuthResponse
Complete the flow (e.g. confirm OTP).
public abstract completeAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<CompleteAuthResponse>
See also: AuthPayload, CompleteAuthResponse
Start the flow (e.g. request an OTP or create a session).
public abstract startAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<StartAuthResponse>
See also: AuthPayload, StartAuthResponse
Links: API, Interfaces, Classes, Functions, Types, Variables
export class Bitails {
readonly chain: sdk.Chain;
readonly apiKey: string;
readonly URL: string;
readonly httpClient: HttpClient;
constructor(chain: sdk.Chain = "main", config: BitailsConfig = {})
getHttpHeaders(): Record<string, string>
async postBeef(beef: Beef, txids: string[]): Promise<sdk.PostBeefResult>
async postRaws(raws: HexString[], txids?: string[]): Promise<sdk.PostBeefResult>
async getMerklePath(txid: string, services: sdk.WalletServices): Promise<sdk.GetMerklePathResult>
}
See also: BitailsConfig, Chain, GetMerklePathResult, PostBeefResult, WalletServices
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.
async postBeef(beef: Beef, txids: string[]): Promise<sdk.PostBeefResult>
See also: PostBeefResult
async postRaws(raws: HexString[], txids?: string[]): Promise<sdk.PostBeefResult>
See also: PostBeefResult
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export class CWIStyleWalletManager implements WalletInterface {
authenticated: boolean;
authenticationMode: "presentation-key-and-password" | "presentation-key-and-recovery-key" | "recovery-key-and-password" = "presentation-key-and-password";
authenticationFlow: "new-user" | "existing-user" = "new-user";
constructor(adminOriginator: OriginatorDomainNameStringUnder250Bytes, walletBuilder: (profilePrimaryKey: number[], profilePrivilegedKeyManager: PrivilegedKeyManager, profileId: number[]) => Promise<WalletInterface>, interactor: UMPTokenInteractor = new OverlayUMPTokenInteractor(), recoveryKeySaver: (key: number[]) => Promise<true>, passwordRetriever: (reason: string, test: (passwordCandidate: string) => boolean) => Promise<string>, newWalletFunder?: (presentationKey: number[], wallet: WalletInterface, adminOriginator: OriginatorDomainNameStringUnder250Bytes) => Promise<void>, stateSnapshot?: number[])
async providePresentationKey(key: number[]): Promise<void>
async providePassword(password: string): Promise<void>
async provideRecoveryKey(recoveryKey: number[]): Promise<void>
saveSnapshot(): number[]
async loadSnapshot(snapshot: number[]): Promise<void>
destroy(): void
listProfiles(): Array<{
id: number[];
name: string;
createdAt: number | null;
active: boolean;
}>
async addProfile(name: string): Promise<number[]>
async deleteProfile(profileId: number[]): Promise<void>
async switchProfile(profileId: number[]): Promise<void>
async changePassword(newPassword: string): Promise<void>
async getRecoveryKey(): Promise<number[]>
async changeRecoveryKey(): Promise<void>
async changePresentationKey(newPresentationKey: number[]): Promise<void>
async getPublicKey(args: GetPublicKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetPublicKeyResult>
async revealCounterpartyKeyLinkage(args: RevealCounterpartyKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealCounterpartyKeyLinkageResult>
async revealSpecificKeyLinkage(args: RevealSpecificKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealSpecificKeyLinkageResult>
async encrypt(args: WalletEncryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletEncryptResult>
async decrypt(args: WalletDecryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletDecryptResult>
async createHmac(args: CreateHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateHmacResult>
async verifyHmac(args: VerifyHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifyHmacResult>
async createSignature(args: CreateSignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateSignatureResult>
async verifySignature(args: VerifySignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifySignatureResult>
async createAction(args: CreateActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateActionResult>
async signAction(args: SignActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<SignActionResult>
async abortAction(args: AbortActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AbortActionResult>
async listActions(args: ListActionsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListActionsResult>
async internalizeAction(args: InternalizeActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<InternalizeActionResult>
async listOutputs(args: ListOutputsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListOutputsResult>
async relinquishOutput(args: RelinquishOutputArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishOutputResult>
async acquireCertificate(args: AcquireCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AcquireCertificateResult>
async listCertificates(args: ListCertificatesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListCertificatesResult>
async proveCertificate(args: ProveCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ProveCertificateResult>
async relinquishCertificate(args: RelinquishCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishCertificateResult>
async discoverByIdentityKey(args: DiscoverByIdentityKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>
async discoverByAttributes(args: DiscoverByAttributesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>
async isAuthenticated(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>
async waitForAuthentication(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>
async getHeight(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeightResult>
async getHeaderForHeight(args: GetHeaderArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeaderResult>
async getNetwork(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetNetworkResult>
async getVersion(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetVersionResult>
}
See also: OverlayUMPTokenInteractor, PrivilegedKeyManager, UMPTokenInteractor, createAction, internalizeAction, listActions, listCertificates, listOutputs, proveCertificate, signAction
Constructs a new CWIStyleWalletManager.
constructor(adminOriginator: OriginatorDomainNameStringUnder250Bytes, walletBuilder: (profilePrimaryKey: number[], profilePrivilegedKeyManager: PrivilegedKeyManager, profileId: number[]) => Promise<WalletInterface>, interactor: UMPTokenInteractor = new OverlayUMPTokenInteractor(), recoveryKeySaver: (key: number[]) => Promise<true>, passwordRetriever: (reason: string, test: (passwordCandidate: string) => boolean) => Promise<string>, newWalletFunder?: (presentationKey: number[], wallet: WalletInterface, adminOriginator: OriginatorDomainNameStringUnder250Bytes) => Promise<void>, stateSnapshot?: number[])
See also: OverlayUMPTokenInteractor, PrivilegedKeyManager, UMPTokenInteractor
Argument Details
Whether the user is currently authenticated (i.e., root keys are available).
authenticated: boolean
Indicates new user or existing user flow.
authenticationFlow: "new-user" | "existing-user" = "new-user"
Current mode of authentication.
authenticationMode: "presentation-key-and-password" | "presentation-key-and-recovery-key" | "recovery-key-and-password" = "presentation-key-and-password"
Adds a new profile with the given name. Generates necessary pads and updates the UMP token. Does not switch to the new profile automatically.
async addProfile(name: string): Promise<number[]>
Returns
The ID of the newly created profile.
Argument Details
Changes the user’s password. Re-wraps keys and updates the UMP token.
async changePassword(newPassword: string): Promise<void>
Changes the user’s presentation key.
async changePresentationKey(newPresentationKey: number[]): Promise<void>
Changes the user’s recovery key. Prompts user to save the new key.
async changeRecoveryKey(): Promise<void>
Deletes a profile by its ID. Cannot delete the default profile. If the active profile is deleted, it switches back to the default profile.
async deleteProfile(profileId: number[]): Promise<void>
Argument Details
Destroys the wallet state, clearing keys, tokens, and profiles.
destroy(): void
Retrieves the current recovery key. Requires privileged access.
async getRecoveryKey(): Promise<number[]>
Lists all available profiles, including the default profile.
listProfiles(): Array<{
id: number[];
name: string;
createdAt: number | null;
active: boolean;
}>
Returns
Array of profile info objects, including an ‘active’ flag.
Loads a previously saved state snapshot. Restores root key, UMP token, profiles, and active profile. Handles Version 1 (legacy) and Version 2 formats.
async loadSnapshot(snapshot: number[]): Promise<void>
Argument Details
Provides the password.
async providePassword(password: string): Promise<void>
Provides the presentation key.
async providePresentationKey(key: number[]): Promise<void>
Provides the recovery key.
async 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]
saveSnapshot(): number[]
Returns
Encrypted snapshot bytes.
Switches the active profile. This re-derives keys and rebuilds the underlying wallet.
async switchProfile(profileId: number[]): Promise<void>
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export abstract class EntityBase<T> {
api: T;
constructor(api: T)
abstract get id(): number;
abstract get entityName(): string;
abstract get entityTable(): string;
abstract updateApi(): void;
abstract equals(ei: T, syncMap?: SyncMap): boolean;
abstract mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>;
abstract mergeExisting(storage: EntityStorage, since: Date | undefined, ei: T, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>;
toApi(): T
}
See also: EntityStorage, SyncMap, TrxToken
Tests for equality or ‘merge’ / ‘convergent’ equality if syncMap is provided.
‘convergent’ equality must satisfy (A sync B) equals (B sync A)
abstract equals(ei: T, syncMap?: SyncMap): boolean
See also: SyncMap
Perform a ‘merge’ / ‘convergent’ equality migration of state
from external ei
to this existing local EntityUser
abstract mergeExisting(storage: EntityStorage, since: Date | undefined, ei: T, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
See also: EntityStorage, SyncMap, TrxToken
Returns
true iff entity state changed and was updated to storage
Perform a ‘merge’ / ‘convergent’ equality migration of state to this new local entity which was constructed as a copy of the external object.
abstract mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
See also: EntityStorage, SyncMap, TrxToken
Argument Details
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.
toApi(): T
Returns
The underlying Api object with any entity decoded properties updated.
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
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityCertificate extends EntityBase<TableCertificate> {
constructor(api?: TableCertificate)
override updateApi(): void
get certificateId()
set certificateId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get userId()
set userId(v: number)
get type()
set type(v: string)
get subject()
set subject(v: string)
get verifier()
set verifier(v: string | undefined)
get serialNumber()
set serialNumber(v: string)
get certifier()
set certifier(v: string)
get revocationOutpoint()
set revocationOutpoint(v: string)
get signature()
set signature(v: string)
get isDeleted()
set isDeleted(v: boolean)
override get id(): number
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override equals(ei: TableCertificate, syncMap?: SyncMap): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableCertificate, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityCertificate;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableCertificate, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, SyncMap, TableCertificate, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityCertificateField extends EntityBase<TableCertificateField> {
constructor(api?: TableCertificateField)
override updateApi(): void
get userId()
set userId(v: number)
get certificateId()
set certificateId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get fieldName()
set fieldName(v: string)
get fieldValue()
set fieldValue(v: string)
get masterKey()
set masterKey(v: string)
override get id(): number
override get entityName(): string
override get entityTable(): string
override equals(ei: TableCertificateField, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableCertificateField, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityCertificateField;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableCertificateField, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, SyncMap, TableCertificateField, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityCommission extends EntityBase<TableCommission> {
constructor(api?: TableCommission)
override updateApi(): void
get commissionId()
set commissionId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get transactionId()
set transactionId(v: number)
get userId()
set userId(v: number)
get isRedeemed()
set isRedeemed(v: boolean)
get keyOffset()
set keyOffset(v: string)
get lockingScript()
set lockingScript(v: number[])
get satoshis()
set satoshis(v: number)
override get id(): number
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override equals(ei: TableCommission, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableCommission, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityCommission;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableCommission, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, SyncMap, TableCommission, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityOutput extends EntityBase<TableOutput> {
constructor(api?: TableOutput)
override updateApi(): void
get outputId()
set outputId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get userId()
set userId(v: number)
get transactionId()
set transactionId(v: number)
get basketId()
set basketId(v: number | undefined)
get spentBy()
set spentBy(v: number | undefined)
get vout()
set vout(v: number)
get satoshis()
set satoshis(v: number)
get outputDescription()
set outputDescription(v: string)
get spendable()
set spendable(v: boolean)
get change()
set change(v: boolean)
get txid()
set txid(v: string | undefined)
get type()
set type(v: string)
get providedBy()
set providedBy(v: sdk.StorageProvidedBy)
get purpose()
set purpose(v: string)
get spendingDescription()
set spendingDescription(v: string | undefined)
get derivationPrefix()
set derivationPrefix(v: string | undefined)
get derivationSuffix()
set derivationSuffix(v: string | undefined)
get senderIdentityKey()
set senderIdentityKey(v: string | undefined)
get customInstructions()
set customInstructions(v: string | undefined)
get lockingScript()
set lockingScript(v: number[] | undefined)
get scriptLength()
set scriptLength(v: number | undefined)
get scriptOffset()
set scriptOffset(v: number | undefined)
override get id(): number
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override equals(ei: TableOutput, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableOutput, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityOutput;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableOutput, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, StorageProvidedBy, SyncMap, TableOutput, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityOutputBasket extends EntityBase<TableOutputBasket> {
constructor(api?: TableOutputBasket)
get basketId()
set basketId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get userId()
set userId(v: number)
get name()
set name(v: string)
get numberOfDesiredUTXOs()
set numberOfDesiredUTXOs(v: number)
get minimumDesiredUTXOValue()
set minimumDesiredUTXOValue(v: number)
get isDeleted()
set isDeleted(v: boolean)
override get id()
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override updateApi(): void
override equals(ei: TableOutputBasket, syncMap?: SyncMap): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableOutputBasket, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityOutputBasket;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableOutputBasket, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, SyncMap, TableOutputBasket, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityOutputTag extends EntityBase<TableOutputTag> {
constructor(api?: TableOutputTag)
override updateApi(): void
get outputTagId()
set outputTagId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get tag()
set tag(v: string)
get userId()
set userId(v: number)
get isDeleted()
set isDeleted(v: boolean)
override get id(): number
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override equals(ei: TableOutputTag, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableOutputTag, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityOutputTag;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableOutputTag, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, SyncMap, TableOutputTag, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityOutputTagMap extends EntityBase<TableOutputTagMap> {
constructor(api?: TableOutputTagMap)
override updateApi(): void
get outputTagId()
set outputTagId(v: number)
get outputId()
set outputId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get isDeleted()
set isDeleted(v: boolean)
override get id(): number
override get entityName(): string
override get entityTable(): string
override equals(ei: TableOutputTagMap, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableOutputTagMap, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityOutputTagMap;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableOutputTagMap, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, SyncMap, TableOutputTagMap, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityProvenTx extends EntityBase<TableProvenTx> {
static async fromTxid(txid: string, services: sdk.WalletServices, rawTx?: number[]): Promise<ProvenTxFromTxidResult>
constructor(api?: TableProvenTx)
override updateApi(): void
getMerklePath(): MerklePath
_mp?: MerklePath;
get provenTxId()
set provenTxId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get txid()
set txid(v: string)
get height()
set height(v: number)
get index()
set index(v: number)
get merklePath()
set merklePath(v: number[])
get rawTx()
set rawTx(v: number[])
get blockHash()
set blockHash(v: string)
get merkleRoot()
set merkleRoot(v: string)
override get id()
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override equals(ei: TableProvenTx, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableProvenTx, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityProvenTx;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableProvenTx, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
static getProofAttemptsLimit = 8;
static getProofMinutes = 60;
static async fromReq(req: EntityProvenTxReq, gmpResult: sdk.GetMerklePathResult, countsAsAttempt: boolean): Promise<EntityProvenTx | undefined>
}
See also: EntityBase, EntityProvenTxReq, EntityStorage, GetMerklePathResult, ProvenTxFromTxidResult, SyncMap, TableProvenTx, TrxToken, WalletServices
How high attempts can go before status is forced to invalid
static getProofAttemptsLimit = 8
How many hours we have to try for a poof
static getProofMinutes = 60
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’
static async fromReq(req: EntityProvenTxReq, gmpResult: sdk.GetMerklePathResult, countsAsAttempt: boolean): Promise<EntityProvenTx | undefined>
See also: EntityProvenTx, EntityProvenTxReq, GetMerklePathResult
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.
static async fromTxid(txid: string, services: sdk.WalletServices, rawTx?: number[]): Promise<ProvenTxFromTxidResult>
See also: ProvenTxFromTxidResult, WalletServices
getMerklePath(): MerklePath
Returns
desirialized MerklePath
object, value is cached.
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityProvenTxReq extends EntityBase<TableProvenTxReq> {
static async fromStorageTxid(storage: EntityStorage, txid: string, trx?: sdk.TrxToken): Promise<EntityProvenTxReq | undefined>
static async fromStorageId(storage: EntityStorage, id: number, trx?: sdk.TrxToken): Promise<EntityProvenTxReq>
static fromTxid(txid: string, rawTx: number[], inputBEEF?: number[]): EntityProvenTxReq
history: ProvenTxReqHistory;
notify: ProvenTxReqNotify;
packApiHistory()
packApiNotify()
unpackApiHistory()
unpackApiNotify()
get apiHistory(): string
get apiNotify(): string
set apiHistory(v: string)
set apiNotify(v: string)
updateApi(): void
unpackApi(): void
async refreshFromStorage(storage: EntityStorage | WalletStorageManager, trx?: sdk.TrxToken): Promise<void>
constructor(api?: TableProvenTxReq)
historySince(since: Date): ProvenTxReqHistory
historyPretty(since?: Date, indent = 0): string
prettyNote(note: sdk.ReqHistoryNote): string
getHistorySummary(): ProvenTxReqHistorySummaryApi
parseHistoryNote(note: sdk.ReqHistoryNote, summary?: ProvenTxReqHistorySummaryApi): string
addNotifyTransactionId(id: number)
addHistoryNote(note: sdk.ReqHistoryNote, noDupes?: boolean)
async updateStorage(storage: EntityStorage, trx?: sdk.TrxToken)
async updateStorageDynamicProperties(storage: WalletStorageManager | StorageProvider, trx?: sdk.TrxToken)
async insertOrMerge(storage: EntityStorage, trx?: sdk.TrxToken): Promise<EntityProvenTxReq>
get status()
set status(v: sdk.ProvenTxReqStatus)
get provenTxReqId()
set provenTxReqId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get txid()
set txid(v: string)
get inputBEEF()
set inputBEEF(v: number[] | undefined)
get rawTx()
set rawTx(v: number[])
get attempts()
set attempts(v: number)
get provenTxId()
set provenTxId(v: number | undefined)
get notified()
set notified(v: boolean)
get batch()
set batch(v: string | undefined)
override get id()
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override equals(ei: TableProvenTxReq, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableProvenTxReq, syncMap: SyncMap, trx?: sdk.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: sdk.ProvenTxReqStatus): boolean
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableProvenTxReq, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, ProvenTxReqHistory, ProvenTxReqHistorySummaryApi, ProvenTxReqNotify, ProvenTxReqStatus, ReqHistoryNote, StorageProvider, SyncMap, TableProvenTxReq, TrxToken, WalletStorageManager
Adds a note to history. Notes with identical property values to an existing note are ignored.
addHistoryNote(note: sdk.ReqHistoryNote, noDupes?: boolean)
See also: ReqHistoryNote
Argument Details
what
value is retained.‘convergent’ equality must satisfy (A sync B) equals (B sync A)
override equals(ei: TableProvenTxReq, syncMap?: SyncMap | undefined): boolean
See also: SyncMap, TableProvenTxReq
Returns history to only what followed since date.
historySince(since: Date): ProvenTxReqHistory
See also: ProvenTxReqHistory
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:
notifying
, after merging the remote attempts and history.completed
.completed
wins.On terminal failure: doubleSpend
trumps invalid
as it contains more data.
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableProvenTxReq, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
See also: EntityStorage, SyncMap, TableProvenTxReq, TrxToken
Updates database record with current state of this EntityUser
async updateStorage(storage: EntityStorage, trx?: sdk.TrxToken)
See also: EntityStorage, TrxToken
Update storage with changes to non-static properties: updated_at provenTxId status history notify notified attempts batch
async updateStorageDynamicProperties(storage: WalletStorageManager | StorageProvider, trx?: sdk.TrxToken)
See also: StorageProvider, TrxToken, WalletStorageManager
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntitySyncState extends EntityBase<TableSyncState> {
constructor(api?: TableSyncState)
validateSyncMap(sm: SyncMap)
static async fromStorage(storage: sdk.WalletStorageSync, userIdentityKey: string, remoteSettings: TableSettings): Promise<EntitySyncState>
async updateStorage(storage: EntityStorage, notSyncMap?: boolean, trx?: sdk.TrxToken)
override updateApi(notSyncMap?: boolean): void
set created_at(v: Date)
get created_at()
set updated_at(v: Date)
get updated_at()
set userId(v: number)
get userId()
set storageIdentityKey(v: string)
get storageIdentityKey()
set storageName(v: string)
get storageName()
set init(v: boolean)
get init()
set refNum(v: string)
get refNum()
set status(v: sdk.SyncStatus)
get status(): sdk.SyncStatus
set when(v: Date | undefined)
get when()
set satoshis(v: number | undefined)
get satoshis()
get apiErrorLocal()
get apiErrorOther()
get apiSyncMap()
override get id(): number
set id(id: number)
override get entityName(): string
override get entityTable(): string
static mergeIdMap(fromMap: Record<number, number>, toMap: Record<number, number>)
mergeSyncMap(iSyncMap: SyncMap)
errorLocal: SyncError | undefined;
errorOther: SyncError | undefined;
syncMap: SyncMap;
override equals(ei: TableSyncState, syncMap?: SyncMap | undefined): boolean
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableSyncState, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
makeRequestSyncChunkArgs(forIdentityKey: string, forStorageIdentityKey: string, maxRoughSize?: number, maxItems?: number): sdk.RequestSyncChunkArgs
static syncChunkSummary(c: sdk.SyncChunk): string {
let log = "";
log += `SYNC CHUNK SUMMARY
from storage: ${c.fromStorageIdentityKey}
to storage: ${c.toStorageIdentityKey}
for user: ${c.userIdentityKey}
`;
if (c.user)
log += ` USER activeStorage ${c.user.activeStorage}\n`;
if (!!c.provenTxs) {
log += ` PROVEN_TXS\n`;
for (const r of c.provenTxs) {
log += ` ${r.provenTxId} ${r.txid}\n`;
}
}
if (!!c.provenTxReqs) {
log += ` PROVEN_TX_REQS\n`;
for (const r of c.provenTxReqs) {
log += ` ${r.provenTxReqId} ${r.txid} ${r.status} ${r.provenTxId || ""}\n`;
}
}
if (!!c.transactions) {
log += ` TRANSACTIONS\n`;
for (const r of c.transactions) {
log += ` ${r.transactionId} ${r.txid} ${r.status} ${r.provenTxId || ""} sats:${r.satoshis}\n`;
}
}
if (!!c.outputs) {
log += ` OUTPUTS\n`;
for (const r of c.outputs) {
log += ` ${r.outputId} ${r.txid}.${r.vout} ${r.transactionId} ${r.spendable ? "spendable" : ""} sats:${r.satoshis}\n`;
}
}
return log;
}
async processSyncChunk(writer: EntityStorage, args: sdk.RequestSyncChunkArgs, chunk: sdk.SyncChunk): Promise<{
done: boolean;
maxUpdated_at: Date | undefined;
updates: number;
inserts: number;
}>
}
See also: EntityBase, EntityStorage, RequestSyncChunkArgs, SyncChunk, SyncError, SyncMap, SyncStatus, TableSettings, TableSyncState, TrxToken, WalletStorageSync
Merge additions to the syncMap
mergeSyncMap(iSyncMap: SyncMap)
See also: SyncMap
Handles both insert and update based on id value: zero indicates insert.
async updateStorage(storage: EntityStorage, notSyncMap?: boolean, trx?: sdk.TrxToken)
See also: EntityStorage, TrxToken
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityTransaction extends EntityBase<TableTransaction> {
getBsvTx(): BsvTransaction | undefined
getBsvTxIns(): TransactionInput[]
async getInputs(storage: EntityStorage, trx?: sdk.TrxToken): Promise<TableOutput[]>
constructor(api?: TableTransaction)
override updateApi(): void
get transactionId()
set transactionId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get version()
set version(v: number | undefined)
get lockTime()
set lockTime(v: number | undefined)
get isOutgoing()
set isOutgoing(v: boolean)
get status()
set status(v: sdk.TransactionStatus)
get userId()
set userId(v: number)
get provenTxId()
set provenTxId(v: number | undefined)
get satoshis()
set satoshis(v: number)
get txid()
set txid(v: string | undefined)
get reference()
set reference(v: string)
get inputBEEF()
set inputBEEF(v: number[] | undefined)
get description()
set description(v: string)
get rawTx()
set rawTx(v: number[] | undefined)
override get id(): number
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override equals(ei: TableTransaction, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableTransaction, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityTransaction;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableTransaction, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
async getProvenTx(storage: EntityStorage, trx?: sdk.TrxToken): Promise<EntityProvenTx | undefined>
}
See also: EntityBase, EntityProvenTx, EntityStorage, SyncMap, TableOutput, TableTransaction, TransactionStatus, TrxToken
getBsvTxIns(): TransactionInput[]
Returns
array of
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.
async getInputs(storage: EntityStorage, trx?: sdk.TrxToken): Promise<TableOutput[]>
See also: EntityStorage, TableOutput, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityTxLabel extends EntityBase<TableTxLabel> {
constructor(api?: TableTxLabel)
override updateApi(): void
get txLabelId()
set txLabelId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get label()
set label(v: string)
get userId()
set userId(v: number)
get isDeleted()
set isDeleted(v: boolean)
override get id(): number
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override equals(ei: TableTxLabel, syncMap?: SyncMap): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableTxLabel, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityTxLabel;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableTxLabel, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, SyncMap, TableTxLabel, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityTxLabelMap extends EntityBase<TableTxLabelMap> {
constructor(api?: TableTxLabelMap)
override updateApi(): void
get txLabelId()
set txLabelId(v: number)
get transactionId()
set transactionId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get isDeleted()
set isDeleted(v: boolean)
override get id(): number
override get entityName(): string
override get entityTable(): string
override equals(ei: TableTxLabelMap, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableTxLabelMap, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityTxLabelMap;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableTxLabelMap, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, SyncMap, TableTxLabelMap, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class EntityUser extends EntityBase<TableUser> {
constructor(api?: TableUser)
override updateApi(): void
get userId()
set userId(v: number)
get created_at()
set created_at(v: Date)
get updated_at()
set updated_at(v: Date)
get identityKey()
set identityKey(v: string)
get activeStorage()
set activeStorage(v: string)
override get id(): number
override set id(v: number)
override get entityName(): string
override get entityTable(): string
override equals(ei: TableUser, syncMap?: SyncMap | undefined): boolean
static async mergeFind(storage: EntityStorage, userId: number, ei: TableUser, trx?: sdk.TrxToken): Promise<{
found: boolean;
eo: EntityUser;
eiId: number;
}>
override async mergeNew(storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<void>
override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableUser, syncMap?: SyncMap, trx?: sdk.TrxToken): Promise<boolean>
}
See also: EntityBase, EntityStorage, SyncMap, TableUser, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export class MergeEntity<API extends sdk.EntityTimeStamp, DE extends EntityBase<API>> {
idMap: Record<number, number>;
constructor(public stateArray: API[] | undefined, public find: (storage: EntityStorage, userId: number, ei: API, syncMap: SyncMap, trx?: sdk.TrxToken) => Promise<{
found: boolean;
eo: DE;
eiId: number;
}>, public esm: EntitySyncMap)
updateSyncMap(map: Record<number, number>, inId: number, outId: number)
async merge(since: Date | undefined, storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
inserts: number;
updates: number;
}>
}
See also: EntityBase, EntityStorage, EntitySyncMap, EntityTimeStamp, SyncMap, TrxToken
async merge(since: Date | undefined, storage: EntityStorage, userId: number, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<{
inserts: number;
updates: number;
}>
See also: EntityStorage, SyncMap, TrxToken
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
Background task to make sure transactions are processed, transaction proofs are received and propagated, and potentially that reorgs update proofs that were already received.
export class Monitor {
static createDefaultWalletMonitorOptions(chain: sdk.Chain, storage: MonitorStorage, services?: Services): MonitorOptions
options: MonitorOptions;
services: Services;
chain: sdk.Chain;
storage: MonitorStorage;
chaintracks: ChaintracksServiceClient;
constructor(options: MonitorOptions)
oneSecond = 1000;
oneMinute = 60 * this.oneSecond;
oneHour = 60 * this.oneMinute;
oneDay = 24 * this.oneHour;
oneWeek = 7 * this.oneDay;
_tasks: WalletMonitorTask[] = [];
_otherTasks: WalletMonitorTask[] = [];
_tasksRunning = false;
defaultPurgeParams: TaskPurgeParams = {
purgeSpent: false,
purgeCompleted: false,
purgeFailed: true,
purgeSpentAge: 2 * this.oneWeek,
purgeCompletedAge: 2 * this.oneWeek,
purgeFailedAge: 5 * this.oneDay
};
addAllTasksToOther(): void
addDefaultTasks(): void
addMultiUserTasks(): void
addTask(task: WalletMonitorTask): void
removeTask(name: string): void
async setupChaintracksListeners(): Promise<void>
async runTask(name: string): Promise<string>
async runOnce(): Promise<void>
_runAsyncSetup: boolean = true;
async startTasks(): Promise<void>
async logEvent(event: string, details?: string): Promise<void>
stopTasks(): void
lastNewHeader: BlockHeader | undefined;
lastNewHeaderWhen: Date | undefined;
processNewBlockHeader(header: BlockHeader): void
processReorg(depth: number, oldTip: BlockHeader, newTip: BlockHeader): void
}
See also: BlockHeader, Chain, MonitorOptions, MonitorStorage, Services, TaskPurgeParams, WalletMonitorTask
_otherTasks can be run by runTask but not by scheduler.
_otherTasks: WalletMonitorTask[] = []
See also: WalletMonitorTask
_tasks are typically run by the scheduler but may also be run by runTask.
_tasks: WalletMonitorTask[] = []
See also: WalletMonitorTask
Default tasks with settings appropriate for a single user storage possibly with sync’ing enabled
addDefaultTasks(): void
Tasks appropriate for multi-user storage without sync’ing enabled.
addMultiUserTasks(): void
Process new chain header event received from Chaintracks
Kicks processing ‘unconfirmed’ and ‘unmined’ request processing.
processNewBlockHeader(header: BlockHeader): void
See also: BlockHeader
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): void
See also: BlockHeader
Links: API, Interfaces, Classes, Functions, Types, Variables
export class OverlayUMPTokenInteractor implements UMPTokenInteractor {
constructor(resolver: LookupResolver = new LookupResolver(), broadcaster: SHIPBroadcaster = new SHIPBroadcaster(["tm_users"]))
public async findByPresentationKeyHash(hash: number[]): Promise<UMPToken | undefined>
public async findByRecoveryKeyHash(hash: number[]): Promise<UMPToken | undefined>
public async buildAndSend(wallet: WalletInterface, adminOriginator: OriginatorDomainNameStringUnder250Bytes, token: UMPToken, oldTokenToConsume?: UMPToken): Promise<OutpointString>
}
See also: UMPToken, UMPTokenInteractor
Construct a new OverlayUMPTokenInteractor.
constructor(resolver: LookupResolver = new LookupResolver(), broadcaster: SHIPBroadcaster = new SHIPBroadcaster(["tm_users"]))
Argument Details
tm_users
overlay.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.
public async buildAndSend(wallet: WalletInterface, adminOriginator: OriginatorDomainNameStringUnder250Bytes, token: UMPToken, oldTokenToConsume?: UMPToken): Promise<OutpointString>
See also: UMPToken
Returns
The outpoint of the newly created UMP token (e.g. “abcd1234…ef.0”).
Argument Details
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.
public async findByPresentationKeyHash(hash: number[]): Promise<UMPToken | undefined>
See also: UMPToken
Returns
A UMPToken object (including currentOutpoint) if found, otherwise undefined.
Argument Details
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.
public async findByRecoveryKeyHash(hash: number[]): Promise<UMPToken | undefined>
See also: UMPToken
Returns
A UMPToken object (including currentOutpoint) if found, otherwise undefined.
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export class PersonaIDInteractor extends AuthMethodInteractor {
public methodType = "PersonaID";
public async startAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<StartAuthResponse>
public async completeAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<CompleteAuthResponse>
}
See also: AuthMethodInteractor, AuthPayload, CompleteAuthResponse, StartAuthResponse
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export class PrivilegedKeyManager implements ProtoWallet {
constructor(keyGetter: (reason: string) => Promise<PrivateKey>, retentionPeriod = 120000)
destroyKey(): void
async getPublicKey(args: GetPublicKeyArgs): Promise<{
publicKey: PubKeyHex;
}>
async revealCounterpartyKeyLinkage(args: RevealCounterpartyKeyLinkageArgs): Promise<RevealCounterpartyKeyLinkageResult>
async revealSpecificKeyLinkage(args: RevealSpecificKeyLinkageArgs): Promise<RevealSpecificKeyLinkageResult>
async encrypt(args: WalletEncryptArgs): Promise<WalletEncryptResult>
async decrypt(args: WalletDecryptArgs): Promise<WalletDecryptResult>
async createHmac(args: CreateHmacArgs): Promise<CreateHmacResult>
async verifyHmac(args: VerifyHmacArgs): Promise<VerifyHmacResult>
async createSignature(args: CreateSignatureArgs): Promise<CreateSignatureResult>
async verifySignature(args: VerifySignatureArgs): Promise<VerifySignatureResult>
}
constructor(keyGetter: (reason: string) => Promise<PrivateKey>, retentionPeriod = 120000)
Argument Details
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
Links: API, Interfaces, Classes, Functions, Types, Variables
Simple Authenticated BSV P2PKH Payment Protocol https://brc.dev/29
export class ScriptTemplateBRC29 implements ScriptTemplate {
p2pkh: P2PKH;
constructor(public params: ScriptTemplateParamsBRC29)
getKeyID()
getKeyDeriver(privKey: PrivateKey | HexString): KeyDeriverApi
lock(lockerPrivKey: string, unlockerPubKey: string): LockingScript
unlock(unlockerPrivKey: string, lockerPubKey: string, sourceSatoshis?: number, lockingScript?: Script): ScriptTemplateUnlock
unlockLength = 108;
}
See also: ScriptTemplateParamsBRC29, ScriptTemplateUnlock
P2PKH unlock estimateLength is a constant
unlockLength = 108
Links: API, Interfaces, Classes, Functions, Types, Variables
Represents a chain tracker based on What’s On Chain .
export default class SdkWhatsOnChain implements ChainTracker {
readonly network: string;
readonly apiKey: string;
protected readonly URL: string;
protected readonly httpClient: HttpClient;
constructor(network: "main" | "test" | "stn" = "main", config: WhatsOnChainConfig = {})
async isValidRootForHeight(root: string, height: number): Promise<boolean>
async currentHeight(): Promise<number>
protected getHttpHeaders(): Record<string, string>
}
Constructs an instance of the WhatsOnChain ChainTracker.
constructor(network: "main" | "test" | "stn" = "main", config: WhatsOnChainConfig = {})
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export class ServiceCollection<T> {
services: {
name: string;
service: T;
}[];
_index: number;
constructor(services?: {
name: string;
service: T;
}[])
add(s: {
name: string;
service: T;
}): ServiceCollection<T>
remove(name: string): void
get name()
get service()
get allServices()
get count()
get index()
reset()
next(): number
clone(): ServiceCollection<T>
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export class Services implements sdk.WalletServices {
static createDefaultOptions(chain: sdk.Chain): sdk.WalletServicesOptions
options: sdk.WalletServicesOptions;
whatsonchain: WhatsOnChain;
arc: ARC;
bitails: Bitails;
getMerklePathServices: ServiceCollection<sdk.GetMerklePathService>;
getRawTxServices: ServiceCollection<sdk.GetRawTxService>;
postBeefServices: ServiceCollection<sdk.PostBeefService>;
getUtxoStatusServices: ServiceCollection<sdk.GetUtxoStatusService>;
getStatusForTxidsServices: ServiceCollection<sdk.GetStatusForTxidsService>;
getScriptHashHistoryServices: ServiceCollection<sdk.GetScriptHashHistoryService>;
updateFiatExchangeRateServices: ServiceCollection<sdk.UpdateFiatExchangeRateService>;
chain: sdk.Chain;
constructor(optionsOrChain: sdk.Chain | sdk.WalletServicesOptions)
async getChainTracker(): Promise<ChainTracker>
async getBsvExchangeRate(): Promise<number>
async getFiatExchangeRate(currency: "USD" | "GBP" | "EUR", base?: "USD" | "GBP" | "EUR"): Promise<number>
get getProofsCount()
get getRawTxsCount()
get postBeefServicesCount()
get getUtxoStatsCount()
async getStatusForTxids(txids: string[], useNext?: boolean): Promise<sdk.GetStatusForTxidsResult>
hashOutputScript(script: string): string
async getUtxoStatus(output: string, outputFormat?: sdk.GetUtxoStatusOutputFormat, outpoint?: string, useNext?: boolean): Promise<sdk.GetUtxoStatusResult>
async getScriptHashHistory(hash: string, useNext?: boolean): Promise<sdk.GetScriptHashHistoryResult>
postBeefCount = 0;
async postBeef(beef: Beef, txids: string[]): Promise<sdk.PostBeefResult[]>
async getRawTx(txid: string, useNext?: boolean): Promise<sdk.GetRawTxResult>
async invokeChaintracksWithRetry<R>(method: () => Promise<R>): Promise<R>
async getHeaderForHeight(height: number): Promise<number[]>
async getHeight(): Promise<number>
async hashToHeader(hash: string): Promise<sdk.BlockHeader>
async getMerklePath(txid: string, useNext?: boolean): Promise<sdk.GetMerklePathResult>
targetCurrencies = ["USD", "GBP", "EUR"];
async updateFiatExchangeRates(rates?: sdk.FiatExchangeRates, updateMsecs?: number): Promise<sdk.FiatExchangeRates>
async nLockTimeIsFinal(tx: string | number[] | BsvTransaction | number): Promise<boolean>
}
See also: ARC, Bitails, BlockHeader, Chain, FiatExchangeRates, GetMerklePathResult, GetMerklePathService, GetRawTxResult, GetRawTxService, GetScriptHashHistoryResult, GetScriptHashHistoryService, GetStatusForTxidsResult, GetStatusForTxidsService, GetUtxoStatusOutputFormat, GetUtxoStatusResult, GetUtxoStatusService, PostBeefResult, PostBeefService, ServiceCollection, UpdateFiatExchangeRateService, WalletServices, WalletServicesOptions, WhatsOnChain
hashOutputScript(script: string): string
Returns
script hash in ‘hashLE’ format, which is the default.
Argument Details
getUtxoStatus
default outputFormat
Links: API, Interfaces, Classes, Functions, Types, Variables
SimpleWalletManager is a slimmed-down wallet manager that only requires two things to authenticate:
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.
export class SimpleWalletManager implements WalletInterface {
authenticated: boolean;
constructor(adminOriginator: OriginatorDomainNameStringUnder250Bytes, walletBuilder: (primaryKey: number[], privilegedKeyManager: PrivilegedKeyManager) => Promise<WalletInterface>, stateSnapshot?: number[])
async providePrimaryKey(key: number[]): Promise<void>
async providePrivilegedKeyManager(manager: PrivilegedKeyManager): Promise<void>
destroy(): void
saveSnapshot(): number[]
async loadSnapshot(snapshot: number[]): Promise<void>
async isAuthenticated(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>
async waitForAuthentication(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>
async getPublicKey(args: GetPublicKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetPublicKeyResult>
async revealCounterpartyKeyLinkage(args: RevealCounterpartyKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealCounterpartyKeyLinkageResult>
async revealSpecificKeyLinkage(args: RevealSpecificKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RevealSpecificKeyLinkageResult>
async encrypt(args: WalletEncryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletEncryptResult>
async decrypt(args: WalletDecryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<WalletDecryptResult>
async createHmac(args: CreateHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateHmacResult>
async verifyHmac(args: VerifyHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifyHmacResult>
async createSignature(args: CreateSignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateSignatureResult>
async verifySignature(args: VerifySignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<VerifySignatureResult>
async createAction(args: CreateActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateActionResult>
async signAction(args: SignActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<SignActionResult>
async abortAction(args: AbortActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AbortActionResult>
async listActions(args: ListActionsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListActionsResult>
async internalizeAction(args: InternalizeActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<InternalizeActionResult>
async listOutputs(args: ListOutputsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListOutputsResult>
async relinquishOutput(args: RelinquishOutputArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishOutputResult>
async acquireCertificate(args: AcquireCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AcquireCertificateResult>
async listCertificates(args: ListCertificatesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListCertificatesResult>
async proveCertificate(args: ProveCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ProveCertificateResult>
async relinquishCertificate(args: RelinquishCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishCertificateResult>
async discoverByIdentityKey(args: DiscoverByIdentityKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>
async discoverByAttributes(args: DiscoverByAttributesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>
async getHeight(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeightResult>
async getHeaderForHeight(args: GetHeaderArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeaderResult>
async getNetwork(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetNetworkResult>
async getVersion(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetVersionResult>
}
See also: PrivilegedKeyManager, createAction, internalizeAction, listActions, listCertificates, listOutputs, proveCertificate, signAction
Constructs a new SimpleWalletManager
.
constructor(adminOriginator: OriginatorDomainNameStringUnder250Bytes, walletBuilder: (primaryKey: number[], privilegedKeyManager: PrivilegedKeyManager) => Promise<WalletInterface>, stateSnapshot?: number[])
See also: PrivilegedKeyManager
Argument Details
WalletInterface
.Whether the user is currently authenticated (meaning both the primary key and privileged key manager have been provided).
authenticated: boolean
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
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.
async isAuthenticated(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>
Argument Details
Throws
If not authenticated, or if the originator is the admin.
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).
async loadSnapshot(snapshot: number[]): Promise<void>
Argument Details
saveSnapshot
.Throws
If the snapshot format is invalid or decryption fails.
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.
async providePrimaryKey(key: number[]): Promise<void>
Argument Details
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.
async providePrivilegedKeyManager(manager: PrivilegedKeyManager): Promise<void>
See also: PrivilegedKeyManager
Argument Details
PrivilegedKeyManager
.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.
saveSnapshot(): number[]
Returns
A byte array representing the encrypted snapshot.
Throws
if no primary key is currently set.
Blocks until the user is authenticated (by providing primaryKey and privileged manager). If not authenticated yet, it waits until that occurs.
async waitForAuthentication(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>
Argument Details
Throws
If the originator is the admin.
Links: API, Interfaces, Classes, Functions, Types, Variables
StorageClient
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.
The AuthFetch
component is used to secure and authenticate the requests to the remote server.
AuthFetch
is initialized with a BRC-100 wallet which establishes the identity of
the party making requests of the remote service.
For details of the API implemented, follow the “See also” link for the WalletStorageProvider
interface.
export class StorageClient implements sdk.WalletStorageProvider {
public settings?: TableSettings;
constructor(wallet: WalletInterface, endpointUrl: string)
isStorageProvider(): boolean
isAvailable(): boolean
getSettings(): TableSettings
async makeAvailable(): Promise<TableSettings>
async destroy(): Promise<void>
async migrate(storageName: string, storageIdentityKey: string): Promise<string>
getServices(): sdk.WalletServices
setServices(v: sdk.WalletServices): void
async internalizeAction(auth: sdk.AuthId, args: InternalizeActionArgs): Promise<InternalizeActionResult>
async createAction(auth: sdk.AuthId, args: sdk.ValidCreateActionArgs): Promise<sdk.StorageCreateActionResult>
async processAction(auth: sdk.AuthId, args: sdk.StorageProcessActionArgs): Promise<sdk.StorageProcessActionResults>
async abortAction(auth: sdk.AuthId, args: AbortActionArgs): Promise<AbortActionResult>
async findOrInsertUser(identityKey): Promise<{
user: TableUser;
isNew: boolean;
}>
async findOrInsertSyncStateAuth(auth: sdk.AuthId, storageIdentityKey: string, storageName: string): Promise<{
syncState: TableSyncState;
isNew: boolean;
}>
async insertCertificateAuth(auth: sdk.AuthId, certificate: TableCertificateX): Promise<number>
async listActions(auth: sdk.AuthId, vargs: sdk.ValidListActionsArgs): Promise<ListActionsResult>
async listOutputs(auth: sdk.AuthId, vargs: sdk.ValidListOutputsArgs): Promise<ListOutputsResult>
async listCertificates(auth: sdk.AuthId, vargs: sdk.ValidListCertificatesArgs): Promise<ListCertificatesResult>
async findCertificatesAuth(auth: sdk.AuthId, args: sdk.FindCertificatesArgs): Promise<TableCertificateX[]>
async findOutputBasketsAuth(auth: sdk.AuthId, args: sdk.FindOutputBasketsArgs): Promise<TableOutputBasket[]>
async findOutputsAuth(auth: sdk.AuthId, args: sdk.FindOutputsArgs): Promise<TableOutput[]>
async findProvenTxReqs(args: sdk.FindProvenTxReqsArgs): Promise<TableProvenTxReq[]>
async relinquishCertificate(auth: sdk.AuthId, args: RelinquishCertificateArgs): Promise<number>
async relinquishOutput(auth: sdk.AuthId, args: RelinquishOutputArgs): Promise<number>
async processSyncChunk(args: sdk.RequestSyncChunkArgs, chunk: sdk.SyncChunk): Promise<sdk.ProcessSyncChunkResult>
async getSyncChunk(args: sdk.RequestSyncChunkArgs): Promise<sdk.SyncChunk>
async updateProvenTxReqWithNewProvenTx(args: sdk.UpdateProvenTxReqWithNewProvenTxArgs): Promise<sdk.UpdateProvenTxReqWithNewProvenTxResult>
async setActive(auth: sdk.AuthId, newActiveStorageIdentityKey: string): Promise<number>
validateDate(date: Date | string | number): Date
validateEntity<T extends sdk.EntityTimeStamp>(entity: T, dateFields?: string[]): T
validateEntities<T extends sdk.EntityTimeStamp>(entities: T[], dateFields?: string[]): T[]
}
See also: AuthId, EntityTimeStamp, FindCertificatesArgs, FindOutputBasketsArgs, FindOutputsArgs, FindProvenTxReqsArgs, ProcessSyncChunkResult, RequestSyncChunkArgs, StorageCreateActionResult, StorageProcessActionArgs, StorageProcessActionResults, SyncChunk, TableCertificateX, TableOutput, TableOutputBasket, TableProvenTxReq, TableSettings, TableSyncState, TableUser, UpdateProvenTxReqWithNewProvenTxArgs, UpdateProvenTxReqWithNewProvenTxResult, ValidCreateActionArgs, ValidListActionsArgs, ValidListCertificatesArgs, ValidListOutputsArgs, WalletServices, WalletStorageProvider, createAction, getSyncChunk, internalizeAction, listActions, listCertificates, listOutputs, processAction
Aborts an action by reference
string.
async abortAction(auth: sdk.AuthId, args: AbortActionArgs): Promise<AbortActionResult>
See also: AuthId
Returns
abortAction
result.
Argument Details
AuthFetch
identity securing the remote conneciton.abortAction
args.Storage level processing for wallet createAction
.
async createAction(auth: sdk.AuthId, args: sdk.ValidCreateActionArgs): Promise<sdk.StorageCreateActionResult>
See also: AuthId, StorageCreateActionResult, ValidCreateActionArgs
Returns
StorageCreateActionResults
supporting additional wallet processing to yield createAction
results.
Argument Details
AuthFetch
identity securing the remote conneciton.createAction
arguments.Called to cleanup resources when no further use of this object will occur.
async destroy(): Promise<void>
Find user certificates, optionally with fields.
This certificate retrieval method supports internal wallet operations. Field values are stored and retrieved encrypted.
async findCertificatesAuth(auth: sdk.AuthId, args: sdk.FindCertificatesArgs): Promise<TableCertificateX[]>
See also: AuthId, FindCertificatesArgs, TableCertificateX
Returns
array of certificates matching args.
Argument Details
AuthFetch
identity securing the remote conneciton.FindCertificatesArgs
determines which certificates to retrieve and whether to include fields.Used to both find and insert a TableSyncState
record for the user to track wallet data replication across storage providers.
async findOrInsertSyncStateAuth(auth: sdk.AuthId, storageIdentityKey: string, storageName: string): Promise<{
syncState: TableSyncState;
isNew: boolean;
}>
See also: AuthId, TableSyncState
Returns
TableSyncState
and whether a new record was created.
Argument Details
AuthFetch
identity securing the remote conneciton.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.
async findOrInsertUser(identityKey): Promise<{
user: TableUser;
isNew: boolean;
}>
See also: TableUser
Returns
TableUser
for the user and whether a new user was created.
Argument Details
Find output baskets.
This retrieval method supports internal wallet operations.
async findOutputBasketsAuth(auth: sdk.AuthId, args: sdk.FindOutputBasketsArgs): Promise<TableOutputBasket[]>
See also: AuthId, FindOutputBasketsArgs, TableOutputBasket
Returns
array of output baskets matching args.
Argument Details
AuthFetch
identity securing the remote conneciton.FindOutputBasketsArgs
determines which baskets to retrieve.Find outputs.
This retrieval method supports internal wallet operations.
async findOutputsAuth(auth: sdk.AuthId, args: sdk.FindOutputsArgs): Promise<TableOutput[]>
See also: AuthId, FindOutputsArgs, TableOutput
Returns
array of outputs matching args.
Argument Details
AuthFetch
identity securing the remote conneciton.FindOutputsArgs
determines which outputs to retrieve.Find requests for transaction proofs.
This retrieval method supports internal wallet operations.
async findProvenTxReqs(args: sdk.FindProvenTxReqsArgs): Promise<TableProvenTxReq[]>
See also: FindProvenTxReqsArgs, TableProvenTxReq
Returns
array of proof requests matching args.
Argument Details
AuthFetch
identity securing the remote conneciton.FindProvenTxReqsArgs
determines which proof requests to retrieve.Remote storage does not offer Services
to remote clients.
getServices(): sdk.WalletServices
See also: WalletServices
Throws
WERR_INVALID_OPERATION
getSettings(): TableSettings
See also: TableSettings
Returns
remote storage TableSettings
if they have been retreived by makeAvailable
.
Throws
WERR_INVALID_OPERATION if makeAvailable
has not yet been called.
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.
async getSyncChunk(args: sdk.RequestSyncChunkArgs): Promise<sdk.SyncChunk>
See also: RequestSyncChunkArgs, SyncChunk
Returns
the next “chunk” of replication data
Argument Details
Inserts a new certificate with fields and keyring into remote storage.
async insertCertificateAuth(auth: sdk.AuthId, certificate: TableCertificateX): Promise<number>
See also: AuthId, TableCertificateX
Returns
record Id of the inserted TableCertificate
record.
Argument Details
AuthFetch
identity securing the remote conneciton.Storage level processing for wallet internalizeAction
.
Updates internalized outputs in remote storage.
Triggers proof validation of containing transaction.
async internalizeAction(auth: sdk.AuthId, args: InternalizeActionArgs): Promise<InternalizeActionResult>
See also: AuthId
Returns
internalizeAction
results
Argument Details
AuthFetch
identity securing the remote conneciton.internalizeAction
arguments.isAvailable(): boolean
Returns
true once storage TableSettings
have been retreived from remote storage.
The StorageClient
implements the WalletStorageProvider
interface.
It does not implement the lower level StorageProvider
interface.
isStorageProvider(): boolean
Returns
false
Storage level processing for wallet listActions
.
async listActions(auth: sdk.AuthId, vargs: sdk.ValidListActionsArgs): Promise<ListActionsResult>
See also: AuthId, ValidListActionsArgs
Returns
listActions
results.
Argument Details
AuthFetch
identity securing the remote conneciton.listActions
arguments.Storage level processing for wallet listCertificates
.
async listCertificates(auth: sdk.AuthId, vargs: sdk.ValidListCertificatesArgs): Promise<ListCertificatesResult>
See also: AuthId, ValidListCertificatesArgs
Returns
listCertificates
results.
Argument Details
AuthFetch
identity securing the remote conneciton.listCertificates
arguments.Storage level processing for wallet listOutputs
.
async listOutputs(auth: sdk.AuthId, vargs: sdk.ValidListOutputsArgs): Promise<ListOutputsResult>
See also: AuthId, ValidListOutputsArgs
Returns
listOutputs
results.
Argument Details
AuthFetch
identity securing the remote conneciton.listOutputs
arguments.Must be called prior to making use of storage.
Retreives TableSettings
from remote storage provider.
async makeAvailable(): Promise<TableSettings>
See also: TableSettings
Returns
remote storage TableSettings
Requests schema migration to latest. Typically remote storage will ignore this request.
async migrate(storageName: string, storageIdentityKey: string): Promise<string>
Returns
current schema migration identifier
Argument Details
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
.
async processAction(auth: sdk.AuthId, args: sdk.StorageProcessActionArgs): Promise<sdk.StorageProcessActionResults>
See also: AuthId, StorageProcessActionArgs, StorageProcessActionResults
Returns
StorageProcessActionResults
supporting final wallet processing to yield createAction
or signAction
results.
Argument Details
AuthFetch
identity securing the remote conneciton.StorageProcessActionArgs
convey completed signed transaction to storage.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.
async processSyncChunk(args: sdk.RequestSyncChunkArgs, chunk: sdk.SyncChunk): Promise<sdk.ProcessSyncChunkResult>
See also: ProcessSyncChunkResult, RequestSyncChunkArgs, SyncChunk
Returns
whether processing is done, counts of inserts and udpates, and related progress tracking properties.
Argument Details
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.
async relinquishCertificate(auth: sdk.AuthId, args: RelinquishCertificateArgs): Promise<number>
See also: AuthId
Argument Details
AuthFetch
identity securing the remote conneciton.relinquishCertificate
args.Relinquish an output.
Relinquishing an output removes the output from whatever basket was tracking it.
async relinquishOutput(auth: sdk.AuthId, args: RelinquishOutputArgs): Promise<number>
See also: AuthId
Argument Details
AuthFetch
identity securing the remote conneciton.relinquishOutput
args.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.
async setActive(auth: sdk.AuthId, newActiveStorageIdentityKey: string): Promise<number>
See also: AuthId
Argument Details
AuthFetch
identity securing the remote conneciton.Ignored. Remote storage cannot share Services
with remote clients.
setServices(v: sdk.WalletServices): void
See also: WalletServices
Handles the data received when a new transaction proof is found in response to an outstanding request for proof data:
TableProvenTx
record.async updateProvenTxReqWithNewProvenTx(args: sdk.UpdateProvenTxReqWithNewProvenTxArgs): Promise<sdk.UpdateProvenTxReqWithNewProvenTxResult>
See also: UpdateProvenTxReqWithNewProvenTxArgs, UpdateProvenTxReqWithNewProvenTxResult
Returns
results of updates
Argument Details
Helper to force uniform behavior across database engines. Use to process all arrays of records with time stamps retreived from database.
validateEntities<T extends sdk.EntityTimeStamp>(entities: T[], dateFields?: string[]): T[]
See also: EntityTimeStamp
Returns
input entities
array with contained values validated.
Helper to force uniform behavior across database engines. Use to process all individual records with time stamps retreived from database.
validateEntity<T extends sdk.EntityTimeStamp>(entity: T, dateFields?: string[]): T
See also: EntityTimeStamp
Links: API, Interfaces, Classes, Functions, Types, Variables
export abstract class StorageProvider extends StorageReaderWriter implements sdk.WalletStorageProvider {
isDirty = false;
_services?: sdk.WalletServices;
feeModel: sdk.StorageFeeModel;
commissionSatoshis: number;
commissionPubKeyHex?: PubKeyHex;
maxRecursionDepth?: number;
static defaultOptions()
static createStorageBaseOptions(chain: sdk.Chain): StorageProviderOptions
constructor(options: StorageProviderOptions)
abstract reviewStatus(args: {
agedLimit: Date;
trx?: sdk.TrxToken;
}): Promise<{
log: string;
}>;
abstract purgeData(params: sdk.PurgeParams, trx?: sdk.TrxToken): Promise<sdk.PurgeResults>;
abstract allocateChangeInput(userId: number, basketId: number, targetSatoshis: number, exactSatoshis: number | undefined, excludeSending: boolean, transactionId: number): Promise<TableOutput | undefined>;
abstract getProvenOrRawTx(txid: string, trx?: sdk.TrxToken): Promise<sdk.ProvenOrRawTx>;
abstract getRawTxOfKnownValidTransaction(txid?: string, offset?: number, length?: number, trx?: sdk.TrxToken): Promise<number[] | undefined>;
abstract getLabelsForTransactionId(transactionId?: number, trx?: sdk.TrxToken): Promise<TableTxLabel[]>;
abstract getTagsForOutputId(outputId: number, trx?: sdk.TrxToken): Promise<TableOutputTag[]>;
abstract listActions(auth: sdk.AuthId, args: sdk.ValidListActionsArgs): Promise<ListActionsResult>;
abstract listOutputs(auth: sdk.AuthId, args: sdk.ValidListOutputsArgs): Promise<ListOutputsResult>;
abstract countChangeInputs(userId: number, basketId: number, excludeSending: boolean): Promise<number>;
abstract findCertificatesAuth(auth: sdk.AuthId, args: sdk.FindCertificatesArgs): Promise<TableCertificateX[]>;
abstract findOutputBasketsAuth(auth: sdk.AuthId, args: sdk.FindOutputBasketsArgs): Promise<TableOutputBasket[]>;
abstract findOutputsAuth(auth: sdk.AuthId, args: sdk.FindOutputsArgs): Promise<TableOutput[]>;
abstract insertCertificateAuth(auth: sdk.AuthId, certificate: TableCertificateX): Promise<number>;
override isStorageProvider(): boolean
setServices(v: sdk.WalletServices)
getServices(): sdk.WalletServices
async abortAction(auth: sdk.AuthId, args: AbortActionArgs): Promise<AbortActionResult>
async internalizeAction(auth: sdk.AuthId, args: InternalizeActionArgs): Promise<InternalizeActionResult>
async getReqsAndBeefToShareWithWorld(txids: string[], knownTxids: string[], trx?: sdk.TrxToken): Promise<GetReqsAndBeefResult>
async mergeReqToBeefToShareExternally(req: TableProvenTxReq, mergeToBeef: Beef, knownTxids: string[], trx?: sdk.TrxToken): Promise<void>
async getProvenOrReq(txid: string, newReq?: TableProvenTxReq, trx?: sdk.TrxToken): Promise<sdk.StorageProvenOrReq>
async updateTransactionsStatus(transactionIds: number[], status: sdk.TransactionStatus, trx?: sdk.TrxToken): Promise<void>
async updateTransactionStatus(status: sdk.TransactionStatus, transactionId?: number, userId?: number, reference?: string, trx?: sdk.TrxToken): Promise<void>
async createAction(auth: sdk.AuthId, args: sdk.ValidCreateActionArgs): Promise<sdk.StorageCreateActionResult>
async processAction(auth: sdk.AuthId, args: sdk.StorageProcessActionArgs): Promise<sdk.StorageProcessActionResults>
async attemptToPostReqsToNetwork(reqs: EntityProvenTxReq[], trx?: sdk.TrxToken): Promise<PostReqsToNetworkResult>
async listCertificates(auth: sdk.AuthId, args: sdk.ValidListCertificatesArgs): Promise<ListCertificatesResult>
async verifyKnownValidTransaction(txid: string, trx?: sdk.TrxToken): Promise<boolean>
async getValidBeefForKnownTxid(txid: string, mergeToBeef?: Beef, trustSelf?: TrustSelf, knownTxids?: string[], trx?: sdk.TrxToken): Promise<Beef>
async getValidBeefForTxid(txid: string, mergeToBeef?: Beef, trustSelf?: TrustSelf, knownTxids?: string[], trx?: sdk.TrxToken): Promise<Beef | undefined>
async getBeefForTransaction(txid: string, options: sdk.StorageGetBeefOptions): Promise<Beef>
async findMonitorEventById(id: number, trx?: sdk.TrxToken): Promise<TableMonitorEvent | undefined>
async relinquishCertificate(auth: sdk.AuthId, args: RelinquishCertificateArgs): Promise<number>
async relinquishOutput(auth: sdk.AuthId, args: RelinquishOutputArgs): Promise<number>
async processSyncChunk(args: sdk.RequestSyncChunkArgs, chunk: sdk.SyncChunk): Promise<sdk.ProcessSyncChunkResult>
async updateProvenTxReqWithNewProvenTx(args: sdk.UpdateProvenTxReqWithNewProvenTxArgs): Promise<sdk.UpdateProvenTxReqWithNewProvenTxResult>
async confirmSpendableOutputs(): Promise<{
invalidSpendableOutputs: TableOutput[];
}>
async updateProvenTxReqDynamics(id: number, update: Partial<TableProvenTxReqDynamics>, trx?: sdk.TrxToken): Promise<number>
}
See also: AuthId, Chain, EntityProvenTxReq, FindCertificatesArgs, FindOutputBasketsArgs, FindOutputsArgs, GetReqsAndBeefResult, PostReqsToNetworkResult, ProcessSyncChunkResult, ProvenOrRawTx, PurgeParams, PurgeResults, RequestSyncChunkArgs, StorageCreateActionResult, StorageFeeModel, StorageGetBeefOptions, StorageProcessActionArgs, StorageProcessActionResults, StorageProvenOrReq, StorageProviderOptions, StorageReaderWriter, SyncChunk, TableCertificateX, TableMonitorEvent, TableOutput, TableOutputBasket, TableOutputTag, TableProvenTxReq, TableProvenTxReqDynamics, TableTxLabel, TransactionStatus, TrxToken, UpdateProvenTxReqWithNewProvenTxArgs, UpdateProvenTxReqWithNewProvenTxResult, ValidCreateActionArgs, ValidListActionsArgs, ValidListCertificatesArgs, ValidListOutputsArgs, WalletServices, WalletStorageProvider, attemptToPostReqsToNetwork, createAction, getBeefForTransaction, internalizeAction, listActions, listCertificates, listOutputs, processAction, purgeData, reviewStatus
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.
async confirmSpendableOutputs(): Promise<{
invalidSpendableOutputs: TableOutput[];
}>
See also: TableOutput
Returns
object with invalidSpendableOutputs array. A good result is an empty array.
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.
async getProvenOrReq(txid: string, newReq?: TableProvenTxReq, trx?: sdk.TrxToken): Promise<sdk.StorageProvenOrReq>
See also: StorageProvenOrReq, TableProvenTxReq, TrxToken
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.
async getReqsAndBeefToShareWithWorld(txids: string[], knownTxids: string[], trx?: sdk.TrxToken): Promise<GetReqsAndBeefResult>
See also: GetReqsAndBeefResult, TrxToken
Handles storage changes when a valid MerklePath and mined block header are found for a ProvenTxReq txid.
Performs the following storage updates (typically):
ProvenTxReq
record for its rawTxargs
and rawTx, yielding a new provenTxIdAlterations of “typically” to handle:
async updateProvenTxReqWithNewProvenTx(args: sdk.UpdateProvenTxReqWithNewProvenTxArgs): Promise<sdk.UpdateProvenTxReqWithNewProvenTxResult>
See also: UpdateProvenTxReqWithNewProvenTxArgs, UpdateProvenTxReqWithNewProvenTxResult
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.
async updateTransactionStatus(status: sdk.TransactionStatus, transactionId?: number, userId?: number, reference?: string, trx?: sdk.TrxToken): Promise<void>
See also: TransactionStatus, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export abstract class StorageReader implements sdk.WalletStorageSyncReader {
chain: sdk.Chain;
_settings?: TableSettings;
whenLastAccess?: Date;
get dbtype(): DBType | undefined
constructor(options: StorageReaderOptions)
isAvailable(): boolean
async makeAvailable(): Promise<TableSettings>
getSettings(): TableSettings
isStorageProvider(): boolean
abstract destroy(): Promise<void>;
abstract transaction<T>(scope: (trx: sdk.TrxToken) => Promise<T>, trx?: sdk.TrxToken): Promise<T>;
abstract readSettings(trx?: sdk.TrxToken): Promise<TableSettings>;
abstract findCertificateFields(args: sdk.FindCertificateFieldsArgs): Promise<TableCertificateField[]>;
abstract findCertificates(args: sdk.FindCertificatesArgs): Promise<TableCertificateX[]>;
abstract findCommissions(args: sdk.FindCommissionsArgs): Promise<TableCommission[]>;
abstract findMonitorEvents(args: sdk.FindMonitorEventsArgs): Promise<TableMonitorEvent[]>;
abstract findOutputBaskets(args: sdk.FindOutputBasketsArgs): Promise<TableOutputBasket[]>;
abstract findOutputs(args: sdk.FindOutputsArgs): Promise<TableOutput[]>;
abstract findOutputTags(args: sdk.FindOutputTagsArgs): Promise<TableOutputTag[]>;
abstract findSyncStates(args: sdk.FindSyncStatesArgs): Promise<TableSyncState[]>;
abstract findTransactions(args: sdk.FindTransactionsArgs): Promise<TableTransaction[]>;
abstract findTxLabels(args: sdk.FindTxLabelsArgs): Promise<TableTxLabel[]>;
abstract findUsers(args: sdk.FindUsersArgs): Promise<TableUser[]>;
abstract countCertificateFields(args: sdk.FindCertificateFieldsArgs): Promise<number>;
abstract countCertificates(args: sdk.FindCertificatesArgs): Promise<number>;
abstract countCommissions(args: sdk.FindCommissionsArgs): Promise<number>;
abstract countMonitorEvents(args: sdk.FindMonitorEventsArgs): Promise<number>;
abstract countOutputBaskets(args: sdk.FindOutputBasketsArgs): Promise<number>;
abstract countOutputs(args: sdk.FindOutputsArgs): Promise<number>;
abstract countOutputTags(args: sdk.FindOutputTagsArgs): Promise<number>;
abstract countSyncStates(args: sdk.FindSyncStatesArgs): Promise<number>;
abstract countTransactions(args: sdk.FindTransactionsArgs): Promise<number>;
abstract countTxLabels(args: sdk.FindTxLabelsArgs): Promise<number>;
abstract countUsers(args: sdk.FindUsersArgs): Promise<number>;
abstract getProvenTxsForUser(args: sdk.FindForUserSincePagedArgs): Promise<TableProvenTx[]>;
abstract getProvenTxReqsForUser(args: sdk.FindForUserSincePagedArgs): Promise<TableProvenTxReq[]>;
abstract getTxLabelMapsForUser(args: sdk.FindForUserSincePagedArgs): Promise<TableTxLabelMap[]>;
abstract getOutputTagMapsForUser(args: sdk.FindForUserSincePagedArgs): Promise<TableOutputTagMap[]>;
async findUserByIdentityKey(key: string): Promise<TableUser | undefined>
async getSyncChunk(args: sdk.RequestSyncChunkArgs): Promise<sdk.SyncChunk>
validateEntityDate(date: Date | string | number): Date | string
validateOptionalEntityDate(date: Date | string | number | null | undefined, useNowAsDefault?: boolean): Date | string | undefined
validateDate(date: Date | string | number): Date
validateOptionalDate(date: Date | string | number | null | undefined): Date | undefined
validateDateForWhere(date: Date | string | number): Date | string | number
}
See also: Chain, DBType, FindCertificateFieldsArgs, FindCertificatesArgs, FindCommissionsArgs, FindForUserSincePagedArgs, FindMonitorEventsArgs, FindOutputBasketsArgs, FindOutputTagsArgs, FindOutputsArgs, FindSyncStatesArgs, FindTransactionsArgs, FindTxLabelsArgs, FindUsersArgs, RequestSyncChunkArgs, StorageReaderOptions, SyncChunk, TableCertificateField, TableCertificateX, TableCommission, TableMonitorEvent, TableOutput, TableOutputBasket, TableOutputTag, TableOutputTagMap, TableProvenTx, TableProvenTxReq, TableSettings, TableSyncState, TableTransaction, TableTxLabel, TableTxLabelMap, TableUser, TrxToken, WalletStorageSyncReader, getSyncChunk
Force dates to strings on SQLite and Date objects on MySQL
validateEntityDate(date: Date | string | number): Date | string
validateOptionalEntityDate(date: Date | string | number | null | undefined, useNowAsDefault?: boolean): Date | string | undefined
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export abstract class StorageReaderWriter extends StorageReader {
constructor(options: StorageReaderWriterOptions)
abstract dropAllData(): Promise<void>;
abstract migrate(storageName: string, storageIdentityKey: string): Promise<string>;
abstract findOutputTagMaps(args: sdk.FindOutputTagMapsArgs): Promise<TableOutputTagMap[]>;
abstract findProvenTxReqs(args: sdk.FindProvenTxReqsArgs): Promise<TableProvenTxReq[]>;
abstract findProvenTxs(args: sdk.FindProvenTxsArgs): Promise<TableProvenTx[]>;
abstract findTxLabelMaps(args: sdk.FindTxLabelMapsArgs): Promise<TableTxLabelMap[]>;
abstract countOutputTagMaps(args: sdk.FindOutputTagMapsArgs): Promise<number>;
abstract countProvenTxReqs(args: sdk.FindProvenTxReqsArgs): Promise<number>;
abstract countProvenTxs(args: sdk.FindProvenTxsArgs): Promise<number>;
abstract countTxLabelMaps(args: sdk.FindTxLabelMapsArgs): Promise<number>;
abstract insertCertificate(certificate: TableCertificate, trx?: sdk.TrxToken): Promise<number>;
abstract insertCertificateField(certificateField: TableCertificateField, trx?: sdk.TrxToken): Promise<void>;
abstract insertCommission(commission: TableCommission, trx?: sdk.TrxToken): Promise<number>;
abstract insertMonitorEvent(event: TableMonitorEvent, trx?: sdk.TrxToken): Promise<number>;
abstract insertOutput(output: TableOutput, trx?: sdk.TrxToken): Promise<number>;
abstract insertOutputBasket(basket: TableOutputBasket, trx?: sdk.TrxToken): Promise<number>;
abstract insertOutputTag(tag: TableOutputTag, trx?: sdk.TrxToken): Promise<number>;
abstract insertOutputTagMap(tagMap: TableOutputTagMap, trx?: sdk.TrxToken): Promise<void>;
abstract insertProvenTx(tx: TableProvenTx, trx?: sdk.TrxToken): Promise<number>;
abstract insertProvenTxReq(tx: TableProvenTxReq, trx?: sdk.TrxToken): Promise<number>;
abstract insertSyncState(syncState: TableSyncState, trx?: sdk.TrxToken): Promise<number>;
abstract insertTransaction(tx: TableTransaction, trx?: sdk.TrxToken): Promise<number>;
abstract insertTxLabel(label: TableTxLabel, trx?: sdk.TrxToken): Promise<number>;
abstract insertTxLabelMap(labelMap: TableTxLabelMap, trx?: sdk.TrxToken): Promise<void>;
abstract insertUser(user: TableUser, trx?: sdk.TrxToken): Promise<number>;
abstract updateCertificate(id: number, update: Partial<TableCertificate>, trx?: sdk.TrxToken): Promise<number>;
abstract updateCertificateField(certificateId: number, fieldName: string, update: Partial<TableCertificateField>, trx?: sdk.TrxToken): Promise<number>;
abstract updateCommission(id: number, update: Partial<TableCommission>, trx?: sdk.TrxToken): Promise<number>;
abstract updateMonitorEvent(id: number, update: Partial<TableMonitorEvent>, trx?: sdk.TrxToken): Promise<number>;
abstract updateOutput(id: number, update: Partial<TableOutput>, trx?: sdk.TrxToken): Promise<number>;
abstract updateOutputBasket(id: number, update: Partial<TableOutputBasket>, trx?: sdk.TrxToken): Promise<number>;
abstract updateOutputTag(id: number, update: Partial<TableOutputTag>, trx?: sdk.TrxToken): Promise<number>;
abstract updateOutputTagMap(outputId: number, tagId: number, update: Partial<TableOutputTagMap>, trx?: sdk.TrxToken): Promise<number>;
abstract updateProvenTx(id: number, update: Partial<TableProvenTx>, trx?: sdk.TrxToken): Promise<number>;
abstract updateProvenTxReq(id: number | number[], update: Partial<TableProvenTxReq>, trx?: sdk.TrxToken): Promise<number>;
abstract updateSyncState(id: number, update: Partial<TableSyncState>, trx?: sdk.TrxToken): Promise<number>;
abstract updateTransaction(id: number | number[], update: Partial<TableTransaction>, trx?: sdk.TrxToken): Promise<number>;
abstract updateTxLabel(id: number, update: Partial<TableTxLabel>, trx?: sdk.TrxToken): Promise<number>;
abstract updateTxLabelMap(transactionId: number, txLabelId: number, update: Partial<TableTxLabelMap>, trx?: sdk.TrxToken): Promise<number>;
abstract updateUser(id: number, update: Partial<TableUser>, trx?: sdk.TrxToken): Promise<number>;
async setActive(auth: sdk.AuthId, newActiveStorageIdentityKey: string): Promise<number>
async findCertificateById(id: number, trx?: sdk.TrxToken): Promise<TableCertificate | undefined>
async findCommissionById(id: number, trx?: sdk.TrxToken): Promise<TableCommission | undefined>
async findOutputById(id: number, trx?: sdk.TrxToken, noScript?: boolean): Promise<TableOutput | undefined>
async findOutputBasketById(id: number, trx?: sdk.TrxToken): Promise<TableOutputBasket | undefined>
async findProvenTxById(id: number, trx?: sdk.TrxToken | undefined): Promise<TableProvenTx | undefined>
async findProvenTxReqById(id: number, trx?: sdk.TrxToken | undefined): Promise<TableProvenTxReq | undefined>
async findSyncStateById(id: number, trx?: sdk.TrxToken): Promise<TableSyncState | undefined>
async findTransactionById(id: number, trx?: sdk.TrxToken, noRawTx?: boolean): Promise<TableTransaction | undefined>
async findTxLabelById(id: number, trx?: sdk.TrxToken): Promise<TableTxLabel | undefined>
async findOutputTagById(id: number, trx?: sdk.TrxToken): Promise<TableOutputTag | undefined>
async findUserById(id: number, trx?: sdk.TrxToken): Promise<TableUser | undefined>
async findOrInsertUser(identityKey: string, trx?: sdk.TrxToken): Promise<{
user: TableUser;
isNew: boolean;
}>
async findOrInsertTransaction(newTx: TableTransaction, trx?: sdk.TrxToken): Promise<{
tx: TableTransaction;
isNew: boolean;
}>
async findOrInsertOutputBasket(userId: number, name: string, trx?: sdk.TrxToken): Promise<TableOutputBasket>
async findOrInsertTxLabel(userId: number, label: string, trx?: sdk.TrxToken): Promise<TableTxLabel>
async findOrInsertTxLabelMap(transactionId: number, txLabelId: number, trx?: sdk.TrxToken): Promise<TableTxLabelMap>
async findOrInsertOutputTag(userId: number, tag: string, trx?: sdk.TrxToken): Promise<TableOutputTag>
async findOrInsertOutputTagMap(outputId: number, outputTagId: number, trx?: sdk.TrxToken): Promise<TableOutputTagMap>
async findOrInsertSyncStateAuth(auth: sdk.AuthId, storageIdentityKey: string, storageName: string): Promise<{
syncState: TableSyncState;
isNew: boolean;
}>
async findOrInsertProvenTxReq(newReq: TableProvenTxReq, trx?: sdk.TrxToken): Promise<{
req: TableProvenTxReq;
isNew: boolean;
}>
async findOrInsertProvenTx(newProven: TableProvenTx, trx?: sdk.TrxToken): Promise<{
proven: TableProvenTx;
isNew: boolean;
}>
abstract processSyncChunk(args: sdk.RequestSyncChunkArgs, chunk: sdk.SyncChunk): Promise<sdk.ProcessSyncChunkResult>;
async tagOutput(partial: Partial<TableOutput>, tag: string, trx?: sdk.TrxToken): Promise<void>
}
See also: AuthId, FindOutputTagMapsArgs, FindProvenTxReqsArgs, FindProvenTxsArgs, FindTxLabelMapsArgs, ProcessSyncChunkResult, RequestSyncChunkArgs, StorageReader, StorageReaderWriterOptions, SyncChunk, TableCertificate, TableCertificateField, TableCommission, TableMonitorEvent, TableOutput, TableOutputBasket, TableOutputTag, TableOutputTagMap, TableProvenTx, TableProvenTxReq, TableSyncState, TableTransaction, TableTxLabel, TableTxLabelMap, TableUser, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export class StorageSyncReader implements sdk.WalletStorageSyncReader {
constructor(public auth: sdk.AuthId, public storage: StorageReader)
async makeAvailable(): Promise<TableSettings>
destroy(): Promise<void>
async getSyncChunk(args: sdk.RequestSyncChunkArgs): Promise<sdk.SyncChunk>
}
See also: AuthId, RequestSyncChunkArgs, StorageReader, SyncChunk, TableSettings, WalletStorageSyncReader, getSyncChunk
Links: API, Interfaces, Classes, Functions, Types, Variables
TaskCheckForProofs
is a WalletMonitor task that retreives merkle proofs for
transactions.
It is normally triggered by the Chaintracks new block header event.
When a new block is found, cwi-external-services are used to obtain proofs for any transactions that are currently in the ‘unmined’ or ‘unknown’ state.
If a proof is obtained and validated, a new ProvenTx record is created and the original ProvenTxReq status is advanced to ‘notifying’.
export class TaskCheckForProofs extends WalletMonitorTask {
static taskName = "CheckForProofs";
static checkNow = false;
constructor(monitor: Monitor, public triggerMsecs = 0)
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
async runTask(): Promise<string>
}
See also: Monitor, WalletMonitorTask
An external service such as the chaintracks new block header listener can set this true to cause
static checkNow = false
Normally triggered by checkNow getting set by new block header found event from chaintracks
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
TaskCheckNoSends
is a WalletMonitor task that retreives merkle proofs for
‘nosend’ transactions that MAY have been shared externally.
Unlike intentionally processed transactions, ‘nosend’ transactions are fully valid transactions which have not been processed by the wallet.
By default, this task runs once a day to check if any ‘nosend’ transaction has managed to get mined by some external process.
If a proof is obtained and validated, a new ProvenTx record is created and the original ProvenTxReq status is advanced to ‘notifying’.
export class TaskCheckNoSends extends WalletMonitorTask {
static taskName = "CheckNoSends";
static checkNow = false;
constructor(monitor: Monitor, public triggerMsecs = monitor.oneDay * 1)
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
async runTask(): Promise<string>
}
See also: Monitor, WalletMonitorTask
An external service such as the chaintracks new block header listener can set this true to cause
static checkNow = false
Normally triggered by checkNow getting set by new block header found event from chaintracks
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export class TaskClock extends WalletMonitorTask {
static taskName = "Clock";
nextMinute: number;
constructor(monitor: Monitor, public triggerMsecs = 1 * monitor.oneSecond)
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
async runTask(): Promise<string>
getNextMinute(): number
}
See also: Monitor, WalletMonitorTask
Links: API, Interfaces, Classes, Functions, Types, Variables
Handles transactions which do not have terminal status and have not been updated for an extended time period.
Calls updateTransactionStatus
to set status
to failed
.
This returns inputs to spendable status and verifies that any
outputs are not spendable.
export class TaskFailAbandoned extends WalletMonitorTask {
static taskName = "FailAbandoned";
constructor(monitor: Monitor, public triggerMsecs = 1000 * 60 * 5)
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
async runTask(): Promise<string>
}
See also: Monitor, WalletMonitorTask
Links: API, Interfaces, Classes, Functions, Types, Variables
export class TaskNewHeader extends WalletMonitorTask {
static taskName = "NewHeader";
header?: BlockHeader;
constructor(monitor: Monitor, public triggerMsecs = 1 * monitor.oneMinute)
async getHeader(): Promise<BlockHeader>
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
async runTask(): Promise<string>
}
See also: BlockHeader, Monitor, WalletMonitorTask
Links: API, Interfaces, Classes, Functions, Types, Variables
export class TaskPurge extends WalletMonitorTask {
static taskName = "Purge";
static checkNow = false;
constructor(monitor: Monitor, public params: TaskPurgeParams, public triggerMsecs = 0)
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
async runTask(): Promise<string>
}
See also: Monitor, TaskPurgeParams, WalletMonitorTask
Set to true to trigger running this task
static checkNow = false
Links: API, Interfaces, Classes, Functions, Types, Variables
Notify Transaction records of changes in ProvenTxReq records they may have missed.
The notified
property flags reqs that do not need to be checked.
Looks for aged Transactions with provenTxId with status != ‘completed’, sets status to ‘completed’.
Looks for reqs with ‘invalid’ status that
export class TaskReviewStatus extends WalletMonitorTask {
static taskName = "ReviewStatus";
static checkNow = false;
constructor(monitor: Monitor, public triggerMsecs = 1000 * 60 * 15, public agedMsecs = 1000 * 60 * 5)
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
async runTask(): Promise<string>
}
See also: Monitor, WalletMonitorTask
Set to true to trigger running this task
static checkNow = false
Links: API, Interfaces, Classes, Functions, Types, Variables
export class TaskSendWaiting extends WalletMonitorTask {
static taskName = "SendWaiting";
lastSendingRunMsecsSinceEpoch: number | undefined;
includeSending: boolean = true;
constructor(monitor: Monitor, public triggerMsecs = monitor.oneSecond * 8, public agedMsecs = monitor.oneSecond * 7, public sendingMsecs = monitor.oneMinute * 5)
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
async runTask(): Promise<string>
async processUnsent(reqApis: TableProvenTxReq[], indent = 0): Promise<string>
}
See also: Monitor, TableProvenTxReq, WalletMonitorTask
Process an array of ‘unsent’ status table.ProvenTxReq
Send rawTx to transaction processor(s), requesting proof callbacks when possible.
Set status ‘invalid’ if req is invalid.
Set status to ‘callback’ on successful network submission with callback service.
Set status to ‘unmined’ on successful network submission without callback service.
Add mapi responses to database table if received.
Increments attempts if sending was attempted.
async processUnsent(reqApis: TableProvenTxReq[], indent = 0): Promise<string>
See also: TableProvenTxReq
Links: API, Interfaces, Classes, Functions, Types, Variables
export class TaskSyncWhenIdle extends WalletMonitorTask {
static taskName = "SyncWhenIdle";
constructor(monitor: Monitor, public triggerMsecs = 1000 * 60 * 1)
trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
async runTask(): Promise<string>
}
See also: Monitor, WalletMonitorTask
Links: API, Interfaces, Classes, Functions, Types, Variables
TwilioPhoneInteractor
A client-side class that knows how to call the WAB server for Twilio-based phone verification.
export class TwilioPhoneInteractor extends AuthMethodInteractor {
public methodType = "TwilioPhone";
public async startAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<StartAuthResponse>
public async completeAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<CompleteAuthResponse>
}
See also: AuthMethodInteractor, AuthPayload, CompleteAuthResponse, StartAuthResponse
Complete the Twilio phone verification on the server.
public async completeAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<CompleteAuthResponse>
See also: AuthPayload, CompleteAuthResponse
Returns
Argument Details
Start the Twilio phone verification on the server.
public async startAuth(serverUrl: string, presentationKey: string, payload: AuthPayload): Promise<StartAuthResponse>
See also: AuthPayload, StartAuthResponse
Returns
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export class WABClient {
constructor(private serverUrl: string)
public async getInfo()
public generateRandomPresentationKey(): string
public async startAuthMethod(authMethod: AuthMethodInteractor, presentationKey: string, payload: any)
public async completeAuthMethod(authMethod: AuthMethodInteractor, presentationKey: string, payload: any)
public async listLinkedMethods(presentationKey: string)
public async unlinkMethod(presentationKey: string, authMethodId: number)
public async requestFaucet(presentationKey: string)
public async deleteUser(presentationKey: string)
}
See also: AuthMethodInteractor
Complete an Auth Method flow
public async completeAuthMethod(authMethod: AuthMethodInteractor, presentationKey: string, payload: any)
See also: AuthMethodInteractor
Delete user
public async deleteUser(presentationKey: string)
Generate a random 256-bit presentation key as a hex string (client side).
public generateRandomPresentationKey(): string
Return the WAB server info
public async getInfo()
List user-linked methods
public async listLinkedMethods(presentationKey: string)
Request faucet
public async requestFaucet(presentationKey: string)
Start an Auth Method flow
public async startAuthMethod(authMethod: AuthMethodInteractor, presentationKey: string, payload: any)
See also: AuthMethodInteractor
Unlink a given Auth Method by ID
public async unlinkMethod(presentationKey: string, authMethodId: number)
Links: API, Interfaces, Classes, Functions, Types, Variables
The request is invalid.
export class WERR_BAD_REQUEST extends WalletError {
constructor(message?: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
Unable to broadcast transaction at this time.
export class WERR_BROADCAST_UNAVAILABLE extends WalletError {
constructor(message?: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export class WERR_INSUFFICIENT_FUNDS extends WalletError {
constructor(public totalSatoshisNeeded: number, public moreSatoshisNeeded: number)
}
See also: WalletError
constructor(public totalSatoshisNeeded: number, public moreSatoshisNeeded: number)
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
An internal error has occurred.
This is an example of an error with an optional custom message
.
export class WERR_INTERNAL extends WalletError {
constructor(message?: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
The ${parameter} parameter is invalid.
This is an example of an error object with a custom property parameter
and templated message
.
export class WERR_INVALID_OPERATION extends WalletError {
constructor(message?: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
The ${parameter} parameter is invalid.
This is an example of an error object with a custom property parameter
and templated message
.
export class WERR_INVALID_PARAMETER extends WalletError {
constructor(public parameter: string, mustBe?: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
export class WERR_INVALID_PUBLIC_KEY extends WalletError {
constructor(public key: string, network: WalletNetwork = "mainnet")
}
See also: WalletError
constructor(public key: string, network: WalletNetwork = "mainnet")
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
The required ${parameter} parameter is missing.
This is an example of an error object with a custom property parameter
export class WERR_MISSING_PARAMETER extends WalletError {
constructor(public parameter: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
Configured network chain is invalid or does not match across services.
export class WERR_NETWORK_CHAIN extends WalletError {
constructor(message?: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
WalletStorageManager is not accessing user’s active storage or there are conflicting active stores configured.
export class WERR_NOT_ACTIVE extends WalletError {
constructor(message?: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
Not implemented.
export class WERR_NOT_IMPLEMENTED extends WalletError {
constructor(message?: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
When a createAction
or signAction
is completed in undelayed mode (acceptDelayedBroadcast
: false),
any unsucccessful result will return the results by way of this exception to ensure attention is
paid to processing errors.
export class WERR_REVIEW_ACTIONS extends WalletError {
constructor(public reviewActionResults: ReviewActionResult[], public sendWithResults: SendWithResult[], public txid?: TXIDHexString, public tx?: AtomicBEEF, public noSendChange?: OutpointString[])
}
See also: ReviewActionResult, WalletError
All parameters correspond to their comparable createAction
or signSction
results
with the exception of reviewActionResults
;
which contains more details, particularly for double spend results.
constructor(public reviewActionResults: ReviewActionResult[], public sendWithResults: SendWithResult[], public txid?: TXIDHexString, public tx?: AtomicBEEF, public noSendChange?: OutpointString[])
See also: ReviewActionResult
Links: API, Interfaces, Classes, Functions, Types, Variables
Access is denied due to an authorization error.
export class WERR_UNAUTHORIZED extends WalletError {
constructor(message?: string)
}
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
export class Wallet implements WalletInterface, ProtoWallet {
chain: sdk.Chain;
keyDeriver: KeyDeriver;
storage: WalletStorageManager;
settingsManager: WalletSettingsManager;
lookupResolver: LookupResolver;
services?: sdk.WalletServices;
monitor?: Monitor;
identityKey: string;
beef: BeefParty;
includeAllSourceTransactions: boolean = true;
autoKnownTxids: boolean = false;
returnTxidOnly: boolean = false;
trustSelf?: TrustSelf;
userParty: string;
proto: ProtoWallet;
privilegedKeyManager?: sdk.PrivilegedKeyManager;
pendingSignActions: Record<string, PendingSignAction>;
randomVals?: number[] = undefined;
constructor(argsOrSigner: WalletArgs | WalletSigner, services?: sdk.WalletServices, monitor?: Monitor, privilegedKeyManager?: sdk.PrivilegedKeyManager)
async destroy(): Promise<void>
getClientChangeKeyPair(): sdk.KeyPair
async 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(): sdk.WalletServices
getKnownTxids(newKnownTxids?: string[]): string[]
getStorageIdentity(): sdk.StorageIdentity
async listActions(args: ListActionsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListActionsResult>
get storageParty(): string
async listOutputs(args: ListOutputsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListOutputsResult>
async listCertificates(args: ListCertificatesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListCertificatesResult>
async acquireCertificate(args: AcquireCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AcquireCertificateResult>
async relinquishCertificate(args: RelinquishCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishCertificateResult>
async proveCertificate(args: ProveCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ProveCertificateResult>
async discoverByIdentityKey(args: DiscoverByIdentityKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>
async discoverByAttributes(args: DiscoverByAttributesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<DiscoverCertificatesResult>
verifyReturnedTxidOnly(beef: Beef): Beef
verifyReturnedTxidOnlyAtomicBEEF(beef: AtomicBEEF): AtomicBEEF
verifyReturnedTxidOnlyBEEF(beef: BEEF): BEEF
async createAction(args: CreateActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<CreateActionResult>
async signAction(args: SignActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<SignActionResult>
async abortAction(args: AbortActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AbortActionResult>
async internalizeAction(args: InternalizeActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<InternalizeActionResult>
async relinquishOutput(args: RelinquishOutputArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<RelinquishOutputResult>
async isAuthenticated(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>
async waitForAuthentication(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<AuthenticatedResult>
async getHeight(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeightResult>
async getHeaderForHeight(args: GetHeaderArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetHeaderResult>
async getNetwork(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetNetworkResult>
async getVersion(args: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<GetVersionResult>
async sweepTo(toWallet: Wallet): Promise<void>
async balanceAndUtxos(basket: string = "default"): Promise<sdk.WalletBalance>
async balance(): Promise<number>
async reviewSpendableOutputs(all = false, release = false, optionalArgs?: Partial<ListOutputsArgs>): Promise<ListOutputsResult>
async setWalletChangeParams(count: number, satoshis: number): Promise<void>
async listNoSendActions(args: ListActionsArgs, abort = false): Promise<ListActionsResult>
async listFailedActions(args: ListActionsArgs, unfail = false): Promise<ListActionsResult>
}
See also: Chain, KeyPair, Monitor, PendingSignAction, PrivilegedKeyManager, StorageIdentity, WalletArgs, WalletBalance, WalletServices, WalletSettingsManager, WalletSigner, WalletStorageManager, createAction, getIdentityKey, internalizeAction, listActions, listCertificates, listOutputs, proveCertificate, signAction
If true, txids that are known to the wallet’s party beef do not need to be returned from storage.
autoKnownTxids: boolean = false
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 = true
For repeatability testing, set to an array of random numbers from [0..1).
randomVals?: number[] = undefined
If true, beefs returned to the user may contain txidOnly transactions.
returnTxidOnly: boolean = false
Uses listOutputs
special operation to compute the total value (of satoshis) for
all spendable outputs in the ‘default’ basket.
async balance(): Promise<number>
Returns
sum of output satoshis
Uses listOutputs
to iterate over chunks of up to 1000 outputs to
compute the sum of output satoshis.
async balanceAndUtxos(basket: string = "default"): Promise<sdk.WalletBalance>
See also: WalletBalance
Returns
total sum of output satoshis and utxo details (satoshis and outpoints)
Argument Details
getKnownTxids(newKnownTxids?: string[]): string[]
Returns
the full list of txids whose validity this wallet claims to know.
Argument Details
Uses listActions
special operation to return only actions with status ‘failed’.
async listFailedActions(args: ListActionsArgs, unfail = false): Promise<ListActionsResult>
Returns
start listActions
result restricted to ‘failed’ status actions.
Argument Details
Uses listActions
special operation to return only actions with status ‘nosend’.
async listNoSendActions(args: ListActionsArgs, abort = false): Promise<ListActionsResult>
Returns
start listActions
result restricted to ‘nosend’ (or ‘failed’ if aborted) actions.
Argument Details
abortAction
on each ‘nosend’ action.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.
async reviewSpendableOutputs(all = false, release = false, optionalArgs?: Partial<ListOutputsArgs>): Promise<ListOutputsResult>
Returns
outputs which are/where considered spendable but currently fail to verify as spendable.
Argument Details
Uses listOutputs
special operation to update the ‘default’ basket’s automatic
change generation parameters.
async setWalletChangeParams(count: number, satoshis: number): Promise<void>
Argument Details
Transfer all possible satoshis held by this wallet to toWallet
.
async sweepTo(toWallet: Wallet): Promise<void>
See also: Wallet
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
WalletAuthenticationManager
A wallet manager that integrates with a WABClient for user authentication flows (e.g. Twilio phone).
export class WalletAuthenticationManager extends CWIStyleWalletManager {
constructor(adminOriginator: string, walletBuilder: (primaryKey: number[], privilegedKeyManager: PrivilegedKeyManager) => Promise<WalletInterface>, interactor: UMPTokenInteractor = new OverlayUMPTokenInteractor(), recoveryKeySaver: (key: number[]) => Promise<true>, passwordRetriever: (reason: string, test: (passwordCandidate: string) => boolean) => Promise<string>, wabClient: WABClient, authMethod?: AuthMethodInteractor, stateSnapshot?: number[])
public setAuthMethod(method: AuthMethodInteractor)
public async startAuth(payload: any): Promise<void>
public async completeAuth(payload: any): Promise<void>
}
See also: AuthMethodInteractor, CWIStyleWalletManager, OverlayUMPTokenInteractor, PrivilegedKeyManager, UMPTokenInteractor, WABClient
Completes the WAB-based flow, retrieving the final presentationKey from WAB if successful.
public async completeAuth(payload: any): Promise<void>
Sets (or switches) the chosen AuthMethodInteractor at runtime, in case the user changes their mind or picks a new method in the UI.
public setAuthMethod(method: AuthMethodInteractor)
See also: AuthMethodInteractor
Initiate the WAB-based flow, e.g. sending an SMS code or starting an ID check, using the chosen AuthMethodInteractor.
public async startAuth(payload: any): Promise<void>
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export class WalletError extends Error implements WalletErrorObject {
isError: true = true;
constructor(name: string, message: string, stack?: string, public details?: Record<string, string>)
get code(): ErrorCodeString10To40Bytes
set code(v: ErrorCodeString10To40Bytes)
get description(): ErrorDescriptionString20To200Bytes
set description(v: ErrorDescriptionString20To200Bytes)
static fromUnknown(err: unknown): WalletError
asStatus(): {
status: string;
code: string;
description: string;
}
}
asStatus(): {
status: string;
code: string;
description: string;
}
Returns
standard HTTP error status object with status property set to ‘error’.
Recovers all public fields from WalletError derived error classes and relevant Error derived errors.
static fromUnknown(err: unknown): WalletError
See also: WalletError
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export abstract class WalletMonitorTask {
lastRunMsecsSinceEpoch = 0;
storage: MonitorStorage;
constructor(public monitor: Monitor, public name: string)
async asyncSetup(): Promise<void>
abstract trigger(nowMsecsSinceEpoch: number): {
run: boolean;
};
abstract runTask(): Promise<string>;
}
See also: Monitor, MonitorStorage
Set by monitor each time runTask completes
lastRunMsecsSinceEpoch = 0
Override to handle async task setup configuration.
Called before first call to trigger
async asyncSetup(): Promise<void>
Return true if runTask
needs to be called now.
abstract trigger(nowMsecsSinceEpoch: number): {
run: boolean;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export class WalletPermissionsManager implements WalletInterface {
constructor(underlyingWallet: WalletInterface, adminOriginator: string, config: PermissionsManagerConfig = {})
public bindCallback(eventName: keyof WalletPermissionsManagerCallbacks, handler: PermissionEventHandler): number
public unbindCallback(eventName: keyof WalletPermissionsManagerCallbacks, reference: number | Function): boolean
public async grantPermission(params: {
requestID: string;
expiry?: number;
ephemeral?: boolean;
amount?: number;
}): Promise<void>
public async denyPermission(requestID: string): Promise<void>
public async ensureProtocolPermission({ originator, privileged, protocolID, counterparty, reason, seekPermission = true, usageType }: {
originator: string;
privileged: boolean;
protocolID: WalletProtocol;
counterparty: string;
reason?: string;
seekPermission?: boolean;
usageType: "signing" | "encrypting" | "hmac" | "publicKey" | "identityKey" | "linkageRevelation" | "generic";
}): Promise<boolean>
public async ensureBasketAccess({ originator, basket, reason, seekPermission = true, usageType }: {
originator: string;
basket: string;
reason?: string;
seekPermission?: boolean;
usageType: "insertion" | "removal" | "listing";
}): Promise<boolean>
public async ensureCertificateAccess({ originator, privileged, verifier, certType, fields, reason, seekPermission = true, usageType }: {
originator: string;
privileged: boolean;
verifier: string;
certType: string;
fields: string[];
reason?: string;
seekPermission?: boolean;
usageType: "disclosure";
}): Promise<boolean>
public async ensureSpendingAuthorization({ originator, satoshis, lineItems, reason, seekPermission = true }: {
originator: string;
satoshis: number;
lineItems?: Array<{
type: "input" | "output" | "fee";
description: string;
satoshis: number;
}>;
reason?: string;
seekPermission?: boolean;
}): Promise<boolean>
public async ensureLabelAccess({ originator, label, reason, seekPermission = true, usageType }: {
originator: string;
label: string;
reason?: string;
seekPermission?: boolean;
usageType: "apply" | "list";
}): Promise<boolean>
public async querySpentSince(token: PermissionToken): Promise<number>
public async listProtocolPermissions({ originator }: {
originator?: string;
}): Promise<PermissionToken[]>
public async hasProtocolPermission(params: {
originator: string;
privileged: boolean;
protocolID: WalletProtocol;
counterparty: string;
}): Promise<boolean>
public async listBasketAccess(params: {
originator?: string;
}): Promise<PermissionToken[]>
public async hasBasketAccess(params: {
originator: string;
basket: string;
}): Promise<boolean>
public async listSpendingAuthorizations(params: {
originator?: string;
}): Promise<PermissionToken[]>
public async hasSpendingAuthorization(params: {
originator: string;
satoshis: number;
}): Promise<boolean>
public async listCertificateAccess(params: {
originator?: string;
}): Promise<PermissionToken[]>
public async hasCertificateAccess(params: {
originator: string;
privileged: boolean;
verifier: string;
certType: string;
fields: string[];
}): Promise<boolean>
public async revokePermission(oldToken: PermissionToken): Promise<void>
public async createAction(args: Parameters<WalletInterface["createAction"]>[0], originator?: string): ReturnType<WalletInterface["createAction"]>
public async signAction(...args: Parameters<WalletInterface["signAction"]>): ReturnType<WalletInterface["signAction"]>
public async abortAction(...args: Parameters<WalletInterface["abortAction"]>): ReturnType<WalletInterface["abortAction"]>
public async listActions(...args: Parameters<WalletInterface["listActions"]>): ReturnType<WalletInterface["listActions"]>
public async internalizeAction(...args: Parameters<WalletInterface["internalizeAction"]>): ReturnType<WalletInterface["internalizeAction"]>
public async listOutputs(...args: Parameters<WalletInterface["listOutputs"]>): ReturnType<WalletInterface["listOutputs"]>
public async relinquishOutput(...args: Parameters<WalletInterface["relinquishOutput"]>): ReturnType<WalletInterface["relinquishOutput"]>
public async getPublicKey(...args: Parameters<WalletInterface["getPublicKey"]>): ReturnType<WalletInterface["getPublicKey"]>
public async revealCounterpartyKeyLinkage(...args: Parameters<WalletInterface["revealCounterpartyKeyLinkage"]>): ReturnType<WalletInterface["revealCounterpartyKeyLinkage"]>
public async revealSpecificKeyLinkage(...args: Parameters<WalletInterface["revealSpecificKeyLinkage"]>): ReturnType<WalletInterface["revealSpecificKeyLinkage"]>
public async encrypt(...args: Parameters<WalletInterface["encrypt"]>): ReturnType<WalletInterface["encrypt"]>
public async decrypt(...args: Parameters<WalletInterface["decrypt"]>): ReturnType<WalletInterface["decrypt"]>
public async createHmac(...args: Parameters<WalletInterface["createHmac"]>): ReturnType<WalletInterface["createHmac"]>
public async verifyHmac(...args: Parameters<WalletInterface["verifyHmac"]>): ReturnType<WalletInterface["verifyHmac"]>
public async createSignature(...args: Parameters<WalletInterface["createSignature"]>): ReturnType<WalletInterface["createSignature"]>
public async verifySignature(...args: Parameters<WalletInterface["verifySignature"]>): ReturnType<WalletInterface["verifySignature"]>
public async acquireCertificate(...args: Parameters<WalletInterface["acquireCertificate"]>): ReturnType<WalletInterface["acquireCertificate"]>
public async listCertificates(...args: Parameters<WalletInterface["listCertificates"]>): ReturnType<WalletInterface["listCertificates"]>
public async proveCertificate(...args: Parameters<WalletInterface["proveCertificate"]>): ReturnType<WalletInterface["proveCertificate"]>
public async relinquishCertificate(...args: Parameters<WalletInterface["relinquishCertificate"]>): ReturnType<WalletInterface["relinquishCertificate"]>
public async discoverByIdentityKey(...args: Parameters<WalletInterface["discoverByIdentityKey"]>): ReturnType<WalletInterface["discoverByIdentityKey"]>
public async discoverByAttributes(...args: Parameters<WalletInterface["discoverByAttributes"]>): ReturnType<WalletInterface["discoverByAttributes"]>
public async isAuthenticated(...args: Parameters<WalletInterface["isAuthenticated"]>): ReturnType<WalletInterface["isAuthenticated"]>
public async waitForAuthentication(...args: Parameters<WalletInterface["waitForAuthentication"]>): ReturnType<WalletInterface["waitForAuthentication"]>
public async getHeight(...args: Parameters<WalletInterface["getHeight"]>): ReturnType<WalletInterface["getHeight"]>
public async getHeaderForHeight(...args: Parameters<WalletInterface["getHeaderForHeight"]>): ReturnType<WalletInterface["getHeaderForHeight"]>
public async getNetwork(...args: Parameters<WalletInterface["getNetwork"]>): ReturnType<WalletInterface["getNetwork"]>
public async getVersion(...args: Parameters<WalletInterface["getVersion"]>): ReturnType<WalletInterface["getVersion"]>
}
See also: PermissionEventHandler, PermissionToken, PermissionsManagerConfig, WalletPermissionsManagerCallbacks, createAction, internalizeAction, listActions, listCertificates, listOutputs, proveCertificate, signAction
Constructs a new Permissions Manager instance.
constructor(underlyingWallet: WalletInterface, adminOriginator: string, config: PermissionsManagerConfig = {})
See also: PermissionsManagerConfig
Argument Details
Binds a callback function to a named event, such as onProtocolPermissionRequested
.
public bindCallback(eventName: keyof WalletPermissionsManagerCallbacks, handler: PermissionEventHandler): number
See also: PermissionEventHandler, WalletPermissionsManagerCallbacks
Returns
A numeric ID you can use to unbind later
Argument Details
Denies a previously requested permission. This method rejects all pending promise calls waiting on that request
public async denyPermission(requestID: string): Promise<void>
Argument Details
Ensures the originator has basket usage permission for the specified basket. If not, triggers a permission request flow.
public async ensureBasketAccess({ originator, basket, reason, seekPermission = true, usageType }: {
originator: string;
basket: string;
reason?: string;
seekPermission?: boolean;
usageType: "insertion" | "removal" | "listing";
}): Promise<boolean>
Ensures the originator has a valid certificate permission. This is relevant when revealing certificate fields in DCAP contexts.
public async ensureCertificateAccess({ originator, privileged, verifier, certType, fields, reason, seekPermission = true, usageType }: {
originator: string;
privileged: boolean;
verifier: string;
certType: string;
fields: string[];
reason?: string;
seekPermission?: boolean;
usageType: "disclosure";
}): Promise<boolean>
Ensures the originator has label usage permission. If no valid (unexpired) permission token is found, triggers a permission request flow.
public async ensureLabelAccess({ originator, label, reason, seekPermission = true, usageType }: {
originator: string;
label: string;
reason?: string;
seekPermission?: boolean;
usageType: "apply" | "list";
}): Promise<boolean>
Ensures the originator has protocol usage permission. If no valid (unexpired) permission token is found, triggers a permission request flow.
public async ensureProtocolPermission({ originator, privileged, protocolID, counterparty, reason, seekPermission = true, 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 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.
public async ensureSpendingAuthorization({ originator, satoshis, lineItems, reason, seekPermission = true }: {
originator: string;
satoshis: number;
lineItems?: Array<{
type: "input" | "output" | "fee";
description: string;
satoshis: number;
}>;
reason?: string;
seekPermission?: boolean;
}): Promise<boolean>
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
)
public async grantPermission(params: {
requestID: string;
expiry?: number;
ephemeral?: boolean;
amount?: number;
}): Promise<void>
Argument Details
ephemeral
usage, etc.Returns true
if the originator already holds a valid unexpired basket permission for basket
.
public async hasBasketAccess(params: {
originator: string;
basket: string;
}): Promise<boolean>
Returns true
if the originator already holds a valid unexpired certificate access
for the given certType/fields. Does not prompt the user.
public async hasCertificateAccess(params: {
originator: string;
privileged: boolean;
verifier: string;
certType: string;
fields: string[];
}): Promise<boolean>
Returns true if the originator already holds a valid unexpired protocol permission.
This calls ensureProtocolPermission
with seekPermission=false
, so it won’t prompt.
public async hasProtocolPermission(params: {
originator: string;
privileged: boolean;
protocolID: WalletProtocol;
counterparty: string;
}): Promise<boolean>
Returns true
if the originator already holds a valid spending authorization token
with enough available monthly spend. We do not prompt (seekPermission=false).
public async hasSpendingAuthorization(params: {
originator: string;
satoshis: number;
}): Promise<boolean>
Lists basket permission tokens (DBAP) for a given originator (or for all if not specified).
public async listBasketAccess(params: {
originator?: string;
}): Promise<PermissionToken[]>
See also: PermissionToken
Lists certificate permission tokens (DCAP) for a given originator (or all).
public async listCertificateAccess(params: {
originator?: string;
}): Promise<PermissionToken[]>
See also: PermissionToken
Lists all protocol permission tokens (DPACP) for a given originator or for all if originator is undefined. This is a convenience method for UI or debug.
public async listProtocolPermissions({ originator }: {
originator?: string;
}): Promise<PermissionToken[]>
See also: PermissionToken
Lists spending authorization tokens (DSAP) for a given originator (or all).
public async listSpendingAuthorizations(params: {
originator?: string;
}): Promise<PermissionToken[]>
See also: PermissionToken
Returns spending for an originator in the current calendar month.
public async querySpentSince(token: PermissionToken): Promise<number>
See also: PermissionToken
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.
public async revokePermission(oldToken: PermissionToken): Promise<void>
See also: PermissionToken
Unbinds a previously registered callback by either its numeric ID (returned by bindCallback
)
or by exact function reference.
public unbindCallback(eventName: keyof WalletPermissionsManagerCallbacks, reference: number | Function): boolean
See also: WalletPermissionsManagerCallbacks
Returns
True if successfully unbound, false otherwise
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
Manages wallet settings
export class WalletSettingsManager {
kv: LocalKVStore;
constructor(private wallet: WalletInterface, private config: WalletSettingsManagerConfig = {
defaultSettings: DEFAULT_SETTINGS
})
async get(): Promise<WalletSettings>
async set(settings: WalletSettings): Promise<void>
async delete(): Promise<void>
}
See also: DEFAULT_SETTINGS, WalletSettings, WalletSettingsManagerConfig
Deletes the user’s settings token.
async delete(): Promise<void>
Returns a user’s wallet settings
async get(): Promise<WalletSettings>
See also: WalletSettings
Returns
Creates (or updates) the user’s settings token.
async set(settings: WalletSettings): Promise<void>
See also: WalletSettings
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export class WalletSigner {
isWalletSigner: true = true;
chain: sdk.Chain;
keyDeriver: KeyDeriver;
storage: WalletStorageManager;
constructor(chain: sdk.Chain, keyDeriver: KeyDeriver, storage: WalletStorageManager)
}
See also: Chain, WalletStorageManager
Links: API, Interfaces, Classes, Functions, Types, Variables
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:
Some storage services do not support multiple writers. WalletStorageManager
manages wait-blocking write requests
for these services.
export class WalletStorageManager implements sdk.WalletStorage {
_stores: ManagedStorage[] = [];
_isAvailable: boolean = false;
_active?: ManagedStorage;
_backups?: ManagedStorage[];
_conflictingActives?: ManagedStorage[];
_authId: sdk.AuthId;
_services?: sdk.WalletServices;
_readerCount: number = 0;
_writerCount: number = 0;
_isSingleWriter: boolean = true;
_syncLocked: boolean = false;
_storageProviderLocked: boolean = false;
constructor(identityKey: string, active?: sdk.WalletStorageProvider, backups?: sdk.WalletStorageProvider[])
isStorageProvider(): boolean
isAvailable(): boolean
get isActiveEnabled(): boolean
canMakeAvailable(): boolean
async makeAvailable(): Promise<TableSettings>
async getAuth(mustBeActive?: boolean): Promise<sdk.AuthId>
async getUserId(): Promise<number>
getActive(): sdk.WalletStorageProvider
getActiveSettings(): TableSettings
getActiveUser(): TableUser
getActiveStore(): string
getActiveStoreName(): string
getBackupStores(): string[]
getConflictingStores(): string[]
getAllStores(): string[]
async getActiveForWriter(): Promise<sdk.WalletStorageWriter>
async getActiveForReader(): Promise<sdk.WalletStorageReader>
async getActiveForSync(): Promise<sdk.WalletStorageSync>
async getActiveForStorageProvider(): Promise<StorageProvider>
async runAsWriter<R>(writer: (active: sdk.WalletStorageWriter) => Promise<R>): Promise<R>
async runAsReader<R>(reader: (active: sdk.WalletStorageReader) => Promise<R>): Promise<R>
async runAsSync<R>(sync: (active: sdk.WalletStorageSync) => Promise<R>, activeSync?: sdk.WalletStorageSync): Promise<R>
async runAsStorageProvider<R>(sync: (active: StorageProvider) => Promise<R>): Promise<R>
isActiveStorageProvider(): boolean
async addWalletStorageProvider(provider: sdk.WalletStorageProvider): Promise<void>
setServices(v: sdk.WalletServices)
getServices(): sdk.WalletServices
getSettings(): TableSettings
async migrate(storageName: string, storageIdentityKey: string): Promise<string>
async destroy(): Promise<void>
async findOrInsertUser(identityKey: string): Promise<{
user: TableUser;
isNew: boolean;
}>
async abortAction(args: AbortActionArgs): Promise<AbortActionResult>
async createAction(vargs: sdk.ValidCreateActionArgs): Promise<sdk.StorageCreateActionResult>
async internalizeAction(args: InternalizeActionArgs): Promise<InternalizeActionResult>
async relinquishCertificate(args: RelinquishCertificateArgs): Promise<number>
async relinquishOutput(args: RelinquishOutputArgs): Promise<number>
async processAction(args: sdk.StorageProcessActionArgs): Promise<sdk.StorageProcessActionResults>
async insertCertificate(certificate: TableCertificate): Promise<number>
async listActions(vargs: sdk.ValidListActionsArgs): Promise<ListActionsResult>
async listCertificates(args: sdk.ValidListCertificatesArgs): Promise<ListCertificatesResult>
async listOutputs(vargs: sdk.ValidListOutputsArgs): Promise<ListOutputsResult>
async findCertificates(args: sdk.FindCertificatesArgs): Promise<TableCertificateX[]>
async findOutputBaskets(args: sdk.FindOutputBasketsArgs): Promise<TableOutputBasket[]>
async findOutputs(args: sdk.FindOutputsArgs): Promise<TableOutput[]>
async findProvenTxReqs(args: sdk.FindProvenTxReqsArgs): Promise<TableProvenTxReq[]>
async syncFromReader(identityKey: string, reader: sdk.WalletStorageSyncReader, activeSync?: sdk.WalletStorageSync, log: string = ""): Promise<{
inserts: number;
updates: number;
log: string;
}>
async syncToWriter(auth: sdk.AuthId, writer: sdk.WalletStorageProvider, activeSync?: sdk.WalletStorageSync, log: string = ""): Promise<{
inserts: number;
updates: number;
log: string;
}>
async updateBackups(activeSync?: sdk.WalletStorageSync): Promise<string>
async setActive(storageIdentityKey: string): Promise<string>
}
See also: AuthId, FindCertificatesArgs, FindOutputBasketsArgs, FindOutputsArgs, FindProvenTxReqsArgs, StorageCreateActionResult, StorageProcessActionArgs, StorageProcessActionResults, StorageProvider, TableCertificate, TableCertificateX, TableOutput, TableOutputBasket, TableProvenTxReq, TableSettings, TableUser, ValidCreateActionArgs, ValidListActionsArgs, ValidListCertificatesArgs, ValidListOutputsArgs, WalletServices, WalletStorage, WalletStorageProvider, WalletStorageReader, WalletStorageSync, WalletStorageSyncReader, WalletStorageWriter, createAction, internalizeAction, listActions, listCertificates, listOutputs, processAction
The current active store which is only enabled if the store’s user record activeStorage property matches its settings record storageIdentityKey property
_active?: ManagedStorage
identityKey is always valid, userId and isActive are valid only if _isAvailable
_authId: sdk.AuthId
See also: AuthId
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[]
True if makeAvailable has been run and access to managed stores (active) is allowed
_isAvailable: boolean = false
if true, allow only a single writer to proceed at a time. queue the blocked requests so they get executed in order when released.
_isSingleWriter: boolean = true
How many read access operations are pending
_readerCount: number = 0
Configured services if any. If valid, shared with stores (which may ignore it).
_services?: sdk.WalletServices
See also: WalletServices
if true, allow no new reader or writers or sync to proceed. queue the blocked requests so they get executed in order when released.
_storageProviderLocked: boolean = false
All configured stores including current active, backups, and conflicting actives.
_stores: ManagedStorage[] = []
if true, allow no new reader or writers to proceed. queue the blocked requests so they get executed in order when released.
_syncLocked: boolean = false
How many write access operations are pending
_writerCount: number = 0
canMakeAvailable(): boolean
Returns
true if at least one WalletStorageProvider has been added.
isActiveStorageProvider(): boolean
Returns
true if the active WalletStorageProvider
also implements StorageProvider
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
.
async makeAvailable(): Promise<TableSettings>
See also: TableSettings
Returns
from the active storage.
Throws
WERR_INVALID_PARAMETER if canMakeAvailable returns false.
async runAsSync<R>(sync: (active: sdk.WalletStorageSync) => Promise<R>, activeSync?: sdk.WalletStorageSync): Promise<R>
See also: WalletStorageSync
Argument Details
Updates backups and switches to new active storage provider from among current backup providers.
Also resolves conflicting actives.
async setActive(storageIdentityKey: string): Promise<string>
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export class WhatsOnChain extends SdkWhatsOnChain {
services: Services;
constructor(chain: sdk.Chain = "main", config: WhatsOnChainConfig = {}, services?: Services)
async getStatusForTxids(txids: string[]): Promise<sdk.GetStatusForTxidsResult>
async getTxPropagation(txid: string): Promise<number>
async getRawTx(txid: string): Promise<string | undefined>
async getRawTxResult(txid: string): Promise<sdk.GetRawTxResult>
async postBeef(beef: Beef, txids: string[]): Promise<sdk.PostBeefResult>
async postRawTx(rawTx: HexString): Promise<sdk.PostTxResultForTxid>
async getMerklePath(txid: string, services: sdk.WalletServices): Promise<sdk.GetMerklePathResult>
async updateBsvExchangeRate(rate?: sdk.BsvExchangeRate, updateMsecs?: number): Promise<sdk.BsvExchangeRate>
async getUtxoStatus(output: string, outputFormat?: sdk.GetUtxoStatusOutputFormat, outpoint?: string): Promise<sdk.GetUtxoStatusResult>
async getScriptHashConfirmedHistory(hash: string): Promise<sdk.GetScriptHashHistoryResult>
async getScriptHashUnconfirmedHistory(hash: string): Promise<sdk.GetScriptHashHistoryResult>
async getScriptHashHistory(hash: string): Promise<sdk.GetScriptHashHistoryResult>
}
See also: BsvExchangeRate, Chain, GetMerklePathResult, GetRawTxResult, GetScriptHashHistoryResult, GetStatusForTxidsResult, GetUtxoStatusOutputFormat, GetUtxoStatusResult, PostBeefResult, PostTxResultForTxid, SdkWhatsOnChain, Services, WalletServices
May return undefined for unmined transactions that are in the mempool.
async getRawTx(txid: string): Promise<string | undefined>
Returns
raw transaction as hex string or undefined if txid not found in mined block.
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”}]
async getStatusForTxids(txids: string[]): Promise<sdk.GetStatusForTxidsResult>
See also: GetStatusForTxidsResult
2025-02-16 throwing internal server error 500.
async getTxPropagation(txid: string): Promise<number>
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.
async postBeef(beef: Beef, txids: string[]): Promise<sdk.PostBeefResult>
See also: PostBeefResult
async postRawTx(rawTx: HexString): Promise<sdk.PostTxResultForTxid>
See also: PostTxResultForTxid
Returns
txid returned by transaction processor of transaction broadcast
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function acquireDirectCertificate(wallet: Wallet, auth: sdk.AuthId, vargs: sdk.ValidAcquireDirectCertificateArgs): Promise<AcquireCertificateResult>
See also: AuthId, ValidAcquireDirectCertificateArgs, Wallet
Links: API, Interfaces, Classes, Functions, Types, Variables
export function arcDefaultUrl(chain: sdk.Chain): string
See also: Chain
Links: API, Interfaces, Classes, Functions, Types, Variables
Compares lengths and direct equality of values.
export function arraysEqual(arr1: Number[], arr2: Number[])
Links: API, Interfaces, Classes, Functions, Types, Variables
export function asArray(val: string | number[]): number[]
Links: API, Interfaces, Classes, Functions, Types, Variables
export function asBsvSdkPrivateKey(privKey: string): PrivateKey
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export function asBsvSdkPublickKey(pubKey: string): PublicKey
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
Coerce a bsv script encoded as a hex string, serialized array, or Script to Script If script is already a Script, just return it.
export function asBsvSdkScript(script: HexString | number[] | Script): Script {
if (Array.isArray(script)) {
script = Script.fromBinary(script);
}
else if (typeof script === "string") {
script = Script.fromHex(script);
}
return script;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
Coerce a bsv transaction encoded as a hex string, serialized array, or Transaction to Transaction If tx is already a Transaction, just return it.
export function asBsvSdkTx(tx: HexString | number[] | Transaction): Transaction {
if (Array.isArray(tx)) {
tx = Transaction.fromBinary(tx);
}
else if (typeof tx === "string") {
tx = Transaction.fromHex(tx);
}
return tx;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
Coerce a value to a hex encoded string if currently a hex encoded string or number[]
export function asString(val: string | number[]): string {
if (typeof val === "string")
return val;
return Utils.toHex(val);
}
Returns
input val if it is a string; or if number[], converts byte values to hex
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
Attempt to post one or more ProvenTxReq
with status ‘unsent’
to the bitcoin network.
export async function attemptToPostReqsToNetwork(storage: StorageProvider, reqs: EntityProvenTxReq[], trx?: sdk.TrxToken): Promise<PostReqsToNetworkResult>
See also: EntityProvenTxReq, PostReqsToNetworkResult, StorageProvider, TrxToken
Links: API, Interfaces, Classes, Functions, Types, Variables
export function buildSignableTransaction(dctr: sdk.StorageCreateActionResult, args: sdk.ValidCreateActionArgs, wallet: Wallet): {
tx: Transaction;
amount: number;
pdi: PendingStorageInput[];
log: string;
}
See also: PendingStorageInput, StorageCreateActionResult, ValidCreateActionArgs, Wallet
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function completeSignedTransaction(prior: PendingSignAction, spends: Record<number, SignActionSpend>, wallet: Wallet): Promise<Transaction>
See also: PendingSignAction, Wallet
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function completeSignedTransaction(prior: PendingSignAction, spends: Record<number, SignActionSpend>, wallet: Wallet): Promise<BsvTransaction>
See also: PendingSignAction, Wallet
Links: API, Interfaces, Classes, Functions, Types, Variables
export function convertProofToMerklePath(txid: string, proof: TscMerkleProofApi): MerklePath
See also: TscMerkleProofApi
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function createAction(storage: StorageProvider, auth: sdk.AuthId, vargs: sdk.ValidCreateActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<sdk.StorageCreateActionResult>
See also: AuthId, StorageCreateActionResult, StorageProvider, ValidCreateActionArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function createAction(wallet: Wallet, auth: sdk.AuthId, vargs: sdk.ValidCreateActionArgs): Promise<CreateActionResultX>
See also: AuthId, CreateActionResultX, ValidCreateActionArgs, Wallet
Links: API, Interfaces, Classes, Functions, Types, Variables
export function createDefaultWalletServicesOptions(chain: sdk.Chain): sdk.WalletServicesOptions
See also: Chain, WalletServicesOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
export function createStorageServiceChargeScript(pubKeyHex: PubKeyHex): {
script: string;
keyOffset: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export function createSyncMap(): SyncMap
See also: SyncMap
Links: API, Interfaces, Classes, Functions, Types, Variables
Calculate the SHA256 hash of the SHA256 hash of an array of bytes.
export function doubleSha256BE(data: number[]): number[] {
return doubleSha256HashLE(data).reverse();
}
See also: doubleSha256HashLE
Returns
reversed (big-endian) double sha256 hash of data, byte 31 of hash first.
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
Calculate the SHA256 hash of the SHA256 hash of an array of bytes.
export function doubleSha256HashLE(data: number[]): number[] {
const first = new Hash.SHA256().update(data).digest();
const second = new Hash.SHA256().update(first).digest();
return second;
}
Returns
double sha256 hash of data, byte 0 of hash first.
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
Simplifications:
Confirms for each availbleChange output that it remains available as they are allocated and selects alternate if not.
export async function generateChangeSdk(params: GenerateChangeSdkParams, allocateChangeInput: (targetSatoshis: number, exactSatoshis?: number) => Promise<GenerateChangeSdkChangeInput | undefined>, releaseChangeInput: (outputId: number) => Promise<void>): Promise<GenerateChangeSdkResult>
See also: GenerateChangeSdkChangeInput, GenerateChangeSdkParams, GenerateChangeSdkResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export function generateChangeSdkMakeStorage(availableChange: GenerateChangeSdkChangeInput[]): {
allocateChangeInput: (targetSatoshis: number, exactSatoshis?: number) => Promise<GenerateChangeSdkChangeInput | undefined>;
releaseChangeInput: (outputId: number) => Promise<void>;
getLog: () => string;
}
See also: GenerateChangeSdkChangeInput
Links: API, Interfaces, Classes, Functions, Types, Variables
Creates a Beef
to support the validity of a transaction identified by its txid
.
storage
is used to retrieve proven transactions and their merkle paths,
or proven_tx_req record with beef of external inputs (internal inputs meged by recursion).
Otherwise external services are used.
options.maxRecursionDepth
can be set to prevent overly deep chained dependencies. Will throw ERR_EXTSVS_ENVELOPE_DEPTH if exceeded.
If trustSelf
is true, a partial Beef
will be returned where transactions known by storage
to
be valid by verified proof are represented solely by ‘txid’.
If knownTxids
is defined, any ‘txid’ required by the Beef
that appears in the array is represented solely as a ‘known’ txid.
export async function getBeefForTransaction(storage: StorageProvider, txid: string, options: sdk.StorageGetBeefOptions): Promise<Beef>
See also: StorageGetBeefOptions, StorageProvider
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function getExchangeRatesIo(key: string): Promise<ExchangeRatesIoApi>
See also: ExchangeRatesIoApi
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function getIdentityKey(wallet: CertOpsWallet): Promise<PubKeyHex>
See also: CertOpsWallet
Links: API, Interfaces, Classes, Functions, Types, Variables
Process an array of table.ProvenTxReq (typically with status ‘unmined’ or ‘unknown’)
If req is invalid, set status ‘invalid’
Verify the requests are valid, lookup proofs or updated transaction status using the array of getProofServices,
When proofs are found, create new ProvenTxApi records and transition the requests’ status to ‘unconfirmed’ or ‘notifying’, depending on chaintracks succeeding on proof verification.
Increments attempts if proofs where requested.
export async function getProofs(task: WalletMonitorTask, reqs: TableProvenTxReq[], indent = 0, countsAsAttempt = false, ignoreStatus = false): Promise<{
proven: TableProvenTxReq[];
invalid: TableProvenTxReq[];
log: string;
}>
See also: TableProvenTxReq, WalletMonitorTask
Returns
reqs partitioned by status
Links: API, Interfaces, Classes, Functions, Types, Variables
Gets the next sync chunk of updated data from un-remoted storage (could be using a remote DB connection).
export async function getSyncChunk(storage: StorageReader, args: sdk.RequestSyncChunkArgs): Promise<sdk.SyncChunk>
See also: RequestSyncChunkArgs, StorageReader, SyncChunk
Links: API, Interfaces, Classes, Functions, Types, Variables
Internalize Action allows a wallet to take ownership of outputs in a pre-existing transaction. The transaction may, or may not already be known to both the storage and user.
Two types of outputs are handled: “wallet payments” and “basket insertions”.
A “basket insertion” output is considered a custom output and has no effect on the wallet’s “balance”.
A “wallet payment” adds an outputs value to the wallet’s change “balance”. These outputs are assigned to the “default” basket.
Processing starts with simple validation and then checks for a pre-existing transaction. If the transaction is already known to the user, then the outputs are reviewed against the existing outputs treatment, and merge rules are added to the arguments passed to the storage layer. The existing transaction must be in the ‘unproven’ or ‘completed’ status. Any other status is an error.
When the transaction already exists, the description is updated. The isOutgoing sense is not changed.
“basket insertion” Merge Rules:
“wallet payment” Merge Rules:
satoshis
, and the wallet balance.export async function internalizeAction(storage: StorageProvider, auth: sdk.AuthId, args: InternalizeActionArgs): Promise<InternalizeActionResult>
See also: AuthId, StorageProvider
Links: API, Interfaces, Classes, Functions, Types, Variables
Internalize Action allows a wallet to take ownership of outputs in a pre-existing transaction. The transaction may, or may not already be known to both the storage and user.
Two types of outputs are handled: “wallet payments” and “basket insertions”.
A “basket insertion” output is considered a custom output and has no effect on the wallet’s “balance”.
A “wallet payment” adds an outputs value to the wallet’s change “balance”. These outputs are assigned to the “default” basket.
Processing starts with simple validation and then checks for a pre-existing transaction. If the transaction is already known to the user, then the outputs are reviewed against the existing outputs treatment, and merge rules are added to the arguments passed to the storage layer. The existing transaction must be in the ‘unproven’ or ‘completed’ status. Any other status is an error.
When the transaction already exists, the description is updated. The isOutgoing sense is not changed.
“basket insertion” Merge Rules:
“wallet payment” Merge Rules:
amount
, and the wallet balance.export async function internalizeAction(wallet: Wallet, auth: sdk.AuthId, args: InternalizeActionArgs): Promise<InternalizeActionResult>
Links: API, Interfaces, Classes, Functions, Types, Variables
Type guard function.
export function isBaseBlockHeader(header: BaseBlockHeader | BlockHeader | LiveBlockHeader): header is BaseBlockHeader {
return typeof header.previousHash === "string";
}
See also: BaseBlockHeader, BlockHeader, LiveBlockHeader
Links: API, Interfaces, Classes, Functions, Types, Variables
Type guard function.
export function isBlockHeader(header: BaseBlockHeader | BlockHeader | LiveBlockHeader): header is LiveBlockHeader {
return "height" in header && typeof header.previousHash === "string";
}
See also: BaseBlockHeader, BlockHeader, LiveBlockHeader
Links: API, Interfaces, Classes, Functions, Types, Variables
export function isCreateActionSpecOp(label: string): boolean
Returns
true iff the label
name is a reserved createAction
special operation identifier.
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export function isHexString(s: string): boolean
Links: API, Interfaces, Classes, Functions, Types, Variables
export function isListActionsSpecOp(label: string): boolean
Returns
true iff the label
name is a reserved listActions
special operation identifier.
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export function isListOutputsSpecOp(basket: string): boolean
Returns
true iff the basket
name is a reserved listOutputs
special operation identifier.
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
Type guard function.
export function isLive(header: BlockHeader | LiveBlockHeader): header is LiveBlockHeader {
return (header as LiveBlockHeader).headerId !== undefined;
}
See also: BlockHeader, LiveBlockHeader
Links: API, Interfaces, Classes, Functions, Types, Variables
Type guard function.
export function isLiveBlockHeader(header: BaseBlockHeader | BlockHeader | LiveBlockHeader): header is LiveBlockHeader {
return "chainwork" in header && typeof header.previousHash === "string";
}
See also: BaseBlockHeader, BlockHeader, LiveBlockHeader
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function listCertificates(storage: StorageProvider, auth: sdk.AuthId, vargs: sdk.ValidListCertificatesArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListCertificatesResult>
See also: AuthId, StorageProvider, ValidListCertificatesArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function lockScriptWithKeyOffsetFromPubKey(pubKey: string, keyOffset?: string): {
script: string;
keyOffset: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export function makeAtomicBeef(tx: Transaction, beef: number[] | Beef): number[]
Links: API, Interfaces, Classes, Functions, Types, Variables
export function makeAtomicBeef(tx: BsvTransaction, beef: number[] | Beef): number[]
Links: API, Interfaces, Classes, Functions, Types, Variables
Derive a change output locking script
export function makeChangeLock(out: sdk.StorageCreateTransactionSdkOutput, dctr: sdk.StorageCreateActionResult, args: sdk.ValidCreateActionArgs, changeKeys: sdk.KeyPair, wallet: Wallet): Script
See also: KeyPair, StorageCreateActionResult, StorageCreateTransactionSdkOutput, ValidCreateActionArgs, Wallet
Links: API, Interfaces, Classes, Functions, Types, Variables
export function maxDate(d1?: Date, d2?: Date): Date | undefined
Links: API, Interfaces, Classes, Functions, Types, Variables
export function offsetPubKey(pubKey: string, keyOffset?: string): {
offsetPubKey: string;
keyOffset: string;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export function optionalArraysEqual(arr1?: Number[], arr2?: Number[])
Links: API, Interfaces, Classes, Functions, Types, Variables
export function parseTxScriptOffsets(rawTx: number[]): TxScriptOffsets
See also: TxScriptOffsets
Links: API, Interfaces, Classes, Functions, Types, Variables
export function parseWalletOutpoint(outpoint: string): {
txid: string;
vout: number;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function processAction(storage: StorageProvider, auth: sdk.AuthId, args: sdk.StorageProcessActionArgs): Promise<sdk.StorageProcessActionResults>
See also: AuthId, StorageProcessActionArgs, StorageProcessActionResults, StorageProvider
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function processAction(prior: PendingSignAction | undefined, wallet: Wallet, auth: sdk.AuthId, vargs: sdk.ValidProcessActionArgs): Promise<sdk.StorageProcessActionResults>
See also: AuthId, PendingSignAction, StorageProcessActionResults, ValidProcessActionArgs, Wallet
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function proveCertificate(wallet: Wallet, auth: sdk.AuthId, vargs: sdk.ValidProveCertificateArgs): Promise<ProveCertificateResult>
See also: AuthId, ValidProveCertificateArgs, Wallet
Links: API, Interfaces, Classes, Functions, Types, Variables
export function randomBytes(count: number): number[]
Returns
count cryptographically secure random bytes as array of bytes
Links: API, Interfaces, Classes, Functions, Types, Variables
export function randomBytesBase64(count: number): string
Returns
count cryptographically secure random bytes as base64 encoded string
Links: API, Interfaces, Classes, Functions, Types, Variables
export function randomBytesHex(count: number): string
Returns
count cryptographically secure random bytes as hex encoded string
Links: API, Interfaces, Classes, Functions, Types, Variables
export function setDisableDoubleSpendCheckForTest(v: boolean)
Links: API, Interfaces, Classes, Functions, Types, Variables
Calculate the SHA256 hash of an array of bytes
export function sha256Hash(data: number[]): number[] {
const first = new Hash.SHA256().update(data).digest();
return first;
}
Returns
sha256 hash of buffer contents.
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function signAction(wallet: Wallet, auth: sdk.AuthId, vargs: sdk.ValidSignActionArgs): Promise<SignActionResultX>
See also: AuthId, SignActionResultX, ValidSignActionArgs, Wallet
Links: API, Interfaces, Classes, Functions, Types, Variables
If a log is being kept, add a time stamped line.
export function stampLog(log: string | undefined | {
log?: string;
}, lineToAdd: string): string | undefined
Returns
undefined or log extended by time stamped lineToAdd
and new line.
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
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
export function stampLogFormat(log?: string): string
Returns
reformated multi-line event log
Argument Details
\n
.Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export function toBinaryBaseBlockHeader(header: sdk.BaseBlockHeader): number[] {
const writer = new Utils.Writer();
writer.writeUInt32BE(header.version);
writer.writeReverse(asArray(header.previousHash));
writer.writeReverse(asArray(header.merkleRoot));
writer.writeUInt32BE(header.time);
writer.writeUInt32BE(header.bits);
writer.writeUInt32BE(header.nonce);
const r = writer.toArray();
return r;
}
See also: BaseBlockHeader, asArray
Returns
80 byte array
Links: API, Interfaces, Classes, Functions, Types, Variables
export function toWalletNetwork(chain: Chain): WalletNetwork
See also: Chain
Links: API, Interfaces, Classes, Functions, Types, Variables
export function transactionInputSize(scriptSize: number): number
Returns
serialized byte length a transaction input
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export function transactionOutputSize(scriptSize: number): number
Returns
serialized byte length a transaction output
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
Compute the serialized binary transaction size in bytes given the number of inputs and outputs, and the size of each script.
export function transactionSize(inputs: number[], outputs: number[]): number
Returns
total transaction size in bytes
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function updateChaintracksFiatExchangeRates(targetCurrencies: string[], options: sdk.WalletServicesOptions): Promise<sdk.FiatExchangeRates>
See also: FiatExchangeRates, WalletServicesOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function updateExchangeratesapi(targetCurrencies: string[], options: sdk.WalletServicesOptions): Promise<sdk.FiatExchangeRates>
See also: FiatExchangeRates, WalletServicesOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateAbortActionArgs(args: AbortActionArgs): ValidAbortActionArgs
See also: ValidAbortActionArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export async function validateAcquireCertificateArgs(args: AcquireCertificateArgs): Promise<ValidAcquireCertificateArgs>
See also: ValidAcquireCertificateArgs
Argument Details
acquisitionProtocol
. public key of the certificate subject.Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateAcquireDirectCertificateArgs(args: AcquireCertificateArgs): ValidAcquireDirectCertificateArgs
See also: ValidAcquireDirectCertificateArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateAcquireIssuanceCertificateArgs(args: AcquireCertificateArgs): ValidAcquireIssuanceCertificateArgs
See also: ValidAcquireIssuanceCertificateArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateBasketInsertion(args?: BasketInsertion): ValidBasketInsertion | undefined
See also: ValidBasketInsertion
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateCreateActionArgs(args: CreateActionArgs): ValidCreateActionArgs
See also: ValidCreateActionArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateCreateActionInput(i: CreateActionInput): ValidCreateActionInput
See also: ValidCreateActionInput
Links: API, Interfaces, Classes, Functions, Types, Variables
Set all default true/false booleans to true or false if undefined.
Set all possibly undefined numbers to their default values.
Set all possibly undefined arrays to empty arrays.
Convert string outpoints to { txid: string, vout: number }
export function validateCreateActionOptions(options?: CreateActionOptions): ValidCreateActionOptions
See also: ValidCreateActionOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateCreateActionOutput(o: CreateActionOutput): ValidCreateActionOutput
See also: ValidCreateActionOutput
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateDiscoverByAttributesArgs(args: DiscoverByAttributesArgs): ValidDiscoverByAttributesArgs
See also: ValidDiscoverByAttributesArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateDiscoverByIdentityKeyArgs(args: DiscoverByIdentityKeyArgs): ValidDiscoverByIdentityKeyArgs
See also: ValidDiscoverByIdentityKeyArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateGenerateChangeSdkParams(params: GenerateChangeSdkParams): ValidateGenerateChangeSdkParamsResult
See also: GenerateChangeSdkParams, ValidateGenerateChangeSdkParamsResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateGenerateChangeSdkResult(params: GenerateChangeSdkParams, r: GenerateChangeSdkResult): {
ok: boolean;
log: string;
}
See also: GenerateChangeSdkParams, GenerateChangeSdkResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateInteger(v: number | undefined, name: string, defaultValue?: number, min?: number, max?: number): number
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateInternalizeActionArgs(args: InternalizeActionArgs): ValidInternalizeActionArgs
See also: ValidInternalizeActionArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateInternalizeOutput(args: InternalizeOutput): ValidInternalizeOutput
See also: ValidInternalizeOutput
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateListActionsArgs(args: ListActionsArgs): ValidListActionsArgs
See also: ValidListActionsArgs
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateListCertificatesArgs(args: ListCertificatesArgs): ValidListCertificatesArgs
See also: ValidListCertificatesArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateListOutputsArgs(args: ListOutputsArgs): ValidListOutputsArgs
See also: ValidListOutputsArgs
Argument Details
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateOptionalInteger(v: number | undefined, name: string, min?: number, max?: number): number | undefined
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateOptionalOutpointString(outpoint: string | undefined, name: string): string | undefined
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateOriginator(s?: string): string | undefined
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateOutpointString(outpoint: string, name: string): string
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validatePositiveIntegerOrZero(v: number, name: string): number
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateProveCertificateArgs(args: ProveCertificateArgs): ValidProveCertificateArgs
See also: ValidProveCertificateArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateRelinquishCertificateArgs(args: RelinquishCertificateArgs): ValidRelinquishCertificateArgs
See also: ValidRelinquishCertificateArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateRelinquishOutputArgs(args: RelinquishOutputArgs): ValidRelinquishOutputArgs
See also: ValidRelinquishOutputArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateSatoshis(v: number | undefined, name: string, min?: number): number
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateScriptHash(output: string, outputFormat?: sdk.GetUtxoStatusOutputFormat): string
See also: GetUtxoStatusOutputFormat
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateSecondsSinceEpoch(time: number): Date
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateSignActionArgs(args: SignActionArgs): ValidSignActionArgs
See also: ValidSignActionArgs
Links: API, Interfaces, Classes, Functions, Types, Variables
Set all default true/false booleans to true or false if undefined.
Set all possibly undefined numbers to their default values.
Set all possibly undefined arrays to empty arrays.
Convert string outpoints to { txid: string, vout: number }
export function validateSignActionOptions(options?: SignActionOptions): ValidSignActionOptions
See also: ValidSignActionOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateStorageFeeModel(v?: sdk.StorageFeeModel): sdk.StorageFeeModel
See also: StorageFeeModel
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateStringLength(s: string, name: string, min?: number, max?: number): string
Links: API, Interfaces, Classes, Functions, Types, Variables
export function validateWalletPayment(args?: WalletPayment): ValidWalletPayment | undefined
See also: ValidWalletPayment
Links: API, Interfaces, Classes, Functions, Types, Variables
Returns the byte size required to encode number as Bitcoin VarUint
export function varUintSize(val: number): 1 | 3 | 5 | 9 {
if (val < 0)
throw new sdk.WERR_INVALID_PARAMETER("varUint", "non-negative");
return val <= 252 ? 1 : val <= 65535 ? 3 : val <= 4294967295 ? 5 : 9;
}
See also: WERR_INVALID_PARAMETER
Links: API, Interfaces, Classes, Functions, Types, Variables
Helper function.
Verifies that a hex string is trimmed and lower case.
export function verifyHexString(v: string): string
Links: API, Interfaces, Classes, Functions, Types, Variables
Helper function.
Verifies that a database record identifier is an integer greater than zero.
export function verifyId(id: number | undefined | null): number
Links: API, Interfaces, Classes, Functions, Types, Variables
Helper function.
Verifies that an optional or null number has a numeric value.
export function verifyInteger(v: number | null | undefined): number
Links: API, Interfaces, Classes, Functions, Types, Variables
Helper function.
Verifies that an optional or null number has a numeric value.
export function verifyNumber(v: number | null | undefined): number
Links: API, Interfaces, Classes, Functions, Types, Variables
Helper function.
export function verifyOne<T>(results: T[], errorDescrition?: string): T
Returns
results[0].
Throws
WERR_BAD_REQUEST if results has length other than one.
Links: API, Interfaces, Classes, Functions, Types, Variables
Helper function.
export function verifyOneOrNone<T>(results: T[]): T | undefined
Returns
results[0] or undefined if length is zero.
Throws
WERR_BAD_REQUEST if results has length greater than one.
Links: API, Interfaces, Classes, Functions, Types, Variables
Helper function.
Verifies that an optional or null hex string is undefined or a trimmed lowercase string.
export function verifyOptionalHexString(v?: string | null): string | undefined
Links: API, Interfaces, Classes, Functions, Types, Variables
Helper function.
Verifies that a possibly optional value has a value.
export function verifyTruthy<T>(v: T | null | undefined, description?: string): T
Links: API, Interfaces, Classes, Functions, Types, Variables
Returns an await’able Promise that resolves in the given number of msecs.
export function wait(msecs: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, msecs));
}
Links: API, Interfaces, Classes, Functions, Types, Variables
Links: API, Interfaces, Classes, Functions, Types, Variables
export type Chain = "main" | "test"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type DBType = "SQLite" | "MySQL"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type DescriptionString5to2000Bytes = string
Links: API, Interfaces, Classes, Functions, Types, Variables
export type EntityStorage = StorageProvider
See also: StorageProvider
Links: API, Interfaces, Classes, Functions, Types, Variables
export type GetMerklePathService = (txid: string, services: WalletServices) => Promise<GetMerklePathResult>
See also: GetMerklePathResult, WalletServices
Links: API, Interfaces, Classes, Functions, Types, Variables
export type GetRawTxService = (txid: string, chain: Chain) => Promise<GetRawTxResult>
See also: Chain, GetRawTxResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export type GetScriptHashHistoryService = (hash: string) => Promise<GetScriptHashHistoryResult>
See also: GetScriptHashHistoryResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export type GetStatusForTxidsService = (txids: string[]) => Promise<GetStatusForTxidsResult>
See also: GetStatusForTxidsResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export type GetUtxoStatusOutputFormat = "hashLE" | "hashBE" | "script"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type GetUtxoStatusService = (output: string, outputFormat?: GetUtxoStatusOutputFormat, outpoint?: string) => Promise<GetUtxoStatusResult>
See also: GetUtxoStatusOutputFormat, GetUtxoStatusResult
Links: API, Interfaces, Classes, Functions, Types, Variables
export type MonitorStorage = WalletStorageManager
See also: WalletStorageManager
Links: API, Interfaces, Classes, Functions, Types, Variables
Signature for functions that handle a permission request event, e.g. “Please ask the user to allow basket X”.
export type PermissionEventHandler = (request: PermissionRequest & {
requestID: string;
}) => void | Promise<void>
See also: PermissionRequest
Links: API, Interfaces, Classes, Functions, Types, Variables
export type PostBeefService = (beef: Beef, txids: string[]) => Promise<PostBeefResult>
See also: PostBeefResult
Links: API, Interfaces, Classes, Functions, Types, Variables
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. ‘doulbeSpend’: The action has been confirmed to double spend one or more inputs, and by the “first-seen-rule” is the loosing 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.
export type PostReqsToNetworkDetailsStatus = "success" | "doubleSpend" | "unknown" | "invalid" | "serviceError" | "invalidTx"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type PostTxsService = (beef: Beef, txids: string[], services: WalletServices) => Promise<PostTxsResult>
See also: PostTxsResult, WalletServices
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export type ProvenTxReqStatus = "sending" | "unsent" | "nosend" | "unknown" | "nonfinal" | "unprocessed" | "unmined" | "callback" | "unconfirmed" | "completed" | "invalid" | "doubleSpend" | "unfail"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type ReqHistoryNote = {
when?: string;
what: string;
[key: string]: boolean | string | number | undefined;
}
Links: API, Interfaces, Classes, Functions, Types, Variables
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. ‘doulbeSpend’: The action has been confirmed to double spend one or more inputs, and by the “first-seen-rule” is the loosing 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.
export type ReviewActionResultStatus = "success" | "doubleSpend" | "serviceError" | "invalidTx"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type ScriptHashFormat = "hashLE" | "hashBE" | "script"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type StorageProvidedBy = "you" | "storage" | "you-and-storage"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type SyncProtocolVersion = "0.1.0"
Links: API, Interfaces, Classes, Functions, Types, Variables
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.
export type SyncStatus = "success" | "error" | "identified" | "updated" | "unknown"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type TransactionStatus = "completed" | "failed" | "unprocessed" | "sending" | "unproven" | "unsigned" | "nosend" | "nonfinal" | "unfail"
Links: API, Interfaces, Classes, Functions, Types, Variables
export type UpdateFiatExchangeRateService = (targetCurrencies: string[], options: WalletServicesOptions) => Promise<FiatExchangeRates>
See also: FiatExchangeRates, WalletServicesOptions
Links: API, Interfaces, Classes, Functions, Types, Variables
Links: API, Interfaces, Classes, Functions, Types, Variables
DEFAULT_PROFILE_ID = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Links: API, Interfaces, Classes, Functions, Types, Variables
DEFAULT_SETTINGS = {
trustSettings: {
trustLevel: 2,
trustedCertifiers: [
{
name: "Metanet Trust Services",
description: "Registry for protocols, baskets, and certificates types",
iconUrl: "https://bsvblockchain.org/favicon.ico",
identityKey: "03daf815fe38f83da0ad83b5bedc520aa488aef5cbc93a93c67a7fe60406cbffe8",
trust: 4
},
{
name: "SocialCert",
description: "Certifies social media handles, phone numbers and emails",
iconUrl: "https://socialcert.net/favicon.ico",
trust: 3,
identityKey: "02cf6cdf466951d8dfc9e7c9367511d0007ed6fba35ed42d425cc412fd6cfd4a17"
}
]
},
theme: { mode: "dark" }
} as WalletSettings
See also: WalletSettings
Links: API, Interfaces, Classes, Functions, Types, Variables
PBKDF2_NUM_ROUNDS = 7777
Links: API, Interfaces, Classes, Functions, Types, Variables
ProvenTxReqNonTerminalStatus: ProvenTxReqStatus[] = [
"sending",
"unsent",
"nosend",
"unknown",
"nonfinal",
"unprocessed",
"unmined",
"callback",
"unconfirmed"
]
See also: ProvenTxReqStatus
Links: API, Interfaces, Classes, Functions, Types, Variables
ProvenTxReqTerminalStatus: ProvenTxReqStatus[] = ["completed", "invalid", "doubleSpend"]
See also: ProvenTxReqStatus
Links: API, Interfaces, Classes, Functions, Types, Variables
TESTNET_DEFAULT_SETTINGS: WalletSettings = {
...DEFAULT_SETTINGS,
trustSettings: {
...DEFAULT_SETTINGS.trustSettings,
trustedCertifiers: DEFAULT_SETTINGS.trustSettings.trustedCertifiers.map(certifier => ({
...certifier,
identityKey: TESTNET_IDENTITY_KEYS[certifier.name] || certifier.identityKey
}))
}
}
See also: DEFAULT_SETTINGS, WalletSettings
Links: API, Interfaces, Classes, Functions, Types, Variables
brc29ProtocolID: WalletProtocol = [2, "3241645161d8"]
Links: API, Interfaces, Classes, Functions, Types, Variables
maxPossibleSatoshis = 2099999999999999
Links: API, Interfaces, Classes, Functions, Types, Variables
outputColumnsWithoutLockingScript = [
"created_at",
"updated_at",
"outputId",
"userId",
"transactionId",
"basketId",
"spendable",
"change",
"vout",
"satoshis",
"providedBy",
"purpose",
"type",
"outputDescription",
"txid",
"senderIdentityKey",
"derivationPrefix",
"derivationSuffix",
"customInstructions",
"spentBy",
"sequenceNumber",
"spendingDescription",
"scriptLength",
"scriptOffset"
]
Links: API, Interfaces, Classes, Functions, Types, Variables
parseResults = async (lookupResult: LookupAnswer): Promise<VerifiableCertificate[]> => {
if (lookupResult.type === "output-list") {
const parsedResults: VerifiableCertificate[] = [];
for (const output of lookupResult.outputs) {
try {
const tx = Transaction.fromBEEF(output.beef);
const decodedOutput = PushDrop.decode(tx.outputs[output.outputIndex].lockingScript);
const certificate: VerifiableCertificate = JSON.parse(Utils.toUTF8(decodedOutput.fields[0]));
const verifiableCert = new VerifiableCertificate(certificate.type, certificate.serialNumber, certificate.subject, certificate.certifier, certificate.revocationOutpoint, certificate.fields, certificate.keyring, certificate.signature);
const decryptedFields = await verifiableCert.decryptFields(new ProtoWallet("anyone"));
await verifiableCert.verify();
verifiableCert.decryptedFields = decryptedFields;
parsedResults.push(verifiableCert);
}
catch (error) {
console.error(error);
}
}
return parsedResults;
}
return [];
}
Links: API, Interfaces, Classes, Functions, Types, Variables
queryOverlay = async (query: unknown, resolver: LookupResolver): Promise<VerifiableCertificate[]> => {
const results = await resolver.query({
service: "ls_identity",
query
});
return await parseResults(results);
}
See also: parseResults
Links: API, Interfaces, Classes, Functions, Types, Variables
specOpFailedActions = "97d4eb1e49215e3374cc2c1939a7c43a55e95c7427bf2d45ed63e3b4e0c88153"
Links: API, Interfaces, Classes, Functions, Types, Variables
specOpInvalidChange = "5a76fd430a311f8bc0553859061710a4475c19fed46e2ff95969aa918e612e57"
Links: API, Interfaces, Classes, Functions, Types, Variables
specOpNoSendActions = "ac6b20a3bb320adafecd637b25c84b792ad828d3aa510d05dc841481f664277d"
Links: API, Interfaces, Classes, Functions, Types, Variables
specOpSetWalletChangeParams = "a4979d28ced8581e9c1c92f1001cc7cb3aabf8ea32e10888ad898f0a509a3929"
Links: API, Interfaces, Classes, Functions, Types, Variables
specOpThrowReviewActions = "a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a"
Links: API, Interfaces, Classes, Functions, Types, Variables
specOpWalletBalance = "893b7646de0e1c9f741bd6e9169b76a8847ae34adef7bef1e6a285371206d2e8"
Links: API, Interfaces, Classes, Functions, Types, Variables
transactionColumnsWithoutRawTx = [
"created_at",
"updated_at",
"transactionId",
"userId",
"provenTxId",
"status",
"reference",
"isOutgoing",
"satoshis",
"version",
"lockTime",
"description",
"txid"
]
Links: API, Interfaces, Classes, Functions, Types, Variables
transformVerifiableCertificatesWithTrust = (trustSettings: TrustSettings, certificates: VerifiableCertificate[]): DiscoverCertificatesResult => {
const identityGroups: Record<string, IdentityGroup> = {};
const certifierCache: Record<string, Certifier> = {};
certificates.forEach(cert => {
const { subject, certifier } = cert;
if (!subject || !certifier)
return;
if (!certifierCache[certifier]) {
const found = trustSettings.trustedCertifiers.find(x => x.identityKey === certifier);
if (!found)
return;
certifierCache[certifier] = found;
}
const certifierInfo: IdentityCertifier = {
name: certifierCache[certifier].name,
iconUrl: certifierCache[certifier].iconUrl || "",
description: certifierCache[certifier].description,
trust: certifierCache[certifier].trust
};
const extendedCert: IdentityCertificate = {
...cert,
signature: cert.signature!,
decryptedFields: cert.decryptedFields as Record<string, string>,
publiclyRevealedKeyring: cert.keyring,
certifierInfo
};
if (!identityGroups[subject]) {
identityGroups[subject] = { totalTrust: 0, members: [] };
}
identityGroups[subject].totalTrust += certifierInfo.trust;
identityGroups[subject].members.push(extendedCert);
});
const finalResults: ExtendedVerifiableCertificate[] = [];
Object.values(identityGroups).forEach(group => {
if (group.totalTrust >= trustSettings.trustLevel) {
finalResults.push(...group.members);
}
});
finalResults.sort((a, b) => b.certifierInfo.trust - a.certifierInfo.trust);
return {
totalCertificates: finalResults.length,
certificates: finalResults
};
}
See also: Certifier, ExtendedVerifiableCertificate, TrustSettings
Links: API, Interfaces, Classes, Functions, Types, Variables