### Setup Spark CLI and SDK Source: https://docs.spark.money/wallet/0-to-1 This snippet covers cloning the Spark SDK repository, installing dependencies, building the SDK, and launching the JavaScript CLI. ```shell # Clone the Spark SDK repo git clone https://github.com/buildonspark/spark.git # Navigate to the JS folder cd spark/sdks/js # Install dependencies and build the SDK yarn && yarn build # Navigate to the JS CLI folder cd examples/spark-cli # Start the CLi yarn cli ``` -------------------------------- ### Install Spark CLI and Dependencies Source: https://docs.spark.money/issuing/quick-launch This snippet shows how to clone the Spark repository, navigate to the JavaScript SDK directory, install dependencies, build the SDK, and finally run the Spark CLI example. ```bash git clone https://github.com/buildonspark/spark.git cd spark/sdks/js yarn install && yarn build cd examples/spark-cli yarn cli ``` -------------------------------- ### Install Dependencies with Yarn Source: https://docs.spark.money/wallet/code-samples Installs project dependencies using Yarn. This command should be run after navigating to the example project directory. ```bash yarn ``` -------------------------------- ### Spark CLI Tool Installation and Usage Source: https://docs.spark.money/issuing/testing-guide Instructions on how to install the Spark CLI tool by cloning the repository, navigating to the JS folder, installing dependencies, building the SDK, and starting the CLI. ```APIDOC ## Spark CLI Tool Installation and Usage ### Description This section guides you through the process of setting up and running the Spark CLI tool to interact with your Spark wallet. No coding is required. ### Installation Steps 1. Clone the Spark SDK repository: ```bash git clone https://github.com/buildonspark/spark.git ``` 2. Navigate to the JS SDK folder: ```bash cd spark/sdks/js ``` 3. Install dependencies and build the SDK: ```bash yarn && yarn build ``` 4. Navigate to the JS CLI folder: ```bash cd examples/spark-cli ``` 5. Start the CLI tool: ```bash yarn cli ``` Once started, you can interact with the wallet by running commands. Type `help` to see the list of available commands. ``` -------------------------------- ### Run Spark SDK Get Balance Sample Source: https://docs.spark.money/wallet/code-samples Executes the get_balance.ts TypeScript script from the Spark SDK examples. It requires a mnemonic phrase as an argument to retrieve the balance. ```bash yarn tsx ./src/spark-sdk/get_balance.ts "your_mnemonic_here" ``` -------------------------------- ### Navigate to Spark Node Express Example Source: https://docs.spark.money/wallet/code-samples Navigates to the directory containing the Spark Node.js Express server example. This directory contains the project files for a sample Express server. ```bash cd spark/sdks/js/examples/spark-node-express/ ``` -------------------------------- ### Install Spark Issuer SDK using npm Source: https://docs.spark.money/issuing/quickstart-setup Installs the Spark Issuer SDK using the npm package manager. Ensure Node.js version 16 or later is installed. ```bash npm i @buildonspark/issuer-sdk ``` -------------------------------- ### Navigate to Spark Nodejs Scripts Example Source: https://docs.spark.money/wallet/code-samples Navigates to the directory containing various Node.js script examples for the Spark SDK. These scripts demonstrate different functionalities. ```bash cd spark/sdks/js/examples/nodejs-scripts/ ``` -------------------------------- ### Install Spark SDK using Yarn Source: https://docs.spark.money/wallet/developer-guide/create-first-wallet This command installs the Spark SDK package using the Yarn package manager. Ensure you have Node.js and Yarn installed. ```bash yarn add @buildonspark/spark-sdk ``` -------------------------------- ### Install Spark Issuer SDK using Yarn Source: https://docs.spark.money/issuing/quickstart-setup Installs the Spark Issuer SDK using the Yarn package manager. Ensure Node.js version 16 or later is installed. ```bash yarn add @buildonspark/issuer-sdk ``` -------------------------------- ### Install Spark SDK with npm Source: https://docs.spark.money/wallet/documentation/api-reference Installs the Spark SDK package using the npm package manager. This provides an alternative installation method for Node.js projects. ```bash npm i @buildonspark/spark-sdk ``` -------------------------------- ### Navigate to Spark Node Express Project Directory Source: https://docs.spark.money/issuing/testing-guide This command changes the current directory to the Spark Node Express example project within the cloned Spark SDK repository. This is typically done to follow setup instructions for running the demo server. ```bash cd spark/sdks/js/examples/spark-node-express/ ``` -------------------------------- ### Clone Spark SDK Repository Source: https://docs.spark.money/wallet/code-samples Clones the Spark SDK repository from GitHub. This is the initial step to access the SDK examples and source code. ```git git clone https://github.com/buildonspark/spark.git ``` -------------------------------- ### Monitor for Static Deposit Transactions (JavaScript) Source: https://docs.spark.money/wallet/developer-guide/deposit-from-bitcoin Provides an example of how to monitor for new Bitcoin transactions sent to a static deposit address. This function itself does not perform monitoring but serves as a placeholder for implementing a custom monitoring solution using blockchain explorers or other infrastructure. ```javascript // You'll need to implement your own monitoring solution const staticAddress = await wallet.getStaticDepositAddress(); // Example: Monitor for new transactions using a block explorer API // const newTransactions = await yourBlockchainMonitor.checkAddress(staticAddress); ``` -------------------------------- ### Initiate Bitcoin Withdrawal with Fee Quote Source: https://docs.spark.money/wallet/developer-guide/cooperative-bitcoin-exit This snippet demonstrates how to get a fee quote for a withdrawal and then use that quote to initiate the withdrawal process. It highlights the importance of using the fee quote before it expires and explains fee deduction options. ```javascript // 1) Get a fee quote (quote includes expiry) const feeQuote = await wallet.getWithdrawalFeeQuote({ amountSats: 17000, withdrawalAddress: "bcrt1pf8hed85p94emupfpfhq2g0p5c40cgzqs4agvvfmeuy32nxeh549syu2lwf", }); // 2) Use the quote before it expires when calling withdraw const withdraw_result = await wallet.withdraw({ onchainAddress: "bcrt1pf8hed85p94emupfpfhq2g0p5c40cgzqs4agvvfmeuy32nxeh549syu2lwf", amountSats: 17000, exitSpeed: ExitSpeed.MEDIUM, feeQuote, deductFeeFromWithdrawalAmount: true, // default }); console.log("Withdraw Result:", withdraw_result); ``` -------------------------------- ### Start Interactive Unilateral Exit (Mainnet) Source: https://docs.spark.money/wallet/developer-guide/unilateral-exit Initiates an interactive unilateral exit process for mainnet. Users are responsible for manually handling timelocks and fee signing, and must provide their own UTXOs. ```bash # Mainnet: manual timelock and signing processsparkcli unilateralexit ``` -------------------------------- ### Initialize Spark Wallet Source: https://docs.spark.money/wallet/0-to-1 Commands to initialize a new Spark wallet or recover an existing one using a mnemonic phrase. ```shell > initwallet ``` ```shell > initwallet ``` -------------------------------- ### Start Interactive Unilateral Exit (Regtest) Source: https://docs.spark.money/wallet/developer-guide/unilateral-exit Initiates an interactive unilateral exit process specifically for regtest environments. It automatically handles timelocks and fee signing, simplifying testing. ```bash # Regtest only - auto-handles timelocks and fee signingsparkcli unilateralexit --testmode=true ``` -------------------------------- ### Sample Express Server Project Setup Source: https://docs.spark.money/issuing/testing-guide Instructions for setting up a sample Express server project using the Spark SDK, including cloning the repository and navigating to the project directory. ```APIDOC ## Sample Express Server Project Setup ### Description This section provides guidance on cloning the Spark SDK repository and navigating to the sample Express server project directory to follow the setup instructions in its README file. ### Cloning the SDK Repo ```bash git clone https://github.com/buildonspark/spark.git ``` ### Navigating to Project Directory ```bash cd spark/sdks/js/examples/spark-node-express/ ``` Follow the instructions in the `README` file within this directory to install dependencies and run the server. ``` -------------------------------- ### Transfer Funds via Spark Source: https://docs.spark.money/wallet/0-to-1 Instructions for sending funds between Spark wallets, including generating a Spark address and initiating a transfer. ```shell # Wallet 2 > initwallet > getsparkaddress # Wallet 1 > initwallet > sendtransfer # Example: > sendtransfer 1000 sprt1pgss9yrf7gljw2yr8fupgw9pevqnffs3qjz6cnnd87hvtt8hkfhsh66mq57r7e ``` -------------------------------- ### Example: Create Lightning Invoices (TypeScript) Source: https://docs.spark.money/wallet/documentation/api-reference Demonstrates how to create various types of Lightning invoices using the `createLightningInvoice` function, including basic, with Spark address, and for other users. ```typescript // 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); ``` -------------------------------- ### Clone Spark SDK and Build JS Source: https://docs.spark.money/wallet/testing-guide This snippet shows how to clone the Spark SDK repository and build the JavaScript SDK. This is a prerequisite for running any of the JavaScript examples or the Spark CLI. ```shell # Clone the Spark SDK repo git clone https://github.com/buildonspark/spark.git # Navigate to the JS folder cd spark/sdks/js # Install dependencies and build the SDK yarn && yarn build ``` -------------------------------- ### Initialize a New Wallet Source: https://docs.spark.money/issuing/quick-launch Command to create a new wallet for token issuance on Spark. It returns a wallet object and a mnemonic phrase, which should be treated as a root of trust. ```cli > initwallet ``` -------------------------------- ### Spark Wallet Deposit Operations Source: https://docs.spark.money/wallet/0-to-1 This section details how to generate a deposit address, retrieve the latest transaction hash for a deposit, and claim a deposit. ```shell > getdepositaddress ``` ```shell > getlatesttx # Example: > getlatesttx bcrt1pz5sxkd4eaycla7av8c9avmdleyertmhkh2zf60vrmn346wwnjayq8phsra ``` ```shell > claimdeposit # Example: > claimdeposit 2c5ccdc5852eb23662344c142970a1d96f2bed539a1be074cbbff65411ba3270 ``` ```shell > getbalance ``` -------------------------------- ### Get Issuer Token Distribution Source: https://docs.spark.money/issuing/quickstart-monitoring Get a snapshot of how your token is distributed, including metrics like wallets holding it, circulation, and burned tokens. ```APIDOC ## GET /api/tokens/distribution ### Description Retrieves a snapshot of the token's distribution metrics, including circulating supply, issued tokens, burned tokens, and the number of unique holders. ### Method GET ### Endpoint /api/tokens/distribution ### Response #### Success Response (200) - **totalCirculatingSupply** (string) - Total circulating supply of the token. - **totalIssued** (string) - Total number of tokens ever minted. - **totalBurned** (string) - Cumulative tokens burned. - **numHoldingAddress** (integer) - Number of unique token holders. - **numConfirmedTransactions** (integer) - Number of confirmed transactions involving this token. #### Response Example ```json { "totalCirculatingSupply": "9000000", "totalIssued": "10000000", "totalBurned": "1000000", "numHoldingAddress": 500, "numConfirmedTransactions": 1500 } ``` ``` -------------------------------- ### Clone Spark SDK Repository Source: https://docs.spark.money/issuing/testing-guide This command clones the official Spark SDK repository from GitHub. This is a prerequisite for accessing the CLI tool and other examples provided by the Spark project. ```bash git clone https://github.com/buildonspark/spark.git ``` -------------------------------- ### Mint Tokens on Spark Source: https://docs.spark.money/issuing/quick-launch Command to mint a specified amount of tokens for your created token. Minting is capped by the `maxSupply` defined during token creation and must originate from the issuer wallet. ```cli > minttokens 500000 ``` -------------------------------- ### Send and Receive Lightning Payment Source: https://docs.spark.money/wallet/0-to-1 This section demonstrates how to create and pay Lightning invoices between Spark wallets, including setting maximum fees. ```shell # Wallet 2 > initwallet > createinvoice # Example: > createinvoice 1000 Spark is awesome! # Wallet 1 > initwallet > payinvoice # Example: > payinvoice lnbcrt10u1p5pqphup[...]cpkql23a 200 ``` -------------------------------- ### Start Token Transaction Source: https://docs.spark.money/lrc20/broadcast-lifecycle Initiates a token transaction (mint or transfer) by signaling intent to Spark Operators and agreeing on transaction parameters. ```APIDOC ## POST /api/transactions/start ### Description Initiates a token transaction by specifying outputs to spend and recipient public keys. This step is non-binding and sets up the agreement on final transaction parameters. ### Method POST ### Endpoint /api/transactions/start ### Parameters #### Request Body - **identity_public_key** (bytes) - Required - The public key of the issuer. - **partial_token_transaction** (TokenTransaction) - Required - A partial token transaction detailing outputs to spend and intended recipients. - **token_transaction_signatures** (TokenTransactionSignatures) - Required - Signatures authorizing the movement of tokens from the input. ### Request Example ```json { "identity_public_key": "...", "partial_token_transaction": { "TokenInputs": { "TransferInput": { "OutputsToSpend": [ { "PrevTokenTransactionHash": "abcdef12345", "PrevTokenTransactionOutputVout": 0 }, { "PrevTokenTransactionHash": "abcdef12345", "PrevTokenTransactionOutputVout": 1 } ] } }, "TokenOutputs": [ { "OwnerPublicKey": "receiver1PublicKey", "TokenPublicKey": "sUSDPublicKey", "TokenAmount": 50 }, { "OwnerPublicKey": "receiver2PublicKey", "TokenPublicKey": "sUSDPublicKey", "TokenAmount": 50 } ], "SparkOperatorIdentityPublicKeys": ["sparkOperatorIdentityKey1", "sparkOperatorIdentityKey2"] }, "token_transaction_signatures": {} } ``` ### Response #### Success Response (200) - **final_token_transaction** (TokenTransaction) - The completed token transaction with output revocation public keys filled. - **keyshare_info** (SigningKeyshare) - Information for fetching and resolving the revocation keyshare on a transfer operation. #### Response Example ```json { "final_token_transaction": { "TokenInputs": { "TransferInput": { "OutputsToSpend": [ { "PrevTokenTransactionHash": "abcdef12345", "PrevTokenTransactionOutputVout": 0, "OutputId": "012131414153", "WithdrawalBondSats": "...", "WithdrawalRelativeBlockLocktime": "...", "RevocationCommitment": "outputUniqueRevocationComitment" } ] } }, "TokenOutputs": [ { "OwnerPublicKey": "receiver1PublicKey", "TokenPublicKey": "sUSDPublicKey", "TokenAmount": 50 } ], "SparkOperatorIdentityPublicKeys": ["sparkOperatorIdentityKey1", "sparkOperatorIdentityKey2"] }, "keyshare_info": { "threshold": 2, "owners": ["owner1", "owner2"] } } ``` ``` -------------------------------- ### Create an Unlimited Supply Token Source: https://docs.spark.money/issuing/quickstart-create-token This example shows how to create a token with an unlimited supply by setting `maxSupply` to `0n`. It includes defining the token's name, ticker, decimals, and whether it's freezable. ```javascript const txId = await wallet.createToken({ tokenName: "USD Coin", tokenTicker: "USDC", maxSupply: 0n, // Unlimited supply decimals: 6, // 1 USDC = 1_000_000 base units isFreezable: true, }); console.log("Token Creation TX:", txId); ``` -------------------------------- ### Transfer Tokens on Spark Source: https://docs.spark.money/issuing/quick-launch Command to transfer a specified amount of your created token to a recipient address. Transfers are instantly settled on Spark without requiring L1 confirmations. ```cli > transfertokens btkn1qwertyuiopasdfghjklzxcvbnm1234567890abcdef 100000 sprt1pgss8nz26ns2nde5mkszlrr7vljxnpjpxuqxn6ds3llzgql4luedmvlsnlnvmz ``` -------------------------------- ### Withdraw Funds to L1 Wallet Source: https://docs.spark.money/wallet/0-to-1 Steps for withdrawing funds from a Spark wallet to an L1 Bitcoin address, including checking withdrawal fees and executing the withdrawal. ```shell # Wallet 2 > initwallet > getdepositaddress # Wallet 1 > initwallet > withdrawalfee # Example: withdrawalfee 15000 bcrt1p6tx52amnr448lv8vyr7fumqt3c2qmlkg4hgvj8swxfcz8cayukvqwk9mu6 # If the fees are acceptable > withdraw # Example: > withdraw 15000 bcrt1pslvlzmkwz8f42u8vr2fkhdhyzyh2x5cwy8l0lpdnqr4ptsjrefrq0sd0gl FAST ``` ```shell # Wallet 2 > initwallet > claimdeposit ``` -------------------------------- ### Legacy Spark CLI Commands Source: https://docs.spark.money/wallet/developer-guide/unilateral-exit Includes legacy commands for expiring timelocks and signing fee bumps, which are now integrated into the main unilateral exit flow. ```bash # Legacy commands (now built into main flow)sparkcli testonly_expiretimelock sparkcli signfeebump ``` -------------------------------- ### Submit Transaction Packages via Bitcoin Core Source: https://docs.spark.money/wallet/developer-guide/unilateral-exit Submits transaction packages (node_tx and fee_bump_tx) using the bitcoin-cli command. This is used for broadcasting on mainnet. ```bash bitcoin-cli submitpackage '["node_tx", "fee_bump_tx"]' ``` -------------------------------- ### Token Identifier Example Source: https://docs.spark.money/issuing/get-token-identifier A sample Bech32m token identifier for the BTKN protocol, which includes the 'btkn' prefix. ```plaintext btkn1fvfy6hfa829lvs9fajqvpk0r8hj8vrfhxamsvugtfvydfm07mg4q7n7szd // This is a token named "Btest", created on 05/12/25 ``` -------------------------------- ### Generate Reusable Bitcoin Deposit Address (JavaScript) Source: https://docs.spark.money/wallet/developer-guide/deposit-from-bitcoin Generates a static, reusable Bitcoin deposit address using the Spark wallet. This address can receive multiple deposits and is recommended for most applications. It returns a P2TR address starting with 'bc1p'. Note that Spark currently supports only one static address per wallet. ```javascript const staticDepositAddress = await wallet.getStaticDepositAddress(); console.log("Static Deposit Address:", staticDepositAddress); // This address can be reused for multiple deposits ``` -------------------------------- ### Wallet Initialization Source: https://docs.spark.money/wallet/documentation/signing-interface Methods for initializing a Spark wallet, including generating a mnemonic, converting it to a seed, and creating a wallet from a seed. ```APIDOC ## generateMnemonic() ### Description Generates a new BIP39 mnemonic phrase for wallet creation. ### Method `async` ### Returns * `Promise`: A 12-word BIP39 mnemonic phrase ### Example ```javascript const mnemonic = await signer.generateMnemonic(); console.log(mnemonic); // "abandon ability able about above absent..." ``` ``` ```APIDOC ## mnemonicToSeed(mnemonic: string) ### Description Converts a BIP39 mnemonic phrase to a cryptographic seed. ### Method `async` ### Parameters * **`mnemonic`** (string) - Valid BIP39 mnemonic phrase ### Returns * `Promise`: 64-byte seed derived from the mnemonic ``` ```APIDOC ## createSparkWalletFromSeed(seed, accountNumber?) ### Description Initializes the signer with a master seed and derives all necessary keys. ### Method `async` ### Parameters * **`seed`** (Uint8Array | string) - Master seed as bytes or hex string * **`accountNumber`** (number) - Optional, default: 0 - Account index for key derivation ### Returns * `Promise`: Hex-encoded identity public key ### Example ```javascript const seed = await signer.mnemonicToSeed(mnemonic); const identityPubKey = await signer.createSparkWalletFromSeed(seed, 0); ``` ``` -------------------------------- ### SparkWallet Initialization Source: https://docs.spark.money/wallet/documentation/api-reference Initializes a new SparkWallet instance with provided credentials or generates a new one. ```APIDOC ## SparkWallet Initialization ### Description Creates and initializes a new SparkWallet instance. You can provide a mnemonic or seed, or let the SDK generate them. ### Method `SparkWallet.initialize(props: SparkWalletProps): Promise<{ wallet: SparkWallet; mnemonic?: string; }>;` ### Parameters #### Request Body - **`props`** (object) - Required - **`mnemonicOrSeed`** (Uint8Array | string) - Optional - BIP-39 mnemonic phrase or raw seed. - **`accountNumber`** (number) - Optional - Account number for key generation (defaults to 1). - **`signer`** (SparkSigner) - Optional - Custom signer implementation. - **`options`** (ConfigOptions) - Optional - Wallet configuration options. ### Response #### Success Response (200) - **`wallet`** (SparkWallet) - The initialized SparkWallet instance. - **`mnemonic`** (string) - The generated mnemonic phrase (if applicable). ### Request Example ```json { "mnemonicOrSeed": "your mnemonic phrase here", "accountNumber": 1 } ``` ### Response Example ```json { "wallet": "SparkWalletInstance", "mnemonic": "generated mnemonic if applicable" } ``` ``` -------------------------------- ### Get Token L1 Address Source: https://docs.spark.money/wallet/documentation/api-reference Gets the Layer 1 Bitcoin address used for token operations. ```APIDOC ## GET /getTokenL1Address ### Description Gets the Layer 1 Bitcoin address for token operations. ### Method GET ### Endpoint /getTokenL1Address ### Response #### Success Response (200) - **string** - The Layer 1 Bitcoin address. #### Response Example ```json "bc1q..." ``` ``` -------------------------------- ### Get Token Layer 1 Address Source: https://docs.spark.money/wallet/documentation/api-reference Gets the Layer 1 Bitcoin address associated with token operations within the wallet. ```typescript async getTokenL1Address(): Promise ``` -------------------------------- ### Spark CLI Command Reference Source: https://docs.spark.money/issuing/testing-guide A comprehensive list of commands available in the Spark CLI tool, detailing their usage for wallet and token management. ```APIDOC ## Spark CLI Command Reference ### Description This is a reference guide for all commands available in the Spark CLI tool. Each command's usage is explained below. ### Commands - **`initwallet`** - **Usage**: `initwallet ` - **Description**: Creates a new wallet instance. If no mnemonic or seed is provided, it generates a new one. - **`getbalance`** - **Description**: Retrieves the current wallet balance and token balances. - **`getsparkaddress`** - **Description**: Generates a new Spark Address for receiving transfers. - **`announcetoken`** - **Usage**: `announcetoken ` - **Description**: Mints a specified amount of tokens with provided details. - **`minttokens`** - **Usage**: `minttokens ` - **Description**: Mints a specified amount of tokens. - **`transfertokens`** - **Usage**: `transfertokens ` - **Description**: Sends tokens to a specified Spark Address using a Bech32m token identifier (e.g., `btkn1...`). - **`burntokens`** - **Usage**: `burntokens ` - **Description**: Burns the specified amount of tokens. - **`freezetokens`** - **Usage**: `freezetokens ` - **Description**: Freezes tokens associated with the given Spark Address. - **`unfreezetokens`** - **Usage**: `unfreezetokens ` - **Description**: Unfreezes tokens associated with the given Spark Address. - **`tokenactivity`** - **Description**: Fetches the token activity for the issuer's token. - **`tokeninfo`** - **Description**: Retrieves information about the issuer's token. - **`help`** - **Description**: Displays the help menu with all available commands. - **`exit`** - **Description**: Exits the Spark CLI tool. ``` -------------------------------- ### Sample Partial Token Transaction - Go Source: https://docs.spark.money/lrc20/broadcast-lifecycle Illustrates the construction of a partial token transaction in Go for transferring tokens. It specifies token inputs to be spent and token outputs with recipient public keys, token types, and amounts. ```go transferTokenTransaction := &pb.TokenTransaction{ TokenInputs: &pb.TokenTransaction_TransferInput{ TransferInput: &pb.TransferInput{ OutputsToSpend: []*pb.TokenOutputToSpend{ { PrevTokenTransactionHash: abcdef12345, PrevTokenTransactionOutputVout: 0, }, { PrevTokenTransactionHash: abcdef12345, PrevTokenTransactionOutputVout: 1, }, }, }, }, TokenOutputs: []*pb.TokenOutput{ { OwnerPublicKey: receiver1PublicKey, TokenPublicKey: sUSDPublicKey, TokenAmount: 50, }, { OwnerPublicKey: receiver2PublicKey, TokenPublicKey: sUSDPublicKey, TokenAmount: 50, }, }, SparkOperatorIdentityPublicKeys: []*bytes{sparkOperatorIdentityKey1,sparkOperatorIdentityKey2,…} } ``` -------------------------------- ### Get Token Identifier from Issuer Wallet Source: https://docs.spark.money/issuing/get-token-identifier Retrieves the token identifier directly from the issuer wallet using an asynchronous method. It logs the identifier to the console. ```javascript const tokenIdentifier = await issuerWallet.getIssuerTokenIdentifier(); console.log(tokenIdentifier); // Example: btkn1qwerty... ``` -------------------------------- ### Get Issuer Token Distribution Source: https://docs.spark.money/issuing/api-reference Gets the token distribution information for the issuer's token, including circulating supply, issued, burned tokens, and holding addresses. This feature is under development. ```typescript async function getIssuerTokenDistribution(): Promise; ``` -------------------------------- ### Initialize SparkWallet Instance Source: https://docs.spark.money/wallet/documentation/api-reference Initializes a new SparkWallet instance with provided parameters such as mnemonic, seed, or a custom signer. It can also configure wallet options and specifies the account number for key generation. ```typescript interface SparkWalletProps { mnemonicOrSeed?: Uint8Array | string; accountNumner?: number signer?: SparkSigner; options?: ConfigOptions; } static async initialize(props: SparkWalletProps): Promise<{ wallet: SparkWallet; mnemonic?: string; }> ``` -------------------------------- ### Get Withdrawal Fee Quote Source: https://docs.spark.money/wallet/documentation/api-reference Gets a fee quote for a cooperative exit (on-chain withdrawal). The quote includes options for different speeds and an expiry time and must be passed to `withdraw` before it expires. ```APIDOC ## GET /getWithdrawalFeeQuote ### Description Gets a fee quote for a cooperative exit (on-chain withdrawal). The quote includes options for different speeds and an expiry time and must be passed to `withdraw` before it expires. ### Method GET ### Endpoint /getWithdrawalFeeQuote ### Parameters #### Query Parameters - **amountSats** (number) - Required - The amount in satoshis to withdraw. - **withdrawalAddress** (string) - Required - The Bitcoin address where the funds should be sent. ### Response #### Success Response (200) - **WithdrawalFeeQuote | null** - A fee quote for the withdrawal, or null if not available. The fee quote object contains fee details and an expiry timestamp. #### Response Example ```json { "feeSats": 500, "expiry": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Get Token Identifier from Balance Call Source: https://docs.spark.money/issuing/get-token-identifier Obtains the token identifier by fetching the balance, where the token balances map includes the 'bech32mTokenIdentifier' for each token. It iterates through the balances to log each token identifier. ```javascript const balance = await issuerWallet.getBalance(); // The tokenBalances map now includes bech32mTokenIdentifier for each token for (const [publicKey, tokenData] of balance.tokenBalances) { console.log(`Token identifier: ${tokenData.bech32mTokenIdentifier}`); } ``` -------------------------------- ### Create a Basic Token Source: https://docs.spark.money/issuing/quickstart-create-token This snippet demonstrates how to create a new token on the Spark network with specified parameters like name, symbol, decimals, and supply. It uses the `createToken` method from the wallet SDK. ```javascript const tokenCreationTx = await wallet.createToken({ tokenName: "Test Token", tokenTicker: "TEST", decimals: 8, maxSupply: 10000000n, isFreezable: true, }); console.log("Token Creation TX:", tokenCreationTx); ``` -------------------------------- ### Get Claim Static Deposit Quote Source: https://docs.spark.money/wallet/documentation/api-reference Gets a quote for claiming a deposit made to a static deposit address. This method returns the transaction details, output index, credit amount in satoshis, and the SSP signature required for claiming. ```APIDOC ## GET /getClaimStaticDepositQuote ### Description Gets a quote for claiming a deposit made to a static deposit address. This method returns the transaction details, output index, credit amount in satoshis, and the SSP signature required for claiming. ### Method GET ### Endpoint /getClaimStaticDepositQuote ### Parameters #### Query Parameters - **txId** (string) - Required - The Bitcoin transaction ID of the deposit transaction. - **outputIndex** (number) - Optional - The index of the output. ### Response #### Success Response (200) - **object** - Object containing transaction details and claiming information. - **txId** (string) - The transaction ID. - **outputIndex** (number) - The index of the output. - **creditAmountSats** (number) - The credit amount in satoshis. - **sspSignature** (string) - The SSP signature required for claiming. #### Response Example ```json { "txId": "deposit-tx-id", "outputIndex": 0, "creditAmountSats": 10000, "sspSignature": "signature-data" } ``` ``` -------------------------------- ### Get Token Information Source: https://docs.spark.money/wallet/documentation/api-reference Retrieves information about all tokens owned by the wallet. ```APIDOC ## GET /getTokenInfo ### Description Gets information about tokens owned by the wallet. ### Method GET ### Endpoint /getTokenInfo ### Response #### Success Response (200) - **TokenInfo[]** - Array of token information objects. #### Response Example ```json [ { "identifier": "btkn1...", "balance": 1000000000, "decimals": 8 } ] ``` ``` -------------------------------- ### Initialize Spark Wallet in TypeScript/React Native Source: https://docs.spark.money/wallet/developer-guide/create-first-wallet Demonstrates how to initialize a Spark Wallet instance using the `SparkWallet.initialize` function. It supports initializing with a mnemonic or seed, auto-generating them if not provided, and allows specifying an account number and network. The function returns the wallet instance and the generated mnemonic. ```typescript // import the SparkWallet and wallet-config from the spark-sdk import { SparkWallet } from "@buildonspark/spark-sdk"; // Initialize a new wallet instance const { wallet, mnemonic } = await SparkWallet.initialize({ mnemonicOrSeed: "optional-mnemonic-or-seed", accountNumber: "optional-number" options: { network: "REGTEST" } }); console.log("Wallet initialized successfully:", mnemonic); ``` -------------------------------- ### Initialize Spark Wallet Source: https://docs.spark.money/issuing/quickstart-setup Initializes a Spark wallet instance using the IssuerSparkWallet class. It can accept a mnemonic or seed, an optional account number, and network options. If no mnemonic or seed is provided, a new one is auto-generated. The generated mnemonic should be stored securely. The accountNumber defaults to 1 for backwards compatibility. ```javascript import { IssuerSparkWallet } from "@buildonspark/issuer-sdk"; // Initialize a new wallet instance const { wallet, mnemonic } = await IssuerSparkWallet.initialize({ mnemonicOrSeed: "optional-mnemonic-or-seed", accountNumber: "optional-number", options: { network: "REGTEST", }, }); console.log("Wallet initialized successfully:", mnemonic); ``` -------------------------------- ### Get Transfers Source: https://docs.spark.money/wallet/documentation/api-reference Retrieves a list of recent transfers associated with the wallet. ```APIDOC ## Get Transfers ### Description Gets all transfers for the wallet, with support for pagination. ### Method `wallet.getTransfers(limit?: number, offset?: number): Promise<{ transfers: WalletTransfer[]; offset: number; }>;` ### Query Parameters - **`limit`** (number) - Optional - Maximum number of transfers to return (default: 20). - **`offset`** (number) - Optional - Offset for pagination (default: 0). ### Response #### Success Response (200) - **`transfers`** (Array) - An array of transfer objects. - **`offset`** (number) - The offset used for the next page of results. ### Response Example ```json { "transfers": [ { "id": "tx123", "amount": 10000, "timestamp": "2023-10-27T10:00:00Z" } ], "offset": 20 } ``` ``` -------------------------------- ### Get Spark Address Source: https://docs.spark.money/wallet/documentation/api-reference Retrieves the wallet's Spark Address. ```APIDOC ## Get Spark Address ### Description Gets the Spark Address of the wallet. ### Method `wallet.getSparkAddress(): Promise;` ### Response #### Success Response (200) - **`Promise`** - The Spark Address. ### Response Example ```json { "sparkAddress": "spark1q8z4..." } ``` ``` -------------------------------- ### Generate Mnemonic Phrase Source: https://docs.spark.money/wallet/documentation/signing-interface Generates a new BIP39 mnemonic phrase used for wallet creation. This is the first step in initializing a new Spark wallet. ```typescript async generateMnemonic(): Promise ``` ```javascript const mnemonic = await signer.generateMnemonic(); console.log(mnemonic); // "abandon ability able about above absent..." ``` -------------------------------- ### GET /lightning/send_request/{id} Source: https://docs.spark.money/wallet/documentation/api-reference Retrieves the status of a specific Lightning send request by its ID. ```APIDOC ## GET /lightning/send_request/{id} ### Description Retrieves the status of a specific Lightning send request by its ID. ### Method GET ### Endpoint /lightning/send_request/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the Lightning send request to check. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the send request. - **status** (string) - The current status of the send request (e.g., "pending", "success", "failed"). - **feePaidSat** (number) - The fee paid for the transaction in satoshis. #### Response Example ```json { "id": "send_67890", "status": "success", "feePaidSat": 5 } ``` #### Error Response (404) - **error** (string) - "Send request not found." ``` -------------------------------- ### Get Balance Source: https://docs.spark.money/wallet/documentation/api-reference Retrieves the current balance of the wallet in satoshis, including token balances. ```APIDOC ## Get Balance ### Description Gets the current balance of the wallet. Can optionally refetch to synchronize pending payments or deposits. ### Method `wallet.getBalance(): Promise<{ balance: bigint; tokenBalances: Map; }>;` ### Response #### Success Response (200) - **`balance`** (bigint) - The wallet’s current balance in satoshis. - **`tokenBalances`** (Map) - A map of token public keys to their balances and Bech32m token identifiers. ### Response Example ```json { "balance": 50000, "tokenBalances": { "token1": { "balance": 1000, "bech32mTokenIdentifier": "spark1token1..." } } } ``` ``` -------------------------------- ### Create Spark Wallet from Seed Source: https://docs.spark.money/wallet/documentation/signing-interface Initializes a new Spark wallet using a master seed. It derives all necessary keys for the wallet and returns the hex-encoded identity public key. ```typescript async createSparkWalletFromSeed( seed: Uint8Array | string, accountNumber?: number, ): Promise ``` ```javascript const seed = await signer.mnemonicToSeed(mnemonic); const identityPubKey = await signer.createSparkWalletFromSeed(seed, 0); ``` -------------------------------- ### Get Identity Public Key Source: https://docs.spark.money/wallet/documentation/api-reference Retrieves the wallet's identity public key. ```APIDOC ## Get Identity Public Key ### Description Gets the identity public key of the wallet. ### Method `wallet.getIdentityPublicKey(): Promise;` ### Response #### Success Response (200) - **`Promise`** - The identity public key as a hex string. ### Response Example ```json { "identityPublicKey": "02abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890" } ``` ``` -------------------------------- ### Get Cooperative Exit Request Source: https://docs.spark.money/wallet/documentation/api-reference Retrieves details of a cooperative exit request by its unique identifier. ```APIDOC ## GET /getCoopExitRequest/{id} ### Description Gets a cooperative exit request by ID. ### Method GET ### Endpoint /getCoopExitRequest/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the cooperative exit request. ### Response #### Success Response (200) - **CoopExitRequest | null** - The cooperative exit request details or null if not found. #### Response Example ```json { "id": "some-exit-request-id", "status": "COMPLETED", "onchainAddress": "bcrt1q..." } ``` ``` -------------------------------- ### Initialize Spark Wallet with SDK Source: https://docs.spark.money/wallet/documentation/identity-key-derivation Demonstrates how to initialize a Spark Wallet instance using the Spark SDK. This function can optionally take a mnemonic or seed, an account number, and wallet configuration options. If no account number is provided, it defaults to '1' for backward compatibility. ```javascript import { SparkWallet } from "@buildonspark/spark-sdk"; // Initialize a new wallet instance const { wallet, mnemonic } = await SparkWallet.initialize({ mnemonicOrSeed: "optional-mnemonic-or-seed", accountNumber: "optional-account-number", options: { network: "REGTEST", }, }); console.log("Wallet initialized successfully:", mnemonic); ``` -------------------------------- ### GET /lightning/receive_request/{id} Source: https://docs.spark.money/wallet/documentation/api-reference Retrieves the status of a specific Lightning receive request (invoice) by its ID. ```APIDOC ## GET /lightning/receive_request/{id} ### Description Retrieves the status of a specific Lightning receive request (invoice) by its ID. ### Method GET ### Endpoint /lightning/receive_request/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the invoice to check. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the invoice. - **paymentRequest** (string) - The BOLT11 payment request string. - **expiresAt** (string) - The ISO 8601 timestamp when the invoice expires. - **status** (string) - The current status of the invoice (e.g., "pending", "paid", "expired"). #### Response Example ```json { "id": "inv_12345", "paymentRequest": "lnbc1pvclz4f...", "expiresAt": "2023-10-27T10:00:00Z", "status": "paid" } ``` #### Error Response (404) - **error** (string) - "Invoice not found." ``` -------------------------------- ### Public Key Generation Source: https://docs.spark.money/wallet/documentation/signing-interface APIs for generating new public keys, optionally deterministically. ```APIDOC ## POST /wallet/public-key/generate ### Description Generates a new signing key pair and returns the public key. ### Method POST ### Endpoint /wallet/public-key/generate ### Parameters #### Request Body - **hash** (Uint8Array) - Optional: Deterministic hash for key derivation ### Request Example ```json { "hash": "..." } ``` ### Response #### Success Response (200) - **publicKey** (Uint8Array) - The generated public key #### Response Example ```json { "publicKey": "..." } ``` ``` -------------------------------- ### Get Unused Deposit Addresses Source: https://docs.spark.money/wallet/documentation/api-reference Retrieves a list of all unused Bitcoin deposit addresses for the wallet. ```APIDOC ## Get Unused Deposit Addresses ### Description Gets all unused deposit addresses for the wallet. ### Method `wallet.getUnusedDepositAddresses(): Promise;` ### Response #### Success Response (200) - **`Promise`** - An array of unused deposit addresses. ### Response Example ```json { "depositAddresses": [ "bc1pabc...", "bc1pdef..." ] } ``` ``` -------------------------------- ### Create a Token with Specific Denomination Source: https://docs.spark.money/issuing/quickstart-create-token This example demonstrates creating a token with a large maximum supply and a specific minimum denomination, similar to Bitcoin's structure. It uses `maxSupply` and `decimals` to define the token's characteristics. ```javascript // Create a token with max 21 million supply and minimum denomination of 0.00000001 const txId = await wallet.createToken({ tokenName: "Example Bitcoin", tokenTicker: "ExBTC", maxSupply: 2_100_000_000_000_000n, decimals: 8, isFreezable: false, }); console.log("Token Creation TX:", txId); ``` -------------------------------- ### Get Wallet Balance Source: https://docs.spark.money/wallet/developer-guide/balances Retrieves the current balance of the Spark wallet, including Bitcoin and token balances. ```APIDOC ## GET /wallet/balance ### Description Retrieves the current balance of the Spark wallet, including Bitcoin and token balances. ### Method GET ### Endpoint /wallet/balance ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **balance** (bigint) - The total amount in satoshis. - **tokenBalances** (Map) - A map of token balances. Each entry contains: - **balance** (bigint) - The token amount. - **tokenInfo** (object) - Information about the specific token. #### Response Example { "balance": "1234567890", "tokenBalances": { "0": { "balance": "5000", "tokenInfo": { "tokenId": "token123", "name": "Spark Token" } } } } ``` -------------------------------- ### Get Tracked Public Keys (TypeScript) Source: https://docs.spark.money/wallet/documentation/signing-interface Returns an array containing all public keys currently being tracked by the signer. ```typescript async getTrackedPublicKeys(): Promise ```