闪光网 SDK
用于与Flashnet Spark AMM功能互动的综合SDK.
特征
- 火花钱包集成 - 以
@buildonspark/issuer-sdk或者说@buildonspark/spark-sdk - AMM 操作 - 创建池(单面和常数产品)、互换令牌、增加/移动流动资金
- 多网络支持 - 横跨Mainnet和Regtest的工程
- 基于意图的签名 - 通过意向签署交易
- 自定义签名符 - 支持任意签名执行(硬件钱包、远程签名等)
- 类型脚本第一 - 全面安全和情报支持
安装
bun add @flashnet/sdk
# or
npm install @flashnet/sdk
# or
yarn add @flashnet/sdk
可选的依赖关系
这个 @buildonspark/spark-sdk 财务报告和审定财务报表 @buildonspark/issuer-sdk 现在 可选同伴依赖关系你只需要安装它们 如果你正在使用全 FlashnetClient 钱包集成 :
# 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
模块导入
SDK现在支持模块化的进口,用于更好的打树和更小的捆绑尺寸:
// 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";
可用出口 :
@flashnet/sdk/auth- 认证设施@flashnet/sdk/api- API 客户端和输入端点@flashnet/sdk/utils- 功能(地址、意图等)@flashnet/sdk/types- 类型脚本@flashnet/sdk/config- 网络配置@flashnet/sdk/client- FlashnetClient(需要钱包)
详细的模块化使用实例见 文档/模块使用.md。 。 。 .
用法选项
Flashnet SDK提供了两种适合不同需要的方法:
1. 完全客户端(推荐给大多数用户)
使用 FlashnetClient 具有网络自动检测、认证和平衡检查的完整、即用解决方案.
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,
});
2. 模块组件(用于高级定制)
使用单个 SDK 组件构建自己的客户端,实现最大灵活性.
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");
何时使用每种方法
当 :
- 你想快点开始
- 您正在使用标准 SparkWallet
- 您想要从钱包中自动检测网络
- 您想要内置平衡检查
- 您需要所有标准的 AMM 操作
当 :
- 您需要自定义认证逻辑
- 你和现有的基础设施融为一体
- 你想对API的电话进行精细控制
- 你正在打造一个专业的应用程序
- 您需要将AMM 操作与其他协议混合
快速启动示例
使用 Flashnet 客户端
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
});
使用模块组件
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(),
});
配置
SDK支持以下网络:
MAINNET- 生产网络REGTEST- 回归测试网络
每个网络预设了以下终点:
- AMM 网关
- 梅姆普尔 API
- 块浏览器
- SparkScan( 可用时)
FlashnetClient API 参考文献
这个 FlashnetClient 为AMM操作提供完整的接口:
初始化
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
集合操作
// 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
});
交换操作
// 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,
});
流动资金管理
// 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",
});
主机业务
// Register as host
await client.registerHost({
namespace: "my-exchange",
minFeeBps: 50,
feeRecipientPublicKey: "optional-different-pubkey",
});
await client.getHost("my-exchange");
await client.getPoolHostFees("my-exchange", "pool-id");
// Withdraw host fees
await client.withdrawHostFees({
lpIdentityPublicKey: "pool-id",
assetAAmount: "1000",
assetBAmount: "500",
});
模块组件参考
1. API 客户端
API客户端处理所有的HTTP通信:
import { ApiClient } from "@flashnet/sdk";
const client = new ApiClient(config);
// Direct endpoints
const pools = await client.ammGet("/v1/pools");
const swapResult = await client.ammPost("/v1/swap", swapData);
// Typed API wrapper
import { TypedAmmApi } from "@flashnet/sdk";
const api = new TypedAmmApi(client);
const pools = await api.listPools({ limit: 10 });
2. 认证和签名
支持多种签名方法 :
// Using Spark Wallet
const authManager = new AuthManager(apiClient, pubkey, wallet);
// Using Custom Signer
class MyCustomSigner implements Signer {
async signMessage(message: Uint8Array): Promise<Uint8Array> {
// Your signing logic
return signature;
}
}
const signer = new MyCustomSigner();
const authManager = new AuthManager(apiClient, pubkey, signer);
await authManager.authenticate();
3. 有意生成
生成操作的意向信息 :
import {
generatePoolSwapIntentMessage,
generateAddLiquidityIntentMessage,
generateConstantProductPoolInitializationIntentMessage,
generateNonce,
BTC_ASSET_PUBKEY,
} from "@flashnet/sdk";
// Swap intent
const swapIntent = generatePoolSwapIntentMessage({
userPublicKey: "userPubkey",
lpIdentityPublicKey: "poolPubkey",
assetASparkTransferId: "transferId",
// ... other parameters
nonce: generateNonce(),
});
4. 火花地址公用事业
与 Spark 地址合作 :
import {
encodeSparkAddress,
decodeSparkAddress,
isValidSparkAddress,
getNetworkFromAddress,
} from "@flashnet/sdk";
// Encode public key to address
const sparkAddress = encodeSparkAddress({
identityPublicKey: "02abc...",
network: "MAINNET",
});
// Detect network from address
const network = getNetworkFromAddress(sparkAddress);
5. 审定公用事业
发送前验证请求 :
import {
validateRequest,
commonValidationRules,
ValidationError,
} from "@flashnet/sdk";
try {
validateRequest(swapRequest, {
userPublicKey: commonValidationRules.publicKey,
amountIn: commonValidationRules.amount,
});
} catch (error) {
if (error instanceof ValidationError) {
console.error(`Invalid ${error.field}: ${error.reason}`);
}
}
处理错误
import { isFlashnetError } from "@flashnet/sdk";
try {
const result = await client.executeSwap(/* ... */);
} catch (error) {
if (isFlashnetError(error)) {
console.error(`API Error ${error.code}: ${error.msg}`);
}
// Handle other errors
}
类型
SDK 输出所有必要的类型脚本 :
import type {
NetworkType,
Pool,
Token,
SwapSimulationRequest,
SwapSimulationResponse,
ExecuteSwapRequest,
AddLiquidityRequest,
RemoveLiquidityRequest,
LpPosition,
Signer,
} from "@flashnet/sdk";
许可证
麻省理工学院