# @balancer-labs/sdk 中文文档

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

版本：1\.1\.6
npm 元数据更新时间：2024-08-19T09:07:31.203Z
中文译文更新时间：2026-11-07T15:50:53.234Z
软件包许可：GPL-3\.0-only

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

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

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

- 包体积（解压后）：11.4 MB，11 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：16 个
- 首次发布：2021-11-30T10:44:53.637Z
- 最新版本发布：2024-08-19T09:07:30.974Z
- 近 30 天下载量：6316（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：337（近 12 个月 0 个）

## 中文简介

用于与平衡器协议 V2 交互的 JavaScript SDK

## 安装

```sh
npm install @balancer-labs/sdk
```

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

## README

# **折旧通知**

这个软件包/图书馆正在被贬值,以有利于我们的新版本和改进版本位于 [还原](https://github.com/balancer/b-sdk)编号 :[软件包](https://www.npmjs.com/package/@balancer/sdk)。 。 。 .

我们建议迁移到新的寄存器,以访问最新的功能(包括V3支持),错误修正和安全补丁. 关于这一变化的详情,请查看示例和文件页:

-   [文档 页 次](https://docs-v3.balancer.fi/developer-reference/sdk/)
-   [实例](https://github.com/balancer/b-sdk/tree/main/examples)

如果您有任何问题或需要协助迁移到新的寄存处,请通过Dev频道随时联系 [解析器](https://discord.balancer.fi/)。 。 。 .

谢谢你的理解,我们希望看到你 在我们的新仓库!

# 平衡器 Javascript SDK

一个JavaScript SDK,它提供了常用的与平衡器协议V2相互作用的用法.

## 如何运行实例( Javascript) ?

**为了运行所提供的实例,需要遵循以下步骤:**

1.  `git clone https://github.com/balancer-labs/balancer-sdk.git`
    
2.  `cd balancer-sdk`
    
3.  `cd balancer-js`
    
4.  在平衡器-js文件夹中创建 .env 文件
    
5.  在.env文件中,您需要定义并初始化以下变量
    
    我们既定义了Alchemy,又定义了Infura,因为一些例子使用Infura,另一些则使用Alchemy. 不过,你可以随意修改 并使用你最喜欢的. ALCHEMY URL= \[ALCHEMY HTPS ENDPOINT\] (英语)  
    INFURA=\[Infura API 关键  
    Turder KEY=\[Metmask Private 关键  
    一些例子还要求定义以下招标配置参数: TENDERLY ACESS KEY=\[TENDERLY APIS 关键 TENDERLY PROJECT= \[TENDERLY PROJECT NAME\] (法语) TENDERLY USER= \[TENDER USERME\] (法语)
    
6.  运行“ npm 运行节点 ” , 这将运行一个本地的 Hardhat 网络
    
7.  打开新终端
    
8.  cd为平衡器-js
    
9.  使用 ts- 节点安装 : `npm install ts-node`
    
10.  使用 : `npm install --save-dev tsconfig-paths`
     
11.  使用下列方式生成合同: `npm run typechain:generate`
     
12.  运行所提供实例之一( 如 npm 运行实例: 运行 -- -- 实例/ join. ts)
     

## 安装

## 开始

```js
import { BalancerSDK, BalancerSdkConfig, Network } from '@balancer-labs/sdk';

const config: BalancerSdkConfig = {
  network: Network.MAINNET,
  rpcUrl: `https://mainnet.infura.io/v3/${process.env.INFURA}`,
};
const balancer = new BalancerSDK(config);
```

在某些例子中,我们提出了结束针对主网国家的贸易的方法。 要运行它们,你需要设置一个本地主机测试节点, 使用工具如甘纳奇,硬帽子,阴道.

安装指令 :

-   [哈达特](https://hardhat.org/getting-started/#installation)
    
    要启动 MainNET 前置节点:
    
    -   设置 var : `ALCHEMY_URL=[ALCHEMY HTTPS ENDPOINT for MAINNET]`
    -   运行 : `npm run node`
    
    要开始一个GOERLI的节点:
    
    -   设置 var : `ALCHEMY_URL_GOERLI=[ALCHEMY HTTPS ENDPOINT for GOERLI]`
    -   运行 : `npm run node:goerli`
-   [安维尔](https://github.com/foundry-rs/foundry/tree/master/anvil#installation) - 谨慎使用,仍然实验.
    
    要启动一个要塞节点:
    
    ```
    anvil -f FORKABLE_RPC_URL (optional pinned block: --fork-block-number XXX)
    ```
    

## 交换模块

Exposes 完成值交换的功能. 用从子图获取的数据使用模块的例子 :

```js
// Uses SOR to find optimal route for a trading pair and amount
const route = balancer.swaps.findRouteGivenIn({
  tokenIn,
  tokenOut,
  amount,
  gasPrice,
  maxPools,
});

// Prepares transaction attributes based on the route
const transactionAttributes = balancer.swaps.buildSwap({
  userAddress,
  swapInfo: route,
  kind: 0, // 0 - givenIn, 1 - givenOut
  deadline,
  maxSlippage,
});

// Extract parameters required for sendTransaction
const { to, data, value } = transactionAttributes;

// Execution with ethers.js
const transactionResponse = await signer.sendTransaction({ to, data, value });
```

## 交换服务

SwapsService提供功能,使用"平衡V2"流动性查询并进行互换.

```js
const swaps = new swapService({
  network: Network;
  rpcUrl: string;
});
```

## 实例

您可以使用 `npm run examples:run -- examples/exampleName.ts`

### {\\fn方正黑体简体\\fs18\\b1\\bord1\\shad1\\3cH2F2F2F}"凯里·巴奇"

平衡阀提供 [模拟调用批量Swap的方法](https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/vault/contracts/interfaces/IVault.sol#L644)。 。 。 . 此功能不检查发件人或收款人或象征性余额或批准。 注意此函数不是"视图"(因为执行细节):客户端代码必须明确执行eth call而不是eth sendTransaction.

@param 批次Swap - 用于查询的批次Swap信息 . @param protectSwap.kind - 无论是准确的In还是准确的Out. @param 批次Swap. swaps - 相接顺序. @param protectSwap.assets - 阵列包含交换中涉及的所有资产的地址. @ returns 返回一个带有净地壳资产余额的阵列 。 正数代表送去地堡的地标(或ETH),负数代表地堡所发地标(或ETH). 每一三角洲对应于2005年12月31日同一指数的资产 `assets` 阵列.

```js
swaps.queryBatchSwap(batchSwap: {
    kind: SwapType,
    swaps: BatchSwapStep[],
    assets: string[]
}): Promise<BigNumberish[]>
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/queryBatchSwap.ts)

### 编码批次分页

编码 a 的静态方法 [批量互换](https://dev.balancer.fi/references/contracts/apis/the-vault#batch-swaps)。 。 。 .

_NB: 此方法不执行批次Swap - 它返回一个 [ABI 字节字符串](https://docs.soliditylang.org/en/latest/abi-spec.html) 包含函数的数据调用合同,然后可以发送到网络(ex. [发送交易](https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#sendtransaction)待执行。 更多信息请参见示例._

```js
/**
 * @param {BatchSwap}           batchSwap - BatchSwap information used for query.
 * @param {SwapType}            batchSwap.kind - either exactIn or exactOut
 * @param {BatchSwapSteps[]}    batchSwap.swaps - sequence of swaps
 * @param {string[]}            batchSwap.assets - array contains the addresses of all assets involved in the swaps
 * @param {FundManagement}      batchSwap.funds - object containing information about where funds should be taken/sent
 * @param {number[]}            batchSwap.limits - limits for each token involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the minimum amount of tokens to receive (by passing a negative value) is specified
 * @param {string}              batchSwap.deadline -  time (in Unix timestamp) after which it will no longer attempt to make a trade
 * @returns {string}            encodedBatchSwapData - Returns an ABI byte string containing the data of the function call on a contract
*/
Swaps.encodeBatchSwap(batchSwap: {
    kind: SwapType,
    swaps: BatchSwapStep[],
    assets: string[],
    funds: FundManagement,
    limits: number[],
    deadline: string
}): string
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/batchSwap.ts)

### 交换服务: 闪光交换

A 类 [闪光交换](https://dev.balancer.fi/resources/swaps/flash-swaps) 是一种特殊的类型 [批量互换](https://dev.balancer.fi/resources/swaps/batch-swaps) 在呼叫者不需要拥有或提供任何输入令牌的情况下——呼叫者实质上是在从"平衡阀"取出"快活出借"(一种无抵押贷款). 输入令牌的全额必须在批次结束前还给Vault(加上任何互换费),但任何输出令牌的超出部分都可以发送到任何地址.

ImportANT:"简单"的闪存互换是一种套利,只执行两个符和两个池, 换入一池再回二池取利. 为了更多 复杂的闪存互换, 您需要直接使用批量互换 .

发现:

-   两个池都必须有两种资产(托盘)进行交换才能工作
-   没有池名符号余额为零
-   如果闪存互换不盈利,内部闪存出借将失败.

### {\\fn方正黑体简体\\fs18\\b1\\bord1\\shad1\\3cH2F2F2F}"小花花"

编码简单闪存交换的静态方法 [批量扫描方法](https://dev.balancer.fi/resources/swaps/flash-swaps)。 。 。 .

_NB: 此方法不会执行任何互换 - 它返回一个 [ABI 字节字符串](https://docs.soliditylang.org/en/latest/abi-spec.html) 包含函数的数据调用合同,然后可以发送到网络(ex. [发送交易](https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#sendtransaction)待执行。 更多信息请参见示例._

```js
/**
 * @param {SimpleFlashSwapParameters}   params - BatchSwap information used for query.
 * @param {string}                      params.flashLoanAmount - initial input amount for the flash loan (first asset)
 * @param {string[]}                    params.poolIds - array of Balancer pool ids
 * @param {string[]}                    params.assets - array of token addresses
 * @param {string}                      params.walletAddress - array of token addresses
 * @returns {string}            encodedBatchSwapData - Returns an ABI byte string containing the data of the function call on a contract
*/
Swaps.encodeSimpleFlashSwap(simpleFlashSwap: {
    flashLoanAmount: string,
    poolIds: string[],
    assets: string[]
    walletAddress: string[]
}): string
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/flashSwap.ts)

### {\\fn黑体\\fs22\\bord1\\shad0\\3aHBE\\4aH00\\fscx67\\fscy66\\2cHFFFFFF\\3cH808080}快闪 {\\fn黑体\\fs22\\bord1\\shad0\\3aHBE\\4aH00\\fscx67\\fscy66\\2cHFFFFFF\\3cH808080}快闪

测试简单闪存互换是否有效的方法并查看潜在利润.

```js
/**
 * @param {SimpleFlashSwapParameters}   params - BatchSwap information used for query.
 * @param {string}                      params.flashLoanAmount - initial input amount for the flash loan (first asset)
 * @param {string[]}                    params.poolIds - array of Balancer pool ids
 * @param {string[]}                    params.assets - array of token addresses
 * @returns {Promise<{profits: Record<string, string>, isProfitable: boolean}>}       Returns an ethersjs transaction response
*/
swaps.querySimpleFlashSwap(batchSwap: {
    kind: SwapType,
    swaps: BatchSwapStep[],
    assets: string[]
}): string
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/querySimpleFlashSwap.ts)

## 定价

Spot Price功能,允许用户查询Spot price对的spoint价格.

### 微分价格

在特定池中找到对的点价 .

```js
const balancer = new BalancerSDK(sdkConfig);
const pool = await balancer.pools.find(poolId);
const spotPrice = await pool.calcSpotPrice(
  ADDRESSES[network].DAI.address,
  ADDRESSES[network].BAL.address
);
```

### 得到的斯波特普莱斯

查找 Spot Price 的对符 - 找到大多数液体路径, 并将其作为参考 SP .

```js
const pricing = new Pricing(sdkConfig);
```

@ param { string } 在地址的 Token 中表示符号 . @ param { string } 符号退出地址 . @param {子图宝Base \[\]} 集合可选 - 集合数据 。 如果不提供数据,将通过数据获取. @ returns { string } 点价 .

```js
async getSpotPrice(
    tokenIn: string,
    tokenOut: string,
    pools: SubgraphPoolBase[] = []
): Promise<string>
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/spotPrice.ts)

## 模拟池加入并存在

平衡阀提供 [模拟连接或退出呼叫池的方法](https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/standalone-utils/contracts/BalancerQueries.sol#L91)。 。 。 . 这些函数允许您在发送实际交易前进行干运行,而不检查发件人/收件人或令牌余额/批准. 注意此功能不是“ 视图 ” (因为执行细节): 客户端代码必须明确执行 `eth_call` 改为 `eth_sendTransaction`。 。 。 .

### 模拟加入

加入游泳池有两种方式:

1.  `joinExactIn`:用已知的代币金额加入游泳池. 这是最常用的方法.
2.  `joinExactOut`:当我们知道我们想要回多少BPT时,问池里有预期的流动性.

在本文件中,我们将侧重于第一种方法(例如:`joinExactIn`用于加入一个有已知代号金额的游泳池.

```js
const pool = await sdk.pools.find(poolId);
const maxAmountsIn = pool.tokenList.map(
  (t) => forEachTokenSpecifyAmountYouWantToJoinWith
);
const queryParams = pool.buildQueryJoinExactIn({ maxAmountsIn });
const response = await balancerContracts.balancerHelpers.queryJoin(
  ...queryParams
);
const { bptOut, amountsIn } = response;
```

`response` 将返回 :

-   `bptOut`: 游泳池返回的预期游泳池值.
-   `amountsIn`: 与最大峰值相同 单位

### 模拟出入口

离池有三种出道方法:

1.  `exitToSingleToken`: 将流动性退出到一个单一的基础符号上是最简单的方法. 但是,如果流动资金的退出数额是集合流动资金总额的一大部分,则可能导致价格下滑.
2.  `exitProportionally`: 将流动资金按比例退出所有公用集合代币. 这是最常用的方法. 不过 `ComposableStable` 池类型不支持它.
3.  `exitExactOut`:当我们知道我们想要回多少钱时,问池里有预期的池值.

在这个例子中,我们将侧重于第一种方法(例如:`exitProportionally`) (中文(简体) ).

```js
const pool = await sdk.pools.find(poolId);
const queryParams = pool.buildQueryJoinExactIn({ bptIn });
const response = await balancerContracts.balancerHelpers.queryJoin(
  ...queryParams
);
const { bptIn, amountsOut } = response;
```

`response` 将返回 :

-   `amountsOut`:托肯金额从游泳池取回.
-   `bptIn`: 与输入 bptIn 相同

更多实例: [https://github.com/labs/laber-sdk/blob/master/laber-js/examples/pools/queries.ts](https://github.com/balancer-labs/balancer-sdk/blob/master/balancer-js/examples/pools/queries.ts)

## 加入池内

### 加入池名符号

Exposes 加入功能,允许用户与其池符加入池.

```js
const balancer = new BalancerSDK(sdkConfig);
const pool = await balancer.pools.find(poolId);
const { to, functionName, attributes, data } = pool.buildJoin(params);
```

#### {\\fn方正粗倩简体\\fs12\\an8\\1cHFFFF00\\b0}建造琼

构建包含精确符号的集合交易参数,并根据滑行可容忍度将最小BPT输出

```js
/**
 * @param joiner Account address joining pool
 * @param tokensIn Token addresses provided for joining pool (same length and order as amountsIn)
 * @param amountsIn Token amounts provided for joining pool in EVM scale
 * @param slippage Maximum slippage tolerance in bps i.e. 50 = 0.5%
 * @returns transaction request ready to send with signer.sendTransaction
 */
buildJoin: (
  joiner: string,
  tokensIn: string[],
  amountsIn: string[],
  slippage: string
) => JoinPoolAttributes;
```

地点 `JoinPoolAttributes` 为:

```js
/**
 * Join with exact tokens in transaction parameters
 * @param to Address that will execute the transaction (vault address)
 * @param functionName Function name to be called (joinPool)
 * @param attributes Transaction attributes ready to be encoded
 * @param data Encoded transaction data
 * @param value (Optional) ETH amount that must be informed when joining with ETH
 * @param minBptOut Minimum BPT amoutn out of join transaction considering slippage tolerance
 * @param expectedBptOut Expected BPT amount out of join transaction
 * @param priceImpact Price impact of join transaction
 */
export interface JoinPoolAttributes {
  to: string;
  functionName: string;
  attributes: JoinPool;
  data: string;
  value?: BigNumber;
  minBPTOut: string;
  expectedBPTOut: string;
  priceImpact: string;
}
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/join.ts)

### {\\fn方正粗倩简体\\fs12\\an8\\1cHFFFF00\\b0}建造重泳

为加权池构建关联交易.

```js
/**
 * @param joiner - The address of the joiner of the pool
 * @param poolId - The id of the pool
 * @param tokensIn - array with the address of the tokens
 * @param amountsIn - array with the amount of each token
 * @returns a InitJoinPoolAttributes object, which can be directly inserted in the transaction to init join a weighted pool
 */
buildInitJoin({
  joiner,
  poolId,
  tokensIn,
  amountsIn,
}) => InitJoinPoolAttributes
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/pools/weighted/init-join.ts) 可用的池类型 :

-   加权
-   可构成稳定[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/pools/composable-stable/init-join.ts)(中文(简体) )

### 加入筑巢池

Exposes 加入功能,允许用户加入一个具有池名符号的池名,即其他池名的BPT,例如:

```
                  CS0
              /        \
            CS1        CS2
          /    \      /   \
         DAI   USDC  USDT  FRAX

Can join with tokens: DAI, USDC, USDT, FRAX, CS1_BPT, CS2_BPT
```

```js
/**
 * Builds generalised join transaction
 *
 * @param poolId          Pool id
 * @param tokens          Token addresses
 * @param amounts         Token amounts in EVM scale
 * @param userAddress     User address
 * @param slippage        Maximum slippage tolerance in bps i.e. 50 = 0.5%.
 * @param signer          JsonRpcSigner that will sign the staticCall transaction if Static simulation chosen
 * @param simulationType  Simulation type (VaultModel, Tenderly or Static)
 * @param authorisation   Optional auhtorisation call to be added to the chained transaction
 * @returns transaction data ready to be sent to the network along with min and expected BPT amounts out.
 */
async generalisedJoin(
  poolId: string,
  tokens: string[],
  amounts: string[],
  userAddress: string,
  slippage: string,
  signer: JsonRpcSigner,
  simulationType: SimulationType,
  authorisation?: string
): Promise<{
  to: string;
  encodedCall: string;
  minOut: string;
  expectedOut: string;
  priceImpact: string;
}>
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/joinGeneralised.ts)

## 退出池

Exposes 退出功能允许用户退出池.

```js
const balancer = new BalancerSDK(sdkConfig);
const pool = await balancer.pools.find(poolId);
const { to, functionName, attributes, data } = pool.buildExitExactBPTIn(params);
```

### \# 建设ExitExactBPTIn

构建一个退出交易,其中包含精确的 BPT , 并基于滑行可容忍性将最小的象征性金额输出出 .

```js
/**
 * Build exit pool transaction parameters with exact BPT in and minimum token amounts out based on slippage tolerance
 * @param exiter Account address exiting pool
 * @param bptIn BPT provided for exiting pool in EVM scale
 * @param slippage Maximum slippage tolerance in bps. i.e. 50 = 5%
 * @param shouldUnwrapNativeAsset Indicates whether wrapped native asset should be unwrapped after exit. Defaults to false.
 * @param singleTokenOut Optional: token address that if provided will exit to given token
 * @returns transaction request ready to send with signer.sendTransaction
 */
buildExitExactBPTIn: (
  exiter: string,
  bptIn: string,
  slippage: string,
  shouldUnwrapNativeAsset?: boolean,
  singleTokenOut?: string
) => ExitExactBPTInAttributes;
```

地点 `ExitExactBPTInAttributes` 为:

```js
/**
 * Exit exact BPT in transaction parameters
 * @param to Address that will execute the transaction (vault address)
 * @param functionName Function name to be called (exitPool)
 * @param attributes Transaction attributes ready to be encoded
 * @param data Encoded transaction data
 * @param expectedAmountsOut Expected amounts out of exit transaction
 * @param minAmountsOut Minimum amounts out of exit transaction considering slippage tolerance
 */
export interface ExitExactBPTInAttributes extends ExitPoolAttributes {
  to: string;
  functionName: string;
  attributes: ExitPool;
  data: string;
  expectedAmountsOut: string[];
  minAmountsOut: string[];
}
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/exitExactBPTIn.ts)  
  
可用的池类型 :

-   加权 [示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/exitExactBPTIn.ts)
-   可构成稳定 [示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/pools/composable-stable/exit.ts)
    -   欧比: **只有可构成稳定 > V2 支持比例退出**
-   Meta 稳定
-   稳定

### \# 构建Exit ExactExkens 游戏

根据滑行容忍度构建一个带有精确符号并最大BPT的退出交易.

```js
/**
 * Build exit pool transaction parameters with exact tokens out and maximum BPT in based on slippage tolerance
 * @param exiter Account address exiting pool
 * @param tokensOut Tokens provided for exiting pool (same length and order as amountsOut)
 * @param amountsOut Amounts provided for exiting pool in EVM scale
 * @param slippage Maximum slippage tolerance in bps. i.e. 50 = 5%
 * @returns transaction request ready to send with signer.sendTransaction
 */
buildExitExactTokensOut: (
  exiter: string,
  tokensOut: string[],
  amountsOut: string[],
  slippage: string
) => ExitExactTokensOutAttributes;
```

地点 `ExitExactTokensOutAttributes` 为:

```js
/**
 * Exit exact tokens out transaction parameters
 * @param to Address that will execute the transaction (vault address)
 * @param functionName Function name to be called (exitPool)
 * @param attributes Transaction attributes ready to be encoded
 * @param data Encoded transaction data
 * @param expectedBPTIn Expected BPT into exit transaction
 * @param maxBPTIn Max BPT into exit transaction considering slippage tolerance
 */
export interface ExitExactTokensOutAttributes extends ExitPoolAttributes {
  to: string;
  functionName: string;
  attributes: ExitPool;
  data: string;
  expectedBPTIn: string;
  maxBPTIn: string;
}
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/exitExactTokensOut.ts)  
  
可用的池类型 :

-   加权 [示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/exitExactTokensOut.ts)
-   可构成稳定
-   Meta 稳定
-   稳定

### 出巢池

Exposes 退出功能,允许用户退出一个有池令牌的池是其他池的 BPT 的池,例如:

```
                  CS0
              /        \
            CS1        CS2
          /    \      /   \
         DAI   USDC  USDT  FRAX

Can exit with CS0_BPT proportionally to: DAI, USDC, USDT and FRAX
```

```js
/**
 * Builds generalised exit transaction
 *
 * @param poolId          Pool id
 * @param amount          Token amount in EVM scale
 * @param userAddress     User address
 * @param slippage        Maximum slippage tolerance in bps i.e. 50 = 0.5%.
 * @param signer          JsonRpcSigner that will sign the staticCall transaction if Static simulation chosen
 * @param simulationType  Simulation type (VaultModel, Tenderly or Static)
 * @param authorisation   Optional auhtorisation call to be added to the chained transaction
 * @param unwrapTokens    Determines if wrapped tokens should be unwrapped. Default = false
 * @returns transaction data ready to be sent to the network along with tokens, min and expected amounts out.
 */
async generalisedExit(
  poolId: string,
  amount: string,
  userAddress: string,
  slippage: string,
  signer: JsonRpcSigner,
  simulationType: SimulationType,
  authorisation?: string,
  unwrapTokens = false
): Promise<{
  to: string;
  encodedCall: string;
  tokensOut: string[];
  expectedAmountsOut: string[];
  minAmountsOut: string[];
  priceImpact: string;
}>
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/exitGeneralised.ts)

# 工厂

### 创建池

### 加权波尔

构建交易以创建加权池.

```js
/**
 * Builds a transaction for a weighted pool create operation.
 * @param factoryAddress - The address of the factory for weighted pool (contract address)
 * @param name - The name of the pool
 * @param symbol - The symbol of the pool
 * @param tokenAddresses - The token's addresses
 * @param weights The weights for each token, ordered
 * @param swapFee - The swapFee for the owner of the pool in string or number format(100% is "1.00" or 1, 10% is "0.1" or 0.1, 1% is "0.01" or 0.01)
 * @param owner - The address of the owner of the pool
 * @returns a TransactionRequest object, which can be directly inserted in the transaction to create a weighted pool
 */
create({
    factoryAddress,
    name,
    symbol,
    tokenAddresses,
    weights,
    swapFee,
    owner,
}) =>  {
    to?: string;
    data: BytesLike;
}
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/pools/weighted/create-and-init-join.ts)

### 可构成的稳定池

构建交易以创建可堆肥的稳定池.

```js
/**
 * Builds a transaction for a composable pool create operation.
 * @param contractAddress - The address of the factory for composable stable pool (contract address)
 * @param name - The name of the pool
 * @param symbol - The symbol of the pool
 * @param swapFee - The swapFee for the owner of the pool in string or number format(100% is "1.00" or 1, 10% is "0.1" or 0.1, 1% is "0.01" or 0.01)
 * @param tokenAddresses - The token's addresses
 * @param rateProviders The addresses of the rate providers for each token, ordered
 * @param tokenRateCacheDurations the Token Rate Cache Duration of each token
 * @param owner - The address of the owner of the pool
 * @param amplificationParameter The amplification parameter(must be greater than 1)
 * @param exemptFromYieldProtocolFeeFlags array containing boolean for each token exemption from yield protocol fee flags
 * @returns a TransactionRequest object, which can be directly inserted in the transaction to create a composable stable pool
 */
create({
    factoryAddress,
    name,
    symbol,
    tokenAddresses,
    amplificationParameter,
    rateProviders,
    tokenRateCacheDurations,
    exemptFromYieldProtocolFeeFlags,
    swapFee,
    owner,
}) =>  {
    to?: string;
    data: BytesLike;
}
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/pools/composable-stable/create-and-init-join.ts)

### 线性池

构建交易以创建线性池.

```js
  /**
   *
   * @param name The name of the pool
   * @param symbol The symbol of the pool (BPT name)
   * @param mainToken The unwrapped token
   * @param wrappedToken The wrapped token
   * @param upperTarget The maximum balance of the unwrapped(main) token (normal number, no need to fix to 18 decimals)
   * @param swapFeeEvm The swap fee of the pool
   * @param owner The address of the owner of the pool
   * @param protocolId The protocolId, to check the available value
   */
  create({
    name,
    symbol,
    mainToken,
    wrappedToken,
    upperTarget,
    swapFeeEvm,
    owner,
    protocolId,
  }: LinearCreatePoolParameters) => {
    to?: string;
    data: BytesLike;
  }
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/pools/linear/create.ts)

## 更新服务

续订合同是(用户选入、审计)合同,可以致电金库(交易 " 招标人 " 是任意地址),并代表他们使用汇款人的ERC20金库津贴、内部余额或BPT.

```js
const relayer = new relayerService(
    swapsService: SwapsService;
    rpcUrl: string;
);
```

## 长期损失

> 永久损失(IL) 描述一个游泳池的价值低于一个游泳池的价值的百分比,如果它们只是持有游泳池外的标志

#### 服务

![class-diagram](https://npmcn.com/package/%40balancer-labs/sdk/IL-class.png)

#### 算法

使用变量三角形公式:

![img.png](https://npmcn.com/package/%40balancer-labs/sdk/img.png)

地点 **ΔP(单位:千美元)** 代表加入公积金日单一令牌价格与当期价格之差.

```javascript
// retrieves pool's tokens
tokens = pool.tokens;
// get weights for tokens
weights = tokens.map((token) => token.weight);
// retrieves current price for tokens
exitPrices = tokens.map((token) => tokenPrices.find(token.address));
// retrieves historical price for tokens
entryPrices = tokens.map((token) =>
  tokenPrices.findBy('timestamp', {
    address: token.address,
    timestamp: timestamp,
  })
);
// retrieves list of pool's assets with prices delta and weights
assets = tokens.map((token) => ({
  priceDelta: this.getDelta(
    entryPrices[token.address],
    exitPrices[token.address]
  ),
  weight: weights[i],
}));

poolValueDelta = assets.reduce(
  (result, asset) =>
    result * Math.pow(Math.abs(asset.priceDelta + 1), asset.weight),
  1
);
holdValueDelta = assets.reduce(
  (result, asset) => result + Math.abs(asset.priceDelta + 1) * asset.weight,
  0
);

const IL = poolValueDelta / holdValueDelta - 1;
```

#### 使用量

```javascript
async impermanentLoss(
  timestamp: number, // the UNIX timestamp from which the IL is desired
  pool: Pool // the pool on which the IL must be calculated
): Promise<number>
```

```javascript
const pool = await sdk.pools.find(poolId);
const joins = (await sdk.data.findByUser(userAddress)).filter(
  (it) => it.type === 'Join' && it.poolId === poolId
);
const join = joins[0];
const IL = await pools.impermanentLoss(join.timestamp, pool);
```

[示例](https://npmcn.com/package/%40balancer-labs/sdk/examples/pools/impermanentLoss.ts)

## 托肯斯索赔

### 服务

![classes](https://npmcn.com/package/%40balancer-labs/sdk/claim-incentives-class.png)

### 托肯斯公司持有者索赔

#### 密码

-   **获得可索赔的奖励**

```javascript
const defaultClaimableTokens = [
  '0x7B50775383d3D6f0215A8F290f2C9e2eEBBEceb2', // bb-a-USD v1
  '0xA13a9247ea42D743238089903570127DdA72fE44', // bb-a-USD v2
  '0xba100000625a3754423978a60c9317c58a424e3D', // BAL
]

const claimableTokens: string[] = userDefinedClaimableTokens ?? defaultClaimableTokens;

const balances = await ClaimService.getClaimableVeBalTokens(userAddress, claimableTokens) {
  return await this.feeDistributor.callStatic.claimTokens(userAddress,claimableTokens);
}

const txData = await getClaimableVeBalTokens.buildClaimVeBalTokensRequest(userAddress, claimableTokens) {
  data = feeDistributorContract.claimBalances(userAddress, claimableTokens);
  to = feeDistributorContract.encodeFunctionData('claimTokens', [userAddress, claimableTokens])
}

//on client
signer.request(txData).then(() => { ... });

```

### 索赔池奖励办法

#### 密码

-   **获得可索赔的奖励**

```javascript
gauges = LiquidityGaugesRepository.fetch();
claimableTokensPerGauge = LiquidityGaugesMulticallRepository.getClaimableTokens(gauges, accountAddress) {
  if (MAINNET) {
    claimableTokens = this.multicall.aggregate('claimable_tokens', gauges, accountAddress);
    claimableReward = gauge.rewardData.forEach(this.multicall.aggregate('claimable_reward', gauges, accountAddress, rewardToken);
    return aggregate(claimableReward, claimableTokens);
  } else {
    return gauge.rewardData.forEach(this.multicall.aggregate('claimable_reward', gauges, accountAddress, rewardToken);
  }
};

```

-   **索赔报酬**

它返回编码的可调用数据,以便输入一个签名人,然后发送到测量合同中.

```javascript
if (MAINNET) {
  const callData = balancerMinterInterface.encodeFunctionData('mintMany', [
    gaugeAddresses,
  ]);
  return { to: balancerMinterAddress, data: callData };
} else {
  const callData = gaugeClaimHelperInterface.encodeFunctionData(
    'claimRewardsFromGauges',
    [gaugeAddresses, userAddress]
  );
  return { to: gaugeClaimHelperAddress, data: callData };
}
```

## 许可证发放

[GNU 通用公共许可版本3(GPL v3)](https://npmcn.com/package/LICENSE)。 。 。 .

## 常见问题

### @balancer-labs/sdk 是什么？

用于与平衡器协议 V2 交互的 JavaScript SDK

### 如何安装 @balancer-labs/sdk？

在项目目录运行 npm install @balancer-labs/sdk，或使用 pnpm add / yarn add / bun add。

### @balancer-labs/sdk 支持 TypeScript 吗？

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

### @balancer-labs/sdk 支持 ESM 还是 CommonJS？

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

### @balancer-labs/sdk 可以商用吗？

@balancer-labs/sdk 使用 GPL-3\.0-only 许可。强 Copyleft：分发包含该代码的软件时，整个作品需以 GPL-3\.0 兼容许可开源，并附带专利与反锁定条款。仅内部使用不触发此义务。以上为概括，不构成法律意见，请以许可原文为准。

### @balancer-labs/sdk 的下载量有多少？

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

### @balancer-labs/sdk 还在维护吗？

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

