### Install SDK with Optional Dependencies Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Install the SDK with optional peer dependencies for full wallet integration or a lightweight backend setup. ```bash # For full wallet integration (frontend) bun i @flashnet/sdk @buildonspark/spark-sdk @buildonspark/issuer-sdk # For backend/lightweight usage (no wallet) bun i @flashnet/sdk ``` -------------------------------- ### Install @flashnet/sdk Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Install the Flashnet SDK using npm or yarn. ```bash npm install @flashnet/sdk # or yarn add @flashnet/sdk ``` -------------------------------- ### Install Flashnet SDK Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Install the Flashnet SDK using your preferred package manager. ```bash bun add @flashnet/sdk # or npm install @flashnet/sdk # or yarn add @flashnet/sdk ``` -------------------------------- ### FlashnetClient Swap Operations Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Demonstrates the swap operations using FlashnetClient, starting with simulating a swap to get expected outcomes, followed by executing a swap with automatic balance checking and slippage tolerance. ```typescript // Simulate first const simulation = await client.simulateSwap({ poolId: "pool-id", assetInTokenPublicKey: "token-in", assetOutTokenPublicKey: "token-out", amountIn: 1000000, }); // Execute with automatic balance checking await client.executeSwap({ poolId: "pool-id", assetInTokenPublicKey: "token-in", assetOutTokenPublicKey: "token-out", amountIn: 1000000n, minAmountOut: 950000n, maxSlippageBps: 500, }); ``` -------------------------------- ### Setup and Use Modular Components Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Illustrates setting up modular components of the Flashnet SDK, including API client, authentication, and typed AMM API wrappers. It shows how to list pools and simulate a swap. ```typescript import { ApiClient, AuthManager, TypedAmmApi, getNetworkConfig, encodeSparkAddress, generatePoolSwapIntentMessage, generateNonce, createWalletSigner, } from "@flashnet/sdk"; // Setup const config = getNetworkConfig("MAINNET"); const apiClient = new ApiClient(config); const api = new TypedAmmApi(apiClient); // Create typed API wrapper // Authenticate with wallet const signer = createWalletSigner(wallet); const authManager = new AuthManager(apiClient, publicKey, signer); const token = await authManager.authenticate(); apiClient.setAuthToken(token); // Use typed endpoints const pools = await api.listPools({ limit: 10, sort: "tvlDesc", minTvl: 1000000, // $10k minimum }); // Manual swap flow const simulation = await api.simulateSwap({ poolId: "pool-id", assetInTokenPublicKey: "token-in", assetOutTokenPublicKey: "token-out", amountIn: 1000000, }); // Generate and sign intent const intentMessage = generatePoolSwapIntentMessage({ userPublicKey: publicKey, lpIdentityPublicKey: poolId, assetASparkTransferId: transferId, assetInTokenPublicKey: "token-in", assetOutTokenPublicKey: "token-out", amountIn: "1000000", minAmountOut: "950000", maxSlippageBps: "500", nonce: generateNonce(), }); const signature = await signer.signMessage( await crypto.subtle.digest("SHA-256", intentMessage) ); // Execute swap const swap = await api.executeSwap({ // ... swap parameters signature: typeof Buffer === "function" ? Buffer.from(signature).toString("hex") : signature.toHex(), }); ``` -------------------------------- ### FlashnetClient Pool Operations Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Provides examples for listing and searching pools, retrieving specific pool details, and getting LP positions. It also includes creating constant product pools and single-sided pools. ```typescript // List and search pools await client.listPools({ limit: 10, sort: "tvlDesc" }); // Get pool details await client.getPool(poolId); // Get LP position await client.getLpPosition(poolId); // Create pools with automatic initial deposits await client.createConstantProductPool({ assetATokenPublicKey: "token-a", assetBTokenPublicKey: "token-b", lpFeeRateBps: 30, totalHostFeeRateBps: 10, initialLiquidity: { // Optional assetAAmount: 1000000n, assetBAmount: 5000n, }, }); await client.createSingleSidedPool({ assetATokenPublicKey: "token-a", assetBTokenPublicKey: BTC_ASSET_PUBKEY, assetAInitialReserve: "1000000", // ... other parameters }); ``` -------------------------------- ### Register and Manage Host Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Register a new host, retrieve host information, and get pool host fees. Fee recipient can be optionally specified during registration. ```typescript await client.registerHost({ namespace: "my-exchange", minFeeBps: 50, feeRecipientPublicKey: "optional-different-pubkey", }); ``` ```typescript await client.getHost("my-exchange"); ``` ```typescript await client.getPoolHostFees("my-exchange", "pool-id"); ``` -------------------------------- ### List and Get Pool Information Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Use these methods to query pools. `listPools` allows for pagination and filtering by host namespace, while `getPool` retrieves details for a specific pool ID. ```typescript const pools = await api.listPools({ hostNamespace: "flashnet_pools", limit: 20 }); // { pools: [...], total: 42 } ``` ```typescript const pool = await api.getPool("pool_abc123"); // { poolId, assetAAddress, assetBAddress, reserveA, reserveB, lpFeeRateBps, ... } ``` -------------------------------- ### FlashnetClient Liquidity Management Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Covers managing liquidity within pools using the FlashnetClient. Examples include adding liquidity with specified amounts, retrieving LP positions, and removing liquidity by specifying the amount of LP tokens to redeem. ```typescript // Add liquidity await client.addLiquidity({ poolId: "pool-id", assetAAmount: 1000000n, assetBAmount: 5000n, }); await client.getLpPosition("pool-id"); // Remove liquidity await client.removeLiquidity({ poolId: "pool-id", lpTokensToRemove: "500000", }); ``` -------------------------------- ### Get Network Configuration Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Resolve network configuration (gateway URLs, etc.) for a named environment or validate a custom configuration. ```typescript import { getClientNetworkConfig } from "@flashnet/sdk"; // Supported environments: "mainnet" | "regtest" | "testnet" | "signet" | "local" const config = getClientNetworkConfig("mainnet"); // { // ammGatewayUrl: "https://api.flashnet.xyz", // mempoolApiUrl: "https://mempool.space", // explorerUrl: "https://mempool.space", // sparkScanUrl: "https://api.sparkscan.io" // } ``` ```typescript import { validateClientNetworkConfig } from "@flashnet/sdk"; const custom = { ammGatewayUrl: "https://my-node", mempoolApiUrl: "https://mempool.space", explorerUrl: "https://mempool.space" }; const { valid, errors } = validateClientNetworkConfig(custom); if (!valid) throw new Error(errors.join(", ")); ``` -------------------------------- ### Make Mempool API Requests Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Perform GET requests to the Mempool API. ```typescript // Mempool API GET const feeEstimate = await client.mempoolGet<{ fastestFee: number }>("/api/v1/fees/recommended"); ``` -------------------------------- ### Make SparkScan API Requests Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Perform GET requests to the SparkScan API. Requires sparkScanUrl in the client configuration. ```typescript // SparkScan GET (requires sparkScanUrl in config) const tokenInfo = await client.sparkScanGet("/tokens/btkn1abc..."); ``` -------------------------------- ### Make Raw AMM Requests Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Perform raw GET and POST requests to the AMM Gateway. ```typescript // Raw AMM GET const pingResult = await client.ammGet<{ status: string }>("/v1/ping"); ``` ```typescript // Raw AMM POST const swapResult = await client.ammPost("/v1/swap", { userPublicKey: "02abc...", lpIdentityPublicKey: "03def...", // ... full swap request body }); ``` -------------------------------- ### Initialize and Use FlashnetClient Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Demonstrates initializing the FlashnetClient with a wallet, checking balances, creating a constant product pool with initial liquidity, and executing a swap with slippage tolerance. ```typescript import { FlashnetClient } from "@flashnet/sdk"; import { IssuerSparkWallet } from "@buildonspark/issuer-sdk"; // Initialize wallet and client const { wallet } = await IssuerSparkWallet.initialize({ mnemonicOrSeed: process.env.MNEMONIC, }); const client = new FlashnetClient(wallet); // Check balance const balance = await client.getBalance(); console.log(`BTC: ${balance.balance} sats`); console.log(`Tokens: ${balance.tokenBalances.size}`); // Create a constant product pool with initial liquidity const pool = await client.createConstantProductPool({ assetATokenPublicKey: "token-pubkey", assetBTokenPublicKey: BTC_ASSET_PUBKEY, lpFeeRateBps: 30, // 0.3% totalHostFeeRateBps: 10, // 0.1% initialLiquidity: { assetAAmount: 1000000n, assetBAmount: 5000n, }, }); // Execute a swap (with automatic balance checking) const swap = await client.executeSwap({ poolId: pool.poolId, assetInTokenPublicKey: "token-in", assetOutTokenPublicKey: BTC_ASSET_PUBKEY, amountIn: 100000n, minAmountOut: 450n, maxSlippageBps: 500, // 5% slippage tolerance }); ``` -------------------------------- ### Initialize FlashnetClient with Options Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Shows how to initialize the FlashnetClient with optional configuration, such as disabling automatic authentication. Also demonstrates accessing client properties like wallet, network type, public key, and Spark address. ```typescript const client = new FlashnetClient(wallet, { autoAuthenticate: true, // Default: true }); // Properties client.wallet; // Access underlying SparkWallet client.networkType; // Get network type client.pubkey; // Get wallet public key client.address; // Get Spark address ``` -------------------------------- ### Get Concentrated Balances Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Retrieves the concentrated balances for all pools. ```APIDOC ## Get Concentrated Balances ### Description Retrieves the concentrated balances for all pools. ### Method `api.getConcentratedBalances` ### Response #### Success Response (200) - `balances` (array) - An array of concentrated balance objects. ``` -------------------------------- ### Initialize and Use FlashnetClient Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Initialize the `FlashnetClient` for a complete, ready-to-use solution with automatic network detection and authentication. This approach is recommended for most users. ```typescript import { FlashnetClient } from "@flashnet/sdk"; import { IssuerSparkWallet } from "@buildonspark/issuer-sdk"; // Initialize wallet const { wallet } = await IssuerSparkWallet.initialize({ mnemonicOrSeed: "your-mnemonic", options: { network: "MAINNET" }, }); // Create client - handles everything automatically const client = new FlashnetClient(wallet); await client.initialize(); // Auto-detects network and authenticates // Ready to use! const pools = await client.listPools(); const swapResult = await client.executeSwap({ poolId: "pool-id", assetInTokenPublicKey: "token-in", assetOutTokenPublicKey: "token-out", amountIn: 1000000n, minAmountOut: 950000n, maxSlippageBps: 500, }); ``` -------------------------------- ### Get Single Concentrated Balance Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Retrieves the concentrated balance for a specific pool. ```APIDOC ## Get Single Concentrated Balance ### Description Retrieves the concentrated balance for a specific pool. ### Method `api.getConcentratedBalance` ### Parameters - `poolId` (string) - Required - The ID of the pool. ### Response #### Success Response (200) - `balance` (object) - The concentrated balance object for the specified pool. ``` -------------------------------- ### Query Configuration Status, Min Amounts, and Allowed Assets Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Use these methods to retrieve configuration details from the API. Ensure the API object is properly initialized. ```typescript const features = await api.getFeatureStatus(); // { swapsEnabled: true, liquidityEnabled: true, ... } ``` ```typescript const mins = await api.getMinAmounts(); // { BTC: "1000", ... } ``` ```typescript const assets = await api.getAllowedAssets(); // { assets: ["020202...", "03abc..."] } ``` -------------------------------- ### Get Pool Details Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Retrieve detailed information about a specific pool using its ID. ```APIDOC ## Get Pool Details ### Description Retrieve detailed information about a specific pool using its ID. ### Method `client.getPool(poolId: string)` ### Parameters - `poolId` (string) - The unique identifier of the pool. ### Request Example ```typescript await client.getPool(poolId); ``` ``` -------------------------------- ### FlashnetClient Initialization Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Initialize the FlashnetClient with a wallet and optional configuration. Access underlying properties like wallet, network type, public key, and address. ```APIDOC ## FlashnetClient Initialization ### Description Initialize the FlashnetClient with a wallet and optional configuration. Access underlying properties like wallet, network type, public key, and address. ### Initialization ```typescript const client = new FlashnetClient(wallet, { autoAuthenticate: true, // Default: true }); ``` ### Properties - `client.wallet`: Access underlying SparkWallet - `client.networkType`: Get network type - `client.pubkey`: Get wallet public key - `client.address`: Get Spark address ``` -------------------------------- ### Simulate and Execute Swap Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Simulates a token swap to determine expected output and then executes the swap. Requires pool and asset details, amounts, and slippage tolerance. ```APIDOC ## `api.simulateSwap` / `api.executeSwap` — Swap tokens ### Description Simulates a token swap to determine expected output and then executes the swap. Requires pool and asset details, amounts, and slippage tolerance. ### Simulate Swap ```typescript const simulation = await api.simulateSwap({ lpIdentityPublicKey: "03pool...", assetInAddress: "020202...", // BTC in assetOutAddress: "03token...", amountIn: "100000", // satoshis maxSlippageBps: "500", // 5% totalIntegratorFeeRateBps: "0", }); console.log("Expected out:", simulation.amountOut, "Min out:", simulation.minAmountOut); ``` ### Execute Swap ```typescript const nonce = crypto.randomUUID(); const intentBytes = generatePoolSwapIntentMessage({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", assetInSparkTransferId: "transfer_id_of_btc", assetInAddress: "020202...", assetOutAddress: "03token...", amountIn: "100000", maxSlippageBps: "500", minAmountOut: simulation.minAmountOut, totalIntegratorFeeRateBps: "0", nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); const swapResult = await api.executeSwap({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", assetInSparkTransferId: "transfer_id_of_btc", assetInAddress: "020202...", assetOutAddress: "03token...", amountIn: "100000", maxSlippageBps: "500", minAmountOut: simulation.minAmountOut, totalIntegratorFeeRateBps: "0", nonce, signature, }); // { amountOut: "9875432", swapId: "swap_abc" } ``` ``` -------------------------------- ### Create a Constant Product Pool with Signature Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Create a constant product (x*y=k) pool by generating an initialization intent message, signing it, and then calling the API. Requires crypto and wallet objects. ```typescript import { generateConstantProductPoolInitializationIntentMessage } from "@flashnet/sdk"; const nonce = crypto.randomUUID(); const intentBytes = generateConstantProductPoolInitializationIntentMessage({ poolOwnerPublicKey: "02abc...", assetAAddress: "020202020202020202020202020202020202020202020202020202020202020202", // BTC assetBAddress: "03def...", // custom token lpFeeRateBps: "30", // 0.30% totalHostFeeRateBps: "10", // 0.10% nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); const pool = await api.createConstantProductPool({ poolOwnerPublicKey: "02abc...", assetAAddress: "020202...", assetBAddress: "03def...", lpFeeRateBps: "30", totalHostFeeRateBps: "10", nonce, signature, }); // { poolId: "pool_abc123", lpWalletAddress: "spark1..." } ``` -------------------------------- ### Configuration Queries Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Retrieve configuration details such as feature enablement, minimum amounts for operations, and allowed assets. ```APIDOC ## Configuration Queries ### Description These methods allow you to query the current configuration of the Flashnet protocol. ### Methods - `api.getFeatureStatus()`: Retrieves the status of various features (e.g., swaps, liquidity). - `api.getMinAmounts()`: Gets the minimum amounts required for certain operations. - `api.getAllowedAssets()`: Lists the assets that are currently allowed on the network. ### Request Example ```typescript const features = await api.getFeatureStatus(); // { swapsEnabled: true, liquidityEnabled: true, ... } const mins = await api.getMinAmounts(); // { BTC: "1000", ... } const assets = await api.getAllowedAssets(); // { assets: ["020202...", "03abc..."] } ``` ``` -------------------------------- ### Get LP Position Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Retrieve information about a user's liquidity provider (LP) position in a specific pool. ```APIDOC ## Get LP Position ### Description Retrieve information about a user's liquidity provider (LP) position in a specific pool. ### Method `client.getLpPosition(poolId: string)` ### Parameters - `poolId` (string) - The unique identifier of the pool. ### Request Example ```typescript await client.getLpPosition("pool-id"); ``` ``` -------------------------------- ### Token Address Utilities Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Derives and encodes deterministic token identifiers from issuer metadata using bech32m. Supports getting raw identifiers and human-readable versions. ```typescript import { getTokenIdentifier, getHumanReadableTokenIdentifier, encodeSparkHumanReadableTokenIdentifier, decodeSparkHumanReadableTokenIdentifier, } from "@flashnet/sdk"; const tokenMeta = { issuerPublicKey: "02abc...", name: "MyToken", ticker: "MTK", decimals: 8, maxSupply: 21_000_000n * 100_000_000n, isFreezable: false, network: "MAINNET" as const, creationEntityPublicKey: "0205fe807e8fe1f368df955cc291f16d840b7f28374b0ed80b80c3e2e0921a0674", }; // Get raw 32-byte identifier const identifier: Uint8Array = getTokenIdentifier(tokenMeta); // Get human-readable bech32m encoded identifier const hrId = getHumanReadableTokenIdentifier(tokenMeta); // "btkn1..." // Encode/decode standalone const encoded = encodeSparkHumanReadableTokenIdentifier(identifier, "MAINNET"); const decoded = decodeSparkHumanReadableTokenIdentifier(encoded, "MAINNET"); // { tokenIdentifier: "hexstring...", network: "MAINNET" } ``` -------------------------------- ### Register a Liquidity Host with Signature Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Register a liquidity host by generating an intent message, signing it with the identity key, and then calling the API. Requires crypto and wallet objects. ```typescript import { generateRegisterHostIntentMessage } from "@flashnet/sdk"; const nonce = crypto.randomUUID(); const intentBytes = generateRegisterHostIntentMessage({ namespace: "my_dex", minFeeBps: 10, feeRecipientPublicKey: "02abc...", nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); const result = await api.registerHost({ namespace: "my_dex", minFeeBps: 10, feeRecipientPublicKey: "02abc...", nonce, signature, }); // { success: true, hostId: "..." } ``` -------------------------------- ### Initialize ApiClient Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Initialize the low-level ApiClient with network configuration. ```typescript import { ApiClient, getClientNetworkConfig } from "@flashnet/sdk"; const config = getClientNetworkConfig("mainnet"); const client = new ApiClient(config); ``` -------------------------------- ### Initialize API Client Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Initialize the API client with configuration. Use direct endpoints for raw HTTP requests or the typed API wrapper for type-safe interactions. ```typescript import { ApiClient } from "@flashnet/sdk"; const client = new ApiClient(config); ``` ```typescript // Direct endpoints const pools = await client.ammGet("/v1/pools"); const swapResult = await client.ammPost("/v1/swap", swapData); ``` ```typescript // Typed API wrapper import { TypedAmmApi } from "@flashnet/sdk"; const api = new TypedAmmApi(client); const pools = await api.listPools({ limit: 10 }); ``` -------------------------------- ### Authentication with Wallets and Custom Signers Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Set up authentication using either a Spark Wallet or a custom signer implementation. Ensure your custom signer implements the Signer interface. ```typescript // Using Spark Wallet const authManager = new AuthManager(apiClient, pubkey, wallet); ``` ```typescript // Using Custom Signer class MyCustomSigner implements Signer { async signMessage(message: Uint8Array): Promise { // Your signing logic return signature; } } const signer = new MyCustomSigner(); const authManager = new AuthManager(apiClient, pubkey, signer); await authManager.authenticate(); ``` -------------------------------- ### Manage Escrow Operations with SDK Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Create, fund, claim, and inspect escrow states. Requires creator and recipient wallet instances for different operations. ```typescript import { generateCreateEscrowIntentMessage, generateFundEscrowIntentMessage, generateClaimEscrowIntentMessage, } from "@flashnet/sdk"; // Create const cNonce = crypto.randomUUID(); const cBytes = generateCreateEscrowIntentMessage({ creatorPublicKey: "02abc...", assetId: "03token...", assetAmount: "500000", recipients: [{ publicKey: "02rec...", amount: "500000" }], claimConditions: [{ type: "signature", publicKey: "02rec..." }], nonce: cNonce, }); const cSig = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(cBytes), true); const escrow = await api.createEscrow({ creatorPublicKey: "02abc...", assetId: "03token...", assetAmount: "500000", recipients: [{ publicKey: "02rec...", amount: "500000" }], claimConditions: [{ type: "signature", publicKey: "02rec..." }], nonce: cNonce, signature: cSig }); // Fund const fNonce = crypto.randomUUID(); const fBytes = generateFundEscrowIntentMessage({ escrowId: escrow.escrowId, creatorPublicKey: "02abc...", sparkTransferId: "tx_fund", nonce: fNonce }); const fSig = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(fBytes), true); await api.fundEscrow({ escrowId: escrow.escrowId, creatorPublicKey: "02abc...", sparkTransferId: "tx_fund", nonce: fNonce, signature: fSig }); // Claim (recipient side) const claimNonce = crypto.randomUUID(); const claimBytes = generateClaimEscrowIntentMessage({ escrowId: escrow.escrowId, recipientPublicKey: "02rec...", nonce: claimNonce }); const claimSig = await recipientWallet.signMessageWithIdentityKey(new TextDecoder().decode(claimBytes), true); await api.claimEscrow({ escrowId: escrow.escrowId, recipientPublicKey: "02rec...", nonce: claimNonce, signature: claimSig }); // Inspect state const state = await api.getEscrow(escrow.escrowId); // { escrowId, status: "claimed", assetId, assetAmount, recipients, ... } ``` -------------------------------- ### Simulate and Execute Add Liquidity Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Use `simulateAddLiquidity` to determine optimal asset amounts and `addLiquidity` to deposit them. The simulation provides minimum required amounts for slippage protection. ```typescript import { generateAddLiquidityIntentMessage } from "@flashnet/sdk"; const sim = await api.simulateAddLiquidity({ lpIdentityPublicKey: "03pool...", assetAAmount: "100000", assetBAmount: "200000", }); const nonce = crypto.randomUUID(); const intentBytes = generateAddLiquidityIntentMessage({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", assetASparkTransferId: "transfer_a", assetBSparkTransferId: "transfer_b", assetAAmount: sim.assetAAmount, assetBAmount: sim.assetBAmount, assetAMinAmountIn: sim.assetAMinAmountIn, assetBMinAmountIn: sim.assetBMinAmountIn, nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); await api.addLiquidity({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", assetASparkTransferId: "transfer_a", assetBSparkTransferId: "transfer_b", assetAAmount: sim.assetAAmount, assetBAmount: sim.assetBAmount, assetAMinAmountIn: sim.assetAMinAmountIn, assetBMinAmountIn: sim.assetBMinAmountIn, nonce, signature }); ``` -------------------------------- ### Register Host Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Register a new liquidity host on the Flashnet network. ```APIDOC ## Register Host ### Description Registers a new liquidity host, enabling it to participate in the Flashnet network. ### Method `api.registerHost(params)` ### Parameters - **namespace** (string) - Required - The namespace for the host. - **minFeeBps** (number) - Required - The minimum fee in basis points. - **feeRecipientPublicKey** (string) - Required - The public key of the fee recipient. - **nonce** (string) - Required - A unique nonce for the transaction. - **signature** (string) - Required - The signature generated for the intent message. ### Request Example ```typescript import { generateRegisterHostIntentMessage } from "@flashnet/sdk"; const nonce = crypto.randomUUID(); const intentBytes = generateRegisterHostIntentMessage({ namespace: "my_dex", minFeeBps: 10, feeRecipientPublicKey: "02abc...", nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); const result = await api.registerHost({ namespace: "my_dex", minFeeBps: 10, feeRecipientPublicKey: "02abc...", nonce, signature, }); // { success: true, hostId: "..." } ``` ``` -------------------------------- ### Use Modular Components for Customization Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Build a custom client using individual SDK components for maximum flexibility. This approach is suitable for advanced customization, custom authentication, and fine-grained API control. ```typescript import { ApiClient, AuthManager, getNetworkConfig, generatePoolSwapIntentMessage, type NetworkType, } from "@flashnet/sdk"; // Manual setup const network: NetworkType = "MAINNET"; const config = getNetworkConfig(network); const apiClient = new ApiClient(config); // Custom authentication const authManager = new AuthManager(apiClient, publicKey, customSigner); await authManager.authenticate(); // Direct API calls const pools = await apiClient.ammGet("/v1/pools"); ``` -------------------------------- ### Create Constant Product Pool Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Create a new constant product (x*y=k) liquidity pool. ```APIDOC ## Create Constant Product Pool ### Description Creates a new liquidity pool based on the constant product formula (x*y=k). ### Method `api.createConstantProductPool(params)` ### Parameters - **poolOwnerPublicKey** (string) - Required - The public key of the pool owner. - **assetAAddress** (string) - Required - The address of asset A. - **assetBAddress** (string) - Required - The address of asset B. - **lpFeeRateBps** (string) - Required - The liquidity provider fee rate in basis points. - **totalHostFeeRateBps** (string) - Required - The total host fee rate in basis points. - **nonce** (string) - Required - A unique nonce for the transaction. - **signature** (string) - Required - The signature generated for the intent message. ### Request Example ```typescript import { generateConstantProductPoolInitializationIntentMessage } from "@flashnet/sdk"; const nonce = crypto.randomUUID(); const intentBytes = generateConstantProductPoolInitializationIntentMessage({ poolOwnerPublicKey: "02abc...", assetAAddress: "020202020202020202020202020202020202020202020202020202020202020202", // BTC assetBAddress: "03def...", // custom token lpFeeRateBps: "30", // 0.30% totalHostFeeRateBps: "10", // 0.10% nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); const pool = await api.createConstantProductPool({ poolOwnerPublicKey: "02abc...", assetAAddress: "020202...", assetBAddress: "03def...", lpFeeRateBps: "30", totalHostFeeRateBps: "10", nonce, signature, }); // { poolId: "pool_abc123", lpWalletAddress: "spark1..." } ``` ``` -------------------------------- ### Manage Integrator Fees with SDK Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Fetch integrator fees and their withdrawal history, and initiate withdrawals. Requires integrator and LP identity public keys for withdrawal. ```typescript import { generateWithdrawIntegratorFeesIntentMessage } from "@flashnet/sdk"; const fees = await api.getIntegratorFees(); const history = await api.getIntegratorFeeWithdrawalHistory(); const nonce = crypto.randomUUID(); const wBytes = generateWithdrawIntegratorFeesIntentMessage({ integratorPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", nonce }); const sig = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(wBytes), true); await api.withdrawIntegratorFees({ integratorPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", nonce, signature: sig }); ``` -------------------------------- ### Manage V3 Position Ownership with SDK Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Use these functions to lock, list, and transfer V3 positions. Ensure you have the necessary wallet and API instances initialized. ```typescript import { generateLockPositionIntentMessage, generateTransferPositionIntentMessage, } from "@flashnet/sdk"; // Lock a V3 position until a future timestamp const lockUntil = String(Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 30); // 30 days const nonce = crypto.randomUUID(); const lockBytes = generateLockPositionIntentMessage({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", lockUntilTimestamp: lockUntil, tickLower: -60000, tickUpper: 60000, nonce }); const sig = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(lockBytes), true); await api.lockPosition({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", lockUntilTimestamp: lockUntil, tickLower: -60000, tickUpper: 60000, nonce, signature: sig }); // List locks const locks = await api.getPositionLocks("pool_abc123", "02abc..."); // Transfer V3 position ownership const tNonce = crypto.randomUUID(); const tBytes = generateTransferPositionIntentMessage({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", newOwnerPublicKey: "02new...", tickLower: -60000, tickUpper: 60000, nonce: tNonce }); const tSig = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(tBytes), true); await api.transferPosition({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", newOwnerPublicKey: "02new...", tickLower: -60000, tickUpper: 60000, nonce: tNonce, signature: tSig }); ``` -------------------------------- ### Simulate and Add Liquidity Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Simulates adding liquidity to a pool to determine optimal amounts and then executes the addition. Requires pool identity and amounts for both assets. ```APIDOC ## `api.simulateAddLiquidity` / `api.addLiquidity` — Add liquidity ### Description Simulates adding liquidity to a pool to determine optimal amounts and then executes the addition. Requires pool identity and amounts for both assets. ### Simulate Add Liquidity ```typescript const sim = await api.simulateAddLiquidity({ lpIdentityPublicKey: "03pool...", assetAAmount: "100000", assetBAmount: "200000", }); ``` ### Add Liquidity ```typescript const nonce = crypto.randomUUID(); const intentBytes = generateAddLiquidityIntentMessage({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", assetASparkTransferId: "transfer_a", assetBSparkTransferId: "transfer_b", assetAAmount: sim.assetAAmount, assetBAmount: sim.assetBAmount, assetAMinAmountIn: sim.assetAMinAmountIn, assetBMinAmountIn: sim.assetBMinAmountIn, nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); await api.addLiquidity({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", assetASparkTransferId: "transfer_a", assetBSparkTransferId: "transfer_b", assetAAmount: sim.assetAAmount, assetBAmount: sim.assetBAmount, assetAMinAmountIn: sim.assetAMinAmountIn, assetBMinAmountIn: sim.assetBMinAmountIn, nonce, signature }); ``` ``` -------------------------------- ### Simulate and Execute Single-Hop Token Swap Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Use `simulateSwap` to preview a swap and `executeSwap` to perform it. Ensure `minAmountOut` from simulation is used in execution to guarantee minimum received amount. ```typescript import { generatePoolSwapIntentMessage } from "@flashnet/sdk"; // Simulate first const simulation = await api.simulateSwap({ lpIdentityPublicKey: "03pool...", assetInAddress: "020202...", // BTC in assetOutAddress: "03token...", amountIn: "100000", // satoshis maxSlippageBps: "500", // 5% totalIntegratorFeeRateBps: "0", }); console.log("Expected out:", simulation.amountOut, "Min out:", simulation.minAmountOut); // Execute swap const nonce = crypto.randomUUID(); const intentBytes = generatePoolSwapIntentMessage({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", assetInSparkTransferId: "transfer_id_of_btc", assetInAddress: "020202...", assetOutAddress: "03token...", amountIn: "100000", maxSlippageBps: "500", minAmountOut: simulation.minAmountOut, totalIntegratorFeeRateBps: "0", nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); const swapResult = await api.executeSwap({ userPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", assetInSparkTransferId: "transfer_id_of_btc", assetInAddress: "020202...", assetOutAddress: "03token...", amountIn: "100000", maxSlippageBps: "500", minAmountOut: simulation.minAmountOut, totalIntegratorFeeRateBps: "0", nonce, signature, }); // { amountOut: "9875432", swapId: "swap_abc" } ``` -------------------------------- ### Simulate and Execute Multi-hop Route Swap Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Simulates and executes a token swap across multiple liquidity pools (multi-hop route). Requires defining the sequence of hops, input amount, and slippage tolerance. ```APIDOC ## `api.simulateRouteSwap` / `api.executeRouteSwap` — Multi-hop route swap ### Description Simulates and executes a token swap across multiple liquidity pools (multi-hop route). Requires defining the sequence of hops, input amount, and slippage tolerance. ### Simulate Route Swap ```typescript const sim = await api.simulateRouteSwap({ hops: [ { lpIdentityPublicKey: "03pool1...", assetInAddress: "020202...", assetOutAddress: "03mid...", integratorFeeRateBps: "0" }, { lpIdentityPublicKey: "03pool2...", assetInAddress: "03mid...", assetOutAddress: "03out...", integratorFeeRateBps: "0" }, ], inputAmount: "500000", maxRouteSlippageBps: "500", }); ``` ### Execute Route Swap ```typescript const nonce = crypto.randomUUID(); const intentBytes = generateRouteSwapIntentMessage({ userPublicKey: "02abc...", hops: sim.hops, initialSparkTransferId: "transfer_btc", inputAmount: "500000", maxRouteSlippageBps: "500", minAmountOut: sim.minFinalOutputAmount, nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); await api.executeRouteSwap({ ...sim, initialSparkTransferId: "transfer_btc", nonce, signature }); ``` ``` -------------------------------- ### Manage Host Fees with SDK Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Retrieve pool-specific or all host fees, and withdraw them. Requires host and LP identity public keys for withdrawal. ```typescript import { generateWithdrawHostFeesIntentMessage } from "@flashnet/sdk"; const poolFees = await api.getPoolHostFees({ lpIdentityPublicKey: "03pool..." }); const allFees = await api.getHostFees({ hostPublicKey: "02abc..." }); const history = await api.getHostFeeWithdrawalHistory({ limit: 10 }); const nonce = crypto.randomUUID(); const wBytes = generateWithdrawHostFeesIntentMessage({ hostPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", nonce }); const sig = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(wBytes), true); await api.withdrawHostFees({ hostPublicKey: "02abc...", lpIdentityPublicKey: "03pool...", nonce, signature: sig }); ``` -------------------------------- ### Simulate and Execute Multi-Hop Route Swap Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Use `simulateRouteSwap` for multi-hop swaps and `executeRouteSwap` to perform. The simulation provides optimal hops and minimum output amounts, which are then used in the intent message generation. ```typescript import { generateRouteSwapIntentMessage } from "@flashnet/sdk"; const sim = await api.simulateRouteSwap({ hops: [ { lpIdentityPublicKey: "03pool1...", assetInAddress: "020202...", assetOutAddress: "03mid...", integratorFeeRateBps: "0" }, { lpIdentityPublicKey: "03pool2...", assetInAddress: "03mid...", assetOutAddress: "03out...", integratorFeeRateBps: "0" }, ], inputAmount: "500000", maxRouteSlippageBps: "500", }); const nonce = crypto.randomUUID(); const intentBytes = generateRouteSwapIntentMessage({ userPublicKey: "02abc...", hops: sim.hops, initialSparkTransferId: "transfer_btc", inputAmount: "500000", maxRouteSlippageBps: "500", minAmountOut: sim.minFinalOutputAmount, nonce, }); const signature = await wallet.signMessageWithIdentityKey(new TextDecoder().decode(intentBytes), true); await api.executeRouteSwap({ ...sim, initialSparkTransferId: "transfer_btc", nonce, signature }); ``` -------------------------------- ### Create Constant Product Pool Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Create a new constant product Automated Market Maker (AMM) pool with optional initial liquidity. ```APIDOC ## Create Constant Product Pool ### Description Create a new constant product Automated Market Maker (AMM) pool with optional initial liquidity. ### Method `client.createConstantProductPool(params: { assetATokenPublicKey: string; assetBTokenPublicKey: string; lpFeeRateBps: number; totalHostFeeRateBps: number; initialLiquidity?: { assetAAmount: bigint; assetBAmount: bigint; }; })` ### Parameters - `assetATokenPublicKey` (string) - Public key of the first asset token. - `assetBTokenPublicKey` (string) - Public key of the second asset token. - `lpFeeRateBps` (number) - Liquidity provider fee rate in basis points (e.g., 30 for 0.3%). - `totalHostFeeRateBps` (number) - Total host fee rate in basis points (e.g., 10 for 0.1%). - `initialLiquidity` (object, optional) - Initial amounts of asset A and asset B to provide as liquidity. - `assetAAmount` (bigint) - Amount of asset A. - `assetBAmount` (bigint) - Amount of asset B. ### Request Example ```typescript await client.createConstantProductPool({ assetATokenPublicKey: "token-a", assetBTokenPublicKey: "token-b", lpFeeRateBps: 30, totalHostFeeRateBps: 10, initialLiquidity: { assetAAmount: 1000000n, assetBAmount: 5000n, }, }); ``` ``` -------------------------------- ### getClientNetworkConfig Source: https://context7.com/flashnetxyz/ts-sdk/llms.txt Resolves and returns the pre-built ClientNetworkConfig for a specified environment (mainnet, regtest, testnet, signet, local). It also includes a utility to validate custom network configurations. ```APIDOC ## getClientNetworkConfig — Resolve network configuration by environment Returns the pre-built `ClientNetworkConfig` (AMM Gateway URL, Mempool API URL, Explorer URL, SparkScan URL) for a named environment. ```typescript import { getClientNetworkConfig } from "@flashnet/sdk"; // Supported environments: "mainnet" | "regtest" | "testnet" | "signet" | "local" const config = getClientNetworkConfig("mainnet"); // { // ammGatewayUrl: "https://api.flashnet.xyz", // mempoolApiUrl: "https://mempool.space", // explorerUrl: "https://mempool.space", // sparkScanUrl: "https://api.sparkscan.io" // } // Custom config import { validateClientNetworkConfig } from "@flashnet/sdk"; const custom = { ammGatewayUrl: "https://my-node", mempoolApiUrl: "https://mempool.space", explorerUrl: "https://mempool.space" }; const { valid, errors } = validateClientNetworkConfig(custom); if (!valid) throw new Error(errors.join(", ")); ``` ``` -------------------------------- ### Modular Imports for Flashnet SDK Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Import only the necessary modules from the Flashnet SDK to optimize bundle size. Wallet dependencies are not required for most modular imports. ```typescript // Import only what you need - no wallet dependencies required import { AuthManager } from "@flashnet/sdk/auth"; import { ApiClient } from "@flashnet/sdk/api"; import { encodeSparkAddress } from "@flashnet/sdk/utils"; import type { Signer } from "@flashnet/sdk/types"; // Full SDK (requires wallet dependencies) import { FlashnetClient } from "@flashnet/sdk"; ``` -------------------------------- ### Simulate Swap Source: https://github.com/flashnetxyz/ts-sdk/blob/main/README.md Simulate a swap operation to estimate the output amount without executing the trade. ```APIDOC ## Simulate Swap ### Description Simulate a swap operation to estimate the output amount without executing the trade. ### Method `client.simulateSwap(params: { poolId: string; assetInTokenPublicKey: string; assetOutTokenPublicKey: string; amountIn: number | bigint; })` ### Parameters - `poolId` (string) - The ID of the pool to swap in. - `assetInTokenPublicKey` (string) - The public key of the asset being swapped in. - `assetOutTokenPublicKey` (string) - The public key of the asset being swapped out. - `amountIn` (number | bigint) - The amount of the input asset. ### Request Example ```typescript const simulation = await client.simulateSwap({ poolId: "pool-id", assetInTokenPublicKey: "token-in", assetOutTokenPublicKey: "token-out", amountIn: 1000000, }); ``` ```