Options
All
  • Public
  • Public/Protected
  • All
Menu

Class WalletBackend

The WalletBackend provides an interface that allows you to synchronize with a daemon, download blocks, process them, and pick out transactions that belong to you. It also allows you to inspect these transactions, view your balance, send transactions, and more.

Hierarchy

  • EventEmitter
    • WalletBackend

Index

Events

on

  • on(event: "transaction", callback: function): this
  • on(event: "incomingtx", callback: function): this
  • on(event: "outgoingtx", callback: function): this
  • on(event: "fusiontx", callback: function): this
  • on(event: "createdtx", callback: function): this
  • on(event: "createdfusiontx", callback: function): this
  • on(event: "sync", callback: function): this
  • on(event: "desync", callback: function): this
  • on(event: "disconnect", callback: function): this
  • on(event: "connect", callback: function): this
  • on(event: "heightchange", callback: function): this
  • on(event: "deadnode", callback: function): this
  • This is emitted whenever the wallet finds a new transaction.

    See the incomingtx and outgoingtx events if you need more fine grained control.

    Example:

    wallet.on('transaction', (transaction) => {
        console.log(`Transaction of ${transaction.totalAmount()} received!`);
    });

    Parameters

    • event: "transaction"
    • callback: function

    Returns this

  • This is emitted whenever the wallet finds an incoming transaction.

    Example:

    wallet.on('incomingtx', (transaction) => {
        console.log(`Incoming transaction of ${transaction.totalAmount()} received!`);
    });

    Parameters

    • event: "incomingtx"
    • callback: function

    Returns this

  • This is emitted whenever the wallet finds an outgoing transaction.

    Example:

    wallet.on('outgoingtx', (transaction) => {
        console.log(`Outgoing transaction of ${transaction.totalAmount()} received!`);
    });

    Parameters

    • event: "outgoingtx"
    • callback: function

    Returns this

  • This is emitted whenever the wallet finds a fusion transaction.

    Example:

    wallet.on('fusiontx', (transaction) => {
        console.log('Fusion transaction found!');
    });

    Parameters

    • event: "fusiontx"
    • callback: function

    Returns this

  • This is emitted whenever the wallet creates and sends a transaction.

    This is distinct from the outgoingtx event, as this event is fired when we send a transaction, while outgoingtx is fired when the tx is included in a block, and scanned by the wallet.

    Example:

    wallet.on('createdtx', (transaction) => {
         console.log('Transaction created!');
    });

    Parameters

    • event: "createdtx"
    • callback: function

    Returns this

  • This is emitted whenever the wallet creates and sends a fusion transaction.

    Example:

    wallet.on('createdfusiontx', (transaction) => {
         console.log('Fusion transaction created!');
    });

    Parameters

    • event: "createdfusiontx"
    • callback: function

    Returns this

  • This is emitted whenever the wallet first syncs with the network. It will also be fired if the wallet unsyncs from the network, then resyncs.

    Example:

    wallet.on('sync', (walletHeight, networkHeight) => {
        console.log(`Wallet synced! Wallet height: ${walletHeight}, Network height: ${networkHeight}`);
    });

    Parameters

    • event: "sync"
    • callback: function
        • (walletHeight: number, networkHeight: number): void
        • Parameters

          • walletHeight: number
          • networkHeight: number

          Returns void

    Returns this

  • This is emitted whenever the wallet first desyncs with the network. It will only be fired after the wallet has initially fired the sync event.

    Example:

    wallet.on('desync', (walletHeight, networkHeight) => {
        console.log(`Wallet is no longer synced! Wallet height: ${walletHeight}, Network height: ${networkHeight}`);
    });

    Parameters

    • event: "desync"
    • callback: function
        • (walletHeight: number, networkHeight: number): void
        • Parameters

          • walletHeight: number
          • networkHeight: number

          Returns void

    Returns this

  • This is emitted whenever the wallet fails to contact the underlying daemon. This event will only be emitted on the first disconnection. It will not be emitted again, until the daemon connects, and then disconnects again.

    Example:

    wallet.on('disconnect', (error) => {
        console.log('Possibly lost connection to daemon: ' + error.toString());
    });

    Note that these events will only be emitted if using the Daemon daemon type, as the other daemon types are considered legacy and are not having new features added.

    Parameters

    • event: "disconnect"
    • callback: function
        • (error: Error): void
        • Parameters

          • error: Error

          Returns void

    Returns this

  • This is emitted whenever the wallet previously failed to contact the underlying daemon, and has now reconnected. This event will only be emitted on the first connection. It will not be emitted again, until the daemon disconnects, and then reconnects again.

    Example:

    wallet.on('connect', () => {
        console.log('Regained connection to daemon!');
    });

    Note that these events will only be emitted if using the Daemon daemon type, as the other daemon types are considered legacy and are not having new features added.

    Parameters

    • event: "connect"
    • callback: function
        • (): void
        • Returns void

    Returns this

  • This is emitted whenever the walletBlockCount (Amount of blocks the wallet has synced), localDaemonBlockCount (Amount of blocks the daemon you're connected to has synced), or networkBlockCount (Amount of blocks the network has) changes.

    This can be used in place of repeatedly polling getSyncStatus

    Example:

    
    wallet.on('heightchange', (walletBlockCount, localDaemonBlockCount, networkBlockCount) => {
        console.log(`New sync status: ${walletBlockCount} / ${localDaemonBlockCount}`);
    });

    Parameters

    • event: "heightchange"
    • callback: function
        • (walletBlockCount: number, localDaemonBlockCount: number, networkBlockCount: number): void
        • Parameters

          • walletBlockCount: number
          • localDaemonBlockCount: number
          • networkBlockCount: number

          Returns void

    Returns this

  • This is emitted when we consider the node to no longer be online. There are a few categories we use to determine this.

    1) We have not recieved any data from /getwalletsyncdata since the configured timeout. (Default 3 mins)

    2) The network height has not changed since the configured timeout (Default 3 mins)

    3) The local daemon height has not changed since the configured timeout (Default 3 mins)

    Example:

    wallet.on('deadnode', () => {
        console.log('Ruh roh, looks like the daemon is dead.. maybe you want to swapNode()?');
    });

    Parameters

    • event: "deadnode"
    • callback: function
        • (): void
        • Returns void

    Returns this

Methods

addSubWallet

  • addSubWallet(): [undefined, WalletError] | [string, undefined]
  • Adds a subwallet to the wallet container. Must not be used on a view only wallet. For more information on subwallets, see https://docs.zent.cash/developer/subwallets

    Example:

    const [address, error] = wallet.addSubWallet();
    
    if (!error) {
         console.log(`Created subwallet with address of ${address}`);
    }

    Returns [undefined, WalletError] | [string, undefined]

    Returns the newly created address or an error.

deletePreparedTransaction

  • deletePreparedTransaction(transactionHash: string): boolean
  • Delete a prepared transaction stored to free up RAM. Returns whether the transaction was found and has been removed, or false if it was not found.

    Example:

    const destinations = [
         ['Zexyz...', 1000],
         ['Zezyx...', 10000],
    ];
    
    const creation = await wallet.sendTransactionAdvanced(
         destinations,
         undefined, // mixin
         undefined, // fee
         undefined, // payment ID
         undefined, // subWalletsToTakeFrom
         undefined, // changeAddress
         false // relay to network
    );
    
    if (creation.success)
         // Inspect certain transaction properties before sending if desired
         if (creation.fee > 100000) {
             console.log('Fee is quite high! You may wish to attempt optimizing your wallet');
             return;
         }
    
         const result = await wallet.sendRawPreparedTransaction(creation.preparedTransaction);
    
         if (result.success) {
             console.log(`Sent transaction, hash ${result.transactionHash}, fee ${WB.prettyPrintAmount(result.fee)}`);
         } else {
             console.log(`Failed to relay transaction: ${result.error.toString()}`);
         }
    } else {
         console.log(`Failed to send transaction: ${creation.error.toString()}`);
         wallet.deletePreparedTransaction(creation.transactionHash);
    }

    Parameters

    • transactionHash: string

    Returns boolean

deleteSubWallet

  • Removes the subwallet specified from the wallet container. If you have not backed up the private keys for this subwallet, all funds in it will be lost.

    Example:

    const error = wallet.deleteSubWallet('Ze3GSL9kqRAHteE7P2R5ue4Jj2ZHiDj4qi1BXvrU4GnYLbDn4cEuSn4N7mdLmqBhErGo99MaRVJEzhyUpoMwMEp122fubUUCW');
    
    if (error) {
         console.log(`Failed to delete subwallet: ${error.toString()}`);
    }

    Parameters

    • address: string

      The subwallet address to remove

    Returns WalletError

enableAutoOptimization

  • enableAutoOptimization(shouldAutoOptimize: boolean): void
  • This flag will automatically send fusion transactions when needed to keep your wallet permanently optimized.

    The downsides are that sometimes your wallet will 'unexpectedly' have locked funds.

    The upside is that when you come to sending a large transaction, it should nearly always succeed.

    This flag is ENABLED by default.

    Example:

    wallet.enableAutoOptimization(false);

    Parameters

    • shouldAutoOptimize: boolean

      Should we automatically keep the wallet optimized?

    Returns void

encryptWalletToString

  • encryptWalletToString(password: string): string
  • Encrypt the wallet using the given password. Password may be empty. Note that an empty password does not mean an unencrypted wallet - simply a wallet encrypted with the empty string.

    This will take some time (Roughly a second on a modern PC) - it runs 500,000 iterations of pbkdf2.

    Example:

    const saved = wallet.encryptWalletToString('hunter2');
    

    Parameters

    • password: string

      The password to encrypt the wallet with

    Returns string

    Returns the encrypted wallet as astring.

getAddresses

  • getAddresses(): string[]
  • Gets the address of every subwallet in this container.

    Example:

    let i = 1;
    
    for (const address of wallet.getAddresses()) {
         console.log(`Address [${i}]: ${address}`);
         i++;
    }

    Returns string[]

getBalance

  • getBalance(subWalletsToTakeFrom?: string[]): [number, number]
  • Get the unlocked and locked balance for the wallet container.

    Example:

    const [unlockedBalance, lockedBalance] = wallet.getBalance();

    Parameters

    • Optional subWalletsToTakeFrom: string[]

      The addresses to check the balance of. If not given, defaults to all addresses.

    Returns [number, number]

getDaemonConnectionInfo

  • Gets information on the currently connected daemon - It's host, port, daemon type, and ssl presence. This can be helpful if you are taking arbitary host/port from a user, and wish to display the daemon type they are connecting to once we have figured it out. Note that the ssl and daemonType variables may have not been determined yet - If you have not awaited start yet, or if the daemon is having connection issues.

    For this reason, there are two additional properties - sslDetermined, and daemonTypeDetermined which let you verify that we have managed to contact the daemon and detect its specifics.

    Example:

    const daemonInfo = wallet.getDaemonConnectionInfo();
    console.log(`Connected to ${daemonInfo.ssl ? 'https://' : 'http://'}${daemonInfo.host}:${daemonInfo.port}`);

    Returns DaemonConnection

getMnemonicSeed

  • getMnemonicSeed(): [undefined, WalletError] | [string, undefined]
  • Get the primary address mnemonic seed. If the primary address isn't a deterministic wallet, it will return a WalletError.

    Example:

    const [seed, err] = wallet.getMnemonicSeed();
    
    if (err) {
         console.log('Wallet is not a deterministic wallet: ' + err.toString());
    }

    Returns [undefined, WalletError] | [string, undefined]

getMnemonicSeedForAddress

  • getMnemonicSeedForAddress(address: string): [undefined, WalletError] | [string, undefined]
  • Get the mnemonic seed for the specified address. If the specified address is invalid or the address isn't a deterministic wallet, it will return a WalletError.

    Example:

    const [seed, err] = wallet.getMnemonicSeedForAddress('Ze...');
    
    if (err) {
         console.log('Address does not belong to a deterministic wallet: ' + err.toString());
    }

    Parameters

    • address: string

      A valid address that exists in this container

    Returns [undefined, WalletError] | [string, undefined]

getNodeFee

  • getNodeFee(): [string, number]
  • Get the node fee the daemon you are connected to is charging for transactions. If the daemon charges no fee, this will return ['', 0]

    Fees returned will be zero if you have not yet awaited start.

    Example:

    const [nodeFeeAddress, nodeFeeAmount] = wallet.getNodeFee();
    
    if (nodeFeeAmount === 0) {
         console.log('Yay, no fees!');
    }

    Returns [string, number]

getNumTransactions

  • getNumTransactions(subWallet?: undefined | string, includeFusions?: boolean): number
  • Get the number of transactions belonging to the given subWallet. If no subWallet is given, gets the total number of transactions in the wallet container. Can be used if you want to avoid fetching all transactions repeatedly when nothing has changed.

    Note that it probably is more effective to subscribe to the transaction related events to update your UI, rather than polling for the number of transactions.

    Example:

    let numTransactions = 0;
    
    while (true) {
         const tmpNumTransactions = wallet.getNumTransactions();
    
         if (numTransactions != tmpNumTransactions) {
             console.log(tmpNumTransactions - numTransactions + ' new transactions found!');
             numTransactions = tmpNumTransactions;
         }
    }

    Parameters

    • Optional subWallet: undefined | string

      Should we only count transactions of the specified subWallet?

    • Default value includeFusions: boolean = true

      Should we count fusion transactions? Defaults to true.

    Returns number

getPrimaryAddress

  • getPrimaryAddress(): string
  • Gets the primary address of a wallet container. The primary address is the address that was created first in the wallet container.

    Example:

    const address = wallet.getPrimaryAddress();

    Returns string

getPrimaryAddressPrivateKeys

  • getPrimaryAddressPrivateKeys(): [string, string]
  • Gets the private spend and private view for the primary address. The primary address is the first created wallet in the container.

    Example:

    const [privateSpendKey, privateViewKey] = wallet.getPrimaryAddressPrivateKeys();

    Returns [string, string]

getPrivateViewKey

  • getPrivateViewKey(): string
  • Gets the shared private view key for this wallet container.

    Example:

    const privateViewKey = wallet.getPrivateViewKey();

    Returns string

getSpendKeys

  • getSpendKeys(address: string): [string, string, undefined] | [undefined, undefined, WalletError]
  • Gets the publicSpendKey and privateSpendKey for the given address, if possible.

    Note: secret key will be 00000... (64 zeros) if this wallet is a view only wallet.

    Example:

    const [publicSpendKey, privateSpendKey, err] = wallet.getSpendKeys('Zexyz...');
    
    if (err) {
         console.log('Failed to get spend keys for address: ' + err.toString());
    }

    Parameters

    • address: string

      A valid address in this container, to get the spend keys of

    Returns [string, string, undefined] | [undefined, undefined, WalletError]

getSyncStatus

  • getSyncStatus(): [number, number, number]
  • Gets the wallet, local daemon, and network block count

    Example:

    const [walletBlockCount, localDaemonBlockCount, networkBlockCount] =
         wallet.getSyncStatus();

    Returns [number, number, number]

getTransaction

  • getTransaction(hash: string): Transaction | undefined
  • Gets the specified transaction, if it exists in this wallet container.

    Example:

    const tx = wallet.getTransaction('693950eeec41dc36cfc5109eba15807ce3d63eff21f1eec20a7d1bda99563b1c');
    
    if (tx) {
         console.log(`Tx ${tx.hash} is worth ${WB.prettyPrintAmount(tx.totalAmount())}`);
    } else {
         console.log("Couldn't find transaction! Is your wallet synced?");
    }

    Parameters

    • hash: string

      The hash of the transaction to get

    Returns Transaction | undefined

getTransactions

  • getTransactions(startIndex?: undefined | number, numTransactions?: undefined | number, includeFusions?: boolean, subWallet?: undefined | string): Transaction[]
  • Gets all the transactions in the wallet container unless a subWallet address is specified, in which case we get only the transactions for that subWallet.

    Newer transactions are at the front of the array - Unconfirmed transactions come at the very front.

    Example:

    for (const tx of wallet.getTransactions()) {
         console.log(`Transaction ${tx.hash} - ${WB.prettyPrintAmount(tx.totalAmount())} - ${tx.timestamp}`);
    }

    Parameters

    • Optional startIndex: undefined | number

      Index to start taking transactions from

    • Optional numTransactions: undefined | number

      Number of transactions to take

    • Default value includeFusions: boolean = true

      Should we include fusion transactions?

    • Optional subWallet: undefined | string

      Should we only include transactions of the specified subWallet?

    Returns Transaction[]

getWalletCount

  • getWalletCount(): number
  • Returns the number of subwallets in this wallet.

    Example:

    const count = wallet.getWalletCount();
    
    console.log(`Wallet has ${count} subwallets`);

    Returns number

importSubWallet

  • importSubWallet(privateSpendKey: string, scanHeight?: undefined | number): Promise<[undefined, WalletError] | [string, undefined]>
  • Imports a subwallet to the wallet container. Must not be used on a view only wallet. For more information on subwallets, see https://docs.zent.cash/developer/subwallets

    Example:

    const [address, error] = await wallet.importSubWallet('c984628484a1a5eaab4cfb63831b2f8ac8c3a56af2102472ab35044b46742501');
    
    if (!error) {
         console.log(`Imported subwallet with address of ${address}`);
    } else {
         console.log(`Failed to import subwallet: ${error.toString()}`);
    }

    Parameters

    • privateSpendKey: string

      The private spend key of the subwallet to import

    • Optional scanHeight: undefined | number

      The scan height to start scanning this subwallet from. If the scan height is less than the wallets current height, the entire wallet will be rewound to that height, and will restart syncing. If not specified, this defaults to the current height.

    Returns Promise<[undefined, WalletError] | [string, undefined]>

    Returns the newly created address or an error.

importViewSubWallet

  • importViewSubWallet(publicSpendKey: string, scanHeight?: undefined | number): Promise<[undefined, WalletError] | [string, undefined]>
  • Imports a view only subwallet to the wallet container. Must not be used on a non view wallet. For more information on subwallets, see https://docs.zent.cash/developer/subwallets

    Example:

    const [address, error] = await wallet.importViewSubWallet('c984628484a1a5eaab4cfb63831b2f8ac8c3a56af2102472ab35044b46742501');
    
    if (!error) {
         console.log(`Imported view subwallet with address of ${address}`);
    } else {
         console.log(`Failed to import view subwallet: ${error.toString()}`);
    }

    Parameters

    • publicSpendKey: string

      The public spend key of the subwallet to import

    • Optional scanHeight: undefined | number

      The scan height to start scanning this subwallet from. If the scan height is less than the wallets current height, the entire wallet will be rewound to that height, and will restart syncing. If not specified, this defaults to the current height.

    Returns Promise<[undefined, WalletError] | [string, undefined]>

    Returns the newly created address or an error.

internal

  • internal(): object
  • Exposes some internal functions for those who know what they're doing...

    Example:

    const syncFunc = wallet.internal().sync;
    await syncFunc(true);

    Returns object

    Returns an object with two members, sync(), and updateDaemonInfo().

optimize

  • optimize(): Promise<[number, string[]]>
  • Optimizes your wallet as much as possible. It will optimize every single subwallet correctly, if you have multiple subwallets. Note that this method does not wait for the funds to return to your wallet before returning, so, it is likely balances will remain locked.

    Note that if you want to alert the user in real time of the hashes or number of transactions sent, you can subscribe to the createdfusiontx event. This will be fired every time a fusion transaction is sent.

    You may also want to consider manually creating individual transactions if you want more control over the process. See sendFusionTransactionBasic.

    This method may take a very long time if your wallet is not optimized at all. It is suggested to not block the UI/mainloop of your program when using this method.

    Example:

    const [numberOfTransactionsSent, hashesOfSentFusionTransactions] = await wallet.optimize();
    
    console.log(`Sent ${numberOfTransactionsSent} fusion transactions, hashes: ${hashesOfSentFusionTransactions.join(', ')}`);

    Returns Promise<[number, string[]]>

rescan

  • rescan(): Promise<void>
  • Performs the same operation as reset(), but uses the initial scan height or timestamp. For example, if you created your wallet at block 800,000, this method would start rescanning from then.

    This function will return once the wallet has been successfully reset, and syncing has began again.

    Example:

    await wallet.rescan();

    Returns Promise<void>

reset

  • reset(scanHeight?: number, scanTimestamp?: number): Promise<void>
  • Discard all transaction data, and begin scanning the wallet again from the scanHeight or timestamp given. Defaults to a height of zero, if not given.

    This function will return once the wallet has been successfully reset, and syncing has began again.

    Example:

    await wallet.reset(123456);

    Parameters

    • Default value scanHeight: number = 0

      The scan height to begin scanning transactions from

    • Default value scanTimestamp: number = 0

    Returns Promise<void>

rewind

  • rewind(scanHeight?: number): Promise<void>
  • This function works similarly to both reset and rescan.

    The difference is that while reset and rescan discard all progress before the specified height, and then continues syncing from there, rewind instead retains the information previous, and only removes information after the rewind height.

    This can be helpful if you suspect a transaction has been missed by the sync process, and want to only rescan a small section of blocks.

    Example:

    await wallet.rewind(123456);

    Parameters

    • Default value scanHeight: number = 0

      The scan height to rewind to

    Returns Promise<void>

saveWalletToFile

  • saveWalletToFile(filename: string, password: string): boolean
  • Save the wallet to the given filename. Password may be empty, but filename must not be. Note that an empty password does not mean an unencrypted wallet - simply a wallet encrypted with the empty string.

    This will take some time (Roughly a second on a modern PC) - it runs 500,000 iterations of pbkdf2.

    Example:

    const saved = wallet.saveWalletToFile('test.wallet', 'hunter2');
    
    if (!saved) {
         console.log('Failed to save wallet!');
    }

    Parameters

    • filename: string

      The file location to save the wallet to.

    • password: string

      The password to encrypt the wallet with

    Returns boolean

    Returns a boolean indicating success.

scanCoinbaseTransactions

  • scanCoinbaseTransactions(shouldScan: boolean): void
  • Most people don't mine blocks, so by default we don't scan them. If you want to scan them, flip it on/off here.

    Example:

    wallet.scanCoinbaseTransactions(true);

    Parameters

    • shouldScan: boolean

      Should we scan coinbase transactions?

    Returns void

sendFusionTransactionAdvanced

  • sendFusionTransactionAdvanced(mixin?: undefined | number, subWalletsToTakeFrom?: string[], destination?: undefined | string): Promise<SendTransactionResult>
  • Sends a fusion transaction, if possible. Fusion transactions are zero fee, and optimize your wallet for sending larger amounts. You may (probably will) need to perform multiple fusion transactions.

    If you want to ensure your wallet gets fully optimized, consider using optimize.

    All parameters are optional.

    Example:

    const result = await wallet.sendFusionTransactionAdvanced(3, undefined, 'Zexyz..');
    
    if (result.success) {
         console.log(`Sent transaction, hash ${result.transactionHash}, fee ${WB.prettyPrintAmount(result.fee)}`);
    } else {
         console.log(`Failed to send transaction: ${result.error.toString()}`);
    }

    Parameters

    • Optional mixin: undefined | number

      The amount of input keys to hide your input with. Your network may enforce a static mixin.

    • Optional subWalletsToTakeFrom: string[]

      The addresses of the subwallets to draw funds from.

    • Optional destination: undefined | string

      The destination for the fusion transaction to be sent to. Must be an address existing in this container.

    Returns Promise<SendTransactionResult>

sendFusionTransactionBasic

  • Sends a fusion transaction, if possible. Fusion transactions are zero fee, and optimize your wallet for sending larger amounts. You may (probably will) need to perform multiple fusion transactions.

    If you want to ensure your wallet gets fully optimized, consider using optimize.

    Example:

    const result = await wallet.sendFusionTransactionBasic();
    
    if (result.success) {
         console.log(`Sent transaction, hash ${result.transactionHash}`);
    } else {
         console.log(`Failed to send transaction: ${result.error.toString()}`);
    }

    Returns Promise<SendTransactionResult>

sendPreparedTransaction

  • Relays a previously prepared transaction to the network.

    Example:

    const destinations = [
         ['Zexyz...', 1000],
         ['Zezyx...', 10000],
    ];
    
    const creation = await wallet.sendTransactionAdvanced(
         destinations,
         undefined, // mixin
         undefined, // fee
         undefined, // payment ID
         undefined, // subWalletsToTakeFrom
         undefined, // changeAddress
         false // relay to network
    );
    
    if (creation.success)
         // Inspect certain transaction properties before sending if desired
         if (creation.fee > 100000) {
             console.log('Fee is quite high! You may wish to attempt optimizing your wallet');
             return;
         }
    
         const result = await wallet.sendPreparedTransaction(creation.transactionHash);
    
         if (result.success) {
             console.log(`Sent transaction, hash ${result.transactionHash}, fee ${WB.prettyPrintAmount(result.fee)}`);
         } else {
             console.log(`Failed to relay transaction: ${result.error.toString()}`);
         }
    } else {
         wallet.deletePreparedTransaction(creation.transactionHash);
         console.log(`Failed to send transaction: ${creation.error.toString()}`);
    }
    

    Parameters

    • transactionHash: string

    Returns Promise<SendTransactionResult>

sendRawPreparedTransaction

  • Relays a previously prepared transaction to the network. Data can be stored client side if you wish for prepared transactions to still be usable after restarting the wallet app, for example.

    Example:

    const destinations = [
         ['Zexyz...', 1000],
         ['Zezyx...', 10000],
    ];
    
    const creation = await wallet.sendTransactionAdvanced(
         destinations,
         undefined, // mixin
         undefined, // fee
         undefined, // payment ID
         undefined, // subWalletsToTakeFrom
         undefined, // changeAddress
         false // relay to network
    );
    
    if (creation.success)
         // Inspect certain transaction properties before sending if desired
         if (creation.fee > 100000) {
             console.log('Fee is quite high! You may wish to attempt optimizing your wallet');
             return;
         }
    
         const result = await wallet.sendRawPreparedTransaction(creation.preparedTransaction);
    
         if (result.success) {
             console.log(`Sent transaction, hash ${result.transactionHash}, fee ${WB.prettyPrintAmount(result.fee)}`);
         } else {
             console.log(`Failed to relay transaction: ${result.error.toString()}`);
         }
    } else {
         console.log(`Failed to send transaction: ${creation.error.toString()}`);
         wallet.deletePreparedTransaction(creation.transactionHash);
    }
    

    Parameters

    Returns Promise<SendTransactionResult>

sendTransactionAdvanced

  • sendTransactionAdvanced(destinations: Array<[string, number]>, mixin?: undefined | number, fee?: FeeType, paymentID?: undefined | string, subWalletsToTakeFrom?: string[], changeAddress?: undefined | string, relayToNetwork?: undefined | false | true, sendAll?: undefined | false | true): Promise<SendTransactionResult>
  • Sends a transaction, which permits multiple amounts to different destinations, specifying the mixin, fee, subwallets to draw funds from, and change address.

    All parameters are optional aside from destinations.

    Example:

    const destinations = [
         ['Zexyz...', 1000],
         ['Zezyx...', 10000],
    ];
    
    const result = await wallet.sendTransactionAdvanced(
         destinations,
         undefined,
         undefined,
         'c59d157d1d96f280ece0816a8925cae8232432b7235d1fa92c70faf3064434b3'
    );
    
    if (result.success) {
         console.log(`Sent transaction, hash ${result.transactionHash}, fee ${WB.prettyPrintAmount(result.fee)}`);
    } else {
         console.log(`Failed to send transaction: ${result.error.toString()}`);
    }

    Parameters

    • destinations: Array<[string, number]>

      An array of destinations, and amounts to send to that destination. Amounts are in ATOMIC units.

    • Optional mixin: undefined | number

      The amount of input keys to hide your input with. Your network may enforce a static mixin.

    • Optional fee: FeeType

      The network fee, fee per byte, or minimum fee to use with this transaction. Defaults to minimum fee.

    • Optional paymentID: undefined | string

      The payment ID to include with this transaction. Defaults to none.

    • Optional subWalletsToTakeFrom: string[]

      The addresses of the subwallets to draw funds from. Defaults to all addresses.

    • Optional changeAddress: undefined | string

      The address to send any returned change to. Defaults to the primary address.

    • Optional relayToNetwork: undefined | false | true

      Whether we should submit the transaction to the network or not. If set to false, allows you to review the transaction fee before sending it. Use sendPreparedTransaction to send a transaction that you have not relayed to the network. Defaults to true.

    • Optional sendAll: undefined | false | true

      Whether we should send the entire balance available. Since fee per byte means estimating fees is difficult, we can handle that process on your behalf. The entire balance minus fees will be sent to the first destination address. The amount given in the first destination address will be ignored. Any following destinations will have the given amount sent. For example, if your destinations array was [['address1', 0], ['address2', 50], ['address3', 100]] Then address2 would be sent 50, address3 would be sent 100, and address1 would get whatever remains of the balance after paying node/network fees. Defaults to false.

    Returns Promise<SendTransactionResult>

sendTransactionBasic

  • sendTransactionBasic(destination: string, amount: number, paymentID?: undefined | string): Promise<SendTransactionResult>
  • Sends a transaction of amount to the address destination, using the given payment ID, if specified.

    Network fee is set to default, mixin is set to default, all subwallets are taken from, primary address is used as change address.

    If you need more control, use sendTransactionAdvanced.

    Example:

    const result = await wallet.sendTransactionBasic('Zexyz...', 1234);
    
    if (result.success) {
         console.log(`Sent transaction, hash ${result.transactionHash}, fee ${WB.prettyPrintAmount(result.fee)}`);
    } else {
         console.log(`Failed to send transaction: ${result.error.toString()}`);
    }

    Parameters

    • destination: string

      The address to send the funds to

    • amount: number

      The amount to send, in ATOMIC units

    • Optional paymentID: undefined | string

      The payment ID to include with this transaction. Optional.

    Returns Promise<SendTransactionResult>

    Returns either an error, or the transaction hash.

setBlockOutputProcessFunc

  • setBlockOutputProcessFunc(func: function): void
  • Provide a function to process blocks instead of the inbuilt one. The only use for this is to leverage native code to provide quicker cryptography functions - the default JavaScript is not that speedy.

    Note that if you're in a node environment, this library will use C++ code with node-gyp, so it will be nearly as fast as C++ implementations. You only need to worry about this in less conventional environments, like react-native, or possibly the web.

    If you don't know what you're doing, DO NOT TOUCH THIS - YOU WILL BREAK WALLET SYNCING

    Note you don't have to set the globalIndex properties on returned inputs. We will fetch them from the daemon if needed. However, if you have them, return them, to save us a daemon call.

    Your function should return an array of [publicSpendKey, TransactionInput]. The public spend key is the corresponding subwallet that the transaction input belongs to.

    Return an empty array if no inputs are found that belong to the user.

    Example:

    wallet.setBlockOutputProcessFunc(mySuperSpeedyFunction);

    Parameters

    • func: function

      The function to process block outputs.

        • (block: Block, privateViewKey: string, spendKeys: Array<[string, string]>, isViewWallet: boolean, processCoinbaseTransactions: boolean): Array<[string, TransactionInput]>
        • Parameters

          • block: Block

            The block to be processed.

          • privateViewKey: string

            The private view key of this wallet container.

          • spendKeys: Array<[string, string]>

            An array of [publicSpendKey, privateSpendKey]. These are the spend keys of each subwallet.

          • isViewWallet: boolean

            Whether this wallet is a view only wallet or not.

          • processCoinbaseTransactions: boolean

            Whether you should process coinbase transactions or not.

          Returns Array<[string, TransactionInput]>

    Returns void

setLogLevel

  • Sets the log level. Log messages below this level are not shown.

    Logging by default occurs to stdout. See setLoggerCallback to modify this, or gain more control over what is logged.

    Example:

    wallet.setLogLevel(WB.LogLevel.DEBUG);

    Parameters

    • logLevel: LogLevel

      The level to log messages at.

    Returns void

setLoggerCallback

  • setLoggerCallback(callback: function): void
  • Sets a callback to be used instead of console.log for more fined control of the logging output.

    Ensure that you have enabled logging for this function to take effect. See setLogLevel for more details.

    Example:

    wallet.setLoggerCallback((prettyMessage, message, level, categories) => {
          if (categories.includes(WB.LogCategory.SYNC)) {
              console.log(prettyMessage);
          }
      });

    Parameters

    • callback: function

      The callback to use for log messages

        • Parameters

          • prettyMessage: string

            A nicely formatted log message, with timestamp, levels, and categories

          • message: string

            The raw log message

          • level: LogLevel

            The level at which the message was logged at

          • categories: LogCategory[]

            The categories this log message falls into

          Returns any

    Returns void

start

  • start(): Promise<void>
  • Initializes and starts the wallet sync process. You should call this function before enquiring about daemon info or fee info. The wallet will not process blocks until you call this method.

    Example:

    await wallet.start();

    Returns Promise<void>

stop

  • stop(): Promise<void>
  • The inverse of the start method, this pauses the blockchain sync process.

    If you want the node process to close cleanly (i.e, without using process.exit()), you need to call this function. Otherwise, the library will keep firing callbacks, and so your script will hang.

    Example:

    wallet.stop();

    Returns Promise<void>

swapNode

  • swapNode(newDaemon: IDaemon): Promise<void>
  • Swaps the currently connected daemon with a different one. If the wallet is currently started, it will remain started after the node is swapped, if it is currently stopped, it will remain stopped.

    Example:

    const daemon = new WB.Daemon('seedpro2.zent.cash', 21698);
    await wallet.swapNode(daemon);
    const daemonInfo = wallet.getDaemonConnectionInfo();
    console.log(`Connected to ${daemonInfo.ssl ? 'https://' : 'http://'}${daemonInfo.host}:${daemonInfo.port}`);

    Parameters

    Returns Promise<void>

toJSONString

  • toJSONString(): string
  • Converts the wallet into a JSON string. This can be used to later restore the wallet with loadWalletFromJSON.

    Example:

    const walletData = wallet.toJSONString();

    Returns string

Static createWallet

  • This method creates a new wallet instance with a random key pair.

    Example:

    const WB = require('zentcash-wallet-backend');
    
    const daemon = new WB.Daemon('127.0.0.1', 21698);
    
    const wallet = WB.WalletBackend.createWallet(daemon);

    Parameters

    • daemon: IDaemon

      An implementation of the IDaemon interface.

    • Optional config: IConfig

    Returns WalletBackend

Static importViewWallet

  • This method imports a wallet you have previously created, in a 'watch only' state. This wallet can view incoming transactions, but cannot send transactions. It also cannot view outgoing transactions, so balances may appear incorrect. This is useful for viewing your balance whilst not risking your funds or private keys being stolen.

    Example:

    const WB = require('zentcash-wallet-backend');
    
    const daemon = new WB.Daemon('127.0.0.1', 21698);
    
    const privateViewKey = 'ce4c27d5b135dc5310669b35e53efc9d50d92438f00c76442adf8c85f73f1a01';
    
    const address = 'Ze3GSL9kqRAHteE7P2R5ue4Jj2ZHiDj4qi1BXvrU4GnYLbDn4cEuSn4N7mdLmqBhErGo99MaRVJEzhyUpoMwMEp122fubUUCW';
    
    const [wallet, err] = WB.WalletBackend.importViewWallet(daemon, 100000, privateViewKey, address);
    
    if (err) {
         console.log('Failed to load wallet: ' + err.toString());
    }

    Parameters

    • daemon: IDaemon

      An implementation of the IDaemon interface.

    • Default value scanHeight: number = 0

      The height to begin scanning the blockchain from. This can greatly increase sync speeds if given. Defaults to zero.

    • privateViewKey: string

      The private view key of this view wallet. Should be a 64 char hex string.

    • address: string

      The public address of this view wallet.

    • Optional config: IConfig

    Returns [WalletBackend, undefined] | [undefined, WalletError]

Static importWalletFromKeys

  • Imports a wallet from a pair of private keys.

    Example:

    const WB = require('zentcash-wallet-backend');
    
    const daemon = new WB.Daemon('127.0.0.1', 21698);
    
    const privateViewKey = 'ce4c27d5b135dc5310669b35e53efc9d50d92438f00c76442adf8c85f73f1a01';
    const privateSpendKey = 'f1b1e9a6f56241594ddabb243cdb39355a8b4a1a1c0343dde36f3b57835fe607';
    
    const [wallet, err] = WB.WalletBackend.importWalletFromSeed(daemon, 100000, privateViewKey, privateSpendKey);
    
    if (err) {
         console.log('Failed to load wallet: ' + err.toString());
    }

    Parameters

    • daemon: IDaemon

      An implementation of the IDaemon interface.

    • Default value scanHeight: number = 0

      The height to begin scanning the blockchain from. This can greatly increase sync speeds if given. Defaults to zero.

    • privateViewKey: string

      The private view key to import. Should be a 64 char hex string.

    • privateSpendKey: string

      The private spend key to import. Should be a 64 char hex string.

    • Optional config: IConfig

    Returns [WalletBackend, undefined] | [undefined, WalletError]

Static importWalletFromSeed

  • Imports a wallet from a 25 word mnemonic seed.

    Example:

    const WB = require('zentcash-wallet-backend');
    
    const daemon = new WB.Daemon('127.0.0.1', 21698);
    
    const seed = 'necklace went vials phone both haunted either eskimos ' +
                 'dialect civilian western dabbing snout rustled balding ' +
                 'puddle looking orbit rest agenda jukebox opened sarcasm ' +
                 'solved eskimos';
    
    const [wallet, err] = WB.WalletBackend.importWalletFromSeed(daemon, 100000, seed);
    
    if (err) {
         console.log('Failed to load wallet: ' + err.toString());
    }

    Parameters

    • daemon: IDaemon

      An implementation of the IDaemon interface.

    • Default value scanHeight: number = 0

      The height to begin scanning the blockchain from. This can greatly increase sync speeds if given. Defaults to zero if not given.

    • mnemonicSeed: string

      The mnemonic seed to import. Should be a 25 word string.

    • Optional config: IConfig

    Returns [WalletBackend, undefined] | [undefined, WalletError]

Static loadWalletFromJSON

  • Loads a wallet from a JSON encoded string. For the correct format for the JSON to use, see https://github.com/ZentCashFoundation/wallet-file-interaction

    You can obtain this JSON using toJSONString.

    Example:

    const WB = require('zentcash-wallet-backend');
    
    const daemon = new WB.Daemon('127.0.0.1', 21698);
    
    const [wallet, err] = WB.WalletBackend.loadWalletFromJSON(daemon, json);
    
    if (err) {
         console.log('Failed to load wallet: ' + err.toString());
    }

    Parameters

    • daemon: IDaemon

      An implementation of the IDaemon interface.

    • json: string

      Wallet info encoded as a JSON encoded string. Note that this should be a string, NOT a JSON object. This function will call JSON.parse(), so you should not do that yourself.

    • Optional config: IConfig

    Returns [WalletBackend, undefined] | [undefined, WalletError]

Static openWalletFromEncryptedString

  • This method opens a password protected wallet from an encrypted string. The password protection follows the same format as wallet-api, zentwallet-beta, and WalletBackend. It does NOT follow the same format as zent-service or zedwallet, and will be unable to open wallets created with this program.

    Example:

    const WB = require('zentcash-wallet-backend');
    
    const daemon = new WB.Daemon('127.0.0.1', 21698);
    const data = 'ENCRYPTED_WALLET_STRING';
    
    const [wallet, error] = WB.WalletBackend.openWalletFromEncryptedString(daemon, data, 'hunter2');
    
    if (err) {
         console.log('Failed to open wallet: ' + err.toString());
    }

    Parameters

    • deamon: IDaemon
    • data: string

      The encrypted string representing the wallet data

    • password: string

      The password to use to decrypt the wallet. May be blank.

    • Optional config: IConfig

    Returns [WalletBackend, undefined] | [undefined, WalletError]

Static openWalletFromFile

  • This method opens a password protected wallet from a filepath. The password protection follows the same format as wallet-api, zedwallet-beta, and WalletBackend. It does NOT follow the same format as zent-service or zedwallet, and will be unable to open wallets created with this program.

    Example:

    const WB = require('zentcash-wallet-backend');
    
    const daemon = new WB.Daemon('127.0.0.1', 21698);
    
    const [wallet, error] = WB.WalletBackend.openWalletFromFile(daemon, 'mywallet.wallet', 'hunter2');
    
    if (err) {
         console.log('Failed to open wallet: ' + err.toString());
    }

    Parameters

    • daemon: IDaemon
    • filename: string

      The location of the wallet file on disk

    • password: string

      The password to use to decrypt the wallet. May be blank.

    • Optional config: IConfig

    Returns [WalletBackend, undefined] | [undefined, WalletError]

Generated using TypeDoc