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

initWallet(mnemonicOrSeed?: Uint8Array | string)

Initializes the wallet using either a mnemonic phrase or a raw seed.

initWallet will also claim any pending incoming lightning payment, spark transfer, or bitcoin deposit.

async initWallet(mnemonicOrSeed?: Uint8Array | string): Promise<{
    mnemonic?: string;
    balance: bigint;
    tokenBalances: Map<string, {
        balance: bigint;
    }>;
}>

Parameters:

  • mnemonicOrSeed: (Optional) Either:
    • A BIP-39 mnemonic phrase as string
    • A raw seed as Uint8Array or hex string
    • If not provided, generates a new mnemonic and uses it to create a new wallet

Returns:

  • Object containing:
    • mnemonic: The mnemonic if one was generated (undefined for raw seed)
    • balance: The wallet’s initial balance in satoshis
    • tokenBalance: Map of token balances and leaf counts

Example:

// import the SparkWallet and Network from the spark-sdk
import { SparkWallet } from "@buildonspark/spark-sdk";
import { Network } from "@buildonspark/spark-sdk/utils";

// Initialize a new wallet instance
const wallet = new SparkWallet(Network.REGTEST); // or Network.MAINNET

// Create wallet from mnemonic
const menmonicPhrase = await wallet.initWallet("optional-mnemonic-or-seed");

console.log("Wallet initialized successfully:", menmonicPhrase);

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(forceRefetch?: boolean): Promise<{
    balance: bigint;
    tokenBalances: Map<string, {
        balance: bigint;
    }>;
}>

Parameters:

  • forceRefetch: (Optional) Synchronizes the wallet before returning the balance, which will claim any pending incoming lightning payment, spark transfer, or bitcoin deposit.

Returns:

  • Object containing:
    • balance: The wallet’s current balance in satoshis
    • tokenBalance: Map of token balances and leaf counts

Example:

const balance = await wallet.getBalance();
console.log("Balance:", balance);

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

Example:

const depositAddress = await wallet.getDepositAddress();
console.log("Deposit Address:", depositAddress);

sendSparkTransfer()

Sends a transfer to another Spark user.

async sendSparkTransfer({
    receiverSparkAddress: string,
    amountSats: number
}): Promise<Transfer>

Parameters:

  • receiverSparkAddress: The recipient’s Spark address
  • amountSats: Amount to send in satoshis

Returns:

  • Promise<Transfer>: The completed transfer details

Example:

const transfer = await wallet.sendSparkTransfer({
  receiverSparkAddress: "03e9cd9c3077c...",
  amountSats: 100,
});
console.log("Transfer:", transfer);

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

payLightningInvoice()

Pays a Lightning invoice.

async payLightningInvoice({
    invoice
}: PayLightningInvoiceParams): Promise<LightningSendRequest>

Parameters:

  • params: An object with the following properties:
    • invoice: (Required) The BOLT11-encoded Lightning invoice to pay

Returns:

  • Promise<LightningSendRequest>: The Lightning payment request details

Example:

const invoice_response = await wallet.payLightningInvoice({
  invoice: "lnbcrt1u1p...k", // BOLT11 invoice string
});
console.log("Invoice Response:", invoice_response);

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

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;
  senderIdentityPublicKey: Uint8Array;
  receiverIdentityPublicKey: Uint8Array;
  status: TransferStatus;
  totalValue: number;
  expiryTime: Date | undefined;
  leaves: TransferLeaf[];
}

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