@berachain/berajs 0.2.1 → 0.2.3
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/dist/actions/exports.d.cts +3 -3
- package/dist/actions/exports.d.ts +3 -3
- package/dist/{getValidatorQueuedOperatorAddress-Dstyaomr.d.cts → getValidatorQueuedOperatorAddress-D_LEt3vv.d.cts} +1 -1
- package/dist/{getValidatorQueuedOperatorAddress-RW4OMcD1.d.ts → getValidatorQueuedOperatorAddress-NrjpnEn8.d.ts} +1 -1
- package/dist/{global.d-CN6l2b9E.d.cts → global.d-DLRtrPG5.d.cts} +1 -0
- package/dist/{global.d-wYu8G8IQ.d.ts → global.d-X3cqpCEB.d.ts} +1 -0
- package/dist/hooks/exports.cjs +3 -3
- package/dist/hooks/exports.cjs.map +1 -1
- package/dist/hooks/exports.d.cts +26 -4
- package/dist/hooks/exports.d.ts +26 -4
- package/dist/hooks/exports.mjs +3 -3
- package/dist/hooks/exports.mjs.map +1 -1
- package/dist/types/exports.d.cts +1 -1
- package/dist/types/exports.d.ts +1 -1
- package/package.json +6 -6
- package/src/hooks/pol/useStakedData.ts +169 -92
- package/src/types/pol.d.ts +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/hooks/exports.cjs","../../src/hooks/bend/useGetConvertToAssets.ts","../../src/hooks/dex/useAggregatorsQuotes.ts","../../src/actions/dex/aggregators/bex.ts","../../src/actions/dex/aggregators/bgt.ts","../../src/actions/dex/aggregators/enso/enso.ts","../../src/hooks/dex/useLiquidityMismatch.ts","../../src/hooks/tokens/useTokenCurrentPrices.ts"],"names":["useGetConvertToAssets","sharesAmount","vaultAddress","vaultChainId","options","publicClient","usePublicClient","swrResponse","useSWR","_","assertPublicClient","getConvertToAssets","DEFAULT_DEADLINE","STALE_PRICE_THRESHOLD","swapKind","SwapKind","BexAggregator","BaseAggregator","ChainId","getUriFromLink","address","isToken","priceImpact","onChainAmount","sorPaths","sorAmount","queryData","deltaFromSorAmount","formatEther","error","BeraError","p","BeraMonitoring","args","balancerApi","BalancerApi","tokenIn","tokenOut","amount","slippage","account","zeroAddress","wberaIsBera","tokenInV3","Token","tokenOutV3","tokenAmount","TokenAmount","RequestError","swap","Swap","queryOutput","callData","Slippage","params","functionName","decodeFunctionData","balancerVaultAbi","bex","RedeemBgtAggregator","beraToken","InvalidArgumentError","bgtRedeem","EnsoAggregator","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees"],"mappings":"AAAA,wnDAAiE,yDAAspB,yDAAgG,yDAAwE,yDAAkD,iCAA8B,iCAA8B,iCAA8B,iCAA8B,yDAA2C,yDAAgF,yDAAmD,yDAAkF,iCAA8B,yDAAgE,yDAAwD,oECA56C,+CAEa,IAOnBA,EAAAA,CAAwB,CACnC,CACE,YAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CACAC,CAAAA,CAAAA,EACG,CACH,IAAMC,CAAAA,CAAeC,oCAAAA,CAAkB,OAAA,CAASH,CAAa,CAAC,CAAA,CACxDI,CAAAA,CAAcC,2BAAAA,CAClBH,EAAgBJ,CAAAA,EAAgBC,CAAAA,CAC5B,CAAC,uBAAA,CAAyBD,CAAAA,CAAcC,CAAAA,CAAcC,CAAY,CAAA,CAClE,IAAA,CACJ,KAAA,CAAO,CAACM,CAAAA,CAAGR,CAAAA,CAAcC,CAAY,CAAA,CAAA,EAAA,CACnCQ,iCAAAA,CAA+B,CAAA,CAExBC,iCAAAA,CACL,YAAA,CAAAV,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,YAAA,CAAAG,CACF,CAAC,CAAA,CAAA,CAEH,CACE,mBAAGD,CAAAA,6BAAS,MACd,CACF,CAAA,CAEA,MAAO,CACL,GAAGG,CAAAA,CACH,OAAA,CAAS,CAA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,CAAAA,CACA0B,CACF,CAAA,CAEA,IAAA,CAAK,GAAA,CAAMC,CAAAA,CACP,kCAAA,CACA,CAAA,EAAA;ACuHS,gEAAA;ACnKjB,mFAAA","file":"/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/hooks/exports.cjs","sourcesContent":[null,"import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport type { GetConvertToAssetsProps } from \"~/actions/bend/getConvertToAssets\";\nimport { getConvertToAssets } from \"~/actions/bend/getConvertToAssets\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\n\nexport const useGetConvertToAssets = (\n {\n sharesAmount,\n vaultAddress,\n vaultChainId,\n }: Omit<GetConvertToAssetsProps, \"publicClient\"> & { vaultChainId?: number },\n options?: DefaultHookOptions,\n) => {\n const publicClient = usePublicClient({ chainId: vaultChainId });\n const swrResponse = useSWR(\n publicClient && sharesAmount && vaultAddress\n ? [\"useGetConvertToAssets\", sharesAmount, vaultAddress, vaultChainId]\n : null,\n async ([_, sharesAmount, vaultAddress]) => {\n assertPublicClient(publicClient);\n\n return getConvertToAssets({\n sharesAmount,\n vaultAddress,\n publicClient,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n};\n","import { useMemo } from \"react\";\nimport { type Address, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { bex } from \"~/actions/dex/aggregators/bex\";\nimport { bgtRedeem } from \"~/actions/dex/aggregators/bgt\";\nimport { enso } from \"~/actions/dex/aggregators/enso/enso\";\nimport { erc4626Deposit } from \"~/actions/dex/aggregators/erc4626\";\nimport { fly } from \"~/actions/dex/aggregators/fly\";\nimport { haiku } from \"~/actions/dex/aggregators/haiku\";\nimport { honeyNative } from \"~/actions/dex/aggregators/honey\";\nimport { kyberswap } from \"~/actions/dex/aggregators/kyberswap\";\nimport { oogabooga } from \"~/actions/dex/aggregators/oogabooga\";\nimport { openOcean } from \"~/actions/dex/aggregators/openOcean\";\nimport { wberaSwap } from \"~/actions/dex/aggregators/wbera\";\nimport { useBeraFlag } from \"~/contexts/BeraFlags/BeraFlags\";\nimport type { HoneyConfigContextReturn } from \"~/contexts/HoneyConfigProvider\";\nimport type { SwapReferrer } from \"~/enum/dex\";\nimport { useAggregatorsRouterFeeBps } from \"~/hooks/dex/useAggregatorsRouterFeeBps\";\nimport type { IRawAggregatorQuote, MinimalERC20 } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { isToken } from \"~/utils/tokens\";\nimport { useUnderlyingAsset } from \"../tokens/useUnderlyingAsset\";\nimport { useBexStatus } from \"./useBexStatus\";\nimport {\n getAggregatorsSWROptions,\n raw_useSingleAggregatorQuote,\n} from \"./useSingleAggregatorQuote\";\n\nconst AGGREGATORS = [\n oogabooga,\n fly,\n kyberswap,\n openOcean,\n haiku,\n enso,\n bex,\n honeyNative,\n erc4626Deposit,\n];\n\ntype IUseAggregatorsQuotesArgs = BeraJS.BaseFunctionArgs & {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n amount: string;\n slippage: number;\n referrer?: SwapReferrer;\n rewardVault?: Address;\n /**\n * Useful cause the collaterals are provided byt he honeyContext and this way we can\n * use the Provider only in the swap page where is needed.\n *\n * The collaterals for the honey mint/redeem aggregator.\n */\n honeyNativeState?: Pick<\n HoneyConfigContextReturn,\n \"collateralList\" | \"protocol\"\n >;\n};\n\nexport function useAggregatorsQuotes(\n args: IUseAggregatorsQuotesArgs,\n options?: DefaultHookOptions,\n) {\n const { address: account } = useBeraWallet();\n const proxyAggregatorsThroughVercel = useBeraFlag(\n \"proxyAggregatorsThroughVercel\",\n );\n const activeAggregators = useBeraFlag(\"aggregators\");\n const publicClient = usePublicClient();\n const { data: feeBps } = useAggregatorsRouterFeeBps();\n\n const isWrapOrUnwrap =\n (isToken(args.tokenIn.address, \"BERA\") ||\n isToken(args.tokenIn.address, \"WBERA\")) &&\n (isToken(args.tokenOut.address, \"BERA\") ||\n isToken(args.tokenOut.address, \"WBERA\"));\n\n const isBgtRedeem = isToken(args.tokenIn.address, \"BGT\", {\n chainId: defaultChainId,\n });\n\n const { data: underlyingToken } = useUnderlyingAsset({\n token: args.tokenOut,\n });\n\n /**\n * Whether it's a native swap (wrap/unwrap) or BGT redeem\n */\n const isNativeSwap = isWrapOrUnwrap || isBgtRedeem;\n\n const { config } = parseBaseArgs(args);\n\n const isMAEnabled = config.bex.aggregatorsRouter !== zeroAddress;\n\n const swrOptions = getAggregatorsSWROptions(options);\n\n const sharedArgs = {\n activeAggregators,\n isMAEnabled,\n underlyingToken,\n isNativeSwap,\n account,\n publicClient,\n proxyAggregatorsThroughVercel,\n feeBps,\n } as const;\n\n // we're using independent useSWRs so we can show quotes as they come\n // instead of waiting for all of them to load\n const oogaBogaResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: oogabooga,\n },\n { opts: swrOptions },\n );\n\n const flyResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: fly,\n },\n { opts: swrOptions },\n );\n\n const erc4626Result = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: erc4626Deposit,\n },\n { opts: swrOptions },\n );\n\n const kyberswapResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: kyberswap,\n },\n { opts: swrOptions },\n );\n\n const openOceanResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: openOcean,\n },\n { opts: swrOptions },\n );\n\n const haikuResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: haiku,\n },\n { opts: swrOptions },\n );\n\n const ensoResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: enso,\n },\n { opts: swrOptions },\n );\n\n const { protocol: bexProtocol } = useBexStatus();\n\n const bexResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: bex,\n },\n { opts: { ...swrOptions, isEnabled: bexProtocol.isPaused === false } },\n );\n\n const wberaSwapResult = raw_useSingleAggregatorQuote({\n ...sharedArgs,\n ...args,\n aggregator: wberaSwap,\n });\n\n const bgtRedeemResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: bgtRedeem,\n },\n { opts: swrOptions },\n );\n\n const honeyResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: honeyNative,\n },\n { opts: swrOptions },\n );\n\n const results = isWrapOrUnwrap\n ? [wberaSwapResult]\n : isBgtRedeem\n ? [bgtRedeemResult]\n : [\n oogaBogaResult,\n erc4626Result,\n flyResult,\n kyberswapResult,\n openOceanResult,\n haikuResult,\n ensoResult,\n honeyResult,\n bexProtocol.isPaused === false ? bexResult : null,\n ].filter((i): i is NonNullable<typeof i> => i !== null);\n\n const data = useMemo(() => {\n const error = results.reduce<(typeof results)[number][\"error\"]>(\n (error, result) => error || result.error,\n undefined,\n );\n\n const loadingAggregatorsNames = results\n .map((r, i) =>\n r.isLoading\n ? isNativeSwap\n ? wberaSwap.name\n : AGGREGATORS[i].name\n : null,\n )\n .filter(Boolean);\n\n const quotes = results\n .filter(\n (result) =>\n result !== undefined &&\n !result.isLoading &&\n !result.error &&\n result.data?.amountOut,\n )\n .map(({ data }) => data) as IRawAggregatorQuote[];\n\n const isLoading = quotes.length === 0 && loadingAggregatorsNames.length > 0;\n return { quotes, loadingAggregatorsNames, isLoading, error };\n }, [results]);\n\n return {\n ...data,\n refresh: () => results.map((r) => r.mutate()),\n };\n}\n","import {\n type Address,\n Slippage,\n type SorSwapResult,\n Swap,\n SwapKind,\n Token,\n TokenAmount,\n} from \"@berachain-foundation/berancer-sdk\";\nimport { decodeFunctionData, formatEther, zeroAddress } from \"viem\";\n\nimport { getUriFromLink } from \"@berachain/config\";\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { balancerVaultAbi } from \"~/abi/bex/balancerVault\";\nimport { BalancerApi } from \"~/actions/dex/b-sdk\";\nimport { Aggregators } from \"~/enum/dex\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { BeraMonitoring } from \"~/errors/BeraMonitoring\";\nimport { RequestError } from \"~/errors/RequestError\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\nimport { isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\n// Constants\nconst DEFAULT_DEADLINE = 60 * 5; // default transaction deadline in seconds\nconst STALE_PRICE_THRESHOLD = 0.05; // 5% threshold for stale prices\nconst swapKind = SwapKind.GivenIn;\n\nclass BexAggregator extends BaseAggregator {\n name = Aggregators.HubPools;\n supportedChains = [ChainId.MAINNET, ChainId.BEPOLIA];\n readonly url = getUriFromLink(this.config.api);\n readonly type = \"graphql\";\n\n /**\n * Helper function to convert zero address to wrapped token address\n */\n private convertZeroToWrapped(address: Address): Address {\n return isToken(address, \"BERA\") ? this.config.tokens.wbera : address;\n }\n\n /**\n * Helper to calculate price impact percentage\n */\n private calculatePriceImpact(priceImpact: {\n error: string | null;\n priceImpact?: string;\n }): number {\n if (priceImpact.error) {\n console.error(\"Swap price impact error\", priceImpact);\n return 0;\n }\n\n return Number(priceImpact.priceImpact);\n }\n\n /**\n * Helper to check for stale SOR prices\n */\n private checkStalePrices({\n onChainAmount,\n sorPaths,\n sorAmount,\n queryData,\n }: {\n onChainAmount: TokenAmount;\n sorPaths: { pools: string[] }[];\n sorAmount: string;\n queryData: IAggregatorArgs;\n }): void {\n // Check for stale prices\n const deltaFromSorAmount =\n Number.parseFloat(formatEther(onChainAmount.scale18)) /\n Number.parseFloat(sorAmount);\n\n if (Math.abs(1 - deltaFromSorAmount) > STALE_PRICE_THRESHOLD) {\n console.warn(\n \"SOR returned stale prices. Delta from return amount is more than 5%\",\n {\n deltaFromSorAmount,\n },\n );\n\n const error = new BeraError({\n reason: \"SOR_STALE_PRICES\",\n level: \"warning\",\n message:\n \"SOR returned stale prices. Delta from return amount is more than 5%\",\n extra: {\n deltaFromSorAmount,\n pools: sorPaths.map((p) => p.pools),\n onChainAmount: formatEther(onChainAmount.scale18),\n sorAmount,\n queryData,\n },\n fingerprint: [\"SOR_STALE_PRICES\"],\n });\n BeraMonitoring.captureException(error);\n }\n }\n\n async getQuote(args: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n const balancerApi = new BalancerApi(\n this.url,\n // @ts-expect-error b-sdk has more chains than berajs\n this.chainId,\n );\n const {\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n publicClient,\n } = args;\n this.assertChainSupport({ tokenIn, tokenOut });\n\n assertPublicClient(publicClient);\n\n const wberaIsBera = isToken(tokenIn, \"BERA\") || isToken(tokenOut, \"BERA\");\n\n // Initialize tokens\n const tokenInV3 = new Token(\n this.chainId,\n this.convertZeroToWrapped(tokenIn.address),\n tokenIn.decimals,\n );\n const tokenOutV3 = new Token(\n this.chainId,\n this.convertZeroToWrapped(tokenOut.address),\n tokenOut.decimals,\n );\n\n const tokenAmount = TokenAmount.fromRawAmount(\n tokenInV3,\n amount as `${number}`,\n );\n\n // swap paths\n const {\n paths: sorPaths,\n priceImpact,\n returnAmount: sorAmount,\n }: SorSwapResult = await balancerApi.sorSwapPaths.fetchSorSwapPaths({\n // @ts-expect-error b-sdk has more chains than berajs\n chainId: this.chainId,\n tokenIn: tokenInV3.address,\n tokenOut: tokenOutV3.address,\n swapKind,\n swapAmount: tokenAmount,\n });\n\n if (!sorPaths?.length) {\n throw new RequestError({\n response: undefined,\n endpoint: {\n url: this.url,\n name: this.name,\n type: this.type,\n },\n reason: BaseAggregator.PATH_NOT_FOUND_REASON,\n chainId: this.chainId,\n payload: {\n tokenIn: tokenInV3.address,\n tokenOut: tokenOutV3.address,\n swapKind,\n swapAmount: tokenAmount,\n },\n message: `No swap paths returned from Balancer API`,\n });\n }\n\n // execute swap query\n const swap = new Swap({\n chainId: this.chainId,\n paths: sorPaths,\n swapKind,\n userData: \"0x\" as `0x${string}`,\n });\n const queryOutput = await swap.query(publicClient.transport.url);\n\n if (!(\"expectedAmountOut\" in queryOutput)) {\n throw new Error(\"No Bex paths found\");\n }\n\n this.checkStalePrices({\n onChainAmount: queryOutput.expectedAmountOut,\n sorPaths,\n sorAmount,\n queryData: args,\n });\n\n // format quote response\n return {\n amountOut: queryOutput.expectedAmountOut.amount.toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: queryOutput.to,\n }),\n name: this.name,\n priceImpactPercentage: this.calculatePriceImpact(priceImpact),\n swapFeeBps: 0,\n getCalldata: ({ account }) => {\n // generate user transaction data\n const callData = swap.buildCall({\n slippage: Slippage.fromPercentage(slippage.toString() as `${number}`),\n deadline: BigInt(Math.round(Date.now() / 1000) + DEFAULT_DEADLINE),\n queryOutput,\n sender: account as Address,\n recipient: account as Address,\n wethIsEth: wberaIsBera,\n });\n\n const { args: params, functionName } = decodeFunctionData({\n abi: balancerVaultAbi,\n data: callData.callData,\n });\n\n return {\n params,\n functionName,\n abi: balancerVaultAbi,\n address: callData.to,\n value: callData.value || BigInt(0),\n };\n },\n };\n }\n}\n\nexport const bex = new BexAggregator();\n","import { ChainId } from \"@berachain/config/internal\";\n\nimport { Aggregators } from \"~/enum/dex\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n MinimalERC20,\n} from \"~/types/dex\";\nimport { beraToken, isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\nclass RedeemBgtAggregator extends BaseAggregator {\n name = Aggregators.RedeemBgt;\n supportedChains = [ChainId.MAINNET, ChainId.BEPOLIA];\n readonly type = \"rpc\";\n\n checkChainSupport({\n tokenIn,\n tokenOut,\n }: {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n }): boolean {\n if (!super.checkChainSupport({ tokenIn, tokenOut })) {\n return false;\n }\n\n return (\n // only supported on same chain\n tokenIn.chainId === tokenOut.chainId &&\n isToken(tokenIn, \"BGT\", { chainId: tokenIn.chainId }) &&\n isToken(tokenOut, \"BERA\")\n );\n }\n // handles native swaps: wrap and unwrap\n async getQuote({\n tokenIn,\n amount,\n }: Omit<\n IAggregatorArgs,\n \"slippage\" | \"feeBps\" | \"tokenOut\" | \"account\"\n >): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({\n tokenIn,\n tokenOut: { ...beraToken, chainId: tokenIn.chainId },\n });\n\n if (!isToken(tokenIn, \"BGT\", { config: this.config })) {\n throw new InvalidArgumentError({\n property: \"tokenIn\",\n value: tokenIn,\n expected: \"BGT\",\n level: \"warning\",\n });\n }\n\n return {\n amountOut: amount,\n amountIn: amount,\n allowanceRequirements: [],\n name: Aggregators.RedeemBgt,\n isNativeSwap: true,\n swapFeeBps: 0,\n // not adding calldata here because it depends on the connected wallet\n // bgt redeem requires a receiver address\n // moreover this is a sensitive operation, better be sure of what data is being sent\n // by controlling it on the consumer side\n } as const;\n }\n}\n\nexport const bgtRedeem = new RedeemBgtAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { aggregatorsRouterAbi } from \"~/abi/bex/aggregatorsRouter\";\nimport { Aggregators } from \"~/enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\nimport { BaseAggregator } from \"../base\";\n\nexport class EnsoAggregator extends BaseAggregator {\n name = Aggregators.Enso;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n needsAccountForQuote = true;\n\n notFoundMessages: string[] = [\n \"Could not build shortcuts for route\",\n \"Could not quote shortcuts for route\",\n \"Swap not found for a required underlying of defi route,\",\n \"No route found from\",\n ];\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=enso`\n : `${this.config.bex.aggregatorsProxyUrl}/enso/api/v1/shortcuts/route?`;\n\n const url = new URL(this.url);\n url.searchParams.set(\n \"fromAddress\",\n this.config.bex.aggregatorsRouterExecutor,\n );\n url.searchParams.set(\"receiver\", this.config.bex.aggregatorsRouterExecutor);\n url.searchParams.set(\"spender\", this.config.bex.aggregatorsRouterExecutor);\n url.searchParams.set(\"amountIn\", inputAmountAfterFees);\n url.searchParams.set(\"tokenIn\", tokenInAddress);\n url.searchParams.set(\"tokenOut\", tokenOutAddress);\n url.searchParams.set(\"chainId\", ChainId.MAINNET.toString());\n url.searchParams.set(\"slippage\", (Number(slippage) * 100).toString());\n url.searchParams.set(\"refundReceiver\", account);\n\n const response = await this.fetch(url);\n\n const quote = await response.json();\n\n const inputData = this.getInputData({\n tokenIn: tokenInAddress,\n amountIn: amount,\n isNative: isTokenInNative,\n });\n\n const outputData = {\n tokenOut: tokenOutAddress,\n receiver: account,\n minAmountOut: this.getMinAmountOut(quote.amountOut.toString(), slippage),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quote.tx?.to,\n data: quote.tx?.data,\n };\n\n return {\n amountOut: quote.amountOut.toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n getCalldata: () => ({\n params: [\n inputData,\n outputData,\n aggregatorData,\n {\n rewardVault: rewardVault ?? zeroAddress,\n isSwapAndStake: !!rewardVault,\n },\n ],\n functionName: \"swap\",\n abi: aggregatorsRouterAbi,\n // send full amount to router first, which will deduct the swap fee before executing trade\n value: isTokenInNative ? BigInt(amount) : BigInt(\"0\"),\n address: this.config.bex.aggregatorsRouter,\n }),\n };\n }\n}\n\nexport const enso = new EnsoAggregator();\n","import { useEffect, useState } from \"react\";\nimport { PoolType } from \"@berachain-foundation/berancer-sdk\";\n\nimport { PoolCreationStep } from \"~/enum/dex\";\nimport type { TokenCurrentPriceMap, TokenWithAmount } from \"~/types/dex\";\nimport { wrapNativeTokens } from \"~/utils/tokenWrapping\";\nimport { type Oracle, OracleMode } from \"./useCreatePool\";\n\nconst DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT = 0.05; // 5%\n\nexport type LiquidityMismatchInfo = {\n title: string | null;\n message: string | null;\n suggestWeighted?: boolean;\n};\n\ninterface UseLiquidityMismatchParams {\n currentStep: PoolCreationStep;\n tokenPrices?: TokenCurrentPriceMap;\n isLoadingTokenPrices: boolean;\n tokens: TokenWithAmount[] | null;\n weights: bigint[] | null;\n weightsError: string | null;\n poolType: PoolType;\n liquidityMismatchTolerancePercent?: number;\n oracles: Oracle[];\n}\n\n/**\n * Hook for detecting liquidity mismatches.\n *\n * @param {PoolCreationStep} currentStep - The current step of the pool creation process.\n * @param {Record<string, number>} tokenPrices - The current token prices.\n * @param {boolean} isLoadingTokenPrices - Whether the token prices are still loading.\n * @param {Array<{ address: string, amount: number }>} tokens - The tokens in the pool, including their addresses and amounts.\n * @param {Record<string, number>} weights - The per-token weights in the pool we are creating.\n * @param {string | null} weightsError - An error message for the weights indicating that the weights are invalid.\n * @param {string} poolType - The type of pool being created.\n * @param {number} liquidityMismatchTolerancePercent - The tolerance for liquidity mismatches in percent.\n * @returns {Object} The liquidity mismatch info.\n */\nexport const useLiquidityMismatch = ({\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent = DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT,\n oracles,\n}: UseLiquidityMismatchParams): LiquidityMismatchInfo => {\n // NOTE: would be nice to use Maps/Records more in here, as the zipping/unzipping is cumbersome.\n // NOTE: if we pull in string literal for currentStep things would also be a bit clearer in here.\n const [liquidityMismatchInfo, setLiquidityMismatchInfo] =\n useState<LiquidityMismatchInfo>({ title: null, message: null });\n\n useEffect(() => {\n // If we are either using custom rate-providing oracles or have incorrect/loading token prices, we cant do validation.\n if (\n !tokenPrices ||\n isLoadingTokenPrices ||\n !tokens ||\n !weights ||\n weightsError ||\n tokens.some((token) => !token.address) ||\n oracles.some((oracle) => oracle.mode === OracleMode.Custom) // Oracles give prices on their own, we dont support that here yet.\n ) {\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Calculate some basic metrics we'll use to determine per-token contributions and model potential losses from arbitrage.\n let totalLiquidityUSD = 0;\n const tokenUSDAmounts: number[] = [];\n const numTokens = tokens.length;\n const wrappedTokens = wrapNativeTokens(tokens);\n const tokenUSDPrices = wrappedTokens.map((token) => {\n const tokenPriceUSD =\n tokenPrices[token.address.toLowerCase()]?.price ?? 0;\n if (!tokenPriceUSD || tokenPriceUSD === 0) {\n tokenUSDAmounts.push(0);\n return null;\n }\n const tokenAmountUSD = tokenPriceUSD * Number.parseFloat(token.amount);\n tokenUSDAmounts.push(tokenAmountUSD);\n totalLiquidityUSD += tokenAmountUSD;\n return tokenPriceUSD;\n });\n\n // Doesn't matter what step it is, if we have missing token prices for tokens we have selected, we cant issue a real warning.\n if (\n tokenUSDPrices.some((price) => price === null) ||\n tokenUSDPrices.length !== numTokens\n ) {\n setLiquidityMismatchInfo({\n title: \"Missing token price data\",\n message: `One or more token(s) do not have valid market price data. Please verify that token market prices align with the pool\n weightings and your initial liquidity amounts.`,\n });\n return;\n }\n\n // Step 1 - During token selection we check for a deviation in the quote prices of the tokens selected (for stable pools).\n if (\n currentStep === PoolCreationStep.SELECT_TOKENS &&\n poolType === PoolType.ComposableStable\n ) {\n const normalizedUSDPrices = tokenUSDPrices.map(\n (priceUSD) => priceUSD! / tokenUSDPrices[0]!, // always normalize on the first token's price\n );\n const maxDifference =\n Math.max(...normalizedUSDPrices) - Math.min(...normalizedUSDPrices);\n\n if (maxDifference > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n title: \"Selected tokens have a significant price deviation\",\n message: \"Did you mean to create a Weighted pool instead?\",\n suggestWeighted: true,\n });\n } else {\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n\n return;\n }\n\n // Validation During Liquidity Input and onwards.\n if (\n totalLiquidityUSD === 0 ||\n tokenUSDAmounts.some((value) => value === 0)\n ) {\n // User has not yet entered fully their liquidity values, so return early.\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Simulate arbitrage for the pool to determine potential losses from arbitrageurs.\n // NOTE: we assume shortfalls and excesses are losses, but in reality the actual losses would be more complex to realise.\n // Balancer does this similarily https://github.com/balancer/frontend-v2/blob/8563b8d33b6bff266148bd48d7ebc89f921374f4/src/components/cards/CreatePool/InitialLiquidity.vue#L75\n let totalLossUSD = 0;\n if (poolType === PoolType.ComposableStable) {\n const expectedPerTokenLiquidityUSD = totalLiquidityUSD / numTokens;\n tokenUSDAmounts.forEach((value) => {\n totalLossUSD += Math.abs(expectedPerTokenLiquidityUSD - value);\n });\n } else if (poolType === PoolType.Weighted) {\n tokenUSDAmounts.forEach((value, index) => {\n const weightProportion = Number(weights[index]) / 1e18;\n const expectedValueUSD = totalLiquidityUSD * weightProportion;\n totalLossUSD += Math.abs(expectedValueUSD - value);\n });\n }\n\n // We'll show a total loss if it's 90% or more\n const isTotalLoss = totalLossUSD >= totalLiquidityUSD * 0.9;\n totalLossUSD = Math.min(totalLossUSD, totalLiquidityUSD);\n const totalLossPercentage = totalLossUSD / totalLiquidityUSD;\n\n if (totalLossPercentage > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n // If it's a total loss we dont display a percentage\n title: isTotalLoss\n ? \"You could lose all of your initial liquidity\"\n : `You could lose $${totalLossUSD.toFixed(2)} (~${(\n totalLossPercentage * 100\n ).toFixed(2)}%)`,\n message: `Based on the market token prices, the value of tokens does not align with the specified pool weights. \n This discrepancy could expose you to potential losses from arbitrageurs. ${\n poolType === PoolType.ComposableStable\n ? \"Did you mean to create a Weighted pool instead?\"\n : \"\"\n }`,\n suggestWeighted: poolType === PoolType.ComposableStable,\n });\n } else {\n // All good bb bb\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n }, [\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent,\n oracles,\n ]);\n return liquidityMismatchInfo;\n};\n","import { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport { type Address, isAddress, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { getTokenCurrentPrices } from \"~/actions/prices/getTokenCurrentPrices\";\nimport { POLLING } from \"~/enum/polling\";\nimport { useTokens } from \"~/hooks/tokens/useTokens\";\nimport type { TokenCurrentPriceMap, TokenWithPrice } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { isToken } from \"~/utils/tokens\";\n\n/**\n * @deprecated use useTokenPrices instead that supports multichain tokens\n */\nexport function useTokenCurrentPrices(\n {\n addressIn,\n }: {\n addressIn?: string[] | readonly string[];\n } = {},\n options: DefaultHookOptions = {\n opts: {\n refreshInterval: POLLING.NORMAL,\n revalidateOnFocus: true,\n },\n },\n) {\n const { tokenList, ensoTokens } = useTokens();\n\n /**\n * Berachain or Bepolia Tokens. All tokens from other chains are excluded since API doesn't price them.\n */\n const beraAddresses = useMemo<Address[]>(() => {\n const addresses: Address[] = [];\n\n if (addressIn) {\n addresses.push(\n ...(addressIn.filter((a): a is Address => isAddress(a)) as Address[]),\n );\n }\n return addresses.map((a) => a.toLowerCase() as Address);\n }, [tokenList]);\n\n const hasAddressesNotInTokenList = useMemo(() => {\n const tokenSet = new Set(\n tokenList?.map((token) => token.address.toLowerCase() as Address),\n );\n // Native BERA (zero address) is priced via WBERA in getTokenCurrentPrices.\n // Treat zero address as \"known\" whenever WBERA exists in token list.\n if (tokenList.some((token) => isToken(token, \"WBERA\"))) {\n tokenSet.add(zeroAddress);\n }\n\n return beraAddresses?.some((a) => !tokenSet.has(a));\n }, [beraAddresses, tokenList]);\n\n /**\n * If no addressIn is provided, use default token list\n * If all addressIn are in the token list, use default token list\n * If some addressIn are not in the token list, use addressIn\n */\n const addresses = hasAddressesNotInTokenList\n ? beraAddresses\n : tokenList.map((token) => token.address);\n\n const QUERY_KEY =\n addresses && (options.opts?.isEnabled ?? true)\n ? ([\n \"useTokenCurrentPrices\",\n addresses.map((a) => a.toLowerCase() as Address),\n ] as const)\n : null;\n\n const apiResponse = useSWR(\n QUERY_KEY,\n async ([, addresses]) => {\n // this only works for Berachain tokens\n return getTokenCurrentPrices({ addressIn: addresses });\n },\n options.opts,\n );\n\n const ensoMatchingPrices = useMemo<TokenCurrentPriceMap>(() => {\n if (!ensoTokens) return {};\n\n const ensoPricesMap = new Map<number, Map<Address, TokenWithPrice>>([\n [defaultChainId, new Map()],\n ]);\n\n for (const token of ensoTokens) {\n if (token.price === undefined || token.chainId !== defaultChainId)\n continue;\n\n ensoPricesMap\n .get(defaultChainId)\n ?.set(token.address.toLowerCase() as Address, {\n ...token,\n price: token.price,\n chainId: defaultChainId,\n });\n }\n\n return Object.fromEntries(\n addresses.map((address) => {\n const price = ensoPricesMap.get(defaultChainId)?.get(address)?.price;\n\n if (!price) return [null, null];\n\n return [\n address.toLowerCase() as Address,\n {\n price,\n chainId: defaultChainId,\n updatedAt: Date.now(),\n },\n ];\n }),\n );\n }, [ensoTokens]);\n\n const data = useMemo(\n () => ({\n ...ensoMatchingPrices,\n // in this deprecated hook, we let api override enso prices, since there's no multichain support\n ...apiResponse.data,\n }),\n [ensoMatchingPrices, apiResponse.data],\n );\n\n return {\n ...apiResponse,\n data,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/hooks/exports.cjs","../../src/hooks/bend/useGetConvertToAssets.ts","../../src/hooks/dex/useAggregatorsQuotes.ts","../../src/actions/dex/aggregators/bex.ts","../../src/actions/dex/aggregators/bgt.ts","../../src/actions/dex/aggregators/enso/enso.ts","../../src/hooks/dex/useLiquidityMismatch.ts","../../src/hooks/tokens/useTokenCurrentPrices.ts"],"names":["useGetConvertToAssets","sharesAmount","vaultAddress","vaultChainId","options","publicClient","usePublicClient","swrResponse","useSWR","_","assertPublicClient","getConvertToAssets","DEFAULT_DEADLINE","STALE_PRICE_THRESHOLD","swapKind","SwapKind","BexAggregator","BaseAggregator","ChainId","getUriFromLink","address","isToken","priceImpact","onChainAmount","sorPaths","sorAmount","queryData","deltaFromSorAmount","formatEther","error","BeraError","p","BeraMonitoring","args","balancerApi","BalancerApi","tokenIn","tokenOut","amount","slippage","account","zeroAddress","wberaIsBera","tokenInV3","Token","tokenOutV3","tokenAmount","TokenAmount","RequestError","swap","Swap","queryOutput","callData","Slippage","params","functionName","decodeFunctionData","balancerVaultAbi","bex","RedeemBgtAggregator","beraToken","InvalidArgumentError","bgtRedeem","EnsoAggregator","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees"],"mappings":"AAAA,wnDAAiE,yDAAspB,yDAAgG,yDAAwE,yDAAmD,iCAA8B,iCAA8B,iCAA8B,iCAA8B,yDAA2C,yDAAgF,yDAAmD,yDAAkF,iCAA8B,yDAAgE,yDAAwD,oECA76C,+CAEa,IAOnBA,EAAAA,CAAwB,CACnC,CACE,YAAA,CAAAC,CAAAA,CACA,YAAA,CA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ACb,OAAA,CAAAkB,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAAUC,iBAAAA,CACV,iBAAA,CAAAuB,CAAAA,CACA,6BAAA,CAAAC,CAAAA,CAAgC,CAAA,CAAA,CAChC,WAAA,CAAAC,CACF,CAAA,CAAkD,CAChD,IAAA,CAAK,kBAAA,CAAmB,CAAE,OAAA,CAAA9B,CAAAA,CAAS,QAAA,CAAAC,CAAS,CAAC,CAAA,CAE7C,GAAM,CACJ,cAAA,CAAA8B,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CACF,CAAA,CAAI,IAAA,CAAK,cAAA,CAAelC,CAAAA,CAAQ,OAAA,CAASC,CAAAA,CAAS,OAAO,CAAA,CAEnDkC,CAAAA,CAAuB,IAAA,CAAK,kBAAA,CAChCjC,CAAAA,CACA0B,CACF,CAAA,CAEA,IAAA,CAAK,GAAA,CAAMC,CAAAA,CACP,kCAAA,CACA,CAAA,EAAA;ACuHS,gEAAA;ACnKR,mFAAA","file":"/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/hooks/exports.cjs","sourcesContent":[null,"import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport type { GetConvertToAssetsProps } from \"~/actions/bend/getConvertToAssets\";\nimport { getConvertToAssets } from \"~/actions/bend/getConvertToAssets\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\n\nexport const useGetConvertToAssets = (\n {\n sharesAmount,\n vaultAddress,\n vaultChainId,\n }: Omit<GetConvertToAssetsProps, \"publicClient\"> & { vaultChainId?: number },\n options?: DefaultHookOptions,\n) => {\n const publicClient = usePublicClient({ chainId: vaultChainId });\n const swrResponse = useSWR(\n publicClient && sharesAmount && vaultAddress\n ? [\"useGetConvertToAssets\", sharesAmount, vaultAddress, vaultChainId]\n : null,\n async ([_, sharesAmount, vaultAddress]) => {\n assertPublicClient(publicClient);\n\n return getConvertToAssets({\n sharesAmount,\n vaultAddress,\n publicClient,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n};\n","import { useMemo } from \"react\";\nimport { type Address, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { bex } from \"~/actions/dex/aggregators/bex\";\nimport { bgtRedeem } from \"~/actions/dex/aggregators/bgt\";\nimport { enso } from \"~/actions/dex/aggregators/enso/enso\";\nimport { erc4626Deposit } from \"~/actions/dex/aggregators/erc4626\";\nimport { fly } from \"~/actions/dex/aggregators/fly\";\nimport { haiku } from \"~/actions/dex/aggregators/haiku\";\nimport { honeyNative } from \"~/actions/dex/aggregators/honey\";\nimport { kyberswap } from \"~/actions/dex/aggregators/kyberswap\";\nimport { oogabooga } from \"~/actions/dex/aggregators/oogabooga\";\nimport { openOcean } from \"~/actions/dex/aggregators/openOcean\";\nimport { wberaSwap } from \"~/actions/dex/aggregators/wbera\";\nimport { useBeraFlag } from \"~/contexts/BeraFlags/BeraFlags\";\nimport type { HoneyConfigContextReturn } from \"~/contexts/HoneyConfigProvider\";\nimport type { SwapReferrer } from \"~/enum/dex\";\nimport { useAggregatorsRouterFeeBps } from \"~/hooks/dex/useAggregatorsRouterFeeBps\";\nimport type { IRawAggregatorQuote, MinimalERC20 } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { isToken } from \"~/utils/tokens\";\nimport { useUnderlyingAsset } from \"../tokens/useUnderlyingAsset\";\nimport { useBexStatus } from \"./useBexStatus\";\nimport {\n getAggregatorsSWROptions,\n raw_useSingleAggregatorQuote,\n} from \"./useSingleAggregatorQuote\";\n\nconst AGGREGATORS = [\n oogabooga,\n fly,\n kyberswap,\n openOcean,\n haiku,\n enso,\n bex,\n honeyNative,\n erc4626Deposit,\n];\n\ntype IUseAggregatorsQuotesArgs = BeraJS.BaseFunctionArgs & {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n amount: string;\n slippage: number;\n referrer?: SwapReferrer;\n rewardVault?: Address;\n /**\n * Useful cause the collaterals are provided byt he honeyContext and this way we can\n * use the Provider only in the swap page where is needed.\n *\n * The collaterals for the honey mint/redeem aggregator.\n */\n honeyNativeState?: Pick<\n HoneyConfigContextReturn,\n \"collateralList\" | \"protocol\"\n >;\n};\n\nexport function useAggregatorsQuotes(\n args: IUseAggregatorsQuotesArgs,\n options?: DefaultHookOptions,\n) {\n const { address: account } = useBeraWallet();\n const proxyAggregatorsThroughVercel = useBeraFlag(\n \"proxyAggregatorsThroughVercel\",\n );\n const activeAggregators = useBeraFlag(\"aggregators\");\n const publicClient = usePublicClient();\n const { data: feeBps } = useAggregatorsRouterFeeBps();\n\n const isWrapOrUnwrap =\n (isToken(args.tokenIn.address, \"BERA\") ||\n isToken(args.tokenIn.address, \"WBERA\")) &&\n (isToken(args.tokenOut.address, \"BERA\") ||\n isToken(args.tokenOut.address, \"WBERA\"));\n\n const isBgtRedeem = isToken(args.tokenIn.address, \"BGT\", {\n chainId: defaultChainId,\n });\n\n const { data: underlyingToken } = useUnderlyingAsset({\n token: args.tokenOut,\n });\n\n /**\n * Whether it's a native swap (wrap/unwrap) or BGT redeem\n */\n const isNativeSwap = isWrapOrUnwrap || isBgtRedeem;\n\n const { config } = parseBaseArgs(args);\n\n const isMAEnabled = config.bex.aggregatorsRouter !== zeroAddress;\n\n const swrOptions = getAggregatorsSWROptions(options);\n\n const sharedArgs = {\n activeAggregators,\n isMAEnabled,\n underlyingToken,\n isNativeSwap,\n account,\n publicClient,\n proxyAggregatorsThroughVercel,\n feeBps,\n } as const;\n\n // we're using independent useSWRs so we can show quotes as they come\n // instead of waiting for all of them to load\n const oogaBogaResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: oogabooga,\n },\n { opts: swrOptions },\n );\n\n const flyResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: fly,\n },\n { opts: swrOptions },\n );\n\n const erc4626Result = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: erc4626Deposit,\n },\n { opts: swrOptions },\n );\n\n const kyberswapResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: kyberswap,\n },\n { opts: swrOptions },\n );\n\n const openOceanResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: openOcean,\n },\n { opts: swrOptions },\n );\n\n const haikuResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: haiku,\n },\n { opts: swrOptions },\n );\n\n const ensoResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: enso,\n },\n { opts: swrOptions },\n );\n\n const { protocol: bexProtocol } = useBexStatus();\n\n const bexResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: bex,\n },\n { opts: { ...swrOptions, isEnabled: bexProtocol.isPaused === false } },\n );\n\n const wberaSwapResult = raw_useSingleAggregatorQuote({\n ...sharedArgs,\n ...args,\n aggregator: wberaSwap,\n });\n\n const bgtRedeemResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: bgtRedeem,\n },\n { opts: swrOptions },\n );\n\n const honeyResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: honeyNative,\n },\n { opts: swrOptions },\n );\n\n const results = isWrapOrUnwrap\n ? [wberaSwapResult]\n : isBgtRedeem\n ? [bgtRedeemResult]\n : [\n oogaBogaResult,\n erc4626Result,\n flyResult,\n kyberswapResult,\n openOceanResult,\n haikuResult,\n ensoResult,\n honeyResult,\n bexProtocol.isPaused === false ? bexResult : null,\n ].filter((i): i is NonNullable<typeof i> => i !== null);\n\n const data = useMemo(() => {\n const error = results.reduce<(typeof results)[number][\"error\"]>(\n (error, result) => error || result.error,\n undefined,\n );\n\n const loadingAggregatorsNames = results\n .map((r, i) =>\n r.isLoading\n ? isNativeSwap\n ? wberaSwap.name\n : AGGREGATORS[i].name\n : null,\n )\n .filter(Boolean);\n\n const quotes = results\n .filter(\n (result) =>\n result !== undefined &&\n !result.isLoading &&\n !result.error &&\n result.data?.amountOut,\n )\n .map(({ data }) => data) as IRawAggregatorQuote[];\n\n const isLoading = quotes.length === 0 && loadingAggregatorsNames.length > 0;\n return { quotes, loadingAggregatorsNames, isLoading, error };\n }, [results]);\n\n return {\n ...data,\n refresh: () => results.map((r) => r.mutate()),\n };\n}\n","import {\n type Address,\n Slippage,\n type SorSwapResult,\n Swap,\n SwapKind,\n Token,\n TokenAmount,\n} from \"@berachain-foundation/berancer-sdk\";\nimport { decodeFunctionData, formatEther, zeroAddress } from \"viem\";\n\nimport { getUriFromLink } from \"@berachain/config\";\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { balancerVaultAbi } from \"~/abi/bex/balancerVault\";\nimport { BalancerApi } from \"~/actions/dex/b-sdk\";\nimport { Aggregators } from \"~/enum/dex\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { BeraMonitoring } from \"~/errors/BeraMonitoring\";\nimport { RequestError } from \"~/errors/RequestError\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\nimport { isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\n// Constants\nconst DEFAULT_DEADLINE = 60 * 5; // default transaction deadline in seconds\nconst STALE_PRICE_THRESHOLD = 0.05; // 5% threshold for stale prices\nconst swapKind = SwapKind.GivenIn;\n\nclass BexAggregator extends BaseAggregator {\n name = Aggregators.HubPools;\n supportedChains = [ChainId.MAINNET, ChainId.BEPOLIA];\n readonly url = getUriFromLink(this.config.api);\n readonly type = \"graphql\";\n\n /**\n * Helper function to convert zero address to wrapped token address\n */\n private convertZeroToWrapped(address: Address): Address {\n return isToken(address, \"BERA\") ? this.config.tokens.wbera : address;\n }\n\n /**\n * Helper to calculate price impact percentage\n */\n private calculatePriceImpact(priceImpact: {\n error: string | null;\n priceImpact?: string;\n }): number {\n if (priceImpact.error) {\n console.error(\"Swap price impact error\", priceImpact);\n return 0;\n }\n\n return Number(priceImpact.priceImpact);\n }\n\n /**\n * Helper to check for stale SOR prices\n */\n private checkStalePrices({\n onChainAmount,\n sorPaths,\n sorAmount,\n queryData,\n }: {\n onChainAmount: TokenAmount;\n sorPaths: { pools: string[] }[];\n sorAmount: string;\n queryData: IAggregatorArgs;\n }): void {\n // Check for stale prices\n const deltaFromSorAmount =\n Number.parseFloat(formatEther(onChainAmount.scale18)) /\n Number.parseFloat(sorAmount);\n\n if (Math.abs(1 - deltaFromSorAmount) > STALE_PRICE_THRESHOLD) {\n console.warn(\n \"SOR returned stale prices. Delta from return amount is more than 5%\",\n {\n deltaFromSorAmount,\n },\n );\n\n const error = new BeraError({\n reason: \"SOR_STALE_PRICES\",\n level: \"warning\",\n message:\n \"SOR returned stale prices. Delta from return amount is more than 5%\",\n extra: {\n deltaFromSorAmount,\n pools: sorPaths.map((p) => p.pools),\n onChainAmount: formatEther(onChainAmount.scale18),\n sorAmount,\n queryData,\n },\n fingerprint: [\"SOR_STALE_PRICES\"],\n });\n BeraMonitoring.captureException(error);\n }\n }\n\n async getQuote(args: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n const balancerApi = new BalancerApi(\n this.url,\n // @ts-expect-error b-sdk has more chains than berajs\n this.chainId,\n );\n const {\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n publicClient,\n } = args;\n this.assertChainSupport({ tokenIn, tokenOut });\n\n assertPublicClient(publicClient);\n\n const wberaIsBera = isToken(tokenIn, \"BERA\") || isToken(tokenOut, \"BERA\");\n\n // Initialize tokens\n const tokenInV3 = new Token(\n this.chainId,\n this.convertZeroToWrapped(tokenIn.address),\n tokenIn.decimals,\n );\n const tokenOutV3 = new Token(\n this.chainId,\n this.convertZeroToWrapped(tokenOut.address),\n tokenOut.decimals,\n );\n\n const tokenAmount = TokenAmount.fromRawAmount(\n tokenInV3,\n amount as `${number}`,\n );\n\n // swap paths\n const {\n paths: sorPaths,\n priceImpact,\n returnAmount: sorAmount,\n }: SorSwapResult = await balancerApi.sorSwapPaths.fetchSorSwapPaths({\n // @ts-expect-error b-sdk has more chains than berajs\n chainId: this.chainId,\n tokenIn: tokenInV3.address,\n tokenOut: tokenOutV3.address,\n swapKind,\n swapAmount: tokenAmount,\n });\n\n if (!sorPaths?.length) {\n throw new RequestError({\n response: undefined,\n endpoint: {\n url: this.url,\n name: this.name,\n type: this.type,\n },\n reason: BaseAggregator.PATH_NOT_FOUND_REASON,\n chainId: this.chainId,\n payload: {\n tokenIn: tokenInV3.address,\n tokenOut: tokenOutV3.address,\n swapKind,\n swapAmount: tokenAmount,\n },\n message: `No swap paths returned from Balancer API`,\n });\n }\n\n // execute swap query\n const swap = new Swap({\n chainId: this.chainId,\n paths: sorPaths,\n swapKind,\n userData: \"0x\" as `0x${string}`,\n });\n const queryOutput = await swap.query(publicClient.transport.url);\n\n if (!(\"expectedAmountOut\" in queryOutput)) {\n throw new Error(\"No Bex paths found\");\n }\n\n this.checkStalePrices({\n onChainAmount: queryOutput.expectedAmountOut,\n sorPaths,\n sorAmount,\n queryData: args,\n });\n\n // format quote response\n return {\n amountOut: queryOutput.expectedAmountOut.amount.toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: queryOutput.to,\n }),\n name: this.name,\n priceImpactPercentage: this.calculatePriceImpact(priceImpact),\n swapFeeBps: 0,\n getCalldata: ({ account }) => {\n // generate user transaction data\n const callData = swap.buildCall({\n slippage: Slippage.fromPercentage(slippage.toString() as `${number}`),\n deadline: BigInt(Math.round(Date.now() / 1000) + DEFAULT_DEADLINE),\n queryOutput,\n sender: account as Address,\n recipient: account as Address,\n wethIsEth: wberaIsBera,\n });\n\n const { args: params, functionName } = decodeFunctionData({\n abi: balancerVaultAbi,\n data: callData.callData,\n });\n\n return {\n params,\n functionName,\n abi: balancerVaultAbi,\n address: callData.to,\n value: callData.value || BigInt(0),\n };\n },\n };\n }\n}\n\nexport const bex = new BexAggregator();\n","import { ChainId } from \"@berachain/config/internal\";\n\nimport { Aggregators } from \"~/enum/dex\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n MinimalERC20,\n} from \"~/types/dex\";\nimport { beraToken, isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\nclass RedeemBgtAggregator extends BaseAggregator {\n name = Aggregators.RedeemBgt;\n supportedChains = [ChainId.MAINNET, ChainId.BEPOLIA];\n readonly type = \"rpc\";\n\n checkChainSupport({\n tokenIn,\n tokenOut,\n }: {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n }): boolean {\n if (!super.checkChainSupport({ tokenIn, tokenOut })) {\n return false;\n }\n\n return (\n // only supported on same chain\n tokenIn.chainId === tokenOut.chainId &&\n isToken(tokenIn, \"BGT\", { chainId: tokenIn.chainId }) &&\n isToken(tokenOut, \"BERA\")\n );\n }\n // handles native swaps: wrap and unwrap\n async getQuote({\n tokenIn,\n amount,\n }: Omit<\n IAggregatorArgs,\n \"slippage\" | \"feeBps\" | \"tokenOut\" | \"account\"\n >): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({\n tokenIn,\n tokenOut: { ...beraToken, chainId: tokenIn.chainId },\n });\n\n if (!isToken(tokenIn, \"BGT\", { config: this.config })) {\n throw new InvalidArgumentError({\n property: \"tokenIn\",\n value: tokenIn,\n expected: \"BGT\",\n level: \"warning\",\n });\n }\n\n return {\n amountOut: amount,\n amountIn: amount,\n allowanceRequirements: [],\n name: Aggregators.RedeemBgt,\n isNativeSwap: true,\n swapFeeBps: 0,\n // not adding calldata here because it depends on the connected wallet\n // bgt redeem requires a receiver address\n // moreover this is a sensitive operation, better be sure of what data is being sent\n // by controlling it on the consumer side\n } as const;\n }\n}\n\nexport const bgtRedeem = new RedeemBgtAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { aggregatorsRouterAbi } from \"~/abi/bex/aggregatorsRouter\";\nimport { Aggregators } from \"~/enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\nimport { BaseAggregator } from \"../base\";\n\nexport class EnsoAggregator extends BaseAggregator {\n name = Aggregators.Enso;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n needsAccountForQuote = true;\n\n notFoundMessages: string[] = [\n \"Could not build shortcuts for route\",\n \"Could not quote shortcuts for route\",\n \"Swap not found for a required underlying of defi route,\",\n \"No route found from\",\n ];\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=enso`\n : `${this.config.bex.aggregatorsProxyUrl}/enso/api/v1/shortcuts/route?`;\n\n const url = new URL(this.url);\n url.searchParams.set(\n \"fromAddress\",\n this.config.bex.aggregatorsRouterExecutor,\n );\n url.searchParams.set(\"receiver\", this.config.bex.aggregatorsRouterExecutor);\n url.searchParams.set(\"spender\", this.config.bex.aggregatorsRouterExecutor);\n url.searchParams.set(\"amountIn\", inputAmountAfterFees);\n url.searchParams.set(\"tokenIn\", tokenInAddress);\n url.searchParams.set(\"tokenOut\", tokenOutAddress);\n url.searchParams.set(\"chainId\", ChainId.MAINNET.toString());\n url.searchParams.set(\"slippage\", (Number(slippage) * 100).toString());\n url.searchParams.set(\"refundReceiver\", account);\n\n const response = await this.fetch(url);\n\n const quote = await response.json();\n\n const inputData = this.getInputData({\n tokenIn: tokenInAddress,\n amountIn: amount,\n isNative: isTokenInNative,\n });\n\n const outputData = {\n tokenOut: tokenOutAddress,\n receiver: account,\n minAmountOut: this.getMinAmountOut(quote.amountOut.toString(), slippage),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quote.tx?.to,\n data: quote.tx?.data,\n };\n\n return {\n amountOut: quote.amountOut.toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n getCalldata: () => ({\n params: [\n inputData,\n outputData,\n aggregatorData,\n {\n rewardVault: rewardVault ?? zeroAddress,\n isSwapAndStake: !!rewardVault,\n },\n ],\n functionName: \"swap\",\n abi: aggregatorsRouterAbi,\n // send full amount to router first, which will deduct the swap fee before executing trade\n value: isTokenInNative ? BigInt(amount) : BigInt(\"0\"),\n address: this.config.bex.aggregatorsRouter,\n }),\n };\n }\n}\n\nexport const enso = new EnsoAggregator();\n","import { useEffect, useState } from \"react\";\nimport { PoolType } from \"@berachain-foundation/berancer-sdk\";\n\nimport { PoolCreationStep } from \"~/enum/dex\";\nimport type { TokenCurrentPriceMap, TokenWithAmount } from \"~/types/dex\";\nimport { wrapNativeTokens } from \"~/utils/tokenWrapping\";\nimport { type Oracle, OracleMode } from \"./useCreatePool\";\n\nconst DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT = 0.05; // 5%\n\nexport type LiquidityMismatchInfo = {\n title: string | null;\n message: string | null;\n suggestWeighted?: boolean;\n};\n\ninterface UseLiquidityMismatchParams {\n currentStep: PoolCreationStep;\n tokenPrices?: TokenCurrentPriceMap;\n isLoadingTokenPrices: boolean;\n tokens: TokenWithAmount[] | null;\n weights: bigint[] | null;\n weightsError: string | null;\n poolType: PoolType;\n liquidityMismatchTolerancePercent?: number;\n oracles: Oracle[];\n}\n\n/**\n * Hook for detecting liquidity mismatches.\n *\n * @param {PoolCreationStep} currentStep - The current step of the pool creation process.\n * @param {Record<string, number>} tokenPrices - The current token prices.\n * @param {boolean} isLoadingTokenPrices - Whether the token prices are still loading.\n * @param {Array<{ address: string, amount: number }>} tokens - The tokens in the pool, including their addresses and amounts.\n * @param {Record<string, number>} weights - The per-token weights in the pool we are creating.\n * @param {string | null} weightsError - An error message for the weights indicating that the weights are invalid.\n * @param {string} poolType - The type of pool being created.\n * @param {number} liquidityMismatchTolerancePercent - The tolerance for liquidity mismatches in percent.\n * @returns {Object} The liquidity mismatch info.\n */\nexport const useLiquidityMismatch = ({\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent = DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT,\n oracles,\n}: UseLiquidityMismatchParams): LiquidityMismatchInfo => {\n // NOTE: would be nice to use Maps/Records more in here, as the zipping/unzipping is cumbersome.\n // NOTE: if we pull in string literal for currentStep things would also be a bit clearer in here.\n const [liquidityMismatchInfo, setLiquidityMismatchInfo] =\n useState<LiquidityMismatchInfo>({ title: null, message: null });\n\n useEffect(() => {\n // If we are either using custom rate-providing oracles or have incorrect/loading token prices, we cant do validation.\n if (\n !tokenPrices ||\n isLoadingTokenPrices ||\n !tokens ||\n !weights ||\n weightsError ||\n tokens.some((token) => !token.address) ||\n oracles.some((oracle) => oracle.mode === OracleMode.Custom) // Oracles give prices on their own, we dont support that here yet.\n ) {\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Calculate some basic metrics we'll use to determine per-token contributions and model potential losses from arbitrage.\n let totalLiquidityUSD = 0;\n const tokenUSDAmounts: number[] = [];\n const numTokens = tokens.length;\n const wrappedTokens = wrapNativeTokens(tokens);\n const tokenUSDPrices = wrappedTokens.map((token) => {\n const tokenPriceUSD =\n tokenPrices[token.address.toLowerCase()]?.price ?? 0;\n if (!tokenPriceUSD || tokenPriceUSD === 0) {\n tokenUSDAmounts.push(0);\n return null;\n }\n const tokenAmountUSD = tokenPriceUSD * Number.parseFloat(token.amount);\n tokenUSDAmounts.push(tokenAmountUSD);\n totalLiquidityUSD += tokenAmountUSD;\n return tokenPriceUSD;\n });\n\n // Doesn't matter what step it is, if we have missing token prices for tokens we have selected, we cant issue a real warning.\n if (\n tokenUSDPrices.some((price) => price === null) ||\n tokenUSDPrices.length !== numTokens\n ) {\n setLiquidityMismatchInfo({\n title: \"Missing token price data\",\n message: `One or more token(s) do not have valid market price data. Please verify that token market prices align with the pool\n weightings and your initial liquidity amounts.`,\n });\n return;\n }\n\n // Step 1 - During token selection we check for a deviation in the quote prices of the tokens selected (for stable pools).\n if (\n currentStep === PoolCreationStep.SELECT_TOKENS &&\n poolType === PoolType.ComposableStable\n ) {\n const normalizedUSDPrices = tokenUSDPrices.map(\n (priceUSD) => priceUSD! / tokenUSDPrices[0]!, // always normalize on the first token's price\n );\n const maxDifference =\n Math.max(...normalizedUSDPrices) - Math.min(...normalizedUSDPrices);\n\n if (maxDifference > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n title: \"Selected tokens have a significant price deviation\",\n message: \"Did you mean to create a Weighted pool instead?\",\n suggestWeighted: true,\n });\n } else {\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n\n return;\n }\n\n // Validation During Liquidity Input and onwards.\n if (\n totalLiquidityUSD === 0 ||\n tokenUSDAmounts.some((value) => value === 0)\n ) {\n // User has not yet entered fully their liquidity values, so return early.\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Simulate arbitrage for the pool to determine potential losses from arbitrageurs.\n // NOTE: we assume shortfalls and excesses are losses, but in reality the actual losses would be more complex to realise.\n // Balancer does this similarily https://github.com/balancer/frontend-v2/blob/8563b8d33b6bff266148bd48d7ebc89f921374f4/src/components/cards/CreatePool/InitialLiquidity.vue#L75\n let totalLossUSD = 0;\n if (poolType === PoolType.ComposableStable) {\n const expectedPerTokenLiquidityUSD = totalLiquidityUSD / numTokens;\n tokenUSDAmounts.forEach((value) => {\n totalLossUSD += Math.abs(expectedPerTokenLiquidityUSD - value);\n });\n } else if (poolType === PoolType.Weighted) {\n tokenUSDAmounts.forEach((value, index) => {\n const weightProportion = Number(weights[index]) / 1e18;\n const expectedValueUSD = totalLiquidityUSD * weightProportion;\n totalLossUSD += Math.abs(expectedValueUSD - value);\n });\n }\n\n // We'll show a total loss if it's 90% or more\n const isTotalLoss = totalLossUSD >= totalLiquidityUSD * 0.9;\n totalLossUSD = Math.min(totalLossUSD, totalLiquidityUSD);\n const totalLossPercentage = totalLossUSD / totalLiquidityUSD;\n\n if (totalLossPercentage > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n // If it's a total loss we dont display a percentage\n title: isTotalLoss\n ? \"You could lose all of your initial liquidity\"\n : `You could lose $${totalLossUSD.toFixed(2)} (~${(\n totalLossPercentage * 100\n ).toFixed(2)}%)`,\n message: `Based on the market token prices, the value of tokens does not align with the specified pool weights. \n This discrepancy could expose you to potential losses from arbitrageurs. ${\n poolType === PoolType.ComposableStable\n ? \"Did you mean to create a Weighted pool instead?\"\n : \"\"\n }`,\n suggestWeighted: poolType === PoolType.ComposableStable,\n });\n } else {\n // All good bb bb\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n }, [\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent,\n oracles,\n ]);\n return liquidityMismatchInfo;\n};\n","import { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport { type Address, isAddress, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { getTokenCurrentPrices } from \"~/actions/prices/getTokenCurrentPrices\";\nimport { POLLING } from \"~/enum/polling\";\nimport { useTokens } from \"~/hooks/tokens/useTokens\";\nimport type { TokenCurrentPriceMap, TokenWithPrice } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { isToken } from \"~/utils/tokens\";\n\n/**\n * @deprecated use useTokenPrices instead that supports multichain tokens\n */\nexport function useTokenCurrentPrices(\n {\n addressIn,\n }: {\n addressIn?: string[] | readonly string[];\n } = {},\n options: DefaultHookOptions = {\n opts: {\n refreshInterval: POLLING.NORMAL,\n revalidateOnFocus: true,\n },\n },\n) {\n const { tokenList, ensoTokens } = useTokens();\n\n /**\n * Berachain or Bepolia Tokens. All tokens from other chains are excluded since API doesn't price them.\n */\n const beraAddresses = useMemo<Address[]>(() => {\n const addresses: Address[] = [];\n\n if (addressIn) {\n addresses.push(\n ...(addressIn.filter((a): a is Address => isAddress(a)) as Address[]),\n );\n }\n return addresses.map((a) => a.toLowerCase() as Address);\n }, [tokenList]);\n\n const hasAddressesNotInTokenList = useMemo(() => {\n const tokenSet = new Set(\n tokenList?.map((token) => token.address.toLowerCase() as Address),\n );\n // Native BERA (zero address) is priced via WBERA in getTokenCurrentPrices.\n // Treat zero address as \"known\" whenever WBERA exists in token list.\n if (tokenList.some((token) => isToken(token, \"WBERA\"))) {\n tokenSet.add(zeroAddress);\n }\n\n return beraAddresses?.some((a) => !tokenSet.has(a));\n }, [beraAddresses, tokenList]);\n\n /**\n * If no addressIn is provided, use default token list\n * If all addressIn are in the token list, use default token list\n * If some addressIn are not in the token list, use addressIn\n */\n const addresses = hasAddressesNotInTokenList\n ? beraAddresses\n : tokenList.map((token) => token.address);\n\n const QUERY_KEY =\n addresses && (options.opts?.isEnabled ?? true)\n ? ([\n \"useTokenCurrentPrices\",\n addresses.map((a) => a.toLowerCase() as Address),\n ] as const)\n : null;\n\n const apiResponse = useSWR(\n QUERY_KEY,\n async ([, addresses]) => {\n // this only works for Berachain tokens\n return getTokenCurrentPrices({ addressIn: addresses });\n },\n options.opts,\n );\n\n const ensoMatchingPrices = useMemo<TokenCurrentPriceMap>(() => {\n if (!ensoTokens) return {};\n\n const ensoPricesMap = new Map<number, Map<Address, TokenWithPrice>>([\n [defaultChainId, new Map()],\n ]);\n\n for (const token of ensoTokens) {\n if (token.price === undefined || token.chainId !== defaultChainId)\n continue;\n\n ensoPricesMap\n .get(defaultChainId)\n ?.set(token.address.toLowerCase() as Address, {\n ...token,\n price: token.price,\n chainId: defaultChainId,\n });\n }\n\n return Object.fromEntries(\n addresses.map((address) => {\n const price = ensoPricesMap.get(defaultChainId)?.get(address)?.price;\n\n if (!price) return [null, null];\n\n return [\n address.toLowerCase() as Address,\n {\n price,\n chainId: defaultChainId,\n updatedAt: Date.now(),\n },\n ];\n }),\n );\n }, [ensoTokens]);\n\n const data = useMemo(\n () => ({\n ...ensoMatchingPrices,\n // in this deprecated hook, we let api override enso prices, since there's no multichain support\n ...apiResponse.data,\n }),\n [ensoMatchingPrices, apiResponse.data],\n );\n\n return {\n ...apiResponse,\n data,\n };\n}\n"]}
|
package/dist/hooks/exports.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as swr from 'swr';
|
|
2
2
|
import { SWRResponse } from 'swr';
|
|
3
|
-
import { G as GetConvertToAssetsProps, O as OnChainPool, B as BaseAggregator, c as GetHoneyVaultsBalanceResponse, e as IsBadCollateralResponse, f as GetBgtAprSimulationArgs, h as GetBgtAprSimulationResult, k as GlobalData, m as GetMarkets, S as StakedBeraWithdrawal, R as RewardVaultIncentive, q as GetRewardVaultRewardsReturn, s as GetGaugeData, u as VaultMetadata, x as GetUserVaultsResponse, z as GetVaultHistoryArgs, V as ValidatorRewardAllocation, C as ValidatorWithUserBoost, E as UserBoostsOnValidator, H as UserStakingPoolPosition, K as ValidatorQueuedCommission, M as ValidatorQueuedOperatorAddress } from '../getValidatorQueuedOperatorAddress-
|
|
4
|
-
import { D as DefaultHookOptions, c as DefaultHookReturnType, G as GovernanceTopic, a as CustomProposalErrors, C as CustomProposal, S as StakingConfig, d as StakedBeraAsset, U as UserVaultInfo, e as IUseContractWriteArgs, f as UseContractWriteApi, B as BribeBoostRewardProof } from '../global.d-
|
|
5
|
-
export { T as TxnEventKeys } from '../global.d-
|
|
3
|
+
import { G as GetConvertToAssetsProps, O as OnChainPool, B as BaseAggregator, c as GetHoneyVaultsBalanceResponse, e as IsBadCollateralResponse, f as GetBgtAprSimulationArgs, h as GetBgtAprSimulationResult, k as GlobalData, m as GetMarkets, S as StakedBeraWithdrawal, R as RewardVaultIncentive, q as GetRewardVaultRewardsReturn, s as GetGaugeData, u as VaultMetadata, x as GetUserVaultsResponse, z as GetVaultHistoryArgs, V as ValidatorRewardAllocation, C as ValidatorWithUserBoost, E as UserBoostsOnValidator, H as UserStakingPoolPosition, K as ValidatorQueuedCommission, M as ValidatorQueuedOperatorAddress } from '../getValidatorQueuedOperatorAddress-D_LEt3vv.cjs';
|
|
4
|
+
import { D as DefaultHookOptions, c as DefaultHookReturnType, G as GovernanceTopic, a as CustomProposalErrors, C as CustomProposal, S as StakingConfig, d as StakedBeraAsset, U as UserVaultInfo, e as IUseContractWriteArgs, f as UseContractWriteApi, B as BribeBoostRewardProof } from '../global.d-DLRtrPG5.cjs';
|
|
5
|
+
export { T as TxnEventKeys } from '../global.d-DLRtrPG5.cjs';
|
|
6
6
|
import { S as SwapReferrer, A as Aggregators, a as PoolCreationStep } from '../dex-C_BB0b0O.cjs';
|
|
7
7
|
import * as viem from 'viem';
|
|
8
8
|
import { Address, Hex } from 'viem';
|
|
@@ -1225,7 +1225,29 @@ declare function useStakedAPR({ range, }: {
|
|
|
1225
1225
|
range: GqlVaultSnapshotDataRange;
|
|
1226
1226
|
}): DefaultHookReturnType<UseStakedAPR>;
|
|
1227
1227
|
|
|
1228
|
-
|
|
1228
|
+
/**
|
|
1229
|
+
* Fetches staked asset data in two phases for progressive loading:
|
|
1230
|
+
*
|
|
1231
|
+
* 1. APR — independent fetch, resolves quickly, shared by both phases.
|
|
1232
|
+
* 2. Balances (fast path) — wallet balances (via usePollWalletBalances),
|
|
1233
|
+
* token prices (via useTokenPrices), and exchange rates.
|
|
1234
|
+
* Provides staked amounts and USD values immediately (earnings are 0).
|
|
1235
|
+
* 3. Positions (slow path) — adds earnings data from the vault.
|
|
1236
|
+
* Provides the full picture with earned amounts and USD values.
|
|
1237
|
+
*
|
|
1238
|
+
* Consumers can show `balances` right away and swap in `data` once positions resolve.
|
|
1239
|
+
*/
|
|
1240
|
+
declare const useStakedData: (stakingConfigs: StakingConfig[]) => {
|
|
1241
|
+
/** Fast path: staked amounts + USD values (no earnings) */
|
|
1242
|
+
balances: StakedBeraAsset[] | undefined;
|
|
1243
|
+
/** Slow path: full enriched positions with earnings */
|
|
1244
|
+
data: StakedBeraAsset[] | undefined;
|
|
1245
|
+
/** True only when both balances and positions are still loading */
|
|
1246
|
+
isLoading: boolean;
|
|
1247
|
+
isLoadingBalances: boolean;
|
|
1248
|
+
isLoadingPositions: boolean;
|
|
1249
|
+
isValidatingPositions: boolean;
|
|
1250
|
+
};
|
|
1229
1251
|
|
|
1230
1252
|
type UseStakedBeraSnapshot = Record<Address, {
|
|
1231
1253
|
_timestamp: number;
|
package/dist/hooks/exports.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as swr from 'swr';
|
|
2
2
|
import { SWRResponse } from 'swr';
|
|
3
|
-
import { G as GetConvertToAssetsProps, O as OnChainPool, B as BaseAggregator, c as GetHoneyVaultsBalanceResponse, e as IsBadCollateralResponse, f as GetBgtAprSimulationArgs, h as GetBgtAprSimulationResult, k as GlobalData, m as GetMarkets, S as StakedBeraWithdrawal, R as RewardVaultIncentive, q as GetRewardVaultRewardsReturn, s as GetGaugeData, u as VaultMetadata, x as GetUserVaultsResponse, z as GetVaultHistoryArgs, V as ValidatorRewardAllocation, C as ValidatorWithUserBoost, E as UserBoostsOnValidator, H as UserStakingPoolPosition, K as ValidatorQueuedCommission, M as ValidatorQueuedOperatorAddress } from '../getValidatorQueuedOperatorAddress-
|
|
4
|
-
import { D as DefaultHookOptions, c as DefaultHookReturnType, G as GovernanceTopic, a as CustomProposalErrors, C as CustomProposal, S as StakingConfig, d as StakedBeraAsset, U as UserVaultInfo, e as IUseContractWriteArgs, f as UseContractWriteApi, B as BribeBoostRewardProof } from '../global.d-
|
|
5
|
-
export { T as TxnEventKeys } from '../global.d-
|
|
3
|
+
import { G as GetConvertToAssetsProps, O as OnChainPool, B as BaseAggregator, c as GetHoneyVaultsBalanceResponse, e as IsBadCollateralResponse, f as GetBgtAprSimulationArgs, h as GetBgtAprSimulationResult, k as GlobalData, m as GetMarkets, S as StakedBeraWithdrawal, R as RewardVaultIncentive, q as GetRewardVaultRewardsReturn, s as GetGaugeData, u as VaultMetadata, x as GetUserVaultsResponse, z as GetVaultHistoryArgs, V as ValidatorRewardAllocation, C as ValidatorWithUserBoost, E as UserBoostsOnValidator, H as UserStakingPoolPosition, K as ValidatorQueuedCommission, M as ValidatorQueuedOperatorAddress } from '../getValidatorQueuedOperatorAddress-NrjpnEn8.js';
|
|
4
|
+
import { D as DefaultHookOptions, c as DefaultHookReturnType, G as GovernanceTopic, a as CustomProposalErrors, C as CustomProposal, S as StakingConfig, d as StakedBeraAsset, U as UserVaultInfo, e as IUseContractWriteArgs, f as UseContractWriteApi, B as BribeBoostRewardProof } from '../global.d-X3cqpCEB.js';
|
|
5
|
+
export { T as TxnEventKeys } from '../global.d-X3cqpCEB.js';
|
|
6
6
|
import { S as SwapReferrer, A as Aggregators, a as PoolCreationStep } from '../dex-C_BB0b0O.js';
|
|
7
7
|
import * as viem from 'viem';
|
|
8
8
|
import { Address, Hex } from 'viem';
|
|
@@ -1225,7 +1225,29 @@ declare function useStakedAPR({ range, }: {
|
|
|
1225
1225
|
range: GqlVaultSnapshotDataRange;
|
|
1226
1226
|
}): DefaultHookReturnType<UseStakedAPR>;
|
|
1227
1227
|
|
|
1228
|
-
|
|
1228
|
+
/**
|
|
1229
|
+
* Fetches staked asset data in two phases for progressive loading:
|
|
1230
|
+
*
|
|
1231
|
+
* 1. APR — independent fetch, resolves quickly, shared by both phases.
|
|
1232
|
+
* 2. Balances (fast path) — wallet balances (via usePollWalletBalances),
|
|
1233
|
+
* token prices (via useTokenPrices), and exchange rates.
|
|
1234
|
+
* Provides staked amounts and USD values immediately (earnings are 0).
|
|
1235
|
+
* 3. Positions (slow path) — adds earnings data from the vault.
|
|
1236
|
+
* Provides the full picture with earned amounts and USD values.
|
|
1237
|
+
*
|
|
1238
|
+
* Consumers can show `balances` right away and swap in `data` once positions resolve.
|
|
1239
|
+
*/
|
|
1240
|
+
declare const useStakedData: (stakingConfigs: StakingConfig[]) => {
|
|
1241
|
+
/** Fast path: staked amounts + USD values (no earnings) */
|
|
1242
|
+
balances: StakedBeraAsset[] | undefined;
|
|
1243
|
+
/** Slow path: full enriched positions with earnings */
|
|
1244
|
+
data: StakedBeraAsset[] | undefined;
|
|
1245
|
+
/** True only when both balances and positions are still loading */
|
|
1246
|
+
isLoading: boolean;
|
|
1247
|
+
isLoadingBalances: boolean;
|
|
1248
|
+
isLoadingPositions: boolean;
|
|
1249
|
+
isValidatingPositions: boolean;
|
|
1250
|
+
};
|
|
1229
1251
|
|
|
1230
1252
|
type UseStakedBeraSnapshot = Record<Address, {
|
|
1231
1253
|
_timestamp: number;
|