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 }>;
}>

Returns:

  • Object containing:
    • balance: The wallet’s current balance in satoshis
    • tokenBalances: Map of token public keys to token balances

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;
}

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.

Returns:

  • Promise<LightningSendRequest>: The Lightning payment request details

transferTokens(params)

Transfers tokens to another user.

async transferTokens({
  tokenPublicKey,
  tokenAmount,
  receiverSparkAddress,
  selectedOutputs,
}: {
  tokenPublicKey: string;
  tokenAmount: bigint;
  receiverSparkAddress: string;
  selectedOutputs?: OutputWithPreviousTransactionData[];
}): Promise<string>

Parameters:

  • params: Object containing:
    • tokenPublicKey: The public key 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(tokenPublicKeys: string[], tokenTransactionHashes?: string[])

Retrieves token transaction history for specified tokens owned by the wallet. Can optionally filter by specific transaction hashes.

async queryTokenTransactions(
  tokenPublicKeys: string[],
  tokenTransactionHashes?: string[]
): Promise<TokenTransactionWithStatus[]>

Parameters:

  • tokenPublicKeys: Array of token public keys to query
  • tokenTransactionHashes: (Optional) Array of token transaction hashes 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;
}

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.

Returns:

  • Promise<CoopExitRequest | null | undefined>: The withdrawal request details, or null/undefined if the request cannot be completed.

Example:

const withdraw_result = await wallet.withdraw({
  onchainAddress:
    "bcrt1pf8hed85p94emupfpfhq2g0p5c40cgzqs4agvvfmeuy32nxeh549syu2lwf",
  amountSats: 17000,
  exitSpeed: ExitSpeed.MEDIUM, // Or ExitSpeed.FAST, ExitSpeed.SLOW
});
console.log("Withdraw Result:", withdraw_result);

getWithdrawalFeeEstimate(params)

Gets fee estimate for cooperative exit (on-chain withdrawal).

async getWithdrawalFeeEstimate({
  amountSats,
  withdrawalAddress,
}: {
  amountSats: number;
  withdrawalAddress: string;
}): Promise<CoopExitFeeEstimatesOutput | null>

Parameters:

  • params: Object containing:
    • amountSats: The amount in satoshis to withdraw.
    • withdrawalAddress: The Bitcoin address where the funds should be sent.

Returns:

  • Promise<CoopExitFeeEstimatesOutput | null>: Fee estimate 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.

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
  • listener: The callback function to remove

Returns:

  • this: The SparkWallet instance for chaining

removeAllListeners(event?: string)

Removes all listeners, or those of the specified event.

removeAllListeners(event?: keyof SparkWalletEvents): this

Parameters:

  • event: (Optional) The event name

Returns:

  • this: The SparkWallet instance for chaining

Events

SparkWallet emits the following events:

transfer:claimed

Emitted when an incoming transfer is successfully claimed.

Callback Parameters:

  • transferId: The ID of the claimed transfer
  • updatedBalance: The new total balance after claiming the transfer

deposit:confirmed

Emitted when a deposit is marked as available.

Callback Parameters:

  • depositId: The ID of the confirmed deposit
  • updatedBalance: The new total balance after confirming the deposit

stream:connected

Emitted when the stream is connected.

stream:disconnected

Emitted when the stream disconnects and fails to reconnect after max attempts.

Callback Parameters:

  • reason: The reason for disconnection

stream:reconnecting

Emitted when attempting to reconnect the stream.

Callback Parameters:

  • attempt: The current reconnection attempt number
  • maxAttempts: The maximum number of reconnection attempts
  • delayMs: The delay in milliseconds before the next reconnection attempt
  • error: The error that caused the reconnection attempt

Supporting Types

BitcoinNetwork (Enum)

Represents the Bitcoin network to use with the wallet.

enum BitcoinNetwork {
  UNSPECIFIED = 0,
  MAINNET = 1,
  REGTEST = 2,
  TESTNET = 3,
  SIGNET = 4,
  UNRECOGNIZED = -1,
}

CreateLightningInvoiceParams (Type)

Parameters for creating a Lightning invoice.

type CreateLightningInvoiceParams = {
  amountSats: number;
  memo?: string;
  expirySeconds?: number;
  includeSparkAddress?: boolean;
  receiverIdentityPubkey?: string;
};

PayLightningInvoiceParams (Type)

Parameters for paying a Lightning invoice.

type PayLightningInvoiceParams = {
  invoice: string;
  maxFeeSats: number;
  preferSpark?: boolean;
};

SparkSigner (Interface)

Interface for a custom signer implementation.

interface SparkSigner {
  getIdentityPublicKey(): Promise<Uint8Array>;
  generatePublicKey(seed?: Uint8Array): Promise<Uint8Array>;
  generateMnemonic(): Promise<string>;
  mnemonicToSeed(mnemonic: string): Promise<Uint8Array>;
  createSparkWalletFromSeed(
    seed: Uint8Array | string,
    network: Network
  ): Promise<string>;
  restoreSigningKeysFromLeafs(leaves: TreeNode[]): Promise<void>;
  getTrackedPublicKeys(): Promise<Uint8Array[]>;
  signMessageWithIdentityKey(
    message: Uint8Array,
    compact?: boolean
  ): Promise<Uint8Array>;
  signMessage(message: Uint8Array, publicKey: Uint8Array): Promise<Uint8Array>;
}

SparkWalletProps (Interface)

Properties for initializing a SparkWallet.

interface SparkWalletProps {
  mnemonicOrSeed?: Uint8Array | string;
  accountNumber?: number;
  signer?: SparkSigner;
  options?: ConfigOptions;
}

WalletLeaf (Interface)

Represents a leaf in the wallet’s tree structure, as used by the SDK. This is often a mapped version of the proto TreeNode.

interface WalletLeaf {
  id: string;
  treeId: string;
  value: number;
  parentNodeId?: string | undefined;
  nodeTx: string; // Hex encoded
  refundTx: string; // Hex encoded
  vout: number;
  verifyingPublicKey: string; // Hex encoded
  ownerIdentityPublicKey: string; // Hex encoded
  signingKeyshare: SigningKeyshare | undefined;
  status: string;
  network: keyof typeof Network; // String key of the Network enum (e.g., "MAINNET")
}

TransferDirection (Enum)

Represents the direction of a transfer (SDK specific enum).

enum TransferDirection {
  INCOMING = "INCOMING",
  OUTGOING = "OUTGOING",
}

TransferStatus (Enum)

The possible states of a transfer. (Corresponds to proto TransferStatus)

enum TransferStatus {
  TRANSFER_STATUS_SENDER_INITIATED = 0,
  TRANSFER_STATUS_SENDER_KEY_TWEAK_PENDING = 1,
  TRANSFER_STATUS_SENDER_KEY_TWEAKED = 2,
  TRANSFER_STATUS_RECEIVER_KEY_TWEAKED = 3,
  TRANSFER_STATUSR_RECEIVER_REFUND_SIGNED = 4,
  TRANSFER_STATUS_COMPLETED = 5,
  TRANSFER_STATUS_EXPIRED = 6,
  TRANSFER_STATUS_RETURNED = 7,
  UNRECOGNIZED = -1,
}

TransferType (Enum)

The types of transfers. (Corresponds to proto TransferType)

enum TransferType {
  PREIMAGE_SWAP = 0,
  COOPERATIVE_EXIT = 1,
  TRANSFER = 2,
  SWAP = 30,
  COUNTER_SWAP = 40,
  UNRECOGNIZED = -1,
}

WalletTransferLeaf (Interface)

Represents a leaf within a transfer, as used by the SDK.

interface WalletTransferLeaf {
  leaf: WalletLeaf | undefined;
  secretCipher: string; // Hex encoded
  signature: string; // Hex encoded
  intermediateRefundTx: string; // Hex encoded
}

WalletTransfer (Interface)

Represents a transfer between users, as used by the SDK.

interface WalletTransfer {
  id: string;
  senderIdentityPublicKey: string; // Hex encoded
  receiverIdentityPublicKey: string; // Hex encoded
  status: keyof typeof TransferStatus; // String key of TransferStatus enum
  totalValue: number;
  expiryTime: Date | undefined;
  leaves: WalletTransferLeaf[];
  createdTime: Date | undefined;
  updatedTime: Date | undefined;
  type: keyof typeof TransferType; // String key of TransferType enum
  transferDirection: keyof typeof TransferDirection; // Uses the SDK's TransferDirection enum
}

ExitSpeed (Enum)

Represents the desired speed for a cooperative exit.

enum ExitSpeed {
  FUTURE_VALUE = "FUTURE_VALUE",
  FAST = "FAST",
  MEDIUM = "MEDIUM",
  SLOW = "SLOW",
}

TokenOutput (Interface)

Represents a token output. (Corresponds to proto TokenOutput)

interface TokenOutput {
  id?: string;
  ownerPublicKey: Uint8Array;
  revocationCommitment?: Uint8Array;
  withdrawBondSats?: number;
  withdrawRelativeBlockLocktime?: number;
  tokenPublicKey: Uint8Array;
  tokenAmount: Uint8Array; // Represents a uint128 value
}

OutputWithPreviousTransactionData (Interface)

Represents an output with its previous transaction data, used for token transfers. (Corresponds to proto OutputWithPreviousTransactionData)

interface OutputWithPreviousTransactionData {
  output?: TokenOutput;
  previousTransactionHash: Uint8Array;
  previousTransactionVout: number;
}

TokenInfo (Interface)

Represents information about a specific token (SDK specific type).

interface TokenInfo {
  tokenPublicKey: string;
  tokenName: string;
  tokenSymbol: string;
  tokenDecimals: number;
  maxSupply: bigint;
}

CoopExitRequest (Type)

The result of a withdrawal request (SDK specific type).

type CoopExitRequest =
  | {
      id: string;
      status: string;
      amount: bigint;
      destinationAddress: string;
      transactionId?: string;
    }
  | null
  | undefined;

LightningSendRequest (Type)

The result of a Lightning payment request (SDK specific type).

type LightningSendRequest = {
  id: string;
  status: string;
  amount: bigint;
  paymentRequest: string;
  paymentHash: string;
  fee?: bigint;
};

LightningReceiveRequest (Type)

The result of a Lightning invoice creation (SDK specific type).

type LightningReceiveRequest = {
  id: string;
  status: string;
  amount: bigint;
  paymentRequest: string;
  paymentHash: string;
  expiresAt: Date;
  memo?: string;
};

CurrencyAmount (Type)

Represents an amount in a specific currency (SDK specific type).

type CurrencyAmount = {
  originalValue: number;
  originalUnit: string;
  preferredCurrencyUnit: string;
  preferredCurrencyValueRounded: number;
  preferredCurrencyValueApprox: number;
};

CoopExitFeeEstimatesOutput (Type)

Fee estimates for cooperative exit (SDK specific type).

type CoopExitFeeEstimatesOutput = {
  speedFast?: {
    l1BroadcastFee: CurrencyAmount;
    userFee: CurrencyAmount;
  };
  speedMedium?: {
    l1BroadcastFee: CurrencyAmount;
    userFee: CurrencyAmount;
  };
  speedSlow?: {
    l1BroadcastFee: CurrencyAmount;
    userFee: CurrencyAmount;
  };
};

TokenTransactionStatus (Enum)

Status of a token transaction. (Corresponds to proto TokenTransactionStatus)

enum TokenTransactionStatus {
  TOKEN_TRANSACTION_STARTED = 0,
  TOKEN_TRANSACTION_SIGNED = 1,
  TOKEN_TRANSACTION_FINALIZED = 2,
  UNRECOGNIZED = -1,
}

TokenMintInput (Interface)

Input for a token mint operation. (Corresponds to proto TokenMintInput)

interface TokenMintInput {
  issuerPublicKey: Uint8Array;
  issuerProvidedTimestamp: number;
}

TokenOutputToSpend (Interface)

Specifies a token output to be spent. (Corresponds to proto TokenOutputToSpend)

interface TokenOutputToSpend {
  prevTokenTransactionHash: Uint8Array;
  prevTokenTransactionVout: number;
}

TokenTransferInput (Interface)

Input for a token transfer operation. (Corresponds to proto TokenTransferInput)

interface TokenTransferInput {
  outputsToSpend: TokenOutputToSpend[];
}

TokenTransaction (Interface)

Represents a token transaction. (Corresponds to proto TokenTransaction)

interface TokenTransaction {
  tokenInputs?:
    | { $case: "mintInput"; mintInput: TokenMintInput }
    | { $case: "transferInput"; transferInput: TokenTransferInput };
  tokenOutputs: TokenOutput[];
  sparkOperatorIdentityPublicKeys: Uint8Array[];
  network: Network; // Numeric Network enum from proto
}

TokenTransactionWithStatus (Type)

Represents a token transaction with its status. (Corresponds to proto TokenTransactionWithStatus)

type TokenTransactionWithStatus = {
  tokenTransaction?: TokenTransaction;
  status: TokenTransactionStatus; // Uses the TokenTransactionStatus enum
};

SparkAddressFormat (Type)

Represents a formatted Spark address.

type SparkAddressFormat = string;

SparkWalletEvents (Interface)

Defines the events that can be emitted by a SparkWallet instance.

interface SparkWalletEvents {
  "transfer:claimed": (transferId: string, updatedBalance: number) => void;
  "deposit:confirmed": (depositId: string, updatedBalance: number) => void;
  "stream:connected": () => void;
  "stream:disconnected": (reason: string) => void;
  "stream:reconnecting": (
    attempt: number,
    maxAttempts: number,
    delayMs: number,
    error: string
  ) => void;
}