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

create({ mnemonicOrSeed, signer, options, lrc20WalletApiConfig }: SparkWalletProps)

Creates and initializes a new SparkWallet instance.

interface SparkWalletProps {
  mnemonicOrSeed?: Uint8Array | string;
  signer?: SparkSigner;
  options?: ConfigOptions;
  lrc20WalletApiConfig?: LRC20WalletApiConfig;
}

static async create(props: SparkWalletProps): Promise<{
  wallet: SparkWallet;
  mnemonic?: string;
}>

Parameters:

  • props: Object containing:
    • mnemonicOrSeed: (Optional) BIP-39 mnemonic phrase or raw seed
    • signer: (Optional) Custom signer implementation
    • options: (Optional) Wallet configuration options
    • lrc20WalletApiConfig: (Optional) LRC20 wallet configuration

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<string>

Returns:

  • Promise<string>: The Spark Address as a hex string

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

Gets all transfers for the wallet.

async getTransfers(
  limit: number = 20,
  offset: number = 0
): Promise<QueryAllTransfersResponse>

Parameters:

  • limit: (Optional, default: 20) Maximum number of transfers to return
  • offset: (Optional, default: 0) Offset for pagination

Returns:

  • Promise<QueryAllTransfersResponse>: Response containing the list of transfers

getBalance()

Gets the current balance of the wallet.

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 balances indexed by token public key

getDepositAddress()

Generates a new deposit address for receiving bitcoin funds. Note that this function returns a bitcoin address, not a Spark Address. 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 getDepositAddress(): 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

payLightningInvoice(params: PayLightningInvoiceParams)

Pays a Lightning invoice.

interface PayLightningInvoiceParams {
  invoice: string;
}

async payLightningInvoice(params: PayLightningInvoiceParams): Promise<LightningSendRequest>

Parameters:

  • params: Object containing:
    • invoice: The BOLT11-encoded Lightning invoice to pay

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?: LeafWithPreviousTransactionData[];
}): 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 public key
    • selectedLeaves: (Optional) Specific leaves to use for the transfer

Returns:

  • Promise<string>: The transaction ID of the token transfer

withdrawTokens(tokenPublicKey: string, receiverPublicKey?: string, leafIds?: string[])

Withdraws tokens from the Spark network.

async withdrawTokens(
  tokenPublicKey: string,
  receiverPublicKey?: string,
  outputIds?: string[]
): Promise<{ txid: string } | undefined>

Parameters:

  • tokenPublicKey: The public key of the token to withdraw
  • receiverPublicKey: (Optional) The public key of the receiver
  • outputIds: (Optional) Specific token output IDs to withdraw

Returns:

  • Promise<{ txid: string } | undefined>: The transaction ID of the withdrawal, or undefined if the withdrawal fails

createLightningInvoice()

Creates a Lightning invoice for receiving payments.

async createLightningInvoice({
  amountSats: number,
  memo: string
}): Promise<string>

Parameters:

  • amountSats: Amount in satoshis
  • memo: Description for the invoice

Returns:

  • Promise<string>: BOLT11 encoded invoice

Example:

const invoice = await wallet.createLightningInvoice({
  amountSats: 100,
  memo: "test invoice",
});
console.log("Invoice:", invoice);

withdraw()

Initiates a withdrawal to move funds from the Spark network to an on-chain Bitcoin address.

async withdraw({
  onchainAddress: string,
  targetAmountSats?: number
}): Promise<CoopExitRequest | null | undefined>

Parameters:

  • params: An object with the following properties:
  • onchainAddress: (Required) The Bitcoin address where the funds should be sent
  • targetAmountSats: (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",
});
console.log("Withdraw Result:", withdraw_result);

getPendingTransfers()

Gets all pending transfers.

async getPendingTransfers(): Promise<Transfer[]>

Returns:

  • Promise<Transfer[]>: The pending transfers

claimTransfer(transfer: Transfer)

Claims a specific transfer.

async claimTransfer(transfer: Transfer): Promise<{
    nodes: TreeNode[];
}>

Parameters:

  • transfer: The transfer to claim

Returns:

  • Promise<{ nodes: TreeNode[] }>: The claim result containing the new nodes

claimTransfers()

Claims all pending transfers.

async claimTransfers(): Promise<boolean>

Returns:

  • Promise<boolean>: True if any transfers were claimed

Supporting Types

Network (Enum)

Represents the Bitcoin network to use with the wallet.

enum Network {
  MAINNET = 0,
  REGTEST = 1,
  TESTNET = 2,
  SIGNET = 3,
  UNRECOGNIZED = -1,
}

CreateLightningInvoiceParams (Type)

Parameters for creating a Lightning invoice.

type CreateLightningInvoiceParams = {
  amountSats: number;
  memo: string;
};

PayLightningInvoiceParams (Type)

Parameters for paying a Lightning invoice.

type PayLightningInvoiceParams = {
  invoice: string;
};

Transfer (Interface)

Represents a transfer between users.

interface Transfer {
  id: string;
  status: TransferStatus;
  leaves: TransferLeaf[];
    // ... other properties from TransferService
}

TreeNode (Interface)

Represents a node in the Spark tree.

interface TreeNode {
  id: string;
  parentNodeId?: string;
  refundTx: Uint8Array;
  value: number;
    // ... other properties from TreeNode type
}

TransferStatus (Enum)

The possible states of a transfer.

enum TransferStatus {
  TRANSFER_STATUS_SENDER_INITIATED = 0,
  TRANSFER_STATUS_SENDER_KEY_TWEAKED = 1,
  TRANSFER_STATUS_RECEIVER_KEY_TWEAKED = 2,
  TRANSFER_STATUS_RECEIVER_REFUND_SIGNED = 3
}

TokenBalance (Type)

Represents a token’s balance and leaf count.

type TokenBalance = {
  balance: bigint;
};

WithdrawParams (Type)

Parameters for initiating a withdrawal.

type WithdrawParams = {
  onchainAddress: string;
  targetAmountSats?: number;
};

CoopExitRequest (Type)

The result of a withdrawal request.

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

LightningSendRequest (Type)

The result of a Lightning payment request.

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

TokenBalanceMap (Type)

Map of token balances indexed by token public key.

type TokenBalanceMap = Map<
  string,
  {
    balance: bigint;
  }
>;