SparkWallet

The SparkWallet class is the primary interface for interacting with the Spark network. It provides methods for creating and managing wallets, handling deposits, executing transfers, and interacting with the Lightning Network.

Installation

yarn add @buildonspark/spark-sdk
or npm
npm i @buildonspark/spark-sdk

Methods

initialize({ mnemonicOrSeed, signer, options }: SparkWalletProps)

Creates and initializes a new SparkWallet instance.
interface SparkWalletProps {
  mnemonicOrSeed?: Uint8Array | string;
  accountNumner?: number
  signer?: SparkSigner;
  options?: ConfigOptions;
}

static async initialize(props: SparkWalletProps): Promise<{
  wallet: SparkWallet;
  mnemonic?: string;
}>
Parameters:
  • props: Object containing:
    • mnemonicOrSeed: (Optional) BIP-39 mnemonic phrase or raw seed
    • accountNumber: (Optional) number used to generate multiple identity keys from the same mnemonic
    • signer: (Optional) Custom signer implementation
    • options: (Optional) Wallet configuration options
If no account number is provided, our JS-SDK defaults accountNumber to 1 to support backwards compatability for mainnet wallets created with earlier versions of the SDK.
Returns:
  • Object containing:
    • wallet: The initialized SparkWallet instance
    • mnemonic: The mnemonic if one was generated (undefined for raw seed)

getIdentityPublicKey()

Gets the identity public key of the wallet.
async getIdentityPublicKey(): Promise<string>
Returns:
  • Promise<string>: The identity public key as a hex string

getSparkAddress()

Gets the Spark Address of the wallet.
async getSparkAddress(): Promise<SparkAddressFormat>
Returns:
  • Promise<SparkAddressFormat>: The Spark Address

getTransfers(limit?: number, offset?: number)

Gets all transfers for the wallet.
async getTransfers(
  limit: number = 20,
  offset: number = 0
): Promise<{
  transfers: WalletTransfer[];
  offset: number;
}>
Parameters:
  • limit: (Optional, default: 20) Maximum number of transfers to return
  • offset: (Optional, default: 0) Offset for pagination
Returns:
  • Promise<{ transfers: WalletTransfer[]; offset: number; }>: Response containing the list of transfers and offset

getBalance()

Gets the current balance of the wallet. You can use the forceRefetch option to synchronize your wallet and claim any pending incoming lightning payment, spark transfer, or bitcoin deposit before returning the balance.
async getBalance(): Promise<{
  balance: bigint;
  tokenBalances: Map<string, { balance: bigint, bech32mTokenIdentifier: string }>;
}>
Returns:
  • Object containing:
    • balance: The wallet’s current balance in satoshis
    • tokenBalances: Map of token public keys to token balances with Bech32m token identifiers

getSingleUseDepositAddress()

Generates a new single-use deposit address for receiving bitcoin funds. Note that this function returns a bitcoin address, not a Spark Address. Once used, this address should not be used again. For Layer 1 Bitcoin deposits, Spark generates Pay to Taproot (P2TR) addresses. These addresses start with “bc1p” and can be used to receive Bitcoin from any wallet.
async getSingleUseDepositAddress(): Promise<string>
Returns:
  • Promise<string>: A Bitcoin address for depositing funds

getUnusedDepositAddresses()

Gets all unused deposit addresses for the wallet.
async getUnusedDepositAddresses(): Promise<string[]>
Returns:
  • Promise<string[]>: Array of unused deposit addresses

transfer(params)

Transfers Bitcoin to another Spark wallet.
async transfer({
  receiverSparkAddress,
  amountSats,
}: {
  receiverSparkAddress: string;
  amountSats: number;
}): Promise<WalletTransfer>
Parameters:
  • params: Object containing:
    • receiverSparkAddress: The recipient’s Spark Address
    • amountSats: The amount in satoshis to transfer
Returns:
  • Promise<WalletTransfer>: The completed transfer details

payLightningInvoice(params: PayLightningInvoiceParams)

Pays a Lightning invoice.
interface PayLightningInvoiceParams {
  invoice: string;
  maxFeeSats: number;
  preferSpark?: boolean;
  amountSatsToSend?: number;
}

async payLightningInvoice(params: PayLightningInvoiceParams): Promise<LightningSendRequest>
Parameters:
  • params: Object containing:
    • invoice: The BOLT11-encoded Lightning invoice to pay.
    • maxFeeSats: Maximum fee in satoshis to pay for the invoice.
    • preferSpark: (Optional) Boolean that defaults to false. When preferSpark is set to true, Spark wallets will initiate a Spark transfer instead of a Lightning transfer if a valid Spark address is found in the invoice. If not, a regular Lightning payment will occur.
    • amountSatsToSend: (Optional) Amount in satoshis to send. This parameter is only used for zero-amount invoices. For regular invoices with a fixed amount, this parameter is ignored.
Returns:
  • Promise<LightningSendRequest>: The Lightning payment request details
Examples:
// Pay a regular invoice
const payment_response = await wallet.payLightningInvoice({
  invoice: "lnbc100n...", // Regular Lightning invoice with amount
  maxFeeSats: 5,
});
console.log("Payment Response:", payment_response);

// Pay a zero-amount invoice
const zeroAmountPayment = await wallet.payLightningInvoice({
  invoice: "lnbc...", // Zero-amount Lightning invoice
  maxFeeSats: 5,
  amountSatsToSend: 1000, // Specify amount for zero-amount invoice
});
console.log("Zero-amount Payment Response:", zeroAmountPayment);

transferTokens(params)

Transfers tokens to another user.
async transferTokens({
  tokenIdentifier,
  tokenAmount,
  receiverSparkAddress,
  selectedOutputs,
}: {
  tokenIdentifier: string;
  tokenAmount: bigint;
  receiverSparkAddress: string;
  selectedOutputs?: OutputWithPreviousTransactionData[];
}): Promise<string>
Parameters:
  • params: Object containing:
    • tokenIdentifier: The Bech32m token identifier (eg: btkn1…) of the token to transfer
    • tokenAmount: The amount of tokens to transfer
    • receiverSparkAddress: The recipient’s Spark Address
    • selectedOutputs: (Optional) Specific outputs to use for the transfer
Returns:
  • Promise<string>: The transaction ID of the token transfer

getTokenInfo()

Gets information about tokens owned by the wallet.
async getTokenInfo(): Promise<TokenInfo[]>
Returns:
  • Promise<TokenInfo[]>: Array of token information objects

queryTokenTransactions()

Retrieves token transaction from the network. Can optionally filter by ownerPublicKeys, issuerPublicKeys, tokenTransactionHashes, tokenIdentifiers, or outputIds.
async queryTokenTransactions({
  ownerPublicKeys,
  issuerPublicKeys,
  tokenTransactionHashes,
  tokenIdentifiers,
  outputIds,
}: {
  ownerPublicKeys?: string[];
  issuerPublicKeys?: string[];
  tokenTransactionHashes?: string[];
  tokenIdentifiers?: string[];
  outputIds?: string[];
}): Promise<TokenTransactionWithStatus[]>
Parameters:
  • ownerPublicKeys: (Optional) Array of owner public keys to filter by
  • issuerPublicKeys: (Optional) Array of issuer public keys to filter by
  • tokenTransactionHashes: (Optional) Array of token transaction hashes to filter by
  • tokenIdentifiers: (Optional) Array of Bech32m token identifiers to filter by
  • outputIds: (Optional) Array of output IDs to filter by
Returns:
  • Promise<TokenTransactionWithStatus[]>: Array of token transactions with status

getTokenL1Address()

Gets the Layer 1 Bitcoin address for token operations.
async getTokenL1Address(): Promise<string>
Returns:
  • Promise<string>: The Layer 1 Bitcoin address

createLightningInvoice(params)

Creates a Lightning invoice for receiving payments.
interface CreateLightningInvoiceParams {
  amountSats: number;
  memo?: string;
  expirySeconds?: number;
  includeSparkAddress?: boolean;
  receiverIdentityPubkey?: string;
}

async createLightningInvoice(params: CreateLightningInvoiceParams): Promise<LightningReceiveRequest>
Parameters:
  • params: Object containing:
    • amountSats: Amount in satoshis
    • memo: (Optional) Description for the invoice
    • expirySeconds: (Optional) Expiry time in seconds, defaults to 30 days
    • includeSparkAddress: (Optional) By passing in true, a 36-byte string consisting of a recognizable header and a receiver’s compressed identity public key SPK:identitypubkey will get embedded in the fallback address (f) field of a BOLT11 invoice
    • receiverIdentityPubkey: (Optional) To generate an invoice for another Spark user, pass in the 33-byte compressed identity pubkey as a string
Returns:
  • Promise<LightningReceiveRequest>: The Lightning receive request details
Examples:
// Basic invoice
const invoice = await wallet.createLightningInvoice({
  amountSats: 100,
  memo: "test invoice",
});
console.log("Invoice:", invoice);

// Invoice with embedded Spark address
const invoiceWithSpark = await wallet.createLightningInvoice({
  amountSats: 100,
  memo: "Invoice with Spark integration",
  includeSparkAddress: true,
});
console.log("Invoice with Spark address:", invoiceWithSpark);

// Invoice for another Spark user
const invoiceForOther = await wallet.createLightningInvoice({
  amountSats: 100,
  memo: "Invoice for another user",
  receiverIdentityPubkey: "033b4f8cf891e45e2e3995e29b3c8b3d4d4e67f8a9b2c1d3e4f567890abcdef12",
});
console.log("Invoice for other user:", invoiceForOther);

getLightningReceiveRequest(id: string)

Gets the status of a Lightning receive request (invoice).
async getLightningReceiveRequest(id: string): Promise<LightningReceiveRequest | null>
Parameters:
  • id: The ID of the invoice to check.
Returns:
  • Promise<LightningReceiveRequest | null>: The Lightning receive request details or null if not found.

getLightningSendRequest(id: string)

Gets the status of a Lightning send request.
async getLightningSendRequest(id: string): Promise<LightningSendRequest | null>
Parameters:
  • id: The ID of the Lightning send request to check.
Returns:
  • Promise<LightningSendRequest | null>: The Lightning send request details or null if not found.

getLightningSendFeeEstimate(params)

Estimates the fee for sending a Lightning payment.
interface LightningSendFeeEstimateInput {
  encodedInvoice: string;
}

async getLightningSendFeeEstimate(params: LightningSendFeeEstimateInput): Promise<number>
Parameters:
  • params: Object containing:
    • encodedInvoice: The BOLT11-encoded Lightning invoice.
Returns:
  • Promise<number>: The estimated fee in satoshis.

withdraw(params)

Initiates a withdrawal to move funds from the Spark network to an on-chain Bitcoin address.
interface WithdrawParams {
  onchainAddress: string;
  exitSpeed: ExitSpeed;
  amountSats?: number;
  feeQuote: WithdrawalFeeQuote; // returned by getWithdrawalFeeQuote
  deductFeeFromWithdrawalAmount?: boolean; // default: true
}

async withdraw(params: WithdrawParams): Promise<CoopExitRequest | null | undefined>
Parameters:
  • params: An object with the following properties:
    • onchainAddress: (Required) The Bitcoin address where the funds should be sent.
    • exitSpeed: (Required) The desired speed of the exit (FAST, MEDIUM, SLOW).
    • amountSats: (Optional) The amount in satoshis to withdraw. If not specified, attempts to withdraw all available funds.
    • feeQuote: (Required) The fee quote object returned by getWithdrawalFeeQuote. Must be used before it expires.
    • deductFeeFromWithdrawalAmount: (Optional, default: true) When true, fees are deducted from the withdrawal amount. When false, fees are deducted from the remaining wallet balance.
Returns:
  • Promise<CoopExitRequest | null | undefined>: The withdrawal request details, or null/undefined if the request cannot be completed.
Example:
// 1) Fetch a fee quote
const feeQuote = await wallet.getWithdrawalFeeQuote({
  amountSats: 17000,
  withdrawalAddress:
    "bcrt1pf8hed85p94emupfpfhq2g0p5c40cgzqs4agvvfmeuy32nxeh549syu2lwf",
});

// 2) Use the quote before it expires to create the withdrawal
const withdraw_result = await wallet.withdraw({
  onchainAddress:
    "bcrt1pf8hed85p94emupfpfhq2g0p5c40cgzqs4agvvfmeuy32nxeh549syu2lwf",
  amountSats: 17000,
  exitSpeed: ExitSpeed.MEDIUM, // Or ExitSpeed.FAST, ExitSpeed.SLOW
  feeQuote,
  deductFeeFromWithdrawalAmount: true,
});
console.log("Withdraw Result:", withdraw_result);

getWithdrawalFeeQuote(params)

Gets a fee quote for a cooperative exit (on-chain withdrawal). The quote includes options for different speeds and an expiry time and must be passed to withdraw before it expires.
async getWithdrawalFeeQuote({
  amountSats,
  withdrawalAddress,
}: {
  amountSats: number;
  withdrawalAddress: string;
}): Promise<WithdrawalFeeQuote | null>
Parameters:
  • params: Object containing:
    • amountSats: The amount in satoshis to withdraw.
    • withdrawalAddress: The Bitcoin address where the funds should be sent.
Returns:
  • Promise<WithdrawalFeeQuote | null>: A fee quote for the withdrawal, or null if not available.

getCoopExitRequest(id: string)

Gets a cooperative exit request by ID.
async getCoopExitRequest(id: string): Promise<CoopExitRequest | null>
Parameters:
  • id: The ID of the cooperative exit request.
Returns:
  • Promise<CoopExitRequest | null>: The cooperative exit request details or null if not found.

claimDeposit(txId: string)

Claims a Bitcoin deposit made to a single-use deposit address.
async claimDeposit(txId: string): Promise<WalletLeaf[]>
Parameters:
  • txId: The transaction ID of the Bitcoin deposit.
Returns:
  • Promise<WalletLeaf[]>: The wallet leaves resulting from the claim operation.

getStaticDepositAddress()

Returns a Bitcoin address that users can deposit funds to as many times as they like. Currently Spark only supports one static deposit address per wallet. If you try to create a second address, it will return your existing static deposit address.
async getStaticDepositAddress(): Promise<string>
Returns:
  • Promise<string>: A reusable Bitcoin address for depositing funds

getClaimStaticDepositQuote(txId: string, outputIndex?: number)

Gets a quote for claiming a deposit made to a static deposit address. This method returns the transaction details, output index, credit amount in satoshis, and the SSP signature required for claiming.
async getClaimStaticDepositQuote(
  txId: string,
  outputIndex?: number
): Promise<{
  txId: string;
  outputIndex: number;
  creditAmountSats: number;
  sspSignature: string;
}>
Parameters:
  • txId: The Bitcoin transaction ID of the deposit transaction.
  • outputIndex: (Optional) The index of the output
Returns:
  • Promise<object>: Object containing transaction details and claiming information

claimStaticDeposit(params)

Claims a deposit made to a static deposit address using the quote information from getClaimStaticDepositQuote.
async claimStaticDeposit({
  transactionId,
  creditAmountSats,
  sspSignature,
  outputIndex,
}: {
  transactionId: string;
  creditAmountSats: number;
  sspSignature: string;
  outputIndex?: number;
}): Promise<ClaimStaticDepositOutput | null>
Parameters:
  • params: Object containing:
    • transactionId: The Bitcoin transaction ID from the quote
    • creditAmountSats: The amount of sats from the quote
    • sspSignature: The SSP signature from the quote
    • outputIndex: (Optional) The index of the output
Returns:
  • Promise<ClaimStaticDepositOutput | null>: The claim result or null if the operation fails

refundStaticDeposit(depositTxId: string, destinationAddress: string, feeSats: number)

Refunds a deposit made to a static deposit address back to a specified Bitcoin address. The minimum fee is 300 satoshis.
async refundStaticDeposit(
  depositTxId: string, 
  destinationAddress: string, 
  feeSats: number
): Promise<string>
Parameters:
  • depositTxId: The transaction ID of the original deposit
  • destinationAddress: The Bitcoin address to send the refund to
  • feeSats: The fee to pay for the refund transaction (minimum 300 sats)
Returns:
  • Promise<string>: The refund transaction as a hex string that needs to be broadcast

advancedDeposit(txHex: string)

Non-trusty flow for depositing funds to the wallet. Construct the tx spending from an L1 wallet to the Spark address.
async advancedDeposit(txHex: string): Promise<TreeNode[]>
Parameters:
  • txHex: The hex string of the transaction to deposit.
Returns:
  • Promise<TreeNode[]>: The nodes resulting from the deposit.

getSwapFeeEstimate(amountSats: number)

Gets the estimated fee for a swap of leaves.
async getSwapFeeEstimate(amountSats: number): Promise<LeavesSwapFeeEstimateOutput>
Parameters:
  • amountSats: The amount of sats to swap.
Returns:
  • Promise<LeavesSwapFeeEstimateOutput>: The estimated fee for the swap.

cleanupConnections()

Cleans up connections and aborts any active streams.
async cleanupConnections(): Promise<void>
Returns:
  • Promise<void>

Inherited Methods from EventEmitter

SparkWallet extends EventEmitter, so it inherits the following methods:

on(event: string, listener: Function)

Adds a listener for the specified event.
on(event: keyof SparkWalletEvents, listener: Function): this
Parameters:
  • event: The event name to listen for
  • listener: The callback function to execute when the event is emitted
Returns:
  • this: The SparkWallet instance for chaining
Example:
wallet.on("transfer:claimed", (transferId, updatedBalance) => {
  console.log(`Transfer ${transferId} claimed. New balance: ${updatedBalance}`);
});

once(event: string, listener: Function)

Adds a one-time listener for the specified event.
once(event: keyof SparkWalletEvents, listener: Function): this
Parameters:
  • event: The event name to listen for
  • listener: The callback function to execute when the event is emitted
Returns:
  • this: The SparkWallet instance for chaining

off(event: string, listener: Function)

Removes the specified listener from the specified event.
off(event: keyof SparkWalletEvents, listener: Function): this
Parameters:
  • event: The event name
  • **`