# @bucket-protocol/sdk 中文文档

规范地址：https://npmcn.com/package/%40bucket-protocol/sdk/

版本：2\.3\.0
npm 元数据更新时间：2026-08-21T06:37:47.486Z
中文译文更新时间：2026-11-08T19:40:00.952Z
软件包许可：Apache-2\.0

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

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

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

- 包体积（解压后）：2.9 MB，901 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20
- 运行依赖：0 个
- peer 依赖：@mysten/bcs \>=2\.0\.0，@mysten/sui \>=2\.0\.0
- 首次发布：2025-09-18T04:41:41.551Z
- 最新版本发布：2026-08-21T06:37:47.107Z
- 近 30 天下载量：3226（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：43（近 12 个月 35 个）

## 中文简介

Bucket 协议类型SDK

## 安装

```sh
npm install @bucket-protocol/sdk
```

也可以使用：`pnpm add @bucket-protocol/sdk`、`yarn add @bucket-protocol/sdk`、`bun add @bucket-protocol/sdk`

## README

# Bucket 协议 SDK

Bucket Protocol TypeScript SDK是一个全面的开发工具包,用于与Bucket Protocol互动,支持CDP(担保债务位置)操作并使得开发者能够轻松地整合出借功能.

## 安装

```bash
npm install @mysten/sui  # >= 2.0.0
npm install @mysten/bcs  # >= 2.0.0
npm install @bucket-protocol/sdk
```

## 快速启动

### 初始化客户端

```typescript
import { BucketClient } from '@bucket-protocol/sdk';
import { SuiGrpcClient } from '@mysten/sui/grpc';

// Recommended: Create client with config fetched from chain (waits for config to be ready)
const client = await BucketClient.initialize({ network: 'mainnet' });

// Alternative: Sync constructor (config loads in background; config-dependent methods are async)
// const client = new BucketClient({ network: 'mainnet' });
// Then use await client.getConfig(), await client.getAllCollateralTypes(), etc.

// With custom SuiGrpcClient
const customSuiClient = new SuiGrpcClient({
  network: 'mainnet',
  baseUrl: 'https://your-custom-rpc-url',
});
const client = await BucketClient.initialize({
  suiClient: customSuiClient,
  network: 'mainnet',
});
```

### 基本查询

```typescript
// Get all supported collateral types (async when using sync constructor)
const collateralTypes = await client.getAllCollateralTypes();
console.log('Supported collaterals:', collateralTypes);
// Example: ['0x2::sui::SUI', '0x...::btc::BTC', ...]

// Get all vault information (CDP vaults)
const vaults = await client.getAllVaultObjects();
console.log('Vault info:', vaults);
// Returns: { [coinType]: VaultInfo, ... }

// Get user positions (collateral and debt)
const positions = await client.getUserPositions({
  address: '0x...user-address'
});
console.log('User positions:', positions);
// Returns: PositionInfo[]

// Get all PSM pools
const psmPools = await client.getAllPsmPoolObjects();
console.log('PSM Pools:', psmPools);
// Returns: { [coinType]: PsmPoolInfo, ... }

// Get all saving pools
const savingPools = await client.getAllSavingPoolObjects();
console.log('Saving Pools:', savingPools);
// Returns: { [lpType]: SavingPoolInfo, ... }

// Get user's savings
const userSavings = await client.getUserSavings({
  address: '0x...user-address'
});
console.log('User Savings:', userSavings);
// Returns: SavingInfo[]
```

## 核心特征

### 1\. 管理职位

**存款抵押和借款**

```typescript
import { SUI_TYPE_ARG } from '@mysten/sui/utils';
import { Transaction } from '@mysten/sui/transactions';
import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';

// Create transaction
const tx = new Transaction();

// Build transaction: deposit 1 SUI, borrow 1 USDB
await client.buildManagePositionTransaction(tx, {
  coinType: SUI_TYPE_ARG, // SUI as collateral
  depositCoinOrAmount: 1 * 10 ** 9, // 1 SUI (9 decimals)
  borrowAmount: 1 * 10 ** 6, // 1 USDB (6 decimals)
});

// Sign and execute transaction
const keypair = Ed25519Keypair.fromSecretKey('your-private-key');
tx.setSender(keypair.getPublicKey().toSuiAddress());
const result = await client.getSuiClient().signAndExecuteTransaction({
  signer: keypair,
  transaction: tx,
});
```

**偿还债务并收回抵押品:**

```typescript
const tx = new Transaction();
await client.buildManagePositionTransaction(tx, {
  coinType: SUI_TYPE_ARG,
  repayCoinOrAmount: 1 * 10 ** 6, // Repay 1 USDB
  withdrawAmount: 0.5 * 10 ** 9, // Withdraw 0.5 SUI
});
```

### 2\. 关闭位置

```typescript
// Close entire position (repay all debt, withdraw all collateral)
const tx = new Transaction();
const address = keypair.getPublicKey().toSuiAddress();
await client.buildClosePositionTransaction(tx, {
  coinType: SUI_TYPE_ARG,
  address,
});

tx.setSender(address);
const result = await client.getSuiClient().signAndExecuteTransaction({
  signer: keypair,
  transaction: tx,
});
```

### 3\. 贴出位置查询

```typescript
// Query all positions for specific collateral (paginated)
const positions = await client.getAllPositions({
  coinType: SUI_TYPE_ARG,
  pageSize: 50,
  cursor: null, // null for first query
});

console.log('Position list:', positions.positions);
console.log('Next cursor:', positions.nextCursor);

// Query next page
if (positions.nextCursor) {
  const nextPage = await client.getAllPositions({
    coinType: SUI_TYPE_ARG,
    pageSize: 50,
    cursor: positions.nextCursor,
  });
}
```

### 4\. PSM(Peg稳定模块)

PSM允许用户以低收费的公平价格互换到/从USDB.

**将稳定币换入USDB( 刷入) :**

```typescript
import { Transaction } from '@mysten/sui/transactions';

const tx = new Transaction();

// Example: Swap 10 USDC to USDB
const usdcAmount = 10 * 10 ** 6; // 10 USDC (6 decimals)
const USDC_TYPE = '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC';

const usdbCoin = await client.buildPSMSwapInTransaction(tx, {
  coinType: USDC_TYPE,
  inputCoinOrAmount: usdcAmount, // Can also pass a coin object
});

// Transfer or use the USDB coin
tx.transferObjects([usdbCoin], keypair.getPublicKey().toSuiAddress());

// Sign and execute
tx.setSender(keypair.getPublicKey().toSuiAddress());
const result = await client.getSuiClient().signAndExecuteTransaction({
  signer: keypair,
  transaction: tx,
});
```

**将 USDB 交换为 squipcoin (Swap Out):**

```typescript
const tx = new Transaction();

// Example: Swap 10 USDB to USDC
const usdbAmount = 10 * 10 ** 6; // 10 USDB (6 decimals)

const usdcCoin = await client.buildPSMSwapOutTransaction(tx, {
  coinType: USDC_TYPE,
  usdbCoinOrAmount: usdbAmount, // Can also pass a coin object
});

// Transfer USDC to user
tx.transferObjects([usdcCoin], keypair.getPublicKey().toSuiAddress());

tx.setSender(keypair.getPublicKey().toSuiAddress());
const result = await client.getSuiClient().signAndExecuteTransaction({
  signer: keypair,
  transaction: tx,
});
```

**查询 PSM 集合信息 :**

```typescript
// Get all PSM pools
const psmPools = await client.getAllPsmPoolObjects();
console.log('PSM Pools:', psmPools);

// Example output:
// {
//   'USDC': {
//     coinType: '0x...::usdc::USDC',
//     decimal: 6,
//     balance: 1000000n,
//     usdbSupply: 1000000n,
//     feeRate: { swapIn: 0.001, swapOut: 0.001 },
//     partnerFeeRate: {}
//   }
// }
```

### 5\. 储蓄池

将USDB存入储蓄池,以长期赚取利息和奖励.

**将USDB存入储蓄池 :**

```typescript
const tx = new Transaction();

const usdbAmount = 100 * 10 ** 6; // 100 USDB
const SUSDB_TYPE = '0x38f61c75fa8407140294c84167dd57684580b55c3066883b48dedc344b1cde1e::susdb::SUSDB';
const userAddress = keypair.getPublicKey().toSuiAddress();

await client.buildDepositToSavingPoolTransaction(tx, {
  lpType: SUSDB_TYPE,
  address: userAddress,
  depositCoinOrAmount: usdbAmount, // Can also pass a coin object
});

tx.setSender(userAddress);
const result = await client.getSuiClient().signAndExecuteTransaction({
  signer: keypair,
  transaction: tx,
});
```

**退出 USDB 保存池 :**

```typescript
const tx = new Transaction();

// Withdraw 50 LP tokens worth of USDB
const lpAmount = 50 * 10 ** 6; // 50 SUSDB (LP tokens)

const usdbCoin = await client.buildWithdrawFromSavingPoolTransaction(tx, {
  lpType: SUSDB_TYPE,
  amount: lpAmount,
});

// Transfer withdrawn USDB to user
tx.transferObjects([usdbCoin], userAddress);

tx.setSender(userAddress);
const result = await client.getSuiClient().signAndExecuteTransaction({
  signer: keypair,
  transaction: tx,
});
```

**储蓄池中的索赔奖励:**

```typescript
const tx = new Transaction();

// Claim all available rewards
const rewardsRecord = await client.buildClaimSavingRewardsTransaction(tx, {
  lpType: SUSDB_TYPE,
});

// Transfer all reward coins to user
tx.transferObjects(Object.values(rewardsRecord), userAddress);

tx.setSender(userAddress);
const result = await client.getSuiClient().signAndExecuteTransaction({
  signer: keypair,
  transaction: tx,
});
```

**查询保存池信息 :**

```typescript
// Get all saving pools
const savingPools = await client.getAllSavingPoolObjects();
console.log('Saving Pools:', savingPools);

// Get user's savings positions
const userSavings = await client.getUserSavings({ address: userAddress });
console.log('User Savings:', userSavings);

// Get user's rewards for specific pools
const rewards = await client.getAccountSavingPoolRewards({
  address: userAddress,
  lpTypes: [SUSDB_TYPE],
});
console.log('Claimable Rewards:', rewards);
```

**索赔应计利息(零存款/提取):**

```typescript
const tx = new Transaction();

// Deposit zero to distribute interest
const zeroUsdb = tx.splitCoins(tx.gas, [0]); // Zero coin
await client.buildDepositToSavingPoolTransaction(tx, {
  lpType: SUSDB_TYPE,
  address: userAddress,
  depositCoinOrAmount: zeroUsdb,
});

// Withdraw zero to claim accumulated interest
const accruedUsdb = await client.buildWithdrawFromSavingPoolTransaction(tx, {
  lpType: SUSDB_TYPE,
  amount: 0,
});

tx.transferObjects([accruedUsdb], userAddress);
```

### 6\. 闪光薄荷

闪薄荷允许在一次交易中无抵押品地借入USDB,可用于套利和清算.

**基本闪光薄荷 :**

```typescript
const tx = new Transaction();

// Flash mint 1000 USDB
const amount = 1000 * 10 ** 6; // 1000 USDB
const [usdbCoin, flashReceipt] = await client.flashMint(tx, { amount });

// Use USDB for operations...
// (e.g., arbitrage, liquidation, swaps)

// Repay with 0.05% fee
const feeAmount = Math.ceil(amount * 0.0005);
const totalRepayment = amount + feeAmount;

// Get USDB to repay (from operations or swap)
// ...

// Burn to repay flash loan
await client.flashBurn(tx, { usdbCoin, flashMintReceipt: flashReceipt });
```

### 7\. 一体化模式

**模式1:将稳定币和存款交换到储蓄池**

```typescript
const tx = new Transaction();

// Step 1: Swap USDC to USDB via PSM
const usdcAmount = 100 * 10 ** 6; // 100 USDC
const usdbCoin = await client.buildPSMSwapInTransaction(tx, {
  coinType: USDC_TYPE,
  inputCoinOrAmount: usdcAmount,
});

// Step 2: Deposit USDB to saving pool
await client.buildDepositToSavingPoolTransaction(tx, {
  lpType: SUSDB_TYPE,
  address: userAddress,
  depositCoinOrAmount: usdbCoin,
});

tx.setSender(userAddress);
const result = await client.getSuiClient().signAndExecuteTransaction({
  signer: keypair,
  transaction: tx,
});
```

**图案2:用 PSM 偿还的闪光薄荷**

```typescript
const tx = new Transaction();

// Step 1: Flash mint USDB
const amount = 1000 * 10 ** 6; // 1000 USDB
const [usdbCoin, flashReceipt] = await client.flashMint(tx, { amount });

// Step 2: Use USDB for operations...
// (e.g., arbitrage, liquidation, etc.)

// Step 3: Get fee in stablecoin (0.05% fee)
const feeAmount = Math.ceil(amount * 0.0005);
const feeUsdbCoin = await client.buildPSMSwapInTransaction(tx, {
  coinType: USDC_TYPE,
  inputCoinOrAmount: feeAmount,
});

// Step 4: Repay flash loan
tx.mergeCoins(usdbCoin, [feeUsdbCoin]);
await client.flashBurn(tx, { usdbCoin, flashMintReceipt: flashReceipt });

tx.setSender(userAddress);
const result = await client.getSuiClient().signAndExecuteTransaction({
  signer: keypair,
  transaction: tx,
});
```

**模式3:伙伴账户一体化**

```typescript
const tx = new Transaction();

// Use partner account for fee sharing
const partnerAccountId = '0x...partner-account-id';

// PSM swap with partner account
const usdbCoin = await client.buildPSMSwapInTransaction(tx, {
  accountObjectOrId: partnerAccountId,
  coinType: USDC_TYPE,
  inputCoinOrAmount: usdcAmount,
});

// Deposit to saving pool with partner account
await client.buildDepositToSavingPoolTransaction(tx, {
  accountObjectOrId: partnerAccountId,
  lpType: SUSDB_TYPE,
  address: userAddress,
  depositCoinOrAmount: usdbCoin,
});
```

## 支持的担保类型

目前,SDK支持以下担保品:

```typescript
// SUI
const SUI_TYPE = '0x2::sui::SUI';

// BTC
const BTC_TYPE = '0xaafb102dd0902f5055cadecd687fb5b71ca82ef0e0285d90afde828ec58ca96b::btc::BTC';

// BFBTC
const BFBTC_TYPE = '0x7438e8caf5c345fbd3772517380bf0ca432f53892dee65ee0dda3eb127993cd9::bfbtc::BFBTC';

// WAL
const WAL_TYPE = '0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL';

// LayerZero WBTC
const LZ_WBTC_TYPE = '0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN';
```

## 支持的 PSM 稳定币

```typescript
// USDC
const USDC_TYPE = '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC';

// USDT
const USDT_TYPE = '0x375f70cf2ae4c00bf37117d0c85a2c71545e6ee05c4a5c7d282cd66a4504b068::usdt::USDT';

// BUCK
const BUCK_TYPE = '0xce7ff77a83ea0cb6fd39bd8748e2ec89a3f41e8efdc3f4eb123e0ca37b184db2::buck::BUCK';
```

## 支持的保存池

```typescript
// SUSDB (Mainnet)
const SUSDB_TYPE = '0x38f61c75fa8407140294c84167dd57684580b55c3066883b48dedc344b1cde1e::susdb::SUSDB';
// Rewards: SUI
```

## 价格合计特征

SDK目前支持增强价格汇总能力:

### 批量价格汇总

```typescript
// Get oracle prices for multiple coin types
const coinTypes = [SUI_TYPE_ARG, BTC_TYPE, WAL_TYPE];
const prices = await client.getOraclePrices({ coinTypes });
console.log('Prices:', prices);

// Get all oracle prices
const allPrices = await client.getAllOraclePrices();
```

### 个人价格收集器创建

```typescript
// Create a price collector (within a transaction)
const tx = new Transaction();
const collector = await client.newPriceCollector(tx, { coinType: SUI_TYPE_ARG });
```

## 高级使用

### 自定义交易楼

```typescript
// Create a new transaction
const tx = new Transaction();

// Aggregate prices for multiple coin types
const coinTypes = [SUI_TYPE_ARG];
const [priceResult] = await client.aggregatePrices(tx, { coinTypes });

// Create debtor request
const debtorReq = await client.debtorRequest(tx, {
  coinType: SUI_TYPE_ARG,
  borrowAmount: 1 * 10 ** 6,
});

// Check update position request
const updateRequest = await client.checkUpdatePositionRequest(tx, {
  coinType: SUI_TYPE_ARG,
  request: debtorReq,
});

// Update position
const [collCoin, usdbCoin, response] = await client.updatePosition(tx, {
  coinType: SUI_TYPE_ARG,
  updateRequest,
  priceResult,
});

// Check response
await client.checkUpdatePositionResponse(tx, {
  coinType: SUI_TYPE_ARG,
  response,
});
```

### 干运行交易

```typescript
// Build transaction
const tx = new Transaction();
await client.buildManagePositionTransaction(tx, {
  coinType: SUI_TYPE_ARG,
  depositCoinOrAmount: 1 * 10 ** 9,
  borrowAmount: 1 * 10 ** 6,
});

// Simulate execution (won't actually execute on-chain)
tx.setSender('0x...your-address');
const simResult = await client.getSuiClient().simulateTransaction({
  transaction: tx,
});
console.log('Simulation result:', simResult.$kind === 'Transaction' ? 'success' : 'failed');
```

## 处理错误

```typescript
try {
  const tx = new Transaction();
  await client.buildManagePositionTransaction(tx, {
    coinType: SUI_TYPE_ARG,
    depositCoinOrAmount: 1 * 10 ** 9,
    borrowAmount: 1 * 10 ** 6,
  });

  const address = keypair.getPublicKey().toSuiAddress();
  tx.setSender(address);
  const result = await client.getSuiClient().signAndExecuteTransaction({
    signer: keypair,
    transaction: tx,
  });

  console.log('Transaction successful:', result.digest);
} catch (error) {
  if (error.message.includes('Not enough balance')) {
    console.error('Insufficient balance');
  } else if (error.message.includes('Invalid signer')) {
    console.error('Invalid signer');
  } else if (error.message.includes('Unsupported collateral type')) {
    console.error('Unsupported collateral type');
  } else if (error.message.includes('No price feed')) {
    console.error('No price feed available');
  } else {
    console.error('Unknown error:', error.message);
  }
}
```

## 数据类型

### 断层信息

```typescript
type VaultInfo = {
  collateralType: string; // Collateral type
  collateralDecimal: number; // Collateral decimals
  collateralBalance: bigint; // Total collateral amount
  minCollateralRatio: number; // Minimum collateralization ratio
  interestRate: number; // Interest rate
  usdbSupply: bigint; // Current USDB supply
  maxUsdbSupply: bigint; // Maximum supply
  positionTableSize: number; // Number of positions
  rewardRate: Record<string, number>; // Reward rates by reward type
};
```

### 位置信息

```typescript
type PositionInfo = {
  collateralType: string; // Collateral type
  collateralAmount: bigint; // Collateral amount
  debtAmount: bigint; // Debt amount
  debtor: string; // Debtor address
  accountId?: string; // Account object ID (if using Account)
  rewards: Record<string, bigint>; // Borrow rewards by reward type
};
```

### 悬浮药

```typescript
type PaginatedPositionsResult = {
  positions: {
    collateralType: string;
    collateralAmount: bigint;
    debtAmount: bigint;
    debtor: string;
  }[];
  nextCursor: string | null; // Pagination cursor
};
```

### PsmPoolInfo 图像

```typescript
type PsmPoolInfo = {
  coinType: string; // The stable coin type
  decimal: number; // Token decimals
  balance: bigint; // Pool balance amount
  usdbSupply: bigint; // USDB supply from this pool
  feeRate: {
    swapIn: number; // Fee rate for swapping in (e.g., 0.001 = 0.1%)
    swapOut: number; // Fee rate for swapping out
  };
  partnerFeeRate: Record<
    string,
    {
      swapIn: number;
      swapOut: number;
    }
  >; // Partner-specific fee rates
};
```

### 保存波尔信息

```typescript
type SavingPoolInfo = {
  lpType: string; // LP token type
  lpSupply: bigint; // Total LP supply
  usdbBalance: bigint; // USDB reserves in pool
  usdbDepositCap: bigint | null; // Optional deposit cap
  savingRate: number; // Annual saving rate (e.g., 0.05 = 5%)
  rewardRate: Record<string, number>; // APR by reward type
};
```

### 保存信息

```typescript
type SavingInfo = {
  lpType: string; // LP token type
  address: string; // User address
  accountId?: string; // Account object ID (optional)
  usdbBalance: bigint; // User's USDB value in pool
  lpBalance: bigint; // User's LP token balance
  rewards: Record<string, bigint>; // Claimable rewards by type
};
```

### 聚合对象信息

```typescript
type AggregatorObjectInfo = {
  coinType: string; // Coin type
  priceAggregator: SharedObjectRef; // Price aggregator object
  pythPriceId?: string; // Pyth price ID
};
```

### 默认对象信息

```typescript
type VaultObjectInfo = {
  collateralCoinType: string; // Collateral type
  vault: SharedObjectRef; // Vault object
  rewarders?: SharedObjectRef[]; // Rewarder objects (optional)
};
```

### PsmPool 对象信息

```typescript
type PsmPoolObjectInfo = {
  pool: SharedObjectRef; // Shared object reference to PSM pool
};
```

### 保存Pool对象信息

```typescript
type SavingPoolObjectInfo = {
  pool: SharedObjectRef; // Shared object reference
  reward?: {
    rewardManager: SharedObjectRef; // Reward manager object
    rewardTypes: string[]; // List of reward token types
  };
};
```

## 建筑改进

### 分离的聚合器配置

新版本将价格聚合器配置与金库配置区分开来,提供了更好的模块化:

```typescript
// Get aggregator information
const aggInfo = await client.getAggregatorObjectInfo({ coinType: SUI_TYPE_ARG });

// Get vault information
const vaultInfo = await client.getVaultObjectInfo({ coinType: SUI_TYPE_ARG });
```

### 增强价格合计

```typescript
// Get oracle prices (supports both basic and derivative prices)
const prices = await client.getOraclePrices({
  coinTypes: [SUI_TYPE_ARG, BTC_TYPE],
});

// Within a transaction, aggregate prices for use in PTBs
const tx = new Transaction();
const priceResults = await client.aggregatePrices(tx, {
  coinTypes: [SUI_TYPE_ARG, BTC_TYPE],
});
```

## 工具函数

### USDB 托肯类型

```typescript
// Get USDB token type
const usdbType = await client.getUsdbCoinType();
console.log('USDB Type:', usdbType);
```

### 账户管理

```typescript
const tx = new Transaction();

// Create account request for EOA (Externally Owned Account)
const accountRequest = await client.newAccountRequest(tx, {});

// Create account request with account object
const accountRequest = await client.newAccountRequest(tx, {
  accountObjectOrId: '0x...account-object-id',
});
```

## 与 Pyth 甲骨文合并

SDK与Pyth Network集成,用于价格饲料而无需Pyth SDK. 从 Hermes (公共 REST API) 获取价格更新数据 `SuiGrpcClient`在调用使用的方法时自动应用价格更新 `aggregatePrices()` (例如:. `getOraclePrices`, (中文(简体) ), `buildManagePositionTransaction` 与借款/提取, `buildPSMSwapInTransaction`, (中文(简体) ), `buildPSMSwapOutTransaction`) (中文(简体) ).

## 最佳做法

1.  **设置适当的剪贴板保护**:借贷业务可能受到价格波动的影响
2.  **显示器抵押比率**:确保比率高于最低要求以避免清算
3.  **处理错误**: 正确处理网络错误和交易失败
4.  **测试环境**:在投入生产前先测试测试网
5.  **天然气管理**: 考虑复杂交易的天然气成本
6.  **位置监测**: 定期检查健康状况和市场状况
7.  **批量操作**: 使用批量价格汇总特性提高效率
8.  **交易管理**: 总是创建新 `Transaction` 建筑物交易对象
9.  **PSM 用途**: 在互换前检查收费标准; 考虑使用PSM进行大型稳定币互换, 以尽量减少误差
10.  **保存池战略**: 定期使用零储量/抽取天然气效率索赔应计利息
11.  **补偿索赔**: 定期要求储蓄池的奖励,以最大限度地增加收益
12.  **账户对象**: 使用账户对象进行伙伴整合,以便能够分享费用

## 示例项目

关于完整的使用实例,请参考 [测试/e2e/](https://npmcn.com/package/%40bucket-protocol/sdk/test/e2e/) 目录( 例如 ). [cdp.test.ts (中文(简体) )](https://npmcn.com/package/%40bucket-protocol/sdk/test/e2e/cdp.test.ts), (中文(简体) ), [psm.test.ts (中文(简体) )](https://npmcn.com/package/%40bucket-protocol/sdk/test/e2e/psm.test.ts), (中文(简体) ), [保存. test.ts](https://npmcn.com/package/%40bucket-protocol/sdk/test/e2e/saving.test.ts), (中文(简体) ), [闪存. test.ts](https://npmcn.com/package/%40bucket-protocol/sdk/test/e2e/flash.test.ts)) (中文(简体) ).

## API 参考

### 客户端初始化

**建议: `BucketClient.initialize()` (同步工厂)**

创建客户端并等待配置准备好 。 未提供时从链中获取配置 :

```typescript
const client = await BucketClient.initialize({
  suiClient,       // Optional: custom SuiGrpcClient
  network,         // Optional: 'mainnet' | 'testnet' (default: 'mainnet')
  configObjectId,  // Optional: override entry config object ID
  config,          // Optional: pre-built config (skips chain fetch)
  configOverrides, // Optional: e.g. { PRICE_SERVICE_ENDPOINT: 'https://...' }
});
```

**替代品:同步构建器**

对于依赖性注射或者需要同步即时注射. 背景中的配置负载; 使用配置的方法( C)`getConfig`, (中文(简体) ), `getAllCollateralTypes`, (中文(简体) ), `buildClosePositionTransaction`等)为同位素:

```typescript
const client = new BucketClient({
  suiClient?: SuiGrpcClient;
  network?: Network;
  configObjectId?: string;
  config?: ConfigType;      // Optional: pre-built config
  configOverrides?: Partial<ConfigType>;
});
// Use await client.getConfig() before calling config-dependent methods
```

### 交易选项

**CDP(管理职位):**

```typescript
interface ManagePositionOptions {
  coinType: string; // Collateral token type
  depositCoinOrAmount?: number | TransactionArgument; // Amount or coin to deposit
  borrowAmount?: number | TransactionArgument; // Amount to borrow
  repayCoinOrAmount?: number | TransactionArgument; // Amount or coin to repay
  withdrawAmount?: number | TransactionArgument; // Amount to withdraw
  accountObjectOrId?: string | TransactionArgument; // Account object ID (optional)
}
```

**PSM(Peg稳定模块):**

```typescript
interface PSMSwapInOptions {
  coinType: string; // Stablecoin type (USDC, USDT, BUCK)
  inputCoinOrAmount: number | TransactionArgument; // Stablecoin amount or coin object
  accountObjectOrId?: string | TransactionArgument; // Account object ID (optional)
}

interface PSMSwapOutOptions {
  coinType: string; // Stablecoin type to receive
  usdbCoinOrAmount: number | TransactionArgument; // USDB amount or coin object
  accountObjectOrId?: string | TransactionArgument; // Account object ID (optional)
}
```

**保存池 :**

```typescript
interface DepositToSavingPoolOptions {
  lpType: string; // LP token type (e.g., SUSDB)
  address: string; // User address
  depositCoinOrAmount: number | TransactionArgument; // USDB amount or coin object
  accountObjectOrId?: string | TransactionArgument; // Account object ID (optional)
}

interface WithdrawFromSavingPoolOptions {
  lpType: string; // LP token type
  amount: number; // LP token amount to withdraw
  accountObjectOrId?: string | TransactionArgument; // Account object ID (optional)
}

interface ClaimSavingRewardsOptions {
  lpType: string; // LP token type
  accountObjectOrId?: string | TransactionArgument; // Account object ID (optional)
}
```

**闪光薄荷 :**

```typescript
interface FlashMintOptions {
  amount: number; // USDB amount to flash mint
}

interface FlashBurnOptions {
  usdbCoin: TransactionArgument; // USDB coin to burn (must include fee)
  flashMintReceipt: TransactionArgument; // Receipt from flashMint()
}
```

## 解决问题

### 共同问题

**"无效债务人地址"出错:**

```typescript
// Ensure address is provided when querying positions
const positions = await client.getUserPositions({ address: '0x...your-address' });
```

**"不够平衡"错误 :**

```typescript
// Check balance before attempting transactions
const address = '0x...your-address';
const { objects: coins } = await client.getSuiClient().listCoins({
  owner: address,
  coinType: SUI_TYPE_ARG,
});
console.log('Available balance:', coins);
```

**“ 不支持的附属类型” 错误 :**

```typescript
// Use supported collateral types
const supportedTypes = await client.getAllCollateralTypes();
console.log('Supported types:', supportedTypes);
```

**"无价饲料"出错:**

```typescript
// Ensure the coin type has a valid price feed
const aggInfo = await client.getAggregatorObjectInfo({ coinType: SUI_TYPE_ARG });
console.log('Pyth Price ID:', aggInfo.pythPriceId);
```

**"不支持的 PSM 硬币类型" 错误 :**

```typescript
// Use supported PSM stablecoins
const supportedPsmCoins = await client.getAllPsmPoolObjects();
console.log('Supported PSM coins:', Object.keys(supportedPsmCoins));
```

**"不足池余额"出错(PSM):**

```typescript
// Check PSM pool balance before swapping
const psmPools = await client.getAllPsmPoolObjects();
const poolInfo = psmPools[USDC_TYPE];
console.log('Available balance:', poolInfo.balance);
console.log('USDB supply:', poolInfo.usdbSupply);
```

**“ 已到达保存封顶” 出错( 保存池 ) :**

```typescript
// Check saving pool deposit cap
const savingPools = await client.getAllSavingPoolObjects();
const poolInfo = savingPools[SUSDB_TYPE];
if (poolInfo.usdbDepositCap) {
  const remaining = poolInfo.usdbDepositCap - poolInfo.usdbBalance;
  console.log('Remaining deposit capacity:', remaining);
}
```

**"LP平衡不足"出错(保存池):**

```typescript
// Check user's LP balance before withdrawing
const userSavings = await client.getUserSavings({ address: userAddress });
const saving = userSavings.find(s => s.lpType === SUSDB_TYPE);
if (saving) {
  console.log('Available LP balance:', saving.lpBalance);
  console.log('Equivalent USDB value:', saving.usdbBalance);
}
```

## 支持和贡献

-   **GitHub 图像**数字 : [桶- protocol- sdk (英语)](https://github.com/Bucket-Protocol/bucket-protocol-sdk)
-   **问题**: 请为错误报告或特性请求提交 GitHub 上的问题
-   **许可证**: Apache-2.0 数据
-   **维护者**梁静一 [仅此而已@ bucketprotocol.io](mailto:justa@bucketprotocol.io)

## 版本信息

**当前版本**页:1 **节点.js 要求**: **依赖关系**数字 :

-   @mysten/sui:>= 2.0.0
-   @mysten/bcs: >= 2. 0

## 常见问题

### @bucket-protocol/sdk 是什么？

Bucket 协议类型SDK

### 如何安装 @bucket-protocol/sdk？

在项目目录运行 npm install @bucket-protocol/sdk，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@mysten/bcs（\>=2\.0\.0）、@mysten/sui（\>=2\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @bucket-protocol/sdk 支持 TypeScript 吗？

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

### @bucket-protocol/sdk 支持 ESM 还是 CommonJS？

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

### @bucket-protocol/sdk 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=20。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @bucket-protocol/sdk 可以商用吗？

@bucket-protocol/sdk 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @bucket-protocol/sdk 的下载量有多少？

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

### @bucket-protocol/sdk 还在维护吗？

最新版本 2\.3\.0 发布于 2026/08/21（2 个月前）；至今共发布 43 个版本，其中过去 12 个月发布了 35 个；首次发布于 2025/09/18。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

