@defiverse/balancer-sdk-megaeth 0.1.252
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +843 -0
- package/dist/index.d.ts +6898 -0
- package/dist/index.esm.js +489 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/index.js +489 -0
- package/dist/index.js.map +1 -0
- package/dist/index.umd.js +489 -0
- package/dist/index.umd.js.map +1 -0
- package/package.json +102 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../../src/pool-stable/encoder.ts","../../src/pool-weighted/encoder.ts","../../src/pool-weighted/normalizedWeights.ts","../../src/pool-composable-stable/encoder.ts","../node_modules/tiny-invariant/dist/esm/tiny-invariant.js","../../src/pool-utils/poolId.ts","../../src/lib/constants/network.ts","../../src/lib/constants/pools.ts","../../src/lib/utils/aaveHelpers.ts","../../src/lib/utils/assetHelpers.ts","../../src/lib/utils/errors.ts","../../src/lib/utils/signatures.ts","../../src/lib/utils/permit.ts","../../src/lib/utils/solidityMaths.ts","../../src/lib/utils/poolHelper.ts","../../src/lib/constants/tokens.ts","../../src/modules/data/pool-gauges/types.ts","../../src/modules/data/pool-shares/types.ts","../../src/modules/data/gauge-shares/types.ts","../../src/types.ts","../node_modules/@ethersproject/logger/lib.esm/index.js","../node_modules/@ethersproject/logger/lib.esm/_version.js","../node_modules/@ethersproject/units/lib.esm/_version.js","../node_modules/@ethersproject/units/lib.esm/index.js","../../src/modules/data/token-yields/tokens/aave.ts","../../src/lib/utils/tokens.ts","../../src/lib/utils/debouncer.ts","../../src/lib/utils/math.ts","../../src/lib/utils/index.ts","../../src/lib/graphql/formatters/balancer-api.ts","../../src/lib/graphql/formatters/subgraph.ts","../../src/lib/graphql/args-builder.ts","../../src/modules/swaps/types.ts","../../src/modules/swaps/helpers.ts","../../src/lib/utils/slippageHelper.ts","../../src/lib/constants/config.ts","../../src/balancerErrors.ts","../../src/modules/pools/pool-types/concerns/stable/exit.concern.ts","../../src/modules/pools/pool-types/concerns/stable/join.concern.ts","../../src/modules/pools/pool-types/concerns/stable/liquidity.concern.ts","../../src/modules/pools/pool-types/concerns/stable/spotPrice.concern.ts","../../src/modules/pricing/priceImpact.ts","../../src/lib/utils/stableMathHelpers.ts","../../src/modules/pools/pool-types/concerns/stable/priceImpact.concern.ts","../../src/modules/pools/pool-types/stable.module.ts","../../src/modules/pools/pool-types/concerns/stablePhantom/spotPrice.concern.ts","../../src/modules/pools/pool-types/concerns/stablePhantom/priceImpact.concern.ts","../../src/modules/pools/pool-types/concerns/composableStable/join.concern.ts","../../src/modules/pools/pool-types/concerns/composableStable/exit.concern.ts","../../src/modules/pools/pool-types/composableStable.module.ts","../../src/modules/pools/pool-types/concerns/weighted/exit.concern.ts","../../src/modules/pools/pool-types/concerns/weighted/join.concern.ts","../../src/modules/pools/pool-types/concerns/weighted/liquidity.concern.ts","../../src/modules/pools/pool-types/concerns/weighted/spotPrice.concern.ts","../../src/modules/pools/pool-types/concerns/weighted/priceImpact.concern.ts","../../src/modules/pools/pool-types/weighted.module.ts","../../src/modules/pools/pool-types/concerns/metaStable/exit.concern.ts","../../src/modules/pools/pool-types/concerns/metaStable/join.concern.ts","../../src/modules/pools/pool-types/concerns/metaStable/liquidity.concern.ts","../../src/modules/pools/pool-types/concerns/metaStable/spotPrice.concern.ts","../../src/modules/pools/pool-types/concerns/metaStable/priceImpact.concern.ts","../../src/modules/pools/pool-types/metaStable.module.ts","../../src/modules/pools/pool-types/concerns/stablePhantom/exit.concern.ts","../../src/modules/pools/pool-types/concerns/stablePhantom/join.concern.ts","../../src/modules/pools/pool-types/stablePhantom.module.ts","../../src/modules/pools/pool-types/concerns/linear/exit.concern.ts","../../src/modules/pools/pool-types/concerns/linear/join.concern.ts","../../src/modules/pools/pool-types/concerns/linear/liquidity.concern.ts","../../src/modules/pools/pool-types/concerns/linear/spotPrice.concern.ts","../../src/modules/pools/pool-types/concerns/linear/priceImpact.concern.ts","../../src/modules/pools/pool-types/linear.module.ts","../../src/modules/pools/pool-type-concerns.ts","../../src/modules/liquidity/liquidity.module.ts","../../src/modules/swaps/queryBatchSwap.ts","../node_modules/tslib/tslib.es6.js","../node_modules/graphql-tag/lib/index.js","../../src/modules/subgraph/generated/balancer-subgraph-types.ts","../../src/modules/subgraph/generated/balancer-gauges.ts","../../src/modules/subgraph/subgraph.ts","../../src/modules/contracts/implementations/multicall.ts","../../src/lib/utils/multiCaller.ts","../../src/modules/sor/pool-data/onChainData.ts","../../src/modules/sor/pool-data/subgraphPoolDataService.ts","../../src/modules/sor/token-price/coingeckoTokenPriceService.ts","../../src/modules/sor/token-price/subgraphTokenPriceService.ts","../../src/modules/sdk.helpers.ts","../../src/modules/sor/sor.module.ts","../../src/modules/swaps/flashSwap/index.ts","../../src/modules/swaps/swap_builder/swap_utils.ts","../../src/modules/swaps/swap_builder/swap_info_decorator.ts","../../src/modules/swaps/swap_builder/single_swap_builder.ts","../../src/modules/swaps/swap_builder/batch_swap_builder.ts","../../src/modules/swaps/swaps.module.ts","../../src/modules/relayer/relayer.module.ts","../../src/modules/subgraph/subgraph.module.ts","../../src/modules/pricing/pricing.module.ts","../../src/lib/utils/time.ts","../../src/modules/contracts/implementations/veBAL.ts","../../src/modules/contracts/implementations/veBAL-proxy.ts","../../src/modules/contracts/implementations/relayer.ts","../../src/modules/contracts/contracts.module.ts","../../src/modules/contracts/implementations/ERC20.ts","../../src/modules/contracts/implementations/liquidity-gauge.ts","../../src/modules/zaps/bbausd2-migrations/addresses.ts","../../src/modules/zaps/bbausd2-migrations/stabal3.ts","../../src/modules/zaps/bbausd2-migrations/bbausd1.ts","../../src/modules/zaps/bbausd2-migrations/stables.ts","../../src/modules/zaps/bbausd2-migrations/maiusd.ts","../../src/modules/zaps/migrations.ts","../../src/modules/zaps/zaps.module.ts","../../src/modules/pools/impermanentLoss/impermanentLossService.ts","../../src/modules/data/bal/emissions.ts","../../src/modules/pools/apr/protocol-revenue.ts","../../src/modules/pools/fees/fees.ts","../../src/modules/pools/apr/apr.ts","../../src/modules/graph/graph.ts","../../src/lib/utils/tenderlyHelper.ts","../../src/modules/joins/joins.module.ts","../../src/modules/exits/exits.module.ts","../../src/modules/pools/volume/volume.ts","../../src/modules/pools/factory/composable-stable/composable-stable.factory.ts","../../src/modules/pools/factory/weighted/weighted.factory.ts","../../src/modules/pools/pool-factory__factory.ts","../../src/modules/pools/queries/params_builder.ts","../../src/modules/pools/queries/get_encoder.ts","../../src/modules/pools/emissions/index.ts","../../src/modules/pools/proportional-amounts/index.ts","../../src/modules/pools/index.ts","../../src/modules/data/gauge-controller/multicall.ts","../../src/modules/subgraph/repository/abstract-subgraph-repository.ts","../../src/modules/subgraph/repository/balancer-subgraph-repository.ts","../../src/modules/subgraph/repository/gauges-subgraph-repository.ts","../../src/modules/data/gauge-shares/repository.ts","../../src/modules/data/liquidity-gauges/multicall.ts","../../src/modules/data/liquidity-gauges/subgraph.ts","../../src/modules/data/liquidity-gauges/provider.ts","../../src/modules/api/balancer-api.client.ts","../../src/modules/data/pool/balancer-api.ts","../../src/modules/data/pool/fallback.ts","../../src/modules/data/pool/static.ts","../../src/modules/data/pool/subgraph.ts","../../src/modules/data/pool/subgraphOnChain.ts","../../src/modules/data/pool-gauges/repository.ts","../../src/modules/data/pool-joinExit/types.ts","../../src/modules/data/pool-joinExit/repository.ts","../../src/modules/data/pool-shares/repository.ts","../../src/modules/data/token/static.ts","../../src/modules/data/token-prices/static.ts","../../src/modules/data/token-prices/coingecko.ts","../../src/modules/data/token-prices/coingecko-historical.ts","../../src/modules/data/token-prices/subgraph.ts","../../src/modules/data/token-prices/provider.ts","../../src/modules/data/token-prices/historical-price-provider.ts","../../src/modules/data/token-prices/aave-rates.ts","../../src/modules/data/fee-distributor/repository.ts","../../src/modules/data/fee-collector/repository.ts","../../src/modules/data/protocol-fees/provider.ts","../../src/modules/data/token-yields/tokens/lido.ts","../../src/modules/data/token-yields/tokens/rocketpool.ts","../../src/modules/data/token-yields/tokens/lido-polygon.ts","../../src/modules/data/token-yields/tokens/overnight.ts","../../src/modules/data/token-yields/tokens/sfrxeth.ts","../../src/modules/data/token-yields/tokens/maticx.ts","../../src/modules/data/token-yields/tokens/tranchess.ts","../../src/modules/data/token-yields/tokens/usdr.ts","../../src/modules/data/token-yields/tokens/stafi.ts","../../src/modules/data/token-yields/tokens/tessera.ts","../../src/modules/data/token-yields/tokens/euler.ts","../../src/modules/data/token-yields/repository.ts","../../src/modules/data/block-number/index.ts","../../src/modules/swaps/joinAndExit.ts","../../src/modules/data/index.ts","../../src/modules/sdk.module.ts"],"sourcesContent":["import { defaultAbiCoder } from '@ethersproject/abi';\nimport { BigNumberish } from '@ethersproject/bignumber';\n\nexport enum StablePoolJoinKind {\n INIT = 0,\n EXACT_TOKENS_IN_FOR_BPT_OUT,\n TOKEN_IN_FOR_EXACT_BPT_OUT,\n}\n\nexport enum StablePhantomPoolJoinKind {\n INIT = 0,\n COLLECT_PROTOCOL_FEES,\n}\n\nexport enum StablePoolExitKind {\n EXACT_BPT_IN_FOR_ONE_TOKEN_OUT = 0,\n EXACT_BPT_IN_FOR_TOKENS_OUT,\n BPT_IN_FOR_EXACT_TOKENS_OUT,\n}\n\nexport class StablePoolEncoder {\n /**\n * Cannot be constructed.\n */\n private constructor() {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n }\n\n /**\n * Encodes the userData parameter for providing the initial liquidity to a StablePool\n * @param initialBalances - the amounts of tokens to send to the pool to form the initial balances\n */\n static joinInit = (amountsIn: BigNumberish[]): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256[]'],\n [StablePoolJoinKind.INIT, amountsIn]\n );\n\n /**\n * Encodes the userData parameter for collecting protocol fees for StablePhantomPool\n */\n static joinCollectProtocolFees = (): string =>\n defaultAbiCoder.encode(\n ['uint256'],\n [StablePhantomPoolJoinKind.COLLECT_PROTOCOL_FEES]\n );\n\n /**\n * Encodes the userData parameter for joining a StablePool with exact token inputs\n * @param amountsIn - the amounts each of token to deposit in the pool as liquidity\n * @param minimumBPT - the minimum acceptable BPT to receive in return for deposited tokens\n */\n static joinExactTokensInForBPTOut = (\n amountsIn: BigNumberish[],\n minimumBPT: BigNumberish\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256[]', 'uint256'],\n [StablePoolJoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, amountsIn, minimumBPT]\n );\n\n /**\n * Encodes the userData parameter for joining a StablePool with to receive an exact amount of BPT\n * @param bptAmountOut - the amount of BPT to be minted\n * @param enterTokenIndex - the index of the token to be provided as liquidity\n */\n static joinTokenInForExactBPTOut = (\n bptAmountOut: BigNumberish,\n enterTokenIndex: number\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256', 'uint256'],\n [\n StablePoolJoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT,\n bptAmountOut,\n enterTokenIndex,\n ]\n );\n\n /**\n * Encodes the userData parameter for exiting a StablePool by removing a single token in return for an exact amount of BPT\n * @param bptAmountIn - the amount of BPT to be burned\n * @param enterTokenIndex - the index of the token to removed from the pool\n */\n static exitExactBPTInForOneTokenOut = (\n bptAmountIn: BigNumberish,\n exitTokenIndex: number\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256', 'uint256'],\n [\n StablePoolExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,\n bptAmountIn,\n exitTokenIndex,\n ]\n );\n\n /**\n * Encodes the userData parameter for exiting a StablePool by removing tokens in return for an exact amount of BPT\n * @param bptAmountIn - the amount of BPT to be burned\n */\n static exitExactBPTInForTokensOut = (bptAmountIn: BigNumberish): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256'],\n [StablePoolExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT, bptAmountIn]\n );\n\n /**\n * Encodes the userData parameter for exiting a StablePool by removing exact amounts of tokens\n * @param amountsOut - the amounts of each token to be withdrawn from the pool\n * @param maxBPTAmountIn - the minimum acceptable BPT to burn in return for withdrawn tokens\n */\n static exitBPTInForExactTokensOut = (\n amountsOut: BigNumberish[],\n maxBPTAmountIn: BigNumberish\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256[]', 'uint256'],\n [\n StablePoolExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT,\n amountsOut,\n maxBPTAmountIn,\n ]\n );\n}\n","import { defaultAbiCoder } from '@ethersproject/abi';\nimport { BigNumberish } from '@ethersproject/bignumber';\n\nexport enum WeightedPoolJoinKind {\n INIT = 0,\n EXACT_TOKENS_IN_FOR_BPT_OUT,\n TOKEN_IN_FOR_EXACT_BPT_OUT,\n ALL_TOKENS_IN_FOR_EXACT_BPT_OUT,\n}\n\nexport enum WeightedPoolExitKind {\n EXACT_BPT_IN_FOR_ONE_TOKEN_OUT = 0,\n EXACT_BPT_IN_FOR_TOKENS_OUT,\n BPT_IN_FOR_EXACT_TOKENS_OUT,\n MANAGEMENT_FEE_TOKENS_OUT,\n}\n\nexport class WeightedPoolEncoder {\n /**\n * Cannot be constructed.\n */\n private constructor() {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n }\n\n /**\n * Encodes the userData parameter for providing the initial liquidity to a WeightedPool\n * @param initialBalances - the amounts of tokens to send to the pool to form the initial balances\n */\n static joinInit = (amountsIn: BigNumberish[]): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256[]'],\n [WeightedPoolJoinKind.INIT, amountsIn]\n );\n\n /**\n * Encodes the userData parameter for joining a WeightedPool with exact token inputs\n * @param amountsIn - the amounts each of token to deposit in the pool as liquidity\n * @param minimumBPT - the minimum acceptable BPT to receive in return for deposited tokens\n */\n static joinExactTokensInForBPTOut = (\n amountsIn: BigNumberish[],\n minimumBPT: BigNumberish\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256[]', 'uint256'],\n [WeightedPoolJoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, amountsIn, minimumBPT]\n );\n\n /**\n * Encodes the userData parameter for joining a WeightedPool with a single token to receive an exact amount of BPT\n * @param bptAmountOut - the amount of BPT to be minted\n * @param enterTokenIndex - the index of the token to be provided as liquidity\n */\n static joinTokenInForExactBPTOut = (\n bptAmountOut: BigNumberish,\n enterTokenIndex: number\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256', 'uint256'],\n [\n WeightedPoolJoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT,\n bptAmountOut,\n enterTokenIndex,\n ]\n );\n\n /**\n * Encodes the userData parameter for joining a WeightedPool proportionally to receive an exact amount of BPT\n * @param bptAmountOut - the amount of BPT to be minted\n */\n static joinAllTokensInForExactBPTOut = (bptAmountOut: BigNumberish): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256'],\n [WeightedPoolJoinKind.ALL_TOKENS_IN_FOR_EXACT_BPT_OUT, bptAmountOut]\n );\n\n /**\n * Encodes the userData parameter for exiting a WeightedPool by removing a single token in return for an exact amount of BPT\n * @param bptAmountIn - the amount of BPT to be burned\n * @param enterTokenIndex - the index of the token to removed from the pool\n */\n static exitExactBPTInForOneTokenOut = (\n bptAmountIn: BigNumberish,\n exitTokenIndex: number\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256', 'uint256'],\n [\n WeightedPoolExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,\n bptAmountIn,\n exitTokenIndex,\n ]\n );\n\n /**\n * Encodes the userData parameter for exiting a WeightedPool by removing tokens in return for an exact amount of BPT\n * @param bptAmountIn - the amount of BPT to be burned\n */\n static exitExactBPTInForTokensOut = (bptAmountIn: BigNumberish): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256'],\n [WeightedPoolExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT, bptAmountIn]\n );\n\n /**\n * Encodes the userData parameter for exiting a WeightedPool by removing exact amounts of tokens\n * @param amountsOut - the amounts of each token to be withdrawn from the pool\n * @param maxBPTAmountIn - the minimum acceptable BPT to burn in return for withdrawn tokens\n */\n static exitBPTInForExactTokensOut = (\n amountsOut: BigNumberish[],\n maxBPTAmountIn: BigNumberish\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256[]', 'uint256'],\n [\n WeightedPoolExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT,\n amountsOut,\n maxBPTAmountIn,\n ]\n );\n}\n\nexport class ManagedPoolEncoder {\n /**\n * Cannot be constructed.\n */\n private constructor() {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n }\n\n /**\n * Encodes the userData parameter for exiting a ManagedPool for withdrawing management fees.\n * This can only be done by the pool owner.\n */\n static exitForManagementFees = (): string =>\n defaultAbiCoder.encode(\n ['uint256'],\n [WeightedPoolExitKind.MANAGEMENT_FEE_TOKENS_OUT]\n );\n}\n","import { BigNumber, BigNumberish } from '@ethersproject/bignumber';\nimport { Zero, WeiPerEther as ONE } from '@ethersproject/constants';\n\n// Should match MAX_WEIGHTED_TOKENS from v2-helpers/constants\n// Including would introduce a dependency\nconst MaxWeightedTokens = 100;\n\n/**\n * Normalize an array of token weights to ensure they sum to `1e18`\n * @param weights - an array of token weights to be normalized\n * @returns an equivalent set of normalized weights\n */\nexport function toNormalizedWeights(weights: BigNumber[]): BigNumber[] {\n // When the number is exactly equal to the max, normalizing with common inputs\n // leads to a value < 0.01, which reverts. In this case fill in the weights exactly.\n if (weights.length == MaxWeightedTokens) {\n return Array(MaxWeightedTokens).fill(ONE.div(MaxWeightedTokens));\n }\n\n const sum = weights.reduce((total, weight) => total.add(weight), Zero);\n if (sum.eq(ONE)) return weights;\n\n const normalizedWeights = [];\n let normalizedSum = Zero;\n for (let index = 0; index < weights.length; index++) {\n if (index < weights.length - 1) {\n normalizedWeights[index] = weights[index].mul(ONE).div(sum);\n normalizedSum = normalizedSum.add(normalizedWeights[index]);\n } else {\n normalizedWeights[index] = ONE.sub(normalizedSum);\n }\n }\n\n return normalizedWeights;\n}\n\n/**\n * Check whether a set of weights are normalized\n * @param weights - an array of potentially unnormalized weights\n * @returns a boolean of whether the weights are normalized\n */\nexport const isNormalizedWeights = (weights: BigNumberish[]): boolean => {\n const totalWeight = weights.reduce(\n (total: BigNumber, weight) => total.add(weight),\n Zero\n );\n return totalWeight.eq(ONE);\n};\n","import { defaultAbiCoder } from '@ethersproject/abi';\nimport { BigNumberish } from '@ethersproject/bignumber';\nimport { StablePhantomPoolJoinKind } from '../pool-stable/index';\n\nexport enum ComposableStablePoolJoinKind {\n INIT = 0,\n EXACT_TOKENS_IN_FOR_BPT_OUT,\n TOKEN_IN_FOR_EXACT_BPT_OUT,\n}\n\nexport enum ComposableStablePoolExitKind {\n EXACT_BPT_IN_FOR_ONE_TOKEN_OUT = 0,\n BPT_IN_FOR_EXACT_TOKENS_OUT,\n}\n\nexport class ComposableStablePoolEncoder {\n /**\n * Cannot be constructed.\n */\n private constructor() {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n }\n\n /**\n * Encodes the userData parameter for providing the initial liquidity to a ComposableStablePool\n * @param initialBalances - the amounts of tokens to send to the pool to form the initial balances\n */\n static joinInit = (amountsIn: BigNumberish[]): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256[]'],\n [ComposableStablePoolJoinKind.INIT, amountsIn]\n );\n\n /**\n * Encodes the userData parameter for collecting protocol fees for StablePhantomPool\n */\n static joinCollectProtocolFees = (): string =>\n defaultAbiCoder.encode(\n ['uint256'],\n [StablePhantomPoolJoinKind.COLLECT_PROTOCOL_FEES]\n );\n\n /**\n * Encodes the userData parameter for joining a ComposableStablePool with exact token inputs\n * @param amountsIn - the amounts each of token to deposit in the pool as liquidity\n * @param minimumBPT - the minimum acceptable BPT to receive in return for deposited tokens\n */\n static joinExactTokensInForBPTOut = (\n amountsIn: BigNumberish[],\n minimumBPT: BigNumberish\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256[]', 'uint256'],\n [\n ComposableStablePoolJoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT,\n amountsIn,\n minimumBPT,\n ]\n );\n\n /**\n * Encodes the userData parameter for joining a ComposableStablePool with to receive an exact amount of BPT\n * @param bptAmountOut - the amount of BPT to be minted\n * @param enterTokenIndex - the index of the token to be provided as liquidity\n */\n static joinTokenInForExactBPTOut = (\n bptAmountOut: BigNumberish,\n enterTokenIndex: number\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256', 'uint256'],\n [\n ComposableStablePoolJoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT,\n bptAmountOut,\n enterTokenIndex,\n ]\n );\n\n /**\n * Encodes the userData parameter for exiting a ComposableStablePool by removing a single token in return for an exact amount of BPT\n * @param bptAmountIn - the amount of BPT to be burned\n * @param enterTokenIndex - the index of the token to removed from the pool\n */\n static exitExactBPTInForOneTokenOut = (\n bptAmountIn: BigNumberish,\n exitTokenIndex: number\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256', 'uint256'],\n [\n ComposableStablePoolExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,\n bptAmountIn,\n exitTokenIndex,\n ]\n );\n\n /**\n * Encodes the userData parameter for exiting a ComposableStablePool by removing exact amounts of tokens\n * @param amountsOut - the amounts of each token to be withdrawn from the pool\n * @param maxBPTAmountIn - the minimum acceptable BPT to burn in return for withdrawn tokens\n */\n static exitBPTInForExactTokensOut = (\n amountsOut: BigNumberish[],\n maxBPTAmountIn: BigNumberish\n ): string =>\n defaultAbiCoder.encode(\n ['uint256', 'uint256[]', 'uint256'],\n [\n ComposableStablePoolExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT,\n amountsOut,\n maxBPTAmountIn,\n ]\n );\n}\n","var isProduction = process.env.NODE_ENV === 'production';\nvar prefix = 'Invariant failed';\nfunction invariant(condition, message) {\n if (condition) {\n return;\n }\n if (isProduction) {\n throw new Error(prefix);\n }\n var provided = typeof message === 'function' ? message() : message;\n var value = provided ? \"\".concat(prefix, \": \").concat(provided) : prefix;\n throw new Error(value);\n}\n\nexport { invariant as default };\n","import { BigNumber } from '@ethersproject/bignumber';\nimport { PoolSpecialization } from '../types';\nimport invariant from 'tiny-invariant';\n\n/**\n * Splits a poolId into its components, i.e. pool address, pool specialization and its nonce\n * @param poolId - a bytes32 string of the pool's ID\n * @returns an object with the decomposed poolId\n */\nexport const splitPoolId = (\n poolId: string\n): {\n address: string;\n specialization: PoolSpecialization;\n nonce: BigNumber;\n} => {\n return {\n address: getPoolAddress(poolId),\n specialization: getPoolSpecialization(poolId),\n nonce: getPoolNonce(poolId),\n };\n};\n\n/**\n * Extracts a pool's address from its poolId\n * @param poolId - a bytes32 string of the pool's ID\n * @returns the pool's address\n */\nexport const getPoolAddress = (poolId: string): string => {\n invariant(poolId.length === 66, 'Invalid poolId length');\n return poolId.slice(0, 42);\n};\n\n/**\n * Extracts a pool's specialization from its poolId\n * @param poolId - a bytes32 string of the pool's ID\n * @returns the pool's specialization\n */\nexport const getPoolSpecialization = (poolId: string): PoolSpecialization => {\n invariant(poolId.length === 66, 'Invalid poolId length');\n\n // Only have 3 pool specializations so we can just pull the relevant character\n const specializationCode = parseInt(poolId[45]);\n invariant(specializationCode < 3, 'Invalid pool specialization');\n\n return specializationCode;\n};\n\n/**\n * Extracts a pool's nonce from its poolId\n * @param poolId - a bytes32 string of the pool's ID\n * @returns the pool's nonce\n */\nexport const getPoolNonce = (poolId: string): BigNumber => {\n invariant(poolId.length === 66, 'Invalid poolId length');\n return BigNumber.from(`0x${poolId.slice(46)}`);\n};\n","export enum Network {\n MAINNET = 1,\n ROPSTEN = 3,\n RINKEBY = 4,\n GOERLI = 5,\n GÖRLI = 5,\n OPTIMISM = 10,\n KOVAN = 42,\n GNOSIS = 100,\n POLYGON = 137,\n ARBITRUM = 42161,\n DEFIVERSE = 16116,\n DEFIVERSE_TESTNET = 17117,\n OASYS = 248,\n OASYS_TESTNET = 9372,\n}\n","import { Network } from '@/lib/constants/network';\n\n// Do not display APR values greater than this amount; they are likely to be nonsensical\n// These can arise from pools with extremely low balances (e.g., completed LBPs)\nexport const APR_THRESHOLD = 10_000;\n\n/**\n * For proportional exits from ComposableStable pools the ExactBPTInForTokensOut\n * exit type was removed. Therefore we have to use BPTInForExactTokensOut which\n * makes proportional exits using a user's total BPT balance impossible. In\n * order to 'fix' this we need to subtract a little bit from the bptIn value\n * when calculating the ExactTokensOut. The variable below is that \"little bit\".\n */\nexport const SHALLOW_COMPOSABLE_STABLE_BUFFER = 1e6; // EVM scale, so this is 1 Mwei\n\ntype FactoryType =\n | 'oracleWeightedPool'\n | 'weightedPool'\n | 'stablePool'\n | 'managedPool'\n | 'liquidityBootstrappingPool'\n | 'boostedPool'\n | 'composableStablePool';\n\ntype PoolMetadata = {\n name: string;\n hasIcon: boolean;\n};\n\nexport type NamedPools = {\n staBAL: string;\n bbAaveUSD: {\n v1: string;\n v2: string;\n };\n xMatic: {\n v1: string;\n v2: string;\n };\n stMatic: {\n v1: string;\n v2: string;\n };\n mai4: {\n mai4: string;\n maiBbaUsd: string;\n };\n veBAL: string;\n};\n\ntype Pools = {\n IdsMap: Partial<NamedPools>;\n Pagination: {\n PerPage: number;\n PerPool: number;\n PerPoolInitial: number;\n };\n DelegateOwner: string;\n ZeroAddress: string;\n DynamicFees: {\n Gauntlet: string[];\n };\n BlockList: string[];\n ExcludedPoolTypes: string[];\n Stable: {\n AllowList: string[];\n };\n Investment: {\n AllowList: string[];\n };\n Factories: Record<string, FactoryType>;\n Stakable: {\n AllowList: string[];\n };\n Metadata: Record<string, PoolMetadata>;\n};\n\nconst POOLS_KOVAN: Pools = {\n IdsMap: {\n staBAL:\n '0xd387dfd3a786e7caa06e6cf0c675352c7ffff30400000000000000000000063e',\n bbAaveUSD: {\n v1: '0x8fd162f338b770f7e879030830cde9173367f3010000000000000000000004d8',\n v2: '',\n },\n veBAL: '0xdc2ecfdf2688f92c85064be0b929693acc6dbca6000200000000000000000701',\n },\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [\n '0x22d398c68030ef6b1c55321cca6e0cecc5c93b2f000200000000000000000678',\n '0xca1eb8624be8e11418f629559321587197557e0c000200000000000000000682',\n '0xa21da5768186c1bc0f56dd72aa94672d77bdf23e00020000000000000000067a',\n '0x7f9db0d15eea32e205b7df0fa5184f4a8a905abb000200000000000000000683',\n '0x72c5a86831f019df6fac146fc14ef60ebe0d5f2600020000000000000000067f',\n '0x542b9f6fd4500b94d453974d8c70783ef794ff6a00020000000000000000067c',\n '0x47f9309a8c5a68a93ac27a4cccc0e222cd3adfa2000200000000000000000684',\n '0x3f3050a0fe84778aeff96906c9218b318f924d22000200000000000000000680',\n '0x31e61587b5dc148ae42ae323655fb8d7af7bb86600020000000000000000067d',\n '0x28efa7f86341aa0ad534bdfb033edb4f4ac6adf700020000000000000000067e',\n '0x10ee90b9ff4b9a44a773107280c0ce083619286800020000000000000000067b',\n ],\n ExcludedPoolTypes: ['Element', 'AaveLinear', 'Linear', 'ERC4626Linear'],\n Stable: {\n AllowList: [\n '0x6b15a01b5d46a5321b627bd7deef1af57bc629070000000000000000000000d4', // kovan\n '0xe08590bde837eb9b2d42aa1196469d6e08fe96ec000200000000000000000101', // kovan\n '0xb4c23af48e79f73e3a7e36c0e54eb38e1ce1755e0002000000000000000000d3', // kovan\n '0x8fd162f338b770f7e879030830cde9173367f3010000000000000000000004d8', // kovan bb-a-USD,\n '0xd387dfd3a786e7caa06e6cf0c675352c7ffff30400000000000000000000063e', // kovan staBAL3,\n ],\n },\n Investment: {\n AllowList: [\n '0x4fd63966879300cafafbb35d157dc5229278ed23000100000000000000000169', // kovan\n '0x37a6fc079cad790e556baedda879358e076ef1b3000100000000000000000348', // WSB Kovan\n ],\n },\n Factories: {\n '0xa5bf2ddf098bb0ef6d120c98217dd6b141c74ee0': 'oracleWeightedPool',\n '0x8e9aa87e45e92bad84d5f8dd1bff34fb92637de9': 'weightedPool',\n '0xc66ba2b6595d3613ccab350c886ace23866ede24': 'stablePool',\n '0x1b57f637ce3408f1f834b0b70f9a595b062daea7': 'liquidityBootstrappingPool',\n '0x751dfdace1ad995ff13c927f6f761c6604532c79': 'stablePool', // Kovan\n '0x590e544e7ca956bb878f8c873e82e65550d67d2f': 'stablePool', // Kovan Metastable\n '0xb08e16cfc07c684daa2f93c70323badb2a6cbfd2': 'managedPool', // Kovan Managed\n '0x6c7f4d97269ece163fd08d5c2584a21e4a33934c': 'boostedPool', // kovan stablephantom\n '0x1f47ab83420cd1f818df9acbd6ee68341bb91592': 'stablePool', // stable pool v2\n },\n Stakable: {\n AllowList: [\n '0xf767f0a3fcf1eafec2180b7de79d0c559d7e7e370001000000000000000003e3',\n '0xdc2ecfdf2688f92c85064be0b929693acc6dbca6000200000000000000000701',\n '0x647c1fd457b95b75d0972ff08fe01d7d7bda05df000200000000000000000001',\n '0x8fd162f338b770f7e879030830cde9173367f3010000000000000000000004d8',\n ],\n },\n Metadata: {\n '0x8fd162f338b770f7e879030830cde9173367f3010000000000000000000004d8': {\n name: 'Balancer Boosted Aave USD',\n hasIcon: false,\n },\n '0xd387dfd3a786e7caa06e6cf0c675352c7ffff30400000000000000000000063e': {\n name: 'Balancer Stable USD',\n hasIcon: false,\n },\n },\n};\n\nconst POOLS_GOERLI: Pools = {\n IdsMap: {\n staBAL:\n '0xdcdd4a3d36dec8d57594e89763d069a7e9b223e2000000000000000000000062',\n bbAaveUSD: {\n v1: '0x13acd41c585d7ebb4a9460f7c8f50be60dc080cd00000000000000000000005f',\n v2: '0x3d5981bdd8d3e49eb7bbdc1d2b156a3ee019c18e0000000000000000000001a7',\n },\n veBAL: '0xf8a0623ab66f985effc1c69d05f1af4badb01b00000200000000000000000060',\n },\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [\n '0x22d398c68030ef6b1c55321cca6e0cecc5c93b2f000200000000000000000678',\n ],\n ExcludedPoolTypes: ['Element', 'AaveLinear', 'Linear', 'ERC4626Linear'],\n Stable: {\n AllowList: [\n '0x13acd41c585d7ebb4a9460f7c8f50be60dc080cd00000000000000000000005f',\n '0xb60e46d90f2de35f7062a27d3a98749414036d5d000200000000000000000061',\n '0xdcdd4a3d36dec8d57594e89763d069a7e9b223e2000000000000000000000062',\n '0xc957b1acceb21707b782eb8eee2ed8e20088463d000200000000000000000076',\n '0x3d5981bdd8d3e49eb7bbdc1d2b156a3ee019c18e0000000000000000000001a7',\n '0x14f93df8a4e37bfdb49d2cec4789df7a010603d700000000000000000000011d',\n '0x00a62d31b6c776b6813543bc99ff265f7222dbe100000000000000000000011e',\n '0x0c925fce89a22e36ebd9b3c6e0262234e853d2f600000000000000000000019c',\n ],\n },\n Investment: {\n AllowList: [],\n },\n Factories: {\n '0xa5bf2ddf098bb0ef6d120c98217dd6b141c74ee0': 'oracleWeightedPool',\n '0x8e9aa87e45e92bad84d5f8dd1bff34fb92637de9': 'weightedPool',\n '0x44afeb87c871d8fea9398a026dea2bd3a13f5769': 'stablePool',\n '0xa55f73e2281c60206ba43a3590db07b8955832be': 'stablePool', // Metastable\n '0xb48cc42c45d262534e46d5965a9ac496f1b7a830': 'liquidityBootstrappingPool',\n '0xb0c726778c3ae4b3454d85557a48e8fa502bdd6a': 'liquidityBootstrappingPool', // LBP (zero protocol fee)\n '0x41e9036ae350baedcc7107760a020dca3c0731ec': 'boostedPool',\n '0xb848f50141f3d4255b37ac288c25c109104f2158': 'composableStablePool',\n '0x94f68b54191f62f781fe8298a8a5fa3ed772d227': 'weightedPool', // weighted pool v2\n },\n Stakable: {\n AllowList: [\n '0x16faf9f73748013155b7bc116a3008b57332d1e600020000000000000000005b',\n '0x13acd41c585d7ebb4a9460f7c8f50be60dc080cd00000000000000000000005f',\n '0xdcdd4a3d36dec8d57594e89763d069a7e9b223e2000000000000000000000062',\n '0x67f8fcb9d3c463da05de1392efdbb2a87f8599ea000200000000000000000059',\n ],\n },\n Metadata: {\n '0x13acd41c585d7ebb4a9460f7c8f50be60dc080cd00000000000000000000005f': {\n name: 'Balancer Boosted Aave USD',\n hasIcon: false,\n },\n },\n};\n\nconst POOLS_MAINNET: Pools = {\n IdsMap: {\n staBAL:\n '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000063',\n bbAaveUSD: {\n v1: '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb20000000000000000000000fe',\n v2: '0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d',\n },\n veBAL: '0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014',\n },\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [''],\n ExcludedPoolTypes: [\n 'Element',\n 'AaveLinear',\n 'Linear',\n 'ERC4626Linear',\n 'Gyro2',\n 'Gyro3',\n ],\n Stable: {\n AllowList: [\n '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000063', // staBAL3 (DAI-USD-USDC)\n '0xfeadd389a5c427952d8fdb8057d6c8ba1156cc56000000000000000000000066', // WBTC-renBTC-sBTC\n '0x9f19a375709baf0e8e35c2c5c65aca676c4c719100000000000000000000006e', // PAR-sEUR-EURS\n '0x32296969ef14eb0c6d29669c550d4a0449130230000200000000000000000080', // Lido Metastable\n '0x1e19cf2d73a72ef1332c882f20534b6519be0276000200000000000000000112', // Rocket Pool Metastable\n '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb20000000000000000000000fe', // Mainnet bb-a-USD\n '0x851523a36690bf267bbfec389c823072d82921a90002000000000000000001ed', // wstETH/WETH #2\n '0x3dd0843a028c86e0b760b1a76929d1c5ef93a2dd000200000000000000000249', // b-auraBAL-Stable (auraBal / 8020 BALETH)\n '0x2d011adf89f0576c9b722c28269fcb5d50c2d17900020000000000000000024d', // sdBAL Stable Pool (sdBAL / 8020 BALETH)\n '0x178e029173417b1f9c8bc16dcec6f697bc32374600000000000000000000025d', // Fiat DAO Stable Pool\n '0xf93579002dbe8046c43fefe86ec78b1112247bb80000000000000000000002bc', // USDD 3 pool\n '0xf3aeb3abba741f0eece8a1b1d2f11b85899951cb000200000000000000000351', // MAI stable pool\n '0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d', // bb-a-USD V2\n '0x5b3240b6be3e7487d61cd1afdfc7fe4fa1d81e6400000000000000000000037b', // DOLA/INV stable pool\n ],\n },\n Investment: {\n AllowList: [\n '0xccf5575570fac94cec733a58ff91bb3d073085c70002000000000000000000af', // iROBOT mainnet\n '0xe7b1d394f3b40abeaa0b64a545dbcf89da1ecb3f00010000000000000000009a', // Techemy mainnet\n '0x3b40d7d5ae25df2561944dd68b252016c4c7b2800001000000000000000000c2', // WSB-DEFI mainnet\n ],\n },\n Factories: {\n '0xa5bf2ddf098bb0ef6d120c98217dd6b141c74ee0': 'oracleWeightedPool',\n '0x8e9aa87e45e92bad84d5f8dd1bff34fb92637de9': 'weightedPool',\n '0xc66ba2b6595d3613ccab350c886ace23866ede24': 'stablePool',\n '0x67d27634e44793fe63c467035e31ea8635117cd4': 'stablePool', // Metastable\n '0x751a0bc0e3f75b38e01cf25bfce7ff36de1c87de': 'liquidityBootstrappingPool', // Mainnet LBP\n '0x0f3e0c4218b7b0108a3643cfe9d3ec0d4f57c54e': 'liquidityBootstrappingPool', // Mainnet LBP (zero protocol fee)\n '0x48767f9f868a4a7b86a90736632f6e44c2df7fa9': 'managedPool', // Mainnet Managed\n '0xb08e16cfc07c684daa2f93c70323badb2a6cbfd2': 'boostedPool', // mainnet stablephantom\n '0x8df6efec5547e31b0eb7d1291b511ff8a2bf987c': 'stablePool', // stable pool v2\n '0xf9ac7b9df2b3454e841110cce5550bd5ac6f875f': 'composableStablePool', // ComposableStable\n '0xcc508a455f5b0073973107db6a878ddbdab957bc': 'weightedPool', // weighted pool v2\n },\n Stakable: {\n AllowList: [\n '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000063',\n '0x072f14b85add63488ddad88f855fda4a99d6ac9b000200000000000000000027',\n '0x0b09dea16768f0799065c475be02919503cb2a3500020000000000000000001a',\n '0x186084ff790c65088ba694df11758fae4943ee9e000200000000000000000013',\n '0x1e19cf2d73a72ef1332c882f20534b6519be0276000200000000000000000112',\n '0x27c9f71cc31464b906e0006d4fcbc8900f48f15f00020000000000000000010f',\n '0x32296969ef14eb0c6d29669c550d4a0449130230000200000000000000000080',\n '0x350196326aeaa9b98f1903fb5e8fc2686f85318c000200000000000000000084',\n '0x3e5fa9518ea95c3e533eb377c001702a9aacaa32000200000000000000000052',\n '0x51735bdfbfe3fc13dea8dc6502e2e958989429610002000000000000000000a0',\n '0x5d66fff62c17d841935b60df5f07f6cf79bd0f4700020000000000000000014c',\n '0x5f7fa48d765053f8dd85e052843e12d23e3d7bc50002000000000000000000c0',\n '0x702605f43471183158938c1a3e5f5a359d7b31ba00020000000000000000009f',\n '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb20000000000000000000000fe',\n '0x7edde0cb05ed19e03a9a47cd5e53fc57fde1c80c0002000000000000000000c8',\n '0x8f4205e1604133d1875a3e771ae7e4f2b086563900020000000000000000010e',\n '0x90291319f1d4ea3ad4db0dd8fe9e12baf749e84500020000000000000000013c',\n '0x96646936b91d6b9d7d0c47c496afbf3d6ec7b6f8000200000000000000000019',\n '0x96ba9025311e2f47b840a1f68ed57a3df1ea8747000200000000000000000160',\n '0xa02e4b3d18d4e6b8d18ac421fbc3dfff8933c40a00020000000000000000004b',\n '0xa6f548df93de924d73be7d25dc02554c6bd66db500020000000000000000000e',\n '0xbaeec99c90e3420ec6c1e7a769d2a856d2898e4d00020000000000000000008a',\n '0xbf96189eee9357a95c7719f4f5047f76bde804e5000200000000000000000087',\n '0xe2469f47ab58cf9cf59f9822e3c5de4950a41c49000200000000000000000089',\n '0xe99481dc77691d8e2456e5f3f61c1810adfc1503000200000000000000000018',\n '0xec60a5fef79a92c741cb74fdd6bfc340c0279b01000200000000000000000015',\n '0xedf085f65b4f6c155e13155502ef925c9a756003000200000000000000000123',\n '0xefaa1604e82e1b3af8430b90192c1b9e8197e377000200000000000000000021',\n '0xf4c0dd9b82da36c07605df83c8a416f11724d88b000200000000000000000026',\n '0xf5aaf7ee8c39b651cebf5f1f50c10631e78e0ef9000200000000000000000069',\n '0xfeadd389a5c427952d8fdb8057d6c8ba1156cc56000000000000000000000066',\n '0x92762b42a06dcdddc5b7362cfb01e631c4d44b40000200000000000000000182',\n '0xde8c195aa41c11a0c4787372defbbddaa31306d2000200000000000000000181',\n '0x17ddd9646a69c9445cd8a9f921d4cd93bf50d108000200000000000000000159',\n '0xc45d42f801105e861e86658648e3678ad7aa70f900010000000000000000011e',\n '0x2d344a84bac123660b021eebe4eb6f12ba25fe8600020000000000000000018a',\n '0xb460daa847c45f1c4a41cb05bfb3b51c92e41b36000200000000000000000194',\n '0x5122e01d819e58bb2e22528c0d68d310f0aa6fd7000200000000000000000163',\n '0x851523a36690bf267bbfec389c823072d82921a90002000000000000000001ed',\n '0xe8cc7e765647625b95f59c15848379d10b9ab4af0002000000000000000001de',\n '0x85370d9e3bb111391cc89f6de344e801760461830002000000000000000001ef',\n '0xa7ff759dbef9f3efdd1d59beee44b966acafe214000200000000000000000180',\n '0x3f7c10701b14197e2695dec6428a2ca4cf7fc3b800020000000000000000023c',\n '0x2d011adf89f0576c9b722c28269fcb5d50c2d17900020000000000000000024d',\n '0x178e029173417b1f9c8bc16dcec6f697bc32374600000000000000000000025d',\n '0xcfca23ca9ca720b6e98e3eb9b6aa0ffc4a5c08b9000200000000000000000274',\n '0x3dd0843a028c86e0b760b1a76929d1c5ef93a2dd000200000000000000000249',\n '0x0578292cb20a443ba1cde459c985ce14ca2bdee5000100000000000000000269',\n '0x8eb6c82c3081bbbd45dcac5afa631aac53478b7c000100000000000000000270',\n '0x1b65fe4881800b91d4277ba738b567cbb200a60d0002000000000000000002cc',\n '0x99a14324cfd525a34bbc93ac7e348929909d57fd00020000000000000000030e',\n '0x9b532ab955417afd0d012eb9f7389457cd0ea712000000000000000000000338',\n '0x48607651416a943bf5ac71c41be1420538e78f87000200000000000000000327',\n '0x6a5ead5433a50472642cd268e584dafa5a394490000200000000000000000366',\n '0x0fd5663d4893ae0d579d580584806aadd2dd0b8b000200000000000000000367',\n '0x441b8a1980f2f2e43a9397099d15cc2fe6d3625000020000000000000000035f',\n '0xf3aeb3abba741f0eece8a1b1d2f11b85899951cb000200000000000000000351',\n '0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d',\n ],\n },\n Metadata: {\n '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb20000000000000000000000fe': {\n name: 'Balancer Boosted Aave USD',\n hasIcon: true,\n },\n '0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d': {\n name: 'Balancer Boosted Aave USD',\n hasIcon: true,\n },\n '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000063': {\n name: 'Balancer Stable USD',\n hasIcon: true,\n },\n '0x3dd0843a028c86e0b760b1a76929d1c5ef93a2dd000200000000000000000249': {\n name: 'AuraBAL Stable Pool',\n hasIcon: false,\n },\n },\n};\n\nconst POOLS_POLYGON: Pools = {\n IdsMap: {\n xMatic: {\n v1: '0xc17636e36398602dd37bb5d1b3a9008c7629005f0002000000000000000004c4',\n v2: '0xb20fc01d21a50d2c734c4a1262b4404d41fa7bf000000000000000000000075c',\n },\n stMatic: {\n v1: '0xaf5e0b5425de1f5a630a8cb5aa9d97b8141c908d000200000000000000000366',\n v2: '0x8159462d255c1d24915cb51ec361f700174cd99400000000000000000000075d',\n },\n mai4: {\n mai4: '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000012',\n maiBbaUsd:\n '0xb54b2125b711cd183edd3dd09433439d5396165200000000000000000000075e',\n },\n },\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [''],\n ExcludedPoolTypes: [\n 'Element',\n 'AaveLinear',\n 'Linear',\n 'ERC4626Linear',\n 'Gyro2',\n 'Gyro3',\n ],\n Stable: {\n AllowList: [\n '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000012', // polygon MAI/DAI/USDC/USDT\n '0xfeadd389a5c427952d8fdb8057d6c8ba1156cc5600020000000000000000001e', // polygon WBTC/renBTC\n '0xf38cf113d2d4f60c36cbd95af2f48a9a0167045a00000000000000000000005b', // polygon,\n '0x0d34e5dd4d8f043557145598e4e2dc286b35fd4f000000000000000000000068', // tusd polygon\n '0x5028497af0c9a54ea8c6d42a054c0341b9fc616800020000000000000000007b', // dusd polygon\n '0xaf5e0b5425de1f5a630a8cb5aa9d97b8141c908d000200000000000000000366', // polygon staked matic\n '0xb4670d1389c758e4380c4211bcbc85342688b9c50002000000000000000003d8', // vQi,\n '0xc31a37105b94ab4efca1954a14f059af11fcd9bb000000000000000000000455', // 4pool\n '0xc17636e36398602dd37bb5d1b3a9008c7629005f0002000000000000000004c4', // maticx metastable\n '0xb4b22bd6cdad0ab828be6f8a4086dfa54e9b373600020000000000000000058f', // Polygon tetuBAL-80BAL-20WETH\n '0xb797adfb7b268faeaa90cadbfed464c76ee599cd0002000000000000000005ba', // tetuBAL-80BAL-20WETH V2 (with short name)\n '0x0b8319061732b34cab22445fa83b81f950e4b7ed000000000000000000000709',\n '0xaf5e0b5425de1f5a630a8cb5aa9d97b8141c908d000200000000000000000366',\n '0x8159462d255c1d24915cb51ec361f700174cd99400000000000000000000075d',\n '0xb20fc01d21a50d2c734c4a1262b4404d41fa7bf000000000000000000000075c',\n '0xb54b2125b711cd183edd3dd09433439d5396165200000000000000000000075e', // mai / bb-am-USD\n '0x48e6b98ef6329f8f0a30ebb8c7c960330d64808500000000000000000000075b', // bb-am-USD\n '0xa48d164f6eb0edc68bd03b56fa59e12f24499ad10000000000000000000007c4', // ageur stable\n ],\n },\n Investment: {\n AllowList: [''],\n },\n Factories: {\n '0xa5bf2ddf098bb0ef6d120c98217dd6b141c74ee0': 'oracleWeightedPool',\n '0x8e9aa87e45e92bad84d5f8dd1bff34fb92637de9': 'weightedPool',\n '0xc66ba2b6595d3613ccab350c886ace23866ede24': 'stablePool',\n '0xdae7e32adc5d490a43ccba1f0c736033f2b4efca': 'stablePool', // Metastable\n '0x751a0bc0e3f75b38e01cf25bfce7ff36de1c87de': 'liquidityBootstrappingPool', // LBP\n '0x41b953164995c11c81da73d212ed8af25741b7ac': 'liquidityBootstrappingPool', // LBP (zero protocol fee)\n '0x0f7bb7ce7b6ed9366f9b6b910adefe72dc538193': 'managedPool', // Polygon Managed\n '0xc128a9954e6c874ea3d62ce62b468ba073093f25': 'boostedPool', // polygon stablephantom\n '0xca96c4f198d343e251b1a01f3eba061ef3da73c1': 'stablePool', // stable pool v2,\n '0x136fd06fa01ecf624c7f2b3cb15742c1339dc2c4': 'composableStablePool', // ComposableStable\n '0x0e39c3d9b2ec765efd9c5c70bb290b1fcd8536e3': 'weightedPool', // weighted pool v2\n },\n Stakable: {\n AllowList: [\n '0x0297e37f1873d2dab4487aa67cd56b58e2f27875000100000000000000000002',\n '0x03cd191f589d12b0582a99808cf19851e468e6b500010000000000000000000a',\n '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000012',\n '0x0d34e5dd4d8f043557145598e4e2dc286b35fd4f000000000000000000000068',\n '0x10f21c9bd8128a29aa785ab2de0d044dcdd79436000200000000000000000059',\n '0x186084ff790c65088ba694df11758fae4943ee9e000200000000000000000032',\n '0x36128d5436d2d70cab39c9af9cce146c38554ff0000100000000000000000008',\n '0x5a6ae1fd70d04ba4a279fc219dfabc53825cb01d00020000000000000000020e',\n '0x614b5038611729ed49e0ded154d8a5d3af9d1d9e00010000000000000000001d',\n '0x7c9cf12d783821d5c63d8e9427af5c44bad92445000100000000000000000051',\n '0x805ca3ccc61cc231851dee2da6aabff0a7714aa7000200000000000000000361',\n '0xaf5e0b5425de1f5a630a8cb5aa9d97b8141c908d000200000000000000000366',\n '0xb204bf10bc3a5435017d3db247f56da601dfe08a0002000000000000000000fe',\n '0xc31a37105b94ab4efca1954a14f059af11fcd9bb000000000000000000000455',\n '0xce66904b68f1f070332cbc631de7ee98b650b499000100000000000000000009',\n '0xcf354603a9aebd2ff9f33e1b04246d8ea204ae9500020000000000000000005a',\n '0xdb1db6e248d7bb4175f6e5a382d0a03fe3dcc813000100000000000000000035',\n '0xea4e073c8ac859f2994c07e627178719c8002dc00002000000000000000003dc',\n '0xfeadd389a5c427952d8fdb8057d6c8ba1156cc5600020000000000000000001e',\n '0xc17636e36398602dd37bb5d1b3a9008c7629005f0002000000000000000004c4',\n '0x2dbc9ab0160087ae59474fb7bed95b9e808fa6bc0001000000000000000003db',\n '0xb797adfb7b268faeaa90cadbfed464c76ee599cd0002000000000000000005ba',\n '0x8f9dd2064eb38e8e40f2ab67bde27c0e16ea9b080002000000000000000004ca',\n '0x48e6b98ef6329f8f0a30ebb8c7c960330d64808500000000000000000000075b',\n '0xb54b2125b711cd183edd3dd09433439d5396165200000000000000000000075e',\n '0x8159462d255c1d24915cb51ec361f700174cd99400000000000000000000075d',\n '0xb20fc01d21a50d2c734c4a1262b4404d41fa7bf000000000000000000000075c',\n ],\n },\n Metadata: {},\n};\n\nconst POOLS_ARBITRUM: Pools = {\n IdsMap: {},\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [''],\n ExcludedPoolTypes: ['Element', 'AaveLinear', 'Linear', 'ERC4626Linear'],\n Stable: {\n AllowList: [\n '0x9be7de742865d021c0e8fb9d64311b2c040c1ec1000200000000000000000012', // arbitrum\n '0x1533a3278f3f9141d5f820a184ea4b017fce2382000000000000000000000016', // arbitrum\n '0x386b5d43ba8b97c43d4afb4cdae7877a1b295e8a000000000000000000000020', // tusd arbitrum\n '0x0510ccf9eb3ab03c1508d3b9769e8ee2cfd6fdcf00000000000000000000005d', // mai\n '0x5a5884fc31948d59df2aeccca143de900d49e1a300000000000000000000006f', // VST\n '0xd89746affa5483627a87e55713ec1905114394950002000000000000000000bf', // fluid stable\n '0x7bceaa9c5e7f4836fec3bce2d5346637c9b13970000000000000000000000102', // vesta new stable\n '0xfb5e6d0c1dfed2ba000fbc040ab8df3615ac329c000000000000000000000159', // stETH\n ],\n },\n Investment: {\n AllowList: [''],\n },\n Factories: {\n '0x7dfdef5f355096603419239ce743bfaf1120312b': 'weightedPool', // Arbitrum Weighted\n '0xcf0a32bbef8f064969f21f7e02328fb577382018': 'weightedPool', // Arbitrum WeightedOracle\n '0x2433477a10fc5d31b9513c638f19ee85caed53fd': 'stablePool', // Arbitrum Stable\n '0xebfd5681977e38af65a7487dc70b8221d089ccad': 'stablePool', // Arbitrum MetaStable\n '0x142b9666a0a3a30477b052962dda81547e7029ab': 'liquidityBootstrappingPool', // Arbitrum LBP (old)\n '0x1802953277fd955f9a254b80aa0582f193cf1d77': 'liquidityBootstrappingPool', // Arbitrum LBP (new)\n '0xacd615b3705b9c880e4e7293f1030b34e57b4c1c': 'managedPool', // arbitrum managed\n '0xdae7e32adc5d490a43ccba1f0c736033f2b4efca': 'boostedPool', // arbitrum stablephantom\n '0xef44d6786b2b4d544b7850fe67ce6381626bf2d6': 'stablePool', // stable pool v2\n '0xaeb406b0e430bf5ea2dc0b9fe62e4e53f74b3a33': 'composableStablePool', // ComposableStable\n '0x8df6efec5547e31b0eb7d1291b511ff8a2bf987c': 'weightedPool', // weighted pool v2\n },\n Stakable: {\n AllowList: [\n '0x0510ccf9eb3ab03c1508d3b9769e8ee2cfd6fdcf00000000000000000000005d',\n '0x0adeb25cb5920d4f7447af4a0428072edc2cee2200020000000000000000004a',\n '0x1533a3278f3f9141d5f820a184ea4b017fce2382000000000000000000000016',\n '0x1779900c7707885720d39aa741f4086886307e9e00020000000000000000004b',\n '0x4a3a22a3e7fee0ffbb66f1c28bfac50f75546fc7000200000000000000000008',\n '0x5a5884fc31948d59df2aeccca143de900d49e1a300000000000000000000006f',\n '0x64541216bafffeec8ea535bb71fbc927831d0595000100000000000000000002',\n '0x651e00ffd5ecfa7f3d4f33d62ede0a97cf62ede2000200000000000000000006',\n '0xb28670b3e7ad27bd41fb5938136bf9e9cba90d6500020000000000000000001e',\n '0xb340b6b1a34019853cb05b2de6ee8ffd0b89a008000100000000000000000036',\n '0xb5b77f1ad2b520df01612399258e7787af63025d000200000000000000000010',\n '0xc2f082d33b5b8ef3a7e3de30da54efd3114512ac000200000000000000000017',\n '0xc61ff48f94d801c1ceface0289085197b5ec44f000020000000000000000004d',\n '0xcc65a812ce382ab909a11e434dbf75b34f1cc59d000200000000000000000001',\n '0xe1b40094f1446722c424c598ac412d590e0b3ffb000200000000000000000076',\n '0xb3028ca124b80cfe6e9ca57b70ef2f0ccc41ebd40002000000000000000000ba',\n '0x7bceaa9c5e7f4836fec3bce2d5346637c9b13970000000000000000000000102',\n '0xfb5e6d0c1dfed2ba000fbc040ab8df3615ac329c000000000000000000000159',\n '0x178e029173417b1f9c8bc16dcec6f697bc323746000200000000000000000158',\n ],\n },\n Metadata: {},\n};\n\nconst POOLS_GNOSIS: Pools = {\n IdsMap: {},\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [''],\n ExcludedPoolTypes: [\n 'Element',\n 'AaveLinear',\n 'Linear',\n 'ERC4626Linear',\n 'FX',\n 'Gyro2',\n 'Gyro3',\n 'GyroE',\n 'HighAmpComposableStable',\n ],\n Stable: {\n AllowList: [\n '0x11884da90fb4221b3aa288a7741c51ec4fc43b2f000000000000000000000004',\n '0x707b7d4a1bae449d546dcab869256591bbb3d70b000000000000000000000000',\n ],\n },\n Investment: {\n AllowList: [],\n },\n Factories: {},\n Stakable: {\n AllowList: [],\n },\n Metadata: {},\n};\n\nconst POOLS_GENERIC: Pools = {\n IdsMap: {},\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [''],\n ExcludedPoolTypes: ['Element', 'AaveLinear', 'Linear', 'ERC4626Linear'],\n Stable: {\n AllowList: [\n '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000063',\n '0xfeadd389a5c427952d8fdb8057d6c8ba1156cc56000000000000000000000066',\n '0x9f19a375709baf0e8e35c2c5c65aca676c4c719100000000000000000000006e',\n '0x32296969ef14eb0c6d29669c550d4a0449130230000200000000000000000080', // Lido Metastable\n '0x1e19cf2d73a72ef1332c882f20534b6519be0276000200000000000000000112', // Rocket Pool Metastable\n '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000012', // polygon\n '0xfeadd389a5c427952d8fdb8057d6c8ba1156cc5600020000000000000000001e', // polygon\n '0x6b15a01b5d46a5321b627bd7deef1af57bc629070000000000000000000000d4', // kovan\n '0xe08590bde837eb9b2d42aa1196469d6e08fe96ec000200000000000000000101', // kovan\n '0xb4c23af48e79f73e3a7e36c0e54eb38e1ce1755e0002000000000000000000d3', // kovan\n '0x9be7de742865d021c0e8fb9d64311b2c040c1ec1000200000000000000000012', // arbitrum\n '0x9f19a375709baf0e8e35c2c5c65aca676c4c7191000200000000000000000022', // polygon PAR/PAR,\n '0x1533a3278f3f9141d5f820a184ea4b017fce2382000000000000000000000016', // arbitrum\n '0xf38cf113d2d4f60c36cbd95af2f48a9a0167045a00000000000000000000005b', // polygon,\n '0x0d34e5dd4d8f043557145598e4e2dc286b35fd4f000000000000000000000068', // tusd polygon\n '0x386b5d43ba8b97c43d4afb4cdae7877a1b295e8a000000000000000000000020', // tusd arbitrum\n '0x5028497af0c9a54ea8c6d42a054c0341b9fc616800020000000000000000007b', // dusd polygon\n '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb20000000000000000000000fe', // Mainnet bb-a-USD\n '0x8fd162f338b770f7e879030830cde9173367f3010000000000000000000004d8', // kovan bb-a-USD,\n '0xd387dfd3a786e7caa06e6cf0c675352c7ffff30400000000000000000000063e', // kovan staBAL3,\n '0xaf5e0b5425de1f5a630a8cb5aa9d97b8141c908d000200000000000000000366', // staked matic\n ],\n },\n Investment: {\n AllowList: [\n '0x4fd63966879300cafafbb35d157dc5229278ed23000100000000000000000169', // kovan\n '0x37a6fc079cad790e556baedda879358e076ef1b3000100000000000000000348', // WSB Kovan\n '0xccf5575570fac94cec733a58ff91bb3d073085c70002000000000000000000af', // iROBOT mainnet\n '0xe7b1d394f3b40abeaa0b64a545dbcf89da1ecb3f00010000000000000000009a', // Techemy mainnet\n '0x3b40d7d5ae25df2561944dd68b252016c4c7b2800001000000000000000000c2', // WSB-DEFI mainnet\n ],\n },\n Factories: {\n '0xa5bf2ddf098bb0ef6d120c98217dd6b141c74ee0': 'oracleWeightedPool',\n '0x8e9aa87e45e92bad84d5f8dd1bff34fb92637de9': 'weightedPool',\n '0xc66ba2b6595d3613ccab350c886ace23866ede24': 'stablePool',\n '0x67d27634e44793fe63c467035e31ea8635117cd4': 'stablePool', // Metastable\n '0x751dfdace1ad995ff13c927f6f761c6604532c79': 'stablePool', // Kovan\n '0x590e544e7ca956bb878f8c873e82e65550d67d2f': 'stablePool', // Kovan Metastable\n // '0xb08e16cfc07c684daa2f93c70323badb2a6cbfd2': 'managedPool', // Kovan Managed (clash with mainnet StablePhantom address)\n '0x7dfdef5f355096603419239ce743bfaf1120312b': 'weightedPool', // Arbitrum Weighted\n '0xcf0a32bbef8f064969f21f7e02328fb577382018': 'weightedPool', // Arbitrum WeightedOracle\n '0x2433477a10fc5d31b9513c638f19ee85caed53fd': 'stablePool', // Arbitrum Stable\n '0xebfd5681977e38af65a7487dc70b8221d089ccad': 'stablePool', // Arbitrum MetaStable\n '0x751a0bc0e3f75b38e01cf25bfce7ff36de1c87de': 'liquidityBootstrappingPool', // Mainnet LBP\n '0x0f3e0c4218b7b0108a3643cfe9d3ec0d4f57c54e': 'liquidityBootstrappingPool', // Mainnet LBP (zero protocol fee)\n '0x142b9666a0a3a30477b052962dda81547e7029ab': 'liquidityBootstrappingPool', // Arbitrum LBP (old)\n '0x1802953277fd955f9a254b80aa0582f193cf1d77': 'liquidityBootstrappingPool', // Arbitrum LBP (new)\n '0x48767f9f868a4a7b86a90736632f6e44c2df7fa9': 'managedPool', // Mainnet Managed\n '0x0f7bb7ce7b6ed9366f9b6b910adefe72dc538193': 'managedPool', // Polygon Managed\n '0xacd615b3705b9c880e4e7293f1030b34e57b4c1c': 'managedPool', // arbitrum managed\n '0xb08e16cfc07c684daa2f93c70323badb2a6cbfd2': 'boostedPool', // mainnet stablephantom\n '0xdae7e32adc5d490a43ccba1f0c736033f2b4efca': 'boostedPool', // arbitrum stablephantom\n '0xc128a9954e6c874ea3d62ce62b468ba073093f25': 'boostedPool', // polygon stablephantom\n '0x6c7f4d97269ece163fd08d5c2584a21e4a33934c': 'boostedPool', // kovan stablephantom\n },\n Stakable: {\n AllowList: [],\n },\n Metadata: {\n '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb20000000000000000000000fe': {\n name: 'Balancer Boosted Aave USD',\n hasIcon: true,\n },\n '0x8fd162f338b770f7e879030830cde9173367f3010000000000000000000004d8': {\n name: 'Balancer Boosted Aave USD',\n hasIcon: true,\n },\n '0xd387dfd3a786e7caa06e6cf0c675352c7ffff30400000000000000000000063e': {\n name: 'Balancer Stable USD',\n hasIcon: true,\n },\n },\n};\n\nconst POOLS_DEFIVERSE: Pools = {\n IdsMap: {\n veBAL: '',\n },\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [''],\n ExcludedPoolTypes: [\n 'Element',\n 'AaveLinear',\n 'EulerLinear',\n 'Linear',\n 'ERC4626Linear',\n 'FX',\n 'Gyro2',\n 'Gyro3',\n 'GyroE',\n 'HighAmpComposableStable',\n ],\n Stable: {\n AllowList: [\n // '0xfedb19ec000d38d92af4b21436870f115db22725000000000000000000000010', // bb-ag-usd\n ],\n },\n Investment: {\n AllowList: [],\n },\n Factories: {\n '0xd01ad3085fb3e1fbb2541b5b3326b1f47b189747': 'composableStablePool', // ComposableStable V2\n '0xd1920dd25e4998b0d7cc8de7f12beaf9796c7475': 'weightedPool', // WeightedPool V3\n '0xe952b0409e6768e270a671ebbc5b8605a7c5a0b8': 'weightedPool', // WeightedPool V3\n '0xc04ce4fe0f4013814ea1a4b0577d3678d5a7c91c': 'weightedPool', // WeightedPool V3\n '0x9f9e8668ee128c365365f7d1963b4891034fb513': 'weightedPool', // WeightedPool V3\n },\n Stakable: {\n AllowList: [\n //\n ],\n },\n Metadata: {},\n};\n\nconst POOLS_DEFIVERSE_TESTNET: Pools = {\n IdsMap: {\n veBAL: '',\n },\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [''],\n ExcludedPoolTypes: [\n 'Element',\n 'AaveLinear',\n 'EulerLinear',\n 'Linear',\n 'ERC4626Linear',\n 'FX',\n 'Gyro2',\n 'Gyro3',\n 'GyroE',\n 'HighAmpComposableStable',\n ],\n Stable: {\n AllowList: [\n // '0xfedb19ec000d38d92af4b21436870f115db22725000000000000000000000010', // bb-ag-usd\n // '0x4db586b0c7f39034e6334a7d6301a2602b97650a000000000000000000000009',\n ],\n },\n Investment: {\n AllowList: [],\n },\n Factories: {\n '0xab6bac0f5f4c7c166c5234b528a1cd46fbcb9f4b': 'weightedPool', // WeightedPool V3\n '0x58e6f99bb65378f47a520fc9630bd711f2cf3dc7': 'composableStablePool', // ComposableStable V3\n '0x48494fa9ead46ee8e3fcb66487a6dbbd34dcafe3': 'weightedPool', // WeightedPool V3\n },\n Stakable: {\n AllowList: [],\n },\n Metadata: {},\n};\n\nconst POOLS_OASYS: Pools = {\n IdsMap: {\n veBAL: '',\n },\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [''],\n ExcludedPoolTypes: [\n 'Element',\n 'AaveLinear',\n 'EulerLinear',\n 'Linear',\n 'ERC4626Linear',\n 'FX',\n 'Gyro2',\n 'Gyro3',\n 'GyroE',\n 'HighAmpComposableStable',\n ],\n Stable: {\n AllowList: [\n // '0xfedb19ec000d38d92af4b21436870f115db22725000000000000000000000010', // bb-ag-usd\n ],\n },\n Investment: {\n AllowList: [],\n },\n Factories: {\n '0x061e05853fb45d3d41ec227459ec98bb25580ad3': 'composableStablePool', // ComposableStable V2\n '0x4ef0b4827ce3d5fecbc2c6ab80ee81dbf9631d37': 'weightedPool', // WeightedPool V3\n '0x5737600b98e7f1cf98daca2a36bca22c974370b0': 'weightedPool',\n },\n Stakable: {\n AllowList: [\n //\n ],\n },\n Metadata: {},\n};\n\nconst POOLS_OASYS_TESTNET: Pools = {\n IdsMap: {\n veBAL: '',\n },\n Pagination: {\n PerPage: 10,\n PerPool: 10,\n PerPoolInitial: 5,\n },\n DelegateOwner: '0xba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1ba1b',\n ZeroAddress: '0x0000000000000000000000000000000000000000',\n DynamicFees: {\n Gauntlet: [],\n },\n BlockList: [\n '0x950f31e8a327a49ae4443284d0137f3b74858474000200000000000000000030',\n ],\n ExcludedPoolTypes: [\n 'Element',\n 'AaveLinear',\n 'EulerLinear',\n 'Linear',\n 'ERC4626Linear',\n 'FX',\n 'Gyro2',\n 'Gyro3',\n 'GyroE',\n 'HighAmpComposableStable',\n ],\n Stable: {\n AllowList: [\n '0xeaac5ae5255407cf933dfcf2b0d3eb4f5dc042cd000000000000000000000035',\n '0x34936c3e61371e9ebd1dcd580b23a52c26080b70000000000000000000000036',\n ],\n },\n Investment: {\n AllowList: [],\n },\n Factories: {\n '0xfda8fa80dd77a99bf71becfce47077859e689898': 'composableStablePool', // ComposableStable V2\n '0xd2d7f457b9749b6a0a637685a65681f03116125c': 'weightedPool', // WeightedPool V3\n },\n Stakable: {\n AllowList: [\n '0x4e66d5f08e81979bd5951c93839bc97265681975000200000000000000000000',\n '0x66180966de2a4180183d7e5dffd76e13b364efe2000200000000000000000001',\n '0xe5b67bf732b7f96127454126069f94f939914d62000200000000000000000002',\n '0x82bfc330a92789c02b3ce2daed3ca889b1a112b7000100000000000000000003',\n '0x0b014863ba970f50b0ea2ad7d57151994b7cac21000100000000000000000004',\n '0x4a54649fb507ee0bf3ad2e1661516b5700c520ab000100000000000000000005',\n '0x981401f589c5768a41d3c4d1a39e84a86f11ad9f000200000000000000000006',\n ],\n },\n Metadata: {},\n};\n\nconst POOLS_MAP = {\n [Network.KOVAN]: POOLS_KOVAN,\n [Network.GOERLI]: POOLS_GOERLI,\n [Network.MAINNET]: POOLS_MAINNET,\n [Network.POLYGON]: POOLS_POLYGON,\n [Network.ARBITRUM]: POOLS_ARBITRUM,\n [Network.GNOSIS]: POOLS_GNOSIS,\n [Network.DEFIVERSE]: POOLS_DEFIVERSE,\n [Network.DEFIVERSE_TESTNET]: POOLS_DEFIVERSE_TESTNET,\n [Network.OASYS]: POOLS_OASYS,\n [Network.OASYS_TESTNET]: POOLS_OASYS_TESTNET,\n};\n\nexport function POOLS(networkId: Network): Pools {\n const id = networkId as keyof typeof POOLS_MAP;\n return POOLS_MAP[id] ? POOLS_MAP[id] : POOLS_GENERIC;\n}\n","import { JsonRpcProvider } from '@ethersproject/providers';\nimport { Contract } from '@ethersproject/contracts';\n\nimport aTokenRateProviderAbi from '../abi/StaticATokenRateProvider.json';\n\nexport class AaveHelpers {\n static async getRate(\n rateProviderAddress: string,\n provider: JsonRpcProvider\n ): Promise<string> {\n const rateProviderContract = new Contract(\n rateProviderAddress,\n aTokenRateProviderAbi,\n provider\n );\n\n const rate = await rateProviderContract.getRate();\n return rate.toString();\n }\n}\n","import { getAddress } from '@ethersproject/address';\nimport { AddressZero } from '@ethersproject/constants';\nimport invariant from 'tiny-invariant';\n\nconst cmpTokens = (tokenA: string, tokenB: string): number =>\n tokenA.toLowerCase() > tokenB.toLowerCase() ? 1 : -1;\n\nconst transposeMatrix = (matrix: unknown[][]): unknown[][] =>\n matrix[0].map((_, columnIndex) => matrix.map((row) => row[columnIndex]));\n\nexport class AssetHelpers {\n public readonly ETH: string = AddressZero;\n public readonly WETH: string;\n\n constructor(wethAddress: string) {\n this.WETH = getAddress(wethAddress);\n }\n\n static isEqual = (addressA: string, addressB: string): boolean =>\n getAddress(addressA) === getAddress(addressB);\n\n /**\n * Tests whether `token` is ETH (represented by `0x0000...0000`).\n *\n * @param token - the address of the asset to be checked\n */\n isETH = (token: string): boolean => AssetHelpers.isEqual(token, this.ETH);\n\n /**\n * Tests whether `token` is WETH.\n *\n * @param token - the address of the asset to be checked\n */\n isWETH = (token: string): boolean => AssetHelpers.isEqual(token, this.WETH);\n\n /**\n * Converts an asset to the equivalent ERC20 address.\n *\n * For ERC20s this will return the passed address but passing ETH (`0x0000...0000`) will return the WETH address\n * @param token - the address of the asset to be translated to an equivalent ERC20\n * @returns the address of translated ERC20 asset\n */\n translateToERC20 = (token: string): string =>\n this.isETH(token) ? this.WETH : token;\n\n /**\n * Sorts an array of token addresses into ascending order to match the format expected by the Vault.\n *\n * Passing additional arrays will result in each being sorted to maintain relative ordering to token addresses.\n *\n * The zero address (representing ETH) is sorted as if it were the WETH address.\n * This matches the behaviour expected by the Vault when receiving an array of addresses.\n *\n * @param tokens - an array of token addresses to be sorted in ascending order\n * @param others - a set of arrays to be sorted in the same order as the tokens, e.g. token weights or asset manager addresses\n * @returns an array of the form `[tokens, ...others]` where each subarray has been sorted to maintain its ordering relative to `tokens`\n *\n * @example\n * const [tokens] = sortTokens([tokenB, tokenC, tokenA])\n * const [tokens, weights] = sortTokens([tokenB, tokenC, tokenA], [weightB, weightC, weightA])\n * // where tokens = [tokenA, tokenB, tokenC], weights = [weightA, weightB, weightC]\n */\n sortTokens(\n tokens: string[],\n ...others: unknown[][]\n ): [string[], ...unknown[][]] {\n others.forEach((array) =>\n invariant(tokens.length === array.length, 'array length mismatch')\n );\n\n // We want to sort ETH as if were WETH so we translate to ERC20s\n const erc20Tokens = tokens.map(this.translateToERC20);\n\n const transpose = transposeMatrix([erc20Tokens, ...others]) as [\n string,\n ...unknown[]\n ][];\n const sortedTranspose = transpose.sort(([tokenA], [tokenB]) =>\n cmpTokens(tokenA, tokenB)\n );\n const [sortedErc20s, ...sortedOthers] = transposeMatrix(\n sortedTranspose\n ) as [string[], ...unknown[][]];\n\n // If one of the tokens was ETH, we need to translate back from WETH\n const sortedTokens = tokens.includes(this.ETH)\n ? sortedErc20s.map((token) => (this.isWETH(token) ? this.ETH : token))\n : sortedErc20s;\n return [sortedTokens, ...sortedOthers];\n }\n}\n","const balancerErrorCodes: Record<string, string> = {\n '000': 'ADD_OVERFLOW',\n '001': 'SUB_OVERFLOW',\n '002': 'SUB_UNDERFLOW',\n '003': 'MUL_OVERFLOW',\n '004': 'ZERO_DIVISION',\n '005': 'DIV_INTERNAL',\n '006': 'X_OUT_OF_BOUNDS',\n '007': 'Y_OUT_OF_BOUNDS',\n '008': 'PRODUCT_OUT_OF_BOUNDS',\n '009': 'INVALID_EXPONENT',\n '100': 'OUT_OF_BOUNDS',\n '101': 'UNSORTED_ARRAY',\n '102': 'UNSORTED_TOKENS',\n '103': 'INPUT_LENGTH_MISMATCH',\n '104': 'ZERO_TOKEN',\n '200': 'MIN_TOKENS',\n '201': 'MAX_TOKENS',\n '202': 'MAX_SWAP_FEE_PERCENTAGE',\n '203': 'MIN_SWAP_FEE_PERCENTAGE',\n '204': 'MINIMUM_BPT',\n '205': 'CALLER_NOT_VAULT',\n '206': 'UNINITIALIZED',\n '207': 'BPT_IN_MAX_AMOUNT',\n '208': 'BPT_OUT_MIN_AMOUNT',\n '209': 'EXPIRED_PERMIT',\n '210': 'NOT_TWO_TOKENS',\n '211': 'DISABLED',\n '300': 'MIN_AMP',\n '301': 'MAX_AMP',\n '302': 'MIN_WEIGHT',\n '303': 'MAX_STABLE_TOKENS',\n '304': 'MAX_IN_RATIO',\n '305': 'MAX_OUT_RATIO',\n '306': 'MIN_BPT_IN_FOR_TOKEN_OUT',\n '307': 'MAX_OUT_BPT_FOR_TOKEN_IN',\n '308': 'NORMALIZED_WEIGHT_INVARIANT',\n '309': 'INVALID_TOKEN',\n '310': 'UNHANDLED_JOIN_KIND',\n '311': 'ZERO_INVARIANT',\n '312': 'ORACLE_INVALID_SECONDS_QUERY',\n '313': 'ORACLE_NOT_INITIALIZED',\n '314': 'ORACLE_QUERY_TOO_OLD',\n '315': 'ORACLE_INVALID_INDEX',\n '316': 'ORACLE_BAD_SECS',\n '317': 'AMP_END_TIME_TOO_CLOSE',\n '318': 'AMP_ONGOING_UPDATE',\n '319': 'AMP_RATE_TOO_HIGH',\n '320': 'AMP_NO_ONGOING_UPDATE',\n '321': 'STABLE_INVARIANT_DIDNT_CONVERGE',\n '322': 'STABLE_GET_BALANCE_DIDNT_CONVERGE',\n '323': 'RELAYER_NOT_CONTRACT',\n '324': 'BASE_POOL_RELAYER_NOT_CALLED',\n '325': 'REBALANCING_RELAYER_REENTERED',\n '326': 'GRADUAL_UPDATE_TIME_TRAVEL',\n '327': 'SWAPS_DISABLED',\n '328': 'CALLER_IS_NOT_LBP_OWNER',\n '329': 'PRICE_RATE_OVERFLOW',\n '330': 'INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED',\n '331': 'WEIGHT_CHANGE_TOO_FAST',\n '332': 'LOWER_GREATER_THAN_UPPER_TARGET',\n '333': 'UPPER_TARGET_TOO_HIGH',\n '334': 'UNHANDLED_BY_LINEAR_POOL',\n '335': 'OUT_OF_TARGET_RANGE',\n '336': 'UNHANDLED_EXIT_KIND ',\n '337': 'UNAUTHORIZED_EXIT',\n '338': 'MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE',\n '339': 'UNHANDLED_BY_MANAGED_POOL',\n '340': 'UNHANDLED_BY_PHANTOM_POOL',\n '341': 'TOKEN_DOES_NOT_HAVE_RATE_PROVIDER',\n '342': 'INVALID_INITIALIZATION',\n '343': 'OUT_OF_NEW_TARGET_RANGE',\n '344': 'UNAUTHORIZED_OPERATION',\n '345': 'UNINITIALIZED_POOL_CONTROLLER',\n '400': 'REENTRANCY',\n '401': 'SENDER_NOT_ALLOWED',\n '402': 'PAUSED',\n '403': 'PAUSE_WINDOW_EXPIRED',\n '404': 'MAX_PAUSE_WINDOW_DURATION',\n '405': 'MAX_BUFFER_PERIOD_DURATION',\n '406': 'INSUFFICIENT_BALANCE',\n '407': 'INSUFFICIENT_ALLOWANCE',\n '408': 'ERC20_TRANSFER_FROM_ZERO_ADDRESS',\n '409': 'ERC20_TRANSFER_TO_ZERO_ADDRESS',\n '410': 'ERC20_MINT_TO_ZERO_ADDRESS',\n '411': 'ERC20_BURN_FROM_ZERO_ADDRESS',\n '412': 'ERC20_APPROVE_FROM_ZERO_ADDRESS',\n '413': 'ERC20_APPROVE_TO_ZERO_ADDRESS',\n '414': 'ERC20_TRANSFER_EXCEEDS_ALLOWANCE',\n '415': 'ERC20_DECREASED_ALLOWANCE_BELOW_ZERO',\n '416': 'ERC20_TRANSFER_EXCEEDS_BALANCE',\n '417': 'ERC20_BURN_EXCEEDS_ALLOWANCE',\n '418': 'SAFE_ERC20_CALL_FAILED',\n '419': 'ADDRESS_INSUFFICIENT_BALANCE',\n '420': 'ADDRESS_CANNOT_SEND_VALUE',\n '421': 'SAFE_CAST_VALUE_CANT_FIT_INT256',\n '422': 'GRANT_SENDER_NOT_ADMIN',\n '423': 'REVOKE_SENDER_NOT_ADMIN',\n '424': 'RENOUNCE_SENDER_NOT_ALLOWED',\n '425': 'BUFFER_PERIOD_EXPIRED',\n '426': 'CALLER_IS_NOT_OWNER',\n '427': 'NEW_OWNER_IS_ZERO',\n '428': 'CODE_DEPLOYMENT_FAILED',\n '429': 'CALL_TO_NON_CONTRACT',\n '430': 'LOW_LEVEL_CALL_FAILED',\n '431': 'NOT_PAUSED',\n '432': 'ADDRESS_ALREADY_ALLOWLISTED',\n '433': 'ADDRESS_NOT_ALLOWLISTED',\n '434': 'ERC20_BURN_EXCEEDS_BALANCE',\n '500': 'INVALID_POOL_ID',\n '501': 'CALLER_NOT_POOL',\n '502': 'SENDER_NOT_ASSET_MANAGER',\n '503': 'USER_DOESNT_ALLOW_RELAYER',\n '504': 'INVALID_SIGNATURE',\n '505': 'EXIT_BELOW_MIN',\n '506': 'JOIN_ABOVE_MAX',\n '507': 'SWAP_LIMIT',\n '508': 'SWAP_DEADLINE',\n '509': 'CANNOT_SWAP_SAME_TOKEN',\n '510': 'UNKNOWN_AMOUNT_IN_FIRST_SWAP',\n '511': 'MALCONSTRUCTED_MULTIHOP_SWAP',\n '512': 'INTERNAL_BALANCE_OVERFLOW',\n '513': 'INSUFFICIENT_INTERNAL_BALANCE',\n '514': 'INVALID_ETH_INTERNAL_BALANCE',\n '515': 'INVALID_POST_LOAN_BALANCE',\n '516': 'INSUFFICIENT_ETH',\n '517': 'UNALLOCATED_ETH',\n '518': 'ETH_TRANSFER',\n '519': 'CANNOT_USE_ETH_SENTINEL',\n '520': 'TOKENS_MISMATCH',\n '521': 'TOKEN_NOT_REGISTERED',\n '522': 'TOKEN_ALREADY_REGISTERED',\n '523': 'TOKENS_ALREADY_SET',\n '524': 'TOKENS_LENGTH_MUST_BE_2',\n '525': 'NONZERO_TOKEN_BALANCE',\n '526': 'BALANCE_TOTAL_OVERFLOW',\n '527': 'POOL_NO_TOKENS',\n '528': 'INSUFFICIENT_FLASH_LOAN_BALANCE',\n '600': 'SWAP_FEE_PERCENTAGE_TOO_HIGH',\n '601': 'FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH',\n '602': 'INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT',\n};\n\nexport class BalancerErrors {\n /**\n * Cannot be constructed.\n */\n private constructor() {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n }\n\n static isErrorCode = (error: string): boolean => {\n if (!error.includes('BAL#')) return false;\n\n const errorCode = error.replace('BAL#', '');\n return Object.keys(balancerErrorCodes).includes(errorCode);\n };\n\n /**\n * Decodes a Balancer error code into the corresponding reason\n * @param error - a Balancer error code of the form `BAL#000`\n * @returns The decoded error reason\n */\n static parseErrorCode = (error: string): string => {\n if (!error.includes('BAL#')) throw new Error('Error code not found');\n const errorCode = error.replace('BAL#', '');\n\n const actualError = balancerErrorCodes[errorCode];\n\n if (!actualError) throw new Error('Error code not found');\n\n return actualError;\n };\n\n /**\n * Decodes a Balancer error code into the corresponding reason\n * @param error - a Balancer error code of the form `BAL#000`\n * @returns The decoded error reason if passed a valid error code, otherwise returns passed input\n */\n static tryParseErrorCode = (error: string): string => {\n try {\n return BalancerErrors.parseErrorCode(error);\n } catch {\n return error;\n }\n };\n\n /**\n * Tests whether a string is a known Balancer error message\n * @param error - a string to be checked verified as a Balancer error message\n */\n static isBalancerError = (error: string): boolean =>\n Object.values(balancerErrorCodes).includes(error);\n\n /**\n * Encodes an error string into the corresponding error code\n * @param error - a Balancer error message string\n * @returns a Balancer error code of the form `BAL#000`\n */\n static encodeError = (error: string): string => {\n const encodedError = Object.entries(balancerErrorCodes).find(\n ([, message]) => message === error\n );\n\n if (!encodedError) throw Error('Error message not found');\n\n return `BAL#${encodedError[0]}`;\n };\n}\n","import { MaxUint256 as MAX_DEADLINE } from '@ethersproject/constants';\nimport { Contract } from '@ethersproject/contracts';\nimport { hexValue, hexZeroPad, splitSignature } from '@ethersproject/bytes';\nimport { BigNumber, BigNumberish } from '@ethersproject/bignumber';\nimport { Signer, TypedDataSigner } from '@ethersproject/abstract-signer';\n\nexport type Account = string | Signer | Contract;\n\nexport async function accountToAddress(account: Account): Promise<string> {\n if (typeof account == 'string') return account;\n if (Signer.isSigner(account)) return account.getAddress();\n if (account.address) return account.address;\n throw new Error('Could not read account address');\n}\n\nexport enum RelayerAction {\n JoinPool = 'JoinPool',\n ExitPool = 'ExitPool',\n Swap = 'Swap',\n BatchSwap = 'BatchSwap',\n SetRelayerApproval = 'SetRelayerApproval',\n}\n\nexport class RelayerAuthorization {\n /**\n * Cannot be constructed.\n */\n private constructor() {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n }\n\n static encodeCalldataAuthorization = (\n calldata: string,\n deadline: BigNumberish,\n signature: string\n ): string => {\n const encodedDeadline = hexZeroPad(hexValue(deadline), 32).slice(2);\n const { v, r, s } = splitSignature(signature);\n const encodedV = hexZeroPad(hexValue(v), 32).slice(2);\n const encodedR = r.slice(2);\n const encodedS = s.slice(2);\n return `${calldata}${encodedDeadline}${encodedV}${encodedR}${encodedS}`;\n };\n\n static signJoinAuthorization = (\n validator: Contract,\n user: Signer & TypedDataSigner,\n allowedSender: Account,\n allowedCalldata: string,\n deadline?: BigNumberish,\n nonce?: BigNumberish\n ): Promise<string> =>\n RelayerAuthorization.signAuthorizationFor(\n RelayerAction.JoinPool,\n validator,\n user,\n allowedSender,\n allowedCalldata,\n deadline,\n nonce\n );\n\n static signExitAuthorization = (\n validator: Contract,\n user: Signer & TypedDataSigner,\n allowedSender: Account,\n allowedCalldata: string,\n deadline?: BigNumberish,\n nonce?: BigNumberish\n ): Promise<string> =>\n RelayerAuthorization.signAuthorizationFor(\n RelayerAction.ExitPool,\n validator,\n user,\n allowedSender,\n allowedCalldata,\n deadline,\n nonce\n );\n\n static signSwapAuthorization = (\n validator: Contract,\n user: Signer & TypedDataSigner,\n allowedSender: Account,\n allowedCalldata: string,\n deadline?: BigNumberish,\n nonce?: BigNumberish\n ): Promise<string> =>\n RelayerAuthorization.signAuthorizationFor(\n RelayerAction.Swap,\n validator,\n user,\n allowedSender,\n allowedCalldata,\n deadline,\n nonce\n );\n\n static signBatchSwapAuthorization = (\n validator: Contract,\n user: Signer & TypedDataSigner,\n allowedSender: Account,\n allowedCalldata: string,\n deadline?: BigNumberish,\n nonce?: BigNumberish\n ): Promise<string> =>\n RelayerAuthorization.signAuthorizationFor(\n RelayerAction.BatchSwap,\n validator,\n user,\n allowedSender,\n allowedCalldata,\n deadline,\n nonce\n );\n\n static signSetRelayerApprovalAuthorization = (\n validator: Contract,\n user: Signer & TypedDataSigner,\n allowedSender: Account,\n allowedCalldata: string,\n deadline?: BigNumberish,\n nonce?: BigNumberish\n ): Promise<string> =>\n RelayerAuthorization.signAuthorizationFor(\n RelayerAction.SetRelayerApproval,\n validator,\n user,\n allowedSender,\n allowedCalldata,\n deadline,\n nonce\n );\n\n static signAuthorizationFor = async (\n type: RelayerAction,\n validator: Contract,\n user: Signer & TypedDataSigner,\n allowedSender: Account,\n allowedCalldata: string,\n deadline: BigNumberish = MAX_DEADLINE,\n nonce?: BigNumberish\n ): Promise<string> => {\n const { chainId } = await validator.provider.getNetwork();\n if (!nonce) {\n const userAddress = await user.getAddress();\n nonce = (await validator.getNextNonce(userAddress)) as BigNumberish;\n }\n\n const domain = {\n name: 'Balancer V2 Vault',\n version: '1',\n chainId,\n verifyingContract: validator.address,\n };\n\n const types = {\n [type]: [\n { name: 'calldata', type: 'bytes' },\n { name: 'sender', type: 'address' },\n { name: 'nonce', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n ],\n };\n\n const value = {\n calldata: allowedCalldata,\n sender: await accountToAddress(allowedSender),\n nonce: nonce.toString(),\n deadline: deadline.toString(),\n };\n\n return user._signTypedData(domain, types, value);\n };\n}\n\nexport class BalancerMinterAuthorization {\n /**\n * Cannot be constructed.\n */\n private constructor() {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n }\n\n static signSetMinterApproval = async (\n minterContract: Contract,\n minter: Account,\n approval: boolean,\n user: Signer & TypedDataSigner,\n deadline: BigNumberish = MAX_DEADLINE,\n nonce?: BigNumberish\n ): Promise<{ v: number; r: string; s: string; deadline: BigNumber }> => {\n const { chainId } = await minterContract.provider.getNetwork();\n if (!nonce) {\n const userAddress = await user.getAddress();\n nonce = (await minterContract.getNextNonce(userAddress)) as BigNumberish;\n }\n\n const domain = {\n name: 'Balancer Minter',\n version: '1',\n chainId,\n verifyingContract: minterContract.address,\n };\n\n const types = {\n SetMinterApproval: [\n { name: 'minter', type: 'address' },\n { name: 'approval', type: 'bool' },\n { name: 'nonce', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n ],\n };\n\n const value = {\n minter: await accountToAddress(minter),\n approval,\n nonce: nonce.toString(),\n deadline: deadline.toString(),\n };\n\n const signature = await user._signTypedData(domain, types, value);\n\n return {\n ...splitSignature(signature),\n deadline: BigNumber.from(deadline),\n };\n };\n}\n","import { Signer, TypedDataSigner } from '@ethersproject/abstract-signer';\nimport { BigNumber, BigNumberish } from '@ethersproject/bignumber';\nimport { splitSignature } from '@ethersproject/bytes';\nimport { MaxUint256 as MAX_DEADLINE } from '@ethersproject/constants';\nimport { Contract } from '@ethersproject/contracts';\nimport { Account, accountToAddress } from './signatures';\n\nexport const signPermit = async (\n token: Contract,\n owner: Signer & TypedDataSigner,\n spender: Account,\n amount: BigNumberish,\n deadline: BigNumberish = MAX_DEADLINE,\n nonce?: BigNumberish\n): Promise<{\n v: number;\n r: string;\n s: string;\n deadline: BigNumber;\n nonce: BigNumber;\n}> => {\n const { chainId } = await token.provider.getNetwork();\n const ownerAddress = await owner.getAddress();\n\n if (!nonce) nonce = (await token.nonces(ownerAddress)) as BigNumberish;\n\n const domain = {\n name: await token.name(),\n version: '1',\n chainId,\n verifyingContract: token.address,\n };\n\n const types = {\n Permit: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n ],\n };\n\n const value = {\n owner: ownerAddress,\n spender: await accountToAddress(spender),\n value: amount,\n nonce,\n deadline,\n };\n\n const signature = await owner._signTypedData(domain, types, value);\n return {\n ...splitSignature(signature),\n deadline: BigNumber.from(deadline),\n nonce: BigNumber.from(nonce),\n };\n};\n","export const BZERO = BigInt(0);\nexport const BONE = BigInt(1);\nexport const ONE = BigInt('1000000000000000000'); // 18 decimal places\n\nconst _require = (b: boolean, message: string) => {\n if (!b) throw new Error(message);\n};\n\n/**\n * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if\n * it had 18 decimals.\n */\nexport function _computeScalingFactor(tokenDecimals: bigint): bigint {\n // Tokens with more than 18 decimals are not supported.\n const decimalsDifference = BigInt(18) - tokenDecimals;\n return ONE * BigInt(10) ** decimalsDifference;\n}\n\n/**\n * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed\n * scaling or not.\n */\nexport function _upscale(amount: bigint, scalingFactor: bigint): bigint {\n // Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of\n // token in should be rounded up, and that of token out rounded down. This is the only place where we round in\n // the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no\n // rounding error unless `_scalingFactor()` is overriden).\n return SolidityMaths.mulDownFixed(amount, scalingFactor);\n}\n\n/**\n * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates*\n * the `amounts` array.\n */\nexport function _upscaleArray(\n amounts: bigint[],\n scalingFactors: bigint[]\n): bigint[] {\n const upscaledAmounts = new Array<bigint>(amounts.length);\n for (let i = 0; i < amounts.length; ++i) {\n upscaledAmounts[i] = SolidityMaths.mulDownFixed(\n amounts[i],\n scalingFactors[i]\n );\n }\n return upscaledAmounts;\n}\n\n/**\n * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on\n * whether it needed scaling or not. The result is rounded down.\n */\nexport function _downscaleDown(amount: bigint, scalingFactor: bigint): bigint {\n return SolidityMaths.divDownFixed(amount, scalingFactor);\n}\n\n/**\n * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead\n * *mutates* the `amounts` array.\n */\nexport function _downscaleDownArray(\n amounts: bigint[],\n scalingFactors: bigint[]\n): bigint[] {\n const downscaledAmounts = new Array<bigint>(amounts.length);\n for (let i = 0; i < amounts.length; ++i) {\n downscaledAmounts[i] = SolidityMaths.divDownFixed(\n amounts[i],\n scalingFactors[i]\n );\n }\n return downscaledAmounts;\n}\n\n/**\n * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on\n * whether it needed scaling or not. The result is rounded up.\n */\nexport function _downscaleUp(amount: bigint, scalingFactor: bigint): bigint {\n return SolidityMaths.divUpFixed(amount, scalingFactor);\n}\n\nexport class SolidityMaths {\n /**\n * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.\n */\n // add(a: bigint, b: bigint): bigint {\n // const c = a + b;\n // // _require(c >= a, Errors.ADD_OVERFLOW);\n // return c;\n // }\n\n /**\n * @dev Returns the addition of two signed integers, reverting on overflow.\n */\n static add(a: bigint, b: bigint): bigint {\n const c = a + b;\n _require((b >= 0 && c >= a) || (b < 0 && c < a), 'Errors.ADD_OVERFLOW');\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.\n */\n static sub(a: bigint, b: bigint): bigint {\n _require(b <= a, 'Errors.SUB_OVERFLOW');\n const c = a - b;\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two signed integers, reverting on overflow.\n */\n // sub(int256 a, int256 b) internal pure returns (int256) {\n // int256 c = a - b;\n // // _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);\n // return c;\n // }\n\n /**\n * @dev Returns the largest of two numbers of 256 bits.\n */\n static max(a: bigint, b: bigint): bigint {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers of 256 bits.\n */\n static min(a: bigint, b: bigint): bigint {\n return a < b ? a : b;\n }\n\n static mul(a: bigint, b: bigint): bigint {\n const c = a * b;\n _require(a == BZERO || c / a == b, 'Errors.MUL_OVERFLOW');\n return c;\n }\n\n static div(a: bigint, b: bigint, roundUp: boolean): bigint {\n return roundUp ? this.divUp(a, b) : this.divDown(a, b);\n }\n\n static divDown(a: bigint, b: bigint): bigint {\n _require(b != BZERO, 'Errors.ZERO_DIVISION');\n return a / b;\n }\n\n static divUp(a: bigint, b: bigint): bigint {\n _require(b != BZERO, 'Errors.ZERO_DIVISION');\n\n if (a == BZERO) {\n return BZERO;\n } else {\n return BONE + (a - BONE) / b;\n }\n }\n\n // Modification: Taken from the fixed point class\n static MAX_POW_RELATIVE_ERROR = BigInt(10000);\n\n static mulUpFixed(a: bigint, b: bigint): bigint {\n const product = a * b;\n _require(a == BZERO || product / a == b, 'Errors.MUL_OVERFLOW');\n\n if (product == BZERO) {\n return BZERO;\n } else {\n // The traditional divUp formula is:\n // divUp(x, y) := (x + y - 1) / y\n // To avoid intermediate overflow in the addition, we distribute the division and get:\n // divUp(x, y) := (x - 1) / y + 1\n // Note that this requires x != 0, which we already tested for.\n\n return (product - BONE) / ONE + BONE;\n }\n }\n\n // Modification: Taken from the fixed point class\n static divDownFixed(a: bigint, b: bigint): bigint {\n _require(b != BZERO, 'Errors.ZERO_DIVISION');\n if (a == BZERO) {\n return BZERO;\n } else {\n const aInflated = a * ONE;\n // _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow\n\n return aInflated / b;\n }\n }\n\n // Modification: Taken from the fixed point class\n static divUpFixed(a: bigint, b: bigint): bigint {\n _require(b != BZERO, 'Errors.ZERO_DIVISION');\n\n if (a == BZERO) {\n return BZERO;\n } else {\n const aInflated = a * ONE;\n _require(aInflated / a == ONE, 'Errors.DIV_INTERNAL'); // mul overflow\n\n // The traditional divUp formula is:\n // divUp(x, y) := (x + y - 1) / y\n // To avoid intermediate overflow in the addition, we distribute the division and get:\n // divUp(x, y) := (x - 1) / y + 1\n // Note that this requires x != 0, which we already tested for.\n\n return (aInflated - BONE) / b + BONE;\n }\n }\n\n // Modification: Taken from the fixed point class\n static powUpFixed(x: bigint, y: bigint): bigint {\n const raw = LogExpMath.pow(x, y);\n const maxError = this.add(\n this.mulUpFixed(raw, this.MAX_POW_RELATIVE_ERROR),\n BONE\n );\n\n return this.add(raw, maxError);\n }\n\n // Modification: Taken from the fixed point class\n static complementFixed(x: bigint): bigint {\n return x < ONE ? ONE - x : BZERO;\n }\n\n static mulDownFixed(a: bigint, b: bigint): bigint {\n const product = a * b;\n _require(a == BZERO || product / a == b, 'Errors.MUL_OVERFLOW');\n\n return product / ONE;\n }\n}\n\nclass LogExpMath {\n // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying\n // two numbers, and multiply by ONE when dividing them.\n\n // All arguments and return values are 18 decimal fixed point numbers.\n static ONE_18 = BigInt('1000000000000000000');\n\n // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the\n // case of ln36, 36 decimals.\n static ONE_20 = BigInt('100000000000000000000');\n static ONE_36 = BigInt('1000000000000000000000000000000000000');\n\n // The domain of natural exponentiation is bound by the word size and number of decimals used.\n //\n // Because internally the result will be stored using 20 decimals, the largest possible result is\n // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.\n // The smallest possible result is 10^(-18), which makes largest negative argument\n // ln(10^(-18)) = -41.446531673892822312.\n // We use 130.0 and -41.0 to have some safety margin.\n static MAX_NATURAL_EXPONENT = BigInt('130000000000000000000');\n static MIN_NATURAL_EXPONENT = BigInt('-41000000000000000000');\n\n // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point\n // 256 bit integer.\n static LN_36_LOWER_BOUND: bigint =\n BigInt(LogExpMath.ONE_18) - BigInt('100000000000000000');\n static LN_36_UPPER_BOUND: bigint =\n BigInt(LogExpMath.ONE_18) + BigInt('100000000000000000');\n\n static MILD_EXPONENT_BOUND: bigint =\n BigInt(2) ** BigInt(254) / LogExpMath.ONE_20;\n\n // 18 decimal constants\n static x0 = BigInt('128000000000000000000'); // 2ˆ7\n static a0 = BigInt(\n '38877084059945950922200000000000000000000000000000000000'\n ); // eˆ(x0) (no decimals)\n static x1 = BigInt('64000000000000000000'); // 2ˆ6\n static a1 = BigInt('6235149080811616882910000000'); // eˆ(x1) (no decimals)\n\n // 20 decimal constants\n static x2 = BigInt('3200000000000000000000'); // 2ˆ5\n static a2 = BigInt('7896296018268069516100000000000000'); // eˆ(x2)\n static x3 = BigInt('1600000000000000000000'); // 2ˆ4\n static a3 = BigInt('888611052050787263676000000'); // eˆ(x3)\n static x4 = BigInt('800000000000000000000'); // 2ˆ3\n static a4 = BigInt('298095798704172827474000'); // eˆ(x4)\n static x5 = BigInt('400000000000000000000'); // 2ˆ2\n static a5 = BigInt('5459815003314423907810'); // eˆ(x5)\n static x6 = BigInt('200000000000000000000'); // 2ˆ1\n static a6 = BigInt('738905609893065022723'); // eˆ(x6)\n static x7 = BigInt('100000000000000000000'); // 2ˆ0\n static a7 = BigInt('271828182845904523536'); // eˆ(x7)\n static x8 = BigInt('50000000000000000000'); // 2ˆ-1\n static a8 = BigInt('164872127070012814685'); // eˆ(x8)\n static x9 = BigInt('25000000000000000000'); // 2ˆ-2\n static a9 = BigInt('128402541668774148407'); // eˆ(x9)\n static x10 = BigInt('12500000000000000000'); // 2ˆ-3\n static a10 = BigInt('113314845306682631683'); // eˆ(x10)\n static x11 = BigInt('6250000000000000000'); // 2ˆ-4\n static a11 = BigInt('106449445891785942956'); // eˆ(x11)\n\n // All arguments and return values are 18 decimal fixed point numbers.\n static pow(x: bigint, y: bigint): bigint {\n if (y === BZERO) {\n // We solve the 0^0 indetermination by making it equal one.\n return this.ONE_18;\n }\n\n if (x == BZERO) {\n return BZERO;\n }\n\n // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to\n // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means\n // x^y = exp(y * ln(x)).\n\n // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.\n _require(\n x <\n BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819968'\n ),\n 'Errors.X_OUT_OF_BOUNDS'\n );\n const x_int256 = x;\n\n // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In\n // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.\n\n // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.\n _require(y < this.MILD_EXPONENT_BOUND, 'Errors.Y_OUT_OF_BOUNDS');\n const y_int256 = y;\n\n let logx_times_y;\n if (\n this.LN_36_LOWER_BOUND < x_int256 &&\n x_int256 < this.LN_36_UPPER_BOUND\n ) {\n const ln_36_x = this._ln_36(x_int256);\n\n // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just\n // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal\n // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the\n // (downscaled) last 18 decimals.\n logx_times_y =\n (ln_36_x / this.ONE_18) * y_int256 +\n ((ln_36_x % this.ONE_18) * y_int256) / this.ONE_18;\n } else {\n logx_times_y = this._ln(x_int256) * y_int256;\n }\n logx_times_y /= this.ONE_18;\n\n // Finally, we compute exp(y * ln(x)) to arrive at x^y\n _require(\n this.MIN_NATURAL_EXPONENT <= logx_times_y &&\n logx_times_y <= this.MAX_NATURAL_EXPONENT,\n 'Errors.PRODUCT_OUT_OF_BOUNDS'\n );\n\n // return uint256(exp(logx_times_y));\n return this.exp(logx_times_y);\n }\n\n static exp(x: bigint): bigint {\n _require(\n x >= this.MIN_NATURAL_EXPONENT && x <= this.MAX_NATURAL_EXPONENT,\n 'Errors.INVALID_EXPONENT'\n );\n\n if (x < 0) {\n // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it\n // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).\n // Fixed point division requires multiplying by ONE_18.\n return (this.ONE_18 * this.ONE_18) / this.exp(BigInt(-1) * x);\n }\n\n // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,\n // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7\n // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the\n // decomposition.\n // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this\n // decomposition, which will be lower than the smallest x_n.\n // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.\n // We mutate x by subtracting x_n, making it the remainder of the decomposition.\n\n // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause\n // intermediate overflows. Instead we store them as plain integers, with 0 decimals.\n // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the\n // decomposition.\n\n // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct\n // it and compute the accumulated product.\n\n let firstAN;\n if (x >= this.x0) {\n x -= this.x0;\n firstAN = this.a0;\n } else if (x >= this.x1) {\n x -= this.x1;\n firstAN = this.a1;\n } else {\n firstAN = BigInt(1); // One with no decimal places\n }\n\n // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the\n // smaller terms.\n x *= BigInt(100);\n\n // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point\n // one. Recall that fixed point multiplication requires dividing by ONE_20.\n let product = this.ONE_20;\n\n if (x >= this.x2) {\n x -= this.x2;\n product = (product * this.a2) / this.ONE_20;\n }\n if (x >= this.x3) {\n x -= this.x3;\n product = (product * this.a3) / this.ONE_20;\n }\n if (x >= this.x4) {\n x -= this.x4;\n product = (product * this.a4) / this.ONE_20;\n }\n if (x >= this.x5) {\n x -= this.x5;\n product = (product * this.a5) / this.ONE_20;\n }\n if (x >= this.x6) {\n x -= this.x6;\n product = (product * this.a6) / this.ONE_20;\n }\n if (x >= this.x7) {\n x -= this.x7;\n product = (product * this.a7) / this.ONE_20;\n }\n if (x >= this.x8) {\n x -= this.x8;\n product = (product * this.a8) / this.ONE_20;\n }\n if (x >= this.x9) {\n x -= this.x9;\n product = (product * this.a9) / this.ONE_20;\n }\n\n // x10 and x11 are unnecessary here since we have high enough precision already.\n\n // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series\n // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).\n\n let seriesSum = this.ONE_20; // The initial one in the sum, with 20 decimal places.\n let term; // Each term in the sum, where the nth term is (x^n / n!).\n\n // The first term is simply x.\n term = x;\n seriesSum += term;\n\n // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,\n // multiplying by it requires dividing by this.ONE_20, but dividing by the non-fixed point n values does not.\n\n term = (term * x) / this.ONE_20 / BigInt(2);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(3);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(4);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(5);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(6);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(7);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(8);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(9);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(10);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(11);\n seriesSum += term;\n\n term = (term * x) / this.ONE_20 / BigInt(12);\n seriesSum += term;\n\n // 12 Taylor terms are sufficient for 18 decimal precision.\n\n // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor\n // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply\n // all three (one 20 decimal fixed point multiplication, dividing by this.ONE_20, and one integer multiplication),\n // and then drop two digits to return an 18 decimal value.\n\n return (((product * seriesSum) / this.ONE_20) * firstAN) / BigInt(100);\n }\n\n static _ln_36(x: bigint): bigint {\n // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits\n // worthwhile.\n\n // First, we transform x to a 36 digit fixed point value.\n x *= this.ONE_18;\n\n // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).\n // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))\n\n // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires\n // division by ONE_36.\n const z = ((x - this.ONE_36) * this.ONE_36) / (x + this.ONE_36);\n const z_squared = (z * z) / this.ONE_36;\n\n // num is the numerator of the series: the z^(2 * n + 1) term\n let num = z;\n\n // seriesSum holds the accumulated sum of each term in the series, starting with the initial z\n let seriesSum = num;\n\n // In each step, the numerator is multiplied by z^2\n num = (num * z_squared) / this.ONE_36;\n seriesSum += num / BigInt(3);\n\n num = (num * z_squared) / this.ONE_36;\n seriesSum += num / BigInt(5);\n\n num = (num * z_squared) / this.ONE_36;\n seriesSum += num / BigInt(7);\n\n num = (num * z_squared) / this.ONE_36;\n seriesSum += num / BigInt(9);\n\n num = (num * z_squared) / this.ONE_36;\n seriesSum += num / BigInt(11);\n\n num = (num * z_squared) / this.ONE_36;\n seriesSum += num / BigInt(13);\n\n num = (num * z_squared) / this.ONE_36;\n seriesSum += num / BigInt(15);\n\n // 8 Taylor terms are sufficient for 36 decimal precision.\n\n // All that remains is multiplying by 2 (non fixed point).\n return seriesSum * BigInt(2);\n }\n\n /**\n * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.\n */\n static _ln(a: bigint): bigint {\n if (a < this.ONE_18) {\n // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less\n // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.\n // Fixed point division requires multiplying by this.ONE_18.\n return BigInt(-1) * this._ln((this.ONE_18 * this.ONE_18) / a);\n }\n\n // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which\n // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,\n // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot\n // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.\n // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this\n // decomposition, which will be lower than the smallest a_n.\n // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.\n // We mutate a by subtracting a_n, making it the remainder of the decomposition.\n\n // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point\n // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by\n // this.ONE_18 to convert them to fixed point.\n // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide\n // by it and compute the accumulated sum.\n\n let sum = BZERO;\n if (a >= this.a0 * this.ONE_18) {\n a /= this.a0; // Integer, not fixed point division\n sum += this.x0;\n }\n\n if (a >= this.a1 * this.ONE_18) {\n a /= this.a1; // Integer, not fixed point division\n sum += this.x1;\n }\n\n // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.\n sum *= BigInt(100);\n a *= BigInt(100);\n\n // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.\n\n if (a >= this.a2) {\n a = (a * this.ONE_20) / this.a2;\n sum += this.x2;\n }\n\n if (a >= this.a3) {\n a = (a * this.ONE_20) / this.a3;\n sum += this.x3;\n }\n\n if (a >= this.a4) {\n a = (a * this.ONE_20) / this.a4;\n sum += this.x4;\n }\n\n if (a >= this.a5) {\n a = (a * this.ONE_20) / this.a5;\n sum += this.x5;\n }\n\n if (a >= this.a6) {\n a = (a * this.ONE_20) / this.a6;\n sum += this.x6;\n }\n\n if (a >= this.a7) {\n a = (a * this.ONE_20) / this.a7;\n sum += this.x7;\n }\n\n if (a >= this.a8) {\n a = (a * this.ONE_20) / this.a8;\n sum += this.x8;\n }\n\n if (a >= this.a9) {\n a = (a * this.ONE_20) / this.a9;\n sum += this.x9;\n }\n\n if (a >= this.a10) {\n a = (a * this.ONE_20) / this.a10;\n sum += this.x10;\n }\n\n if (a >= this.a11) {\n a = (a * this.ONE_20) / this.a11;\n sum += this.x11;\n }\n\n // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series\n // that converges rapidly for values of `a` close to one - the same one used in ln_36.\n // Let z = (a - 1) / (a + 1).\n // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))\n\n // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires\n // division by ONE_20.\n const z = ((a - this.ONE_20) * this.ONE_20) / (a + this.ONE_20);\n const z_squared = (z * z) / this.ONE_20;\n\n // num is the numerator of the series: the z^(2 * n + 1) term\n let num = z;\n\n // seriesSum holds the accumulated sum of each term in the series, starting with the initial z\n let seriesSum = num;\n\n // In each step, the numerator is multiplied by z^2\n num = (num * z_squared) / this.ONE_20;\n seriesSum += num / BigInt(3);\n\n num = (num * z_squared) / this.ONE_20;\n seriesSum += num / BigInt(5);\n\n num = (num * z_squared) / this.ONE_20;\n seriesSum += num / BigInt(7);\n\n num = (num * z_squared) / this.ONE_20;\n seriesSum += num / BigInt(9);\n\n num = (num * z_squared) / this.ONE_20;\n seriesSum += num / BigInt(11);\n\n // 6 Taylor terms are sufficient for 36 decimal precision.\n\n // Finally, we multiply by 2 (non fixed point) to compute ln(remainder)\n seriesSum *= BigInt(2);\n\n // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both\n // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal\n // value.\n\n return (sum + seriesSum) / BigInt(100);\n }\n}\n","import { parseFixed } from '@ethersproject/bignumber';\nimport { Pool } from '../../types';\nimport { _computeScalingFactor } from '@/lib/utils/solidityMaths';\nimport { AssetHelpers } from './assetHelpers';\n\nconst AMP_PRECISION = 3; // number of decimals -> precision 1000\n\n/**\n * Parse pool info into EVM amounts. Sorts by token order if wrappedNativeAsset param passed.\n * @param {Pool} pool\n * @param {string} wrappedNativeAsset\n * @returns parsed pool info\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport const parsePoolInfo = (pool: Pool, wrappedNativeAsset?: string) => {\n let parsedTokens = pool.tokens.map((token) => token.address);\n let parsedDecimals = pool.tokens.map((token) => {\n return token.decimals ? token.decimals.toString() : undefined;\n });\n let scalingFactors = parsedDecimals.map((decimals) =>\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n _computeScalingFactor(BigInt(decimals!))\n );\n let parsedBalances = pool.tokens.map((token) =>\n parseFixed(token.balance, token.decimals).toString()\n );\n // This assumes token.balance is in human scale (e.g. from SG)\n let upScaledBalances = pool.tokens.map((token) =>\n parseFixed(token.balance, 18).toString()\n );\n let parsedWeights = pool.tokens.map((token) => {\n return token.weight ? parseFixed(token.weight, 18).toString() : undefined;\n });\n let parsedPriceRates = pool.tokens.map((token) => {\n return token.priceRate\n ? parseFixed(token.priceRate, 18).toString()\n : undefined;\n });\n\n if (wrappedNativeAsset) {\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n let sfString;\n [\n parsedTokens,\n parsedDecimals,\n sfString,\n parsedBalances,\n upScaledBalances,\n parsedWeights,\n parsedPriceRates,\n ] = assetHelpers.sortTokens(\n parsedTokens,\n parsedDecimals,\n scalingFactors,\n parsedBalances,\n upScaledBalances,\n parsedWeights,\n parsedPriceRates\n ) as [string[], string[], string[], string[], string[], string[], string[]];\n scalingFactors = sfString.map(BigInt);\n }\n\n const parsedAmp = pool.amp\n ? parseFixed(pool.amp, AMP_PRECISION).toString() // Solidity maths uses precison method for amp that must be replicated\n : undefined;\n const parsedTotalShares = parseFixed(pool.totalShares, 18).toString();\n const parsedSwapFee = parseFixed(pool.swapFee, 18).toString();\n\n const scalingFactorsWithoutBpt: bigint[] = [],\n parsedTokensWithoutBpt: string[] = [],\n parsedBalancesWithoutBpt: string[] = [];\n const bptIndex = parsedTokens.indexOf(pool.address);\n if (bptIndex !== -1) {\n scalingFactors.forEach((_, i) => {\n if (i !== bptIndex) {\n scalingFactorsWithoutBpt.push(scalingFactors[i]);\n parsedTokensWithoutBpt.push(parsedTokens[i]);\n parsedBalancesWithoutBpt.push(parsedBalances[i]);\n }\n });\n }\n\n return {\n parsedTokens,\n parsedDecimals,\n parsedBalances,\n parsedWeights,\n parsedPriceRates,\n parsedAmp,\n parsedTotalShares,\n parsedSwapFee,\n upScaledBalances,\n scalingFactors,\n scalingFactorsWithoutBpt,\n parsedTokensWithoutBpt,\n parsedBalancesWithoutBpt,\n bptIndex,\n };\n};\n","import { Network } from '@/lib/constants/network';\n\n/**\n * TYPES\n */\ntype CommonTokens = {\n nativeAsset: string;\n wNativeAsset: string;\n WETH: string;\n BAL: string;\n bbaUSD?: string;\n bbaUSDv2?: string;\n DFV?: string;\n GDT?: string;\n};\n\ntype TokenConstants = {\n Popular: {\n Symbols: string[];\n };\n Addresses: CommonTokens;\n PriceChainMap?: Record<string, string>;\n};\n\n/**\n * CONSTANTS\n */\nexport const DEFAULT_TOKEN_DECIMALS = 18;\n\nexport const TOKENS_MAINNET: TokenConstants = {\n Popular: {\n Symbols: ['WBTC', 'DAI', 'USDC', 'BAL', 'AAVE', 'WETH'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',\n wNativeAsset: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n BAL: '0xba100000625a3754423978a60c9317c58a424e3d',\n bbaUSD: '0x7B50775383d3D6f0215A8F290f2C9e2eEBBEceb2',\n bbaUSDv2: '0xA13a9247ea42D743238089903570127DdA72fE44',\n },\n};\n\nexport const TOKENS_POLYGON: TokenConstants = {\n Popular: {\n Symbols: ['WBTC', 'DAI', 'USDC', 'BAL', 'AAVE', 'WETH'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',\n wNativeAsset: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',\n WETH: '0x7ceb23fd6bc0add59e62ac25578270cff1b9f619',\n BAL: '0x9a71012b13ca4d3d0cdc72a177df3ef03b0e76a3',\n },\n};\n\nexport const TOKENS_ARBITRUM: TokenConstants = {\n Popular: {\n Symbols: ['WBTC', 'DAI', 'USDC', 'BAL', 'AAVE', 'WETH'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',\n wNativeAsset: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',\n WETH: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',\n BAL: '0x040d1EdC9569d4Bab2D15287Dc5A4F10F56a56B8',\n },\n};\n\nexport const TOKENS_GNOSIS: TokenConstants = {\n Popular: {\n Symbols: ['xDAI', 'WXDAI', 'WETH', 'BAL'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',\n wNativeAsset: '0xe91d153e0b41518a2ce8dd3d7944fa863463a97d',\n WETH: '0x6A023CCd1ff6F2045C3309768eAd9E68F978f6e1',\n BAL: '0x7eF541E2a22058048904fE5744f9c7E4C57AF717',\n },\n};\n\nexport const TOKENS_KOVAN: TokenConstants = {\n Popular: {\n Symbols: ['WBTC', 'DAI', 'USDC', 'BAL', 'AAVE', 'WETH'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',\n wNativeAsset: '0xdFCeA9088c8A88A76FF74892C1457C17dfeef9C1',\n WETH: '0xdFCeA9088c8A88A76FF74892C1457C17dfeef9C1',\n BAL: '0xcb355677E36f390Ccc4a5d4bEADFbF1Eb2071c81',\n bbaUSD: '0x8fd162f338B770F7E879030830cDe9173367f301',\n },\n PriceChainMap: {\n /**\n * Addresses must be lower case and map from kovan to mainnet, e.g\n * [kovan address]: mainnet address\n */\n '0xdfcea9088c8a88a76ff74892c1457c17dfeef9c1':\n '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n '0x1c8e3bcb3378a443cc591f154c5ce0ebb4da9648':\n '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599',\n // '0x41286bb1d3e870f3f750eb7e1c25d7e48c8a1ac7':\n // '0xba100000625a3754423978a60c9317c58a424e3d',\n '0x8f4bebf498cc624a0797fe64114a6ff169eee078':\n '0xbc396689893d065f41bc2c6ecbee5e0085233447',\n '0xaf9ac3235be96ed496db7969f60d354fe5e426b0':\n '0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2',\n // BAL\n '0xcb355677e36f390ccc4a5d4beadfbf1eb2071c81':\n '0xba100000625a3754423978a60c9317c58a424e3d',\n // USDC\n '0xc2569dd7d0fd715b054fbf16e75b001e5c0c1115':\n '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n '0x04df6e4121c27713ed22341e7c7df330f56f289b':\n '0x6b175474e89094c44da98b954eedeac495271d0f',\n '0x4803bb90d18a1cb7a2187344fe4feb0e07878d05':\n '0xae7ab96520de3a18e5e111b5eaab095312d7fe84',\n // AAVE DAI\n '0xff795577d9ac8bd7d90ee22b6c1703490b6512fd':\n '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI\n // AAVE USDC\n '0xe22da380ee6b445bb8273c81944adeb6e8450422':\n '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC\n // AAVE USDT\n '0x13512979ade267ab5100878e2e0f485b568328a4':\n '0xdac17f958d2ee523a2206206994597c13d831ec7', // USDT\n // wstETH\n '0xa387b91e393cfb9356a460370842bc8dbb2f29af':\n '0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0',\n },\n};\n\nexport const TOKENS_GOERLI: TokenConstants = {\n Popular: {\n Symbols: ['WBTC', 'DAI', 'USDC', 'BAL', 'USDT', 'WETH'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',\n wNativeAsset: '0xdFCeA9088c8A88A76FF74892C1457C17dfeef9C1',\n WETH: '0xdFCeA9088c8A88A76FF74892C1457C17dfeef9C1',\n BAL: '0xfA8449189744799aD2AcE7e0EBAC8BB7575eff47',\n bbaUSD: '0x13ACD41C585d7EbB4a9460f7C8f50BE60DC080Cd',\n },\n PriceChainMap: {\n /**\n * Addresses must be lower case and map from goerli to mainnet, e.g\n * [goerli address]: mainnet address\n */\n '0xdfcea9088c8a88a76ff74892c1457c17dfeef9c1':\n '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n '0x37f03a12241e9fd3658ad6777d289c3fb8512bc9':\n '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599',\n '0xfa8449189744799ad2ace7e0ebac8bb7575eff47':\n '0xba100000625a3754423978a60c9317c58a424e3d',\n '0xe0c9275e44ea80ef17579d33c55136b7da269aeb':\n '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n '0x8c9e6c40d3402480ace624730524facc5482798c':\n '0x6b175474e89094c44da98b954eedeac495271d0f',\n '0x1f1f156e0317167c11aa412e3d1435ea29dc3cce':\n '0xdac17f958d2ee523a2206206994597c13d831ec7',\n '0x4cb1892fddf14f772b2e39e299f44b2e5da90d04':\n '0x3ed3b47dd13ec9a98b44e6204a523e766b225811',\n '0x811151066392fd641fe74a9b55a712670572d161':\n '0xbcca60bb61934080951369a648fb03df4f96263c',\n '0x89534a24450081aa267c79b07411e9617d984052':\n '0x028171bca77440897b824ca71d1c56cac55b68a3',\n '0x829f35cebbcd47d3c120793c12f7a232c903138b':\n '0x956f47f50a910163d8bf957cf5846d573e7f87ca',\n '0xff386a3d08f80ac38c77930d173fa56c6286dc8b':\n '0x6810e776880c02933d47db1b9fc05908e5386b96',\n },\n};\n\nexport const TOKENS_GENERIC: TokenConstants = {\n Popular: {\n Symbols: ['WBTC', 'DAI', 'USDC', 'BAL', 'AAVE', 'WETH'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',\n wNativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',\n WETH: '0x0000000000000000000000000000000000000000',\n BAL: '0x0000000000000000000000000000000000000000',\n },\n};\n\nexport const TOKENS_DEFIVERSE: TokenConstants = {\n Popular: {\n Symbols: ['GDT', 'BAL', 'WETH', 'OAS'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // need CONFIRM\n wNativeAsset: '0x5a89E11Cb554E00c2f51C4bb7F05bc7Ab0Fa6351', // need CONFIRM\n WETH: '0x5a89E11Cb554E00c2f51C4bb7F05bc7Ab0Fa6351',\n BAL: '',\n GDT: '',\n },\n PriceChainMap: {\n '0x5a89e11cb554e00c2f51c4bb7f05bc7ab0fa6351':\n '0x5a89e11cb554e00c2f51c4bb7f05bc7ab0fa6351', // USDC\n\n '0x7c6b91d9be155a6db01f749217d76ff02a7227f2':\n '0x7c6b91d9be155a6db01f749217d76ff02a7227f2', // USDC\n },\n};\n\nexport const TOKENS_DEFIVERSE_TESTNET: TokenConstants = {\n Popular: {\n Symbols: ['WETH', 'OAS'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // need CONFIRM\n wNativeAsset: '0x6B382742b07AAbBA58c38d792B5d7CBAaB246e99', // need CONFIRM\n WETH: '0x6B382742b07AAbBA58c38d792B5d7CBAaB246e99',\n BAL: '',\n GDT: '',\n },\n PriceChainMap: {},\n};\n\nexport const TOKENS_OASYS: TokenConstants = {\n Popular: {\n Symbols: ['GDT', 'BAL', 'WETH', 'OAS'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // need CONFIRM\n wNativeAsset: '0x5200000000000000000000000000000000000001', // need CONFIRM\n WETH: '0x5200000000000000000000000000000000000001',\n BAL: '0x2B726256AdD04e65403cEf6679A2f2dfF7DDe9F9',\n GDT: '',\n },\n PriceChainMap: {\n '0x5200000000000000000000000000000000000001':\n '0x5a89e11cb554e00c2f51c4bb7f05bc7ab0fa6351', // USDC\n },\n};\n\nexport const TOKENS_OASYS_TESTNET: TokenConstants = {\n Popular: {\n Symbols: ['GDT', 'BAL', 'WETH', 'OAS'],\n },\n Addresses: {\n nativeAsset: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // need CONFIRM\n wNativeAsset: '0x5200000000000000000000000000000000000001', // need CONFIRM\n WETH: '0x5200000000000000000000000000000000000001',\n BAL: '0x9288F664FEFc9f374A53C4307BD3c8F91e83f466',\n GDT: '0x9288F664FEFc9f374A53C4307BD3c8F91e83f466',\n },\n PriceChainMap: {\n '0x5200000000000000000000000000000000000001':\n '0x5a89e11cb554e00c2f51c4bb7f05bc7ab0fa6351', // USDC\n },\n};\n\nexport const TOKENS_MAP = {\n [Network.KOVAN]: TOKENS_KOVAN,\n [Network.GOERLI]: TOKENS_GOERLI,\n [Network.MAINNET]: TOKENS_MAINNET,\n [Network.POLYGON]: TOKENS_POLYGON,\n [Network.ARBITRUM]: TOKENS_ARBITRUM,\n [Network.GNOSIS]: TOKENS_GNOSIS,\n [Network.DEFIVERSE]: TOKENS_DEFIVERSE,\n [Network.DEFIVERSE_TESTNET]: TOKENS_DEFIVERSE_TESTNET,\n [Network.OASYS]: TOKENS_OASYS,\n [Network.OASYS_TESTNET]: TOKENS_OASYS_TESTNET,\n};\n\nexport function TOKENS(networkId: Network): TokenConstants {\n const id = networkId as keyof typeof TOKENS_MAP;\n return TOKENS_MAP[id] ? TOKENS_MAP[id] : TOKENS_GENERIC;\n}\n","export enum PoolGaugesAttributes {\n Id = 'id',\n Address = 'address',\n PoolId = 'poolId',\n}\n\nexport interface PoolGauges {\n preferentialGauge: {\n id: string;\n };\n gauges: {\n id: string;\n relativeWeightCap?: string | null;\n }[];\n}\n","export enum PoolShareAttributes {\n Balance = 'balance',\n Id = 'id',\n PoolId = 'poolId',\n UserAddress = 'userAddress',\n}\n\nexport interface PoolShare {\n id: string;\n userAddress: string;\n poolId: string;\n balance: string;\n}\n","export enum GaugeShareAttributes {\n Id = 'id',\n UserAddress = 'user',\n GaugeId = 'gauge',\n Balance = 'balance',\n}\n\nexport interface GaugeShare {\n id: string;\n balance: string;\n userAddress: string;\n gauge: {\n id: string;\n poolId?: string;\n isKilled: boolean;\n totalSupply: string;\n };\n}\n","import { Network } from './lib/constants/network';\nimport type { BigNumberish } from '@ethersproject/bignumber';\nimport type { Contract } from '@ethersproject/contracts';\nimport type { PoolDataService, TokenPriceService } from '@defiverse/sor';\nimport type {\n ExitExactBPTInAttributes,\n ExitExactTokensOutAttributes,\n JoinPoolAttributes,\n} from './modules/pools/pool-types/concerns/types';\nimport type {\n Findable,\n Searchable,\n LiquidityGauge,\n PoolAttribute,\n TokenAttribute,\n} from '@/modules/data/types';\nimport type {\n BaseFeeDistributor,\n GaugeSharesRepository,\n PoolGaugesRepository,\n PoolSharesRepository,\n ProtocolFeesProvider,\n PoolJoinExitRepository,\n} from './modules/data';\nimport type { GraphQLArgs } from './lib/graphql';\nimport type { AprBreakdown } from '@/modules/pools/apr/apr';\nimport * as Queries from '@/modules/pools/queries/types';\nexport * from '@/modules/data/types';\nexport { Network, AprBreakdown };\n\nexport type Address = string;\n\nexport interface BalancerSdkConfig {\n //use a known network or provide an entirely custom config\n network: Network | BalancerNetworkConfig;\n rpcUrl: string;\n //overwrite the subgraph url if you don't want to use the balancer labs maintained version\n customSubgraphUrl?: string;\n subgraphQuery?: GraphQLQuery;\n //optionally overwrite parts of the standard SOR config\n sor?: Partial<BalancerSdkSorConfig>;\n tenderly?: BalancerTenderlyConfig;\n}\n\nexport interface BalancerTenderlyConfig {\n accessKey?: string;\n user?: string;\n project?: string;\n blockNumber?: number;\n}\n\nexport interface BalancerSdkSorConfig {\n //use a built-in service or provide a custom implementation of a TokenPriceService\n //defaults to coingecko\n tokenPriceService: 'coingecko' | 'subgraph' | TokenPriceService;\n //use a built-in service or provide a custom implementation of a PoolDataService\n //defaults to subgraph\n poolDataService: 'subgraph' | PoolDataService;\n //if a custom PoolDataService is provided, on chain balance fetching needs to be handled externally\n //default to true.\n fetchOnChainBalances: boolean;\n}\n\nexport interface ContractAddresses {\n vault: string;\n multicall: string;\n balancerHelpers: string;\n lidoRelayer?: string;\n relayerV3?: string;\n relayerV4?: string;\n gaugeController?: string;\n feeDistributor?: string;\n veBal?: string;\n veBalProxy?: string;\n protocolFeePercentagesProvider?: string;\n weightedPoolFactory?: string;\n composableStablePoolFactory?: string;\n}\n\nexport interface BalancerNetworkConfig {\n chainId: Network;\n addresses: {\n contracts: ContractAddresses;\n tokens: {\n wrappedNativeAsset: string;\n lbpRaisingTokens?: string[];\n stETH?: string;\n wstETH?: string;\n bal?: string;\n veBal?: string;\n bbaUsd?: string;\n };\n };\n tenderly?: BalancerTenderlyConfig;\n urls: {\n subgraph: string;\n gaugesSubgraph?: string;\n blockNumberSubgraph?: string;\n priceUrl?: string;\n };\n pools: {\n wETHwstETH?: PoolReference;\n };\n poolsToIgnore?: string[];\n sorConnectingTokens?: { symbol: string; address: string }[];\n}\n\nexport interface BalancerDataRepositories {\n pools: Findable<Pool, PoolAttribute> & Searchable<Pool>;\n poolsOnChain: Findable<Pool, PoolAttribute> & Searchable<Pool>;\n yesterdaysPools?: Findable<Pool, PoolAttribute> & Searchable<Pool>;\n tokenPrices: Findable<Price>;\n tokenHistoricalPrices: Findable<Price>;\n tokenMeta: Findable<Token, TokenAttribute>;\n liquidityGauges?: Findable<LiquidityGauge>;\n feeDistributor?: BaseFeeDistributor;\n feeCollector: Findable<number>;\n protocolFees?: ProtocolFeesProvider;\n tokenYields: Findable<number>;\n poolShares: PoolSharesRepository;\n poolGauges?: PoolGaugesRepository;\n poolJoinExits: PoolJoinExitRepository;\n gaugeShares?: GaugeSharesRepository;\n}\n\nexport type PoolReference = {\n id: string;\n address: string;\n};\n\nexport enum PoolSpecialization {\n GeneralPool = 0,\n MinimalSwapInfoPool,\n TwoTokenPool,\n}\n\n// Joins\n\nexport type JoinPoolRequest = {\n assets: string[];\n maxAmountsIn: BigNumberish[];\n userData: string;\n fromInternalBalance: boolean;\n};\n\n// Exit\n\nexport type ExitPoolRequest = {\n assets: string[];\n minAmountsOut: string[];\n userData: string;\n toInternalBalance: boolean;\n};\n\n// Balance Operations\n\nexport enum UserBalanceOpKind {\n DepositInternal = 0,\n WithdrawInternal,\n TransferInternal,\n TransferExternal,\n}\n\nexport type UserBalanceOp = {\n kind: UserBalanceOpKind;\n asset: string;\n amount: BigNumberish;\n sender: string;\n recipient: string;\n};\n\nexport enum PoolBalanceOpKind {\n Withdraw = 0,\n Deposit = 1,\n Update = 2,\n}\n\nexport type PoolBalanceOp = {\n kind: PoolBalanceOpKind;\n poolId: string;\n token: string;\n amount: BigNumberish;\n};\n\nexport interface TransactionData {\n contract?: Contract;\n function: string;\n params: string[];\n outputs?: {\n amountsIn?: string[];\n amountsOut?: string[];\n };\n}\n\nexport type Currency = 'eth' | 'usd';\n\nexport type Price = { [currency in Currency]?: string };\nexport type TokenPrices = { [address: string]: Price };\nexport type HistoricalPrices = {\n prices: [[number, number]];\n market_caps: [[number, number]];\n total_volumes: [[number, number]];\n};\n\nexport interface Token {\n address: string;\n decimals?: number;\n symbol?: string;\n price?: Price;\n}\n\nexport interface PoolToken extends Token {\n balance: string;\n priceRate?: string;\n weight?: string | null;\n isExemptFromYieldProtocolFee?: boolean;\n token?: SubPoolMeta;\n}\n\nexport interface SubPoolMeta {\n pool: SubPool | null;\n latestUSDPrice?: string;\n}\n\nexport interface SubPool {\n id: string;\n address: string;\n poolType: PoolType;\n totalShares: string;\n mainIndex: number;\n tokens?: PoolToken[];\n}\n\nexport interface OnchainTokenData {\n balance: string;\n weight: number;\n decimals: number;\n logoURI: string | undefined;\n name: string;\n symbol: string;\n}\n\nexport interface OnchainPoolData {\n tokens: Record<Address, OnchainTokenData>;\n totalSupply: string;\n decimals: number;\n swapFee: string;\n amp?: string;\n swapEnabled: boolean;\n tokenRates?: string[];\n}\n\nexport enum PoolType {\n Weighted = 'Weighted',\n Investment = 'Investment',\n Stable = 'Stable',\n HighAmpComposableStable = 'HighAmpComposableStable',\n ComposableStable = 'ComposableStable',\n MetaStable = 'MetaStable',\n StablePhantom = 'StablePhantom',\n LiquidityBootstrapping = 'LiquidityBootstrapping',\n AaveLinear = 'AaveLinear',\n Linear = 'Linear',\n EulerLinear = 'EulerLinear',\n ERC4626Linear = 'ERC4626Linear',\n Element = 'Element',\n Gyro2 = 'Gyro2',\n Gyro3 = 'Gyro3',\n Managed = 'Managed',\n}\n\nexport interface Pool {\n id: string;\n name: string;\n address: string;\n chainId: number;\n poolType: PoolType;\n poolTypeVersion: number;\n swapFee: string;\n protocolYieldFeeCache: string;\n protocolSwapFeeCache: string;\n owner?: string;\n factory?: string;\n tokens: PoolToken[];\n tokensList: string[];\n tokenAddresses?: string[];\n totalLiquidity: string;\n totalShares: string;\n totalSwapFee?: string;\n totalSwapVolume?: string;\n onchain?: OnchainPoolData;\n createTime?: number;\n mainTokens?: string[];\n wrappedTokens?: string[];\n unwrappedTokens?: string[];\n isNew?: boolean;\n volumeSnapshot?: string;\n feesSnapshot?: string;\n boost?: string;\n symbol?: string;\n swapEnabled: boolean;\n amp?: string;\n wrappedIndex?: number;\n mainIndex?: number;\n apr?: AprBreakdown;\n liquidity?: string;\n totalWeight: string;\n lowerTarget: string;\n upperTarget: string;\n priceRateProviders?: PriceRateProvider[];\n}\n\nexport interface PriceRateProvider {\n address: string;\n token: {\n address: string;\n };\n}\n\n/**\n * Pool use-cases / controller layer\n */\nexport interface PoolWithMethods extends Pool, Queries.ParamsBuilder {\n buildJoin: (\n joiner: string,\n tokensIn: string[],\n amountsIn: string[],\n slippage: string\n ) => JoinPoolAttributes;\n calcPriceImpact: (\n amountsIn: string[],\n minBPTOut: string,\n isJoin: boolean\n ) => Promise<string>;\n buildExitExactBPTIn: (\n exiter: string,\n bptIn: string,\n slippage: string,\n shouldUnwrapNativeAsset?: boolean,\n singleTokenMaxOut?: string\n ) => ExitExactBPTInAttributes;\n buildExitExactTokensOut: (\n exiter: string,\n tokensOut: string[],\n amountsOut: string[],\n slippage: string\n ) => ExitExactTokensOutAttributes;\n calcSpotPrice: (tokenIn: string, tokenOut: string) => string;\n}\n\nexport interface GraphQLQuery {\n args: GraphQLArgs;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attrs: any;\n}\n","\"use strict\";\nlet _permanentCensorErrors = false;\nlet _censorErrors = false;\nconst LogLevels = { debug: 1, \"default\": 2, info: 2, warning: 3, error: 4, off: 5 };\nlet _logLevel = LogLevels[\"default\"];\nimport { version } from \"./_version\";\nlet _globalLogger = null;\nfunction _checkNormalize() {\n try {\n const missing = [];\n // Make sure all forms of normalization are supported\n [\"NFD\", \"NFC\", \"NFKD\", \"NFKC\"].forEach((form) => {\n try {\n if (\"test\".normalize(form) !== \"test\") {\n throw new Error(\"bad normalize\");\n }\n ;\n }\n catch (error) {\n missing.push(form);\n }\n });\n if (missing.length) {\n throw new Error(\"missing \" + missing.join(\", \"));\n }\n if (String.fromCharCode(0xe9).normalize(\"NFD\") !== String.fromCharCode(0x65, 0x0301)) {\n throw new Error(\"broken implementation\");\n }\n }\n catch (error) {\n return error.message;\n }\n return null;\n}\nconst _normalizeError = _checkNormalize();\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[\"DEBUG\"] = \"DEBUG\";\n LogLevel[\"INFO\"] = \"INFO\";\n LogLevel[\"WARNING\"] = \"WARNING\";\n LogLevel[\"ERROR\"] = \"ERROR\";\n LogLevel[\"OFF\"] = \"OFF\";\n})(LogLevel || (LogLevel = {}));\nexport var ErrorCode;\n(function (ErrorCode) {\n ///////////////////\n // Generic Errors\n // Unknown Error\n ErrorCode[\"UNKNOWN_ERROR\"] = \"UNKNOWN_ERROR\";\n // Not Implemented\n ErrorCode[\"NOT_IMPLEMENTED\"] = \"NOT_IMPLEMENTED\";\n // Unsupported Operation\n // - operation\n ErrorCode[\"UNSUPPORTED_OPERATION\"] = \"UNSUPPORTED_OPERATION\";\n // Network Error (i.e. Ethereum Network, such as an invalid chain ID)\n // - event (\"noNetwork\" is not re-thrown in provider.ready; otherwise thrown)\n ErrorCode[\"NETWORK_ERROR\"] = \"NETWORK_ERROR\";\n // Some sort of bad response from the server\n ErrorCode[\"SERVER_ERROR\"] = \"SERVER_ERROR\";\n // Timeout\n ErrorCode[\"TIMEOUT\"] = \"TIMEOUT\";\n ///////////////////\n // Operational Errors\n // Buffer Overrun\n ErrorCode[\"BUFFER_OVERRUN\"] = \"BUFFER_OVERRUN\";\n // Numeric Fault\n // - operation: the operation being executed\n // - fault: the reason this faulted\n ErrorCode[\"NUMERIC_FAULT\"] = \"NUMERIC_FAULT\";\n ///////////////////\n // Argument Errors\n // Missing new operator to an object\n // - name: The name of the class\n ErrorCode[\"MISSING_NEW\"] = \"MISSING_NEW\";\n // Invalid argument (e.g. value is incompatible with type) to a function:\n // - argument: The argument name that was invalid\n // - value: The value of the argument\n ErrorCode[\"INVALID_ARGUMENT\"] = \"INVALID_ARGUMENT\";\n // Missing argument to a function:\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"MISSING_ARGUMENT\"] = \"MISSING_ARGUMENT\";\n // Too many arguments\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"UNEXPECTED_ARGUMENT\"] = \"UNEXPECTED_ARGUMENT\";\n ///////////////////\n // Blockchain Errors\n // Call exception\n // - transaction: the transaction\n // - address?: the contract address\n // - args?: The arguments passed into the function\n // - method?: The Solidity method signature\n // - errorSignature?: The EIP848 error signature\n // - errorArgs?: The EIP848 error parameters\n // - reason: The reason (only for EIP848 \"Error(string)\")\n ErrorCode[\"CALL_EXCEPTION\"] = \"CALL_EXCEPTION\";\n // Insufficient funds (< value + gasLimit * gasPrice)\n // - transaction: the transaction attempted\n ErrorCode[\"INSUFFICIENT_FUNDS\"] = \"INSUFFICIENT_FUNDS\";\n // Nonce has already been used\n // - transaction: the transaction attempted\n ErrorCode[\"NONCE_EXPIRED\"] = \"NONCE_EXPIRED\";\n // The replacement fee for the transaction is too low\n // - transaction: the transaction attempted\n ErrorCode[\"REPLACEMENT_UNDERPRICED\"] = \"REPLACEMENT_UNDERPRICED\";\n // The gas limit could not be estimated\n // - transaction: the transaction passed to estimateGas\n ErrorCode[\"UNPREDICTABLE_GAS_LIMIT\"] = \"UNPREDICTABLE_GAS_LIMIT\";\n // The transaction was replaced by one with a higher gas price\n // - reason: \"cancelled\", \"replaced\" or \"repriced\"\n // - cancelled: true if reason == \"cancelled\" or reason == \"replaced\")\n // - hash: original transaction hash\n // - replacement: the full TransactionsResponse for the replacement\n // - receipt: the receipt of the replacement\n ErrorCode[\"TRANSACTION_REPLACED\"] = \"TRANSACTION_REPLACED\";\n ///////////////////\n // Interaction Errors\n // The user rejected the action, such as signing a message or sending\n // a transaction\n ErrorCode[\"ACTION_REJECTED\"] = \"ACTION_REJECTED\";\n})(ErrorCode || (ErrorCode = {}));\n;\nconst HEX = \"0123456789abcdef\";\nexport class Logger {\n constructor(version) {\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n value: version,\n writable: false\n });\n }\n _log(logLevel, args) {\n const level = logLevel.toLowerCase();\n if (LogLevels[level] == null) {\n this.throwArgumentError(\"invalid log level name\", \"logLevel\", logLevel);\n }\n if (_logLevel > LogLevels[level]) {\n return;\n }\n console.log.apply(console, args);\n }\n debug(...args) {\n this._log(Logger.levels.DEBUG, args);\n }\n info(...args) {\n this._log(Logger.levels.INFO, args);\n }\n warn(...args) {\n this._log(Logger.levels.WARNING, args);\n }\n makeError(message, code, params) {\n // Errors are being censored\n if (_censorErrors) {\n return this.makeError(\"censored error\", code, {});\n }\n if (!code) {\n code = Logger.errors.UNKNOWN_ERROR;\n }\n if (!params) {\n params = {};\n }\n const messageDetails = [];\n Object.keys(params).forEach((key) => {\n const value = params[key];\n try {\n if (value instanceof Uint8Array) {\n let hex = \"\";\n for (let i = 0; i < value.length; i++) {\n hex += HEX[value[i] >> 4];\n hex += HEX[value[i] & 0x0f];\n }\n messageDetails.push(key + \"=Uint8Array(0x\" + hex + \")\");\n }\n else {\n messageDetails.push(key + \"=\" + JSON.stringify(value));\n }\n }\n catch (error) {\n messageDetails.push(key + \"=\" + JSON.stringify(params[key].toString()));\n }\n });\n messageDetails.push(`code=${code}`);\n messageDetails.push(`version=${this.version}`);\n const reason = message;\n let url = \"\";\n switch (code) {\n case ErrorCode.NUMERIC_FAULT: {\n url = \"NUMERIC_FAULT\";\n const fault = message;\n switch (fault) {\n case \"overflow\":\n case \"underflow\":\n case \"division-by-zero\":\n url += \"-\" + fault;\n break;\n case \"negative-power\":\n case \"negative-width\":\n url += \"-unsupported\";\n break;\n case \"unbound-bitwise-result\":\n url += \"-unbound-result\";\n break;\n }\n break;\n }\n case ErrorCode.CALL_EXCEPTION:\n case ErrorCode.INSUFFICIENT_FUNDS:\n case ErrorCode.MISSING_NEW:\n case ErrorCode.NONCE_EXPIRED:\n case ErrorCode.REPLACEMENT_UNDERPRICED:\n case ErrorCode.TRANSACTION_REPLACED:\n case ErrorCode.UNPREDICTABLE_GAS_LIMIT:\n url = code;\n break;\n }\n if (url) {\n message += \" [ See: https:/\\/links.ethers.org/v5-errors-\" + url + \" ]\";\n }\n if (messageDetails.length) {\n message += \" (\" + messageDetails.join(\", \") + \")\";\n }\n // @TODO: Any??\n const error = new Error(message);\n error.reason = reason;\n error.code = code;\n Object.keys(params).forEach(function (key) {\n error[key] = params[key];\n });\n return error;\n }\n throwError(message, code, params) {\n throw this.makeError(message, code, params);\n }\n throwArgumentError(message, name, value) {\n return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {\n argument: name,\n value: value\n });\n }\n assert(condition, message, code, params) {\n if (!!condition) {\n return;\n }\n this.throwError(message, code, params);\n }\n assertArgument(condition, message, name, value) {\n if (!!condition) {\n return;\n }\n this.throwArgumentError(message, name, value);\n }\n checkNormalize(message) {\n if (message == null) {\n message = \"platform missing String.prototype.normalize\";\n }\n if (_normalizeError) {\n this.throwError(\"platform missing String.prototype.normalize\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"String.prototype.normalize\", form: _normalizeError\n });\n }\n }\n checkSafeUint53(value, message) {\n if (typeof (value) !== \"number\") {\n return;\n }\n if (message == null) {\n message = \"value not safe\";\n }\n if (value < 0 || value >= 0x1fffffffffffff) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"out-of-safe-range\",\n value: value\n });\n }\n if (value % 1) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"non-integer\",\n value: value\n });\n }\n }\n checkArgumentCount(count, expectedCount, message) {\n if (message) {\n message = \": \" + message;\n }\n else {\n message = \"\";\n }\n if (count < expectedCount) {\n this.throwError(\"missing argument\" + message, Logger.errors.MISSING_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n if (count > expectedCount) {\n this.throwError(\"too many arguments\" + message, Logger.errors.UNEXPECTED_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n }\n checkNew(target, kind) {\n if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n checkAbstract(target, kind) {\n if (target === kind) {\n this.throwError(\"cannot instantiate abstract class \" + JSON.stringify(kind.name) + \" directly; use a sub-class\", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: \"new\" });\n }\n else if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n static globalLogger() {\n if (!_globalLogger) {\n _globalLogger = new Logger(version);\n }\n return _globalLogger;\n }\n static setCensorship(censorship, permanent) {\n if (!censorship && permanent) {\n this.globalLogger().throwError(\"cannot permanently disable censorship\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n if (_permanentCensorErrors) {\n if (!censorship) {\n return;\n }\n this.globalLogger().throwError(\"error censorship permanent\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n _censorErrors = !!censorship;\n _permanentCensorErrors = !!permanent;\n }\n static setLogLevel(logLevel) {\n const level = LogLevels[logLevel.toLowerCase()];\n if (level == null) {\n Logger.globalLogger().warn(\"invalid log level - \" + logLevel);\n return;\n }\n _logLevel = level;\n }\n static from(version) {\n return new Logger(version);\n }\n}\nLogger.errors = ErrorCode;\nLogger.levels = LogLevel;\n//# sourceMappingURL=index.js.map","export const version = \"logger/5.7.0\";\n//# sourceMappingURL=_version.js.map","export const version = \"units/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { formatFixed, parseFixed } from \"@ethersproject/bignumber\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nconst names = [\n \"wei\",\n \"kwei\",\n \"mwei\",\n \"gwei\",\n \"szabo\",\n \"finney\",\n \"ether\",\n];\n// Some environments have issues with RegEx that contain back-tracking, so we cannot\n// use them.\nexport function commify(value) {\n const comps = String(value).split(\".\");\n if (comps.length > 2 || !comps[0].match(/^-?[0-9]*$/) || (comps[1] && !comps[1].match(/^[0-9]*$/)) || value === \".\" || value === \"-.\") {\n logger.throwArgumentError(\"invalid value\", \"value\", value);\n }\n // Make sure we have at least one whole digit (0 if none)\n let whole = comps[0];\n let negative = \"\";\n if (whole.substring(0, 1) === \"-\") {\n negative = \"-\";\n whole = whole.substring(1);\n }\n // Make sure we have at least 1 whole digit with no leading zeros\n while (whole.substring(0, 1) === \"0\") {\n whole = whole.substring(1);\n }\n if (whole === \"\") {\n whole = \"0\";\n }\n let suffix = \"\";\n if (comps.length === 2) {\n suffix = \".\" + (comps[1] || \"0\");\n }\n while (suffix.length > 2 && suffix[suffix.length - 1] === \"0\") {\n suffix = suffix.substring(0, suffix.length - 1);\n }\n const formatted = [];\n while (whole.length) {\n if (whole.length <= 3) {\n formatted.unshift(whole);\n break;\n }\n else {\n const index = whole.length - 3;\n formatted.unshift(whole.substring(index));\n whole = whole.substring(0, index);\n }\n }\n return negative + formatted.join(\",\") + suffix;\n}\nexport function formatUnits(value, unitName) {\n if (typeof (unitName) === \"string\") {\n const index = names.indexOf(unitName);\n if (index !== -1) {\n unitName = 3 * index;\n }\n }\n return formatFixed(value, (unitName != null) ? unitName : 18);\n}\nexport function parseUnits(value, unitName) {\n if (typeof (value) !== \"string\") {\n logger.throwArgumentError(\"value must be a string\", \"value\", value);\n }\n if (typeof (unitName) === \"string\") {\n const index = names.indexOf(unitName);\n if (index !== -1) {\n unitName = 3 * index;\n }\n }\n return parseFixed(value, (unitName != null) ? unitName : 18);\n}\nexport function formatEther(wei) {\n return formatUnits(wei, 18);\n}\nexport function parseEther(ether) {\n return parseUnits(ether, 18);\n}\n//# sourceMappingURL=index.js.map","import { Network } from '@/types';\nimport { AprFetcher } from '../repository';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { formatUnits } from '@ethersproject/units';\nimport axios from 'axios';\n\n// can be fetched from subgraph\n// aave-js: supplyAPR = graph.liquidityRate = core.getReserveCurrentLiquidityRate(_reserve)\n// or directly from RPC:\n// wrappedAaveToken.LENDING_POOL.getReserveCurrentLiquidityRate(mainTokenAddress)\n\nexport const yieldTokens = {\n [Network.MAINNET]: {\n waUSDT: '0xf8fd466f12e236f4c96f7cce6c79eadb819abf58',\n waUSDC: '0xd093fa4fb80d09bb30817fdcd442d4d02ed3e5de',\n waDAI: '0x02d60b84491589974263d922d9cc7a3152618ef6',\n },\n [Network.POLYGON]: {\n wamDAI: '0xee029120c72b0607344f35b17cdd90025e647b00',\n wamUSDC: '0x221836a597948dce8f3568e044ff123108acc42a',\n wamUSDT: '0x19c60a251e525fa88cd6f3768416a8024e98fc19',\n },\n};\n\nexport const allYieldTokens = {\n ...yieldTokens[Network.MAINNET],\n ...yieldTokens[Network.POLYGON],\n};\n\nexport const wrappedTokensMap = {\n [Network.MAINNET]: {\n // USDT\n [yieldTokens[Network.MAINNET].waUSDT]: {\n aToken: '0x3ed3b47dd13ec9a98b44e6204a523e766b225811',\n underlying: '0xdac17f958d2ee523a2206206994597c13d831ec7',\n },\n // USDC\n [yieldTokens[Network.MAINNET].waUSDC]: {\n aToken: '0xbcca60bb61934080951369a648fb03df4f96263c',\n underlying: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n },\n // DAI\n [yieldTokens[Network.MAINNET].waDAI]: {\n aToken: '0x028171bca77440897b824ca71d1c56cac55b68a3',\n underlying: '0x6b175474e89094c44da98b954eedeac495271d0f',\n },\n },\n [Network.POLYGON]: {\n // USDT\n [yieldTokens[Network.POLYGON].wamUSDT]: {\n aToken: '0x60d55f02a771d515e077c9c2403a1ef324885cec',\n underlying: '0xc2132d05d31c914a87c6611c10748aeb04b58e8f',\n },\n // USDC\n [yieldTokens[Network.POLYGON].wamUSDC]: {\n aToken: '0x1a13f4ca1d028320a707d99520abfefca3998b7f',\n underlying: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174',\n },\n // DAI\n [yieldTokens[Network.POLYGON].wamDAI]: {\n aToken: '0x27f8d03b3a2196956ed754badc28d73be8830a6e',\n underlying: '0x8f3cf7ad23cd3cadbd9735aff958023239c6a063',\n },\n },\n};\n\nconst aTokens = {\n [Network.MAINNET]: Object.values(wrappedTokensMap[Network.MAINNET]).map(\n (t) => t.aToken\n ),\n [Network.POLYGON]: Object.values(wrappedTokensMap[Network.POLYGON]).map(\n (t) => t.aToken\n ),\n};\n\nconst underlyingAssets = {\n [Network.MAINNET]: Object.values(wrappedTokensMap[Network.MAINNET]).map(\n (t) => t.underlying\n ),\n [Network.POLYGON]: Object.values(wrappedTokensMap[Network.POLYGON]).map(\n (t) => t.underlying\n ),\n};\n\nconst underlyingToWrapped = {\n [Network.MAINNET]: Object.fromEntries(\n Object.keys(wrappedTokensMap[Network.MAINNET]).map((wrapped) => [\n wrappedTokensMap[Network.MAINNET][\n wrapped as keyof typeof wrappedTokensMap[Network.MAINNET]\n ].underlying,\n wrapped,\n ])\n ),\n [Network.POLYGON]: Object.fromEntries(\n Object.keys(wrappedTokensMap[Network.POLYGON]).map((wrapped) => [\n wrappedTokensMap[Network.POLYGON][\n wrapped as keyof typeof wrappedTokensMap[Network.POLYGON]\n ].underlying,\n wrapped,\n ])\n ),\n};\n\n// Subgraph\n// liquidityRate, depositors APR (in rays - 27 digits)\nconst endpoint = {\n [Network.MAINNET]: 'https://api.thegraph.com/subgraphs/name/aave/protocol-v2',\n [Network.POLYGON]:\n 'https://api.thegraph.com/subgraphs/name/aave/aave-v2-matic',\n};\n\nconst query = `\n query getReserves($aTokens: [String!], $underlyingAssets: [Bytes!]) {\n reserves(\n where: {\n aToken_in: $aTokens\n underlyingAsset_in: $underlyingAssets\n isActive: true\n }\n ) {\n underlyingAsset\n liquidityRate\n }\n }\n`;\n\ninterface ReserveResponse {\n data: {\n reserves: [\n {\n underlyingAsset: string;\n liquidityRate: string;\n }\n ];\n };\n}\n\n/**\n * Fetching and parsing aave APRs from a subgraph\n *\n * @returns APRs for aave tokens\n */\nexport const aave: AprFetcher = async (network?: Network) => {\n const noRates = Object.fromEntries(\n Object.keys(wrappedTokensMap).map((key) => [key, 0])\n );\n\n if (!network || (network != Network.MAINNET && network != Network.POLYGON)) {\n return noRates;\n }\n\n try {\n const graphqlQuery = {\n operationName: 'getReserves',\n query,\n variables: {\n aTokens: aTokens[network],\n underlyingAssets: underlyingAssets[network],\n },\n };\n\n const response = await axios.post(endpoint[network], graphqlQuery);\n\n const {\n data: { reserves },\n } = response.data as ReserveResponse;\n\n const aprEntries = reserves.map((r) => [\n underlyingToWrapped[network][r.underlyingAsset],\n // Note: our assumption is frontend usage, this service is not a good source where more accuracy is needed.\n // Converting from aave ray number (27 digits) to bsp\n // essentially same as here:\n // https://github.com/aave/aave-utilities/blob/master/packages/math-utils/src/formatters/reserve/index.ts#L231\n Math.round(\n parseFloat(formatUnits(BigNumber.from(r.liquidityRate), 27)) * 10000\n ),\n ]);\n\n return Object.fromEntries(aprEntries);\n } catch (error) {\n console.log(error);\n\n return noRates;\n }\n};\n\n// TODO: RPC multicall\n// always upto date\n// const lendingPoolAddress = '0x7d2768de32b0b80b7a3454c06bdac94a69ddc7a9';\n","import { Token, TokenPrices, Network } from '@/types';\nimport { TOKENS } from '@/lib/constants/tokens';\nimport { wrappedTokensMap as aaveWrappedMap } from '@/modules/data/token-yields/tokens/aave';\n\nexport function tokensToTokenPrices(tokens: Token[]): TokenPrices {\n const tokenPrices: TokenPrices = {};\n tokens.forEach((token) => {\n if (token.price) {\n tokenPrices[token.address] = token.price;\n }\n });\n\n return tokenPrices;\n}\n\nexport function tokenAddressForPricing(\n address: string,\n chainId: Network\n): string {\n let a = address.toLowerCase();\n a = addressMapIn(a, chainId);\n a = unwrapToken(a, chainId);\n\n return a;\n}\n\n/**\n * Maps testnet tokens, eg: on Göreli to a mainnet one.\n * Used to get the pricing information on networks not supported by a price feed.\n *\n * @param address Address on a testnet network\n */\nexport const addressMapIn = (address: string, chainId: Network): string => {\n const addressMap = TOKENS(chainId).PriceChainMap;\n return (addressMap && addressMap[address.toLowerCase()]) || address;\n};\n\n/**\n * Finds an underlying token address for a wrapped one\n *\n * @param wrappedAddress\n * @param chainId\n * @returns underlying token address\n */\nexport const unwrapToken = (\n wrappedAddress: string,\n chainId: Network\n): string => {\n const lowercase = wrappedAddress.toLocaleLowerCase();\n\n const aaveChain = chainId as keyof typeof aaveWrappedMap;\n if (\n aaveWrappedMap[aaveChain] != undefined &&\n aaveWrappedMap[aaveChain] != null\n ) {\n // Double if to avoid skipping just to at after compile: Object.keys()?.includes\n if (Object.keys(aaveWrappedMap[aaveChain]).includes(lowercase)) {\n return aaveWrappedMap[aaveChain][\n lowercase as keyof typeof aaveWrappedMap[typeof aaveChain]\n ].aToken;\n } else {\n return lowercase;\n }\n } else {\n return lowercase;\n }\n};\n","/* eslint-disable @typescript-eslint/no-empty-function */\n\n/**\n * Debouncer for different attributes requested over time, which need to be aggregated into a single resolving call\n *\n * Choosing deferred promise since we have setTimeout that returns a promise\n * Some reference for history buffs: https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns\n */\n\ninterface Promised<T> {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (reason: unknown) => void;\n}\n\nconst makePromise = <T>(): Promised<T> => {\n let resolve: (value: T) => void = () => {};\n let reject: (reason: unknown) => void = () => {};\n const promise = new Promise<T>((res, rej) => {\n [resolve, reject] = [res, rej];\n });\n return { promise, reject, resolve };\n};\n\n/**\n * Aggregates attributes and exectutes a debounced call\n *\n * @param fn Function to debounce\n * @param wait Debouncing waiting time [ms]\n */\nexport class Debouncer<T, A> {\n requestSet = new Set<A>(); // collection of requested attributes\n promisedCalls: Promised<T>[] = []; // When requesting a price we return a deferred promise\n promisedCount = 0; // New request coming when setTimeout is executing will make a new promise\n timeout?: ReturnType<typeof setTimeout>;\n debounceCancel = (): void => {}; // Allow to cancel mid-flight requests\n\n constructor(private fn: (attrs: A[]) => Promise<T>, private wait = 200) {}\n\n fetch(attr?: A): Promise<T> {\n if (attr) {\n this.requestSet.add(attr);\n }\n\n if (this.promisedCalls[this.promisedCount]) {\n return this.promisedCalls[this.promisedCount].promise;\n }\n\n this.promisedCalls[this.promisedCount] = makePromise();\n\n const { promise, resolve, reject } = this.promisedCalls[this.promisedCount];\n\n if (this.timeout) {\n clearTimeout(this.timeout);\n }\n\n this.timeout = setTimeout(() => {\n this.promisedCount++; // after execution started any new call will get a new promise\n const requestAttrs = [...this.requestSet];\n this.requestSet.clear(); // clear optimistically assuming successful results\n this.fn(requestAttrs)\n .then((results) => {\n resolve(results);\n this.debounceCancel = () => {};\n })\n .catch((reason) => {\n if (\n reason.response &&\n reason.response.data &&\n reason.response.data.error\n ) {\n reason = reason.response.data.error;\n }\n reject(reason);\n });\n }, this.wait);\n\n this.debounceCancel = () => {\n if (this.timeout) {\n clearTimeout(this.timeout);\n }\n reject('Cancelled');\n delete this.promisedCalls[this.promisedCount];\n };\n\n return promise;\n }\n}\n","import {\n BigNumber,\n BigNumberish,\n parseFixed as _parseFixed,\n formatFixed as _formatFixed,\n} from '@ethersproject/bignumber';\n\nexport function parseFixed(value: string, decimals?: BigNumberish): BigNumber {\n const valueWithTrimmedDecimals = new RegExp(`[0-9]+\\\\.?[0-9]{0,${decimals}}`);\n const result = value.match(valueWithTrimmedDecimals);\n let parsedValue = value;\n if (result) {\n parsedValue = result[0];\n }\n\n return _parseFixed(parsedValue, decimals);\n}\n\nexport function formatFixed(value: BigNumber, decimals: BigNumberish): string {\n const ethersFormat = _formatFixed(value, decimals);\n return ethersFormat.replace(/(.0$)/, '');\n}\n\nexport function parseToBigInt18(value: string): bigint {\n return parseFixed(value, 18).toBigInt();\n}\n\nexport function formatFromBigInt18(value: bigint): string {\n return _formatFixed(BigNumber.from(value), 18);\n}\n\n/**\n * Like parseEther but for numbers. Converts floating point to BigNumber using 18 decimals\n */\nexport const bn = (value: number): BigNumber => _parseFixed(`${value}`, 18);\n","import { getAddress } from '@ethersproject/address';\n\nexport * from './aaveHelpers';\nexport * from './assetHelpers';\nexport * from './errors';\nexport * from './permit';\nexport * from './poolHelper';\nexport * from './signatures';\nexport * from './tokens';\nexport * from './debouncer';\nexport * from './math';\n\nexport const isSameAddress = (address1: string, address2: string): boolean =>\n getAddress(address1) === getAddress(address2);\n\nexport function insert<T>(arr: T[], index: number, newItem: T): T[] {\n return [\n // part of the array before the specified index\n ...arr.slice(0, index),\n // inserted item\n newItem,\n // part of the array after the specified index\n ...arr.slice(index),\n ];\n}\n","import { GraphQLArgs, GraphQLArgsFormatter } from '../types';\n\nexport class BalancerAPIArgsFormatter implements GraphQLArgsFormatter {\n format(args: GraphQLArgs): GraphQLArgs {\n return args;\n }\n}\n","import { GraphQLArgs, GraphQLArgsFormatter, GraphQLFilter } from '../types';\n\nexport class SubgraphArgsFormatter implements GraphQLArgsFormatter {\n operatorMap: Record<string, string>;\n\n constructor() {\n this.operatorMap = {\n gt: '_gt',\n lt: '_lt',\n eq: '',\n in: '_in',\n not_in: '_not_in',\n contains: '_contains',\n };\n }\n\n format(args: GraphQLArgs): GraphQLArgs {\n const whereQuery: Record<string, GraphQLFilter> = {};\n if (args.where) {\n Object.entries(args.where).forEach(([name, filter]) => {\n Object.entries(filter).forEach(([operator, value]) => {\n whereQuery[`${name}${this.operatorMap[operator]}`] = value;\n });\n });\n }\n\n return {\n ...args,\n ...{ where: whereQuery },\n };\n }\n}\n","import { mergeWith } from 'lodash';\nimport { GraphQLArgs, GraphQLArgsFormatter } from './types';\n\nexport * from './formatters';\n\nexport class GraphQLArgsBuilder {\n constructor(readonly args: GraphQLArgs) {}\n\n merge(other: GraphQLArgsBuilder): GraphQLArgsBuilder {\n const mergedArgs = mergeWith(\n this.args,\n other.args,\n (objValue: unknown, srcValue: unknown) => {\n if (Array.isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n\n return new GraphQLArgsBuilder(mergedArgs);\n }\n\n format(formatter: GraphQLArgsFormatter): unknown {\n return formatter.format(this.args);\n }\n}\n","import { SwapInfo } from '@defiverse/sor';\nimport { Vault } from '@balancer-labs/typechain';\nimport { BigNumber, BigNumberish } from '@ethersproject/bignumber';\n\nexport enum SwapType {\n SwapExactIn,\n SwapExactOut,\n}\n\nexport type FundManagement = {\n sender: string;\n recipient: string;\n fromInternalBalance: boolean;\n toInternalBalance: boolean;\n};\n\nexport type SingleSwap = {\n poolId: string;\n kind: SwapType;\n assetIn: string;\n assetOut: string;\n amount: BigNumberish;\n userData: string;\n};\n\nexport type Swap = {\n request: SingleSwap;\n funds: FundManagement;\n limit: BigNumberish;\n deadline: BigNumberish;\n value?: BigNumberish;\n outputReference?: BigNumberish;\n};\n\nexport type BatchSwapStep = {\n poolId: string;\n assetInIndex: number;\n assetOutIndex: number;\n amount: string;\n userData: string;\n};\n\nexport type BatchSwap = {\n kind: SwapType;\n swaps: BatchSwapStep[];\n assets: string[];\n funds: FundManagement;\n limits: BigNumberish[];\n deadline: BigNumberish;\n value?: BigNumberish;\n outputReferences?: { index: BigNumberish; key: BigNumberish }[];\n};\n\nexport interface FetchPoolsInput {\n fetchPools: boolean;\n fetchOnChain: boolean;\n}\n\nexport interface QueryWithSorInput {\n tokensIn: string[];\n tokensOut: string[];\n swapType: SwapType;\n amounts: string[];\n fetchPools: FetchPoolsInput;\n}\n\nexport interface SwapInput {\n tokenIn: string;\n tokenOut: string;\n swapType: SwapType;\n amount: string;\n}\n\nexport interface QueryWithSorOutput {\n returnAmounts: string[];\n swaps: BatchSwapStep[];\n assets: string[];\n deltas: string[];\n}\n\nexport interface QuerySimpleFlashSwapParameters {\n poolIds: string[];\n assets: BatchSwap['assets'];\n flashLoanAmount: string;\n vaultContract: Vault;\n}\n\nexport interface SimpleFlashSwapParameters {\n poolIds: string[];\n assets: BatchSwap['assets'];\n flashLoanAmount: string;\n walletAddress: string;\n}\n\nexport interface QuerySimpleFlashSwapResponse {\n profits: Record<string, string>;\n isProfitable: boolean;\n}\n\nexport interface FindRouteParameters {\n tokenIn: string;\n tokenOut: string;\n amount: BigNumber;\n gasPrice: BigNumber;\n maxPools: number;\n}\n\nexport interface BuildTransactionParameters {\n userAddress: string;\n recipient?: string;\n swapInfo: SwapInfo;\n kind: SwapType;\n deadline: BigNumber;\n maxSlippage: number;\n}\n\nexport interface SwapTransactionRequest {\n to: string;\n data: string;\n value?: BigNumber;\n}\n\nexport interface SwapAttributes {\n to: string;\n functionName: string;\n attributes: Swap | BatchSwap;\n data: string;\n value?: BigNumber;\n}\n","import { BigNumberish, BigNumber } from '@ethersproject/bignumber';\nimport { Zero, WeiPerEther } from '@ethersproject/constants';\n\nimport { SwapType } from './types';\nimport { isSameAddress } from '@/lib/utils';\n\n/**\n * Helper to create limits using a defined slippage amount.\n * @param tokensIn - Array of token in addresses.\n * @param tokensOut - Array of token out addresses.\n * @param swapType - Type of swap - SwapExactIn or SwapExactOut\n * @param deltas - An array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at the same index in the `assets` array.\n * @param assets - array contains the addresses of all assets involved in the swaps.\n * @param slippage - Slippage to be applied. i.e. 5%=50000000000000000.\n * @returns Returns an array (same length as assets) with limits applied for each asset.\n */\nexport function getLimitsForSlippage(\n tokensIn: string[],\n tokensOut: string[],\n swapType: SwapType,\n deltas: BigNumberish[],\n assets: string[],\n slippage: BigNumberish\n): BigNumberish[] {\n // Limits:\n // +ve means max to send\n // -ve mean min to receive\n // For a multihop the intermediate tokens should be 0\n const limits: BigNumber[] = new Array(assets.length).fill(Zero);\n\n assets.forEach((token, i) => {\n if (tokensIn.some((tokenIn) => isSameAddress(token, tokenIn))) {\n // For SwapExactOut slippage is on tokenIn, i.e. amtIn + slippage\n const slippageAmount = BigNumber.from(slippage).add(WeiPerEther);\n limits[i] =\n swapType === SwapType.SwapExactOut\n ? limits[i].add(\n BigNumber.from(deltas[i]).mul(slippageAmount).div(WeiPerEther)\n )\n : limits[i].add(deltas[i]);\n }\n\n if (tokensOut.some((tokenOut) => isSameAddress(token, tokenOut))) {\n // For SwapExactIn slippage is on tokenOut, i.e. amtOut - slippage\n const slippageAmount = WeiPerEther.sub(BigNumber.from(slippage));\n limits[i] =\n swapType === SwapType.SwapExactIn\n ? limits[i].add(\n BigNumber.from(deltas[i]).mul(slippageAmount).div(WeiPerEther)\n )\n : limits[i].add(deltas[i]);\n }\n });\n\n return limits;\n}\n","import { BigNumber } from '@ethersproject/bignumber';\n\nconst bpsPerOne = BigNumber.from('10000'); // number of basis points in 100%\n\n/**\n * Multiplies input by slippage amount\n *\n * @param {BigNumber} amount Input amount (not parsed)\n * @param {BigNumber} slippage Slippage value in bps - i.e. 50 = 0.5%\n * @returns Result delta from multiplying amount and slippage\n */\nexport const mulSlippage = (\n amount: BigNumber,\n slippage: BigNumber\n): BigNumber => {\n const delta = amount.mul(slippage).div(bpsPerOne);\n return delta;\n};\n\n/**\n * Reduce input amount by slippage factor\n *\n * @param {BigNumber} amount Input in EVM amounts\n * @param {BigNumber} slippage Slippage value in bps - i.e. 50 = 0.5%\n * @returns Result amount subtracting slippage\n */\nexport const subSlippage = (\n amount: BigNumber,\n slippage: BigNumber\n): BigNumber => {\n const delta = mulSlippage(amount, slippage);\n return amount.sub(delta);\n};\n\n/**\n * Increase input amount by slippage factor\n *\n * @param {BigNumber} amount Input in EVM amounts\n * @param {BigNumber} slippage Slippage value in bps - i.e. 50 = 0.5%\n * @returns Result amount adding slippage\n */\nexport const addSlippage = (\n amount: BigNumber,\n slippage: BigNumber\n): BigNumber => {\n const delta = mulSlippage(amount, slippage);\n return amount.add(delta);\n};\n","import { Network } from './network';\nimport { BalancerNetworkConfig } from '@/types';\n\n// export const balancerVault = '0xBA12222222228d8Ba445958a75a0704d566BF2C8';\n// export const balancerVault = '0xef570b45a20e9bDe7855BDF5940Be3ac17B4c610';\nexport const balancerVault = '0x2FA699664752B34E90A414A42D62D7A8b2702B85';\n\nexport const BALANCER_NETWORK_CONFIG: Record<Network, BalancerNetworkConfig> = {\n [Network.MAINNET]: {\n chainId: Network.MAINNET, //1\n addresses: {\n contracts: {\n vault: '0xBA12222222228d8Ba445958a75a0704d566BF2C8',\n multicall: '0xeefba1e63905ef1d7acba5a8513c70307c1ce441',\n balancerHelpers: '0x5aDDCCa35b7A0D07C74063c48700C8590E87864E',\n lidoRelayer: '0xdcdbf71A870cc60C6F9B621E28a7D3Ffd6Dd4965',\n relayerV3: '0x886A3Ec7bcC508B8795990B60Fa21f85F9dB7948',\n relayerV4: '0x2536dfeeCB7A0397CF98eDaDA8486254533b1aFA',\n gaugeController: '0xc128468b7ce63ea702c1f104d55a2566b13d3abd',\n feeDistributor: '0xD3cf852898b21fc233251427c2DC93d3d604F3BB',\n protocolFeePercentagesProvider:\n '0x97207B095e4D5C9a6e4cfbfcd2C3358E03B90c4A',\n veBal: '0xC128a9954e6c874eA3d62ce62B468bA073093F25',\n veBalProxy: '0x6f5a2eE11E7a772AeB5114A20d0D7c0ff61EB8A0',\n weightedPoolFactory: '0x8E9aa87E45e92bad84D5F8DD1bff34Fb92637dE9',\n composableStablePoolFactory:\n '0x85a80afee867adf27b50bdb7b76da70f1e853062',\n },\n tokens: {\n wrappedNativeAsset: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n lbpRaisingTokens: [\n '0x6B175474E89094C44Da98b954EedeAC495271d0F',\n '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n ],\n stETH: '0xae7ab96520de3a18e5e111b5eaab095312d7fe84',\n wstETH: '0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0',\n bal: '0xba100000625a3754423978a60c9317c58a424e3d',\n veBal: '0xC128a9954e6c874eA3d62ce62B468bA073093F25',\n bbaUsd: '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb2',\n },\n },\n urls: {\n subgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-v2',\n gaugesSubgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-gauges',\n blockNumberSubgraph:\n 'https://api.thegraph.com/subgraphs/name/blocklytics/ethereum-blocks',\n },\n pools: {\n wETHwstETH: {\n id: '0x32296969ef14eb0c6d29669c550d4a0449130230000200000000000000000080',\n address: '0x32296969ef14eb0c6d29669c550d4a0449130230',\n },\n },\n poolsToIgnore: [\n '0xbd482ffb3e6e50dc1c437557c3bea2b68f3683ee', // a pool made by an external dev who was playing with a novel rate provider mechanism in production.\n ],\n sorConnectingTokens: [\n {\n symbol: 'wEth',\n address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n },\n {\n symbol: 'wstEth',\n address: '0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0',\n },\n {\n symbol: 'DOLA',\n address: '0x865377367054516e17014CcdED1e7d814EDC9ce4',\n },\n ],\n },\n [Network.POLYGON]: {\n chainId: Network.POLYGON, //137\n addresses: {\n contracts: {\n vault: '0xBA12222222228d8Ba445958a75a0704d566BF2C8',\n multicall: '0xa1B2b503959aedD81512C37e9dce48164ec6a94d',\n relayerV3: '0xcf6a66E32dCa0e26AcC3426b851FD8aCbF12Dac7',\n relayerV4: '0x28A224d9d398a1eBB7BA69BCA515898966Bb1B6b',\n balancerHelpers: '0x239e55F427D44C3cc793f49bFB507ebe76638a2b',\n weightedPoolFactory: '0x0e39C3D9b2ec765eFd9c5c70BB290B1fCD8536E3',\n composableStablePoolFactory:\n '0x85a80afee867adf27b50bdb7b76da70f1e853062',\n },\n tokens: {\n bal: '0x9a71012b13ca4d3d0cdc72a177df3ef03b0e76a3',\n wrappedNativeAsset: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',\n },\n },\n urls: {\n subgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-polygon-prune-v2',\n gaugesSubgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-gauges-polygon',\n blockNumberSubgraph:\n 'https://api.thegraph.com/subgraphs/name/ianlapham/polygon-blocks',\n },\n pools: {},\n poolsToIgnore: [\n '0x600bd01b6526611079e12e1ff93aba7a3e34226f', // This pool has rateProviders with incorrect scaling\n ],\n sorConnectingTokens: [\n {\n symbol: 'weth',\n address: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',\n },\n {\n symbol: 'bbrz2',\n address: '0xe22483774bd8611be2ad2f4194078dac9159f4ba',\n }, // Joins Stables<>BRZ via https://app.balancer.fi/#/polygon/pool/0x4a0b73f0d13ff6d43e304a174697e3d5cfd310a400020000000000000000091c\n ],\n },\n [Network.ARBITRUM]: {\n chainId: Network.ARBITRUM, //42161\n addresses: {\n contracts: {\n vault: '0xBA12222222228d8Ba445958a75a0704d566BF2C8',\n multicall: '0x269ff446d9892c9e19082564df3f5e8741e190a1',\n relayerV3: '0x42E49B48573c725ee32d2579060Ed06894f97002',\n relayerV4: '0x5bf3B7c14b10f16939d63Bd679264A1Aa951B4D5',\n balancerHelpers: '0x77d46184d22CA6a3726a2F500c776767b6A3d6Ab',\n weightedPoolFactory: '0x8df6EfEc5547e31B0eb7d1291B511FF8a2bf987c',\n composableStablePoolFactory:\n '0x85a80afee867adf27b50bdb7b76da70f1e853062',\n },\n tokens: {\n bal: '0x040d1edc9569d4bab2d15287dc5a4f10f56a56b8',\n wrappedNativeAsset: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',\n },\n },\n urls: {\n subgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-arbitrum-v2',\n gaugesSubgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-gauges-arbitrum',\n blockNumberSubgraph:\n 'https://api.thegraph.com/subgraphs/name/ianlapham/arbitrum-one-blocks',\n },\n pools: {},\n sorConnectingTokens: [\n {\n symbol: 'weth',\n address: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',\n },\n ],\n },\n [Network.KOVAN]: {\n chainId: Network.KOVAN, //42\n addresses: {\n contracts: {\n vault: '0xBA12222222228d8Ba445958a75a0704d566BF2C8',\n multicall: '0x2cc8688C5f75E365aaEEb4ea8D6a480405A48D2A',\n veBal: '0x16ba924752EF283C7946db8A122a6742AA35C1DC',\n veBalProxy: '0x98D0d0a65cBeCCaa647a5a95cf27Cf2f00E1231C',\n balancerHelpers: '0x94905e703fEAd7f0fD0eEe355D267eE909784e6d',\n weightedPoolFactory: '0x8df6EfEc5547e31B0eb7d1291B511FF8a2bf987c',\n },\n tokens: {\n wrappedNativeAsset: '0xdFCeA9088c8A88A76FF74892C1457C17dfeef9C1',\n },\n },\n urls: {\n subgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-kovan-v2',\n gaugesSubgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-gauges',\n },\n pools: {},\n },\n [Network.ROPSTEN]: {\n chainId: Network.ROPSTEN, //3\n addresses: {\n contracts: {\n vault: '0xBA12222222228d8Ba445958a75a0704d566BF2C8',\n multicall: '0x53c43764255c17bd724f74c4ef150724ac50a3ed',\n balancerHelpers: '',\n },\n tokens: {\n wrappedNativeAsset: '0xdFCeA9088c8A88A76FF74892C1457C17dfeef9C1',\n },\n },\n urls: {\n subgraph: '',\n gaugesSubgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-gauges',\n },\n pools: {},\n },\n [Network.RINKEBY]: {\n chainId: Network.RINKEBY, //4\n addresses: {\n contracts: {\n vault: '0xBA12222222228d8Ba445958a75a0704d566BF2C8',\n multicall: '0x42ad527de7d4e9d9d011ac45b31d8551f8fe9821',\n balancerHelpers: '0x5aDDCCa35b7A0D07C74063c48700C8590E87864E',\n weightedPoolFactory: '0x8df6EfEc5547e31B0eb7d1291B511FF8a2bf987c',\n },\n tokens: {\n wrappedNativeAsset: '0xdFCeA9088c8A88A76FF74892C1457C17dfeef9C1',\n },\n },\n urls: {\n subgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-rinkeby-v2',\n gaugesSubgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-gauges',\n },\n pools: {},\n },\n [Network.GOERLI]: {\n chainId: Network.GOERLI, //5\n addresses: {\n contracts: {\n vault: '0xBA12222222228d8Ba445958a75a0704d566BF2C8',\n multicall: '0x77dCa2C955b15e9dE4dbBCf1246B4B85b651e50e',\n relayerV3: '0x7b9B6f094DC2Bd1c12024b0D9CC63d6993Be1888',\n relayerV4: '0x00e695aA8000df01B8DC8401B4C34Fba5D56BBb2',\n gaugeController: '0xBB1CE49b16d55A1f2c6e88102f32144C7334B116',\n veBal: '0x33A99Dcc4C85C014cf12626959111D5898bbCAbF',\n veBalProxy: '0xA1F107D1cD709514AE8A914eCB757E95f9cedB31',\n balancerHelpers: '0x5aDDCCa35b7A0D07C74063c48700C8590E87864E',\n weightedPoolFactory: '0x8E9aa87E45e92bad84D5F8DD1bff34Fb92637dE9',\n composableStablePoolFactory:\n '0x85a80afee867adf27b50bdb7b76da70f1e853062',\n },\n tokens: {\n wrappedNativeAsset: '0xdFCeA9088c8A88A76FF74892C1457C17dfeef9C1',\n },\n },\n urls: {\n subgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-goerli-v2',\n gaugesSubgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-gauges-goerli',\n blockNumberSubgraph:\n 'https://api.thegraph.com/subgraphs/name/blocklytics/goerli-blocks',\n },\n pools: {},\n sorConnectingTokens: [\n {\n symbol: 'weth',\n address: '0xdFCeA9088c8A88A76FF74892C1457C17dfeef9C1',\n },\n ],\n },\n [Network.OPTIMISM]: {\n chainId: Network.OPTIMISM, //10\n addresses: {\n contracts: {\n vault: '0xBA12222222228d8Ba445958a75a0704d566BF2C8',\n multicall: '0x2dc0e2aa608532da689e89e237df582b783e552c',\n relayerV3: '0x195CcCBE464EF9073d1f7A1ba1C9Bf0f56dfFFff',\n relayerV4: '0x1a58897Ab366082028ced3740900ecBD765Af738',\n balancerHelpers: '0x8E9aa87E45e92bad84D5F8DD1bff34Fb92637dE9',\n weightedPoolFactory: '0x0e39C3D9b2ec765eFd9c5c70BB290B1fCD8536E3',\n composableStablePoolFactory:\n '0x85a80afee867adf27b50bdb7b76da70f1e853062',\n },\n tokens: {\n wrappedNativeAsset: '0x4200000000000000000000000000000000000006',\n },\n },\n urls: {\n subgraph:\n 'https://api.thegraph.com/subgraphs/name/beethovenxfi/beethovenx-optimism',\n gaugesSubgraph: '',\n },\n pools: {},\n sorConnectingTokens: [\n {\n symbol: 'weth',\n address: '0x4200000000000000000000000000000000000006',\n },\n ],\n },\n [Network.GNOSIS]: {\n chainId: Network.GNOSIS, //100\n addresses: {\n contracts: {\n vault: '0xBA12222222228d8Ba445958a75a0704d566BF2C8',\n multicall: '0xbb6fab6b627947dae0a75808250d8b2652952cb5',\n relayerV4: '0xeF606F58A4FD0fCcb066c6203d0994694d3eB2D3',\n balancerHelpers: '0x8E9aa87E45e92bad84D5F8DD1bff34Fb92637dE9',\n weightedPoolFactory: '0xf302f9F50958c5593770FDf4d4812309fF77414f',\n composableStablePoolFactory:\n '0x76578ecf9a141296ec657847fb45b0585bcda3a6',\n },\n tokens: {\n wrappedNativeAsset: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d',\n },\n },\n urls: {\n subgraph:\n 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-gnosis-chain-v2',\n gaugesSubgraph: '',\n },\n pools: {},\n sorConnectingTokens: [\n {\n symbol: 'weth',\n address: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d',\n },\n ],\n },\n [Network.DEFIVERSE]: {\n chainId: Network.DEFIVERSE, //16116\n addresses: {\n contracts: {\n vault: '0x2FA699664752B34E90A414A42D62D7A8b2702B85',\n multicall: '0x8633dD7223f76c99bdc5a2D116FCF369d79852C4', // NEED CONFIRM\n relayerV4: '0x00e695aA8000df01B8DC8401B4C34Fba5D56BBb2', // NEED CONFIRM\n gaugeController: '',\n feeDistributor: '',\n protocolFeePercentagesProvider:\n '0xC462175C87672c7aad536c1248b72B1Cf46BEe27',\n veBal: '',\n veBalProxy: '',\n balancerHelpers: '0x4087EDb699803608A0214FD92e32119CAF57EcA3',\n //weightedPoolFactory: '0xE952b0409e6768E270A671ebbC5b8605a7C5A0B8',\n weightedPoolFactory: '0xD1920DD25e4998B0d7cC8de7F12BeAf9796C7475', // 2025-02-04\n composableStablePoolFactory:\n '0xD01ad3085fb3e1fbB2541b5B3326B1F47B189747',\n },\n tokens: {\n wrappedNativeAsset: '0x5a89E11Cb554E00c2f51C4bb7F05bc7Ab0Fa6351',\n bal: '',\n veBal: '',\n },\n },\n urls: {\n priceUrl: 'https://price-api.gaming-dex.com/api/v1',\n subgraph:\n 'https://graphnode.defi-verse.org/subgraphs/name/balancer-labs/defiverse',\n gaugesSubgraph:\n 'https://graphnode.defi-verse.org/subgraphs/name/balancer-labs/gauges-defiverse',\n },\n pools: {},\n sorConnectingTokens: [\n {\n symbol: 'weth',\n address: '0x5a89E11Cb554E00c2f51C4bb7F05bc7Ab0Fa6351',\n },\n ],\n },\n [Network.DEFIVERSE_TESTNET]: {\n chainId: Network.DEFIVERSE_TESTNET, //17117\n addresses: {\n contracts: {\n vault: '0x2Da016a77E290fb82F5af7051198304d57779f5d',\n multicall: '0xEB47269E97EeDB20EF782EB8caFb09ed55b02A39', // NEED CONFIRM\n relayerV4: '0x00e695aA8000df01B8DC8401B4C34Fba5D56BBb2', // NEED CONFIRM\n gaugeController: '',\n feeDistributor: '',\n protocolFeePercentagesProvider:\n '0x38d04d161247031484B31fB8403D20bed5287cf7',\n veBal: '',\n veBalProxy: '',\n balancerHelpers: '0x47404b46E0340F879ECC15977Ce196458cadc2DF',\n //weightedPoolFactory: '0xaB6BaC0f5F4C7C166C5234B528a1cD46Fbcb9F4B',\n weightedPoolFactory: '0x48494Fa9eAd46EE8E3FcB66487a6dBBD34DcAFe3', // no admin role\n composableStablePoolFactory:\n '0x58e6F99bB65378f47A520fC9630Bd711f2cf3Dc7',\n },\n tokens: {\n wrappedNativeAsset: '0x6B382742b07AAbBA58c38d792B5d7CBAaB246e99',\n bal: '0xb5C5C48D3082751f60EE1CAc8FC84a921931EC24',\n // veBal: '0x9Ba4a34cF63eFBf66c4d6a36470632b7D5511864',\n },\n },\n urls: {\n priceUrl: 'https://price-api-testnet.gaming-dex.com/api/v1',\n subgraph:\n 'https://graphnode-testnet.defi-verse.org/subgraphs/name/balancer-labs/defiverse-testnet-v2',\n gaugesSubgraph:\n 'https://graphnode-testnet.defi-verse.org/subgraphs/name/balancer-labs/gauges-defiverse-testnet-v2',\n },\n pools: {},\n sorConnectingTokens: [\n {\n symbol: 'weth',\n address: '0x6B382742b07AAbBA58c38d792B5d7CBAaB246e99',\n },\n ],\n },\n [Network.OASYS]: {\n chainId: Network.OASYS, //248\n addresses: {\n contracts: {\n vault: '0xfb6f8FEdE0Cb63674Ab964affB93D65a4a7D55eA',\n multicall: '0xc52dc4a7dad06BEAB9230D482AcBEcFFc3aB009B', // NEED CONFIRM\n relayerV4: '0x00e695aA8000df01B8DC8401B4C34Fba5D56BBb2', // NEED CONFIRM\n // gaugeController: '0x24df42CeCD0C24A35171FD21662FA44dad9C9B5E',\n // gaugeController: '0x2010fA63Eb1Edb6Ff9299De507E613cc05729de6',\n // gaugeController: '0x8e7C11EFEdf91a7E0Dc6f6330f62477F73d04470',\n gaugeController: '0x2D2BB676EfE00998ABf25aa499A19af16cC99F3e',\n feeDistributor: '0xE93F762E0d736fB2780bb9271233367942189B86',\n protocolFeePercentagesProvider:\n '0x56C181Ecf83e773978137b2B567d660768f8c8e3',\n veBal: '0x2B726256AdD04e65403cEf6679A2f2dfF7DDe9F9',\n veBalProxy: '0xe5276B39E604999c05d3051D896310A620E4Cc49',\n balancerHelpers: '0xf199DDb57d75225e13Fe13eb8BDDE8b16e188374',\n // weightedPoolFactory: '0x5737600b98E7F1cf98dAca2a36bCa22C974370b0',\n weightedPoolFactory: '0x4EF0b4827cE3D5FEcBc2C6ab80Ee81dBF9631D37', // 2025-02-04\n composableStablePoolFactory:\n '0x0A7A98c9553192755f22b282278f0FA26f4de742',\n },\n tokens: {\n wrappedNativeAsset: '0x5200000000000000000000000000000000000001',\n bal: '0x2B726256AdD04e65403cEf6679A2f2dfF7DDe9F9',\n veBal: '0x2B726256AdD04e65403cEf6679A2f2dfF7DDe9F9',\n },\n },\n urls: {\n priceUrl: 'https://price-api.gaming-dex.com/api/v1',\n subgraph:\n 'https://graphnode-oasys.defi-verse.org/subgraphs/name/balancer-labs/oasys',\n gaugesSubgraph:\n 'https://graphnode-oasys.defi-verse.org/subgraphs/name/balancer-labs/gauges-oasys',\n },\n pools: {},\n sorConnectingTokens: [\n {\n symbol: 'weth',\n address: '0x5200000000000000000000000000000000000001',\n },\n ],\n },\n [Network.OASYS_TESTNET]: {\n chainId: Network.OASYS_TESTNET, //16116\n addresses: {\n contracts: {\n vault: '0x1f7a0Bea1CB70FaA0f6b7B1126eCbd01Ef4E5BC8',\n multicall: '0xe5Fce05D922e3961F053bD2BF1F29F92d2a0a94B', // NEED CONFIRM\n relayerV4: '0x00e695aA8000df01B8DC8401B4C34Fba5D56BBb2', // NEED CONFIRM\n gaugeController: '0x82e3ACEE6e747B164327cca5e6309bb38f114848',\n feeDistributor: '0x8A55C4F4f178d62Da281c244e4AD98A9C72c418a',\n protocolFeePercentagesProvider:\n '0xACA587e675102f0fDcBc9FddC441f820cB2c64b9',\n veBal: '0x9288F664FEFc9f374A53C4307BD3c8F91e83f466',\n veBalProxy: '0x0b205Ed28BC51E7DE4686ef725488bCecEe87606',\n balancerHelpers: '0x3B847f3Fa5585Dc3aeDB40780fF47e31B0fF14C0',\n // weightedPoolFactory: '0x900c1Bc6a6915Ed153c18763e4B8aE8133E839f1',\n weightedPoolFactory: '0xd2d7F457B9749B6A0A637685A65681F03116125C', // no admin role\n composableStablePoolFactory:\n '0xfDA8fa80dd77A99BF71BeCFce47077859e689898',\n },\n tokens: {\n wrappedNativeAsset: '0x5200000000000000000000000000000000000001',\n bal: '0x9288F664FEFc9f374A53C4307BD3c8F91e83f466',\n veBal: '0x9288F664FEFc9f374A53C4307BD3c8F91e83f466',\n },\n },\n urls: {\n priceUrl: 'https://price-api-testnet.gaming-dex.com/api/v1',\n subgraph:\n 'https://graphnode-oasys-testnet.defi-verse.org/subgraphs/name/balancer-labs/oasys-testnet',\n gaugesSubgraph:\n 'https://graphnode-oasys-testnet.defi-verse.org/subgraphs/name/balancer-labs/gauges-oasys-testnet-v2',\n },\n pools: {},\n sorConnectingTokens: [\n {\n symbol: 'weth',\n address: '0x5200000000000000000000000000000000000001',\n },\n ],\n },\n};\n\nexport const networkAddresses = (\n chainId: number\n): BalancerNetworkConfig['addresses'] =>\n BALANCER_NETWORK_CONFIG[chainId as Network].addresses;\n","export enum BalancerErrorCode {\n SWAP_ZERO_RETURN_AMOUNT = 'SWAP_ZERO_RETURN_AMOUNT',\n UNWRAP_ZERO_AMOUNT = 'UNWRAP_ZERO_AMOUNT',\n WRAP_ZERO_AMOUNT = 'WRAP_ZERO_AMOUNT',\n QUERY_BATCH_SWAP = 'QUERY_BATCH_SWAP',\n POOL_DOESNT_EXIST = 'POOL_DOESNT_EXIST',\n UNSUPPORTED_POOL_TYPE = 'UNSUPPORTED_POOL_TYPE',\n UNSUPPORTED_PAIR = 'UNSUPPORTED_PAIR',\n NO_POOL_DATA = 'NO_POOL_DATA',\n INPUT_OUT_OF_BOUNDS = 'INPUT_OUT_OF_BOUNDS',\n INPUT_LENGTH_MISMATCH = 'INPUT_LENGTH_MISMATCH',\n INPUT_TOKEN_INVALID = 'INPUT_TOKEN_INVALID',\n INPUT_ZERO_NOT_ALLOWED = 'INPUT_ZERO_NOT_ALLOWED',\n INTERNAL_ERROR_INVALID_ABI = 'INTERNAL_ERROR_INVALID_ABI',\n TOKEN_MISMATCH = 'TOKEN_MISMATCH',\n MISSING_TOKENS = 'MISSING_TOKENS',\n MISSING_AMP = 'MISSING_AMP',\n MISSING_DECIMALS = 'MISSING_DECIMALS',\n MISSING_PRICE_RATE = 'MISSING_PRICE_RATE',\n MISSING_WEIGHT = 'MISSING_WEIGHT',\n RELAY_SWAP_AMOUNTS = 'RELAY_SWAP_AMOUNTS',\n NO_VALUE_PARAMETER = 'NO_VALUE_PARAMETER',\n ILLEGAL_PARAMETER = 'ILLEGAL_PARAMETER',\n TIMESTAMP_IN_THE_FUTURE = 'TIMESTAMP_IN_THE_FUTURE',\n JOIN_DELTA_AMOUNTS = 'JOIN_DELTA_AMOUNTS',\n EXIT_DELTA_AMOUNTS = 'EXIT_DELTA_AMOUNTS',\n}\n\nexport class BalancerError extends Error {\n constructor(public code: BalancerErrorCode) {\n super(BalancerError.getMessage(code));\n this.name = 'BalancerError';\n }\n\n static getMessage(code: BalancerErrorCode): string {\n switch (code) {\n case BalancerErrorCode.SWAP_ZERO_RETURN_AMOUNT:\n return 'queryBatchSwapWithSor returned 0 amount';\n case BalancerErrorCode.UNWRAP_ZERO_AMOUNT:\n return 'swapUnwrapAaveStaticExactIn unwrapped amount < 0';\n case BalancerErrorCode.WRAP_ZERO_AMOUNT:\n return 'swapUnwrapAaveStaticExactOut wrapped amount < 0';\n case BalancerErrorCode.QUERY_BATCH_SWAP:\n return 'queryBatchSwap on chain call error';\n case BalancerErrorCode.POOL_DOESNT_EXIST:\n return 'balancer pool does not exist';\n case BalancerErrorCode.UNSUPPORTED_POOL_TYPE:\n return 'unsupported pool type';\n case BalancerErrorCode.UNSUPPORTED_PAIR:\n return 'unsupported token pair';\n case BalancerErrorCode.NO_POOL_DATA:\n return 'no pool data';\n case BalancerErrorCode.INPUT_OUT_OF_BOUNDS:\n return 'input out of bounds';\n case BalancerErrorCode.INPUT_LENGTH_MISMATCH:\n return 'input length mismatch';\n case BalancerErrorCode.INPUT_TOKEN_INVALID:\n return 'input token invalid';\n case BalancerErrorCode.TOKEN_MISMATCH:\n return 'token mismatch';\n case BalancerErrorCode.MISSING_DECIMALS:\n return 'missing decimals';\n case BalancerErrorCode.MISSING_TOKENS:\n return 'missing tokens';\n case BalancerErrorCode.MISSING_AMP:\n return 'missing amp';\n case BalancerErrorCode.MISSING_PRICE_RATE:\n return 'missing price rate';\n case BalancerErrorCode.MISSING_WEIGHT:\n return 'missing weight';\n case BalancerErrorCode.INPUT_ZERO_NOT_ALLOWED:\n return 'zero input not allowed';\n case BalancerErrorCode.RELAY_SWAP_AMOUNTS:\n return 'Error when checking swap amounts';\n case BalancerErrorCode.NO_VALUE_PARAMETER:\n return 'Illegal value passed as parameter';\n case BalancerErrorCode.TIMESTAMP_IN_THE_FUTURE:\n return 'Timestamp cannot be in the future';\n case BalancerErrorCode.ILLEGAL_PARAMETER:\n return 'An illegal parameter has been passed';\n case BalancerErrorCode.JOIN_DELTA_AMOUNTS:\n return 'Error when checking join call deltas';\n case BalancerErrorCode.EXIT_DELTA_AMOUNTS:\n return 'Error when checking exit call deltas';\n default:\n return 'Unknown error';\n }\n }\n}\n","import { BigNumber, parseFixed } from '@ethersproject/bignumber';\nimport { AddressZero } from '@ethersproject/constants';\nimport * as SOR from '@defiverse/sor';\nimport {\n ExitConcern,\n ExitExactBPTInAttributes,\n ExitExactTokensOutAttributes,\n ExitExactBPTInParameters,\n ExitExactTokensOutParameters,\n ExitPool,\n} from '../types';\nimport { AssetHelpers, isSameAddress, parsePoolInfo } from '@/lib/utils';\nimport { Vault__factory } from '@balancer-labs/typechain';\nimport { addSlippage, subSlippage } from '@/lib/utils/slippageHelper';\nimport { balancerVault } from '@/lib/constants/config';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { StablePoolEncoder } from '@/pool-stable';\nimport { _downscaleDownArray, _upscaleArray } from '@/lib/utils/solidityMaths';\n\nexport class StablePoolExit implements ExitConcern {\n buildExitExactBPTIn = ({\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut,\n }: ExitExactBPTInParameters): ExitExactBPTInAttributes => {\n if (!bptIn.length || parseFixed(bptIn, 18).isNegative()) {\n throw new BalancerError(BalancerErrorCode.INPUT_OUT_OF_BOUNDS);\n }\n if (\n singleTokenMaxOut &&\n singleTokenMaxOut !== AddressZero &&\n !pool.tokens\n .map((t) => t.address)\n .some((a) => isSameAddress(a, singleTokenMaxOut))\n ) {\n throw new BalancerError(BalancerErrorCode.TOKEN_MISMATCH);\n }\n\n if (!shouldUnwrapNativeAsset && singleTokenMaxOut === AddressZero)\n throw new Error(\n 'shouldUnwrapNativeAsset and singleTokenMaxOut should not have conflicting values'\n );\n\n // Check if there's any relevant stable pool info missing\n if (pool.tokens.some((token) => !token.decimals))\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n if (!pool.amp) throw new BalancerError(BalancerErrorCode.MISSING_AMP);\n\n // Parse pool info into EVM amounts in order to match amountsIn scalling\n const {\n parsedTokens,\n parsedAmp,\n parsedTotalShares,\n parsedSwapFee,\n upScaledBalances,\n scalingFactors,\n } = parsePoolInfo(pool);\n\n // Replace WETH address with ETH - required for exiting with ETH\n const unwrappedTokens = parsedTokens.map((token) =>\n token === wrappedNativeAsset ? AddressZero : token\n );\n\n // Sort pool info based on tokens addresses\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n const [sortedTokens, sortedUpscaledBalances, sortedScalingFactors] =\n assetHelpers.sortTokens(\n shouldUnwrapNativeAsset ? unwrappedTokens : parsedTokens,\n upScaledBalances,\n scalingFactors\n ) as [string[], string[], string[]];\n\n let expectedAmountsOut = Array(parsedTokens.length).fill('0');\n let minAmountsOut = Array(parsedTokens.length).fill('0');\n let userData: string;\n\n if (singleTokenMaxOut) {\n // Exit pool with single token using exact bptIn\n\n const singleTokenMaxOutIndex = parsedTokens.indexOf(singleTokenMaxOut);\n\n // Calculate amount out given BPT in\n const amountOut = SOR.StableMathBigInt._calcTokenOutGivenExactBptIn(\n BigInt(parsedAmp as string),\n sortedUpscaledBalances.map((b) => BigInt(b)),\n singleTokenMaxOutIndex,\n BigInt(bptIn),\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n expectedAmountsOut[singleTokenMaxOutIndex] = amountOut;\n\n // Apply slippage tolerance\n minAmountsOut[singleTokenMaxOutIndex] = subSlippage(\n BigNumber.from(amountOut),\n BigNumber.from(slippage)\n ).toString();\n\n userData = StablePoolEncoder.exitExactBPTInForOneTokenOut(\n bptIn,\n singleTokenMaxOutIndex\n );\n } else {\n // Exit pool with all tokens proportinally\n\n // Calculate amount out given BPT in\n const amountsOut = SOR.StableMathBigInt._calcTokensOutGivenExactBptIn(\n sortedUpscaledBalances.map((b) => BigInt(b)),\n BigInt(bptIn),\n BigInt(parsedTotalShares)\n ).map((amount) => amount.toString());\n\n // Maths return numbers scaled to 18 decimals. Must scale down to token decimals.\n const amountsOutScaledDown = _downscaleDownArray(\n amountsOut.map((a) => BigInt(a)),\n sortedScalingFactors.map((a) => BigInt(a))\n );\n\n expectedAmountsOut = amountsOutScaledDown.map((amount) =>\n amount.toString()\n );\n\n // Apply slippage tolerance\n minAmountsOut = amountsOutScaledDown.map((amount) => {\n const minAmount = subSlippage(\n BigNumber.from(amount),\n BigNumber.from(slippage)\n );\n return minAmount.toString();\n });\n\n userData = StablePoolEncoder.exitExactBPTInForTokensOut(bptIn);\n }\n\n const to = balancerVault;\n const functionName = 'exitPool';\n const attributes: ExitPool = {\n poolId: pool.id,\n sender: exiter,\n recipient: exiter,\n exitPoolRequest: {\n assets: sortedTokens,\n minAmountsOut,\n userData,\n toInternalBalance: false,\n },\n };\n\n // Encode transaction data into an ABI byte string which can be sent to the network to be executed\n const vaultInterface = Vault__factory.createInterface();\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.exitPoolRequest,\n ]);\n\n return {\n to,\n functionName,\n attributes,\n data,\n expectedAmountsOut,\n minAmountsOut,\n };\n };\n\n buildExitExactTokensOut = ({\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset,\n }: ExitExactTokensOutParameters): ExitExactTokensOutAttributes => {\n if (\n tokensOut.length != amountsOut.length ||\n tokensOut.length != pool.tokensList.length\n ) {\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n }\n\n // Check if there's any relevant stable pool info missing\n if (pool.tokens.some((token) => !token.decimals))\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n if (!pool.amp) throw new BalancerError(BalancerErrorCode.MISSING_AMP);\n\n // Parse pool info into EVM amounts in order to match amountsOut scalling\n const {\n parsedTokens,\n parsedAmp,\n parsedTotalShares,\n parsedSwapFee,\n upScaledBalances,\n scalingFactors,\n } = parsePoolInfo(pool);\n\n // Sort pool info based on tokens addresses\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n const [, sortedUpScaledBalances, sortedScalingFactors] =\n assetHelpers.sortTokens(\n parsedTokens,\n upScaledBalances,\n scalingFactors\n ) as [string[], string[], string[]];\n const [sortedTokens, sortedAmountsOut] = assetHelpers.sortTokens(\n tokensOut,\n amountsOut\n ) as [string[], string[]];\n\n // Maths should use upscaled amounts, e.g. 1USDC => 1e18 not 1e6\n const upScaledAmountsOut = _upscaleArray(\n sortedAmountsOut.map((a) => BigInt(a)),\n sortedScalingFactors.map((a) => BigInt(a))\n );\n\n // Calculate expected BPT in given tokens out\n const bptIn = SOR.StableMathBigInt._calcBptInGivenExactTokensOut(\n BigInt(parsedAmp as string),\n sortedUpScaledBalances.map((b) => BigInt(b)),\n upScaledAmountsOut,\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n // Apply slippage tolerance\n const maxBPTIn = addSlippage(\n BigNumber.from(bptIn),\n BigNumber.from(slippage)\n ).toString();\n\n const userData = StablePoolEncoder.exitBPTInForExactTokensOut(\n sortedAmountsOut,\n maxBPTIn\n );\n\n const to = balancerVault;\n const functionName = 'exitPool';\n const attributes: ExitPool = {\n poolId: pool.id,\n sender: exiter,\n recipient: exiter,\n exitPoolRequest: {\n assets: sortedTokens,\n minAmountsOut: sortedAmountsOut,\n userData,\n toInternalBalance: false,\n },\n };\n\n // encode transaction data into an ABI byte string which can be sent to the network to be executed\n const vaultInterface = Vault__factory.createInterface();\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.exitPoolRequest,\n ]);\n\n return {\n to,\n functionName,\n attributes,\n data,\n expectedBPTIn: bptIn,\n maxBPTIn,\n };\n };\n}\n","import * as SOR from '@defiverse/sor';\n\nimport {\n JoinConcern,\n JoinPool,\n JoinPoolAttributes,\n JoinPoolParameters,\n} from '../types';\nimport { subSlippage } from '@/lib/utils/slippageHelper';\nimport { AssetHelpers, parsePoolInfo } from '@/lib/utils';\nimport { balancerVault } from '@/lib/constants/config';\nimport { Vault__factory } from '@balancer-labs/typechain';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { AddressZero } from '@ethersproject/constants';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { StablePoolEncoder } from '@/pool-stable';\nimport { _upscaleArray } from '@/lib/utils/solidityMaths';\n\nexport class StablePoolJoin implements JoinConcern {\n /**\n * Build join pool transaction parameters with exact tokens in and minimum BPT out based on slippage tolerance\n * @param {JoinPoolParameters} params - parameters used to build exact tokens in for bpt out transaction\n * @param {string} params.joiner - Account address joining pool\n * @param {Pool} params.pool - Subgraph pool object of pool being joined\n * @param {string[]} params.tokensIn - Token addresses provided for joining pool (same length and order as amountsIn)\n * @param {string[]} params.amountsIn - - Token amounts provided for joining pool in EVM amounts\n * @param {string} params.slippage - Maximum slippage tolerance in bps i.e. 50 = 0.5%\n * @returns transaction request ready to send with signer.sendTransaction\n */\n buildJoin = ({\n joiner,\n pool,\n tokensIn,\n amountsIn,\n slippage,\n wrappedNativeAsset,\n }: JoinPoolParameters): JoinPoolAttributes => {\n if (\n tokensIn.length != amountsIn.length ||\n tokensIn.length != pool.tokensList.length\n ) {\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n }\n\n // Check if there's any relevant stable pool info missing\n if (pool.tokens.some((token) => !token.decimals))\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n if (!pool.amp) throw new BalancerError(BalancerErrorCode.MISSING_AMP);\n\n // Parse pool info into EVM amounts in order to match amountsIn scalling\n const {\n parsedTokens,\n parsedAmp,\n parsedTotalShares,\n parsedSwapFee,\n scalingFactors,\n upScaledBalances,\n } = parsePoolInfo(pool);\n\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n // sort inputs\n const [sortedTokens, sortedAmountsIn] = assetHelpers.sortTokens(\n tokensIn,\n amountsIn\n ) as [string[], string[]];\n // sort pool info\n const [, sortedUpscaledBalances, sortedScalingFactors] =\n assetHelpers.sortTokens(\n parsedTokens,\n upScaledBalances,\n scalingFactors\n ) as [string[], string[], string[]];\n\n // Maths should use upscaled amounts, e.g. 1USDC => 1e18 not 1e6\n const scaledAmountsIn = _upscaleArray(\n sortedAmountsIn.map((a) => BigInt(a)),\n sortedScalingFactors.map((a) => BigInt(a))\n );\n\n const expectedBPTOut = SOR.StableMathBigInt._calcBptOutGivenExactTokensIn(\n BigInt(parsedAmp as string),\n sortedUpscaledBalances.map((b) => BigInt(b)),\n scaledAmountsIn,\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n const minBPTOut = subSlippage(\n BigNumber.from(expectedBPTOut),\n BigNumber.from(slippage)\n ).toString();\n\n const userData = StablePoolEncoder.joinExactTokensInForBPTOut(\n sortedAmountsIn,\n minBPTOut\n );\n\n const to = balancerVault;\n const functionName = 'joinPool';\n const attributes: JoinPool = {\n poolId: pool.id,\n sender: joiner,\n recipient: joiner,\n joinPoolRequest: {\n assets: sortedTokens,\n maxAmountsIn: sortedAmountsIn,\n userData,\n fromInternalBalance: false,\n },\n };\n const vaultInterface = Vault__factory.createInterface();\n // encode transaction data into an ABI byte string which can be sent to the network to be executed\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.joinPoolRequest,\n ]);\n const values = amountsIn.filter((amount, i) => tokensIn[i] === AddressZero); // filter native asset (e.g. ETH) amounts\n const value = values[0] ? BigNumber.from(values[0]) : undefined;\n\n return {\n to,\n functionName,\n attributes,\n data,\n value,\n minBPTOut,\n expectedBPTOut,\n };\n };\n}\n","import { LiquidityConcern } from '../types';\nimport { PoolToken } from '@/types';\nimport { BigNumber, formatFixed } from '@ethersproject/bignumber';\nimport { parseFixed } from '@/lib/utils/math';\n\nconst SCALING_FACTOR = 18;\n\nexport class StablePoolLiquidity implements LiquidityConcern {\n calcTotal(tokens: PoolToken[]): string {\n let sumBalance = BigNumber.from(0);\n let sumValue = BigNumber.from(0);\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n\n // if a token's price is unknown, ignore it\n // it will be computed at the next step\n if (!token.price?.usd) {\n continue;\n }\n\n const price = parseFixed(token.price.usd.toString(), SCALING_FACTOR);\n const balance = parseFixed(token.balance, SCALING_FACTOR);\n\n const value = balance.mul(price);\n sumValue = sumValue.add(value);\n sumBalance = sumBalance.add(balance);\n }\n\n // if at least the partial value of the pool is known\n // then compute the rest of the value of tokens with unknown prices\n if (sumBalance.gt(0)) {\n const avgPrice = sumValue.div(sumBalance);\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n\n if (token.price?.usd) {\n continue;\n }\n\n const balance = parseFixed(token.balance, SCALING_FACTOR);\n\n const value = balance.mul(avgPrice);\n sumValue = sumValue.add(value);\n sumBalance = sumBalance.add(balance);\n }\n }\n\n return formatFixed(sumValue, SCALING_FACTOR * 2).toString();\n }\n}\n","import { SpotPriceConcern } from '../types';\nimport { SubgraphPoolBase, StablePool, ZERO } from '@defiverse/sor';\nimport { Pool } from '@/types';\n\nexport class StablePoolSpotPrice implements SpotPriceConcern {\n calcPoolSpotPrice(tokenIn: string, tokenOut: string, pool: Pool): string {\n const stablePool = StablePool.fromPool(pool as SubgraphPoolBase);\n const poolPairData = stablePool.parsePoolPairData(tokenIn, tokenOut);\n return stablePool\n ._spotPriceAfterSwapExactTokenInForTokenOut(poolPairData, ZERO)\n .toString();\n }\n}\n","import { ONE, SolidityMaths } from '@/lib/utils/solidityMaths';\n\nexport function calcPriceImpact(\n bptAmount: bigint,\n bptZeroPriceImpact: bigint,\n isJoin: boolean\n): bigint {\n if (isJoin) return calcPriceImpactJoin(bptAmount, bptZeroPriceImpact);\n else return calcPriceImpactExit(bptAmount, bptZeroPriceImpact);\n}\n\nfunction calcPriceImpactJoin(\n bptAmount: bigint,\n bptZeroPriceImpact: bigint\n): bigint {\n // 1 - (bptAmount/bptZeroPI)\n const pi = ONE - SolidityMaths.divDownFixed(bptAmount, bptZeroPriceImpact);\n return pi < 0 ? BigInt(0) : pi;\n}\nfunction calcPriceImpactExit(\n bptAmount: bigint,\n bptZeroPriceImpact: bigint\n): bigint {\n // (bptAmount/bptZeroPI) - 1\n const pi = SolidityMaths.divDownFixed(bptAmount, bptZeroPriceImpact) - ONE;\n return pi < 0 ? BigInt(0) : pi;\n}\n","import { BZERO, SolidityMaths } from './solidityMaths';\n\nconst AMP_PRECISION = BigInt(1e3);\n\nexport function bptSpotPrice(\n amp: bigint,\n balances: bigint[],\n bptSupply: bigint,\n tokenIndexIn: number\n): bigint {\n const totalCoins = balances.length;\n const D = _calculateInvariant(amp, balances, true);\n let S = BZERO;\n let D_P = D / BigInt(totalCoins);\n for (let i = 0; i < totalCoins; i++) {\n if (i != tokenIndexIn) {\n S = S + balances[i];\n D_P = (D_P * D) / (BigInt(totalCoins) * balances[i]);\n }\n }\n const x = balances[tokenIndexIn];\n const alpha = amp * BigInt(totalCoins);\n const beta = alpha * S; // units: 10 ** 21\n const gamma = BigInt(AMP_PRECISION) - alpha;\n const partial_x = BigInt(2) * alpha * x + beta + gamma * D;\n const minus_partial_D =\n D_P * BigInt(totalCoins + 1) * AMP_PRECISION - gamma * x;\n const ans = SolidityMaths.divUpFixed(\n (partial_x * bptSupply) / minus_partial_D,\n D\n );\n return ans;\n}\n\nfunction _calculateInvariant(\n amp: bigint,\n balances: bigint[],\n roundUp: boolean\n): bigint {\n /**********************************************************************************************\n // invariant //\n // D = invariant D^(n+1) //\n // A = amplification coefficient A n^n S + D = A D n^n + ----------- //\n // S = sum of balances n^n P //\n // P = product of balances //\n // n = number of tokens //\n *********x************************************************************************************/\n\n // We support rounding up or down.\n\n let sum = BZERO;\n const numTokens = balances.length;\n for (let i = 0; i < numTokens; i++) {\n sum = sum + balances[i];\n }\n if (sum == BZERO) {\n return BZERO;\n }\n\n let prevInvariant = BZERO;\n let invariant = sum;\n const ampTimesTotal = amp * BigInt(numTokens);\n\n for (let i = 0; i < 255; i++) {\n let P_D = balances[0] * BigInt(numTokens);\n for (let j = 1; j < numTokens; j++) {\n P_D = SolidityMaths.div(\n SolidityMaths.mul(\n SolidityMaths.mul(P_D, balances[j]),\n BigInt(numTokens)\n ),\n invariant,\n roundUp\n );\n }\n prevInvariant = invariant;\n invariant = SolidityMaths.div(\n SolidityMaths.mul(\n SolidityMaths.mul(BigInt(numTokens), invariant),\n invariant\n ) +\n SolidityMaths.div(\n SolidityMaths.mul(SolidityMaths.mul(ampTimesTotal, sum), P_D),\n AMP_PRECISION,\n roundUp\n ),\n SolidityMaths.mul(BigInt(numTokens + 1), invariant) +\n // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1\n SolidityMaths.div(\n SolidityMaths.mul(ampTimesTotal - AMP_PRECISION, P_D),\n AMP_PRECISION,\n !roundUp\n ),\n roundUp\n );\n\n if (invariant > prevInvariant) {\n if (invariant - prevInvariant <= 1) {\n return invariant;\n }\n } else if (prevInvariant - invariant <= 1) {\n return invariant;\n }\n }\n\n throw new Error('Errors.STABLE_INVARIANT_DIDNT_CONVERGE');\n}\n","import { PriceImpactConcern } from '@/modules/pools/pool-types/concerns/types';\nimport {\n ONE,\n BZERO,\n _computeScalingFactor,\n _upscale,\n} from '@/lib/utils/solidityMaths';\nimport { calcPriceImpact } from '@/modules/pricing/priceImpact';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { Pool } from '@/types';\nimport { bptSpotPrice } from '@/lib/utils/stableMathHelpers';\nimport { parsePoolInfo } from '@/lib/utils';\n\nexport class StablePoolPriceImpact implements PriceImpactConcern {\n /**\n * Calculates the BPT return amount when investing with no price impact.\n * @param { Pool } pool Investment pool.\n * @param { bigint [] } amounts Token amounts being invested. Needs a value for each pool token.\n * @returns { bigint } BPT amount.\n */\n bptZeroPriceImpact(pool: Pool, tokenAmounts: bigint[]): bigint {\n if (tokenAmounts.length !== pool.tokensList.length)\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n\n // upscales amp, swapfee, totalshares\n const { parsedBalances, parsedDecimals, parsedAmp, parsedTotalShares } =\n parsePoolInfo(pool);\n\n const decimals = parsedDecimals.map((decimals) => {\n if (!decimals)\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n return BigInt(decimals);\n });\n if (!parsedAmp)\n throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n const totalShares = BigInt(parsedTotalShares);\n\n const scalingFactors = decimals.map((decimals) =>\n _computeScalingFactor(BigInt(decimals))\n );\n const balances = parsedBalances.map((balance, i) =>\n _upscale(BigInt(balance), scalingFactors[i])\n );\n\n let bptZeroPriceImpact = BZERO;\n for (let i = 0; i < balances.length; i++) {\n const price = bptSpotPrice(\n BigInt(parsedAmp), // this already includes the extra digits from precision\n balances,\n totalShares,\n i\n );\n const scalingFactor = _computeScalingFactor(BigInt(decimals[i]));\n const amountUpscaled = _upscale(tokenAmounts[i], scalingFactor);\n const newTerm = (price * amountUpscaled) / ONE;\n bptZeroPriceImpact += newTerm;\n }\n return bptZeroPriceImpact;\n }\n\n calcPriceImpact(\n pool: Pool,\n tokenAmounts: string[],\n bptAmount: string,\n isJoin: boolean\n ): string {\n const bptZeroPriceImpact = this.bptZeroPriceImpact(\n pool,\n tokenAmounts.map((a) => BigInt(a))\n );\n return calcPriceImpact(\n BigInt(bptAmount),\n bptZeroPriceImpact,\n isJoin\n ).toString();\n }\n}\n","import { StablePoolExit } from './concerns/stable/exit.concern';\nimport { StablePoolJoin } from './concerns/stable/join.concern';\nimport { StablePoolLiquidity } from './concerns/stable/liquidity.concern';\nimport { StablePoolSpotPrice } from './concerns/stable/spotPrice.concern';\nimport { StablePoolPriceImpact } from './concerns/stable/priceImpact.concern';\nimport { PoolType } from './pool-type.interface';\nimport {\n ExitConcern,\n JoinConcern,\n LiquidityConcern,\n PriceImpactConcern,\n SpotPriceConcern,\n} from './concerns/types';\n\nexport class Stable implements PoolType {\n constructor(\n public exit: ExitConcern = new StablePoolExit(),\n public join: JoinConcern = new StablePoolJoin(),\n public liquidity: LiquidityConcern = new StablePoolLiquidity(),\n public spotPriceCalculator: SpotPriceConcern = new StablePoolSpotPrice(),\n public priceImpactCalculator: PriceImpactConcern = new StablePoolPriceImpact()\n ) {}\n}\n","import { SpotPriceConcern } from '../types';\nimport { SubgraphPoolBase, PhantomStablePool, ZERO } from '@defiverse/sor';\nimport { Pool } from '@/types';\n\nexport class PhantomStablePoolSpotPrice implements SpotPriceConcern {\n calcPoolSpotPrice(tokenIn: string, tokenOut: string, pool: Pool): string {\n const metaStablePool = PhantomStablePool.fromPool(pool as SubgraphPoolBase);\n const poolPairData = metaStablePool.parsePoolPairData(tokenIn, tokenOut);\n return metaStablePool\n ._spotPriceAfterSwapExactTokenInForTokenOut(poolPairData, ZERO)\n .toString();\n }\n}\n","import { cloneDeep } from 'lodash';\nimport { PriceImpactConcern } from '@/modules/pools/pool-types/concerns/types';\nimport { calcPriceImpact } from '@/modules/pricing/priceImpact';\nimport {\n ONE,\n BZERO,\n _computeScalingFactor,\n _upscale,\n SolidityMaths,\n} from '@/lib/utils/solidityMaths';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { bptSpotPrice } from '@/lib/utils/stableMathHelpers';\nimport { Pool } from '@/types';\nimport { parsePoolInfo } from '@/lib/utils';\n\nexport class StablePhantomPriceImpact implements PriceImpactConcern {\n /**\n * Calculates the BPT return amount when investing with no price impact.\n * @param { Pool } pool Investment pool.\n * @param { bigint [] } amounts Token amounts being invested. Needs a value for each pool token that is not a PhantomBpt.\n * @returns { bigint } BPT amount.\n */\n bptZeroPriceImpact(pool: Pool, tokenAmounts: bigint[]): bigint {\n if (tokenAmounts.length !== pool.tokensList.length - 1)\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n\n const tokensList = cloneDeep(pool.tokensList);\n const bptIndex = tokensList.findIndex((token) => token == pool.address);\n\n // upscales amp, swapfee, totalshares\n const {\n parsedBalances,\n parsedDecimals,\n parsedPriceRates,\n parsedAmp,\n parsedTotalShares,\n } = parsePoolInfo(pool);\n const decimals = parsedDecimals.map((decimals) => {\n if (!decimals)\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n return BigInt(decimals);\n });\n const priceRates = parsedPriceRates.map((rate) => {\n if (!rate) throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n return BigInt(rate);\n });\n if (!parsedAmp)\n throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n const totalShares = BigInt(parsedTotalShares);\n tokensList.splice(bptIndex, 1);\n\n const scalingFactors = decimals.map((decimals) =>\n _computeScalingFactor(BigInt(decimals))\n );\n const balances = parsedBalances.map((balance, i) =>\n _upscale(BigInt(balance), scalingFactors[i])\n );\n if (tokenAmounts.length !== tokensList.length)\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n balances.splice(bptIndex, 1);\n const balancesScaled = balances.map((balance, i) =>\n SolidityMaths.mulDownFixed(balance, priceRates[i])\n );\n let bptZeroPriceImpact = BZERO;\n for (let i = 0; i < tokensList.length; i++) {\n const price =\n (bptSpotPrice(\n BigInt(parsedAmp), // this already includes the extra digits from precision\n balancesScaled,\n totalShares,\n i\n ) *\n priceRates[i]) /\n ONE;\n const scalingFactor = _computeScalingFactor(BigInt(decimals[i]));\n const amountUpscaled = _upscale(tokenAmounts[i], scalingFactor);\n const newTerm = (price * amountUpscaled) / ONE;\n bptZeroPriceImpact += newTerm;\n }\n return bptZeroPriceImpact;\n }\n\n calcPriceImpact(\n pool: Pool,\n tokenAmounts: string[],\n bptAmount: string,\n isJoin: boolean\n ): string {\n const bptZeroPriceImpact = this.bptZeroPriceImpact(\n pool,\n tokenAmounts.map((a) => BigInt(a))\n );\n return calcPriceImpact(\n BigInt(bptAmount),\n bptZeroPriceImpact,\n isJoin\n ).toString();\n }\n}\n","import {\n JoinPoolParameters,\n JoinConcern,\n JoinPoolAttributes,\n JoinPool,\n} from '../types';\nimport { StableMathBigInt } from '@defiverse/sor';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { AssetHelpers, parsePoolInfo, insert } from '@/lib/utils';\nimport { subSlippage } from '@/lib/utils/slippageHelper';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { ComposableStablePoolEncoder } from '@/pool-composable-stable';\nimport { balancerVault } from '@/lib/constants/config';\nimport { Vault__factory } from '@balancer-labs/typechain';\nimport { AddressZero } from '@ethersproject/constants';\nimport { _upscaleArray } from '@/lib/utils/solidityMaths';\n\nexport class ComposableStablePoolJoin implements JoinConcern {\n buildJoin = ({\n joiner,\n pool,\n tokensIn,\n amountsIn,\n slippage,\n wrappedNativeAsset,\n }: JoinPoolParameters): JoinPoolAttributes => {\n if (\n tokensIn.length != amountsIn.length ||\n tokensIn.length != pool.tokensList.length - 1\n ) {\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n }\n\n if (pool.tokens.some((token) => !token.decimals))\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n\n // amountsIn must be sorted in correct order. Currently ordered with relation to tokensIn so need sorted relative to those\n const [, sortedAmountsIn] = assetHelpers.sortTokens(\n tokensIn,\n amountsIn\n ) as [string[], string[]];\n\n // This will order everything correctly based on pool tokens\n const {\n parsedTokens,\n parsedAmp,\n parsedSwapFee,\n parsedTotalShares,\n scalingFactorsWithoutBpt,\n parsedBalancesWithoutBpt,\n bptIndex,\n } = parsePoolInfo(pool, wrappedNativeAsset);\n if (!parsedAmp) {\n throw new BalancerError(BalancerErrorCode.MISSING_AMP);\n }\n\n const scaledAmountsIn = _upscaleArray(\n sortedAmountsIn.map(BigInt),\n scalingFactorsWithoutBpt.map(BigInt)\n );\n //NEED TO SEND SORTED BALANCES AND AMOUNTS WITHOUT BPT VALUES\n const expectedBPTOut = StableMathBigInt._calcBptOutGivenExactTokensIn(\n BigInt(parsedAmp),\n parsedBalancesWithoutBpt.map(BigInt), // Should not have BPT\n scaledAmountsIn, // Should not have BPT\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n const minBPTOut = subSlippage(\n BigNumber.from(expectedBPTOut),\n BigNumber.from(slippage)\n ).toString();\n\n //NEEDS TO ENCODE USER DATA WITHOUT BPT AMOUNT\n const userData = ComposableStablePoolEncoder.joinExactTokensInForBPTOut(\n sortedAmountsIn,\n minBPTOut\n );\n\n const functionName = 'joinPool';\n //assets AND maxAmountsIn NEEDS THE BPT VALUE IN THE ARRAY\n const attributes: JoinPool = {\n poolId: pool.id,\n sender: joiner,\n recipient: joiner,\n joinPoolRequest: {\n assets: parsedTokens, // With BPT\n maxAmountsIn: insert(sortedAmountsIn, bptIndex, '0'), // Need to add value for BPT\n userData,\n fromInternalBalance: false,\n },\n };\n\n const vaultInterface = Vault__factory.createInterface();\n\n // encode transaction data into an ABI byte string which can be sent to the network to be executed\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.joinPoolRequest,\n ]);\n\n const values = amountsIn.filter((amount, i) => tokensIn[i] === AddressZero); // filter native asset (e.g. ETH) amounts\n const value = values[0] ? BigNumber.from(values[0]) : undefined;\n\n return {\n to: balancerVault,\n functionName,\n attributes,\n data,\n value,\n minBPTOut,\n expectedBPTOut,\n };\n };\n}\n","import {\n ExitConcern,\n ExitExactBPTInParameters,\n ExitExactTokensOutParameters,\n ExitExactBPTInAttributes,\n ExitExactTokensOutAttributes,\n} from '../types';\n\nexport class ComposableStablePoolExit implements ExitConcern {\n buildExitExactBPTIn = ({\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut,\n }: ExitExactBPTInParameters): ExitExactBPTInAttributes => {\n // TODO implementation\n console.log(\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut\n );\n\n throw new Error('To be implemented');\n };\n\n buildExitExactTokensOut = ({\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset,\n }: ExitExactTokensOutParameters): ExitExactTokensOutAttributes => {\n // TODO implementation\n console.log(\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset\n );\n\n throw new Error('To be implemented');\n };\n}\n","import { StablePoolLiquidity } from './concerns/stable/liquidity.concern';\nimport { PhantomStablePoolSpotPrice } from './concerns/stablePhantom/spotPrice.concern';\nimport { StablePhantomPriceImpact } from './concerns/stablePhantom/priceImpact.concern';\nimport { ComposableStablePoolJoin } from './concerns/composableStable/join.concern';\nimport { ComposableStablePoolExit } from './concerns/composableStable/exit.concern';\nimport { PoolType } from './pool-type.interface';\nimport {\n ExitConcern,\n JoinConcern,\n LiquidityConcern,\n PriceImpactConcern,\n SpotPriceConcern,\n} from './concerns/types';\n\nexport class ComposableStable implements PoolType {\n constructor(\n public exit: ExitConcern = new ComposableStablePoolExit(),\n public liquidity: LiquidityConcern = new StablePoolLiquidity(),\n public spotPriceCalculator: SpotPriceConcern = new PhantomStablePoolSpotPrice(),\n public priceImpactCalculator: PriceImpactConcern = new StablePhantomPriceImpact(),\n public join: JoinConcern = new ComposableStablePoolJoin()\n ) {}\n}\n","import { BigNumber, parseFixed } from '@ethersproject/bignumber';\nimport * as SOR from '@defiverse/sor';\nimport {\n ExitConcern,\n ExitExactBPTInParameters,\n ExitExactTokensOutParameters,\n ExitPool,\n ExitExactBPTInAttributes,\n ExitExactTokensOutAttributes,\n} from '../types';\nimport { AssetHelpers, isSameAddress, parsePoolInfo } from '@/lib/utils';\nimport { Vault__factory } from '@balancer-labs/typechain';\nimport { WeightedPoolEncoder } from '@/pool-weighted';\nimport { addSlippage, subSlippage } from '@/lib/utils/slippageHelper';\nimport { balancerVault } from '@/lib/constants/config';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { AddressZero } from '@ethersproject/constants';\n\nexport class WeightedPoolExit implements ExitConcern {\n buildExitExactBPTIn = ({\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut,\n }: ExitExactBPTInParameters): ExitExactBPTInAttributes => {\n if (!bptIn.length || parseFixed(bptIn, 18).isNegative()) {\n throw new BalancerError(BalancerErrorCode.INPUT_OUT_OF_BOUNDS);\n }\n if (\n singleTokenMaxOut &&\n singleTokenMaxOut !== AddressZero &&\n !pool.tokens\n .map((t) => t.address)\n .some((a) => isSameAddress(a, singleTokenMaxOut))\n ) {\n throw new BalancerError(BalancerErrorCode.TOKEN_MISMATCH);\n }\n if (!shouldUnwrapNativeAsset && singleTokenMaxOut === AddressZero)\n throw new Error(\n 'shouldUnwrapNativeAsset and singleTokenMaxOut should not have conflicting values'\n );\n\n // Parse pool info into EVM amounts in order to match amountsIn scalling\n const {\n parsedTokens,\n parsedBalances,\n parsedWeights,\n parsedTotalShares,\n parsedSwapFee,\n } = parsePoolInfo(pool);\n\n // Replace WETH address with ETH - required for exiting with ETH\n const unwrappedTokens = parsedTokens.map((token) =>\n token === wrappedNativeAsset ? AddressZero : token\n );\n\n // Sort pool info based on tokens addresses\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n const [sortedTokens, sortedBalances, sortedWeights] =\n assetHelpers.sortTokens(\n shouldUnwrapNativeAsset ? unwrappedTokens : parsedTokens,\n parsedBalances,\n parsedWeights\n ) as [string[], string[], string[]];\n\n let expectedAmountsOut = Array(sortedTokens.length).fill('0');\n let minAmountsOut = Array(sortedTokens.length).fill('0');\n let userData: string;\n\n if (singleTokenMaxOut) {\n // Exit pool with single token using exact bptIn\n\n const singleTokenMaxOutIndex = sortedTokens.indexOf(singleTokenMaxOut);\n\n // Calculate amount out given BPT in\n const amountOut = SOR.WeightedMaths._calcTokenOutGivenExactBptIn(\n BigInt(sortedBalances[singleTokenMaxOutIndex]),\n BigInt(sortedWeights[singleTokenMaxOutIndex]),\n BigInt(bptIn),\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n expectedAmountsOut[singleTokenMaxOutIndex] = amountOut;\n\n // Apply slippage tolerance\n minAmountsOut[singleTokenMaxOutIndex] = subSlippage(\n BigNumber.from(amountOut),\n BigNumber.from(slippage)\n ).toString();\n\n userData = WeightedPoolEncoder.exitExactBPTInForOneTokenOut(\n bptIn,\n singleTokenMaxOutIndex\n );\n } else {\n // Exit pool with all tokens proportinally\n\n // Calculate amounts out given BPT in\n expectedAmountsOut = SOR.WeightedMaths._calcTokensOutGivenExactBptIn(\n sortedBalances.map((b) => BigInt(b)),\n BigInt(bptIn),\n BigInt(parsedTotalShares)\n ).map((amount) => amount.toString());\n\n // Apply slippage tolerance\n minAmountsOut = expectedAmountsOut.map((amount) => {\n const minAmount = subSlippage(\n BigNumber.from(amount),\n BigNumber.from(slippage)\n );\n return minAmount.toString();\n });\n\n userData = WeightedPoolEncoder.exitExactBPTInForTokensOut(bptIn);\n }\n\n const to = balancerVault;\n const functionName = 'exitPool';\n const attributes: ExitPool = {\n poolId: pool.id,\n sender: exiter,\n recipient: exiter,\n exitPoolRequest: {\n assets: sortedTokens,\n minAmountsOut,\n userData,\n toInternalBalance: false,\n },\n };\n\n // encode transaction data into an ABI byte string which can be sent to the network to be executed\n const vaultInterface = Vault__factory.createInterface();\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.exitPoolRequest,\n ]);\n\n return {\n to,\n functionName,\n attributes,\n data,\n expectedAmountsOut,\n minAmountsOut,\n };\n };\n\n buildExitExactTokensOut = ({\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset,\n }: ExitExactTokensOutParameters): ExitExactTokensOutAttributes => {\n if (\n tokensOut.length != amountsOut.length ||\n tokensOut.length != pool.tokensList.length\n ) {\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n }\n\n // Parse pool info into EVM amounts in order to match amountsIn scalling\n const {\n parsedTokens,\n parsedBalances,\n parsedWeights,\n parsedTotalShares,\n parsedSwapFee,\n } = parsePoolInfo(pool);\n\n // Sort pool info and inputs based on tokens addresses\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n const [, sortedBalances, sortedWeights] = assetHelpers.sortTokens(\n parsedTokens,\n parsedBalances,\n parsedWeights\n ) as [string[], string[], string[]];\n const [sortedTokens, sortedAmounts] = assetHelpers.sortTokens(\n tokensOut,\n amountsOut\n ) as [string[], string[]];\n\n // Calculate expected BPT in given tokens out\n const bptIn = SOR.WeightedMaths._calcBptInGivenExactTokensOut(\n sortedBalances.map((b) => BigInt(b)),\n sortedWeights.map((w) => BigInt(w)),\n sortedAmounts.map((a) => BigInt(a)),\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n // Apply slippage tolerance\n const maxBPTIn = addSlippage(\n BigNumber.from(bptIn),\n BigNumber.from(slippage)\n ).toString();\n\n const userData = WeightedPoolEncoder.exitBPTInForExactTokensOut(\n sortedAmounts,\n maxBPTIn\n );\n\n const to = balancerVault;\n const functionName = 'exitPool';\n const attributes: ExitPool = {\n poolId: pool.id,\n sender: exiter,\n recipient: exiter,\n exitPoolRequest: {\n assets: sortedTokens,\n minAmountsOut: sortedAmounts,\n userData,\n toInternalBalance: false,\n },\n };\n\n // encode transaction data into an ABI byte string which can be sent to the network to be executed\n const vaultInterface = Vault__factory.createInterface();\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.exitPoolRequest,\n ]);\n\n return {\n to,\n functionName,\n attributes,\n data,\n expectedBPTIn: bptIn,\n maxBPTIn,\n };\n };\n}\n","import { WeightedMaths } from '@defiverse/sor';\nimport { WeightedPoolEncoder } from '@/pool-weighted';\nimport {\n JoinConcern,\n JoinPool,\n JoinPoolAttributes,\n JoinPoolParameters,\n} from '../types';\nimport { subSlippage } from '@/lib/utils/slippageHelper';\nimport { AssetHelpers, parsePoolInfo } from '@/lib/utils';\nimport { balancerVault } from '@/lib/constants/config';\nimport { Vault__factory } from '@balancer-labs/typechain';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { AddressZero } from '@ethersproject/constants';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\n\nexport class WeightedPoolJoin implements JoinConcern {\n /**\n * Build join pool transaction parameters with exact tokens in and minimum BPT out based on slippage tolerance\n * @param {JoinPoolParameters} params - parameters used to build exact tokens in for bpt out transaction\n * @param {string} params.joiner - Account address joining pool\n * @param {SubgraphPoolBase} params.pool - Subgraph pool object of pool being joined\n * @param {string[]} params.tokensIn - Token addresses provided for joining pool (same length and order as amountsIn)\n * @param {string[]} params.amountsIn - - Token amounts provided for joining pool in EVM amounts\n * @param {string} params.slippage - Maximum slippage tolerance in bps i.e. 50 = 0.5%\n * @param {string} params.wrappedNativeAsset - Address of wrapped native asset for specific network config. Required for joining with ETH.\n * @returns transaction request ready to send with signer.sendTransaction\n */\n buildJoin = ({\n joiner,\n pool,\n tokensIn,\n amountsIn,\n slippage,\n wrappedNativeAsset,\n }: JoinPoolParameters): JoinPoolAttributes => {\n if (\n tokensIn.length != amountsIn.length ||\n tokensIn.length != pool.tokensList.length\n ) {\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n }\n\n // Check if there's any relevant weighted pool info missing\n if (pool.tokens.some((token) => !token.decimals))\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n if (pool.tokens.some((token) => !token.weight))\n throw new BalancerError(BalancerErrorCode.MISSING_WEIGHT);\n\n // Parse pool info into EVM amounts in order to match amountsIn scalling\n const {\n parsedTokens,\n parsedBalances,\n parsedWeights,\n parsedTotalShares,\n parsedSwapFee,\n } = parsePoolInfo(pool);\n\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n // sort inputs\n const [sortedTokens, sortedAmounts] = assetHelpers.sortTokens(\n tokensIn,\n amountsIn\n ) as [string[], string[]];\n // sort pool info\n const [, sortedBalances, sortedWeights] = assetHelpers.sortTokens(\n parsedTokens,\n parsedBalances,\n parsedWeights\n ) as [string[], string[], string[]];\n\n const expectedBPTOut = WeightedMaths._calcBptOutGivenExactTokensIn(\n sortedBalances.map((b) => BigInt(b)),\n sortedWeights.map((w) => BigInt(w)),\n sortedAmounts.map((a) => BigInt(a)),\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n const minBPTOut = subSlippage(\n BigNumber.from(expectedBPTOut),\n BigNumber.from(slippage)\n ).toString();\n\n const userData = WeightedPoolEncoder.joinExactTokensInForBPTOut(\n sortedAmounts,\n minBPTOut\n );\n\n const to = balancerVault;\n const functionName = 'joinPool';\n const attributes: JoinPool = {\n poolId: pool.id,\n sender: joiner,\n recipient: joiner,\n joinPoolRequest: {\n assets: sortedTokens,\n maxAmountsIn: sortedAmounts,\n userData,\n fromInternalBalance: false,\n },\n };\n const vaultInterface = Vault__factory.createInterface();\n // encode transaction data into an ABI byte string which can be sent to the network to be executed\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.joinPoolRequest,\n ]);\n const values = amountsIn.filter((amount, i) => tokensIn[i] === AddressZero); // filter native asset (e.g. ETH) amounts\n const value = values[0] ? BigNumber.from(values[0]) : undefined;\n\n return {\n to,\n functionName,\n attributes,\n data,\n value,\n minBPTOut,\n expectedBPTOut,\n };\n };\n}\n","import { LiquidityConcern } from '../types';\nimport { PoolToken } from '@/types';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { parseFixed, formatFixed } from '@/lib/utils/math';\n\nconst SCALING_FACTOR = 18;\n\nexport class WeightedPoolLiquidity implements LiquidityConcern {\n calcTotal(tokens: PoolToken[]): string {\n let sumWeight = BigNumber.from(0);\n let sumValue = BigNumber.from(0);\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n if (!token.price?.usd) {\n continue;\n }\n\n let price: BigNumber;\n if (parseFloat(token.price.usd) < 1) {\n price = parseFixed(parseFloat(token.price.usd).toFixed(10), 10).mul(\n 1e8\n );\n } else {\n price = parseFixed(token.price.usd, SCALING_FACTOR);\n }\n const balance = parseFixed(token.balance, SCALING_FACTOR);\n const weight = parseFixed(token.weight || '0', SCALING_FACTOR);\n\n const value = balance.mul(price);\n sumValue = sumValue.add(value);\n sumWeight = sumWeight.add(weight);\n }\n\n // Scale the known prices of x% of the pool to get value of 100% of the pool.\n const totalWeight = tokens.reduce(\n (total: BigNumber, token) =>\n total.add(parseFixed(token.weight || '0', SCALING_FACTOR)),\n BigNumber.from(0)\n );\n if (sumWeight.gt(0)) {\n const liquidity = sumValue.mul(totalWeight).div(sumWeight);\n return formatFixed(liquidity, SCALING_FACTOR * 2);\n }\n\n return '0';\n }\n}\n","import { SpotPriceConcern } from '../types';\nimport {\n SubgraphPoolBase,\n WeightedPool,\n ZERO,\n SubgraphToken,\n} from '@defiverse/sor';\nimport { Pool } from '@/types';\n\nexport class WeightedPoolSpotPrice implements SpotPriceConcern {\n calcPoolSpotPrice(tokenIn: string, tokenOut: string, pool: Pool): string {\n const isBPTAsToken = tokenIn === pool.address || tokenOut === pool.address;\n if (isBPTAsToken) {\n const bptAsToken: SubgraphToken = {\n address: pool.address,\n balance: pool.totalShares,\n decimals: 18,\n priceRate: '1',\n weight: '0',\n };\n pool.tokens.push(bptAsToken);\n pool.tokensList.push(pool.address);\n }\n const weightedPool = WeightedPool.fromPool(pool as SubgraphPoolBase);\n const poolPairData = weightedPool.parsePoolPairData(tokenIn, tokenOut);\n const spotPrice = weightedPool\n ._spotPriceAfterSwapExactTokenInForTokenOut(poolPairData, ZERO)\n .toString();\n if (isBPTAsToken) {\n pool.tokens.pop();\n pool.tokensList.pop();\n }\n return spotPrice;\n }\n}\n","import { cloneDeep } from 'lodash';\nimport { PriceImpactConcern } from '@/modules/pools/pool-types/concerns/types';\nimport { calcPriceImpact } from '@/modules/pricing/priceImpact';\nimport {\n ONE,\n BZERO,\n _computeScalingFactor,\n _upscale,\n} from '@/lib/utils/solidityMaths';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { Pool } from '@/types';\nimport { parsePoolInfo } from '@/lib/utils';\n\nexport class WeightedPoolPriceImpact implements PriceImpactConcern {\n /**\n * Calculates the BPT return amount when investing with no price impact.\n * @param { Pool } pool Investment pool.\n * @param { bigint [] } amounts Token amounts being invested. EVM Scale. Needs a value for each pool token.\n * @returns { bigint } BPT amount.\n */\n bptZeroPriceImpact(pool: Pool, tokenAmounts: bigint[]): bigint {\n if (tokenAmounts.length !== pool.tokensList.length)\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n\n // swapFee, totalShares, totalWeight all scaled up to 18 decimals\n const { parsedBalances, parsedDecimals, parsedTotalShares, parsedWeights } =\n parsePoolInfo(pool);\n\n const totalShares = BigInt(parsedTotalShares);\n const tokensList = cloneDeep(pool.tokensList);\n let bptZeroPriceImpact = BZERO;\n for (let i = 0; i < tokensList.length; i++) {\n const decimals = parsedDecimals[i];\n let scalingFactor: bigint;\n let balance: bigint;\n if (!decimals)\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n else {\n scalingFactor = _computeScalingFactor(BigInt(decimals));\n balance = _upscale(BigInt(parsedBalances[i]), scalingFactor);\n }\n const weightString = parsedWeights[i];\n let weight: bigint;\n if (!weightString)\n throw new BalancerError(BalancerErrorCode.MISSING_WEIGHT);\n else {\n weight = BigInt(weightString);\n }\n const price = (weight * totalShares) / balance;\n const amountUpscaled = _upscale(tokenAmounts[i], scalingFactor);\n const newTerm = (price * amountUpscaled) / ONE;\n bptZeroPriceImpact += newTerm;\n }\n return bptZeroPriceImpact;\n }\n\n calcPriceImpact(\n pool: Pool,\n tokenAmounts: string[],\n bptAmount: string,\n isJoin: boolean\n ): string {\n const bptZeroPriceImpact = this.bptZeroPriceImpact(\n pool,\n tokenAmounts.map((a) => BigInt(a))\n );\n return calcPriceImpact(\n BigInt(bptAmount),\n bptZeroPriceImpact,\n isJoin\n ).toString();\n }\n}\n","import { WeightedPoolExit } from './concerns/weighted/exit.concern';\nimport { WeightedPoolJoin } from './concerns/weighted/join.concern';\nimport { WeightedPoolLiquidity } from './concerns/weighted/liquidity.concern';\nimport { WeightedPoolSpotPrice } from './concerns/weighted/spotPrice.concern';\nimport { WeightedPoolPriceImpact } from './concerns/weighted/priceImpact.concern';\nimport { PoolType } from './pool-type.interface';\nimport {\n ExitConcern,\n JoinConcern,\n LiquidityConcern,\n PriceImpactConcern,\n SpotPriceConcern,\n} from './concerns/types';\n\nexport class Weighted implements PoolType {\n constructor(\n public exit: ExitConcern = new WeightedPoolExit(),\n public join: JoinConcern = new WeightedPoolJoin(),\n public liquidity: LiquidityConcern = new WeightedPoolLiquidity(),\n public spotPriceCalculator: SpotPriceConcern = new WeightedPoolSpotPrice(),\n public priceImpactCalculator: PriceImpactConcern = new WeightedPoolPriceImpact()\n ) {}\n}\n","import { BigNumber, parseFixed } from '@ethersproject/bignumber';\nimport * as SOR from '@defiverse/sor';\nimport {\n ExitConcern,\n ExitExactBPTInParameters,\n ExitExactTokensOutParameters,\n ExitPool,\n ExitExactBPTInAttributes,\n ExitExactTokensOutAttributes,\n} from '../types';\nimport { AssetHelpers, isSameAddress, parsePoolInfo } from '@/lib/utils';\nimport { Vault__factory } from '@balancer-labs/typechain';\nimport { addSlippage, subSlippage } from '@/lib/utils/slippageHelper';\nimport { balancerVault } from '@/lib/constants/config';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { AddressZero } from '@ethersproject/constants';\nimport { StablePoolEncoder } from '@/pool-stable';\n\nexport class MetaStablePoolExit implements ExitConcern {\n buildExitExactBPTIn = ({\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut,\n }: ExitExactBPTInParameters): ExitExactBPTInAttributes => {\n if (!bptIn.length || parseFixed(bptIn, 18).isNegative()) {\n throw new BalancerError(BalancerErrorCode.INPUT_OUT_OF_BOUNDS);\n }\n if (\n singleTokenMaxOut &&\n singleTokenMaxOut !== AddressZero &&\n !pool.tokens\n .map((t) => t.address)\n .some((a) => isSameAddress(a, singleTokenMaxOut))\n ) {\n throw new BalancerError(BalancerErrorCode.TOKEN_MISMATCH);\n }\n\n if (!shouldUnwrapNativeAsset && singleTokenMaxOut === AddressZero)\n throw new Error(\n 'shouldUnwrapNativeAsset and singleTokenMaxOut should not have conflicting values'\n );\n\n // Check if there's any relevant meta stable pool info missing\n if (pool.tokens.some((token) => !token.decimals))\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n if (!pool.amp) throw new BalancerError(BalancerErrorCode.MISSING_AMP);\n if (pool.tokens.some((token) => !token.priceRate))\n throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n\n // Parse pool info into EVM amounts in order to match amountsIn scalling\n const {\n parsedTokens,\n parsedBalances,\n parsedAmp,\n parsedPriceRates,\n parsedTotalShares,\n parsedSwapFee,\n } = parsePoolInfo(pool);\n\n // Replace WETH address with ETH - required for exiting with ETH\n const unwrappedTokens = parsedTokens.map((token) =>\n token === wrappedNativeAsset ? AddressZero : token\n );\n\n // Sort pool info based on tokens addresses\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n const [sortedTokens, sortedBalances, sortedPriceRates] =\n assetHelpers.sortTokens(\n shouldUnwrapNativeAsset ? unwrappedTokens : parsedTokens,\n parsedBalances,\n parsedPriceRates\n ) as [string[], string[], string[]];\n\n // Scale balances based on price rate for each token\n const scaledBalances = sortedBalances.map((balance, i) => {\n return BigNumber.from(balance)\n .mul(BigNumber.from(sortedPriceRates[i]))\n .div(parseFixed('1', 18))\n .toString();\n });\n\n let expectedAmountsOut = Array(parsedTokens.length).fill('0');\n let minAmountsOut = Array(parsedTokens.length).fill('0');\n let userData: string;\n\n if (singleTokenMaxOut) {\n // Exit pool with single token using exact bptIn\n\n const singleTokenMaxOutIndex = sortedTokens.indexOf(singleTokenMaxOut);\n\n // Calculate amount out given BPT in\n const scaledAmountOut = SOR.StableMathBigInt._calcTokenOutGivenExactBptIn(\n BigInt(parsedAmp as string),\n scaledBalances.map((b) => BigInt(b)),\n singleTokenMaxOutIndex,\n BigInt(bptIn),\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n // Reverse scaled amount out based on token price rate\n const amountOut = BigNumber.from(scaledAmountOut)\n .div(BigNumber.from(sortedPriceRates[singleTokenMaxOutIndex]))\n .mul(parseFixed('1', 18))\n .toString();\n\n expectedAmountsOut[singleTokenMaxOutIndex] = amountOut;\n\n minAmountsOut[singleTokenMaxOutIndex] = subSlippage(\n BigNumber.from(amountOut),\n BigNumber.from(slippage)\n ).toString();\n\n userData = StablePoolEncoder.exitExactBPTInForOneTokenOut(\n bptIn,\n singleTokenMaxOutIndex\n );\n } else {\n // Exit pool with all tokens proportinally\n\n // Calculate amount out given BPT in\n const scaledAmountsOut =\n SOR.StableMathBigInt._calcTokensOutGivenExactBptIn(\n scaledBalances.map((b) => BigInt(b)),\n BigInt(bptIn),\n BigInt(parsedTotalShares)\n ).map((amount) => amount.toString());\n\n // Reverse scaled amounts out based on token price rate\n expectedAmountsOut = scaledAmountsOut.map((amount, i) => {\n return BigNumber.from(amount)\n .mul(parseFixed('1', 18))\n .div(BigNumber.from(sortedPriceRates[i]))\n .toString();\n });\n\n // Apply slippage tolerance\n minAmountsOut = expectedAmountsOut.map((amount) => {\n const minAmount = subSlippage(\n BigNumber.from(amount),\n BigNumber.from(slippage)\n );\n return minAmount.toString();\n });\n\n userData = StablePoolEncoder.exitExactBPTInForTokensOut(bptIn);\n }\n\n const to = balancerVault;\n const functionName = 'exitPool';\n const attributes: ExitPool = {\n poolId: pool.id,\n sender: exiter,\n recipient: exiter,\n exitPoolRequest: {\n assets: sortedTokens,\n minAmountsOut,\n userData,\n toInternalBalance: false,\n },\n };\n\n // encode transaction data into an ABI byte string which can be sent to the network to be executed\n const vaultInterface = Vault__factory.createInterface();\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.exitPoolRequest,\n ]);\n\n return {\n to,\n functionName,\n attributes,\n data,\n expectedAmountsOut,\n minAmountsOut,\n };\n };\n\n buildExitExactTokensOut = ({\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset,\n }: ExitExactTokensOutParameters): ExitExactTokensOutAttributes => {\n if (\n tokensOut.length != amountsOut.length ||\n tokensOut.length != pool.tokensList.length\n ) {\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n }\n\n // Check if there's any relevant meta stable pool info missing\n if (pool.tokens.some((token) => !token.decimals))\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n if (!pool.amp) throw new BalancerError(BalancerErrorCode.MISSING_AMP);\n if (pool.tokens.some((token) => !token.priceRate))\n throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n\n // Parse pool info into EVM amounts in order to match amountsOut scalling\n const {\n parsedTokens,\n parsedBalances,\n parsedPriceRates,\n parsedAmp,\n parsedTotalShares,\n parsedSwapFee,\n } = parsePoolInfo(pool);\n\n // Sort pool info based on tokens addresses\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n const [, sortedBalances, sortedPriceRates] = assetHelpers.sortTokens(\n parsedTokens,\n parsedBalances,\n parsedPriceRates\n ) as [string[], string[], string[]];\n const [sortedTokens, sortedAmounts] = assetHelpers.sortTokens(\n tokensOut,\n amountsOut\n ) as [string[], string[]];\n\n // Scale amounts out based on price rate for each token\n const scaledAmounts = sortedAmounts.map((amount, i) => {\n return BigNumber.from(amount)\n .mul(BigNumber.from(sortedPriceRates[i]))\n .div(parseFixed('1', 18))\n .toString();\n });\n\n // Scale balances based on price rate for each token\n const scaledBalances = sortedBalances.map((balance, i) => {\n return BigNumber.from(balance)\n .mul(BigNumber.from(sortedPriceRates[i]))\n .div(parseFixed('1', 18))\n .toString();\n });\n\n // Calculate expected BPT in given tokens out\n const bptIn = SOR.StableMathBigInt._calcBptInGivenExactTokensOut(\n BigInt(parsedAmp as string),\n scaledBalances.map((b) => BigInt(b)),\n scaledAmounts.map((a) => BigInt(a)),\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n // Apply slippage tolerance\n const maxBPTIn = addSlippage(\n BigNumber.from(bptIn),\n BigNumber.from(slippage)\n ).toString();\n\n const userData = StablePoolEncoder.exitBPTInForExactTokensOut(\n sortedAmounts, // must not use scaledAmounts because it should match amountsOut provided by the user\n maxBPTIn\n );\n\n // This is a hack to get around rounding issues for scaled amounts on MetaStable pools\n // TODO: do this more elegantly\n const minAmountsOut = sortedAmounts.map((a, i) =>\n a === scaledAmounts[i] ? a : BigNumber.from(a).sub(1).toString()\n );\n\n const to = balancerVault;\n const functionName = 'exitPool';\n const attributes: ExitPool = {\n poolId: pool.id,\n sender: exiter,\n recipient: exiter,\n exitPoolRequest: {\n assets: sortedTokens,\n minAmountsOut,\n userData,\n toInternalBalance: false,\n },\n };\n\n // encode transaction data into an ABI byte string which can be sent to the network to be executed\n const vaultInterface = Vault__factory.createInterface();\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.exitPoolRequest,\n ]);\n\n return {\n to,\n functionName,\n attributes,\n data,\n expectedBPTIn: bptIn,\n maxBPTIn,\n };\n };\n}\n","import * as SOR from '@defiverse/sor';\n\nimport {\n JoinConcern,\n JoinPool,\n JoinPoolAttributes,\n JoinPoolParameters,\n} from '../types';\nimport { subSlippage } from '@/lib/utils/slippageHelper';\nimport { AssetHelpers, parsePoolInfo } from '@/lib/utils';\nimport { balancerVault } from '@/lib/constants/config';\nimport { Vault__factory } from '@balancer-labs/typechain';\nimport { BigNumber, parseFixed } from '@ethersproject/bignumber';\nimport { AddressZero } from '@ethersproject/constants';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { StablePoolEncoder } from '@/pool-stable';\n\nexport class MetaStablePoolJoin implements JoinConcern {\n /**\n * Build join pool transaction parameters with exact tokens in and minimum BPT out based on slippage tolerance\n * @param {JoinPoolParameters} params - parameters used to build exact tokens in for bpt out transaction\n * @param {string} params.joiner - Account address joining pool\n * @param {Pool} params.pool - Subgraph pool object of pool being joined\n * @param {string[]} params.tokensIn - Token addresses provided for joining pool (same length and order as amountsIn)\n * @param {string[]} params.amountsIn - - Token amounts provided for joining pool in EVM amounts\n * @param {string} params.slippage - Maximum slippage tolerance in bps i.e. 50 = 0.5%\n * @returns transaction request ready to send with signer.sendTransaction\n */\n buildJoin = ({\n joiner,\n pool,\n tokensIn,\n amountsIn,\n slippage,\n wrappedNativeAsset,\n }: JoinPoolParameters): JoinPoolAttributes => {\n if (\n tokensIn.length != amountsIn.length ||\n tokensIn.length != pool.tokensList.length\n ) {\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n }\n\n // Check if there's any relevant meta stable pool info missing\n if (pool.tokens.some((token) => !token.decimals))\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n if (!pool.amp) throw new BalancerError(BalancerErrorCode.MISSING_AMP);\n if (pool.tokens.some((token) => !token.priceRate))\n throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n\n // Parse pool info into EVM amounts in order to match amountsIn scalling\n const {\n parsedTokens,\n parsedBalances,\n parsedPriceRates,\n parsedAmp,\n parsedTotalShares,\n parsedSwapFee,\n } = parsePoolInfo(pool);\n\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n // sort input\n const [sortedTokens, sortedAmounts] = assetHelpers.sortTokens(\n tokensIn,\n amountsIn\n ) as [string[], string[]];\n // sort pool info\n const [, sortedBalances, sortedPriceRates] = assetHelpers.sortTokens(\n parsedTokens,\n parsedBalances,\n parsedPriceRates\n ) as [string[], string[], string[]];\n\n // scale amounts in based on price rate for each token\n const scaledAmounts = sortedAmounts.map((amount, i) => {\n return BigNumber.from(amount)\n .mul(BigNumber.from(sortedPriceRates[i]))\n .div(parseFixed('1', 18))\n .toString();\n });\n\n // scale balances based on price rate for each token\n const scaledBalances = sortedBalances.map((balance, i) => {\n return BigNumber.from(balance)\n .mul(BigNumber.from(sortedPriceRates[i]))\n .div(parseFixed('1', 18))\n .toString();\n });\n\n const expectedBPTOut = SOR.StableMathBigInt._calcBptOutGivenExactTokensIn(\n BigInt(parsedAmp as string),\n scaledBalances.map((b) => BigInt(b)),\n scaledAmounts.map((a) => BigInt(a)),\n BigInt(parsedTotalShares),\n BigInt(parsedSwapFee)\n ).toString();\n\n const minBPTOut = subSlippage(\n BigNumber.from(expectedBPTOut),\n BigNumber.from(slippage)\n ).toString();\n\n const userData = StablePoolEncoder.joinExactTokensInForBPTOut(\n sortedAmounts,\n minBPTOut\n );\n\n const to = balancerVault;\n const functionName = 'joinPool';\n const attributes: JoinPool = {\n poolId: pool.id,\n sender: joiner,\n recipient: joiner,\n joinPoolRequest: {\n assets: sortedTokens,\n maxAmountsIn: sortedAmounts,\n userData,\n fromInternalBalance: false,\n },\n };\n const vaultInterface = Vault__factory.createInterface();\n // encode transaction data into an ABI byte string which can be sent to the network to be executed\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.joinPoolRequest,\n ]);\n const values = amountsIn.filter((amount, i) => tokensIn[i] === AddressZero); // filter native asset (e.g. ETH) amounts\n const value = values[0] ? BigNumber.from(values[0]) : undefined;\n\n return {\n to,\n functionName,\n attributes,\n data,\n value,\n minBPTOut,\n expectedBPTOut,\n };\n };\n}\n","import { LiquidityConcern } from '../types';\nimport { PoolToken } from '@/types';\nimport { formatFixed } from '@ethersproject/bignumber';\nimport { parseFixed } from '@/lib/utils/math';\nimport { Zero } from '@ethersproject/constants';\n\nconst SCALING_FACTOR = 18;\n\nexport class MetaStablePoolLiquidity implements LiquidityConcern {\n calcTotal(tokens: PoolToken[]): string {\n let sumBalance = Zero;\n let sumValue = Zero;\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n\n // if a token's price is unknown, ignore it\n // it will be computed at the next step\n if (!token.price?.usd) {\n continue;\n }\n\n const price = parseFixed(token.price.usd.toString(), SCALING_FACTOR);\n\n const balance = parseFixed(token.balance, SCALING_FACTOR);\n\n const value = balance.mul(price);\n sumValue = sumValue.add(value);\n sumBalance = sumBalance.add(balance);\n }\n\n // if at least the partial value of the pool is known\n // then compute the rest of the value of tokens with unknown prices\n if (sumBalance.gt(0)) {\n const avgPrice = sumValue.div(sumBalance);\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n\n if (token.price?.usd) {\n continue;\n }\n\n const balance = parseFixed(token.balance, SCALING_FACTOR);\n\n const value = balance.mul(avgPrice);\n sumValue = sumValue.add(value);\n sumBalance = sumBalance.add(balance);\n }\n }\n\n return formatFixed(sumValue, SCALING_FACTOR * 2).toString();\n }\n}\n","import { SpotPriceConcern } from '../types';\nimport { SubgraphPoolBase, MetaStablePool, ZERO } from '@defiverse/sor';\nimport { Pool } from '@/types';\n\nexport class MetaStablePoolSpotPrice implements SpotPriceConcern {\n calcPoolSpotPrice(tokenIn: string, tokenOut: string, pool: Pool): string {\n const metaStablePool = MetaStablePool.fromPool(pool as SubgraphPoolBase);\n const poolPairData = metaStablePool.parsePoolPairData(tokenIn, tokenOut);\n return metaStablePool\n ._spotPriceAfterSwapExactTokenInForTokenOut(poolPairData, ZERO)\n .toString();\n }\n}\n","import { PriceImpactConcern } from '@/modules/pools/pool-types/concerns/types';\nimport { calcPriceImpact } from '@/modules/pricing/priceImpact';\nimport {\n ONE,\n BZERO,\n SolidityMaths,\n _upscale,\n _computeScalingFactor,\n} from '@/lib/utils/solidityMaths';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { Pool } from '@/types';\nimport { parsePoolInfo } from '@/lib/utils';\nimport { bptSpotPrice } from '@/lib/utils/stableMathHelpers';\n\nexport class MetaStablePoolPriceImpact implements PriceImpactConcern {\n /**\n * Calculates the BPT return amount when investing with no price impact.\n * @param { Pool } pool Investment pool.\n * @param { string [] } amounts Token amounts being invested. Needs a value for each pool token.\n * @returns { string } BPT amount.\n */\n bptZeroPriceImpact(pool: Pool, tokenAmounts: bigint[]): bigint {\n if (tokenAmounts.length !== pool.tokensList.length)\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n\n const {\n parsedBalances,\n parsedDecimals,\n parsedPriceRates,\n parsedAmp,\n parsedTotalShares,\n } = parsePoolInfo(pool);\n const totalShares = BigInt(parsedTotalShares);\n const decimals = parsedDecimals.map((decimals) => {\n if (!decimals)\n throw new BalancerError(BalancerErrorCode.MISSING_DECIMALS);\n return BigInt(decimals);\n });\n const priceRates = parsedPriceRates.map((rate) => {\n if (!rate) throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n return BigInt(rate);\n });\n if (!parsedAmp)\n throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n\n const scalingFactors = decimals.map((decimals) =>\n _computeScalingFactor(BigInt(decimals))\n );\n const balances = parsedBalances.map((balance, i) =>\n _upscale(BigInt(balance), scalingFactors[i])\n );\n const balancesScaled = balances.map((balance, i) =>\n SolidityMaths.mulDownFixed(balance, priceRates[i])\n );\n let bptZeroPriceImpact = BZERO;\n for (let i = 0; i < balances.length; i++) {\n const price =\n (bptSpotPrice(\n BigInt(parsedAmp as string), // this already includes the extra digits from precision\n balancesScaled,\n totalShares,\n i\n ) *\n priceRates[i]) /\n ONE;\n const scalingFactor = _computeScalingFactor(\n BigInt(pool.tokens[i].decimals as number)\n );\n const amountUpscaled = _upscale(tokenAmounts[i], scalingFactor);\n const newTerm = (price * amountUpscaled) / ONE;\n bptZeroPriceImpact += newTerm;\n }\n return bptZeroPriceImpact;\n }\n\n calcPriceImpact(\n pool: Pool,\n tokenAmounts: string[],\n bptAmount: string,\n isJoin: boolean\n ): string {\n const bptZeroPriceImpact = this.bptZeroPriceImpact(\n pool,\n tokenAmounts.map((a) => BigInt(a))\n );\n return calcPriceImpact(\n BigInt(bptAmount),\n bptZeroPriceImpact,\n isJoin\n ).toString();\n }\n}\n","import { MetaStablePoolExit } from './concerns/metaStable/exit.concern';\nimport { MetaStablePoolJoin } from './concerns/metaStable/join.concern';\nimport { MetaStablePoolLiquidity } from './concerns/metaStable/liquidity.concern';\nimport { MetaStablePoolSpotPrice } from './concerns/metaStable/spotPrice.concern';\nimport { MetaStablePoolPriceImpact } from './concerns/metaStable/priceImpact.concern';\nimport { PoolType } from './pool-type.interface';\nimport {\n ExitConcern,\n JoinConcern,\n LiquidityConcern,\n SpotPriceConcern,\n PriceImpactConcern,\n} from './concerns/types';\n\nexport class MetaStable implements PoolType {\n constructor(\n public exit: ExitConcern = new MetaStablePoolExit(),\n public join: JoinConcern = new MetaStablePoolJoin(),\n public liquidity: LiquidityConcern = new MetaStablePoolLiquidity(),\n public spotPriceCalculator: SpotPriceConcern = new MetaStablePoolSpotPrice(),\n public priceImpactCalculator: PriceImpactConcern = new MetaStablePoolPriceImpact()\n ) {}\n}\n","import {\n ExitConcern,\n ExitExactBPTInParameters,\n ExitExactTokensOutParameters,\n ExitExactBPTInAttributes,\n ExitExactTokensOutAttributes,\n} from '../types';\n\nexport class StablePhantomPoolExit implements ExitConcern {\n buildExitExactBPTIn = ({\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut,\n }: ExitExactBPTInParameters): ExitExactBPTInAttributes => {\n // TODO implementation\n console.log(\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut\n );\n throw new Error('To be implemented');\n };\n\n buildExitExactTokensOut = ({\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset,\n }: ExitExactTokensOutParameters): ExitExactTokensOutAttributes => {\n // TODO implementation\n console.log(\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset\n );\n throw new Error('To be implemented');\n };\n}\n","import { JoinPoolParameters, JoinConcern, JoinPoolAttributes } from '../types';\n\nexport class StablePhantomPoolJoin implements JoinConcern {\n buildJoin = ({\n joiner,\n pool,\n tokensIn,\n amountsIn,\n slippage,\n wrappedNativeAsset,\n }: JoinPoolParameters): JoinPoolAttributes => {\n // TODO implementation\n console.log(\n joiner,\n pool,\n tokensIn,\n amountsIn,\n slippage,\n wrappedNativeAsset\n );\n throw new Error('To be implemented');\n };\n}\n","import { StablePhantomPoolExit } from './concerns/stablePhantom/exit.concern';\nimport { StablePhantomPoolJoin } from './concerns/stablePhantom/join.concern';\nimport { StablePoolLiquidity } from './concerns/stable/liquidity.concern';\nimport { PhantomStablePoolSpotPrice } from './concerns/stablePhantom/spotPrice.concern';\nimport { StablePhantomPriceImpact } from './concerns/stablePhantom/priceImpact.concern';\nimport { PoolType } from './pool-type.interface';\nimport {\n ExitConcern,\n JoinConcern,\n PriceImpactConcern,\n LiquidityConcern,\n SpotPriceConcern,\n} from './concerns/types';\n\nexport class StablePhantom implements PoolType {\n constructor(\n public exit: ExitConcern = new StablePhantomPoolExit(),\n public join: JoinConcern = new StablePhantomPoolJoin(),\n public liquidity: LiquidityConcern = new StablePoolLiquidity(),\n public spotPriceCalculator: SpotPriceConcern = new PhantomStablePoolSpotPrice(),\n public priceImpactCalculator: PriceImpactConcern = new StablePhantomPriceImpact()\n ) {}\n}\n","import {\n ExitConcern,\n ExitExactBPTInParameters,\n ExitExactTokensOutParameters,\n ExitExactBPTInAttributes,\n ExitExactTokensOutAttributes,\n} from '../types';\n\nexport class LinearPoolExit implements ExitConcern {\n buildExitExactBPTIn = ({\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut,\n }: ExitExactBPTInParameters): ExitExactBPTInAttributes => {\n // TODO implementation\n console.log(\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut\n );\n throw new Error('To be implemented');\n };\n\n buildExitExactTokensOut = ({\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset,\n }: ExitExactTokensOutParameters): ExitExactTokensOutAttributes => {\n // TODO implementation\n console.log(\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset\n );\n throw new Error('To be implemented');\n };\n}\n","import { JoinPoolParameters, JoinConcern, JoinPoolAttributes } from '../types';\n\nexport class LinearPoolJoin implements JoinConcern {\n buildJoin = ({\n joiner,\n pool,\n tokensIn,\n amountsIn,\n slippage,\n wrappedNativeAsset,\n }: JoinPoolParameters): JoinPoolAttributes => {\n // TODO implementation\n console.log(\n joiner,\n pool,\n tokensIn,\n amountsIn,\n slippage,\n wrappedNativeAsset\n );\n throw new Error('To be implemented');\n };\n}\n","import { LiquidityConcern } from '../types';\nimport { PoolToken } from '@/types';\nimport { parseFixed, formatFixed } from '@/lib/utils/math';\nimport { Zero } from '@ethersproject/constants';\n\nconst SCALING_FACTOR = 18;\nconst ONE = parseFixed('1', SCALING_FACTOR);\n\nexport class LinearPoolLiquidity implements LiquidityConcern {\n calcTotal(tokens: PoolToken[]): string {\n let sumBalance = Zero;\n let sumValue = Zero;\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n\n // if a token's price is unknown, ignore it\n // it will be computed at the next step\n if (!token.price?.usd) {\n continue;\n }\n\n const price = parseFixed(token.price.usd.toString(), SCALING_FACTOR);\n\n const balance = parseFixed(token.balance, SCALING_FACTOR);\n const value = balance.mul(price);\n\n sumValue = sumValue.add(value);\n sumBalance = sumBalance.add(balance);\n }\n\n // if at least the partial value of the pool is known\n // then compute the rest of the value of tokens with unknown prices\n if (sumBalance.gt(0)) {\n const avgPrice = sumValue.div(sumBalance);\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n\n if (token.price?.usd) {\n continue;\n }\n\n const priceRate = parseFixed(token.priceRate || '1', SCALING_FACTOR);\n\n // Apply priceRate to scale the balance correctly\n const balance = parseFixed(token.balance, SCALING_FACTOR)\n .mul(priceRate)\n .div(ONE);\n\n const value = balance.mul(avgPrice);\n sumValue = sumValue.add(value);\n sumBalance = sumBalance.add(balance);\n }\n }\n\n return formatFixed(sumValue, SCALING_FACTOR * 2);\n }\n}\n","import { SpotPriceConcern } from '../types';\nimport { SubgraphPoolBase, LinearPool, ZERO } from '@defiverse/sor';\nimport { Pool } from '@/types';\n\nexport class LinearPoolSpotPrice implements SpotPriceConcern {\n calcPoolSpotPrice(tokenIn: string, tokenOut: string, pool: Pool): string {\n const linearPool = LinearPool.fromPool(pool as SubgraphPoolBase);\n const poolPairData = linearPool.parsePoolPairData(tokenIn, tokenOut);\n return linearPool\n ._spotPriceAfterSwapExactTokenInForTokenOut(poolPairData, ZERO)\n .toString();\n }\n}\n","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { PriceImpactConcern } from '../types';\nimport { Pool } from '@/types';\n\nexport class LinearPriceImpact implements PriceImpactConcern {\n bptZeroPriceImpact(pool: Pool, amounts: bigint[]): bigint {\n throw new Error('Linear Pool bptZeroPriceImpact Not Implented');\n }\n calcPriceImpact(\n pool: Pool,\n tokenAmounts: string[],\n bptAmount: string\n ): string {\n throw new Error('Linear Pool Price Impact Not Implented');\n }\n}\n","import { LinearPoolExit } from './concerns/linear/exit.concern';\nimport { LinearPoolJoin } from './concerns/linear/join.concern';\nimport { LinearPoolLiquidity } from './concerns/linear/liquidity.concern';\nimport { LinearPoolSpotPrice } from './concerns/linear/spotPrice.concern';\nimport { LinearPriceImpact } from './concerns/linear/priceImpact.concern';\nimport { PoolType } from './pool-type.interface';\nimport {\n ExitConcern,\n JoinConcern,\n LiquidityConcern,\n PriceImpactConcern,\n SpotPriceConcern,\n} from './concerns/types';\n\nexport class Linear implements PoolType {\n constructor(\n public exit: ExitConcern = new LinearPoolExit(),\n public join: JoinConcern = new LinearPoolJoin(),\n public liquidity: LiquidityConcern = new LinearPoolLiquidity(),\n public spotPriceCalculator: SpotPriceConcern = new LinearPoolSpotPrice(),\n public priceImpactCalculator: PriceImpactConcern = new LinearPriceImpact()\n ) {}\n}\n","import { BalancerSdkConfig, PoolType } from '@/types';\nimport { Stable } from './pool-types/stable.module';\nimport { ComposableStable } from './pool-types/composableStable.module';\nimport { Weighted } from './pool-types/weighted.module';\nimport { MetaStable } from './pool-types/metaStable.module';\nimport { StablePhantom } from './pool-types/stablePhantom.module';\nimport { Linear } from './pool-types/linear.module';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\n\n/**\n * Wrapper around pool type specific methods.\n *\n * Returns a class instance of a type specific method handlers.\n */\nexport class PoolTypeConcerns {\n constructor(\n config: BalancerSdkConfig,\n public weighted = new Weighted(),\n public stable = new Stable(),\n public composableStable = new ComposableStable(),\n public metaStable = new MetaStable(),\n public stablePhantom = new StablePhantom(),\n public linear = new Linear()\n ) {}\n\n static from(\n poolType: PoolType\n ):\n | Weighted\n | Stable\n | ComposableStable\n | MetaStable\n | StablePhantom\n | Linear {\n // Calculate spot price using pool type\n switch (poolType) {\n case 'Weighted':\n case 'Investment':\n case 'LiquidityBootstrapping': {\n return new Weighted();\n }\n case 'Stable': {\n return new Stable();\n }\n case 'HighAmpComposableStable':\n case 'ComposableStable': {\n return new ComposableStable();\n }\n case 'MetaStable': {\n return new MetaStable();\n }\n case 'StablePhantom': {\n return new StablePhantom();\n }\n case 'AaveLinear':\n case 'EulerLinear':\n case 'ERC4626Linear': {\n return new Linear();\n }\n default:\n throw new BalancerError(BalancerErrorCode.UNSUPPORTED_POOL_TYPE);\n }\n }\n}\n","import { Findable, Pool, PoolToken, Price } from '@/types';\nimport { PoolAttribute } from '../data';\nimport { PoolTypeConcerns } from '../pools/pool-type-concerns';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { formatFixed, parseFixed } from '@/lib/utils/math';\n\nconst SCALE = 18;\n\nexport interface PoolBPTValue {\n address: string;\n liquidity: string;\n}\n\nexport class Liquidity {\n constructor(\n private pools: Findable<Pool, PoolAttribute>,\n private tokenPrices: Findable<Price>\n ) {}\n\n async getLiquidity(pool: Pool): Promise<string> {\n if (pool.totalLiquidity) {\n return pool.totalLiquidity;\n }\n\n // Remove any tokens with same address as pool as they are pre-printed BPT\n const parsedTokens = pool.tokens.filter((token) => {\n return token.address !== pool.address;\n });\n\n // For all tokens that are pools (BPT), recurse into them and fetch their liquidity\n const subPoolLiquidity = await Promise.all(\n parsedTokens.map(async (token) => {\n const pool = await this.pools.findBy('address', token.address);\n if (!pool) return;\n\n const liquidity = parseFixed(await this.getLiquidity(pool), SCALE);\n const totalBPT = parseFixed(pool.totalShares, SCALE);\n const bptInParentPool = parseFixed(token.balance, SCALE);\n const liquidityInParentPool = totalBPT.eq(0)\n ? 0\n : liquidity.mul(bptInParentPool).div(totalBPT);\n\n return {\n address: pool.address,\n liquidity: liquidityInParentPool.toString(),\n };\n })\n );\n\n const totalSubPoolLiquidity = subPoolLiquidity.reduce(\n (totalLiquidity, subPool) => {\n return totalLiquidity.add(\n subPool ? subPool.liquidity : BigNumber.from(0)\n );\n },\n BigNumber.from(0)\n );\n\n // Filter tokens within pool that are not BPT themselves\n const nonPoolTokens = parsedTokens.filter((token) => {\n return !subPoolLiquidity.find((pool) => pool?.address === token.address);\n });\n\n // Update price using tokenPrices repository\n const nonPoolTokensWithUpdatedPrice: PoolToken[] = await Promise.all(\n nonPoolTokens.map(async (token) => {\n const tokenPrice = await this.tokenPrices.find(token.address);\n const poolToken: PoolToken = {\n address: token.address,\n decimals: token.decimals,\n priceRate: token.priceRate,\n price: (tokenPrice?.usd && tokenPrice) || {\n usd: token.token?.latestUSDPrice,\n },\n balance: token.balance,\n weight: token.weight,\n };\n return poolToken;\n })\n );\n\n // TODO: Just in case we need it soon. Otherwise remove without mercy.\n // Any of the tokens is missing the price, use subgraph totalLiquidity\n // if(nonPoolTokensWithUpdatedPrice.map((t) => t.price?.usd).indexOf(undefined) > -1) {\n // return pool.totalLiquidity\n // }\n\n const tokenLiquidity = PoolTypeConcerns.from(\n pool.poolType\n ).liquidity.calcTotal(nonPoolTokensWithUpdatedPrice);\n\n const parsedTokenLiquidity = parseFixed(tokenLiquidity, SCALE);\n\n const totalLiquidity = totalSubPoolLiquidity.add(parsedTokenLiquidity);\n\n return formatFixed(totalLiquidity, SCALE);\n }\n}\n","import { BigNumberish } from '@ethersproject/bignumber';\nimport { AddressZero, Zero } from '@ethersproject/constants';\nimport { SOR, SwapTypes, SwapInfo } from '@defiverse/sor';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport {\n SwapType,\n BatchSwapStep,\n FundManagement,\n QueryWithSorInput,\n QueryWithSorOutput,\n} from './types';\nimport { Vault } from '@balancer-labs/typechain';\n\n/*\n * queryBatchSwap simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be\n * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.\n *\n * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)\n * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it\n * receives are the same that an equivalent `batchSwap` call would receive.\n */\nexport async function queryBatchSwap(\n vaultContract: Vault,\n swapType: SwapType,\n swaps: BatchSwapStep[],\n assets: string[]\n): Promise<string[]> {\n const funds: FundManagement = {\n sender: AddressZero,\n recipient: AddressZero,\n fromInternalBalance: false,\n toInternalBalance: false,\n };\n\n try {\n const deltas = await vaultContract.callStatic.queryBatchSwap(\n swapType,\n swaps,\n assets,\n funds\n );\n return deltas.map((d: BigNumberish) => d.toString());\n } catch (err) {\n throw `queryBatchSwap call error: ${err}`;\n }\n}\n\n/*\nUses SOR to create a batchSwap which is then queried onChain.\n*/\nexport async function queryBatchSwapWithSor(\n sor: SOR,\n vaultContract: Vault,\n queryWithSor: QueryWithSorInput\n): Promise<QueryWithSorOutput> {\n if (queryWithSor.fetchPools.fetchPools) await sor.fetchPools();\n\n const swaps: BatchSwapStep[][] = [];\n const assetArray: string[][] = [];\n // get path information for each tokenIn\n for (let i = 0; i < queryWithSor.tokensIn.length; i++) {\n const swap = await getSorSwapInfo(\n queryWithSor.tokensIn[i],\n queryWithSor.tokensOut[i],\n queryWithSor.swapType,\n queryWithSor.amounts[i].toString(),\n sor\n );\n if (!swap.returnAmount.gt(Zero))\n // Throw here because swaps with 0 amounts has no path and has misleading result for query\n throw new BalancerError(BalancerErrorCode.SWAP_ZERO_RETURN_AMOUNT);\n\n swaps.push(swap.swaps);\n assetArray.push(swap.tokenAddresses);\n }\n\n // Join swaps and assets together correctly\n const batchedSwaps = batchSwaps(assetArray, swaps);\n\n const returnTokens =\n queryWithSor.swapType === SwapType.SwapExactIn\n ? queryWithSor.tokensOut\n : queryWithSor.tokensIn;\n const returnAmounts: string[] = Array(returnTokens.length).fill('0');\n let deltas: BigNumberish[] = Array(batchedSwaps.assets.length).fill('0');\n try {\n // Onchain query\n deltas = await queryBatchSwap(\n vaultContract,\n queryWithSor.swapType,\n batchedSwaps.swaps,\n batchedSwaps.assets\n );\n\n if (deltas.length > 0) {\n returnTokens.forEach(\n (t, i) =>\n (returnAmounts[i] =\n deltas[batchedSwaps.assets.indexOf(t.toLowerCase())].toString() ??\n Zero.toString())\n );\n }\n } catch (err) {\n throw new BalancerError(BalancerErrorCode.QUERY_BATCH_SWAP);\n }\n\n return {\n returnAmounts,\n swaps: batchedSwaps.swaps,\n assets: batchedSwaps.assets,\n deltas: deltas.map((d) => d.toString()),\n };\n}\n\n/*\nUse SOR to get swapInfo for tokenIn>tokenOut.\nSwapInfos.swaps has path information.\n*/\nexport async function getSorSwapInfo(\n tokenIn: string,\n tokenOut: string,\n swapType: SwapType,\n amount: string,\n sor: SOR\n): Promise<SwapInfo> {\n const swapTypeSOR: SwapTypes =\n swapType === SwapType.SwapExactIn\n ? SwapTypes.SwapExactIn\n : SwapTypes.SwapExactOut;\n const swapInfo = await sor.getSwaps(\n tokenIn.toLowerCase(),\n tokenOut.toLowerCase(),\n swapTypeSOR,\n amount\n );\n return swapInfo;\n}\n\n/*\nFormat multiple individual swaps/assets into a single swap/asset.\n*/\nfunction batchSwaps(\n assetArray: string[][],\n swaps: BatchSwapStep[][]\n): { swaps: BatchSwapStep[]; assets: string[] } {\n // asset addresses without duplicates\n const newAssetArray = [...new Set(assetArray.flat())];\n\n // Update indices of each swap to use new asset array\n swaps.forEach((swap, i) => {\n swap.forEach((poolSwap) => {\n poolSwap.assetInIndex = newAssetArray.indexOf(\n assetArray[i][poolSwap.assetInIndex]\n );\n poolSwap.assetOutIndex = newAssetArray.indexOf(\n assetArray[i][poolSwap.assetOutIndex]\n );\n });\n });\n\n // Join Swaps into a single batchSwap\n const batchedSwaps = swaps.flat();\n return { swaps: batchedSwaps, assets: newAssetArray };\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.push(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.push(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n","import { __assign } from \"tslib\";\nimport { parse } from 'graphql';\nvar docCache = new Map();\nvar fragmentSourceMap = new Map();\nvar printFragmentWarnings = true;\nvar experimentalFragmentVariables = false;\nfunction normalize(string) {\n return string.replace(/[\\s,]+/g, ' ').trim();\n}\nfunction cacheKeyFromLoc(loc) {\n return normalize(loc.source.body.substring(loc.start, loc.end));\n}\nfunction processFragments(ast) {\n var seenKeys = new Set();\n var definitions = [];\n ast.definitions.forEach(function (fragmentDefinition) {\n if (fragmentDefinition.kind === 'FragmentDefinition') {\n var fragmentName = fragmentDefinition.name.value;\n var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);\n var sourceKeySet = fragmentSourceMap.get(fragmentName);\n if (sourceKeySet && !sourceKeySet.has(sourceKey)) {\n if (printFragmentWarnings) {\n console.warn(\"Warning: fragment with name \" + fragmentName + \" already exists.\\n\"\n + \"graphql-tag enforces all fragment names across your application to be unique; read more about\\n\"\n + \"this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names\");\n }\n }\n else if (!sourceKeySet) {\n fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);\n }\n sourceKeySet.add(sourceKey);\n if (!seenKeys.has(sourceKey)) {\n seenKeys.add(sourceKey);\n definitions.push(fragmentDefinition);\n }\n }\n else {\n definitions.push(fragmentDefinition);\n }\n });\n return __assign(__assign({}, ast), { definitions: definitions });\n}\nfunction stripLoc(doc) {\n var workSet = new Set(doc.definitions);\n workSet.forEach(function (node) {\n if (node.loc)\n delete node.loc;\n Object.keys(node).forEach(function (key) {\n var value = node[key];\n if (value && typeof value === 'object') {\n workSet.add(value);\n }\n });\n });\n var loc = doc.loc;\n if (loc) {\n delete loc.startToken;\n delete loc.endToken;\n }\n return doc;\n}\nfunction parseDocument(source) {\n var cacheKey = normalize(source);\n if (!docCache.has(cacheKey)) {\n var parsed = parse(source, {\n experimentalFragmentVariables: experimentalFragmentVariables,\n allowLegacyFragmentVariables: experimentalFragmentVariables\n });\n if (!parsed || parsed.kind !== 'Document') {\n throw new Error('Not a valid GraphQL document.');\n }\n docCache.set(cacheKey, stripLoc(processFragments(parsed)));\n }\n return docCache.get(cacheKey);\n}\nexport function gql(literals) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (typeof literals === 'string') {\n literals = [literals];\n }\n var result = literals[0];\n args.forEach(function (arg, i) {\n if (arg && arg.kind === 'Document') {\n result += arg.loc.source.body;\n }\n else {\n result += arg;\n }\n result += literals[i + 1];\n });\n return parseDocument(result);\n}\nexport function resetCaches() {\n docCache.clear();\n fragmentSourceMap.clear();\n}\nexport function disableFragmentWarnings() {\n printFragmentWarnings = false;\n}\nexport function enableExperimentalFragmentVariables() {\n experimentalFragmentVariables = true;\n}\nexport function disableExperimentalFragmentVariables() {\n experimentalFragmentVariables = false;\n}\nvar extras = {\n gql: gql,\n resetCaches: resetCaches,\n disableFragmentWarnings: disableFragmentWarnings,\n enableExperimentalFragmentVariables: enableExperimentalFragmentVariables,\n disableExperimentalFragmentVariables: disableExperimentalFragmentVariables\n};\n(function (gql_1) {\n gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;\n})(gql || (gql = {}));\ngql[\"default\"] = gql;\nexport default gql;\n//# sourceMappingURL=index.js.map","import { GraphQLClient } from 'graphql-request';\nimport * as Dom from 'graphql-request/dist/types.dom';\nimport gql from 'graphql-tag';\nexport type Maybe<T> = T | null;\nexport type InputMaybe<T> = Maybe<T>;\nexport type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };\nexport type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };\nexport type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };\n/** All built-in and custom scalars, mapped to their actual values */\nexport type Scalars = {\n ID: string;\n String: string;\n Boolean: boolean;\n Int: number;\n Float: number;\n BigDecimal: string;\n BigInt: string;\n Bytes: string;\n};\n\nexport type AmpUpdate = {\n __typename?: 'AmpUpdate';\n endAmp: Scalars['BigInt'];\n endTimestamp: Scalars['BigInt'];\n id: Scalars['ID'];\n poolId: Pool;\n scheduledTimestamp: Scalars['Int'];\n startAmp: Scalars['BigInt'];\n startTimestamp: Scalars['BigInt'];\n};\n\nexport type AmpUpdate_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n endAmp?: InputMaybe<Scalars['BigInt']>;\n endAmp_gt?: InputMaybe<Scalars['BigInt']>;\n endAmp_gte?: InputMaybe<Scalars['BigInt']>;\n endAmp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n endAmp_lt?: InputMaybe<Scalars['BigInt']>;\n endAmp_lte?: InputMaybe<Scalars['BigInt']>;\n endAmp_not?: InputMaybe<Scalars['BigInt']>;\n endAmp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n endTimestamp?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_gt?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_gte?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n endTimestamp_lt?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_lte?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_not?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolId?: InputMaybe<Scalars['String']>;\n poolId_?: InputMaybe<Pool_Filter>;\n poolId_contains?: InputMaybe<Scalars['String']>;\n poolId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_ends_with?: InputMaybe<Scalars['String']>;\n poolId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_gt?: InputMaybe<Scalars['String']>;\n poolId_gte?: InputMaybe<Scalars['String']>;\n poolId_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_lt?: InputMaybe<Scalars['String']>;\n poolId_lte?: InputMaybe<Scalars['String']>;\n poolId_not?: InputMaybe<Scalars['String']>;\n poolId_not_contains?: InputMaybe<Scalars['String']>;\n poolId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_starts_with?: InputMaybe<Scalars['String']>;\n poolId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n scheduledTimestamp?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_gt?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_gte?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n scheduledTimestamp_lt?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_lte?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_not?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n startAmp?: InputMaybe<Scalars['BigInt']>;\n startAmp_gt?: InputMaybe<Scalars['BigInt']>;\n startAmp_gte?: InputMaybe<Scalars['BigInt']>;\n startAmp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n startAmp_lt?: InputMaybe<Scalars['BigInt']>;\n startAmp_lte?: InputMaybe<Scalars['BigInt']>;\n startAmp_not?: InputMaybe<Scalars['BigInt']>;\n startAmp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n startTimestamp?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_gt?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_gte?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n startTimestamp_lt?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_lte?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_not?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n};\n\nexport enum AmpUpdate_OrderBy {\n EndAmp = 'endAmp',\n EndTimestamp = 'endTimestamp',\n Id = 'id',\n PoolId = 'poolId',\n ScheduledTimestamp = 'scheduledTimestamp',\n StartAmp = 'startAmp',\n StartTimestamp = 'startTimestamp'\n}\n\nexport type Balancer = {\n __typename?: 'Balancer';\n id: Scalars['ID'];\n poolCount: Scalars['Int'];\n pools?: Maybe<Array<Pool>>;\n totalLiquidity: Scalars['BigDecimal'];\n totalSwapCount: Scalars['BigInt'];\n totalSwapFee: Scalars['BigDecimal'];\n totalSwapVolume: Scalars['BigDecimal'];\n};\n\n\nexport type BalancerPoolsArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Pool_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<Pool_Filter>;\n};\n\nexport type BalancerSnapshot = {\n __typename?: 'BalancerSnapshot';\n id: Scalars['ID'];\n poolCount: Scalars['Int'];\n timestamp: Scalars['Int'];\n totalLiquidity: Scalars['BigDecimal'];\n totalSwapCount: Scalars['BigInt'];\n totalSwapFee: Scalars['BigDecimal'];\n totalSwapVolume: Scalars['BigDecimal'];\n vault: Balancer;\n};\n\nexport type BalancerSnapshot_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolCount?: InputMaybe<Scalars['Int']>;\n poolCount_gt?: InputMaybe<Scalars['Int']>;\n poolCount_gte?: InputMaybe<Scalars['Int']>;\n poolCount_in?: InputMaybe<Array<Scalars['Int']>>;\n poolCount_lt?: InputMaybe<Scalars['Int']>;\n poolCount_lte?: InputMaybe<Scalars['Int']>;\n poolCount_not?: InputMaybe<Scalars['Int']>;\n poolCount_not_in?: InputMaybe<Array<Scalars['Int']>>;\n timestamp?: InputMaybe<Scalars['Int']>;\n timestamp_gt?: InputMaybe<Scalars['Int']>;\n timestamp_gte?: InputMaybe<Scalars['Int']>;\n timestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n timestamp_lt?: InputMaybe<Scalars['Int']>;\n timestamp_lte?: InputMaybe<Scalars['Int']>;\n timestamp_not?: InputMaybe<Scalars['Int']>;\n timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n totalLiquidity?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalLiquidity_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_not?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapCount?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_gt?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_gte?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_in?: InputMaybe<Array<Scalars['BigInt']>>;\n totalSwapCount_lt?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_lte?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_not?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n totalSwapFee?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapFee_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n vault?: InputMaybe<Scalars['String']>;\n vault_?: InputMaybe<Balancer_Filter>;\n vault_contains?: InputMaybe<Scalars['String']>;\n vault_contains_nocase?: InputMaybe<Scalars['String']>;\n vault_ends_with?: InputMaybe<Scalars['String']>;\n vault_ends_with_nocase?: InputMaybe<Scalars['String']>;\n vault_gt?: InputMaybe<Scalars['String']>;\n vault_gte?: InputMaybe<Scalars['String']>;\n vault_in?: InputMaybe<Array<Scalars['String']>>;\n vault_lt?: InputMaybe<Scalars['String']>;\n vault_lte?: InputMaybe<Scalars['String']>;\n vault_not?: InputMaybe<Scalars['String']>;\n vault_not_contains?: InputMaybe<Scalars['String']>;\n vault_not_contains_nocase?: InputMaybe<Scalars['String']>;\n vault_not_ends_with?: InputMaybe<Scalars['String']>;\n vault_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n vault_not_in?: InputMaybe<Array<Scalars['String']>>;\n vault_not_starts_with?: InputMaybe<Scalars['String']>;\n vault_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n vault_starts_with?: InputMaybe<Scalars['String']>;\n vault_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum BalancerSnapshot_OrderBy {\n Id = 'id',\n PoolCount = 'poolCount',\n Timestamp = 'timestamp',\n TotalLiquidity = 'totalLiquidity',\n TotalSwapCount = 'totalSwapCount',\n TotalSwapFee = 'totalSwapFee',\n TotalSwapVolume = 'totalSwapVolume',\n Vault = 'vault'\n}\n\nexport type Balancer_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolCount?: InputMaybe<Scalars['Int']>;\n poolCount_gt?: InputMaybe<Scalars['Int']>;\n poolCount_gte?: InputMaybe<Scalars['Int']>;\n poolCount_in?: InputMaybe<Array<Scalars['Int']>>;\n poolCount_lt?: InputMaybe<Scalars['Int']>;\n poolCount_lte?: InputMaybe<Scalars['Int']>;\n poolCount_not?: InputMaybe<Scalars['Int']>;\n poolCount_not_in?: InputMaybe<Array<Scalars['Int']>>;\n pools_?: InputMaybe<Pool_Filter>;\n totalLiquidity?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalLiquidity_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_not?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapCount?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_gt?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_gte?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_in?: InputMaybe<Array<Scalars['BigInt']>>;\n totalSwapCount_lt?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_lte?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_not?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n totalSwapFee?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapFee_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum Balancer_OrderBy {\n Id = 'id',\n PoolCount = 'poolCount',\n Pools = 'pools',\n TotalLiquidity = 'totalLiquidity',\n TotalSwapCount = 'totalSwapCount',\n TotalSwapFee = 'totalSwapFee',\n TotalSwapVolume = 'totalSwapVolume'\n}\n\nexport type BlockChangedFilter = {\n number_gte: Scalars['Int'];\n};\n\nexport type Block_Height = {\n hash?: InputMaybe<Scalars['Bytes']>;\n number?: InputMaybe<Scalars['Int']>;\n number_gte?: InputMaybe<Scalars['Int']>;\n};\n\nexport type GradualWeightUpdate = {\n __typename?: 'GradualWeightUpdate';\n endTimestamp: Scalars['BigInt'];\n endWeights: Array<Scalars['BigInt']>;\n id: Scalars['ID'];\n poolId: Pool;\n scheduledTimestamp: Scalars['Int'];\n startTimestamp: Scalars['BigInt'];\n startWeights: Array<Scalars['BigInt']>;\n};\n\nexport type GradualWeightUpdate_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n endTimestamp?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_gt?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_gte?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n endTimestamp_lt?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_lte?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_not?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n endWeights?: InputMaybe<Array<Scalars['BigInt']>>;\n endWeights_contains?: InputMaybe<Array<Scalars['BigInt']>>;\n endWeights_contains_nocase?: InputMaybe<Array<Scalars['BigInt']>>;\n endWeights_not?: InputMaybe<Array<Scalars['BigInt']>>;\n endWeights_not_contains?: InputMaybe<Array<Scalars['BigInt']>>;\n endWeights_not_contains_nocase?: InputMaybe<Array<Scalars['BigInt']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolId?: InputMaybe<Scalars['String']>;\n poolId_?: InputMaybe<Pool_Filter>;\n poolId_contains?: InputMaybe<Scalars['String']>;\n poolId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_ends_with?: InputMaybe<Scalars['String']>;\n poolId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_gt?: InputMaybe<Scalars['String']>;\n poolId_gte?: InputMaybe<Scalars['String']>;\n poolId_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_lt?: InputMaybe<Scalars['String']>;\n poolId_lte?: InputMaybe<Scalars['String']>;\n poolId_not?: InputMaybe<Scalars['String']>;\n poolId_not_contains?: InputMaybe<Scalars['String']>;\n poolId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_starts_with?: InputMaybe<Scalars['String']>;\n poolId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n scheduledTimestamp?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_gt?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_gte?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n scheduledTimestamp_lt?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_lte?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_not?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n startTimestamp?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_gt?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_gte?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n startTimestamp_lt?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_lte?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_not?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n startWeights?: InputMaybe<Array<Scalars['BigInt']>>;\n startWeights_contains?: InputMaybe<Array<Scalars['BigInt']>>;\n startWeights_contains_nocase?: InputMaybe<Array<Scalars['BigInt']>>;\n startWeights_not?: InputMaybe<Array<Scalars['BigInt']>>;\n startWeights_not_contains?: InputMaybe<Array<Scalars['BigInt']>>;\n startWeights_not_contains_nocase?: InputMaybe<Array<Scalars['BigInt']>>;\n};\n\nexport enum GradualWeightUpdate_OrderBy {\n EndTimestamp = 'endTimestamp',\n EndWeights = 'endWeights',\n Id = 'id',\n PoolId = 'poolId',\n ScheduledTimestamp = 'scheduledTimestamp',\n StartTimestamp = 'startTimestamp',\n StartWeights = 'startWeights'\n}\n\nexport enum InvestType {\n Exit = 'Exit',\n Join = 'Join'\n}\n\nexport type JoinExit = {\n __typename?: 'JoinExit';\n amounts: Array<Scalars['BigDecimal']>;\n id: Scalars['ID'];\n pool: Pool;\n sender: Scalars['Bytes'];\n timestamp: Scalars['Int'];\n tx: Scalars['Bytes'];\n type: InvestType;\n user: User;\n valueUSD?: Maybe<Scalars['BigDecimal']>;\n};\n\nexport type JoinExit_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n amounts?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_contains?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_contains_nocase?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_not?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_not_contains?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_not_contains_nocase?: InputMaybe<Array<Scalars['BigDecimal']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n pool?: InputMaybe<Scalars['String']>;\n pool_?: InputMaybe<Pool_Filter>;\n pool_contains?: InputMaybe<Scalars['String']>;\n pool_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_ends_with?: InputMaybe<Scalars['String']>;\n pool_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_gt?: InputMaybe<Scalars['String']>;\n pool_gte?: InputMaybe<Scalars['String']>;\n pool_in?: InputMaybe<Array<Scalars['String']>>;\n pool_lt?: InputMaybe<Scalars['String']>;\n pool_lte?: InputMaybe<Scalars['String']>;\n pool_not?: InputMaybe<Scalars['String']>;\n pool_not_contains?: InputMaybe<Scalars['String']>;\n pool_not_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_not_ends_with?: InputMaybe<Scalars['String']>;\n pool_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_not_in?: InputMaybe<Array<Scalars['String']>>;\n pool_not_starts_with?: InputMaybe<Scalars['String']>;\n pool_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n pool_starts_with?: InputMaybe<Scalars['String']>;\n pool_starts_with_nocase?: InputMaybe<Scalars['String']>;\n sender?: InputMaybe<Scalars['Bytes']>;\n sender_contains?: InputMaybe<Scalars['Bytes']>;\n sender_gt?: InputMaybe<Scalars['Bytes']>;\n sender_gte?: InputMaybe<Scalars['Bytes']>;\n sender_in?: InputMaybe<Array<Scalars['Bytes']>>;\n sender_lt?: InputMaybe<Scalars['Bytes']>;\n sender_lte?: InputMaybe<Scalars['Bytes']>;\n sender_not?: InputMaybe<Scalars['Bytes']>;\n sender_not_contains?: InputMaybe<Scalars['Bytes']>;\n sender_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n timestamp?: InputMaybe<Scalars['Int']>;\n timestamp_gt?: InputMaybe<Scalars['Int']>;\n timestamp_gte?: InputMaybe<Scalars['Int']>;\n timestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n timestamp_lt?: InputMaybe<Scalars['Int']>;\n timestamp_lte?: InputMaybe<Scalars['Int']>;\n timestamp_not?: InputMaybe<Scalars['Int']>;\n timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n tx?: InputMaybe<Scalars['Bytes']>;\n tx_contains?: InputMaybe<Scalars['Bytes']>;\n tx_gt?: InputMaybe<Scalars['Bytes']>;\n tx_gte?: InputMaybe<Scalars['Bytes']>;\n tx_in?: InputMaybe<Array<Scalars['Bytes']>>;\n tx_lt?: InputMaybe<Scalars['Bytes']>;\n tx_lte?: InputMaybe<Scalars['Bytes']>;\n tx_not?: InputMaybe<Scalars['Bytes']>;\n tx_not_contains?: InputMaybe<Scalars['Bytes']>;\n tx_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n type?: InputMaybe<InvestType>;\n type_in?: InputMaybe<Array<InvestType>>;\n type_not?: InputMaybe<InvestType>;\n type_not_in?: InputMaybe<Array<InvestType>>;\n user?: InputMaybe<Scalars['String']>;\n user_?: InputMaybe<User_Filter>;\n user_contains?: InputMaybe<Scalars['String']>;\n user_contains_nocase?: InputMaybe<Scalars['String']>;\n user_ends_with?: InputMaybe<Scalars['String']>;\n user_ends_with_nocase?: InputMaybe<Scalars['String']>;\n user_gt?: InputMaybe<Scalars['String']>;\n user_gte?: InputMaybe<Scalars['String']>;\n user_in?: InputMaybe<Array<Scalars['String']>>;\n user_lt?: InputMaybe<Scalars['String']>;\n user_lte?: InputMaybe<Scalars['String']>;\n user_not?: InputMaybe<Scalars['String']>;\n user_not_contains?: InputMaybe<Scalars['String']>;\n user_not_contains_nocase?: InputMaybe<Scalars['String']>;\n user_not_ends_with?: InputMaybe<Scalars['String']>;\n user_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n user_not_in?: InputMaybe<Array<Scalars['String']>>;\n user_not_starts_with?: InputMaybe<Scalars['String']>;\n user_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n user_starts_with?: InputMaybe<Scalars['String']>;\n user_starts_with_nocase?: InputMaybe<Scalars['String']>;\n valueUSD?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_gt?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_gte?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n valueUSD_lt?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_lte?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_not?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum JoinExit_OrderBy {\n Amounts = 'amounts',\n Id = 'id',\n Pool = 'pool',\n Sender = 'sender',\n Timestamp = 'timestamp',\n Tx = 'tx',\n Type = 'type',\n User = 'user',\n ValueUsd = 'valueUSD'\n}\n\nexport type LatestPrice = {\n __typename?: 'LatestPrice';\n asset: Scalars['Bytes'];\n block: Scalars['BigInt'];\n id: Scalars['ID'];\n poolId: Pool;\n price: Scalars['BigDecimal'];\n pricingAsset: Scalars['Bytes'];\n};\n\nexport type LatestPrice_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n asset?: InputMaybe<Scalars['Bytes']>;\n asset_contains?: InputMaybe<Scalars['Bytes']>;\n asset_gt?: InputMaybe<Scalars['Bytes']>;\n asset_gte?: InputMaybe<Scalars['Bytes']>;\n asset_in?: InputMaybe<Array<Scalars['Bytes']>>;\n asset_lt?: InputMaybe<Scalars['Bytes']>;\n asset_lte?: InputMaybe<Scalars['Bytes']>;\n asset_not?: InputMaybe<Scalars['Bytes']>;\n asset_not_contains?: InputMaybe<Scalars['Bytes']>;\n asset_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n block?: InputMaybe<Scalars['BigInt']>;\n block_gt?: InputMaybe<Scalars['BigInt']>;\n block_gte?: InputMaybe<Scalars['BigInt']>;\n block_in?: InputMaybe<Array<Scalars['BigInt']>>;\n block_lt?: InputMaybe<Scalars['BigInt']>;\n block_lte?: InputMaybe<Scalars['BigInt']>;\n block_not?: InputMaybe<Scalars['BigInt']>;\n block_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolId?: InputMaybe<Scalars['String']>;\n poolId_?: InputMaybe<Pool_Filter>;\n poolId_contains?: InputMaybe<Scalars['String']>;\n poolId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_ends_with?: InputMaybe<Scalars['String']>;\n poolId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_gt?: InputMaybe<Scalars['String']>;\n poolId_gte?: InputMaybe<Scalars['String']>;\n poolId_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_lt?: InputMaybe<Scalars['String']>;\n poolId_lte?: InputMaybe<Scalars['String']>;\n poolId_not?: InputMaybe<Scalars['String']>;\n poolId_not_contains?: InputMaybe<Scalars['String']>;\n poolId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_starts_with?: InputMaybe<Scalars['String']>;\n poolId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n price?: InputMaybe<Scalars['BigDecimal']>;\n price_gt?: InputMaybe<Scalars['BigDecimal']>;\n price_gte?: InputMaybe<Scalars['BigDecimal']>;\n price_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n price_lt?: InputMaybe<Scalars['BigDecimal']>;\n price_lte?: InputMaybe<Scalars['BigDecimal']>;\n price_not?: InputMaybe<Scalars['BigDecimal']>;\n price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n pricingAsset?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_contains?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_gt?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_gte?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_in?: InputMaybe<Array<Scalars['Bytes']>>;\n pricingAsset_lt?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_lte?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_not?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_not_contains?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n};\n\nexport enum LatestPrice_OrderBy {\n Asset = 'asset',\n Block = 'block',\n Id = 'id',\n PoolId = 'poolId',\n Price = 'price',\n PricingAsset = 'pricingAsset'\n}\n\nexport type ManagementOperation = {\n __typename?: 'ManagementOperation';\n cashDelta: Scalars['BigDecimal'];\n id: Scalars['ID'];\n managedDelta: Scalars['BigDecimal'];\n poolTokenId: PoolToken;\n timestamp: Scalars['Int'];\n type: OperationType;\n};\n\nexport type ManagementOperation_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n cashDelta?: InputMaybe<Scalars['BigDecimal']>;\n cashDelta_gt?: InputMaybe<Scalars['BigDecimal']>;\n cashDelta_gte?: InputMaybe<Scalars['BigDecimal']>;\n cashDelta_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n cashDelta_lt?: InputMaybe<Scalars['BigDecimal']>;\n cashDelta_lte?: InputMaybe<Scalars['BigDecimal']>;\n cashDelta_not?: InputMaybe<Scalars['BigDecimal']>;\n cashDelta_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n managedDelta?: InputMaybe<Scalars['BigDecimal']>;\n managedDelta_gt?: InputMaybe<Scalars['BigDecimal']>;\n managedDelta_gte?: InputMaybe<Scalars['BigDecimal']>;\n managedDelta_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n managedDelta_lt?: InputMaybe<Scalars['BigDecimal']>;\n managedDelta_lte?: InputMaybe<Scalars['BigDecimal']>;\n managedDelta_not?: InputMaybe<Scalars['BigDecimal']>;\n managedDelta_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n poolTokenId?: InputMaybe<Scalars['String']>;\n poolTokenId_?: InputMaybe<PoolToken_Filter>;\n poolTokenId_contains?: InputMaybe<Scalars['String']>;\n poolTokenId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolTokenId_ends_with?: InputMaybe<Scalars['String']>;\n poolTokenId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolTokenId_gt?: InputMaybe<Scalars['String']>;\n poolTokenId_gte?: InputMaybe<Scalars['String']>;\n poolTokenId_in?: InputMaybe<Array<Scalars['String']>>;\n poolTokenId_lt?: InputMaybe<Scalars['String']>;\n poolTokenId_lte?: InputMaybe<Scalars['String']>;\n poolTokenId_not?: InputMaybe<Scalars['String']>;\n poolTokenId_not_contains?: InputMaybe<Scalars['String']>;\n poolTokenId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolTokenId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolTokenId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolTokenId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolTokenId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolTokenId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolTokenId_starts_with?: InputMaybe<Scalars['String']>;\n poolTokenId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n timestamp?: InputMaybe<Scalars['Int']>;\n timestamp_gt?: InputMaybe<Scalars['Int']>;\n timestamp_gte?: InputMaybe<Scalars['Int']>;\n timestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n timestamp_lt?: InputMaybe<Scalars['Int']>;\n timestamp_lte?: InputMaybe<Scalars['Int']>;\n timestamp_not?: InputMaybe<Scalars['Int']>;\n timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n type?: InputMaybe<OperationType>;\n type_in?: InputMaybe<Array<OperationType>>;\n type_not?: InputMaybe<OperationType>;\n type_not_in?: InputMaybe<Array<OperationType>>;\n};\n\nexport enum ManagementOperation_OrderBy {\n CashDelta = 'cashDelta',\n Id = 'id',\n ManagedDelta = 'managedDelta',\n PoolTokenId = 'poolTokenId',\n Timestamp = 'timestamp',\n Type = 'type'\n}\n\nexport enum OperationType {\n Deposit = 'Deposit',\n Update = 'Update',\n Withdraw = 'Withdraw'\n}\n\n/** Defines the order direction, either ascending or descending */\nexport enum OrderDirection {\n Asc = 'asc',\n Desc = 'desc'\n}\n\nexport type Pool = {\n __typename?: 'Pool';\n address: Scalars['Bytes'];\n alpha?: Maybe<Scalars['BigDecimal']>;\n amp?: Maybe<Scalars['BigInt']>;\n baseToken?: Maybe<Scalars['Bytes']>;\n beta?: Maybe<Scalars['BigDecimal']>;\n c?: Maybe<Scalars['BigDecimal']>;\n createTime: Scalars['Int'];\n dSq?: Maybe<Scalars['BigDecimal']>;\n delta?: Maybe<Scalars['BigDecimal']>;\n epsilon?: Maybe<Scalars['BigDecimal']>;\n expiryTime?: Maybe<Scalars['BigInt']>;\n factory?: Maybe<Scalars['Bytes']>;\n historicalValues?: Maybe<Array<PoolHistoricalLiquidity>>;\n holdersCount: Scalars['BigInt'];\n id: Scalars['ID'];\n isInRecoveryMode?: Maybe<Scalars['Boolean']>;\n isPaused?: Maybe<Scalars['Boolean']>;\n lambda?: Maybe<Scalars['BigDecimal']>;\n lowerTarget?: Maybe<Scalars['BigDecimal']>;\n mainIndex?: Maybe<Scalars['Int']>;\n managementFee?: Maybe<Scalars['BigDecimal']>;\n name?: Maybe<Scalars['String']>;\n oracleEnabled: Scalars['Boolean'];\n owner?: Maybe<Scalars['Bytes']>;\n poolType?: Maybe<Scalars['String']>;\n poolTypeVersion?: Maybe<Scalars['Int']>;\n priceRateProviders?: Maybe<Array<PriceRateProvider>>;\n principalToken?: Maybe<Scalars['Bytes']>;\n protocolAumFeeCache?: Maybe<Scalars['BigDecimal']>;\n protocolId?: Maybe<Scalars['Int']>;\n protocolSwapFeeCache?: Maybe<Scalars['BigDecimal']>;\n protocolYieldFeeCache?: Maybe<Scalars['BigDecimal']>;\n root3Alpha?: Maybe<Scalars['BigDecimal']>;\n s?: Maybe<Scalars['BigDecimal']>;\n shares?: Maybe<Array<PoolShare>>;\n snapshots?: Maybe<Array<PoolSnapshot>>;\n sqrtAlpha?: Maybe<Scalars['BigDecimal']>;\n sqrtBeta?: Maybe<Scalars['BigDecimal']>;\n strategyType: Scalars['Int'];\n swapEnabled: Scalars['Boolean'];\n swapFee: Scalars['BigDecimal'];\n swaps?: Maybe<Array<Swap>>;\n swapsCount: Scalars['BigInt'];\n symbol?: Maybe<Scalars['String']>;\n tauAlphaX?: Maybe<Scalars['BigDecimal']>;\n tauAlphaY?: Maybe<Scalars['BigDecimal']>;\n tauBetaX?: Maybe<Scalars['BigDecimal']>;\n tauBetaY?: Maybe<Scalars['BigDecimal']>;\n tokens?: Maybe<Array<PoolToken>>;\n tokensList: Array<Scalars['Bytes']>;\n totalLiquidity: Scalars['BigDecimal'];\n totalShares: Scalars['BigDecimal'];\n totalSwapFee: Scalars['BigDecimal'];\n totalSwapVolume: Scalars['BigDecimal'];\n totalWeight?: Maybe<Scalars['BigDecimal']>;\n tx?: Maybe<Scalars['Bytes']>;\n u?: Maybe<Scalars['BigDecimal']>;\n unitSeconds?: Maybe<Scalars['BigInt']>;\n upperTarget?: Maybe<Scalars['BigDecimal']>;\n v?: Maybe<Scalars['BigDecimal']>;\n vaultID: Balancer;\n w?: Maybe<Scalars['BigDecimal']>;\n weightUpdates?: Maybe<Array<GradualWeightUpdate>>;\n wrappedIndex?: Maybe<Scalars['Int']>;\n z?: Maybe<Scalars['BigDecimal']>;\n};\n\n\nexport type PoolHistoricalValuesArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolHistoricalLiquidity_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<PoolHistoricalLiquidity_Filter>;\n};\n\n\nexport type PoolPriceRateProvidersArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PriceRateProvider_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<PriceRateProvider_Filter>;\n};\n\n\nexport type PoolSharesArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<PoolShare_Filter>;\n};\n\n\nexport type PoolSnapshotsArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<PoolSnapshot_Filter>;\n};\n\n\nexport type PoolSwapsArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Swap_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<Swap_Filter>;\n};\n\n\nexport type PoolTokensArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolToken_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<PoolToken_Filter>;\n};\n\n\nexport type PoolWeightUpdatesArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GradualWeightUpdate_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<GradualWeightUpdate_Filter>;\n};\n\nexport type PoolContract = {\n __typename?: 'PoolContract';\n id: Scalars['ID'];\n pool: Pool;\n};\n\nexport type PoolContract_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n pool?: InputMaybe<Scalars['String']>;\n pool_?: InputMaybe<Pool_Filter>;\n pool_contains?: InputMaybe<Scalars['String']>;\n pool_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_ends_with?: InputMaybe<Scalars['String']>;\n pool_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_gt?: InputMaybe<Scalars['String']>;\n pool_gte?: InputMaybe<Scalars['String']>;\n pool_in?: InputMaybe<Array<Scalars['String']>>;\n pool_lt?: InputMaybe<Scalars['String']>;\n pool_lte?: InputMaybe<Scalars['String']>;\n pool_not?: InputMaybe<Scalars['String']>;\n pool_not_contains?: InputMaybe<Scalars['String']>;\n pool_not_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_not_ends_with?: InputMaybe<Scalars['String']>;\n pool_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_not_in?: InputMaybe<Array<Scalars['String']>>;\n pool_not_starts_with?: InputMaybe<Scalars['String']>;\n pool_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n pool_starts_with?: InputMaybe<Scalars['String']>;\n pool_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum PoolContract_OrderBy {\n Id = 'id',\n Pool = 'pool'\n}\n\nexport type PoolHistoricalLiquidity = {\n __typename?: 'PoolHistoricalLiquidity';\n block: Scalars['BigInt'];\n id: Scalars['ID'];\n poolId: Pool;\n poolLiquidity: Scalars['BigDecimal'];\n poolShareValue: Scalars['BigDecimal'];\n poolTotalShares: Scalars['BigDecimal'];\n pricingAsset: Scalars['Bytes'];\n};\n\nexport type PoolHistoricalLiquidity_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n block?: InputMaybe<Scalars['BigInt']>;\n block_gt?: InputMaybe<Scalars['BigInt']>;\n block_gte?: InputMaybe<Scalars['BigInt']>;\n block_in?: InputMaybe<Array<Scalars['BigInt']>>;\n block_lt?: InputMaybe<Scalars['BigInt']>;\n block_lte?: InputMaybe<Scalars['BigInt']>;\n block_not?: InputMaybe<Scalars['BigInt']>;\n block_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolId?: InputMaybe<Scalars['String']>;\n poolId_?: InputMaybe<Pool_Filter>;\n poolId_contains?: InputMaybe<Scalars['String']>;\n poolId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_ends_with?: InputMaybe<Scalars['String']>;\n poolId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_gt?: InputMaybe<Scalars['String']>;\n poolId_gte?: InputMaybe<Scalars['String']>;\n poolId_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_lt?: InputMaybe<Scalars['String']>;\n poolId_lte?: InputMaybe<Scalars['String']>;\n poolId_not?: InputMaybe<Scalars['String']>;\n poolId_not_contains?: InputMaybe<Scalars['String']>;\n poolId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_starts_with?: InputMaybe<Scalars['String']>;\n poolId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolLiquidity?: InputMaybe<Scalars['BigDecimal']>;\n poolLiquidity_gt?: InputMaybe<Scalars['BigDecimal']>;\n poolLiquidity_gte?: InputMaybe<Scalars['BigDecimal']>;\n poolLiquidity_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n poolLiquidity_lt?: InputMaybe<Scalars['BigDecimal']>;\n poolLiquidity_lte?: InputMaybe<Scalars['BigDecimal']>;\n poolLiquidity_not?: InputMaybe<Scalars['BigDecimal']>;\n poolLiquidity_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n poolShareValue?: InputMaybe<Scalars['BigDecimal']>;\n poolShareValue_gt?: InputMaybe<Scalars['BigDecimal']>;\n poolShareValue_gte?: InputMaybe<Scalars['BigDecimal']>;\n poolShareValue_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n poolShareValue_lt?: InputMaybe<Scalars['BigDecimal']>;\n poolShareValue_lte?: InputMaybe<Scalars['BigDecimal']>;\n poolShareValue_not?: InputMaybe<Scalars['BigDecimal']>;\n poolShareValue_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n poolTotalShares?: InputMaybe<Scalars['BigDecimal']>;\n poolTotalShares_gt?: InputMaybe<Scalars['BigDecimal']>;\n poolTotalShares_gte?: InputMaybe<Scalars['BigDecimal']>;\n poolTotalShares_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n poolTotalShares_lt?: InputMaybe<Scalars['BigDecimal']>;\n poolTotalShares_lte?: InputMaybe<Scalars['BigDecimal']>;\n poolTotalShares_not?: InputMaybe<Scalars['BigDecimal']>;\n poolTotalShares_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n pricingAsset?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_contains?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_gt?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_gte?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_in?: InputMaybe<Array<Scalars['Bytes']>>;\n pricingAsset_lt?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_lte?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_not?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_not_contains?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n};\n\nexport enum PoolHistoricalLiquidity_OrderBy {\n Block = 'block',\n Id = 'id',\n PoolId = 'poolId',\n PoolLiquidity = 'poolLiquidity',\n PoolShareValue = 'poolShareValue',\n PoolTotalShares = 'poolTotalShares',\n PricingAsset = 'pricingAsset'\n}\n\nexport type PoolShare = {\n __typename?: 'PoolShare';\n balance: Scalars['BigDecimal'];\n id: Scalars['ID'];\n poolId: Pool;\n userAddress: User;\n};\n\nexport type PoolShare_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n balance?: InputMaybe<Scalars['BigDecimal']>;\n balance_gt?: InputMaybe<Scalars['BigDecimal']>;\n balance_gte?: InputMaybe<Scalars['BigDecimal']>;\n balance_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n balance_lt?: InputMaybe<Scalars['BigDecimal']>;\n balance_lte?: InputMaybe<Scalars['BigDecimal']>;\n balance_not?: InputMaybe<Scalars['BigDecimal']>;\n balance_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolId?: InputMaybe<Scalars['String']>;\n poolId_?: InputMaybe<Pool_Filter>;\n poolId_contains?: InputMaybe<Scalars['String']>;\n poolId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_ends_with?: InputMaybe<Scalars['String']>;\n poolId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_gt?: InputMaybe<Scalars['String']>;\n poolId_gte?: InputMaybe<Scalars['String']>;\n poolId_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_lt?: InputMaybe<Scalars['String']>;\n poolId_lte?: InputMaybe<Scalars['String']>;\n poolId_not?: InputMaybe<Scalars['String']>;\n poolId_not_contains?: InputMaybe<Scalars['String']>;\n poolId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_starts_with?: InputMaybe<Scalars['String']>;\n poolId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress?: InputMaybe<Scalars['String']>;\n userAddress_?: InputMaybe<User_Filter>;\n userAddress_contains?: InputMaybe<Scalars['String']>;\n userAddress_contains_nocase?: InputMaybe<Scalars['String']>;\n userAddress_ends_with?: InputMaybe<Scalars['String']>;\n userAddress_ends_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress_gt?: InputMaybe<Scalars['String']>;\n userAddress_gte?: InputMaybe<Scalars['String']>;\n userAddress_in?: InputMaybe<Array<Scalars['String']>>;\n userAddress_lt?: InputMaybe<Scalars['String']>;\n userAddress_lte?: InputMaybe<Scalars['String']>;\n userAddress_not?: InputMaybe<Scalars['String']>;\n userAddress_not_contains?: InputMaybe<Scalars['String']>;\n userAddress_not_contains_nocase?: InputMaybe<Scalars['String']>;\n userAddress_not_ends_with?: InputMaybe<Scalars['String']>;\n userAddress_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress_not_in?: InputMaybe<Array<Scalars['String']>>;\n userAddress_not_starts_with?: InputMaybe<Scalars['String']>;\n userAddress_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress_starts_with?: InputMaybe<Scalars['String']>;\n userAddress_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum PoolShare_OrderBy {\n Balance = 'balance',\n Id = 'id',\n PoolId = 'poolId',\n UserAddress = 'userAddress'\n}\n\nexport type PoolSnapshot = {\n __typename?: 'PoolSnapshot';\n amounts: Array<Scalars['BigDecimal']>;\n holdersCount: Scalars['BigInt'];\n id: Scalars['ID'];\n liquidity: Scalars['BigDecimal'];\n pool: Pool;\n swapFees: Scalars['BigDecimal'];\n swapVolume: Scalars['BigDecimal'];\n swapsCount: Scalars['BigInt'];\n timestamp: Scalars['Int'];\n totalShares: Scalars['BigDecimal'];\n};\n\nexport type PoolSnapshot_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n amounts?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_contains?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_contains_nocase?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_not?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_not_contains?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amounts_not_contains_nocase?: InputMaybe<Array<Scalars['BigDecimal']>>;\n holdersCount?: InputMaybe<Scalars['BigInt']>;\n holdersCount_gt?: InputMaybe<Scalars['BigInt']>;\n holdersCount_gte?: InputMaybe<Scalars['BigInt']>;\n holdersCount_in?: InputMaybe<Array<Scalars['BigInt']>>;\n holdersCount_lt?: InputMaybe<Scalars['BigInt']>;\n holdersCount_lte?: InputMaybe<Scalars['BigInt']>;\n holdersCount_not?: InputMaybe<Scalars['BigInt']>;\n holdersCount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n liquidity?: InputMaybe<Scalars['BigDecimal']>;\n liquidity_gt?: InputMaybe<Scalars['BigDecimal']>;\n liquidity_gte?: InputMaybe<Scalars['BigDecimal']>;\n liquidity_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n liquidity_lt?: InputMaybe<Scalars['BigDecimal']>;\n liquidity_lte?: InputMaybe<Scalars['BigDecimal']>;\n liquidity_not?: InputMaybe<Scalars['BigDecimal']>;\n liquidity_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n pool?: InputMaybe<Scalars['String']>;\n pool_?: InputMaybe<Pool_Filter>;\n pool_contains?: InputMaybe<Scalars['String']>;\n pool_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_ends_with?: InputMaybe<Scalars['String']>;\n pool_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_gt?: InputMaybe<Scalars['String']>;\n pool_gte?: InputMaybe<Scalars['String']>;\n pool_in?: InputMaybe<Array<Scalars['String']>>;\n pool_lt?: InputMaybe<Scalars['String']>;\n pool_lte?: InputMaybe<Scalars['String']>;\n pool_not?: InputMaybe<Scalars['String']>;\n pool_not_contains?: InputMaybe<Scalars['String']>;\n pool_not_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_not_ends_with?: InputMaybe<Scalars['String']>;\n pool_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_not_in?: InputMaybe<Array<Scalars['String']>>;\n pool_not_starts_with?: InputMaybe<Scalars['String']>;\n pool_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n pool_starts_with?: InputMaybe<Scalars['String']>;\n pool_starts_with_nocase?: InputMaybe<Scalars['String']>;\n swapFees?: InputMaybe<Scalars['BigDecimal']>;\n swapFees_gt?: InputMaybe<Scalars['BigDecimal']>;\n swapFees_gte?: InputMaybe<Scalars['BigDecimal']>;\n swapFees_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n swapFees_lt?: InputMaybe<Scalars['BigDecimal']>;\n swapFees_lte?: InputMaybe<Scalars['BigDecimal']>;\n swapFees_not?: InputMaybe<Scalars['BigDecimal']>;\n swapFees_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n swapVolume?: InputMaybe<Scalars['BigDecimal']>;\n swapVolume_gt?: InputMaybe<Scalars['BigDecimal']>;\n swapVolume_gte?: InputMaybe<Scalars['BigDecimal']>;\n swapVolume_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n swapVolume_lt?: InputMaybe<Scalars['BigDecimal']>;\n swapVolume_lte?: InputMaybe<Scalars['BigDecimal']>;\n swapVolume_not?: InputMaybe<Scalars['BigDecimal']>;\n swapVolume_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n swapsCount?: InputMaybe<Scalars['BigInt']>;\n swapsCount_gt?: InputMaybe<Scalars['BigInt']>;\n swapsCount_gte?: InputMaybe<Scalars['BigInt']>;\n swapsCount_in?: InputMaybe<Array<Scalars['BigInt']>>;\n swapsCount_lt?: InputMaybe<Scalars['BigInt']>;\n swapsCount_lte?: InputMaybe<Scalars['BigInt']>;\n swapsCount_not?: InputMaybe<Scalars['BigInt']>;\n swapsCount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n timestamp?: InputMaybe<Scalars['Int']>;\n timestamp_gt?: InputMaybe<Scalars['Int']>;\n timestamp_gte?: InputMaybe<Scalars['Int']>;\n timestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n timestamp_lt?: InputMaybe<Scalars['Int']>;\n timestamp_lte?: InputMaybe<Scalars['Int']>;\n timestamp_not?: InputMaybe<Scalars['Int']>;\n timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n totalShares?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalShares_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_not?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum PoolSnapshot_OrderBy {\n Amounts = 'amounts',\n HoldersCount = 'holdersCount',\n Id = 'id',\n Liquidity = 'liquidity',\n Pool = 'pool',\n SwapFees = 'swapFees',\n SwapVolume = 'swapVolume',\n SwapsCount = 'swapsCount',\n Timestamp = 'timestamp',\n TotalShares = 'totalShares'\n}\n\nexport type PoolToken = {\n __typename?: 'PoolToken';\n address: Scalars['String'];\n assetManager: Scalars['Bytes'];\n balance: Scalars['BigDecimal'];\n cashBalance: Scalars['BigDecimal'];\n decimals: Scalars['Int'];\n id: Scalars['ID'];\n index?: Maybe<Scalars['Int']>;\n isExemptFromYieldProtocolFee?: Maybe<Scalars['Boolean']>;\n managedBalance: Scalars['BigDecimal'];\n managements?: Maybe<Array<ManagementOperation>>;\n name: Scalars['String'];\n poolId?: Maybe<Pool>;\n priceRate: Scalars['BigDecimal'];\n symbol: Scalars['String'];\n token: Token;\n weight?: Maybe<Scalars['BigDecimal']>;\n};\n\n\nexport type PoolTokenManagementsArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<ManagementOperation_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<ManagementOperation_Filter>;\n};\n\nexport type PoolToken_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n address?: InputMaybe<Scalars['String']>;\n address_contains?: InputMaybe<Scalars['String']>;\n address_contains_nocase?: InputMaybe<Scalars['String']>;\n address_ends_with?: InputMaybe<Scalars['String']>;\n address_ends_with_nocase?: InputMaybe<Scalars['String']>;\n address_gt?: InputMaybe<Scalars['String']>;\n address_gte?: InputMaybe<Scalars['String']>;\n address_in?: InputMaybe<Array<Scalars['String']>>;\n address_lt?: InputMaybe<Scalars['String']>;\n address_lte?: InputMaybe<Scalars['String']>;\n address_not?: InputMaybe<Scalars['String']>;\n address_not_contains?: InputMaybe<Scalars['String']>;\n address_not_contains_nocase?: InputMaybe<Scalars['String']>;\n address_not_ends_with?: InputMaybe<Scalars['String']>;\n address_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n address_not_in?: InputMaybe<Array<Scalars['String']>>;\n address_not_starts_with?: InputMaybe<Scalars['String']>;\n address_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n address_starts_with?: InputMaybe<Scalars['String']>;\n address_starts_with_nocase?: InputMaybe<Scalars['String']>;\n assetManager?: InputMaybe<Scalars['Bytes']>;\n assetManager_contains?: InputMaybe<Scalars['Bytes']>;\n assetManager_gt?: InputMaybe<Scalars['Bytes']>;\n assetManager_gte?: InputMaybe<Scalars['Bytes']>;\n assetManager_in?: InputMaybe<Array<Scalars['Bytes']>>;\n assetManager_lt?: InputMaybe<Scalars['Bytes']>;\n assetManager_lte?: InputMaybe<Scalars['Bytes']>;\n assetManager_not?: InputMaybe<Scalars['Bytes']>;\n assetManager_not_contains?: InputMaybe<Scalars['Bytes']>;\n assetManager_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n balance?: InputMaybe<Scalars['BigDecimal']>;\n balance_gt?: InputMaybe<Scalars['BigDecimal']>;\n balance_gte?: InputMaybe<Scalars['BigDecimal']>;\n balance_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n balance_lt?: InputMaybe<Scalars['BigDecimal']>;\n balance_lte?: InputMaybe<Scalars['BigDecimal']>;\n balance_not?: InputMaybe<Scalars['BigDecimal']>;\n balance_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n cashBalance?: InputMaybe<Scalars['BigDecimal']>;\n cashBalance_gt?: InputMaybe<Scalars['BigDecimal']>;\n cashBalance_gte?: InputMaybe<Scalars['BigDecimal']>;\n cashBalance_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n cashBalance_lt?: InputMaybe<Scalars['BigDecimal']>;\n cashBalance_lte?: InputMaybe<Scalars['BigDecimal']>;\n cashBalance_not?: InputMaybe<Scalars['BigDecimal']>;\n cashBalance_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n decimals?: InputMaybe<Scalars['Int']>;\n decimals_gt?: InputMaybe<Scalars['Int']>;\n decimals_gte?: InputMaybe<Scalars['Int']>;\n decimals_in?: InputMaybe<Array<Scalars['Int']>>;\n decimals_lt?: InputMaybe<Scalars['Int']>;\n decimals_lte?: InputMaybe<Scalars['Int']>;\n decimals_not?: InputMaybe<Scalars['Int']>;\n decimals_not_in?: InputMaybe<Array<Scalars['Int']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n index?: InputMaybe<Scalars['Int']>;\n index_gt?: InputMaybe<Scalars['Int']>;\n index_gte?: InputMaybe<Scalars['Int']>;\n index_in?: InputMaybe<Array<Scalars['Int']>>;\n index_lt?: InputMaybe<Scalars['Int']>;\n index_lte?: InputMaybe<Scalars['Int']>;\n index_not?: InputMaybe<Scalars['Int']>;\n index_not_in?: InputMaybe<Array<Scalars['Int']>>;\n isExemptFromYieldProtocolFee?: InputMaybe<Scalars['Boolean']>;\n isExemptFromYieldProtocolFee_in?: InputMaybe<Array<Scalars['Boolean']>>;\n isExemptFromYieldProtocolFee_not?: InputMaybe<Scalars['Boolean']>;\n isExemptFromYieldProtocolFee_not_in?: InputMaybe<Array<Scalars['Boolean']>>;\n managedBalance?: InputMaybe<Scalars['BigDecimal']>;\n managedBalance_gt?: InputMaybe<Scalars['BigDecimal']>;\n managedBalance_gte?: InputMaybe<Scalars['BigDecimal']>;\n managedBalance_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n managedBalance_lt?: InputMaybe<Scalars['BigDecimal']>;\n managedBalance_lte?: InputMaybe<Scalars['BigDecimal']>;\n managedBalance_not?: InputMaybe<Scalars['BigDecimal']>;\n managedBalance_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n managements_?: InputMaybe<ManagementOperation_Filter>;\n name?: InputMaybe<Scalars['String']>;\n name_contains?: InputMaybe<Scalars['String']>;\n name_contains_nocase?: InputMaybe<Scalars['String']>;\n name_ends_with?: InputMaybe<Scalars['String']>;\n name_ends_with_nocase?: InputMaybe<Scalars['String']>;\n name_gt?: InputMaybe<Scalars['String']>;\n name_gte?: InputMaybe<Scalars['String']>;\n name_in?: InputMaybe<Array<Scalars['String']>>;\n name_lt?: InputMaybe<Scalars['String']>;\n name_lte?: InputMaybe<Scalars['String']>;\n name_not?: InputMaybe<Scalars['String']>;\n name_not_contains?: InputMaybe<Scalars['String']>;\n name_not_contains_nocase?: InputMaybe<Scalars['String']>;\n name_not_ends_with?: InputMaybe<Scalars['String']>;\n name_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n name_not_in?: InputMaybe<Array<Scalars['String']>>;\n name_not_starts_with?: InputMaybe<Scalars['String']>;\n name_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n name_starts_with?: InputMaybe<Scalars['String']>;\n name_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId?: InputMaybe<Scalars['String']>;\n poolId_?: InputMaybe<Pool_Filter>;\n poolId_contains?: InputMaybe<Scalars['String']>;\n poolId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_ends_with?: InputMaybe<Scalars['String']>;\n poolId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_gt?: InputMaybe<Scalars['String']>;\n poolId_gte?: InputMaybe<Scalars['String']>;\n poolId_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_lt?: InputMaybe<Scalars['String']>;\n poolId_lte?: InputMaybe<Scalars['String']>;\n poolId_not?: InputMaybe<Scalars['String']>;\n poolId_not_contains?: InputMaybe<Scalars['String']>;\n poolId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_starts_with?: InputMaybe<Scalars['String']>;\n poolId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n priceRate?: InputMaybe<Scalars['BigDecimal']>;\n priceRate_gt?: InputMaybe<Scalars['BigDecimal']>;\n priceRate_gte?: InputMaybe<Scalars['BigDecimal']>;\n priceRate_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n priceRate_lt?: InputMaybe<Scalars['BigDecimal']>;\n priceRate_lte?: InputMaybe<Scalars['BigDecimal']>;\n priceRate_not?: InputMaybe<Scalars['BigDecimal']>;\n priceRate_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n symbol?: InputMaybe<Scalars['String']>;\n symbol_contains?: InputMaybe<Scalars['String']>;\n symbol_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_ends_with?: InputMaybe<Scalars['String']>;\n symbol_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_gt?: InputMaybe<Scalars['String']>;\n symbol_gte?: InputMaybe<Scalars['String']>;\n symbol_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_lt?: InputMaybe<Scalars['String']>;\n symbol_lte?: InputMaybe<Scalars['String']>;\n symbol_not?: InputMaybe<Scalars['String']>;\n symbol_not_contains?: InputMaybe<Scalars['String']>;\n symbol_not_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_not_starts_with?: InputMaybe<Scalars['String']>;\n symbol_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_starts_with?: InputMaybe<Scalars['String']>;\n symbol_starts_with_nocase?: InputMaybe<Scalars['String']>;\n token?: InputMaybe<Scalars['String']>;\n token_?: InputMaybe<Token_Filter>;\n token_contains?: InputMaybe<Scalars['String']>;\n token_contains_nocase?: InputMaybe<Scalars['String']>;\n token_ends_with?: InputMaybe<Scalars['String']>;\n token_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token_gt?: InputMaybe<Scalars['String']>;\n token_gte?: InputMaybe<Scalars['String']>;\n token_in?: InputMaybe<Array<Scalars['String']>>;\n token_lt?: InputMaybe<Scalars['String']>;\n token_lte?: InputMaybe<Scalars['String']>;\n token_not?: InputMaybe<Scalars['String']>;\n token_not_contains?: InputMaybe<Scalars['String']>;\n token_not_contains_nocase?: InputMaybe<Scalars['String']>;\n token_not_ends_with?: InputMaybe<Scalars['String']>;\n token_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token_not_in?: InputMaybe<Array<Scalars['String']>>;\n token_not_starts_with?: InputMaybe<Scalars['String']>;\n token_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n token_starts_with?: InputMaybe<Scalars['String']>;\n token_starts_with_nocase?: InputMaybe<Scalars['String']>;\n weight?: InputMaybe<Scalars['BigDecimal']>;\n weight_gt?: InputMaybe<Scalars['BigDecimal']>;\n weight_gte?: InputMaybe<Scalars['BigDecimal']>;\n weight_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n weight_lt?: InputMaybe<Scalars['BigDecimal']>;\n weight_lte?: InputMaybe<Scalars['BigDecimal']>;\n weight_not?: InputMaybe<Scalars['BigDecimal']>;\n weight_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum PoolToken_OrderBy {\n Address = 'address',\n AssetManager = 'assetManager',\n Balance = 'balance',\n CashBalance = 'cashBalance',\n Decimals = 'decimals',\n Id = 'id',\n Index = 'index',\n IsExemptFromYieldProtocolFee = 'isExemptFromYieldProtocolFee',\n ManagedBalance = 'managedBalance',\n Managements = 'managements',\n Name = 'name',\n PoolId = 'poolId',\n PriceRate = 'priceRate',\n Symbol = 'symbol',\n Token = 'token',\n Weight = 'weight'\n}\n\nexport type Pool_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n address?: InputMaybe<Scalars['Bytes']>;\n address_contains?: InputMaybe<Scalars['Bytes']>;\n address_gt?: InputMaybe<Scalars['Bytes']>;\n address_gte?: InputMaybe<Scalars['Bytes']>;\n address_in?: InputMaybe<Array<Scalars['Bytes']>>;\n address_lt?: InputMaybe<Scalars['Bytes']>;\n address_lte?: InputMaybe<Scalars['Bytes']>;\n address_not?: InputMaybe<Scalars['Bytes']>;\n address_not_contains?: InputMaybe<Scalars['Bytes']>;\n address_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n alpha?: InputMaybe<Scalars['BigDecimal']>;\n alpha_gt?: InputMaybe<Scalars['BigDecimal']>;\n alpha_gte?: InputMaybe<Scalars['BigDecimal']>;\n alpha_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n alpha_lt?: InputMaybe<Scalars['BigDecimal']>;\n alpha_lte?: InputMaybe<Scalars['BigDecimal']>;\n alpha_not?: InputMaybe<Scalars['BigDecimal']>;\n alpha_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amp?: InputMaybe<Scalars['BigInt']>;\n amp_gt?: InputMaybe<Scalars['BigInt']>;\n amp_gte?: InputMaybe<Scalars['BigInt']>;\n amp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n amp_lt?: InputMaybe<Scalars['BigInt']>;\n amp_lte?: InputMaybe<Scalars['BigInt']>;\n amp_not?: InputMaybe<Scalars['BigInt']>;\n amp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n baseToken?: InputMaybe<Scalars['Bytes']>;\n baseToken_contains?: InputMaybe<Scalars['Bytes']>;\n baseToken_gt?: InputMaybe<Scalars['Bytes']>;\n baseToken_gte?: InputMaybe<Scalars['Bytes']>;\n baseToken_in?: InputMaybe<Array<Scalars['Bytes']>>;\n baseToken_lt?: InputMaybe<Scalars['Bytes']>;\n baseToken_lte?: InputMaybe<Scalars['Bytes']>;\n baseToken_not?: InputMaybe<Scalars['Bytes']>;\n baseToken_not_contains?: InputMaybe<Scalars['Bytes']>;\n baseToken_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n beta?: InputMaybe<Scalars['BigDecimal']>;\n beta_gt?: InputMaybe<Scalars['BigDecimal']>;\n beta_gte?: InputMaybe<Scalars['BigDecimal']>;\n beta_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n beta_lt?: InputMaybe<Scalars['BigDecimal']>;\n beta_lte?: InputMaybe<Scalars['BigDecimal']>;\n beta_not?: InputMaybe<Scalars['BigDecimal']>;\n beta_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n c?: InputMaybe<Scalars['BigDecimal']>;\n c_gt?: InputMaybe<Scalars['BigDecimal']>;\n c_gte?: InputMaybe<Scalars['BigDecimal']>;\n c_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n c_lt?: InputMaybe<Scalars['BigDecimal']>;\n c_lte?: InputMaybe<Scalars['BigDecimal']>;\n c_not?: InputMaybe<Scalars['BigDecimal']>;\n c_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n createTime?: InputMaybe<Scalars['Int']>;\n createTime_gt?: InputMaybe<Scalars['Int']>;\n createTime_gte?: InputMaybe<Scalars['Int']>;\n createTime_in?: InputMaybe<Array<Scalars['Int']>>;\n createTime_lt?: InputMaybe<Scalars['Int']>;\n createTime_lte?: InputMaybe<Scalars['Int']>;\n createTime_not?: InputMaybe<Scalars['Int']>;\n createTime_not_in?: InputMaybe<Array<Scalars['Int']>>;\n dSq?: InputMaybe<Scalars['BigDecimal']>;\n dSq_gt?: InputMaybe<Scalars['BigDecimal']>;\n dSq_gte?: InputMaybe<Scalars['BigDecimal']>;\n dSq_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n dSq_lt?: InputMaybe<Scalars['BigDecimal']>;\n dSq_lte?: InputMaybe<Scalars['BigDecimal']>;\n dSq_not?: InputMaybe<Scalars['BigDecimal']>;\n dSq_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n delta?: InputMaybe<Scalars['BigDecimal']>;\n delta_gt?: InputMaybe<Scalars['BigDecimal']>;\n delta_gte?: InputMaybe<Scalars['BigDecimal']>;\n delta_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n delta_lt?: InputMaybe<Scalars['BigDecimal']>;\n delta_lte?: InputMaybe<Scalars['BigDecimal']>;\n delta_not?: InputMaybe<Scalars['BigDecimal']>;\n delta_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n epsilon?: InputMaybe<Scalars['BigDecimal']>;\n epsilon_gt?: InputMaybe<Scalars['BigDecimal']>;\n epsilon_gte?: InputMaybe<Scalars['BigDecimal']>;\n epsilon_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n epsilon_lt?: InputMaybe<Scalars['BigDecimal']>;\n epsilon_lte?: InputMaybe<Scalars['BigDecimal']>;\n epsilon_not?: InputMaybe<Scalars['BigDecimal']>;\n epsilon_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n expiryTime?: InputMaybe<Scalars['BigInt']>;\n expiryTime_gt?: InputMaybe<Scalars['BigInt']>;\n expiryTime_gte?: InputMaybe<Scalars['BigInt']>;\n expiryTime_in?: InputMaybe<Array<Scalars['BigInt']>>;\n expiryTime_lt?: InputMaybe<Scalars['BigInt']>;\n expiryTime_lte?: InputMaybe<Scalars['BigInt']>;\n expiryTime_not?: InputMaybe<Scalars['BigInt']>;\n expiryTime_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n factory?: InputMaybe<Scalars['Bytes']>;\n factory_contains?: InputMaybe<Scalars['Bytes']>;\n factory_gt?: InputMaybe<Scalars['Bytes']>;\n factory_gte?: InputMaybe<Scalars['Bytes']>;\n factory_in?: InputMaybe<Array<Scalars['Bytes']>>;\n factory_lt?: InputMaybe<Scalars['Bytes']>;\n factory_lte?: InputMaybe<Scalars['Bytes']>;\n factory_not?: InputMaybe<Scalars['Bytes']>;\n factory_not_contains?: InputMaybe<Scalars['Bytes']>;\n factory_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n historicalValues_?: InputMaybe<PoolHistoricalLiquidity_Filter>;\n holdersCount?: InputMaybe<Scalars['BigInt']>;\n holdersCount_gt?: InputMaybe<Scalars['BigInt']>;\n holdersCount_gte?: InputMaybe<Scalars['BigInt']>;\n holdersCount_in?: InputMaybe<Array<Scalars['BigInt']>>;\n holdersCount_lt?: InputMaybe<Scalars['BigInt']>;\n holdersCount_lte?: InputMaybe<Scalars['BigInt']>;\n holdersCount_not?: InputMaybe<Scalars['BigInt']>;\n holdersCount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n isInRecoveryMode?: InputMaybe<Scalars['Boolean']>;\n isInRecoveryMode_in?: InputMaybe<Array<Scalars['Boolean']>>;\n isInRecoveryMode_not?: InputMaybe<Scalars['Boolean']>;\n isInRecoveryMode_not_in?: InputMaybe<Array<Scalars['Boolean']>>;\n isPaused?: InputMaybe<Scalars['Boolean']>;\n isPaused_in?: InputMaybe<Array<Scalars['Boolean']>>;\n isPaused_not?: InputMaybe<Scalars['Boolean']>;\n isPaused_not_in?: InputMaybe<Array<Scalars['Boolean']>>;\n lambda?: InputMaybe<Scalars['BigDecimal']>;\n lambda_gt?: InputMaybe<Scalars['BigDecimal']>;\n lambda_gte?: InputMaybe<Scalars['BigDecimal']>;\n lambda_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n lambda_lt?: InputMaybe<Scalars['BigDecimal']>;\n lambda_lte?: InputMaybe<Scalars['BigDecimal']>;\n lambda_not?: InputMaybe<Scalars['BigDecimal']>;\n lambda_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n lowerTarget?: InputMaybe<Scalars['BigDecimal']>;\n lowerTarget_gt?: InputMaybe<Scalars['BigDecimal']>;\n lowerTarget_gte?: InputMaybe<Scalars['BigDecimal']>;\n lowerTarget_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n lowerTarget_lt?: InputMaybe<Scalars['BigDecimal']>;\n lowerTarget_lte?: InputMaybe<Scalars['BigDecimal']>;\n lowerTarget_not?: InputMaybe<Scalars['BigDecimal']>;\n lowerTarget_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n mainIndex?: InputMaybe<Scalars['Int']>;\n mainIndex_gt?: InputMaybe<Scalars['Int']>;\n mainIndex_gte?: InputMaybe<Scalars['Int']>;\n mainIndex_in?: InputMaybe<Array<Scalars['Int']>>;\n mainIndex_lt?: InputMaybe<Scalars['Int']>;\n mainIndex_lte?: InputMaybe<Scalars['Int']>;\n mainIndex_not?: InputMaybe<Scalars['Int']>;\n mainIndex_not_in?: InputMaybe<Array<Scalars['Int']>>;\n managementFee?: InputMaybe<Scalars['BigDecimal']>;\n managementFee_gt?: InputMaybe<Scalars['BigDecimal']>;\n managementFee_gte?: InputMaybe<Scalars['BigDecimal']>;\n managementFee_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n managementFee_lt?: InputMaybe<Scalars['BigDecimal']>;\n managementFee_lte?: InputMaybe<Scalars['BigDecimal']>;\n managementFee_not?: InputMaybe<Scalars['BigDecimal']>;\n managementFee_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n name?: InputMaybe<Scalars['String']>;\n name_contains?: InputMaybe<Scalars['String']>;\n name_contains_nocase?: InputMaybe<Scalars['String']>;\n name_ends_with?: InputMaybe<Scalars['String']>;\n name_ends_with_nocase?: InputMaybe<Scalars['String']>;\n name_gt?: InputMaybe<Scalars['String']>;\n name_gte?: InputMaybe<Scalars['String']>;\n name_in?: InputMaybe<Array<Scalars['String']>>;\n name_lt?: InputMaybe<Scalars['String']>;\n name_lte?: InputMaybe<Scalars['String']>;\n name_not?: InputMaybe<Scalars['String']>;\n name_not_contains?: InputMaybe<Scalars['String']>;\n name_not_contains_nocase?: InputMaybe<Scalars['String']>;\n name_not_ends_with?: InputMaybe<Scalars['String']>;\n name_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n name_not_in?: InputMaybe<Array<Scalars['String']>>;\n name_not_starts_with?: InputMaybe<Scalars['String']>;\n name_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n name_starts_with?: InputMaybe<Scalars['String']>;\n name_starts_with_nocase?: InputMaybe<Scalars['String']>;\n oracleEnabled?: InputMaybe<Scalars['Boolean']>;\n oracleEnabled_in?: InputMaybe<Array<Scalars['Boolean']>>;\n oracleEnabled_not?: InputMaybe<Scalars['Boolean']>;\n oracleEnabled_not_in?: InputMaybe<Array<Scalars['Boolean']>>;\n owner?: InputMaybe<Scalars['Bytes']>;\n owner_contains?: InputMaybe<Scalars['Bytes']>;\n owner_gt?: InputMaybe<Scalars['Bytes']>;\n owner_gte?: InputMaybe<Scalars['Bytes']>;\n owner_in?: InputMaybe<Array<Scalars['Bytes']>>;\n owner_lt?: InputMaybe<Scalars['Bytes']>;\n owner_lte?: InputMaybe<Scalars['Bytes']>;\n owner_not?: InputMaybe<Scalars['Bytes']>;\n owner_not_contains?: InputMaybe<Scalars['Bytes']>;\n owner_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n poolType?: InputMaybe<Scalars['String']>;\n poolTypeVersion?: InputMaybe<Scalars['Int']>;\n poolTypeVersion_gt?: InputMaybe<Scalars['Int']>;\n poolTypeVersion_gte?: InputMaybe<Scalars['Int']>;\n poolTypeVersion_in?: InputMaybe<Array<Scalars['Int']>>;\n poolTypeVersion_lt?: InputMaybe<Scalars['Int']>;\n poolTypeVersion_lte?: InputMaybe<Scalars['Int']>;\n poolTypeVersion_not?: InputMaybe<Scalars['Int']>;\n poolTypeVersion_not_in?: InputMaybe<Array<Scalars['Int']>>;\n poolType_contains?: InputMaybe<Scalars['String']>;\n poolType_contains_nocase?: InputMaybe<Scalars['String']>;\n poolType_ends_with?: InputMaybe<Scalars['String']>;\n poolType_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolType_gt?: InputMaybe<Scalars['String']>;\n poolType_gte?: InputMaybe<Scalars['String']>;\n poolType_in?: InputMaybe<Array<Scalars['String']>>;\n poolType_lt?: InputMaybe<Scalars['String']>;\n poolType_lte?: InputMaybe<Scalars['String']>;\n poolType_not?: InputMaybe<Scalars['String']>;\n poolType_not_contains?: InputMaybe<Scalars['String']>;\n poolType_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolType_not_ends_with?: InputMaybe<Scalars['String']>;\n poolType_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolType_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolType_not_starts_with?: InputMaybe<Scalars['String']>;\n poolType_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolType_starts_with?: InputMaybe<Scalars['String']>;\n poolType_starts_with_nocase?: InputMaybe<Scalars['String']>;\n priceRateProviders_?: InputMaybe<PriceRateProvider_Filter>;\n principalToken?: InputMaybe<Scalars['Bytes']>;\n principalToken_contains?: InputMaybe<Scalars['Bytes']>;\n principalToken_gt?: InputMaybe<Scalars['Bytes']>;\n principalToken_gte?: InputMaybe<Scalars['Bytes']>;\n principalToken_in?: InputMaybe<Array<Scalars['Bytes']>>;\n principalToken_lt?: InputMaybe<Scalars['Bytes']>;\n principalToken_lte?: InputMaybe<Scalars['Bytes']>;\n principalToken_not?: InputMaybe<Scalars['Bytes']>;\n principalToken_not_contains?: InputMaybe<Scalars['Bytes']>;\n principalToken_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n protocolAumFeeCache?: InputMaybe<Scalars['BigDecimal']>;\n protocolAumFeeCache_gt?: InputMaybe<Scalars['BigDecimal']>;\n protocolAumFeeCache_gte?: InputMaybe<Scalars['BigDecimal']>;\n protocolAumFeeCache_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n protocolAumFeeCache_lt?: InputMaybe<Scalars['BigDecimal']>;\n protocolAumFeeCache_lte?: InputMaybe<Scalars['BigDecimal']>;\n protocolAumFeeCache_not?: InputMaybe<Scalars['BigDecimal']>;\n protocolAumFeeCache_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n protocolId?: InputMaybe<Scalars['Int']>;\n protocolId_gt?: InputMaybe<Scalars['Int']>;\n protocolId_gte?: InputMaybe<Scalars['Int']>;\n protocolId_in?: InputMaybe<Array<Scalars['Int']>>;\n protocolId_lt?: InputMaybe<Scalars['Int']>;\n protocolId_lte?: InputMaybe<Scalars['Int']>;\n protocolId_not?: InputMaybe<Scalars['Int']>;\n protocolId_not_in?: InputMaybe<Array<Scalars['Int']>>;\n protocolSwapFeeCache?: InputMaybe<Scalars['BigDecimal']>;\n protocolSwapFeeCache_gt?: InputMaybe<Scalars['BigDecimal']>;\n protocolSwapFeeCache_gte?: InputMaybe<Scalars['BigDecimal']>;\n protocolSwapFeeCache_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n protocolSwapFeeCache_lt?: InputMaybe<Scalars['BigDecimal']>;\n protocolSwapFeeCache_lte?: InputMaybe<Scalars['BigDecimal']>;\n protocolSwapFeeCache_not?: InputMaybe<Scalars['BigDecimal']>;\n protocolSwapFeeCache_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n protocolYieldFeeCache?: InputMaybe<Scalars['BigDecimal']>;\n protocolYieldFeeCache_gt?: InputMaybe<Scalars['BigDecimal']>;\n protocolYieldFeeCache_gte?: InputMaybe<Scalars['BigDecimal']>;\n protocolYieldFeeCache_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n protocolYieldFeeCache_lt?: InputMaybe<Scalars['BigDecimal']>;\n protocolYieldFeeCache_lte?: InputMaybe<Scalars['BigDecimal']>;\n protocolYieldFeeCache_not?: InputMaybe<Scalars['BigDecimal']>;\n protocolYieldFeeCache_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n root3Alpha?: InputMaybe<Scalars['BigDecimal']>;\n root3Alpha_gt?: InputMaybe<Scalars['BigDecimal']>;\n root3Alpha_gte?: InputMaybe<Scalars['BigDecimal']>;\n root3Alpha_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n root3Alpha_lt?: InputMaybe<Scalars['BigDecimal']>;\n root3Alpha_lte?: InputMaybe<Scalars['BigDecimal']>;\n root3Alpha_not?: InputMaybe<Scalars['BigDecimal']>;\n root3Alpha_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n s?: InputMaybe<Scalars['BigDecimal']>;\n s_gt?: InputMaybe<Scalars['BigDecimal']>;\n s_gte?: InputMaybe<Scalars['BigDecimal']>;\n s_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n s_lt?: InputMaybe<Scalars['BigDecimal']>;\n s_lte?: InputMaybe<Scalars['BigDecimal']>;\n s_not?: InputMaybe<Scalars['BigDecimal']>;\n s_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n shares_?: InputMaybe<PoolShare_Filter>;\n snapshots_?: InputMaybe<PoolSnapshot_Filter>;\n sqrtAlpha?: InputMaybe<Scalars['BigDecimal']>;\n sqrtAlpha_gt?: InputMaybe<Scalars['BigDecimal']>;\n sqrtAlpha_gte?: InputMaybe<Scalars['BigDecimal']>;\n sqrtAlpha_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n sqrtAlpha_lt?: InputMaybe<Scalars['BigDecimal']>;\n sqrtAlpha_lte?: InputMaybe<Scalars['BigDecimal']>;\n sqrtAlpha_not?: InputMaybe<Scalars['BigDecimal']>;\n sqrtAlpha_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n sqrtBeta?: InputMaybe<Scalars['BigDecimal']>;\n sqrtBeta_gt?: InputMaybe<Scalars['BigDecimal']>;\n sqrtBeta_gte?: InputMaybe<Scalars['BigDecimal']>;\n sqrtBeta_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n sqrtBeta_lt?: InputMaybe<Scalars['BigDecimal']>;\n sqrtBeta_lte?: InputMaybe<Scalars['BigDecimal']>;\n sqrtBeta_not?: InputMaybe<Scalars['BigDecimal']>;\n sqrtBeta_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n strategyType?: InputMaybe<Scalars['Int']>;\n strategyType_gt?: InputMaybe<Scalars['Int']>;\n strategyType_gte?: InputMaybe<Scalars['Int']>;\n strategyType_in?: InputMaybe<Array<Scalars['Int']>>;\n strategyType_lt?: InputMaybe<Scalars['Int']>;\n strategyType_lte?: InputMaybe<Scalars['Int']>;\n strategyType_not?: InputMaybe<Scalars['Int']>;\n strategyType_not_in?: InputMaybe<Array<Scalars['Int']>>;\n swapEnabled?: InputMaybe<Scalars['Boolean']>;\n swapEnabled_in?: InputMaybe<Array<Scalars['Boolean']>>;\n swapEnabled_not?: InputMaybe<Scalars['Boolean']>;\n swapEnabled_not_in?: InputMaybe<Array<Scalars['Boolean']>>;\n swapFee?: InputMaybe<Scalars['BigDecimal']>;\n swapFee_gt?: InputMaybe<Scalars['BigDecimal']>;\n swapFee_gte?: InputMaybe<Scalars['BigDecimal']>;\n swapFee_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n swapFee_lt?: InputMaybe<Scalars['BigDecimal']>;\n swapFee_lte?: InputMaybe<Scalars['BigDecimal']>;\n swapFee_not?: InputMaybe<Scalars['BigDecimal']>;\n swapFee_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n swapsCount?: InputMaybe<Scalars['BigInt']>;\n swapsCount_gt?: InputMaybe<Scalars['BigInt']>;\n swapsCount_gte?: InputMaybe<Scalars['BigInt']>;\n swapsCount_in?: InputMaybe<Array<Scalars['BigInt']>>;\n swapsCount_lt?: InputMaybe<Scalars['BigInt']>;\n swapsCount_lte?: InputMaybe<Scalars['BigInt']>;\n swapsCount_not?: InputMaybe<Scalars['BigInt']>;\n swapsCount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n swaps_?: InputMaybe<Swap_Filter>;\n symbol?: InputMaybe<Scalars['String']>;\n symbol_contains?: InputMaybe<Scalars['String']>;\n symbol_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_ends_with?: InputMaybe<Scalars['String']>;\n symbol_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_gt?: InputMaybe<Scalars['String']>;\n symbol_gte?: InputMaybe<Scalars['String']>;\n symbol_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_lt?: InputMaybe<Scalars['String']>;\n symbol_lte?: InputMaybe<Scalars['String']>;\n symbol_not?: InputMaybe<Scalars['String']>;\n symbol_not_contains?: InputMaybe<Scalars['String']>;\n symbol_not_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_not_starts_with?: InputMaybe<Scalars['String']>;\n symbol_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_starts_with?: InputMaybe<Scalars['String']>;\n symbol_starts_with_nocase?: InputMaybe<Scalars['String']>;\n tauAlphaX?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaX_gt?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaX_gte?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaX_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tauAlphaX_lt?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaX_lte?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaX_not?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaX_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tauAlphaY?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaY_gt?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaY_gte?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaY_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tauAlphaY_lt?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaY_lte?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaY_not?: InputMaybe<Scalars['BigDecimal']>;\n tauAlphaY_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tauBetaX?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaX_gt?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaX_gte?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaX_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tauBetaX_lt?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaX_lte?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaX_not?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaX_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tauBetaY?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaY_gt?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaY_gte?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaY_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tauBetaY_lt?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaY_lte?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaY_not?: InputMaybe<Scalars['BigDecimal']>;\n tauBetaY_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tokensList?: InputMaybe<Array<Scalars['Bytes']>>;\n tokensList_contains?: InputMaybe<Array<Scalars['Bytes']>>;\n tokensList_contains_nocase?: InputMaybe<Array<Scalars['Bytes']>>;\n tokensList_not?: InputMaybe<Array<Scalars['Bytes']>>;\n tokensList_not_contains?: InputMaybe<Array<Scalars['Bytes']>>;\n tokensList_not_contains_nocase?: InputMaybe<Array<Scalars['Bytes']>>;\n tokens_?: InputMaybe<PoolToken_Filter>;\n totalLiquidity?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalLiquidity_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_not?: InputMaybe<Scalars['BigDecimal']>;\n totalLiquidity_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalShares?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalShares_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_not?: InputMaybe<Scalars['BigDecimal']>;\n totalShares_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapFee?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapFee_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalWeight?: InputMaybe<Scalars['BigDecimal']>;\n totalWeight_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalWeight_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalWeight_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalWeight_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalWeight_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalWeight_not?: InputMaybe<Scalars['BigDecimal']>;\n totalWeight_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tx?: InputMaybe<Scalars['Bytes']>;\n tx_contains?: InputMaybe<Scalars['Bytes']>;\n tx_gt?: InputMaybe<Scalars['Bytes']>;\n tx_gte?: InputMaybe<Scalars['Bytes']>;\n tx_in?: InputMaybe<Array<Scalars['Bytes']>>;\n tx_lt?: InputMaybe<Scalars['Bytes']>;\n tx_lte?: InputMaybe<Scalars['Bytes']>;\n tx_not?: InputMaybe<Scalars['Bytes']>;\n tx_not_contains?: InputMaybe<Scalars['Bytes']>;\n tx_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n u?: InputMaybe<Scalars['BigDecimal']>;\n u_gt?: InputMaybe<Scalars['BigDecimal']>;\n u_gte?: InputMaybe<Scalars['BigDecimal']>;\n u_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n u_lt?: InputMaybe<Scalars['BigDecimal']>;\n u_lte?: InputMaybe<Scalars['BigDecimal']>;\n u_not?: InputMaybe<Scalars['BigDecimal']>;\n u_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n unitSeconds?: InputMaybe<Scalars['BigInt']>;\n unitSeconds_gt?: InputMaybe<Scalars['BigInt']>;\n unitSeconds_gte?: InputMaybe<Scalars['BigInt']>;\n unitSeconds_in?: InputMaybe<Array<Scalars['BigInt']>>;\n unitSeconds_lt?: InputMaybe<Scalars['BigInt']>;\n unitSeconds_lte?: InputMaybe<Scalars['BigInt']>;\n unitSeconds_not?: InputMaybe<Scalars['BigInt']>;\n unitSeconds_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n upperTarget?: InputMaybe<Scalars['BigDecimal']>;\n upperTarget_gt?: InputMaybe<Scalars['BigDecimal']>;\n upperTarget_gte?: InputMaybe<Scalars['BigDecimal']>;\n upperTarget_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n upperTarget_lt?: InputMaybe<Scalars['BigDecimal']>;\n upperTarget_lte?: InputMaybe<Scalars['BigDecimal']>;\n upperTarget_not?: InputMaybe<Scalars['BigDecimal']>;\n upperTarget_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n v?: InputMaybe<Scalars['BigDecimal']>;\n v_gt?: InputMaybe<Scalars['BigDecimal']>;\n v_gte?: InputMaybe<Scalars['BigDecimal']>;\n v_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n v_lt?: InputMaybe<Scalars['BigDecimal']>;\n v_lte?: InputMaybe<Scalars['BigDecimal']>;\n v_not?: InputMaybe<Scalars['BigDecimal']>;\n v_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n vaultID?: InputMaybe<Scalars['String']>;\n vaultID_?: InputMaybe<Balancer_Filter>;\n vaultID_contains?: InputMaybe<Scalars['String']>;\n vaultID_contains_nocase?: InputMaybe<Scalars['String']>;\n vaultID_ends_with?: InputMaybe<Scalars['String']>;\n vaultID_ends_with_nocase?: InputMaybe<Scalars['String']>;\n vaultID_gt?: InputMaybe<Scalars['String']>;\n vaultID_gte?: InputMaybe<Scalars['String']>;\n vaultID_in?: InputMaybe<Array<Scalars['String']>>;\n vaultID_lt?: InputMaybe<Scalars['String']>;\n vaultID_lte?: InputMaybe<Scalars['String']>;\n vaultID_not?: InputMaybe<Scalars['String']>;\n vaultID_not_contains?: InputMaybe<Scalars['String']>;\n vaultID_not_contains_nocase?: InputMaybe<Scalars['String']>;\n vaultID_not_ends_with?: InputMaybe<Scalars['String']>;\n vaultID_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n vaultID_not_in?: InputMaybe<Array<Scalars['String']>>;\n vaultID_not_starts_with?: InputMaybe<Scalars['String']>;\n vaultID_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n vaultID_starts_with?: InputMaybe<Scalars['String']>;\n vaultID_starts_with_nocase?: InputMaybe<Scalars['String']>;\n w?: InputMaybe<Scalars['BigDecimal']>;\n w_gt?: InputMaybe<Scalars['BigDecimal']>;\n w_gte?: InputMaybe<Scalars['BigDecimal']>;\n w_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n w_lt?: InputMaybe<Scalars['BigDecimal']>;\n w_lte?: InputMaybe<Scalars['BigDecimal']>;\n w_not?: InputMaybe<Scalars['BigDecimal']>;\n w_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n weightUpdates_?: InputMaybe<GradualWeightUpdate_Filter>;\n wrappedIndex?: InputMaybe<Scalars['Int']>;\n wrappedIndex_gt?: InputMaybe<Scalars['Int']>;\n wrappedIndex_gte?: InputMaybe<Scalars['Int']>;\n wrappedIndex_in?: InputMaybe<Array<Scalars['Int']>>;\n wrappedIndex_lt?: InputMaybe<Scalars['Int']>;\n wrappedIndex_lte?: InputMaybe<Scalars['Int']>;\n wrappedIndex_not?: InputMaybe<Scalars['Int']>;\n wrappedIndex_not_in?: InputMaybe<Array<Scalars['Int']>>;\n z?: InputMaybe<Scalars['BigDecimal']>;\n z_gt?: InputMaybe<Scalars['BigDecimal']>;\n z_gte?: InputMaybe<Scalars['BigDecimal']>;\n z_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n z_lt?: InputMaybe<Scalars['BigDecimal']>;\n z_lte?: InputMaybe<Scalars['BigDecimal']>;\n z_not?: InputMaybe<Scalars['BigDecimal']>;\n z_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum Pool_OrderBy {\n Address = 'address',\n Alpha = 'alpha',\n Amp = 'amp',\n BaseToken = 'baseToken',\n Beta = 'beta',\n C = 'c',\n CreateTime = 'createTime',\n DSq = 'dSq',\n Delta = 'delta',\n Epsilon = 'epsilon',\n ExpiryTime = 'expiryTime',\n Factory = 'factory',\n HistoricalValues = 'historicalValues',\n HoldersCount = 'holdersCount',\n Id = 'id',\n IsInRecoveryMode = 'isInRecoveryMode',\n IsPaused = 'isPaused',\n Lambda = 'lambda',\n LowerTarget = 'lowerTarget',\n MainIndex = 'mainIndex',\n ManagementFee = 'managementFee',\n Name = 'name',\n OracleEnabled = 'oracleEnabled',\n Owner = 'owner',\n PoolType = 'poolType',\n PoolTypeVersion = 'poolTypeVersion',\n PriceRateProviders = 'priceRateProviders',\n PrincipalToken = 'principalToken',\n ProtocolAumFeeCache = 'protocolAumFeeCache',\n ProtocolId = 'protocolId',\n ProtocolSwapFeeCache = 'protocolSwapFeeCache',\n ProtocolYieldFeeCache = 'protocolYieldFeeCache',\n Root3Alpha = 'root3Alpha',\n S = 's',\n Shares = 'shares',\n Snapshots = 'snapshots',\n SqrtAlpha = 'sqrtAlpha',\n SqrtBeta = 'sqrtBeta',\n StrategyType = 'strategyType',\n SwapEnabled = 'swapEnabled',\n SwapFee = 'swapFee',\n Swaps = 'swaps',\n SwapsCount = 'swapsCount',\n Symbol = 'symbol',\n TauAlphaX = 'tauAlphaX',\n TauAlphaY = 'tauAlphaY',\n TauBetaX = 'tauBetaX',\n TauBetaY = 'tauBetaY',\n Tokens = 'tokens',\n TokensList = 'tokensList',\n TotalLiquidity = 'totalLiquidity',\n TotalShares = 'totalShares',\n TotalSwapFee = 'totalSwapFee',\n TotalSwapVolume = 'totalSwapVolume',\n TotalWeight = 'totalWeight',\n Tx = 'tx',\n U = 'u',\n UnitSeconds = 'unitSeconds',\n UpperTarget = 'upperTarget',\n V = 'v',\n VaultId = 'vaultID',\n W = 'w',\n WeightUpdates = 'weightUpdates',\n WrappedIndex = 'wrappedIndex',\n Z = 'z'\n}\n\nexport type PriceRateProvider = {\n __typename?: 'PriceRateProvider';\n address: Scalars['Bytes'];\n cacheDuration?: Maybe<Scalars['Int']>;\n cacheExpiry?: Maybe<Scalars['Int']>;\n id: Scalars['ID'];\n lastCached?: Maybe<Scalars['Int']>;\n poolId: Pool;\n rate?: Maybe<Scalars['BigDecimal']>;\n token: PoolToken;\n};\n\nexport type PriceRateProvider_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n address?: InputMaybe<Scalars['Bytes']>;\n address_contains?: InputMaybe<Scalars['Bytes']>;\n address_gt?: InputMaybe<Scalars['Bytes']>;\n address_gte?: InputMaybe<Scalars['Bytes']>;\n address_in?: InputMaybe<Array<Scalars['Bytes']>>;\n address_lt?: InputMaybe<Scalars['Bytes']>;\n address_lte?: InputMaybe<Scalars['Bytes']>;\n address_not?: InputMaybe<Scalars['Bytes']>;\n address_not_contains?: InputMaybe<Scalars['Bytes']>;\n address_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n cacheDuration?: InputMaybe<Scalars['Int']>;\n cacheDuration_gt?: InputMaybe<Scalars['Int']>;\n cacheDuration_gte?: InputMaybe<Scalars['Int']>;\n cacheDuration_in?: InputMaybe<Array<Scalars['Int']>>;\n cacheDuration_lt?: InputMaybe<Scalars['Int']>;\n cacheDuration_lte?: InputMaybe<Scalars['Int']>;\n cacheDuration_not?: InputMaybe<Scalars['Int']>;\n cacheDuration_not_in?: InputMaybe<Array<Scalars['Int']>>;\n cacheExpiry?: InputMaybe<Scalars['Int']>;\n cacheExpiry_gt?: InputMaybe<Scalars['Int']>;\n cacheExpiry_gte?: InputMaybe<Scalars['Int']>;\n cacheExpiry_in?: InputMaybe<Array<Scalars['Int']>>;\n cacheExpiry_lt?: InputMaybe<Scalars['Int']>;\n cacheExpiry_lte?: InputMaybe<Scalars['Int']>;\n cacheExpiry_not?: InputMaybe<Scalars['Int']>;\n cacheExpiry_not_in?: InputMaybe<Array<Scalars['Int']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n lastCached?: InputMaybe<Scalars['Int']>;\n lastCached_gt?: InputMaybe<Scalars['Int']>;\n lastCached_gte?: InputMaybe<Scalars['Int']>;\n lastCached_in?: InputMaybe<Array<Scalars['Int']>>;\n lastCached_lt?: InputMaybe<Scalars['Int']>;\n lastCached_lte?: InputMaybe<Scalars['Int']>;\n lastCached_not?: InputMaybe<Scalars['Int']>;\n lastCached_not_in?: InputMaybe<Array<Scalars['Int']>>;\n poolId?: InputMaybe<Scalars['String']>;\n poolId_?: InputMaybe<Pool_Filter>;\n poolId_contains?: InputMaybe<Scalars['String']>;\n poolId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_ends_with?: InputMaybe<Scalars['String']>;\n poolId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_gt?: InputMaybe<Scalars['String']>;\n poolId_gte?: InputMaybe<Scalars['String']>;\n poolId_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_lt?: InputMaybe<Scalars['String']>;\n poolId_lte?: InputMaybe<Scalars['String']>;\n poolId_not?: InputMaybe<Scalars['String']>;\n poolId_not_contains?: InputMaybe<Scalars['String']>;\n poolId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_starts_with?: InputMaybe<Scalars['String']>;\n poolId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n rate?: InputMaybe<Scalars['BigDecimal']>;\n rate_gt?: InputMaybe<Scalars['BigDecimal']>;\n rate_gte?: InputMaybe<Scalars['BigDecimal']>;\n rate_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n rate_lt?: InputMaybe<Scalars['BigDecimal']>;\n rate_lte?: InputMaybe<Scalars['BigDecimal']>;\n rate_not?: InputMaybe<Scalars['BigDecimal']>;\n rate_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n token?: InputMaybe<Scalars['String']>;\n token_?: InputMaybe<PoolToken_Filter>;\n token_contains?: InputMaybe<Scalars['String']>;\n token_contains_nocase?: InputMaybe<Scalars['String']>;\n token_ends_with?: InputMaybe<Scalars['String']>;\n token_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token_gt?: InputMaybe<Scalars['String']>;\n token_gte?: InputMaybe<Scalars['String']>;\n token_in?: InputMaybe<Array<Scalars['String']>>;\n token_lt?: InputMaybe<Scalars['String']>;\n token_lte?: InputMaybe<Scalars['String']>;\n token_not?: InputMaybe<Scalars['String']>;\n token_not_contains?: InputMaybe<Scalars['String']>;\n token_not_contains_nocase?: InputMaybe<Scalars['String']>;\n token_not_ends_with?: InputMaybe<Scalars['String']>;\n token_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token_not_in?: InputMaybe<Array<Scalars['String']>>;\n token_not_starts_with?: InputMaybe<Scalars['String']>;\n token_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n token_starts_with?: InputMaybe<Scalars['String']>;\n token_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum PriceRateProvider_OrderBy {\n Address = 'address',\n CacheDuration = 'cacheDuration',\n CacheExpiry = 'cacheExpiry',\n Id = 'id',\n LastCached = 'lastCached',\n PoolId = 'poolId',\n Rate = 'rate',\n Token = 'token'\n}\n\nexport type Query = {\n __typename?: 'Query';\n /** Access to subgraph metadata */\n _meta?: Maybe<_Meta_>;\n ampUpdate?: Maybe<AmpUpdate>;\n ampUpdates: Array<AmpUpdate>;\n balancer?: Maybe<Balancer>;\n balancerSnapshot?: Maybe<BalancerSnapshot>;\n balancerSnapshots: Array<BalancerSnapshot>;\n balancers: Array<Balancer>;\n gradualWeightUpdate?: Maybe<GradualWeightUpdate>;\n gradualWeightUpdates: Array<GradualWeightUpdate>;\n joinExit?: Maybe<JoinExit>;\n joinExits: Array<JoinExit>;\n latestPrice?: Maybe<LatestPrice>;\n latestPrices: Array<LatestPrice>;\n managementOperation?: Maybe<ManagementOperation>;\n managementOperations: Array<ManagementOperation>;\n pool?: Maybe<Pool>;\n poolContract?: Maybe<PoolContract>;\n poolContracts: Array<PoolContract>;\n poolHistoricalLiquidities: Array<PoolHistoricalLiquidity>;\n poolHistoricalLiquidity?: Maybe<PoolHistoricalLiquidity>;\n poolShare?: Maybe<PoolShare>;\n poolShares: Array<PoolShare>;\n poolSnapshot?: Maybe<PoolSnapshot>;\n poolSnapshots: Array<PoolSnapshot>;\n poolToken?: Maybe<PoolToken>;\n poolTokens: Array<PoolToken>;\n pools: Array<Pool>;\n priceRateProvider?: Maybe<PriceRateProvider>;\n priceRateProviders: Array<PriceRateProvider>;\n swap?: Maybe<Swap>;\n swapFeeUpdate?: Maybe<SwapFeeUpdate>;\n swapFeeUpdates: Array<SwapFeeUpdate>;\n swaps: Array<Swap>;\n token?: Maybe<Token>;\n tokenPrice?: Maybe<TokenPrice>;\n tokenPrices: Array<TokenPrice>;\n tokenSnapshot?: Maybe<TokenSnapshot>;\n tokenSnapshots: Array<TokenSnapshot>;\n tokens: Array<Token>;\n tradePair?: Maybe<TradePair>;\n tradePairSnapshot?: Maybe<TradePairSnapshot>;\n tradePairSnapshots: Array<TradePairSnapshot>;\n tradePairs: Array<TradePair>;\n user?: Maybe<User>;\n userInternalBalance?: Maybe<UserInternalBalance>;\n userInternalBalances: Array<UserInternalBalance>;\n users: Array<User>;\n};\n\n\nexport type Query_MetaArgs = {\n block?: InputMaybe<Block_Height>;\n};\n\n\nexport type QueryAmpUpdateArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryAmpUpdatesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<AmpUpdate_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<AmpUpdate_Filter>;\n};\n\n\nexport type QueryBalancerArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryBalancerSnapshotArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryBalancerSnapshotsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<BalancerSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<BalancerSnapshot_Filter>;\n};\n\n\nexport type QueryBalancersArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Balancer_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Balancer_Filter>;\n};\n\n\nexport type QueryGradualWeightUpdateArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryGradualWeightUpdatesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GradualWeightUpdate_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GradualWeightUpdate_Filter>;\n};\n\n\nexport type QueryJoinExitArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryJoinExitsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<JoinExit_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<JoinExit_Filter>;\n};\n\n\nexport type QueryLatestPriceArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryLatestPricesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<LatestPrice_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<LatestPrice_Filter>;\n};\n\n\nexport type QueryManagementOperationArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryManagementOperationsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<ManagementOperation_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<ManagementOperation_Filter>;\n};\n\n\nexport type QueryPoolArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryPoolContractArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryPoolContractsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolContract_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolContract_Filter>;\n};\n\n\nexport type QueryPoolHistoricalLiquiditiesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolHistoricalLiquidity_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolHistoricalLiquidity_Filter>;\n};\n\n\nexport type QueryPoolHistoricalLiquidityArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryPoolShareArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryPoolSharesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolShare_Filter>;\n};\n\n\nexport type QueryPoolSnapshotArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryPoolSnapshotsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolSnapshot_Filter>;\n};\n\n\nexport type QueryPoolTokenArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryPoolTokensArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolToken_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolToken_Filter>;\n};\n\n\nexport type QueryPoolsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Pool_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Pool_Filter>;\n};\n\n\nexport type QueryPriceRateProviderArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryPriceRateProvidersArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PriceRateProvider_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PriceRateProvider_Filter>;\n};\n\n\nexport type QuerySwapArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QuerySwapFeeUpdateArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QuerySwapFeeUpdatesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<SwapFeeUpdate_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<SwapFeeUpdate_Filter>;\n};\n\n\nexport type QuerySwapsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Swap_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Swap_Filter>;\n};\n\n\nexport type QueryTokenArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryTokenPriceArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryTokenPricesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<TokenPrice_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<TokenPrice_Filter>;\n};\n\n\nexport type QueryTokenSnapshotArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryTokenSnapshotsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<TokenSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<TokenSnapshot_Filter>;\n};\n\n\nexport type QueryTokensArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Token_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Token_Filter>;\n};\n\n\nexport type QueryTradePairArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryTradePairSnapshotArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryTradePairSnapshotsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<TradePairSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<TradePairSnapshot_Filter>;\n};\n\n\nexport type QueryTradePairsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<TradePair_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<TradePair_Filter>;\n};\n\n\nexport type QueryUserArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryUserInternalBalanceArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryUserInternalBalancesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<UserInternalBalance_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<UserInternalBalance_Filter>;\n};\n\n\nexport type QueryUsersArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<User_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<User_Filter>;\n};\n\nexport type Subscription = {\n __typename?: 'Subscription';\n /** Access to subgraph metadata */\n _meta?: Maybe<_Meta_>;\n ampUpdate?: Maybe<AmpUpdate>;\n ampUpdates: Array<AmpUpdate>;\n balancer?: Maybe<Balancer>;\n balancerSnapshot?: Maybe<BalancerSnapshot>;\n balancerSnapshots: Array<BalancerSnapshot>;\n balancers: Array<Balancer>;\n gradualWeightUpdate?: Maybe<GradualWeightUpdate>;\n gradualWeightUpdates: Array<GradualWeightUpdate>;\n joinExit?: Maybe<JoinExit>;\n joinExits: Array<JoinExit>;\n latestPrice?: Maybe<LatestPrice>;\n latestPrices: Array<LatestPrice>;\n managementOperation?: Maybe<ManagementOperation>;\n managementOperations: Array<ManagementOperation>;\n pool?: Maybe<Pool>;\n poolContract?: Maybe<PoolContract>;\n poolContracts: Array<PoolContract>;\n poolHistoricalLiquidities: Array<PoolHistoricalLiquidity>;\n poolHistoricalLiquidity?: Maybe<PoolHistoricalLiquidity>;\n poolShare?: Maybe<PoolShare>;\n poolShares: Array<PoolShare>;\n poolSnapshot?: Maybe<PoolSnapshot>;\n poolSnapshots: Array<PoolSnapshot>;\n poolToken?: Maybe<PoolToken>;\n poolTokens: Array<PoolToken>;\n pools: Array<Pool>;\n priceRateProvider?: Maybe<PriceRateProvider>;\n priceRateProviders: Array<PriceRateProvider>;\n swap?: Maybe<Swap>;\n swapFeeUpdate?: Maybe<SwapFeeUpdate>;\n swapFeeUpdates: Array<SwapFeeUpdate>;\n swaps: Array<Swap>;\n token?: Maybe<Token>;\n tokenPrice?: Maybe<TokenPrice>;\n tokenPrices: Array<TokenPrice>;\n tokenSnapshot?: Maybe<TokenSnapshot>;\n tokenSnapshots: Array<TokenSnapshot>;\n tokens: Array<Token>;\n tradePair?: Maybe<TradePair>;\n tradePairSnapshot?: Maybe<TradePairSnapshot>;\n tradePairSnapshots: Array<TradePairSnapshot>;\n tradePairs: Array<TradePair>;\n user?: Maybe<User>;\n userInternalBalance?: Maybe<UserInternalBalance>;\n userInternalBalances: Array<UserInternalBalance>;\n users: Array<User>;\n};\n\n\nexport type Subscription_MetaArgs = {\n block?: InputMaybe<Block_Height>;\n};\n\n\nexport type SubscriptionAmpUpdateArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionAmpUpdatesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<AmpUpdate_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<AmpUpdate_Filter>;\n};\n\n\nexport type SubscriptionBalancerArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionBalancerSnapshotArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionBalancerSnapshotsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<BalancerSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<BalancerSnapshot_Filter>;\n};\n\n\nexport type SubscriptionBalancersArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Balancer_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Balancer_Filter>;\n};\n\n\nexport type SubscriptionGradualWeightUpdateArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionGradualWeightUpdatesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GradualWeightUpdate_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GradualWeightUpdate_Filter>;\n};\n\n\nexport type SubscriptionJoinExitArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionJoinExitsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<JoinExit_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<JoinExit_Filter>;\n};\n\n\nexport type SubscriptionLatestPriceArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionLatestPricesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<LatestPrice_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<LatestPrice_Filter>;\n};\n\n\nexport type SubscriptionManagementOperationArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionManagementOperationsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<ManagementOperation_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<ManagementOperation_Filter>;\n};\n\n\nexport type SubscriptionPoolArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionPoolContractArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionPoolContractsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolContract_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolContract_Filter>;\n};\n\n\nexport type SubscriptionPoolHistoricalLiquiditiesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolHistoricalLiquidity_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolHistoricalLiquidity_Filter>;\n};\n\n\nexport type SubscriptionPoolHistoricalLiquidityArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionPoolShareArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionPoolSharesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolShare_Filter>;\n};\n\n\nexport type SubscriptionPoolSnapshotArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionPoolSnapshotsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolSnapshot_Filter>;\n};\n\n\nexport type SubscriptionPoolTokenArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionPoolTokensArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolToken_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PoolToken_Filter>;\n};\n\n\nexport type SubscriptionPoolsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Pool_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Pool_Filter>;\n};\n\n\nexport type SubscriptionPriceRateProviderArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionPriceRateProvidersArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PriceRateProvider_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<PriceRateProvider_Filter>;\n};\n\n\nexport type SubscriptionSwapArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionSwapFeeUpdateArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionSwapFeeUpdatesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<SwapFeeUpdate_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<SwapFeeUpdate_Filter>;\n};\n\n\nexport type SubscriptionSwapsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Swap_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Swap_Filter>;\n};\n\n\nexport type SubscriptionTokenArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionTokenPriceArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionTokenPricesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<TokenPrice_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<TokenPrice_Filter>;\n};\n\n\nexport type SubscriptionTokenSnapshotArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionTokenSnapshotsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<TokenSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<TokenSnapshot_Filter>;\n};\n\n\nexport type SubscriptionTokensArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Token_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Token_Filter>;\n};\n\n\nexport type SubscriptionTradePairArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionTradePairSnapshotArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionTradePairSnapshotsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<TradePairSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<TradePairSnapshot_Filter>;\n};\n\n\nexport type SubscriptionTradePairsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<TradePair_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<TradePair_Filter>;\n};\n\n\nexport type SubscriptionUserArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionUserInternalBalanceArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionUserInternalBalancesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<UserInternalBalance_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<UserInternalBalance_Filter>;\n};\n\n\nexport type SubscriptionUsersArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<User_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<User_Filter>;\n};\n\nexport type Swap = {\n __typename?: 'Swap';\n caller: Scalars['Bytes'];\n id: Scalars['ID'];\n poolId: Pool;\n timestamp: Scalars['Int'];\n tokenAmountIn: Scalars['BigDecimal'];\n tokenAmountOut: Scalars['BigDecimal'];\n tokenIn: Scalars['Bytes'];\n tokenInSym: Scalars['String'];\n tokenOut: Scalars['Bytes'];\n tokenOutSym: Scalars['String'];\n tx: Scalars['Bytes'];\n userAddress: User;\n valueUSD: Scalars['BigDecimal'];\n};\n\nexport type SwapFeeUpdate = {\n __typename?: 'SwapFeeUpdate';\n endSwapFeePercentage: Scalars['BigDecimal'];\n endTimestamp: Scalars['BigInt'];\n id: Scalars['ID'];\n pool: Pool;\n scheduledTimestamp: Scalars['Int'];\n startSwapFeePercentage: Scalars['BigDecimal'];\n startTimestamp: Scalars['BigInt'];\n};\n\nexport type SwapFeeUpdate_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n endSwapFeePercentage?: InputMaybe<Scalars['BigDecimal']>;\n endSwapFeePercentage_gt?: InputMaybe<Scalars['BigDecimal']>;\n endSwapFeePercentage_gte?: InputMaybe<Scalars['BigDecimal']>;\n endSwapFeePercentage_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n endSwapFeePercentage_lt?: InputMaybe<Scalars['BigDecimal']>;\n endSwapFeePercentage_lte?: InputMaybe<Scalars['BigDecimal']>;\n endSwapFeePercentage_not?: InputMaybe<Scalars['BigDecimal']>;\n endSwapFeePercentage_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n endTimestamp?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_gt?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_gte?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n endTimestamp_lt?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_lte?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_not?: InputMaybe<Scalars['BigInt']>;\n endTimestamp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n pool?: InputMaybe<Scalars['String']>;\n pool_?: InputMaybe<Pool_Filter>;\n pool_contains?: InputMaybe<Scalars['String']>;\n pool_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_ends_with?: InputMaybe<Scalars['String']>;\n pool_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_gt?: InputMaybe<Scalars['String']>;\n pool_gte?: InputMaybe<Scalars['String']>;\n pool_in?: InputMaybe<Array<Scalars['String']>>;\n pool_lt?: InputMaybe<Scalars['String']>;\n pool_lte?: InputMaybe<Scalars['String']>;\n pool_not?: InputMaybe<Scalars['String']>;\n pool_not_contains?: InputMaybe<Scalars['String']>;\n pool_not_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_not_ends_with?: InputMaybe<Scalars['String']>;\n pool_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_not_in?: InputMaybe<Array<Scalars['String']>>;\n pool_not_starts_with?: InputMaybe<Scalars['String']>;\n pool_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n pool_starts_with?: InputMaybe<Scalars['String']>;\n pool_starts_with_nocase?: InputMaybe<Scalars['String']>;\n scheduledTimestamp?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_gt?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_gte?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n scheduledTimestamp_lt?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_lte?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_not?: InputMaybe<Scalars['Int']>;\n scheduledTimestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n startSwapFeePercentage?: InputMaybe<Scalars['BigDecimal']>;\n startSwapFeePercentage_gt?: InputMaybe<Scalars['BigDecimal']>;\n startSwapFeePercentage_gte?: InputMaybe<Scalars['BigDecimal']>;\n startSwapFeePercentage_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n startSwapFeePercentage_lt?: InputMaybe<Scalars['BigDecimal']>;\n startSwapFeePercentage_lte?: InputMaybe<Scalars['BigDecimal']>;\n startSwapFeePercentage_not?: InputMaybe<Scalars['BigDecimal']>;\n startSwapFeePercentage_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n startTimestamp?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_gt?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_gte?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n startTimestamp_lt?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_lte?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_not?: InputMaybe<Scalars['BigInt']>;\n startTimestamp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n};\n\nexport enum SwapFeeUpdate_OrderBy {\n EndSwapFeePercentage = 'endSwapFeePercentage',\n EndTimestamp = 'endTimestamp',\n Id = 'id',\n Pool = 'pool',\n ScheduledTimestamp = 'scheduledTimestamp',\n StartSwapFeePercentage = 'startSwapFeePercentage',\n StartTimestamp = 'startTimestamp'\n}\n\nexport type Swap_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n caller?: InputMaybe<Scalars['Bytes']>;\n caller_contains?: InputMaybe<Scalars['Bytes']>;\n caller_gt?: InputMaybe<Scalars['Bytes']>;\n caller_gte?: InputMaybe<Scalars['Bytes']>;\n caller_in?: InputMaybe<Array<Scalars['Bytes']>>;\n caller_lt?: InputMaybe<Scalars['Bytes']>;\n caller_lte?: InputMaybe<Scalars['Bytes']>;\n caller_not?: InputMaybe<Scalars['Bytes']>;\n caller_not_contains?: InputMaybe<Scalars['Bytes']>;\n caller_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolId?: InputMaybe<Scalars['String']>;\n poolId_?: InputMaybe<Pool_Filter>;\n poolId_contains?: InputMaybe<Scalars['String']>;\n poolId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_ends_with?: InputMaybe<Scalars['String']>;\n poolId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_gt?: InputMaybe<Scalars['String']>;\n poolId_gte?: InputMaybe<Scalars['String']>;\n poolId_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_lt?: InputMaybe<Scalars['String']>;\n poolId_lte?: InputMaybe<Scalars['String']>;\n poolId_not?: InputMaybe<Scalars['String']>;\n poolId_not_contains?: InputMaybe<Scalars['String']>;\n poolId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_starts_with?: InputMaybe<Scalars['String']>;\n poolId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n timestamp?: InputMaybe<Scalars['Int']>;\n timestamp_gt?: InputMaybe<Scalars['Int']>;\n timestamp_gte?: InputMaybe<Scalars['Int']>;\n timestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n timestamp_lt?: InputMaybe<Scalars['Int']>;\n timestamp_lte?: InputMaybe<Scalars['Int']>;\n timestamp_not?: InputMaybe<Scalars['Int']>;\n timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n tokenAmountIn?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountIn_gt?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountIn_gte?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountIn_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tokenAmountIn_lt?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountIn_lte?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountIn_not?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountIn_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tokenAmountOut?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountOut_gt?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountOut_gte?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountOut_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tokenAmountOut_lt?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountOut_lte?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountOut_not?: InputMaybe<Scalars['BigDecimal']>;\n tokenAmountOut_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n tokenIn?: InputMaybe<Scalars['Bytes']>;\n tokenInSym?: InputMaybe<Scalars['String']>;\n tokenInSym_contains?: InputMaybe<Scalars['String']>;\n tokenInSym_contains_nocase?: InputMaybe<Scalars['String']>;\n tokenInSym_ends_with?: InputMaybe<Scalars['String']>;\n tokenInSym_ends_with_nocase?: InputMaybe<Scalars['String']>;\n tokenInSym_gt?: InputMaybe<Scalars['String']>;\n tokenInSym_gte?: InputMaybe<Scalars['String']>;\n tokenInSym_in?: InputMaybe<Array<Scalars['String']>>;\n tokenInSym_lt?: InputMaybe<Scalars['String']>;\n tokenInSym_lte?: InputMaybe<Scalars['String']>;\n tokenInSym_not?: InputMaybe<Scalars['String']>;\n tokenInSym_not_contains?: InputMaybe<Scalars['String']>;\n tokenInSym_not_contains_nocase?: InputMaybe<Scalars['String']>;\n tokenInSym_not_ends_with?: InputMaybe<Scalars['String']>;\n tokenInSym_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n tokenInSym_not_in?: InputMaybe<Array<Scalars['String']>>;\n tokenInSym_not_starts_with?: InputMaybe<Scalars['String']>;\n tokenInSym_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n tokenInSym_starts_with?: InputMaybe<Scalars['String']>;\n tokenInSym_starts_with_nocase?: InputMaybe<Scalars['String']>;\n tokenIn_contains?: InputMaybe<Scalars['Bytes']>;\n tokenIn_gt?: InputMaybe<Scalars['Bytes']>;\n tokenIn_gte?: InputMaybe<Scalars['Bytes']>;\n tokenIn_in?: InputMaybe<Array<Scalars['Bytes']>>;\n tokenIn_lt?: InputMaybe<Scalars['Bytes']>;\n tokenIn_lte?: InputMaybe<Scalars['Bytes']>;\n tokenIn_not?: InputMaybe<Scalars['Bytes']>;\n tokenIn_not_contains?: InputMaybe<Scalars['Bytes']>;\n tokenIn_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n tokenOut?: InputMaybe<Scalars['Bytes']>;\n tokenOutSym?: InputMaybe<Scalars['String']>;\n tokenOutSym_contains?: InputMaybe<Scalars['String']>;\n tokenOutSym_contains_nocase?: InputMaybe<Scalars['String']>;\n tokenOutSym_ends_with?: InputMaybe<Scalars['String']>;\n tokenOutSym_ends_with_nocase?: InputMaybe<Scalars['String']>;\n tokenOutSym_gt?: InputMaybe<Scalars['String']>;\n tokenOutSym_gte?: InputMaybe<Scalars['String']>;\n tokenOutSym_in?: InputMaybe<Array<Scalars['String']>>;\n tokenOutSym_lt?: InputMaybe<Scalars['String']>;\n tokenOutSym_lte?: InputMaybe<Scalars['String']>;\n tokenOutSym_not?: InputMaybe<Scalars['String']>;\n tokenOutSym_not_contains?: InputMaybe<Scalars['String']>;\n tokenOutSym_not_contains_nocase?: InputMaybe<Scalars['String']>;\n tokenOutSym_not_ends_with?: InputMaybe<Scalars['String']>;\n tokenOutSym_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n tokenOutSym_not_in?: InputMaybe<Array<Scalars['String']>>;\n tokenOutSym_not_starts_with?: InputMaybe<Scalars['String']>;\n tokenOutSym_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n tokenOutSym_starts_with?: InputMaybe<Scalars['String']>;\n tokenOutSym_starts_with_nocase?: InputMaybe<Scalars['String']>;\n tokenOut_contains?: InputMaybe<Scalars['Bytes']>;\n tokenOut_gt?: InputMaybe<Scalars['Bytes']>;\n tokenOut_gte?: InputMaybe<Scalars['Bytes']>;\n tokenOut_in?: InputMaybe<Array<Scalars['Bytes']>>;\n tokenOut_lt?: InputMaybe<Scalars['Bytes']>;\n tokenOut_lte?: InputMaybe<Scalars['Bytes']>;\n tokenOut_not?: InputMaybe<Scalars['Bytes']>;\n tokenOut_not_contains?: InputMaybe<Scalars['Bytes']>;\n tokenOut_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n tx?: InputMaybe<Scalars['Bytes']>;\n tx_contains?: InputMaybe<Scalars['Bytes']>;\n tx_gt?: InputMaybe<Scalars['Bytes']>;\n tx_gte?: InputMaybe<Scalars['Bytes']>;\n tx_in?: InputMaybe<Array<Scalars['Bytes']>>;\n tx_lt?: InputMaybe<Scalars['Bytes']>;\n tx_lte?: InputMaybe<Scalars['Bytes']>;\n tx_not?: InputMaybe<Scalars['Bytes']>;\n tx_not_contains?: InputMaybe<Scalars['Bytes']>;\n tx_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n userAddress?: InputMaybe<Scalars['String']>;\n userAddress_?: InputMaybe<User_Filter>;\n userAddress_contains?: InputMaybe<Scalars['String']>;\n userAddress_contains_nocase?: InputMaybe<Scalars['String']>;\n userAddress_ends_with?: InputMaybe<Scalars['String']>;\n userAddress_ends_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress_gt?: InputMaybe<Scalars['String']>;\n userAddress_gte?: InputMaybe<Scalars['String']>;\n userAddress_in?: InputMaybe<Array<Scalars['String']>>;\n userAddress_lt?: InputMaybe<Scalars['String']>;\n userAddress_lte?: InputMaybe<Scalars['String']>;\n userAddress_not?: InputMaybe<Scalars['String']>;\n userAddress_not_contains?: InputMaybe<Scalars['String']>;\n userAddress_not_contains_nocase?: InputMaybe<Scalars['String']>;\n userAddress_not_ends_with?: InputMaybe<Scalars['String']>;\n userAddress_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress_not_in?: InputMaybe<Array<Scalars['String']>>;\n userAddress_not_starts_with?: InputMaybe<Scalars['String']>;\n userAddress_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress_starts_with?: InputMaybe<Scalars['String']>;\n userAddress_starts_with_nocase?: InputMaybe<Scalars['String']>;\n valueUSD?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_gt?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_gte?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n valueUSD_lt?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_lte?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_not?: InputMaybe<Scalars['BigDecimal']>;\n valueUSD_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum Swap_OrderBy {\n Caller = 'caller',\n Id = 'id',\n PoolId = 'poolId',\n Timestamp = 'timestamp',\n TokenAmountIn = 'tokenAmountIn',\n TokenAmountOut = 'tokenAmountOut',\n TokenIn = 'tokenIn',\n TokenInSym = 'tokenInSym',\n TokenOut = 'tokenOut',\n TokenOutSym = 'tokenOutSym',\n Tx = 'tx',\n UserAddress = 'userAddress',\n ValueUsd = 'valueUSD'\n}\n\nexport type Token = {\n __typename?: 'Token';\n address: Scalars['String'];\n decimals: Scalars['Int'];\n id: Scalars['ID'];\n latestFXPrice?: Maybe<Scalars['BigDecimal']>;\n latestPrice?: Maybe<LatestPrice>;\n latestUSDPrice?: Maybe<Scalars['BigDecimal']>;\n name?: Maybe<Scalars['String']>;\n pool?: Maybe<Pool>;\n symbol?: Maybe<Scalars['String']>;\n totalBalanceNotional: Scalars['BigDecimal'];\n totalBalanceUSD: Scalars['BigDecimal'];\n totalSwapCount: Scalars['BigInt'];\n totalVolumeNotional: Scalars['BigDecimal'];\n totalVolumeUSD: Scalars['BigDecimal'];\n};\n\nexport type TokenPrice = {\n __typename?: 'TokenPrice';\n amount: Scalars['BigDecimal'];\n asset: Scalars['Bytes'];\n block: Scalars['BigInt'];\n id: Scalars['ID'];\n poolId: Pool;\n price: Scalars['BigDecimal'];\n pricingAsset: Scalars['Bytes'];\n timestamp: Scalars['Int'];\n};\n\nexport type TokenPrice_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n amount?: InputMaybe<Scalars['BigDecimal']>;\n amount_gt?: InputMaybe<Scalars['BigDecimal']>;\n amount_gte?: InputMaybe<Scalars['BigDecimal']>;\n amount_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n amount_lt?: InputMaybe<Scalars['BigDecimal']>;\n amount_lte?: InputMaybe<Scalars['BigDecimal']>;\n amount_not?: InputMaybe<Scalars['BigDecimal']>;\n amount_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n asset?: InputMaybe<Scalars['Bytes']>;\n asset_contains?: InputMaybe<Scalars['Bytes']>;\n asset_gt?: InputMaybe<Scalars['Bytes']>;\n asset_gte?: InputMaybe<Scalars['Bytes']>;\n asset_in?: InputMaybe<Array<Scalars['Bytes']>>;\n asset_lt?: InputMaybe<Scalars['Bytes']>;\n asset_lte?: InputMaybe<Scalars['Bytes']>;\n asset_not?: InputMaybe<Scalars['Bytes']>;\n asset_not_contains?: InputMaybe<Scalars['Bytes']>;\n asset_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n block?: InputMaybe<Scalars['BigInt']>;\n block_gt?: InputMaybe<Scalars['BigInt']>;\n block_gte?: InputMaybe<Scalars['BigInt']>;\n block_in?: InputMaybe<Array<Scalars['BigInt']>>;\n block_lt?: InputMaybe<Scalars['BigInt']>;\n block_lte?: InputMaybe<Scalars['BigInt']>;\n block_not?: InputMaybe<Scalars['BigInt']>;\n block_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolId?: InputMaybe<Scalars['String']>;\n poolId_?: InputMaybe<Pool_Filter>;\n poolId_contains?: InputMaybe<Scalars['String']>;\n poolId_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_ends_with?: InputMaybe<Scalars['String']>;\n poolId_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_gt?: InputMaybe<Scalars['String']>;\n poolId_gte?: InputMaybe<Scalars['String']>;\n poolId_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_lt?: InputMaybe<Scalars['String']>;\n poolId_lte?: InputMaybe<Scalars['String']>;\n poolId_not?: InputMaybe<Scalars['String']>;\n poolId_not_contains?: InputMaybe<Scalars['String']>;\n poolId_not_contains_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with?: InputMaybe<Scalars['String']>;\n poolId_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_not_in?: InputMaybe<Array<Scalars['String']>>;\n poolId_not_starts_with?: InputMaybe<Scalars['String']>;\n poolId_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n poolId_starts_with?: InputMaybe<Scalars['String']>;\n poolId_starts_with_nocase?: InputMaybe<Scalars['String']>;\n price?: InputMaybe<Scalars['BigDecimal']>;\n price_gt?: InputMaybe<Scalars['BigDecimal']>;\n price_gte?: InputMaybe<Scalars['BigDecimal']>;\n price_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n price_lt?: InputMaybe<Scalars['BigDecimal']>;\n price_lte?: InputMaybe<Scalars['BigDecimal']>;\n price_not?: InputMaybe<Scalars['BigDecimal']>;\n price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n pricingAsset?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_contains?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_gt?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_gte?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_in?: InputMaybe<Array<Scalars['Bytes']>>;\n pricingAsset_lt?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_lte?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_not?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_not_contains?: InputMaybe<Scalars['Bytes']>;\n pricingAsset_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n timestamp?: InputMaybe<Scalars['Int']>;\n timestamp_gt?: InputMaybe<Scalars['Int']>;\n timestamp_gte?: InputMaybe<Scalars['Int']>;\n timestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n timestamp_lt?: InputMaybe<Scalars['Int']>;\n timestamp_lte?: InputMaybe<Scalars['Int']>;\n timestamp_not?: InputMaybe<Scalars['Int']>;\n timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n};\n\nexport enum TokenPrice_OrderBy {\n Amount = 'amount',\n Asset = 'asset',\n Block = 'block',\n Id = 'id',\n PoolId = 'poolId',\n Price = 'price',\n PricingAsset = 'pricingAsset',\n Timestamp = 'timestamp'\n}\n\nexport type TokenSnapshot = {\n __typename?: 'TokenSnapshot';\n id: Scalars['ID'];\n timestamp: Scalars['Int'];\n token: Token;\n totalBalanceNotional: Scalars['BigDecimal'];\n totalBalanceUSD: Scalars['BigDecimal'];\n totalSwapCount: Scalars['BigInt'];\n totalVolumeNotional: Scalars['BigDecimal'];\n totalVolumeUSD: Scalars['BigDecimal'];\n};\n\nexport type TokenSnapshot_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n timestamp?: InputMaybe<Scalars['Int']>;\n timestamp_gt?: InputMaybe<Scalars['Int']>;\n timestamp_gte?: InputMaybe<Scalars['Int']>;\n timestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n timestamp_lt?: InputMaybe<Scalars['Int']>;\n timestamp_lte?: InputMaybe<Scalars['Int']>;\n timestamp_not?: InputMaybe<Scalars['Int']>;\n timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n token?: InputMaybe<Scalars['String']>;\n token_?: InputMaybe<Token_Filter>;\n token_contains?: InputMaybe<Scalars['String']>;\n token_contains_nocase?: InputMaybe<Scalars['String']>;\n token_ends_with?: InputMaybe<Scalars['String']>;\n token_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token_gt?: InputMaybe<Scalars['String']>;\n token_gte?: InputMaybe<Scalars['String']>;\n token_in?: InputMaybe<Array<Scalars['String']>>;\n token_lt?: InputMaybe<Scalars['String']>;\n token_lte?: InputMaybe<Scalars['String']>;\n token_not?: InputMaybe<Scalars['String']>;\n token_not_contains?: InputMaybe<Scalars['String']>;\n token_not_contains_nocase?: InputMaybe<Scalars['String']>;\n token_not_ends_with?: InputMaybe<Scalars['String']>;\n token_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token_not_in?: InputMaybe<Array<Scalars['String']>>;\n token_not_starts_with?: InputMaybe<Scalars['String']>;\n token_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n token_starts_with?: InputMaybe<Scalars['String']>;\n token_starts_with_nocase?: InputMaybe<Scalars['String']>;\n totalBalanceNotional?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalBalanceNotional_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_not?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalBalanceUSD?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalBalanceUSD_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_not?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapCount?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_gt?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_gte?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_in?: InputMaybe<Array<Scalars['BigInt']>>;\n totalSwapCount_lt?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_lte?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_not?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n totalVolumeNotional?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalVolumeNotional_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_not?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalVolumeUSD?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalVolumeUSD_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_not?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum TokenSnapshot_OrderBy {\n Id = 'id',\n Timestamp = 'timestamp',\n Token = 'token',\n TotalBalanceNotional = 'totalBalanceNotional',\n TotalBalanceUsd = 'totalBalanceUSD',\n TotalSwapCount = 'totalSwapCount',\n TotalVolumeNotional = 'totalVolumeNotional',\n TotalVolumeUsd = 'totalVolumeUSD'\n}\n\nexport type Token_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n address?: InputMaybe<Scalars['String']>;\n address_contains?: InputMaybe<Scalars['String']>;\n address_contains_nocase?: InputMaybe<Scalars['String']>;\n address_ends_with?: InputMaybe<Scalars['String']>;\n address_ends_with_nocase?: InputMaybe<Scalars['String']>;\n address_gt?: InputMaybe<Scalars['String']>;\n address_gte?: InputMaybe<Scalars['String']>;\n address_in?: InputMaybe<Array<Scalars['String']>>;\n address_lt?: InputMaybe<Scalars['String']>;\n address_lte?: InputMaybe<Scalars['String']>;\n address_not?: InputMaybe<Scalars['String']>;\n address_not_contains?: InputMaybe<Scalars['String']>;\n address_not_contains_nocase?: InputMaybe<Scalars['String']>;\n address_not_ends_with?: InputMaybe<Scalars['String']>;\n address_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n address_not_in?: InputMaybe<Array<Scalars['String']>>;\n address_not_starts_with?: InputMaybe<Scalars['String']>;\n address_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n address_starts_with?: InputMaybe<Scalars['String']>;\n address_starts_with_nocase?: InputMaybe<Scalars['String']>;\n decimals?: InputMaybe<Scalars['Int']>;\n decimals_gt?: InputMaybe<Scalars['Int']>;\n decimals_gte?: InputMaybe<Scalars['Int']>;\n decimals_in?: InputMaybe<Array<Scalars['Int']>>;\n decimals_lt?: InputMaybe<Scalars['Int']>;\n decimals_lte?: InputMaybe<Scalars['Int']>;\n decimals_not?: InputMaybe<Scalars['Int']>;\n decimals_not_in?: InputMaybe<Array<Scalars['Int']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n latestFXPrice?: InputMaybe<Scalars['BigDecimal']>;\n latestFXPrice_gt?: InputMaybe<Scalars['BigDecimal']>;\n latestFXPrice_gte?: InputMaybe<Scalars['BigDecimal']>;\n latestFXPrice_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n latestFXPrice_lt?: InputMaybe<Scalars['BigDecimal']>;\n latestFXPrice_lte?: InputMaybe<Scalars['BigDecimal']>;\n latestFXPrice_not?: InputMaybe<Scalars['BigDecimal']>;\n latestFXPrice_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n latestPrice?: InputMaybe<Scalars['String']>;\n latestPrice_?: InputMaybe<LatestPrice_Filter>;\n latestPrice_contains?: InputMaybe<Scalars['String']>;\n latestPrice_contains_nocase?: InputMaybe<Scalars['String']>;\n latestPrice_ends_with?: InputMaybe<Scalars['String']>;\n latestPrice_ends_with_nocase?: InputMaybe<Scalars['String']>;\n latestPrice_gt?: InputMaybe<Scalars['String']>;\n latestPrice_gte?: InputMaybe<Scalars['String']>;\n latestPrice_in?: InputMaybe<Array<Scalars['String']>>;\n latestPrice_lt?: InputMaybe<Scalars['String']>;\n latestPrice_lte?: InputMaybe<Scalars['String']>;\n latestPrice_not?: InputMaybe<Scalars['String']>;\n latestPrice_not_contains?: InputMaybe<Scalars['String']>;\n latestPrice_not_contains_nocase?: InputMaybe<Scalars['String']>;\n latestPrice_not_ends_with?: InputMaybe<Scalars['String']>;\n latestPrice_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n latestPrice_not_in?: InputMaybe<Array<Scalars['String']>>;\n latestPrice_not_starts_with?: InputMaybe<Scalars['String']>;\n latestPrice_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n latestPrice_starts_with?: InputMaybe<Scalars['String']>;\n latestPrice_starts_with_nocase?: InputMaybe<Scalars['String']>;\n latestUSDPrice?: InputMaybe<Scalars['BigDecimal']>;\n latestUSDPrice_gt?: InputMaybe<Scalars['BigDecimal']>;\n latestUSDPrice_gte?: InputMaybe<Scalars['BigDecimal']>;\n latestUSDPrice_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n latestUSDPrice_lt?: InputMaybe<Scalars['BigDecimal']>;\n latestUSDPrice_lte?: InputMaybe<Scalars['BigDecimal']>;\n latestUSDPrice_not?: InputMaybe<Scalars['BigDecimal']>;\n latestUSDPrice_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n name?: InputMaybe<Scalars['String']>;\n name_contains?: InputMaybe<Scalars['String']>;\n name_contains_nocase?: InputMaybe<Scalars['String']>;\n name_ends_with?: InputMaybe<Scalars['String']>;\n name_ends_with_nocase?: InputMaybe<Scalars['String']>;\n name_gt?: InputMaybe<Scalars['String']>;\n name_gte?: InputMaybe<Scalars['String']>;\n name_in?: InputMaybe<Array<Scalars['String']>>;\n name_lt?: InputMaybe<Scalars['String']>;\n name_lte?: InputMaybe<Scalars['String']>;\n name_not?: InputMaybe<Scalars['String']>;\n name_not_contains?: InputMaybe<Scalars['String']>;\n name_not_contains_nocase?: InputMaybe<Scalars['String']>;\n name_not_ends_with?: InputMaybe<Scalars['String']>;\n name_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n name_not_in?: InputMaybe<Array<Scalars['String']>>;\n name_not_starts_with?: InputMaybe<Scalars['String']>;\n name_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n name_starts_with?: InputMaybe<Scalars['String']>;\n name_starts_with_nocase?: InputMaybe<Scalars['String']>;\n pool?: InputMaybe<Scalars['String']>;\n pool_?: InputMaybe<Pool_Filter>;\n pool_contains?: InputMaybe<Scalars['String']>;\n pool_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_ends_with?: InputMaybe<Scalars['String']>;\n pool_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_gt?: InputMaybe<Scalars['String']>;\n pool_gte?: InputMaybe<Scalars['String']>;\n pool_in?: InputMaybe<Array<Scalars['String']>>;\n pool_lt?: InputMaybe<Scalars['String']>;\n pool_lte?: InputMaybe<Scalars['String']>;\n pool_not?: InputMaybe<Scalars['String']>;\n pool_not_contains?: InputMaybe<Scalars['String']>;\n pool_not_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_not_ends_with?: InputMaybe<Scalars['String']>;\n pool_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_not_in?: InputMaybe<Array<Scalars['String']>>;\n pool_not_starts_with?: InputMaybe<Scalars['String']>;\n pool_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n pool_starts_with?: InputMaybe<Scalars['String']>;\n pool_starts_with_nocase?: InputMaybe<Scalars['String']>;\n symbol?: InputMaybe<Scalars['String']>;\n symbol_contains?: InputMaybe<Scalars['String']>;\n symbol_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_ends_with?: InputMaybe<Scalars['String']>;\n symbol_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_gt?: InputMaybe<Scalars['String']>;\n symbol_gte?: InputMaybe<Scalars['String']>;\n symbol_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_lt?: InputMaybe<Scalars['String']>;\n symbol_lte?: InputMaybe<Scalars['String']>;\n symbol_not?: InputMaybe<Scalars['String']>;\n symbol_not_contains?: InputMaybe<Scalars['String']>;\n symbol_not_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_not_starts_with?: InputMaybe<Scalars['String']>;\n symbol_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_starts_with?: InputMaybe<Scalars['String']>;\n symbol_starts_with_nocase?: InputMaybe<Scalars['String']>;\n totalBalanceNotional?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalBalanceNotional_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_not?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceNotional_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalBalanceUSD?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalBalanceUSD_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_not?: InputMaybe<Scalars['BigDecimal']>;\n totalBalanceUSD_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapCount?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_gt?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_gte?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_in?: InputMaybe<Array<Scalars['BigInt']>>;\n totalSwapCount_lt?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_lte?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_not?: InputMaybe<Scalars['BigInt']>;\n totalSwapCount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n totalVolumeNotional?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalVolumeNotional_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_not?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeNotional_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalVolumeUSD?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalVolumeUSD_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_not?: InputMaybe<Scalars['BigDecimal']>;\n totalVolumeUSD_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum Token_OrderBy {\n Address = 'address',\n Decimals = 'decimals',\n Id = 'id',\n LatestFxPrice = 'latestFXPrice',\n LatestPrice = 'latestPrice',\n LatestUsdPrice = 'latestUSDPrice',\n Name = 'name',\n Pool = 'pool',\n Symbol = 'symbol',\n TotalBalanceNotional = 'totalBalanceNotional',\n TotalBalanceUsd = 'totalBalanceUSD',\n TotalSwapCount = 'totalSwapCount',\n TotalVolumeNotional = 'totalVolumeNotional',\n TotalVolumeUsd = 'totalVolumeUSD'\n}\n\nexport type TradePair = {\n __typename?: 'TradePair';\n /** Token Address - Token Address */\n id: Scalars['ID'];\n token0: Token;\n token1: Token;\n totalSwapFee: Scalars['BigDecimal'];\n totalSwapVolume: Scalars['BigDecimal'];\n};\n\nexport type TradePairSnapshot = {\n __typename?: 'TradePairSnapshot';\n id: Scalars['ID'];\n pair: TradePair;\n timestamp: Scalars['Int'];\n totalSwapFee: Scalars['BigDecimal'];\n totalSwapVolume: Scalars['BigDecimal'];\n};\n\nexport type TradePairSnapshot_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n pair?: InputMaybe<Scalars['String']>;\n pair_?: InputMaybe<TradePair_Filter>;\n pair_contains?: InputMaybe<Scalars['String']>;\n pair_contains_nocase?: InputMaybe<Scalars['String']>;\n pair_ends_with?: InputMaybe<Scalars['String']>;\n pair_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pair_gt?: InputMaybe<Scalars['String']>;\n pair_gte?: InputMaybe<Scalars['String']>;\n pair_in?: InputMaybe<Array<Scalars['String']>>;\n pair_lt?: InputMaybe<Scalars['String']>;\n pair_lte?: InputMaybe<Scalars['String']>;\n pair_not?: InputMaybe<Scalars['String']>;\n pair_not_contains?: InputMaybe<Scalars['String']>;\n pair_not_contains_nocase?: InputMaybe<Scalars['String']>;\n pair_not_ends_with?: InputMaybe<Scalars['String']>;\n pair_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pair_not_in?: InputMaybe<Array<Scalars['String']>>;\n pair_not_starts_with?: InputMaybe<Scalars['String']>;\n pair_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n pair_starts_with?: InputMaybe<Scalars['String']>;\n pair_starts_with_nocase?: InputMaybe<Scalars['String']>;\n timestamp?: InputMaybe<Scalars['Int']>;\n timestamp_gt?: InputMaybe<Scalars['Int']>;\n timestamp_gte?: InputMaybe<Scalars['Int']>;\n timestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n timestamp_lt?: InputMaybe<Scalars['Int']>;\n timestamp_lte?: InputMaybe<Scalars['Int']>;\n timestamp_not?: InputMaybe<Scalars['Int']>;\n timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n totalSwapFee?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapFee_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum TradePairSnapshot_OrderBy {\n Id = 'id',\n Pair = 'pair',\n Timestamp = 'timestamp',\n TotalSwapFee = 'totalSwapFee',\n TotalSwapVolume = 'totalSwapVolume'\n}\n\nexport type TradePair_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n token0?: InputMaybe<Scalars['String']>;\n token0_?: InputMaybe<Token_Filter>;\n token0_contains?: InputMaybe<Scalars['String']>;\n token0_contains_nocase?: InputMaybe<Scalars['String']>;\n token0_ends_with?: InputMaybe<Scalars['String']>;\n token0_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token0_gt?: InputMaybe<Scalars['String']>;\n token0_gte?: InputMaybe<Scalars['String']>;\n token0_in?: InputMaybe<Array<Scalars['String']>>;\n token0_lt?: InputMaybe<Scalars['String']>;\n token0_lte?: InputMaybe<Scalars['String']>;\n token0_not?: InputMaybe<Scalars['String']>;\n token0_not_contains?: InputMaybe<Scalars['String']>;\n token0_not_contains_nocase?: InputMaybe<Scalars['String']>;\n token0_not_ends_with?: InputMaybe<Scalars['String']>;\n token0_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token0_not_in?: InputMaybe<Array<Scalars['String']>>;\n token0_not_starts_with?: InputMaybe<Scalars['String']>;\n token0_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n token0_starts_with?: InputMaybe<Scalars['String']>;\n token0_starts_with_nocase?: InputMaybe<Scalars['String']>;\n token1?: InputMaybe<Scalars['String']>;\n token1_?: InputMaybe<Token_Filter>;\n token1_contains?: InputMaybe<Scalars['String']>;\n token1_contains_nocase?: InputMaybe<Scalars['String']>;\n token1_ends_with?: InputMaybe<Scalars['String']>;\n token1_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token1_gt?: InputMaybe<Scalars['String']>;\n token1_gte?: InputMaybe<Scalars['String']>;\n token1_in?: InputMaybe<Array<Scalars['String']>>;\n token1_lt?: InputMaybe<Scalars['String']>;\n token1_lte?: InputMaybe<Scalars['String']>;\n token1_not?: InputMaybe<Scalars['String']>;\n token1_not_contains?: InputMaybe<Scalars['String']>;\n token1_not_contains_nocase?: InputMaybe<Scalars['String']>;\n token1_not_ends_with?: InputMaybe<Scalars['String']>;\n token1_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n token1_not_in?: InputMaybe<Array<Scalars['String']>>;\n token1_not_starts_with?: InputMaybe<Scalars['String']>;\n token1_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n token1_starts_with?: InputMaybe<Scalars['String']>;\n token1_starts_with_nocase?: InputMaybe<Scalars['String']>;\n totalSwapFee?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapFee_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapFee_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSwapVolume_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSwapVolume_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum TradePair_OrderBy {\n Id = 'id',\n Token0 = 'token0',\n Token1 = 'token1',\n TotalSwapFee = 'totalSwapFee',\n TotalSwapVolume = 'totalSwapVolume'\n}\n\nexport type User = {\n __typename?: 'User';\n id: Scalars['ID'];\n sharesOwned?: Maybe<Array<PoolShare>>;\n swaps?: Maybe<Array<Swap>>;\n userInternalBalances?: Maybe<Array<UserInternalBalance>>;\n};\n\n\nexport type UserSharesOwnedArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<PoolShare_Filter>;\n};\n\n\nexport type UserSwapsArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Swap_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<Swap_Filter>;\n};\n\n\nexport type UserUserInternalBalancesArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<UserInternalBalance_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<UserInternalBalance_Filter>;\n};\n\nexport type UserInternalBalance = {\n __typename?: 'UserInternalBalance';\n balance: Scalars['BigDecimal'];\n id: Scalars['ID'];\n token: Scalars['Bytes'];\n userAddress?: Maybe<User>;\n};\n\nexport type UserInternalBalance_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n balance?: InputMaybe<Scalars['BigDecimal']>;\n balance_gt?: InputMaybe<Scalars['BigDecimal']>;\n balance_gte?: InputMaybe<Scalars['BigDecimal']>;\n balance_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n balance_lt?: InputMaybe<Scalars['BigDecimal']>;\n balance_lte?: InputMaybe<Scalars['BigDecimal']>;\n balance_not?: InputMaybe<Scalars['BigDecimal']>;\n balance_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n token?: InputMaybe<Scalars['Bytes']>;\n token_contains?: InputMaybe<Scalars['Bytes']>;\n token_gt?: InputMaybe<Scalars['Bytes']>;\n token_gte?: InputMaybe<Scalars['Bytes']>;\n token_in?: InputMaybe<Array<Scalars['Bytes']>>;\n token_lt?: InputMaybe<Scalars['Bytes']>;\n token_lte?: InputMaybe<Scalars['Bytes']>;\n token_not?: InputMaybe<Scalars['Bytes']>;\n token_not_contains?: InputMaybe<Scalars['Bytes']>;\n token_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n userAddress?: InputMaybe<Scalars['String']>;\n userAddress_?: InputMaybe<User_Filter>;\n userAddress_contains?: InputMaybe<Scalars['String']>;\n userAddress_contains_nocase?: InputMaybe<Scalars['String']>;\n userAddress_ends_with?: InputMaybe<Scalars['String']>;\n userAddress_ends_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress_gt?: InputMaybe<Scalars['String']>;\n userAddress_gte?: InputMaybe<Scalars['String']>;\n userAddress_in?: InputMaybe<Array<Scalars['String']>>;\n userAddress_lt?: InputMaybe<Scalars['String']>;\n userAddress_lte?: InputMaybe<Scalars['String']>;\n userAddress_not?: InputMaybe<Scalars['String']>;\n userAddress_not_contains?: InputMaybe<Scalars['String']>;\n userAddress_not_contains_nocase?: InputMaybe<Scalars['String']>;\n userAddress_not_ends_with?: InputMaybe<Scalars['String']>;\n userAddress_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress_not_in?: InputMaybe<Array<Scalars['String']>>;\n userAddress_not_starts_with?: InputMaybe<Scalars['String']>;\n userAddress_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n userAddress_starts_with?: InputMaybe<Scalars['String']>;\n userAddress_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum UserInternalBalance_OrderBy {\n Balance = 'balance',\n Id = 'id',\n Token = 'token',\n UserAddress = 'userAddress'\n}\n\nexport type User_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n sharesOwned_?: InputMaybe<PoolShare_Filter>;\n swaps_?: InputMaybe<Swap_Filter>;\n userInternalBalances_?: InputMaybe<UserInternalBalance_Filter>;\n};\n\nexport enum User_OrderBy {\n Id = 'id',\n SharesOwned = 'sharesOwned',\n Swaps = 'swaps',\n UserInternalBalances = 'userInternalBalances'\n}\n\nexport type _Block_ = {\n __typename?: '_Block_';\n /** The hash of the block */\n hash?: Maybe<Scalars['Bytes']>;\n /** The block number */\n number: Scalars['Int'];\n /** Integer representation of the timestamp stored in blocks for the chain */\n timestamp?: Maybe<Scalars['Int']>;\n};\n\n/** The type for the top-level _meta field */\nexport type _Meta_ = {\n __typename?: '_Meta_';\n /**\n * Information about a specific subgraph block. The hash of the block\n * will be null if the _meta field has a block constraint that asks for\n * a block number. It will be filled if the _meta field has no block constraint\n * and therefore asks for the latest block\n *\n */\n block: _Block_;\n /** The deployment ID */\n deployment: Scalars['String'];\n /** If `true`, the subgraph encountered indexing errors at some past block */\n hasIndexingErrors: Scalars['Boolean'];\n};\n\nexport enum _SubgraphErrorPolicy_ {\n /** Data will be returned even if the subgraph has indexing errors */\n Allow = 'allow',\n /** If the subgraph has indexing errors, data will be omitted. The default. */\n Deny = 'deny'\n}\n\nexport type PoolShareQueryVariables = Exact<{\n id: Scalars['ID'];\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type PoolShareQuery = { __typename?: 'Query', poolShare?: { __typename?: 'PoolShare', id: string, balance: string, userAddress: { __typename?: 'User', id: string }, poolId: { __typename?: 'Pool', id: string, address: string } } | null };\n\nexport type PoolSharesQueryVariables = Exact<{\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<PoolShare_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type PoolSharesQuery = { __typename?: 'Query', poolShares: Array<{ __typename?: 'PoolShare', id: string, balance: string, userAddress: { __typename?: 'User', id: string }, poolId: { __typename?: 'Pool', id: string, address: string } }> };\n\nexport type SubgraphPoolShareFragment = { __typename?: 'PoolShare', id: string, balance: string, userAddress: { __typename?: 'User', id: string }, poolId: { __typename?: 'Pool', id: string, address: string } };\n\nexport type PoolsQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Pool_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<Pool_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type PoolsQuery = { __typename?: 'Query', pools: Array<{ __typename?: 'Pool', id: string, address: string, poolType?: string | null, poolTypeVersion?: number | null, factory?: string | null, strategyType: number, symbol?: string | null, name?: string | null, swapEnabled: boolean, swapFee: string, protocolYieldFeeCache?: string | null, protocolSwapFeeCache?: string | null, owner?: string | null, totalWeight?: string | null, totalSwapVolume: string, totalSwapFee: string, totalLiquidity: string, totalShares: string, swapsCount: string, holdersCount: string, tokensList: Array<string>, amp?: string | null, expiryTime?: string | null, unitSeconds?: string | null, createTime: number, principalToken?: string | null, baseToken?: string | null, wrappedIndex?: number | null, mainIndex?: number | null, lowerTarget?: string | null, upperTarget?: string | null, sqrtAlpha?: string | null, sqrtBeta?: string | null, root3Alpha?: string | null, tokens?: Array<{ __typename?: 'PoolToken', id: string, symbol: string, name: string, decimals: number, address: string, balance: string, managedBalance: string, weight?: string | null, priceRate: string, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null } | null } }> | null } | null } }> | null } | null } }> | null, priceRateProviders?: Array<{ __typename?: 'PriceRateProvider', address: string, token: { __typename?: 'PoolToken', address: string } }> | null }> };\n\nexport type AllPoolsQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Pool_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<Pool_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type AllPoolsQuery = { __typename?: 'Query', pool0: Array<{ __typename?: 'Pool', id: string, address: string, poolType?: string | null, poolTypeVersion?: number | null, factory?: string | null, strategyType: number, symbol?: string | null, name?: string | null, swapEnabled: boolean, swapFee: string, protocolYieldFeeCache?: string | null, protocolSwapFeeCache?: string | null, owner?: string | null, totalWeight?: string | null, totalSwapVolume: string, totalSwapFee: string, totalLiquidity: string, totalShares: string, swapsCount: string, holdersCount: string, tokensList: Array<string>, amp?: string | null, expiryTime?: string | null, unitSeconds?: string | null, createTime: number, principalToken?: string | null, baseToken?: string | null, wrappedIndex?: number | null, mainIndex?: number | null, lowerTarget?: string | null, upperTarget?: string | null, sqrtAlpha?: string | null, sqrtBeta?: string | null, root3Alpha?: string | null, tokens?: Array<{ __typename?: 'PoolToken', id: string, symbol: string, name: string, decimals: number, address: string, balance: string, managedBalance: string, weight?: string | null, priceRate: string, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null } | null } }> | null } | null } }> | null } | null } }> | null, priceRateProviders?: Array<{ __typename?: 'PriceRateProvider', address: string, token: { __typename?: 'PoolToken', address: string } }> | null }>, pool1000: Array<{ __typename?: 'Pool', id: string, address: string, poolType?: string | null, poolTypeVersion?: number | null, factory?: string | null, strategyType: number, symbol?: string | null, name?: string | null, swapEnabled: boolean, swapFee: string, protocolYieldFeeCache?: string | null, protocolSwapFeeCache?: string | null, owner?: string | null, totalWeight?: string | null, totalSwapVolume: string, totalSwapFee: string, totalLiquidity: string, totalShares: string, swapsCount: string, holdersCount: string, tokensList: Array<string>, amp?: string | null, expiryTime?: string | null, unitSeconds?: string | null, createTime: number, principalToken?: string | null, baseToken?: string | null, wrappedIndex?: number | null, mainIndex?: number | null, lowerTarget?: string | null, upperTarget?: string | null, sqrtAlpha?: string | null, sqrtBeta?: string | null, root3Alpha?: string | null, tokens?: Array<{ __typename?: 'PoolToken', id: string, symbol: string, name: string, decimals: number, address: string, balance: string, managedBalance: string, weight?: string | null, priceRate: string, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null } | null } }> | null } | null } }> | null } | null } }> | null, priceRateProviders?: Array<{ __typename?: 'PriceRateProvider', address: string, token: { __typename?: 'PoolToken', address: string } }> | null }>, pool2000: Array<{ __typename?: 'Pool', id: string, address: string, poolType?: string | null, poolTypeVersion?: number | null, factory?: string | null, strategyType: number, symbol?: string | null, name?: string | null, swapEnabled: boolean, swapFee: string, protocolYieldFeeCache?: string | null, protocolSwapFeeCache?: string | null, owner?: string | null, totalWeight?: string | null, totalSwapVolume: string, totalSwapFee: string, totalLiquidity: string, totalShares: string, swapsCount: string, holdersCount: string, tokensList: Array<string>, amp?: string | null, expiryTime?: string | null, unitSeconds?: string | null, createTime: number, principalToken?: string | null, baseToken?: string | null, wrappedIndex?: number | null, mainIndex?: number | null, lowerTarget?: string | null, upperTarget?: string | null, sqrtAlpha?: string | null, sqrtBeta?: string | null, root3Alpha?: string | null, tokens?: Array<{ __typename?: 'PoolToken', id: string, symbol: string, name: string, decimals: number, address: string, balance: string, managedBalance: string, weight?: string | null, priceRate: string, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null } | null } }> | null } | null } }> | null } | null } }> | null, priceRateProviders?: Array<{ __typename?: 'PriceRateProvider', address: string, token: { __typename?: 'PoolToken', address: string } }> | null }> };\n\nexport type PoolQueryVariables = Exact<{\n id: Scalars['ID'];\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type PoolQuery = { __typename?: 'Query', pool?: { __typename?: 'Pool', id: string, address: string, poolType?: string | null, poolTypeVersion?: number | null, factory?: string | null, strategyType: number, symbol?: string | null, name?: string | null, swapEnabled: boolean, swapFee: string, protocolYieldFeeCache?: string | null, protocolSwapFeeCache?: string | null, owner?: string | null, totalWeight?: string | null, totalSwapVolume: string, totalSwapFee: string, totalLiquidity: string, totalShares: string, swapsCount: string, holdersCount: string, tokensList: Array<string>, amp?: string | null, expiryTime?: string | null, unitSeconds?: string | null, createTime: number, principalToken?: string | null, baseToken?: string | null, wrappedIndex?: number | null, mainIndex?: number | null, lowerTarget?: string | null, upperTarget?: string | null, sqrtAlpha?: string | null, sqrtBeta?: string | null, root3Alpha?: string | null, tokens?: Array<{ __typename?: 'PoolToken', id: string, symbol: string, name: string, decimals: number, address: string, balance: string, managedBalance: string, weight?: string | null, priceRate: string, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null } | null } }> | null } | null } }> | null } | null } }> | null, priceRateProviders?: Array<{ __typename?: 'PriceRateProvider', address: string, token: { __typename?: 'PoolToken', address: string } }> | null } | null };\n\nexport type SubgraphPoolFragment = { __typename?: 'Pool', id: string, address: string, poolType?: string | null, poolTypeVersion?: number | null, factory?: string | null, strategyType: number, symbol?: string | null, name?: string | null, swapEnabled: boolean, swapFee: string, protocolYieldFeeCache?: string | null, protocolSwapFeeCache?: string | null, owner?: string | null, totalWeight?: string | null, totalSwapVolume: string, totalSwapFee: string, totalLiquidity: string, totalShares: string, swapsCount: string, holdersCount: string, tokensList: Array<string>, amp?: string | null, expiryTime?: string | null, unitSeconds?: string | null, createTime: number, principalToken?: string | null, baseToken?: string | null, wrappedIndex?: number | null, mainIndex?: number | null, lowerTarget?: string | null, upperTarget?: string | null, sqrtAlpha?: string | null, sqrtBeta?: string | null, root3Alpha?: string | null, tokens?: Array<{ __typename?: 'PoolToken', id: string, symbol: string, name: string, decimals: number, address: string, balance: string, managedBalance: string, weight?: string | null, priceRate: string, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null } | null } }> | null } | null } }> | null } | null } }> | null, priceRateProviders?: Array<{ __typename?: 'PriceRateProvider', address: string, token: { __typename?: 'PoolToken', address: string } }> | null };\n\nexport type SubgraphPoolTokenFragment = { __typename?: 'PoolToken', id: string, symbol: string, name: string, decimals: number, address: string, balance: string, managedBalance: string, weight?: string | null, priceRate: string, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null } | null } }> | null } | null } }> | null } | null } };\n\nexport type SubgraphSubPoolTokenFragment = { __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null };\n\nexport type TokenAttrsFragment = { __typename?: 'Token', address: string, symbol?: string | null, decimals: number };\n\nexport type SubgraphSubPoolFragment = { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null };\n\nexport type TokenTreeFragment = { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null, tokens?: Array<{ __typename?: 'PoolToken', address: string, balance: string, weight?: string | null, priceRate: string, symbol: string, decimals: number, isExemptFromYieldProtocolFee?: boolean | null, token: { __typename?: 'Token', latestUSDPrice?: string | null, pool?: { __typename?: 'Pool', id: string, totalShares: string, address: string, poolType?: string | null, mainIndex?: number | null } | null } }> | null } | null } }> | null } | null };\n\nexport type SubgraphPriceRateProviderFragment = { __typename?: 'PriceRateProvider', address: string, token: { __typename?: 'PoolToken', address: string } };\n\nexport type PoolHistoricalLiquiditiesQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolHistoricalLiquidity_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<PoolHistoricalLiquidity_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type PoolHistoricalLiquiditiesQuery = { __typename?: 'Query', poolHistoricalLiquidities: Array<{ __typename?: 'PoolHistoricalLiquidity', id: string, poolTotalShares: string, poolLiquidity: string, poolShareValue: string, pricingAsset: string, block: string, poolId: { __typename?: 'Pool', id: string } }> };\n\nexport type PoolSnapshotsQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<PoolSnapshot_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<PoolSnapshot_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type PoolSnapshotsQuery = { __typename?: 'Query', poolSnapshots: Array<{ __typename?: 'PoolSnapshot', id: string, totalShares: string, swapVolume: string, swapFees: string, timestamp: number, pool: { __typename?: 'Pool', id: string } }> };\n\nexport type SubgraphPoolSnapshotFragment = { __typename?: 'PoolSnapshot', id: string, totalShares: string, swapVolume: string, swapFees: string, timestamp: number, pool: { __typename?: 'Pool', id: string } };\n\nexport type JoinExitsQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<JoinExit_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<JoinExit_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type JoinExitsQuery = { __typename?: 'Query', joinExits: Array<{ __typename?: 'JoinExit', amounts: Array<string>, id: string, sender: string, timestamp: number, tx: string, type: InvestType, user: { __typename?: 'User', id: string }, pool: { __typename?: 'Pool', id: string, tokensList: Array<string> } }> };\n\nexport type SubgraphJoinExitFragment = { __typename?: 'JoinExit', amounts: Array<string>, id: string, sender: string, timestamp: number, tx: string, type: InvestType, user: { __typename?: 'User', id: string }, pool: { __typename?: 'Pool', id: string, tokensList: Array<string> } };\n\nexport type BalancersQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Balancer_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<Balancer_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type BalancersQuery = { __typename?: 'Query', balancers: Array<{ __typename?: 'Balancer', id: string, totalLiquidity: string, totalSwapVolume: string, totalSwapFee: string, totalSwapCount: string, poolCount: number }> };\n\nexport type SubgraphBalancerFragment = { __typename?: 'Balancer', id: string, totalLiquidity: string, totalSwapVolume: string, totalSwapFee: string, totalSwapCount: string, poolCount: number };\n\nexport type TokenPricesQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<TokenPrice_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<TokenPrice_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type TokenPricesQuery = { __typename?: 'Query', tokenPrices: Array<{ __typename?: 'TokenPrice', id: string, asset: string, amount: string, pricingAsset: string, price: string, block: string, timestamp: number, poolId: { __typename?: 'Pool', id: string } }> };\n\nexport type SubgraphTokenPriceFragment = { __typename?: 'TokenPrice', id: string, asset: string, amount: string, pricingAsset: string, price: string, block: string, timestamp: number, poolId: { __typename?: 'Pool', id: string } };\n\nexport type TokenLatestPricesQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<LatestPrice_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<LatestPrice_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type TokenLatestPricesQuery = { __typename?: 'Query', latestPrices: Array<{ __typename?: 'LatestPrice', id: string, asset: string, price: string, pricingAsset: string, poolId: { __typename?: 'Pool', id: string } }> };\n\nexport type TokenLatestPriceQueryVariables = Exact<{\n id: Scalars['ID'];\n}>;\n\n\nexport type TokenLatestPriceQuery = { __typename?: 'Query', latestPrice?: { __typename?: 'LatestPrice', id: string, asset: string, price: string, pricingAsset: string, poolId: { __typename?: 'Pool', id: string } } | null };\n\nexport type SubgraphTokenLatestPriceFragment = { __typename?: 'LatestPrice', id: string, asset: string, price: string, pricingAsset: string, poolId: { __typename?: 'Pool', id: string } };\n\nexport type UserQueryVariables = Exact<{\n id: Scalars['ID'];\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type UserQuery = { __typename?: 'Query', user?: { __typename?: 'User', id: string, sharesOwned?: Array<{ __typename?: 'PoolShare', balance: string, poolId: { __typename?: 'Pool', id: string } }> | null } | null };\n\nexport type UsersQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<User_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<User_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type UsersQuery = { __typename?: 'Query', users: Array<{ __typename?: 'User', id: string, sharesOwned?: Array<{ __typename?: 'PoolShare', balance: string, poolId: { __typename?: 'Pool', id: string } }> | null }> };\n\nexport type SubgraphUserFragment = { __typename?: 'User', id: string, sharesOwned?: Array<{ __typename?: 'PoolShare', balance: string, poolId: { __typename?: 'Pool', id: string } }> | null };\n\nexport const SubgraphPoolShareFragmentDoc = gql`\n fragment SubgraphPoolShare on PoolShare {\n id\n balance\n userAddress {\n id\n }\n poolId {\n id\n address\n }\n}\n `;\nexport const SubgraphSubPoolFragmentDoc = gql`\n fragment SubgraphSubPool on Pool {\n id\n totalShares\n address\n poolType\n mainIndex\n}\n `;\nexport const SubgraphSubPoolTokenFragmentDoc = gql`\n fragment SubgraphSubPoolToken on PoolToken {\n address\n balance\n weight\n priceRate\n symbol\n decimals\n isExemptFromYieldProtocolFee\n}\n `;\nexport const TokenTreeFragmentDoc = gql`\n fragment TokenTree on Token {\n latestUSDPrice\n pool {\n ...SubgraphSubPool\n tokens {\n ...SubgraphSubPoolToken\n token {\n latestUSDPrice\n pool {\n ...SubgraphSubPool\n tokens {\n ...SubgraphSubPoolToken\n token {\n latestUSDPrice\n pool {\n ...SubgraphSubPool\n }\n }\n }\n }\n }\n }\n }\n}\n ${SubgraphSubPoolFragmentDoc}\n${SubgraphSubPoolTokenFragmentDoc}`;\nexport const SubgraphPoolTokenFragmentDoc = gql`\n fragment SubgraphPoolToken on PoolToken {\n id\n symbol\n name\n decimals\n address\n balance\n managedBalance\n weight\n priceRate\n isExemptFromYieldProtocolFee\n token {\n ...TokenTree\n }\n}\n ${TokenTreeFragmentDoc}`;\nexport const SubgraphPriceRateProviderFragmentDoc = gql`\n fragment SubgraphPriceRateProvider on PriceRateProvider {\n address\n token {\n address\n }\n}\n `;\nexport const SubgraphPoolFragmentDoc = gql`\n fragment SubgraphPool on Pool {\n id\n address\n poolType\n poolTypeVersion\n factory\n strategyType\n symbol\n name\n swapEnabled\n swapFee\n protocolYieldFeeCache\n protocolSwapFeeCache\n owner\n totalWeight\n totalSwapVolume\n totalSwapFee\n totalLiquidity\n totalShares\n tokens(first: 100) {\n ...SubgraphPoolToken\n }\n swapsCount\n holdersCount\n tokensList\n amp\n priceRateProviders(first: 100) {\n ...SubgraphPriceRateProvider\n }\n expiryTime\n unitSeconds\n createTime\n principalToken\n baseToken\n wrappedIndex\n mainIndex\n lowerTarget\n upperTarget\n sqrtAlpha\n sqrtBeta\n root3Alpha\n}\n ${SubgraphPoolTokenFragmentDoc}\n${SubgraphPriceRateProviderFragmentDoc}`;\nexport const TokenAttrsFragmentDoc = gql`\n fragment TokenAttrs on Token {\n address\n symbol\n decimals\n}\n `;\nexport const SubgraphPoolSnapshotFragmentDoc = gql`\n fragment SubgraphPoolSnapshot on PoolSnapshot {\n id\n pool {\n id\n }\n totalShares\n swapVolume\n swapFees\n timestamp\n}\n `;\nexport const SubgraphJoinExitFragmentDoc = gql`\n fragment SubgraphJoinExit on JoinExit {\n amounts\n id\n sender\n timestamp\n tx\n type\n user {\n id\n }\n pool {\n id\n tokensList\n }\n}\n `;\nexport const SubgraphBalancerFragmentDoc = gql`\n fragment SubgraphBalancer on Balancer {\n id\n totalLiquidity\n totalSwapVolume\n totalSwapFee\n totalSwapCount\n poolCount\n}\n `;\nexport const SubgraphTokenPriceFragmentDoc = gql`\n fragment SubgraphTokenPrice on TokenPrice {\n id\n poolId {\n id\n }\n asset\n amount\n pricingAsset\n price\n block\n timestamp\n}\n `;\nexport const SubgraphTokenLatestPriceFragmentDoc = gql`\n fragment SubgraphTokenLatestPrice on LatestPrice {\n id\n asset\n price\n poolId {\n id\n }\n pricingAsset\n}\n `;\nexport const SubgraphUserFragmentDoc = gql`\n fragment SubgraphUser on User {\n id\n sharesOwned(first: 1000) {\n balance\n poolId {\n id\n }\n }\n}\n `;\nexport const PoolShareDocument = gql`\n query PoolShare($id: ID!, $block: Block_height) {\n poolShare(id: $id, block: $block) {\n ...SubgraphPoolShare\n }\n}\n ${SubgraphPoolShareFragmentDoc}`;\nexport const PoolSharesDocument = gql`\n query PoolShares($first: Int, $orderBy: PoolShare_orderBy, $orderDirection: OrderDirection, $skip: Int, $where: PoolShare_filter, $block: Block_height) {\n poolShares(\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n skip: $skip\n where: $where\n block: $block\n ) {\n ...SubgraphPoolShare\n }\n}\n ${SubgraphPoolShareFragmentDoc}`;\nexport const PoolsDocument = gql`\n query Pools($skip: Int, $first: Int, $orderBy: Pool_orderBy, $orderDirection: OrderDirection, $where: Pool_filter, $block: Block_height) {\n pools(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphPool\n }\n}\n ${SubgraphPoolFragmentDoc}`;\nexport const AllPoolsDocument = gql`\n query AllPools($skip: Int, $first: Int, $orderBy: Pool_orderBy, $orderDirection: OrderDirection, $where: Pool_filter, $block: Block_height) {\n pool0: pools(\n first: 1000\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphPool\n }\n pool1000: pools(\n first: 1000\n skip: 1000\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphPool\n }\n pool2000: pools(\n first: 1000\n skip: 2000\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphPool\n }\n}\n ${SubgraphPoolFragmentDoc}`;\nexport const PoolDocument = gql`\n query Pool($id: ID!, $block: Block_height) {\n pool(id: $id, block: $block) {\n ...SubgraphPool\n }\n}\n ${SubgraphPoolFragmentDoc}`;\nexport const PoolHistoricalLiquiditiesDocument = gql`\n query PoolHistoricalLiquidities($skip: Int, $first: Int, $orderBy: PoolHistoricalLiquidity_orderBy, $orderDirection: OrderDirection, $where: PoolHistoricalLiquidity_filter, $block: Block_height) {\n poolHistoricalLiquidities(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n id\n poolId {\n id\n }\n poolTotalShares\n poolLiquidity\n poolShareValue\n pricingAsset\n block\n }\n}\n `;\nexport const PoolSnapshotsDocument = gql`\n query PoolSnapshots($skip: Int, $first: Int, $orderBy: PoolSnapshot_orderBy, $orderDirection: OrderDirection, $where: PoolSnapshot_filter, $block: Block_height) {\n poolSnapshots(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphPoolSnapshot\n }\n}\n ${SubgraphPoolSnapshotFragmentDoc}`;\nexport const JoinExitsDocument = gql`\n query JoinExits($skip: Int, $first: Int, $orderBy: JoinExit_orderBy, $orderDirection: OrderDirection, $where: JoinExit_filter, $block: Block_height) {\n joinExits(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphJoinExit\n }\n}\n ${SubgraphJoinExitFragmentDoc}`;\nexport const BalancersDocument = gql`\n query Balancers($skip: Int, $first: Int, $orderBy: Balancer_orderBy, $orderDirection: OrderDirection, $where: Balancer_filter, $block: Block_height) {\n balancers(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphBalancer\n }\n}\n ${SubgraphBalancerFragmentDoc}`;\nexport const TokenPricesDocument = gql`\n query TokenPrices($skip: Int, $first: Int, $orderBy: TokenPrice_orderBy, $orderDirection: OrderDirection, $where: TokenPrice_filter, $block: Block_height) {\n tokenPrices(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphTokenPrice\n }\n}\n ${SubgraphTokenPriceFragmentDoc}`;\nexport const TokenLatestPricesDocument = gql`\n query TokenLatestPrices($skip: Int, $first: Int, $orderBy: LatestPrice_orderBy, $orderDirection: OrderDirection, $where: LatestPrice_filter, $block: Block_height) {\n latestPrices(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphTokenLatestPrice\n }\n}\n ${SubgraphTokenLatestPriceFragmentDoc}`;\nexport const TokenLatestPriceDocument = gql`\n query TokenLatestPrice($id: ID!) {\n latestPrice(id: $id) {\n ...SubgraphTokenLatestPrice\n }\n}\n ${SubgraphTokenLatestPriceFragmentDoc}`;\nexport const UserDocument = gql`\n query User($id: ID!, $block: Block_height) {\n user(id: $id, block: $block) {\n ...SubgraphUser\n }\n}\n ${SubgraphUserFragmentDoc}`;\nexport const UsersDocument = gql`\n query Users($skip: Int, $first: Int, $orderBy: User_orderBy, $orderDirection: OrderDirection, $where: User_filter, $block: Block_height) {\n users(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphUser\n }\n}\n ${SubgraphUserFragmentDoc}`;\n\nexport type SdkFunctionWrapper = <T>(action: (requestHeaders?:Record<string, string>) => Promise<T>, operationName: string, operationType?: string) => Promise<T>;\n\n\nconst defaultWrapper: SdkFunctionWrapper = (action, _operationName, _operationType) => action();\n\nexport function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {\n return {\n PoolShare(variables: PoolShareQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<PoolShareQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<PoolShareQuery>(PoolShareDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'PoolShare', 'query');\n },\n PoolShares(variables?: PoolSharesQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<PoolSharesQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<PoolSharesQuery>(PoolSharesDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'PoolShares', 'query');\n },\n Pools(variables?: PoolsQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<PoolsQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<PoolsQuery>(PoolsDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'Pools', 'query');\n },\n AllPools(variables?: AllPoolsQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<AllPoolsQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<AllPoolsQuery>(AllPoolsDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'AllPools', 'query');\n },\n Pool(variables: PoolQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<PoolQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<PoolQuery>(PoolDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'Pool', 'query');\n },\n PoolHistoricalLiquidities(variables?: PoolHistoricalLiquiditiesQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<PoolHistoricalLiquiditiesQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<PoolHistoricalLiquiditiesQuery>(PoolHistoricalLiquiditiesDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'PoolHistoricalLiquidities', 'query');\n },\n PoolSnapshots(variables?: PoolSnapshotsQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<PoolSnapshotsQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<PoolSnapshotsQuery>(PoolSnapshotsDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'PoolSnapshots', 'query');\n },\n JoinExits(variables?: JoinExitsQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<JoinExitsQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<JoinExitsQuery>(JoinExitsDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'JoinExits', 'query');\n },\n Balancers(variables?: BalancersQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<BalancersQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<BalancersQuery>(BalancersDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'Balancers', 'query');\n },\n TokenPrices(variables?: TokenPricesQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<TokenPricesQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<TokenPricesQuery>(TokenPricesDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'TokenPrices', 'query');\n },\n TokenLatestPrices(variables?: TokenLatestPricesQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<TokenLatestPricesQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<TokenLatestPricesQuery>(TokenLatestPricesDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'TokenLatestPrices', 'query');\n },\n TokenLatestPrice(variables: TokenLatestPriceQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<TokenLatestPriceQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<TokenLatestPriceQuery>(TokenLatestPriceDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'TokenLatestPrice', 'query');\n },\n User(variables: UserQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<UserQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<UserQuery>(UserDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'User', 'query');\n },\n Users(variables?: UsersQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<UsersQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<UsersQuery>(UsersDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'Users', 'query');\n }\n };\n}\nexport type Sdk = ReturnType<typeof getSdk>;","import { GraphQLClient } from 'graphql-request';\nimport * as Dom from 'graphql-request/dist/types.dom';\nimport gql from 'graphql-tag';\nexport type Maybe<T> = T | null;\nexport type InputMaybe<T> = Maybe<T>;\nexport type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };\nexport type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };\nexport type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };\n/** All built-in and custom scalars, mapped to their actual values */\nexport type Scalars = {\n ID: string;\n String: string;\n Boolean: boolean;\n Int: number;\n Float: number;\n BigDecimal: string;\n BigInt: string;\n Bytes: string;\n};\n\nexport type BlockChangedFilter = {\n number_gte: Scalars['Int'];\n};\n\nexport type Block_Height = {\n hash?: InputMaybe<Scalars['Bytes']>;\n number?: InputMaybe<Scalars['Int']>;\n number_gte?: InputMaybe<Scalars['Int']>;\n};\n\nexport enum Chain {\n Arbitrum = 'Arbitrum',\n Optimism = 'Optimism',\n Polygon = 'Polygon',\n Defiverse = 'Defiverse'\n}\n\nexport type Gauge = {\n __typename?: 'Gauge';\n /** Timestamp at which Balancer DAO added the gauge to GaugeController [seconds] */\n addedTimestamp: Scalars['Int'];\n /** Address of the gauge */\n address: Scalars['Bytes'];\n /** Equal to: <gaugeAddress>-<typeID> */\n id: Scalars['ID'];\n /** Reference to LiquidityGauge */\n liquidityGauge?: Maybe<LiquidityGauge>;\n /** Reference to RootGauge */\n rootGauge?: Maybe<RootGauge>;\n /** Type of the gauge */\n type: GaugeType;\n};\n\nexport type GaugeFactory = {\n __typename?: 'GaugeFactory';\n /** List of gauges created through the factory */\n gauges?: Maybe<Array<LiquidityGauge>>;\n /** Factory contract address */\n id: Scalars['ID'];\n /** Number of gauges created through the factory */\n numGauges: Scalars['Int'];\n};\n\n\nexport type GaugeFactoryGaugesArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<LiquidityGauge_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<LiquidityGauge_Filter>;\n};\n\nexport type GaugeFactory_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n gauges_?: InputMaybe<LiquidityGauge_Filter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n numGauges?: InputMaybe<Scalars['Int']>;\n numGauges_gt?: InputMaybe<Scalars['Int']>;\n numGauges_gte?: InputMaybe<Scalars['Int']>;\n numGauges_in?: InputMaybe<Array<Scalars['Int']>>;\n numGauges_lt?: InputMaybe<Scalars['Int']>;\n numGauges_lte?: InputMaybe<Scalars['Int']>;\n numGauges_not?: InputMaybe<Scalars['Int']>;\n numGauges_not_in?: InputMaybe<Array<Scalars['Int']>>;\n};\n\nexport enum GaugeFactory_OrderBy {\n Gauges = 'gauges',\n Id = 'id',\n NumGauges = 'numGauges'\n}\n\nexport type GaugeShare = {\n __typename?: 'GaugeShare';\n /** User's balance of gauge deposit tokens */\n balance: Scalars['BigDecimal'];\n /** Reference to LiquidityGauge entity */\n gauge: LiquidityGauge;\n /** Equal to: <userAddress>-<gaugeAddress> */\n id: Scalars['ID'];\n /** Reference to User entity */\n user: User;\n};\n\nexport type GaugeShare_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n balance?: InputMaybe<Scalars['BigDecimal']>;\n balance_gt?: InputMaybe<Scalars['BigDecimal']>;\n balance_gte?: InputMaybe<Scalars['BigDecimal']>;\n balance_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n balance_lt?: InputMaybe<Scalars['BigDecimal']>;\n balance_lte?: InputMaybe<Scalars['BigDecimal']>;\n balance_not?: InputMaybe<Scalars['BigDecimal']>;\n balance_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n gauge?: InputMaybe<Scalars['String']>;\n gauge_?: InputMaybe<LiquidityGauge_Filter>;\n gauge_contains?: InputMaybe<Scalars['String']>;\n gauge_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_ends_with?: InputMaybe<Scalars['String']>;\n gauge_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_gt?: InputMaybe<Scalars['String']>;\n gauge_gte?: InputMaybe<Scalars['String']>;\n gauge_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_lt?: InputMaybe<Scalars['String']>;\n gauge_lte?: InputMaybe<Scalars['String']>;\n gauge_not?: InputMaybe<Scalars['String']>;\n gauge_not_contains?: InputMaybe<Scalars['String']>;\n gauge_not_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_not_starts_with?: InputMaybe<Scalars['String']>;\n gauge_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_starts_with?: InputMaybe<Scalars['String']>;\n gauge_starts_with_nocase?: InputMaybe<Scalars['String']>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n user?: InputMaybe<Scalars['String']>;\n user_?: InputMaybe<User_Filter>;\n user_contains?: InputMaybe<Scalars['String']>;\n user_contains_nocase?: InputMaybe<Scalars['String']>;\n user_ends_with?: InputMaybe<Scalars['String']>;\n user_ends_with_nocase?: InputMaybe<Scalars['String']>;\n user_gt?: InputMaybe<Scalars['String']>;\n user_gte?: InputMaybe<Scalars['String']>;\n user_in?: InputMaybe<Array<Scalars['String']>>;\n user_lt?: InputMaybe<Scalars['String']>;\n user_lte?: InputMaybe<Scalars['String']>;\n user_not?: InputMaybe<Scalars['String']>;\n user_not_contains?: InputMaybe<Scalars['String']>;\n user_not_contains_nocase?: InputMaybe<Scalars['String']>;\n user_not_ends_with?: InputMaybe<Scalars['String']>;\n user_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n user_not_in?: InputMaybe<Array<Scalars['String']>>;\n user_not_starts_with?: InputMaybe<Scalars['String']>;\n user_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n user_starts_with?: InputMaybe<Scalars['String']>;\n user_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum GaugeShare_OrderBy {\n Balance = 'balance',\n Gauge = 'gauge',\n Id = 'id',\n User = 'user'\n}\n\nexport type GaugeType = {\n __typename?: 'GaugeType';\n /** Type ID */\n id: Scalars['ID'];\n /** Name of the type - empty string if call reverts */\n name: Scalars['String'];\n};\n\nexport type GaugeType_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n name?: InputMaybe<Scalars['String']>;\n name_contains?: InputMaybe<Scalars['String']>;\n name_contains_nocase?: InputMaybe<Scalars['String']>;\n name_ends_with?: InputMaybe<Scalars['String']>;\n name_ends_with_nocase?: InputMaybe<Scalars['String']>;\n name_gt?: InputMaybe<Scalars['String']>;\n name_gte?: InputMaybe<Scalars['String']>;\n name_in?: InputMaybe<Array<Scalars['String']>>;\n name_lt?: InputMaybe<Scalars['String']>;\n name_lte?: InputMaybe<Scalars['String']>;\n name_not?: InputMaybe<Scalars['String']>;\n name_not_contains?: InputMaybe<Scalars['String']>;\n name_not_contains_nocase?: InputMaybe<Scalars['String']>;\n name_not_ends_with?: InputMaybe<Scalars['String']>;\n name_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n name_not_in?: InputMaybe<Array<Scalars['String']>>;\n name_not_starts_with?: InputMaybe<Scalars['String']>;\n name_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n name_starts_with?: InputMaybe<Scalars['String']>;\n name_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum GaugeType_OrderBy {\n Id = 'id',\n Name = 'name'\n}\n\nexport type GaugeVote = {\n __typename?: 'GaugeVote';\n /** Reference to Gauge entity */\n gauge: Gauge;\n /** Equal to: <userAddress>-<gaugeAddress> */\n id: Scalars['ID'];\n /** Timestamp at which user voted [seconds] */\n timestamp?: Maybe<Scalars['BigInt']>;\n /** Reference to User entity */\n user: User;\n /** Weight of veBAL power user has used to vote */\n weight?: Maybe<Scalars['BigDecimal']>;\n};\n\nexport type GaugeVote_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n gauge?: InputMaybe<Scalars['String']>;\n gauge_?: InputMaybe<Gauge_Filter>;\n gauge_contains?: InputMaybe<Scalars['String']>;\n gauge_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_ends_with?: InputMaybe<Scalars['String']>;\n gauge_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_gt?: InputMaybe<Scalars['String']>;\n gauge_gte?: InputMaybe<Scalars['String']>;\n gauge_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_lt?: InputMaybe<Scalars['String']>;\n gauge_lte?: InputMaybe<Scalars['String']>;\n gauge_not?: InputMaybe<Scalars['String']>;\n gauge_not_contains?: InputMaybe<Scalars['String']>;\n gauge_not_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_not_starts_with?: InputMaybe<Scalars['String']>;\n gauge_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_starts_with?: InputMaybe<Scalars['String']>;\n gauge_starts_with_nocase?: InputMaybe<Scalars['String']>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n timestamp?: InputMaybe<Scalars['BigInt']>;\n timestamp_gt?: InputMaybe<Scalars['BigInt']>;\n timestamp_gte?: InputMaybe<Scalars['BigInt']>;\n timestamp_in?: InputMaybe<Array<Scalars['BigInt']>>;\n timestamp_lt?: InputMaybe<Scalars['BigInt']>;\n timestamp_lte?: InputMaybe<Scalars['BigInt']>;\n timestamp_not?: InputMaybe<Scalars['BigInt']>;\n timestamp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n user?: InputMaybe<Scalars['String']>;\n user_?: InputMaybe<User_Filter>;\n user_contains?: InputMaybe<Scalars['String']>;\n user_contains_nocase?: InputMaybe<Scalars['String']>;\n user_ends_with?: InputMaybe<Scalars['String']>;\n user_ends_with_nocase?: InputMaybe<Scalars['String']>;\n user_gt?: InputMaybe<Scalars['String']>;\n user_gte?: InputMaybe<Scalars['String']>;\n user_in?: InputMaybe<Array<Scalars['String']>>;\n user_lt?: InputMaybe<Scalars['String']>;\n user_lte?: InputMaybe<Scalars['String']>;\n user_not?: InputMaybe<Scalars['String']>;\n user_not_contains?: InputMaybe<Scalars['String']>;\n user_not_contains_nocase?: InputMaybe<Scalars['String']>;\n user_not_ends_with?: InputMaybe<Scalars['String']>;\n user_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n user_not_in?: InputMaybe<Array<Scalars['String']>>;\n user_not_starts_with?: InputMaybe<Scalars['String']>;\n user_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n user_starts_with?: InputMaybe<Scalars['String']>;\n user_starts_with_nocase?: InputMaybe<Scalars['String']>;\n weight?: InputMaybe<Scalars['BigDecimal']>;\n weight_gt?: InputMaybe<Scalars['BigDecimal']>;\n weight_gte?: InputMaybe<Scalars['BigDecimal']>;\n weight_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n weight_lt?: InputMaybe<Scalars['BigDecimal']>;\n weight_lte?: InputMaybe<Scalars['BigDecimal']>;\n weight_not?: InputMaybe<Scalars['BigDecimal']>;\n weight_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum GaugeVote_OrderBy {\n Gauge = 'gauge',\n Id = 'id',\n Timestamp = 'timestamp',\n User = 'user',\n Weight = 'weight'\n}\n\nexport type Gauge_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n addedTimestamp?: InputMaybe<Scalars['Int']>;\n addedTimestamp_gt?: InputMaybe<Scalars['Int']>;\n addedTimestamp_gte?: InputMaybe<Scalars['Int']>;\n addedTimestamp_in?: InputMaybe<Array<Scalars['Int']>>;\n addedTimestamp_lt?: InputMaybe<Scalars['Int']>;\n addedTimestamp_lte?: InputMaybe<Scalars['Int']>;\n addedTimestamp_not?: InputMaybe<Scalars['Int']>;\n addedTimestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;\n address?: InputMaybe<Scalars['Bytes']>;\n address_contains?: InputMaybe<Scalars['Bytes']>;\n address_gt?: InputMaybe<Scalars['Bytes']>;\n address_gte?: InputMaybe<Scalars['Bytes']>;\n address_in?: InputMaybe<Array<Scalars['Bytes']>>;\n address_lt?: InputMaybe<Scalars['Bytes']>;\n address_lte?: InputMaybe<Scalars['Bytes']>;\n address_not?: InputMaybe<Scalars['Bytes']>;\n address_not_contains?: InputMaybe<Scalars['Bytes']>;\n address_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n liquidityGauge?: InputMaybe<Scalars['String']>;\n liquidityGauge_?: InputMaybe<LiquidityGauge_Filter>;\n liquidityGauge_contains?: InputMaybe<Scalars['String']>;\n liquidityGauge_contains_nocase?: InputMaybe<Scalars['String']>;\n liquidityGauge_ends_with?: InputMaybe<Scalars['String']>;\n liquidityGauge_ends_with_nocase?: InputMaybe<Scalars['String']>;\n liquidityGauge_gt?: InputMaybe<Scalars['String']>;\n liquidityGauge_gte?: InputMaybe<Scalars['String']>;\n liquidityGauge_in?: InputMaybe<Array<Scalars['String']>>;\n liquidityGauge_lt?: InputMaybe<Scalars['String']>;\n liquidityGauge_lte?: InputMaybe<Scalars['String']>;\n liquidityGauge_not?: InputMaybe<Scalars['String']>;\n liquidityGauge_not_contains?: InputMaybe<Scalars['String']>;\n liquidityGauge_not_contains_nocase?: InputMaybe<Scalars['String']>;\n liquidityGauge_not_ends_with?: InputMaybe<Scalars['String']>;\n liquidityGauge_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n liquidityGauge_not_in?: InputMaybe<Array<Scalars['String']>>;\n liquidityGauge_not_starts_with?: InputMaybe<Scalars['String']>;\n liquidityGauge_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n liquidityGauge_starts_with?: InputMaybe<Scalars['String']>;\n liquidityGauge_starts_with_nocase?: InputMaybe<Scalars['String']>;\n rootGauge?: InputMaybe<Scalars['String']>;\n rootGauge_?: InputMaybe<RootGauge_Filter>;\n rootGauge_contains?: InputMaybe<Scalars['String']>;\n rootGauge_contains_nocase?: InputMaybe<Scalars['String']>;\n rootGauge_ends_with?: InputMaybe<Scalars['String']>;\n rootGauge_ends_with_nocase?: InputMaybe<Scalars['String']>;\n rootGauge_gt?: InputMaybe<Scalars['String']>;\n rootGauge_gte?: InputMaybe<Scalars['String']>;\n rootGauge_in?: InputMaybe<Array<Scalars['String']>>;\n rootGauge_lt?: InputMaybe<Scalars['String']>;\n rootGauge_lte?: InputMaybe<Scalars['String']>;\n rootGauge_not?: InputMaybe<Scalars['String']>;\n rootGauge_not_contains?: InputMaybe<Scalars['String']>;\n rootGauge_not_contains_nocase?: InputMaybe<Scalars['String']>;\n rootGauge_not_ends_with?: InputMaybe<Scalars['String']>;\n rootGauge_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n rootGauge_not_in?: InputMaybe<Array<Scalars['String']>>;\n rootGauge_not_starts_with?: InputMaybe<Scalars['String']>;\n rootGauge_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n rootGauge_starts_with?: InputMaybe<Scalars['String']>;\n rootGauge_starts_with_nocase?: InputMaybe<Scalars['String']>;\n type?: InputMaybe<Scalars['String']>;\n type_?: InputMaybe<GaugeType_Filter>;\n type_contains?: InputMaybe<Scalars['String']>;\n type_contains_nocase?: InputMaybe<Scalars['String']>;\n type_ends_with?: InputMaybe<Scalars['String']>;\n type_ends_with_nocase?: InputMaybe<Scalars['String']>;\n type_gt?: InputMaybe<Scalars['String']>;\n type_gte?: InputMaybe<Scalars['String']>;\n type_in?: InputMaybe<Array<Scalars['String']>>;\n type_lt?: InputMaybe<Scalars['String']>;\n type_lte?: InputMaybe<Scalars['String']>;\n type_not?: InputMaybe<Scalars['String']>;\n type_not_contains?: InputMaybe<Scalars['String']>;\n type_not_contains_nocase?: InputMaybe<Scalars['String']>;\n type_not_ends_with?: InputMaybe<Scalars['String']>;\n type_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n type_not_in?: InputMaybe<Array<Scalars['String']>>;\n type_not_starts_with?: InputMaybe<Scalars['String']>;\n type_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n type_starts_with?: InputMaybe<Scalars['String']>;\n type_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum Gauge_OrderBy {\n AddedTimestamp = 'addedTimestamp',\n Address = 'address',\n Id = 'id',\n LiquidityGauge = 'liquidityGauge',\n RootGauge = 'rootGauge',\n Type = 'type'\n}\n\nexport type LiquidityGauge = {\n __typename?: 'LiquidityGauge';\n /** Factory contract address */\n factory: GaugeFactory;\n /** Reference to Gauge entity - created when LiquidityGauge is added to GaugeController */\n gauge?: Maybe<Gauge>;\n /** LiquidityGauge contract address */\n id: Scalars['ID'];\n /** Whether Balancer DAO killed the gauge */\n isKilled: Scalars['Boolean'];\n /** Whether the LiquidityGauge is the most recent added to GaugeController */\n isPreferentialGauge: Scalars['Boolean'];\n /** Reference to Pool entity */\n pool?: Maybe<Pool>;\n /** Address of the pool (lp_token of the gauge) */\n poolAddress: Scalars['Bytes'];\n /** Pool ID if lp_token is a Balancer pool; null otherwise */\n poolId?: Maybe<Scalars['Bytes']>;\n /** Relative weight cap of the gauge (0.01 = 1%) - V2 factories only */\n relativeWeightCap?: Maybe<Scalars['BigDecimal']>;\n /** List of user shares */\n shares?: Maybe<Array<GaugeShare>>;\n /** Address of the contract that streams reward tokens to the gauge - ChildChainLiquidityGauge only */\n streamer?: Maybe<Scalars['Bytes']>;\n /** ERC20 token symbol */\n symbol: Scalars['String'];\n /** List of reward tokens depositted in the gauge */\n tokens?: Maybe<Array<RewardToken>>;\n /** Total of BPTs users have staked in the LiquidityGauge */\n totalSupply: Scalars['BigDecimal'];\n};\n\n\nexport type LiquidityGaugeSharesArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<GaugeShare_Filter>;\n};\n\n\nexport type LiquidityGaugeTokensArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<RewardToken_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<RewardToken_Filter>;\n};\n\nexport type LiquidityGauge_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n factory?: InputMaybe<Scalars['String']>;\n factory_?: InputMaybe<GaugeFactory_Filter>;\n factory_contains?: InputMaybe<Scalars['String']>;\n factory_contains_nocase?: InputMaybe<Scalars['String']>;\n factory_ends_with?: InputMaybe<Scalars['String']>;\n factory_ends_with_nocase?: InputMaybe<Scalars['String']>;\n factory_gt?: InputMaybe<Scalars['String']>;\n factory_gte?: InputMaybe<Scalars['String']>;\n factory_in?: InputMaybe<Array<Scalars['String']>>;\n factory_lt?: InputMaybe<Scalars['String']>;\n factory_lte?: InputMaybe<Scalars['String']>;\n factory_not?: InputMaybe<Scalars['String']>;\n factory_not_contains?: InputMaybe<Scalars['String']>;\n factory_not_contains_nocase?: InputMaybe<Scalars['String']>;\n factory_not_ends_with?: InputMaybe<Scalars['String']>;\n factory_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n factory_not_in?: InputMaybe<Array<Scalars['String']>>;\n factory_not_starts_with?: InputMaybe<Scalars['String']>;\n factory_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n factory_starts_with?: InputMaybe<Scalars['String']>;\n factory_starts_with_nocase?: InputMaybe<Scalars['String']>;\n gauge?: InputMaybe<Scalars['String']>;\n gauge_?: InputMaybe<Gauge_Filter>;\n gauge_contains?: InputMaybe<Scalars['String']>;\n gauge_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_ends_with?: InputMaybe<Scalars['String']>;\n gauge_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_gt?: InputMaybe<Scalars['String']>;\n gauge_gte?: InputMaybe<Scalars['String']>;\n gauge_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_lt?: InputMaybe<Scalars['String']>;\n gauge_lte?: InputMaybe<Scalars['String']>;\n gauge_not?: InputMaybe<Scalars['String']>;\n gauge_not_contains?: InputMaybe<Scalars['String']>;\n gauge_not_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_not_starts_with?: InputMaybe<Scalars['String']>;\n gauge_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_starts_with?: InputMaybe<Scalars['String']>;\n gauge_starts_with_nocase?: InputMaybe<Scalars['String']>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n isKilled?: InputMaybe<Scalars['Boolean']>;\n isKilled_in?: InputMaybe<Array<Scalars['Boolean']>>;\n isKilled_not?: InputMaybe<Scalars['Boolean']>;\n isKilled_not_in?: InputMaybe<Array<Scalars['Boolean']>>;\n isPreferentialGauge?: InputMaybe<Scalars['Boolean']>;\n isPreferentialGauge_in?: InputMaybe<Array<Scalars['Boolean']>>;\n isPreferentialGauge_not?: InputMaybe<Scalars['Boolean']>;\n isPreferentialGauge_not_in?: InputMaybe<Array<Scalars['Boolean']>>;\n pool?: InputMaybe<Scalars['String']>;\n poolAddress?: InputMaybe<Scalars['Bytes']>;\n poolAddress_contains?: InputMaybe<Scalars['Bytes']>;\n poolAddress_gt?: InputMaybe<Scalars['Bytes']>;\n poolAddress_gte?: InputMaybe<Scalars['Bytes']>;\n poolAddress_in?: InputMaybe<Array<Scalars['Bytes']>>;\n poolAddress_lt?: InputMaybe<Scalars['Bytes']>;\n poolAddress_lte?: InputMaybe<Scalars['Bytes']>;\n poolAddress_not?: InputMaybe<Scalars['Bytes']>;\n poolAddress_not_contains?: InputMaybe<Scalars['Bytes']>;\n poolAddress_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n poolId?: InputMaybe<Scalars['Bytes']>;\n poolId_contains?: InputMaybe<Scalars['Bytes']>;\n poolId_gt?: InputMaybe<Scalars['Bytes']>;\n poolId_gte?: InputMaybe<Scalars['Bytes']>;\n poolId_in?: InputMaybe<Array<Scalars['Bytes']>>;\n poolId_lt?: InputMaybe<Scalars['Bytes']>;\n poolId_lte?: InputMaybe<Scalars['Bytes']>;\n poolId_not?: InputMaybe<Scalars['Bytes']>;\n poolId_not_contains?: InputMaybe<Scalars['Bytes']>;\n poolId_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n pool_?: InputMaybe<Pool_Filter>;\n pool_contains?: InputMaybe<Scalars['String']>;\n pool_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_ends_with?: InputMaybe<Scalars['String']>;\n pool_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_gt?: InputMaybe<Scalars['String']>;\n pool_gte?: InputMaybe<Scalars['String']>;\n pool_in?: InputMaybe<Array<Scalars['String']>>;\n pool_lt?: InputMaybe<Scalars['String']>;\n pool_lte?: InputMaybe<Scalars['String']>;\n pool_not?: InputMaybe<Scalars['String']>;\n pool_not_contains?: InputMaybe<Scalars['String']>;\n pool_not_contains_nocase?: InputMaybe<Scalars['String']>;\n pool_not_ends_with?: InputMaybe<Scalars['String']>;\n pool_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n pool_not_in?: InputMaybe<Array<Scalars['String']>>;\n pool_not_starts_with?: InputMaybe<Scalars['String']>;\n pool_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n pool_starts_with?: InputMaybe<Scalars['String']>;\n pool_starts_with_nocase?: InputMaybe<Scalars['String']>;\n relativeWeightCap?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_gt?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_gte?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n relativeWeightCap_lt?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_lte?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_not?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n shares_?: InputMaybe<GaugeShare_Filter>;\n streamer?: InputMaybe<Scalars['Bytes']>;\n streamer_contains?: InputMaybe<Scalars['Bytes']>;\n streamer_gt?: InputMaybe<Scalars['Bytes']>;\n streamer_gte?: InputMaybe<Scalars['Bytes']>;\n streamer_in?: InputMaybe<Array<Scalars['Bytes']>>;\n streamer_lt?: InputMaybe<Scalars['Bytes']>;\n streamer_lte?: InputMaybe<Scalars['Bytes']>;\n streamer_not?: InputMaybe<Scalars['Bytes']>;\n streamer_not_contains?: InputMaybe<Scalars['Bytes']>;\n streamer_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n symbol?: InputMaybe<Scalars['String']>;\n symbol_contains?: InputMaybe<Scalars['String']>;\n symbol_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_ends_with?: InputMaybe<Scalars['String']>;\n symbol_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_gt?: InputMaybe<Scalars['String']>;\n symbol_gte?: InputMaybe<Scalars['String']>;\n symbol_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_lt?: InputMaybe<Scalars['String']>;\n symbol_lte?: InputMaybe<Scalars['String']>;\n symbol_not?: InputMaybe<Scalars['String']>;\n symbol_not_contains?: InputMaybe<Scalars['String']>;\n symbol_not_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_not_starts_with?: InputMaybe<Scalars['String']>;\n symbol_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_starts_with?: InputMaybe<Scalars['String']>;\n symbol_starts_with_nocase?: InputMaybe<Scalars['String']>;\n tokens_?: InputMaybe<RewardToken_Filter>;\n totalSupply?: InputMaybe<Scalars['BigDecimal']>;\n totalSupply_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalSupply_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalSupply_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalSupply_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalSupply_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalSupply_not?: InputMaybe<Scalars['BigDecimal']>;\n totalSupply_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum LiquidityGauge_OrderBy {\n Factory = 'factory',\n Gauge = 'gauge',\n Id = 'id',\n IsKilled = 'isKilled',\n IsPreferentialGauge = 'isPreferentialGauge',\n Pool = 'pool',\n PoolAddress = 'poolAddress',\n PoolId = 'poolId',\n RelativeWeightCap = 'relativeWeightCap',\n Shares = 'shares',\n Streamer = 'streamer',\n Symbol = 'symbol',\n Tokens = 'tokens',\n TotalSupply = 'totalSupply'\n}\n\n/** Defines the order direction, either ascending or descending */\nexport enum OrderDirection {\n Asc = 'asc',\n Desc = 'desc'\n}\n\nexport type Pool = {\n __typename?: 'Pool';\n /** Address of the pool (lp_token of the gauge) */\n address: Scalars['Bytes'];\n /** List of gauges created for the pool */\n gauges?: Maybe<Array<LiquidityGauge>>;\n /** List of the pool's gauges addresses */\n gaugesList: Array<Scalars['Bytes']>;\n /** Address of the pool (lp_token of the gauge) */\n id: Scalars['ID'];\n /** Pool ID if lp_token is a Balancer pool; null otherwise */\n poolId?: Maybe<Scalars['Bytes']>;\n /** Most recent, unkilled gauge in the GaugeController */\n preferentialGauge?: Maybe<LiquidityGauge>;\n};\n\n\nexport type PoolGaugesArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<LiquidityGauge_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<LiquidityGauge_Filter>;\n};\n\nexport type Pool_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n address?: InputMaybe<Scalars['Bytes']>;\n address_contains?: InputMaybe<Scalars['Bytes']>;\n address_gt?: InputMaybe<Scalars['Bytes']>;\n address_gte?: InputMaybe<Scalars['Bytes']>;\n address_in?: InputMaybe<Array<Scalars['Bytes']>>;\n address_lt?: InputMaybe<Scalars['Bytes']>;\n address_lte?: InputMaybe<Scalars['Bytes']>;\n address_not?: InputMaybe<Scalars['Bytes']>;\n address_not_contains?: InputMaybe<Scalars['Bytes']>;\n address_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n gaugesList?: InputMaybe<Array<Scalars['Bytes']>>;\n gaugesList_contains?: InputMaybe<Array<Scalars['Bytes']>>;\n gaugesList_contains_nocase?: InputMaybe<Array<Scalars['Bytes']>>;\n gaugesList_not?: InputMaybe<Array<Scalars['Bytes']>>;\n gaugesList_not_contains?: InputMaybe<Array<Scalars['Bytes']>>;\n gaugesList_not_contains_nocase?: InputMaybe<Array<Scalars['Bytes']>>;\n gauges_?: InputMaybe<LiquidityGauge_Filter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n poolId?: InputMaybe<Scalars['Bytes']>;\n poolId_contains?: InputMaybe<Scalars['Bytes']>;\n poolId_gt?: InputMaybe<Scalars['Bytes']>;\n poolId_gte?: InputMaybe<Scalars['Bytes']>;\n poolId_in?: InputMaybe<Array<Scalars['Bytes']>>;\n poolId_lt?: InputMaybe<Scalars['Bytes']>;\n poolId_lte?: InputMaybe<Scalars['Bytes']>;\n poolId_not?: InputMaybe<Scalars['Bytes']>;\n poolId_not_contains?: InputMaybe<Scalars['Bytes']>;\n poolId_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n preferentialGauge?: InputMaybe<Scalars['String']>;\n preferentialGauge_?: InputMaybe<LiquidityGauge_Filter>;\n preferentialGauge_contains?: InputMaybe<Scalars['String']>;\n preferentialGauge_contains_nocase?: InputMaybe<Scalars['String']>;\n preferentialGauge_ends_with?: InputMaybe<Scalars['String']>;\n preferentialGauge_ends_with_nocase?: InputMaybe<Scalars['String']>;\n preferentialGauge_gt?: InputMaybe<Scalars['String']>;\n preferentialGauge_gte?: InputMaybe<Scalars['String']>;\n preferentialGauge_in?: InputMaybe<Array<Scalars['String']>>;\n preferentialGauge_lt?: InputMaybe<Scalars['String']>;\n preferentialGauge_lte?: InputMaybe<Scalars['String']>;\n preferentialGauge_not?: InputMaybe<Scalars['String']>;\n preferentialGauge_not_contains?: InputMaybe<Scalars['String']>;\n preferentialGauge_not_contains_nocase?: InputMaybe<Scalars['String']>;\n preferentialGauge_not_ends_with?: InputMaybe<Scalars['String']>;\n preferentialGauge_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n preferentialGauge_not_in?: InputMaybe<Array<Scalars['String']>>;\n preferentialGauge_not_starts_with?: InputMaybe<Scalars['String']>;\n preferentialGauge_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n preferentialGauge_starts_with?: InputMaybe<Scalars['String']>;\n preferentialGauge_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum Pool_OrderBy {\n Address = 'address',\n Gauges = 'gauges',\n GaugesList = 'gaugesList',\n Id = 'id',\n PoolId = 'poolId',\n PreferentialGauge = 'preferentialGauge'\n}\n\nexport type Query = {\n __typename?: 'Query';\n /** Access to subgraph metadata */\n _meta?: Maybe<_Meta_>;\n gauge?: Maybe<Gauge>;\n gaugeFactories: Array<GaugeFactory>;\n gaugeFactory?: Maybe<GaugeFactory>;\n gaugeShare?: Maybe<GaugeShare>;\n gaugeShares: Array<GaugeShare>;\n gaugeType?: Maybe<GaugeType>;\n gaugeTypes: Array<GaugeType>;\n gaugeVote?: Maybe<GaugeVote>;\n gaugeVotes: Array<GaugeVote>;\n gauges: Array<Gauge>;\n liquidityGauge?: Maybe<LiquidityGauge>;\n liquidityGauges: Array<LiquidityGauge>;\n pool?: Maybe<Pool>;\n pools: Array<Pool>;\n rewardToken?: Maybe<RewardToken>;\n rewardTokens: Array<RewardToken>;\n rootGauge?: Maybe<RootGauge>;\n rootGauges: Array<RootGauge>;\n user?: Maybe<User>;\n users: Array<User>;\n votingEscrow?: Maybe<VotingEscrow>;\n votingEscrowLock?: Maybe<VotingEscrowLock>;\n votingEscrowLocks: Array<VotingEscrowLock>;\n votingEscrows: Array<VotingEscrow>;\n};\n\n\nexport type Query_MetaArgs = {\n block?: InputMaybe<Block_Height>;\n};\n\n\nexport type QueryGaugeArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryGaugeFactoriesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeFactory_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GaugeFactory_Filter>;\n};\n\n\nexport type QueryGaugeFactoryArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryGaugeShareArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryGaugeSharesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GaugeShare_Filter>;\n};\n\n\nexport type QueryGaugeTypeArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryGaugeTypesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeType_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GaugeType_Filter>;\n};\n\n\nexport type QueryGaugeVoteArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryGaugeVotesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeVote_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GaugeVote_Filter>;\n};\n\n\nexport type QueryGaugesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Gauge_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Gauge_Filter>;\n};\n\n\nexport type QueryLiquidityGaugeArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryLiquidityGaugesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<LiquidityGauge_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<LiquidityGauge_Filter>;\n};\n\n\nexport type QueryPoolArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryPoolsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Pool_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Pool_Filter>;\n};\n\n\nexport type QueryRewardTokenArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryRewardTokensArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<RewardToken_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<RewardToken_Filter>;\n};\n\n\nexport type QueryRootGaugeArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryRootGaugesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<RootGauge_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<RootGauge_Filter>;\n};\n\n\nexport type QueryUserArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryUsersArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<User_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<User_Filter>;\n};\n\n\nexport type QueryVotingEscrowArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryVotingEscrowLockArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type QueryVotingEscrowLocksArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<VotingEscrowLock_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<VotingEscrowLock_Filter>;\n};\n\n\nexport type QueryVotingEscrowsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<VotingEscrow_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<VotingEscrow_Filter>;\n};\n\nexport type RewardToken = {\n __typename?: 'RewardToken';\n /** ERC20 token decimals - zero if call to decimals() reverts */\n decimals: Scalars['Int'];\n /** Reference to LiquidityGauge entity */\n gauge: LiquidityGauge;\n /** Equal to: <tokenAddress>-<gaugeAddress> */\n id: Scalars['ID'];\n /** Timestamp at which finishes the period of rewards */\n periodFinish?: Maybe<Scalars['BigInt']>;\n /** Rate of reward tokens streamed per second */\n rate?: Maybe<Scalars['BigDecimal']>;\n /** ERC20 token symbol - empty string if call to symbol() reverts */\n symbol: Scalars['String'];\n /** Amount of reward tokens that has been deposited into the gauge */\n totalDeposited: Scalars['BigDecimal'];\n};\n\nexport type RewardToken_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n decimals?: InputMaybe<Scalars['Int']>;\n decimals_gt?: InputMaybe<Scalars['Int']>;\n decimals_gte?: InputMaybe<Scalars['Int']>;\n decimals_in?: InputMaybe<Array<Scalars['Int']>>;\n decimals_lt?: InputMaybe<Scalars['Int']>;\n decimals_lte?: InputMaybe<Scalars['Int']>;\n decimals_not?: InputMaybe<Scalars['Int']>;\n decimals_not_in?: InputMaybe<Array<Scalars['Int']>>;\n gauge?: InputMaybe<Scalars['String']>;\n gauge_?: InputMaybe<LiquidityGauge_Filter>;\n gauge_contains?: InputMaybe<Scalars['String']>;\n gauge_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_ends_with?: InputMaybe<Scalars['String']>;\n gauge_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_gt?: InputMaybe<Scalars['String']>;\n gauge_gte?: InputMaybe<Scalars['String']>;\n gauge_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_lt?: InputMaybe<Scalars['String']>;\n gauge_lte?: InputMaybe<Scalars['String']>;\n gauge_not?: InputMaybe<Scalars['String']>;\n gauge_not_contains?: InputMaybe<Scalars['String']>;\n gauge_not_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_not_starts_with?: InputMaybe<Scalars['String']>;\n gauge_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_starts_with?: InputMaybe<Scalars['String']>;\n gauge_starts_with_nocase?: InputMaybe<Scalars['String']>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n periodFinish?: InputMaybe<Scalars['BigInt']>;\n periodFinish_gt?: InputMaybe<Scalars['BigInt']>;\n periodFinish_gte?: InputMaybe<Scalars['BigInt']>;\n periodFinish_in?: InputMaybe<Array<Scalars['BigInt']>>;\n periodFinish_lt?: InputMaybe<Scalars['BigInt']>;\n periodFinish_lte?: InputMaybe<Scalars['BigInt']>;\n periodFinish_not?: InputMaybe<Scalars['BigInt']>;\n periodFinish_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n rate?: InputMaybe<Scalars['BigDecimal']>;\n rate_gt?: InputMaybe<Scalars['BigDecimal']>;\n rate_gte?: InputMaybe<Scalars['BigDecimal']>;\n rate_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n rate_lt?: InputMaybe<Scalars['BigDecimal']>;\n rate_lte?: InputMaybe<Scalars['BigDecimal']>;\n rate_not?: InputMaybe<Scalars['BigDecimal']>;\n rate_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n symbol?: InputMaybe<Scalars['String']>;\n symbol_contains?: InputMaybe<Scalars['String']>;\n symbol_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_ends_with?: InputMaybe<Scalars['String']>;\n symbol_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_gt?: InputMaybe<Scalars['String']>;\n symbol_gte?: InputMaybe<Scalars['String']>;\n symbol_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_lt?: InputMaybe<Scalars['String']>;\n symbol_lte?: InputMaybe<Scalars['String']>;\n symbol_not?: InputMaybe<Scalars['String']>;\n symbol_not_contains?: InputMaybe<Scalars['String']>;\n symbol_not_contains_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with?: InputMaybe<Scalars['String']>;\n symbol_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_not_in?: InputMaybe<Array<Scalars['String']>>;\n symbol_not_starts_with?: InputMaybe<Scalars['String']>;\n symbol_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n symbol_starts_with?: InputMaybe<Scalars['String']>;\n symbol_starts_with_nocase?: InputMaybe<Scalars['String']>;\n totalDeposited?: InputMaybe<Scalars['BigDecimal']>;\n totalDeposited_gt?: InputMaybe<Scalars['BigDecimal']>;\n totalDeposited_gte?: InputMaybe<Scalars['BigDecimal']>;\n totalDeposited_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n totalDeposited_lt?: InputMaybe<Scalars['BigDecimal']>;\n totalDeposited_lte?: InputMaybe<Scalars['BigDecimal']>;\n totalDeposited_not?: InputMaybe<Scalars['BigDecimal']>;\n totalDeposited_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum RewardToken_OrderBy {\n Decimals = 'decimals',\n Gauge = 'gauge',\n Id = 'id',\n PeriodFinish = 'periodFinish',\n Rate = 'rate',\n Symbol = 'symbol',\n TotalDeposited = 'totalDeposited'\n}\n\nexport type RootGauge = {\n __typename?: 'RootGauge';\n /** Chain where emissions by this gauge will be bridged to */\n chain: Chain;\n /** Factory contract address */\n factory: GaugeFactory;\n /** Reference to Gauge entity - created when LiquidityGauge is added to GaugeController */\n gauge?: Maybe<Gauge>;\n /** RootGauge contract address */\n id: Scalars['ID'];\n /** Whether Balancer DAO killed the gauge */\n isKilled: Scalars['Boolean'];\n /** Address where emissions by this gauge will be bridged to */\n recipient: Scalars['Bytes'];\n /** Relative weight cap of the gauge (0.01 = 1%) - V2 factories only */\n relativeWeightCap?: Maybe<Scalars['BigDecimal']>;\n};\n\nexport type RootGauge_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n chain?: InputMaybe<Chain>;\n chain_in?: InputMaybe<Array<Chain>>;\n chain_not?: InputMaybe<Chain>;\n chain_not_in?: InputMaybe<Array<Chain>>;\n factory?: InputMaybe<Scalars['String']>;\n factory_?: InputMaybe<GaugeFactory_Filter>;\n factory_contains?: InputMaybe<Scalars['String']>;\n factory_contains_nocase?: InputMaybe<Scalars['String']>;\n factory_ends_with?: InputMaybe<Scalars['String']>;\n factory_ends_with_nocase?: InputMaybe<Scalars['String']>;\n factory_gt?: InputMaybe<Scalars['String']>;\n factory_gte?: InputMaybe<Scalars['String']>;\n factory_in?: InputMaybe<Array<Scalars['String']>>;\n factory_lt?: InputMaybe<Scalars['String']>;\n factory_lte?: InputMaybe<Scalars['String']>;\n factory_not?: InputMaybe<Scalars['String']>;\n factory_not_contains?: InputMaybe<Scalars['String']>;\n factory_not_contains_nocase?: InputMaybe<Scalars['String']>;\n factory_not_ends_with?: InputMaybe<Scalars['String']>;\n factory_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n factory_not_in?: InputMaybe<Array<Scalars['String']>>;\n factory_not_starts_with?: InputMaybe<Scalars['String']>;\n factory_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n factory_starts_with?: InputMaybe<Scalars['String']>;\n factory_starts_with_nocase?: InputMaybe<Scalars['String']>;\n gauge?: InputMaybe<Scalars['String']>;\n gauge_?: InputMaybe<Gauge_Filter>;\n gauge_contains?: InputMaybe<Scalars['String']>;\n gauge_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_ends_with?: InputMaybe<Scalars['String']>;\n gauge_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_gt?: InputMaybe<Scalars['String']>;\n gauge_gte?: InputMaybe<Scalars['String']>;\n gauge_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_lt?: InputMaybe<Scalars['String']>;\n gauge_lte?: InputMaybe<Scalars['String']>;\n gauge_not?: InputMaybe<Scalars['String']>;\n gauge_not_contains?: InputMaybe<Scalars['String']>;\n gauge_not_contains_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with?: InputMaybe<Scalars['String']>;\n gauge_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_not_in?: InputMaybe<Array<Scalars['String']>>;\n gauge_not_starts_with?: InputMaybe<Scalars['String']>;\n gauge_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n gauge_starts_with?: InputMaybe<Scalars['String']>;\n gauge_starts_with_nocase?: InputMaybe<Scalars['String']>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n isKilled?: InputMaybe<Scalars['Boolean']>;\n isKilled_in?: InputMaybe<Array<Scalars['Boolean']>>;\n isKilled_not?: InputMaybe<Scalars['Boolean']>;\n isKilled_not_in?: InputMaybe<Array<Scalars['Boolean']>>;\n recipient?: InputMaybe<Scalars['Bytes']>;\n recipient_contains?: InputMaybe<Scalars['Bytes']>;\n recipient_gt?: InputMaybe<Scalars['Bytes']>;\n recipient_gte?: InputMaybe<Scalars['Bytes']>;\n recipient_in?: InputMaybe<Array<Scalars['Bytes']>>;\n recipient_lt?: InputMaybe<Scalars['Bytes']>;\n recipient_lte?: InputMaybe<Scalars['Bytes']>;\n recipient_not?: InputMaybe<Scalars['Bytes']>;\n recipient_not_contains?: InputMaybe<Scalars['Bytes']>;\n recipient_not_in?: InputMaybe<Array<Scalars['Bytes']>>;\n relativeWeightCap?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_gt?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_gte?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n relativeWeightCap_lt?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_lte?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_not?: InputMaybe<Scalars['BigDecimal']>;\n relativeWeightCap_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum RootGauge_OrderBy {\n Chain = 'chain',\n Factory = 'factory',\n Gauge = 'gauge',\n Id = 'id',\n IsKilled = 'isKilled',\n Recipient = 'recipient',\n RelativeWeightCap = 'relativeWeightCap'\n}\n\nexport type Subscription = {\n __typename?: 'Subscription';\n /** Access to subgraph metadata */\n _meta?: Maybe<_Meta_>;\n gauge?: Maybe<Gauge>;\n gaugeFactories: Array<GaugeFactory>;\n gaugeFactory?: Maybe<GaugeFactory>;\n gaugeShare?: Maybe<GaugeShare>;\n gaugeShares: Array<GaugeShare>;\n gaugeType?: Maybe<GaugeType>;\n gaugeTypes: Array<GaugeType>;\n gaugeVote?: Maybe<GaugeVote>;\n gaugeVotes: Array<GaugeVote>;\n gauges: Array<Gauge>;\n liquidityGauge?: Maybe<LiquidityGauge>;\n liquidityGauges: Array<LiquidityGauge>;\n pool?: Maybe<Pool>;\n pools: Array<Pool>;\n rewardToken?: Maybe<RewardToken>;\n rewardTokens: Array<RewardToken>;\n rootGauge?: Maybe<RootGauge>;\n rootGauges: Array<RootGauge>;\n user?: Maybe<User>;\n users: Array<User>;\n votingEscrow?: Maybe<VotingEscrow>;\n votingEscrowLock?: Maybe<VotingEscrowLock>;\n votingEscrowLocks: Array<VotingEscrowLock>;\n votingEscrows: Array<VotingEscrow>;\n};\n\n\nexport type Subscription_MetaArgs = {\n block?: InputMaybe<Block_Height>;\n};\n\n\nexport type SubscriptionGaugeArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionGaugeFactoriesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeFactory_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GaugeFactory_Filter>;\n};\n\n\nexport type SubscriptionGaugeFactoryArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionGaugeShareArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionGaugeSharesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GaugeShare_Filter>;\n};\n\n\nexport type SubscriptionGaugeTypeArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionGaugeTypesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeType_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GaugeType_Filter>;\n};\n\n\nexport type SubscriptionGaugeVoteArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionGaugeVotesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeVote_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<GaugeVote_Filter>;\n};\n\n\nexport type SubscriptionGaugesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Gauge_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Gauge_Filter>;\n};\n\n\nexport type SubscriptionLiquidityGaugeArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionLiquidityGaugesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<LiquidityGauge_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<LiquidityGauge_Filter>;\n};\n\n\nexport type SubscriptionPoolArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionPoolsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Pool_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<Pool_Filter>;\n};\n\n\nexport type SubscriptionRewardTokenArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionRewardTokensArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<RewardToken_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<RewardToken_Filter>;\n};\n\n\nexport type SubscriptionRootGaugeArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionRootGaugesArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<RootGauge_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<RootGauge_Filter>;\n};\n\n\nexport type SubscriptionUserArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionUsersArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<User_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<User_Filter>;\n};\n\n\nexport type SubscriptionVotingEscrowArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionVotingEscrowLockArgs = {\n block?: InputMaybe<Block_Height>;\n id: Scalars['ID'];\n subgraphError?: _SubgraphErrorPolicy_;\n};\n\n\nexport type SubscriptionVotingEscrowLocksArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<VotingEscrowLock_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<VotingEscrowLock_Filter>;\n};\n\n\nexport type SubscriptionVotingEscrowsArgs = {\n block?: InputMaybe<Block_Height>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<VotingEscrow_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n subgraphError?: _SubgraphErrorPolicy_;\n where?: InputMaybe<VotingEscrow_Filter>;\n};\n\nexport type User = {\n __typename?: 'User';\n /** List of gauge the user has shares */\n gaugeShares?: Maybe<Array<GaugeShare>>;\n /** List of votes on gauges */\n gaugeVotes?: Maybe<Array<GaugeVote>>;\n /** User address */\n id: Scalars['ID'];\n /** List of locks the user created */\n votingLocks?: Maybe<Array<VotingEscrowLock>>;\n};\n\n\nexport type UserGaugeSharesArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<GaugeShare_Filter>;\n};\n\n\nexport type UserGaugeVotesArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeVote_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<GaugeVote_Filter>;\n};\n\n\nexport type UserVotingLocksArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<VotingEscrowLock_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<VotingEscrowLock_Filter>;\n};\n\nexport type User_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n gaugeShares_?: InputMaybe<GaugeShare_Filter>;\n gaugeVotes_?: InputMaybe<GaugeVote_Filter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n votingLocks_?: InputMaybe<VotingEscrowLock_Filter>;\n};\n\nexport enum User_OrderBy {\n GaugeShares = 'gaugeShares',\n GaugeVotes = 'gaugeVotes',\n Id = 'id',\n VotingLocks = 'votingLocks'\n}\n\nexport type VotingEscrow = {\n __typename?: 'VotingEscrow';\n /** VotingEscrow contract address */\n id: Scalars['ID'];\n /** List of veBAL locks created */\n locks?: Maybe<Array<VotingEscrowLock>>;\n /** Amount of B-80BAL-20WETH BPT locked */\n stakedSupply: Scalars['BigDecimal'];\n};\n\n\nexport type VotingEscrowLocksArgs = {\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<VotingEscrowLock_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<VotingEscrowLock_Filter>;\n};\n\nexport type VotingEscrowLock = {\n __typename?: 'VotingEscrowLock';\n /** Equal to: <userAdress>-<votingEscrow> */\n id: Scalars['ID'];\n /** Amount of B-80BAL-20WETH BPT the user has locked */\n lockedBalance: Scalars['BigDecimal'];\n /** Timestamp at which B-80BAL-20WETH BPT can be unlocked by user [seconds] */\n unlockTime?: Maybe<Scalars['BigInt']>;\n updatedAt: Scalars['Int'];\n /** Reference to User entity */\n user: User;\n /** Reference to VotingEscrow entity */\n votingEscrowID: VotingEscrow;\n};\n\nexport type VotingEscrowLock_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n lockedBalance?: InputMaybe<Scalars['BigDecimal']>;\n lockedBalance_gt?: InputMaybe<Scalars['BigDecimal']>;\n lockedBalance_gte?: InputMaybe<Scalars['BigDecimal']>;\n lockedBalance_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n lockedBalance_lt?: InputMaybe<Scalars['BigDecimal']>;\n lockedBalance_lte?: InputMaybe<Scalars['BigDecimal']>;\n lockedBalance_not?: InputMaybe<Scalars['BigDecimal']>;\n lockedBalance_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n unlockTime?: InputMaybe<Scalars['BigInt']>;\n unlockTime_gt?: InputMaybe<Scalars['BigInt']>;\n unlockTime_gte?: InputMaybe<Scalars['BigInt']>;\n unlockTime_in?: InputMaybe<Array<Scalars['BigInt']>>;\n unlockTime_lt?: InputMaybe<Scalars['BigInt']>;\n unlockTime_lte?: InputMaybe<Scalars['BigInt']>;\n unlockTime_not?: InputMaybe<Scalars['BigInt']>;\n unlockTime_not_in?: InputMaybe<Array<Scalars['BigInt']>>;\n updatedAt?: InputMaybe<Scalars['Int']>;\n updatedAt_gt?: InputMaybe<Scalars['Int']>;\n updatedAt_gte?: InputMaybe<Scalars['Int']>;\n updatedAt_in?: InputMaybe<Array<Scalars['Int']>>;\n updatedAt_lt?: InputMaybe<Scalars['Int']>;\n updatedAt_lte?: InputMaybe<Scalars['Int']>;\n updatedAt_not?: InputMaybe<Scalars['Int']>;\n updatedAt_not_in?: InputMaybe<Array<Scalars['Int']>>;\n user?: InputMaybe<Scalars['String']>;\n user_?: InputMaybe<User_Filter>;\n user_contains?: InputMaybe<Scalars['String']>;\n user_contains_nocase?: InputMaybe<Scalars['String']>;\n user_ends_with?: InputMaybe<Scalars['String']>;\n user_ends_with_nocase?: InputMaybe<Scalars['String']>;\n user_gt?: InputMaybe<Scalars['String']>;\n user_gte?: InputMaybe<Scalars['String']>;\n user_in?: InputMaybe<Array<Scalars['String']>>;\n user_lt?: InputMaybe<Scalars['String']>;\n user_lte?: InputMaybe<Scalars['String']>;\n user_not?: InputMaybe<Scalars['String']>;\n user_not_contains?: InputMaybe<Scalars['String']>;\n user_not_contains_nocase?: InputMaybe<Scalars['String']>;\n user_not_ends_with?: InputMaybe<Scalars['String']>;\n user_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n user_not_in?: InputMaybe<Array<Scalars['String']>>;\n user_not_starts_with?: InputMaybe<Scalars['String']>;\n user_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n user_starts_with?: InputMaybe<Scalars['String']>;\n user_starts_with_nocase?: InputMaybe<Scalars['String']>;\n votingEscrowID?: InputMaybe<Scalars['String']>;\n votingEscrowID_?: InputMaybe<VotingEscrow_Filter>;\n votingEscrowID_contains?: InputMaybe<Scalars['String']>;\n votingEscrowID_contains_nocase?: InputMaybe<Scalars['String']>;\n votingEscrowID_ends_with?: InputMaybe<Scalars['String']>;\n votingEscrowID_ends_with_nocase?: InputMaybe<Scalars['String']>;\n votingEscrowID_gt?: InputMaybe<Scalars['String']>;\n votingEscrowID_gte?: InputMaybe<Scalars['String']>;\n votingEscrowID_in?: InputMaybe<Array<Scalars['String']>>;\n votingEscrowID_lt?: InputMaybe<Scalars['String']>;\n votingEscrowID_lte?: InputMaybe<Scalars['String']>;\n votingEscrowID_not?: InputMaybe<Scalars['String']>;\n votingEscrowID_not_contains?: InputMaybe<Scalars['String']>;\n votingEscrowID_not_contains_nocase?: InputMaybe<Scalars['String']>;\n votingEscrowID_not_ends_with?: InputMaybe<Scalars['String']>;\n votingEscrowID_not_ends_with_nocase?: InputMaybe<Scalars['String']>;\n votingEscrowID_not_in?: InputMaybe<Array<Scalars['String']>>;\n votingEscrowID_not_starts_with?: InputMaybe<Scalars['String']>;\n votingEscrowID_not_starts_with_nocase?: InputMaybe<Scalars['String']>;\n votingEscrowID_starts_with?: InputMaybe<Scalars['String']>;\n votingEscrowID_starts_with_nocase?: InputMaybe<Scalars['String']>;\n};\n\nexport enum VotingEscrowLock_OrderBy {\n Id = 'id',\n LockedBalance = 'lockedBalance',\n UnlockTime = 'unlockTime',\n UpdatedAt = 'updatedAt',\n User = 'user',\n VotingEscrowId = 'votingEscrowID'\n}\n\nexport type VotingEscrow_Filter = {\n /** Filter for the block changed event. */\n _change_block?: InputMaybe<BlockChangedFilter>;\n id?: InputMaybe<Scalars['ID']>;\n id_gt?: InputMaybe<Scalars['ID']>;\n id_gte?: InputMaybe<Scalars['ID']>;\n id_in?: InputMaybe<Array<Scalars['ID']>>;\n id_lt?: InputMaybe<Scalars['ID']>;\n id_lte?: InputMaybe<Scalars['ID']>;\n id_not?: InputMaybe<Scalars['ID']>;\n id_not_in?: InputMaybe<Array<Scalars['ID']>>;\n locks_?: InputMaybe<VotingEscrowLock_Filter>;\n stakedSupply?: InputMaybe<Scalars['BigDecimal']>;\n stakedSupply_gt?: InputMaybe<Scalars['BigDecimal']>;\n stakedSupply_gte?: InputMaybe<Scalars['BigDecimal']>;\n stakedSupply_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n stakedSupply_lt?: InputMaybe<Scalars['BigDecimal']>;\n stakedSupply_lte?: InputMaybe<Scalars['BigDecimal']>;\n stakedSupply_not?: InputMaybe<Scalars['BigDecimal']>;\n stakedSupply_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;\n};\n\nexport enum VotingEscrow_OrderBy {\n Id = 'id',\n Locks = 'locks',\n StakedSupply = 'stakedSupply'\n}\n\nexport type _Block_ = {\n __typename?: '_Block_';\n /** The hash of the block */\n hash?: Maybe<Scalars['Bytes']>;\n /** The block number */\n number: Scalars['Int'];\n /** Integer representation of the timestamp stored in blocks for the chain */\n timestamp?: Maybe<Scalars['Int']>;\n};\n\n/** The type for the top-level _meta field */\nexport type _Meta_ = {\n __typename?: '_Meta_';\n /**\n * Information about a specific subgraph block. The hash of the block\n * will be null if the _meta field has a block constraint that asks for\n * a block number. It will be filled if the _meta field has no block constraint\n * and therefore asks for the latest block\n *\n */\n block: _Block_;\n /** The deployment ID */\n deployment: Scalars['String'];\n /** If `true`, the subgraph encountered indexing errors at some past block */\n hasIndexingErrors: Scalars['Boolean'];\n};\n\nexport enum _SubgraphErrorPolicy_ {\n /** Data will be returned even if the subgraph has indexing errors */\n Allow = 'allow',\n /** If the subgraph has indexing errors, data will be omitted. The default. */\n Deny = 'deny'\n}\n\nexport type GaugeShareQueryVariables = Exact<{\n id: Scalars['ID'];\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type GaugeShareQuery = { __typename?: 'Query', gaugeShare?: { __typename?: 'GaugeShare', id: string, balance: string, user: { __typename?: 'User', id: string }, gauge: { __typename?: 'LiquidityGauge', id: string, isKilled: boolean, poolId?: string | null, poolAddress: string, totalSupply: string } } | null };\n\nexport type GaugeSharesQueryVariables = Exact<{\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<GaugeShare_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n where?: InputMaybe<GaugeShare_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type GaugeSharesQuery = { __typename?: 'Query', gaugeShares: Array<{ __typename?: 'GaugeShare', id: string, balance: string, user: { __typename?: 'User', id: string }, gauge: { __typename?: 'LiquidityGauge', id: string, isKilled: boolean, poolId?: string | null, poolAddress: string, totalSupply: string } }> };\n\nexport type SubgraphGaugeShareFragment = { __typename?: 'GaugeShare', id: string, balance: string, user: { __typename?: 'User', id: string }, gauge: { __typename?: 'LiquidityGauge', id: string, isKilled: boolean, poolId?: string | null, poolAddress: string, totalSupply: string } };\n\nexport type LiquidityGaugesQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<LiquidityGauge_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<LiquidityGauge_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type LiquidityGaugesQuery = { __typename?: 'Query', liquidityGauges: Array<{ __typename?: 'LiquidityGauge', id: string, symbol: string, poolAddress: string, poolId?: string | null, streamer?: string | null, totalSupply: string, factory: { __typename?: 'GaugeFactory', id: string, numGauges: number }, tokens?: Array<{ __typename?: 'RewardToken', id: string, symbol: string, decimals: number, totalDeposited: string, rate?: string | null, periodFinish?: string | null }> | null }> };\n\nexport type SubgraphLiquidityGaugeFragment = { __typename?: 'LiquidityGauge', id: string, symbol: string, poolAddress: string, poolId?: string | null, streamer?: string | null, totalSupply: string, factory: { __typename?: 'GaugeFactory', id: string, numGauges: number }, tokens?: Array<{ __typename?: 'RewardToken', id: string, symbol: string, decimals: number, totalDeposited: string, rate?: string | null, periodFinish?: string | null }> | null };\n\nexport type PoolsQueryVariables = Exact<{\n skip?: InputMaybe<Scalars['Int']>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Pool_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n where?: InputMaybe<Pool_Filter>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type PoolsQuery = { __typename?: 'Query', pools: Array<{ __typename?: 'Pool', id: string, poolId?: string | null, preferentialGauge?: { __typename?: 'LiquidityGauge', id: string, symbol: string, poolAddress: string, poolId?: string | null, streamer?: string | null, totalSupply: string, factory: { __typename?: 'GaugeFactory', id: string, numGauges: number }, tokens?: Array<{ __typename?: 'RewardToken', id: string, symbol: string, decimals: number, totalDeposited: string, rate?: string | null, periodFinish?: string | null }> | null } | null }> };\n\nexport type SubgraphPoolWithPreferentialGaugeFragment = { __typename?: 'Pool', id: string, poolId?: string | null, preferentialGauge?: { __typename?: 'LiquidityGauge', id: string, symbol: string, poolAddress: string, poolId?: string | null, streamer?: string | null, totalSupply: string, factory: { __typename?: 'GaugeFactory', id: string, numGauges: number }, tokens?: Array<{ __typename?: 'RewardToken', id: string, symbol: string, decimals: number, totalDeposited: string, rate?: string | null, periodFinish?: string | null }> | null } | null };\n\nexport type PoolGaugesQueryVariables = Exact<{\n where?: InputMaybe<Pool_Filter>;\n first?: InputMaybe<Scalars['Int']>;\n orderBy?: InputMaybe<Pool_OrderBy>;\n orderDirection?: InputMaybe<OrderDirection>;\n skip?: InputMaybe<Scalars['Int']>;\n block?: InputMaybe<Block_Height>;\n}>;\n\n\nexport type PoolGaugesQuery = { __typename?: 'Query', pools: Array<{ __typename?: 'Pool', gauges?: Array<{ __typename?: 'LiquidityGauge', id: string, relativeWeightCap?: string | null }> | null, preferentialGauge?: { __typename?: 'LiquidityGauge', id: string } | null }> };\n\nexport const SubgraphGaugeShareFragmentDoc = gql`\n fragment SubgraphGaugeShare on GaugeShare {\n id\n balance\n user {\n id\n }\n gauge {\n id\n isKilled\n poolId\n poolAddress\n totalSupply\n }\n}\n `;\nexport const SubgraphLiquidityGaugeFragmentDoc = gql`\n fragment SubgraphLiquidityGauge on LiquidityGauge {\n id\n symbol\n poolAddress\n poolId\n streamer\n factory {\n id\n numGauges\n }\n totalSupply\n tokens {\n id\n symbol\n decimals\n totalDeposited\n rate\n periodFinish\n }\n}\n `;\nexport const SubgraphPoolWithPreferentialGaugeFragmentDoc = gql`\n fragment SubgraphPoolWithPreferentialGauge on Pool {\n id\n poolId\n preferentialGauge {\n ...SubgraphLiquidityGauge\n }\n}\n ${SubgraphLiquidityGaugeFragmentDoc}`;\nexport const GaugeShareDocument = gql`\n query GaugeShare($id: ID!, $block: Block_height) {\n gaugeShare(id: $id, block: $block) {\n ...SubgraphGaugeShare\n }\n}\n ${SubgraphGaugeShareFragmentDoc}`;\nexport const GaugeSharesDocument = gql`\n query GaugeShares($first: Int, $orderBy: GaugeShare_orderBy, $orderDirection: OrderDirection, $skip: Int, $where: GaugeShare_filter, $block: Block_height) {\n gaugeShares(\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n skip: $skip\n where: $where\n block: $block\n ) {\n ...SubgraphGaugeShare\n }\n}\n ${SubgraphGaugeShareFragmentDoc}`;\nexport const LiquidityGaugesDocument = gql`\n query LiquidityGauges($skip: Int, $first: Int, $orderBy: LiquidityGauge_orderBy, $orderDirection: OrderDirection, $where: LiquidityGauge_filter, $block: Block_height) {\n liquidityGauges(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphLiquidityGauge\n }\n}\n ${SubgraphLiquidityGaugeFragmentDoc}`;\nexport const PoolsDocument = gql`\n query Pools($skip: Int, $first: Int, $orderBy: Pool_orderBy, $orderDirection: OrderDirection, $where: Pool_filter, $block: Block_height) {\n pools(\n skip: $skip\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n where: $where\n block: $block\n ) {\n ...SubgraphPoolWithPreferentialGauge\n }\n}\n ${SubgraphPoolWithPreferentialGaugeFragmentDoc}`;\nexport const PoolGaugesDocument = gql`\n query PoolGauges($where: Pool_filter, $first: Int, $orderBy: Pool_orderBy, $orderDirection: OrderDirection, $skip: Int, $block: Block_height) {\n pools(\n where: $where\n first: $first\n orderBy: $orderBy\n orderDirection: $orderDirection\n skip: $skip\n block: $block\n ) {\n gauges {\n id\n relativeWeightCap\n }\n preferentialGauge {\n id\n }\n }\n}\n `;\n\nexport type SdkFunctionWrapper = <T>(action: (requestHeaders?:Record<string, string>) => Promise<T>, operationName: string, operationType?: string) => Promise<T>;\n\n\nconst defaultWrapper: SdkFunctionWrapper = (action, _operationName, _operationType) => action();\n\nexport function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {\n return {\n GaugeShare(variables: GaugeShareQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<GaugeShareQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<GaugeShareQuery>(GaugeShareDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'GaugeShare', 'query');\n },\n GaugeShares(variables?: GaugeSharesQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<GaugeSharesQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<GaugeSharesQuery>(GaugeSharesDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'GaugeShares', 'query');\n },\n LiquidityGauges(variables?: LiquidityGaugesQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<LiquidityGaugesQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<LiquidityGaugesQuery>(LiquidityGaugesDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'LiquidityGauges', 'query');\n },\n Pools(variables?: PoolsQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<PoolsQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<PoolsQuery>(PoolsDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'Pools', 'query');\n },\n PoolGauges(variables?: PoolGaugesQueryVariables, requestHeaders?: Dom.RequestInit[\"headers\"]): Promise<PoolGaugesQuery> {\n return withWrapper((wrappedRequestHeaders) => client.request<PoolGaugesQuery>(PoolGaugesDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'PoolGauges', 'query');\n }\n };\n}\nexport type Sdk = ReturnType<typeof getSdk>;","import { GraphQLClient } from 'graphql-request';\nimport { getSdk, Sdk } from './generated/balancer-subgraph-types';\nimport * as Gauges from './generated/balancer-gauges';\nimport * as V2 from './generated/balancer-subgraph-types';\n\nexport * from './generated/balancer-subgraph-types';\n\nexport type SubgraphClient = Sdk;\nexport type GaugesClient = Gauges.Sdk;\nexport type SubgraphLiquidityGauge = Gauges.LiquidityGauge;\nexport type SubgraphPool = V2.SubgraphPoolFragment;\n\nexport function createSubgraphClient(subgraphUrl: string): SubgraphClient {\n const client = new GraphQLClient(subgraphUrl);\n\n return getSdk(client);\n}\n\nexport function createGaugesClient(url: string): GaugesClient {\n const client = new GraphQLClient(url);\n\n return Gauges.getSdk(client);\n}\n","import { Contract } from '@ethersproject/contracts';\nimport { Provider } from '@ethersproject/providers';\n\nconst multicallAbi = [\n 'function aggregate(tuple[](address target, bytes callData) memory calls) public view returns (uint256 blockNumber, bytes[] memory returnData)',\n];\n\nexport const Multicall = (address: string, provider: Provider): Contract =>\n new Contract(address, multicallAbi, provider);\n","import { set } from 'lodash';\nimport { Fragment, JsonFragment, Interface, Result } from '@ethersproject/abi';\nimport { CallOverrides } from '@ethersproject/contracts';\nimport { Provider } from '@ethersproject/providers';\nimport { BytesLike } from '@ethersproject/bytes';\nimport { Multicall } from '@/modules/contracts/implementations/multicall';\n\nexport class Multicaller {\n private multiAddress: string;\n private provider: Provider;\n private interface: Interface;\n public options: CallOverrides = {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private calls: [string, string, any][] = [];\n private paths: string[] = [];\n\n constructor(\n multiAddress: string,\n provider: Provider,\n abi: string | Array<Fragment | JsonFragment | string>,\n options = {}\n ) {\n this.multiAddress = multiAddress;\n this.provider = provider;\n this.interface = new Interface(abi);\n this.options = options;\n }\n\n call(\n path: string,\n address: string,\n functionName: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n params?: any[]\n ): Multicaller {\n this.calls.push([address, functionName, params]);\n this.paths.push(path);\n return this;\n }\n\n async execute(\n from: Record<string, unknown> = {}\n ): Promise<Record<string, unknown>> {\n const obj = from;\n const results = await this.executeMulticall();\n results.forEach((result, i) =>\n set(obj, this.paths[i], result.length > 1 ? result : result[0])\n );\n this.calls = [];\n this.paths = [];\n return obj;\n }\n\n private async executeMulticall(): Promise<Result[]> {\n const multi = Multicall(this.multiAddress, this.provider);\n\n const [, res] = await multi.aggregate(\n this.calls.map(([address, functionName, params]) => [\n address,\n this.interface.encodeFunctionData(functionName, params),\n ]),\n this.options\n );\n\n return res.map((result: BytesLike, i: number) =>\n this.interface.decodeFunctionResult(this.calls[i][1], result)\n );\n }\n}\n","import { formatFixed } from '@ethersproject/bignumber';\nimport { Provider } from '@ethersproject/providers';\nimport { PoolFilter, SubgraphPoolBase, SubgraphToken } from '@defiverse/sor';\nimport { Multicaller } from '@/lib/utils/multiCaller';\nimport { isSameAddress } from '@/lib/utils';\nimport { Vault__factory } from '@balancer-labs/typechain';\nimport { Pool, PoolToken } from '@/types';\n\n// TODO: decide whether we want to trim these ABIs down to the relevant functions\nimport aTokenRateProvider from '@/lib/abi/StaticATokenRateProvider.json';\n\nimport weightedPoolAbi from '@/lib/abi/WeightedPool.json';\nimport stablePoolAbi from '@/lib/abi/StablePool.json';\nimport elementPoolAbi from '@/lib/abi/ConvergentCurvePool.json';\nimport linearPoolAbi from '@/lib/abi/LinearPool.json';\nimport composableStableAbi from '@/lib/abi/ComposableStable.json';\n\nexport async function getOnChainBalances<\n GenericPool extends Omit<SubgraphPoolBase | Pool, 'tokens'> & {\n tokens: (SubgraphToken | PoolToken)[];\n }\n>(\n subgraphPoolsOriginal: GenericPool[],\n multiAddress: string,\n vaultAddress: string,\n provider: Provider\n): Promise<GenericPool[]> {\n if (subgraphPoolsOriginal.length === 0) return subgraphPoolsOriginal;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const abis: any = Object.values(\n // Remove duplicate entries using their names\n Object.fromEntries(\n [\n ...Vault__factory.abi,\n ...aTokenRateProvider,\n ...weightedPoolAbi,\n ...stablePoolAbi,\n ...elementPoolAbi,\n ...linearPoolAbi,\n ...composableStableAbi,\n ].map((row) => [row.name, row])\n )\n );\n\n const multiPool = new Multicaller(multiAddress, provider, abis);\n\n const supportedPoolTypes: string[] = Object.values(PoolFilter);\n const subgraphPools: GenericPool[] = [];\n subgraphPoolsOriginal.forEach((pool) => {\n if (!supportedPoolTypes.includes(pool.poolType)) {\n console.error(`Unknown pool type: ${pool.poolType} ${pool.id}`);\n return;\n }\n\n subgraphPools.push(pool);\n\n multiPool.call(`${pool.id}.poolTokens`, vaultAddress, 'getPoolTokens', [\n pool.id,\n ]);\n multiPool.call(`${pool.id}.totalSupply`, pool.address, 'totalSupply');\n\n // Pools with pre minted BPT\n if (pool.poolType.includes('Linear') || pool.poolType === 'StablePhantom') {\n multiPool.call(\n `${pool.id}.virtualSupply`,\n pool.address,\n 'getVirtualSupply'\n );\n }\n\n /**\n * Returns the effective BPT supply.\n * In other pools, this would be the same as `totalSupply`, but there are two key differences here:\n * - this pool pre-mints BPT and holds it in the Vault as a token, and as such we need to subtract the Vault's\n * balance to get the total \"circulating supply\". This is called the 'virtualSupply'.\n * - the Pool owes debt to the Protocol in the form of unminted BPT, which will be minted immediately before the\n * next join or exit. We need to take these into account since, even if they don't yet exist, they will\n * effectively be included in any Pool operation that involves BPT.\n * In the vast majority of cases, this function should be used instead of `totalSupply()`.\n */\n if (pool.poolType === 'ComposableStable')\n multiPool.call(\n `${pool.id}.actualSupply`,\n pool.address,\n 'getActualSupply'\n );\n\n // TO DO - Make this part of class to make more flexible?\n if (\n pool.poolType === 'Weighted' ||\n pool.poolType === 'LiquidityBootstrapping' ||\n pool.poolType === 'Investment'\n ) {\n multiPool.call(\n `${pool.id}.weights`,\n pool.address,\n 'getNormalizedWeights'\n );\n multiPool.call(\n `${pool.id}.swapFee`,\n pool.address,\n 'getSwapFeePercentage'\n );\n } else if (\n pool.poolType === 'Stable' ||\n pool.poolType === 'MetaStable' ||\n pool.poolType === 'StablePhantom' ||\n pool.poolType === 'ComposableStable'\n ) {\n // MetaStable & StablePhantom is the same as Stable for multicall purposes\n multiPool.call(\n `${pool.id}.amp`,\n pool.address,\n 'getAmplificationParameter'\n );\n multiPool.call(\n `${pool.id}.swapFee`,\n pool.address,\n 'getSwapFeePercentage'\n );\n } else if (pool.poolType === 'Element') {\n multiPool.call(`${pool.id}.swapFee`, pool.address, 'percentFee');\n } else if (pool.poolType.toString().includes('Linear')) {\n multiPool.call(\n `${pool.id}.swapFee`,\n pool.address,\n 'getSwapFeePercentage'\n );\n\n multiPool.call(`${pool.id}.targets`, pool.address, 'getTargets');\n multiPool.call(`${pool.id}.rate`, pool.address, 'getWrappedTokenRate');\n } else if (pool.poolType.toString().includes('Gyro')) {\n multiPool.call(\n `${pool.id}.swapFee`,\n pool.address,\n 'getSwapFeePercentage'\n );\n }\n });\n\n let pools = {} as Record<\n string,\n {\n amp?: string[];\n swapFee: string;\n weights?: string[];\n targets?: string[];\n poolTokens: {\n tokens: string[];\n balances: string[];\n };\n totalSupply: string;\n virtualSupply?: string;\n rate?: string;\n actualSupply?: string;\n }\n >;\n\n try {\n pools = (await multiPool.execute()) as Record<\n string,\n {\n amp?: string[];\n swapFee: string;\n weights?: string[];\n poolTokens: {\n tokens: string[];\n balances: string[];\n };\n totalSupply: string;\n virtualSupply?: string;\n rate?: string;\n actualSupply?: string;\n }\n >;\n } catch (err) {\n throw `Issue with multicall execution.`;\n }\n\n const onChainPools: GenericPool[] = [];\n\n Object.entries(pools).forEach(([poolId, onchainData], index) => {\n try {\n const {\n poolTokens,\n swapFee,\n weights,\n totalSupply,\n virtualSupply,\n actualSupply,\n } = onchainData;\n\n if (\n subgraphPools[index].poolType === 'Stable' ||\n subgraphPools[index].poolType === 'MetaStable' ||\n subgraphPools[index].poolType === 'StablePhantom' ||\n subgraphPools[index].poolType === 'ComposableStable'\n ) {\n if (!onchainData.amp) {\n console.error(`Stable Pool Missing Amp: ${poolId}`);\n return;\n } else {\n // Need to scale amp by precision to match expected Subgraph scale\n // amp is stored with 3 decimals of precision\n subgraphPools[index].amp = formatFixed(onchainData.amp[0], 3);\n }\n }\n\n if (subgraphPools[index].poolType.includes('Linear')) {\n if (!onchainData.targets) {\n console.error(`Linear Pool Missing Targets: ${poolId}`);\n return;\n } else {\n subgraphPools[index].lowerTarget = formatFixed(\n onchainData.targets[0],\n 18\n );\n subgraphPools[index].upperTarget = formatFixed(\n onchainData.targets[1],\n 18\n );\n }\n\n const wrappedIndex = subgraphPools[index].wrappedIndex;\n if (wrappedIndex === undefined || onchainData.rate === undefined) {\n console.error(\n `Linear Pool Missing WrappedIndex or PriceRate: ${poolId}`\n );\n return;\n }\n // Update priceRate of wrappedToken\n subgraphPools[index].tokens[wrappedIndex].priceRate = formatFixed(\n onchainData.rate,\n 18\n );\n }\n\n subgraphPools[index].swapFee = formatFixed(swapFee, 18);\n\n poolTokens.tokens.forEach((token, i) => {\n const tokens = subgraphPools[index].tokens;\n const T = tokens.find((t) => isSameAddress(t.address, token));\n if (!T) throw `Pool Missing Expected Token: ${poolId} ${token}`;\n T.balance = formatFixed(poolTokens.balances[i], T.decimals);\n if (weights) {\n // Only expected for WeightedPools\n T.weight = formatFixed(weights[i], 18);\n }\n });\n\n // Pools with pre minted BPT\n if (\n subgraphPools[index].poolType.includes('Linear') ||\n subgraphPools[index].poolType === 'StablePhantom'\n ) {\n if (virtualSupply === undefined) {\n console.error(\n `Pool with pre-minted BPT missing Virtual Supply: ${poolId}`\n );\n return;\n }\n subgraphPools[index].totalShares = formatFixed(virtualSupply, 18);\n } else if (subgraphPools[index].poolType === 'ComposableStable') {\n if (actualSupply === undefined) {\n console.error(`ComposableStable missing Actual Supply: ${poolId}`);\n return;\n }\n subgraphPools[index].totalShares = formatFixed(actualSupply, 18);\n } else {\n subgraphPools[index].totalShares = formatFixed(totalSupply, 18);\n }\n\n onChainPools.push(subgraphPools[index]);\n } catch (err) {\n throw `Issue with pool onchain data: ${err}`;\n }\n });\n\n return onChainPools;\n}\n","import { PoolDataService, SubgraphPoolBase } from '@defiverse/sor';\nimport {\n OrderDirection,\n Pool_OrderBy,\n SubgraphClient,\n} from '@/modules/subgraph/subgraph';\nimport { parseInt } from 'lodash';\nimport { getOnChainBalances } from './onChainData';\nimport { Provider } from '@ethersproject/providers';\nimport { BalancerNetworkConfig, BalancerSdkSorConfig } from '@/types';\nimport { isSameAddress } from '@/lib/utils';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function mapPools(pools: any[]): SubgraphPoolBase[] {\n return pools.map((pool) => ({\n ...pool,\n poolType: pool.poolType || '',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tokens: (pool.tokens || []).map((token: any) => ({\n ...token,\n weight: token.weight || null,\n })),\n totalWeight: pool.totalWeight || undefined,\n amp: pool.amp || undefined,\n expiryTime: pool.expiryTime ? parseInt(pool.expiryTime) : undefined,\n unitSeconds: pool.unitSeconds ? parseInt(pool.unitSeconds) : undefined,\n principalToken: pool.principalToken || undefined,\n baseToken: pool.baseToken || undefined,\n }));\n}\n\nexport class SubgraphPoolDataService implements PoolDataService {\n constructor(\n private readonly client: SubgraphClient,\n private readonly provider: Provider,\n private readonly network: BalancerNetworkConfig,\n private readonly sorConfig: BalancerSdkSorConfig\n ) {}\n\n public async getPools(): Promise<SubgraphPoolBase[]> {\n const pools = await this.getSubgraphPools();\n\n const filteredPools = pools.filter((p) => {\n if (!this.network.poolsToIgnore) return true;\n const index = this.network.poolsToIgnore.findIndex((addr) =>\n isSameAddress(addr, p.address)\n );\n return index === -1;\n });\n\n const mapped = mapPools(filteredPools);\n\n if (this.sorConfig.fetchOnChainBalances === false) {\n return mapped;\n }\n\n return getOnChainBalances(\n mapped,\n this.network.addresses.contracts.multicall,\n this.network.addresses.contracts.vault,\n this.provider\n );\n }\n\n private async getSubgraphPools() {\n const { pool0, pool1000, pool2000 } = await this.client.AllPools({\n //where: { swapEnabled: true, totalShares_gt: '0.000000000001' },\n where: { swapEnabled: true, totalShares_gt: '1' },\n // where: { swapEnabled: true },\n orderBy: Pool_OrderBy.TotalLiquidity,\n orderDirection: OrderDirection.Desc,\n });\n\n const pools = [...pool0, ...pool1000, ...pool2000];\n\n return pools;\n }\n}\n","import { TokenPriceService } from '@defiverse/sor';\nimport axios from 'axios';\n\nexport class CoingeckoTokenPriceService implements TokenPriceService {\n constructor(private readonly chainId: number) {}\n\n public async getNativeAssetPriceInToken(\n tokenAddress: string\n ): Promise<string> {\n const ethPerToken = await this.getTokenPriceInNativeAsset(tokenAddress);\n\n // We get the price of token in terms of ETH\n // We want the price of 1 ETH in terms of the token base units\n return `${1 / parseFloat(ethPerToken)}`;\n }\n\n /**\n * @dev Assumes that the native asset has 18 decimals\n * @param tokenAddress - the address of the token contract\n * @returns the price of 1 ETH in terms of the token base units\n */\n async getTokenPriceInNativeAsset(tokenAddress: string): Promise<string> {\n const endpoint = `https://api.coingecko.com/api/v3/simple/token_price/${this.platformId}?contract_addresses=${tokenAddress}&vs_currencies=${this.nativeAssetId}`;\n\n const { data } = await axios.get(endpoint, {\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n });\n\n if (data[tokenAddress.toLowerCase()][this.nativeAssetId] === undefined) {\n throw Error('No price returned from Coingecko');\n }\n\n return data[tokenAddress.toLowerCase()][this.nativeAssetId];\n }\n\n private get platformId(): string {\n switch (this.chainId) {\n case 1:\n return 'ethereum';\n case 42:\n return 'ethereum';\n case 137:\n return 'polygon-pos';\n case 42161:\n return 'arbitrum-one';\n case 100:\n return 'xdai';\n case 248:\n return 'ethereum';\n case 16116:\n return 'ethereum';\n case 17117:\n return 'ethereum';\n }\n\n return '3';\n }\n\n private get nativeAssetId(): string {\n switch (this.chainId) {\n case 1:\n return 'eth';\n case 42:\n return 'eth';\n case 137:\n return '';\n case 42161:\n return 'eth';\n case 100:\n return 'xdai';\n case 248:\n return 'eth';\n case 16116:\n return 'eth';\n case 17117:\n return 'eth';\n }\n\n return '';\n }\n}\n","import { TokenPriceService } from '@defiverse/sor';\nimport { SubgraphClient } from '@/modules/subgraph/subgraph';\nimport { keyBy } from 'lodash';\n\nexport class SubgraphTokenPriceService implements TokenPriceService {\n private readonly weth: string;\n\n constructor(private readonly client: SubgraphClient, weth: string) {\n //the subgraph addresses are all toLowerCase\n this.weth = weth.toLowerCase();\n }\n\n public async getNativeAssetPriceInToken(\n tokenAddress: string\n ): Promise<string> {\n const ethPerToken = await this.getLatestPriceInEthFromSubgraph(\n tokenAddress\n );\n\n if (!ethPerToken) {\n throw Error('No price found in the subgraph');\n }\n\n // We want the price of 1 ETH in terms of the token base units\n return `${1 / ethPerToken}`;\n }\n\n public async getLatestPriceInEthFromSubgraph(\n tokenAddress: string\n ): Promise<number | null> {\n tokenAddress = tokenAddress.toLowerCase();\n\n const { latestPrices } = await this.client.TokenLatestPrices({\n where: { asset_in: [tokenAddress, this.weth] },\n });\n const pricesKeyedOnId = keyBy(latestPrices, 'id');\n\n //the ids are set as ${asset}-${pricingAsset}\n //first try to find an exact match\n if (pricesKeyedOnId[`${tokenAddress}-${this.weth}`]) {\n return parseFloat(pricesKeyedOnId[`${tokenAddress}-${this.weth}`].price);\n }\n\n //no exact match, try to traverse the path\n const matchingLatestPrices = latestPrices.filter(\n (price) => price.asset === tokenAddress\n );\n\n //pick the first one we match on.\n //There is no timestamp on latestPrice, should get introduced to allow for sorting by latest\n for (const tokenPrice of matchingLatestPrices) {\n const pricingAssetPricedInEth =\n pricesKeyedOnId[`${tokenPrice.pricingAsset}-${this.weth}`];\n\n //1 BAL = 20 USDC, 1 USDC = 0.00025 ETH, 1 BAL = 20 * 0.00025\n if (pricingAssetPricedInEth) {\n return (\n parseFloat(tokenPrice.price) *\n parseFloat(pricingAssetPricedInEth.price)\n );\n }\n }\n\n return null;\n }\n}\n","import { BALANCER_NETWORK_CONFIG } from '@/lib/constants/config';\nimport { BalancerNetworkConfig, BalancerSdkConfig } from '@/types';\nexport function getNetworkConfig(\n config: BalancerSdkConfig\n): BalancerNetworkConfig {\n if (typeof config.network === 'number') {\n const networkConfig = BALANCER_NETWORK_CONFIG[config.network];\n\n return {\n ...networkConfig,\n urls: {\n ...networkConfig.urls,\n subgraph: config.customSubgraphUrl ?? networkConfig.urls.subgraph,\n },\n tenderly: config.tenderly,\n };\n }\n\n return {\n ...config.network,\n urls: {\n ...config.network.urls,\n subgraph: config.customSubgraphUrl ?? config.network.urls.subgraph,\n },\n tenderly: config.network.tenderly,\n };\n}\n","import {\n SOR,\n SorConfig,\n TokenPriceService,\n SwapTypes,\n SwapOptions,\n SwapInfo,\n PoolFilter,\n SubgraphPoolBase,\n} from '@defiverse/sor';\nimport { Provider, JsonRpcProvider } from '@ethersproject/providers';\nimport { SubgraphPoolDataService } from './pool-data/subgraphPoolDataService';\nimport { CoingeckoTokenPriceService } from './token-price/coingeckoTokenPriceService';\nimport {\n SubgraphClient,\n createSubgraphClient,\n} from '@/modules/subgraph/subgraph';\nimport {\n BalancerNetworkConfig,\n BalancerSdkConfig,\n BalancerSdkSorConfig,\n} from '@/types';\nimport { SubgraphTokenPriceService } from './token-price/subgraphTokenPriceService';\nimport { getNetworkConfig } from '@/modules/sdk.helpers';\n\nimport { BigNumber, BigNumberish, parseFixed } from '@ethersproject/bignumber';\n\nexport class Sor extends SOR {\n constructor(sdkConfig: BalancerSdkConfig) {\n const network = getNetworkConfig(sdkConfig);\n const sorConfig = Sor.getSorConfig(sdkConfig);\n const sorNetworkConfig = Sor.getSorNetworkConfig(network);\n const provider = new JsonRpcProvider(\n sdkConfig.rpcUrl,\n sdkConfig.network as number\n );\n const subgraphClient = createSubgraphClient(network.urls.subgraph);\n\n const poolDataService = Sor.getPoolDataService(\n network,\n sorConfig,\n provider,\n subgraphClient\n );\n\n const tokenPriceService = Sor.getTokenPriceService(\n network,\n sorConfig,\n subgraphClient\n );\n\n super(provider, sorNetworkConfig, poolDataService, tokenPriceService);\n }\n\n private static getSorConfig(config: BalancerSdkConfig): BalancerSdkSorConfig {\n return {\n tokenPriceService: 'coingecko',\n poolDataService: 'subgraph',\n fetchOnChainBalances: true,\n ...config.sor,\n };\n }\n\n private static getSorNetworkConfig(\n network: BalancerNetworkConfig\n ): SorConfig {\n return {\n ...network,\n vault: network.addresses.contracts.vault,\n weth: network.addresses.tokens.wrappedNativeAsset,\n lbpRaisingTokens: network.addresses.tokens?.lbpRaisingTokens,\n wETHwstETH: network.pools.wETHwstETH,\n connectingTokens: network.sorConnectingTokens,\n };\n }\n\n private static getPoolDataService(\n network: BalancerNetworkConfig,\n sorConfig: BalancerSdkSorConfig,\n provider: Provider,\n subgraphClient: SubgraphClient\n ) {\n return typeof sorConfig.poolDataService === 'object'\n ? sorConfig.poolDataService\n : new SubgraphPoolDataService(\n subgraphClient,\n provider,\n network,\n sorConfig\n );\n }\n\n private static getTokenPriceService(\n network: BalancerNetworkConfig,\n sorConfig: BalancerSdkSorConfig,\n subgraphClient: SubgraphClient\n ): TokenPriceService {\n if (typeof sorConfig.tokenPriceService === 'object') {\n return sorConfig.tokenPriceService;\n } else if (sorConfig.tokenPriceService === 'subgraph') {\n new SubgraphTokenPriceService(\n subgraphClient,\n network.addresses.tokens.wrappedNativeAsset\n );\n }\n\n return new CoingeckoTokenPriceService(network.chainId);\n }\n}\n","import {\n QuerySimpleFlashSwapParameters,\n QuerySimpleFlashSwapResponse,\n SimpleFlashSwapParameters,\n SwapType,\n} from '../types';\nimport { queryBatchSwap } from '../queryBatchSwap';\nimport { BatchSwap } from '../types';\nimport { sum } from 'lodash';\n\nfunction checkSimpleFlashSwapParams(params: {\n poolIds: string[];\n assets: string[];\n}) {\n if (params.poolIds.length > 2) {\n throw new Error('Simple flash swap only supports a maximum of two pools');\n }\n\n if (params.assets.length > 2) {\n throw new Error(\n 'Simple flash swap only supports a maximum of to two assets (tokens)'\n );\n }\n}\n\nfunction createSwaps(\n poolIds: SimpleFlashSwapParameters['poolIds'],\n amount: string\n): BatchSwap['swaps'] {\n return [\n {\n poolId: poolIds[0],\n assetInIndex: 0,\n assetOutIndex: 1,\n amount,\n userData: '0x',\n },\n {\n poolId: poolIds[1],\n assetInIndex: 1,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n ];\n}\n\nexport function convertSimpleFlashSwapToBatchSwapParameters({\n poolIds,\n assets,\n flashLoanAmount,\n walletAddress,\n}: SimpleFlashSwapParameters & {\n walletAddress: string;\n}): BatchSwap {\n checkSimpleFlashSwapParams({ poolIds, assets });\n\n const swaps = createSwaps(poolIds, flashLoanAmount);\n\n const funds = {\n sender: walletAddress,\n fromInternalBalance: false,\n recipient: walletAddress,\n toInternalBalance: false,\n };\n\n const limits = ['0', '0'];\n\n const deadline = '999999999999999999';\n\n return {\n kind: SwapType.SwapExactIn,\n swaps,\n assets,\n funds,\n limits,\n deadline,\n };\n}\n\nfunction deltaToExpectedProfit(delta: string) {\n return Number(delta) * -1;\n}\n\nfunction calcProfit(profits: string[]) {\n return sum(profits);\n}\n\n/**\n * Simple interface to test if a simple flash swap is valid and see potential profits.\n *\n * A \"simple\" flash swap is an arbitrage executed with only two tokens and two pools,\n * swapping in the first pool and then back in the second pool for a profit. For more\n * complex flash swaps, you will have to use the batch swap method.\n *\n * Learn more: A [Flash Swap](https://dev.balancer.fi/resources/swaps/flash-swaps).\n *\n * _NB: This method doesn't execute a flashSwap\n *\n * @param {SimpleFlashSwapParameters} params - BatchSwap information used for query.\n * @param {Contract} params.vaultContract - the ethersjs contract for the Balancer Vault.\n * @param {string} params.flashLoanAmount - initial input amount for the flash loan (first asset)\n * @param {string[]} params.poolIds - array of Balancer pool ids\n * @param {string[]} params.assets - array of token addresses\n * @returns {Promise<QuerySimpleFlashSwapResponse}>} Returns an ethersjs transaction response\n */\nexport async function querySimpleFlashSwap(\n params: QuerySimpleFlashSwapParameters\n): Promise<QuerySimpleFlashSwapResponse> {\n checkSimpleFlashSwapParams(params);\n\n const [tokenAddress0, tokenAddress1] = params.assets;\n\n try {\n const deltas = await queryBatchSwap(\n params.vaultContract,\n SwapType.SwapExactIn,\n createSwaps(params.poolIds, params.flashLoanAmount),\n params.assets\n );\n\n const profits = {\n [tokenAddress0]: deltaToExpectedProfit(deltas[0]).toString(),\n [tokenAddress1]: deltaToExpectedProfit(deltas[1]).toString(),\n };\n\n return {\n profits,\n isProfitable:\n calcProfit([profits[tokenAddress0], profits[tokenAddress1]]) > 0,\n };\n } catch (err) {\n throw `Failed to querySimpleFlashSwap: ${err}`;\n }\n}\n","import { Vault__factory } from '@balancer-labs/typechain';\nimport BatchRelayerLibraryAbi from '@/lib/abi/BatchRelayerLibrary.json';\nimport { JsonFragment } from '@ethersproject/abi';\nimport { networkAddresses } from '@/lib/constants/config';\n\n/**\n * Maps SOR data to get the tokenIn used in swaps.\n * Logic related to a relayer wrapping and unwrapping tokens.\n * SOR returns list of already wrapped tokenAddresses used in the swap.\n * However tokenIn defined as an input is the unwrapped token.\n * Note: tokenAddresses are transformed in SOR lib wrapInfo.setWrappedInfo\n * TODO: Once PR is merged, this table can be removed.\n */\ntype WrappedList = {\n [key: string]: string;\n};\n\nconst underlyingToWrappedMap: WrappedList = {\n // stETH => wstETH\n '0xae7ab96520de3a18e5e111b5eaab095312d7fe84':\n '0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0',\n\n // AMPL => WAMPL\n '0xd46ba6d942050d489dbd938a2c909a5d5039a161':\n '0xedb171c18ce90b633db442f2a6f72874093b49ef',\n\n // aAMPL -> ubAAMPL\n '0x1e6bb68acec8fefbd87d192be09bb274170a0548':\n '0xF03387d8d0FF326ab586A58E0ab4121d106147DF',\n};\n\n/**\n * Vault swaps are operating on wrapped tokens. When user is sending an unwrapped token, it's wrapped in a relayer.\n * SOR is returning an array of tokens already wrapped.\n * Converts tokenIn to match tokenIn used in a swap.\n *\n * TODO: add tokenIn and tokenOut addressed used for swap in the SOR results as tokenInForSwap, tokenOutForSwap\n *\n * @param token token address\n * @returns wrapped token address\n */\nfunction tokenForSwaps(token: string): string {\n let wrapped = token;\n // eslint-disable-next-line no-prototype-builtins\n if (underlyingToWrappedMap.hasOwnProperty(token)) {\n wrapped = underlyingToWrappedMap[token as keyof WrappedList];\n }\n return wrapped;\n}\n\nexport enum Relayers {\n vault = 1,\n lido = 2,\n}\n\nexport interface SwapRelayer {\n id: Relayers;\n address: string;\n}\n\n/**\n * Resolves a contract address for sending swap transaction to.\n * Balancer is using relayers to automatically wrap / unwrap tokens not compatibile with ERC20.\n */\nfunction relayerResolver(\n assetIn: string,\n assetOut: string,\n chainId: number\n): SwapRelayer {\n const { tokens, contracts } = networkAddresses(chainId);\n\n let to = {\n id: Relayers.vault,\n address: contracts.vault,\n };\n\n if (tokens.stETH && contracts.lidoRelayer)\n if ([assetIn, assetOut].includes(tokens.stETH))\n to = {\n id: Relayers.lido,\n address: contracts.lidoRelayer,\n };\n\n return to;\n}\n\nfunction swapFragment(relayer: SwapRelayer): JsonFragment[] {\n let source = Vault__factory.abi;\n if (relayer.id === Relayers.lido) source = BatchRelayerLibraryAbi;\n\n const signatures = source.filter(\n (fn) => fn.name && ['swap', 'batchSwap'].includes(fn.name)\n );\n\n return signatures;\n}\n\nfunction batchSwapFragment(\n assetIn: string,\n assetOut: string,\n chainId: number\n): JsonFragment[] {\n const vaultSignaturesForSwaps = Vault__factory.abi.filter(\n (fn) => fn.name && ['batchSwap'].includes(fn.name)\n );\n const relayerSignaturesForSwaps = BatchRelayerLibraryAbi.filter(\n (fn) => fn.name && ['batchSwap'].includes(fn.name)\n );\n let returnSignatures = vaultSignaturesForSwaps;\n const { tokens, contracts } = networkAddresses(chainId);\n if (tokens.stETH && contracts.lidoRelayer) {\n if ([assetIn, assetOut].includes(tokens.stETH))\n returnSignatures = relayerSignaturesForSwaps;\n }\n\n return returnSignatures;\n}\n\nexport { tokenForSwaps, relayerResolver, swapFragment, batchSwapFragment };\n","import { SwapInfo } from '@defiverse/sor';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { tokenForSwaps } from './swap_utils';\nimport { SwapType } from '../types';\n\ninterface AmountForLimit {\n amount: BigNumber;\n max: (slippage: number) => BigNumber;\n min: (slippage: number) => BigNumber;\n}\n\ninterface SDKSwapInfo extends SwapInfo {\n /** Name mapping to improve readability. */\n amountIn: BigNumber;\n amountOut: BigNumber;\n /** Name mapping for amounts used specifically for limits calculations. */\n amountInForLimits: AmountForLimit;\n amountOutForLimits: AmountForLimit;\n /** Wrapped token addresses used in the swap. */\n tokenInForSwaps: string;\n tokenOutFromSwaps: string;\n}\n\n/** Applies slippage to a number */\nfunction amountForLimit(amount: BigNumber): AmountForLimit {\n return {\n amount,\n max: (maxSlippage: number): BigNumber => {\n return amount.mul(1e3 + maxSlippage).div(1e3);\n },\n min: (maxSlippage: number): BigNumber => {\n return amount.mul(1e3 - maxSlippage).div(1e3);\n },\n };\n}\n\nfunction decorateSorSwapInfo(\n swapInfo: SwapInfo,\n swapType: SwapType\n): SDKSwapInfo {\n const amountIn =\n swapType === SwapType.SwapExactIn\n ? swapInfo.swapAmount\n : swapInfo.returnAmount;\n const amountOut =\n swapType === SwapType.SwapExactIn\n ? swapInfo.returnAmount\n : swapInfo.swapAmount;\n const amountInForLimits =\n swapType === SwapType.SwapExactIn\n ? swapInfo.swapAmountForSwaps || swapInfo.swapAmount\n : swapInfo.returnAmountFromSwaps || swapInfo.returnAmount;\n const amountOutForLimits =\n swapType === SwapType.SwapExactIn\n ? swapInfo.returnAmountFromSwaps || swapInfo.returnAmount\n : swapInfo.swapAmountForSwaps || swapInfo.swapAmount;\n const tokenInForSwaps = tokenForSwaps(swapInfo.tokenIn);\n const tokenOutFromSwaps = tokenForSwaps(swapInfo.tokenOut);\n\n return {\n ...swapInfo,\n amountIn,\n amountOut,\n amountInForLimits: amountForLimit(amountInForLimits),\n amountOutForLimits: amountForLimit(amountOutForLimits),\n tokenInForSwaps,\n tokenOutFromSwaps,\n };\n}\n\nexport { SDKSwapInfo, tokenForSwaps, decorateSorSwapInfo };\n","import { BigNumber, BigNumberish } from '@ethersproject/bignumber';\nimport { FundManagement, SingleSwap, Swap, SwapType } from '../types';\nimport { Interface, JsonFragment } from '@ethersproject/abi';\nimport { SwapInfo } from '@defiverse/sor';\nimport { SDKSwapInfo, decorateSorSwapInfo } from './swap_info_decorator';\nimport { AddressZero } from '@ethersproject/constants';\nimport { swapFragment, relayerResolver, SwapRelayer } from './swap_utils';\n\nclass SingleSwapBuilder {\n private swapInfo: SDKSwapInfo;\n funds?: FundManagement;\n limit?: BigNumberish;\n deadline?: BigNumberish;\n relayer: SwapRelayer;\n readonly functionName = 'swap';\n\n /**\n * Building swap transaction data\n *\n * @param swapInfo SOR result\n * @param kind\n * @param chainId used to resolve relayer addresses\n */\n constructor(\n swapInfo: SwapInfo,\n private readonly kind: SwapType,\n private readonly chainId: number\n ) {\n this.swapInfo = decorateSorSwapInfo(swapInfo, kind);\n this.relayer = relayerResolver(\n this.swapInfo.tokenIn,\n this.swapInfo.tokenOut,\n this.chainId\n );\n }\n\n setFunds(sender: string, recipient?: string): void {\n this.funds = {\n sender,\n recipient: recipient || sender,\n fromInternalBalance: false,\n toInternalBalance: false,\n };\n }\n\n /**\n * @param deadline block timestamp\n */\n setDeadline(deadline: BigNumber): void {\n this.deadline = deadline.toString();\n }\n\n get amount(): BigNumber {\n return this.kind === SwapType.SwapExactOut\n ? this.swapInfo.amountOutForLimits.amount\n : this.swapInfo.amountInForLimits.amount;\n }\n\n /**\n * Calculates the limit for token amount.\n * https://dev.balancer.fi/guides/swaps/single-swaps\n * https://dev.balancer.fi/resources/swaps/single-swap\n *\n * For swap:\n * The meaning of limit depends on the value of kind\n * GIVEN_IN: The minimum amount of tokens we would accept to receive from the swap.\n * GIVEN_OUT: The maximum amount of tokens we would be sending to swap.\n *\n * @param maxSlippage [bps], eg: 1 === 0.01%, 100 === 1%\n */\n setLimits(maxSlippage: number): void {\n this.limit =\n this.kind === SwapType.SwapExactIn\n ? this.swapInfo.amountOutForLimits.min(maxSlippage).toString()\n : this.swapInfo.amountInForLimits.max(maxSlippage).toString();\n }\n\n get singleSwap(): SingleSwap {\n const poolId = this.swapInfo.swaps[0].poolId;\n const kind = this.kind;\n const assetIn = this.swapInfo.tokenInForSwaps;\n const assetOut = this.swapInfo.tokenOutFromSwaps;\n const amount = this.amount.toString();\n const userData = '0x';\n\n return {\n poolId,\n kind,\n assetIn,\n assetOut,\n amount,\n userData,\n };\n }\n\n attributes(): Swap {\n if (!this.funds || !this.limit || !this.deadline) {\n throw new Error('Uninitialized arguments');\n }\n\n // TODO: Raise errors when some parameters are missing\n let attrs: Swap = {\n request: this.singleSwap,\n funds: this.funds,\n limit: this.limit,\n deadline: this.deadline,\n };\n\n // TODO: Call this logic from a relayer module maybe? Do we actually need to do that?\n // additional parameters on a contract:\n // https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/standalone-utils/contracts/relayer/VaultActions.sol#L44\n const fragment = this.fragment();\n if (fragment[0].inputs && fragment[0].inputs?.length > 4) {\n attrs = {\n ...attrs,\n value: '0',\n outputReference: '0',\n };\n }\n\n return attrs;\n }\n\n data(): string {\n const contractInterface = new Interface(this.fragment());\n\n return contractInterface.encodeFunctionData(\n 'swap',\n Object.values(this.attributes())\n );\n }\n\n value(maxSlippage: number): BigNumber {\n let amount = BigNumber.from(0);\n if (this.swapInfo.tokenIn === AddressZero)\n amount =\n this.kind === SwapType.SwapExactIn\n ? this.swapInfo.amountIn\n : this.swapInfo.amountInForLimits.max(maxSlippage);\n return amount;\n }\n\n to(): string {\n return this.relayer.address;\n }\n\n private fragment(): JsonFragment[] {\n return swapFragment(this.relayer).filter(\n (f) => f.name === this.functionName\n );\n }\n}\n\nexport { SingleSwapBuilder };\n","import { BigNumber, BigNumberish } from '@ethersproject/bignumber';\nimport { BatchSwap, FundManagement, SwapType } from '../types';\nimport { Interface, JsonFragment } from '@ethersproject/abi';\nimport { SwapInfo } from '@defiverse/sor';\nimport { SDKSwapInfo, decorateSorSwapInfo } from './swap_info_decorator';\nimport { AddressZero } from '@ethersproject/constants';\nimport { swapFragment, relayerResolver, SwapRelayer } from './swap_utils';\n\nclass BatchSwapBuilder {\n private swapInfo: SDKSwapInfo;\n funds?: FundManagement;\n limits?: BigNumberish[];\n deadline?: BigNumberish;\n relayer: SwapRelayer;\n readonly functionName = 'batchSwap';\n\n /**\n * Building swap transaction data\n *\n * @param swapInfo SOR result\n * @param kind\n */\n constructor(\n swapInfo: SwapInfo,\n private readonly kind: SwapType,\n private readonly chainId: number\n ) {\n this.swapInfo = decorateSorSwapInfo(swapInfo, kind);\n this.relayer = relayerResolver(\n this.swapInfo.tokenIn,\n this.swapInfo.tokenOut,\n this.chainId\n );\n }\n\n setFunds(sender: string, recipient?: string): void {\n this.funds = {\n sender,\n recipient: recipient || sender,\n fromInternalBalance: false,\n toInternalBalance: false,\n };\n }\n\n /**\n * @param deadline block timestamp\n */\n setDeadline(deadline: BigNumber): void {\n this.deadline = deadline;\n }\n\n /**\n * Given IN it's the minimum amount we are willing to accept.\n * Given OUT it's the fixed amount defined as output.\n */\n minAmountOut(maxSlippage: number): BigNumber {\n return this.kind === SwapType.SwapExactIn\n ? this.swapInfo.amountOutForLimits.min(maxSlippage)\n : this.swapInfo.amountOutForLimits.amount;\n }\n\n /**\n * Given IN it's the fixed amount we define as input.\n * Given OUT it's the maximum amount we are willing to pay for the request.\n */\n maxAmountIn(maxSlippage: number): BigNumber {\n return this.kind === SwapType.SwapExactOut\n ? this.swapInfo.amountInForLimits.max(maxSlippage)\n : this.swapInfo.amountInForLimits.amount;\n }\n\n /**\n * Calculates limits for token amount.\n * Maximum number of tokens to send is a positive number\n * Minimum amount of tokens to receive is a negative number\n * https://dev.balancer.fi/guides/swaps/batch-swaps\n * https://dev.balancer.fi/resources/swaps/batch-swaps#multi-hop-examples\n *\n * For batchSwap:\n * An array of of the maximum net amounts of each asset which can be taken to perform the swap.\n * Should the total trade require more than limits[i] tokens to be taken from sender for any i\n * then the transaction shall fail.\n *\n * @param maxSlippage [bps], eg: 1 === 0.01%, 100 === 1%\n */\n setLimits(maxSlippage: number): void {\n // TODO: This implementation handles only a single input. We might want to extend it for multiple token inputs\n this.limits = this.swapInfo.tokenAddresses\n .map((token) => {\n let amount = BigNumber.from(0);\n if (token === this.swapInfo.tokenInForSwaps) {\n amount = this.maxAmountIn(maxSlippage);\n }\n if (token === this.swapInfo.tokenOutFromSwaps) {\n amount = this.minAmountOut(maxSlippage).mul(-1);\n }\n return amount;\n })\n .map((limit) => limit.toString().split('.')[0]);\n }\n\n attributes(): BatchSwap {\n // TODO: Raise errors when some parameters are missing\n if (!this.funds || !this.limits || !this.deadline) {\n throw new Error('Uninitialized arguments');\n }\n\n let attrs: BatchSwap = {\n kind: this.kind,\n swaps: this.swapInfo.swaps,\n assets: this.swapInfo.tokenAddresses,\n funds: this.funds,\n limits: this.limits,\n deadline: this.deadline,\n };\n\n const fragment = this.fragment();\n\n // TODO: Call this logic from a relayer module maybe? Do we actually need to do that?\n // additional parameters on a contract:\n // https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/standalone-utils/contracts/relayer/VaultActions.sol#L67\n if (fragment[0].inputs && fragment[0].inputs?.length > 6) {\n attrs = {\n ...attrs,\n value: '0',\n outputReferences: [],\n };\n }\n\n return attrs;\n }\n\n data(): string {\n const contractInterface = new Interface(this.fragment());\n\n return contractInterface.encodeFunctionData(\n 'batchSwap',\n Object.values(this.attributes())\n );\n }\n\n value(maxSlippage: number): BigNumber {\n let amount = BigNumber.from(0);\n if (this.swapInfo.tokenIn === AddressZero)\n amount = this.maxAmountIn(maxSlippage);\n return amount;\n }\n\n to(): string {\n return this.relayer.address;\n }\n\n private fragment(): JsonFragment[] {\n return swapFragment(this.relayer).filter(\n (f) => f.name === this.functionName\n );\n }\n}\n\nexport { BatchSwapBuilder };\n","import { SOR, SubgraphPoolBase, SwapInfo, SwapTypes } from '@defiverse/sor';\nimport { Vault__factory, Vault } from '@balancer-labs/typechain';\nimport {\n BatchSwap,\n QuerySimpleFlashSwapParameters,\n QuerySimpleFlashSwapResponse,\n QueryWithSorInput,\n QueryWithSorOutput,\n SimpleFlashSwapParameters,\n FindRouteParameters,\n BuildTransactionParameters,\n SwapAttributes,\n SwapType,\n} from './types';\nimport {\n queryBatchSwap,\n queryBatchSwapWithSor,\n getSorSwapInfo,\n} from './queryBatchSwap';\nimport { balancerVault } from '@/lib/constants/config';\nimport { getLimitsForSlippage } from './helpers';\nimport { BalancerSdkConfig } from '@/types';\nimport { SwapInput } from './types';\nimport { Sor } from '@/modules/sor/sor.module';\nimport {\n convertSimpleFlashSwapToBatchSwapParameters,\n querySimpleFlashSwap,\n} from './flashSwap';\nimport {\n SingleSwapBuilder,\n BatchSwapBuilder,\n} from '@/modules/swaps/swap_builder';\n\nexport class Swaps {\n readonly sor: SOR;\n chainId: number;\n vaultContract: Vault;\n\n // TODO: sorOrConfig - let's make it more predictable and always pass configuration explicitly\n constructor(sorOrConfig: SOR | BalancerSdkConfig) {\n if (sorOrConfig instanceof SOR) {\n this.sor = sorOrConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.chainId = (<any>this.sor.provider)['_network']['chainId'];\n } else {\n this.sor = new Sor(sorOrConfig);\n this.chainId = sorOrConfig.network as number;\n }\n\n this.vaultContract = Vault__factory.connect(\n balancerVault,\n this.sor.provider\n );\n }\n\n static getLimitsForSlippage(\n tokensIn: string[],\n tokensOut: string[],\n swapType: SwapType,\n deltas: string[],\n assets: string[],\n slippage: string\n ): string[] {\n // TO DO - Check best way to do this?\n const limits = getLimitsForSlippage(\n tokensIn,\n tokensOut,\n swapType,\n deltas,\n assets,\n slippage\n );\n\n return limits.map((l) => l.toString());\n }\n\n /**\n * Uses SOR to find optimal route for a trading pair and amount\n *\n * @param FindRouteParameters\n * @param FindRouteParameters.tokenIn Address\n * @param FindRouteParameters.tokenOut Address\n * @param FindRouteParameters.amount BigNumber with a trade amount\n * @param FindRouteParameters.gasPrice BigNumber current gas price\n * @param FindRouteParameters.maxPools number of pool included in path\n * @returns Best trade route information\n */\n async findRouteGivenIn({\n tokenIn,\n tokenOut,\n amount,\n gasPrice,\n maxPools = 4,\n }: FindRouteParameters): Promise<SwapInfo> {\n return this.sor.getSwaps(tokenIn, tokenOut, SwapTypes.SwapExactIn, amount, {\n gasPrice,\n maxPools,\n });\n }\n\n /**\n * Uses SOR to find optimal route for a trading pair and amount\n *\n * @param FindRouteParameters\n * @param FindRouteParameters.tokenIn Address\n * @param FindRouteParameters.tokenOut Address\n * @param FindRouteParameters.amount BigNumber with a trade amount\n * @param FindRouteParameters.gasPrice BigNumber current gas price\n * @param FindRouteParameters.maxPools number of pool included in path\n * @returns Best trade route information\n */\n async findRouteGivenOut({\n tokenIn,\n tokenOut,\n amount,\n gasPrice,\n maxPools,\n }: FindRouteParameters): Promise<SwapInfo> {\n return this.sor.getSwaps(\n tokenIn,\n tokenOut,\n SwapTypes.SwapExactOut,\n amount,\n {\n gasPrice,\n maxPools,\n }\n );\n }\n\n /**\n * Uses SOR to find optimal route for a trading pair and amount\n *\n * @param BuildTransactionParameters\n * @param BuildTransactionParameters.userAddress Address\n * @param BuildTransactionParameters.swapInfo result of route finding\n * @param BuildTransactionParameters.kind 0 - givenIn, 1 - givenOut\n * @param BuildTransactionParameters.deadline BigNumber block timestamp\n * @param BuildTransactionParameters.maxSlippage [bps], eg: 1 === 0.01%, 100 === 1%\n * @returns transaction request ready to send with signer.sendTransaction\n */\n buildSwap({\n userAddress,\n recipient,\n swapInfo,\n kind,\n deadline,\n maxSlippage,\n }: BuildTransactionParameters): SwapAttributes {\n if (!this.chainId) throw 'Missing network configuration';\n\n // one vs batch (gas cost optimisation when using single swap)\n const builder =\n swapInfo.swaps.length > 1\n ? new BatchSwapBuilder(swapInfo, kind, this.chainId)\n : new SingleSwapBuilder(swapInfo, kind, this.chainId);\n builder.setFunds(userAddress, recipient);\n builder.setDeadline(deadline);\n builder.setLimits(maxSlippage);\n\n const to = builder.to();\n const { functionName } = builder;\n const attributes = builder.attributes();\n const data = builder.data();\n const value = builder.value(maxSlippage);\n\n return { to, functionName, attributes, data, value };\n }\n\n /**\n * Encode batchSwap in an ABI byte string\n *\n * [See method for a batchSwap](https://dev.balancer.fi/references/contracts/apis/the-vault#batch-swaps).\n *\n * _NB: This method doesn't execute a batchSwap -- it returns an [ABI byte string](https://docs.soliditylang.org/en/latest/abi-spec.html)\n * containing the data of the function call on a contract, which can then be sent to the network to be executed.\n * (ex. [sendTransaction](https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#sendtransaction)).\n *\n * @param {BatchSwap} batchSwap - BatchSwap information used for query.\n * @param {SwapType} batchSwap.kind - either exactIn or exactOut\n * @param {BatchSwapSteps[]} batchSwap.swaps - sequence of swaps\n * @param {string[]} batchSwap.assets - array contains the addresses of all assets involved in the swaps\n * @param {FundManagement} batchSwap.funds - object containing information about where funds should be taken/sent\n * @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\n * @param {string} batchSwap.deadline - time (in Unix timestamp) after which it will no longer attempt to make a trade\n * @returns {string} encodedBatchSwapData - Returns an ABI byte string containing the data of the function call on a contract\n */\n static encodeBatchSwap(batchSwap: BatchSwap): string {\n const vaultInterface = Vault__factory.createInterface();\n\n return vaultInterface.encodeFunctionData('batchSwap', [\n batchSwap.kind,\n batchSwap.swaps,\n batchSwap.assets,\n batchSwap.funds,\n batchSwap.limits,\n batchSwap.deadline,\n ]);\n }\n\n /**\n * Encode simple flash swap into a ABI byte string\n *\n * A \"simple\" flash swap is an arbitrage executed with only two tokens and two pools,\n * swapping in the first pool and then back in the second pool for a profit. For more\n * complex flash swaps, you will have to use the batch swap method.\n *\n * Learn more: A [Flash Swap](https://dev.balancer.fi/resources/swaps/flash-swaps).\n *\n * @param {SimpleFlashSwapParameters} params - BatchSwap information used for query.\n * @param {string} params.flashLoanAmount - initial input amount for the flash loan (first asset)\n * @param {string[]} params.poolIds - array of Balancer pool ids\n * @param {string[]} params.assets - array of token addresses\n * @param {string} params.walletAddress - array of token addresses\n * @returns {string} encodedBatchSwapData - Returns an ABI byte string containing the data of the function call on a contract\n */\n static encodeSimpleFlashSwap(params: SimpleFlashSwapParameters): string {\n return this.encodeBatchSwap(\n convertSimpleFlashSwapToBatchSwapParameters(params)\n );\n }\n\n /**\n * fetchPools saves updated pools data to SOR internal onChainBalanceCache.\n * @param {SubgraphPoolBase[]} [poolsData=[]] If poolsData passed uses this as pools source otherwise fetches from config.subgraphUrl.\n * @param {boolean} [isOnChain=true] If isOnChain is true will retrieve all required onChain data via multicall otherwise uses subgraph values.\n * @returns {boolean} Boolean indicating whether pools data was fetched correctly (true) or not (false).\n */\n async fetchPools(): Promise<boolean> {\n return this.sor.fetchPools();\n }\n\n public getPools(): SubgraphPoolBase[] {\n return this.sor.getPools();\n }\n\n /**\n * queryBatchSwap simulates a call to `batchSwap`, returning an array of Vault asset deltas.\n * @param batchSwap - BatchSwap information used for query.\n * @param {SwapType} batchSwap.kind - either exactIn or exactOut.\n * @param {BatchSwapStep[]} batchSwap.swaps - sequence of swaps.\n * @param {string[]} batchSwap.assets - array contains the addresses of all assets involved in the swaps.\n * @returns {Promise<string[]>} Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the\n * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at\n * the same index in the `assets` array.\n */\n async queryBatchSwap(\n batchSwap: Pick<BatchSwap, 'kind' | 'swaps' | 'assets'>\n ): Promise<string[]> {\n return await queryBatchSwap(\n this.vaultContract,\n batchSwap.kind,\n batchSwap.swaps,\n batchSwap.assets\n );\n }\n\n /**\n * Uses SOR to create and query a batchSwap.\n * @param {QueryWithSorInput} queryWithSor - Swap information used for querying using SOR.\n * @param {string[]} queryWithSor.tokensIn - Array of addresses of assets in.\n * @param {string[]} queryWithSor.tokensOut - Array of addresses of assets out.\n * @param {SwapType} queryWithSor.swapType - Type of Swap, ExactIn/Out.\n * @param {string[]} queryWithSor.amounts - Array of amounts used in swap.\n * @param {FetchPoolsInput} queryWithSor.fetchPools - Set whether SOR will fetch updated pool info.\n * @returns {Promise<QueryWithSorOutput>} Returns amount of tokens swaps along with swap and asset info that can be submitted to a batchSwap call.\n */\n async queryBatchSwapWithSor(\n queryWithSor: QueryWithSorInput\n ): Promise<QueryWithSorOutput> {\n return await queryBatchSwapWithSor(\n this.sor,\n this.vaultContract,\n queryWithSor\n );\n }\n\n /**\n * Simple interface to test if a simple flash swap is valid and see potential profits.\n *\n * A \"simple\" flash swap is an arbitrage executed with only two tokens and two pools,\n * swapping in the first pool and then back in the second pool for a profit. For more\n * complex flash swaps, you will have to use the batch swap method.\n *\n * Learn more: A [Flash Swap](https://dev.balancer.fi/resources/swaps/flash-swaps).\n *\n * _NB: This method doesn't execute a flashSwap\n *\n * @param {SimpleFlashSwapParameters} params - BatchSwap information used for query.\n * @param {string} params.flashLoanAmount - initial input amount for the flash loan (first asset)\n * @param {string[]} params.poolIds - array of Balancer pool ids\n * @param {string[]} params.assets - array of token addresses\n * @returns {Promise<{profits: Record<string, string>, isProfitable: boolean}>} Returns an ethersjs transaction response\n */\n async querySimpleFlashSwap(\n params: Omit<QuerySimpleFlashSwapParameters, 'vaultContract'>\n ): Promise<QuerySimpleFlashSwapResponse> {\n return await querySimpleFlashSwap({\n ...params,\n vaultContract: this.vaultContract,\n });\n }\n\n /**\n * Use SOR to get swapInfo for tokenIn<>tokenOut.\n * @param {SwapInput} swapInput - Swap information used for querying using SOR.\n * @param {string} swapInput.tokenIn - Addresse of asset in.\n * @param {string} swapInput.tokenOut - Addresse of asset out.\n * @param {SwapType} swapInput.swapType - Type of Swap, ExactIn/Out.\n * @param {string} swapInput.amount - Amount used in swap.\n * @returns {Promise<SwapInfo>} SOR swap info.\n */\n async getSorSwap(swapInput: SwapInput): Promise<SwapInfo> {\n return await getSorSwapInfo(\n swapInput.tokenIn,\n swapInput.tokenOut,\n swapInput.swapType,\n swapInput.amount,\n this.sor\n );\n }\n}\n","import { JsonRpcSigner } from '@ethersproject/providers';\nimport { BigNumberish, BigNumber } from '@ethersproject/bignumber';\nimport { Interface } from '@ethersproject/abi';\nimport { MaxUint256, WeiPerEther, Zero } from '@ethersproject/constants';\nimport { Vault } from '@balancer-labs/typechain';\n\nimport { Swaps } from '@/modules/swaps/swaps.module';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport {\n EncodeBatchSwapInput,\n EncodeWrapAaveDynamicTokenInput,\n EncodeUnwrapAaveStaticTokenInput,\n OutputReference,\n EncodeExitPoolInput,\n EncodeJoinPoolInput,\n ExitAndBatchSwapInput,\n ExitPoolData,\n JoinPoolData,\n} from './types';\nimport {\n TransactionData,\n ExitPoolRequest,\n JoinPoolRequest,\n BalancerSdkConfig,\n} from '@/types';\nimport {\n SwapType,\n FundManagement,\n BatchSwapStep,\n FetchPoolsInput,\n} from '../swaps/types';\nimport { SubgraphPoolBase } from '@defiverse/sor';\nimport { RelayerAuthorization } from '@/lib/utils';\n\nimport relayerLibraryAbi from '@/lib/abi/BatchRelayerLibrary.json';\n\nexport * from './types';\n\nconst relayerLibrary = new Interface(relayerLibraryAbi);\n\nexport class Relayer {\n private readonly swaps: Swaps;\n\n static CHAINED_REFERENCE_TEMP_PREFIX = 'ba10'; // Temporary reference: it is deleted after a read.\n static CHAINED_REFERENCE_READONLY_PREFIX = 'ba11'; // Read-only reference: it is not deleted after a read.\n\n constructor(swapsOrConfig: Swaps | BalancerSdkConfig) {\n if (swapsOrConfig instanceof Swaps) {\n this.swaps = swapsOrConfig;\n } else {\n this.swaps = new Swaps(swapsOrConfig);\n }\n }\n\n /**\n * Returns true if `amount` is not actually an amount, but rather a chained reference.\n */\n static isChainedReference(amount: string): boolean {\n const amountBn = BigNumber.from(amount);\n const mask = BigNumber.from(\n '0xfff0000000000000000000000000000000000000000000000000000000000000'\n );\n const readonly =\n '0xba10000000000000000000000000000000000000000000000000000000000000';\n const check = amountBn.toBigInt() & mask.toBigInt();\n return readonly === BigNumber.from(check)._hex.toString();\n }\n\n static encodeApproveVault(tokenAddress: string, maxAmount: string): string {\n return relayerLibrary.encodeFunctionData('approveVault', [\n tokenAddress,\n maxAmount,\n ]);\n }\n\n static encodeSetRelayerApproval(\n relayerAdress: string,\n approved: boolean,\n authorisation: string\n ): string {\n return relayerLibrary.encodeFunctionData('setRelayerApproval', [\n relayerAdress,\n approved,\n authorisation,\n ]);\n }\n\n static encodeGaugeWithdraw(\n gaugeAddress: string,\n sender: string,\n recipient: string,\n amount: string\n ): string {\n return relayerLibrary.encodeFunctionData('gaugeWithdraw', [\n gaugeAddress,\n sender,\n recipient,\n amount,\n ]);\n }\n\n static encodeGaugeDeposit(\n gaugeAddress: string,\n sender: string,\n recipient: string,\n amount: string\n ): string {\n return relayerLibrary.encodeFunctionData('gaugeDeposit', [\n gaugeAddress,\n sender,\n recipient,\n amount,\n ]);\n }\n\n static encodeBatchSwap(params: EncodeBatchSwapInput): string {\n return relayerLibrary.encodeFunctionData('batchSwap', [\n params.swapType,\n params.swaps,\n params.assets,\n params.funds,\n params.limits,\n params.deadline,\n params.value,\n params.outputReferences,\n ]);\n }\n\n static encodeExitPool(params: EncodeExitPoolInput): string {\n return relayerLibrary.encodeFunctionData('exitPool', [\n params.poolId,\n params.poolKind,\n params.sender,\n params.recipient,\n params.exitPoolRequest,\n params.outputReferences,\n ]);\n }\n\n static encodeJoinPool(params: EncodeJoinPoolInput): string {\n return relayerLibrary.encodeFunctionData('joinPool', [\n params.poolId,\n params.kind,\n params.sender,\n params.recipient,\n params.joinPoolRequest,\n params.value,\n params.outputReference,\n ]);\n }\n\n static encodeWrapAaveDynamicToken(\n params: EncodeWrapAaveDynamicTokenInput\n ): string {\n return relayerLibrary.encodeFunctionData('wrapAaveDynamicToken', [\n params.staticToken,\n params.sender,\n params.recipient,\n params.amount,\n params.fromUnderlying,\n params.outputReference,\n ]);\n }\n\n static encodeUnwrapAaveStaticToken(\n params: EncodeUnwrapAaveStaticTokenInput\n ): string {\n return relayerLibrary.encodeFunctionData('unwrapAaveStaticToken', [\n params.staticToken,\n params.sender,\n params.recipient,\n params.amount,\n params.toUnderlying,\n params.outputReferences,\n ]);\n }\n\n static encodePeekChainedReferenceValue(reference: BigNumberish): string {\n return relayerLibrary.encodeFunctionData('peekChainedReferenceValue', [\n reference,\n ]);\n }\n\n static toChainedReference(key: BigNumberish, isTemporary = true): BigNumber {\n const prefix = isTemporary\n ? Relayer.CHAINED_REFERENCE_TEMP_PREFIX\n : Relayer.CHAINED_REFERENCE_READONLY_PREFIX;\n // The full padded prefix is 66 characters long, with 64 hex characters and the 0x prefix.\n const paddedPrefix = `0x${prefix}${'0'.repeat(64 - prefix.length)}`;\n return BigNumber.from(paddedPrefix).add(key);\n }\n\n static fromChainedReference(ref: string, isTemporary = true): BigNumber {\n const prefix = isTemporary\n ? Relayer.CHAINED_REFERENCE_TEMP_PREFIX\n : Relayer.CHAINED_REFERENCE_READONLY_PREFIX;\n // The full padded prefix is 66 characters long, with 64 hex characters and the 0x prefix.\n const paddedPrefix = `0x${prefix}${'0'.repeat(64 - prefix.length)}`;\n return BigNumber.from(ref).sub(BigNumber.from(paddedPrefix));\n }\n\n static constructExitCall(params: ExitPoolData): string {\n const {\n assets,\n minAmountsOut,\n userData,\n toInternalBalance,\n poolId,\n poolKind,\n sender,\n recipient,\n outputReferences,\n } = params;\n\n const exitPoolRequest: ExitPoolRequest = {\n assets,\n minAmountsOut,\n userData,\n toInternalBalance,\n };\n\n const exitPoolInput: EncodeExitPoolInput = {\n poolId,\n poolKind,\n sender,\n recipient,\n outputReferences,\n exitPoolRequest,\n };\n\n const exitEncoded = Relayer.encodeExitPool(exitPoolInput);\n return exitEncoded;\n }\n\n static constructJoinCall(params: JoinPoolData): string {\n const {\n assets,\n maxAmountsIn,\n userData,\n fromInternalBalance,\n poolId,\n kind,\n sender,\n recipient,\n value,\n outputReference,\n } = params;\n\n const joinPoolRequest: JoinPoolRequest = {\n assets,\n maxAmountsIn,\n userData,\n fromInternalBalance,\n };\n\n const joinPoolInput: EncodeJoinPoolInput = {\n poolId,\n kind,\n sender,\n recipient,\n value,\n outputReference,\n joinPoolRequest,\n };\n\n const joinEncoded = Relayer.encodeJoinPool(joinPoolInput);\n return joinEncoded;\n }\n\n /**\n * fetchPools saves updated pools data to SOR internal onChainBalanceCache.\n * @param {SubgraphPoolBase[]} [poolsData=[]] If poolsData passed uses this as pools source otherwise fetches from config.subgraphUrl.\n * @param {boolean} [isOnChain=true] If isOnChain is true will retrieve all required onChain data via multicall otherwise uses subgraph values.\n * @returns {boolean} Boolean indicating whether pools data was fetched correctly (true) or not (false).\n */\n async fetchPools(): Promise<boolean> {\n return this.swaps.fetchPools();\n }\n\n public getPools(): SubgraphPoolBase[] {\n return this.swaps.getPools();\n }\n\n /**\n * exitPoolAndBatchSwap Chains poolExit with batchSwap to final tokens.\n * @param {ExitAndBatchSwapInput} params\n * @param {string} exiter - Address used to exit pool.\n * @param {string} swapRecipient - Address that receives final tokens.\n * @param {string} poolId - Id of pool being exited.\n * @param {string[]} exitTokens - Array containing addresses of tokens to receive after exiting pool. (must have the same length and order as the array returned by `getPoolTokens`.)\n * @param {string} userData - Encoded exitPool data.\n * @param {string[]} expectedAmountsOut - Expected amounts of exitTokens to receive when exiting pool.\n * @param {string[]} finalTokensOut - Array containing the addresses of the final tokens out.\n * @param {string} slippage - Slippage to be applied to swap section. i.e. 5%=50000000000000000.\n * @param {FetchPoolsInput} fetchPools - Set whether SOR will fetch updated pool info.\n * @returns Transaction data with calldata. Outputs.amountsOut has amounts of finalTokensOut returned.\n */\n async exitPoolAndBatchSwap(\n params: ExitAndBatchSwapInput\n ): Promise<TransactionData> {\n const slippageAmountNegative = WeiPerEther.sub(\n BigNumber.from(params.slippage)\n );\n // Set min amounts out of exit pool based on slippage\n const minAmountsOut = params.expectedAmountsOut.map((amt) =>\n BigNumber.from(amt)\n .mul(slippageAmountNegative)\n .div(WeiPerEther)\n .toString()\n );\n\n // Output of exit is used as input to swaps\n const outputReferences: OutputReference[] = [];\n params.exitTokens.forEach((asset, i) => {\n const key = Relayer.toChainedReference(i);\n outputReferences.push({\n index: i,\n key: key,\n });\n });\n\n const exitCall = Relayer.constructExitCall({\n assets: params.exitTokens,\n minAmountsOut,\n userData: params.userData,\n toInternalBalance: true, // Creates exitPool request with exit to internal balance to save gas for following swaps\n poolId: params.poolId,\n poolKind: 0, // This will always be 0 to match supported Relayer types\n sender: params.exiter,\n recipient: params.exiter,\n outputReferences: outputReferences,\n exitPoolRequest: {} as ExitPoolRequest,\n });\n\n // Use swapsService to get swap info for exitTokens>finalTokens\n // This will give batchSwap swap paths\n // Amounts out will be worst case amounts\n const queryResult = await this.swaps.queryBatchSwapWithSor({\n tokensIn: params.exitTokens,\n tokensOut: params.finalTokensOut,\n swapType: SwapType.SwapExactIn,\n amounts: minAmountsOut, // Use minAmountsOut as input to swap to account for slippage\n fetchPools: params.fetchPools,\n });\n\n // This is a safety check to avoid issues when a swap path exists with 0 value\n if (queryResult.returnAmounts.includes('0'))\n throw new BalancerError(BalancerErrorCode.SWAP_ZERO_RETURN_AMOUNT);\n\n // Update swap amounts with ref outputs from exitPool\n queryResult.swaps.forEach((swap) => {\n const token = queryResult.assets[swap.assetInIndex];\n const index = params.exitTokens.indexOf(token);\n if (index !== -1) swap.amount = outputReferences[index].key.toString();\n });\n\n // const tempDeltas = ['10096980', '0', '0', '10199896999999482390', '0']; // Useful for debug\n\n // Replace tokenIn delta for swaps with amount + slippage.\n // This gives tolerance for limit incase amount out of exitPool is larger min,\n const slippageAmountPositive = WeiPerEther.add(params.slippage);\n params.exitTokens.forEach((exitToken, i) => {\n const index = queryResult.assets\n .map((elem) => elem.toLowerCase())\n .indexOf(exitToken.toLowerCase());\n if (index !== -1) {\n queryResult.deltas[index] = BigNumber.from(params.expectedAmountsOut[i])\n .mul(slippageAmountPositive)\n .div(WeiPerEther)\n .toString();\n }\n });\n\n // Creates limit array.\n // Slippage set to 0. Already accounted for as swap used amounts out of pool with worst case slippage.\n const limits = Swaps.getLimitsForSlippage(\n params.exitTokens, // tokensIn\n params.finalTokensOut, // tokensOut\n SwapType.SwapExactIn,\n queryResult.deltas, // tempDeltas // Useful for debug\n queryResult.assets,\n '0'\n );\n\n // Creates fund management using internal balance as source of tokens\n const funds: FundManagement = {\n sender: params.exiter,\n recipient: params.swapRecipient,\n fromInternalBalance: true,\n toInternalBalance: false,\n };\n\n const encodedBatchSwap = Relayer.encodeBatchSwap({\n swapType: SwapType.SwapExactIn,\n swaps: queryResult.swaps,\n assets: queryResult.assets,\n funds: funds,\n limits: limits.map((l) => l.toString()),\n deadline: MaxUint256,\n value: '0',\n outputReferences: [],\n });\n\n // Return amounts from swap\n const calls = [exitCall, encodedBatchSwap];\n return {\n function: 'multicall',\n params: calls,\n outputs: {\n amountsOut: queryResult.returnAmounts,\n },\n };\n }\n\n /**\n * swapUnwrapAaveStaticExactIn Finds swaps for tokenIn>wrapped Aave static tokens and chains with unwrap to underlying stable.\n * @param {string[]} tokensIn - array to token addresses for swapping as tokens in.\n * @param {string[]} aaveStaticTokens - array contains the addresses of the Aave static tokens that tokenIn will be swapped to. These will be unwrapped.\n * @param {string[]} amountsIn - amounts to be swapped for each token in.\n * @param {string[]} rates - The rate used to convert wrappedToken to underlying.\n * @param {FundManagement} funds - Funding info for swap. Note - recipient should be relayer and sender should be caller.\n * @param {string} slippage - Slippage to be applied to swap section. i.e. 5%=50000000000000000.\n * @param {FetchPoolsInput} fetchPools - Set whether SOR will fetch updated pool info.\n * @returns Transaction data with calldata. Outputs.amountsOut has final amounts out of unwrapped tokens.\n */\n async swapUnwrapAaveStaticExactIn(\n tokensIn: string[],\n aaveStaticTokens: string[],\n amountsIn: string[],\n rates: string[],\n funds: FundManagement,\n slippage: string,\n fetchPools: FetchPoolsInput = {\n fetchPools: true,\n fetchOnChain: false,\n }\n ): Promise<TransactionData> {\n // Use swapsService to get swap info for tokensIn>wrappedTokens\n const queryResult = await this.swaps.queryBatchSwapWithSor({\n tokensIn,\n tokensOut: aaveStaticTokens,\n swapType: SwapType.SwapExactIn,\n amounts: amountsIn,\n fetchPools,\n });\n\n // This is a safety check to avoid issues when a swap path exists with 0 value\n if (queryResult.returnAmounts.includes('0'))\n throw new BalancerError(BalancerErrorCode.SWAP_ZERO_RETURN_AMOUNT);\n\n // Gets limits array for tokensIn>wrappedTokens based on input slippage\n const limits = Swaps.getLimitsForSlippage(\n tokensIn, // tokensIn\n aaveStaticTokens, // tokensOut\n SwapType.SwapExactIn,\n queryResult.deltas,\n queryResult.assets,\n slippage\n );\n\n const calls = this.encodeSwapUnwrap(\n aaveStaticTokens,\n SwapType.SwapExactIn,\n queryResult.swaps,\n queryResult.assets,\n funds,\n limits\n );\n\n const amountsUnwrapped = queryResult.returnAmounts.map(\n (amountWrapped, i) => {\n const amountUnwrapped = BigNumber.from(amountWrapped)\n .abs()\n .mul(rates[i])\n .div(WeiPerEther);\n\n // This is a safety check to avoid issues when a swap path exists with 0 value\n if (!amountUnwrapped.gt(Zero))\n throw new BalancerError(BalancerErrorCode.UNWRAP_ZERO_AMOUNT);\n\n return amountUnwrapped.toString();\n }\n );\n\n return {\n function: 'multicall',\n params: calls,\n outputs: {\n amountsOut: amountsUnwrapped,\n },\n };\n }\n\n /**\n * swapUnwrapAaveStaticExactOut Finds swaps for tokenIn>wrapped Aave static tokens and chains with unwrap to underlying stable.\n * @param {string[]} tokensIn - array to token addresses for swapping as tokens in.\n * @param {string[]} aaveStaticTokens - array contains the addresses of the Aave static tokens that tokenIn will be swapped to. These will be unwrapped.\n * @param {string[]} amountsUnwrapped - amounts of unwrapped tokens out.\n * @param {string[]} rates - The rate used to convert wrappedToken to underlying.\n * @param {FundManagement} funds - Funding info for swap. Note - recipient should be relayer and sender should be caller.\n * @param {string} slippage - Slippage to be applied to swap section. i.e. 5%=50000000000000000.\n * @param {FetchPoolsInput} fetchPools - Set whether SOR will fetch updated pool info.\n * @returns Transaction data with calldata. Outputs.amountsIn has the amounts of tokensIn.\n */\n async swapUnwrapAaveStaticExactOut(\n tokensIn: string[],\n aaveStaticTokens: string[],\n amountsUnwrapped: string[],\n rates: string[],\n funds: FundManagement,\n slippage: string,\n fetchPools: FetchPoolsInput = {\n fetchPools: true,\n fetchOnChain: false,\n }\n ): Promise<TransactionData> {\n const amountsWrapped = amountsUnwrapped.map((amountInwrapped, i) => {\n const amountWrapped = BigNumber.from(amountInwrapped)\n .mul(WeiPerEther)\n .div(rates[i]);\n\n // This is a safety check to avoid issues when a swap path exists with 0 value\n if (!amountWrapped.gt(Zero))\n throw new BalancerError(BalancerErrorCode.WRAP_ZERO_AMOUNT);\n\n return amountWrapped.toString();\n });\n\n // Use swapsService to get swap info for tokensIn>wrappedTokens\n const queryResult = await this.swaps.queryBatchSwapWithSor({\n tokensIn,\n tokensOut: aaveStaticTokens,\n swapType: SwapType.SwapExactOut,\n amounts: amountsWrapped,\n fetchPools,\n });\n\n // This is a safety check to avoid issues when a swap path exists with 0 value\n if (queryResult.returnAmounts.includes('0'))\n throw new BalancerError(BalancerErrorCode.SWAP_ZERO_RETURN_AMOUNT);\n\n // Gets limits array for tokensIn>wrappedTokens based on input slippage\n const limits = Swaps.getLimitsForSlippage(\n tokensIn, // tokensIn\n aaveStaticTokens, // tokensOut\n SwapType.SwapExactOut,\n queryResult.deltas,\n queryResult.assets,\n slippage\n );\n\n const calls = this.encodeSwapUnwrap(\n aaveStaticTokens,\n SwapType.SwapExactOut,\n queryResult.swaps,\n queryResult.assets,\n funds,\n limits\n );\n\n return {\n function: 'multicall',\n params: calls,\n outputs: {\n amountsIn: queryResult.returnAmounts.map((amount) => amount.toString()),\n },\n };\n }\n\n /**\n * Creates encoded multicalls using swap outputs as input amounts for token unwrap.\n * @param wrappedTokens\n * @param swapType\n * @param swaps\n * @param assets\n * @param funds\n * @param limits\n * @returns\n */\n encodeSwapUnwrap(\n wrappedTokens: string[],\n swapType: SwapType,\n swaps: BatchSwapStep[],\n assets: string[],\n funds: FundManagement,\n limits: BigNumberish[]\n ): string[] {\n // Output of swaps (wrappedTokens) is used as input to unwrap\n // Need indices of output tokens and outputReferences need to be made with those as key\n const outputReferences: OutputReference[] = [];\n const unwrapCalls: string[] = [];\n wrappedTokens.forEach((wrappedToken, i) => {\n // Find index of wrappedToken in asset array. This is used as ref in Relayer.\n const index = assets.findIndex(\n (token) => token.toLowerCase() === wrappedToken.toLowerCase()\n );\n // There may be cases where swap isn't possible for wrappedToken\n if (index === -1) return;\n\n const key = Relayer.toChainedReference(i);\n\n outputReferences.push({\n index: index,\n key: key,\n });\n\n // console.log(`Unwrapping ${wrappedToken} with amt: ${key.toHexString()}`);\n\n const encodedUnwrap = Relayer.encodeUnwrapAaveStaticToken({\n staticToken: wrappedToken,\n sender: funds.recipient, // This should be relayer\n recipient: funds.sender, // This will be caller\n amount: key, // Use output of swap as input for unwrap\n toUnderlying: true,\n outputReferences: 0,\n });\n\n unwrapCalls.push(encodedUnwrap);\n });\n\n const encodedBatchSwap = Relayer.encodeBatchSwap({\n swapType: swapType,\n swaps: swaps,\n assets: assets,\n funds: funds, // Note - this should have Relayer as recipient\n limits: limits.map((l) => l.toString()),\n deadline: MaxUint256,\n value: '0',\n outputReferences: outputReferences,\n });\n return [encodedBatchSwap, ...unwrapCalls];\n }\n\n static signRelayerApproval = async (\n relayerAddress: string,\n signerAddress: string,\n signer: JsonRpcSigner,\n vault: Vault\n ): Promise<string> => {\n const approval = vault.interface.encodeFunctionData('setRelayerApproval', [\n signerAddress,\n relayerAddress,\n true,\n ]);\n\n const signature =\n await RelayerAuthorization.signSetRelayerApprovalAuthorization(\n vault,\n signer,\n relayerAddress,\n approval\n );\n\n const calldata = RelayerAuthorization.encodeCalldataAuthorization(\n '0x',\n MaxUint256,\n signature\n );\n\n return calldata;\n };\n}\n","import { BalancerSdkConfig } from '@/types';\nimport { GraphQLClient } from 'graphql-request';\nimport { getNetworkConfig } from '../sdk.helpers';\nimport { getSdk } from './generated/balancer-subgraph-types';\nimport { SubgraphClient } from './subgraph';\n\nexport class Subgraph {\n public readonly url: string;\n public readonly client: SubgraphClient;\n\n constructor(config: BalancerSdkConfig) {\n this.url = getNetworkConfig(config).urls.subgraph;\n this.client = this.initClient();\n }\n\n private initClient(): SubgraphClient {\n const client = new GraphQLClient(this.url);\n return getSdk(client);\n }\n}\n","import { Swaps } from '@/modules/swaps/swaps.module';\nimport { BalancerSdkConfig } from '@/types';\nimport {\n SubgraphPoolBase,\n ZERO,\n parseToPoolsDict,\n getSpotPriceAfterSwapForPath,\n} from '@defiverse/sor';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\n\nexport class Pricing {\n private readonly swaps: Swaps;\n\n constructor(config: BalancerSdkConfig, swaps?: Swaps) {\n if (swaps) {\n this.swaps = swaps;\n } else {\n this.swaps = new Swaps(config);\n }\n }\n\n /**\n * Retrieves pools using poolDataService.\n * @returns {boolean} Boolean indicating whether pools data was fetched correctly (true) or not (false).\n */\n async fetchPools(): Promise<boolean> {\n return this.swaps.fetchPools();\n }\n\n /**\n * Get currently saved pools list (fetched using fetchPools()).\n * @returns {SubgraphPoolBase[]} pools list.\n */\n public getPools(): SubgraphPoolBase[] {\n return this.swaps.getPools();\n }\n\n /**\n * Calculates Spot Price for a token pair - finds most liquid path and uses this as reference SP.\n * @param { string } tokenIn Token in address.\n * @param { string } tokenOut Token out address.\n * @param { SubgraphPoolBase[] } pools Optional - Pool data. Will be fetched via dataProvider if not supplied.\n * @returns { string } Spot price.\n */\n async getSpotPrice(\n tokenIn: string,\n tokenOut: string,\n pools: SubgraphPoolBase[] = []\n ): Promise<string> {\n // If pools list isn't supplied fetch it from swaps data provider\n if (pools.length === 0) {\n await this.fetchPools();\n pools = this.getPools();\n }\n\n // We find the path for the pair with the highest liquidity and use this as the ref SP\n const poolsDict = parseToPoolsDict(pools, 0);\n // This creates all paths for tokenIn>Out ordered by liquidity\n const paths = this.swaps.sor.routeProposer.getCandidatePathsFromDict(\n tokenIn,\n tokenOut,\n 0,\n poolsDict,\n 4\n );\n\n if (paths.length === 0)\n throw new BalancerError(BalancerErrorCode.UNSUPPORTED_PAIR);\n return getSpotPriceAfterSwapForPath(paths[0], 0, ZERO).toString();\n }\n}\n","export const oneSecondInMs = 1000;\nexport const twentyFourHoursInSecs = 24 * 60 * 60;\n\nexport function toJsTimestamp(unixTimestamp: number): number {\n return unixTimestamp * oneSecondInMs;\n}\n\nexport function toUnixTimestamp(jsTimestamp: number): number {\n return Math.round(jsTimestamp / oneSecondInMs);\n}\n\nexport function isLessThan24Hours(incomingDateInSec: number): boolean {\n const now = Math.round(Date.now() / 1000);\n const difference = now - incomingDateInSec;\n\n return difference < twentyFourHoursInSecs;\n}\n","import { Provider } from '@ethersproject/providers';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { formatUnits } from '@ethersproject/units';\nimport { Multicaller } from '@/lib/utils/multiCaller';\nimport { toJsTimestamp } from '@/lib/utils/time';\nimport { ContractAddresses } from '@/types';\nimport veBalAbi from '@/lib/abi/veBal.json';\n\nexport type VeBalLockInfo = {\n lockedEndDate: number;\n lockedAmount: string;\n totalSupply: string;\n epoch: string;\n hasExistingLock: boolean;\n isExpired: boolean;\n};\n\ntype VeBalLockInfoResult = {\n locked: BigNumber[];\n epoch: BigNumber;\n totalSupply: BigNumber;\n};\n\nexport class VeBal {\n addresses: ContractAddresses;\n provider: Provider;\n\n constructor(addresses: ContractAddresses, provider: Provider) {\n this.addresses = addresses;\n this.provider = provider;\n }\n\n public async getLockInfo(\n account: string\n ): Promise<VeBalLockInfo | undefined> {\n if (!this.addresses.veBal) throw new Error('veBal address must be defined');\n\n const multicaller = new Multicaller(\n this.addresses.multicall,\n this.provider,\n veBalAbi\n );\n\n multicaller.call('locked', this.addresses.veBal, 'locked', [account]);\n multicaller.call('epoch', this.addresses.veBal, 'epoch');\n multicaller.call('totalSupply', this.addresses.veBal, 'totalSupply()');\n\n const result = <VeBalLockInfoResult>await multicaller.execute();\n\n return this.formatLockInfo(result);\n }\n\n public formatLockInfo(lockInfo: VeBalLockInfoResult): VeBalLockInfo {\n const [lockedAmount, lockedEndDate] = lockInfo.locked;\n\n const hasExistingLock = lockedAmount.gt(0);\n const lockedEndDateNormalised = toJsTimestamp(lockedEndDate.toNumber());\n const isExpired = hasExistingLock && Date.now() > lockedEndDateNormalised;\n\n return {\n lockedEndDate: lockedEndDateNormalised,\n lockedAmount: formatUnits(lockedAmount),\n totalSupply: formatUnits(lockInfo.totalSupply),\n epoch: formatUnits(lockInfo.epoch, 0),\n hasExistingLock,\n isExpired,\n };\n }\n}\n","import { ContractAddresses } from '@/types';\nimport { Provider } from '@ethersproject/providers';\nimport { Contract } from '@ethersproject/contracts';\nimport { formatUnits } from '@ethersproject/units';\nimport veBalProxyAbi from '@/lib/abi/veDelegationProxy.json';\n\nexport class VeBalProxy {\n instance: Contract;\n\n constructor(addresses: ContractAddresses, provider: Provider) {\n if (!addresses.veBalProxy)\n throw new Error('veBalProxy address must be defined');\n this.instance = new Contract(addresses.veBalProxy, veBalProxyAbi, provider);\n }\n\n async getAdjustedBalance(account: string): Promise<string> {\n const balance = await this.instance.adjustedBalanceOf(account);\n return formatUnits(balance);\n }\n}\n","import { Contract } from '@ethersproject/contracts';\nimport { Provider } from '@ethersproject/providers';\nimport RelayerV4ABI from '@/lib/abi/RelayerV4.json';\nimport RelayerV3ABI from '@/lib/abi/BalancerRelayer.json';\n\nexport const Relayer = (\n address: string,\n provider: Provider,\n version: number\n): Contract => {\n switch (version) {\n case 3:\n return new Contract(address, RelayerV3ABI, provider);\n case 4:\n return new Contract(address, RelayerV4ABI, provider);\n default:\n throw new Error('relayer not supported');\n }\n};\n","import { Contract } from '@ethersproject/contracts';\nimport { Provider } from '@ethersproject/providers';\nimport { Signer } from '@ethersproject/abstract-signer';\nimport { ContractAddresses } from '@/types';\nimport { Network } from '@/lib/constants/network';\nimport { BALANCER_NETWORK_CONFIG } from '@/lib/constants/config';\nimport {\n Vault__factory,\n Vault,\n LidoRelayer__factory,\n LidoRelayer,\n BalancerHelpers,\n BalancerHelpers__factory,\n} from '@balancer-labs/typechain';\nimport { Multicall } from './implementations/multicall';\nimport { ERC20 } from './implementations/ERC20';\nimport { VeBal } from './implementations/veBAL';\nimport { VeBalProxy } from './implementations/veBAL-proxy';\nimport { Relayer } from './implementations/relayer';\nimport { LiquidityGauge } from './implementations/liquidity-gauge';\n\ntype ContractFactory = (\n address: string,\n signerOrProvider: Signer | Provider\n) => Contract;\n\nexport interface ContractInstances {\n vault: Vault;\n balancerHelpers: BalancerHelpers;\n lidoRelayer?: LidoRelayer;\n multicall: Contract;\n relayerV3?: Contract;\n relayerV4?: Contract;\n veBal?: VeBal;\n veBalProxy?: VeBalProxy;\n ERC20: ContractFactory;\n liquidityGauge: ContractFactory;\n}\n\nexport class Contracts {\n contractAddresses: ContractAddresses;\n vault: Vault;\n balancerHelpers: BalancerHelpers;\n lidoRelayer?: LidoRelayer;\n multicall: Contract;\n relayerV3?: Contract;\n relayerV4?: Contract;\n veBal?: VeBal;\n veBalProxy?: VeBalProxy;\n\n /**\n * Create instances of Balancer contracts connected to passed provider.\n * @param { Network | ContractAddresses } networkOrAddresses\n * @param { Provider } provider\n */\n constructor(\n networkOrAddresses: Network | ContractAddresses,\n provider: Provider\n ) {\n // Access addresses using passed network if available\n if (typeof networkOrAddresses === 'number') {\n this.contractAddresses =\n BALANCER_NETWORK_CONFIG[networkOrAddresses].addresses.contracts;\n } else {\n this.contractAddresses = networkOrAddresses;\n }\n\n this.vault = Vault__factory.connect(this.contractAddresses.vault, provider);\n this.balancerHelpers = BalancerHelpers__factory.connect(\n this.contractAddresses.balancerHelpers,\n provider\n );\n\n if (this.contractAddresses.lidoRelayer)\n this.lidoRelayer = LidoRelayer__factory.connect(\n this.contractAddresses.lidoRelayer,\n provider\n );\n\n // These contracts aren't included in Balancer Typechain but are still useful.\n // TO DO - Possibly create via Typechain but seems unnecessary?\n this.multicall = Multicall(this.contractAddresses.multicall, provider);\n if (this.contractAddresses.relayerV3)\n this.relayerV3 = Relayer(this.contractAddresses.relayerV3, provider, 3);\n if (this.contractAddresses.relayerV4)\n this.relayerV4 = Relayer(this.contractAddresses.relayerV4, provider, 4);\n\n if (this.contractAddresses.veBal) {\n this.veBal = new VeBal(this.contractAddresses, provider);\n }\n\n if (this.contractAddresses.veBalProxy) {\n this.veBalProxy = new VeBalProxy(this.contractAddresses, provider);\n }\n }\n\n /**\n * Expose contract instances.\n */\n get contracts(): ContractInstances {\n return {\n vault: this.vault,\n balancerHelpers: this.balancerHelpers,\n lidoRelayer: this.lidoRelayer,\n multicall: this.multicall,\n relayerV3: this.relayerV3,\n relayerV4: this.relayerV4,\n veBal: this.veBal,\n veBalProxy: this.veBalProxy,\n ERC20: this.getErc20,\n liquidityGauge: this.getLiquidityGauge,\n };\n }\n\n /**\n * Helper to create ERC20 contract.\n * @param { string } address ERC20 address.\n * @param { Signer | Provider } signerOrProvider Signer or Provider.\n * @returns Contract.\n */\n getErc20(address: string, signerOrProvider: Signer | Provider): Contract {\n return ERC20(address, signerOrProvider);\n }\n\n /**\n * Helper to create LiquidityGauge contract.\n * @param { string } address Gauge address.\n * @param { Signer | Provider} signerOrProvider Signer or Provider.\n * @returns Contract.\n */\n getLiquidityGauge(\n address: string,\n signerOrProvider: Signer | Provider\n ): Contract {\n return LiquidityGauge(address, signerOrProvider);\n }\n}\n","import { Contract } from '@ethersproject/contracts';\nimport { Provider } from '@ethersproject/providers';\nimport { Signer } from '@ethersproject/abstract-signer';\nimport abi from '../../../lib/abi/ERC20.json';\n\nexport const ERC20 = (\n address: string,\n signerOrProvider: Signer | Provider\n): Contract => new Contract(address, abi, signerOrProvider);\n","import { Provider } from '@ethersproject/providers';\nimport { Signer } from '@ethersproject/abstract-signer';\nimport { Contract } from '@ethersproject/contracts';\nimport abi from '@/lib/abi/LiquidityGaugeV5.json';\n\nexport const LiquidityGauge = (\n address: string,\n signerOrProvider: Signer | Provider\n): Contract => new Contract(address, abi, signerOrProvider);\n","export const ADDRESSES = {\n 1: {\n relayer: '0x886A3Ec7bcC508B8795990B60Fa21f85F9dB7948',\n staBal3: {\n id: '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000063',\n address: '0x06df3b2bbb68adc8b0e302443692037ed9f91b42',\n gauge: '0x34f33cdaed8ba0e1ceece80e5f4a73bcf234cfac',\n assetOrder: ['DAI', 'USDC', 'USDT'],\n },\n bbausd1: {\n id: '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb20000000000000000000000fe',\n address: '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb2',\n gauge: '0x68d019f64a7aa97e2d4e7363aee42251d08124fb',\n assetOrder: ['bb-a-USDT', 'bb-a-DAI', 'bb-a-USDC'],\n },\n bbausd2: {\n id: '0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d',\n address: '0xa13a9247ea42d743238089903570127dda72fe44',\n gauge: '0xa6325e799d266632d347e41265a69af111b05403',\n },\n linearUsdc1: {\n id: '0x9210f1204b5a24742eba12f710636d76240df3d00000000000000000000000fc',\n address: '0x9210F1204b5a24742Eba12f710636D76240dF3d0',\n },\n linearDai1: {\n id: '0x804cdb9116a10bb78768d3252355a1b18067bf8f0000000000000000000000fb',\n address: '0x804CdB9116a10bB78768D3252355a1b18067bF8f',\n },\n linearUsdt1: {\n id: '0x2bbf681cc4eb09218bee85ea2a5d3d13fa40fc0c0000000000000000000000fd',\n address: '0x2BBf681cC4eb09218BEe85EA2a5d3D13Fa40fC0C',\n },\n linearUsdc2: {\n id: '0x82698AECC9E28E9BB27608BD52CF57F704BD1B83000000000000000000000336',\n address: '0x82698aeCc9E28e9Bb27608Bd52cF57f704BD1B83',\n },\n linearDai2: {\n id: '0xAE37D54AE477268B9997D4161B96B8200755935C000000000000000000000337',\n address: '0xae37D54Ae477268B9997d4161B96b8200755935c',\n },\n linearUsdt2: {\n id: '0x2F4EB100552EF93840D5ADC30560E5513DFFFACB000000000000000000000334',\n address: '0x2F4eb100552ef93840d5aDC30560E5513DFfFACb',\n },\n maiusd: {\n id: '',\n address: '',\n gauge: '',\n assetOrder: ['USDT', 'miMATIC', 'DAI', 'USDC'],\n },\n maibbausd: {\n id: '',\n address: '',\n gauge: '',\n assetOrder: ['bb-a-USD', 'miMATIC'],\n },\n DAI: '0x6b175474e89094c44da98b954eedeac495271d0f',\n USDC: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n waDAI: '0x02d60b84491589974263d922d9cc7a3152618ef6',\n waUSDC: '0xd093fa4fb80d09bb30817fdcd442d4d02ed3e5de',\n waUSDT: '0xf8fd466f12e236f4c96f7cce6c79eadb819abf58',\n miMATIC: '',\n },\n 5: {\n relayer: '0x7b9B6f094DC2Bd1c12024b0D9CC63d6993Be1888',\n staBal3: {\n id: '0xdcdd4a3d36dec8d57594e89763d069a7e9b223e2000000000000000000000062',\n address: '0xdcdd4a3d36dec8d57594e89763d069a7e9b223e2',\n gauge: '0xfd364cda96bb7db06b65706182c448a73f0a5f9a',\n assetOrder: ['USDT', 'DAI', 'USDC'],\n },\n staBal3_2: {\n id: '0xff9d677474d4344379924e10b68c8fea67e03294000000000000000000000072',\n address: '0xff9d677474d4344379924e10b68c8fea67e03294',\n gauge: '0x4e4ebf2aa90e41174d716a5168895357762d68af',\n assetOrder: ['USDT', 'DAI', 'USDC'],\n },\n staBal3_3: {\n id: '0x3bfc8a0509f1a68aefd446f6c19bf37b3c75a8fc0000000000000000000000a5',\n address: '0x3bfc8a0509f1a68aefd446f6c19bf37b3c75a8fc',\n gauge: '0x7776e1008d7c20ab54aa57a7c44fc7de602de29a',\n assetOrder: ['USDT', 'DAI', 'USDC'],\n },\n bbausd1: {\n id: '0x13acd41c585d7ebb4a9460f7c8f50be60dc080cd00000000000000000000005f',\n address: '0x13acd41c585d7ebb4a9460f7c8f50be60dc080cd',\n gauge: '0xa2d0ea81a47d68598922cd54c59249ff58c2a3ff',\n assetOrder: ['bb-a-USDC', 'bb-a-DAI', 'bb-a-USDT'],\n },\n bbausd2: {\n id: '0x13acd41c585d7ebb4a9460f7c8f50be60dc080cd00000000000000000000005f',\n address: '0x13acd41c585d7ebb4a9460f7c8f50be60dc080cd',\n gauge: '0xa2d0ea81a47d68598922cd54c59249ff58c2a3ff',\n },\n linearUsdc1: {\n id: '0x0595d1df64279ddb51f1bdc405fe2d0b4cc8668100000000000000000000005c',\n address: '0x0595d1df64279ddb51f1bdc405fe2d0b4cc86681',\n },\n linearDai1: {\n id: '0x5cea6a84ed13590ed14903925fa1a73c36297d9900000000000000000000005d',\n address: '0x5cea6a84ed13590ed14903925fa1a73c36297d99',\n },\n linearUsdt1: {\n id: '0xefd681a82970ac5d980b9b2d40499735e7bf3f1f00000000000000000000005e',\n address: '0xefd681a82970ac5d980b9b2d40499735e7bf3f1f',\n },\n linearUsdc2: {\n id: '0x0595d1df64279ddb51f1bdc405fe2d0b4cc8668100000000000000000000005c',\n address: '0x0595d1df64279ddb51f1bdc405fe2d0b4cc86681',\n },\n linearDai2: {\n id: '0x5cea6a84ed13590ed14903925fa1a73c36297d9900000000000000000000005d',\n address: '0x5cea6a84ed13590ed14903925fa1a73c36297d99',\n },\n linearUsdt2: {\n id: '0xefd681a82970ac5d980b9b2d40499735e7bf3f1f00000000000000000000005e',\n address: '0xefd681a82970ac5d980b9b2d40499735e7bf3f1f',\n },\n maiusd: {\n id: '0x6a8f9ab364b85725973d2a33cb9aae2dac43b5e30000000000000000000000a6',\n address: '0x6a8f9ab364b85725973d2a33cb9aae2dac43b5e3',\n gauge: '0x58141bdcecb7fbae006964f4131cf6f65c948357',\n assetOrder: ['USDT', 'miMATIC', 'DAI', 'USDC'],\n },\n maibbausd: {\n id: '0xb04b03b78cf79788a1931545bd2744161029648f0000000000000000000000a8',\n address: '0xb04b03b78cf79788a1931545bd2744161029648f',\n gauge: '0xdc3f6fc8898830e53c777543fe252b14f22680d4',\n assetOrder: ['bb-a-USD', 'miMATIC', 'MAI BSP'],\n },\n USDT: '0x1f1f156e0317167c11aa412e3d1435ea29dc3cce',\n DAI: '0x8c9e6c40d3402480ace624730524facc5482798c',\n USDC: '0xe0c9275e44ea80ef17579d33c55136b7da269aeb',\n waDAI: '0x89534a24450081aa267c79b07411e9617d984052',\n waUSDC: '0x811151066392fd641fe74a9b55a712670572d161',\n waUSDT: '0x4cb1892fddf14f772b2e39e299f44b2e5da90d04',\n miMATIC: '0x398106564948feeb1fedea0709ae7d969d62a391',\n },\n 137: {\n relayer: '0xcf6a66E32dCa0e26AcC3426b851FD8aCbF12Dac7',\n staBal3: {\n id: '',\n address: '',\n gauge: '',\n assetOrder: ['USDT', 'DAI', 'USDC'],\n },\n bbausd1: {\n id: '',\n address: '',\n gauge: '',\n assetOrder: ['bb-a-USDC', 'bb-a-DAI', 'bb-a-USDT'],\n },\n bbausd2: {\n id: '0x48e6b98ef6329f8f0a30ebb8c7c960330d64808500000000000000000000075b',\n address: '0x48e6b98ef6329f8f0a30ebb8c7c960330d648085',\n gauge: '',\n },\n linearUsdc1: {\n id: '',\n address: '',\n },\n linearDai1: {\n id: '',\n address: '',\n },\n linearUsdt1: {\n id: '',\n address: '',\n },\n linearUsdc2: {\n id: '0xf93579002dbe8046c43fefe86ec78b1112247bb8000000000000000000000759',\n address: '0xf93579002dbe8046c43fefe86ec78b1112247bb8',\n },\n linearDai2: {\n id: '0x178e029173417b1f9c8bc16dcec6f697bc323746000000000000000000000758',\n address: '0x178e029173417b1f9c8bc16dcec6f697bc323746',\n },\n linearUsdt2: {\n id: '0xff4ce5aaab5a627bf82f4a571ab1ce94aa365ea600000000000000000000075a',\n address: '0xff4ce5aaab5a627bf82f4a571ab1ce94aa365ea6',\n },\n maiusd: {\n id: '0x06df3b2bbb68adc8b0e302443692037ed9f91b42000000000000000000000012',\n address: '0x06df3b2bbb68adc8b0e302443692037ed9f91b42',\n gauge: '0x72843281394e68de5d55bcf7072bb9b2ebc24150',\n assetOrder: ['USDC', 'DAI', 'miMATIC', 'USDT'],\n },\n maibbausd: {\n id: '0xb54b2125b711cd183edd3dd09433439d5396165200000000000000000000075e',\n address: '0xb54b2125b711cd183edd3dd09433439d53961652',\n gauge: '0x9a105ef22a59484aa2731c357049f6a13d0891f5',\n assetOrder: ['bb-a-USD', 'miMATIC'],\n },\n USDT: '0xc2132d05d31c914a87c6611c10748aeb04b58e8f',\n DAI: '0x8f3cf7ad23cd3cadbd9735aff958023239c6a063',\n USDC: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174',\n waDAI: '0xEE029120c72b0607344f35B17cdD90025e647B00',\n waUSDC: '0x221836a597948Dce8F3568E044fF123108aCc42A',\n waUSDT: '0x19C60a251e525fa88Cd6f3768416a8024e98fC19',\n miMATIC: '0xa3fa99a148fa48d14ed51d610c367c61876997f1',\n },\n};\n","import { StablePoolEncoder } from '@/pool-stable/encoder';\nimport { ADDRESSES } from './addresses';\nimport { Relayer } from '@/modules/relayer/relayer.module';\nimport { ExitPoolRequest } from '@/types';\nimport { BatchSwapStep, FundManagement, SwapType } from '@/modules/swaps/types';\nimport { Interface } from '@ethersproject/abi';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { MaxInt256 } from '@ethersproject/constants';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\n// TODO - Ask Nico to update Typechain?\nimport balancerRelayerAbi from '@/lib/abi/BalancerRelayer.json';\nconst balancerRelayerInterface = new Interface(balancerRelayerAbi);\n\nconst EXIT_DAI = Relayer.toChainedReference('21');\nconst EXIT_USDC = Relayer.toChainedReference('22');\nconst EXIT_USDT = Relayer.toChainedReference('23');\nconst SWAP_RESULT_BBAUSD = Relayer.toChainedReference('24');\n\nexport class StaBal3Builder {\n private addresses;\n\n constructor(networkId: 1 | 5 | 137) {\n this.addresses = ADDRESSES[networkId];\n }\n\n /**\n * Builds migration call data.\n * Migrates tokens from staBal3 to bbausd2 pool.\n * Tokens that are initially staked are re-staked at the end of migration. Non-staked are not.\n *\n * @param userAddress User address.\n * @param staBal3Amount Amount of BPT tokens to migrate.\n * @param minBbausd2Out Minimum of expected BPT out ot the migration flow.\n * @param staked Indicates whether tokens are initially staked or not.\n * @param authorisation Encoded authorisation call.\n * @returns Migration transaction request ready to send with signer.sendTransaction\n */\n calldata(\n userAddress: string,\n staBal3Amount: string,\n minBbausd2Out: string,\n staked: boolean,\n authorisation?: string\n ): {\n to: string;\n data: string;\n } {\n if (BigNumber.from(staBal3Amount).lte(0))\n throw new BalancerError(BalancerErrorCode.INPUT_ZERO_NOT_ALLOWED);\n const relayer = this.addresses.relayer;\n let calls: string[] = [];\n\n if (authorisation) {\n calls = [this.buildSetRelayerApproval(authorisation)];\n }\n\n if (staked) {\n calls = [\n ...calls,\n this.buildWithdraw(userAddress, staBal3Amount),\n this.buildExit(relayer, staBal3Amount),\n this.buildSwap(minBbausd2Out, relayer),\n this.buildDeposit(userAddress),\n ];\n } else {\n calls = [\n ...calls,\n this.buildExit(userAddress, staBal3Amount),\n this.buildSwap(minBbausd2Out, userAddress),\n ];\n }\n\n const callData = balancerRelayerInterface.encodeFunctionData('multicall', [\n calls,\n ]);\n\n return {\n to: relayer,\n data: callData,\n };\n }\n\n /**\n * Encodes exitPool callData.\n * Exit staBal3 pool proportionally to underlying stables. Exits to relayer.\n * Outputreferences are used to store exit amounts for next transaction.\n *\n * @param sender Sender address.\n * @param amount Amount of staBal3 BPT to exit with.\n * @returns Encoded exitPool call. Output references.\n */\n buildExit(sender: string, amount: string): string {\n // Goerli and Mainnet has different assets ordering\n const { assetOrder } = this.addresses.staBal3;\n const assets = assetOrder.map(\n (key) => this.addresses[key as keyof typeof this.addresses] as string\n );\n\n // Assume gaugeWithdraw returns same amount value\n const userData = StablePoolEncoder.exitExactBPTInForTokensOut(amount);\n // const userData = StablePoolEncoder.exitExactBPTInForOneTokenOut(\n // amount,\n // assetOrder.indexOf('DAI')\n // );\n\n // Ask to store exit outputs for batchSwap of exit is used as input to swaps\n const outputReferences = [\n { index: assetOrder.indexOf('DAI'), key: EXIT_DAI },\n { index: assetOrder.indexOf('USDC'), key: EXIT_USDC },\n { index: assetOrder.indexOf('USDT'), key: EXIT_USDT },\n ];\n\n const callData = Relayer.constructExitCall({\n assets,\n minAmountsOut: ['0', '0', '0'],\n userData,\n toInternalBalance: true,\n poolId: this.addresses.staBal3.id,\n poolKind: 0, // This will always be 0 to match supported Relayer types\n sender,\n recipient: this.addresses.relayer,\n outputReferences,\n exitPoolRequest: {} as ExitPoolRequest,\n });\n\n return callData;\n }\n\n /**\n * Creates encoded batchSwap function with following swaps: stables -> linear pools -> boosted pool\n * outputreferences should contain the amount of resulting BPT.\n *\n * @param expectedBptReturn BPT amount expected out of the swap.\n * @param recipient Recipient address.\n * @returns Encoded batchSwap call. Output references.\n */\n buildSwap(expectedBptReturn: string, recipient: string): string {\n const assets = [\n this.addresses.bbausd2.address,\n this.addresses.DAI,\n this.addresses.linearDai2.address,\n this.addresses.USDC,\n this.addresses.linearUsdc2.address,\n this.addresses.USDT,\n this.addresses.linearUsdt2.address,\n ];\n\n const outputReferences = [{ index: 0, key: SWAP_RESULT_BBAUSD }];\n\n // for each linear pool swap -\n // linear1Bpt[linear1]stable[linear2]linear2bpt[bbausd2]bbausd2 Uses chainedReference from previous action for amount.\n // TO DO - Will swap order matter here? John to ask Fernando.\n const swaps: BatchSwapStep[] = [\n {\n poolId: this.addresses.linearDai2.id,\n assetInIndex: 1,\n assetOutIndex: 2,\n amount: EXIT_DAI.toString(),\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd2.id,\n assetInIndex: 2,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.linearUsdc2.id,\n assetInIndex: 3,\n assetOutIndex: 4,\n amount: EXIT_USDC.toString(),\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd2.id,\n assetInIndex: 4,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.linearUsdt2.id,\n assetInIndex: 5,\n assetOutIndex: 6,\n amount: EXIT_USDT.toString(),\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd2.id,\n assetInIndex: 6,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n ];\n\n // For tokens going in to the Vault, the limit shall be a positive number. For tokens going out of the Vault, the limit shall be a negative number.\n const limits = [\n BigNumber.from(expectedBptReturn).mul(-1).toString(),\n MaxInt256.toString(),\n '0',\n MaxInt256.toString(),\n '0',\n MaxInt256.toString(),\n '0',\n ];\n\n // Swap to/from Relayer\n const funds: FundManagement = {\n sender: this.addresses.relayer,\n recipient,\n fromInternalBalance: true,\n toInternalBalance: false,\n };\n\n const encodedBatchSwap = Relayer.encodeBatchSwap({\n swapType: SwapType.SwapExactIn,\n swaps,\n assets,\n funds,\n limits,\n deadline: BigNumber.from(Math.ceil(Date.now() / 1000) + 3600), // 1 hour from now\n value: '0',\n outputReferences,\n });\n\n return encodedBatchSwap;\n }\n\n /**\n * Uses relayer to withdraw staked BPT from gauge and send to relayer\n *\n * @param sender Sender address.\n * @param amount Amount of BPT to exit with.\n * @returns withdraw call\n */\n buildWithdraw(sender: string, amount: string): string {\n return Relayer.encodeGaugeWithdraw(\n this.addresses.staBal3.gauge,\n sender,\n this.addresses.relayer,\n amount\n );\n }\n\n /**\n * Uses relayer to deposit user's BPT to gauge and sends to recipient\n *\n * @param recipient Recipient address.\n * @returns deposit call\n */\n buildDeposit(recipient: string): string {\n return Relayer.encodeGaugeDeposit(\n this.addresses.bbausd2.gauge,\n this.addresses.relayer,\n recipient,\n SWAP_RESULT_BBAUSD.toString()\n );\n }\n\n /**\n * Uses relayer to approve itself to act in behalf of the user\n *\n * @param authorisation Encoded authorisation call.\n * @returns relayer approval call\n */\n buildSetRelayerApproval(authorisation: string): string {\n return Relayer.encodeSetRelayerApproval(\n this.addresses.relayer,\n true,\n authorisation\n );\n }\n}\n","import { ADDRESSES } from './addresses';\nimport { Relayer } from '@/modules/relayer/relayer.module';\nimport { BatchSwapStep, FundManagement, SwapType } from '@/modules/swaps/types';\nimport { Interface } from '@ethersproject/abi';\n// TODO - Ask Nico to update Typechain?\nimport balancerRelayerAbi from '@/lib/abi/BalancerRelayer.json';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { Zero } from '@ethersproject/constants';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nconst balancerRelayerInterface = new Interface(balancerRelayerAbi);\n\nconst SWAP_RESULT_BBAUSD = Relayer.toChainedReference('24');\nexport class BbaUsd1Builder {\n private addresses;\n\n constructor(networkId: 1 | 5 | 137) {\n this.addresses = ADDRESSES[networkId];\n }\n\n /**\n * Builds migration call data.\n * Migrates tokens from bbausd1 to bbausd2 pool.\n * Tokens that are initially staked are re-staked at the end of migration. Non-staked are not.\n *\n * @param userAddress User address.\n * @param bbausd1Amount Amount of BPT tokens to migrate.\n * @param minBbausd2Out Minimum of expected BPT out ot the migration flow.\n * @param staked Indicates whether tokens are initially staked or not.\n * @param tokenBalances Token balances in EVM scale. Array must have the same length and order as tokens in pool being migrated from. Refer to [getPoolTokens](https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/interfaces/contracts/vault/IVault.sol#L334).\n * @param authorisation Encoded authorisation call.\n * @returns Migration transaction request ready to send with signer.sendTransaction\n */\n calldata(\n userAddress: string,\n bbausd1Amount: string,\n minBbausd2Out: string,\n staked: boolean,\n tokenBalances: string[],\n authorisation?: string\n ): {\n to: string;\n data: string;\n } {\n if (BigNumber.from(bbausd1Amount).lte(0))\n throw new BalancerError(BalancerErrorCode.INPUT_ZERO_NOT_ALLOWED);\n const relayer = this.addresses.relayer;\n let calls: string[] = [];\n\n if (authorisation) {\n calls = [this.buildSetRelayerApproval(authorisation)];\n }\n\n if (staked) {\n calls = [\n ...calls,\n this.buildWithdraw(userAddress, bbausd1Amount),\n this.buildSwap(\n bbausd1Amount,\n minBbausd2Out,\n relayer,\n relayer,\n tokenBalances\n ),\n this.buildDeposit(userAddress),\n ];\n } else {\n calls = [\n ...calls,\n this.buildSwap(\n bbausd1Amount,\n minBbausd2Out,\n userAddress,\n userAddress,\n tokenBalances\n ),\n ];\n }\n\n const callData = balancerRelayerInterface.encodeFunctionData('multicall', [\n calls,\n ]);\n\n return {\n to: this.addresses.relayer,\n data: callData,\n };\n }\n\n /**\n * Creates encoded batchSwap function with following swaps: boosted -> linears -> stables -> linears -> boosted\n * outputreferences should contain the amount of resulting BPT.\n *\n * @param bbausd1Amount Amount of BPT tokens to migrate.\n * @param minBbausd2Out Minimum of expected BPT out ot the migration flow.\n * @param sender Sender address.\n * @param recipient Recipient address.\n * @param tokenBalances Token balances in EVM scale.\n * @returns Encoded batchSwap call. Output references.\n */\n buildSwap(\n bbausd1Amount: string,\n minBbausd2Out: string,\n sender: string,\n recipient: string,\n tokenBalances: string[]\n ): string {\n const assets = [\n this.addresses.bbausd2.address,\n this.addresses.waDAI,\n this.addresses.linearDai1.address,\n this.addresses.linearDai2.address,\n this.addresses.waUSDC,\n this.addresses.linearUsdc1.address,\n this.addresses.linearUsdc2.address,\n this.addresses.waUSDT,\n this.addresses.linearUsdt1.address,\n this.addresses.linearUsdt2.address,\n this.addresses.bbausd1.address,\n ];\n\n const outputReferences = [{ index: 0, key: SWAP_RESULT_BBAUSD }];\n\n // Calculate proportional token amounts\n\n // Assuming 1:1 exchange rates between tokens\n // TODO: Fetch current prices, or use price or priceRate from subgraph?\n const totalLiquidity = tokenBalances.reduce(\n (sum, tokenBalance) => sum.add(BigNumber.from(tokenBalance)),\n Zero\n );\n\n // bbausd1[bbausd1]blinear1[linear1]stable[linear2]blinear2[bbausd2]bbausd2 and then do that proportionally for each underlying stable.\n // Split BPT amount proportionally:\n const { assetOrder } = this.addresses.bbausd1;\n const usdcBptAmt = BigNumber.from(bbausd1Amount)\n .mul(tokenBalances[assetOrder.indexOf('bb-a-USDC')])\n .div(totalLiquidity)\n .toString();\n const daiBptAmt = BigNumber.from(bbausd1Amount)\n .mul(tokenBalances[assetOrder.indexOf('bb-a-DAI')])\n .div(totalLiquidity)\n .toString();\n const usdtBptAmt = BigNumber.from(bbausd1Amount)\n .sub(usdcBptAmt)\n .sub(daiBptAmt)\n .toString();\n\n const swaps: BatchSwapStep[] = [\n {\n poolId: this.addresses.bbausd1.id,\n assetInIndex: 10,\n assetOutIndex: 2,\n amount: daiBptAmt,\n userData: '0x',\n },\n {\n poolId: this.addresses.linearDai1.id,\n assetInIndex: 2,\n assetOutIndex: 1,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.linearDai2.id,\n assetInIndex: 1,\n assetOutIndex: 3,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd2.id,\n assetInIndex: 3,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd1.id,\n assetInIndex: 10,\n assetOutIndex: 5,\n amount: usdcBptAmt,\n userData: '0x',\n },\n {\n poolId: this.addresses.linearUsdc1.id,\n assetInIndex: 5,\n assetOutIndex: 4,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.linearUsdc2.id,\n assetInIndex: 4,\n assetOutIndex: 6,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd2.id,\n assetInIndex: 6,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd1.id,\n assetInIndex: 10,\n assetOutIndex: 8,\n amount: usdtBptAmt,\n userData: '0x',\n },\n {\n poolId: this.addresses.linearUsdt1.id,\n assetInIndex: 8,\n assetOutIndex: 7,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.linearUsdt2.id,\n assetInIndex: 7,\n assetOutIndex: 9,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd2.id,\n assetInIndex: 9,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n ];\n\n // For tokens going in to the Vault, the limit shall be a positive number. For tokens going out of the Vault, the limit shall be a negative number.\n const limits = [\n BigNumber.from(minBbausd2Out).mul(-1).toString(), // bbausd2\n '0',\n '0',\n '0',\n '0',\n '0',\n '0',\n '0',\n '0',\n '0',\n bbausd1Amount, // Max in should be bbausd1 amount\n ];\n\n // Swap to/from Relayer\n const funds: FundManagement = {\n sender,\n recipient,\n fromInternalBalance: false,\n toInternalBalance: false,\n };\n\n const encodedBatchSwap = Relayer.encodeBatchSwap({\n swapType: SwapType.SwapExactIn,\n swaps,\n assets,\n funds,\n limits,\n deadline: BigNumber.from(Math.ceil(Date.now() / 1000) + 3600), // 1 hour from now\n value: '0',\n outputReferences,\n });\n\n return encodedBatchSwap;\n }\n\n /**\n * Uses relayer to withdraw staked BPT from gauge and send to relayer\n *\n * @param sender Sender address.\n * @param amount Amount of BPT to exit with.\n * @returns withdraw call\n */\n buildWithdraw(sender: string, amount: string): string {\n return Relayer.encodeGaugeWithdraw(\n this.addresses.bbausd1.gauge,\n sender,\n this.addresses.relayer,\n amount\n );\n }\n\n /**\n * Uses relayer to deposit user's BPT to gauge and sends to recipient\n *\n * @param recipient Recipient address.\n * @returns deposit call\n */\n buildDeposit(recipient: string): string {\n return Relayer.encodeGaugeDeposit(\n this.addresses.bbausd2.gauge,\n this.addresses.relayer,\n recipient,\n SWAP_RESULT_BBAUSD.toString()\n );\n }\n\n /**\n * Uses relayer to approve itself to act in behalf of the user\n *\n * @param authorisation Encoded authorisation call.\n * @returns relayer approval call\n */\n buildSetRelayerApproval(authorisation: string): string {\n return Relayer.encodeSetRelayerApproval(\n this.addresses.relayer,\n true,\n authorisation\n );\n }\n}\n","import { StablePoolEncoder } from '@/pool-stable/encoder';\nimport { ADDRESSES } from './addresses';\nimport { Relayer } from '@/modules/relayer/relayer.module';\nimport { ExitPoolRequest } from '@/types';\nimport { BatchSwapStep, FundManagement, SwapType } from '@/modules/swaps/types';\nimport { Interface } from '@ethersproject/abi';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { MaxInt256 } from '@ethersproject/constants';\n// TODO - Ask Nico to update Typechain?\nimport balancerRelayerAbi from '@/lib/abi/BalancerRelayer.json';\nconst balancerRelayerInterface = new Interface(balancerRelayerAbi);\n\nconst SWAP_RESULT = Relayer.toChainedReference('0');\nconst EXIT_RESULTS: BigNumber[] = [];\n\nexport class StablesBuilder {\n private addresses;\n\n constructor(networkId: 1 | 5 | 137) {\n this.addresses = ADDRESSES[networkId];\n }\n\n /**\n * Builds migration call data.\n * Migrates tokens from old stable to new stable phantom pools with the same underlying tokens.\n * Tokens that are initially staked are re-staked at the end of migration. Non-staked are not.\n *\n * @param userAddress User address.\n * @param from Pool info being migrated from\n * @param to Pool info being migrated to\n * @param bptIn Amount of BPT tokens to migrate.\n * @param minBptOut Minimum of expected BPT out ot the migration flow.\n * @param staked Indicates whether tokens are initially staked or not.\n * @param underlyingTokens Underlying token addresses. Array must have the same length and order as underlying tokens in pool being migrated from. Refer to [getPoolTokens](https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/interfaces/contracts/vault/IVault.sol#L334).\n * @param authorisation Encoded authorisation call.\n * @returns Migration transaction request ready to send with signer.sendTransaction\n */\n calldata(\n userAddress: string,\n from: { id: string; address: string; gauge?: string },\n to: { id: string; address: string; gauge?: string },\n bptIn: string,\n minBptOut: string,\n staked: boolean,\n underlyingTokens: string[],\n authorisation?: string\n ): {\n to: string;\n data: string;\n } {\n if (staked && (from.gauge == undefined || to.gauge == undefined))\n throw new Error(\n 'Staked flow migration requires gauge addresses to be provided'\n );\n\n const relayer = this.addresses.relayer;\n let calls: string[] = [];\n\n if (authorisation) {\n calls = [this.buildSetRelayerApproval(authorisation)];\n }\n\n if (staked) {\n calls = [\n ...calls,\n this.buildWithdraw(userAddress, bptIn, from.gauge as string),\n this.buildExit(from.id, relayer, bptIn, underlyingTokens),\n this.buildSwap(minBptOut, relayer, to.id, to.address, underlyingTokens),\n this.buildDeposit(userAddress, to.gauge as string),\n ];\n } else {\n calls = [\n ...calls,\n this.buildExit(from.id, userAddress, bptIn, underlyingTokens),\n this.buildSwap(\n minBptOut,\n userAddress,\n to.id,\n to.address,\n underlyingTokens\n ),\n ];\n }\n\n const callData = balancerRelayerInterface.encodeFunctionData('multicall', [\n calls,\n ]);\n\n return {\n to: this.addresses.relayer,\n data: callData,\n };\n }\n\n /**\n * Encodes exitPool call data.\n * Exit stable pool proportionally to underlying stables. Exits to relayer.\n * Outputreferences are used to store exit amounts for next transaction.\n *\n * @param poolId Pool id.\n * @param sender Sender address.\n * @param amount Amount of BPT to exit with.\n * @param underlyingTokens Token addresses to exit to.\n * @returns Encoded exitPool call. Output references.\n */\n buildExit(\n poolId: string,\n sender: string,\n amount: string,\n underlyingTokens: string[]\n ): string {\n // Assume gaugeWithdraw returns same amount value\n const userData = StablePoolEncoder.exitExactBPTInForTokensOut(amount);\n\n // Store exit outputs to be used as swaps inputs\n const outputReferences = [];\n for (let i = 0; i < underlyingTokens.length; i++) {\n outputReferences[i] = {\n index: i,\n key: Relayer.toChainedReference(`${i + 1}`), // index 0 will be used by swap result\n };\n EXIT_RESULTS.push(outputReferences[i].key);\n }\n\n const minAmountsOut = Array<string>(underlyingTokens.length).fill('0');\n\n const callData = Relayer.constructExitCall({\n assets: underlyingTokens,\n minAmountsOut,\n userData,\n toInternalBalance: true,\n poolId,\n poolKind: 0, // This will always be 0 to match supported Relayer types\n sender,\n recipient: this.addresses.relayer,\n outputReferences,\n exitPoolRequest: {} as ExitPoolRequest,\n });\n\n return callData;\n }\n\n /**\n * Creates encoded batchSwap function to swap stables to new phantom stable pool BPT.\n * outputreferences should contain the amount of resulting BPT.\n *\n * @param expectedBptReturn BPT amount expected out of the swap.\n * @param recipient Recipient address.\n * @param poolId Pool id\n * @param poolAddress Pool address\n * @param tokens Token addresses to swap from.\n * @returns BatchSwap call.\n */\n buildSwap(\n expectedBptReturn: string,\n recipient: string,\n poolId: string,\n poolAddress: string,\n tokens: string[]\n ): string {\n const assets = [poolAddress, ...tokens];\n\n const outputReferences = [{ index: 0, key: SWAP_RESULT }];\n\n const swaps: BatchSwapStep[] = [];\n // Add a swap flow for each token provided\n for (let i = 0; i < tokens.length; i++) {\n swaps.push({\n poolId,\n assetInIndex: i + 1,\n assetOutIndex: 0,\n amount: EXIT_RESULTS[i].toString(),\n userData: '0x',\n });\n }\n\n // For tokens going in to the Vault, the limit shall be a positive number. For tokens going out of the Vault, the limit shall be a negative number.\n const limits = [BigNumber.from(expectedBptReturn).mul(-1).toString()];\n for (let i = 0; i < tokens.length; i++) {\n limits.push(MaxInt256.toString());\n }\n\n // Swap to/from Relayer\n const funds: FundManagement = {\n sender: this.addresses.relayer,\n recipient,\n fromInternalBalance: true,\n toInternalBalance: false,\n };\n\n const encodedBatchSwap = Relayer.encodeBatchSwap({\n swapType: SwapType.SwapExactIn,\n swaps,\n assets,\n funds,\n limits,\n deadline: BigNumber.from(Math.ceil(Date.now() / 1000) + 3600), // 1 hour from now\n value: '0',\n outputReferences,\n });\n\n return encodedBatchSwap;\n }\n\n /**\n * Uses relayer to withdraw staked BPT from gauge and send to relayer\n *\n * @param sender Sender address.\n * @param amount Amount of BPT to exit with.\n * @param gaugeAddress Gauge address.\n * @returns withdraw call\n */\n buildWithdraw(sender: string, amount: string, gaugeAddress: string): string {\n return Relayer.encodeGaugeWithdraw(\n gaugeAddress,\n sender,\n this.addresses.relayer,\n amount\n );\n }\n\n /**\n * Uses relayer to deposit user's BPT to gauge and sends to recipient\n *\n * @param recipient Recipient address.\n * @param gaugeAddress Gauge address.\n * @returns deposit call\n */\n buildDeposit(recipient: string, gaugeAddress: string): string {\n return Relayer.encodeGaugeDeposit(\n gaugeAddress,\n this.addresses.relayer,\n recipient,\n SWAP_RESULT.toString()\n );\n }\n\n /**\n * Uses relayer to approve itself to act in behalf of the user\n *\n * @param authorisation Encoded authorisation call.\n * @returns relayer approval call\n */\n buildSetRelayerApproval(authorisation: string): string {\n return Relayer.encodeSetRelayerApproval(\n this.addresses.relayer,\n true,\n authorisation\n );\n }\n}\n","import { StablePoolEncoder } from '@/pool-stable/encoder';\nimport { ADDRESSES } from './addresses';\nimport { Relayer } from '@/modules/relayer/relayer.module';\nimport { ExitPoolRequest } from '@/types';\nimport { BatchSwapStep, FundManagement, SwapType } from '@/modules/swaps/types';\nimport { Interface } from '@ethersproject/abi';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { MaxInt256 } from '@ethersproject/constants';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\n// TODO - Ask Nico to update Typechain?\nimport balancerRelayerAbi from '@/lib/abi/BalancerRelayer.json';\nconst balancerRelayerInterface = new Interface(balancerRelayerAbi);\n\nconst EXIT_MIMATIC = Relayer.toChainedReference('20');\nconst EXIT_DAI = Relayer.toChainedReference('21');\nconst EXIT_USDC = Relayer.toChainedReference('22');\nconst EXIT_USDT = Relayer.toChainedReference('23');\nconst SWAP_RESULT = Relayer.toChainedReference('24');\n\nexport class MaiusdBuilder {\n private addresses;\n\n constructor(networkId: 1 | 5 | 137) {\n this.addresses = ADDRESSES[networkId];\n }\n\n /**\n * Builds migration call data.\n * Migrates tokens from maiusd to maibbausd pool.\n * Tokens that are initially staked are re-staked at the end of migration. Non-staked are not.\n *\n * @param userAddress User address.\n * @param bptIn Amount of BPT tokens to migrate.\n * @param minBptOut Minimum of expected BPT out ot the migration flow.\n * @param staked Indicates whether tokens are initially staked or not.\n * @param authorisation Encoded authorisation call.\n * @returns Migration transaction request ready to send with signer.sendTransaction\n */\n calldata(\n userAddress: string,\n bptIn: string,\n minBptOut: string,\n staked: boolean,\n authorisation?: string\n ): {\n to: string;\n data: string;\n } {\n if (BigNumber.from(bptIn).lte(0))\n throw new BalancerError(BalancerErrorCode.INPUT_ZERO_NOT_ALLOWED);\n\n const relayer = this.addresses.relayer;\n let calls: string[] = [];\n\n if (authorisation) {\n calls = [this.buildSetRelayerApproval(authorisation)];\n }\n\n if (staked) {\n calls = [\n ...calls,\n this.buildWithdraw(userAddress, bptIn),\n this.buildExit(relayer, bptIn),\n this.buildSwap(relayer, minBptOut),\n this.buildDeposit(userAddress),\n ];\n } else {\n calls = [\n ...calls,\n this.buildExit(userAddress, bptIn),\n this.buildSwap(userAddress, minBptOut),\n ];\n }\n\n const callData = balancerRelayerInterface.encodeFunctionData('multicall', [\n calls,\n ]);\n\n return {\n to: relayer,\n data: callData,\n };\n }\n\n /**\n * Encodes exitPool callData.\n * Exit maiusd pool proportionally to underlying stables. Exits to relayer.\n * Outputreferences are used to store exit amounts for next transaction.\n *\n * @param sender Sender address.\n * @param amount Amount of BPT to exit with.\n * @returns Encoded exitPool call. Output references.\n */\n buildExit(sender: string, amount: string): string {\n const { assetOrder } = this.addresses.maiusd;\n const assets = assetOrder.map(\n (key) => this.addresses[key as keyof typeof this.addresses] as string\n );\n\n // Assume gaugeWithdraw returns same amount value\n const userData = StablePoolEncoder.exitExactBPTInForTokensOut(amount);\n\n // Store exit outputs to be used as swaps inputs\n const outputReferences = [\n { index: assetOrder.indexOf('miMATIC'), key: EXIT_MIMATIC },\n { index: assetOrder.indexOf('DAI'), key: EXIT_DAI },\n { index: assetOrder.indexOf('USDC'), key: EXIT_USDC },\n { index: assetOrder.indexOf('USDT'), key: EXIT_USDT },\n ];\n\n const minAmountsOut = Array<string>(assets.length).fill('0');\n\n const callData = Relayer.constructExitCall({\n assets,\n minAmountsOut,\n userData,\n toInternalBalance: true,\n poolId: this.addresses.maiusd.id,\n poolKind: 0, // This will always be 0 to match supported Relayer types\n sender,\n recipient: this.addresses.relayer,\n outputReferences,\n exitPoolRequest: {} as ExitPoolRequest,\n });\n\n return callData;\n }\n\n /**\n * Creates encoded batchSwap function with following swaps: stables -> linear pools -> boosted pool\n * outputreferences should contain the amount of resulting BPT.\n *\n * @param recipient Sender address.\n * @param minBptOut Minimum BPT out expected from the join transaction.\n * @returns Encoded batchSwap call. Output references.\n */\n buildSwap(recipient: string, minBptOut: string): string {\n const assets = [\n this.addresses.bbausd2.address,\n this.addresses.DAI,\n this.addresses.linearDai2.address,\n this.addresses.USDC,\n this.addresses.linearUsdc2.address,\n this.addresses.USDT,\n this.addresses.linearUsdt2.address,\n this.addresses.miMATIC,\n this.addresses.maibbausd.address,\n ];\n\n const outputReferences = [{ index: 8, key: SWAP_RESULT }];\n\n const swaps: BatchSwapStep[] = [\n {\n poolId: this.addresses.linearDai2.id,\n assetInIndex: 1,\n assetOutIndex: 2,\n amount: EXIT_DAI.toString(),\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd2.id,\n assetInIndex: 2,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.maibbausd.id,\n assetInIndex: 0,\n assetOutIndex: 8,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.linearUsdc2.id,\n assetInIndex: 3,\n assetOutIndex: 4,\n amount: EXIT_USDC.toString(),\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd2.id,\n assetInIndex: 4,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.maibbausd.id,\n assetInIndex: 0,\n assetOutIndex: 8,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.linearUsdt2.id,\n assetInIndex: 5,\n assetOutIndex: 6,\n amount: EXIT_USDT.toString(),\n userData: '0x',\n },\n {\n poolId: this.addresses.bbausd2.id,\n assetInIndex: 6,\n assetOutIndex: 0,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.maibbausd.id,\n assetInIndex: 0,\n assetOutIndex: 8,\n amount: '0',\n userData: '0x',\n },\n {\n poolId: this.addresses.maibbausd.id,\n assetInIndex: 7,\n assetOutIndex: 8,\n amount: EXIT_MIMATIC.toString(),\n userData: '0x',\n },\n ];\n\n // For tokens going in to the Vault, the limit shall be a positive number. For tokens going out of the Vault, the limit shall be a negative number.\n const limits = [\n '0',\n MaxInt256.toString(),\n '0',\n MaxInt256.toString(),\n '0',\n MaxInt256.toString(),\n '0',\n MaxInt256.toString(),\n BigNumber.from(minBptOut).mul(-1).toString(),\n ];\n\n // Swap to/from Relayer\n const funds: FundManagement = {\n sender: this.addresses.relayer,\n recipient,\n fromInternalBalance: true,\n toInternalBalance: false,\n };\n\n const encodedBatchSwap = Relayer.encodeBatchSwap({\n swapType: SwapType.SwapExactIn,\n swaps,\n assets,\n funds,\n limits,\n deadline: BigNumber.from(Math.ceil(Date.now() / 1000) + 3600), // 1 hour from now\n value: '0',\n outputReferences,\n });\n\n return encodedBatchSwap;\n }\n\n /**\n * Uses relayer to withdraw staked BPT from gauge and send to relayer\n *\n * @param sender Sender address.\n * @param amount Amount of BPT to exit with.\n * @returns withdraw call\n */\n buildWithdraw(sender: string, amount: string): string {\n return Relayer.encodeGaugeWithdraw(\n this.addresses.maiusd.gauge,\n sender,\n this.addresses.relayer,\n amount\n );\n }\n\n /**\n * Uses relayer to deposit user's BPT to gauge and sends to recipient\n *\n * @param recipient Recipient address.\n * @returns deposit call\n */\n buildDeposit(recipient: string): string {\n return Relayer.encodeGaugeDeposit(\n this.addresses.maibbausd.gauge,\n this.addresses.relayer,\n recipient,\n SWAP_RESULT.toString()\n );\n }\n\n /**\n * Uses relayer to approve itself to act in behalf of the user\n *\n * @param authorisation Encoded authorisation call.\n * @returns relayer approval call\n */\n buildSetRelayerApproval(authorisation: string): string {\n return Relayer.encodeSetRelayerApproval(\n this.addresses.relayer,\n true,\n authorisation\n );\n }\n}\n","import { defaultAbiCoder } from '@ethersproject/abi';\nimport { StaBal3Builder } from './bbausd2-migrations/stabal3';\nimport { BbaUsd1Builder } from './bbausd2-migrations/bbausd1';\nimport { StablesBuilder } from './bbausd2-migrations/stables';\nimport { MaiusdBuilder } from './bbausd2-migrations/maiusd';\n\nexport class Migrations {\n constructor(private network: 1 | 5 | 137) {}\n\n /**\n * Builds migration call data.\n * Migrates tokens from staBal3 to bbausd2 pool.\n * Tokens that are initially staked are re-staked at the end of migration. Non-staked are not.\n *\n * @param userAddress User address.\n * @param staBal3Amount Amount of BPT tokens to migrate.\n * @param minBbausd2Out Minimum of expected BPT out ot the migration flow.\n * @param staked Indicates whether tokens are initially staked or not.\n * @param authorisation Encoded authorisation call.\n * @returns Migration transaction request ready to send with signer.sendTransaction\n */\n stabal3(\n userAddress: string,\n staBal3Amount: string,\n minBbausd2Out: string,\n staked: boolean,\n authorisation?: string\n ): {\n to: string;\n data: string;\n decode: (output: string, staked: boolean) => string;\n } {\n const builder = new StaBal3Builder(this.network);\n const request = builder.calldata(\n userAddress,\n staBal3Amount,\n minBbausd2Out,\n staked,\n authorisation\n );\n\n return {\n to: request.to,\n data: request.data,\n decode: (output, staked) => {\n let swapIndex = staked ? 2 : 1;\n if (authorisation) swapIndex += 1;\n const multicallResult = defaultAbiCoder.decode(['bytes[]'], output);\n const swapDeltas = defaultAbiCoder.decode(\n ['int256[]'],\n multicallResult[0][swapIndex]\n );\n // bbausd2AmountOut\n return swapDeltas[0][0].abs().toString();\n },\n };\n }\n\n /**\n * Builds migration call data.\n * Migrates tokens from bbausd1 to bbausd2 pool.\n * Tokens that are initially staked are re-staked at the end of migration. Non-staked are not.\n *\n * @param userAddress User address.\n * @param bbausd1Amount Amount of BPT tokens to migrate.\n * @param minBbausd2Out Minimum of expected BPT out ot the migration flow.\n * @param staked Indicates whether tokens are initially staked or not.\n * @param tokenBalances Token balances in EVM scale. Array must have the same length and order as tokens in pool being migrated from. Refer to [getPoolTokens](https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/interfaces/contracts/vault/IVault.sol#L334).\n * @param authorisation Encoded authorisation call.\n * @returns Migration transaction request ready to send with signer.sendTransaction\n */\n bbaUsd(\n userAddress: string,\n bbausd1Amount: string,\n minBbausd2Out: string,\n staked: boolean,\n tokenBalances: string[],\n authorisation?: string\n ): {\n to: string;\n data: string;\n decode: (output: string, staked: boolean) => string;\n } {\n const builder = new BbaUsd1Builder(this.network);\n const request = builder.calldata(\n userAddress,\n bbausd1Amount,\n minBbausd2Out,\n staked,\n tokenBalances,\n authorisation\n );\n\n return {\n to: request.to,\n data: request.data,\n decode: (output, staked) => {\n let swapIndex = staked ? 1 : 0;\n if (authorisation) swapIndex += 1;\n const multicallResult = defaultAbiCoder.decode(['bytes[]'], output);\n const swapDeltas = defaultAbiCoder.decode(\n ['int256[]'],\n multicallResult[0][swapIndex]\n );\n return swapDeltas[0][0].abs().toString(); // bptOut\n },\n };\n }\n\n /**\n * Builds migration call data.\n * Migrates tokens from old stable to new stable phantom pools with the same underlying tokens.\n * Tokens that are initially staked are re-staked at the end of migration. Non-staked are not.\n *\n * @param userAddress User address.\n * @param from Pool info being migrated from\n * @param to Pool info being migrated to\n * @param bptIn Amount of BPT tokens to migrate.\n * @param minBptOut Minimum of expected BPT out ot the migration flow.\n * @param staked Indicates whether tokens are initially staked or not.\n * @param underlyingTokens Underlying token addresses. Array must have the same length and order as tokens in pool being migrated from. Refer to [getPoolTokens](https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/interfaces/contracts/vault/IVault.sol#L334).\n * @param authorisation Encoded authorisation call.\n * @returns Migration transaction request ready to send with signer.sendTransaction\n */\n stables(\n userAddress: string,\n from: { id: string; address: string; gauge?: string },\n to: { id: string; address: string; gauge?: string },\n bptIn: string,\n minBptOut: string,\n staked: boolean,\n underlyingTokens: string[],\n authorisation?: string\n ): {\n to: string;\n data: string;\n decode: (output: string, staked: boolean) => string;\n } {\n const builder = new StablesBuilder(this.network);\n const request = builder.calldata(\n userAddress,\n from,\n to,\n bptIn,\n minBptOut,\n staked,\n underlyingTokens,\n authorisation\n );\n\n return {\n to: request.to,\n data: request.data,\n decode: (output, staked) => {\n let swapIndex = staked ? 2 : 1;\n if (authorisation) swapIndex += 1;\n const multicallResult = defaultAbiCoder.decode(['bytes[]'], output);\n const swapDeltas = defaultAbiCoder.decode(\n ['int256[]'],\n multicallResult[0][swapIndex]\n );\n // bbausd2AmountOut\n return swapDeltas[0][0].abs().toString();\n },\n };\n }\n\n /**\n * Builds migration call data.\n * Migrates tokens from staBal3 to bbausd2 pool.\n * Tokens that are initially staked are re-staked at the end of migration. Non-staked are not.\n *\n * @param userAddress User address.\n * @param bptIn Amount of BPT tokens to migrate.\n * @param minBptOut Minimum of expected BPT out ot the migration flow.\n * @param staked Indicates whether tokens are initially staked or not.\n * @param authorisation Encoded authorisation call.\n * @returns Migration transaction request ready to send with signer.sendTransaction\n */\n maiusd(\n userAddress: string,\n bptIn: string,\n minBptOut: string,\n staked: boolean,\n authorisation?: string\n ): {\n to: string;\n data: string;\n decode: (output: string, staked: boolean) => string;\n } {\n const builder = new MaiusdBuilder(this.network);\n const request = builder.calldata(\n userAddress,\n bptIn,\n minBptOut,\n staked,\n authorisation\n );\n\n return {\n to: request.to,\n data: request.data,\n decode: (output, staked) => {\n let swapIndex = staked ? 2 : 1;\n if (authorisation) swapIndex += 1;\n const multicallResult = defaultAbiCoder.decode(['bytes[]'], output);\n const swapDeltas = defaultAbiCoder.decode(\n ['int256[]'],\n multicallResult[0][swapIndex]\n );\n const bptOut = swapDeltas[0][8].abs().toString();\n return bptOut;\n },\n };\n }\n}\n","import { Network } from '@/lib/constants/network';\nimport { Migrations } from './migrations';\n\nexport class Zaps {\n public migrations: Migrations;\n\n constructor(public network: Network) {\n this.migrations = new Migrations(network as 1 | 5);\n }\n}\n","/**\n * Calculate the Impermanent Loss for a given pool and user.\n *\n * 1. Prepare the data:\n * a. get exit price for pools' tokens\n * b. get entry price for pools' tokens\n * 2. calculate delta values for tokens in pools\n * 3. calculate and return the impermanent loss as percentage rounded to 2 decimal places.\n *\n */\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { Findable, Pool, PoolToken, Price } from '@/types';\n\ntype Asset = {\n priceDelta: number;\n weight: number;\n};\n\ntype TokenPrices = {\n [key: string]: number;\n};\n\nexport class ImpermanentLossService {\n constructor(\n private tokenPrices: Findable<Price>,\n private tokenHistoricalPrices: Findable<Price>\n ) {}\n\n /**\n * entry point to calculate impermanent loss.\n *\n * The function will\n * - retrieve the tokens' historical value at the desired time in the future\n * - calculate the relative variation between current and historical value\n * - return the IL in percentage rounded to 2 decimal places\n *\n * @param timestamp UNIX timestamp from which the IL is desired\n * @param pool the pool\n * @returns the impermanent loss as percentage rounded to 2 decimal places\n */\n async calcImpLoss(timestamp: number, pool: Pool): Promise<number> {\n if (timestamp * 1000 >= Date.now()) {\n console.error(\n `[ImpermanentLossService][calcImpLoss]Error: ${BalancerError.getMessage(\n BalancerErrorCode.TIMESTAMP_IN_THE_FUTURE\n )}`\n );\n throw new BalancerError(BalancerErrorCode.TIMESTAMP_IN_THE_FUTURE);\n }\n const assets = await this.prepareData(timestamp, pool);\n\n const poolValueDelta = this.getPoolValueDelta(assets);\n const holdValueDelta = this.getHoldValueDelta(assets);\n\n const impLoss = this.calculateImpermanentLoss(\n poolValueDelta,\n holdValueDelta\n );\n return impLoss;\n }\n\n calculateImpermanentLoss(\n poolValueDelta: number,\n holdValueDelta: number\n ): number {\n return (\n Math.floor(Math.abs(poolValueDelta / holdValueDelta - 1) * 100 * 100) /\n 100\n );\n }\n\n getPoolValueDelta(assets: Asset[]): number {\n return assets.reduce(\n (result, asset) =>\n result * Math.pow(Math.abs(asset.priceDelta + 1), asset.weight),\n 1\n );\n }\n\n getHoldValueDelta(assets: Asset[]): number {\n return assets.reduce(\n (result, asset) => result + Math.abs(asset.priceDelta + 1) * asset.weight,\n 0\n );\n }\n\n /**\n * prepare the data for calculating the impermanent loss\n *\n * @param entryTimestamp UNIX timestamp from which the IL is desired\n * @param pool the pool\n * @returns a list of pair weight/price delta for each token in the pool\n * @throws BalancerError if\n * 1. a token's price is unknown\n * 2. a token's weight is unknown\n * 3. the user has no liquidity invested in the pool\n */\n async prepareData(entryTimestamp: number, pool: Pool): Promise<Asset[]> {\n const poolTokens = pool.tokens.filter(\n (token) => token.address !== pool.address\n );\n\n const weights = this.getWeights(poolTokens);\n\n const tokenAddresses = poolTokens.map((t) => t.address);\n\n const entryPrices = await this.getEntryPrices(\n entryTimestamp,\n tokenAddresses\n );\n const exitPrices: TokenPrices = await this.getExitPrices(poolTokens);\n\n return this.getAssets(poolTokens, exitPrices, entryPrices, weights);\n }\n\n getAssets(\n poolTokens: PoolToken[],\n exitPrices: TokenPrices,\n entryPrices: TokenPrices,\n weights: number[]\n ): Asset[] {\n return poolTokens.map((token, i) => ({\n priceDelta: this.getDelta(\n entryPrices[token.address],\n exitPrices[token.address]\n ),\n weight: weights[i],\n }));\n }\n\n getDelta(entryPrice: number, exitPrice: number): number {\n if (entryPrice === 0) {\n console.error(\n `[ImpermanentLossService][getDelta]Error: ${BalancerError.getMessage(\n BalancerErrorCode.ILLEGAL_PARAMETER\n )}: entry price is 0`\n );\n throw new BalancerError(BalancerErrorCode.ILLEGAL_PARAMETER);\n }\n return (exitPrice - entryPrice) / entryPrice;\n }\n\n /**\n * returns the list of token's weights.\n *\n * @param poolTokens the pools' tokens\n * @returns the list of token's weights\n * @throws BalancerError if a token's weight is missing\n *\n */\n getWeights(poolTokens: PoolToken[]): number[] {\n const noWeights = poolTokens.every((token) => !token.weight);\n const uniformWeight = Math.round((1 / poolTokens.length) * 100) / 100;\n const weights: number[] = noWeights\n ? poolTokens.map(() => uniformWeight) // if no weight is returned we assume the tokens are balanced uniformly in the pool\n : poolTokens.map((token) => Number(token.weight ?? 0));\n\n if (weights.some((w) => w === 0)) {\n console.error(\n `[ImpermanentLossService][getWeights]Error: ${BalancerError.getMessage(\n BalancerErrorCode.MISSING_WEIGHT\n )}`\n );\n throw new BalancerError(BalancerErrorCode.MISSING_WEIGHT);\n }\n return weights;\n }\n\n /**\n * get the current's tokens' prices\n * @param tokens the pools' tokens\n * @returns a list of tokens with prices\n */\n async getExitPrices(tokens: PoolToken[]): Promise<TokenPrices> {\n const prices = await Promise.all(\n tokens.map((token) => this.tokenPrices.find(token.address))\n ).catch(() => []);\n\n if (!prices.length || prices.some((price) => price?.usd === undefined)) {\n console.error(\n `[ImpermanentLossService][getExitPrices]Error: ${BalancerError.getMessage(\n BalancerErrorCode.MISSING_PRICE_RATE\n )}`\n );\n throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n }\n\n const tokensWithPrice = tokens.map((token, i) => ({\n ...token,\n price: prices[i],\n }));\n\n const tokenPrices: TokenPrices = {};\n for (const token of tokensWithPrice) {\n if (token.price?.usd) tokenPrices[token.address] = +token.price.usd; // price.usd is never undefined but JS complains\n }\n return tokenPrices;\n }\n\n /**\n * get the tokens' price at a given time\n *\n * @param timestamp the Unix timestamp\n * @param tokenAddresses the tokens' addresses\n * @returns a map of tokens' price\n */\n async getEntryPrices(\n timestamp: number,\n tokenAddresses: string[]\n ): Promise<TokenPrices> {\n const prices: TokenPrices = {};\n for (const address of tokenAddresses) {\n const price = await this.tokenHistoricalPrices\n .findBy(address, timestamp)\n .catch((reason) => {\n console.error(\n `[ImpermanentLossService][getEntryPrices]Error: ${reason.message}`\n );\n return undefined;\n });\n if (!price?.usd) {\n console.error(\n `[ImpermanentLossService][getEntryPrices]Error: ${BalancerError.getMessage(\n BalancerErrorCode.MISSING_PRICE_RATE\n )}`\n );\n throw new BalancerError(BalancerErrorCode.MISSING_PRICE_RATE);\n }\n prices[address] = +price.usd;\n }\n return prices;\n }\n}\n","/**\n * Weekly Bal emissions are fixed / year according to:\n * https://docs.google.com/spreadsheets/d/1FY0gi596YWBOTeu_mrxhWcdF74SwKMNhmu0qJVgs0KI/edit#gid=0\n *\n * Using regular numbers for simplicity assuming frontend use only.\n *\n * Calculation source\n * https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/liquidity-mining/contracts/BalancerTokenAdmin.sol\n */\n\n// export const INITIAL_RATE = 145000; // Testnet\n// export const INITIAL_RATE = 375000; // Mainnet\nexport const INITIAL_RATE = 335000; // Gauge v3.1\n\n// export const START_EPOCH_TIME = 1759363200; // Oasys Testnet\nexport const START_EPOCH_TIME = 1759363200; // Oasys Mainnet // Thu Oct 02 2025 00:00:00 GMT+0000\n\nconst RATE_REDUCTION_TIME = 365 * 86400;\nconst RATE_REDUCTION_COEFFICIENT = 2 ** (1 / 4);\n\n/**\n * Weekly BAL emissions\n *\n * @param currentTimestamp used to get the epoch\n * @returns BAL emitted in a week\n */\nexport const weekly = (\n currentTimestamp: number = Math.round(new Date().getTime() / 1000)\n): number => {\n // const miningEpoch = Math.floor(\n // (currentTimestamp - START_EPOCH_TIME) / RATE_REDUCTION_TIME\n // );\n\n // const rate = INITIAL_RATE * RATE_REDUCTION_COEFFICIENT ** -miningEpoch;\n return INITIAL_RATE;\n};\n\n/**\n * Total BAL emitted in epoch (1 year)\n *\n * @param epoch starting from 0 for the first year of emissions\n * @returns BAL emitted in epoch\n */\nexport const total = (epoch: number): number => {\n // const weeklyRate = INITIAL_RATE * RATE_REDUCTION_COEFFICIENT ** -epoch;\n // const dailyRate = weeklyRate / 7;\n const weeklyRate = weekly();\n const dailyRate = weeklyRate / 7;\n\n return dailyRate * 365;\n};\n\n/**\n * Total BAL emitted between two timestamps\n *\n * @param start starting timestamp\n * @param end ending timestamp\n * @returns BAL emitted in period\n */\nexport const between = (start: number, end: number): number => {\n if (start < START_EPOCH_TIME) {\n throw 'start timestamp before emission schedule deployment';\n }\n if (end < start) {\n throw 'cannot finish before starting';\n }\n\n /*\n let totalEmissions = 0;\n\n const startingEpoch = Math.floor(\n (start - START_EPOCH_TIME) / RATE_REDUCTION_TIME\n );\n const endingEpoch = Math.floor(\n (end - START_EPOCH_TIME) / RATE_REDUCTION_TIME\n );\n\n for (\n let currentEpoch = startingEpoch;\n currentEpoch <= endingEpoch;\n currentEpoch++\n ) {\n totalEmissions += total(currentEpoch);\n }\n\n // Subtract what isn't emmited within the time range\n const startingEpochEnd =\n START_EPOCH_TIME + RATE_REDUCTION_TIME * (startingEpoch + 1);\n const endingEpochStart = START_EPOCH_TIME + RATE_REDUCTION_TIME * endingEpoch;\n\n const secondsInStartingEpoch = startingEpochEnd - start;\n const secondsInEndingEpoch = end - endingEpochStart;\n\n totalEmissions -=\n (total(startingEpoch) * (RATE_REDUCTION_TIME - secondsInStartingEpoch)) /\n RATE_REDUCTION_TIME;\n totalEmissions -=\n (total(endingEpoch) * (RATE_REDUCTION_TIME - secondsInEndingEpoch)) /\n RATE_REDUCTION_TIME;\n\n return totalEmissions;*/\n\n const dt = end - start;\n const weeklyRate = weekly();\n const dailyRate = weeklyRate / 7;\n return Math.round(dt / 86400) * dailyRate;\n};\n","import { Findable, Price } from '@/types';\nimport { BaseFeeDistributor } from '@/modules/data';\n\nexport interface ProtocolRevenueData {\n lastWeekBalRevenue: number;\n lastWeekBBAUsdRevenue: number;\n veBalSupply: number;\n}\n\nexport class ProtocolRevenue {\n constructor(\n private repository: BaseFeeDistributor,\n private tokenPrices: Findable<Price>\n ) {}\n\n async data(now = Date.now()): Promise<ProtocolRevenueData> {\n const data = await this.repository.multicallData(now);\n const balPrice = await this.tokenPrices.find(data.balAddress);\n\n if (!balPrice || !balPrice.usd) {\n throw `No BAL USD price found`;\n }\n\n return {\n lastWeekBalRevenue: data.balAmount * parseFloat(balPrice.usd),\n lastWeekBBAUsdRevenue: data.bbAUsdAmount * data.bbAUsdPrice,\n veBalSupply: data.veBalSupply,\n };\n }\n}\n","/**\n * Calculates pool fees\n *\n * 1. Pool fees in last 24hrs\n */\nimport { isLessThan24Hours } from '@/lib/utils/time';\nimport { Pool, Findable, PoolAttribute } from '@/types';\n\nexport class PoolFees {\n constructor(\n private yesterdaysPools: Findable<Pool, PoolAttribute> | undefined\n ) {}\n\n // 🚨 this is adding 1 call to get yesterday's block height and 2nd call to fetch yesterday's pools data from subgraph\n // TODO: find a better data source for that eg. add blocks to graph, replace with a database, or dune\n async last24h(pool: Pool): Promise<number> {\n let yesterdaysPool;\n if (this.yesterdaysPools) {\n yesterdaysPool = await this.yesterdaysPools.find(pool.id);\n }\n if (!pool.totalSwapFee) {\n return 0;\n }\n\n if (!yesterdaysPool?.totalSwapFee) {\n // Process edge case when pool creation time is less that 24h\n if (pool.createTime && isLessThan24Hours(pool.createTime)) {\n return parseFloat(pool.totalSwapFee);\n }\n return 0;\n }\n\n return (\n parseFloat(pool.totalSwapFee) - parseFloat(yesterdaysPool.totalSwapFee)\n );\n }\n}\n","import { formatUnits } from '@ethersproject/units';\nimport * as emissions from '@/modules/data/bal/emissions';\nimport type {\n Findable,\n Pool,\n PoolAttribute,\n Price,\n Token,\n TokenAttribute,\n LiquidityGauge,\n Network,\n PoolToken,\n} from '@/types';\nimport { BaseFeeDistributor, RewardData } from '@/modules/data';\nimport { ProtocolRevenue } from './protocol-revenue';\nimport { Liquidity } from '@/modules/liquidity/liquidity.module';\nimport { identity, zipObject, pickBy } from 'lodash';\nimport { PoolFees } from '../fees/fees';\nimport { BALANCER_NETWORK_CONFIG } from '@/lib/constants/config';\n\nexport interface AprBreakdown {\n swapFees: number;\n tokenAprs: {\n total: number;\n breakdown: { [address: string]: number };\n };\n stakingApr: {\n min: number;\n max: number;\n };\n rewardAprs: {\n total: number;\n breakdown: { [address: string]: number };\n };\n protocolApr: number;\n min: number;\n max: number;\n}\n\n/**\n * Calculates pool APR via summing up sources of APR:\n *\n * 1. Swap fees (pool level) data coming from subgraph\n * 2. Yield bearing pool tokens, with data from external sources eg: http endpoints, subgraph, onchain\n * * stETH\n * * aave\n * * usd+\n * map token: calculatorFn\n * 3. Staking rewards based from veBal gauges\n */\nexport class PoolApr {\n constructor(\n private pools: Findable<Pool, PoolAttribute>,\n private tokenPrices: Findable<Price>,\n private tokenMeta: Findable<Token, TokenAttribute>,\n private tokenYields: Findable<number>,\n private feeCollector: Findable<number>,\n private yesterdaysPools?: Findable<Pool, PoolAttribute>,\n private liquidityGauges?: Findable<LiquidityGauge>,\n private feeDistributor?: BaseFeeDistributor\n ) {}\n\n /**\n * Pool revenue via swap fees.\n * Fees and liquidity are takes from subgraph as USD floats.\n *\n * @returns APR [bsp] from fees accumulated over last 24h\n */\n async swapFees(pool: Pool): Promise<number> {\n // 365 * dailyFees * (1 - protocolFees) / totalLiquidity\n const last24hFees = await this.last24hFees(pool);\n const totalLiquidity = await this.totalLiquidity(pool);\n // TODO: what to do when we are missing last24hFees or totalLiquidity?\n // eg: stable phantom returns 0\n if (!last24hFees || !totalLiquidity) {\n return 0;\n }\n const dailyFees =\n last24hFees * (1 - (await this.protocolSwapFeePercentage(pool)));\n const feesDailyBsp = 10000 * (dailyFees / parseFloat(totalLiquidity));\n\n return Math.round(365 * feesDailyBsp);\n }\n\n /**\n * Pool revenue from holding yield-bearing wrapped tokens.\n *\n * @returns APR [bsp] from tokens contained in the pool\n */\n async tokenAprs(pool: Pool): Promise<AprBreakdown['tokenAprs']> {\n // Hung: GamingDex has no token aprs\n return {\n total: 0,\n breakdown: {},\n };\n\n // if (!pool.tokens) {\n // return {\n // total: 0,\n // breakdown: {},\n // };\n // }\n\n // const totalLiquidity = await this.totalLiquidity(pool);\n\n // // Filter out BPT: token with the same address as the pool\n // // TODO: move this to data layer\n // const bptFreeTokens = pool.tokens.filter((token) => {\n // return token.address !== pool.address;\n // });\n\n // // Get each token APRs\n // const aprs = await Promise.all(\n // bptFreeTokens.map(async (token) => {\n // let apr = 0;\n // const tokenYield = await this.tokenYields.find(token.address);\n\n // if (tokenYield) {\n // if (pool.poolType === 'MetaStable') {\n // apr =\n // tokenYield * (1 - (await this.protocolSwapFeePercentage(pool)));\n // } else if (\n // pool.poolType === 'ComposableStable' ||\n // (pool.poolType === 'Weighted' && pool.poolTypeVersion === 2)\n // // (pool.poolType === 'Weighted' && pool.poolTypeVersion === 3) // Hung added\n // ) {\n // if (token.isExemptFromYieldProtocolFee) {\n // apr = tokenYield;\n // } else {\n // apr =\n // tokenYield *\n // (1 - parseFloat(pool.protocolYieldFeeCache || '0.5'));\n // }\n // } else {\n // apr = tokenYield;\n // }\n // } else {\n // // Handle subpool APRs with recursive call to get the subPool APR\n // const subPool = await this.pools.findBy('address', token.address);\n\n // if (subPool) {\n // // INFO: Liquidity mining APR can't cascade to other pools\n // const subSwapFees = await this.swapFees(subPool);\n // const subtokenAprs = await this.tokenAprs(subPool);\n // let subApr = subtokenAprs.total;\n // if (\n // pool.poolType === 'ComposableStable' ||\n // (pool.poolType === 'Weighted' && pool.poolTypeVersion === 2)\n // // (pool.poolType === 'Weighted' && pool.poolTypeVersion === 3) // Hung added\n // ) {\n // if (!token.isExemptFromYieldProtocolFee) {\n // subApr =\n // subApr *\n // (1 - parseFloat(pool.protocolYieldFeeCache || '0.5'));\n // }\n // }\n // apr = subSwapFees + subApr;\n // }\n // }\n\n // return apr;\n // })\n // );\n\n // // Get token weights normalised by usd price\n // const getWeight = async (token: PoolToken): Promise<number> => {\n // let tokenPrice: string | undefined;\n // if (token.weight) {\n // return parseFloat(token.weight);\n // } else if (token.token?.pool?.poolType) {\n // const poolToken = await this.pools.findBy('address', token.address);\n // if (poolToken) {\n // tokenPrice = (await this.bptPrice(poolToken)).toString();\n // }\n // } else {\n // tokenPrice =\n // token.price?.usd ||\n // (await this.tokenPrices.find(token.address))?.usd ||\n // token.token?.latestUSDPrice;\n // }\n // if (tokenPrice) {\n // // using floats assuming frontend purposes with low precision needs\n // const tokenValue = parseFloat(token.balance) * parseFloat(tokenPrice);\n // return tokenValue / parseFloat(totalLiquidity);\n // } else {\n // throw `No price for ${token.address}`;\n // }\n // };\n\n // // Normalise tokenAPRs according to weights\n // const weightedAprs = await Promise.all(\n // bptFreeTokens.map(async (token, idx) => {\n // if (aprs[idx] === 0) {\n // return 0;\n // }\n\n // const weight = await getWeight(token);\n // return Math.round(aprs[idx] * weight);\n // })\n // );\n\n // // sum them up to get pool APRs\n // const apr = weightedAprs.reduce((sum, apr) => sum + apr, 0);\n // const breakdown = pickBy(\n // zipObject(\n // bptFreeTokens.map((t) => t.address),\n // weightedAprs\n // ),\n // identity\n // );\n\n // return {\n // total: apr,\n // breakdown,\n // };\n }\n\n /**\n * Calculates staking rewards based on veBal gauges deployed with Curve Finance contracts.\n * https://curve.readthedocs.io/dao-gauges.html\n *\n * Terminology:\n * - LP token of a gauge is a BPT of a pool\n * - Depositing into a gauge is called staking on the frontend\n * - gauge totalSupply - BPT tokens deposited to a gauge\n * - gauge workingSupply - effective BPT tokens participating in reward distribution. sum of 40% deposit + 60% boost from individual user's veBal\n * - gauge relative weight - weight of this gauge in bal inflation distribution [0..1] scaled to 1e18\n *\n * APR sources:\n * - gauge BAL emissions = min: 40% of totalSupply, max: 40% of totalSupply + 60% of totalSupply * gauge LPs voting power\n * https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/liquidity-mining/contracts/gauges/ethereum/LiquidityGaugeV5.vy#L338\n * - gauge reward tokens: Admin or designated depositor has an option to deposit additional reward with a weekly accruing cadence.\n * https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/liquidity-mining/contracts/gauges/ethereum/LiquidityGaugeV5.vy#L641\n * rate: amount of token per second\n *\n * @param pool\n * @param boost range between 1 and 2.5\n * @returns APR [bsp] from protocol rewards.\n */\n async stakingApr(pool: Pool, boost = 1): Promise<number> {\n if (!this.liquidityGauges) {\n return 0;\n }\n // Data resolving\n const gauge = await this.liquidityGauges.findBy('poolId', pool.id);\n // Hung\n if (\n !gauge ||\n ((pool.chainId == 248 || pool.chainId == 9372) &&\n gauge.workingSupply == 0) ||\n (pool.chainId != 248 &&\n pool.chainId != 9372 &&\n pool.chainId > 1 &&\n gauge.totalSupply == 0)\n ) {\n return 0;\n }\n const bal =\n BALANCER_NETWORK_CONFIG[pool.chainId as Network].addresses.tokens.bal;\n if (!bal) {\n return 0;\n }\n\n const [balPrice, bptPriceUsd] = await Promise.all([\n this.tokenPrices.find(bal), // BAL\n this.bptPrice(pool),\n ]);\n if (!balPrice?.usd) {\n throw 'Missing BAL price';\n }\n const balPriceUsd = parseFloat(balPrice.usd);\n // Subgraph is returning BAL staking rewards as reward tokens for L2 gauges.\n // Hung: Disable L2\n // if (pool.chainId > 1 && pool.chainId != 16116) {\n // if (!gauge.rewardTokens) {\n // return 0;\n // }\n // const balReward = bal && gauge.rewardTokens[bal];\n // if (balReward) {\n // const reward = await this.rewardTokenApr(bal, balReward);\n // const totalSupplyUsd = gauge.totalSupply * bptPriceUsd;\n // const rewardValue = reward.value / totalSupplyUsd;\n // return Math.round(10000 * rewardValue);\n // } else {\n // return 0;\n // }\n // }\n\n const totalBalEmissions = (emissions.weekly() / 7) * 365;\n const gaugeBalEmissions = totalBalEmissions * gauge.relativeWeight;\n const gaugeBalEmissionsUsd = gaugeBalEmissions * balPriceUsd;\n const gaugeSupply = (gauge.workingSupply + 0.4) / 0.4; // Only 40% of LP token staked accrue emissions, totalSupply = workingSupply * 2.5\n const gaugeSupplyUsd = gaugeSupply * bptPriceUsd;\n const gaugeBalAprBps = Math.round(\n (boost * 10000 * gaugeBalEmissionsUsd) / gaugeSupplyUsd\n );\n\n // console.error(``);\n // console.error(`==balPriceUsd: ${balPriceUsd}`);\n // console.error(`==bptPriceUsd: ${bptPriceUsd}`);\n // console.error(`==relativeWeight: ${gauge.relativeWeight}`);\n // console.error(`==workingSupply: ${gauge.workingSupply}`);\n // console.error(`==gaugeSupply: ${gaugeSupply}`);\n // console.error(`--`);\n // console.error(`==boost: ${boost}`);\n // console.error(`==gaugeBalEmissionsUsd: ${gaugeBalEmissionsUsd}`);\n // console.error(`==gaugeSupplyUsd: ${gaugeSupplyUsd}`);\n // console.error(`==gaugeBalAprBps: ${gaugeBalAprBps}`);\n // console.error(``);\n\n return gaugeBalAprBps;\n }\n\n async stakingAprNextPeriod(pool: Pool, boost = 1): Promise<number> {\n if (!this.liquidityGauges) {\n return 0;\n }\n const gauge = await this.liquidityGauges.findBy('poolId', pool.id);\n\n // if (\n // !gauge ||\n // ((pool.chainId == 248 || pool.chainId == 9372) &&\n // gauge.workingSupply == 0) ||\n // (pool.chainId != 248 &&\n // pool.chainId != 9372 &&\n // pool.chainId > 1 &&\n // gauge.totalSupply == 0)\n // ) {\n // return -1;\n // }\n\n if (!gauge) {\n return 0;\n }\n\n if (gauge.workingSupply == 0) {\n if (\n gauge.relativeWeightNextPeriod &&\n gauge.relativeWeightNextPeriod > 0\n ) {\n return -1;\n }\n return 0;\n }\n\n const bal =\n BALANCER_NETWORK_CONFIG[pool.chainId as Network].addresses.tokens.bal;\n if (!bal) {\n return 0;\n }\n\n const [balPrice, bptPriceUsd] = await Promise.all([\n this.tokenPrices.find(bal), // BAL\n this.bptPrice(pool),\n ]);\n if (!balPrice?.usd) {\n throw 'Missing BAL price';\n }\n const balPriceUsd = parseFloat(balPrice.usd);\n // Subgraph is returning BAL staking rewards as reward tokens for L2 gauges.\n // Hung: Disable L2\n // if (pool.chainId > 1 && pool.chainId != 16116) {\n // if (!gauge.rewardTokens) {\n // return 0;\n // }\n // const balReward = bal && gauge.rewardTokens[bal];\n // if (balReward) {\n // const reward = await this.rewardTokenApr(bal, balReward);\n // const totalSupplyUsd = gauge.totalSupply * bptPriceUsd;\n // const rewardValue = reward.value / totalSupplyUsd;\n // return Math.round(10000 * rewardValue);\n // } else {\n // return 0;\n // }\n // }\n\n const totalBalEmissions = (emissions.weekly() / 7) * 365;\n const gaugeBalEmissions =\n totalBalEmissions * (gauge.relativeWeightNextPeriod || 0);\n const gaugeBalEmissionsUsd = gaugeBalEmissions * balPriceUsd;\n const gaugeSupply = (gauge.workingSupply + 0.4) / 0.4; // Only 40% of LP token staked accrue emissions, totalSupply = workingSupply * 2.5\n const gaugeSupplyUsd = gaugeSupply * bptPriceUsd;\n const gaugeBalAprBps = Math.round(\n (boost * 10000 * gaugeBalEmissionsUsd) / gaugeSupplyUsd\n );\n\n // console.error(``);\n // console.error(`==balPriceUsd: ${balPriceUsd}`);\n // console.error(`==bptPriceUsd: ${bptPriceUsd}`);\n // console.error(\n // `==relativeWeightNextPeriod: ${gauge.relativeWeightNextPeriod}`\n // );\n // console.error(`==workingSupply: ${gauge.workingSupply}`);\n // console.error(`==gaugeSupply: ${gaugeSupply}`);\n // console.error(`--`);\n // console.error(`==boost: ${boost}`);\n // console.error(`==gaugeBalEmissionsUsd: ${gaugeBalEmissionsUsd}`);\n // console.error(`==gaugeSupplyUsd: ${gaugeSupplyUsd}`);\n // console.error(`==gaugeBalAprBps: ${gaugeBalAprBps}`);\n // console.error(``);\n\n return gaugeBalAprBps;\n }\n\n /**\n * Some gauges are holding tokens distributed as rewards to LPs.\n *\n * @param pool\n * @returns APR [bsp] from token rewards.\n */\n async rewardAprs(pool: Pool): Promise<AprBreakdown['rewardAprs']> {\n if (!this.liquidityGauges) {\n return { total: 0, breakdown: {} };\n }\n\n // Data resolving\n const gauge = await this.liquidityGauges.findBy('poolId', pool.id);\n if (!gauge) {\n return { total: 0, breakdown: {} };\n }\n\n if (!gauge.rewardTokens) {\n return { total: 0, breakdown: {} };\n }\n\n if (Object.keys(gauge.rewardTokens).length < 1) {\n return { total: 0, breakdown: {} };\n }\n\n // BAL rewards already returned as stakingApr, so we can filter them out\n const bal =\n BALANCER_NETWORK_CONFIG[pool.chainId as Network].addresses.tokens.bal;\n const rewardTokenAddresses = Object.keys(gauge.rewardTokens).filter(\n (a) => a != bal\n );\n\n // Gets each tokens rate, extrapolate to a year and convert to USD\n const rewards = rewardTokenAddresses.map(async (tAddress) => {\n /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */\n const data = gauge!.rewardTokens![tAddress];\n return this.rewardTokenApr(tAddress, data);\n });\n\n // Get the gauge totalSupplyUsd\n const bptPriceUsd = await this.bptPrice(pool);\n const totalSupplyUsd = gauge.totalSupply * bptPriceUsd;\n\n // Hung: Check thu\n // if (totalSupplyUsd == 0) {\n // return { total: 0, breakdown: {} };\n // }\n\n const rewardTokensBreakdown: Record<string, number> = {};\n\n let total = 0;\n for await (const reward of Object.values(rewards)) {\n const rewardValue =\n totalSupplyUsd > 0 ? reward.value / totalSupplyUsd : 0;\n const rewardValueScaled = Math.round(10000 * rewardValue);\n total += rewardValueScaled;\n rewardTokensBreakdown[reward.address] = rewardValueScaled;\n }\n\n return {\n total,\n breakdown: rewardTokensBreakdown,\n };\n }\n\n /**\n * 80BAL-20WETH pool is accruing protocol revenue.\n *\n * @param pool\n * @returns accrued protocol revenue as APR [bsp]\n */\n async protocolApr(pool: Pool): Promise<number> {\n // const veBalPoolId =\n // '0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014';\n\n // Hung\n const veBalPoolId = '';\n\n if (pool.id != veBalPoolId || !this.feeDistributor) {\n return 0;\n }\n\n const revenue = new ProtocolRevenue(this.feeDistributor, this.tokenPrices);\n\n const { lastWeekBalRevenue, lastWeekBBAUsdRevenue, veBalSupply } =\n await revenue.data();\n\n const bptPrice = await this.bptPrice(pool);\n if (!bptPrice) {\n throw 'bptPrice for veBal pool missing';\n }\n\n const dailyRevenue = (lastWeekBalRevenue + lastWeekBBAUsdRevenue) / 7;\n const apr = Math.round(\n (10000 * (365 * dailyRevenue)) / (bptPrice * veBalSupply)\n );\n\n return apr;\n }\n\n /**\n * Composes all sources for total pool APR.\n *\n * @returns pool APR split [bsp]\n */\n async apr(pool: Pool): Promise<AprBreakdown> {\n const [\n swapFees,\n tokenAprs,\n minStakingApr,\n maxStakingApr,\n rewardAprs,\n protocolApr,\n ] = await Promise.all([\n this.swapFees(pool), // pool snapshot for last 24h fees dependency\n this.tokenAprs(pool),\n this.stakingApr(pool),\n this.stakingApr(pool, 2.5),\n this.rewardAprs(pool),\n this.protocolApr(pool),\n ]);\n\n return {\n swapFees,\n tokenAprs,\n stakingApr: {\n min: minStakingApr,\n max: maxStakingApr,\n },\n rewardAprs,\n protocolApr,\n min: swapFees + tokenAprs.total + rewardAprs.total + minStakingApr,\n max:\n swapFees +\n tokenAprs.total +\n rewardAprs.total +\n protocolApr +\n maxStakingApr,\n };\n }\n\n async aprNextPeriod(pool: Pool): Promise<AprBreakdown> {\n const [\n swapFees,\n tokenAprs,\n minStakingApr,\n maxStakingApr,\n rewardAprs,\n protocolApr,\n ] = await Promise.all([\n this.swapFees(pool), // pool snapshot for last 24h fees dependency\n this.tokenAprs(pool),\n this.stakingAprNextPeriod(pool),\n this.stakingAprNextPeriod(pool, 2.5),\n this.rewardAprs(pool),\n this.protocolApr(pool),\n ]);\n\n return {\n swapFees,\n tokenAprs,\n stakingApr: {\n min: minStakingApr,\n max: maxStakingApr,\n },\n rewardAprs,\n protocolApr,\n min: swapFees + tokenAprs.total + rewardAprs.total + minStakingApr,\n max:\n swapFees +\n tokenAprs.total +\n rewardAprs.total +\n protocolApr +\n maxStakingApr,\n };\n }\n\n private async last24hFees(pool: Pool): Promise<number> {\n const poolFees = new PoolFees(this.yesterdaysPools);\n return poolFees.last24h(pool);\n }\n\n /**\n * Total Liquidity based on USD token prices taken from external price feed, eg: coingecko.\n *\n * @param pool\n * @returns Pool liquidity in USD\n */\n private async totalLiquidity(pool: Pool): Promise<string> {\n try {\n const liquidityService = new Liquidity(this.pools, this.tokenPrices);\n const liquidity = await liquidityService.getLiquidity(pool);\n return liquidity;\n } catch (err) {\n console.error('Liquidity calculcation failed, falling back to subgraph');\n return pool.totalLiquidity;\n }\n }\n\n /**\n * BPT price as pool totalLiquidity / pool total Shares\n * Total Liquidity is calculated based on USD token prices taken from external price feed, eg: coingecko.\n *\n * @param pool\n * @returns BPT price in USD\n */\n private async bptPrice(pool: Pool) {\n const _totalLiquidity = await this.totalLiquidity(pool);\n const _totalShares = pool.totalShares;\n return parseFloat(_totalLiquidity) / parseFloat(_totalShares);\n }\n\n private async protocolSwapFeePercentage(pool: Pool) {\n let fee = 0;\n\n if (\n pool.poolType == 'ComposableStable' ||\n (pool.poolType == 'Weighted' && pool.poolTypeVersion == 2)\n ) {\n fee = 0;\n } else if (pool.protocolSwapFeeCache) {\n fee = parseFloat(pool.protocolSwapFeeCache);\n } else {\n fee = (await this.feeCollector.find('')) || 0;\n }\n\n return fee;\n }\n\n private async rewardTokenApr(tokenAddress: string, rewardData: RewardData) {\n if (rewardData.period_finish.toNumber() < Date.now() / 1000) {\n return {\n address: tokenAddress,\n value: 0,\n };\n } else {\n const yearlyReward = rewardData.rate.mul(86400).mul(365);\n const price = await this.tokenPrices.find(tokenAddress);\n if (price && price.usd) {\n let decimals = 18;\n if (rewardData.decimals) {\n decimals = rewardData.decimals;\n } else {\n const meta = await this.tokenMeta.find(tokenAddress);\n if (meta && meta.decimals !== undefined) {\n decimals = meta.decimals;\n }\n }\n const yearlyRewardUsd =\n parseFloat(formatUnits(yearlyReward, decimals)) *\n parseFloat(price.usd);\n return {\n address: tokenAddress,\n value: yearlyRewardUsd,\n };\n } else {\n throw `No USD price for ${tokenAddress}`;\n }\n }\n }\n}\n","import { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { isSameAddress, parsePoolInfo } from '@/lib/utils';\nimport { Pool, PoolAttribute, PoolType } from '@/types';\nimport { Zero, WeiPerEther } from '@ethersproject/constants';\nimport { BigNumber, parseFixed } from '@ethersproject/bignumber';\nimport { Findable } from '../data/types';\nimport { PoolTypeConcerns } from '../pools/pool-type-concerns';\n\ntype SpotPrices = { [tokenIn: string]: string };\nexport interface Node {\n address: string;\n id: string;\n joinAction: JoinAction;\n exitAction: ExitAction;\n type: string;\n children: Node[];\n marked: boolean;\n index: string;\n proportionOfParent: BigNumber;\n parent: Node | undefined;\n isLeaf: boolean;\n spotPrices: SpotPrices;\n decimals: number;\n}\n\ntype JoinAction =\n | 'input'\n | 'batchSwap'\n | 'wrap'\n | 'joinPool'\n | 'wrapAaveDynamicToken'\n | 'wrapERC4626';\nconst joinActions = new Map<PoolType, JoinAction>();\njoinActions.set(PoolType.AaveLinear, 'batchSwap');\njoinActions.set(PoolType.EulerLinear, 'batchSwap');\njoinActions.set(PoolType.ERC4626Linear, 'batchSwap');\njoinActions.set(PoolType.Element, 'batchSwap');\njoinActions.set(PoolType.Investment, 'joinPool');\njoinActions.set(PoolType.LiquidityBootstrapping, 'joinPool');\njoinActions.set(PoolType.MetaStable, 'joinPool');\njoinActions.set(PoolType.Stable, 'joinPool');\njoinActions.set(PoolType.StablePhantom, 'batchSwap');\njoinActions.set(PoolType.Weighted, 'joinPool');\njoinActions.set(PoolType.ComposableStable, 'joinPool');\n\ntype ExitAction =\n | 'output'\n | 'batchSwap'\n | 'unwrap'\n | 'exitPool'\n | 'unwrapAaveStaticToken'\n | 'unwrapERC4626';\nconst exitActions = new Map<PoolType, ExitAction>();\nexitActions.set(PoolType.AaveLinear, 'batchSwap');\njoinActions.set(PoolType.EulerLinear, 'batchSwap');\nexitActions.set(PoolType.ERC4626Linear, 'batchSwap');\nexitActions.set(PoolType.Element, 'batchSwap');\nexitActions.set(PoolType.Investment, 'exitPool');\nexitActions.set(PoolType.LiquidityBootstrapping, 'exitPool');\nexitActions.set(PoolType.MetaStable, 'exitPool');\nexitActions.set(PoolType.Stable, 'exitPool');\nexitActions.set(PoolType.StablePhantom, 'batchSwap');\nexitActions.set(PoolType.Weighted, 'exitPool');\nexitActions.set(PoolType.ComposableStable, 'exitPool');\n\nexport class PoolGraph {\n constructor(private pools: Findable<Pool, PoolAttribute>) {}\n\n async buildGraphFromRootPool(\n poolId: string,\n wrapMainTokens: boolean\n ): Promise<Node> {\n const rootPool = await this.pools.find(poolId);\n if (!rootPool) throw new BalancerError(BalancerErrorCode.POOL_DOESNT_EXIST);\n const nodeIndex = 0;\n const rootNode = await this.buildGraphFromPool(\n rootPool.address,\n nodeIndex,\n undefined,\n WeiPerEther,\n wrapMainTokens\n );\n return rootNode[0];\n }\n\n getTokenTotal(pool: Pool): BigNumber {\n const bptIndex = pool.tokensList.indexOf(pool.address);\n let total = Zero;\n const { parsedBalances } = parsePoolInfo(pool);\n parsedBalances.forEach((balance, i) => {\n // Ignore phantomBpt balance\n if (bptIndex !== i) {\n total = total.add(balance);\n }\n });\n return total;\n }\n\n async buildGraphFromPool(\n address: string,\n nodeIndex: number,\n parent: Node | undefined,\n proportionOfParent: BigNumber,\n wrapMainTokens: boolean\n ): Promise<[Node, number]> {\n const pool = await this.pools.findBy('address', address);\n\n if (!pool) {\n if (!parent) {\n // If pool not found by address and is root pool (without parent), then throw error\n throw new BalancerError(BalancerErrorCode.POOL_DOESNT_EXIST);\n } else {\n // If pool not found by address, but it has parent, assume it's a leaf token and add a leafTokenNode\n // TODO: maybe it's a safety issue? Can we be safer?\n const parentPool = (await this.pools.findBy(\n 'address',\n parent.address\n )) as Pool;\n const leafTokenDecimals =\n parentPool.tokens[parentPool.tokensList.indexOf(address)].decimals ??\n 18;\n\n const nodeInfo = PoolGraph.createInputTokenNode(\n nodeIndex,\n address,\n leafTokenDecimals,\n parent,\n proportionOfParent\n );\n return nodeInfo;\n }\n }\n\n const joinAction = joinActions.get(pool.poolType);\n const exitAction = exitActions.get(pool.poolType);\n if (!joinAction || !exitAction)\n throw new BalancerError(BalancerErrorCode.UNSUPPORTED_POOL_TYPE);\n\n const tokenTotal = this.getTokenTotal(pool);\n // Spot price service\n const { spotPriceCalculator } = PoolTypeConcerns.from(pool.poolType);\n const spotPrices: SpotPrices = {};\n let decimals = 18;\n // Spot price of a path is product of the sp of each pool in path. We calculate the sp for each pool token here to use as required later.\n pool.tokens.forEach((token) => {\n if (isSameAddress(token.address, pool.address)) {\n // Updated node with BPT token decimal\n decimals = token.decimals ? token.decimals : 18;\n return;\n }\n const sp = spotPriceCalculator.calcPoolSpotPrice(\n token.address,\n pool.address,\n pool\n );\n spotPrices[token.address] = sp;\n });\n\n let poolNode: Node = {\n address: pool.address,\n id: pool.id,\n type: pool.poolType,\n joinAction,\n exitAction,\n children: [],\n marked: false,\n index: nodeIndex.toString(),\n parent,\n proportionOfParent,\n isLeaf: false,\n spotPrices,\n decimals,\n };\n nodeIndex++;\n if (pool.poolType.toString().includes('Linear')) {\n [poolNode, nodeIndex] = this.createLinearNodeChildren(\n poolNode,\n nodeIndex,\n pool,\n wrapMainTokens\n );\n } else {\n const { parsedBalances } = parsePoolInfo(pool);\n for (let i = 0; i < pool.tokens.length; i++) {\n // ignore any phantomBpt tokens\n if (isSameAddress(pool.tokens[i].address, pool.address)) continue;\n let proportion: BigNumber;\n // If the pool is a weighted pool we can use the actual tokenWeight as proportion\n if (pool.poolType === 'Weighted') {\n const tokenWeight = pool.tokens[i].weight as string;\n proportion = parseFixed(tokenWeight, 18);\n } else {\n proportion = BigNumber.from(parsedBalances[i])\n .mul((1e18).toString())\n .div(tokenTotal);\n }\n const finalProportion = proportion\n .mul(proportionOfParent)\n .div((1e18).toString());\n const childNode = await this.buildGraphFromPool(\n pool.tokens[i].address,\n nodeIndex,\n poolNode,\n finalProportion,\n wrapMainTokens\n );\n nodeIndex = childNode[1];\n if (childNode[0]) poolNode.children.push(childNode[0]);\n }\n }\n return [poolNode, nodeIndex];\n }\n\n createLinearNodeChildren(\n linearPoolNode: Node,\n nodeIndex: number,\n linearPool: Pool,\n wrapMainTokens: boolean\n ): [Node, number] {\n if (wrapMainTokens) {\n // Linear pool will be joined via wrapped token. This will be the child node.\n const wrappedNodeInfo = this.createWrappedTokenNode(\n linearPool,\n nodeIndex,\n linearPoolNode,\n linearPoolNode.proportionOfParent\n );\n linearPoolNode.children.push(wrappedNodeInfo[0]);\n return [linearPoolNode, wrappedNodeInfo[1]];\n } else {\n // Main token\n if (linearPool.mainIndex === undefined)\n throw new Error('Issue With Linear Pool');\n\n const mainTokenDecimals =\n linearPool.tokens[linearPool.mainIndex].decimals ?? 18;\n\n const nodeInfo = PoolGraph.createInputTokenNode(\n nodeIndex,\n linearPool.tokensList[linearPool.mainIndex],\n mainTokenDecimals,\n linearPoolNode,\n linearPoolNode.proportionOfParent\n );\n linearPoolNode.children.push(nodeInfo[0]);\n nodeIndex = nodeInfo[1];\n return [linearPoolNode, nodeIndex];\n }\n }\n\n createWrappedTokenNode(\n linearPool: Pool,\n nodeIndex: number,\n parent: Node | undefined,\n proportionOfParent: BigNumber\n ): [Node, number] {\n if (\n linearPool.wrappedIndex === undefined ||\n linearPool.mainIndex === undefined\n )\n throw new Error('Issue With Linear Pool');\n\n // Relayer can support different wrapped tokens\n let joinAction: JoinAction = 'wrapAaveDynamicToken';\n switch (linearPool.poolType) {\n case PoolType.ERC4626Linear:\n joinAction = 'wrapERC4626';\n }\n let exitAction: ExitAction = 'unwrapAaveStaticToken';\n switch (linearPool.poolType) {\n case PoolType.ERC4626Linear:\n exitAction = 'unwrapERC4626';\n }\n\n const wrappedTokenNode: Node = {\n type: 'WrappedToken',\n address: linearPool.tokensList[linearPool.wrappedIndex],\n id: 'N/A',\n children: [],\n marked: false,\n joinAction,\n exitAction,\n index: nodeIndex.toString(),\n parent,\n proportionOfParent,\n isLeaf: false,\n spotPrices: {},\n decimals: 18,\n };\n nodeIndex++;\n\n const mainTokenDecimals =\n linearPool.tokens[linearPool.mainIndex].decimals ?? 18;\n\n const inputNode = PoolGraph.createInputTokenNode(\n nodeIndex,\n linearPool.tokensList[linearPool.mainIndex],\n mainTokenDecimals,\n wrappedTokenNode,\n proportionOfParent\n );\n wrappedTokenNode.children = [inputNode[0]];\n nodeIndex = inputNode[1];\n return [wrappedTokenNode, nodeIndex];\n }\n\n static createInputTokenNode(\n nodeIndex: number,\n address: string,\n decimals: number,\n parent: Node | undefined,\n proportionOfParent: BigNumber\n ): [Node, number] {\n return [\n {\n address,\n id: 'N/A',\n type: 'Input',\n children: [],\n marked: false,\n joinAction: 'input',\n exitAction: 'output',\n index: nodeIndex.toString(), // This will be updated with real amounts in join construction.\n parent,\n proportionOfParent,\n isLeaf: true,\n spotPrices: {},\n decimals,\n },\n nodeIndex + 1,\n ];\n }\n\n static orderByBfs(root: Node): Node[] {\n // Breadth first traversal of graph\n const nodes: Node[] = [];\n const orderedNodes: Node[] = [];\n root.marked = true;\n nodes.push(root);\n while (nodes.length > 0) {\n const currentNode = nodes.shift(); // removes first\n if (currentNode) orderedNodes.push(currentNode);\n currentNode?.children.forEach((c) => {\n if (!c.marked) {\n c.marked = true;\n nodes.push(c);\n }\n });\n }\n return orderedNodes;\n }\n\n // Return a list of leaf token addresses\n static getLeafAddresses(nodes: Node[]): string[] {\n return nodes.filter((n) => n.isLeaf).map((n) => n.address);\n }\n\n // Get full graph from root pool and return ordered nodes\n static getGraphNodes = async (\n isJoin: boolean,\n poolId: string,\n pools: Findable<Pool, PoolAttribute>,\n wrapMainTokens: boolean\n ): Promise<Node[]> => {\n const rootPool = await pools.find(poolId);\n if (!rootPool) throw new BalancerError(BalancerErrorCode.POOL_DOESNT_EXIST);\n const poolsGraph = new PoolGraph(pools);\n\n const rootNode = await poolsGraph.buildGraphFromRootPool(\n poolId,\n wrapMainTokens\n );\n\n if (rootNode.id !== poolId) throw new Error('Error creating graph nodes');\n\n if (isJoin) return PoolGraph.orderByBfs(rootNode).reverse();\n else return PoolGraph.orderByBfs(rootNode);\n };\n}\n","import axios from 'axios';\nimport { MaxInt256 } from '@ethersproject/constants';\nimport { networkAddresses } from '@/lib/constants/config';\nimport { BalancerTenderlyConfig } from '@/types';\n\ntype StateOverrides = {\n [address: string]: { value: { [key: string]: string } };\n};\n\nexport default class TenderlyHelper {\n private vaultAddress;\n private tenderlyUrl;\n private opts?;\n private blockNumber: number | undefined;\n\n constructor(\n private chainId: number,\n tenderlyConfig?: BalancerTenderlyConfig\n ) {\n const { contracts } = networkAddresses(this.chainId);\n this.vaultAddress = contracts.vault as string;\n if (tenderlyConfig?.user && tenderlyConfig?.project) {\n this.tenderlyUrl = `https://api.tenderly.co/api/v1/account/${tenderlyConfig.user}/project/${tenderlyConfig.project}/`;\n } else {\n this.tenderlyUrl = 'https://api.balancer.fi/tenderly/';\n }\n\n if (tenderlyConfig?.accessKey) {\n this.opts = {\n headers: {\n 'X-Access-Key': tenderlyConfig.accessKey,\n },\n };\n }\n\n this.blockNumber = tenderlyConfig?.blockNumber;\n }\n\n simulateMulticall = async (\n to: string,\n data: string,\n userAddress: string,\n tokens: string[]\n ): Promise<string> => {\n const tokensOverrides = await this.encodeBalanceAndAllowanceOverrides(\n userAddress,\n tokens\n );\n const relayerApprovalOverride = await this.encodeRelayerApprovalOverride(\n userAddress,\n to\n );\n const encodedStateOverrides = {\n ...tokensOverrides,\n ...relayerApprovalOverride,\n };\n return this.simulateTransaction(\n to,\n data,\n userAddress,\n encodedStateOverrides\n );\n };\n\n simulateTransaction = async (\n to: string,\n data: string,\n userAddress: string,\n encodedStateOverrides: StateOverrides\n ): Promise<string> => {\n // Map encoded-state response into simulate request body by replacing property names\n const state_objects = Object.fromEntries(\n Object.keys(encodedStateOverrides).map((address) => {\n // Object.fromEntries require format [key, value] instead of {key: value}\n return [address, { storage: encodedStateOverrides[address].value }];\n })\n );\n\n const body = {\n // -- Standard TX fields --\n network_id: this.chainId.toString(),\n block_number: this.blockNumber,\n from: userAddress,\n to,\n input: data,\n // gas: 8000000,\n // gas_price: '0',\n // value: '0',\n // -- Simulation config (tenderly specific) --\n save_if_fails: true,\n // save: true,\n simulation_type: 'quick', // remove this while developing/debugging\n state_objects,\n };\n\n const SIMULATE_URL = this.tenderlyUrl + 'simulate';\n\n const resp = await axios.post(SIMULATE_URL, body, this.opts);\n\n const simulatedTransactionOutput =\n resp.data.transaction.transaction_info.call_trace.output;\n\n return simulatedTransactionOutput;\n };\n\n // Encode relayer approval state override\n encodeRelayerApprovalOverride = async (\n userAddress: string,\n relayerAddress: string\n ): Promise<StateOverrides> => {\n const stateOverrides: StateOverrides = {\n [`${this.vaultAddress}`]: {\n value: {\n [`_approvedRelayers[${userAddress}][${relayerAddress}]`]:\n true.toString(),\n },\n },\n };\n\n const encodedStateOverrides = await this.requestStateOverrides(\n stateOverrides\n );\n\n return encodedStateOverrides;\n };\n\n // Encode token balances and allowances overrides to max value\n encodeBalanceAndAllowanceOverrides = async (\n userAddress: string,\n tokens: string[]\n ): Promise<StateOverrides> => {\n if (tokens.length === 0) return {};\n\n // Create balances and allowances overrides for each token address provided\n let stateOverrides: StateOverrides = {};\n tokens.forEach(\n (token) =>\n (stateOverrides = {\n ...stateOverrides,\n [`${token}`]: {\n value: {\n [`_balances[${userAddress}]`]: MaxInt256.toString(),\n [`_allowances[${userAddress}][${this.vaultAddress}]`]:\n MaxInt256.toString(),\n [`balanceOf[${userAddress}]`]: MaxInt256.toString(),\n [`allowance[${userAddress}][${this.vaultAddress}]`]:\n MaxInt256.toString(),\n [`balances[${userAddress}]`]: MaxInt256.toString(),\n [`allowed[${userAddress}][${this.vaultAddress}]`]:\n MaxInt256.toString(),\n },\n },\n })\n );\n\n const encodedStateOverrides = await this.requestStateOverrides(\n stateOverrides\n );\n\n if (\n Object.keys(encodedStateOverrides).some((k) => {\n return Object.keys(encodedStateOverrides[k].value).length !== 2;\n })\n )\n throw new Error(\n \"Couldn't encode state overrides - states should match the ones in the contracts\"\n );\n\n return encodedStateOverrides;\n };\n\n private requestStateOverrides = async (\n stateOverrides: StateOverrides\n ): Promise<StateOverrides> => {\n const ENCODE_STATES_URL = this.tenderlyUrl + 'contracts/encode-states';\n const body = {\n networkID: this.chainId.toString(),\n stateOverrides,\n };\n\n const encodedStatesResponse = await axios.post(\n ENCODE_STATES_URL,\n body,\n this.opts\n );\n const encodedStateOverrides = encodedStatesResponse.data\n .stateOverrides as StateOverrides;\n\n if (\n !encodedStateOverrides ||\n Object.keys(encodedStateOverrides).length !==\n Object.keys(stateOverrides).length\n )\n throw new Error(\n \"Couldn't encode state overrides - contracts should be verified and whitelisted on Tenderly\"\n );\n\n return encodedStateOverrides;\n };\n}\n","import { defaultAbiCoder } from '@ethersproject/abi';\nimport { cloneDeep } from 'lodash';\nimport { Interface } from '@ethersproject/abi';\nimport { BigNumber, parseFixed } from '@ethersproject/bignumber';\nimport {\n AddressZero,\n MaxInt256,\n WeiPerEther,\n Zero,\n} from '@ethersproject/constants';\n\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { Relayer } from '@/modules/relayer/relayer.module';\nimport { BatchSwapStep, FundManagement, SwapType } from '@/modules/swaps/types';\nimport { StablePoolEncoder } from '@/pool-stable';\nimport {\n BalancerNetworkConfig,\n JoinPoolRequest,\n Pool,\n PoolAttribute,\n PoolType,\n} from '@/types';\nimport { Findable } from '../data/types';\nimport { PoolGraph, Node } from '../graph/graph';\n\nimport { subSlippage } from '@/lib/utils/slippageHelper';\nimport TenderlyHelper from '@/lib/utils/tenderlyHelper';\nimport balancerRelayerAbi from '@/lib/abi/RelayerV4.json';\nimport { networkAddresses } from '@/lib/constants/config';\nimport { AssetHelpers, isSameAddress } from '@/lib/utils';\nimport {\n SolidityMaths,\n _computeScalingFactor,\n _upscale,\n} from '@/lib/utils/solidityMaths';\nimport { calcPriceImpact } from '../pricing/priceImpact';\nimport { WeightedPoolEncoder } from '@/pool-weighted';\nimport { getPoolAddress } from '@/pool-utils';\nconst balancerRelayerInterface = new Interface(balancerRelayerAbi);\n\nexport class Join {\n private relayer: string;\n private wrappedNativeAsset;\n private tenderlyHelper: TenderlyHelper;\n constructor(\n private pools: Findable<Pool, PoolAttribute>,\n networkConfig: BalancerNetworkConfig\n ) {\n const { tokens, contracts } = networkAddresses(networkConfig.chainId);\n this.relayer = contracts.relayerV4 as string;\n this.wrappedNativeAsset = tokens.wrappedNativeAsset;\n\n this.tenderlyHelper = new TenderlyHelper(\n networkConfig.chainId,\n networkConfig.tenderly\n );\n }\n\n async joinPool(\n poolId: string,\n tokensIn: string[],\n amountsIn: string[],\n userAddress: string,\n wrapMainTokens: boolean,\n slippage: string,\n authorisation?: string\n ): Promise<{\n to: string;\n callData: string;\n expectedOut: string;\n minOut: string;\n priceImpact: string;\n }> {\n if (tokensIn.length != amountsIn.length)\n throw new BalancerError(BalancerErrorCode.INPUT_LENGTH_MISMATCH);\n\n // Create nodes for each pool/token interaction and order by breadth first\n const orderedNodes = await PoolGraph.getGraphNodes(\n true,\n poolId,\n this.pools,\n wrapMainTokens\n );\n\n const joinPaths = Join.getJoinPaths(orderedNodes, tokensIn, amountsIn);\n\n const totalBptZeroPi = Join.totalBptZeroPriceImpact(joinPaths);\n /*\n - Create calls with 0 min bpt for each root join\n - static call (or V4 special call) to get actual amounts for each root join\n - Apply slippage to amounts\n - Recreate calls with minAmounts === actualAmountsWithSlippage\n - Return minAmoutOut (sum actualAmountsWithSlippage), UI would use this to display to user\n - Return updatedCalls, UI would use this to execute tx\n */\n // Create calls with 0 expected for each root join\n // Peek is enabled here so we can static call the returned amounts and use these to set limits\n const { callData: queryData, outputIndexes } = await this.createCalls(\n joinPaths,\n userAddress,\n undefined,\n authorisation\n );\n\n // static call (or V4 special call) to get actual amounts for each root join\n const { amountsOut, totalAmountOut } = await this.amountsOutByJoinPath(\n userAddress,\n queryData,\n tokensIn,\n outputIndexes\n );\n\n const { minAmountsOut, totalMinAmountOut } = this.minAmountsOutByJoinPath(\n slippage,\n amountsOut,\n totalAmountOut\n );\n const priceImpact = calcPriceImpact(\n BigInt(totalAmountOut),\n totalBptZeroPi.toBigInt(),\n true\n ).toString();\n\n // Create calls with minAmountsOut\n const { callData, deltas } = await this.createCalls(\n joinPaths,\n userAddress,\n minAmountsOut,\n authorisation\n );\n\n this.assertDeltas(poolId, deltas, tokensIn, amountsIn, totalMinAmountOut);\n\n return {\n to: this.relayer,\n callData,\n expectedOut: totalAmountOut,\n minOut: totalMinAmountOut,\n priceImpact,\n };\n }\n\n private assertDeltas(\n poolId: string,\n deltas: Record<string, BigNumber>,\n tokensIn: string[],\n amountsIn: string[],\n minBptOut: string\n ): void {\n const poolAddress = getPoolAddress(poolId);\n const outDiff = deltas[poolAddress.toLowerCase()].add(minBptOut);\n\n if (outDiff.abs().gt(3)) {\n console.error(\n `join assertDeltas, bptOut: `,\n poolAddress,\n minBptOut,\n deltas[poolAddress.toLowerCase()]?.toString()\n );\n throw new BalancerError(BalancerErrorCode.JOIN_DELTA_AMOUNTS);\n }\n delete deltas[poolAddress.toLowerCase()];\n\n tokensIn.forEach((token, i) => {\n if (\n !BigNumber.from(amountsIn[i]).eq(0) &&\n deltas[token.toLowerCase()]?.toString() !== amountsIn[i]\n ) {\n console.error(\n `join assertDeltas, tokenIn: `,\n token,\n amountsIn[i],\n deltas[token.toLowerCase()]?.toString()\n );\n throw new BalancerError(BalancerErrorCode.JOIN_DELTA_AMOUNTS);\n }\n delete deltas[token.toLowerCase()];\n });\n\n for (const token in deltas) {\n if (deltas[token].toString() !== '0') {\n console.error(\n `join assertDeltas, non-input token should be 0: `,\n token,\n deltas[token].toString()\n );\n throw new BalancerError(BalancerErrorCode.JOIN_DELTA_AMOUNTS);\n }\n }\n }\n\n // Create join paths from tokensIn all the way to the root node.\n static getJoinPaths = (\n orderedNodes: Node[],\n tokensIn: string[],\n amountsIn: string[]\n ): Node[][] => {\n const joinPaths: Node[][] = [];\n\n // Filter all nodes that contain a token in the tokensIn array\n const inputNodes = orderedNodes.filter((node) =>\n tokensIn\n .filter((t, i) => BigNumber.from(amountsIn[i]).gt(0)) // Remove input tokens with 0 amounts\n .map((tokenIn) => tokenIn.toLowerCase())\n .includes(node.address.toLowerCase())\n );\n\n // If inputNodes contain at least one leaf token, then add path to join proportionally with all leaf tokens contained in tokensIn\n const containsLeafNode = inputNodes.some((node) => node.isLeaf);\n if (containsLeafNode) {\n joinPaths.push(orderedNodes);\n }\n\n // Add a join path for each non-leaf input node\n const nonLeafInputNodes = inputNodes.filter((node) => !node.isLeaf);\n nonLeafInputNodes.forEach((nonLeafInputNode) => {\n // Get amount in for current node\n const nonLeafAmountIn = amountsIn.find((amountIn, i) =>\n isSameAddress(tokensIn[i], nonLeafInputNode.address)\n ) as string;\n // Split amount in between nodes with same non-leaf input token based on proportionOfParent\n const totalProportions = nonLeafInputNodes\n .filter((node) => isSameAddress(node.address, nonLeafInputNode.address))\n .reduce(\n (total, node) => total.add(node.proportionOfParent),\n BigNumber.from(0)\n );\n const proportionalNonLeafAmountIn = BigNumber.from(nonLeafAmountIn)\n .mul(nonLeafInputNode.proportionOfParent)\n .div(totalProportions)\n .toString();\n // Create input node for current non-leaf input token\n const [inputTokenNode] = PoolGraph.createInputTokenNode(\n 0, // temp value that will be updated after creation\n nonLeafInputNode.address,\n nonLeafInputNode.decimals,\n nonLeafInputNode.parent,\n WeiPerEther\n );\n // Update index to be actual amount in\n inputTokenNode.index = proportionalNonLeafAmountIn;\n inputTokenNode.isLeaf = false;\n // Start join path with input node\n const nonLeafJoinPath = [inputTokenNode];\n // Add each parent to the join path until we reach the root node\n let parent = nonLeafInputNode.parent;\n while (parent) {\n nonLeafJoinPath.push(cloneDeep(parent));\n parent = parent.parent;\n }\n // Add join path to list of join paths\n joinPaths.push(nonLeafJoinPath);\n });\n\n // After creating all join paths, update the index of each input node to be the amount in for that node\n // All other node indexes will be used as a reference to store the amounts out for that node\n this.updateInputAmounts(joinPaths, tokensIn, amountsIn);\n\n return joinPaths;\n };\n\n /*\n AmountsIn should be adjusted after being split between tokensIn to fix eventual rounding issues.\n This prevents the transaction to leave out dust amounts.\n */\n private static updateInputAmounts = (\n joinPaths: Node[][],\n tokensIn: string[],\n amountsIn: string[]\n ): void => {\n // Helper function to calculate and adjust amount difference for each token in\n const ajdustAmountInDiff = (\n tokenInInputNodes: Node[],\n amountIn: string\n ): void => {\n if (tokenInInputNodes.length > 1) {\n // Sum of amountsIn from each input node with same tokenIn\n const amountsInSumforTokenIn = tokenInInputNodes.reduce(\n (sum, currentNode) => sum.add(currentNode.index),\n BigNumber.from(0)\n );\n // Compare total amountIn with sum of amountIn split between each input node with same tokenIn\n const diff = BigNumber.from(amountIn).sub(amountsInSumforTokenIn);\n // Apply difference to first input node with same tokenIn\n tokenInInputNodes[0].index = diff\n .add(tokenInInputNodes[0].index)\n .toString();\n }\n };\n\n // Update amountsIn within leaf join path\n const leafJoinPath = joinPaths.find((joinPath) => joinPath[0].isLeaf);\n if (leafJoinPath) {\n // Update input proportions so inputs are shared correctly between leaf nodes with same tokenIn\n const totalProportions = this.updateTotalProportions(leafJoinPath);\n // Update input nodes to have correct input amount\n leafJoinPath.forEach((node) => {\n if (node.joinAction === 'input')\n node = this.updateNodeAmount(\n node,\n tokensIn,\n amountsIn,\n totalProportions\n );\n });\n // Adjust amountIn for each tokenIn to fix eventual rounding issues\n tokensIn.forEach((tokenIn, i) => {\n const tokenInInputNodes = leafJoinPath.filter(\n (inputNode) =>\n inputNode.isLeaf && isSameAddress(inputNode.address, tokenIn)\n );\n ajdustAmountInDiff(tokenInInputNodes, amountsIn[i]);\n });\n }\n\n // Adjust amountsIn shared between non-leaf join paths with same tokenIn\n const nonLeafJoinPaths = joinPaths.filter(\n (joinPath) => !joinPath[0].isLeaf\n );\n if (nonLeafJoinPaths.length > 1) {\n tokensIn.forEach((tokenIn, i) => {\n const tokenInInputNodes = nonLeafJoinPaths\n .map((path) => path[0])\n .filter((node) => isSameAddress(node.address, tokenIn));\n ajdustAmountInDiff(tokenInInputNodes, amountsIn[i]);\n });\n }\n };\n\n private createCalls = async (\n joinPaths: Node[][],\n userAddress: string,\n minAmountsOut?: string[], // one for each joinPath\n authorisation?: string\n ): Promise<{\n callData: string;\n outputIndexes: number[];\n deltas: Record<string, BigNumber>;\n }> => {\n // Create calls for both leaf and non-leaf inputs\n const { calls, outputIndexes, deltas } = this.createActionCalls(\n joinPaths,\n userAddress,\n minAmountsOut\n );\n\n if (authorisation) {\n calls.unshift(this.createSetRelayerApproval(authorisation));\n }\n\n const callData = balancerRelayerInterface.encodeFunctionData('multicall', [\n calls,\n ]);\n\n return {\n callData,\n outputIndexes: authorisation\n ? outputIndexes.map((i) => i + 1)\n : outputIndexes,\n deltas,\n };\n };\n\n /*\n 1. For each input token:\n 1. recursively find the spot price for each pool in the path of the join\n 2. take the product to get the spot price of the path\n 3. multiply the input amount of that token by the path spot price to get the \"zeroPriceImpact\" amount of BPT for that token\n 2. Sum each tokens zeroPriceImpact BPT amount to get total zeroPriceImpact BPT\n */\n static totalBptZeroPriceImpact = (joinPaths: Node[][]): BigNumber => {\n // Add bptZeroPriceImpact for all inputs\n let totalBptZeroPi = BigNumber.from('0');\n joinPaths.forEach((joinPath) => {\n const isLeafJoin = joinPath[0].isLeaf;\n if (isLeafJoin) {\n // Calculate bptZeroPriceImpact for leaf inputs\n const leafNodes = joinPath.filter((node) => node.isLeaf);\n leafNodes.forEach((leafNode) => {\n const bptOut = this.bptOutZeroPiForInputNode(leafNode);\n totalBptZeroPi = totalBptZeroPi.add(bptOut);\n });\n } else {\n // Calculate bptZeroPriceImpact for non-leaf inputs\n const bptOut = this.bptOutZeroPiForInputNode(joinPath[0]);\n totalBptZeroPi = totalBptZeroPi.add(bptOut);\n }\n });\n return totalBptZeroPi;\n };\n\n /*\n 1. recursively find the spot price for each pool in the path of the join\n 2. take the product to get the spot price of the path\n 3. multiply the input amount of that token by the path spot price to get the \"zeroPriceImpact\" amount of BPT for that token \n */\n static bptOutZeroPiForInputNode = (inputNode: Node): bigint => {\n if (inputNode.index === '0' || inputNode.joinAction !== 'input')\n return BigInt(0);\n let spProduct = 1;\n let parentNode: Node | undefined = inputNode.parent;\n let childAddress = inputNode.address;\n // Traverse up graph until we reach root adding each node\n while (parentNode !== undefined) {\n if (\n parentNode.joinAction === 'batchSwap' ||\n parentNode.joinAction === 'joinPool'\n ) {\n const sp = parentNode.spotPrices[childAddress.toLowerCase()];\n spProduct = spProduct * parseFloat(sp);\n childAddress = parentNode.address;\n }\n parentNode = parentNode.parent;\n }\n const spPriceScaled = parseFixed(spProduct.toFixed(18), 18);\n const scalingFactor = _computeScalingFactor(BigInt(inputNode.decimals));\n const inputAmountScaled = _upscale(BigInt(inputNode.index), scalingFactor);\n const bptOut = SolidityMaths.divDownFixed(\n inputAmountScaled,\n spPriceScaled.toBigInt()\n );\n return bptOut;\n };\n\n /*\n Simulate transaction and decodes each output of interest.\n */\n private amountsOutByJoinPath = async (\n userAddress: string,\n callData: string,\n tokensIn: string[],\n outputIndexes: number[]\n ): Promise<{ amountsOut: string[]; totalAmountOut: string }> => {\n const amountsOut: string[] = [];\n\n const staticResult = await this.tenderlyHelper.simulateMulticall(\n this.relayer,\n callData,\n userAddress,\n tokensIn\n );\n\n const multicallResult = defaultAbiCoder.decode(\n ['bytes[]'],\n staticResult\n )[0] as string[];\n\n let totalAmountOut = BigNumber.from('0');\n // Decode each root output\n outputIndexes.forEach((outputIndex) => {\n const value = defaultAbiCoder.decode(\n ['uint256'],\n multicallResult[outputIndex]\n );\n amountsOut.push(value.toString());\n totalAmountOut = totalAmountOut.add(value.toString());\n });\n\n return {\n amountsOut,\n totalAmountOut: totalAmountOut.toString(),\n };\n };\n\n /*\n Apply slippage to amounts\n */\n private minAmountsOutByJoinPath = (\n slippage: string,\n amounts: string[],\n totalAmountOut: string\n ): { minAmountsOut: string[]; totalMinAmountOut: string } => {\n const minAmountsOut = amounts.map((amount) =>\n subSlippage(BigNumber.from(amount), BigNumber.from(slippage)).toString()\n );\n const totalMinAmountOut = subSlippage(\n BigNumber.from(totalAmountOut),\n BigNumber.from(slippage)\n ).toString();\n\n return {\n minAmountsOut,\n totalMinAmountOut,\n };\n };\n\n private updateDeltas(\n deltas: Record<string, BigNumber>,\n assets: string[],\n amounts: string[]\n ): Record<string, BigNumber> {\n assets.forEach((t, i) => {\n const asset = t.toLowerCase();\n if (!deltas[asset]) deltas[asset] = Zero;\n deltas[asset] = deltas[asset].add(amounts[i]);\n });\n return deltas;\n }\n\n // Create actions for each Node and return in multicall array\n // Create calls for each path, use value stored in minBptAmounts if available\n private createActionCalls = (\n joinPaths: Node[][],\n userAddress: string,\n minAmountsOut?: string[]\n ): {\n calls: string[];\n outputIndexes: number[];\n deltas: Record<string, BigNumber>;\n } => {\n const calls: string[] = [];\n const outputIndexes: number[] = [];\n const isPeek = !minAmountsOut;\n const deltas: Record<string, BigNumber> = {};\n\n joinPaths.forEach((joinPath, j) => {\n const isLeafJoin = joinPath[0].isLeaf;\n joinPath.forEach((node, i) => {\n let nodeChildrenWithinJoinPath;\n if (isLeafJoin) {\n nodeChildrenWithinJoinPath = joinPath.filter(\n (joinNode) =>\n node.children.map((n) => n.address).includes(joinNode.address) &&\n node.index === joinNode.parent?.index // Ensure child nodes with same address are not included\n );\n } else {\n nodeChildrenWithinJoinPath = i > 0 ? [joinPath[i - 1]] : [];\n }\n\n // Prevent adding action calls with input amounts equal 0\n if (\n nodeChildrenWithinJoinPath.length > 0 &&\n nodeChildrenWithinJoinPath.filter((c) => c.index !== '0').length === 0\n ) {\n node.index = '0';\n return;\n }\n\n // If child node was input the tokens come from user not relayer\n // wrapped tokens have to come from user (Relayer has no approval for wrapped tokens)\n const fromUser = nodeChildrenWithinJoinPath.some(\n (child) =>\n child.joinAction === 'input' ||\n child.joinAction === 'wrapAaveDynamicToken'\n );\n const sender = fromUser ? userAddress : userAddress;\n\n const isLastChainedCall = i === joinPath.length - 1;\n // Always send to user on last call otherwise send to relayer\n const recipient = isLastChainedCall ? userAddress : userAddress;\n // Last action will use minBptOut to protect user. Middle calls can safely have 0 minimum as tx will revert if last fails.\n const minOut =\n isLastChainedCall && minAmountsOut ? minAmountsOut[j] : '0';\n\n switch (node.joinAction) {\n // TODO - Add other Relayer supported Unwraps\n case 'wrapAaveDynamicToken':\n // relayer has no allowance to spend its own wrapped tokens so recipient must be the user\n calls.push(\n this.createAaveWrap(\n node,\n nodeChildrenWithinJoinPath,\n j,\n sender,\n userAddress\n )\n );\n break;\n case 'batchSwap': {\n const [call, assets, limits] = this.createBatchSwap(\n node,\n nodeChildrenWithinJoinPath,\n j,\n minOut,\n sender,\n recipient\n );\n calls.push(call);\n this.updateDeltas(deltas, assets, limits);\n break;\n }\n case 'joinPool': {\n const [call, tokensIn, amountsIn, minBptOut] = this.createJoinPool(\n node,\n nodeChildrenWithinJoinPath,\n j,\n minOut,\n sender,\n recipient\n );\n calls.push(call);\n this.updateDeltas(\n deltas,\n [node.address, ...tokensIn],\n [minBptOut, ...amountsIn]\n );\n break;\n }\n }\n });\n if (isPeek) {\n const outputRef = 100 * j;\n const peekCall = Relayer.encodePeekChainedReferenceValue(\n Relayer.toChainedReference(outputRef, false)\n );\n calls.push(peekCall);\n outputIndexes.push(calls.indexOf(peekCall));\n }\n });\n\n return { calls, outputIndexes, deltas };\n };\n\n /**\n * Creates a map of node address and total proportion. Used for the case where there may be multiple inputs using same token, e.g. DAI input to 2 pools.\n * @param nodes nodes to consider.\n */\n static updateTotalProportions = (\n nodes: Node[]\n ): Record<string, BigNumber> => {\n const totalProportions: Record<string, BigNumber> = {};\n nodes.forEach((node) => {\n if (!totalProportions[node.address])\n totalProportions[node.address] = node.proportionOfParent;\n else {\n totalProportions[node.address] = totalProportions[node.address].add(\n node.proportionOfParent\n );\n }\n });\n return totalProportions;\n };\n\n /**\n * Uses relayer to approve itself to act in behalf of the user\n *\n * @param authorisation Encoded authorisation call.\n * @returns relayer approval call\n */\n private createSetRelayerApproval = (authorisation: string): string => {\n return Relayer.encodeSetRelayerApproval(this.relayer, true, authorisation);\n };\n\n static updateNodeAmount = (\n node: Node,\n tokensIn: string[],\n amountsIn: string[],\n totalProportions: Record<string, BigNumber>\n ): Node => {\n /*\n An input node requires a real amount (not an outputRef) as it is first node in chain.\n This amount will be used when chaining to parent.\n Amounts are split proportionally between all inputs with same token.\n */\n const tokenIndex = tokensIn\n .map((t) => t.toLowerCase())\n .indexOf(node.address.toLowerCase());\n if (tokenIndex === -1) {\n node.index = '0';\n return node;\n }\n\n // Calculate proportional split\n const totalProportion = totalProportions[node.address];\n const inputProportion = node.proportionOfParent\n .mul((1e18).toString())\n .div(totalProportion);\n const inputAmount = inputProportion\n .mul(amountsIn[tokenIndex])\n .div((1e18).toString());\n // Update index with actual value\n node.index = inputAmount.toString();\n // console.log(\n // `${node.type} ${node.address} prop: ${node.proportionOfParent.toString()}\n // ${node.joinAction} (\n // Inputs: ${inputAmount.toString()}\n // OutputRef: ${node.index}\n // )`\n // );\n return node;\n };\n\n private createAaveWrap = (\n node: Node,\n nodeChildrenWithinJoinPath: Node[],\n joinPathIndex: number,\n sender: string,\n recipient: string\n ): string => {\n // Throws error based on the assumption that aaveWrap apply only to input tokens from leaf nodes\n if (nodeChildrenWithinJoinPath.length !== 1)\n throw new Error('aaveWrap nodes should always have a single child node');\n\n const childNode = nodeChildrenWithinJoinPath[0];\n\n const staticToken = node.address;\n const amount = childNode.index;\n const call = Relayer.encodeWrapAaveDynamicToken({\n staticToken,\n sender,\n recipient,\n amount,\n fromUnderlying: true,\n outputReference: this.getOutputRefValue(joinPathIndex, node).value,\n });\n\n // console.log(\n // `${node.type} ${node.address} prop: ${node.proportionOfParent.toString()}\n // ${node.joinAction} (\n // staticToken: ${staticToken},\n // input: ${amount},\n // outputRef: ${node.index.toString()}\n // )`\n // );\n\n return call;\n };\n\n private createBatchSwap = (\n node: Node,\n nodeChildrenWithinJoinPath: Node[],\n joinPathIndex: number,\n expectedOut: string,\n sender: string,\n recipient: string\n ): [string, string[], string[]] => {\n // We only need batchSwaps for main/wrapped > linearBpt so shouldn't be more than token > token\n if (nodeChildrenWithinJoinPath.length !== 1)\n throw new Error('Unsupported batchswap');\n const inputToken = nodeChildrenWithinJoinPath[0].address;\n const inputValue = this.getOutputRefValue(\n joinPathIndex,\n nodeChildrenWithinJoinPath[0]\n );\n const assets = [node.address, inputToken];\n\n // For tokens going in to the Vault, the limit shall be a positive number. For tokens going out of the Vault, the limit shall be a negative number.\n // First asset will always be the output token (which will be linearBpt) so use expectedOut to set limit\n // We don't know input amounts if they are part of a chain so set to max input\n // TODO can we be safer?\n const limits: string[] = [\n BigNumber.from(expectedOut).mul(-1).toString(),\n inputValue.isRef ? MaxInt256.toString() : inputValue.value,\n ];\n\n // TODO Change to single swap to save gas\n const swaps: BatchSwapStep[] = [\n {\n poolId: node.id,\n assetInIndex: 1,\n assetOutIndex: 0,\n amount: inputValue.value,\n userData: '0x',\n },\n ];\n\n const funds: FundManagement = {\n sender,\n recipient,\n fromInternalBalance: sender === this.relayer,\n toInternalBalance: recipient === this.relayer,\n };\n\n const outputReferences = [\n {\n index: assets\n .map((a) => a.toLowerCase())\n .indexOf(node.address.toLowerCase()),\n key: BigNumber.from(this.getOutputRefValue(joinPathIndex, node).value),\n },\n ];\n\n // console.log(\n // `${node.type} ${node.address} prop: ${node.proportionOfParent.toString()}\n // ${node.joinAction}(\n // inputAmt: ${nodeChildrenWithinJoinPath[0].index},\n // inputToken: ${nodeChildrenWithinJoinPath[0].address},\n // pool: ${node.id},\n // outputToken: ${node.address},\n // outputRef: ${this.getOutputRefValue(joinPathIndex, node).value},\n // sender: ${sender},\n // recipient: ${recipient}\n // )`\n // );\n\n const call = Relayer.encodeBatchSwap({\n swapType: SwapType.SwapExactIn,\n swaps,\n assets,\n funds,\n limits,\n deadline: BigNumber.from(Math.ceil(Date.now() / 1000) + 3600), // 1 hour from now\n value: '0',\n outputReferences,\n });\n\n // If the sender is the Relayer the swap is part of a chain and shouldn't be considered for user deltas\n const userTokenIn = sender === this.relayer ? '0' : limits[1];\n // If the receiver is the Relayer the swap is part of a chain and shouldn't be considered for user deltas\n const userBptOut = recipient === this.relayer ? '0' : limits[0];\n\n return [call, assets, [userBptOut, userTokenIn]];\n };\n\n private createJoinPool = (\n node: Node,\n nodeChildrenWithinJoinPath: Node[],\n joinPathIndex: number,\n minAmountOut: string,\n sender: string,\n recipient: string\n ): [string, string[], string[], string] => {\n const inputTokens: string[] = [];\n const inputAmts: string[] = [];\n\n // inputTokens needs to include each asset even if it has 0 amount\n node.children.forEach((child) => {\n inputTokens.push(child.address);\n // non-leaf joins should set input amounts only for children that are in their joinPath\n const childWithinJoinPath = nodeChildrenWithinJoinPath.find((c) =>\n isSameAddress(c.address, child.address)\n );\n if (childWithinJoinPath) {\n inputAmts.push(\n this.getOutputRefValue(joinPathIndex, childWithinJoinPath).value\n );\n } else {\n inputAmts.push('0');\n }\n });\n\n if (node.type === PoolType.ComposableStable) {\n // assets need to include the phantomPoolToken\n inputTokens.push(node.address);\n // need to add a placeholder so sorting works\n inputAmts.push('0');\n }\n\n // sort inputs\n const assetHelpers = new AssetHelpers(this.wrappedNativeAsset);\n const [sortedTokens, sortedAmounts] = assetHelpers.sortTokens(\n inputTokens,\n inputAmts\n ) as [string[], string[]];\n\n // userData amounts should not include the BPT of the pool being joined\n let userDataAmounts = [];\n const bptIndex = sortedTokens\n .map((t) => t.toLowerCase())\n .indexOf(node.address.toLowerCase());\n if (bptIndex === -1) {\n userDataAmounts = sortedAmounts;\n } else {\n userDataAmounts = [\n ...sortedAmounts.slice(0, bptIndex),\n ...sortedAmounts.slice(bptIndex + 1),\n ];\n }\n\n let userData: string;\n if (node.type === PoolType.Weighted) {\n userData = WeightedPoolEncoder.joinExactTokensInForBPTOut(\n userDataAmounts,\n minAmountOut\n );\n } else {\n userData = StablePoolEncoder.joinExactTokensInForBPTOut(\n userDataAmounts,\n minAmountOut\n );\n }\n\n // TODO: add test to join weth/wsteth pool using ETH\n const ethIndex = sortedTokens.indexOf(AddressZero);\n const value = ethIndex === -1 ? '0' : sortedAmounts[ethIndex];\n\n // console.log(\n // `${node.type} ${node.address} prop: ${node.proportionOfParent.toString()}\n // ${node.joinAction}(\n // poolId: ${node.id},\n // assets: ${sortedTokens.toString()},\n // maxAmtsIn: ${sortedAmounts.toString()},\n // amountsIn: ${userDataAmounts.toString()},\n // minOut: ${minAmountOut},\n // outputRef: ${this.getOutputRefValue(joinPathIndex, node).value},\n // sender: ${sender},\n // recipient: ${recipient}\n // )`\n // );\n\n const call = Relayer.constructJoinCall({\n poolId: node.id,\n kind: 0,\n sender,\n recipient,\n value,\n outputReference: this.getOutputRefValue(joinPathIndex, node).value,\n joinPoolRequest: {} as JoinPoolRequest,\n assets: sortedTokens, // Must include BPT token\n maxAmountsIn: sortedAmounts,\n userData,\n fromInternalBalance: sender === this.relayer,\n });\n\n const userAmountsTokenIn = sortedAmounts.map((a) =>\n Relayer.isChainedReference(a) ? '0' : a\n );\n const userAmountOut = Relayer.isChainedReference(minAmountOut)\n ? '0'\n : minAmountOut;\n\n return [\n call,\n // If the sender is the Relayer the join is part of a chain and shouldn't be considered for user deltas\n sender === this.relayer ? [] : sortedTokens,\n sender === this.relayer ? [] : userAmountsTokenIn,\n // If the receiver is the Relayer the join is part of a chain and shouldn't be considered for user deltas\n recipient === this.relayer\n ? Zero.toString()\n : Zero.sub(userAmountOut).toString(), // -ve because coming from Vault\n ];\n };\n\n private getOutputRefValue = (\n joinPathIndex: number,\n node: Node\n ): { value: string; isRef: boolean } => {\n if (node.joinAction === 'input') {\n // Input nodes have their indexes set as the actual input amount, instead of a chained reference\n return { value: node.index, isRef: false };\n } else if (node.index !== '0' || !node.parent) {\n // Root node (parent === undefined) has index zero, but should still pass chained reference as outputRef value\n return {\n value: Relayer.toChainedReference(\n BigNumber.from(node.index).add(joinPathIndex * 100)\n ).toString(),\n isRef: true,\n };\n } else {\n return {\n value: '0',\n isRef: true,\n };\n }\n };\n}\n","import { defaultAbiCoder } from '@ethersproject/abi';\nimport { cloneDeep } from 'lodash';\nimport { Interface } from '@ethersproject/abi';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { MaxInt256, WeiPerEther, Zero } from '@ethersproject/constants';\n\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { Relayer } from '@/modules/relayer/relayer.module';\nimport { BatchSwapStep, FundManagement, SwapType } from '@/modules/swaps/types';\nimport { WeightedPoolEncoder } from '@/pool-weighted';\nimport { StablePoolEncoder } from '@/pool-stable';\nimport {\n BalancerNetworkConfig,\n ExitPoolRequest,\n Pool,\n PoolAttribute,\n PoolType,\n} from '@/types';\nimport { Findable } from '../data/types';\nimport { PoolGraph, Node } from '../graph/graph';\n\nimport { subSlippage } from '@/lib/utils/slippageHelper';\nimport TenderlyHelper from '@/lib/utils/tenderlyHelper';\nimport balancerRelayerAbi from '@/lib/abi/RelayerV4.json';\nimport { networkAddresses } from '@/lib/constants/config';\nimport { AssetHelpers } from '@/lib/utils';\nimport { getPoolAddress } from '@/pool-utils';\nimport { Join } from '../joins/joins.module';\nimport { calcPriceImpact } from '../pricing/priceImpact';\n\nconst balancerRelayerInterface = new Interface(balancerRelayerAbi);\n\nexport class Exit {\n private wrappedNativeAsset: string;\n private relayer: string;\n private tenderlyHelper: TenderlyHelper;\n\n constructor(\n private pools: Findable<Pool, PoolAttribute>,\n networkConfig: BalancerNetworkConfig\n ) {\n const { tokens, contracts } = networkAddresses(networkConfig.chainId);\n this.wrappedNativeAsset = tokens.wrappedNativeAsset;\n this.relayer = contracts.relayerV4 as string;\n\n this.tenderlyHelper = new TenderlyHelper(\n networkConfig.chainId,\n networkConfig.tenderly\n );\n }\n\n async exitPool(\n poolId: string,\n amountBptIn: string,\n userAddress: string,\n slippage: string,\n authorisation?: string\n ): Promise<{\n to: string;\n callData: string;\n tokensOut: string[];\n expectedAmountsOut: string[];\n minAmountsOut: string[];\n priceImpact: string;\n }> {\n /*\n Overall exit flow description:\n - Create calls with 0 expected min amount for each token out\n - static call (or V4 special call) to get actual amounts for each token out\n - Apply slippage to amountsOut\n - Recreate calls with minAmounts === actualAmountsWithSlippage\n - Return minAmoutsOut, UI would use this to display to user\n - Return updatedCalls, UI would use this to execute tx\n */\n\n // Create nodes and order by breadth first\n const orderedNodes = await PoolGraph.getGraphNodes(\n false,\n poolId,\n this.pools,\n false\n );\n\n // Create exit paths for each output node and splits amount in proportionally between them\n const outputNodes = orderedNodes.filter((n) => n.exitAction === 'output');\n\n const exitPaths = this.getExitPaths(outputNodes, amountBptIn);\n\n const tokensOutByExitPath = outputNodes.map((n) => n.address.toLowerCase());\n const tokensOut = [...new Set(tokensOutByExitPath)].sort();\n\n // Create calls with minimum expected amount out for each exit path\n const staticCall = await this.createCalls(\n exitPaths,\n userAddress,\n undefined,\n authorisation\n );\n\n const { expectedAmountsOutByExitPath, minAmountsOutByExitPath } =\n await this.amountsOutByExitPath(\n userAddress,\n staticCall.callData,\n orderedNodes[0].address,\n staticCall.outputIndexes,\n slippage\n );\n\n // Create calls with minimum expected amount out for each exit path\n const { callData, deltas } = await this.createCalls(\n exitPaths,\n userAddress,\n minAmountsOutByExitPath,\n authorisation\n );\n\n const { expectedAmountsOut, minAmountsOut } = this.amountsOutByTokenOut(\n tokensOut,\n tokensOutByExitPath,\n expectedAmountsOutByExitPath,\n slippage\n );\n\n this.assertDeltas(poolId, deltas, amountBptIn, tokensOut, minAmountsOut);\n\n const priceImpact = await this.calculatePriceImpact(\n poolId,\n tokensOut,\n expectedAmountsOut,\n amountBptIn\n );\n\n return {\n to: this.relayer,\n callData,\n tokensOut,\n expectedAmountsOut,\n minAmountsOut,\n priceImpact,\n };\n }\n\n /*\n (From Fernando)\n 1. Given a bpt amount in find the expect token amounts out (proportionally)\n 2. Uses bptZeroPi = _bptForTokensZeroPriceImpact (the same is used for joins too)\n 3. PI = bptAmountIn / bptZeroPi - 1\n */\n private async calculatePriceImpact(\n poolId: string,\n tokensOut: string[],\n amountsOut: string[],\n amountBptIn: string\n ): Promise<string> {\n // Create nodes for each pool/token interaction and order by breadth first\n const orderedNodesForJoin = await PoolGraph.getGraphNodes(\n true,\n poolId,\n this.pools,\n false\n );\n const joinPaths = Join.getJoinPaths(\n orderedNodesForJoin,\n tokensOut,\n amountsOut\n );\n const totalBptZeroPi = Join.totalBptZeroPriceImpact(joinPaths);\n const priceImpact = calcPriceImpact(\n BigInt(amountBptIn),\n totalBptZeroPi.toBigInt(),\n false\n ).toString();\n return priceImpact;\n }\n\n private assertDeltas(\n poolId: string,\n deltas: Record<string, BigNumber>,\n bptIn: string,\n tokensOut: string[],\n amountsOut: string[]\n ): void {\n const poolAddress = getPoolAddress(poolId);\n const outDiff = deltas[poolAddress.toLowerCase()].sub(bptIn);\n\n if (outDiff.abs().gt(3)) {\n console.error(\n `exit assertDeltas, bptIn: `,\n poolAddress,\n bptIn,\n deltas[poolAddress.toLowerCase()]?.toString()\n );\n throw new BalancerError(BalancerErrorCode.EXIT_DELTA_AMOUNTS);\n }\n delete deltas[poolAddress.toLowerCase()];\n\n tokensOut.forEach((token, i) => {\n const diff = deltas[token.toLowerCase()].add(amountsOut[i]);\n if (diff.abs().gt(1)) {\n console.error(\n `exit assertDeltas, tokenOut: `,\n token,\n amountsOut[i],\n deltas[token.toLowerCase()]?.toString()\n );\n throw new BalancerError(BalancerErrorCode.EXIT_DELTA_AMOUNTS);\n }\n delete deltas[token.toLowerCase()];\n });\n\n for (const token in deltas) {\n if (deltas[token].toString() !== '0') {\n console.error(\n `exit assertDeltas, non-input token should be 0: `,\n token,\n deltas[token].toString()\n );\n throw new BalancerError(BalancerErrorCode.EXIT_DELTA_AMOUNTS);\n }\n }\n }\n\n // Query amounts out through static call and return decoded result\n private amountsOutByExitPath = async (\n userAddress: string,\n callData: string,\n tokenIn: string,\n outputIndexes: number[],\n slippage: string\n ): Promise<{\n expectedAmountsOutByExitPath: string[];\n minAmountsOutByExitPath: string[];\n }> => {\n const simulationResult = await this.tenderlyHelper.simulateMulticall(\n this.relayer,\n callData,\n userAddress,\n [tokenIn]\n );\n\n // Decode each exit path amount out from static call result\n const multiCallResult = defaultAbiCoder.decode(\n ['bytes[]'],\n simulationResult\n )[0] as string[];\n\n const expectedAmountsOutByExitPath = outputIndexes.map((outputIndex) => {\n const result = defaultAbiCoder.decode(\n ['uint256'],\n multiCallResult[outputIndex]\n );\n return result.toString();\n });\n\n // Apply slippage tolerance on expected amount out for each exit path\n const minAmountsOutByExitPath = expectedAmountsOutByExitPath.map(\n (expectedAmountOut) =>\n subSlippage(\n BigNumber.from(expectedAmountOut),\n BigNumber.from(slippage)\n ).toString()\n );\n\n return { expectedAmountsOutByExitPath, minAmountsOutByExitPath };\n };\n\n // Aggregate amounts out by exit path into amounts out by token out\n private amountsOutByTokenOut = (\n tokensOut: string[],\n tokensOutByExitPath: string[],\n expectedAmountsOutByExitPath: string[],\n slippage: string\n ) => {\n // Aggregate amountsOutByExitPath into expectedAmountsOut\n const expectedAmountsOutMap: Record<string, BigNumber> = {};\n tokensOutByExitPath.forEach(\n (tokenOut, i) =>\n (expectedAmountsOutMap[tokenOut] = (\n expectedAmountsOutMap[tokenOut] ?? Zero\n ).add(expectedAmountsOutByExitPath[i]))\n );\n const expectedAmountsOut = tokensOut.map((tokenOut) =>\n expectedAmountsOutMap[tokenOut].toString()\n );\n\n // Apply slippage tolerance on each expected amount out\n const minAmountsOut = expectedAmountsOut.map((expectedAmountOut) =>\n subSlippage(\n BigNumber.from(expectedAmountOut),\n BigNumber.from(slippage)\n ).toString()\n );\n\n return { expectedAmountsOut, minAmountsOut };\n };\n\n // Create one exit path for each output node\n private getExitPaths = (outputNodes: Node[], amountIn: string): Node[][] => {\n const exitPaths = outputNodes.map((outputNode) => {\n const exitPath = [outputNode];\n while (exitPath[0].parent) {\n exitPath.unshift(cloneDeep(exitPath[0].parent));\n }\n /*\n The input/root node requires a real amount (not a reference/index) as it is first node in chain.\n This amount will be used when chaining to children.\n */\n exitPath[0].index = exitPath[exitPath.length - 1].proportionOfParent\n .mul(amountIn)\n .div(WeiPerEther)\n .toString();\n return exitPath;\n });\n\n /*\n Amounts in for exit paths should be adjusted after caculated to fix eventual rounding issues\n */\n // Sum amountIn for each exit path\n const amountsInSum = exitPaths.reduce((accumulator, currentExitPath) => {\n const amountInForCurrentExitPath = currentExitPath[0].index;\n return BigNumber.from(amountInForCurrentExitPath).add(accumulator);\n }, Zero);\n // Compare total amountIn with sum of calculated amountIn for each exit path\n const amountsInDiff = BigNumber.from(amountIn).sub(amountsInSum);\n // Add diff to last exit path amountIn\n exitPaths[exitPaths.length - 1][0].index = amountsInDiff\n .add(exitPaths[exitPaths.length - 1][0].index)\n .toString();\n\n return exitPaths;\n };\n\n private async createCalls(\n exitPaths: Node[][],\n userAddress: string,\n minAmountsOut?: string[],\n authorisation?: string\n ): Promise<{\n callData: string;\n outputIndexes: number[];\n deltas: Record<string, BigNumber>;\n }> {\n const { calls, outputIndexes, deltas } = this.createActionCalls(\n cloneDeep(exitPaths),\n userAddress,\n minAmountsOut\n );\n\n if (authorisation) {\n calls.unshift(\n Relayer.encodeSetRelayerApproval(this.relayer, true, authorisation)\n );\n }\n\n const callData = balancerRelayerInterface.encodeFunctionData('multicall', [\n calls,\n ]);\n\n return {\n callData,\n outputIndexes: authorisation\n ? outputIndexes.map((i) => i + 1)\n : outputIndexes,\n deltas,\n };\n }\n\n private updateDeltas(\n deltas: Record<string, BigNumber>,\n assets: string[],\n amounts: string[]\n ): Record<string, BigNumber> {\n assets.forEach((t, i) => {\n const asset = t.toLowerCase();\n if (!deltas[asset]) deltas[asset] = Zero;\n deltas[asset] = deltas[asset].add(amounts[i]);\n });\n return deltas;\n }\n\n private createActionCalls(\n exitPaths: Node[][],\n userAddress: string,\n minAmountsOut?: string[]\n ): {\n calls: string[];\n outputIndexes: number[];\n deltas: Record<string, BigNumber>;\n } {\n const calls: string[] = [];\n const outputIndexes: number[] = [];\n const isPeek = !minAmountsOut;\n const deltas: Record<string, BigNumber> = {};\n\n // Create actions for each Node and return in multicall array\n\n exitPaths.forEach((exitPath, i) => {\n exitPath.forEach((node) => {\n // Calls from root node are sent by the user. Otherwise sent by the relayer\n const isRootNode = !node.parent;\n const sender = isRootNode ? userAddress : this.relayer;\n // Always send to user on output calls otherwise send to relayer\n const exitChild = node.children.find((child) =>\n exitPath.map((n) => n.index).includes(child.index)\n );\n const isLastActionFromExitPath = exitChild?.exitAction === 'output';\n const recipient = isLastActionFromExitPath ? userAddress : this.relayer;\n // Last calls will use minAmountsOut to protect user. Middle calls can safely have 0 minimum as tx will revert if last fails.\n const minAmountOut =\n isLastActionFromExitPath && minAmountsOut ? minAmountsOut[i] : '0';\n\n switch (node.exitAction) {\n case 'batchSwap': {\n const [call, assets, limits] = this.createBatchSwap(\n node,\n exitChild as Node,\n i,\n minAmountOut,\n sender,\n recipient\n );\n calls.push(call);\n this.updateDeltas(deltas, assets, limits);\n break;\n }\n case 'exitPool': {\n const [call, bptIn, tokensOut, amountsOut] = this.createExitPool(\n node,\n exitChild as Node,\n i,\n minAmountOut,\n sender,\n recipient\n );\n calls.push(call);\n this.updateDeltas(\n deltas,\n [node.address, ...tokensOut],\n [bptIn, ...amountsOut]\n );\n break;\n }\n case 'output':\n if (isPeek) {\n calls.push(\n Relayer.encodePeekChainedReferenceValue(\n Relayer.toChainedReference(\n this.getOutputRef(i, node.index),\n false\n )\n )\n );\n outputIndexes.push(calls.length - 1);\n }\n break;\n default:\n return;\n }\n });\n });\n\n return { calls, outputIndexes, deltas };\n }\n\n private createBatchSwap(\n node: Node,\n exitChild: Node,\n exitPathIndex: number,\n minAmountOut: string,\n sender: string,\n recipient: string\n ): [string, string[], string[]] {\n const isRootNode = !node.parent;\n const amountIn = isRootNode\n ? node.index\n : Relayer.toChainedReference(\n this.getOutputRef(exitPathIndex, node.index)\n ).toString();\n\n const tokenOut = exitChild.address;\n const assets = [tokenOut, node.address];\n\n // For tokens going in to the Vault, the limit shall be a positive number. For tokens going out of the Vault, the limit shall be a negative number.\n // First asset will always be the output token so use expectedOut to set limit\n const limits: string[] = [\n BigNumber.from(minAmountOut).mul(-1).toString(),\n Relayer.isChainedReference(amountIn) ? MaxInt256.toString() : amountIn, // We don't know input amounts if they are part of a chain so set to max input\n ];\n\n // TODO Change to single swap to save gas\n const swaps: BatchSwapStep[] = [\n {\n poolId: node.id,\n assetInIndex: 1,\n assetOutIndex: 0,\n amount: amountIn,\n userData: '0x',\n },\n ];\n\n const funds: FundManagement = {\n sender,\n recipient,\n fromInternalBalance: false,\n toInternalBalance: false,\n };\n\n const outputReferences = [\n {\n index: assets\n .map((a) => a.toLowerCase())\n .indexOf(tokenOut.toLowerCase()),\n key: Relayer.toChainedReference(\n this.getOutputRef(exitPathIndex, exitChild.index)\n ),\n },\n ];\n\n // console.log(\n // `${node.type} ${node.address} prop: ${formatFixed(\n // node.proportionOfParent,\n // 18\n // )}\n // ${node.exitAction}(\n // inputAmt: ${amountIn},\n // inputToken: ${node.address},\n // pool: ${node.id},\n // outputToken: ${exitChild.address},\n // outputRef: ${this.getOutputRef(exitPathIndex, exitChild.index)},\n // sender: ${sender},\n // recipient: ${recipient}\n // )`\n // );\n\n const call = Relayer.encodeBatchSwap({\n swapType: SwapType.SwapExactIn,\n swaps,\n assets,\n funds,\n limits,\n deadline: BigNumber.from(Math.ceil(Date.now() / 1000) + 3600), // 1 hour from now\n value: '0',\n outputReferences,\n });\n\n let userTokenOutAmount = limits[0];\n const userBptAmount = limits[1];\n // If the sender is the Relayer the swap is part of a chain and shouldn't be considered for user deltas\n const bptIn = sender === this.relayer ? '0' : userBptAmount;\n // If the receiver is the Relayer the swap is part of a chain and shouldn't be considered for user deltas\n userTokenOutAmount = recipient === this.relayer ? '0' : userTokenOutAmount;\n return [call, assets, [userTokenOutAmount, bptIn]];\n }\n\n private createExitPool(\n node: Node,\n exitChild: Node,\n exitPathIndex: number,\n minAmountOut: string,\n sender: string,\n recipient: string\n ): [string, string, string[], string[]] {\n const tokenOut = exitChild.address;\n const isRootNode = !node.parent;\n const amountIn = isRootNode\n ? node.index\n : Relayer.toChainedReference(\n this.getOutputRef(exitPathIndex, node.index)\n ).toString();\n\n const tokensOut: string[] = [];\n const amountsOut: string[] = [];\n\n // tokensOut needs to include each asset even if it has 0 amount\n node.children.forEach((child) => {\n tokensOut.push(child.address);\n amountsOut.push(child.address === tokenOut ? minAmountOut : '0');\n });\n\n if (node.type === PoolType.ComposableStable) {\n // assets need to include the phantomPoolToken\n tokensOut.push(node.address);\n // need to add a placeholder so sorting works\n amountsOut.push('0');\n }\n\n // sort inputs\n const assetHelpers = new AssetHelpers(this.wrappedNativeAsset);\n const [sortedTokens, sortedAmounts] = assetHelpers.sortTokens(\n tokensOut,\n amountsOut\n ) as [string[], string[]];\n\n // userData amounts should not include the BPT of the pool being joined\n let userDataTokens = [];\n const bptIndex = sortedTokens\n .map((t) => t.toLowerCase())\n .indexOf(node.address.toLowerCase());\n if (bptIndex === -1) {\n userDataTokens = sortedTokens;\n } else {\n userDataTokens = [\n ...sortedTokens.slice(0, bptIndex),\n ...sortedTokens.slice(bptIndex + 1),\n ];\n }\n\n let userData: string;\n if (node.type === PoolType.Weighted) {\n userData = WeightedPoolEncoder.exitExactBPTInForOneTokenOut(\n amountIn,\n userDataTokens.indexOf(tokenOut)\n );\n } else {\n userData = StablePoolEncoder.exitExactBPTInForOneTokenOut(\n amountIn,\n userDataTokens.indexOf(tokenOut)\n );\n }\n\n const outputReferences = [\n {\n index: sortedTokens\n .map((t) => t.toLowerCase())\n .indexOf(tokenOut.toLowerCase()),\n key: Relayer.toChainedReference(\n this.getOutputRef(exitPathIndex, exitChild.index)\n ),\n },\n ];\n\n // console.log(\n // `${node.type} ${node.address} prop: ${formatFixed(\n // node.proportionOfParent,\n // 18\n // )}\n // ${node.exitAction}(\n // poolId: ${node.id},\n // tokensOut: ${sortedTokens},\n // tokenOut: ${sortedTokens[sortedTokens.indexOf(tokenOut)].toString()},\n // amountOut: ${sortedAmounts[sortedTokens.indexOf(tokenOut)].toString()},\n // amountIn: ${amountIn},\n // minAmountOut: ${minAmountOut},\n // outputRef: ${this.getOutputRef(exitPathIndex, exitChild.index)},\n // sender: ${sender},\n // recipient: ${recipient}\n // )`\n // );\n\n const call = Relayer.constructExitCall({\n poolId: node.id,\n poolKind: 0,\n sender,\n recipient,\n outputReferences,\n exitPoolRequest: {} as ExitPoolRequest,\n assets: sortedTokens,\n minAmountsOut: sortedAmounts,\n userData,\n toInternalBalance: false,\n });\n\n const userAmountTokensOut = sortedAmounts.map((a) =>\n Relayer.isChainedReference(a) ? '0' : Zero.sub(a).toString()\n );\n const userBptIn = Relayer.isChainedReference(amountIn) ? '0' : amountIn;\n\n return [\n call,\n // If the sender is the Relayer the exit is part of a chain and shouldn't be considered for user deltas\n sender === this.relayer ? Zero.toString() : userBptIn,\n // If the receiver is the Relayer the exit is part of a chain and shouldn't be considered for user deltas\n recipient === this.relayer ? [] : sortedTokens,\n recipient === this.relayer ? [] : userAmountTokensOut,\n ];\n }\n\n private getOutputRef = (exitPathIndex: number, nodeIndex: string): number => {\n return exitPathIndex * 100 + parseInt(nodeIndex);\n };\n}\n","/**\n * Calculates pool fees\n *\n * 1. Pool fees in last 24hrs\n */\nimport { isLessThan24Hours } from '@/lib/utils/time';\nimport { Pool, Findable, PoolAttribute } from '@/types';\n\nexport class PoolVolume {\n constructor(\n private yesterdaysPools: Findable<Pool, PoolAttribute> | undefined\n ) {}\n\n // 🚨 this is adding 1 call to get yesterday's block height and 2nd call to fetch yesterday's pools data from subgraph\n // TODO: find a better data source for that eg. add blocks to graph, replace with a database, or dune\n async last24h(pool: Pool): Promise<number> {\n let yesterdaysPool;\n if (this.yesterdaysPools) {\n yesterdaysPool = await this.yesterdaysPools.find(pool.id);\n }\n\n if (!pool.totalSwapVolume) {\n return 0;\n }\n\n if (!yesterdaysPool?.totalSwapVolume) {\n // Process edge case when pool creation time is less that 24h\n if (pool.createTime && isLessThan24Hours(pool.createTime)) {\n return parseFloat(pool.totalSwapVolume);\n }\n return 0;\n }\n\n return (\n parseFloat(pool.totalSwapVolume) -\n parseFloat(yesterdaysPool.totalSwapVolume)\n );\n }\n}\n","import {\n ComposableStableCreatePoolParameters,\n InitJoinPoolAttributes,\n InitJoinPoolParameters,\n} from '@/modules/pools/factory/types';\nimport { AssetHelpers, parseToBigInt18 } from '@/lib/utils';\nimport { TransactionRequest } from '@ethersproject/providers';\nimport { PoolFactory } from '@/modules/pools/factory/pool-factory';\nimport composableStableAbi from '../../../../lib/abi/ComposableStableFactory.json';\nimport { FunctionFragment, Interface } from '@ethersproject/abi';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { networkAddresses } from '@/lib/constants/config';\nimport { BalancerNetworkConfig } from '@/types';\n\nexport class ComposableStableFactory implements PoolFactory {\n private wrappedNativeAsset: string;\n\n constructor(networkConfig: BalancerNetworkConfig) {\n const { tokens } = networkAddresses(networkConfig.chainId);\n this.wrappedNativeAsset = tokens.wrappedNativeAsset;\n }\n\n /***\n * @param params\n * * Builds a transaction for a composable pool create operation.\n * * @param contractAddress - The address of the factory for composable stable pool (contract address)\n * * @param name - The name of the pool\n * * @param symbol - The symbol of the pool\n * * @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)\n * * @param tokenAddresses - The token's addresses\n * * @param rateProviders The addresses of the rate providers for each token, ordered\n * * @param tokenRateCacheDurations the Token Rate Cache Duration of each token\n * * @param owner - The address of the owner of the pool\n * * @param amplificationParameter The amplification parameter(must be greater than 1)\n * * @param exemptFromYieldProtocolFeeFlags array containing boolean for each token exemption from yield protocol fee flags\n * * @returns a TransactionRequest object, which can be directly inserted in the transaction to create a composable stable pool\n */\n create({\n factoryAddress,\n name,\n symbol,\n tokenAddresses,\n amplificationParameter,\n rateProviders,\n tokenRateCacheDurations,\n exemptFromYieldProtocolFeeFlags,\n swapFee,\n owner,\n }: ComposableStableCreatePoolParameters): TransactionRequest {\n const swapFeeScaled = parseToBigInt18(`${swapFee}`);\n const assetHelpers = new AssetHelpers(this.wrappedNativeAsset);\n const [\n sortedTokens,\n sortedRateProviders,\n sortedTokenRateCacheDurations,\n sortedExemptFromYieldProtocols,\n ] = assetHelpers.sortTokens(\n tokenAddresses,\n rateProviders,\n tokenRateCacheDurations,\n exemptFromYieldProtocolFeeFlags\n ) as [string[], string[], string[], boolean[]];\n const params = [\n name,\n symbol,\n sortedTokens,\n amplificationParameter,\n sortedRateProviders,\n sortedTokenRateCacheDurations,\n sortedExemptFromYieldProtocols,\n swapFeeScaled.toString(),\n owner,\n ];\n const composablePoolInterface = new Interface(composableStableAbi);\n const createFunctionAbi = composableStableAbi.find(\n ({ name }) => name === 'create'\n );\n if (!createFunctionAbi)\n throw new BalancerError(BalancerErrorCode.INTERNAL_ERROR_INVALID_ABI);\n const createFunctionFragment = FunctionFragment.from(createFunctionAbi);\n const encodedFunctionData = composablePoolInterface.encodeFunctionData(\n createFunctionFragment,\n params\n );\n return {\n to: factoryAddress,\n data: encodedFunctionData,\n };\n }\n\n /***\n * @param params\n * * Returns an array of calculated weights for every token in the PoolSeedToken array \"tokens\"\n * * @param joiner - The address of the joiner of the pool\n * * @param poolId - The id of the pool\n * * @param poolAddress - The address of the pool\n * * @param tokensIn - array with the address of the tokens\n * * @param amountsIn - array with the amount of each token\n * * @param wrappedNativeAsset\n * * @returns a InitJoinPoolAttributes object, which can be directly inserted in the transaction to init join a composable stable pool\n */\n buildInitJoin({\n joiner,\n poolId,\n poolAddress,\n tokensIn,\n amountsIn,\n }: InitJoinPoolParameters): InitJoinPoolAttributes {\n console.log(joiner, poolId, poolAddress, tokensIn, amountsIn);\n throw new Error('To be implemented');\n // const assetHelpers = new AssetHelpers(this.wrappedNativeAsset);\n // // sort inputs\n // tokensIn.push(poolAddress);\n // amountsIn.push('0');\n //\n // const [sortedTokens, sortedAmounts] = assetHelpers.sortTokens(\n // tokensIn,\n // amountsIn\n // ) as [string[], string[]];\n //\n // let userDataAmounts;\n // const bptIndex = sortedTokens\n // .map((t) => t.toLowerCase())\n // .indexOf(poolAddress.toLowerCase());\n // if (bptIndex === -1) {\n // userDataAmounts = sortedAmounts;\n // } else {\n // userDataAmounts = [\n // ...sortedAmounts.slice(0, bptIndex),\n // ...sortedAmounts.slice(bptIndex + 1),\n // ];\n // }\n //\n // const userData = ComposableStablePoolEncoder.joinInit(userDataAmounts);\n // const functionName = 'joinPool';\n //\n // const attributes = {\n // poolId: poolId,\n // sender: joiner,\n // recipient: joiner,\n // joinPoolRequest: {\n // assets: sortedTokens,\n // maxAmountsIn: sortedAmounts,\n // userData,\n // fromInternalBalance: false,\n // },\n // };\n //\n // const vaultInterface = Vault__factory.createInterface();\n // const data = vaultInterface.encodeFunctionData(functionName, [\n // attributes.poolId,\n // attributes.sender,\n // attributes.recipient,\n // attributes.joinPoolRequest,\n // ]);\n //\n // return {\n // to: balancerVault,\n // functionName,\n // attributes,\n // data,\n // };\n }\n}\n","import {\n InitJoinPoolAttributes,\n InitJoinPoolParameters,\n WeightedCreatePoolParameters,\n} from '@/modules/pools/factory/types';\nimport { AssetHelpers, parseToBigInt18 } from '@/lib/utils';\nimport { TransactionRequest } from '@ethersproject/providers';\nimport { PoolFactory } from '@/modules/pools/factory/pool-factory';\nimport { FunctionFragment, Interface } from '@ethersproject/abi';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { balancerVault, networkAddresses } from '@/lib/constants/config';\nimport { BalancerNetworkConfig } from '@/types';\nimport {\n Vault__factory,\n WeightedPoolFactory__factory,\n} from '@balancer-labs/typechain';\nimport { BigNumberish } from '@ethersproject/bignumber';\nimport { WeightedPoolEncoder } from '@/pool-weighted';\n\nexport class WeightedFactory implements PoolFactory {\n private wrappedNativeAsset: string;\n\n constructor(networkConfig: BalancerNetworkConfig) {\n const { tokens } = networkAddresses(networkConfig.chainId);\n this.wrappedNativeAsset = tokens.wrappedNativeAsset;\n }\n\n /***\n * @param params\n * * Builds a transaction for a weighted pool create operation.\n * * @param factoryAddress - The address of the factory for weighted pool (contract address)\n * * @param name - The name of the pool\n * * @param symbol - The symbol of the pool\n * * @param tokenAddresses - The token's addresses\n * * @param weights The weights for each token, ordered\n * * @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)\n * * @param owner - The address of the owner of the pool\n * * @returns a TransactionRequest object, which can be directly inserted in the transaction to create a weighted pool\n */\n create({\n factoryAddress,\n name,\n symbol,\n tokenAddresses,\n weights,\n swapFee,\n owner,\n }: WeightedCreatePoolParameters): TransactionRequest {\n const swapFeeScaled = parseToBigInt18(`${swapFee}`);\n const assetHelpers = new AssetHelpers(this.wrappedNativeAsset);\n const [sortedTokens, sortedWeights] = assetHelpers.sortTokens(\n tokenAddresses,\n weights\n ) as [string[], BigNumberish[]];\n const params = [\n name,\n symbol,\n sortedTokens,\n sortedWeights,\n swapFeeScaled.toString(),\n owner,\n ];\n const weightedPoolInterface = new Interface(\n WeightedPoolFactory__factory.abi\n );\n const createFunctionAbi = WeightedPoolFactory__factory.abi.find(\n ({ name }) => name === 'create'\n );\n if (!createFunctionAbi)\n throw new BalancerError(BalancerErrorCode.INTERNAL_ERROR_INVALID_ABI);\n const createFunctionFragment = FunctionFragment.from(createFunctionAbi);\n const encodedFunctionData = weightedPoolInterface.encodeFunctionData(\n createFunctionFragment,\n params\n );\n return {\n to: factoryAddress,\n data: encodedFunctionData,\n };\n }\n\n /***\n * @param params\n * * Returns a InitJoinPoolAttributes to make a init join transaction\n * * @param joiner - The address of the joiner of the pool\n * * @param poolId - The id of the pool\n * * @param tokensIn - array with the address of the tokens\n * * @param amountsIn - array with the amount of each token\n * * @returns a InitJoinPoolAttributes object, which can be directly inserted in the transaction to init join a weighted pool\n */\n buildInitJoin({\n joiner,\n poolId,\n tokensIn,\n amountsIn,\n }: InitJoinPoolParameters): InitJoinPoolAttributes {\n const assetHelpers = new AssetHelpers(this.wrappedNativeAsset);\n\n const [sortedTokens, sortedAmounts] = assetHelpers.sortTokens(\n tokensIn,\n amountsIn\n ) as [string[], string[]];\n\n const userData = WeightedPoolEncoder.joinInit(sortedAmounts);\n const functionName = 'joinPool';\n\n const attributes = {\n poolId: poolId,\n sender: joiner,\n recipient: joiner,\n joinPoolRequest: {\n assets: sortedTokens,\n maxAmountsIn: sortedAmounts,\n userData,\n fromInternalBalance: false,\n },\n };\n\n const vaultInterface = Vault__factory.createInterface();\n const data = vaultInterface.encodeFunctionData(functionName, [\n attributes.poolId,\n attributes.sender,\n attributes.recipient,\n attributes.joinPoolRequest,\n ]);\n\n return {\n to: balancerVault,\n functionName,\n attributes,\n data,\n };\n }\n}\n","import { BalancerNetworkConfig, PoolType } from '@/types';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\nimport { PoolFactory } from '@/modules/pools/factory/pool-factory';\nimport { ComposableStableFactory } from '@/modules/pools/factory/composable-stable/composable-stable.factory';\nimport { WeightedFactory } from '@/modules/pools/factory/weighted/weighted.factory';\n\n/**\n * Wrapper around pool type specific methods.\n *\n * Returns a class instance of a type specific factory.\n */\nexport class PoolFactory__factory {\n networkConfig: BalancerNetworkConfig;\n\n constructor(networkConfig: BalancerNetworkConfig) {\n this.networkConfig = networkConfig;\n }\n\n of(poolType: PoolType): PoolFactory {\n switch (poolType) {\n case 'Weighted':\n return new WeightedFactory(this.networkConfig);\n case 'Investment':\n case 'LiquidityBootstrapping': {\n throw new BalancerError(BalancerErrorCode.UNSUPPORTED_POOL_TYPE);\n }\n case 'Stable': {\n throw new BalancerError(BalancerErrorCode.UNSUPPORTED_POOL_TYPE);\n }\n case 'ComposableStable': {\n return new ComposableStableFactory(this.networkConfig);\n }\n case 'MetaStable': {\n throw new BalancerError(BalancerErrorCode.UNSUPPORTED_POOL_TYPE);\n }\n case 'StablePhantom': {\n throw new BalancerError(BalancerErrorCode.UNSUPPORTED_POOL_TYPE);\n }\n case 'AaveLinear':\n case 'ERC4626Linear': {\n throw new BalancerError(BalancerErrorCode.UNSUPPORTED_POOL_TYPE);\n }\n default:\n throw new BalancerError(BalancerErrorCode.UNSUPPORTED_POOL_TYPE);\n }\n }\n}\n","import * as PoolQueries from './types';\nimport { AddressZero, Zero, MaxUint256 } from '@ethersproject/constants';\nimport { getEncoder } from './get_encoder';\n\n/**\n * Builds parameters quering join / exit liquidity functions in the Balancer Helpers contract.\n */\nexport class ParamsBuilder implements PoolQueries.ParamsBuilder {\n private encoder: PoolQueries.Encoder;\n\n constructor(private pool: PoolQueries.Pool) {\n const encoder = getEncoder(pool.poolType);\n if (encoder) {\n this.encoder = encoder;\n } else {\n throw 'Pool type not supported';\n }\n }\n\n /**\n * Encodes the query to get expected amount of BPT when joining a Pool with exact token inputs\n *\n * @param maxAmountsIn - the amounts each of token to deposit in the pool as liquidity, order needs to match pool.tokensList\n * @param minimumBPT - the minimum acceptable BPT to receive in return for deposited tokens\n */\n buildQueryJoinExactIn({\n sender = AddressZero,\n recipient = sender,\n maxAmountsIn,\n minimumBPT = Zero,\n fromInternalBalance = false,\n }: PoolQueries.JoinExactInParams): PoolQueries.queryJoinParams {\n const bptIndex = this.pool.tokensList.findIndex((token) =>\n this.pool.id.includes(token)\n );\n const assets = [...this.pool.tokensList];\n\n // Remove BPT token from amounts\n if (bptIndex && bptIndex > -1) {\n maxAmountsIn.splice(bptIndex, 1);\n }\n\n const userData = this.encoder.joinExactTokensInForBPTOut(\n maxAmountsIn,\n minimumBPT\n );\n\n const params = [\n this.pool.id,\n sender,\n recipient,\n {\n assets,\n maxAmountsIn,\n userData,\n fromInternalBalance,\n },\n ] as PoolQueries.queryJoinParams;\n\n return params;\n }\n\n /**\n * Encodes the query to get expected token amount when joining a Pool specifying fixed BPT out.\n *\n * @param maxAmountsIn - max limits of amounts provided as liquidity, can be set to zero, ordered same as pool.tokensList\n * @param bptOut - the expected BPT for providing liquidity\n * @param tokenIn - address of a token joining the pool\n */\n buildQueryJoinExactOut({\n sender = AddressZero,\n recipient = sender,\n maxAmountsIn = [],\n bptOut,\n tokenIn,\n fromInternalBalance = false,\n }: PoolQueries.JoinExactOutParams): PoolQueries.queryJoinParams {\n const tokenIndex = this.pool.tokensList.indexOf(tokenIn);\n\n const userData = this.encoder.joinTokenInForExactBPTOut(bptOut, tokenIndex);\n\n const params = [\n this.pool.id,\n sender,\n recipient,\n {\n assets: this.pool.tokensList,\n maxAmountsIn,\n userData,\n fromInternalBalance,\n },\n ] as PoolQueries.queryJoinParams;\n\n return params;\n }\n\n /**\n * Encodes the query for exiting the pool to a single token\n *\n * @param minAmountsOut - minimum expected amounts, can be set to zero for a query, ordered same as pool.tokensList\n * @param bptIn - BPT, shares of the pool liquidity\n * @param tokenOut - address of an exit liquidity token\n */\n buildQueryExitToSingleToken({\n sender = AddressZero,\n recipient = sender,\n minAmountsOut = [],\n bptIn,\n tokenOut,\n toInternalBalance = false,\n }: PoolQueries.ExitToSingleTokenParams): PoolQueries.queryExitParams {\n const tokenIndex = this.pool.tokensList.indexOf(tokenOut);\n\n const userData = this.encoder.exitExactBPTInForOneTokenOut(\n bptIn,\n tokenIndex\n );\n\n const params = [\n this.pool.id,\n sender,\n recipient,\n {\n assets: this.pool.tokensList,\n minAmountsOut,\n userData,\n toInternalBalance,\n },\n ] as PoolQueries.queryExitParams;\n\n return params;\n }\n\n /**\n * Encodes the query for exiting the pool with all underlying tokens proportionally.\n * Not supported by ComposableStable\n *\n * @param minAmountsOut - minimum expected amounts, can be set to zero for a query, ordered same as pool.tokensList\n * @param bptIn - BPT, shares of the pool liquidity\n */\n buildQueryExitProportionally({\n sender = AddressZero,\n recipient = sender,\n minAmountsOut = [],\n bptIn,\n toInternalBalance = false,\n }: PoolQueries.ExitProportionallyParams): PoolQueries.queryExitParams {\n if (!this.encoder.exitExactBPTInForTokensOut) {\n throw 'Proportional exit not implemented';\n }\n\n const userData = this.encoder.exitExactBPTInForTokensOut(bptIn);\n\n const params = [\n this.pool.id,\n sender,\n recipient,\n {\n assets: this.pool.tokensList,\n minAmountsOut,\n userData,\n toInternalBalance,\n },\n ] as PoolQueries.queryExitParams;\n\n return params;\n }\n\n /**\n * Encodes calldata to query expected BPT for known amounts out.\n *\n * @param minAmountsOut - minimum expected amounts, ordered same as pool.tokensList\n * @param maxBptIn - BPT, shares of the pool liquidity, can be set to zero for a query\n */\n buildQueryExitExactOut({\n sender = AddressZero,\n recipient = sender,\n minAmountsOut,\n maxBptIn = MaxUint256,\n toInternalBalance = false,\n }: PoolQueries.ExitExactOutParams): PoolQueries.queryExitParams {\n const bptIndex = this.pool.tokensList.findIndex((token) =>\n this.pool.id.includes(token)\n );\n\n // Remove BPT token from amounts\n if (bptIndex && bptIndex > -1) {\n minAmountsOut.splice(bptIndex, 1);\n }\n\n const userData = this.encoder.exitBPTInForExactTokensOut(\n minAmountsOut,\n maxBptIn\n );\n\n const params = [\n this.pool.id,\n sender,\n recipient,\n {\n assets: this.pool.tokensList,\n minAmountsOut,\n userData,\n toInternalBalance,\n },\n ] as PoolQueries.queryExitParams;\n\n return params;\n }\n}\n","import { WeightedPoolEncoder } from '@/pool-weighted/encoder';\nimport { StablePoolEncoder } from '@/pool-stable/encoder';\nimport { ComposableStablePoolEncoder } from '@/pool-composable-stable';\nimport { PoolType } from '@/types';\n\nexport const getEncoder = (\n poolType: PoolType\n):\n | typeof WeightedPoolEncoder\n | typeof StablePoolEncoder\n | typeof ComposableStablePoolEncoder\n | undefined => {\n switch (poolType) {\n case PoolType.Weighted:\n return WeightedPoolEncoder;\n\n case PoolType.Stable:\n case PoolType.MetaStable:\n case PoolType.StablePhantom:\n case PoolType.AaveLinear:\n case PoolType.EulerLinear:\n case PoolType.ERC4626Linear:\n case PoolType.Element:\n case PoolType.Gyro2:\n case PoolType.Gyro3:\n return StablePoolEncoder;\n\n case PoolType.ComposableStable:\n return ComposableStablePoolEncoder;\n\n default:\n break;\n }\n};\n","import * as emissions from '@/modules/data/bal/emissions';\nimport { Findable, LiquidityGauge } from '@/types';\n\n/**\n * Returns BAL emissions per pool\n */\nexport class EmissionsService {\n constructor(private liquidityGaugesRepository: Findable<LiquidityGauge>) {}\n\n async relativeWeight(poolId: string): Promise<number> {\n const gauge = await this.liquidityGaugesRepository.findBy('poolId', poolId);\n\n if (gauge) {\n return gauge.relativeWeight;\n }\n\n return 0;\n }\n\n async weekly(poolId: string): Promise<number> {\n const perWeek = emissions.weekly();\n const relativeWeight = await this.relativeWeight(poolId);\n\n return perWeek * relativeWeight;\n }\n}\n","import { parseUnits } from '@ethersproject/units';\nimport { BigNumber } from '@ethersproject/bignumber';\n\n/**\n * Calculates the proportional amounts of tokens in relation to a given token and amount.\n * Useful for calculating the amounts of tokens to be sent to a pool when joining or swapping.\n * When using proportional amounts to join a pool the price impact will be minimal.\n *\n * @param pool - Pool object\n * @param token - Token address in relation to which the amounts are calculated\n * @param amount - Amount of token\n * @returns Object with tokens and amounts\n * @example\n * const pool = {\n * id: '0x0000',\n * tokens: [\n * { address: '0x1234', balance: '10' },\n * { address: '0x5678', balance: '20' }\n * ]\n * }\n *\n * const { tokens, amounts } = proportionalAmounts(pool, '0x1234', '1000000000000000000')\n */\nexport const proportionalAmounts = (\n pool: {\n id: string;\n tokens: { address: string; balance: string; decimals?: number }[];\n },\n token: string,\n amount: string\n): {\n tokens: string[];\n amounts: string[];\n} => {\n const tokensWithoutBpt = pool.tokens.filter(\n (t) => !pool.id.toLowerCase().includes(t.address.toLowerCase())\n );\n const referenceTokenIndex = tokensWithoutBpt.findIndex(\n (t) => t.address.toLowerCase() === token.toLowerCase()\n );\n\n if (referenceTokenIndex == -1) {\n throw new Error('Token not found in pool');\n }\n\n const balances = tokensWithoutBpt.map((t) =>\n parseUnits(t.balance, t.decimals)\n );\n const amountBn = BigNumber.from(amount);\n const proportionalAmounts = balances.map((b) =>\n b.mul(amountBn).div(balances[referenceTokenIndex])\n );\n\n return {\n tokens: tokensWithoutBpt.map((t) => t.address),\n amounts: proportionalAmounts.map((a) => a.toString()),\n };\n};\n","import { ImpermanentLossService } from '@/modules/pools/impermanentLoss/impermanentLossService';\nimport type {\n BalancerNetworkConfig,\n BalancerDataRepositories,\n Findable,\n Searchable,\n Pool,\n PoolWithMethods,\n AprBreakdown,\n PoolAttribute,\n} from '@/types';\nimport { JoinPoolAttributes } from './pool-types/concerns/types';\nimport { PoolTypeConcerns } from './pool-type-concerns';\nimport { PoolApr } from './apr/apr';\nimport { Liquidity } from '../liquidity/liquidity.module';\nimport { Join } from '../joins/joins.module';\nimport { Exit } from '../exits/exits.module';\nimport { PoolVolume } from './volume/volume';\nimport { PoolFees } from './fees/fees';\nimport { PoolFactory__factory } from './pool-factory__factory';\nimport * as Queries from './queries';\nimport { BalancerError } from '@/balancerErrors';\nimport { EmissionsService } from './emissions';\nimport { proportionalAmounts } from './proportional-amounts';\n\nconst notImplemented = (poolType: string, name: string) => () => {\n throw `${name} for poolType ${poolType} not implemented`;\n};\n\n/**\n * Controller / use-case layer for interacting with pools data.\n */\nexport class Pools implements Findable<PoolWithMethods> {\n aprService;\n liquidityService;\n joinService;\n exitService;\n feesService;\n volumeService;\n poolFactory;\n impermanentLossService;\n emissionsService;\n proportionalAmounts;\n\n constructor(\n private networkConfig: BalancerNetworkConfig,\n private repositories: BalancerDataRepositories\n ) {\n this.aprService = new PoolApr(\n this.repositories.pools,\n this.repositories.tokenPrices,\n this.repositories.tokenMeta,\n this.repositories.tokenYields,\n this.repositories.feeCollector,\n this.repositories.yesterdaysPools,\n this.repositories.liquidityGauges,\n this.repositories.feeDistributor\n );\n this.liquidityService = new Liquidity(\n repositories.pools,\n repositories.tokenPrices\n );\n this.joinService = new Join(this.repositories.poolsOnChain, networkConfig);\n this.exitService = new Exit(this.repositories.poolsOnChain, networkConfig);\n this.feesService = new PoolFees(repositories.yesterdaysPools);\n this.volumeService = new PoolVolume(repositories.yesterdaysPools);\n this.poolFactory = new PoolFactory__factory(networkConfig);\n this.impermanentLossService = new ImpermanentLossService(\n repositories.tokenPrices,\n repositories.tokenHistoricalPrices\n );\n if (repositories.liquidityGauges) {\n this.emissionsService = new EmissionsService(\n repositories.liquidityGauges\n );\n }\n this.proportionalAmounts = proportionalAmounts;\n }\n\n dataSource(): Findable<Pool, PoolAttribute> & Searchable<Pool> {\n // TODO: Add API data repository to data and use liveModelProvider as fallback\n return this.repositories.pools;\n }\n\n /**\n * Calculates APR on any pool data\n *\n * @param pool\n * @returns\n */\n async apr(pool: Pool): Promise<AprBreakdown> {\n return this.aprService.apr(pool);\n }\n\n async aprNextPeriod(pool: Pool): Promise<AprBreakdown> {\n return this.aprService.aprNextPeriod(pool);\n }\n\n /**\n * Calculates Impermanent Loss on any pool data\n *\n * @param timestamp\n * @param pool\n * @returns\n */\n async impermanentLoss(timestamp: number, pool: Pool): Promise<number> {\n return this.impermanentLossService.calcImpLoss(timestamp, pool);\n }\n\n /**\n * Calculates total liquidity of the pool\n *\n * @param pool\n * @returns\n */\n async liquidity(pool: Pool): Promise<string> {\n return this.liquidityService.getLiquidity(pool);\n }\n\n /**\n * Builds generalised join transaction\n *\n * @param poolId Pool id\n * @param tokens Token addresses\n * @param amounts Token amounts in EVM scale\n * @param userAddress User address\n * @param wrapMainTokens Indicates whether main tokens should be wrapped before being used\n * @param slippage Maximum slippage tolerance in bps i.e. 50 = 0.5%.\n * @param authorisation Optional auhtorisation call to be added to the chained transaction\n * @returns transaction data ready to be sent to the network along with min and expected BPT amounts out.\n */\n async generalisedJoin(\n poolId: string,\n tokens: string[],\n amounts: string[],\n userAddress: string,\n wrapMainTokens: boolean,\n slippage: string,\n authorisation?: string\n ): Promise<{\n to: string;\n callData: string;\n minOut: string;\n expectedOut: string;\n priceImpact: string;\n }> {\n return this.joinService.joinPool(\n poolId,\n tokens,\n amounts,\n userAddress,\n wrapMainTokens,\n slippage,\n authorisation\n );\n }\n\n /**\n * Builds generalised exit transaction\n *\n * @param poolId Pool id\n * @param amount Token amount in EVM scale\n * @param userAddress User address\n * @param slippage Maximum slippage tolerance in bps i.e. 50 = 0.5%.\n * @param authorisation Optional auhtorisation call to be added to the chained transaction\n * @returns transaction data ready to be sent to the network along with tokens, min and expected amounts out.\n */\n async generalisedExit(\n poolId: string,\n amount: string,\n userAddress: string,\n slippage: string,\n authorisation?: string\n ): Promise<{\n to: string;\n callData: string;\n tokensOut: string[];\n expectedAmountsOut: string[];\n minAmountsOut: string[];\n priceImpact: string;\n }> {\n return this.exitService.exitPool(\n poolId,\n amount,\n userAddress,\n slippage,\n authorisation\n );\n }\n\n /**\n * Calculates total fees for the pool in the last 24 hours\n *\n * @param pool\n * @returns\n */\n async fees(pool: Pool): Promise<number> {\n return this.feesService.last24h(pool);\n }\n\n /**\n * Calculates total volume of the pool in the last 24 hours\n *\n * @param pool\n * @returns\n */\n async volume(pool: Pool): Promise<number> {\n return this.volumeService.last24h(pool);\n }\n\n static wrap(\n pool: Pool,\n networkConfig: BalancerNetworkConfig\n ): PoolWithMethods {\n let concerns: ReturnType<typeof PoolTypeConcerns.from>;\n let queries: Queries.ParamsBuilder;\n let methods;\n try {\n concerns = PoolTypeConcerns.from(pool.poolType);\n methods = {\n buildJoin: (\n joiner: string,\n tokensIn: string[],\n amountsIn: string[],\n slippage: string\n ): JoinPoolAttributes => {\n return concerns.join.buildJoin({\n joiner,\n pool,\n tokensIn,\n amountsIn,\n slippage,\n wrappedNativeAsset,\n });\n },\n calcPriceImpact: async (\n amountsIn: string[],\n minBPTOut: string,\n isJoin: boolean\n ) =>\n concerns.priceImpactCalculator.calcPriceImpact(\n pool,\n amountsIn,\n minBPTOut,\n isJoin\n ),\n buildExitExactBPTIn: (\n exiter: string,\n bptIn: string,\n slippage: string,\n shouldUnwrapNativeAsset = false,\n singleTokenMaxOut?: string\n ) => {\n if (concerns.exit.buildExitExactBPTIn) {\n return concerns.exit.buildExitExactBPTIn({\n exiter,\n pool,\n bptIn,\n slippage,\n shouldUnwrapNativeAsset,\n wrappedNativeAsset,\n singleTokenMaxOut,\n });\n } else {\n throw 'ExitExactBPTIn not supported';\n }\n },\n buildExitExactTokensOut: (\n exiter: string,\n tokensOut: string[],\n amountsOut: string[],\n slippage: string\n ) =>\n concerns.exit.buildExitExactTokensOut({\n exiter,\n pool,\n tokensOut,\n amountsOut,\n slippage,\n wrappedNativeAsset,\n }),\n // TODO: spotPrice fails, because it needs a subgraphType,\n // either we refetch or it needs a type transformation from SDK internal to SOR (subgraph)\n // spotPrice: async (tokenIn: string, tokenOut: string) =>\n // methods.spotPriceCalculator.calcPoolSpotPrice(tokenIn, tokenOut, data),\n calcSpotPrice: (tokenIn: string, tokenOut: string) =>\n concerns.spotPriceCalculator.calcPoolSpotPrice(\n tokenIn,\n tokenOut,\n pool\n ),\n calcProportionalAmounts: (token: string, amount: string) => {\n return proportionalAmounts(pool, token, amount);\n },\n };\n } catch (error) {\n if ((error as BalancerError).code != 'UNSUPPORTED_POOL_TYPE') {\n console.error(error);\n }\n\n methods = {\n buildJoin: notImplemented(pool.poolType, 'buildJoin'),\n calcPriceImpact: notImplemented(pool.poolType, 'calcPriceImpact'),\n buildExitExactBPTIn: notImplemented(\n pool.poolType,\n 'buildExitExactBPTIn'\n ),\n buildExitExactTokensOut: notImplemented(\n pool.poolType,\n 'buildExitExactTokensOut'\n ),\n calcSpotPrice: notImplemented(pool.poolType, 'calcSpotPrice'),\n };\n }\n\n try {\n queries = new Queries.ParamsBuilder(pool);\n methods = {\n ...methods,\n buildQueryJoinExactIn: queries.buildQueryJoinExactIn.bind(queries),\n buildQueryJoinExactOut: queries.buildQueryJoinExactOut.bind(queries),\n buildQueryExitExactOut: queries.buildQueryExitExactOut.bind(queries),\n buildQueryExitToSingleToken:\n queries.buildQueryExitToSingleToken.bind(queries),\n buildQueryExitProportionally:\n queries.buildQueryExitProportionally.bind(queries),\n };\n } catch (error) {\n methods = {\n ...methods,\n buildQueryJoinExactIn: notImplemented(\n pool.poolType,\n 'buildQueryJoinExactIn'\n ),\n buildQueryJoinExactOut: notImplemented(\n pool.poolType,\n 'buildQueryJoinExactOut'\n ),\n buildQueryExitExactOut: notImplemented(\n pool.poolType,\n 'buildQueryExitExactOut'\n ),\n buildQueryExitToSingleToken: notImplemented(\n pool.poolType,\n 'buildQueryExitToSingleToken'\n ),\n buildQueryExitProportionally: notImplemented(\n pool.poolType,\n 'buildQueryExitProportionally'\n ),\n };\n }\n const wrappedNativeAsset =\n networkConfig.addresses.tokens.wrappedNativeAsset.toLowerCase();\n return {\n ...pool,\n ...methods,\n };\n }\n\n async find(id: string): Promise<PoolWithMethods | undefined> {\n const data = await this.dataSource().find(id);\n if (!data) return;\n\n return Pools.wrap(data, this.networkConfig);\n }\n\n async findBy(\n param: string,\n value: string\n ): Promise<PoolWithMethods | undefined> {\n if (param == 'id') {\n return this.find(value);\n } else if (param == 'address') {\n const data = await this.dataSource().findBy('address', value);\n if (!data) return;\n\n return Pools.wrap(data, this.networkConfig);\n } else {\n throw `search by ${param} not implemented`;\n }\n }\n\n async all(): Promise<PoolWithMethods[]> {\n const list = await this.dataSource().all();\n if (!list) return [];\n\n return list\n .map((data: Pool) => Pools.wrap(data, this.networkConfig))\n .filter((p) => p) as PoolWithMethods[];\n }\n\n async where(filter: (pool: Pool) => boolean): Promise<PoolWithMethods[]> {\n const list = await this.dataSource().where(filter);\n if (!list) return [];\n\n const wrapped = list.map((data: Pool) =>\n Pools.wrap(data, this.networkConfig)\n );\n\n return wrapped.filter((p) => p) as PoolWithMethods[];\n }\n}\n","import { Interface } from '@ethersproject/abi';\nimport { getAddress } from '@ethersproject/address';\nimport { Contract } from '@ethersproject/contracts';\nimport { Provider } from '@ethersproject/providers';\nimport { formatUnits } from '@ethersproject/units';\nimport { Multicall } from '@/modules/contracts/implementations/multicall';\n\nconst gaugeControllerInterface = new Interface([\n 'function gauge_relative_weight(address gauge, uint timestamp) view returns (uint)',\n 'function gauge_relative_weight_write(address gauge, uint timestamp) returns (uint)',\n]);\n\nexport class GaugeControllerMulticallRepository {\n multicall: Contract;\n\n constructor(\n multicallAddress: string,\n private gaugeControllerAddress: string,\n provider: Provider\n ) {\n this.multicall = Multicall(multicallAddress, provider);\n }\n\n async getRelativeWeights(\n gaugeAddresses: string[],\n timestamp?: number\n ): Promise<{ [gaugeAddress: string]: number }> {\n const payload = gaugeAddresses.map((gaugeAddress) => [\n this.gaugeControllerAddress,\n gaugeControllerInterface.encodeFunctionData(\n 'gauge_relative_weight_write',\n [getAddress(gaugeAddress), timestamp || Math.floor(Date.now() / 1000)]\n ),\n ]);\n const [, res] = await this.multicall.aggregate(payload);\n\n const weights = gaugeAddresses.reduce(\n (p: { [key: string]: number }, a, i) => {\n p[a] ||= parseFloat(formatUnits(res[i], 18));\n return p;\n },\n {}\n );\n\n return weights;\n }\n}\n","/* eslint-disable @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any */\nimport { Findable } from '@/types';\n\nexport abstract class AbstractSubgraphRepository<T, A>\n implements Findable<T, A>\n{\n protected abstract mapType(subgraphFragment: any): T;\n\n abstract query(args: any): Promise<T[]>;\n\n async get(args: any): Promise<T | undefined> {\n const result = await this.query(args);\n return result?.length > 0 ? result[0] : undefined;\n }\n\n async find(id: string): Promise<T | undefined> {\n return this.get({ where: { id: id } });\n }\n\n async findBy(attribute: A, value: string): Promise<T | undefined> {\n return this.get({ where: { [String(attribute)]: value } });\n }\n\n async findAllBy(\n attribute: A,\n value: string,\n first = 1000,\n skip = 0\n ): Promise<T[]> {\n const args = {\n where: { [String(attribute)]: value },\n first: first,\n skip: skip,\n };\n return this.query(args);\n }\n}\n","import { Network } from '@/lib/constants/network';\nimport { AbstractSubgraphRepository } from './abstract-subgraph-repository';\nimport { createSubgraphClient, SubgraphClient } from '../subgraph';\n\nexport abstract class BalancerSubgraphRepository<\n T,\n A\n> extends AbstractSubgraphRepository<T, A> {\n protected client: SubgraphClient;\n\n constructor(\n url: string,\n protected chainId: Network,\n protected blockHeight?: () => Promise<number | undefined>\n ) {\n super();\n this.client = createSubgraphClient(url);\n }\n}\n","import { Network } from '@/lib/constants/network';\nimport { AbstractSubgraphRepository } from './abstract-subgraph-repository';\nimport { createGaugesClient, GaugesClient } from '../subgraph';\n\nexport abstract class GaugesSubgraphRepository<\n T,\n A\n> extends AbstractSubgraphRepository<T, A> {\n protected client: GaugesClient;\n\n constructor(\n url: string,\n protected chainId: Network,\n protected blockHeight?: () => Promise<number | undefined>\n ) {\n super();\n this.client = createGaugesClient(url);\n }\n}\n","/* eslint-disable @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any */\nimport { GaugeShare, GaugeShareAttributes } from './types';\nimport { GaugesSubgraphRepository } from '@/modules/subgraph/repository';\nimport {\n SubgraphGaugeShareFragment,\n GaugeShare_OrderBy,\n OrderDirection,\n} from '@/modules/subgraph/generated/balancer-gauges';\n\nexport class GaugeSharesRepository extends GaugesSubgraphRepository<\n GaugeShare,\n GaugeShareAttributes\n> {\n async query(args: any): Promise<GaugeShare[]> {\n if (!args.orderBy) args.orderBy = GaugeShare_OrderBy.Balance;\n if (!args.orderDirection) args.orderDirection = OrderDirection.Desc;\n if (!args.block && this.blockHeight)\n args.block = { number: await this.blockHeight() };\n\n const { gaugeShares } = await this.client.GaugeShares(args);\n return gaugeShares.map(this.mapType);\n }\n\n mapType(subgraphGaugeShare: SubgraphGaugeShareFragment): GaugeShare {\n return {\n id: subgraphGaugeShare.id,\n balance: subgraphGaugeShare.balance,\n userAddress: subgraphGaugeShare.user?.id,\n gauge: {\n id: subgraphGaugeShare.gauge.id,\n poolId: subgraphGaugeShare.gauge.poolId || undefined,\n isKilled: subgraphGaugeShare.gauge.isKilled,\n totalSupply: subgraphGaugeShare.gauge.totalSupply,\n },\n };\n }\n\n async findByUser(\n userAddress: string,\n first?: number,\n skip?: number\n ): Promise<GaugeShare[]> {\n return this.findAllBy(\n GaugeShareAttributes.UserAddress,\n userAddress,\n first,\n skip\n );\n }\n\n async findByGauge(\n gaugeId: string,\n first?: number,\n skip?: number\n ): Promise<GaugeShare[]> {\n return this.findAllBy(GaugeShareAttributes.GaugeId, gaugeId, first, skip);\n }\n}\n","import { Multicall } from '@/modules/contracts/implementations/multicall';\nimport { Provider } from '@ethersproject/providers';\nimport { Interface } from '@ethersproject/abi';\nimport { Contract } from '@ethersproject/contracts';\nimport { formatUnits } from '@ethersproject/units';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport type { Network } from '@/types';\n\nconst liquidityGaugeV5Interface = new Interface([\n 'function totalSupply() view returns (uint)',\n 'function working_supply() view returns (uint)',\n 'function reward_count() view returns (uint)',\n 'function reward_tokens(uint rewardIndex) view returns (address)',\n 'function reward_data(address rewardToken) view returns (tuple(address token, address distributor, uint period_finish, uint rate, uint last_update, uint integral) data)',\n]);\n\nexport interface RewardData {\n token: string; // Always 0x0\n distributor: string;\n period_finish: BigNumber;\n rate: BigNumber; // per second\n last_update: BigNumber;\n integral: BigNumber; // sum accrued to date\n decimals?: number; // Provided by subgraph\n}\n\n/**\n * A lot of code to get liquidity gauge state via RPC multicall.\n * TODO: reseach helper contracts or extend subgraph\n */\nexport class LiquidityGaugesMulticallRepository {\n multicall: Contract;\n\n constructor(\n multicallAddress: string,\n private chainId: Network,\n provider: Provider\n ) {\n this.multicall = Multicall(multicallAddress, provider);\n }\n\n async getTotalSupplies(\n gaugeAddresses: string[]\n ): Promise<{ [gaugeAddress: string]: number }> {\n const payload = gaugeAddresses.map((gaugeAddress) => [\n gaugeAddress,\n liquidityGaugeV5Interface.encodeFunctionData('totalSupply', []),\n ]);\n const [, res] = await this.multicall.aggregate(payload);\n // Handle 0x\n const res0x = res.map((r: string) => (r == '0x' ? '0x0' : r));\n\n const totalSupplies = gaugeAddresses.reduce(\n (p: { [key: string]: number }, a, i) => {\n p[a] ||= parseFloat(formatUnits(res0x[i], 18));\n return p;\n },\n {}\n );\n\n return totalSupplies;\n }\n\n async getWorkingSupplies(\n gaugeAddresses: string[]\n ): Promise<{ [gaugeAddress: string]: number }> {\n const payload = gaugeAddresses.map((gaugeAddress) => [\n gaugeAddress,\n liquidityGaugeV5Interface.encodeFunctionData('working_supply', []),\n ]);\n const [, res] = await this.multicall.aggregate(payload);\n // Handle 0x\n const res0x = res.map((r: string) => (r == '0x' ? '0x0' : r));\n\n const workingSupplies = gaugeAddresses.reduce(\n (p: { [key: string]: number }, a, i) => {\n p[a] ||= parseFloat(formatUnits(res0x[i], 18));\n return p;\n },\n {}\n );\n\n return workingSupplies;\n }\n\n async getRewardCounts(\n gaugeAddresses: string[]\n ): Promise<{ [gaugeAddress: string]: number }> {\n let rewardCounts;\n //if (this.chainId == 1) {\n // Hung fix APR\n if (\n this.chainId == 1 ||\n // this.chainId == 16116 ||\n // this.chainId == 17117 ||\n this.chainId == 248 ||\n this.chainId == 9372\n ) {\n const payload = gaugeAddresses.map((gaugeAddress) => [\n gaugeAddress,\n liquidityGaugeV5Interface.encodeFunctionData('reward_count', []),\n ]);\n const [, res] = await this.multicall.aggregate(payload);\n // Handle 0x return values\n const res0x = res.map((r: string) => (r == '0x' ? '0x0' : r));\n\n rewardCounts = gaugeAddresses.reduce(\n (p: { [key: string]: number }, a, i) => {\n p[a] ||= parseInt(res0x[i]);\n return p;\n },\n {}\n );\n } else {\n rewardCounts = gaugeAddresses.reduce(\n (p: { [key: string]: number }, a) => {\n p[a] ||= 1;\n return p;\n },\n {}\n );\n }\n\n return rewardCounts;\n }\n\n async getRewardTokens(\n gaugeAddresses: string[],\n passingRewardCounts?: { [gaugeAddress: string]: number }\n ): Promise<{ [gaugeAddress: string]: string[] }> {\n const rewardCounts =\n passingRewardCounts || (await this.getRewardCounts(gaugeAddresses));\n const gaugesWithRewards = gaugeAddresses.filter(\n (gaugeAddress) => rewardCounts[gaugeAddress] > 0\n );\n const startIndexes = [0];\n const payload = gaugesWithRewards\n .map((gaugeAddress, gaugeIndex) => {\n const calls = [];\n for (let i = 0; i < rewardCounts[gaugeAddress]; i++) {\n calls.push([\n gaugeAddress,\n liquidityGaugeV5Interface.encodeFunctionData('reward_tokens', [i]),\n ]);\n }\n startIndexes[gaugeIndex + 1] =\n startIndexes[gaugeIndex] + rewardCounts[gaugeAddress];\n return calls;\n })\n .flat();\n const [, res] = await this.multicall.aggregate(payload);\n\n const rewardTokens = gaugesWithRewards.reduce(\n (p: { [key: string]: string[] }, a, i) => {\n const start = startIndexes[i];\n const end = startIndexes[i + 1];\n const tokens: string[] = [];\n for (let i = start; i < end; i++) {\n tokens.push(\n liquidityGaugeV5Interface.decodeFunctionResult(\n 'reward_tokens',\n res[i]\n )[0]\n );\n }\n p[a] ||= tokens;\n return p;\n },\n {}\n );\n\n return rewardTokens;\n }\n\n async getRewardData(\n gaugeAddresses: string[],\n passingRewardTokens?: { [gaugeAddress: string]: string[] }\n ): Promise<{\n [gaugeAddress: string]: { [rewardTokenAddress: string]: RewardData };\n }> {\n const rewardTokens =\n passingRewardTokens || (await this.getRewardTokens(gaugeAddresses));\n\n const startIndexes = [0];\n const payload = Object.keys(rewardTokens)\n .map((gaugeAddress, gaugeIndex) => {\n const calls = [];\n for (let i = 0; i < rewardTokens[gaugeAddress].length; i++) {\n calls.push([\n gaugeAddress,\n liquidityGaugeV5Interface.encodeFunctionData('reward_data', [\n rewardTokens[gaugeAddress][i],\n ]),\n ]);\n }\n startIndexes[gaugeIndex + 1] =\n startIndexes[gaugeIndex] + rewardTokens[gaugeAddress].length;\n return calls;\n })\n .flat();\n const [, res] = (await this.multicall.aggregate(payload)) as [\n unknown,\n string[]\n ];\n const decoded = res.map(\n (r) => liquidityGaugeV5Interface.decodeFunctionResult('reward_data', r)[0]\n );\n\n const rewardData = Object.keys(rewardTokens).reduce(\n (p: { [key: string]: { [key: string]: RewardData } }, a, i) => {\n const start = startIndexes[i];\n const data = rewardTokens[a].reduce(\n (d: { [key: string]: RewardData }, t, x) => {\n d[t] ||= decoded[start + x] as RewardData;\n return d;\n },\n {}\n );\n p[a] ||= data;\n return p;\n },\n {}\n );\n\n return rewardData;\n }\n}\n","import { Findable } from '../types';\nimport {\n createGaugesClient,\n GaugesClient,\n SubgraphLiquidityGauge,\n} from '@/modules/subgraph/subgraph';\n\n/**\n * Access liquidity gauges indexed by subgraph.\n * Because we have ~100 gauges to save on repeated http calls we cache all results as `gauges` on an instance.\n * Balancer's subgraph URL: https://thegraph.com/hosted-service/subgraph/balancer-labs/balancer-gauges\n */\nexport class LiquidityGaugesSubgraphRepository\n implements Findable<SubgraphLiquidityGauge>\n{\n private client: GaugesClient;\n public gauges: SubgraphLiquidityGauge[] = [];\n\n constructor(url: string) {\n this.client = createGaugesClient(url);\n }\n\n async fetch(): Promise<SubgraphLiquidityGauge[]> {\n console.time('fetching liquidity gauges');\n const queryResult = await this.client.Pools({\n where: {\n preferentialGauge_not: null,\n },\n first: 1000,\n });\n const qauges = queryResult.pools.map((pool) => pool.preferentialGauge);\n // TODO: optionally convert subgraph type to sdk internal type\n this.gauges = qauges as SubgraphLiquidityGauge[];\n\n console.timeEnd('fetching liquidity gauges');\n return this.gauges;\n }\n\n async find(id: string): Promise<SubgraphLiquidityGauge | undefined> {\n if (this.gauges.length == 0) {\n await this.fetch();\n }\n\n return this.gauges.find((gauge) => gauge.id == id);\n }\n\n async findBy(\n param: string,\n value: string\n ): Promise<SubgraphLiquidityGauge | undefined> {\n if (this.gauges.length == 0) {\n await this.fetch();\n }\n\n if (param == 'id') {\n return this.find(value);\n } else if (param == 'poolId') {\n return this.gauges.find((gauge) => gauge.poolId == value);\n } else if (param == 'poolAddress') {\n return this.gauges.find((gauge) => gauge.poolAddress == value);\n } else {\n throw `search by ${param} not implemented`;\n }\n }\n}\n","import { GaugeControllerMulticallRepository } from '../gauge-controller/multicall';\nimport { LiquidityGaugesMulticallRepository, RewardData } from './multicall';\nimport { LiquidityGaugesSubgraphRepository } from './subgraph';\nimport { parseUnits } from '@ethersproject/units';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport type {\n Maybe,\n SubgraphLiquidityGauge,\n} from '@/modules/subgraph/subgraph';\nimport type { Findable } from '../types';\nimport type { Provider } from '@ethersproject/providers';\nimport type { Network } from '@/types';\n\nconst oneWeekInMs = 86400 * 7 * 1000;\n\nexport interface LiquidityGauge {\n id: string;\n address: string;\n name: string;\n poolId?: Maybe<string>;\n poolAddress: string;\n totalSupply: number;\n workingSupply: number;\n relativeWeight: number;\n relativeWeightNextPeriod?: number;\n rewardTokens?: { [tokenAddress: string]: RewardData };\n}\n\nexport class LiquidityGaugeSubgraphRPCProvider\n implements Findable<LiquidityGauge>\n{\n gaugeController?: GaugeControllerMulticallRepository;\n multicall: LiquidityGaugesMulticallRepository;\n subgraph: LiquidityGaugesSubgraphRepository;\n workingSupplies: { [gaugeAddress: string]: number } = {};\n workingSuppliesNextPeriod: { [gaugeAddress: string]: number } = {};\n relativeWeights: { [gaugeAddress: string]: number } = {};\n relativeWeightsNextPeriod: { [gaugeAddress: string]: number } = {};\n rewardData: {\n [gaugeAddress: string]: { [tokenAddress: string]: RewardData };\n } = {};\n gauges?: Promise<LiquidityGauge[]>;\n\n constructor(\n subgraphUrl: string,\n multicallAddress: string,\n gaugeControllerAddress: string,\n private chainId: Network,\n provider: Provider\n ) {\n if (gaugeControllerAddress) {\n this.gaugeController = new GaugeControllerMulticallRepository(\n multicallAddress,\n gaugeControllerAddress,\n provider\n );\n }\n this.multicall = new LiquidityGaugesMulticallRepository(\n multicallAddress,\n chainId,\n provider\n );\n this.subgraph = new LiquidityGaugesSubgraphRepository(subgraphUrl);\n }\n\n async fetch(): Promise<LiquidityGauge[]> {\n const gauges: SubgraphLiquidityGauge[] = await this.subgraph.fetch();\n const gaugeAddresses = gauges.map((g) => g.id);\n\n if (this.chainId == 248 || this.chainId == 9372) {\n console.time('Fetching multicall.getWorkingSupplies');\n this.workingSupplies = await this.multicall.getWorkingSupplies(\n gaugeAddresses\n );\n console.timeEnd('Fetching multicall.getWorkingSupplies');\n }\n if (this.gaugeController) {\n console.time('Fetching gaugeController.getRelativeWeights');\n this.relativeWeights = await this.gaugeController.getRelativeWeights(\n gaugeAddresses\n );\n console.timeEnd('Fetching gaugeController.getRelativeWeights');\n\n const nextWeekTimestamp =\n Math.round(\n Math.floor((Date.now() + oneWeekInMs) / oneWeekInMs) * oneWeekInMs\n ) / 1000;\n this.relativeWeightsNextPeriod =\n await this.gaugeController.getRelativeWeights(\n gaugeAddresses,\n nextWeekTimestamp\n );\n }\n\n // Kept as a potential fallback for getting rewardData from RPC\n // this.rewardData = await this.multicall.getRewardData(\n // gaugeAddresses //,\n // // rewardTokens\n // );\n\n let hasSubgraphData = false;\n\n // Reward data was made available from subgraph, keeping it separate for potential RPC fallback\n this.rewardData = gauges.reduce(\n (r: { [key: string]: { [key: string]: RewardData } }, g) => {\n r[g.id] ||= g.tokens\n ? Object.fromEntries(\n g.tokens.map((t) => [\n t.id.split('-')[0],\n {\n distributor: '',\n last_update: BigNumber.from(0),\n integral: BigNumber.from(0),\n token: t.id.split('-')[0],\n decimals: t.decimals,\n rate: parseUnits(t.rate || '0', t.decimals),\n period_finish: BigNumber.from(\n (t.periodFinish as unknown as string) || '0'\n ),\n },\n ])\n )\n : {};\n if (g.tokens && g.tokens.length > 0) {\n hasSubgraphData = true;\n }\n return r;\n },\n {}\n );\n\n if (!hasSubgraphData) {\n this.rewardData = await this.multicall.getRewardData(\n gaugeAddresses //,\n // rewardTokens\n );\n }\n return gauges.map(this.compose.bind(this));\n }\n\n async find(id: string): Promise<LiquidityGauge | undefined> {\n if (!this.gauges) {\n this.gauges = this.fetch();\n }\n\n return (await this.gauges).find((g) => g.id == id);\n }\n\n async findBy(\n attribute: string,\n value: string\n ): Promise<LiquidityGauge | undefined> {\n if (!this.gauges) {\n this.gauges = this.fetch();\n }\n\n let gauge: LiquidityGauge | undefined;\n if (attribute == 'id') {\n return this.find(value);\n } else if (attribute == 'address') {\n return this.find(value);\n } else if (attribute == 'poolId') {\n gauge = (await this.gauges).find((g) => g.poolId == value);\n } else if (attribute == 'poolAddress') {\n gauge = (await this.gauges).find((g) => g.poolAddress == value);\n } else {\n throw `search by ${attribute} not implemented`;\n }\n\n return gauge;\n }\n\n private compose(subgraphGauge: SubgraphLiquidityGauge) {\n return {\n id: subgraphGauge.id,\n address: subgraphGauge.id,\n name: subgraphGauge.symbol,\n poolId: subgraphGauge.poolId,\n poolAddress: subgraphGauge.poolAddress,\n totalSupply: parseFloat(subgraphGauge.totalSupply),\n workingSupply: this.workingSupplies[subgraphGauge.id],\n relativeWeight: this.relativeWeights[subgraphGauge.id],\n relativeWeightNextPeriod:\n this.relativeWeightsNextPeriod[subgraphGauge.id],\n rewardTokens: this.rewardData[subgraphGauge.id],\n };\n }\n}\n","import axios from 'axios';\nimport { jsonToGraphQLQuery } from 'json-to-graphql-query';\n\nexport default class BalancerAPIClient {\n constructor(private readonly url: string, private readonly apiKey: string) {}\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public async get(query: unknown): Promise<any> {\n try {\n const payload = this.toPayload(query);\n const { data } = await axios.post(this.url, payload, {\n headers: {\n 'x-api-key': this.apiKey,\n },\n });\n if (data.errors) {\n throw new Error(\n data.errors.map((error: Error) => error.message).join(',')\n );\n }\n return data.data;\n } catch (error) {\n console.error(error);\n throw error;\n }\n\n return [];\n }\n\n public toPayload(query: unknown): unknown {\n return JSON.stringify({ query: jsonToGraphQLQuery({ query }) });\n }\n}\n","import { Findable } from '../types';\nimport { PoolAttribute, PoolsRepositoryFetchOptions } from './types';\nimport { GraphQLQuery, Pool } from '@/types';\nimport BalancerAPIClient from '@/modules/api/balancer-api.client';\nimport {\n GraphQLArgsBuilder,\n BalancerAPIArgsFormatter,\n} from '@/lib/graphql/args-builder';\nimport { GraphQLArgs } from '@/lib/graphql/types';\n\ninterface PoolsBalancerAPIOptions {\n url: string;\n apiKey: string;\n query?: GraphQLQuery;\n}\n\nconst DEFAULT_SKIP = 0;\nconst DEFAULT_FIRST = 10;\n\n/**\n * Access pools using the Balancer GraphQL Api.\n *\n * Balancer's API URL: https://api.balancer.fi/query/\n */\nexport class PoolsBalancerAPIRepository\n implements Findable<Pool, PoolAttribute>\n{\n private client: BalancerAPIClient;\n public pools: Pool[] = [];\n public skip = 0; // Keep track of how many pools to skip on next fetch, so this functions similar to subgraph repository.\n public nextToken: string | undefined; // A token to pass to the next query to retrieve the next page of results.\n private query: GraphQLQuery;\n\n constructor(options: PoolsBalancerAPIOptions) {\n this.client = new BalancerAPIClient(options.url, options.apiKey);\n\n const defaultArgs: GraphQLArgs = {\n chainId: 248,\n orderBy: 'totalLiquidity',\n orderDirection: 'desc',\n where: {\n swapEnabled: {\n eq: true,\n },\n //totalShares: {\n // gt: 0.05,\n //},\n },\n };\n\n const defaultAttributes = {\n id: true,\n address: true,\n };\n\n this.query = {\n args: Object.assign({}, options.query?.args || defaultArgs),\n attrs: Object.assign({}, options.query?.attrs || defaultAttributes),\n };\n\n // skip is not a valid argument for the Balancer API, it uses nextToken\n delete this.query.args.skip;\n }\n\n fetchFromCache(options?: PoolsRepositoryFetchOptions): Pool[] {\n const first = options?.first || DEFAULT_FIRST;\n const skip = options?.skip || DEFAULT_SKIP;\n\n const pools = this.pools.slice(skip, first + skip);\n this.skip = skip + first;\n return pools;\n }\n\n async fetch(options?: PoolsRepositoryFetchOptions): Promise<Pool[]> {\n if (\n this.pools.length >\n (options?.first || DEFAULT_FIRST) + (options?.skip || DEFAULT_SKIP)\n ) {\n return this.fetchFromCache(options);\n }\n\n if (this.nextToken) {\n this.query.args.nextToken = this.nextToken;\n }\n\n if (options?.first) {\n // We need to request more than they specified because filtering is done post limit\n // e.g. if we ask for 10 we may get 7 because 3 were filtered out.\n this.query.args.first = options.first * 2;\n }\n\n const formattedArgs = new GraphQLArgsBuilder(this.query.args).format(\n new BalancerAPIArgsFormatter()\n );\n\n const attrs = this.query.attrs;\n attrs.nextToken = true;\n\n const formattedQuery = {\n pools: {\n __args: formattedArgs,\n ...attrs,\n },\n };\n\n const apiResponse = await this.client.get(formattedQuery);\n const apiResponseData = apiResponse.pools;\n\n this.nextToken = apiResponseData.nextToken;\n this.pools = this.pools.concat(apiResponseData.pools.map(this.format));\n this.skip = this.pools.length;\n\n return this.fetchFromCache(options);\n }\n\n async find(id: string): Promise<Pool | undefined> {\n if (this.pools.length == 0) {\n await this.fetch();\n }\n\n return this.findBy('id', id);\n }\n\n async findBy(param: PoolAttribute, value: string): Promise<Pool | undefined> {\n if (this.pools.length == 0) {\n await this.fetch();\n }\n\n const pool = this.pools.find((pool) => pool[param] == value);\n if (pool) {\n return this.format(pool);\n }\n }\n\n /** Fixes any formatting issues from the subgraph\n * - GraphQL can't store a map so pool.apr.[rewardAprs/tokenAprs].breakdown\n * is JSON data that needs to be parsed so they match the Pool type correctly.\n */\n private format(pool: Pool): Pool {\n if (pool.apr?.rewardAprs.breakdown) {\n // GraphQL can't store this as a map so it's JSON that we must parse\n const rewardsBreakdown = JSON.parse(\n pool.apr?.rewardAprs.breakdown as unknown as string\n );\n pool.apr.rewardAprs.breakdown = rewardsBreakdown;\n }\n if (pool.apr?.tokenAprs.breakdown) {\n // GraphQL can't store this as a map so it's JSON that we must parse\n const tokenAprsBreakdown = JSON.parse(\n pool.apr?.tokenAprs.breakdown as unknown as string\n );\n pool.apr.tokenAprs.breakdown = tokenAprsBreakdown;\n }\n\n return pool;\n }\n}\n","import { Findable } from '../types';\nimport { Pool } from '@/types';\nimport {\n PoolAttribute,\n PoolRepository,\n PoolsFallbackRepositoryOptions,\n PoolsRepositoryFetchOptions,\n} from './types';\n\n/**\n * The fallback provider takes multiple PoolRepository's in an array and uses them in order\n * falling back to the next one if a request times out.\n *\n * This is useful for using the Balancer API while being able to fall back to the graph if it is down\n * to ensure Balancer is maximally decentralized.\n **/\nexport class PoolsFallbackRepository implements Findable<Pool, PoolAttribute> {\n currentProviderIdx: number;\n timeout: number;\n\n constructor(\n private readonly providers: PoolRepository[],\n options: PoolsFallbackRepositoryOptions = {}\n ) {\n this.currentProviderIdx = 0;\n this.timeout = options.timeout || 10000;\n }\n\n async fetch(options?: PoolsRepositoryFetchOptions): Promise<Pool[]> {\n return this.fallbackQuery('fetch', [options]);\n }\n\n get currentProvider(): PoolRepository | undefined {\n if (\n !this.providers.length ||\n this.currentProviderIdx >= this.providers.length\n ) {\n return;\n }\n\n return this.providers[this.currentProviderIdx];\n }\n\n async find(id: string): Promise<Pool | undefined> {\n return this.fallbackQuery('find', [id]);\n }\n\n async findBy(\n attribute: PoolAttribute,\n value: string\n ): Promise<Pool | undefined> {\n return this.fallbackQuery('findBy', [attribute, value]);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async fallbackQuery(func: string, args: unknown[]): Promise<any> {\n if (this.currentProviderIdx >= this.providers.length) {\n throw new Error('No working providers found');\n }\n\n let result;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const currentProvider = this.providers[this.currentProviderIdx] as any;\n result = await Promise.race<unknown | undefined>([\n // eslint-disable-next-line prefer-spread\n currentProvider[func].apply(currentProvider, args),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('timeout')), this.timeout)\n ),\n ]);\n } catch (e: unknown) {\n const message = (e as Error).message;\n if (message === 'timeout') {\n console.error(\n 'Provider ' +\n this.currentProviderIdx +\n ' timed out, falling back to next provider'\n );\n } else {\n console.error(\n 'Provider ' + this.currentProviderIdx + ' failed with error: ',\n message,\n ', falling back to next provider'\n );\n }\n this.currentProviderIdx++;\n result = await this.fallbackQuery.call(this, func, args);\n }\n\n return result;\n }\n}\n","import { Findable, Pool, Searchable } from '@/types';\nimport { PoolAttribute } from './types';\n\nexport class PoolsStaticRepository\n implements Findable<Pool, PoolAttribute>, Searchable<Pool>\n{\n constructor(private pools: Pool[]) {}\n\n async find(id: string): Promise<Pool | undefined> {\n return this.pools.find((pool) => {\n return pool.id.toLowerCase() === id.toLowerCase();\n });\n }\n\n async findBy(\n attribute: PoolAttribute,\n value: string\n ): Promise<Pool | undefined> {\n return this.pools.find((pool) => {\n return pool[attribute] === value;\n });\n }\n\n async all(): Promise<Pool[]> {\n return this.pools;\n }\n\n async where(filter: (pool: Pool) => boolean): Promise<Pool[]> {\n return (await this.all()).filter(filter);\n }\n}\n","import { Findable, Searchable } from '../types';\nimport {\n createSubgraphClient,\n SubgraphClient,\n SubgraphPool,\n Pool_OrderBy,\n OrderDirection,\n SubgraphPoolTokenFragment,\n SubgraphSubPoolFragment,\n SubgraphSubPoolTokenFragment,\n} from '@/modules/subgraph/subgraph';\nimport {\n GraphQLArgsBuilder,\n SubgraphArgsFormatter,\n} from '@/lib/graphql/args-builder';\nimport { GraphQLArgs } from '@/lib/graphql/types';\nimport { PoolAttribute, PoolsRepositoryFetchOptions } from './types';\nimport {\n GraphQLQuery,\n Pool,\n PoolType,\n PoolToken,\n SubPool,\n SubPoolMeta,\n} from '@/types';\nimport { Network } from '@/lib/constants/network';\nimport { PoolsQueryVariables } from '../../subgraph/subgraph';\n\ninterface PoolsSubgraphRepositoryOptions {\n url: string;\n chainId: Network;\n blockHeight?: () => Promise<number | undefined>;\n query?: GraphQLQuery;\n}\n\ninterface SubgraphSubPoolToken extends SubgraphSubPoolTokenFragment {\n token?: SubgraphSubPoolMeta | null;\n}\n\ninterface SubgraphSubPoolMeta {\n latestUSDPrice?: string | null;\n pool?: SubgraphSubPool | null;\n}\n\ninterface SubgraphSubPool extends SubgraphSubPoolFragment {\n tokens: SubgraphSubPoolToken[];\n}\n\n/**\n * Access pools using generated subgraph client.\n *\n * Balancer's subgraph URL: https://thegraph.com/hosted-service/subgraph/balancer-labs/balancer-v2\n */\nexport class PoolsSubgraphRepository\n implements Findable<Pool, PoolAttribute>, Searchable<Pool>\n{\n private client: SubgraphClient;\n private chainId: Network;\n private pools?: Promise<Pool[]>;\n public skip = 0;\n private blockHeight: undefined | (() => Promise<number | undefined>);\n private query: GraphQLQuery;\n\n /**\n * Repository with optional lazy loaded blockHeight\n *\n * @param url subgraph URL\n * @param chainId current network, needed for L2s logic\n * @param blockHeight lazy loading blockHeigh resolver\n */\n constructor(options: PoolsSubgraphRepositoryOptions) {\n this.client = createSubgraphClient(options.url);\n this.blockHeight = options.blockHeight;\n this.chainId = options.chainId;\n\n const defaultArgs: GraphQLArgs = {\n orderBy: Pool_OrderBy.TotalLiquidity,\n orderDirection: OrderDirection.Desc,\n where: {\n swapEnabled: {\n eq: true,\n },\n // totalShares: {\n // gt: 0.000000000001,\n // },\n },\n };\n\n const args = Object.assign({}, options.query?.args || defaultArgs);\n const attrs = Object.assign({}, options.query?.attrs || {});\n\n this.query = {\n args,\n attrs,\n };\n }\n\n /**\n * We need a list of all the pools, for calculating APRs (nested pools), and for SOR (path finding).\n * All the pools are fetched on page load and cachced for speedy lookups.\n *\n * @returns Promise resolving to pools list\n */\n private async fetchDefault(): Promise<Pool[]> {\n console.time('fetching pools');\n const { pool0, pool1000, pool2000 } = await this.client.AllPools({\n //where: { swapEnabled: true, totalShares_gt: '0.000000000001' },\n where: { swapEnabled: true },\n orderBy: Pool_OrderBy.TotalLiquidity,\n orderDirection: OrderDirection.Desc,\n block: await this.block(),\n });\n console.timeEnd('fetching pools');\n\n return [...pool0, ...pool1000, ...pool2000].map(this.mapType.bind(this));\n }\n\n async fetch(options?: PoolsRepositoryFetchOptions): Promise<Pool[]> {\n if (options?.skip) {\n this.query.args.skip = options.skip;\n }\n if (this.blockHeight) {\n this.query.args.block = { number: await this.blockHeight() };\n }\n\n this.query.args.first = options?.first || 1000;\n\n const formattedQuery = new GraphQLArgsBuilder(this.query.args).format(\n new SubgraphArgsFormatter()\n ) as PoolsQueryVariables;\n\n const { pools } = await this.client.Pools(formattedQuery);\n\n this.skip = (options?.skip || 0) + pools.length;\n\n return pools.map(this.mapType.bind(this));\n }\n\n async find(id: string): Promise<Pool | undefined> {\n return await this.findBy('id', id);\n }\n\n async findBy(param: PoolAttribute, value: string): Promise<Pool | undefined> {\n if (!this.pools) {\n this.pools = this.fetchDefault();\n }\n\n return (await this.pools).find((pool) => pool[param] == value);\n\n // TODO: @Nma - Fetching pools outside of default query is causing a lot of requests\n // on a frontend, because results aren't cached anywhere.\n // For fetching pools directly from subgraph with custom queries please use the client not this repository.\n // Code below kept for reference, to be removed later.\n //\n // if (this.pools) {\n // return (await this.pools).find((p) => p[param] === value);\n // }\n // const { pools } = await this.client.Pools({\n // where: {\n // [param]: value,\n // swapEnabled: true,\n // totalShares_gt: '0.000000000001',\n // },\n // block: await this.block(),\n // });\n // const poolsTab: Pool[] = pools.map(this.mapType.bind(this));\n // return poolsTab.length > 0 ? poolsTab[0] : undefined;\n }\n\n async all(): Promise<Pool[]> {\n if (!this.pools) {\n this.pools = this.fetchDefault();\n }\n return this.pools;\n }\n\n async block(): Promise<{ number: number | undefined } | undefined> {\n return this.blockHeight ? { number: await this.blockHeight() } : undefined;\n }\n\n async where(filter: (pool: Pool) => boolean): Promise<Pool[]> {\n if (!this.pools) {\n this.pools = this.fetchDefault();\n }\n\n return (await this.pools).filter(filter);\n }\n\n private mapType(subgraphPool: SubgraphPool): Pool {\n return {\n id: subgraphPool.id,\n name: subgraphPool.name || '',\n address: subgraphPool.address,\n chainId: this.chainId,\n poolType: subgraphPool.poolType as PoolType,\n poolTypeVersion: subgraphPool.poolTypeVersion || 1,\n swapFee: subgraphPool.swapFee,\n swapEnabled: subgraphPool.swapEnabled,\n protocolYieldFeeCache: subgraphPool.protocolYieldFeeCache || '0',\n protocolSwapFeeCache: subgraphPool.protocolSwapFeeCache || '0',\n amp: subgraphPool.amp ?? undefined,\n owner: subgraphPool.owner ?? undefined,\n factory: subgraphPool.factory ?? undefined,\n symbol: subgraphPool.symbol ?? undefined,\n tokens: (subgraphPool.tokens || []).map(this.mapToken.bind(this)),\n tokensList: subgraphPool.tokensList,\n tokenAddresses: (subgraphPool.tokens || []).map((t) => t.address),\n totalLiquidity: subgraphPool.totalLiquidity,\n totalShares: subgraphPool.totalShares,\n totalSwapFee: subgraphPool.totalSwapFee,\n totalSwapVolume: subgraphPool.totalSwapVolume,\n priceRateProviders: subgraphPool.priceRateProviders ?? undefined,\n // onchain: subgraphPool.onchain,\n createTime: subgraphPool.createTime,\n mainIndex: subgraphPool.mainIndex ?? undefined,\n wrappedIndex: subgraphPool.wrappedIndex ?? undefined,\n // mainTokens: subgraphPool.mainTokens,\n // wrappedTokens: subgraphPool.wrappedTokens,\n // unwrappedTokens: subgraphPool.unwrappedTokens,\n // isNew: subgraphPool.isNew,\n // volumeSnapshot: subgraphPool.volumeSnapshot,\n // feesSnapshot: subgraphPool.???, // Approximated last 24h fees\n // boost: subgraphPool.boost,\n totalWeight: subgraphPool.totalWeight || '1',\n lowerTarget: subgraphPool.lowerTarget ?? '0',\n upperTarget: subgraphPool.upperTarget ?? '0',\n };\n }\n\n private mapToken(subgraphToken: SubgraphPoolTokenFragment): PoolToken {\n const subPoolInfo = this.mapSubPools(\n // need to typecast as the fragment is 3 layers deep while the type is infinite levels deep\n subgraphToken.token as SubgraphSubPoolMeta\n );\n return {\n ...subgraphToken,\n isExemptFromYieldProtocolFee:\n subgraphToken.isExemptFromYieldProtocolFee || false,\n token: subPoolInfo,\n };\n }\n\n private mapSubPools(metadata: SubgraphSubPoolMeta): SubPoolMeta {\n let subPool: SubPool | null = null;\n if (metadata.pool) {\n subPool = {\n id: metadata.pool.id,\n address: metadata.pool.address,\n totalShares: metadata.pool.totalShares,\n poolType: metadata.pool.poolType as PoolType,\n mainIndex: metadata.pool.mainIndex || 0,\n };\n\n if (metadata?.pool.tokens) {\n subPool.tokens = metadata.pool.tokens.map(\n this.mapSubPoolToken.bind(this)\n );\n }\n }\n\n return {\n pool: subPool,\n latestUSDPrice: metadata.latestUSDPrice || undefined,\n };\n }\n\n private mapSubPoolToken(token: SubgraphSubPoolToken) {\n return {\n address: token.address,\n decimals: token.decimals,\n symbol: token.symbol,\n balance: token.balance,\n priceRate: token.priceRate,\n weight: token.weight,\n isExemptFromYieldProtocolFee:\n token.isExemptFromYieldProtocolFee || undefined,\n token: token.token ? this.mapSubPools(token.token) : undefined,\n };\n }\n}\n","import { Findable, Searchable } from '../types';\nimport { Provider } from '@ethersproject/providers';\nimport { PoolAttribute, PoolsRepositoryFetchOptions } from './types';\nimport { GraphQLQuery, Pool } from '@/types';\nimport { Network } from '@/lib/constants/network';\nimport { getOnChainBalances } from '../../../modules/sor/pool-data/onChainData';\nimport { PoolsSubgraphRepository } from './subgraph';\n\ninterface PoolsSubgraphOnChainRepositoryOptions {\n url: string;\n chainId: Network;\n provider: Provider;\n multicall: string;\n vault: string;\n blockHeight?: () => Promise<number | undefined>;\n query?: GraphQLQuery;\n}\n\n/**\n * Access pools using generated subgraph client and multicall.\n */\nexport class PoolsSubgraphOnChainRepository\n implements Findable<Pool, PoolAttribute>, Searchable<Pool>\n{\n private poolsSubgraph: PoolsSubgraphRepository;\n private provider: Provider;\n private pools?: Promise<Pool[]>;\n private multicall: string;\n private vault: string;\n public skip = 0;\n\n /**\n * Repository using multicall to get onchain data.\n *\n * @param url subgraph URL\n * @param chainId current network, needed for L2s logic\n * @param blockHeight lazy loading blockHeigh resolver\n * @param multicall multicall address\n * @param valt vault address\n */\n constructor(options: PoolsSubgraphOnChainRepositoryOptions) {\n this.poolsSubgraph = new PoolsSubgraphRepository({\n url: options.url,\n chainId: options.chainId,\n blockHeight: options.blockHeight,\n query: options.query,\n });\n this.provider = options.provider;\n this.multicall = options.multicall;\n this.vault = options.vault;\n }\n\n /**\n * We need a list of all the pools, for calculating APRs (nested pools), and for SOR (path finding).\n * All the pools are fetched on page load and cachced for speedy lookups.\n *\n * @returns Promise resolving to pools list\n */\n private async fetchDefault(): Promise<Pool[]> {\n console.time('fetching pools SG');\n const pools = await this.poolsSubgraph.fetch();\n console.timeEnd('fetching pools SG');\n console.time('fetching pools onchain');\n const onchainPools = await getOnChainBalances(\n pools,\n this.multicall,\n this.vault,\n this.provider\n );\n console.timeEnd('fetching pools onchain');\n\n return onchainPools;\n }\n\n async fetch(options?: PoolsRepositoryFetchOptions): Promise<Pool[]> {\n const pools = await this.poolsSubgraph.fetch(options);\n const onchainPools = await getOnChainBalances(\n pools,\n this.multicall,\n this.vault,\n this.provider\n );\n return onchainPools;\n }\n\n async find(id: string): Promise<Pool | undefined> {\n return await this.findBy('id', id);\n }\n\n async findBy(param: PoolAttribute, value: string): Promise<Pool | undefined> {\n if (!this.pools) {\n this.pools = this.fetchDefault();\n }\n\n return (await this.pools).find((pool) => pool[param] == value);\n }\n\n async all(): Promise<Pool[]> {\n if (!this.pools) {\n this.pools = this.fetchDefault();\n }\n return this.pools;\n }\n\n async where(filter: (pool: Pool) => boolean): Promise<Pool[]> {\n if (!this.pools) {\n this.pools = this.fetchDefault();\n }\n\n return (await this.pools).filter(filter);\n }\n}\n","/* eslint-disable @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any */\nimport { GaugesSubgraphRepository } from '@/modules/subgraph/repository';\nimport { PoolGauges, PoolGaugesAttributes } from './types';\n\nexport class PoolGaugesRepository extends GaugesSubgraphRepository<\n PoolGauges,\n PoolGaugesAttributes\n> {\n async query(args: any): Promise<PoolGauges[]> {\n if (!args.block && this.blockHeight)\n args.block = { number: await this.blockHeight() };\n\n const { pools } = await this.client.PoolGauges(args);\n return pools.map(this.mapType);\n }\n\n mapType(fragment: any): PoolGauges {\n return fragment as PoolGauges;\n }\n}\n","export enum PoolJoinExitAttributes {\n Pool = 'pool',\n Sender = 'sender',\n}\n\nexport interface PoolJoinExit {\n id: string;\n userAddress: string;\n poolId: string;\n timestamp: number;\n type: string;\n amounts: string[];\n tokens: string[];\n}\n","/* eslint-disable @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any */\nimport { PoolJoinExit, PoolJoinExitAttributes } from './types';\nimport { BalancerSubgraphRepository } from '@/modules/subgraph/repository';\nimport {\n JoinExit_OrderBy,\n OrderDirection,\n SubgraphJoinExitFragment,\n} from '@/modules/subgraph/generated/balancer-subgraph-types';\n\nexport class PoolJoinExitRepository extends BalancerSubgraphRepository<\n PoolJoinExit,\n PoolJoinExitAttributes\n> {\n async query(args: any): Promise<PoolJoinExit[]> {\n if (!args.orderBy) args.orderBy = JoinExit_OrderBy.Timestamp;\n if (!args.orderDirection) args.orderDirection = OrderDirection.Asc;\n if (!args.block && this.blockHeight)\n args.block = { number: await this.blockHeight() };\n\n const { joinExits } = await this.client.JoinExits(args);\n return joinExits.map(this.mapType);\n }\n\n mapType(item: SubgraphJoinExitFragment): PoolJoinExit {\n return {\n id: item.id,\n userAddress: item.user.id,\n poolId: item.pool.id,\n timestamp: item.timestamp,\n type: item.type,\n amounts: item.amounts,\n tokens: item.pool.tokensList,\n };\n }\n\n async findByUser(\n sender: string,\n first?: number,\n skip?: number\n ): Promise<PoolJoinExit[]> {\n return this.findAllBy(PoolJoinExitAttributes.Sender, sender, first, skip);\n }\n\n async findJoins(sender: string, pool: string): Promise<PoolJoinExit[]> {\n return this.query({ where: { sender, pool, type: 'Join' } });\n }\n\n async findExits(sender: string, pool: string): Promise<PoolJoinExit[]> {\n return this.query({ where: { sender, pool, type: 'Exit' } });\n }\n\n async findByPool(\n poolId: string,\n first?: number,\n skip?: number\n ): Promise<PoolJoinExit[]> {\n return this.findAllBy(PoolJoinExitAttributes.Pool, poolId, first, skip);\n }\n}\n","/* eslint-disable @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any */\nimport { PoolShare, PoolShareAttributes } from './types';\nimport { BalancerSubgraphRepository } from '@/modules/subgraph/repository';\nimport {\n SubgraphPoolShareFragment,\n PoolShare_OrderBy,\n OrderDirection,\n} from '@/modules/subgraph/generated/balancer-subgraph-types';\n\nexport class PoolSharesRepository extends BalancerSubgraphRepository<\n PoolShare,\n PoolShareAttributes\n> {\n async query(args: any): Promise<PoolShare[]> {\n if (!args.orderBy) args.orderBy = PoolShare_OrderBy.Balance;\n if (!args.orderDirection) args.orderDirection = OrderDirection.Desc;\n if (!args.block && this.blockHeight)\n args.block = { number: await this.blockHeight() };\n\n const { poolShares } = await this.client.PoolShares(args);\n return poolShares.map(this.mapType);\n }\n\n mapType(subgraphPoolShare: SubgraphPoolShareFragment): PoolShare {\n return {\n id: subgraphPoolShare.id,\n userAddress: subgraphPoolShare.userAddress.id,\n poolId: subgraphPoolShare.poolId.id,\n balance: subgraphPoolShare.balance,\n };\n }\n\n async findByUser(\n userAddress: string,\n first?: number,\n skip?: number\n ): Promise<PoolShare[]> {\n return this.findAllBy(\n PoolShareAttributes.UserAddress,\n userAddress,\n first,\n skip\n );\n }\n\n async findByPool(\n poolId: string,\n first?: number,\n skip?: number\n ): Promise<PoolShare[]> {\n return this.findAllBy(PoolShareAttributes.PoolId, poolId, first, skip);\n }\n}\n","import type { Findable, Token } from '@/types';\nimport type { TokenAttribute } from './types';\n\nexport class StaticTokenProvider implements Findable<Token, TokenAttribute> {\n constructor(private tokens: Token[]) {}\n\n async find(address: string): Promise<Token | undefined> {\n return this.tokens.find((token) => {\n return token.address.toLowerCase() === address.toLowerCase();\n });\n }\n\n async findBy(\n attribute: TokenAttribute,\n value: string\n ): Promise<Token | undefined> {\n return this.tokens.find((token) => {\n return token[attribute] === value;\n });\n }\n}\n","import { Findable, Price, TokenPrices } from '@/types';\n\nexport class StaticTokenPriceProvider implements Findable<Price> {\n tokenPrices: TokenPrices;\n constructor(tokenPrices: TokenPrices) {\n this.tokenPrices = Object.fromEntries(\n Object.entries(tokenPrices).map(([address, price]) => {\n return [address.toLowerCase(), price];\n })\n );\n }\n\n async find(address: string): Promise<Price | undefined> {\n const lowercaseAddress = address.toLowerCase();\n const price = this.tokenPrices[lowercaseAddress];\n if (!price) return;\n return price;\n }\n\n async findBy(attribute: string, value: string): Promise<Price | undefined> {\n if (attribute != 'address') {\n return undefined;\n }\n\n return this.find(value);\n }\n}\n","/* eslint-disable @typescript-eslint/no-empty-function */\nimport { Price, Findable, TokenPrices, Network } from '@/types';\nimport axios from 'axios';\nimport { BALANCER_NETWORK_CONFIG } from '@/lib/constants/config';\nimport { TOKENS } from '@/lib/constants/tokens';\nimport { Debouncer, tokenAddressForPricing } from '@/lib/utils';\n\n/**\n * Simple coingecko price source implementation. Configurable by network and token addresses.\n */\nexport class CoingeckoPriceRepository implements Findable<Price> {\n prices: { [key: string]: Promise<Price> } = {};\n nativePrice?: Promise<Price>;\n urlBase: string;\n baseTokenAddresses: string[];\n debouncer: Debouncer<TokenPrices, string>;\n\n constructor(tokenAddresses: string[], private chainId: Network = 1) {\n this.baseTokenAddresses = tokenAddresses.map(tokenAddressForPricing);\n // this.urlBase = `https://api.coingecko.com/api/v3/simple/token_price/${this.platform(\n // chainId\n // )}?vs_currencies=usd,eth`;\n\n this.urlBase = `${BALANCER_NETWORK_CONFIG[chainId].urls.priceUrl}/price/?vs_currencies=usd,eth`;\n\n this.debouncer = new Debouncer<TokenPrices, string>(\n this.fetch.bind(this),\n 200\n );\n }\n\n private fetch(\n addresses: string[],\n { signal }: { signal?: AbortSignal } = {}\n ): Promise<TokenPrices> {\n console.time(`fetching coingecko for ${addresses.length} tokens`);\n return axios\n .get<TokenPrices>(this.url(addresses), { signal })\n .then(({ data }) => {\n return data;\n })\n .finally(() => {\n console.timeEnd(`fetching coingecko for ${addresses.length} tokens`);\n });\n }\n\n private fetchNative({\n signal,\n }: { signal?: AbortSignal } = {}): Promise<Price> {\n console.time(`fetching coingecko for native token`);\n enum Assets {\n ETH = 'ethereum',\n MATIC = 'matic-network',\n XDAI = 'xdai',\n OAS = 'oasys',\n }\n const assetId: Assets = Assets.OAS;\n const url = this.url(['0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000']);\n return axios\n .get<{ [key in Assets]: Price }>(url, { signal })\n .then(({ data }) => {\n return data[assetId];\n })\n .finally(() => {\n console.timeEnd(`fetching coingecko for native token`);\n });\n }\n\n find(inputAddress: string): Promise<Price | undefined> {\n // const address = tokenAddressForPricing(inputAddress, this.chainId);\n const address = inputAddress.toLowerCase();\n\n if (!this.prices[address]) {\n // Make initial call with all the tokens we want to preload\n if (Object.keys(this.prices).length === 0) {\n for (const baseAddress of this.baseTokenAddresses) {\n this.prices[baseAddress] = this.debouncer\n .fetch(baseAddress)\n .then((prices) => prices[baseAddress]);\n }\n }\n\n // Handle native asset special case\n // Hung change price api\n // if (\n // address === TOKENS(this.chainId).Addresses.nativeAsset.toLowerCase()\n // ) {\n // if (!this.nativePrice) {\n // this.prices[address] = this.fetchNative();\n // }\n\n // return this.prices[address];\n // }\n\n this.prices[address] = this.debouncer\n .fetch(address)\n .then((prices) => prices[address]);\n }\n\n return this.prices[address];\n }\n\n async findBy(attribute: string, value: string): Promise<Price | undefined> {\n if (attribute != 'address') {\n return undefined;\n }\n\n return this.find(value);\n }\n\n private platform(chainId: number): string {\n switch (chainId) {\n case 1:\n case 5:\n case 42:\n case 31337:\n case 248:\n case 9372:\n case 16116:\n case 17117:\n return 'ethereum';\n case 100:\n return 'xdai';\n case 137:\n return 'polygon-pos';\n case 42161:\n return 'arbitrum-one';\n }\n\n return '3';\n }\n\n private url(addresses: string[]): string {\n // return `${this.urlBase}&contract_addresses=${addresses.join(',')}`;\n // Hung change price api\n return `${this.urlBase}&contract_addresses=${addresses.join(',')}`;\n }\n}\n","/* eslint-disable @typescript-eslint/no-empty-function */\nimport {\n Price,\n Findable,\n TokenPrices,\n Network,\n HistoricalPrices,\n} from '@/types';\nimport axios from 'axios';\nimport { tokenAddressForPricing } from '@/lib/utils';\n\nconst HOUR = 60 * 60;\n\n/**\n * Simple coingecko price source implementation. Configurable by network and token addresses.\n */\nexport class CoingeckoHistoricalPriceRepository implements Findable<Price> {\n prices: TokenPrices = {};\n nativePrice?: Promise<Price>;\n urlBase: string;\n\n constructor(private chainId: Network = 1) {\n this.urlBase = `https://api.coingecko.com/api/v3/coins/${this.platform(\n chainId\n )}/contract/%TOKEN_ADDRESS%/market_chart/range?vs_currency=usd`;\n }\n\n private fetch(\n address: string,\n timestamp: number,\n { signal }: { signal?: AbortSignal } = {}\n ): Promise<HistoricalPrices> {\n console.time(`fetching coingecko historical for ${address}`);\n const url = this.urlRange(address, timestamp);\n return axios\n .get<HistoricalPrices>(url, { signal })\n .then(({ data }) => {\n return data;\n })\n .finally(() => {\n console.timeEnd(`fetching coingecko historical for ${address}`);\n });\n }\n\n /* eslint-disable @typescript-eslint/no-unused-vars */\n async find(address: string): Promise<Price | undefined> {\n throw `Historic price requires point-in-time timestamp, please use findBy(address, timestamp)`;\n }\n\n async findBy(\n inputAddress: string,\n timestamp: number\n ): Promise<Price | undefined> {\n const address = tokenAddressForPricing(inputAddress, this.chainId);\n const response = await this.fetch(address, timestamp);\n\n return {\n usd: `${response.prices[0][1]}`,\n };\n }\n\n private platform(chainId: number): string {\n switch (chainId) {\n case 1:\n case 5:\n case 42:\n case 31337:\n case 248:\n case 9372:\n case 16116:\n case 17117:\n return 'ethereum';\n case 137:\n return 'polygon-pos';\n case 42161:\n return 'arbitrum-one';\n case 100:\n return 'xdai';\n }\n\n return '2';\n }\n\n private urlRange(address: string, timestamp: number): string {\n const range: { from: number; to: number } = {\n from: timestamp - HOUR,\n to: timestamp + HOUR,\n };\n return `${this.urlBase.replace('%TOKEN_ADDRESS%', address)}&from=${\n range.from\n }&to=${range.to}`;\n }\n}\n","/* eslint-disable @typescript-eslint/no-empty-function */\nimport { Price, Findable, TokenPrices, Network } from '@/types';\nimport axios from 'axios';\nimport { Debouncer, tokenAddressForPricing } from '@/lib/utils';\n\ninterface SubgraphPricesResponse {\n data: {\n tokens: [\n {\n address: string;\n latestUSDPrice?: string;\n }\n ];\n };\n}\n\nexport class SubgraphPriceRepository implements Findable<Price> {\n prices: { [key: string]: Promise<Price> } = {};\n debouncer: Debouncer<TokenPrices, string>;\n\n constructor(private subgraphUrl: string, private chainId: Network = 1) {\n this.debouncer = new Debouncer<TokenPrices, string>(\n this.fetch.bind(this),\n 200\n );\n }\n\n private async fetch(\n addresses: string[],\n { signal }: { signal?: AbortSignal } = {}\n ): Promise<TokenPrices> {\n console.time(`fetching subgraph prices for ${addresses.length} tokens`);\n return axios\n .post<SubgraphPricesResponse>(\n this.subgraphUrl,\n {\n variables: { addresses },\n query: `query($addresses: [String!]) {\n tokens(\n where: {\n id_in: $addresses\n }\n ) {\n address\n latestUSDPrice\n }\n }`,\n },\n { signal }\n )\n .then((response) => response.data.data)\n .then(({ tokens }) =>\n Object.fromEntries(\n tokens.map((token) => [\n token.address,\n { usd: token.latestUSDPrice || undefined },\n ])\n )\n )\n .finally(() => {\n console.timeEnd(\n `fetching subgraph prices for ${addresses.length} tokens`\n );\n });\n }\n\n async find(inputAddress: string): Promise<Price | undefined> {\n const address = tokenAddressForPricing(inputAddress, this.chainId);\n if (!this.prices[address]) {\n this.prices[address] = this.debouncer\n .fetch(address)\n .then((prices) => prices[address]);\n }\n\n return this.prices[address];\n }\n\n async findBy(attribute: string, value: string): Promise<Price | undefined> {\n if (attribute != 'address') {\n return undefined;\n }\n\n return this.find(value);\n }\n}\n","import type { Findable, Price } from '@/types';\nimport { IAaveRates } from './aave-rates';\n\nexport class TokenPriceProvider implements Findable<Price> {\n constructor(\n private coingeckoRepository: Findable<Price>,\n private subgraphRepository: Findable<Price>,\n private aaveRates: IAaveRates\n ) {}\n\n async find(address: string): Promise<Price | undefined> {\n // let price;\n // try {\n // try {\n // price = await this.coingeckoRepository.find(address);\n // if (!price?.usd) {\n // throw new Error(`Price not found:${address}`);\n // }\n // } catch (err) {\n // console.error(`Coingecko API error: ${err}`);\n // price = await this.subgraphRepository.find(address);\n // }\n // } catch (err) {\n // console.error(err);\n // }\n\n // Hung\n let price;\n try {\n try {\n price = await this.coingeckoRepository.find(address);\n if (!price?.usd) {\n throw new Error(`Price not found:${address}`);\n }\n } catch (err) {\n console.error(`Coingecko API error: ${address} ${err}`);\n price = await this.subgraphRepository.find(address);\n }\n } catch (err) {\n console.error(err);\n price = {\n eth: '0',\n usd: '0.1',\n };\n }\n return price;\n\n // const rate = (await this.aaveRates.getRate(address)) || 1;\n // if (price && price.usd) {\n // return {\n // ...price,\n // usd: (parseFloat(price.usd) * rate).toString(),\n // };\n // } else {\n // return price;\n // }\n }\n\n async findBy(attribute: string, value: string): Promise<Price | undefined> {\n if (attribute === 'address') {\n return this.find(value);\n }\n throw `Token price search by ${attribute} not implemented`;\n }\n}\n","import type { Findable, Price } from '@/types';\nimport { IAaveRates } from './aave-rates';\n\nexport class HistoricalPriceProvider implements Findable<Price> {\n constructor(\n private coingeckoRepository: Findable<Price>,\n private aaveRates: IAaveRates\n ) {}\n\n /**\n * get the historical price at time of call\n *\n * @param address the token address\n */\n async find(address: string): Promise<Price | undefined> {\n return this.findBy(address, Math.floor(Date.now() / 1000));\n }\n\n /**\n * get the historical price at the given timestamp.\n *\n * @param address the token address\n * @param timestamp the UNIX timestamp\n * @private\n */\n async findBy(address: string, timestamp: number): Promise<Price | undefined> {\n const price = await this.coingeckoRepository.findBy(address, timestamp);\n const rate = (await this.aaveRates.getRate(address)) || 1;\n if (price && price.usd) {\n return {\n ...price,\n usd: (parseFloat(price.usd) * rate).toString(),\n };\n } else {\n return price;\n }\n }\n}\n","import { Interface } from '@ethersproject/abi';\nimport { Contract } from '@ethersproject/contracts';\nimport { Provider } from '@ethersproject/providers';\nimport { formatUnits } from '@ethersproject/units';\nimport { Multicall } from '@/modules/contracts/implementations/multicall';\nimport { yieldTokens } from '../token-yields/tokens/aave';\nimport { Network } from '@/types';\n\nconst wrappedATokenInterface = new Interface([\n 'function rate() view returns (uint256)',\n]);\n\nexport interface IAaveRates {\n getRate: (address: string) => Promise<number>;\n}\n\nexport class AaveRates implements IAaveRates {\n multicall: Contract;\n rates?: Promise<{ [wrappedATokenAddress: string]: number }>;\n\n constructor(\n multicallAddress: string,\n provider: Provider,\n private network: Network\n ) {\n this.multicall = Multicall(multicallAddress, provider);\n }\n\n private async fetch(\n network: Network.MAINNET | Network.POLYGON\n ): Promise<{ [wrappedATokenAddress: string]: number }> {\n console.time('Fetching aave rates');\n const addresses = Object.values(yieldTokens[network]);\n const payload = addresses.map((wrappedATokenAddress) => [\n wrappedATokenAddress,\n wrappedATokenInterface.encodeFunctionData('rate', []),\n ]);\n const [, res] = await this.multicall.aggregate(payload);\n\n const rates = addresses.reduce((p: { [key: string]: number }, a, i) => {\n p[a] ||= res[i] == '0x' ? 0 : parseFloat(formatUnits(res[i], 27));\n return p;\n }, {});\n console.timeEnd('Fetching aave rates');\n\n return rates;\n }\n\n async getRate(wrappedAToken: string): Promise<number> {\n if (this.network != Network.MAINNET && this.network != Network.POLYGON) {\n return 1;\n }\n if (!Object.values(yieldTokens[this.network]).includes(wrappedAToken)) {\n return 1;\n }\n if (!this.rates) {\n this.rates = this.fetch(this.network);\n }\n\n return (await this.rates)[wrappedAToken];\n }\n}\n","import { Interface } from '@ethersproject/abi';\nimport { Provider } from '@ethersproject/providers';\nimport { Contract } from '@ethersproject/contracts';\nimport { getAddress } from '@ethersproject/address';\nimport { formatUnits } from '@ethersproject/units';\nimport { Multicall } from '@/modules/contracts/implementations/multicall';\n\nexport interface FeeDistributorData {\n balAmount: number;\n bbAUsdAmount: number;\n veBalSupply: number;\n bbAUsdPrice: number;\n balAddress: string;\n}\n\nexport interface BaseFeeDistributor {\n multicallData: (ts: number) => Promise<FeeDistributorData>;\n}\n\nconst feeDistributorInterface = new Interface([\n 'function getTokensDistributedInWeek(address token, uint timestamp) view returns (uint)',\n]);\n\nconst veBalInterface = new Interface([\n 'function totalSupply() view returns (uint)',\n]);\n\nconst bbAUsdInterface = new Interface([\n 'function getRate() view returns (uint)',\n]);\n\nexport class FeeDistributorRepository implements BaseFeeDistributor {\n multicall: Contract;\n data?: FeeDistributorData;\n\n constructor(\n multicallAddress: string,\n private feeDistributorAddress: string,\n private balAddress: string,\n private veBalAddress: string,\n private bbAUsdAddress: string,\n provider: Provider\n ) {\n this.multicall = Multicall(multicallAddress, provider);\n }\n\n async fetch(timestamp: number): Promise<FeeDistributorData> {\n const previousWeek = this.getPreviousWeek(timestamp);\n const payload = [\n [\n this.feeDistributorAddress,\n feeDistributorInterface.encodeFunctionData(\n 'getTokensDistributedInWeek',\n [getAddress(this.balAddress), previousWeek]\n ),\n ],\n [\n this.feeDistributorAddress,\n feeDistributorInterface.encodeFunctionData(\n 'getTokensDistributedInWeek',\n [getAddress(this.bbAUsdAddress), previousWeek]\n ),\n ],\n [this.veBalAddress, veBalInterface.encodeFunctionData('totalSupply', [])],\n [this.bbAUsdAddress, bbAUsdInterface.encodeFunctionData('getRate', [])],\n ];\n const [, res] = await this.multicall.aggregate(payload);\n\n const data = {\n balAmount: parseFloat(formatUnits(res[0], 18)),\n bbAUsdAmount: parseFloat(formatUnits(res[1], 18)),\n veBalSupply: parseFloat(formatUnits(res[2], 18)),\n bbAUsdPrice: parseFloat(formatUnits(res[3], 18)),\n balAddress: this.balAddress,\n };\n\n return data;\n }\n\n async multicallData(timestamp: number): Promise<FeeDistributorData> {\n if (!this.data) {\n this.data = await this.fetch(timestamp);\n }\n\n return this.data;\n }\n\n getPreviousWeek(fromTimestamp: number): number {\n const weeksToGoBack = 1;\n const midnight = new Date(fromTimestamp);\n midnight.setUTCHours(0);\n midnight.setUTCMinutes(0);\n midnight.setUTCSeconds(0);\n midnight.setUTCMilliseconds(0);\n\n let daysSinceThursday = midnight.getUTCDay() - 4;\n if (daysSinceThursday < 0) daysSinceThursday += 7;\n\n daysSinceThursday = daysSinceThursday + weeksToGoBack * 7;\n\n return Math.floor(midnight.getTime() / 1000) - daysSinceThursday * 86400;\n }\n}\n","import { Interface } from '@ethersproject/abi';\nimport { Provider } from '@ethersproject/providers';\nimport { Contract } from '@ethersproject/contracts';\nimport { formatUnits } from '@ethersproject/units';\nimport { Findable } from '../types';\n\nconst vaultInterface = new Interface([\n 'function getProtocolFeesCollector() view returns (address)',\n]);\n\nconst protocolFeesCollectorInterface = new Interface([\n 'function getSwapFeePercentage() view returns (uint)',\n]);\n\n// Using singleton here, so subsequent calls will return the same promise\nlet swapFeePercentagePromise: Promise<number>;\n\nexport class FeeCollectorRepository implements Findable<number> {\n vault: Contract;\n swapFeePercentage?: number;\n\n constructor(vaultAddress: string, private provider: Provider) {\n this.vault = new Contract(vaultAddress, vaultInterface, this.provider);\n }\n\n async fetch(): Promise<number> {\n const address = (await this.vault.getProtocolFeesCollector()) as string;\n\n const collector = new Contract(\n address,\n protocolFeesCollectorInterface,\n this.provider\n );\n const fees = (await collector.getSwapFeePercentage()) as string;\n\n return parseFloat(formatUnits(fees, 18));\n }\n\n async find(): Promise<number> {\n if (!swapFeePercentagePromise) {\n swapFeePercentagePromise = this.fetch();\n }\n this.swapFeePercentage = await swapFeePercentagePromise;\n\n return this.swapFeePercentage;\n }\n\n async findBy(): Promise<number> {\n return this.find();\n }\n}\n","// 0x97207B095e4D5C9a6e4cfbfcd2C3358E03B90c4A\n\nimport { Interface } from '@ethersproject/abi';\nimport { Provider } from '@ethersproject/providers';\nimport { Contract } from '@ethersproject/contracts';\nimport { formatUnits } from '@ethersproject/units';\nimport { Multicall } from '@/modules/contracts/implementations/multicall';\n\nconst iProtocolFeePercentagesProvider = new Interface([\n 'function getSwapFeePercentage() view returns (uint)',\n]);\n\nexport interface ProtocolFees {\n swapFee: number;\n yieldFee: number;\n}\n\n// Using singleton here, so subsequent calls will return the same promise\nlet feesPromise: Promise<ProtocolFees>;\n\nexport class ProtocolFeesProvider {\n multicall: Contract;\n protocolFees?: ProtocolFees;\n\n constructor(\n multicallAddress: string,\n private protocolFeePercentagesProviderAddress: string,\n provider: Provider\n ) {\n this.multicall = Multicall(multicallAddress, provider);\n }\n\n private async fetch(): Promise<ProtocolFees> {\n const payload = [\n [\n this.protocolFeePercentagesProviderAddress,\n iProtocolFeePercentagesProvider.encodeFunctionData(\n 'getFeeTypePercentage',\n [0]\n ),\n ],\n [\n this.protocolFeePercentagesProviderAddress,\n iProtocolFeePercentagesProvider.encodeFunctionData(\n 'getFeeTypePercentage',\n [2]\n ),\n ],\n ];\n const [, res] = await this.multicall.aggregate(payload);\n\n const fees = {\n swapFee: parseFloat(formatUnits(res[0], 18)),\n yieldFee: parseFloat(formatUnits(res[2], 18)),\n };\n\n return fees;\n }\n\n async getFees(): Promise<ProtocolFees> {\n if (!feesPromise) {\n feesPromise = this.fetch();\n }\n this.protocolFees = await feesPromise;\n\n return this.protocolFees;\n }\n}\n","import { AprFetcher } from '../repository';\nimport axios from 'axios';\n\nexport const yieldTokens = {\n stETH: '0xae7ab96520de3a18e5e111b5eaab095312d7fe84',\n wstETH: '0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0',\n arbitrumStEth: '0x5979d7b546e38e414f7e9822514be443a4800529',\n};\n\ninterface LidoAPIResponse {\n data: {\n smaApr: string;\n };\n}\n\n/**\n * Lido APR fetching\n *\n * @returns lido APR for stETH\n */\nexport const lido: AprFetcher = async () => {\n let apr = 0;\n\n try {\n const response = await axios.get(\n 'https://lido-aprs-proxy.balancer.workers.dev/?network=1'\n );\n const { data: aprs } = response.data as LidoAPIResponse;\n\n apr = Math.round(parseFloat(aprs.smaApr) * 100);\n } catch (error) {\n console.error('Failed to fetch stETH APR:', error);\n }\n\n return {\n [yieldTokens.stETH]: apr,\n [yieldTokens.wstETH]: apr,\n [yieldTokens.arbitrumStEth]: apr,\n };\n};\n","import { AprFetcher } from '../repository';\nimport axios from 'axios';\n\nexport const yieldTokens = {\n rETH: '0xae78736cd615f374d3085123a210448e74fc6393',\n};\n\ninterface RocketPoolAPIResponse {\n yearlyAPR: string;\n}\n\n/**\n * APR fetching\n *\n * @returns APR in bsp\n */\nexport const rocketpool: AprFetcher = async () => {\n let apr = 0;\n\n try {\n const response = await axios.get<RocketPoolAPIResponse>(\n 'https://api.rocketpool.net/api/apr'\n );\n const { yearlyAPR } = response.data;\n\n apr = Math.round(parseFloat(yearlyAPR) * 100);\n } catch (error) {\n console.error('Failed to fetch APR:', error);\n }\n\n return {\n [yieldTokens.rETH]: apr,\n };\n};\n","import { AprFetcher } from '../repository';\nimport axios from 'axios';\n\nexport const yieldTokens = {\n stMATIC: '0x3a58a54c066fdc0f2d55fc9c89f0415c92ebf3c4',\n};\n\ninterface LidoAPIResponse {\n price: string;\n apr: string;\n}\n\n/**\n * Lido APR fetching\n *\n * @returns lido APR for stMATIC\n */\nexport const lidoPolygon: AprFetcher = async () => {\n let returnApr = 0;\n\n try {\n const response = await axios.get(\n 'https://lido-aprs-proxy.balancer.workers.dev/?network=137'\n );\n const { apr } = response.data as LidoAPIResponse;\n\n returnApr = Math.round(parseFloat(apr) * 100);\n } catch (error) {\n console.error('Failed to fetch stMATIC APR:', error);\n }\n\n return {\n [yieldTokens.stMATIC]: returnApr,\n };\n};\n","import { AprFetcher } from '../repository';\nimport axios from 'axios';\n\nexport const yieldTokens = {\n usdcUSDplus: '0x1aafc31091d93c3ff003cff5d2d8f7ba2e728425',\n usdcUSDplus2: '0x6933ec1ca55c06a894107860c92acdfd2dd8512f',\n};\n\n/**\n * Overnight token APR fetching\n *\n * @returns cached APR for USD+\n */\nexport const overnight: AprFetcher = async () => {\n let bsp = 0;\n try {\n const { data: rate } = await axios.get(\n 'https://app.overnight.fi/api/balancer/week/apr'\n );\n bsp = Math.round((parseFloat(rate) * 10000) / 100);\n } catch (error) {\n console.error('Failed to fetch USD+ APR:', error);\n }\n\n return Object.fromEntries(\n Object.values(yieldTokens).map((address) => [address, bsp])\n );\n};\n","import { AprFetcher } from '../repository';\nimport axios from 'axios';\n\nexport const yieldTokens = {\n sfrxETH: '0xac3e018457b222d93114458476f3e3416abbe38f',\n};\n\ninterface FraxAPIResponse {\n sfrxethApr: string;\n}\n\n/**\n * APR fetching\n *\n * @returns APR in bsp\n */\nexport const sfrxETH: AprFetcher = async () => {\n let apr = 0;\n\n try {\n const response = await axios.get<FraxAPIResponse>(\n 'https://api.frax.finance/v2/frxeth/summary/latest'\n );\n const { sfrxethApr } = response.data;\n\n apr = Math.round(parseFloat(sfrxethApr) * 100);\n } catch (error) {\n console.error('Failed to fetch APR:', error);\n }\n\n return {\n [yieldTokens.sfrxETH]: apr,\n };\n};\n","import { AprFetcher } from '../repository';\nimport axios from 'axios';\n\nexport const yieldTokens = {\n maticX: '0xfa68fb4628dff1028cfec22b4162fccd0d45efb6',\n};\n\ninterface StaderLabsAPIResponse {\n value: string;\n}\n\n/**\n * APR fetching\n *\n * @returns APR in bsp\n */\nexport const maticX: AprFetcher = async () => {\n let apr = 0;\n\n try {\n const response = await axios.get<StaderLabsAPIResponse>(\n 'https://generic-apr-proxy.balancer.workers.dev/?provider=stader'\n );\n const { value } = response.data;\n\n apr = Math.round(parseFloat(value) * 100);\n } catch (error) {\n console.error('Failed to fetch APR:', error);\n }\n\n return {\n [yieldTokens.maticX]: apr,\n };\n};\n","import { BigNumber } from '@ethersproject/bignumber';\nimport { formatEther } from '@ethersproject/units';\nimport { AprFetcher } from '../repository';\nimport axios from 'axios';\n\nexport const yieldTokens = {\n qETH: '0x93ef1ea305d11a9b2a3ebb9bb4fcc34695292e7d',\n};\n\ninterface TranchessAPIResponse {\n weeklyAveragePnlPercentage: string;\n}\n\n/**\n * APR fetching\n *\n * @returns tokens yields\n */\nexport const tranchess: AprFetcher = async () => {\n let apr = 0;\n\n try {\n const response = await axios.get(\n 'https://generic-apr-proxy.balancer.workers.dev/?provider=tranchess'\n );\n\n const [{ weeklyAveragePnlPercentage }] =\n response.data as TranchessAPIResponse[];\n\n apr = Math.round(\n parseFloat(\n formatEther(\n //The key weeklyAveragePnlPercentage is the daily yield of qETH in 18 decimals, timing 365 should give you the APR.\n BigNumber.from(weeklyAveragePnlPercentage).mul(365).mul(10000)\n )\n )\n );\n } catch (error) {\n console.error('Failed to fetch qETH APR:', error);\n }\n\n return {\n [yieldTokens.qETH]: apr,\n };\n};\n","import { AprFetcher } from '../repository';\nimport axios from 'axios';\n\nexport const yieldTokens = {\n USDR: '0xaf0d9d65fc54de245cda37af3d18cbec860a4d4b',\n};\n\ninterface USDRAPIResponse {\n usdr: string;\n}\n\n/**\n * APR fetching\n *\n * @returns tokens yields\n */\nexport const usdr: AprFetcher = async () => {\n let apr = 0;\n\n try {\n const response = await axios.get(\n 'https://generic-apr-proxy.balancer.workers.dev/?provider=usdr'\n );\n\n const { usdr } = response.data as USDRAPIResponse;\n\n apr = Math.round(parseFloat(usdr) * 100);\n } catch (error) {\n console.error('Failed to fetch USDR APR:', error);\n }\n\n return {\n [yieldTokens.USDR]: apr,\n };\n};\n","import { AprFetcher } from '../repository';\nimport axios from 'axios';\n\nexport const yieldTokens = {\n rETH: '0x9559aaa82d9649c7a7b220e7c461d2e74c9a3593',\n};\n\ninterface StafiAPIResponse {\n data: {\n stakeApr: string;\n };\n}\n\n/**\n * APR fetching\n *\n * @returns APR in bsp\n */\nexport const stafi: AprFetcher = async () => {\n let apr = 0;\n\n try {\n const response = await axios.get<StafiAPIResponse>(\n 'https://drop-api.stafi.io/reth/v1/poolData/'\n );\n\n const { stakeApr } = response.data.data;\n\n apr = Math.round(parseFloat(stakeApr) * 100);\n } catch (error) {\n console.error('Failed to fetch APR:', error);\n }\n\n return {\n [yieldTokens.rETH]: apr,\n };\n};\n","import { AprFetcher } from '../repository';\nimport { JsonRpcProvider } from '@ethersproject/providers';\nimport { Contract } from '@ethersproject/contracts';\n\nconst poolAddress = '0x5954aB967Bc958940b7EB73ee84797Dc8a2AFbb9';\nconst poolAbi = [\n {\n inputs: [],\n name: 'getPoolsUI',\n outputs: [\n {\n components: [\n { internalType: 'uint256', name: 'poolId', type: 'uint256' },\n { internalType: 'uint256', name: 'stakedAmount', type: 'uint256' },\n {\n components: [\n {\n internalType: 'uint48',\n name: 'startTimestampHour',\n type: 'uint48',\n },\n {\n internalType: 'uint48',\n name: 'endTimestampHour',\n type: 'uint48',\n },\n {\n internalType: 'uint96',\n name: 'rewardsPerHour',\n type: 'uint96',\n },\n {\n internalType: 'uint96',\n name: 'capPerPosition',\n type: 'uint96',\n },\n ],\n internalType: 'struct ApeCoinStaking.TimeRange',\n name: 'currentTimeRange',\n type: 'tuple',\n },\n ],\n internalType: 'struct ApeCoinStaking.PoolUI',\n name: '',\n type: 'tuple',\n },\n {\n components: [\n { internalType: 'uint256', name: 'poolId', type: 'uint256' },\n { internalType: 'uint256', name: 'stakedAmount', type: 'uint256' },\n {\n components: [\n {\n internalType: 'uint48',\n name: 'startTimestampHour',\n type: 'uint48',\n },\n {\n internalType: 'uint48',\n name: 'endTimestampHour',\n type: 'uint48',\n },\n {\n internalType: 'uint96',\n name: 'rewardsPerHour',\n type: 'uint96',\n },\n {\n internalType: 'uint96',\n name: 'capPerPosition',\n type: 'uint96',\n },\n ],\n internalType: 'struct ApeCoinStaking.TimeRange',\n name: 'currentTimeRange',\n type: 'tuple',\n },\n ],\n internalType: 'struct ApeCoinStaking.PoolUI',\n name: '',\n type: 'tuple',\n },\n {\n components: [\n { internalType: 'uint256', name: 'poolId', type: 'uint256' },\n { internalType: 'uint256', name: 'stakedAmount', type: 'uint256' },\n {\n components: [\n {\n internalType: 'uint48',\n name: 'startTimestampHour',\n type: 'uint48',\n },\n {\n internalType: 'uint48',\n name: 'endTimestampHour',\n type: 'uint48',\n },\n {\n internalType: 'uint96',\n name: 'rewardsPerHour',\n type: 'uint96',\n },\n {\n internalType: 'uint96',\n name: 'capPerPosition',\n type: 'uint96',\n },\n ],\n internalType: 'struct ApeCoinStaking.TimeRange',\n name: 'currentTimeRange',\n type: 'tuple',\n },\n ],\n internalType: 'struct ApeCoinStaking.PoolUI',\n name: '',\n type: 'tuple',\n },\n {\n components: [\n { internalType: 'uint256', name: 'poolId', type: 'uint256' },\n { internalType: 'uint256', name: 'stakedAmount', type: 'uint256' },\n {\n components: [\n {\n internalType: 'uint48',\n name: 'startTimestampHour',\n type: 'uint48',\n },\n {\n internalType: 'uint48',\n name: 'endTimestampHour',\n type: 'uint48',\n },\n {\n internalType: 'uint96',\n name: 'rewardsPerHour',\n type: 'uint96',\n },\n {\n internalType: 'uint96',\n name: 'capPerPosition',\n type: 'uint96',\n },\n ],\n internalType: 'struct ApeCoinStaking.TimeRange',\n name: 'currentTimeRange',\n type: 'tuple',\n },\n ],\n internalType: 'struct ApeCoinStaking.PoolUI',\n name: '',\n type: 'tuple',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n];\n\nconst provider = new JsonRpcProvider('https://rpc.ankr.com/eth', 1);\nconst stakingContract = new Contract(poolAddress, poolAbi, provider);\nconst contractFetcher = {\n getPoolsUI: stakingContract.getPoolsUI,\n};\n\nexport const yieldTokens = {\n sApe: '0x7966c5bae631294d7cffcea5430b78c2f76db6fa',\n};\n\n/**\n * Staked ApeCoin APR fetching\n * @hidden\n *\n * @param contract - can be ignored, used for testing\n *\n * @returns apr in bsp\n */\nexport const tessera: AprFetcher = async (\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _ = 1,\n contract = contractFetcher\n) => {\n let apr = 0;\n\n try {\n const poolsUI = await contract.getPoolsUI();\n const apePool = poolsUI[0];\n const staked = apePool.stakedAmount;\n const reward = apePool.currentTimeRange.rewardsPerHour.mul(24 * 365);\n\n apr = Number(reward.mul(1e4).div(staked));\n } catch (error) {\n console.error('Failed to fetch Tessera Ape Coin APR:', error);\n }\n\n return {\n [yieldTokens.sApe]: apr,\n };\n};\n","import { AprFetcher } from '../repository';\nimport { Network } from '@/types';\nimport axios from 'axios';\nimport { formatUnits } from '@ethersproject/units';\nimport { BigNumber } from '@ethersproject/bignumber';\n\nexport const yieldTokens = {\n eUSDC: '0xeb91861f8a4e1c12333f42dce8fb0ecdc28da716',\n eDAI: '0xe025e3ca2be02316033184551d4d3aa22024d9dc',\n eUSDT: '0x4d19f33948b99800b6113ff3e83bec9b537c85d2',\n eFRAX: '0x5484451a88a35cd0878a1be177435ca8a0e4054e',\n};\n\nconst query = `\n query getAssetsAPY($eTokenAddress_in: [String!]) {\n assets(\n where: {\n eTokenAddress_in: $eTokenAddress_in\n }\n ) {\n eTokenAddress\n supplyAPY\n }\n }\n`;\n\ninterface EulerResponse {\n data: {\n assets: [\n {\n eTokenAddress: string;\n supplyAPY: string;\n }\n ];\n };\n}\n\nconst endpoint = {\n [Network.MAINNET]:\n 'https://api.thegraph.com/subgraphs/name/euler-xyz/euler-mainnet',\n};\n/**\n * Euler APR fetching\n *\n * @returns Euler APR for USDC, USDT and DAI\n */\nexport const euler: AprFetcher = async () => {\n const network = Network.MAINNET;\n const graphqlQuery = {\n operationName: 'getAssetsAPY',\n query,\n variables: {\n eTokenAddress_in: Object.values(yieldTokens),\n },\n };\n const response = await axios.post(endpoint[network], graphqlQuery);\n const {\n data: { assets },\n } = response.data as EulerResponse;\n const aprs = {\n eUSDT: 0,\n eDAI: 0,\n eUSDC: 0,\n eFRAX: 0,\n };\n assets.forEach(({ eTokenAddress, supplyAPY }) => {\n const key: 'eUSDT' | 'eDAI' | 'eUSDC' | 'eFRAX' = Object.entries(\n yieldTokens\n ).filter(([, value]) => {\n return value.toLocaleLowerCase() === eTokenAddress.toLocaleLowerCase();\n })[0][0] as 'eUSDT' | 'eDAI' | 'eUSDC' | 'eFRAX';\n aprs[key] = Math.round(\n // supplyAPY is 1e27 = 100% and the apy must be returned with 1e4 = 100% (100% is 10000 in this case)\n parseFloat(formatUnits(BigNumber.from(supplyAPY), 27)) * 10000\n );\n });\n return {\n [yieldTokens.eUSDT]: aprs.eUSDT,\n [yieldTokens.eDAI]: aprs.eDAI,\n [yieldTokens.eUSDC]: aprs.eUSDC,\n [yieldTokens.eFRAX]: aprs.eFRAX,\n };\n};\n","import { lido, yieldTokens as lidoTokens } from './tokens/lido';\nimport {\n rocketpool,\n yieldTokens as rocketpoolTokens,\n} from './tokens/rocketpool';\nimport {\n lidoPolygon,\n yieldTokens as lidoPolygonTokens,\n} from './tokens/lido-polygon';\nimport { aave, allYieldTokens as aaveTokens } from './tokens/aave';\nimport { overnight, yieldTokens as overnightTokens } from './tokens/overnight';\nimport { sfrxETH, yieldTokens as fraxTokens } from './tokens/sfrxeth';\nimport { maticX, yieldTokens as staderLabsTokens } from './tokens/maticx';\nimport { tranchess, yieldTokens as tranchessTokens } from './tokens/tranchess';\nimport { usdr, yieldTokens as usdrTokens } from './tokens/usdr';\nimport { stafi, yieldTokens as stafiTokens } from './tokens/stafi';\nimport { tessera, yieldTokens as tesseraTokens } from './tokens/tessera';\nimport { euler, yieldTokens as eulerTokens } from './tokens/euler';\nimport { Network, Findable } from '@/types';\n\n/**\n * Common interface for fetching APR from external sources\n * @interal\n *\n * @param network is optional, used when same source, eg: aave has multiple tokens and all of them can be fetched in one call.\n * @param other is optional, used for passing mocked data for testing.\n */\nexport interface AprFetcher {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (network?: Network, other?: any): Promise<{ [address: string]: number }>;\n}\n\nconst yieldSourceMap: { [address: string]: AprFetcher } = Object.fromEntries([\n ...Object.values(lidoTokens).map((k) => [k, lido]),\n ...Object.values(lidoPolygonTokens).map((k) => [k, lidoPolygon]),\n ...Object.values(aaveTokens).map((k) => [k, aave]),\n ...Object.values(overnightTokens).map((k) => [k, overnight]),\n ...Object.values(rocketpoolTokens).map((k) => [k, rocketpool]),\n ...Object.values(fraxTokens).map((k) => [k, sfrxETH]),\n ...Object.values(staderLabsTokens).map((k) => [k, maticX]),\n ...Object.values(tranchessTokens).map((k) => [k, tranchess]),\n ...Object.values(usdrTokens).map((k) => [k, usdr]),\n ...Object.values(stafiTokens).map((k) => [k, stafi]),\n ...Object.values(tesseraTokens).map((k) => [k, tessera]),\n ...Object.values(eulerTokens).map((k) => [k, euler]),\n]);\n\nexport class TokenYieldsRepository implements Findable<number> {\n private yields: { [address: string]: number } = {};\n\n constructor(private network: Network, private sources = yieldSourceMap) {}\n\n async fetch(address: string): Promise<void> {\n const tokenYields = await this.sources[address](this.network);\n this.yields = {\n ...this.yields,\n ...tokenYields,\n };\n }\n\n async find(address: string): Promise<number | undefined> {\n const lowercase = address.toLocaleLowerCase();\n if (\n Object.keys(this.sources).includes(lowercase) &&\n !Object.keys(this.yields).includes(lowercase)\n ) {\n await this.fetch(lowercase);\n }\n\n return this.yields[lowercase];\n }\n\n async findBy(attribute: string, value: string): Promise<number | undefined> {\n if (attribute != 'address') {\n return undefined;\n }\n\n return this.find(value);\n }\n}\n","import { Findable } from '../types';\nimport axios from 'axios';\n\nconst query = (timestamp: string) => `{\n blocks(first: 1, orderBy: timestamp, orderDirection: asc, where: { timestamp_gt: ${timestamp} }) {\n number\n }\n}`;\n\ninterface BlockNumberResponse {\n data: {\n blocks: [\n {\n number: string;\n }\n ];\n };\n}\n\nconst fetchBlockByTime = async (\n endpoint: string,\n timestamp: string\n): Promise<number> => {\n const payload = {\n query: query(timestamp),\n };\n\n const response = await axios.post(endpoint, payload);\n\n const {\n data: { blocks },\n } = response.data as BlockNumberResponse;\n\n return parseInt(blocks[0].number);\n};\n\nexport class BlockNumberRepository implements Findable<number> {\n blocks: { [ts: string]: Promise<number> } = {};\n\n constructor(private endpoint: string) {}\n\n async find(from: string): Promise<number | undefined> {\n if (from == 'dayAgo') {\n const dayAgo = `${Math.floor(Date.now() / 1000) - 86400}`;\n if (!this.blocks[dayAgo]) {\n this.blocks = {\n ...this.blocks,\n [dayAgo]: fetchBlockByTime(this.endpoint, dayAgo),\n };\n }\n return this.blocks[dayAgo];\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async findBy(attribute = '', value = ''): Promise<number | undefined> {\n return;\n }\n}\n","import { cloneDeep } from 'lodash';\nimport { Interface } from '@ethersproject/abi';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { AddressZero, MaxInt256, MaxUint256 } from '@ethersproject/constants';\nimport { SubgraphPoolBase, SwapInfo, SwapTypes, SwapV2 } from '@defiverse/sor';\nimport {\n Relayer,\n OutputReference,\n EncodeJoinPoolInput,\n EncodeBatchSwapInput,\n ExitPoolData,\n} from '@/modules/relayer/relayer.module';\nimport { getPoolAddress } from '@/pool-utils';\nimport { ExitPoolRequest } from '@/types';\nimport { FundManagement, SwapType } from './types';\nimport { WeightedPoolEncoder } from '@/pool-weighted';\nimport { AssetHelpers } from '@/lib/utils';\nimport { subSlippage } from '@/lib/utils/slippageHelper';\nimport { BalancerError, BalancerErrorCode } from '@/balancerErrors';\n\nimport balancerRelayerAbi from '@/lib/abi/BalancerRelayer.json';\n\nexport enum ActionStep {\n Direct,\n TokenIn,\n TokenOut,\n Middle,\n}\n\nexport enum ActionType {\n Swap,\n BatchSwap,\n Join,\n Exit,\n}\ninterface BaseAction {\n type: ActionType;\n minOut: string;\n assets: string[];\n hasTokenIn: boolean;\n hasTokenOut: boolean;\n}\n\nexport interface JoinAction extends BaseAction {\n type: ActionType.Join;\n poolId: string;\n tokenIn: string;\n bpt: string;\n opRef: OutputReference;\n amountIn: string;\n actionStep: ActionStep;\n sender: string;\n receiver: string;\n fromInternal: boolean;\n}\n\nexport interface ExitAction extends BaseAction {\n type: ActionType.Exit;\n poolId: string;\n tokenOut: string;\n bpt: string;\n opRef: OutputReference[];\n amountIn: string;\n actionStep: ActionStep;\n sender: string;\n receiver: string;\n toInternal: boolean;\n}\n\nexport interface SwapAction extends BaseAction {\n type: ActionType.Swap;\n swap: SwapV2;\n opRef: OutputReference[];\n amountIn: string;\n fromInternal: boolean;\n toInternal: boolean;\n sender: string;\n receiver: string;\n isBptIn: boolean;\n}\n\nexport interface BatchSwapAction extends BaseAction {\n type: ActionType.BatchSwap;\n swaps: SwapV2[];\n opRef: OutputReference[];\n fromInternal: boolean;\n toInternal: boolean;\n limits: BigNumber[];\n approveTokens: string[];\n sender: string;\n receiver: string;\n}\n\nconst EMPTY_BATCHSWAP_ACTION: BatchSwapAction = {\n type: ActionType.BatchSwap,\n swaps: [],\n opRef: [],\n minOut: '0',\n assets: [],\n hasTokenIn: false,\n hasTokenOut: false,\n fromInternal: false,\n toInternal: false,\n limits: [],\n approveTokens: [],\n sender: '',\n receiver: '',\n};\n\ntype Actions = JoinAction | ExitAction | SwapAction | BatchSwapAction;\ntype OrderedActions = JoinAction | ExitAction | BatchSwapAction;\n\nconst balancerRelayerInterface = new Interface(balancerRelayerAbi);\n\nfunction getOutputRef(key: number, index: number): OutputReference {\n const keyRef = Relayer.toChainedReference(key);\n return { index: index, key: keyRef };\n}\n\nfunction isBpt(pools: SubgraphPoolBase[], token: string): boolean {\n return pools.some((p) => p.address.toLowerCase() === token.toLowerCase());\n}\n\nexport function canUseJoinExit(\n swapType: SwapTypes,\n tokenIn: string,\n tokenOut: string\n): boolean {\n if (\n swapType === SwapTypes.SwapExactOut ||\n tokenIn.toLowerCase() === AddressZero.toLowerCase() ||\n tokenOut.toLowerCase() === AddressZero.toLowerCase()\n )\n return false;\n else return true;\n}\n\n/**\n * Uses relayer to approve itself to act in behalf of the user\n * @param authorisation Encoded authorisation call.\n * @returns relayer approval call\n */\nfunction buildSetRelayerApproval(\n authorisation: string,\n relayerAddress: string\n): string {\n return Relayer.encodeSetRelayerApproval(relayerAddress, true, authorisation);\n}\n\n/**\n * Currently SOR only supports join/exit paths through Weighted pools.\n * Weighted pools should not have preminted BPT so can assume if a swap token is pool address it is a join or exit.\n * @param pools\n * @param swap\n * @param assets\n * @returns\n */\nexport function hasJoinExit(\n pools: SubgraphPoolBase[],\n swap: SwapV2,\n assets: string[]\n): boolean {\n const pool = pools.find((p) => p.id === swap.poolId);\n if (pool?.poolType !== 'Weighted') return false;\n const tokenIn = assets[swap.assetInIndex];\n const tokenOut = assets[swap.assetOutIndex];\n return [tokenIn, tokenOut].includes(pool.address);\n}\n\n/**\n * Finds if a swap returned by SOR is a join by checking if tokenOut === poolAddress\n * @param swap\n * @param assets\n * @returns\n */\nexport function isJoin(swap: SwapV2, assets: string[]): boolean {\n // token[join]bpt\n const tokenOut = assets[swap.assetOutIndex];\n const poolAddress = getPoolAddress(swap.poolId);\n return tokenOut.toLowerCase() === poolAddress.toLowerCase();\n}\n\n/**\n * Finds if a swap returned by SOR is an exit by checking if tokenIn === poolAddress\n * @param swap\n * @param assets\n * @returns\n */\nexport function isExit(swap: SwapV2, assets: string[]): boolean {\n // bpt[exit]token\n const tokenIn = assets[swap.assetInIndex];\n const poolAddress = getPoolAddress(swap.poolId);\n return tokenIn.toLowerCase() === poolAddress.toLowerCase();\n}\n\n/**\n * Find if any of the swaps are join/exits. If yes these swaps should be routed via Relayer.\n * @param pools\n * @param swaps\n * @param assets\n * @returns\n */\nexport function someJoinExit(\n pools: SubgraphPoolBase[],\n swaps: SwapV2[],\n assets: string[]\n): boolean {\n return swaps.some((swap) => {\n return hasJoinExit(pools, swap, assets);\n });\n}\n\n/**\n * If its not the final action then we need an outputReferece to chain to next action as input\n * @param actionStep\n * @param tokenOutIndex\n * @param opRefKey\n * @returns\n */\nfunction getActionOutputRef(\n actionStep: ActionStep,\n tokenOutIndex: number,\n opRefKey: number\n): [OutputReference, number] {\n let opRef: OutputReference = {} as OutputReference;\n if (actionStep === ActionStep.TokenIn || actionStep === ActionStep.Middle) {\n opRef = getOutputRef(opRefKey, tokenOutIndex);\n opRefKey++;\n }\n return [opRef, opRefKey];\n}\n\n/**\n * Use slippage to set min amount out\n * @param amountOut\n * @param slippage\n * @returns\n */\nfunction getActionMinOut(amountOut: string, slippage: string): string {\n // Currently only handle ExactIn swap. ExactOut would add slippage\n // We should apply slippage to each swaps amountOut\n return subSlippage(\n BigNumber.from(amountOut),\n BigNumber.from(slippage)\n ).toString();\n}\n\n/**\n * If its not the first action then the amount will come from the previous output ref\n * @param swap\n * @param actionType\n * @param actionStep\n * @param opRefKey\n * @returns\n */\nfunction getActionAmount(\n swap: SwapV2,\n actionType: ActionType,\n actionStep: ActionStep,\n opRefKey: number\n): string {\n let amountIn = swap.amount;\n if (\n actionStep === ActionStep.TokenOut ||\n (actionStep === ActionStep.Middle && actionType === ActionType.Join) ||\n (actionStep === ActionStep.Middle && actionType === ActionType.Exit)\n ) {\n amountIn = Relayer.toChainedReference(opRefKey - 1).toString();\n }\n return amountIn;\n}\n\n/**\n * Find if the Action is:\n * Direct: tokenIn > tokenOut\n * TokenIn: tokenIn > chain...\n * TokenOut: ...chain > tokenOut\n * Middle: ...chain > action > chain...\n * @param tokenInIndex\n * @param tokenOutIndex\n * @param tokenInIndexAction\n * @param tokenOutIndexAction\n * @returns\n */\nfunction getActionStep(\n tokenInIndex: number,\n tokenOutIndex: number,\n tokenInIndexAction: number,\n tokenOutIndexAction: number\n): ActionStep {\n let actionStep: ActionStep;\n if (\n tokenInIndexAction === tokenInIndex &&\n tokenOutIndexAction === tokenOutIndex\n ) {\n actionStep = ActionStep.Direct;\n } else if (tokenInIndexAction === tokenInIndex) {\n actionStep = ActionStep.TokenIn;\n } else if (tokenOutIndexAction === tokenOutIndex) {\n actionStep = ActionStep.TokenOut;\n } else {\n actionStep = ActionStep.Middle;\n }\n return actionStep;\n}\n\n/**\n * Find the number of actions that end with tokenOut\n * @param actions\n * @returns\n */\nexport function getNumberOfOutputActions(actions: OrderedActions[]): number {\n let outputCount = 0;\n for (const a of actions) {\n if (a.hasTokenOut) outputCount++;\n }\n return outputCount;\n}\n\n/**\n * Categorize each action into a Join, Middle or Exit.\n * @param actions\n * @returns\n */\nexport function categorizeActions(actions: Actions[]): Actions[] {\n const enterActions: Actions[] = [];\n const exitActions: Actions[] = [];\n const middleActions: Actions[] = [];\n for (const a of actions) {\n if (a.type === ActionType.Exit || a.type === ActionType.Join) {\n // joins/exits with tokenIn can always be done first\n if (a.hasTokenIn) enterActions.push(a);\n // joins/exits with tokenOut (and not tokenIn) can always be done last\n else if (a.hasTokenOut) exitActions.push(a);\n else middleActions.push(a);\n }\n // All other actions will be chained inbetween\n else middleActions.push(a);\n }\n const allActions: Actions[] = [\n ...enterActions,\n ...middleActions,\n ...exitActions,\n ];\n return allActions;\n}\n\n/**\n * This aims to minimise the number of Actions the Relayer multicall needs to call by batching sequential swaps together.\n * @param actions\n * @param assets\n * @returns\n */\nexport function batchSwapActions(\n allActions: Actions[],\n assets: string[]\n): OrderedActions[] {\n /*\n batchSwaps are a collection of swaps that can all be called in a single batchSwap\n Can batch all swaps with same source\n Any swap without tokenIn && not BPT should be coming from internal balances\n Any swap with tokenIn or BPT should be coming from external balances\n */\n const orderedActions: OrderedActions[] = [];\n let batchSwaps = cloneDeep(EMPTY_BATCHSWAP_ACTION);\n batchSwaps.assets = assets;\n batchSwaps.limits = Array(assets.length).fill(BigNumber.from('0'));\n\n let isFirstSwap = true;\n let lastSwap: SwapAction = {} as SwapAction;\n\n for (const a of allActions) {\n if (a.type === ActionType.Swap) {\n if (isFirstSwap) {\n lastSwap = a;\n isFirstSwap = false;\n }\n if (a.isBptIn) {\n // Older pools don't have pre-approval so need to add this as a step\n batchSwaps.approveTokens.push(a.assets[a.swap.assetInIndex]);\n }\n // If swap has different send/receive params than previous then it will need to be done separately\n if (\n a.fromInternal !== lastSwap.fromInternal ||\n a.toInternal !== lastSwap.toInternal ||\n a.receiver !== lastSwap.receiver ||\n a.sender !== lastSwap.sender\n ) {\n if (batchSwaps.swaps.length > 0) {\n orderedActions.push(batchSwaps);\n batchSwaps = cloneDeep(EMPTY_BATCHSWAP_ACTION);\n batchSwaps.assets = assets;\n batchSwaps.limits = Array(assets.length).fill(BigNumber.from('0'));\n }\n }\n batchSwaps.swaps.push(a.swap);\n batchSwaps.opRef.push(...a.opRef);\n batchSwaps.fromInternal = a.fromInternal;\n batchSwaps.toInternal = a.toInternal;\n batchSwaps.sender = a.sender;\n batchSwaps.receiver = a.receiver;\n if (a.hasTokenIn) {\n batchSwaps.hasTokenIn = true;\n // We need to add amount for each swap that uses tokenIn to get correct total\n batchSwaps.limits[a.swap.assetInIndex] = batchSwaps.limits[\n a.swap.assetInIndex\n ].add(a.amountIn);\n } else {\n // This will be a chained swap/input amount\n batchSwaps.limits[a.swap.assetInIndex] = MaxInt256;\n }\n if (a.hasTokenOut) {\n // We need to add amount for each swap that uses tokenOut to get correct total (should be negative)\n batchSwaps.hasTokenOut = true;\n batchSwaps.limits[a.swap.assetOutIndex] = batchSwaps.limits[\n a.swap.assetOutIndex\n ].sub(a.minOut);\n }\n lastSwap = a;\n } else {\n // Non swap action\n if (batchSwaps.swaps.length > 0) {\n orderedActions.push(batchSwaps);\n // new batchSwap collection as there is a chained join/exit inbetween\n batchSwaps = cloneDeep(EMPTY_BATCHSWAP_ACTION);\n batchSwaps.assets = assets;\n batchSwaps.limits = Array(assets.length).fill(BigNumber.from('0'));\n }\n orderedActions.push(a);\n }\n }\n if (batchSwaps.swaps.length > 0) orderedActions.push(batchSwaps);\n return orderedActions;\n}\n\n/**\n * Organise Actions into order with least amount of calls.\n * @param actions\n * @param assets\n * @returns\n */\nexport function orderActions(\n actions: Actions[],\n assets: string[]\n): OrderedActions[] {\n const categorizedActions = categorizeActions(actions);\n const orderedActions = batchSwapActions(categorizedActions, assets);\n return orderedActions;\n}\n\n/**\n * Translate each swap into an Action. An Action is a join/exit/swap with the chained output refs.\n * @param swapType\n * @param tokenIn\n * @param tokenOut\n * @param swaps\n * @param assets\n * @param slippage\n * @param pools\n * @param user\n * @param relayer\n * @returns\n */\nexport function getActions(\n tokenIn: string,\n tokenOut: string,\n swaps: SwapV2[],\n assets: string[],\n slippage: string,\n pools: SubgraphPoolBase[],\n user: string,\n relayer: string\n): Actions[] {\n const tokenInIndex = assets.findIndex(\n (t) => t.toLowerCase() === tokenIn.toLowerCase()\n );\n const tokenOutIndex = assets.findIndex(\n (t) => t.toLowerCase() === tokenOut.toLowerCase()\n );\n const actions: Actions[] = [];\n let opRefKey = 0;\n let previousAction: Actions = {} as Actions;\n for (const swap of swaps) {\n if (isJoin(swap, assets)) {\n const [joinAction, newOpRefKey] = createJoinAction(\n swap,\n tokenInIndex,\n tokenOutIndex,\n opRefKey,\n assets,\n slippage,\n user,\n relayer\n );\n opRefKey = newOpRefKey;\n actions.push(joinAction);\n previousAction = joinAction;\n continue;\n } else if (isExit(swap, assets)) {\n const [exitAction, newOpRefKey] = createExitAction(\n swap,\n tokenInIndex,\n tokenOutIndex,\n opRefKey,\n assets,\n slippage,\n user,\n relayer\n );\n opRefKey = newOpRefKey;\n actions.push(exitAction);\n previousAction = exitAction;\n continue;\n } else {\n const amount = swap.amount;\n const [swapAction, newOpRefKey] = createSwapAction(\n swap,\n tokenInIndex,\n tokenOutIndex,\n opRefKey,\n assets,\n slippage,\n pools,\n user,\n relayer\n );\n if (previousAction.type === ActionType.Swap && amount === '0') {\n /*\n If its part of a multihop swap the amount will be 0 (and should remain 0)\n The source will be same as previous swap so set previous receiver to match sender. Receiver set as is.\n */\n previousAction.receiver = previousAction.sender;\n previousAction.toInternal = previousAction.fromInternal;\n previousAction.opRef = [];\n swapAction.sender = previousAction.receiver;\n swapAction.fromInternal = previousAction.fromInternal;\n swapAction.amountIn = '0';\n swapAction.swap.amount = '0';\n }\n opRefKey = newOpRefKey;\n actions.push(swapAction);\n previousAction = swapAction;\n continue;\n }\n }\n return actions;\n}\n\n/**\n * Create a JoinAction with relevant info\n * @param swapType\n * @param swap\n * @param mainTokenInIndex\n * @param mainTokenOutIndex\n * @param opRefKey\n * @param assets\n * @param slippage\n * @returns\n */\nfunction createJoinAction(\n swap: SwapV2,\n mainTokenInIndex: number,\n mainTokenOutIndex: number,\n opRefKey: number,\n assets: string[],\n slippage: string,\n user: string,\n relayerAddress: string\n): [JoinAction, number] {\n const actionStep = getActionStep(\n mainTokenInIndex,\n mainTokenOutIndex,\n swap.assetInIndex,\n swap.assetOutIndex\n );\n // Will get actual amount if input or chain amount if part of chain\n const amountIn = getActionAmount(swap, ActionType.Join, actionStep, opRefKey);\n // This will be 0 if not a mainTokenOut action otherwise amount using slippage\n const minOut = getActionMinOut(swap.returnAmount ?? '0', slippage);\n // This will set opRef for next chained action if required\n const [opRef, newOpRefKey] = getActionOutputRef(\n actionStep,\n swap.assetOutIndex,\n opRefKey\n );\n let sender = relayerAddress;\n let fromInternal = true;\n let hasTokenIn = false;\n // If using mainTokenIn we can assume it comes from user\n if (actionStep === ActionStep.Direct || actionStep === ActionStep.TokenIn) {\n sender = user;\n fromInternal = false;\n hasTokenIn = true;\n }\n let receiver = relayerAddress;\n let hasTokenOut = false;\n // If using mainTokenOut we can assume it goes to user\n if (actionStep === ActionStep.Direct || actionStep === ActionStep.TokenOut) {\n receiver = user;\n hasTokenOut = true;\n }\n\n const joinAction: JoinAction = {\n type: ActionType.Join,\n poolId: swap.poolId,\n tokenIn: assets[swap.assetInIndex],\n bpt: assets[swap.assetOutIndex],\n opRef,\n minOut,\n amountIn,\n assets,\n actionStep,\n sender,\n receiver,\n fromInternal,\n hasTokenIn,\n hasTokenOut,\n };\n return [joinAction, newOpRefKey];\n}\n\n/**\n * Create a ExitAction with relevant info.\n * @param swapType\n * @param swap\n * @param tokenInIndex\n * @param tokenOutIndex\n * @param opRefKey\n * @param assets\n * @param slippage\n * @param user\n * @param relayerAddress\n * @returns\n */\nfunction createExitAction(\n swap: SwapV2,\n tokenInIndex: number,\n tokenOutIndex: number,\n opRefKey: number,\n assets: string[],\n slippage: string,\n user: string,\n relayerAddress: string\n): [ExitAction, number] {\n const actionStep = getActionStep(\n tokenInIndex,\n tokenOutIndex,\n swap.assetInIndex,\n swap.assetOutIndex\n );\n // Will get actual amount if input or chain amount if part of chain\n const amountIn = getActionAmount(swap, ActionType.Exit, actionStep, opRefKey);\n // This will be 0 if not a mainTokenOut action otherwise amount using slippage\n const minOut = getActionMinOut(swap.returnAmount ?? '0', slippage);\n // This will set opRef for next chained action if required\n const [opRef, newOpRefKey] = getActionOutputRef(\n actionStep,\n swap.assetOutIndex,\n opRefKey\n );\n let sender = relayerAddress;\n let hasTokenIn = false;\n if (actionStep === ActionStep.Direct || actionStep === ActionStep.TokenIn) {\n sender = user;\n hasTokenIn = true;\n }\n // Send to relayer unless this is main token out\n let hasTokenOut = false;\n let toInternalBalance = true;\n let receiver = relayerAddress;\n if (actionStep === ActionStep.Direct || actionStep === ActionStep.TokenOut) {\n receiver = user;\n toInternalBalance = false;\n hasTokenOut = true;\n }\n\n const exitAction: ExitAction = {\n type: ActionType.Exit,\n poolId: swap.poolId,\n tokenOut: assets[swap.assetOutIndex],\n bpt: assets[swap.assetInIndex],\n opRef: opRef.key ? [opRef] : [],\n minOut,\n amountIn,\n assets,\n actionStep,\n sender,\n receiver,\n toInternal: toInternalBalance,\n hasTokenIn,\n hasTokenOut,\n };\n return [exitAction, newOpRefKey];\n}\n\n/**\n * Create a SwapAction with relevant info.\n * @param swapType\n * @param swap\n * @param mainTokenInIndex\n * @param mainTokenOutIndex\n * @param opRefKey\n * @param assets\n * @param slippage\n * @param pools\n * @param user\n * @param relayer\n * @returns\n */\nfunction createSwapAction(\n swap: SwapV2,\n mainTokenInIndex: number,\n mainTokenOutIndex: number,\n opRefKey: number,\n assets: string[],\n slippage: string,\n pools: SubgraphPoolBase[],\n user: string,\n relayer: string\n): [SwapAction, number] {\n const actionStep = getActionStep(\n mainTokenInIndex,\n mainTokenOutIndex,\n swap.assetInIndex,\n swap.assetOutIndex\n );\n // Will get actual amount if input or chain amount if part of chain\n const amountIn = getActionAmount(swap, ActionType.Swap, actionStep, opRefKey);\n // Updates swap data to use chainedRef if required\n swap.amount = amountIn;\n // This will be 0 if not a mainTokenOut action otherwise amount using slippage\n const minOut = getActionMinOut(swap.returnAmount ?? '0', slippage);\n // This will set opRef for next chained action if required\n const [opRef, newOpRefKey] = getActionOutputRef(\n actionStep,\n swap.assetOutIndex,\n opRefKey\n );\n const hasTokenIn =\n actionStep === ActionStep.Direct || actionStep === ActionStep.TokenIn\n ? true\n : false;\n const hasTokenOut =\n actionStep === ActionStep.Direct || actionStep === ActionStep.TokenOut\n ? true\n : false;\n const isBptIn = isBpt(pools, assets[swap.assetInIndex]);\n // joins - can't join a pool and send BPT to internal balances\n // Because of ^ we can assume that any BPT is coming from external (either from user or join)\n let fromInternal = true;\n if (hasTokenIn || isBptIn) fromInternal = false;\n // exits - can't exit using BPT from internal balances\n // Because of ^ we can assume that any tokenOut BPT is going to external (either to user or exit)\n let toInternal = true;\n if (hasTokenOut || isBpt(pools, assets[swap.assetOutIndex]))\n toInternal = false;\n\n // tokenIn/Out will come from/go to the user. Any other tokens are intermediate and will be from/to Relayer\n let sender: string;\n if (hasTokenIn) {\n sender = user;\n } else {\n sender = relayer;\n }\n let receiver: string;\n if (hasTokenOut) {\n receiver = user;\n } else {\n receiver = relayer;\n }\n\n const swapAction: SwapAction = {\n type: ActionType.Swap,\n opRef: opRef.key ? [opRef] : [],\n minOut,\n amountIn,\n assets,\n swap: swap,\n hasTokenIn,\n hasTokenOut,\n fromInternal,\n toInternal,\n isBptIn,\n sender,\n receiver,\n };\n return [swapAction, newOpRefKey];\n}\n\n/**\n * Creates encoded exitPool call.\n * @param pool\n * @param action\n * @param wrappedNativeAsset\n * @returns\n */\nfunction buildExitCall(\n pool: SubgraphPoolBase,\n action: ExitAction,\n wrappedNativeAsset: string\n): [string, string, string] {\n const assets = pool.tokensList;\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n // tokens must have same order as pool getTokens\n const [sortedTokens] = assetHelpers.sortTokens(assets) as [string[]];\n const exitToken = action.tokenOut;\n const exitTokenIndex = sortedTokens.findIndex(\n (t) => t.toLowerCase() === exitToken.toLowerCase()\n );\n const minAmountsOut = Array(assets.length).fill('0');\n // Variable amount of token out (this has slippage applied)\n minAmountsOut[exitTokenIndex] = action.minOut;\n // Uses exact amount in\n const bptAmtIn = action.amountIn;\n const userData = WeightedPoolEncoder.exitExactBPTInForOneTokenOut(\n bptAmtIn,\n exitTokenIndex\n );\n const exitParams: ExitPoolData = {\n assets: sortedTokens,\n minAmountsOut,\n userData,\n toInternalBalance: action.toInternal,\n poolId: action.poolId,\n poolKind: 0, // This will always be 0 to match supported Relayer types\n sender: action.sender,\n recipient: action.receiver,\n outputReferences: action.opRef,\n exitPoolRequest: {} as ExitPoolRequest,\n };\n // console.log(exitParams);\n const callData = Relayer.constructExitCall(exitParams);\n // These are used for final amount check\n const amountOut = action.hasTokenOut ? minAmountsOut[exitTokenIndex] : '0';\n const amountIn = action.hasTokenIn ? bptAmtIn : '0';\n return [callData, amountIn, amountOut];\n}\n\n/**\n * Creates encoded joinPool call.\n * @param pool\n * @param action\n * @param wrappedNativeAsset\n * @returns\n */\nfunction buildJoinCall(\n pool: SubgraphPoolBase,\n action: JoinAction,\n wrappedNativeAsset: string\n): [string, string, string] {\n const assets = pool.tokensList;\n const assetHelpers = new AssetHelpers(wrappedNativeAsset);\n // tokens must have same order as pool getTokens\n const [sortedTokens] = assetHelpers.sortTokens(assets) as [string[]];\n const joinToken = action.tokenIn;\n const joinTokenIndex = sortedTokens.findIndex(\n (t) => t.toLowerCase() === joinToken.toLowerCase()\n );\n const maxAmountsIn = Array(assets.length).fill('0');\n // Uses exact amounts of tokens in\n maxAmountsIn[joinTokenIndex] = action.amountIn;\n // Variable amount of BPT out (this has slippage applied)\n const bptAmountOut = action.minOut;\n const userData = WeightedPoolEncoder.joinExactTokensInForBPTOut(\n maxAmountsIn,\n bptAmountOut\n );\n const attributes: EncodeJoinPoolInput = {\n poolId: action.poolId,\n sender: action.sender,\n recipient: action.receiver,\n kind: 0,\n joinPoolRequest: {\n assets: sortedTokens,\n maxAmountsIn,\n userData,\n fromInternalBalance: action.fromInternal,\n },\n value: '0',\n outputReference: action.opRef.key ? action.opRef.key.toString() : '0',\n };\n\n // console.log(attributes);\n\n const callData = Relayer.encodeJoinPool(attributes);\n // These are used for final amount check\n const amountOut = action.hasTokenOut ? bptAmountOut : '0';\n const amountIn = action.hasTokenIn ? maxAmountsIn[joinTokenIndex] : '0';\n\n return [callData, amountIn, amountOut];\n}\n\n/**\n * Creates encoded batchSwap call.\n * @param action\n * @param swapType\n * @param tokenIn\n * @param tokenOut\n * @returns\n */\nfunction buildBatchSwapCall(\n action: BatchSwapAction,\n tokenIn: string,\n tokenOut: string\n): [string[], string, string] {\n const calls: string[] = [];\n\n for (const token of action.approveTokens) {\n // If swap tokenIn is a BPT then:\n // new pools have automatic infinite vault allowance, but not old ones\n // const key = Relayer.fromChainedReference(action.swaps[0].amount);\n // const readOnlyRef = Relayer.toChainedReference(key, false);\n // const approval = Relayer.encodeApproveVault(token, readOnlyRef.toString());\n // TODO fix approval amount\n const approval = Relayer.encodeApproveVault(token, MaxUint256.toString());\n calls.push(approval);\n }\n\n const funds: FundManagement = {\n sender: action.sender,\n recipient: action.receiver,\n fromInternalBalance: action.fromInternal,\n toInternalBalance: action.toInternal,\n };\n const batchSwapInput: EncodeBatchSwapInput = {\n swapType: SwapType.SwapExactIn,\n swaps: action.swaps,\n assets: action.assets,\n funds,\n limits: action.limits.map((l) => l.toString()),\n deadline: BigNumber.from(Math.ceil(Date.now() / 1000) + 3600), // 1 hour from now\n value: '0',\n outputReferences: action.opRef,\n };\n // console.log(batchSwapInput);\n\n const encodedBatchSwap = Relayer.encodeBatchSwap(batchSwapInput);\n calls.push(encodedBatchSwap);\n const maintokenInIndex = action.assets.findIndex(\n (t) => t.toLowerCase() === tokenIn.toLowerCase()\n );\n const maintokenOutIndex = action.assets.findIndex(\n (t) => t.toLowerCase() === tokenOut.toLowerCase()\n );\n const amountIn = action.hasTokenIn\n ? action.limits[maintokenInIndex].toString()\n : '0';\n const amountOut = action.hasTokenOut\n ? action.limits[maintokenOutIndex].abs().toString()\n : '0';\n return [calls, amountIn, amountOut];\n}\n\n/**\n * Given swapInfo from the SOR construct the Relayer multicall to execture swaps/joins/exits.\n * @param swapInfo Returned from SOR\n * @param swapType Only supports ExactIn\n * @param pools Pool info from SOR\n * @param user Address of user\n * @param relayerAddress Address of Relayer (>=V4)\n * @param wrappedNativeAsset Address of Native asset\n * @param slippage [bps], eg: 1 === 0.01%, 100 === 1%\n * @param authorisation Encoded authorisation call.\n * @returns\n */\nexport function buildRelayerCalls(\n swapInfo: SwapInfo,\n pools: SubgraphPoolBase[],\n user: string,\n relayerAddress: string,\n wrappedNativeAsset: string,\n slippage: string,\n authorisation: string | undefined\n): {\n to: string;\n data: string;\n rawCalls: string[];\n} {\n // For each 'swap' create a swap/join/exit action\n const actions = getActions(\n swapInfo.tokenIn,\n swapInfo.tokenOut,\n swapInfo.swaps,\n swapInfo.tokenAddresses,\n slippage,\n pools,\n user,\n relayerAddress\n );\n // Arrange action into order that will create minimal amount of calls\n const orderedActions = orderActions(actions, swapInfo.tokenAddresses);\n\n const calls: string[] = [];\n // These amounts are used to compare to expected amounts\n const amountsIn: BigNumber[] = [];\n const amountsOut: BigNumber[] = [];\n if (authorisation)\n calls.push(buildSetRelayerApproval(authorisation, relayerAddress));\n\n // Create encoded call for each action\n for (const action of orderedActions) {\n if (action.type === ActionType.Exit) {\n const pool = pools.find((p) => p.id === action.poolId);\n if (pool === undefined)\n throw new BalancerError(BalancerErrorCode.NO_POOL_DATA);\n const [call, amountIn, amountOut] = buildExitCall(\n pool,\n action,\n wrappedNativeAsset\n );\n calls.push(call);\n amountsIn.push(BigNumber.from(amountIn));\n amountsOut.push(BigNumber.from(amountOut));\n }\n if (action.type === ActionType.Join) {\n const pool = pools.find((p) => p.id === action.poolId);\n if (pool === undefined)\n throw new BalancerError(BalancerErrorCode.NO_POOL_DATA);\n const [call, amountIn, amountOut] = buildJoinCall(\n pool,\n action,\n wrappedNativeAsset\n );\n calls.push(call);\n amountsIn.push(BigNumber.from(amountIn));\n amountsOut.push(BigNumber.from(amountOut));\n }\n if (action.type === ActionType.BatchSwap) {\n const [batchSwapCalls, amountIn, amountOut] = buildBatchSwapCall(\n action,\n swapInfo.tokenIn,\n swapInfo.tokenOut\n );\n calls.push(...batchSwapCalls);\n amountsIn.push(BigNumber.from(amountIn));\n amountsOut.push(BigNumber.from(amountOut));\n }\n }\n\n // Safety check to make sure amounts/limits from calls match expected\n checkAmounts(amountsIn, amountsOut, swapInfo, slippage);\n // encode relayer multicall\n const callData = balancerRelayerInterface.encodeFunctionData('multicall', [\n calls,\n ]);\n\n return {\n to: relayerAddress,\n data: callData,\n rawCalls: calls,\n };\n}\n\nfunction checkAmounts(\n amountsIn: BigNumber[],\n amountsOut: BigNumber[],\n swapInfo: SwapInfo,\n slippage: string\n): void {\n const totalIn = amountsIn.reduce(\n (total = BigNumber.from(0), amount) => (total = total.add(amount))\n );\n const totalOut = amountsOut.reduce(\n (total = BigNumber.from(0), amount) => (total = total.add(amount))\n );\n // totalIn should equal the original input swap amount\n // totalOut should equal the return amount from SOR minus any slippage allowance\n // console.log(totalIn.toString(), 'totalIn');\n // console.log(swapInfo.swapAmount.toString(), 'swapInfo.swapAmount');\n // console.log(totalOut.toString(), 'totalOut');\n // console.log(\n // subSlippage(swapInfo.returnAmount, BigNumber.from(slippage)).toString(),\n // 'slippage'\n // );\n // console.log(swapInfo.returnAmount.toString(), 'swapInfo.returnAmount');\n const diffOut = totalOut.sub(\n subSlippage(swapInfo.returnAmount, BigNumber.from(slippage))\n );\n if (!totalIn.eq(swapInfo.swapAmount) || !diffOut.lt(`3`))\n throw new BalancerError(BalancerErrorCode.RELAY_SWAP_AMOUNTS);\n /* ExactOut case\n // totalIn should equal the return amount from SOR (this is the amount in) plus any slippage allowance\n // totalOut should equal the original input swap amount (the exact amount out)\n if (\n !totalIn.eq(\n addSlippage(swapInfo.returnAmount, BigNumber.from(slippage))\n ) ||\n !totalOut.eq(swapInfo.swapAmount)\n )\n throw new BalancerError(BalancerErrorCode.RELAY_SWAP_AMOUNTS);\n */\n}\n","export * as balEmissions from './bal/emissions';\nexport * from './gauge-controller/multicall';\nexport * from './gauge-shares';\nexport * from './liquidity-gauges';\nexport * from './pool';\nexport * from './pool-gauges';\nexport * from './pool-joinExit';\nexport * from './pool-shares';\nexport * from './token';\nexport * from './token-prices';\nexport * from './fee-distributor/repository';\nexport * from './fee-collector/repository';\nexport * from './protocol-fees/provider';\nexport * from './token-yields/repository';\nexport * from './block-number';\n\nimport {\n BalancerNetworkConfig,\n BalancerDataRepositories,\n GraphQLQuery,\n} from '@/types';\nimport { PoolsSubgraphRepository } from './pool/subgraph';\nimport { PoolSharesRepository } from './pool-shares/repository';\nimport { PoolJoinExitRepository } from './pool-joinExit/repository';\nimport { PoolsSubgraphOnChainRepository } from './pool/subgraphOnChain';\nimport { PoolGaugesRepository } from './pool-gauges/repository';\nimport { GaugeSharesRepository } from './gauge-shares/repository';\nimport { BlockNumberRepository } from './block-number';\nimport {\n CoingeckoPriceRepository,\n AaveRates,\n TokenPriceProvider,\n HistoricalPriceProvider,\n CoingeckoHistoricalPriceRepository,\n} from './token-prices';\nimport { StaticTokenProvider } from './token/static';\nimport { LiquidityGaugeSubgraphRPCProvider } from './liquidity-gauges/provider';\nimport { FeeDistributorRepository } from './fee-distributor/repository';\nimport { FeeCollectorRepository } from './fee-collector/repository';\nimport { TokenYieldsRepository } from './token-yields/repository';\nimport { ProtocolFeesProvider } from './protocol-fees/provider';\nimport { Provider } from '@ethersproject/providers';\n\n// initialCoingeckoList are used to get the initial token list for coingecko\n// TODO: we might want to replace that with what frontend is using\nimport initialCoingeckoList from '@/modules/data/token-prices/initial-list.json';\nimport { SubgraphPriceRepository } from './token-prices/subgraph';\n\nexport class Data implements BalancerDataRepositories {\n pools;\n poolsOnChain;\n yesterdaysPools;\n poolShares;\n poolGauges;\n gaugeShares;\n tokenPrices;\n tokenHistoricalPrices;\n tokenMeta;\n liquidityGauges;\n feeDistributor;\n feeCollector;\n protocolFees;\n tokenYields;\n blockNumbers;\n poolJoinExits;\n\n constructor(\n networkConfig: BalancerNetworkConfig,\n provider: Provider,\n subgraphQuery?: GraphQLQuery\n ) {\n this.pools = new PoolsSubgraphRepository({\n url: networkConfig.urls.subgraph,\n chainId: networkConfig.chainId,\n });\n\n this.poolsOnChain = new PoolsSubgraphOnChainRepository({\n url: networkConfig.urls.subgraph,\n chainId: networkConfig.chainId,\n provider: provider,\n multicall: networkConfig.addresses.contracts.multicall,\n vault: networkConfig.addresses.contracts.vault,\n query: subgraphQuery,\n });\n\n this.poolShares = new PoolSharesRepository(\n networkConfig.urls.subgraph,\n networkConfig.chainId\n );\n\n this.poolJoinExits = new PoolJoinExitRepository(\n networkConfig.urls.subgraph,\n networkConfig.chainId\n );\n\n if (networkConfig.urls.gaugesSubgraph) {\n this.poolGauges = new PoolGaugesRepository(\n networkConfig.urls.gaugesSubgraph,\n networkConfig.chainId\n );\n\n this.gaugeShares = new GaugeSharesRepository(\n networkConfig.urls.gaugesSubgraph,\n networkConfig.chainId\n );\n }\n\n // 🚨 yesterdaysPools is used to calculate swapFees accumulated over last 24 hours\n // TODO: find a better data source for that, eg: maybe DUNE once API is available\n // if (networkConfig.urls.blockNumberSubgraph) {\n // this.blockNumbers = new BlockNumberRepository(\n // networkConfig.urls.blockNumberSubgraph\n // );\n\n // const blockDayAgo = async () => {\n // if (this.blockNumbers) {\n // return await this.blockNumbers.find('dayAgo');\n // }\n // };\n\n // this.yesterdaysPools = new PoolsSubgraphRepository({\n // url: networkConfig.urls.subgraph,\n // chainId: networkConfig.chainId,\n // blockHeight: blockDayAgo,\n // });\n // }\n\n // Hung change\n if (networkConfig.urls.blockNumberSubgraph) {\n this.blockNumbers = new BlockNumberRepository(\n networkConfig.urls.blockNumberSubgraph\n );\n }\n\n const blockDayAgo = async () => {\n const blockPerDay = 5000;\n const currentBlock = await provider.getBlockNumber();\n return Number(currentBlock) - blockPerDay;\n };\n\n this.yesterdaysPools = new PoolsSubgraphRepository({\n url: networkConfig.urls.subgraph,\n chainId: networkConfig.chainId,\n blockHeight: blockDayAgo,\n });\n\n const tokenAddresses = initialCoingeckoList\n .filter((t) => t.chainId == networkConfig.chainId)\n .map((t) => t.address);\n\n const coingeckoRepository = new CoingeckoPriceRepository(\n tokenAddresses,\n networkConfig.chainId\n );\n\n const subgraphPriceRepository = new SubgraphPriceRepository(\n networkConfig.urls.subgraph,\n networkConfig.chainId\n );\n\n const aaveRates = new AaveRates(\n networkConfig.addresses.contracts.multicall,\n provider,\n networkConfig.chainId\n );\n\n this.tokenPrices = new TokenPriceProvider(\n coingeckoRepository,\n subgraphPriceRepository,\n aaveRates\n );\n\n const coingeckoHistoricalRepository =\n new CoingeckoHistoricalPriceRepository(networkConfig.chainId);\n\n this.tokenHistoricalPrices = new HistoricalPriceProvider(\n coingeckoHistoricalRepository,\n aaveRates\n );\n\n this.tokenMeta = new StaticTokenProvider([]);\n\n if (networkConfig.urls.gaugesSubgraph) {\n this.liquidityGauges = new LiquidityGaugeSubgraphRPCProvider(\n networkConfig.urls.gaugesSubgraph,\n networkConfig.addresses.contracts.multicall,\n networkConfig.addresses.contracts.gaugeController || '',\n networkConfig.chainId,\n provider\n );\n }\n\n if (\n networkConfig.addresses.contracts.feeDistributor &&\n networkConfig.addresses.tokens.bal &&\n networkConfig.addresses.tokens.veBal &&\n networkConfig.addresses.tokens.bbaUsd\n ) {\n this.feeDistributor = new FeeDistributorRepository(\n networkConfig.addresses.contracts.multicall,\n networkConfig.addresses.contracts.feeDistributor,\n networkConfig.addresses.tokens.bal,\n networkConfig.addresses.tokens.veBal,\n networkConfig.addresses.tokens.bbaUsd,\n provider\n );\n }\n\n this.feeCollector = new FeeCollectorRepository(\n networkConfig.addresses.contracts.vault,\n provider\n );\n\n if (networkConfig.addresses.contracts.protocolFeePercentagesProvider) {\n this.protocolFees = new ProtocolFeesProvider(\n networkConfig.addresses.contracts.multicall,\n networkConfig.addresses.contracts.protocolFeePercentagesProvider,\n provider\n );\n }\n\n this.tokenYields = new TokenYieldsRepository(networkConfig.chainId);\n }\n}\n","import { BalancerSdkConfig, BalancerNetworkConfig } from '@/types';\nimport { Swaps } from './swaps/swaps.module';\nimport { Relayer } from './relayer/relayer.module';\nimport { Subgraph } from './subgraph/subgraph.module';\nimport { Sor } from './sor/sor.module';\nimport { getNetworkConfig } from './sdk.helpers';\nimport { Pricing } from './pricing/pricing.module';\nimport { ContractInstances, Contracts } from './contracts/contracts.module';\nimport { Zaps } from './zaps/zaps.module';\nimport { Pools } from './pools';\nimport { Data } from './data';\nimport { Provider } from '@ethersproject/providers';\n\nexport interface BalancerSDKRoot {\n config: BalancerSdkConfig;\n sor: Sor;\n subgraph: Subgraph;\n pools: Pools;\n data: Data;\n swaps: Swaps;\n relayer: Relayer;\n networkConfig: BalancerNetworkConfig;\n rpcProvider: Provider;\n}\n\nexport class BalancerSDK implements BalancerSDKRoot {\n readonly swaps: Swaps;\n readonly relayer: Relayer;\n readonly pricing: Pricing;\n readonly pools: Pools;\n readonly data: Data;\n balancerContracts: Contracts;\n zaps: Zaps;\n readonly networkConfig: BalancerNetworkConfig;\n readonly provider: Provider;\n\n constructor(\n public config: BalancerSdkConfig,\n public sor = new Sor(config),\n public subgraph = new Subgraph(config)\n ) {\n this.networkConfig = getNetworkConfig(config);\n this.provider = sor.provider;\n\n this.data = new Data(\n this.networkConfig,\n sor.provider,\n config.subgraphQuery\n );\n this.swaps = new Swaps(this.config);\n this.relayer = new Relayer(this.swaps);\n this.pricing = new Pricing(config, this.swaps);\n this.pools = new Pools(this.networkConfig, this.data);\n\n this.balancerContracts = new Contracts(\n this.networkConfig.addresses.contracts,\n sor.provider\n );\n this.zaps = new Zaps(this.networkConfig.chainId);\n }\n\n get rpcProvider(): Provider {\n return this.sor.provider;\n }\n\n /**\n * Expose balancer contracts, e.g. Vault, LidoRelayer.\n */\n get contracts(): ContractInstances {\n return this.balancerContracts.contracts;\n }\n}\n"],"names":["StablePoolJoinKind","StablePhantomPoolJoinKind","StablePoolExitKind","WeightedPoolJoinKind","WeightedPoolExitKind","StablePoolEncoder","constructor","joinInit","amountsIn","defaultAbiCoder","encode","INIT","joinCollectProtocolFees","COLLECT_PROTOCOL_FEES","joinExactTokensInForBPTOut","minimumBPT","EXACT_TOKENS_IN_FOR_BPT_OUT","joinTokenInForExactBPTOut","bptAmountOut","enterTokenIndex","TOKEN_IN_FOR_EXACT_BPT_OUT","exitExactBPTInForOneTokenOut","bptAmountIn","exitTokenIndex","EXACT_BPT_IN_FOR_ONE_TOKEN_OUT","exitExactBPTInForTokensOut","EXACT_BPT_IN_FOR_TOKENS_OUT","exitBPTInForExactTokensOut","amountsOut","maxBPTAmountIn","BPT_IN_FOR_EXACT_TOKENS_OUT","WeightedPoolEncoder","joinAllTokensInForExactBPTOut","ALL_TOKENS_IN_FOR_EXACT_BPT_OUT","ManagedPoolEncoder","exitForManagementFees","MANAGEMENT_FEE_TOKENS_OUT","toNormalizedWeights","weights","length","Array","fill","ONE","div","sum","reduce","total","weight","add","Zero","eq","normalizedWeights","normalizedSum","index","mul","sub","isNormalizedWeights","totalWeight","ComposableStablePoolJoinKind","ComposableStablePoolExitKind","ComposableStablePoolEncoder","isProduction","process","env","NODE_ENV","prefix","invariant","condition","message","Error","provided","value","concat","splitPoolId","poolId","address","getPoolAddress","specialization","getPoolSpecialization","nonce","getPoolNonce","slice","specializationCode","parseInt","BigNumber","from","Network","APR_THRESHOLD","SHALLOW_COMPOSABLE_STABLE_BUFFER","POOLS_GENERIC","IdsMap","Pagination","PerPage","PerPool","PerPoolInitial","DelegateOwner","ZeroAddress","DynamicFees","Gauntlet","BlockList","ExcludedPoolTypes","Stable","AllowList","Investment","Factories","Stakable","Metadata","name","hasIcon","POOLS_MAP","KOVAN","staBAL","bbAaveUSD","v1","v2","veBAL","GOERLI","MAINNET","POLYGON","xMatic","stMatic","mai4","maiBbaUsd","ARBITRUM","GNOSIS","DEFIVERSE","DEFIVERSE_TESTNET","OASYS","OASYS_TESTNET","POOLS","networkId","AaveHelpers","static","rateProviderAddress","provider","rateProviderContract","Contract","aTokenRateProviderAbi","getRate","toString","transposeMatrix","matrix","map","_","columnIndex","row","AssetHelpers","wethAddress","this","ETH","AddressZero","isETH","token","isEqual","isWETH","WETH","translateToERC20","getAddress","sortTokens","tokens","others","forEach","array","erc20Tokens","sortedTranspose","sort","tokenA","tokenB","toLowerCase","cmpTokens","sortedErc20s","sortedOthers","includes","addressA","addressB","balancerErrorCodes","BalancerErrors","async","accountToAddress","account","Signer","isSigner","RelayerAction","isErrorCode","error","errorCode","replace","Object","keys","parseErrorCode","actualError","tryParseErrorCode","isBalancerError","values","encodeError","encodedError","entries","find","RelayerAuthorization","encodeCalldataAuthorization","calldata","deadline","signature","encodedDeadline","hexZeroPad","hexValue","v","r","s","splitSignature","signJoinAuthorization","validator","user","allowedSender","allowedCalldata","signAuthorizationFor","JoinPool","signExitAuthorization","ExitPool","signSwapAuthorization","Swap","signBatchSwapAuthorization","BatchSwap","signSetRelayerApprovalAuthorization","SetRelayerApproval","type","MAX_DEADLINE","chainId","getNetwork","userAddress","getNextNonce","domain","version","verifyingContract","types","sender","_signTypedData","BalancerMinterAuthorization","signSetMinterApproval","minterContract","minter","approval","SetMinterApproval","signPermit","owner","spender","amount","ownerAddress","nonces","Permit","BZERO","BigInt","BONE","_require","b","_computeScalingFactor","tokenDecimals","decimalsDifference","_upscale","scalingFactor","SolidityMaths","mulDownFixed","_upscaleArray","amounts","scalingFactors","upscaledAmounts","i","a","c","roundUp","divUp","divDown","product","aInflated","x","y","raw","LogExpMath","pow","maxError","mulUpFixed","MAX_POW_RELATIVE_ERROR","ONE_18","x_int256","MILD_EXPONENT_BOUND","y_int256","logx_times_y","LN_36_LOWER_BOUND","LN_36_UPPER_BOUND","ln_36_x","_ln_36","_ln","MIN_NATURAL_EXPONENT","MAX_NATURAL_EXPONENT","exp","firstAN","x0","a0","x1","a1","ONE_20","x2","a2","x3","a3","x4","a4","x5","a5","x6","a6","x7","a7","x8","a8","x9","a9","term","seriesSum","z","ONE_36","z_squared","num","a10","x10","a11","x11","parsePoolInfo","pool","wrappedNativeAsset","parsedTokens","parsedDecimals","decimals","undefined","parsedBalances","parseFixed","balance","upScaledBalances","parsedWeights","parsedPriceRates","priceRate","assetHelpers","sfString","parsedAmp","amp","parsedTotalShares","totalShares","parsedSwapFee","swapFee","scalingFactorsWithoutBpt","parsedTokensWithoutBpt","parsedBalancesWithoutBpt","bptIndex","indexOf","push","TOKENS_GENERIC","Popular","Symbols","Addresses","nativeAsset","wNativeAsset","BAL","TOKENS_MAP","bbaUSD","PriceChainMap","bbaUSDv2","GDT","PoolGaugesAttributes","PoolShareAttributes","GaugeShareAttributes","PoolSpecialization","UserBalanceOpKind","PoolBalanceOpKind","PoolType","_permanentCensorErrors","_censorErrors","LogLevels","debug","default","info","warning","off","_logLevel","_globalLogger","_normalizeError","missing","form","normalize","join","String","fromCharCode","_checkNormalize","LogLevel","ErrorCode","HEX","Logger","defineProperty","enumerable","writable","_log","logLevel","args","level","throwArgumentError","console","log","apply","levels","DEBUG","INFO","warn","WARNING","makeError","code","params","errors","UNKNOWN_ERROR","messageDetails","key","Uint8Array","hex","JSON","stringify","reason","url","NUMERIC_FAULT","fault","CALL_EXCEPTION","INSUFFICIENT_FUNDS","MISSING_NEW","NONCE_EXPIRED","REPLACEMENT_UNDERPRICED","TRANSACTION_REPLACED","UNPREDICTABLE_GAS_LIMIT","throwError","INVALID_ARGUMENT","argument","assert","assertArgument","checkNormalize","UNSUPPORTED_OPERATION","operation","checkSafeUint53","checkArgumentCount","count","expectedCount","MISSING_ARGUMENT","UNEXPECTED_ARGUMENT","checkNew","target","kind","checkAbstract","censorship","permanent","globalLogger","logger","names","formatUnits","unitName","formatFixed","parseUnits","yieldTokens","waUSDT","waUSDC","waDAI","wamDAI","wamUSDC","wamUSDT","allYieldTokens","wrappedTokensMap","aToken","underlying","aTokens","t","underlyingAssets","underlyingToWrapped","fromEntries","wrapped","endpoint","aave","network","noRates","graphqlQuery","operationName","variables","response","axios","post","data","reserves","aprEntries","underlyingAsset","Math","round","parseFloat","liquidityRate","tokensToTokenPrices","tokenPrices","price","tokenAddressForPricing","addressMapIn","unwrapToken","addressMap","wrappedAddress","lowercase","toLocaleLowerCase","aaveChain","aaveWrappedMap","Debouncer","fn","wait","requestSet","Set","promisedCalls","promisedCount","debounceCancel","fetch","attr","promise","resolve","reject","Promise","res","rej","makePromise","timeout","clearTimeout","setTimeout","requestAttrs","clear","then","results","catch","valueWithTrimmedDecimals","RegExp","result","match","parsedValue","_parseFixed","_formatFixed","parseToBigInt18","toBigInt","formatFromBigInt18","bn","isSameAddress","address1","address2","insert","arr","newItem","BalancerAPIArgsFormatter","format","SubgraphArgsFormatter","operatorMap","gt","lt","in","not_in","contains","whereQuery","where","filter","operator","GraphQLArgsBuilder","merge","other","mergedArgs","mergeWith","objValue","srcValue","isArray","formatter","SwapType","getLimitsForSlippage","tokensIn","tokensOut","swapType","deltas","assets","slippage","limits","some","tokenIn","slippageAmount","WeiPerEther","SwapExactOut","tokenOut","SwapExactIn","bpsPerOne","mulSlippage","subSlippage","delta","addSlippage","balancerVault","BALANCER_NETWORK_CONFIG","addresses","contracts","vault","multicall","balancerHelpers","lidoRelayer","relayerV3","relayerV4","gaugeController","feeDistributor","protocolFeePercentagesProvider","veBal","veBalProxy","weightedPoolFactory","composableStablePoolFactory","lbpRaisingTokens","stETH","wstETH","bal","bbaUsd","urls","subgraph","gaugesSubgraph","blockNumberSubgraph","pools","wETHwstETH","id","poolsToIgnore","sorConnectingTokens","symbol","ROPSTEN","RINKEBY","OPTIMISM","priceUrl","networkAddresses","BalancerErrorCode","BalancerError","super","getMessage","SWAP_ZERO_RETURN_AMOUNT","UNWRAP_ZERO_AMOUNT","WRAP_ZERO_AMOUNT","QUERY_BATCH_SWAP","POOL_DOESNT_EXIST","UNSUPPORTED_POOL_TYPE","UNSUPPORTED_PAIR","NO_POOL_DATA","INPUT_OUT_OF_BOUNDS","INPUT_LENGTH_MISMATCH","INPUT_TOKEN_INVALID","TOKEN_MISMATCH","MISSING_DECIMALS","MISSING_TOKENS","MISSING_AMP","MISSING_PRICE_RATE","MISSING_WEIGHT","INPUT_ZERO_NOT_ALLOWED","RELAY_SWAP_AMOUNTS","NO_VALUE_PARAMETER","TIMESTAMP_IN_THE_FUTURE","ILLEGAL_PARAMETER","JOIN_DELTA_AMOUNTS","EXIT_DELTA_AMOUNTS","StablePoolExit","buildExitExactBPTIn","exiter","bptIn","shouldUnwrapNativeAsset","singleTokenMaxOut","isNegative","unwrappedTokens","sortedTokens","sortedUpscaledBalances","sortedScalingFactors","userData","expectedAmountsOut","minAmountsOut","singleTokenMaxOutIndex","amountOut","SOR","StableMathBigInt","_calcTokenOutGivenExactBptIn","amountsOutScaledDown","downscaledAmounts","divDownFixed","_downscaleDownArray","_calcTokensOutGivenExactBptIn","to","functionName","attributes","recipient","exitPoolRequest","toInternalBalance","Vault__factory","createInterface","encodeFunctionData","buildExitExactTokensOut","tokensList","sortedUpScaledBalances","sortedAmountsOut","upScaledAmountsOut","_calcBptInGivenExactTokensOut","maxBPTIn","expectedBPTIn","StablePoolJoin","buildJoin","joiner","sortedAmountsIn","scaledAmountsIn","expectedBPTOut","_calcBptOutGivenExactTokensIn","minBPTOut","joinPoolRequest","maxAmountsIn","fromInternalBalance","StablePoolLiquidity","calcTotal","sumBalance","sumValue","_a","usd","avgPrice","_b","SCALING_FACTOR","StablePoolSpotPrice","calcPoolSpotPrice","stablePool","StablePool","fromPool","poolPairData","parsePoolPairData","_spotPriceAfterSwapExactTokenInForTokenOut","ZERO","calcPriceImpact","bptAmount","bptZeroPriceImpact","isJoin","pi","calcPriceImpactJoin","calcPriceImpactExit","AMP_PRECISION","bptSpotPrice","balances","bptSupply","tokenIndexIn","totalCoins","D","numTokens","prevInvariant","ampTimesTotal","P_D","j","_calculateInvariant","S","D_P","alpha","beta","gamma","partial_x","minus_partial_D","divUpFixed","StablePoolPriceImpact","tokenAmounts","exit","liquidity","spotPriceCalculator","priceImpactCalculator","PhantomStablePoolSpotPrice","metaStablePool","PhantomStablePool","StablePhantomPriceImpact","cloneDeep","findIndex","priceRates","rate","splice","balancesScaled","ComposableStablePoolJoin","ComposableStablePoolExit","ComposableStable","WeightedPoolExit","sortedBalances","sortedWeights","WeightedMaths","sortedAmounts","w","WeightedPoolJoin","WeightedPoolLiquidity","sumWeight","toFixed","WeightedPoolSpotPrice","isBPTAsToken","bptAsToken","weightedPool","WeightedPool","spotPrice","pop","WeightedPoolPriceImpact","weightString","Weighted","MetaStablePoolExit","sortedPriceRates","scaledBalances","scaledAmountOut","scaledAmounts","MetaStablePoolJoin","MetaStablePoolLiquidity","MetaStablePoolSpotPrice","MetaStablePool","MetaStablePoolPriceImpact","MetaStable","StablePhantomPoolExit","StablePhantomPoolJoin","StablePhantom","LinearPoolExit","LinearPoolJoin","LinearPoolLiquidity","LinearPoolSpotPrice","linearPool","LinearPool","LinearPriceImpact","Linear","PoolTypeConcerns","config","weighted","stable","composableStable","metaStable","stablePhantom","linear","poolType","Liquidity","totalLiquidity","subPoolLiquidity","all","findBy","getLiquidity","totalBPT","bptInParentPool","liquidityInParentPool","totalSubPoolLiquidity","subPool","nonPoolTokens","nonPoolTokensWithUpdatedPrice","tokenPrice","latestUSDPrice","parsedTokenLiquidity","queryBatchSwap","vaultContract","swaps","funds","callStatic","d","err","queryBatchSwapWithSor","sor","queryWithSor","fetchPools","assetArray","swap","getSorSwapInfo","returnAmount","tokenAddresses","batchedSwaps","newAssetArray","flat","poolSwap","assetInIndex","assetOutIndex","batchSwaps","returnTokens","returnAmounts","swapTypeSOR","SwapTypes","getSwaps","__assign","assign","n","arguments","p","prototype","hasOwnProperty","call","docCache","Map","fragmentSourceMap","printFragmentWarnings","experimentalFragmentVariables","string","trim","processFragments","ast","seenKeys","definitions","fragmentDefinition","fragmentName","sourceKey","loc","source","body","substring","start","end","sourceKeySet","get","has","set","parseDocument","cacheKey","parsed","parse","allowLegacyFragmentVariables","doc","workSet","node","startToken","endToken","stripLoc","gql","literals","_i","arg","gql_1","extras","resetCaches","disableFragmentWarnings","enableExperimentalFragmentVariables","disableExperimentalFragmentVariables","AmpUpdate_OrderBy","BalancerSnapshot_OrderBy","Balancer_OrderBy","GradualWeightUpdate_OrderBy","InvestType","JoinExit_OrderBy","LatestPrice_OrderBy","ManagementOperation_OrderBy","OperationType","OrderDirection","PoolContract_OrderBy","PoolHistoricalLiquidity_OrderBy","PoolShare_OrderBy","PoolSnapshot_OrderBy","PoolToken_OrderBy","Pool_OrderBy","PriceRateProvider_OrderBy","SwapFeeUpdate_OrderBy","Swap_OrderBy","TokenPrice_OrderBy","TokenSnapshot_OrderBy","Token_OrderBy","TradePairSnapshot_OrderBy","TradePair_OrderBy","UserInternalBalance_OrderBy","User_OrderBy","_SubgraphErrorPolicy_","gql$1","SubgraphPoolShareFragmentDoc","SubgraphPoolFragmentDoc","SubgraphPoolSnapshotFragmentDoc","SubgraphJoinExitFragmentDoc","SubgraphBalancerFragmentDoc","SubgraphTokenPriceFragmentDoc","SubgraphTokenLatestPriceFragmentDoc","SubgraphUserFragmentDoc","PoolShareDocument","PoolSharesDocument","PoolsDocument","AllPoolsDocument","PoolDocument","PoolHistoricalLiquiditiesDocument","PoolSnapshotsDocument","JoinExitsDocument","BalancersDocument","TokenPricesDocument","TokenLatestPricesDocument","TokenLatestPriceDocument","UserDocument","UsersDocument","defaultWrapper","action","_operationName","_operationType","getSdk","client","withWrapper","PoolShare","requestHeaders","wrappedRequestHeaders","request","PoolShares","Pools","AllPools","Pool","PoolHistoricalLiquidities","PoolSnapshots","JoinExits","Balancers","TokenPrices","TokenLatestPrices","TokenLatestPrice","User","Users","Chain","GaugeFactory_OrderBy","GaugeShare_OrderBy","GaugeType_OrderBy","GaugeVote_OrderBy","Gauge_OrderBy","LiquidityGauge_OrderBy","RewardToken_OrderBy","RootGauge_OrderBy","VotingEscrowLock_OrderBy","VotingEscrow_OrderBy","SubgraphGaugeShareFragmentDoc","SubgraphLiquidityGaugeFragmentDoc","SubgraphPoolWithPreferentialGaugeFragmentDoc","GaugeShareDocument","GaugeSharesDocument","LiquidityGaugesDocument","PoolGaugesDocument","createSubgraphClient","subgraphUrl","GraphQLClient","createGaugesClient","GaugeShare","GaugeShares","LiquidityGauges","PoolGauges","Gauges.getSdk","multicallAbi","Multicall","Multicaller","multiAddress","abi","options","calls","paths","interface","Interface","path","obj","executeMulticall","multi","aggregate","decodeFunctionResult","getOnChainBalances","subgraphPoolsOriginal","vaultAddress","abis","aTokenRateProvider","weightedPoolAbi","stablePoolAbi","elementPoolAbi","linearPoolAbi","composableStableAbi","multiPool","supportedPoolTypes","PoolFilter","subgraphPools","execute","onChainPools","onchainData","poolTokens","totalSupply","virtualSupply","actualSupply","targets","lowerTarget","upperTarget","wrappedIndex","T","SubgraphPoolDataService","sorConfig","mapped","expiryTime","unitSeconds","principalToken","baseToken","mapPools","getSubgraphPools","addr","fetchOnChainBalances","pool0","pool1000","pool2000","swapEnabled","totalShares_gt","orderBy","TotalLiquidity","orderDirection","Desc","CoingeckoTokenPriceService","tokenAddress","ethPerToken","getTokenPriceInNativeAsset","platformId","nativeAssetId","headers","Accept","SubgraphTokenPriceService","weth","getLatestPriceInEthFromSubgraph","latestPrices","asset_in","pricesKeyedOnId","keyBy","matchingLatestPrices","asset","pricingAssetPricedInEth","pricingAsset","getNetworkConfig","networkConfig","customSubgraphUrl","tenderly","Sor","sdkConfig","getSorConfig","sorNetworkConfig","getSorNetworkConfig","JsonRpcProvider","rpcUrl","subgraphClient","getPoolDataService","getTokenPriceService","tokenPriceService","poolDataService","connectingTokens","checkSimpleFlashSwapParams","poolIds","createSwaps","deltaToExpectedProfit","Number","calcProfit","profits","underlyingToWrappedMap","tokenForSwaps","Relayers","relayerResolver","assetIn","assetOut","lido","swapFragment","relayer","BatchRelayerLibraryAbi","amountForLimit","max","maxSlippage","min","decorateSorSwapInfo","swapInfo","amountIn","swapAmount","amountInForLimits","swapAmountForSwaps","returnAmountFromSwaps","amountOutForLimits","tokenInForSwaps","tokenOutFromSwaps","SingleSwapBuilder","setFunds","setDeadline","setLimits","limit","singleSwap","attrs","fragment","inputs","outputReference","f","BatchSwapBuilder","minAmountOut","maxAmountIn","split","outputReferences","Swaps","sorOrConfig","connect","l","gasPrice","maxPools","buildSwap","builder","batchSwap","encodeBatchSwap","flashLoanAmount","walletAddress","convertSimpleFlashSwapToBatchSwapParameters","getPools","tokenAddress0","tokenAddress1","isProfitable","querySimpleFlashSwap","swapInput","relayerLibrary","relayerLibraryAbi","Relayer","swapsOrConfig","amountBn","mask","check","_hex","maxAmount","relayerAdress","approved","authorisation","gaugeAddress","poolKind","staticToken","fromUnderlying","toUnderlying","reference","isTemporary","CHAINED_REFERENCE_TEMP_PREFIX","CHAINED_REFERENCE_READONLY_PREFIX","paddedPrefix","repeat","ref","exitPoolInput","encodeExitPool","joinPoolInput","encodeJoinPool","slippageAmountNegative","amt","exitTokens","toChainedReference","exitCall","constructExitCall","queryResult","finalTokensOut","slippageAmountPositive","exitToken","elem","swapRecipient","function","MaxUint256","outputs","aaveStaticTokens","rates","fetchOnChain","encodeSwapUnwrap","amountWrapped","amountUnwrapped","abs","amountsUnwrapped","amountsWrapped","amountInwrapped","wrappedTokens","unwrapCalls","wrappedToken","encodedUnwrap","encodeUnwrapAaveStaticToken","signRelayerApproval","relayerAddress","signerAddress","signer","Subgraph","initClient","Pricing","poolsDict","parseToPoolsDict","routeProposer","getCandidatePathsFromDict","getSpotPriceAfterSwapForPath","isLessThan24Hours","incomingDateInSec","Date","now","VeBal","multicaller","veBalAbi","formatLockInfo","lockInfo","lockedAmount","lockedEndDate","locked","hasExistingLock","lockedEndDateNormalised","toNumber","isExpired","epoch","VeBalProxy","instance","veBalProxyAbi","adjustedBalanceOf","RelayerV3ABI","RelayerV4ABI","Contracts","networkOrAddresses","contractAddresses","BalancerHelpers__factory","LidoRelayer__factory","ERC20","getErc20","liquidityGauge","getLiquidityGauge","signerOrProvider","LiquidityGauge","ADDRESSES","staBal3","gauge","assetOrder","bbausd1","bbausd2","linearUsdc1","linearDai1","linearUsdt1","linearUsdc2","linearDai2","linearUsdt2","maiusd","maibbausd","DAI","USDC","USDT","miMATIC","staBal3_2","staBal3_3","balancerRelayerInterface","balancerRelayerAbi","EXIT_DAI","EXIT_USDC","EXIT_USDT","SWAP_RESULT_BBAUSD","StaBal3Builder","staBal3Amount","minBbausd2Out","staked","lte","buildSetRelayerApproval","buildWithdraw","buildExit","buildDeposit","expectedBptReturn","MaxInt256","ceil","encodeGaugeWithdraw","encodeGaugeDeposit","encodeSetRelayerApproval","BbaUsd1Builder","bbausd1Amount","tokenBalances","callData","tokenBalance","usdcBptAmt","daiBptAmt","usdtBptAmt","SWAP_RESULT","EXIT_RESULTS","StablesBuilder","minBptOut","underlyingTokens","poolAddress","EXIT_MIMATIC","MaiusdBuilder","Migrations","stabal3","decode","output","swapIndex","multicallResult","stables","Zaps","migrations","ImpermanentLossService","tokenHistoricalPrices","timestamp","prepareData","poolValueDelta","getPoolValueDelta","holdValueDelta","getHoldValueDelta","calculateImpermanentLoss","floor","priceDelta","entryTimestamp","getWeights","entryPrices","getEntryPrices","exitPrices","getExitPrices","getAssets","getDelta","entryPrice","exitPrice","noWeights","every","uniformWeight","prices","tokensWithPrice","INITIAL_RATE","START_EPOCH_TIME","weekly","currentTimestamp","getTime","dt","dailyRate","ProtocolRevenue","repository","multicallData","balPrice","balAddress","lastWeekBalRevenue","balAmount","lastWeekBBAUsdRevenue","bbAUsdAmount","bbAUsdPrice","veBalSupply","PoolFees","yesterdaysPools","yesterdaysPool","totalSwapFee","createTime","PoolApr","tokenMeta","tokenYields","feeCollector","liquidityGauges","last24hFees","feesDailyBsp","protocolSwapFeePercentage","breakdown","boost","workingSupply","bptPriceUsd","bptPrice","balPriceUsd","gaugeBalEmissionsUsd","emissions.weekly","relativeWeight","gaugeSupplyUsd","relativeWeightNextPeriod","rewardTokens","rewards","tAddress","rewardTokenApr","totalSupplyUsd","rewardTokensBreakdown","reward","rewardValue","rewardValueScaled","revenue","dailyRevenue","swapFees","tokenAprs","minStakingApr","maxStakingApr","rewardAprs","protocolApr","stakingApr","stakingAprNextPeriod","last24h","liquidityService","_totalLiquidity","_totalShares","fee","poolTypeVersion","protocolSwapFeeCache","rewardData","period_finish","yearlyReward","meta","joinActions","AaveLinear","EulerLinear","ERC4626Linear","Element","LiquidityBootstrapping","exitActions","PoolGraph","wrapMainTokens","rootPool","buildGraphFromPool","getTokenTotal","nodeIndex","parent","proportionOfParent","parentPool","leafTokenDecimals","createInputTokenNode","joinAction","exitAction","tokenTotal","spotPrices","sp","poolNode","children","marked","isLeaf","createLinearNodeChildren","proportion","tokenWeight","finalProportion","childNode","linearPoolNode","wrappedNodeInfo","createWrappedTokenNode","mainIndex","mainTokenDecimals","nodeInfo","wrappedTokenNode","inputNode","root","nodes","orderedNodes","currentNode","shift","getGraphNodes","poolsGraph","rootNode","buildGraphFromRootPool","orderByBfs","reverse","TenderlyHelper","tenderlyConfig","simulateMulticall","encodedStateOverrides","encodeBalanceAndAllowanceOverrides","encodeRelayerApprovalOverride","simulateTransaction","state_objects","storage","network_id","block_number","blockNumber","input","save_if_fails","simulation_type","SIMULATE_URL","tenderlyUrl","opts","transaction","transaction_info","call_trace","stateOverrides","requestStateOverrides","k","ENCODE_STATES_URL","networkID","project","accessKey","Join","createCalls","joinPaths","outputIndexes","createActionCalls","unshift","createSetRelayerApproval","amountsOutByJoinPath","staticResult","tenderlyHelper","totalAmountOut","outputIndex","minAmountsOutByJoinPath","totalMinAmountOut","isPeek","joinPath","isLeafJoin","nodeChildrenWithinJoinPath","joinNode","child","isLastChainedCall","minOut","createAaveWrap","createBatchSwap","updateDeltas","createJoinPool","outputRef","peekCall","encodePeekChainedReferenceValue","joinPathIndex","encodeWrapAaveDynamicToken","getOutputRefValue","expectedOut","inputToken","inputValue","isRef","userTokenIn","inputTokens","inputAmts","childWithinJoinPath","userDataAmounts","ethIndex","constructJoinCall","userAmountsTokenIn","isChainedReference","userAmountOut","getJoinPaths","totalBptZeroPi","totalBptZeroPriceImpact","queryData","priceImpact","assertDeltas","_c","inputNodes","nonLeafInputNodes","nonLeafInputNode","nonLeafAmountIn","totalProportions","proportionalNonLeafAmountIn","inputTokenNode","nonLeafJoinPath","updateInputAmounts","ajdustAmountInDiff","tokenInInputNodes","amountsInSumforTokenIn","diff","leafJoinPath","updateTotalProportions","updateNodeAmount","nonLeafJoinPaths","leafNode","bptOut","bptOutZeroPiForInputNode","spProduct","parentNode","childAddress","spPriceScaled","inputAmountScaled","tokenIndex","totalProportion","inputAmount","Exit","amountsOutByExitPath","simulationResult","multiCallResult","expectedAmountsOutByExitPath","minAmountsOutByExitPath","expectedAmountOut","amountsOutByTokenOut","tokensOutByExitPath","expectedAmountsOutMap","getExitPaths","outputNodes","exitPaths","outputNode","exitPath","amountsInSum","accumulator","currentExitPath","amountInForCurrentExitPath","amountsInDiff","getOutputRef","exitPathIndex","amountBptIn","staticCall","calculatePriceImpact","orderedNodesForJoin","exitChild","isLastActionFromExitPath","createExitPool","userTokenOutAmount","userBptAmount","userDataTokens","userAmountTokensOut","userBptIn","PoolVolume","totalSwapVolume","ComposableStableFactory","create","factoryAddress","amplificationParameter","rateProviders","tokenRateCacheDurations","exemptFromYieldProtocolFeeFlags","swapFeeScaled","sortedRateProviders","sortedTokenRateCacheDurations","sortedExemptFromYieldProtocols","composablePoolInterface","createFunctionAbi","INTERNAL_ERROR_INVALID_ABI","createFunctionFragment","FunctionFragment","buildInitJoin","WeightedFactory","weightedPoolInterface","WeightedPoolFactory__factory","PoolFactory__factory","of","ParamsBuilder","encoder","Gyro2","Gyro3","getEncoder","buildQueryJoinExactIn","buildQueryJoinExactOut","buildQueryExitToSingleToken","buildQueryExitProportionally","buildQueryExitExactOut","maxBptIn","EmissionsService","liquidityGaugesRepository","proportionalAmounts","tokensWithoutBpt","referenceTokenIndex","notImplemented","repositories","aprService","joinService","poolsOnChain","exitService","feesService","volumeService","poolFactory","impermanentLossService","emissionsService","dataSource","apr","aprNextPeriod","calcImpLoss","joinPool","exitPool","concerns","queries","methods","calcSpotPrice","calcProportionalAmounts","Queries.ParamsBuilder","bind","wrap","param","list","gaugeControllerInterface","GaugeControllerMulticallRepository","multicallAddress","gaugeControllerAddress","gaugeAddresses","payload","AbstractSubgraphRepository","query","attribute","first","skip","BalancerSubgraphRepository","blockHeight","GaugesSubgraphRepository","GaugeSharesRepository","Balance","block","number","gaugeShares","mapType","subgraphGaugeShare","isKilled","findAllBy","UserAddress","gaugeId","GaugeId","liquidityGaugeV5Interface","LiquidityGaugesMulticallRepository","res0x","rewardCounts","passingRewardCounts","getRewardCounts","gaugesWithRewards","startIndexes","gaugeIndex","passingRewardTokens","getRewardTokens","decoded","LiquidityGaugesSubgraphRepository","gauges","qauges","preferentialGauge_not","preferentialGauge","oneWeekInMs","LiquidityGaugeSubgraphRPCProvider","workingSupplies","workingSuppliesNextPeriod","relativeWeights","relativeWeightsNextPeriod","g","getWorkingSupplies","getRelativeWeights","nextWeekTimestamp","hasSubgraphData","distributor","last_update","integral","periodFinish","getRewardData","compose","subgraphGauge","BalancerAPIClient","apiKey","toPayload","jsonToGraphQLQuery","PoolsBalancerAPIRepository","fetchFromCache","nextToken","formattedArgs","formattedQuery","__args","apiResponseData","rewardsBreakdown","tokenAprsBreakdown","_d","PoolsFallbackRepository","providers","currentProviderIdx","fallbackQuery","currentProvider","func","race","e","PoolsStaticRepository","PoolsSubgraphRepository","defaultArgs","fetchDefault","subgraphPool","protocolYieldFeeCache","factory","mapToken","priceRateProviders","_e","_f","_g","_h","_j","subgraphToken","subPoolInfo","mapSubPools","isExemptFromYieldProtocolFee","metadata","mapSubPoolToken","PoolsSubgraphOnChainRepository","poolsSubgraph","PoolGaugesRepository","PoolJoinExitAttributes","PoolJoinExitRepository","Timestamp","Asc","joinExits","item","Sender","PoolSharesRepository","poolShares","subgraphPoolShare","PoolId","StaticTokenProvider","StaticTokenPriceProvider","lowercaseAddress","CoingeckoPriceRepository","baseTokenAddresses","urlBase","debouncer","signal","finally","fetchNative","Assets","assetId","OAS","inputAddress","baseAddress","platform","CoingeckoHistoricalPriceRepository","urlRange","range","SubgraphPriceRepository","TokenPriceProvider","coingeckoRepository","subgraphRepository","aaveRates","eth","HistoricalPriceProvider","wrappedATokenInterface","AaveRates","wrappedATokenAddress","wrappedAToken","feeDistributorInterface","veBalInterface","bbAUsdInterface","FeeDistributorRepository","feeDistributorAddress","veBalAddress","bbAUsdAddress","previousWeek","getPreviousWeek","fromTimestamp","midnight","setUTCHours","setUTCMinutes","setUTCSeconds","setUTCMilliseconds","daysSinceThursday","getUTCDay","weeksToGoBack","vaultInterface","protocolFeesCollectorInterface","swapFeePercentagePromise","FeeCollectorRepository","getProtocolFeesCollector","collector","fees","getSwapFeePercentage","swapFeePercentage","iProtocolFeePercentagesProvider","feesPromise","ProtocolFeesProvider","protocolFeePercentagesProviderAddress","yieldFee","protocolFees","arbitrumStEth","aprs","smaApr","rETH","rocketpool","yearlyAPR","stMATIC","lidoPolygon","returnApr","usdcUSDplus","usdcUSDplus2","overnight","bsp","sfrxETH","sfrxethApr","maticX","qETH","tranchess","weeklyAveragePnlPercentage","USDR","usdr","stafi","stakeApr","contractFetcher","getPoolsUI","components","internalType","stateMutability","sApe","tessera","contract","apePool","stakedAmount","currentTimeRange","rewardsPerHour","eUSDC","eDAI","eUSDT","eFRAX","euler","eTokenAddress_in","eTokenAddress","supplyAPY","yieldSourceMap","lidoTokens","lidoPolygonTokens","aaveTokens","overnightTokens","rocketpoolTokens","fraxTokens","staderLabsTokens","tranchessTokens","usdrTokens","stafiTokens","tesseraTokens","eulerTokens","TokenYieldsRepository","sources","yields","fetchBlockByTime","blocks","BlockNumberRepository","dayAgo","ActionStep","ActionType","Data","subgraphQuery","poolJoinExits","poolGauges","blockNumbers","currentBlock","getBlockNumber","initialCoingeckoList","subgraphPriceRepository","coingeckoHistoricalRepository","BalancerSDK","pricing","balancerContracts","zaps","rpcProvider","EMPTY_BATCHSWAP_ACTION","opRef","hasTokenIn","hasTokenOut","fromInternal","toInternal","approveTokens","receiver","isBpt","canUseJoinExit","isExit","someJoinExit","hasJoinExit","getActionOutputRef","actionStep","tokenOutIndex","opRefKey","TokenIn","Middle","getActionMinOut","getActionAmount","actionType","TokenOut","getActionStep","tokenInIndex","tokenInIndexAction","tokenOutIndexAction","Direct","orderActions","actions","categorizedActions","enterActions","middleActions","categorizeActions","orderedActions","allActions","isFirstSwap","lastSwap","isBptIn","batchSwapActions","createJoinAction","mainTokenInIndex","mainTokenOutIndex","newOpRefKey","bpt","createExitAction","createSwapAction","buildExitCall","bptAmtIn","exitParams","buildJoinCall","joinToken","joinTokenIndex","buildBatchSwapCall","encodeApproveVault","batchSwapInput","encodedBatchSwap","maintokenInIndex","maintokenOutIndex","buildRelayerCalls","previousAction","swapAction","getActions","batchSwapCalls","totalIn","totalOut","diffOut","checkAmounts","rawCalls"],"mappings":"4iDAGYA,EAMAC,EAKAC,ECXAC,EAOAC,GDPZ,SAAYJ,GACVA,EAAAA,EAAA,KAAA,GAAA,OACAA,EAAAA,EAAA,4BAAA,GAAA,8BACAA,EAAAA,EAAA,2BAAA,GAAA,4BACD,CAJD,CAAYA,IAAAA,EAIX,CAAA,IAED,SAAYC,GACVA,EAAAA,EAAA,KAAA,GAAA,OACAA,EAAAA,EAAA,sBAAA,GAAA,uBACD,CAHD,CAAYA,IAAAA,EAGX,CAAA,IAED,SAAYC,GACVA,EAAAA,EAAA,+BAAA,GAAA,iCACAA,EAAAA,EAAA,4BAAA,GAAA,8BACAA,EAAAA,EAAA,4BAAA,GAAA,6BACD,CAJD,CAAYA,IAAAA,EAIX,CAAA,UAEYG,EAIXC,cAEC,EAMMD,EAAQE,SAAIC,GACjBC,EAAgBC,OACd,CAAC,UAAW,aACZ,CAACV,EAAmBW,KAAMH,IAMvBH,EAAAO,wBAA0B,IAC/BH,EAAgBC,OACd,CAAC,WACD,CAACT,EAA0BY,wBAQxBR,EAAAS,2BAA6B,CAClCN,EACAO,IAEAN,EAAgBC,OACd,CAAC,UAAW,YAAa,WACzB,CAACV,EAAmBgB,4BAA6BR,EAAWO,IAQzDV,EAAAY,0BAA4B,CACjCC,EACAC,IAEAV,EAAgBC,OACd,CAAC,UAAW,UAAW,WACvB,CACEV,EAAmBoB,2BACnBF,EACAC,IASCd,EAAAgB,6BAA+B,CACpCC,EACAC,IAEAd,EAAgBC,OACd,CAAC,UAAW,UAAW,WACvB,CACER,EAAmBsB,+B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qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,uEAGJI,SAAU,CACR,qEAAsE,CACpEC,KAAM,4BACNC,SAAS,GAEX,qEAAsE,CACpED,KAAM,4BACNC,SAAS,GAEX,qEAAsE,CACpED,KAAM,sBACNC,SAAS,GAEX,qEAAsE,CACpED,KAAM,sBACNC,SAAS,KAogBb,CAACtB,GAAQgC,SA/fkB,CAC3B5B,OAAQ,CACN6B,OAAQ,CACNN,GAAI,qEACJC,GAAI,sEAENM,QAAS,CACPP,GAAI,qEACJC,GAAI,sEAENO,KAAM,CACJA,KAAM,qEACNC,UACE,uEAGN/B,WAAY,CACVC,QAAS,GACTC,QAAS,GACTC,eAAgB,GAElBC,cAAe,6CACfC,YAAa,6CACbC,YAAa,CACXC,SAAU,IAEZC,UAAW,CAAC,IACZC,kBAAmB,CACjB,UACA,aACA,SACA,gBACA,QACA,SAEFC,OAAQ,CACNC,UAAW,CACT,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,uEAGJC,WAAY,CACVD,UAAW,CAAC,KAEdE,UAAW,CACT,6CAA8C,qBAC9C,6CAA8C,eAC9C,6CAA8C,aAC9C,6CAA8C,aAC9C,6CAA8C,6BAC9C,6CAA8C,6BAC9C,6CAA8C,cAC9C,6CAA8C,cAC9C,6CAA8C,aAC9C,6CAA8C,uBAC9C,6CAA8C,gBAEhDC,SAAU,CACRH,UAAW,CACT,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,qEACA,uEAGJI,SAAU,CAAE,GAwZZ,CAACpB,GAAQqC,UArZmB,CAC5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