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

TypeScript SDK for issuing and managing tokens on Spark. Requires Node.js v18+.

## 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 Issuer SDK packages using your package manager of choice.

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

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

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

  <Step title="Setup Issuer">
    Create an issuer instance that will be used to interact with the Spark network.

    ```ts issuer.ts theme={null}
      import { IssuerSparkWallet } from "@buildonspark/issuer-sdk";

      const { wallet, mnemonic } = await IssuerSparkWallet.initialize({
        mnemonicOrSeed: "optional-mnemonic-or-seed",
        accountNumber: 0, // optional
        options: {
          network: "REGTEST",
        },
      });
      console.log("Wallet initialized successfully:", mnemonic);
    ```
  </Step>

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

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

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

        console.log("Issuer wallet created!");
        console.log("Address:", await wallet.getSparkAddress());

        // Create a token
        const { tokenIdentifier, transactionHash } = await wallet.createToken({
          tokenName: "My Token",
          tokenTicker: "MTK",
          decimals: 8,
          maxSupply: BigInt(21000000_00000000), // 21M tokens (with 8 decimals)
          isFreezable: false,
          returnIdentifierForCreate: true,
        });

        console.log("Token created:", tokenIdentifier);
        console.log("Announcement tx:", transactionHash);

        // Mint tokens to yourself
        const mintTxId = await wallet.mintTokens({
          tokenIdentifier,
          tokenAmount: BigInt(1000_00000000), // 1000 tokens (with 8 decimals)
        });
        console.log("Tokens minted:", mintTxId);
      } 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 Issuer Operations

### Initialize an Issuer Wallet

An issuer 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}
import { IssuerSparkWallet } from "@buildonspark/issuer-sdk";

// Initialize a new issuer wallet
const { wallet, mnemonic } = await IssuerSparkWallet.initialize({
  mnemonicOrSeed: "optional-mnemonic-or-seed",
  accountNumber: 0, // optional
  options: {
    network: "REGTEST" // or "MAINNET"
  }
});

console.log("Issuer wallet initialized:", 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 issuer wallet.

## TypeScript Features

### Type Safety

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

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

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

// All methods are fully typed
const address: string = await wallet.getSparkAddress();
const tokensMetadata = await wallet.getIssuerTokensMetadata();
const tokenIdentifiers = await wallet.getIssuerTokenIdentifiers();
```

### Interface Definitions

Key interfaces used by the Issuer SDK:

```ts theme={null}
// Token creation parameters
interface CreateTokenParams {
  tokenName: string;
  tokenTicker: string;
  decimals: number;
  isFreezable: boolean;
  maxSupply?: bigint; // defaults to 0n (unlimited)
  extraMetadata?: Uint8Array;
  returnIdentifierForCreate?: boolean;
}

// Token metadata returned by getIssuerTokensMetadata()
interface IssuerTokenMetadata {
  rawTokenIdentifier: Uint8Array;
  tokenPublicKey: string;
  tokenName: string;
  tokenTicker: string;
  decimals: number;
  maxSupply: bigint;
  isFreezable: boolean;
  extraMetadata?: Uint8Array;
  bech32mTokenIdentifier: Bech32mTokenIdentifier;
}

// Token distribution stats
interface TokenDistribution {
  totalCirculatingSupply: bigint;
  totalIssued: bigint;
  totalBurned: bigint;
  numHoldingAddress: number;
  numConfirmedTransactions: bigint;
}
```

### Error Handling

The SDK provides typed error classes for better error handling:

```ts theme={null}
import { IssuerSparkWallet } from "@buildonspark/issuer-sdk";
import { SparkError, SparkValidationError } from "@buildonspark/spark-sdk";

const { wallet } = await IssuerSparkWallet.initialize({
  options: { network: "REGTEST" },
});

try {
  await wallet.createToken({
    tokenName: "My Token",
    tokenTicker: "MTK",
    decimals: 8,
    maxSupply: BigInt(21000000_00000000),
    isFreezable: false
  });
} catch (error) {
  if (error instanceof SparkValidationError) {
    console.error('Validation error:', error.message);
  } else if (error instanceof SparkError) {
    console.error('SDK error:', error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}
```
