@flashnet/sdk

中文文档
0.5.10发布于 2026/06/09MITTypeScriptESM + CJS构建来源已验证近 30 天下载 1.6万

Flashnet SDK 用于 Spark 钱包操作和 AMM 交互

中文使用文档
文档目录29 节
  1. 特征
  2. 安装
  3. 可选的依赖关系
  4. 模块导入
  5. 用法选项
  6. 1. 完全客户端(推荐给大多数用户)
  7. 2. 模块组件(用于高级定制)
  8. 何时使用每种方法
  9. 当 :
  10. 当 :
  11. 快速启动示例
  12. 使用 Flashnet 客户端
  13. 使用模块组件
  14. 配置
  15. FlashnetClient API 参考文献
  16. 初始化
  17. 集合操作
  18. 交换操作
  19. 流动资金管理
  20. 主机业务
  21. 模块组件参考
  22. 1. API 客户端
  23. 2. 认证和签名
  24. 3. 有意生成
  25. 4. 火花地址公用事业
  26. 5. 审定公用事业
  27. 处理错误
  28. 类型
  29. 许可证

闪光网 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提供了两种适合不同需要的方法:

使用 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";

许可证

麻省理工学院

版本与发布记录

@flashnet/sdk 共发布 65 个版本,首次发布于 2025/07/04;过去 12 个月发布了 19 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.5.10latest2026/06/095 个月前
0.5.92026/05/096 个月前
0.5.82026/04/246 个月前
0.5.72026/03/048 个月前
0.5.62026/02/188 个月前
0.5.52026/02/129 个月前

关于 @flashnet/sdk 的常见问题

@flashnet/sdk 是什么?

Flashnet SDK 用于 Spark 钱包操作和 AMM 交互

如何安装 @flashnet/sdk?

在项目目录运行 npm install @flashnet/sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:typescript(^5)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@flashnet/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@flashnet/sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@flashnet/sdk 可以商用吗?

@flashnet/sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@flashnet/sdk 的下载量有多少?

根据 npm 官方下载统计,@flashnet/sdk 在 2026/10/15 – 2026/11/13 这 30 天内被下载 15,524 次,日均约 517 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@flashnet/sdk 还在维护吗?

最新版本 0.5.10 发布于 2026/06/09(5 个月前);至今共发布 65 个版本,其中过去 12 个月发布了 19 个;首次发布于 2025/07/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。