wallet-toolbox

STORAGE: BSV Wallet Toolbox API Documentation

The documentation is split into various pages, this page covers the persistent storage of wallet data: transactions, outputs and metadata.

The WalletStorageManager class manages a collection of storage providers of which one is the “active” storage at any one time, and the rest are backups. It manages access to wallet data, pushing incremental updates to backups, and switching the active to what was previously a backup.

The StorageClient implements a cloud based storage provider via JSON-RPC. The StorageServer class and @bsv/wallet-infra package can be used to host such a JSON-RPC server.

The StorageKnex class implements Knex based database storage with explicit support for both MySQL and SQLite.

Return To Top

API

Links: API, Interfaces, Classes, Functions, Types, Variables

Interfaces

     
CommitNewTxResults ProvenTxReqHistorySummaryApi TableOutputTag
EntitySyncMap ProvenTxReqNotify TableOutputTagMap
GenerateChangeSdkChangeInput StorageInternalizeActionResult TableOutputX
GenerateChangeSdkChangeOutput StorageKnexOptions TableProvenTx
GenerateChangeSdkInput StorageProviderOptions TableProvenTxReq
GenerateChangeSdkOutput StorageReaderOptions TableProvenTxReqDynamics
GenerateChangeSdkParams StorageReaderWriterOptions TableSettings
GenerateChangeSdkResult SyncError TableSyncState
GenerateChangeSdkStorageChange SyncMap TableTransaction
GetReqsAndBeefDetail TableCertificate TableTxLabel
GetReqsAndBeefResult TableCertificateField TableTxLabelMap
PostBeefResultForTxidApi TableCertificateX TableUser
PostReqsToNetworkDetails TableCommission ValidateGenerateChangeSdkParamsResult
PostReqsToNetworkResult TableMonitorEvent WalletStorageServerOptions
ProvenTxFromTxidResult TableOutput XValidCreateActionOutput
ProvenTxReqHistory TableOutputBasket  

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: CommitNewTxResults
export interface CommitNewTxResults {
    req: EntityProvenTxReq;
    log?: string;
}

See also: EntityProvenTxReq

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: EntitySyncMap
export interface EntitySyncMap {
    entityName: string;
    idMap: Record<number, number>;
    maxUpdated_at?: Date;
    count: number;
}
Property count

The cummulative count of items of this entity type received over all the SyncChunks since the since was last updated.

This is the offset value to use for the next SyncChunk request.

count: number
Property idMap

Maps foreign ids to local ids Some entities don’t have idMaps (CertificateField, TxLabelMap and OutputTagMap)

idMap: Record<number, number>
Property maxUpdated_at

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


Interface: GenerateChangeSdkChangeInput
export interface GenerateChangeSdkChangeInput {
    outputId: number;
    satoshis: number;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: GenerateChangeSdkChangeOutput
export interface GenerateChangeSdkChangeOutput {
    satoshis: number;
    lockingScriptLength: number;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: GenerateChangeSdkInput
export interface GenerateChangeSdkInput {
    satoshis: number;
    unlockingScriptLength: number;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: GenerateChangeSdkOutput
export interface GenerateChangeSdkOutput {
    satoshis: number;
    lockingScriptLength: number;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: GenerateChangeSdkParams
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

Property changeFirstSatoshis

Lowest amount value to assign to a change output. Drop the output if unable to satisfy. default 285

changeFirstSatoshis: number
Property changeInitialSatoshis

Satoshi amount to initialize optional new change outputs.

changeInitialSatoshis: number
Property changeLockingScriptLength

Fixed change locking script length.

For P2PKH template, 25 bytes

changeLockingScriptLength: number
Property changeUnlockingScriptLength

Fixed change unlocking script length.

For P2PKH template, 107 bytes

changeUnlockingScriptLength: number
Property targetNetCount

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


Interface: GenerateChangeSdkResult
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


Interface: GenerateChangeSdkStorageChange
export interface GenerateChangeSdkStorageChange extends GenerateChangeSdkChangeInput {
    spendable: boolean;
}

See also: GenerateChangeSdkChangeInput

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: GetReqsAndBeefDetail
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


Interface: GetReqsAndBeefResult
export interface GetReqsAndBeefResult {
    beef: Beef;
    details: GetReqsAndBeefDetail[];
}

See also: GetReqsAndBeefDetail

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: PostBeefResultForTxidApi
export interface PostBeefResultForTxidApi {
    txid: string;
    status: "success" | "error";
    alreadyKnown?: boolean;
    blockHash?: string;
    blockHeight?: number;
    merklePath?: string;
}
Property alreadyKnown

if true, the transaction was already known to this service. Usually treat as a success.

Potentially stop posting to additional transaction processors.

alreadyKnown?: boolean
Property status

‘success’ - The transaction was accepted for processing

status: "success" | "error"

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: PostReqsToNetworkDetails
export interface PostReqsToNetworkDetails {
    txid: string;
    req: EntityProvenTxReq;
    status: PostReqsToNetworkDetailsStatus;
    competingTxs?: string[];
}

See also: EntityProvenTxReq, PostReqsToNetworkDetailsStatus

Property competingTxs

Any competing double spend txids reported for this txid

competingTxs?: string[]

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: PostReqsToNetworkResult
export interface PostReqsToNetworkResult {
    status: "success" | "error";
    beef: Beef;
    details: PostReqsToNetworkDetails[];
    log: string;
}

See also: PostReqsToNetworkDetails

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ProvenTxFromTxidResult
export interface ProvenTxFromTxidResult {
    proven?: EntityProvenTx;
    rawTx?: number[];
}

See also: EntityProvenTx

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ProvenTxReqHistory
export interface ProvenTxReqHistory {
    notes?: sdk.ReqHistoryNote[];
}

See also: ReqHistoryNote

Property notes

Keys are Date().toISOString() Values are a description of what happened.

notes?: sdk.ReqHistoryNote[]

See also: ReqHistoryNote

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ProvenTxReqHistorySummaryApi
export interface ProvenTxReqHistorySummaryApi {
    setToCompleted: boolean;
    setToCallback: boolean;
    setToUnmined: boolean;
    setToDoubleSpend: boolean;
    setToSending: boolean;
    setToUnconfirmed: boolean;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ProvenTxReqNotify
export interface ProvenTxReqNotify {
    transactionIds?: number[];
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: StorageInternalizeActionResult
export interface StorageInternalizeActionResult extends InternalizeActionResult {
    isMerge: boolean;
    txid: string;
    satoshis: number;
}
Property isMerge

true if internalizing outputs on an existing storage transaction

isMerge: boolean
Property satoshis

net change in change balance for user due to this internalization

satoshis: number
Property txid

txid of transaction being internalized

txid: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: StorageKnexOptions
export interface StorageKnexOptions extends StorageProviderOptions {
    knex: Knex;
}

See also: StorageProviderOptions

Property knex

Knex database interface initialized with valid connection configuration.

knex: Knex

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: StorageProviderOptions
export interface StorageProviderOptions extends StorageReaderWriterOptions {
    chain: sdk.Chain;
    feeModel: sdk.StorageFeeModel;
    commissionSatoshis: number;
    commissionPubKeyHex?: PubKeyHex;
}

See also: Chain, StorageFeeModel, StorageReaderWriterOptions

Property commissionPubKeyHex

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
Property commissionSatoshis

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


Interface: StorageReaderOptions
export interface StorageReaderOptions {
    chain: sdk.Chain;
}

See also: Chain

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: StorageReaderWriterOptions
export interface StorageReaderWriterOptions extends StorageReaderOptions {
}

See also: StorageReaderOptions

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: SyncError
export interface SyncError {
    code: string;
    description: string;
    stack?: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: SyncMap
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


Interface: TableCertificate
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


Interface: TableCertificateField
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


Interface: TableCertificateX
export interface TableCertificateX extends TableCertificate {
    fields?: TableCertificateField[];
}

See also: TableCertificate, TableCertificateField

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: TableCommission
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


Interface: TableMonitorEvent
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


Interface: TableOutput
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


Interface: TableOutputBasket
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


Interface: TableOutputTag
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


Interface: TableOutputTagMap
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


Interface: TableOutputX
export interface TableOutputX extends TableOutput {
    basket?: TableOutputBasket;
    tags?: TableOutputTag[];
}

See also: TableOutput, TableOutputBasket, TableOutputTag

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: TableProvenTx
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


Interface: TableProvenTxReq
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

Property attempts

Count of how many times a service has been asked about this txid

attempts: number
Property batch

If valid, a unique string identifying a batch of transactions to be sent together for processing.

batch?: string
Property history

JSON string of processing history. Parses to ProvenTxReqHistoryApi.

history: string
Property notified

Set to true when a terminal status has been set and notification has occurred.

notified: boolean
Property notify

JSON string of data to drive notifications when this request completes. Parses to ProvenTxReqNotifyApi.

notify: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: TableProvenTxReqDynamics

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

Property attempts

Count of how many times a service has been asked about this txid

attempts: number
Property batch

If valid, a unique string identifying a batch of transactions to be sent together for processing.

batch?: string
Property history

JSON string of processing history. Parses to ProvenTxReqHistoryApi.

history: string
Property notified

Set to true when a terminal status has been set and notification has occurred.

notified: boolean
Property notify

JSON string of data to drive notifications when this request completes. Parses to ProvenTxReqNotifyApi.

notify: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: TableSettings
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

Property storageIdentityKey

The identity key (public key) assigned to this storage

storageIdentityKey: string
Property storageName

The human readable name assigned to this storage.

storageName: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: TableSyncState
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


Interface: TableTransaction
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

Property isOutgoing

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
Property lockTime

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
Property reference

max length of 64, hex encoded

reference: Base64String
Property version

If not undefined, must match value in associated rawTransaction.

version?: number

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: TableTxLabel
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


Interface: TableTxLabelMap
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


Interface: TableUser
export interface TableUser extends sdk.EntityTimeStamp {
    created_at: Date;
    updated_at: Date;
    userId: number;
    identityKey: string;
    activeStorage: string;
}

See also: EntityTimeStamp

Property activeStorage

The storageIdentityKey value of the active wallet storage.

activeStorage: string
Property identityKey

PubKeyHex uniquely identifying user. Typically 66 hex digits.

identityKey: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ValidateGenerateChangeSdkParamsResult
export interface ValidateGenerateChangeSdkParamsResult {
    hasMaxPossibleOutput?: number;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: WalletStorageServerOptions
export interface WalletStorageServerOptions {
    port: number;
    wallet: Wallet;
    monetize: boolean;
    calculateRequestPrice?: (req: Request) => number | Promise<number>;
}

See also: Wallet

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: XValidCreateActionOutput
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


Classes

     
EntityBase EntityProvenTxReq StorageKnex
EntityCertificate EntitySyncState StorageProvider
EntityCertificateField EntityTransaction StorageReader
EntityCommission EntityTxLabel StorageReaderWriter
EntityOutput EntityTxLabelMap StorageServer
EntityOutputBasket EntityUser StorageSyncReader
EntityOutputTag KnexMigrations WalletStorageManager
EntityOutputTagMap MergeEntity  
EntityProvenTx StorageClient  

Links: API, Interfaces, Classes, Functions, Types, Variables


Class: EntityBase
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

Method equals

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

Method mergeExisting

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

Method mergeNew

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

Method toApi

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.

Method updateApi

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


Class: EntityCertificate
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


Class: EntityCertificateField
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


Class: EntityCommission
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


Class: EntityOutput
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


Class: EntityOutputBasket
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


Class: EntityOutputTag
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


Class: EntityOutputTagMap
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


Class: EntityProvenTx
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

Property getProofAttemptsLimit

How high attempts can go before status is forced to invalid

static getProofAttemptsLimit = 8
Property getProofMinutes

How many hours we have to try for a poof

static getProofMinutes = 60
Method fromReq

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

Method fromTxid

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

Method getMerklePath
getMerklePath(): MerklePath 

Returns

desirialized MerklePath object, value is cached.

Links: API, Interfaces, Classes, Functions, Types, Variables


Class: EntityProvenTxReq
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

Method addHistoryNote

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

Method equals

‘convergent’ equality must satisfy (A sync B) equals (B sync A)

override equals(ei: TableProvenTxReq, syncMap?: SyncMap | undefined): boolean 

See also: SyncMap, TableProvenTxReq

Method historySince

Returns history to only what followed since date.

historySince(since: Date): ProvenTxReqHistory 

See also: ProvenTxReqHistory

Method mergeExisting

When merging ProvenTxReq, care is taken to avoid short-cirtuiting notification: status must not transition to completed without passing through notifying. Thus a full convergent merge passes through these sequence steps:

  1. Remote storage completes before local storage.
  2. The remotely completed req and ProvenTx sync to local storage.
  3. The local storage transitions to notifying, after merging the remote attempts and history.
  4. The local storage notifies, transitioning to completed.
  5. Having been updated, the local req, but not ProvenTx sync to remote storage, but do not merge because the earlier completed wins.
  6. Convergent equality is achieved (completing work - history and attempts are equal)

On terminal failure: doubleSpend trumps invalid as it contains more data.

override async mergeExisting(storage: EntityStorage, since: Date | undefined, ei: TableProvenTxReq, syncMap: SyncMap, trx?: sdk.TrxToken): Promise<boolean> 

See also: EntityStorage, SyncMap, TableProvenTxReq, TrxToken

Method updateStorage

Updates database record with current state of this EntityUser

async updateStorage(storage: EntityStorage, trx?: sdk.TrxToken) 

See also: EntityStorage, TrxToken

Method updateStorageDynamicProperties

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


Class: EntitySyncState
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

Method mergeSyncMap

Merge additions to the syncMap

mergeSyncMap(iSyncMap: SyncMap) 

See also: SyncMap

Method updateStorage

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


Class: EntityTransaction
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

Method getBsvTxIns
getBsvTxIns(): TransactionInput[] 

Returns

array of

Method getInputs

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


Class: EntityTxLabel
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


Class: EntityTxLabelMap
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


Class: EntityUser
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


Class: KnexMigrations
export class KnexMigrations implements MigrationSource<string> {
    migrations: Record<string, Migration> = {};
    constructor(public chain: sdk.Chain, public storageName: string, public storageIdentityKey: string, public maxOutputScriptLength: number) 
    async getMigrations(): Promise<string[]> 
    getMigrationName(migration: string) 
    async getMigration(migration: string): Promise<Migration> 
    async getLatestMigration(): Promise<string> 
    static async latestMigration(): Promise<string> 
    setupMigrations(chain: string, storageName: string, storageIdentityKey: string, maxOutputScriptLength: number): Record<string, Migration> 
    static async dbtype(knex: Knex<any, any[]>): Promise<DBType> {
        try {
            const q = `SELECT 
    CASE 
        WHEN (SELECT VERSION() LIKE '%MariaDB%') = 1 THEN 'Unknown'
        WHEN (SELECT VERSION()) IS NOT NULL THEN 'MySQL'
        ELSE 'Unknown'
    END AS database_type;`;
            let r = await knex.raw(q);
            if (!r[0]["database_type"])
                r = r[0];
            if (r["rows"])
                r = r.rows;
            const dbtype: "SQLite" | "MySQL" | "Unknown" = r[0].database_type;
            if (dbtype === "Unknown")
                throw new sdk.WERR_NOT_IMPLEMENTED(`Attempting to create database on unsuported engine.`);
            return dbtype;
        }
        catch (eu: unknown) {
            const e = sdk.WalletError.fromUnknown(eu);
            if (e.code === "SQLITE_ERROR")
                return "SQLite";
            throw new sdk.WERR_NOT_IMPLEMENTED(`Attempting to create database on unsuported engine.`);
        }
    }
}

See also: Chain, DBType, WERR_NOT_IMPLEMENTED, WalletError

Constructor
constructor(public chain: sdk.Chain, public storageName: string, public storageIdentityKey: string, public maxOutputScriptLength: number) 

See also: Chain

Argument Details

Method dbtype
static async dbtype(knex: Knex<any, any[]>): Promise<DBType> 

See also: DBType

Returns

connected database engine variant

Links: API, Interfaces, Classes, Functions, Types, Variables


Class: MergeEntity
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

Method merge
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


Class: StorageClient

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

Method abortAction

Aborts an action by reference string.

async abortAction(auth: sdk.AuthId, args: AbortActionArgs): Promise<AbortActionResult> 

See also: AuthId

Returns

abortAction result.

Argument Details

Method createAction

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

Method destroy

Called to cleanup resources when no further use of this object will occur.

async destroy(): Promise<void> 
Method findCertificatesAuth

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

Method findOrInsertSyncStateAuth

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

Method findOrInsertUser

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

Method findOutputBasketsAuth

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

Method findOutputsAuth

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

Method findProvenTxReqs

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

Method getServices

Remote storage does not offer Services to remote clients.

getServices(): sdk.WalletServices 

See also: WalletServices

Throws

WERR_INVALID_OPERATION

Method getSettings
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.

Method getSyncChunk

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

Method insertCertificateAuth

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

Method internalizeAction

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

Method isAvailable
isAvailable(): boolean 

Returns

true once storage TableSettings have been retreived from remote storage.

Method isStorageProvider

The StorageClient implements the WalletStorageProvider interface. It does not implement the lower level StorageProvider interface.

isStorageProvider(): boolean 

Returns

false

Method listActions

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

Method listCertificates

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

Method listOutputs

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

Method makeAvailable

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

Method migrate

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

Method processAction

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

Method processSyncChunk

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

Method relinquishCertificate

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

Method relinquishOutput

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

Method setActive

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

Method setServices

Ignored. Remote storage cannot share Services with remote clients.

setServices(v: sdk.WalletServices): void 

See also: WalletServices

Method updateProvenTxReqWithNewProvenTx

Handles the data received when a new transaction proof is found in response to an outstanding request for proof data:

async updateProvenTxReqWithNewProvenTx(args: sdk.UpdateProvenTxReqWithNewProvenTxArgs): Promise<sdk.UpdateProvenTxReqWithNewProvenTxResult> 

See also: UpdateProvenTxReqWithNewProvenTxArgs, UpdateProvenTxReqWithNewProvenTxResult

Returns

results of updates

Argument Details

Method validateEntities

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.

Method validateEntity

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


Class: StorageKnex
export class StorageKnex extends StorageProvider implements sdk.WalletStorageProvider {
    knex: Knex;
    constructor(options: StorageKnexOptions) 
    async readSettings(): Promise<TableSettings> 
    override async getProvenOrRawTx(txid: string, trx?: sdk.TrxToken): Promise<sdk.ProvenOrRawTx> 
    dbTypeSubstring(source: string, fromOffset: number, forLength?: number) 
    override async getRawTxOfKnownValidTransaction(txid?: string, offset?: number, length?: number, trx?: sdk.TrxToken): Promise<number[] | undefined> 
    getProvenTxsForUserQuery(args: sdk.FindForUserSincePagedArgs): Knex.QueryBuilder 
    override async getProvenTxsForUser(args: sdk.FindForUserSincePagedArgs): Promise<TableProvenTx[]> 
    getProvenTxReqsForUserQuery(args: sdk.FindForUserSincePagedArgs): Knex.QueryBuilder 
    override async getProvenTxReqsForUser(args: sdk.FindForUserSincePagedArgs): Promise<TableProvenTxReq[]> 
    getTxLabelMapsForUserQuery(args: sdk.FindForUserSincePagedArgs): Knex.QueryBuilder 
    override async getTxLabelMapsForUser(args: sdk.FindForUserSincePagedArgs): Promise<TableTxLabelMap[]> 
    getOutputTagMapsForUserQuery(args: sdk.FindForUserSincePagedArgs): Knex.QueryBuilder 
    override async getOutputTagMapsForUser(args: sdk.FindForUserSincePagedArgs): Promise<TableOutputTagMap[]> 
    override async listActions(auth: sdk.AuthId, vargs: sdk.ValidListActionsArgs): Promise<ListActionsResult> 
    override async listOutputs(auth: sdk.AuthId, vargs: sdk.ValidListOutputsArgs): Promise<ListOutputsResult> 
    override async insertProvenTx(tx: TableProvenTx, trx?: sdk.TrxToken): Promise<number> 
    override async insertProvenTxReq(tx: TableProvenTxReq, trx?: sdk.TrxToken): Promise<number> 
    override async insertUser(user: TableUser, trx?: sdk.TrxToken): Promise<number> 
    override async insertCertificateAuth(auth: sdk.AuthId, certificate: TableCertificateX): Promise<number> 
    override async insertCertificate(certificate: TableCertificateX, trx?: sdk.TrxToken): Promise<number> 
    override async insertCertificateField(certificateField: TableCertificateField, trx?: sdk.TrxToken): Promise<void> 
    override async insertOutputBasket(basket: TableOutputBasket, trx?: sdk.TrxToken): Promise<number> 
    override async insertTransaction(tx: TableTransaction, trx?: sdk.TrxToken): Promise<number> 
    override async insertCommission(commission: TableCommission, trx?: sdk.TrxToken): Promise<number> 
    override async insertOutput(output: TableOutput, trx?: sdk.TrxToken): Promise<number> 
    override async insertOutputTag(tag: TableOutputTag, trx?: sdk.TrxToken): Promise<number> 
    override async insertOutputTagMap(tagMap: TableOutputTagMap, trx?: sdk.TrxToken): Promise<void> 
    override async insertTxLabel(label: TableTxLabel, trx?: sdk.TrxToken): Promise<number> 
    override async insertTxLabelMap(labelMap: TableTxLabelMap, trx?: sdk.TrxToken): Promise<void> 
    override async insertMonitorEvent(event: TableMonitorEvent, trx?: sdk.TrxToken): Promise<number> 
    override async insertSyncState(syncState: TableSyncState, trx?: sdk.TrxToken): Promise<number> 
    override async updateCertificateField(certificateId: number, fieldName: string, update: Partial<TableCertificateField>, trx?: sdk.TrxToken): Promise<number> 
    override async updateCertificate(id: number, update: Partial<TableCertificate>, trx?: sdk.TrxToken): Promise<number> 
    override async updateCommission(id: number, update: Partial<TableCommission>, trx?: sdk.TrxToken): Promise<number> 
    override async updateOutputBasket(id: number, update: Partial<TableOutputBasket>, trx?: sdk.TrxToken): Promise<number> 
    override async updateOutput(id: number, update: Partial<TableOutput>, trx?: sdk.TrxToken): Promise<number> 
    override async updateOutputTagMap(outputId: number, tagId: number, update: Partial<TableOutputTagMap>, trx?: sdk.TrxToken): Promise<number> 
    override async updateOutputTag(id: number, update: Partial<TableOutputTag>, trx?: sdk.TrxToken): Promise<number> 
    override async updateProvenTxReq(id: number | number[], update: Partial<TableProvenTxReq>, trx?: sdk.TrxToken): Promise<number> 
    override async updateProvenTx(id: number, update: Partial<TableProvenTx>, trx?: sdk.TrxToken): Promise<number> 
    override async updateSyncState(id: number, update: Partial<TableSyncState>, trx?: sdk.TrxToken): Promise<number> 
    override async updateTransaction(id: number | number[], update: Partial<TableTransaction>, trx?: sdk.TrxToken): Promise<number> 
    override async updateTxLabelMap(transactionId: number, txLabelId: number, update: Partial<TableTxLabelMap>, trx?: sdk.TrxToken): Promise<number> 
    override async updateTxLabel(id: number, update: Partial<TableTxLabel>, trx?: sdk.TrxToken): Promise<number> 
    override async updateUser(id: number, update: Partial<TableUser>, trx?: sdk.TrxToken): Promise<number> 
    override async updateMonitorEvent(id: number, update: Partial<TableMonitorEvent>, trx?: sdk.TrxToken): Promise<number> 
    setupQuery<T extends object>(table: string, args: sdk.FindPartialSincePagedArgs<T>): Knex.QueryBuilder 
    findCertificateFieldsQuery(args: sdk.FindCertificateFieldsArgs): Knex.QueryBuilder 
    findCertificatesQuery(args: sdk.FindCertificatesArgs): Knex.QueryBuilder 
    findCommissionsQuery(args: sdk.FindCommissionsArgs): Knex.QueryBuilder 
    findOutputBasketsQuery(args: sdk.FindOutputBasketsArgs): Knex.QueryBuilder 
    findOutputsQuery(args: sdk.FindOutputsArgs, count?: boolean): Knex.QueryBuilder 
    findOutputTagMapsQuery(args: sdk.FindOutputTagMapsArgs): Knex.QueryBuilder 
    findOutputTagsQuery(args: sdk.FindOutputTagsArgs): Knex.QueryBuilder 
    findProvenTxReqsQuery(args: sdk.FindProvenTxReqsArgs): Knex.QueryBuilder 
    findProvenTxsQuery(args: sdk.FindProvenTxsArgs): Knex.QueryBuilder 
    findSyncStatesQuery(args: sdk.FindSyncStatesArgs): Knex.QueryBuilder 
    findTransactionsQuery(args: sdk.FindTransactionsArgs, count?: boolean): Knex.QueryBuilder 
    findTxLabelMapsQuery(args: sdk.FindTxLabelMapsArgs): Knex.QueryBuilder 
    findTxLabelsQuery(args: sdk.FindTxLabelsArgs): Knex.QueryBuilder 
    findUsersQuery(args: sdk.FindUsersArgs): Knex.QueryBuilder 
    findMonitorEventsQuery(args: sdk.FindMonitorEventsArgs): Knex.QueryBuilder 
    override async findCertificatesAuth(auth: sdk.AuthId, args: sdk.FindCertificatesArgs): Promise<TableCertificateX[]> 
    override async findOutputBasketsAuth(auth: sdk.AuthId, args: sdk.FindOutputBasketsArgs): Promise<TableOutputBasket[]> 
    override async findOutputsAuth(auth: sdk.AuthId, args: sdk.FindOutputsArgs): Promise<TableOutput[]> 
    override async findCertificateFields(args: sdk.FindCertificateFieldsArgs): Promise<TableCertificateField[]> 
    override async findCertificates(args: sdk.FindCertificatesArgs): Promise<TableCertificateX[]> 
    override async findCommissions(args: sdk.FindCommissionsArgs): Promise<TableCommission[]> 
    override async findOutputBaskets(args: sdk.FindOutputBasketsArgs): Promise<TableOutputBasket[]> 
    override async findOutputs(args: sdk.FindOutputsArgs): Promise<TableOutput[]> 
    override async findOutputTagMaps(args: sdk.FindOutputTagMapsArgs): Promise<TableOutputTagMap[]> 
    override async findOutputTags(args: sdk.FindOutputTagsArgs): Promise<TableOutputTag[]> 
    override async findProvenTxReqs(args: sdk.FindProvenTxReqsArgs): Promise<TableProvenTxReq[]> 
    override async findProvenTxs(args: sdk.FindProvenTxsArgs): Promise<TableProvenTx[]> 
    override async findSyncStates(args: sdk.FindSyncStatesArgs): Promise<TableSyncState[]> 
    override async findTransactions(args: sdk.FindTransactionsArgs): Promise<TableTransaction[]> 
    override async findTxLabelMaps(args: sdk.FindTxLabelMapsArgs): Promise<TableTxLabelMap[]> 
    override async findTxLabels(args: sdk.FindTxLabelsArgs): Promise<TableTxLabel[]> 
    override async findUsers(args: sdk.FindUsersArgs): Promise<TableUser[]> 
    override async findMonitorEvents(args: sdk.FindMonitorEventsArgs): Promise<TableMonitorEvent[]> 
    async getCount<T extends object>(q: Knex.QueryBuilder<T, T[]>): Promise<number> 
    override async countCertificateFields(args: sdk.FindCertificateFieldsArgs): Promise<number> 
    override async countCertificates(args: sdk.FindCertificatesArgs): Promise<number> 
    override async countCommissions(args: sdk.FindCommissionsArgs): Promise<number> 
    override async countOutputBaskets(args: sdk.FindOutputBasketsArgs): Promise<number> 
    override async countOutputs(args: sdk.FindOutputsArgs): Promise<number> 
    override async countOutputTagMaps(args: sdk.FindOutputTagMapsArgs): Promise<number> 
    override async countOutputTags(args: sdk.FindOutputTagsArgs): Promise<number> 
    override async countProvenTxReqs(args: sdk.FindProvenTxReqsArgs): Promise<number> 
    override async countProvenTxs(args: sdk.FindProvenTxsArgs): Promise<number> 
    override async countSyncStates(args: sdk.FindSyncStatesArgs): Promise<number> 
    override async countTransactions(args: sdk.FindTransactionsArgs): Promise<number> 
    override async countTxLabelMaps(args: sdk.FindTxLabelMapsArgs): Promise<number> 
    override async countTxLabels(args: sdk.FindTxLabelsArgs): Promise<number> 
    override async countUsers(args: sdk.FindUsersArgs): Promise<number> 
    override async countMonitorEvents(args: sdk.FindMonitorEventsArgs): Promise<number> 
    override async destroy(): Promise<void> 
    override async migrate(storageName: string, storageIdentityKey: string): Promise<string> 
    override async dropAllData(): Promise<void> 
    override async transaction<T>(scope: (trx: sdk.TrxToken) => Promise<T>, trx?: sdk.TrxToken): Promise<T> 
    toDb(trx?: sdk.TrxToken) 
    async validateRawTransaction(t: TableTransaction, trx?: sdk.TrxToken): Promise<void> 
    async validateOutputScript(o: TableOutput, trx?: sdk.TrxToken): Promise<void> 
    _verifiedReadyForDatabaseAccess: boolean = false;
    async verifyReadyForDatabaseAccess(trx?: sdk.TrxToken): Promise<DBType> 
    validatePartialForUpdate<T extends sdk.EntityTimeStamp>(update: Partial<T>, dateFields?: string[], booleanFields?: string[]): Partial<T> 
    async validateEntityForInsert<T extends sdk.EntityTimeStamp>(entity: T, trx?: sdk.TrxToken, dateFields?: string[], booleanFields?: string[]): Promise<any> 
    override async getLabelsForTransactionId(transactionId?: number, trx?: sdk.TrxToken): Promise<TableTxLabel[]> 
    async extendOutput(o: TableOutput, includeBasket = false, includeTags = false, trx?: sdk.TrxToken): Promise<TableOutputX> 
    override async getTagsForOutputId(outputId: number, trx?: sdk.TrxToken): Promise<TableOutputTag[]> 
    override async purgeData(params: sdk.PurgeParams, trx?: sdk.TrxToken): Promise<sdk.PurgeResults> 
    override async reviewStatus(args: {
        agedLimit: Date;
        trx?: sdk.TrxToken;
    }): Promise<{
        log: string;
    }> 
    async countChangeInputs(userId: number, basketId: number, excludeSending: boolean): Promise<number> 
    async allocateChangeInput(userId: number, basketId: number, targetSatoshis: number, exactSatoshis: number | undefined, excludeSending: boolean, transactionId: number): Promise<TableOutput | undefined> {
        const status: sdk.TransactionStatus[] = ["completed", "unproven"];
        if (!excludeSending)
            status.push("sending");
        const statusText = status.map(s => `'${s}'`).join(",");
        const r: TableOutput | undefined = await this.knex.transaction(async (trx) => {
            const txStatusCondition = `AND (SELECT status FROM transactions WHERE outputs.transactionId = transactions.transactionId) in (${statusText})`;
            let outputId: number | undefined;
            const setOutputId = async (rawQuery: string): Promise<void> => {
                let oidr = await trx.raw(rawQuery);
                outputId = undefined;
                if (!oidr["outputId"] && oidr.length > 0)
                    oidr = oidr[0];
                if (!oidr["outputId"] && oidr.length > 0)
                    oidr = oidr[0];
                if (oidr["outputId"])
                    outputId = Number(oidr["outputId"]);
            };
            if (exactSatoshis !== undefined) {
                await setOutputId(`
                SELECT outputId 
                FROM outputs
                WHERE userId = ${userId} 
                    AND spendable = 1 
                    AND basketId = ${basketId}
                    ${txStatusCondition}
                    AND satoshis = ${exactSatoshis}
                LIMIT 1;
                `);
            }
            if (outputId === undefined) {
                await setOutputId(`
                    SELECT outputId 
                    FROM outputs
                    WHERE userId = ${userId} 
                        AND spendable = 1 
                        AND basketId = ${basketId}
                        ${txStatusCondition}
                        AND satoshis - ${targetSatoshis} = (
                            SELECT MIN(satoshis - ${targetSatoshis}) 
                            FROM outputs 
                            WHERE userId = ${userId} 
                            AND spendable = 1 
                            AND basketId = ${basketId}
                            ${txStatusCondition}
                            AND satoshis - ${targetSatoshis} >= 0
                        )
                    LIMIT 1;
                    `);
            }
            if (outputId === undefined) {
                await setOutputId(`
                    SELECT outputId 
                    FROM outputs
                    WHERE userId = ${userId} 
                        AND spendable = 1 
                        AND basketId = ${basketId}
                        ${txStatusCondition}
                        AND satoshis - ${targetSatoshis} = (
                            SELECT MAX(satoshis - ${targetSatoshis}) 
                            FROM outputs 
                            WHERE userId = ${userId} 
                            AND spendable = 1 
                            AND basketId = ${basketId}
                            ${txStatusCondition}
                            AND satoshis - ${targetSatoshis} < 0
                        )
                    LIMIT 1;
                    `);
            }
            if (outputId === undefined)
                return undefined;
            await this.updateOutput(outputId, {
                spendable: false,
                spentBy: transactionId
            }, trx);
            const r = verifyTruthy(await this.findOutputById(outputId, trx));
            return r;
        });
        return r;
    }
    validateEntity<T extends sdk.EntityTimeStamp>(entity: T, dateFields?: string[], booleanFields?: string[]): T 
    validateEntities<T extends sdk.EntityTimeStamp>(entities: T[], dateFields?: string[], booleanFields?: string[]): T[] 
}

See also: AuthId, DBType, EntityTimeStamp, FindCertificateFieldsArgs, FindCertificatesArgs, FindCommissionsArgs, FindForUserSincePagedArgs, FindMonitorEventsArgs, FindOutputBasketsArgs, FindOutputTagMapsArgs, FindOutputTagsArgs, FindOutputsArgs, FindPartialSincePagedArgs, FindProvenTxReqsArgs, FindProvenTxsArgs, FindSyncStatesArgs, FindTransactionsArgs, FindTxLabelMapsArgs, FindTxLabelsArgs, FindUsersArgs, ProvenOrRawTx, PurgeParams, PurgeResults, StorageKnexOptions, StorageProvider, TableCertificate, TableCertificateField, TableCertificateX, TableCommission, TableMonitorEvent, TableOutput, TableOutputBasket, TableOutputTag, TableOutputTagMap, TableOutputX, TableProvenTx, TableProvenTxReq, TableSettings, TableSyncState, TableTransaction, TableTxLabel, TableTxLabelMap, TableUser, TransactionStatus, TrxToken, ValidListActionsArgs, ValidListOutputsArgs, WalletStorageProvider, listActions, listOutputs, purgeData, reviewStatus, verifyTruthy

Method allocateChangeInput

Finds closest matching available change output to use as input for new transaction.

Transactionally allocate the output such that

async allocateChangeInput(userId: number, basketId: number, targetSatoshis: number, exactSatoshis: number | undefined, excludeSending: boolean, transactionId: number): Promise<TableOutput | undefined> 

See also: TableOutput

Method countChangeInputs

Finds closest matching available change output to use as input for new transaction.

Transactionally allocate the output such that

async countChangeInputs(userId: number, basketId: number, excludeSending: boolean): Promise<number> 
Method toDb

Convert the standard optional TrxToken parameter into either a direct knex database instance, or a Knex.Transaction as appropriate.

toDb(trx?: sdk.TrxToken) 

See also: TrxToken

Method validateEntities

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[], booleanFields?: string[]): T[] 

See also: EntityTimeStamp

Returns

input entities array with contained values validated.

Method validateEntity

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[], booleanFields?: string[]): T 

See also: EntityTimeStamp

Method validateEntityForInsert

Helper to force uniform behavior across database engines. Use to process new entities being inserted into the database.

async validateEntityForInsert<T extends sdk.EntityTimeStamp>(entity: T, trx?: sdk.TrxToken, dateFields?: string[], booleanFields?: string[]): Promise<any> 

See also: EntityTimeStamp, TrxToken

Method validatePartialForUpdate

Helper to force uniform behavior across database engines. Use to process the update template for entities being updated.

validatePartialForUpdate<T extends sdk.EntityTimeStamp>(update: Partial<T>, dateFields?: string[], booleanFields?: string[]): Partial<T> 

See also: EntityTimeStamp

Method verifyReadyForDatabaseAccess

Make sure database is ready for access:

async verifyReadyForDatabaseAccess(trx?: sdk.TrxToken): Promise<DBType> 

See also: DBType, TrxToken

Links: API, Interfaces, Classes, Functions, Types, Variables


Class: StorageProvider
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

Method confirmSpendableOutputs

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.

Method getProvenOrReq

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

Method getReqsAndBeefToShareWithWorld

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

Method updateProvenTxReqWithNewProvenTx

Handles storage changes when a valid MerklePath and mined block header are found for a ProvenTxReq txid.

Performs the following storage updates (typically):

  1. Lookup the exising ProvenTxReq record for its rawTx
  2. Insert a new ProvenTx record using properties from args and rawTx, yielding a new provenTxId
  3. Update ProvenTxReq record with status ‘completed’ and new provenTxId value (and history of status changed)
  4. Unpack notify transactionIds from req and update each transaction’s status to ‘completed’, provenTxId value.
  5. Update ProvenTxReq history again to record that transactions have been notified.
  6. Return results…

Alterations of “typically” to handle:

async updateProvenTxReqWithNewProvenTx(args: sdk.UpdateProvenTxReqWithNewProvenTxArgs): Promise<sdk.UpdateProvenTxReqWithNewProvenTxResult> 

See also: UpdateProvenTxReqWithNewProvenTxArgs, UpdateProvenTxReqWithNewProvenTxResult

Method updateTransactionStatus

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


Class: StorageReader

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

Method validateEntityDate

Force dates to strings on SQLite and Date objects on MySQL

validateEntityDate(date: Date | string | number): Date | string 
Method validateOptionalEntityDate
validateOptionalEntityDate(date: Date | string | number | null | undefined, useNowAsDefault?: boolean): Date | string | undefined 

Argument Details

Links: API, Interfaces, Classes, Functions, Types, Variables


Class: StorageReaderWriter
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


Class: StorageServer
export class StorageServer {
    constructor(storage: StorageProvider, options: WalletStorageServerOptions) 
    public start(): void 
    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: EntityTimeStamp, StorageProvider, WalletStorageServerOptions

Method validateEntities

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.

Method validateEntity

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


Class: StorageSyncReader

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


Class: WalletStorageManager

The WalletStorageManager class delivers authentication checking storage access to the wallet.

If manages multiple StorageBase derived storage services: one actice, the rest as backups.

Of the storage services, one is ‘active’ at any one time. On startup, and whenever triggered by the wallet, WalletStorageManager runs a syncrhonization sequence:

  1. While synchronizing, all other access to storage is blocked waiting.
  2. The active service is confirmed, potentially triggering a resolution process if there is disagreement.
  3. Changes are pushed from the active storage service to each inactive, backup service.

Some storage services do not support multiple writers. WalletStorageManager manages wait-blocking write requests for these services.

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

Property _active

The current active store which is only enabled if the store’s user record activeStorage property matches its settings record storageIdentityKey property

_active?: ManagedStorage
Property _authId

identityKey is always valid, userId and isActive are valid only if _isAvailable

_authId: sdk.AuthId

See also: AuthId

Property _backups

Stores to which state is pushed by updateBackups.

_backups?: ManagedStorage[]
Property _conflictingActives

Stores whose user record activeStorage property disagrees with the active store’s user record activeStorage property.

_conflictingActives?: ManagedStorage[]
Property _isAvailable

True if makeAvailable has been run and access to managed stores (active) is allowed

_isAvailable: boolean = false
Property _isSingleWriter

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
Property _readerCount

How many read access operations are pending

_readerCount: number = 0
Property _services

Configured services if any. If valid, shared with stores (which may ignore it).

_services?: sdk.WalletServices

See also: WalletServices

Property _storageProviderLocked

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
Property _stores

All configured stores including current active, backups, and conflicting actives.

_stores: ManagedStorage[] = []
Property _syncLocked

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
Property _writerCount

How many write access operations are pending

_writerCount: number = 0
Method canMakeAvailable
canMakeAvailable(): boolean 

Returns

true if at least one WalletStorageProvider has been added.

Method isActiveStorageProvider
isActiveStorageProvider(): boolean 

Returns

true if the active WalletStorageProvider also implements StorageProvider

Method makeAvailable

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.

Method runAsSync
async runAsSync<R>(sync: (active: sdk.WalletStorageSync) => Promise<R>, activeSync?: sdk.WalletStorageSync): Promise<R> 

See also: WalletStorageSync

Argument Details

Method setActive

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


Functions

     
attemptToPostReqsToNetwork listActions transactionInputSize
createAction listCertificates transactionOutputSize
createStorageServiceChargeScript listOutputs transactionSize
createSyncMap lockScriptWithKeyOffsetFromPubKey validateGenerateChangeSdkParams
generateChangeSdk offsetPubKey validateGenerateChangeSdkResult
generateChangeSdkMakeStorage processAction validateStorageFeeModel
getBeefForTransaction purgeData varUintSize
getSyncChunk reviewStatus  
internalizeAction setDisableDoubleSpendCheckForTest  

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: attemptToPostReqsToNetwork

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


Function: createAction
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


Function: createStorageServiceChargeScript
export function createStorageServiceChargeScript(pubKeyHex: PubKeyHex): {
    script: string;
    keyOffset: string;
} 

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: createSyncMap
export function createSyncMap(): SyncMap 

See also: SyncMap

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: generateChangeSdk

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


Function: generateChangeSdkMakeStorage
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


Function: getBeefForTransaction

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


Function: getSyncChunk

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


Function: internalizeAction

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:

  1. The “default” basket may not be specified as the insertion basket.
  2. A change output in the “default” basket may not be target of an insertion into a different basket.
  3. These baskets do not affect the wallet’s balance and are typed “custom”.

“wallet payment” Merge Rules:

  1. Targetting an existing change “default” basket output results in a no-op. No error. No alterations made.
  2. Targetting a previously “custom” non-change output converts it into a change output. This alters the transaction’s 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


Function: listActions
export async function listActions(storage: StorageKnex, auth: sdk.AuthId, vargs: sdk.ValidListActionsArgs): Promise<ListActionsResult> 

See also: AuthId, StorageKnex, ValidListActionsArgs

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: listCertificates
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


Function: listOutputs
export async function listOutputs(dsk: StorageKnex, auth: sdk.AuthId, vargs: sdk.ValidListOutputsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise<ListOutputsResult> 

See also: AuthId, StorageKnex, ValidListOutputsArgs

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: lockScriptWithKeyOffsetFromPubKey
export function lockScriptWithKeyOffsetFromPubKey(pubKey: string, keyOffset?: string): {
    script: string;
    keyOffset: string;
} 

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: offsetPubKey
export function offsetPubKey(pubKey: string, keyOffset?: string): {
    offsetPubKey: string;
    keyOffset: string;
} 

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: processAction
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


Function: purgeData
export async function purgeData(storage: StorageKnex, params: sdk.PurgeParams, trx?: sdk.TrxToken): Promise<sdk.PurgeResults> 

See also: PurgeParams, PurgeResults, StorageKnex, TrxToken

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: reviewStatus
export async function reviewStatus(storage: StorageKnex, args: {
    agedLimit: Date;
    trx?: sdk.TrxToken;
}): Promise<{
    log: string;
}> 

See also: StorageKnex, TrxToken

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: setDisableDoubleSpendCheckForTest
export function setDisableDoubleSpendCheckForTest(v: boolean) 

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: transactionInputSize
export function transactionInputSize(scriptSize: number): number 

Returns

serialized byte length a transaction input

Argument Details

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: transactionOutputSize
export function transactionOutputSize(scriptSize: number): number 

Returns

serialized byte length a transaction output

Argument Details

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: transactionSize

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


Function: validateGenerateChangeSdkParams
export function validateGenerateChangeSdkParams(params: GenerateChangeSdkParams): ValidateGenerateChangeSdkParamsResult 

See also: GenerateChangeSdkParams, ValidateGenerateChangeSdkParamsResult

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: validateGenerateChangeSdkResult
export function validateGenerateChangeSdkResult(params: GenerateChangeSdkParams, r: GenerateChangeSdkResult): {
    ok: boolean;
    log: string;
} 

See also: GenerateChangeSdkParams, GenerateChangeSdkResult

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: validateStorageFeeModel
export function validateStorageFeeModel(v?: sdk.StorageFeeModel): sdk.StorageFeeModel 

See also: StorageFeeModel

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: varUintSize

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


Types

 
DBType
EntityStorage
PostReqsToNetworkDetailsStatus

Links: API, Interfaces, Classes, Functions, Types, Variables


Type: DBType
export type DBType = "SQLite" | "MySQL"

Links: API, Interfaces, Classes, Functions, Types, Variables


Type: EntityStorage
export type EntityStorage = StorageProvider

See also: StorageProvider

Links: API, Interfaces, Classes, Functions, Types, Variables


Type: PostReqsToNetworkDetailsStatus

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


Variables

 
maxPossibleSatoshis
outputColumnsWithoutLockingScript
transactionColumnsWithoutRawTx

Links: API, Interfaces, Classes, Functions, Types, Variables


Variable: maxPossibleSatoshis
maxPossibleSatoshis = 2099999999999999

Links: API, Interfaces, Classes, Functions, Types, Variables


Variable: outputColumnsWithoutLockingScript
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


Variable: transactionColumnsWithoutRawTx
transactionColumnsWithoutRawTx = [
    "created_at",
    "updated_at",
    "transactionId",
    "userId",
    "provenTxId",
    "status",
    "reference",
    "isOutgoing",
    "satoshis",
    "version",
    "lockTime",
    "description",
    "txid"
]

Links: API, Interfaces, Classes, Functions, Types, Variables