### Install Dependencies and Run Dev Server Source: https://github.com/balancer/docs/blob/main/README.md Use these commands to install project dependencies, build the custom theme, and start the development server for local setup. ```bash npm install npm run build-theme npm run dev ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Run these commands to install project dependencies, build the project, and copy the example environment file. ```bash npm install npm run build cp .env.example .env ``` -------------------------------- ### Install Balancer SDK using npm Source: https://github.com/balancer/docs/blob/main/docs/guides/arbitrageurs/get-spot-price.md Install the Balancer SDK using npm. This is a prerequisite for using the SDK in your project. ```bash npm install @balancer-labs/sdk ``` -------------------------------- ### Install Balancer SDK using Yarn Source: https://github.com/balancer/docs/blob/main/docs/guides/arbitrageurs/get-spot-price.md Install the Balancer SDK using yarn. This is a prerequisite for using the SDK in your project. ```bash yarn install @balancer-labs/sdk ``` -------------------------------- ### Query Batch Swap Example (ethers.js) Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/vault.md Example of how to use queryBatchSwap with ethers.js using callStatic for a dry run. ```javascript const quote = await vault.callStatic.queryBatchSwap(0, [swap0, swap1], assets, funds); ``` -------------------------------- ### Install AWS CDK Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Installs the AWS Cloud Development Kit globally, which is required for AWS development and deployment. ```bash npm install -g aws-cdk ``` -------------------------------- ### Direct Balance Query Rate Provider Example Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/rate-providers.md This example demonstrates a rate provider that queries the exchange rate from a wrapped rebasing token's own function. It's useful for integrating rebasing tokens like stETH into Balancer. ```solidity pragma solidity ^0.8.0; import {IRateProvider} from "../interfaces/IRateProvider.sol"; contract WstETHRateProvider is IRateProvider { address public immutable wstETH; address public immutable stETH; constructor(address _wstETH, address _stETH) { wstETH = _wstETH; stETH = _stETH; } function getRate() external view override returns (uint256) { // This function would call the underlying stETHPerToken() function on the wstETH contract // For demonstration purposes, we'll return a placeholder value. // In a real implementation, you would interact with the wstETH contract to get the actual rate. // Example: return IWstETH(_wstETH).stEthPerToken(); return 1 ether; // Placeholder value } // Helper function to get the rate for a specific token pair (e.g., wstETH to stETH) function getDirectRate(address tokenIn, address tokenOut) external view returns (uint256) { if (tokenIn == wstETH && tokenOut == stETH) { return getRate(); } else if (tokenIn == stETH && tokenOut == wstETH) { // Inverse rate: 1 / getRate() // Handle potential division by zero or precision issues appropriately return (1 ether * 1e18) / getRate(); // Example inverse calculation } else { // Unsupported token pair return 0; } } } ``` -------------------------------- ### Example SwapInfo Response for ETH to wBTC Source: https://github.com/balancer/docs/blob/main/docs/guides/aggregators/sor-basics.md An example of the swap information returned by the SOR, detailing token addresses, swap details, amounts, and market price. ```javascript { tokenAddresses: [ '0x0000000000000000000000000000000000000000', '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599' ], swaps: [ { poolId: '0xa6f548df93de924d73be7d25dc02554c6bd66db500020000000000000000000e', assetInIndex: 0, assetOutIndex: 1, amount: '1000000000000000000', userData: '0x', returnAmount: '7677860' } ], swapAmount: BigNumber { _hex: '0x0de0b6b3a7640000', _isBigNumber: true }, swapAmountForSwaps: BigNumber { _hex: '0x0de0b6b3a7640000', _isBigNumber: true }, returnAmount: BigNumber { _hex: '0x7527a4', _isBigNumber: true }, returnAmountFromSwaps: BigNumber { _hex: '0x7527a4', _isBigNumber: true }, returnAmountConsideringFees: BigNumber { _hex: '0x752543', _isBigNumber: true }, tokenIn: '0x0000000000000000000000000000000000000000', tokenInForSwaps: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', tokenOut: '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599', tokenOutFromSwaps: '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599' marketSp: '13.022594322651878', } ``` -------------------------------- ### Initialize Balancer SDK Source: https://github.com/balancer/docs/blob/main/docs/guides/arbitrageurs/get-spot-price.md Initialize the Balancer SDK with network configuration and an RPC URL. This setup is required before making any SDK calls. ```typescript 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); ``` -------------------------------- ### Swap WETH for BAL on Arbitrum Source: https://github.com/balancer/docs/blob/main/docs/guides/API/usage.md This example demonstrates how to swap WETH for BAL on the Arbitrum network using the Balancer API. ```APIDOC ## POST /sor/{chainId} ### Description Swaps WETH for BAL on the Arbitrum network. ### Method POST ### Endpoint $ENDPOINT_URL/sor/42161 ### Parameters #### Request Body - **sellToken** (string) - Required - The address of the token to sell. - **buyToken** (string) - Required - The address of the token to buy. - **orderKind** (string) - Required - The type of order, either 'buy' or 'sell'. - **amount** (string) - Required - The amount of tokens to swap. - **gasPrice** (string) - Required - The gas price to use for the transaction. ### Request Example ```json { "sellToken": "0x82af49447d8a07e3bd95bd0d56f35241523fbab1", "buyToken": "0x040d1EdC9569d4Bab2D15287Dc5A4F10F56a56B8", "orderKind": "sell", "amount": "1000000000000000000", "gasPrice": "10000000" } ``` ### Response #### Success Response (200) (Response details not provided in source) ``` -------------------------------- ### Run Local Development Environment Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Commands to start a local DynamoDB, initialize tables, and run the worker and API server for local development. ```bash # Run a local DynamoDB Database npm run dynamodb # Create Tables npm run init # NOTE: If the init command hangs, you may need to fix permissions on your dynamodb data folder. You can do this with: sudo chown -R $(whoami):docker ./docker # Run Worker npm run worker # In another terminal, Run API Server npm start ``` -------------------------------- ### Swap WETH for an exact amount of BAL Source: https://github.com/balancer/docs/blob/main/docs/guides/API/usage.md This example demonstrates how to swap WETH for an exact amount of BAL using the Balancer API. ```APIDOC ## POST /sor/{chainId} ### Description Swaps WETH for an exact amount of BAL. ### Method POST ### Endpoint $ENDPOINT_URL/sor/1 ### Parameters #### Request Body - **sellToken** (string) - Required - The address of the token to sell. - **buyToken** (string) - Required - The address of the token to buy. - **orderKind** (string) - Required - The type of order, either 'buy' or 'sell'. - **amount** (string) - Required - The amount of tokens to swap. - **gasPrice** (string) - Required - The gas price to use for the transaction. ### Request Example ```json { "sellToken": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "buyToken": "0xba100000625a3754423978a60c9317c58a424e3d", "orderKind": "buy", "amount": "1000000000000000000", "gasPrice": "10000000" } ``` ### Response #### Success Response (200) (Response details not provided in source) ``` -------------------------------- ### Swap WETH for BAL on Polygon Source: https://github.com/balancer/docs/blob/main/docs/guides/API/usage.md This example demonstrates how to swap WETH for BAL on the Polygon network using the Balancer API. ```APIDOC ## POST /sor/{chainId} ### Description Swaps WETH for BAL on the Polygon network. ### Method POST ### Endpoint $ENDPOINT_URL/sor/137 ### Parameters #### Request Body - **sellToken** (string) - Required - The address of the token to sell. - **buyToken** (string) - Required - The address of the token to buy. - **orderKind** (string) - Required - The type of order, either 'buy' or 'sell'. - **amount** (string) - Required - The amount of tokens to swap. - **gasPrice** (string) - Required - The gas price to use for the transaction. ### Request Example ```json { "sellToken": "0x9a71012B13Ca47D3D0Cdc72A177DF3ef03b0E76A3", "buyToken": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", "orderKind": "sell", "amount": "1000000000000000000", "gasPrice": "10000000" } ``` ### Response #### Success Response (200) (Response details not provided in source) ``` -------------------------------- ### Get Gradual Weight Update Parameters Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/managed.md Retrieves the parameters for a gradual weight update, including start and end times, and the corresponding start and end weight arrays. ```solidity getGradualWeightUpdateParams() returns (uint256 startTime, uint256 endTime, uint256[] memory startWeights, uint256[] memory endWeights) ``` -------------------------------- ### Initialize Balancer SDK and Get Pool Source: https://github.com/balancer/docs/blob/main/docs/guides/builders/exit-pool.md Sets up the Balancer SDK and retrieves a specific pool using its ID. This is a prerequisite for performing any pool operations. ```javascript import { BalancerSDK } from '@balancer-labs/sdk'; const balancer = new BalancerSDK({ network: 1, // mainnet rpcUrl: 'https://rpc.ankr.com/eth', }); // stETH pool const poolId = '0x32296969ef14eb0c6d29669c550d4a0449130230000200000000000000000080'; // Get the SDK pool with service methods const pool = await balancer.pools.find(poolId); ``` -------------------------------- ### Yield Fees Minted Example Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/rate-providers.md Demonstrates a scenario where yield fees are minted, indicated by positive return values from `WeightedPool._getYieldProtocolFeesPoolPercentage`. ```Sol WeightedPool._getYieldProtocolFeesPoolPercentage ( normalizedWeights = ["800000000000000000","200000000000000000"] ) => (1074881576209740, 978863663373687295) ``` -------------------------------- ### Swap WXDAI for USDC on Gnosis Chain Source: https://github.com/balancer/docs/blob/main/docs/guides/API/usage.md This example demonstrates how to swap WXDAI for USDC on the Gnosis Chain network using the Balancer API. ```APIDOC ## POST /sor/{chainId} ### Description Swaps WXDAI for USDC on the Gnosis Chain network. ### Method POST ### Endpoint $ENDPOINT_URL/sor/100 ### Parameters #### Request Body - **sellToken** (string) - Required - The address of the token to sell. - **buyToken** (string) - Required - The address of the token to buy. - **orderKind** (string) - Required - The type of order, either 'buy' or 'sell'. - **amount** (string) - Required - The amount of tokens to swap. - **gasPrice** (string) - Required - The gas price to use for the transaction. ### Request Example ```json { "sellToken": "0xe91d153e0b41518a2ce8dd3d7944fa863463a97d", "buyToken": "0xDDAfbb505ad214D7b80b1f830fcCc89B60fb7A83", "orderKind": "sell", "amount": "1000000000000000000", "gasPrice": "100000" } ``` ### Response #### Success Response (200) (Response details not provided in source) ``` -------------------------------- ### Swapping with Native Asset Source: https://github.com/balancer/docs/blob/main/docs/sdk/technical-reference/native-asset-address-as-address-zero.md When performing swaps, use address zero to indicate the native asset as the input token. This example demonstrates swapping ETH for WBTC. ```typescript const AddressZero = '0x0000000000000000000000000000000000000000'; const tokenIn = AddressZero; // eth const tokenOut = '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599'; // wBTC const amount = String(BigInt(100e18)); // 100 eth // Building the route payload const payload = await sdk.swaps.buildRouteExactIn( sender, recipient, tokenIn, // eth tokenOut, // wBTC amount, ); ``` -------------------------------- ### Swap BAL for DAI on Polygon Source: https://github.com/balancer/docs/blob/main/docs/guides/API/usage.md This example demonstrates swapping BAL for DAI on the Polygon network. Provide the token addresses for BAL and DAI, the order kind ('sell'), the amount, and the gas price. ```sh curl -X POST -H "Content-Type: application/json" -d '{"sellToken":"0x9a71012B13CA4d3D0Cdc72A177DF3ef03b0E76A3","buyToken":"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174","orderKind":"sell", "amount":"1000000000000000000", "gasPrice":"10000000"}' $ENDPOINT_URL/sor/137 ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Starts the Hardhat network and runs E2E tests that perform SOR requests and on-chain swaps. Ensure API and Hardhat network are running. ```bash # This starts the forked hardhat npm run node # In another terminal npm run test:e2e ``` -------------------------------- ### Get Swap Fee and Gradual Update Parameters Source: https://github.com/balancer/docs/blob/main/docs/concepts/pools/managed.md Retrieves the current swap fee percentage and the parameters for any ongoing gradual swap fee updates. ```Solidity uint256 swapFeePercentage = _managedPool.getSwapFeePercentage(); ( uint256 startTime, uint256 endTime, uint256 startSwapFeePercentage, uint256 endSwapFeePercentage ) = _managedPool.getGradualSwapFeeUpdateParams(); ``` -------------------------------- ### Swap BAL for DAI using SOR Source: https://github.com/balancer/docs/blob/main/docs/guides/API/usage.md Example cURL command to perform a BAL to DAI swap using the /sor endpoint on chain 1 (Mainnet). ```sh curl -X POST -H "Content-Type: application/json" -d '{"sellToken":"0xba100000625a3754423978a60c9317c58a424e3d","buyToken":"0x6b175474e89094c44da98b954eedeac495271d0f","orderKind":"sell", "amount":"1000000000000000000", "gasPrice":"10000000"}' $ENDPOINT_URL/sor/1 ``` -------------------------------- ### Sample Response for Gauge Tokens Query Source: https://github.com/balancer/docs/blob/main/docs/reference/vebal-and-gauges/gauges.md Example JSON response from a GraphQL query for gauge tokens, showing token details like symbol, decimals, and total deposited. ```json { "data": { "liquidityGauges": [ { "id": "0xcd4722b7c24c29e0413bdcd9e51404b4539d14ae", "tokens": [ { "id": "0x5a98fcbea516cf06857215779fd812ca3bef1b32-0xcd4722b7c24c29e0413bdcd9e51404b4539d14ae", "symbol": "LDO", "decimals": 18, "totalDeposited": "150000" } ] } ] } } ``` -------------------------------- ### Build Project and Preview Source: https://github.com/balancer/docs/blob/main/README.md Commands to build the project, including the theme, and then build a production preview. Useful for testing production-specific features like metadata. ```bash npm run build-theme npm run build npm run build:preview ``` -------------------------------- ### Get Gradual Swap Fee Update Parameters Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/managed.md Retrieves the parameters for a gradual swap fee update, including start and end times, and the corresponding start and end swap fee percentages. ```solidity getGradualSwapFeeUpdateParams() returns (uint256 startTime, uint256 endTime, uint256 startSwapFeePercentage, uint256 endSwapFeePercentage) ``` -------------------------------- ### View Upcoming Rewards for Multiple Weeks Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/4_RewardFaucet.md Get an array of reward amounts for a specified number of upcoming weeks, starting from the current week. ```solidity function getUpcomingRewardsForNWeeks(address token, uint256 weeksCount) external view returns (uint256[] memory) ``` -------------------------------- ### Initialize Balancer SDK and Pool Source: https://github.com/balancer/docs/blob/main/docs/guides/builders/join-pool.md Set up the Balancer SDK with network and RPC URL, then find a specific pool by its ID. Ensure you have a signer available for transaction submission. ```javascript import { BalancerSDK } from '@balancer-labs/sdk'; const balancer = new BalancerSDK({ network: 1, // mainnet rpcUrl: 'https://rpc.ankr.com/eth', }); const signer = balancer.provider.getSigner(); const poolId = '0x32296969ef14eb0c6d29669c550d4a0449130230000200000000000000000080'; const pool = balancer.pools.find(poolId); ``` -------------------------------- ### Initialize Pricing Service Source: https://github.com/balancer/docs/blob/main/docs/sdk/technical-reference/pricing.md Instantiate the Pricing service to find the spot price for a token pair. This service finds the most liquid path and uses it as a reference spot price. ```javascript const pricing = new Pricing(sdkConfig); ``` -------------------------------- ### Initialize Balancer SDK and Swaps Module Source: https://github.com/balancer/docs/blob/main/docs/guides/aggregators/sor-basics.md Initialize the Balancer SDK with network and RPC details, then access the swaps module for SOR functionalities. ```javascript import { BalancerSDK } from '@balancer-labs/sdk' const balancer = new BalancerSDK({ network: 1, // Mainnet rpcUrl: 'https://rpc.ankr.com/eth' // rpc endpoint }) const { swaps } = balancer // Swaps module ``` -------------------------------- ### Get Token Address Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/3_RewardDistributor.md Returns the address of the ERC20 token that can be deposited into the VotingEscrow contract. ```solidity function token() external view returns (address) ``` -------------------------------- ### Get Tokens Lambda Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Retrieve a JSON array of all known tokens for a specified chain. ```APIDOC ## GET /tokens/{chainId} ### Description Returns a JSON array of all known tokens for the specified chain. ### Method GET ### Endpoint /tokens/{chainId} ### Parameters #### Path Parameters - **chainId** (string) - Required - The chain/network number (e.g., 1 for Mainnet, 137 for Polygon). ### Response #### Success Response (200) - **tokens** (array) - An array of token objects. ``` -------------------------------- ### Bootstrap AWS CDK Environment Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Initializes the AWS CDK in your account and region. This command must be run before deploying for the first time. ```bash cdk bootstrap aws://$AWS_ACCOUNT_ID/$AWS_REGION ``` -------------------------------- ### Get VotingEscrow Contract Name Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/3_RewardDistributor.md Returns the name of the current VotingEscrow contract associated with this RewardDistributor. ```solidity function name() external view returns (string memory) ``` -------------------------------- ### Get Pools Lambda Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Retrieve a JSON array containing all Balancer pools for a specified chain. ```APIDOC ## GET /pools/{chainId} ### Description Returns a JSON array of all Balancer pools for the specified chain. ### Method GET ### Endpoint /pools/{chainId} ### Parameters #### Path Parameters - **chainId** (string) - Required - The chain/network number (e.g., 1 for Mainnet, 137 for Polygon). ### Request Example ```sh curl $ENDPOINT_URL/pools/1 ``` ### Response #### Success Response (200) - **pools** (array) - An array of Balancer pool objects. ``` -------------------------------- ### updateWeightsGradually Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/managed.md Schedules a gradual change in token weights between specified start and end times. This is a permissioned function. ```APIDOC ## updateWeightsGradually ### Description Schedules a gradual weight change at the block timestamp provided in `startTime`, up until `endTime`. This is a permissioned function that can only be called by an authorized address set by the `owner`. If the pool is paused, the call will revert. Implemented in `ManagedPoolSettings`. ### Method `updateWeightsGradually(uint256 startTime, uint256 endTime, IERC20[] memory tokens, uint256[] memory endWeights)` ### Parameters #### Path Parameters - `startTime` (uint256) - Required - The block timestamp when the gradual weight update begins. - `endTime` (uint256) - Required - The block timestamp when the gradual weight update ends. - `tokens` (IERC20[]) - Required - An array of token addresses. - `endWeights` (uint256[]) - Required - An array of the target weights at the end time. ### Emits - `GradualWeightUpdateScheduled` ``` -------------------------------- ### Deploy and Initialize Vote Escrow System Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/1_launchpad.md Use this function to deploy new VotingEscrow, RewardDistributor, and RewardFaucet contracts. It utilizes the minimal-proxy pattern for deployment and initializes each contract with specific parameters. Ensure that the `tokenBptAddr` is not the same as `balToken`. ```vyper def deploy( tokenBptAddr: address, name: String[64], symbol: String[32], maxLockTime: uint256, rewardDistributorStartTime: uint256, admin_unlock_all: address, admin_early_unlock: address, rewardReceiver: address ) -> (address, address, address): """ @notice Deploys new VotingEscrow, RewardDistributor and RewardFaucet contracts @param tokenBptAddr The address of the token to be used for locking @param name The name for the new VotingEscrow contract @param symbol The symbol for the new VotingEscrow contract @param maxLockTime A constraint for the maximum lock time in the new VotingEscrow contract @param rewardDistributorStartTime The start time for reward distribution @param admin_unlock_all Admin address to enable unlock-all feature in VotingEscrow (zero-address to disable forever) @param admin_early_unlock Admin address to enable early-unlock feature in VotingEscrow (zero-address to disable forever) @param rewardReceiver The receiver address of claimed BAL-token rewards """ assert(balToken != tokenBptAddr), '!bal' newVotingEscrow: address = create_minimal_proxy_to(votingEscrow) newRewardDistributor: address = create_minimal_proxy_to(rewardDistributor) rewardReceiverChangeable: bool = True rewardReceiver_: address = rewardReceiver if rewardReceiver == empty(address): rewardReceiver_ = newRewardDistributor rewardReceiverChangeable = False IVotingEscrow(newVotingEscrow).initialize( tokenBptAddr, name, symbol, msg.sender, admin_unlock_all, admin_early_unlock, maxLockTime, balToken, balMinter, rewardReceiver_, rewardReceiverChangeable, newRewardDistributor ) newRewardFaucet: address = create_minimal_proxy_to(rewardFaucet) IRewardDistributor(newRewardDistributor).initialize( newVotingEscrow, newRewardFaucet, rewardDistributorStartTime, msg.sender ) IRewardFaucet(newRewardFaucet).initialize( newRewardDistributor ) log VESystemCreated( tokenBptAddr, newVotingEscrow, newRewardDistributor, newRewardFaucet, msg.sender ) return (newVotingEscrow, newRewardDistributor, newRewardFaucet) ``` -------------------------------- ### updateSwapFeeGradually Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/managed.md Schedules a gradual change in swap fees between specified start and end times. This is a permissioned function. ```APIDOC ## updateSwapFeeGradually ### Description Schedules a gradual update in swap fees at the block timestamp provided in `startTime`, up until `endTime`. This is a permissioned function that can only be called by an authorized address. If the pool is paused, the call will revert. Implemented in `ManagedPoolSettings`. ### Method `updateSwapFeeGradually(uint256 startTime, uint256 endTime, uint256 startSwapFeePercentage, uint256 endSwapFeePercentage)` ### Parameters #### Path Parameters - `startTime` (uint256) - Required - The block timestamp when the gradual swap fee update begins. - `endTime` (uint256) - Required - The block timestamp when the gradual swap fee update ends. - `startSwapFeePercentage` (uint256) - Required - The swap fee percentage at the start time. - `endSwapFeePercentage` (uint256) - Required - The swap fee percentage at the end time. ### Emits - `GradualSwapFeeUpdateScheduled` ``` -------------------------------- ### Get Protocol Fees Collector Function Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/vault.md Returns the external contract address authorized to collect protocol fees. ```solidity getProtocolFeesCollector() returns (ProtocolFeesCollector) ``` -------------------------------- ### Reconstruct Launchpad Constructor Arguments Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/5_Troubleshooting.md If constructor arguments are lost, they can be manually built by inserting the addresses of the VotingEscrow and RewardDistributor implementations without the '0x' prefix into the provided string format. Use this method only if you have the correct implementation addresses. ```text 0000000000000000000000000000000000000000000000000 ``` ```text 000000000000000000000000692c6827ee5cd22507dd56e3817abc9327382b600000000000000000000000008e4eeecaa12a7e1e00d192ec7db00fb066100d7b ``` -------------------------------- ### getGradualWeightUpdateParams Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/managed.md Fetches the parameters for any ongoing gradual weight updates, including start and end times, and the initial and final weights. ```APIDOC ## getGradualWeightUpdateParams ### Description Returns the current gradual weight change update parameters. Implemented in `ManagedPoolSettings`. ### Method `getGradualWeightUpdateParams()` ### Returns - `uint256 startTime`: The start time of the gradual update. - `uint256 endTime`: The end time of the gradual update. - `uint256[] memory startWeights`: The weights at the start time. - `uint256[] memory endWeights`: The weights at the end time. ``` -------------------------------- ### Deploy SmartWalletWhitelist Contract Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/7_SmartWalletWhitelist.md Execute this command to deploy the SmartWalletWhitelist contract. Ensure you specify the correct network name. ```sh npx hardhat run ./scripts/utils/deploySmartAllowList.ts --network networkName ``` -------------------------------- ### Get Vault Authorizer Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/vault.md Retrieves the Vault's current Authorizer contract address. This is used to manage governance operations. ```solidity getAuthorizer() returns (IAuthorizer) ``` -------------------------------- ### Initialize Relayer Service Source: https://github.com/balancer/docs/blob/main/docs/sdk/technical-reference/relayer.md Instantiate the Relayer service with the SwapsService and RPC URL. Ensure SwapsService is properly configured before initialization. ```javascript const relayer = new relayerService( swapsService: SwapsService; rpcUrl: string; ); ``` -------------------------------- ### Query Single Swap Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/query-functions.md Calculates the output amount for a single swap operation. Use this to get a quote for a swap before executing it. ```solidity querySwap( IVault.SingleSwap memory singleSwap, IVault.FundManagement memory funds) returns (uint256) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Executes the unit tests for the project. ```bash npm run test ``` -------------------------------- ### Deploy New ve-System Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/1_launchpad.md Use this function to create a new pair of VotingEscrow and RewardsDistribution contracts. The caller is assigned the admin role for these new contracts. Ensure parameters like `maxLockTime` and `rewardDistributorStartTime` meet the specified minimums. ```Solidity function deploy( address tokenBptAddr, string memory name, string memory symbol, uint256 maxLockTime, uint256 rewardDistributorStartTime address admin_unlock_all, address admin_early_unlock, address rewardReceiver ) external returns (address, address); ``` -------------------------------- ### Get AUM Fee Parameters Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/managed.md Retrieve the current AUM fee percentage and the timestamp of the last fee collection using `getManagementAumFeeParams`. ```solidity getManagementAumFeeParams() returns (uint256 aumFeePercentage, uint256 lastCollectionTimestamp) ``` -------------------------------- ### Get Single Pool Lambda Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Retrieve detailed JSON information about a specific Balancer pool identified by its ID on a given chain. ```APIDOC ## GET /pools/{chainId}/{id} ### Description Returns JSON information about a specific Balancer pool identified by its ID on the given chain. ### Method GET ### Endpoint /pools/{chainId}/{id} ### Parameters #### Path Parameters - **chainId** (string) - Required - The chain/network number (e.g., 1 for Mainnet, 137 for Polygon). - **id** (string) - Required - The unique identifier of the pool. ### Request Example ```sh curl $ENDPOINT_URL/pools/1/0x5aa90c7362ea46b3cbfbd7f01ea5ca69c98fef1c000200000000000000000020 ``` ### Response #### Success Response (200) - **pool** (object) - An object containing detailed information about the specified pool. ``` -------------------------------- ### Exit Pool - Exact BPT In Source: https://github.com/balancer/docs/blob/main/docs/sdk/technical-reference/liquidity-provisioning.md Exposes Exit functionality allowing users to exit pools. The `buildExitExactBPTIn` method constructs an exit transaction with exact BPT in. ```APIDOC ## buildExitExactBPTIn ### Description Builds an exit transaction with exact BPT in and minimum token amounts out based on slippage tolerance. ### Method Signature ```javascript buildExitExactBPTIn( exiter: string, bptIn: string, slippage: string, singleTokenMaxOut?: string ) => Promise; ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **exiter** (string) - Required - Account address exiting pool. - **bptIn** (string) - Required - BPT provided for exiting pool. - **slippage** (string) - Required - Maximum slippage tolerance in percentage. i.e. 0.05 = 5%. - **singleTokenMaxOut** (string) - Optional - Token address that if provided will exit to the given token. ### Request Example ```javascript const balancer = new BalancerSDK(sdkConfig); const pool = await balancer.pools.find(poolId); const { to, functionName, attributes, data } = pool.buildExitExactBPTIn({ exiter: "0x...", bptIn: "1000000000000000000", slippage: "0.05", singleTokenMaxOut: "0x..." }); ``` ### Response #### Success Response (ExitPoolAttributes) - **to** (string) - The recipient address for the transaction. - **functionName** (string) - The name of the function to be called. - **attributes** (object) - Additional attributes for the transaction. - **data** (string) - The transaction data payload. #### Response Example ```json { "to": "0x...", "functionName": "exitPool", "attributes": { ... }, "data": "0x..." } ``` ``` -------------------------------- ### Initialize Balancer SDK and Find Pool Source: https://github.com/balancer/docs/blob/main/docs/sdk/technical-reference/liquidity-provisioning.md Initializes the Balancer SDK and finds a specific pool by its ID. This is a prerequisite for performing join or exit operations. ```javascript const balancer = new BalancerSDK(sdkConfig); const pool = await balancer.pools.find(poolId); ``` -------------------------------- ### Find Swap Route (Given Out) Source: https://github.com/balancer/docs/blob/main/docs/sdk/technical-reference/smart-order-router.md Finds the optimal swap route when the desired amount of output tokens is known. It considers factors like swap size, gas costs, and slippage. ```APIDOC const swapInfo = await swaps.findRouteGivenOut({ tokenIn: '0xstring', // address of tokenIn tokenOut: '0xstring', // address of tokenOut amount: parseEther('1'), // BigNumber with a swap amount gasPrice: parseFixed('1', 9), // BigNumber current gas price maxPools, // number of pool included in path, above 4 is usually a high gas price }); // Response structure is the same as findRouteGivenIn ``` -------------------------------- ### getGradualSwapFeeUpdateParams Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/managed.md Fetches the parameters for any ongoing gradual swap fee updates, including start and end times, and the initial and final fee percentages. ```APIDOC ## getGradualSwapFeeUpdateParams ### Description Returns the current gradual swap fee update parameters. Implemented in `ManagedPoolSettings`. ### Method `getGradualSwapFeeUpdateParams()` ### Returns - `uint256 startTime`: The start time of the gradual update. - `uint256 endTime`: The end time of the gradual update. - `uint256 startSwapFeePercentage`: The swap fee percentage at the start time. - `uint256 endSwapFeePercentage`: The swap fee percentage at the end time. ``` -------------------------------- ### Find Swap Route (Given In) Source: https://github.com/balancer/docs/blob/main/docs/sdk/technical-reference/smart-order-router.md Finds the optimal swap route when the amount of input tokens is known. It considers factors like swap size, gas costs, and slippage. ```APIDOC const swapInfo = await swaps.findRouteGivenIn({ tokenIn: '0xstring', // address of tokenIn tokenOut: '0xstring', // address of tokenOut amount: parseEther('1'), // BigNumber with a swap amount gasPrice: parseFixed('1', 9), // BigNumber current gas price maxPools, // number of pool included in path, above 4 is usually a high gas price }); // Response structure: // { // tokenAddresses: string[] // tokens used in swaps // swaps: SwapV2[] // swaps calldata // swapAmount: BigNumber // swapAmountForSwaps: BigNumber // used for wrapped assets, eg: stETH / wstETH // returnAmount: BigNumber // returnAmountFromSwaps: BigNumber // used for wrapped assets, eg: stETH/wstETH // returnAmountConsideringFees: BigNumber // tokenIn: string // tokenInForSwaps: string // Used with stETH/wstETH // tokenOut: string // tokenOutFromSwaps: string // Used with stETH/wstETH // marketSp: string // } ``` -------------------------------- ### Get User Claimable Reward for a Single Token Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/6_LensReward.md Retrieves the claimable reward amount for a specific user and reward token from the RewardDistributor contract. ```APIDOC ## getUserClaimableReward ### Description Retrieves the claimable reward amount for a specific user and reward token from the RewardDistributor contract. ### Method `callStatic` (recommended to avoid gas fees) ### Function Signature `LensReward.getUserClaimableReward( address rewardDistributor, address user, address rewardToken ) external view returns (ClaimableRewards memory)` ### Parameters #### Path Parameters - **rewardDistributor** (address) - Required - The address of the RewardDistributor contract. - **user** (address) - Required - The user's address to check pending rewards on. - **rewardToken** (address) - Required - The reward token address to check rewards. ### Response #### Success Response - **ClaimableRewards** (memory) - An object containing the token address and the claimable amount. - **token** (address) - The address of the reward token. - **claimableAmount** (uint256) - The amount of rewards claimable. ``` -------------------------------- ### Calculate LP Token NAV (Pseudocode) Source: https://github.com/balancer/docs/blob/main/docs/reference/lp-tokens/valuing.md This pseudocode demonstrates how to calculate the Net Asset Value (NAV) of an LP token by fetching token balances, their market prices, and then computing the total pool value divided by the LP token supply. Use `getVirtualSupply()` for pools with pre-minted BPT. ```typescript (tokens, balances, lastChangeBlock) = vault.getPoolTokens(poolId); prices = fetchPricesFromPriceProvider(tokens); //ex. CoinGecko poolValueUsd = sum(balances[i]*price[i]); bptPriceUsd = poolValueUsd/bpt.totalSupply(); ``` -------------------------------- ### Flash Swap Execution Steps Source: https://github.com/balancer/docs/blob/main/docs/reference/swaps/flash-swaps.md Details the sequence of swaps within a flash swap. The `amount` field in subsequent swaps can be set to zero to use the output of the previous swap. ```json "swaps": [ { "poolId": "0x3a19030ed746bd1c3f2b0f996ff9479af04c5f0a000200000000000000000004", "assetInIndex": "0", "assetOutIndex": "1", "amount": "1000000" }, { "poolId": "0x32fc95287b14eaef3afa92cccc48c285ee3a280a000100000000000000000005", "assetInIndex": "1", "assetOutIndex": "0", "amount": "0" } ], ``` -------------------------------- ### Get Pool Owner Address Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/pool-interfacing.md Query the owner of a pool contract. The convention for static fees is to set the pool owner to the zero address. ```solidity pool.getOwner() ``` -------------------------------- ### Build and Deploy AWS Infrastructure Source: https://github.com/balancer/docs/blob/main/docs/guides/API/setup.md Commands to compile the CDK code and deploy the AWS infrastructure. Run `npm run build` after making changes to CDK scripts. ```bash # Compile the CDK index.ts to javascript, must be run after changes are made npm run build # Run CDK to create/update your infrastructure npm run deploy ``` -------------------------------- ### Deposit Rewards for a Specific Week Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/4_RewardFaucet.md Deposits rewards into a specific week, starting from the current week. May require manual distribution of past rewards. ```APIDOC ## depositToken ### Description Deposits rewards into a specific week (starting from current). If a week is separated from previous reward weeks, or rewards were not claimed in previous weeks in the RewardDistributor contract, users may need to manually call the `distributePastRewards()` function to ensure that the rewards are added to the RewardDistributor contract. ### Method EXTERNAL ### Endpoint `RewardFaucet.sol:depositToken(address token, uint256 amount, uint256 weekTimeStamp)` ### Parameters #### Path Parameters - **token** (address) - The address of the token to be deposited as a reward. - **amount** (uint256) - The amount of `token` to be deposited as a reward. - **weekTimeStamp** (uint256) - The timestamp of the week for which rewards are being distributed. ``` -------------------------------- ### View Token Rewards for a Specific Week Source: https://github.com/balancer/docs/blob/main/docs/reference/vote-escrow-launchpad/4_RewardFaucet.md Retrieve the reward amount for a given token on a specific week. Weeks are defined as starting on Thursdays at midnight. ```solidity function getTokenWeekAmounts(address token, uint256 pointOfWeek) external view returns (uint256) ``` -------------------------------- ### Get Spot Price Function Signature Source: https://github.com/balancer/docs/blob/main/docs/sdk/technical-reference/pricing.md This is the TypeScript signature for the getSpotPrice function. It allows specifying token addresses and optionally providing pool data. ```typescript /** * @param { string } tokenIn Token in address. * @param { string } tokenOut Token out address. * @param { SubgraphPoolBase[] } pools Optional - Pool data. Will be fetched via dataProvider if not supplied. * @returns { string } Spot price. **/ async getSpotPrice( tokenIn: string, tokenOut: string, pools: SubgraphPoolBase[] = [] ): Promise ``` -------------------------------- ### Get Pool Address and Specialization Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/apis/vault.md Retrieves the contract address and specialization configuration for a given pool ID. This allows other contracts to interact with a specific pool. ```solidity getPool(bytes32 poolId) returns (address, PoolSpecialization) ``` -------------------------------- ### querySwap Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/query-functions.md Simulates a single swap operation and returns the expected output amount. ```APIDOC ## querySwap ### Description Simulates a single swap operation based on the provided swap details and fund management configuration. ### Method Signature ```solidity querySwap( IVault.SingleSwap memory singleSwap, IVault.FundManagement memory funds) returns (uint256) ``` ### Parameters - `singleSwap` (IVault.SingleSwap memory): Details of the swap, including pool ID, asset in/out, amount, and swap kind. - `funds` (IVault.FundManagement memory): Information about the sender, recipient, and internal balance usage. ``` -------------------------------- ### Chainlink Registry Rate Provider Example Source: https://github.com/balancer/docs/blob/main/docs/reference/contracts/rate-providers.md This contract uses Chainlink's registry to dynamically find the correct price feed for an asset pair. It handles potential Chainlink migrations to new price feeds, offering increased robustness at the cost of higher gas fees. ```solidity pragma solidity ^0.8.0; import {IRateProvider} from "../interfaces/IRateProvider.sol"; import {ChainlinkRegistry} from "@chainlink/contracts/src/v0.8/shared/access/ChainlinkRegistry.sol"; contract ChainlinkRegistryRateProvider is IRateProvider, ChainlinkRegistry { address public immutable token; address public immutable quoteAsset; uint8 public immutable decimals; constructor(address _token, address _quoteAsset, uint8 _decimals) { token = _token; quoteAsset = _quoteAsset; decimals = _decimals; } function getRate() external view override returns (uint256) { // Get the latest answer from the Chainlink price feed // The price feed is determined by the token and quoteAsset using Chainlink's registry (, int256 price, , ) = getPrice(token, quoteAsset); // Ensure the price is positive and convert to the correct decimal format require(price > 0, "Negative or zero price feed"); return uint256(price) * (10 ** (18 - decimals)); } } ```