# @flashnet/sdk 中文文档

规范地址：https://npmcn.com/package/%40flashnet/sdk/

版本：0\.5\.10
npm 元数据更新时间：2026-06-11T15:28:20.298Z
中文译文更新时间：2026-11-14T21:41:30.696Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40flashnet/sdk
原文对照：https://npmcn.com/package/%40flashnet/sdk/?lang=original
项目主页：https://github.com/flashnetxyz/ts-sdk#readme
源码仓库：https://github.com/flashnetxyz/ts-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.4 MB，152 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- peer 依赖：typescript ^5，@buildonspark/spark-sdk latest，@buildonspark/issuer-sdk latest，react-native-get-random-values \>=1\.11\.0
- 首次发布：2025-07-04T00:30:48.684Z
- 最新版本发布：2026-06-09T00:22:32.138Z
- 近 30 天下载量：15524（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：65（近 12 个月 19 个）

## 中文简介

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

## 安装

```sh
npm install @flashnet/sdk
```

也可以使用：`pnpm add @flashnet/sdk`、`yarn add @flashnet/sdk`、`bun add @flashnet/sdk`

## README

# 闪光网 SDK

用于与Flashnet Spark AMM功能互动的综合SDK.

## 特征

-   **火花钱包集成** - 以 `@buildonspark/issuer-sdk` 或者说 `@buildonspark/spark-sdk`
-   **AMM 操作** - 创建池(单面和常数产品)、互换令牌、增加/移动流动资金
-   **多网络支持** - 横跨Mainnet和Regtest的工程
-   **基于意图的签名** - 通过意向签署交易
-   **自定义签名符** - 支持任意签名执行(硬件钱包、远程签名等)
-   **类型脚本第一** - 全面安全和情报支持

## 安装

```bash
bun add @flashnet/sdk
# or
npm install @flashnet/sdk
# or
yarn add @flashnet/sdk
```

### 可选的依赖关系

这个 `@buildonspark/spark-sdk` 财务报告和审定财务报表 `@buildonspark/issuer-sdk` 现在 **可选同伴依赖关系**你只需要安装它们 如果你正在使用全 `FlashnetClient` 钱包集成 :

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

## 模块导入

SDK现在支持模块化的进口,用于更好的打树和更小的捆绑尺寸:

```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";
```

可用出口 :

-   `@flashnet/sdk/auth` - 认证设施
-   `@flashnet/sdk/api` - API 客户端和输入端点
-   `@flashnet/sdk/utils` - 功能(地址、意图等)
-   `@flashnet/sdk/types` - 类型脚本
-   `@flashnet/sdk/config` - 网络配置
-   `@flashnet/sdk/client` - FlashnetClient(需要钱包)

详细的模块化使用实例见 [文档/模块使用.md](https://npmcn.com/package/%40flashnet/sdk/docs/modular-usage.md)。 。 。 .

## 用法选项

Flashnet SDK提供了两种适合不同需要的方法:

### 1\. 完全客户端(推荐给大多数用户)

使用 `FlashnetClient` 具有网络自动检测、认证和平衡检查的完整、即用解决方案.

```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,
});
```

### 2\. 模块组件(用于高级定制)

使用单个 SDK 组件构建自己的客户端,实现最大灵活性.

```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");
```

## 何时使用每种方法

### 当 :

-   你想快点开始
-   您正在使用标准 SparkWallet
-   您想要从钱包中自动检测网络
-   您想要内置平衡检查
-   您需要所有标准的 AMM 操作

### 当 :

-   您需要自定义认证逻辑
-   你和现有的基础设施融为一体
-   你想对API的电话进行精细控制
-   你正在打造一个专业的应用程序
-   您需要将AMM 操作与其他协议混合

## 快速启动示例

### 使用 Flashnet 客户端

```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
});
```

### 使用模块组件

```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(),
});
```

## 配置

SDK支持以下网络:

-   `MAINNET` - 生产网络
-   `REGTEST` - 回归测试网络

每个网络预设了以下终点:

-   AMM 网关
-   梅姆普尔 API
-   块浏览器
-   SparkScan( 可用时)

## FlashnetClient API 参考文献

这个 `FlashnetClient` 为AMM操作提供完整的接口:

### 初始化

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

### 集合操作

```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
});
```

### 交换操作

```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,
});
```

### 流动资金管理

```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",
});
```

### 主机业务

```typescript
// 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通信:

```typescript
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\. 认证和签名

支持多种签名方法 :

```typescript
// 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\. 有意生成

生成操作的意向信息 :

```typescript
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 地址合作 :

```typescript
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\. 审定公用事业

发送前验证请求 :

```typescript
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}`);
  }
}
```

## 处理错误

```typescript
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 输出所有必要的类型脚本 :

```typescript
import type {
  NetworkType,
  Pool,
  Token,
  SwapSimulationRequest,
  SwapSimulationResponse,
  ExecuteSwapRequest,
  AddLiquidityRequest,
  RemoveLiquidityRequest,
  LpPosition,
  Signer,
} from "@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 和提交记录判断。

