@bucket-protocol/sdk

中文文档
2.3.0发布于 2026/08/21Apache-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 3226

Bucket Protocol TypeScript SDK

原始使用文档
文档目录49 节
  1. Installation
  2. Quick Start
  3. Initialize Client
  4. Basic Queries
  5. Core Features
  6. 1. Manage Position
  7. 2. Close Position
  8. 3. Paginated Position Queries
  9. 4. PSM (Peg Stability Module)
  10. 5. Saving Pool
  11. 6. Flash Mint
  12. 7. Integration Patterns
  13. Supported Collateral Types
  14. Supported PSM Stablecoins
  15. Supported Saving Pools
  16. Price Aggregation Features
  17. Batch Price Aggregation
  18. Individual Price Collector Creation
  19. Advanced Usage
  20. Custom Transaction Building
  21. Dry Run Transaction
  22. Error Handling
  23. Data Types
  24. VaultInfo
  25. PositionInfo
  26. PaginatedPositionsResult
  27. PsmPoolInfo
  28. SavingPoolInfo
  29. SavingInfo
  30. AggregatorObjectInfo
  31. VaultObjectInfo
  32. PsmPoolObjectInfo
  33. SavingPoolObjectInfo
  34. Architecture Improvements
  35. Separated Aggregator Configuration
  36. Enhanced Price Aggregation
  37. Utility Functions
  38. USDB Token Type
  39. Account Management
  40. Integration with Pyth Oracle
  41. Best Practices
  42. Example Project
  43. API Reference
  44. Client Initialization
  45. Transaction Options
  46. Troubleshooting
  47. Common Issues
  48. Support & Contributing
  49. Version Information

Bucket Protocol SDK

The Bucket Protocol TypeScript SDK is a comprehensive development toolkit for interacting with the Bucket Protocol, supporting CDP (Collateralized Debt Position) operations and enabling developers to easily integrate lending functionality.

Installation

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

Quick Start

Initialize Client

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

Basic Queries

// 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[]

Core Features

1. Manage Position

Deposit collateral and borrow USDB:

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

Repay debt and withdraw collateral:

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. Close Position

// 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. Paginated Position Queries

// 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 Stability Module)

The PSM allows users to swap stablecoins to/from USDB at fair prices with low fees.

Swap stablecoin to USDB (Swap In):

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

Swap USDB to stablecoin (Swap Out):

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

Query PSM pool information:

// 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. Saving Pool

Deposit USDB into saving pools to earn interest and rewards over time.

Deposit USDB to saving pool:

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

Withdraw USDB from saving pool:

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

Claim rewards from saving pool:

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

Query saving pool information:

// 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);

Claim accrued interest (zero deposit/withdraw):

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. Flash Mint

Flash mint allows borrowing USDB within a single transaction without collateral, useful for arbitrage and liquidations.

Basic flash mint:

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. Integration Patterns

Pattern 1: Swap stablecoin and deposit to saving pool

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

Pattern 2: Flash mint with PSM repayment

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

Pattern 3: Partner account integration

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

Supported Collateral Types

Currently, the SDK supports the following collaterals:

// 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';

Supported PSM Stablecoins

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

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

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

Supported Saving Pools

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

Price Aggregation Features

The SDK now supports enhanced price aggregation capabilities:

Batch Price Aggregation

// 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();

Individual Price Collector Creation

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

Advanced Usage

Custom Transaction Building

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

Dry Run Transaction

// 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');

Error Handling

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

Data Types

VaultInfo

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

PositionInfo

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

PaginatedPositionsResult

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

PsmPoolInfo

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

SavingPoolInfo

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

SavingInfo

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

AggregatorObjectInfo

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

VaultObjectInfo

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

PsmPoolObjectInfo

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

SavingPoolObjectInfo

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

Architecture Improvements

Separated Aggregator Configuration

The new version separates price aggregator configuration from vault configuration, providing better modularity:

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

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

Enhanced Price Aggregation

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

Utility Functions

USDB Token Type

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

Account Management

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

Integration with Pyth Oracle

The SDK integrates with Pyth Network for price feeds without requiring the Pyth SDK. Price update data is fetched from Hermes (public REST API) and Move calls are built using SuiGrpcClient. Price updates are applied automatically when you call methods that use aggregatePrices() (e.g. getOraclePrices, buildManagePositionTransaction with borrow/withdraw, buildPSMSwapInTransaction, buildPSMSwapOutTransaction).

Best Practices

  1. Set Appropriate Slippage Protection: Lending operations may be affected by price volatility
  2. Monitor Collateralization Ratio: Ensure the ratio stays above minimum requirements to avoid liquidation
  3. Error Handling: Properly handle network errors and transaction failures
  4. Testing Environment: Test on testnet before deploying to production
  5. Gas Management: Consider gas costs for complex transactions
  6. Position Monitoring: Regularly check position health and market conditions
  7. Batch Operations: Use batch price aggregation features for efficiency
  8. Transaction Management: Always create a new Transaction object for building transactions
  9. PSM Usage: Check fee rates before swapping; consider using PSM for large stablecoin swaps to minimize slippage
  10. Saving Pool Strategy: Claim accrued interest periodically using zero deposit/withdraw for gas efficiency
  11. Reward Claiming: Regularly claim rewards from saving pools to maximize earnings
  12. Account Objects: Use account objects for partner integrations to enable fee sharing

Example Project

For complete usage examples, refer to the test/e2e/ directory (e.g. cdp.test.ts, psm.test.ts, saving.test.ts, flash.test.ts).

API Reference

Client Initialization

Recommended: BucketClient.initialize() (async factory)

Creates a client and waits for config to be ready. Config is fetched from chain when not provided:

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://...' }
});

Alternative: Sync constructor

For dependency injection or when you need sync instantiation. Config loads in background; methods that use config (getConfig, getAllCollateralTypes, buildClosePositionTransaction, etc.) are async:

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

Transaction Options

CDP (Manage Position):

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 Stability Module):

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

Saving Pool:

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

Flash Mint:

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()
}

Troubleshooting

Common Issues

"Invalid debtor address" Error:

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

"Not enough balance" Error:

// 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);

"Unsupported collateral type" Error:

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

"No price feed" Error:

// 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);

"Unsupported PSM coin type" Error:

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

"Insufficient pool balance" Error (PSM):

// 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);

"Deposit cap reached" Error (Saving Pool):

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

"Insufficient LP balance" Error (Saving Pool):

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

Support & Contributing

Version Information

Current Version: 2.0.1 Node.js Requirement: >= 20 Dependencies:

  • @mysten/sui: >= 2.0.0
  • @mysten/bcs: >= 2.0.0

版本与发布记录

@bucket-protocol/sdk 共发布 43 个版本,首次发布于 2025/09/18;过去 12 个月发布了 35 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.3.0latest2026/08/212 个月前
2.2.12026/08/182 个月前
2.2.02026/05/255 个月前
2.1.42026/03/207 个月前
2.1.32026/03/207 个月前
2.1.22026/03/207 个月前

其他发布通道:dev → 2.1.1-dev.0。

关于 @bucket-protocol/sdk 的常见问题

@bucket-protocol/sdk 是什么?

Bucket Protocol TypeScript 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 和提交记录判断。