@balmy/sdk

中文文档
0.9.0发布于 2025/05/20TypeScriptCommonJS近 30 天下载 1万

A comprehensive TypeScript SDK for interacting with the Balmy protocol and various blockchain networks.

原始使用文档
文档目录28 节
  1. 🧪 Installation
  2. Yarn
  3. NPM
  4. Quick Start
  5. 👷🏽‍♀️ Building the SDK
  6. ⚖️ Getting Balance for Multiple Tokens
  7. 💸 Getting Allowances
  8. 🔄 Getting Trade Quotes
  9. Overview
  10. Available Services
  11. Services
  12. Allowances Service
  13. Balances Service
  14. Quotes Service
  15. DCA Service
  16. Gas Service
  17. Prices Service
  18. Metadata Service
  19. Permit2 Service
  20. Earn Service
  21. Advanced Usage
  22. Error Handling
  23. Configuration
  24. Multi-chain Support
  25. 👨‍💻 Development
  26. Environment Setup
  27. Contributing
  28. Docs | X | Discord

Balmy SDK

A comprehensive TypeScript SDK for interacting with the Balmy protocol and various blockchain networks.

🧪 Installation

Yarn

yarn add @balmy/sdk

NPM

npm install @balmy/sdk

Quick Start

👷🏽‍♀️ Building the SDK

import { buildSDK } from "@balmy/sdk";

const sdk = buildSDK(config);

⚖️ Getting Balance for Multiple Tokens

const accountBalances = await sdk.balanceService.getBalancesForTokens({
  account: "0x000000000000000000000000000000000000dead",
  tokens: {
    [Chains.ETHEREUM.chainId]: [
      "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", // USDC
      "0x6b175474e89094c44da98b954eedeac495271d0f", // DAI
    ],
    [Chains.OPTIMISM.chainId]: [
      "0x7f5c764cbc14f9669b88837ca1490cca17c31607", // USDC
      "0xda10009cbd5d07dd0cecc66161fc93d7c9000da1", // DAI
    ],
  },
  config: {
    timeout: "30s",
  },
});

💸 Getting Allowances

const accountAllowances = await sdk.allowanceService.getAllowances({
  chainId: Chains.ETHEREUM.chainId,
  token: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", // USDC
  owner: "0x000000000000000000000000000000000000dead",
  spenders: ["0x6666666600000000000000000000000000009999"],
});

🔄 Getting Trade Quotes

const allQuotes = await sdk.quoteService.getAllQuotesWithTxs({
  request: {
    chainId: Chains.ETHEREUM.chainId,
    sellToken: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
    buyToken: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
    order: {
      type: "sell",
      sellAmount: utils.parseUnits("1000", 6), // 1000 USDC
    },
    slippagePercentage: 1,
    takerAddress: signer.address,
    gasSpeed: {
      speed: "instant",
    },
  },
  config: {
    sort: {
      by: "most-swapped-accounting-for-gas",
    },
  },
});

Overview

The Balmy SDK is a comprehensive TypeScript library that provides a unified interface for interacting with the Balmy protocol and various blockchain networks. The Balmy SDK allows you to interact with the Balmy protocol, providing efficient tools to manage token balances, retrieve trade quotes from DEX aggregators, and check token holdings across multiple chains. It's designed to be modular, with each functionality organized into specialized services that handle specific aspects of blockchain interaction.

Available Services

The SDK is divided into the following services:

Each service provides a focused set of functionality while maintaining a consistent interface and error handling approach. This modular design allows developers to use only the services they need while ensuring a cohesive experience across the entire SDK.

Services

Allowances Service

The Allowances Service provides functionality to check and manage token allowances across different chains.

Objective and Potential

  • Objective: Enable efficient management of token approvals across multiple chains and protocols
  • Potential Use Cases:
    • Batch checking multiple token approvals in a single call
    • Optimizing gas costs by checking approvals before transactions
    • Managing permissions for DeFi protocols and dApps
    • Cross-chain allowance monitoring and management

Methods

supportedChains()

Returns an array of chain IDs that are supported by the service.

const chains = sdk.allowanceService.supportedChains();
getAllowanceInChain(params)

Gets the allowance for a specific token and spender on a given chain.

const allowance = await sdk.allowanceService.getAllowanceInChain({
  chainId: Chains.ETHEREUM.chainId,
  token: "0x...", // Token address
  owner: "0x...", // Owner address
  spender: "0x...", // Spender address
  config: { timeout: TimeString },
});
getAllowancesInChain(params)

Gets multiple allowances in a single call for a specific chain.

const allowances = await sdk.allowanceService.getAllowancesInChain({
  chainId: Chains.ETHEREUM.chainId,
  allowances: [
    { token: "0x...", owner: "0x...", spender: "0x..." },
    { token: "0x...", owner: "0x...", spender: "0x..." },
  ],
  config: { timeout: TimeString },
});
getAllowances(params)

Gets allowances across multiple chains in a single call.

const allowances = await sdk.allowanceService.getAllowances({
  allowances: [
    {
      chainId: Chains.ETHEREUM.chainId,
      token: "0x...",
      owner: "0x...",
      spender: "0x...",
    },
    {
      chainId: Chains.OPTIMISM.chainId,
      token: "0x...",
      owner: "0x...",
      spender: "0x...",
    },
  ],
  config: { timeout: TimeString },
});

Balances Service

The Balances Service allows querying token balances across multiple chains and tokens.

Objective and Potential

  • Objective: Provide a unified interface for retrieving token balances across multiple chains
  • Potential Use Cases:
    • Portfolio tracking across multiple chains
    • Balance monitoring for DeFi positions
    • Multi-chain wallet integration
    • Automated balance checks for trading strategies

Methods

supportedChains()

Returns an array of chain IDs that are supported by the service.

const chains = sdk.balanceService.supportedChains();
getBalancesForAccountInChain(params)

Gets balances for a specific account in a single chain.

const balances = await sdk.balanceService.getBalancesForAccountInChain({
  chainId: Chains.ETHEREUM.chainId,
  account: "0x...",
  tokens: ["0x...", "0x..."],
  config: { timeout: "30s" },
});
getBalancesForAccount(params)

Gets balances for a specific account across multiple chains.

const balances = await sdk.balanceService.getBalancesForAccount({
  account: "0x...",
  tokens: [
    { chainId: Chains.ETHEREUM.chainId, token: "0x..." },
    { chainId: Chains.OPTIMISM.chainId, token: "0x..." },
  ],
  config: { timeout: "30s" },
});
getBalancesInChain(params)

Gets balances for multiple accounts in a single chain.

const balances = await sdk.balanceService.getBalancesInChain({
  chainId: Chains.ETHEREUM.chainId,
  tokens: [
    { account: "0x...", token: "0x..." },
    { account: "0x...", token: "0x..." },
  ],
  config: { timeout: "30s" },
});
getBalances(params)

Gets balances for multiple accounts across multiple chains.

const balances = await sdk.balanceService.getBalances({
  tokens: [
    { chainId: Chains.ETHEREUM.chainId, account: "0x...", token: "0x..." },
    { chainId: Chains.OPTIMISM.chainId, account: "0x...", token: "0x..." },
  ],
  config: { timeout: "30s" },
});

Quotes Service

The Quotes Service provides comprehensive functionality for getting trade quotes from various DEX aggregators.

Objective and Potential

  • Objective: Aggregate and optimize trade quotes from multiple DEX sources
  • Potential Use Cases:
    • Finding the best trade routes across multiple DEXs
    • Gas-optimized trading strategies
    • Cross-chain arbitrage opportunities
    • Automated trading systems
    • Price impact analysis

Methods

supportedSources()

Returns metadata about all supported quote sources.

const sources = sdk.quoteService.supportedSources();
supportedChains()

Returns an array of chain IDs that are supported by the service.

const chains = sdk.quoteService.supportedChains();
supportedSourcesInChain(params)

Returns metadata about quote sources supported in a specific chain.

const sources = sdk.quoteService.supportedSourcesInChain({
  chainId: Chains.ETHEREUM.chainId,
});
supportedGasSpeeds()

Returns supported gas speeds for each chain.

const gasSpeeds = sdk.quoteService.supportedGasSpeeds();
estimateQuotes(params)

Gets estimated quotes from all sources without transaction details.

const quotes = sdk.quoteService.estimateQuotes({
  request: {
    chainId: Chains.ETHEREUM.chainId,
    sellToken: "0x...",
    buyToken: "0x...",
    order: { type: "sell", sellAmount: BigInt("1000000") },
    slippagePercentage: 1,
  },
  config: { timeout: TimeString },
});
estimateAllQuotes(params)

Gets estimated quotes from all sources and returns them in a sorted array.

const quotes = await sdk.quoteService.estimateAllQuotes({
  request: {
    chainId: Chains.ETHEREUM.chainId,
    sellToken: "0x...",
    buyToken: "0x...",
    order: { type: "sell", sellAmount: BigInt("1000000") },
    slippagePercentage: 1,
  },
  config: {
    ignoredFailed: boolean,
    sort: { by: "most-swapped-accounting-for-gas", using: "gas-price" },
    timeout: TimeString,
  },
});
getQuotes(params)

Gets quotes from all sources with transaction details.

const quotes = sdk.quoteService.getQuotes({
  request: {
    chainId: Chains.ETHEREUM.chainId,
    sellToken: "0x...",
    buyToken: "0x...",
    order: { type: "sell", sellAmount: BigInt("1000000") },
    slippagePercentage: 1,
    takerAddress: "0x...",
  },
  config: { timeout: TimeString },
});
getAllQuotes(params)

Gets quotes from all sources and returns them in a sorted array.

const quotes = await sdk.quoteService.getAllQuotes({
  request: {
    chainId: Chains.ETHEREUM.chainId,
    sellToken: "0x...",
    buyToken: "0x...",
    order: { type: "sell", sellAmount: BigInt("1000000") },
    slippagePercentage: 1,
    takerAddress: "0x...",
  },
  config: {
    ignoredFailed: boolean,
    sort: { by: "most-swapped-accounting-for-gas", using: "gas-price" },
    timeout: TimeString,
  },
});
getBestQuote(params)

Gets the best quote according to specified criteria.

const bestQuote = await sdk.quoteService.getBestQuote({
  request: {
    chainId: Chains.ETHEREUM.chainId,
    sellToken: "0x...",
    buyToken: "0x...",
    order: { type: "sell", sellAmount: BigInt("1000000") },
    slippagePercentage: 1,
    takerAddress: "0x...",
  },
  config: {
    choose: { by: "most-swapped-accounting-for-gas", using: "gas-price" },
    timeout: TimeString,
  },
});
getAllQuotesWithTxs(params)

Gets quotes with built transactions from all sources.

const quotesWithTxs = await sdk.quoteService.getAllQuotesWithTxs({
  request: {
    chainId: Chains.ETHEREUM.chainId,
    sellToken: "0x...",
    buyToken: "0x...",
    order: { type: "sell", sellAmount: BigInt("1000000") },
    slippagePercentage: 1,
    takerAddress: "0x...",
  },
  config: {
    ignoredFailed: boolean,
    sort: { by: "most-swapped-accounting-for-gas", using: "gas-price" },
    timeout: TimeString,
  },
});
buildTxs(params)

Builds transactions for given quotes.

const txs = sdk.quoteService.buildTxs({
  quotes: quotes,
  sourceConfig: SourceConfig,
  config: { timeout: TimeString },
});
buildAllTxs(params)

Builds transactions for all quotes and returns them in a sorted array.

const allTxs = await sdk.quoteService.buildAllTxs({
  quotes: quotes,
  sourceConfig: SourceConfig,
  config: {
    timeout: TimeString,
    ignoredFailed: boolean,
  },
});

DCA Service

The DCA (Dollar Cost Averaging) Service provides functionality for setting up and managing DCA positions.

Objective and Potential

  • Objective: Enable automated dollar-cost averaging strategies for any token pair
  • Potential Use Cases:
    • Automated investment strategies
    • Risk management through periodic investments
    • Customizable DCA schedules
    • Multi-chain DCA positions
    • Permission management for shared positions

Methods

getAllowanceTarget(params)

Gets the allowance target address for a DCA position.

const target = sdk.dcaService.getAllowanceTarget({
  chainId: Chains.ETHEREUM.chainId,
  from: "0x...", // Token to sell
  depositWith: "0x...", // Token to deposit with
  usePermit2: boolean,
});
preparePermitData(params)

Prepares permit data for token approvals.

const permitData = await sdk.dcaService.preparePermitData({
  // Permit2 parameters
});
buildCreatePositionTx(params)

Builds a transaction to create a new DCA position.

const tx = await sdk.dcaService.buildCreatePositionTx({
  chainId: Chains.ETHEREUM.chainId,
  from: { address: "0x...", variantId: "..." },
  to: { address: "0x...", variantId: "..." },
  swapInterval: DCASwapInterval.ONE_DAY,
  amountOfSwaps: 30,
  owner: "0x...",
  permissions: [{ operator: "0x...", permissions: [DCAPermission.INCREASE] }],
  deposit: { token: "0x...", amount: BigInt("1000000") },
});
buildIncreasePositionTx(params)

Builds a transaction to increase an existing DCA position.

const tx = await sdk.dcaService.buildIncreasePositionTx({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "123",
  increase: { token: "0x...", amount: BigInt("1000000") },
  amountOfSwaps: 30,
});
buildReducePositionTx(params)

Builds a transaction to reduce an existing DCA position.

const tx = await sdk.dcaService.buildReducePositionTx({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "123",
  amountOfSwaps: 15,
  reduce: { amount: BigInt("500000") },
  recipient: "0x...",
});
buildReduceToBuyPositionTx(params)

Builds a transaction to reduce a position to buy a specific amount.

const tx = await sdk.dcaService.buildReduceToBuyPositionTx({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "123",
  amountOfSwaps: 15,
  reduce: { amountToBuy: BigInt("500000") },
  recipient: "0x...",
});
buildWithdrawPositionTx(params)

Builds a transaction to withdraw from a DCA position.

const tx = await sdk.dcaService.buildWithdrawPositionTx({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "123",
  withdraw: {},
  recipient: "0x...",
});
buildTerminatePositionTx(params)

Builds a transaction to terminate a DCA position.

const tx = await sdk.dcaService.buildTerminatePositionTx({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "123",
  withdraw: {},
  recipient: "0x...",
});
buildMigratePositionTx(params)

Builds a transaction to migrate a DCA position to a new hub.

const tx = await sdk.dcaService.buildMigratePositionTx({
  chainId: Chains.ETHEREUM.chainId,
  sourceHub: "0x...",
  targetHub: "0x...",
  positionId: "123",
  migration: { useFundsFrom: "swapped", sendUnusedFundsTo: "0x..." },
});
getSupportedPairs(params)

Gets supported token pairs for DCA positions.

const pairs = await sdk.dcaService.getSupportedPairs({
  chains: [Chains.ETHEREUM.chainId],
  config: { timeout: "30s" },
});
getPositionsByAccount(params)

Gets DCA positions for specific accounts.

const positions = await sdk.dcaService.getPositionsByAccount({
  accounts: ["0x..."],
  chains: [Chains.ETHEREUM.chainId],
  includeHistory: true,
  config: { timeout: "30s" },
});
getPositionsById(params)

Gets DCA positions by their IDs.

const positions = await sdk.dcaService.getPositionsById({
  ids: [{ chainId: Chains.ETHEREUM.chainId, hub: "0x...", positionId: 123 }],
  includeHistory: true,
  config: { timeout: "30s" },
});
getPairSwaps(params)

Gets swap history for a token pair.

const swaps = await sdk.dcaService.getPairSwaps({
  chainId: Chains.ETHEREUM.chainId,
  variantTokenA: "...",
  variantTokenB: "...",
  config: { timeout: "30s" },
});

Gas Service

The Gas Service provides gas price estimation and optimization across different chains.

Objective and Potential

  • Objective: Optimize transaction costs across different chains and networks
  • Potential Use Cases:
    • Gas price monitoring and optimization
    • Transaction cost estimation
    • Gas-aware trading strategies
    • Multi-chain gas price comparison
    • Automated gas price optimization

Methods

supportedChains()

Returns an array of chain IDs that are supported by the service.

const chains = sdk.gasService.supportedChains();
supportedSpeeds()

Returns supported gas speeds for each chain.

const speeds = sdk.gasService.supportedSpeeds();
estimateGas(params)

Estimates gas usage for a transaction.

const gasEstimation = await sdk.gasService.estimateGas({
  chainId: Chains.ETHEREUM.chainId,
  tx: {
    from: "0x...",
    to: "0x...",
    data: "0x...",
  },
  config: { timeout: TimeString },
});
getGasPrice(params)

Gets gas prices for different speeds on a chain.

const gasPrices = await sdk.gasService.getGasPrice({
  chainId: Chains.ETHEREUM.chainId,
  config: {
    timeout: TimeString,
    fields: {
      standard: "required" | "best effort" | "can ignore",
      fast: "required" | "best effort" | "can ignore",
      instant: "required" | "best effort" | "can ignore",
    },
  },
});
calculateGasCost(params)

Calculates gas cost for a transaction.

const gasCost = await sdk.gasService.calculateGasCost({
  chainId: Chains.ETHEREUM.chainId,
  gasEstimation: BigInt("21000"),
  tx: {
    from: "0x...",
    to: "0x...",
    data: "0x...",
  },
  config: {
    timeout: TimeString,
    fields: {
      standard: "required" | "best effort" | "can ignore",
      fast: "required" | "best effort" | "can ignore",
      instant: "required" | "best effort" | "can ignore",
    },
  },
});
getQuickGasCalculator(params)

Gets a quick gas calculator for a specific chain.

const calculator = await sdk.gasService.getQuickGasCalculator({
  chainId: Chains.ETHEREUM.chainId,
  config: {
    timeout: TimeString,
    fields: {
      standard: "required" | "best effort" | "can ignore",
      fast: "required" | "best effort" | "can ignore",
      instant: "required" | "best effort" | "can ignore",
    },
  },
});

// Use the calculator
const gasPrices = calculator.getGasPrice();
const gasCost = calculator.calculateGasCost({
  gasEstimation: BigInt("21000"),
  tx: {
    from: "0x...",
    to: "0x...",
    data: "0x...",
  },
});

Prices Service

The Prices Service provides token price information across multiple chains.

Objective and Potential

  • Objective: Provide a unified interface for retrieving token prices across multiple chains
  • Potential Use Cases:
    • Price feeds for DeFi applications
    • Token value calculations
    • Historical price analysis
    • Price chart generation
    • Multi-chain price aggregation

Methods

supportedChains()

Returns an array of chain IDs that are supported by the service.

const chains = sdk.pricesService.supportedChains();
supportedQueries()

Returns the supported price queries for each chain.

const queries = sdk.pricesService.supportedQueries();
getCurrentPricesInChain(params)

Gets current prices for tokens in a specific chain.

const prices = await sdk.pricesService.getCurrentPricesInChain({
  chainId: Chains.ETHEREUM.chainId,
  tokens: ["0x...", "0x..."],
  config: { timeout: "30s" },
});
getCurrentPrices(params)

Gets current prices for tokens across multiple chains.

const prices = await sdk.pricesService.getCurrentPrices({
  tokens: [
    { chainId: Chains.ETHEREUM.chainId, token: "0x..." },
    { chainId: Chains.OPTIMISM.chainId, token: "0x..." },
  ],
  config: { timeout: "30s" },
});
getHistoricalPricesInChain(params)

Gets historical prices for tokens in a specific chain at a given timestamp.

const prices = await sdk.pricesService.getHistoricalPricesInChain({
  chainId: Chains.ETHEREUM.chainId,
  tokens: ["0x...", "0x..."],
  timestamp: 1234567890,
  searchWidth: "1h",
  config: { timeout: "30s" },
});
getHistoricalPrices(params)

Gets historical prices for tokens across multiple chains at a given timestamp.

const prices = await sdk.pricesService.getHistoricalPrices({
  tokens: [
    { chainId: Chains.ETHEREUM.chainId, token: "0x..." },
    { chainId: Chains.OPTIMISM.chainId, token: "0x..." },
  ],
  timestamp: 1234567890,
  searchWidth: "1h",
  config: { timeout: "30s" },
});
getBulkHistoricalPrices(params)

Gets historical prices for multiple tokens at different timestamps.

const prices = await sdk.pricesService.getBulkHistoricalPrices({
  tokens: [
    { chainId: Chains.ETHEREUM.chainId, token: "0x...", timestamp: 1234567890 },
    { chainId: Chains.OPTIMISM.chainId, token: "0x...", timestamp: 1234567890 },
  ],
  searchWidth: "1h",
  config: { timeout: "30s" },
});
getChart(params)

Gets price chart data for tokens over a specified time period.

const chart = await sdk.pricesService.getChart({
  tokens: [
    { chainId: Chains.ETHEREUM.chainId, token: "0x..." },
    { chainId: Chains.OPTIMISM.chainId, token: "0x..." },
  ],
  span: 100,
  period: "1d",
  bound: { from: 1234567890 },
  searchWidth: "1h",
});

Metadata Service

The Metadata Service provides token metadata information across multiple chains.

Objective and Potential

  • Objective: Provide a unified interface for retrieving token metadata across multiple chains
  • Potential Use Cases:
    • Token information display in UIs
    • Token validation and verification
    • Multi-chain token management
    • Token data aggregation

Methods

supportedChains()

Returns an array of chain IDs that are supported by the service.

const chains = sdk.metadataService.supportedChains();
supportedProperties()

Returns the supported metadata properties for each chain.

const properties = sdk.metadataService.supportedProperties();
getMetadataInChain(params)

Gets metadata for tokens in a specific chain.

const metadata = await sdk.metadataService.getMetadataInChain({
  chainId: Chains.ETHEREUM.chainId,
  tokens: ["0x...", "0x..."],
  config: {
    fields: { symbol: "required", decimals: "required" },
    timeout: "30s",
  },
});
getMetadata(params)

Gets metadata for tokens across multiple chains.

const metadata = await sdk.metadataService.getMetadata({
  tokens: [
    { chainId: Chains.ETHEREUM.chainId, token: "0x..." },
    { chainId: Chains.OPTIMISM.chainId, token: "0x..." },
  ],
  config: {
    fields: { symbol: "required", decimals: "required" },
    timeout: "30s",
  },
});

Permit2 Service

The Permit2 Service provides functionality for managing token approvals using the Permit2 protocol.

Objective and Potential

  • Objective: Enable efficient and secure token approvals using the Permit2 standard
  • Potential Use Cases:
    • Gas-optimized token approvals
    • Batch approvals
    • Cross-protocol permission management
    • Automated approval systems
    • Security-focused approval workflows
// Get permit2 allowance
const allowance = await sdk.permit2Service.getAllowance({
  chainId: Chains.ETHEREUM.chainId,
  token: "0x...",
  owner: "0x...",
  spender: "0x...",
});

Earn Service

The Earn Service provides functionality for yield farming and staking operations.

Objective and Potential

  • Objective: Enable efficient yield farming and staking operations across multiple protocols
  • Potential Use Cases:
    • Yield farming strategy management
    • Automated position management
    • Cross-protocol yield optimization
    • Permission-based position sharing
    • Delayed withdrawal management
    • Strategy migration and optimization

Methods

getAllowanceTarget(params)

Gets the allowance target address for a strategy.

const target = await sdk.earnService.getAllowanceTarget({
  chainId: Chains.ETHEREUM.chainId,
  strategyId: "1-0x1234567890123456789012345678901234567890-42", // Format: chainId-registryAddress-strategyNumber
  depositWith: "0x...", // Token to deposit with
  usePermit2: boolean,
});
preparePermitData(params)

Prepares permit data for token approvals.

const permitData = await sdk.earnService.preparePermitData({
  chainId: Chains.ETHEREUM.chainId,
  token: "0x...",
  amount: "1000000",
  spender: "0x...",
});
preparePermissionData(params)

Prepares permission data for position management.

const permissionData = await sdk.earnService.preparePermissionData({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "1-0xabcdef1234567890123456789012345678901234-1337", // Format: chainId-vaultAddress-positionNumber
  permissions: [{ operator: "0x...", permissions: [EarnPermission.INCREASE] }],
  signerAddress: "0x...",
  signatureValidFor: "1w",
});
buildCreatePositionTx(params)

Builds a transaction to create a new earn position.

const tx = await sdk.earnService.buildCreatePositionTx({
  chainId: Chains.ETHEREUM.chainId,
  strategyId: "1-0x1234567890123456789012345678901234567890-42", // Format: chainId-registryAddress-strategyNumber
  owner: "0x...",
  permissions: [{ operator: "0x...", permissions: [EarnPermission.INCREASE] }],
  deposit: { token: "0x...", amount: "1000000" },
});
buildIncreasePositionTx(params)

Builds a transaction to increase an existing position.

const tx = await sdk.earnService.buildIncreasePositionTx({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "1-0xabcdef1234567890123456789012345678901234-1337", // Format: chainId-vaultAddress-positionNumber
  increase: { token: "0x...", amount: "1000000" },
});
buildWithdrawPositionTx(params)

Builds a transaction to withdraw from a position.

const tx = await sdk.earnService.buildWithdrawPositionTx({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "1-0xabcdef1234567890123456789012345678901234-1337", // Format: chainId-vaultAddress-positionNumber
  withdraw: { type: "market", token: "0x...", amount: "1000000" },
});
buildClaimDelayedWithdrawPositionTx(params)

Builds a transaction to claim a delayed withdrawal.

const tx = await sdk.earnService.buildClaimDelayedWithdrawPositionTx({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "1-0xabcdef1234567890123456789012345678901234-1337", // Format: chainId-vaultAddress-positionNumber
});
estimateMarketWithdraw(params)

Estimates the amount of tokens that would be received from a market withdrawal.

const estimation = await sdk.earnService.estimateMarketWithdraw({
  chainId: Chains.ETHEREUM.chainId,
  positionId: "1-0xabcdef1234567890123456789012345678901234-1337", // Format: chainId-vaultAddress-positionNumber
  token: "0x...",
  amount: "1000000",
  swapConfig: {
    slippagePercentage: 1,
    txValidFor: "1w",
  },
});
getSupportedStrategies(params)

Gets supported strategies for yield farming.

const strategies = await sdk.earnService.getSupportedStrategies({
  chains: [Chains.ETHEREUM.chainId],
  config: { timeout: "30s" },
});
getStrategy(params)

Gets detailed information about a specific strategy.

const strategy = await sdk.earnService.getStrategy({
  strategy: "1-0x1234567890123456789012345678901234567890-42", // Format: chainId-registryAddress-strategyNumber
  config: { timeout: "30s" },
});
getPositionsByAccount(params)

Gets earn positions for specific accounts.

const positions = await sdk.earnService.getPositionsByAccount({
  accounts: ["0x..."],
  chains: [Chains.ETHEREUM.chainId],
  includeHistory: true,
  includeHistoricalBalancesFrom: 1672531200,
  config: { timeout: "30s" },
});
getPositionsById(params)

Gets earn positions by their IDs.

const positions = await sdk.earnService.getPositionsById({
  ids: ["1-0xabcdef1234567890123456789012345678901234-1337"], // Format: chainId-vaultAddress-positionNumber
  includeHistory: true,
  includeHistoricalBalancesFrom: 1672531200,
  config: { timeout: "30s" },
});
getStrategyAsset(params)

Gets the asset token for a strategy or position.

const asset = await sdk.earnService.getStrategyAsset({
  chainId: Chains.ETHEREUM.chainId,
  strategyId: "1-0x1234567890123456789012345678901234567890-42", // Format: chainId-registryAddress-strategyNumber
  // or positionId: "1-0xabcdef1234567890123456789012345678901234-1337" // Format: chainId-vaultAddress-positionNumber
});

Advanced Usage

Error Handling

The SDK provides comprehensive error handling for all services:

try {
  const quotes = await sdk.quoteService.getAllQuotes({...});
} catch (error) {
  if (error instanceof FailedToGenerateAnyQuotesError) {
    // Handle quote generation failure
  }
}

Configuration

Each service can be configured with custom timeouts and other parameters:

const quotes = await sdk.quoteService.getAllQuotes({
  request: {...},
  config: {
    timeout: "30s",
    ignoredFailed: true,
    sort: {
      by: "most-swapped-accounting-for-gas",
      using: "gas-price"
    }
  }
});

Multi-chain Support

All services support operations across multiple chains:

const balances = await sdk.balanceService.getBalancesForTokens({
  account: "0x...",
  tokens: {
    [Chains.ETHEREUM.chainId]: ["0x..."],
    [Chains.OPTIMISM.chainId]: ["0x..."],
    [Chains.ARBITRUM.chainId]: ["0x..."],
  },
});

👨‍💻 Development

Environment Setup

yarn install

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Docs | X | Discord

版本与发布记录

@balmy/sdk 共发布 87 个版本,首次发布于 2024/04/27;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.9.0latest2025/05/201.5 年前
0.8.02025/05/091.5 年前
0.7.142025/05/031.5 年前
0.7.132025/04/251.5 年前
0.7.122025/04/241.5 年前
0.7.112025/04/121.6 年前

关于 @balmy/sdk 的常见问题

@balmy/sdk 是什么?

A comprehensive TypeScript SDK for interacting with the Balmy protocol and various blockchain networks.

如何安装 @balmy/sdk?

在项目目录运行 npm install @balmy/sdk,或使用 pnpm add / yarn add / bun add。

@balmy/sdk 支持 TypeScript 吗?

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

@balmy/sdk 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@balmy/sdk 可以商用吗?

@balmy/sdk 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

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

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

@balmy/sdk 还在维护吗?

最新版本 0.9.0 发布于 2025/05/20(1.5 年前);至今共发布 87 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/04/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。