> ## Documentation Index
> Fetch the complete documentation index at: https://docs.spark.money/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

TypeScript SDK for building Bitcoin wallet applications on Node.js and browsers. Requires Node.js v18+.

<Frame className="chill">
  <img src="https://mintcdn.com/lightspark/LXy5D0om_64exAOj/images/wallets/ts-spark.png?fit=max&auto=format&n=LXy5D0om_64exAOj&q=85&s=ed07ba78f1ccf85d8912b6e93d7ee7cf" alt="TypeScript SDK" width="1920" height="1080" data-path="images/wallets/ts-spark.png" />
</Frame>

## Getting Started

To get started, follow the steps below.

<Tip>
  Want to skip the manual setup? Scaffold a new project instantly:

  ```bash theme={null}
  npx @buildonspark/create-spark-app my-app
  ```

  Supports React (Vite), Next.js, React Native, Expo, Express, and [more](https://github.com/buildonspark/spark).
</Tip>

<Steps>
  <Step title="Install SDK">
    Install the Spark SDK packages using your package manager of choice.

    <CodeGroup>
      ```bash npm theme={null}
      npm install @buildonspark/spark-sdk
      ```

      ```bash yarn theme={null}
      yarn add @buildonspark/spark-sdk
      ```

      ```bash pnpm theme={null}
      pnpm add @buildonspark/spark-sdk
      ```
    </CodeGroup>
  </Step>

  <Step title="Setup Wallet">
    Create a wallet instance that will be used to interact with the Spark network.

    ```ts wallet.ts theme={null}
    import { SparkWallet } from "@buildonspark/spark-sdk";

    export const initializeWallet = async () => {
      const { wallet, mnemonic } = await SparkWallet.initialize({
        mnemonicOrSeed: "optional-mnemonic-or-seed",
        accountNumber: 0, // optional
        options: {
          network: "REGTEST" // or "MAINNET"
        }
      });

      console.log("Wallet initialized successfully:", mnemonic);
      return wallet;
    };
    ```
  </Step>

  <Step title="Start Building">
    You're ready to start building.

    ```ts app.ts theme={null}
    import { SparkWallet } from "@buildonspark/spark-sdk";

    async function main() {
      try {
        // Initialize wallet
        const { wallet, mnemonic } = await SparkWallet.initialize({
          options: { network: "REGTEST" }
        });

        console.log("Wallet created successfully!");
        console.log("Mnemonic:", mnemonic);
        console.log("Address:", await wallet.getSparkAddress());
        
        const { balance } = await wallet.getBalance();
        console.log("Balance:", balance, "sats");

        // Example: Send Bitcoin
        const transfer = await wallet.transfer({
          receiverSparkAddress: "spark1...",
          amountSats: 1000,
        });

        console.log("Transfer completed:", transfer.id);
      } catch (error) {
        console.error("Error:", error);
      }
    }

    main();
    ```
  </Step>
</Steps>

## TypeScript Configuration

### tsconfig.json

Create a `tsconfig.json` file in your project root:

```json tsconfig.json theme={null}
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}
```

### Package.json Scripts

Add TypeScript build scripts to your `package.json`:

```json package.json theme={null}
{
  "scripts": {
    "build": "tsc",
    "start": "node dist/app.js",
    "dev": "ts-node src/app.ts",
    "watch": "tsc --watch"
  }
}
```

## Core Wallet Operations

### Initialize a Wallet

A wallet requires either a mnemonic or raw seed for initialization. The `initialize()` function accepts both. If no input is given, it will auto-generate a mnemonic and return it.

```ts theme={null}
// Initialize a new wallet instance
const { wallet, mnemonic } = await SparkWallet.initialize({
  mnemonicOrSeed: "optional-mnemonic-or-seed",
  accountNumber: 0, // optional
  options: {
    network: "REGTEST" // or "MAINNET"
  }
});

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

### Mnemonic Phrases

A mnemonic is a human-readable encoding of your wallet's seed. It's a 12- or 24-word phrase from the BIP-39 wordlist, used to derive the cryptographic keys that control your wallet.

## TypeScript Features

### Type Safety

The Spark TypeScript SDK provides full type safety for all wallet operations:

```ts theme={null}
import { SparkWallet } from "@buildonspark/spark-sdk";

// TypeScript will provide autocomplete and type checking
const { wallet } = await SparkWallet.initialize({
  options: { network: "REGTEST" }
});

// All methods are fully typed
const address: string = await wallet.getSparkAddress();
const { balance, tokenBalances } = await wallet.getBalance();
// balance: bigint (satoshis)
// tokenBalances: Map<Bech32mTokenIdentifier, { ownedBalance: bigint, availableToSendBalance: bigint, tokenMetadata }>
```

### Interface Definitions

All wallet methods return properly typed interfaces:

```ts theme={null}
interface InitResult {
  wallet: SparkWallet;
  mnemonic?: string; // undefined if raw seed was provided
}

interface BalanceResult {
  balance: bigint;
  tokenBalances: Map<string, { ownedBalance: bigint; availableToSendBalance: bigint; tokenMetadata: UserTokenMetadata }>;
}

interface WalletTransfer {
  id: string;
  senderIdentityPublicKey: string;
  receiverIdentityPublicKey: string;
  status: TransferStatus; // See TransferStatus enum below
  totalValue: number;
  expiryTime: Date | undefined;
  leaves: WalletTransferLeaf[];
  createdTime: Date | undefined;
  updatedTime: Date | undefined;
  type: TransferType; // "TRANSFER" | "COOPERATIVE_EXIT" | "PREIMAGE_SWAP" | "UTXO_SWAP"
  transferDirection: "INCOMING" | "OUTGOING";
  userRequest: UserRequestType | undefined;
  sparkInvoice: string | undefined; // Spark invoice associated with this transfer
}

// Common status values you'll encounter:
type TransferStatus =
  | "TRANSFER_STATUS_COMPLETED"
  | "TRANSFER_STATUS_EXPIRED"
  | "TRANSFER_STATUS_RETURNED"
  | "TRANSFER_STATUS_SENDER_INITIATED"
  // ... and other intermediate states
```
