@berachain/berajs 0.1.2 → 0.2.0
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/{BeraError-D1HS_rbb.d.cts → BeraError-_mQdkanr.d.cts} +35 -10
- package/dist/{BeraError-D1HS_rbb.d.ts → BeraError-_mQdkanr.d.ts} +35 -10
- package/dist/HoneyConfigProvider-CK6mOKFH.d.ts +390 -0
- package/dist/HoneyConfigProvider-Ca3ouozs.d.cts +390 -0
- package/dist/{RequestError-D8AE6xnI.d.cts → RequestError-A8XJ6QR9.d.cts} +1 -1
- package/dist/{RequestError-m4jxyM7D.d.ts → RequestError-Dk97z8rm.d.ts} +1 -1
- package/dist/abi/exports.cjs +2 -0
- package/dist/abi/exports.cjs.map +1 -0
- package/dist/abi/{index.d.cts → exports.d.cts} +12369 -9122
- package/dist/abi/{index.d.ts → exports.d.ts} +12369 -9122
- package/dist/abi/exports.mjs +2 -0
- package/dist/abi/exports.mjs.map +1 -0
- package/dist/actions/exports.cjs +2 -0
- package/dist/actions/exports.cjs.map +1 -0
- package/dist/actions/{index.d.cts → exports.d.cts} +80 -107
- package/dist/actions/{index.d.ts → exports.d.ts} +80 -107
- package/dist/actions/exports.mjs +2 -0
- package/dist/actions/exports.mjs.map +1 -0
- package/dist/chunk-575OK77P.mjs +2 -0
- package/dist/chunk-575OK77P.mjs.map +1 -0
- package/dist/chunk-7GWTHOLO.mjs +2 -0
- package/dist/chunk-7GWTHOLO.mjs.map +1 -0
- package/dist/chunk-7SC4VD3U.cjs +2 -0
- package/dist/chunk-7SC4VD3U.cjs.map +1 -0
- package/dist/chunk-BHNQX4XC.mjs +2 -0
- package/dist/chunk-BHNQX4XC.mjs.map +1 -0
- package/dist/chunk-BOYZVULX.cjs +2 -0
- package/dist/chunk-BOYZVULX.cjs.map +1 -0
- package/dist/chunk-C3FHGFLK.mjs +2 -0
- package/dist/chunk-C3FHGFLK.mjs.map +1 -0
- package/dist/chunk-C3G5KXCH.mjs +2 -0
- package/dist/chunk-C3G5KXCH.mjs.map +1 -0
- package/dist/chunk-CYKCYPFR.cjs +2 -0
- package/dist/chunk-CYKCYPFR.cjs.map +1 -0
- package/dist/chunk-F4BKSBEM.mjs +2 -0
- package/dist/chunk-F4BKSBEM.mjs.map +1 -0
- package/dist/chunk-FL2N3XHK.cjs +2 -0
- package/dist/chunk-FL2N3XHK.cjs.map +1 -0
- package/dist/chunk-G6NA6NSM.mjs +4 -0
- package/dist/chunk-G6NA6NSM.mjs.map +1 -0
- package/dist/chunk-H2QSRMVS.mjs +2 -0
- package/dist/chunk-H2QSRMVS.mjs.map +1 -0
- package/dist/chunk-IJM76AWK.cjs +4 -0
- package/dist/chunk-IJM76AWK.cjs.map +1 -0
- package/dist/chunk-MTS5SZLA.mjs +2 -0
- package/dist/chunk-MTS5SZLA.mjs.map +1 -0
- package/dist/chunk-MUNAP5TM.cjs +2 -0
- package/dist/chunk-MUNAP5TM.cjs.map +1 -0
- package/dist/chunk-NAXAZJJY.mjs +2 -0
- package/dist/chunk-NAXAZJJY.mjs.map +1 -0
- package/dist/chunk-OGJMSGB2.mjs +2 -0
- package/dist/chunk-OGJMSGB2.mjs.map +1 -0
- package/dist/chunk-OIYXOKTT.cjs +2 -0
- package/dist/chunk-OIYXOKTT.cjs.map +1 -0
- package/dist/chunk-OS5AJMYJ.cjs +2 -0
- package/dist/chunk-OS5AJMYJ.cjs.map +1 -0
- package/dist/chunk-Q3SCM6WL.mjs +2 -0
- package/dist/chunk-Q3SCM6WL.mjs.map +1 -0
- package/dist/chunk-SWMJQOH6.cjs +2 -0
- package/dist/chunk-SWMJQOH6.cjs.map +1 -0
- package/dist/chunk-TEBJWAVU.mjs +2 -0
- package/dist/chunk-TEBJWAVU.mjs.map +1 -0
- package/dist/chunk-TJWKS54T.mjs +2 -0
- package/dist/chunk-TJWKS54T.mjs.map +1 -0
- package/dist/chunk-UQUWMHVF.cjs +2 -0
- package/dist/chunk-UQUWMHVF.cjs.map +1 -0
- package/dist/chunk-UXUWSRVV.cjs +2 -0
- package/dist/chunk-UXUWSRVV.cjs.map +1 -0
- package/dist/chunk-VP7XUOSI.cjs +2 -0
- package/dist/chunk-VP7XUOSI.cjs.map +1 -0
- package/dist/chunk-VXL2ZZ4X.cjs +2 -0
- package/dist/chunk-VXL2ZZ4X.cjs.map +1 -0
- package/dist/chunk-WRFDB3QJ.cjs +2 -0
- package/dist/chunk-WRFDB3QJ.cjs.map +1 -0
- package/dist/chunk-WTCBORPB.cjs +2 -0
- package/dist/chunk-WTCBORPB.cjs.map +1 -0
- package/dist/chunk-XNJLSA6P.cjs +2 -0
- package/dist/chunk-XNJLSA6P.cjs.map +1 -0
- package/dist/chunk-YQGZMWDT.mjs +2 -0
- package/dist/chunk-YQGZMWDT.mjs.map +1 -0
- package/dist/chunk-YXLFOEZN.mjs +2 -0
- package/dist/chunk-YXLFOEZN.mjs.map +1 -0
- package/dist/chunk-ZAKA4TGK.cjs +2 -0
- package/dist/chunk-ZAKA4TGK.cjs.map +1 -0
- package/dist/chunk-ZQRACIGR.mjs +2 -0
- package/dist/chunk-ZQRACIGR.mjs.map +1 -0
- package/dist/contexts/exports.cjs +2 -0
- package/dist/contexts/exports.cjs.map +1 -0
- package/dist/contexts/{index.d.ts → exports.d.cts} +19 -28
- package/dist/contexts/{index.d.cts → exports.d.ts} +19 -28
- package/dist/contexts/exports.mjs +2 -0
- package/dist/contexts/exports.mjs.map +1 -0
- package/dist/contracts-CQIPk0Jc.d.cts +74 -0
- package/dist/contracts-CQIPk0Jc.d.ts +74 -0
- package/dist/{defaultFlags-V-tJs2K8.d.cts → defaultFlags-d0kPbT0i.d.cts} +1 -1
- package/dist/{defaultFlags-V-tJs2K8.d.ts → defaultFlags-d0kPbT0i.d.ts} +1 -1
- package/dist/dex-C_BB0b0O.d.cts +37 -0
- package/dist/dex-C_BB0b0O.d.ts +37 -0
- package/dist/enum/exports.cjs +2 -0
- package/dist/enum/exports.cjs.map +1 -0
- package/dist/enum/exports.d.cts +24 -0
- package/dist/enum/exports.d.ts +24 -0
- package/dist/enum/exports.mjs +2 -0
- package/dist/enum/exports.mjs.map +1 -0
- package/dist/errors/exports.cjs +2 -0
- package/dist/errors/exports.cjs.map +1 -0
- package/dist/errors/exports.d.cts +385 -0
- package/dist/errors/exports.d.ts +385 -0
- package/dist/errors/exports.mjs +2 -0
- package/dist/{getValidatorQueuedOperatorAddress-9xY2RUGe.d.cts → getValidatorQueuedOperatorAddress-BX35p2Lv.d.ts} +125 -15
- package/dist/{getValidatorQueuedOperatorAddress-Ne2zoiiV.d.ts → getValidatorQueuedOperatorAddress-It0GsdvQ.d.cts} +125 -15
- package/dist/global.d-Ba-NIojH.d.cts +474 -0
- package/dist/global.d-By70bEv2.d.ts +474 -0
- package/dist/honey-CYm0RWf4.d.cts +14 -0
- package/dist/honey-CYm0RWf4.d.ts +14 -0
- package/dist/hooks/exports.cjs +4 -0
- package/dist/hooks/exports.cjs.map +1 -0
- package/dist/hooks/{index.d.cts → exports.d.cts} +223 -173
- package/dist/hooks/{index.d.ts → exports.d.ts} +223 -173
- package/dist/hooks/exports.mjs +4 -0
- package/dist/hooks/exports.mjs.map +1 -0
- package/dist/{BexStatusProvider-nS3NcdxI.d.cts → transactionStore-BvStaXf3.d.ts} +41 -1
- package/dist/{BexStatusProvider-nS3NcdxI.d.ts → transactionStore-CQrGYSY2.d.cts} +41 -1
- package/dist/{txnEnum-BQKDfaeH.d.cts → txnEnum-BYNbCxla.d.cts} +1 -0
- package/dist/{txnEnum-BQKDfaeH.d.ts → txnEnum-BYNbCxla.d.ts} +1 -0
- package/dist/types/exports.cjs +1 -0
- package/dist/types/exports.cjs.map +1 -0
- package/dist/types/exports.d.cts +58 -0
- package/dist/types/exports.d.ts +58 -0
- package/dist/types/exports.mjs +1 -0
- package/dist/{useHoneySwapState-C-9BV4VB.d.cts → useHoneySwapState-B-vmIP1b.d.cts} +1 -1
- package/dist/{useHoneySwapState-CUY5Sm1b.d.ts → useHoneySwapState-D1DKG_Of.d.ts} +1 -1
- package/dist/utils/exports.cjs +2 -0
- package/dist/utils/exports.cjs.map +1 -0
- package/dist/utils/{index.d.cts → exports.d.cts} +83 -20
- package/dist/utils/{index.d.ts → exports.d.ts} +83 -20
- package/dist/utils/exports.mjs +2 -0
- package/dist/utils/exports.mjs.map +1 -0
- package/package.json +16 -17
- package/src/abi/{index.ts → exports.ts} +3 -0
- package/src/abi/pol/LSTStakerVault.ts +2032 -0
- package/src/abi/utils/openChainErrors.ts +71 -30
- package/src/abi/utils/thirdwebMinimalAccount.ts +616 -0
- package/src/actions/clients/BeraApolloClient.ts +8 -6
- package/src/actions/dex/__tests__/aggregators.unit.test.ts +2 -5
- package/src/actions/dex/aggregators/base.ts +74 -16
- package/src/actions/dex/aggregators/bex.ts +54 -74
- package/src/actions/dex/aggregators/bgt.ts +31 -8
- package/src/actions/dex/aggregators/{enso.ts → enso/enso.ts} +18 -14
- package/src/actions/dex/aggregators/enso/ensoErc4626.debug.test.ts +37 -0
- package/src/actions/dex/aggregators/enso/ensoErc4626.ts +176 -0
- package/src/actions/dex/aggregators/erc4626.ts +122 -0
- package/src/actions/dex/aggregators/fly.ts +59 -53
- package/src/actions/dex/aggregators/haiku.ts +52 -54
- package/src/actions/dex/aggregators/honey.ts +54 -45
- package/src/actions/dex/aggregators/kyberswap.ts +41 -39
- package/src/actions/dex/aggregators/oogabooga.ts +47 -46
- package/src/actions/dex/aggregators/openOcean.ts +51 -46
- package/src/actions/dex/aggregators/wbera.ts +54 -42
- package/src/actions/dex/b-sdk.ts +5 -2
- package/src/actions/dex/getIsTokenExploited.ts +2 -2
- package/src/actions/enso/{zap.ts → getEnsoSwapBundle.ts} +4 -5
- package/src/actions/enso/getEnsoUserTokensWithBalances.debug.test.ts +73 -0
- package/src/actions/enso/{getEnsoUserToken.ts → getEnsoUserTokensWithBalances.ts} +42 -30
- package/src/actions/enso/util.ts +1 -1
- package/src/actions/{index.ts → exports.ts} +5 -0
- package/src/actions/governance/__tests__/checkProposalField.unit.test.ts +1 -1
- package/src/actions/governance/__tests__/getQuorum.integration.test.ts +1 -1
- package/src/actions/governance/checkProposalField.ts +1 -1
- package/src/actions/governance/computeActualStatus.ts +1 -1
- package/src/actions/governance/getBodyErrors.ts +1 -1
- package/src/actions/governance/getDecodedFunctionData.ts +1 -4
- package/src/actions/governance/getProposalDetails.ts +2 -2
- package/src/actions/governance/getProposalFromTx.ts +1 -2
- package/src/actions/governance/getProposalParams.ts +7 -8
- package/src/actions/governance/getQuorum.ts +1 -2
- package/src/actions/honey/getCollateralWeights.ts +1 -1
- package/src/actions/honey/getHoneyCollaterals.ts +1 -0
- package/src/actions/honey/getHoneyVaultsBalance.ts +51 -55
- package/src/actions/honey/getSwapPayload.ts +37 -35
- package/src/actions/honey/tests/pyth.integration.test.ts +0 -1
- package/src/actions/pol/__tests__/getAllValidators.integration.test.ts +1 -1
- package/src/actions/pol/getEarnedStakedBeraVault.ts +31 -0
- package/src/actions/pol/getGlobalData.ts +14 -13
- package/src/actions/pol/getLSTStakeConfig.ts +67 -0
- package/src/actions/pol/getMarkets.ts +1 -1
- package/src/actions/pol/getRewardProofsByValidator.ts +1 -1
- package/src/actions/pol/getRewardVaultIncentives.ts +3 -5
- package/src/actions/pol/getRewardVaults.ts +2 -3
- package/src/actions/pol/getSWBeraVaultMetadata.ts +7 -5
- package/src/actions/pol/getSWBeraWithdrawal.ts +41 -27
- package/src/actions/pol/getStakeWithdrawalCooldown.ts +5 -7
- package/src/actions/pol/getStakingDailyAssets.ts +21 -0
- package/src/actions/pol/getStakingTokenInformation.ts +3 -4
- package/src/actions/pol/getTotalStakedAmount.ts +47 -0
- package/src/actions/pol/getUserClaimableIncentives.ts +1 -1
- package/src/actions/pol/getUserVaults.ts +8 -6
- package/src/actions/pol/getUserVaultsBalance.ts +4 -16
- package/src/actions/prices/getTokenCurrentPrices.ts +8 -3
- package/src/actions/tokens/getAllowances.ts +68 -41
- package/src/actions/tokens/getTokenInformation.ts +4 -1
- package/src/actions/tokens/getTokens.ts +1 -1
- package/src/actions/tokens/getUnderlyingToken.ts +53 -0
- package/src/actions/tokens/getWalletBalances.integration.test.ts +53 -14
- package/src/actions/tokens/getWalletBalances.ts +69 -43
- package/src/actions/transactions/beraWriteContract.integration.test.ts +18 -6
- package/src/actions/transactions/beraWriteContract.ts +3 -3
- package/src/actions/validators/getUserActiveValidators.ts +2 -3
- package/src/actions/validators/getUserBoostsOnValidator.ts +2 -3
- package/src/contexts/BeraFlags/defaultFlags.ts +4 -0
- package/src/contexts/SwrFallback.tsx +13 -3
- package/src/contexts/TokensProvider.tsx +35 -8
- package/src/{hooks/transactions → contexts}/TransactionStoreContext.tsx +32 -4
- package/src/contexts/block-time-provider.tsx +1 -1
- package/src/contexts/{index.ts → exports.ts} +1 -1
- package/src/data/contracts.ts +16 -1
- package/src/enum/contracts.ts +13 -0
- package/src/enum/dex.ts +29 -0
- package/src/enum/{index.ts → exports.ts} +3 -0
- package/src/enum/governance.ts +61 -0
- package/src/enum/honey.ts +12 -0
- package/src/enum/txnEnum.ts +1 -0
- package/src/errors/BeraError.ts +50 -11
- package/src/errors/BeraMonitoring.ts +66 -0
- package/src/errors/BeraTracing.ts +79 -0
- package/src/errors/BeraTracing.unit.test.ts +198 -0
- package/src/errors/RequestError.ts +2 -2
- package/src/errors/assert.ts +4 -2
- package/src/errors/assert.unit.test.ts +6 -2
- package/src/errors/errorMap.ts +16 -6
- package/src/errors/{index.ts → exports.ts} +7 -0
- package/src/errors/getErrorMessage.ts +22 -3
- package/src/errors/getRevertReason.integration.test.ts +17 -5
- package/src/errors/getRevertReason.ts +41 -2
- package/src/errors/initBeraError.ts +52 -7
- package/src/errors/parseViemError.ts +114 -27
- package/src/errors/severity.ts +12 -0
- package/src/hooks/bend/useGetConvertToAssets.ts +3 -2
- package/src/hooks/dex/useAggregatorsQuotes.ts +126 -365
- package/src/hooks/dex/useAllUserPools.ts +1 -1
- package/src/hooks/dex/useApiPool.ts +1 -1
- package/src/hooks/dex/useCreatePool.ts +6 -5
- package/src/hooks/dex/useExploitedTokens.ts +1 -1
- package/src/hooks/dex/useLiquidityMismatch.ts +2 -5
- package/src/hooks/dex/useLpPosition.ts +21 -20
- package/src/hooks/dex/useMultipleTokenApprovalsWithSlippage.ts +40 -29
- package/src/hooks/dex/usePollPoolCreationRelayerApproval.ts +1 -1
- package/src/hooks/dex/usePoolEvents.ts +1 -1
- package/src/hooks/dex/usePools.ts +1 -1
- package/src/hooks/dex/usePriceImpact.ts +40 -0
- package/src/hooks/dex/useSingleAggregatorQuote.ts +350 -0
- package/src/hooks/enso/useBendZapSupply.ts +216 -0
- package/src/hooks/enso/useEnsoSwapBundle.ts +107 -0
- package/src/hooks/enso/useEnsoUserTokensWithBalances.ts +43 -0
- package/src/hooks/enso/useZapStakeBera.ts +113 -0
- package/src/hooks/{index.ts → exports.ts} +18 -7
- package/src/hooks/governance/useCreateProposal.ts +8 -8
- package/src/hooks/governance/usePollAllProposals.ts +1 -1
- package/src/hooks/governance/usePollProposal.ts +1 -1
- package/src/hooks/governance/usePollProposalThreshold.ts +1 -1
- package/src/hooks/governance/usePollUserDelegates.ts +1 -1
- package/src/hooks/governance/useProposalState.ts +2 -2
- package/src/hooks/honey/useCappedGlobally.ts +2 -1
- package/src/hooks/honey/useCappedRelatively.ts +1 -1
- package/src/hooks/honey/useCollateralWeights.ts +2 -1
- package/src/hooks/honey/useHoneyAlerts.ts +11 -11
- package/src/hooks/honey/useHoneyBalances.ts +7 -3
- package/src/hooks/honey/useHoneyGlobalData.ts +2 -1
- package/src/hooks/honey/useHoneySwapState.ts +2 -1
- package/src/hooks/honey/useHoneyVaultsBalance.ts +1 -1
- package/src/hooks/honey/useIsBadCollateralAsset.ts +2 -1
- package/src/hooks/honey/useIsBasketModeEnabled.ts +1 -1
- package/src/hooks/honey/usePythLatestPrices.ts +1 -1
- package/src/hooks/pol/useOnChainRewardVault.ts +3 -2
- package/src/hooks/pol/usePollGlobalData.ts +1 -1
- package/src/hooks/pol/usePollMarkets.ts +1 -1
- package/src/hooks/pol/useQueuedBeraUnlock.ts +17 -15
- package/src/hooks/pol/useRewardTokenToBeraRate.ts +6 -3
- package/src/hooks/pol/useRewardVault.ts +1 -1
- package/src/hooks/pol/useRewardVaults.ts +1 -1
- package/src/hooks/pol/useSWBeraVaultMetadata.ts +35 -0
- package/src/hooks/pol/useStakedAPR.ts +38 -0
- package/src/hooks/pol/useStakedData.ts +117 -0
- package/src/hooks/pol/useStakedSnapshots.ts +52 -0
- package/src/hooks/pol/useTotalStakedAmount.ts +30 -0
- package/src/hooks/pol/useUserVaultInfo.ts +1 -1
- package/src/hooks/pol/useVaultValidators.ts +1 -1
- package/src/hooks/tokens/useMultipleTokenInformation.ts +15 -6
- package/src/hooks/tokens/usePollAllowances.ts +15 -19
- package/src/hooks/tokens/usePollBalance.ts +8 -4
- package/src/hooks/tokens/usePollWalletBalances.ts +14 -11
- package/src/hooks/tokens/useStakingTokenInformation.ts +2 -1
- package/src/hooks/tokens/useTokenCurrentPrice.ts +4 -2
- package/src/hooks/tokens/useTokenCurrentPrices.ts +92 -13
- package/src/hooks/tokens/useTokenInformation.ts +11 -6
- package/src/hooks/tokens/useTokenPrice.ts +21 -0
- package/src/hooks/tokens/useTokenPrices.ts +133 -0
- package/src/hooks/tokens/useTokens.ts +1 -0
- package/src/hooks/tokens/useUnderlyingAsset.ts +23 -0
- package/src/hooks/transactions/transactionStore.ts +86 -65
- package/src/hooks/transactions/transactionStore.unit.test.ts +54 -1
- package/src/hooks/transactions/useAddRecentTransaction.ts +1 -1
- package/src/hooks/transactions/useRecentTransactions.ts +1 -1
- package/src/hooks/transactions/useSetTransactionStatus.ts +31 -0
- package/src/hooks/useContractWrite/useBeraContractWrite.ts +2 -1
- package/src/hooks/validators/useAllValidators.ts +1 -1
- package/src/hooks/validators/useApiValidator.ts +1 -1
- package/src/hooks/validators/useDailyValidatorBlockStats.ts +1 -1
- package/src/hooks/validators/useManagedValidatorByAccount.ts +1 -1
- package/src/hooks/validators/useManagedValidatorRole.ts +1 -1
- package/src/hooks/validators/useOnChainValidator.ts +1 -1
- package/src/hooks/validators/useStakingPoolBatch.ts +1 -1
- package/src/hooks/validators/useUserActiveValidators.ts +1 -1
- package/src/hooks/validators/useUserBoostsOnValidator.ts +1 -1
- package/src/hooks/validators/useUserClaimableIncentives.ts +8 -8
- package/src/hooks/validators/useValidator.ts +1 -1
- package/src/hooks/validators/useValidatorAnalytics.ts +1 -1
- package/src/hooks/validators/useValidatorCommission.ts +1 -1
- package/src/hooks/validators/useValidatorQueuedCommission.ts +1 -1
- package/src/hooks/validators/useValidatorQueuedOperatorAddress.ts +1 -1
- package/src/hooks/validators/useValidatorQueuedRewardAllocation.ts +1 -1
- package/src/hooks/validators/useValidatorRewardAllocation.ts +1 -1
- package/src/types/{dex.ts → dex.d.ts} +96 -67
- package/src/types/{enso.ts → enso.d.ts} +1 -1
- package/src/types/exports.ts +8 -0
- package/src/types/{global.ts → global.d.ts} +1 -30
- package/src/types/{governance.ts → governance.d.ts} +2 -64
- package/src/types/{honeySwap.ts → honeySwap.d.ts} +1 -13
- package/src/types/{pol.ts → pol.d.ts} +12 -1
- package/src/types/staking.d.ts +22 -0
- package/src/utils/createEmitter.ts +122 -0
- package/src/utils/createEmitter.unit.test.ts +149 -0
- package/src/utils/{index.ts → exports.ts} +3 -2
- package/src/utils/filter.ts +34 -0
- package/src/utils/formatNumber.ts +1 -1
- package/src/utils/formatNumber.unit.test.ts +2 -1
- package/src/utils/formatTokenList.ts +4 -10
- package/src/utils/getHoneySwapMessage.test.ts +1 -2
- package/src/utils/getServerSideClient.ts +4 -5
- package/src/utils/isDifferenceExceedingThreshold.ts +1 -1
- package/src/utils/layerZeroScan.ts +122 -0
- package/src/utils/math.ts +1 -1
- package/src/utils/parseWhiskToken.ts +15 -0
- package/src/utils/poolNamings.ts +1 -1
- package/src/utils/tokens.ts +23 -7
- package/dist/HoneyConfigProvider-6PXZJMSU.d.cts +0 -562
- package/dist/HoneyConfigProvider-CwDFrt02.d.ts +0 -562
- package/dist/abi/index.cjs +0 -2
- package/dist/abi/index.cjs.map +0 -1
- package/dist/abi/index.mjs +0 -2
- package/dist/actions/index.cjs +0 -2
- package/dist/actions/index.cjs.map +0 -1
- package/dist/actions/index.mjs +0 -2
- package/dist/aggregatorsRouter-Cny4B_MB.d.cts +0 -593
- package/dist/aggregatorsRouter-Cny4B_MB.d.ts +0 -593
- package/dist/chunk-22MQVFHP.cjs +0 -2
- package/dist/chunk-22MQVFHP.cjs.map +0 -1
- package/dist/chunk-3TKSVFZ3.mjs +0 -2
- package/dist/chunk-3TKSVFZ3.mjs.map +0 -1
- package/dist/chunk-6VF3RF53.cjs +0 -3
- package/dist/chunk-6VF3RF53.cjs.map +0 -1
- package/dist/chunk-6W22TFYA.mjs +0 -2
- package/dist/chunk-6W22TFYA.mjs.map +0 -1
- package/dist/chunk-AMRJ4B36.mjs +0 -2
- package/dist/chunk-AMRJ4B36.mjs.map +0 -1
- package/dist/chunk-DS2ZDVKU.mjs +0 -2
- package/dist/chunk-DS2ZDVKU.mjs.map +0 -1
- package/dist/chunk-ED43NYSE.cjs +0 -2
- package/dist/chunk-ED43NYSE.cjs.map +0 -1
- package/dist/chunk-EU4WFADK.cjs +0 -2
- package/dist/chunk-EU4WFADK.cjs.map +0 -1
- package/dist/chunk-HCTFDGXL.mjs +0 -2
- package/dist/chunk-HCTFDGXL.mjs.map +0 -1
- package/dist/chunk-IOSYBHKU.mjs +0 -2
- package/dist/chunk-IOSYBHKU.mjs.map +0 -1
- package/dist/chunk-JMKLDDKY.cjs +0 -2
- package/dist/chunk-JMKLDDKY.cjs.map +0 -1
- package/dist/chunk-KMKUXP2S.mjs +0 -3
- package/dist/chunk-KMKUXP2S.mjs.map +0 -1
- package/dist/chunk-OJXJ6CZ4.mjs +0 -4
- package/dist/chunk-OJXJ6CZ4.mjs.map +0 -1
- package/dist/chunk-PHIOKO3A.mjs +0 -2
- package/dist/chunk-PHIOKO3A.mjs.map +0 -1
- package/dist/chunk-QCK474XD.cjs +0 -2
- package/dist/chunk-QCK474XD.cjs.map +0 -1
- package/dist/chunk-REDXXUK7.cjs +0 -2
- package/dist/chunk-REDXXUK7.cjs.map +0 -1
- package/dist/chunk-S74ZMG2G.cjs +0 -2
- package/dist/chunk-S74ZMG2G.cjs.map +0 -1
- package/dist/chunk-TOAXF4YW.cjs +0 -2
- package/dist/chunk-TOAXF4YW.cjs.map +0 -1
- package/dist/chunk-UZ5CB33M.cjs +0 -2
- package/dist/chunk-UZ5CB33M.cjs.map +0 -1
- package/dist/chunk-VYWYJR63.mjs +0 -2
- package/dist/chunk-VYWYJR63.mjs.map +0 -1
- package/dist/chunk-XFPTQMAK.cjs +0 -4
- package/dist/chunk-XFPTQMAK.cjs.map +0 -1
- package/dist/chunk-YK4NINF5.mjs +0 -2
- package/dist/chunk-YK4NINF5.mjs.map +0 -1
- package/dist/contexts/index.cjs +0 -2
- package/dist/contexts/index.cjs.map +0 -1
- package/dist/contexts/index.mjs +0 -2
- package/dist/contexts/index.mjs.map +0 -1
- package/dist/enum/index.cjs +0 -2
- package/dist/enum/index.cjs.map +0 -1
- package/dist/enum/index.d.cts +0 -31
- package/dist/enum/index.d.ts +0 -31
- package/dist/enum/index.mjs +0 -2
- package/dist/enum/index.mjs.map +0 -1
- package/dist/errors/index.cjs +0 -2
- package/dist/errors/index.cjs.map +0 -1
- package/dist/errors/index.d.cts +0 -204
- package/dist/errors/index.d.ts +0 -204
- package/dist/errors/index.mjs +0 -2
- package/dist/errors/index.mjs.map +0 -1
- package/dist/hooks/index.cjs +0 -4
- package/dist/hooks/index.cjs.map +0 -1
- package/dist/hooks/index.mjs +0 -4
- package/dist/hooks/index.mjs.map +0 -1
- package/dist/staking-F9Nx9TKD.d.ts +0 -246
- package/dist/staking-f4BpYH7l.d.cts +0 -246
- package/dist/types/index.cjs +0 -2
- package/dist/types/index.cjs.map +0 -1
- package/dist/types/index.d.cts +0 -56
- package/dist/types/index.d.ts +0 -56
- package/dist/types/index.mjs +0 -2
- package/dist/types/index.mjs.map +0 -1
- package/dist/utils/index.cjs +0 -2
- package/dist/utils/index.cjs.map +0 -1
- package/dist/utils/index.mjs +0 -2
- package/dist/utils/index.mjs.map +0 -1
- package/src/actions/dex/getTransactionCount.ts +0 -29
- package/src/actions/enso/bend.ts +0 -143
- package/src/actions/enso/getEnsoUserToken.debug.test.ts +0 -57
- package/src/contexts/berajsProvider/context.tsx +0 -49
- package/src/contexts/berajsProvider/index.ts +0 -2
- package/src/contexts/berajsProvider/useBeraJs.ts +0 -18
- package/src/hooks/dex/usePollVaultIsPaused.ts +0 -30
- package/src/hooks/enso/useBendTransactionRequests.ts +0 -247
- package/src/hooks/enso/useEnsoZap.ts +0 -166
- package/src/hooks/enso/useZapTransactionRequests.ts +0 -81
- package/src/hooks/pol/useEarnedStakedBeraVault.ts +0 -59
- package/src/hooks/pol/useStakedBeraSnapshots.ts +0 -27
- package/src/hooks/validators/validatorRoleManager.ts +0 -0
- package/src/types/index.ts +0 -8
- package/src/types/staking.ts +0 -7
- package/src/utils/formatAggregatorsQuotes.ts +0 -57
- package/src/utils/formatAggregatorsQuotes.unit.test.ts +0 -191
- package/src/utils/sentryBeforeSend.ts +0 -52
- /package/dist/{abi/index.mjs.map → errors/exports.mjs.map} +0 -0
- /package/dist/{actions/index.mjs.map → types/exports.mjs.map} +0 -0
- /package/src/actions/dex/{__tests__ → aggregators}/haiku.integration.test.ts +0 -0
- /package/src/types/{bribe-boost.ts → bribe-boost.d.ts} +0 -0
package/dist/hooks/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../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.ts","../../src/actions/dex/aggregators/fly.ts","../../src/actions/dex/aggregators/haiku.ts","../../src/actions/dex/aggregators/honey.ts","../../src/actions/dex/aggregators/kyberswap.ts","../../src/actions/dex/aggregators/oogabooga.ts","../../src/actions/dex/aggregators/openOcean.ts","../../src/actions/dex/aggregators/wbera.ts","../../src/hooks/dex/useAggregatorsRouterFeeBps.ts","../../src/hooks/dex/useAllUserPools.ts","../../src/hooks/dex/useApiPool.ts","../../src/hooks/dex/useCreatePool.ts","../../src/utils/poolNamings.ts","../../src/hooks/dex/useExploitedTokens.ts","../../src/actions/dex/getIsTokenExploited.ts","../../src/hooks/dex/useGlobalLiquidityAndSwapVolume.ts","../../src/hooks/dex/useLiquidityMismatch.ts","../../src/hooks/dex/useLpPosition.ts","../../src/hooks/pol/useRewardVaultBalanceFromStakingToken.ts","../../src/hooks/pol/useRewardVaultFromToken.ts","../../src/hooks/tokens/usePollBalance.ts","../../src/hooks/tokens/useTokenInformation.ts","../../src/hooks/dex/useMultipleTokenApprovalsWithSlippage.ts","../../src/hooks/tokens/usePollAllowances.ts","../../src/hooks/dex/useOnChainPoolData.ts","../../src/hooks/tokens/useMultipleTokenInformation.ts","../../src/hooks/tokens/useTokenCurrentPrices.ts","../../src/hooks/tokens/useTokens.ts","../../src/hooks/dex/usePollPoolCreationRelayerApproval.ts","../../src/hooks/dex/usePool.ts","../../src/hooks/dex/usePoolEvents.ts","../../src/hooks/dex/usePoolHistoricalData.ts","../../src/hooks/dex/usePools.ts","../../src/hooks/enso/useBendTransactionRequests.ts","../../src/hooks/enso/useEnsoZap.ts","../../src/actions/enso/bend.ts","../../src/actions/enso/util.ts","../../src/actions/enso/zap.ts","../../src/actions/clients/getEnsoClient.ts","../../src/actions/enso/getEnsoUserToken.ts","../../src/hooks/enso/useZapTransactionRequests.ts","../../src/hooks/governance/useCreateProposal.ts","../../src/actions/governance/getProposalParams.ts","../../src/utils/hasAnyTruthyValues.ts","../../src/hooks/governance/useGetPastVotes.ts","../../src/hooks/governance/useProposalSnapshot.ts","../../src/hooks/governance/useHasVoted.ts","../../src/hooks/governance/useIsCanceller.ts","../../src/actions/governance/constants.ts","../../src/hooks/governance/usePollAllProposals.ts","../../src/hooks/governance/usePollProposal.ts","../../src/hooks/governance/usePollProposalThreshold.ts","../../src/hooks/governance/usePollProposalVotes.ts","../../src/hooks/governance/usePollUserDelegates.ts","../../src/hooks/governance/useProposalFromTx.ts","../../src/hooks/governance/useProposalState.ts","../../src/hooks/governance/useProposalTimelockState.ts","../../src/hooks/governance/useQuorum.ts","../../src/actions/governance/getQuorum.ts","../../src/hooks/honey/useCappedGlobally.ts","../../src/hooks/honey/usePythLatestPrices.ts","../../src/hooks/honey/useCappedRelatively.ts","../../src/hooks/honey/useCollateralWeights.ts","../../src/hooks/honey/useHoneyAlerts.ts","../../src/hooks/honey/useHoneyBalances.ts","../../src/hooks/honey/useHoneyVaultsBalance.ts","../../src/hooks/honey/useIsBadCollateralAsset.ts","../../src/hooks/honey/useHoneyChartData.ts","../../src/hooks/honey/useHoneyGlobalData.ts","../../src/hooks/honey/useHoneySwapState.ts","../../src/hooks/honey/useIsBasketModeEnabled.ts","../../src/hooks/perps/usePythUpdateFee.ts","../../src/hooks/pol/useBgtAprSimulation.ts","../../src/hooks/pol/useBgtUnstakedBalance.ts","../../src/hooks/pol/useClaimableFees.ts","../../src/hooks/pol/useEarnedStakedBeraVault.ts","../../src/hooks/pol/useHighestVaultsAPR.ts","../../src/hooks/pol/useRewardVaults.ts","../../src/hooks/pol/usePollGlobalData.ts","../../src/hooks/pol/usePollMarkets.ts","../../src/hooks/pol/useQueuedBeraUnlock.ts","../../src/hooks/pol/useRewardTokenToBeraRate.ts","../../src/hooks/pol/useRewardVault.ts","../../src/hooks/pol/useOnChainRewardVault.ts","../../src/actions/pol/getStakingTokenInformation.ts","../../src/hooks/pol/useRewardVaultIncentives.ts","../../src/hooks/pol/useRewardVaultRewards.ts","../../src/hooks/pol/useStakedBeraSnapshots.ts","../../src/hooks/pol/useUserVaultInfo.ts","../../src/hooks/pol/useUserVaults.ts","../../src/hooks/pol/useVaultAddress.ts","../../src/hooks/pol/useVaultHistory.ts","../../src/hooks/pol/useVaultValidators.ts","../../src/hooks/tokens/useBeraCurrentPrice.ts","../../src/hooks/tokens/useTokenCurrentPrice.ts","../../src/hooks/tokens/usePollWalletBalances.ts","../../src/hooks/tokens/useStakingTokenInformation.ts","../../src/hooks/tokens/useTotalSupply.ts","../../src/hooks/transactions/useAddRecentTransaction.ts","../../src/hooks/transactions/useRecentTransactions.ts","../../src/hooks/useBlockToTimestamp.ts","../../src/hooks/useContractWrite/useBeraContractWrite.ts","../../src/hooks/useContractWrite/stateReducer.ts","../../src/hooks/useGetVerifiedAbi.ts","../../src/hooks/useHistoryState.ts","../../src/hooks/usePrevious.ts","../../src/hooks/validators/useAllValidators.ts","../../src/hooks/validators/useApiEnrichedAllocation.ts","../../src/hooks/validators/useApiValidator.ts","../../src/hooks/validators/useBaselineRewardAllocation.ts","../../src/abi/pol/rewardAllocationFactory.ts","../../src/actions/validators/getBaselineRewardAllocation.ts","../../src/hooks/validators/useDailyValidatorBlockStats.ts","../../src/hooks/validators/useDefaultRewardAllocation.ts","../../src/hooks/validators/useManagedValidatorByAccount.ts","../../src/hooks/validators/useManagedValidatorRole.ts","../../src/actions/validators/getValidatorRewardAllocatorAddress.ts","../../src/hooks/validators/useOnChainValidator.ts","../../src/hooks/validators/useStakingPoolBatch.ts","../../src/hooks/validators/useSubgraphUserValidators.ts","../../src/hooks/validators/useUserActiveValidators.ts","../../src/hooks/validators/useUserBoostsOnValidator.ts","../../src/hooks/validators/useUserClaimableIncentives.ts","../../src/utils/formatIncentivesTokenMap.ts","../../src/hooks/validators/useUserStakingPositions.ts","../../src/hooks/validators/useValidator.ts","../../src/hooks/validators/useValidatorAnalytics.ts","../../src/hooks/validators/useValidatorCommission.ts","../../src/hooks/validators/useValidatorEstimatedBgtPerYear.ts","../../src/hooks/validators/useValidatorQueuedCommission.ts","../../src/hooks/validators/useValidatorQueuedOperatorAddress.ts","../../src/hooks/validators/useValidatorQueuedRewardAllocation.ts","../../src/hooks/validators/useValidatorRewardAllocation.ts"],"sourcesContent":["import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { type GetConvertToAssetsProps, getConvertToAssets } from \"~/actions\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types\";\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 useSWR, { type SWRConfiguration } from \"swr\";\nimport { type Address, type PublicClient, parseUnits, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { BaseAggregator } from \"~/actions/dex/aggregators/base\";\nimport { bex } from \"~/actions/dex/aggregators/bex\";\nimport { bgtRedeem } from \"~/actions/dex/aggregators/bgt\";\nimport { enso } from \"~/actions/dex/aggregators/enso\";\nimport { fly } from \"~/actions/dex/aggregators/fly\";\nimport { haiku } from \"~/actions/dex/aggregators/haiku\";\nimport {\n HoneyNativeAggregator,\n honeyNative,\n} 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 {\n HoneyConfigContextReturn,\n TokenWithOrder,\n} from \"~/contexts/HoneyConfigProvider\";\nimport { POLLING } from \"~/enum\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { RequestError } from \"~/errors/RequestError\";\nimport { useAggregatorsRouterFeeBps } from \"~/hooks\";\nimport type {\n DefaultHookOptions,\n IRawAggregatorQuote,\n SwapReferrer,\n} from \"~/types\";\nimport type { Aggregators } from \"~/types/dex\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { seconds } from \"~/utils/time\";\nimport { isToken } from \"~/utils/tokens\";\nimport { useBexStatus } from \"./useBexStatus\";\n\nconst AGGREGATORS = [\n oogabooga,\n fly,\n kyberswap,\n openOcean,\n haiku,\n enso,\n bex,\n honeyNative,\n];\n\ntype IUseAggregatorsQuotesArgs = BeraJS.BaseFunctionArgs & {\n tokenIn: Address;\n tokenOut: Address;\n tokenInDecimals: number;\n tokenOutDecimals: number;\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\ntype IQueryKey = readonly [\n string, // \"useAggregatorsQuotes\n string, // name\n Address, // tokenIn\n Address, // tokenOut\n string, // parsedAmount\n number, // slippage\n Address | undefined, // account\n number | undefined, // feeBps\n number, // tokenInDecimals\n number, // tokenOutDecimals\n SwapReferrer | undefined, // referrer\n Address | undefined, // rewardVault\n TokenWithOrder[] | undefined, // collateralList\n];\n\nexport const USE_AGGREGATORS_QUOTES_QUERY_KEY = \"useAggregatorsQuotes\";\n\nfunction getQueryKey({\n name,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n honeyNativeState,\n}: {\n name: Aggregators;\n account: Address | undefined;\n args: IUseAggregatorsQuotesArgs;\n feeBps: number | undefined;\n options?: DefaultHookOptions;\n /**\n * List of active aggregators fetched from edge config flags.\n *\n * If undefined, all aggregators are enabled.\n */\n activeAggregators: string[] | undefined;\n honeyNativeState?: Pick<HoneyConfigContextReturn, \"collateralList\">;\n}): IQueryKey | null {\n if (name !== bgtRedeem.name) {\n if (\n isToken(args.tokenIn, \"BGT\", { chainId: defaultChainId }) ||\n isToken(args.tokenOut, \"BGT\", { chainId: defaultChainId })\n ) {\n // can't happen, but just in case\n return null;\n }\n }\n\n const {\n tokenIn,\n tokenOut,\n tokenInDecimals,\n tokenOutDecimals,\n amount,\n slippage,\n referrer,\n rewardVault,\n } = args;\n const parsedAmount = parseUnits(amount, tokenInDecimals).toString();\n\n const isEnabledOnConfig =\n !activeAggregators ||\n activeAggregators.includes(name.toLowerCase().replaceAll(\" \", \"\"));\n\n return options?.opts?.isEnabled &&\n Number(amount) &&\n feeBps !== undefined &&\n isEnabledOnConfig\n ? [\n USE_AGGREGATORS_QUOTES_QUERY_KEY,\n name,\n tokenIn,\n tokenOut,\n parsedAmount,\n slippage,\n account,\n feeBps,\n tokenInDecimals,\n tokenOutDecimals,\n referrer,\n rewardVault,\n honeyNativeState?.collateralList,\n ]\n : null;\n}\n\nfunction getQueryFn({\n aggregator,\n publicClient,\n proxyAggregatorsThroughVercel,\n}: {\n aggregator: BaseAggregator;\n publicClient?: PublicClient;\n proxyAggregatorsThroughVercel?: boolean;\n}) {\n return async ([\n ,\n ,\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account,\n aggregatorsFeeBps,\n tokenInDecimals,\n tokenOutDecimals,\n referrer,\n rewardVault,\n honeyCollaterals,\n ]: IQueryKey) =>\n aggregator.getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account,\n aggregatorsFeeBps,\n tokenInDecimals,\n tokenOutDecimals,\n publicClient,\n proxyAggregatorsThroughVercel,\n referrer,\n rewardVault,\n honeyNativeState: {\n collateralList: honeyCollaterals ?? [],\n },\n });\n}\n\nexport const 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 { collateralList: collaterals, protocol: honeyProtocol } =\n args.honeyNativeState ?? {};\n\n const isWrapOrUnwrap =\n (isToken(args.tokenIn, \"BERA\") || isToken(args.tokenIn, \"WBERA\")) &&\n (isToken(args.tokenOut, \"BERA\") || isToken(args.tokenOut, \"WBERA\"));\n\n const isBgtRedeem = isToken(args.tokenIn, \"BGT\", { chainId: defaultChainId });\n\n // retrieve the honey collaterals in order to check if the swap is a honey mint or redeem\n const isHoneyNative = useMemo(\n () => HoneyNativeAggregator.isHoneyNativeSwap(args),\n [args.tokenOut, args.tokenIn, collaterals],\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: SWRConfiguration = {\n refreshInterval: POLLING.FAST, // every 10s\n errorRetryCount: 3,\n // biome-ignore lint/nursery/useMaxParams: the function is defined in the SWRConfiguration type\n onErrorRetry(err, key, config, revalidate, revalidateOpts) {\n if (err instanceof BeraError) {\n if (err.reason === BaseAggregator.PATH_NOT_FOUND_REASON) {\n return;\n }\n }\n\n if (err instanceof RequestError && err.statusCode === 403) {\n console.warn(key[1], \"returned error 403, stopping retries\");\n return;\n }\n\n if (revalidateOpts.retryCount > (config.errorRetryCount ?? 3)) {\n return;\n }\n\n setTimeout(() => {\n revalidate();\n }, config.errorRetryInterval ?? seconds(10));\n },\n };\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 = useSWR(\n isNativeSwap || !isMAEnabled\n ? null\n : getQueryKey({\n name: oogabooga.name,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n }),\n getQueryFn({ aggregator: oogabooga, proxyAggregatorsThroughVercel }),\n swrOptions,\n );\n const flyResult = useSWR(\n isNativeSwap || !isMAEnabled\n ? null\n : getQueryKey({\n name: fly.name,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n }),\n getQueryFn({ aggregator: fly, proxyAggregatorsThroughVercel }),\n swrOptions,\n );\n const kyberswapResult = useSWR(\n isNativeSwap || !isMAEnabled\n ? null\n : getQueryKey({\n name: kyberswap.name,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n }),\n getQueryFn({ aggregator: kyberswap, proxyAggregatorsThroughVercel }),\n swrOptions,\n );\n const openOceanResult = useSWR(\n isNativeSwap || !isMAEnabled\n ? null\n : getQueryKey({\n name: openOcean.name,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n }),\n getQueryFn({\n aggregator: openOcean,\n publicClient,\n proxyAggregatorsThroughVercel,\n }),\n swrOptions,\n );\n const haikuResult = useSWR(\n isNativeSwap || !isMAEnabled\n ? null\n : getQueryKey({\n name: haiku.name,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n }),\n getQueryFn({\n aggregator: haiku,\n publicClient,\n proxyAggregatorsThroughVercel,\n }),\n\n swrOptions,\n );\n const ensoResult = useSWR(\n isNativeSwap || !isMAEnabled\n ? null\n : getQueryKey({\n name: enso.name,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n }),\n getQueryFn({ aggregator: enso, proxyAggregatorsThroughVercel }),\n swrOptions,\n );\n const { protocol: bexProtocol } = useBexStatus();\n\n const bexResult = useSWR(\n isNativeSwap ||\n // dont use undefined as falsy\n bexProtocol.isPaused === true ||\n // BEX is not able to stake in a single transaction\n args.rewardVault\n ? null\n : getQueryKey({\n name: bex.name,\n account,\n args,\n // Always zero on bex swaps\n feeBps: 0,\n options,\n activeAggregators,\n }),\n getQueryFn({ aggregator: bex, publicClient }),\n swrOptions,\n );\n const wberaSwapResult = useSWR(\n isWrapOrUnwrap\n ? getQueryKey({\n name: wberaSwap.name,\n account,\n args,\n // Always 0 for wrap/unwrap\n feeBps: 0,\n options,\n // wbera is always enabled\n activeAggregators: undefined,\n })\n : null,\n async ([, , tokenIn, tokenOut, amount, , account]: IQueryKey) => {\n return wberaSwap.getQuote({\n tokenIn,\n tokenOut,\n amount,\n account,\n });\n },\n swrOptions,\n );\n const bgtRedeemResult = useSWR(\n isBgtRedeem\n ? getQueryKey({\n name: bgtRedeem.name,\n account,\n args,\n // Always 0 for native swaps\n feeBps: 0,\n options,\n // BGT redeem is always enabled\n activeAggregators: undefined,\n })\n : null,\n async ([, , tokenIn, , amount]: IQueryKey) => {\n return bgtRedeem.getQuote({\n tokenIn,\n amount,\n });\n },\n swrOptions,\n );\n const honeyResult = useSWR(\n !isHoneyNative ||\n isNativeSwap ||\n honeyProtocol?.isPaused === true ||\n !collaterals\n ? null\n : getQueryKey({\n name: honeyNative.name,\n account,\n args,\n // Always 0 for honey mint/redeem\n feeBps: 0,\n options,\n // honey mint/redeem is always enabled\n activeAggregators: undefined,\n honeyNativeState: {\n collateralList: collaterals,\n },\n }),\n getQueryFn({\n aggregator: honeyNative,\n publicClient,\n proxyAggregatorsThroughVercel,\n }),\n swrOptions,\n );\n const results = isWrapOrUnwrap\n ? [wberaSwapResult]\n : isBgtRedeem\n ? [bgtRedeemResult]\n : [\n oogaBogaResult,\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 * as Sentry from \"@sentry/nextjs\";\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 { assertPublicClient } from \"~/errors/assert\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport { RequestError } from \"~/errors/RequestError\";\nimport {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n} from \"~/types\";\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: 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 });\n Sentry.captureException(error, {\n level: \"warning\",\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 }\n }\n\n async getQuote(args: IAggregatorArgs): Promise<IRawAggregatorQuote<false>> {\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 tokenInDecimals,\n tokenOutDecimals,\n amount,\n slippage,\n account = zeroAddress,\n publicClient,\n } = args;\n this.checkChainSupport();\n\n assertPublicClient(publicClient);\n\n if (!tokenInDecimals) {\n throw new InvalidArgumentError({\n property: \"tokenInDecimals\",\n value: tokenInDecimals,\n expected: \"number\",\n chainId: this.chainId,\n });\n }\n\n if (!tokenOutDecimals) {\n throw new InvalidArgumentError({\n property: \"tokenOutDecimals\",\n value: tokenOutDecimals,\n expected: \"number\",\n chainId: this.chainId,\n });\n }\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 as Address),\n tokenInDecimals,\n );\n const tokenOutV3 = new Token(\n this.chainId,\n this.convertZeroToWrapped(tokenOut as Address),\n tokenOutDecimals,\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 queryOutput.expectedAmountOut,\n sorPaths,\n sorAmount,\n args,\n );\n\n // format quote response\n const formattedQuote = {\n amountOut: queryOutput.expectedAmountOut.amount.toString(),\n amountIn: amount,\n spender: queryOutput.to,\n name: this.name,\n priceImpactPercentage: this.calculatePriceImpact(priceImpact),\n swapFeeBps: 0,\n };\n if (account === zeroAddress) return formattedQuote;\n\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 ...formattedQuote,\n calldata: {\n params,\n functionName,\n abi: balancerVaultAbi,\n address: callData.to,\n value: callData.value || BigInt(0),\n },\n };\n }\n}\n\nexport const bex = new BexAggregator();\n","import { ChainId } from \"@berachain/config/internal\";\n\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n} from \"~/types\";\nimport { 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 // 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.checkChainSupport();\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 spender: undefined,\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 {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n} from \"~/types\";\nimport { BaseAggregator } from \"./base\";\n\nclass EnsoAggregator extends BaseAggregator {\n name = Aggregators.Enso;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n\n notFoundMessages: string[] = [\n \"Could not build shortcuts for route\",\n \"Swap not found for a required underlying of defi route,\",\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.checkChainSupport();\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn, tokenOut);\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 spender: this.config.bex.aggregatorsRouter,\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n\n calldata: {\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 { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { aggregatorsRouterAbi } from \"~/abi/bex/aggregatorsRouter\";\nimport {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n} from \"~/types\";\nimport { isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\nconst BASE_URL = \"https://api.magpiefi.xyz/aggregator\";\n\nclass FlyAggregator extends BaseAggregator {\n name = Aggregators.Fly;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n notFoundMessages: string[] = [\n \"Couldn't recognize to token\",\n \"There is not enough liquidity. Amount is too high.\",\n \"Routes were not found\",\n ];\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n aggregatorsFeeBps,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.checkChainSupport();\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn, tokenOut);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n const url = new URL(`${BASE_URL}/quote`);\n this.url = url.toString();\n const params = new URLSearchParams({\n fromTokenAddress: tokenInAddress,\n toTokenAddress: tokenOutAddress,\n sellAmount: inputAmountAfterFees,\n slippage: (slippage / 100).toString(),\n gasless: \"false\",\n network: \"berachain\",\n });\n\n if (account !== zeroAddress) {\n // fly will transfer funds from the executor and will send amountOut to the executor\n // which in turn will send the funds to the account\n params.set(\"fromAddress\", this.config.bex.aggregatorsRouterExecutor);\n params.set(\"toAddress\", this.config.bex.aggregatorsRouterExecutor);\n }\n url.search = params.toString();\n\n const response = await this.fetch(url);\n\n const quoteData = await response.json();\n\n const formattedQuote = {\n amountOut: quoteData.amountOut,\n amountIn: amount,\n spender: this.config.bex.aggregatorsRouter,\n name: this.name,\n swapFeeBps: aggregatorsFeeBps ?? 0,\n };\n // if no account, return quote early\n if (account === zeroAddress) return formattedQuote;\n\n // fetch transaction data immediately to improve UX and prevent potential failures during swap execution\n const txUrl = new URL(`${BASE_URL}/transaction`);\n this.url = txUrl.toString();\n\n const txParams = new URLSearchParams({\n quoteId: quoteData.id,\n estimateGas: \"false\",\n });\n txUrl.search = txParams.toString();\n\n const txResponse = await this.fetch(txUrl);\n\n const txData = await txResponse.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(quoteData.amountOut, slippage),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: txData.to,\n data: txData.data,\n };\n\n return {\n ...formattedQuote,\n calldata: {\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: isToken(tokenIn, \"BERA\") ? BigInt(amount) : BigInt(\"0\"),\n address: this.config.bex.aggregatorsRouter,\n },\n };\n }\n}\n\nexport const fly = new FlyAggregator();\n","import { formatUnits, parseUnits, zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { aggregatorsRouterAbi } from \"~/abi\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n} from \"~/types\";\nimport { SwapReferrer } from \"~/types/dex\";\nimport { BaseAggregator } from \"./base\";\n\nclass HaikuAggregator extends BaseAggregator {\n name = Aggregators.Haiku;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n\n notFoundMessages: string[] = [\n \"token not found\",\n \"Token is not supported\",\n \"No route found for the given input or the liquidity is not enough\",\n \"Invalid input amount. Please ensure the total amount of input is greater than 0.001 USD\",\n ];\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n tokenInDecimals,\n tokenOutDecimals,\n aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n referrer,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n if (tokenInDecimals === undefined || tokenOutDecimals === undefined) {\n throw new BeraError({\n message: \"Missing required params\",\n level: \"error\",\n });\n }\n\n this.checkChainSupport();\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn, tokenOut);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n // get route quote from haiku api\n const quoteBody = {\n intent: {\n allowancesMode: \"approve\",\n slippage: slippage / 100,\n receiver: this.config.bex.aggregatorsRouterExecutor,\n input_positions: {\n [`bera:${tokenInAddress}`]: formatUnits(\n BigInt(inputAmountAfterFees),\n tokenInDecimals,\n ),\n },\n target_weights: {\n [`bera:${tokenOutAddress}`]: 1, // 100% into the output token\n },\n },\n };\n\n // haiku request to use separate API KEYs for zap and swap\n // hence the separate proxy paths (api keys are used at the proxy level)\n const proxyPath = referrer === SwapReferrer.ZAP ? \"zap-haiku\" : \"haiku\";\n\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=haikuQuote`\n : `${this.config.bex.aggregatorsProxyUrl}/${proxyPath}/v1/quoteIntent`;\n\n const quoteResponse = await this.fetch(\n // using vercel proxy in development to avoid CORS issues\n this.url,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(quoteBody),\n },\n );\n\n const quoteData = await quoteResponse.json();\n\n const formattedQuote = {\n amountOut: parseUnits(\n quoteData.balances[0].amount,\n tokenOutDecimals,\n ).toString(),\n amountIn: amount,\n spender: this.config.bex.aggregatorsRouter,\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n };\n\n // If no account, return quote early\n if (account === zeroAddress) return formattedQuote;\n\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=haikuSolve`\n : `${this.config.bex.aggregatorsProxyUrl}/${proxyPath}/v1/solveIntent`;\n\n const solveResponse = await this.fetch(this.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n quoteId: quoteData.quoteId,\n }),\n });\n\n const solveData = await solveResponse.json();\n\n const inputData = this.getInputData({\n tokenIn: tokenInAddress,\n amountIn: amount,\n isNative: isTokenInNative,\n isPermit2Approval: true, // haiku requires permit2 approval\n permit2SpenderAddress: this.config.bex.haikuAgentAddress,\n });\n\n const outputData = {\n tokenOut: tokenOutAddress,\n receiver: account,\n minAmountOut: this.getMinAmountOut(formattedQuote.amountOut, slippage),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: solveData.to,\n data: solveData.data,\n };\n\n return {\n ...formattedQuote,\n calldata: {\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 haiku = new HaikuAggregator();\n","import { BigNumber } from \"bignumber.js\";\nimport { type Address, formatUnits } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport {\n getHoneyPreview,\n type HoneyPreviewArgs,\n HoneyPreviewMethod,\n} from \"~/actions/honey/getHoneyPreview\";\nimport { getHoneyVaultsBalance } from \"~/actions/honey/getHoneyVaultsBalance\";\nimport { getSwapPayload } from \"~/actions/honey/getSwapPayload\";\nimport { isBasketModeEnabled } from \"~/actions/honey/isBasketModeEnabled\";\nimport type { HoneyConfigContextReturn } from \"~/contexts/HoneyConfigProvider\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n type TokenWithMetadata,\n} from \"~/types/dex\";\nimport { getHoneyToken, isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\ninterface IHoneyNativeArgs\n extends Omit<\n IAggregatorArgs,\n \"slippage\" | \"feeBps\" | \"aggregatorsFeeBps\" | \"referrer\"\n > {}\n\nfunction _getPreviewMethod(isMint: boolean): HoneyPreviewMethod {\n return isMint ? HoneyPreviewMethod.Mint : HoneyPreviewMethod.Redeem;\n}\n\nexport class HoneyNativeAggregator extends BaseAggregator {\n name = Aggregators.Honey;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rpc\";\n\n readonly honeyToken: TokenWithMetadata = getHoneyToken(this);\n /**\n * Determines if the swap is a honey mint or redeem based on the tokenIn, tokenOut and the colalterals passed.\n * @returns True if the swap is a honey mint or redeem\n */\n static isHoneyNativeSwap({\n tokenIn,\n tokenOut,\n honeyNativeState,\n ...args\n }: BeraJS.BaseFunctionArgs & {\n tokenIn: Address;\n tokenOut: Address;\n honeyNativeState?: Pick<HoneyConfigContextReturn, \"collateralList\">;\n }) {\n if (!honeyNativeState?.collateralList) return false;\n\n const isMint = isToken(tokenOut, \"HONEY\", args);\n const isRedeem = isToken(tokenIn, \"HONEY\", args);\n\n if (!isMint && !isRedeem) return false;\n\n return honeyNativeState.collateralList.some((coll) =>\n isToken(coll.address, isMint ? tokenIn : tokenOut),\n );\n }\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n publicClient,\n account,\n honeyNativeState,\n }: IHoneyNativeArgs): Promise<IRawAggregatorQuote<false> | undefined> {\n const { collateralList: collaterals } = honeyNativeState ?? {};\n if (!collaterals) {\n throw new InvalidArgumentError({\n message: \"Invalid Honey Context state\",\n property: \"collaterals\",\n value: collaterals,\n expected: \"TokenWithOrder[]\",\n });\n }\n assertPublicClient(publicClient);\n\n this.checkChainSupport();\n\n const isMint = isToken(tokenOut, this.honeyToken);\n\n // these should never happen but just in case\n // checking that the tokenOut & tokenIn are correct to allow mint or redeem\n if (\n !HoneyNativeAggregator.isHoneyNativeSwap({\n tokenIn: tokenIn as Address,\n tokenOut: tokenOut as Address,\n honeyNativeState,\n })\n ) {\n throw new BeraError({\n message: \"Honey Aggregator only supports minting or redeeming Honey\",\n });\n }\n\n /**\n * The collaterals on Honey are managed with a state that changes the order based on the selected collateral.\n * hub does not do that, so we need to order the collaterals based on the tokenIn.\n * The first collateral will be the tokenIn.\n * */\n const hubOrderedCollaterals = collaterals;\n\n // Check if the token requested as collateral is a valid collateral token that can be used to mint or redeem honey\n const collateral = collaterals.find((collateral) =>\n isToken(\n collateral.address,\n isMint ? (tokenIn as Address) : (tokenOut as Address),\n ),\n );\n if (!collateral) {\n throw new BeraError({\n message: \"This collateral is not part of the Honey protocol\",\n });\n }\n\n /*\n * honeyVaultBalances: Balances of the collateral's vault to check if the vault has enough liquidity\n * isBasketMode: Whether the basket mode is enabled\n */\n const [honeyVaultBalances, isBasketMode] = await Promise.all([\n getHoneyVaultsBalance({\n client: publicClient,\n collateralList: [collateral],\n }),\n isBasketModeEnabled({\n client: publicClient,\n isMint,\n collateralList: collaterals,\n latestPrices: undefined, // no need to get the latest prices for the aggregator\n isPythWrapperEnabled: false, // Pyth wrapper is not supported for the aggregator\n }),\n ]);\n if (!honeyVaultBalances) {\n throw new BeraError({\n message: \"Failed to fetch the Honey vault balances\",\n });\n }\n // Need this to prevent mint or redeem in case of a basket mode\n if (isBasketMode) {\n return undefined;\n }\n\n const collateralVaultBalance = honeyVaultBalances[0];\n\n // Order the collaterals manually\n const collateralIdx = collateral.order;\n if (hubOrderedCollaterals.length > 1 && collateralIdx !== 0) {\n hubOrderedCollaterals.splice(collateralIdx, 1);\n hubOrderedCollaterals.unshift(collateral);\n }\n\n // Honey's contract expects the amount to be in a raw format\n const honeyFormattedAmountIn = formatUnits(\n BigInt(amount),\n isMint ? collateral.decimals : this.honeyToken.decimals,\n );\n\n // Parameters for the honey preview call\n const quoteParams = {\n client: publicClient,\n collateral: collateral,\n collateralList: collaterals,\n amount: honeyFormattedAmountIn,\n method: _getPreviewMethod(isMint),\n latestPrices: undefined, // no need to get the latest prices for the aggregator\n isPythWrapperEnabled: false, // Pyth wrapper is not supported for the aggregator\n } satisfies HoneyPreviewArgs;\n\n // Get the quote for the Honey mint\n const quoteData = await getHoneyPreview(quoteParams);\n\n if (!quoteData) {\n throw new BeraError({\n message: \"Failed to fetch the Honey preview\",\n });\n }\n\n // The quote contains the honey & the collaterals amount, but we'll only ever need honey\n const { honey: honeyQuote, collaterals: collateralsQuote } = quoteData;\n\n // check if the vault has enough liquidity to redeem the collateral\n const haveEnoughLiquidity = !isMint\n ? new BigNumber(collateralVaultBalance?.formattedBalance ?? \"0\").gte(\n formatUnits(\n collateralsQuote[collateral.address],\n collateral.decimals,\n ),\n )\n : true;\n\n if (!haveEnoughLiquidity) {\n return undefined;\n }\n\n /**\n * Get the swap payload for the Honey mint\n * If the account is not provided, we will not get the payload\n */\n const payload = account\n ? await getSwapPayload({\n state: {\n actionType: isMint ? \"mint\" : \"redeem\",\n fromAmount: [honeyFormattedAmountIn],\n collaterals: hubOrderedCollaterals,\n isBasketModeEnabled: false, // In Hub, we don't support basket mode\n },\n account: account,\n collateralList: hubOrderedCollaterals,\n publicClient,\n priceFeedMap: undefined,\n isPythWrapperEnabled: false,\n })\n : undefined;\n\n // In case the user is not connected the payload will not be generated but the preview yes\n if (!payload && account) {\n throw new BeraError({\n message: \"Failed to fetch the Honey swap payload\",\n });\n }\n\n return {\n amountIn: amount,\n amountOut: isMint\n ? honeyQuote.toString()\n : collateralsQuote[collateral.address].toString(),\n spender: this.config.honey.factory,\n name: Aggregators.Honey,\n swapFeeBps: 0,\n calldata: payload,\n };\n }\n}\n\nexport const honeyNative = new HoneyNativeAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { aggregatorsRouterAbi } from \"~/abi/bex/aggregatorsRouter\";\nimport {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n} from \"~/types\";\nimport { BaseAggregator } from \"./base\";\n\nclass KyberSwapAggregator extends BaseAggregator {\n name = Aggregators.KyberSwap;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n\n notFoundMessages = [\n \"token not found\",\n \"route not found\",\n \"amountIn is greater than max allowed\",\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.checkChainSupport();\n const {\n isTokenInNative,\n isTokenOutNative,\n tokenInAddress,\n tokenOutAddress,\n } = this.parseAddresses(tokenIn, tokenOut);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=kyberswapRoutes`\n : `${this.config.bex.aggregatorsProxyUrl}/kyberswap/berachain/api/v1/routes`;\n\n const url = new URL(this.url);\n // First, get route quote\n url.searchParams.set(\"tokenIn\", tokenInAddress);\n url.searchParams.set(\"tokenOut\", tokenOutAddress);\n url.searchParams.set(\"amountIn\", inputAmountAfterFees);\n url.searchParams.set(\"slippageTolerance\", (slippage / 100).toString());\n url.searchParams.set(\"to\", this.config.bex.aggregatorsRouterExecutor);\n url.searchParams.set(\"clientData\", JSON.stringify({ source: \"berachain\" }));\n\n const routeResponse = await this.fetch(url);\n\n const routeData = await routeResponse.json();\n const formattedQuote = {\n amountOut: routeData.data.routeSummary.amountOut,\n amountIn: amount,\n spender: this.config.bex.aggregatorsRouter,\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n };\n\n // If no account, return quote early\n if (account === zeroAddress) return formattedQuote;\n\n // Get the build route data for transaction\n const buildRouteBody = {\n routeSummary: routeData.data.routeSummary,\n sender: this.config.bex.aggregatorsRouterExecutor,\n recipient: this.config.bex.aggregatorsRouterExecutor,\n slippageTolerance: slippage * 100, // kyberswap expects the slippage in basis points\n deadline: Math.floor(Date.now() / 1000) + 60 * 5, // 5 minutes from now\n source: \"berachain\",\n };\n\n const params = url.searchParams.entries();\n\n const buildUrl = new URL(\n proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=kyberswapBuild`\n : `${this.config.bex.aggregatorsProxyUrl}/kyberswap/berachain/api/v1/route/build`,\n );\n\n for (const [key, value] of params) {\n buildUrl.searchParams.set(key, value);\n }\n\n const buildRouteResponse = await this.fetch(buildUrl, {\n method: \"POST\",\n body: JSON.stringify(buildRouteBody),\n });\n\n const buildData = await buildRouteResponse.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(formattedQuote.amountOut, slippage),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: buildData.data.routerAddress,\n data: buildData.data.data,\n };\n\n return {\n ...formattedQuote,\n calldata: {\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 kyberswap = new KyberSwapAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { aggregatorsRouterAbi } from \"~/abi/bex/aggregatorsRouter\";\nimport {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n} from \"~/types\";\nimport { BaseAggregator } from \"./base\";\n\nclass OogaboogaAggregator extends BaseAggregator {\n name = Aggregators.Oogabooga;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\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.checkChainSupport();\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn, tokenOut);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n const params = new URLSearchParams({\n tokenIn: tokenInAddress,\n tokenOut: tokenOutAddress,\n amount: inputAmountAfterFees,\n slippage: (slippage / 100).toString(),\n to: this.config.bex.aggregatorsRouterExecutor,\n referrer: this.config.bex.aggregatorsRouter,\n });\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=oogabooga&${params.toString()}`\n : `${this.config.bex.aggregatorsProxyUrl}/oogabooga/v1/swap?${params.toString()}`;\n\n const response = await this.fetch(this.url);\n\n const quote = await response.json();\n\n const formattedQuote = {\n amountOut: quote.assumedAmountOut,\n amountIn: amount,\n spender: this.config.bex.aggregatorsRouter,\n name: this.name,\n priceImpactPercentage: quote.priceImpact,\n swapFeeBps: aggregatorsFeeBps!,\n };\n\n // if no account, return quote early\n if (account === zeroAddress) return formattedQuote;\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(formattedQuote.amountOut, slippage),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quote.tx?.to,\n data: quote.tx?.data,\n };\n\n return {\n ...formattedQuote,\n calldata: {\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 oogabooga = new OogaboogaAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { aggregatorsRouterAbi } from \"~/abi/bex/aggregatorsRouter\";\nimport { assertPublicClient, InvalidArgumentError } from \"~/errors\";\nimport { RequestError } from \"~/errors/RequestError\";\nimport {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n} from \"~/types\";\nimport { BaseAggregator } from \"./base\";\n\nclass OpenOceanAggregator extends BaseAggregator {\n name = Aggregators.OpenOcean;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n readonly url = \"https://open-api.openocean.finance/v4/bera/swap\";\n\n notFoundMessages = [\"No avail liquidity for the pair\"];\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n aggregatorsFeeBps,\n tokenInDecimals,\n publicClient,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n assertPublicClient(publicClient);\n\n if (!tokenInDecimals) {\n throw new InvalidArgumentError({\n property: \"tokenInDecimals\",\n value: tokenInDecimals,\n expected: \"number\",\n chainId: this.chainId,\n });\n }\n\n this.checkChainSupport();\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn, tokenOut);\n\n const gasPrice = (await publicClient.getGasPrice()).toString();\n\n const quoteParams = new URLSearchParams({\n chain: ChainId.MAINNET.toString(),\n inTokenAddress: tokenInAddress,\n outTokenAddress: tokenOutAddress,\n amountDecimals: inputAmountAfterFees,\n // OpenOcean requires slippage to be at least 0.01%\n slippage: slippage < 0.01 ? \"0.01\" : slippage.toString(),\n account: this.config.bex.aggregatorsRouterExecutor,\n referrer: this.config.bex.aggregatorsRouter,\n gasPrice,\n });\n\n const quoteResponse = await this.fetch(\n `${this.url}?${quoteParams.toString()}`,\n );\n\n const quoteData = await quoteResponse.json();\n\n // validate successful quote response\n if (quoteData.code !== 200 || !quoteData.data) {\n const isNotFound = this.notFoundMessages.some((message) =>\n quoteData.error.includes(message),\n );\n\n throw new RequestError({\n response: quoteResponse,\n endpoint: { url: this.url, name: this.name, type: this.type },\n cause: quoteData,\n reason: isNotFound\n ? BaseAggregator.PATH_NOT_FOUND_REASON\n : quoteData.error,\n });\n }\n\n const formattedQuote = {\n amountOut: quoteData.data.outAmount,\n amountIn: amount,\n spender: this.config.bex.aggregatorsRouter,\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n };\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(formattedQuote.amountOut, slippage),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quoteData.data.to,\n data: quoteData.data.data,\n };\n\n return {\n ...formattedQuote,\n calldata: {\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 openOcean = new OpenOceanAggregator();\n","import { ChainId } from \"@berachain/config/internal\";\n\nimport { wberaAbi } from \"~/abi/pol/wbera\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport {\n Aggregators,\n type IAggregatorArgs,\n type IRawAggregatorQuote,\n} from \"~/types\";\nimport type { IContractWrite } from \"~/types/global\";\nimport { isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\nclass WBeraAggregator extends BaseAggregator {\n name = Aggregators.Wrap;\n supportedChains = [ChainId.MAINNET, ChainId.BEPOLIA];\n readonly type = \"rpc\";\n\n // handles native swaps: wrap and unwrap\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n }: Omit<IAggregatorArgs, \"slippage\" | \"feeBps\">): Promise<\n IRawAggregatorQuote<false>\n > {\n this.checkChainSupport();\n\n if (\n (!isToken(tokenIn, \"BERA\") && !isToken(tokenIn, \"WBERA\")) ||\n (!isToken(tokenOut, \"WBERA\") && !isToken(tokenOut, \"BERA\"))\n ) {\n throw new BeraError({\n message: \"Invalid token pair\",\n level: \"error\",\n });\n }\n\n const isWrap = isToken(tokenIn, \"BERA\") && isToken(tokenOut, \"WBERA\");\n return {\n amountOut: amount,\n amountIn: amount,\n spender: undefined,\n name: isWrap ? Aggregators.Wrap : Aggregators.Unwrap,\n isNativeSwap: true,\n swapFeeBps: 0,\n calldata: isWrap\n ? ({\n abi: wberaAbi,\n address: this.config.tokens.wbera,\n functionName: \"deposit\",\n params: [],\n value: BigInt(amount),\n } satisfies Omit<\n IContractWrite<typeof wberaAbi, \"deposit\">,\n \"message\" | \"actionType\"\n >)\n : ({\n abi: wberaAbi,\n address: this.config.tokens.wbera,\n functionName: \"withdraw\",\n params: [BigInt(amount)],\n value: BigInt(0),\n } satisfies Omit<\n IContractWrite<typeof wberaAbi, \"withdraw\">,\n \"message\" | \"actionType\"\n >),\n };\n }\n}\n\nexport const wberaSwap = new WBeraAggregator();\n","import useSWRImmutable from \"swr/immutable\";\nimport { type PublicClient, zeroAddress } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { aggregatorsRouterAbi } from \"~/abi/bex/aggregatorsRouter\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport const useAggregatorsRouterFeeBps = () => {\n const publicClient = usePublicClient() as PublicClient;\n const { config } = parseBaseArgs({\n chainId: publicClient.chain?.id,\n });\n const swrResponse = useSWRImmutable(\n publicClient &&\n config.bex.aggregatorsRouter &&\n config.bex.aggregatorsRouter !== zeroAddress\n ? ([\"useAggregatorsRouterFeeBps\", config.bex.aggregatorsRouter] as const)\n : null,\n async ([, aggregatorsRouter]) => {\n const fee = await publicClient.readContract({\n address: aggregatorsRouter,\n abi: aggregatorsRouterAbi,\n functionName: \"SWAP_FEE_RATE\",\n });\n return Number(fee);\n },\n );\n\n return {\n ...swrResponse,\n refresh: swrResponse.mutate,\n };\n};\n","import useSWR from \"swr\";\n\nimport type { GetPoolsQueryVariables } from \"@berachain/graphql/dex/api\";\n\nimport { getAllPools } from \"~/actions/dex/getAllPools\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { DefaultHookOptions } from \"~/types\";\n\nexport const useAllUserPoolsQueryKey = ({\n query,\n}: {\n query?: GetPoolsQueryVariables;\n} = {}) => {\n return [\"useAllUserPools\", query];\n};\n\nexport const useAllUserPools = (\n query: GetPoolsQueryVariables,\n options?: DefaultHookOptions,\n) => {\n const swrResponse = useSWR(\n useAllUserPoolsQueryKey({ query }),\n async ([_, params]: [string, GetPoolsQueryVariables]) => {\n return getAllPools({ ...params, fetchPolicy: \"no-cache\" });\n },\n {\n refreshInterval: POLLING.SLOW,\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n};\n","import useSWR from \"swr\";\nimport { type Address, type Hex, isAddress } from \"viem\";\n\nimport type { MinimalPoolFragment } from \"@berachain/graphql/dex/api\";\n\nimport { getApiPool } from \"~/actions/dex/getApiPool\";\nimport { POLLING } from \"~/enum/polling\";\nimport { InvalidArgumentError } from \"~/errors\";\n\nexport const useApiPoolQueryKey = ({\n poolId,\n account,\n}: {\n poolId: Hex;\n account?: Address;\n}) => {\n return poolId ? ([`usePool-api`, poolId, account] as const) : null;\n};\n\nexport function useApiPool({\n poolId,\n account,\n}: {\n poolId: Hex;\n account?: Address;\n}) {\n const res = useSWR(\n useApiPoolQueryKey({ poolId, account }),\n async ([, poolId, account]): Promise<MinimalPoolFragment> => {\n if (account && !isAddress(account)) {\n throw new InvalidArgumentError({\n property: \"account\",\n value: account,\n expected: \"Address\",\n });\n }\n return getApiPool({\n poolId,\n account: account as Address,\n });\n },\n {\n refreshInterval: POLLING.NORMAL,\n },\n );\n\n return {\n ...res,\n refresh: () => {\n res.mutate();\n },\n };\n}\n","import { useMemo } from \"react\";\nimport { PoolType } from \"@berachain-foundation/berancer-sdk\";\nimport useSWRImmutable from \"swr/immutable\";\nimport {\n type Address,\n formatUnits,\n keccak256,\n parseUnits,\n zeroAddress,\n} from \"viem\";\n\nimport {\n GetDedupedSubgraphPools,\n type GetDedupedSubgraphPoolsQuery,\n type SubgraphPoolFragment,\n} from \"@berachain/graphql/dex/subgraph\";\n\nimport { balancerPoolCreationHelperAbi } from \"~/abi/bex/balancerPoolCreationHelper\";\nimport { getApolloClient } from \"~/actions/clients/getApolloClient\";\nimport { TransactionActionType } from \"~/enum/txnEnum\";\nimport type { IContractWrite, Token, TokenInput } from \"~/types\";\nimport { DEFAULT_METAMASK_GAS_LIMIT } from \"~/utils\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { generatePoolName, generatePoolSymbol } from \"~/utils/poolNamings\";\nimport { isToken } from \"~/utils/tokens\";\nimport { wrapNativeTokens } from \"~/utils/tokenWrapping\";\n\nconst DEFAULT_WEIGHTS_DUPLICATION_THRESHOLD = 0.005;\ninterface UseCreatePoolProps extends BeraJS.BaseFunctionArgs {\n poolCreateTokens: Token[];\n initialLiquidityTokens: TokenInput[];\n normalizedWeights: bigint[]; // NOTE: if you pass weights that have off-by-1 errors pool create will fail (ex: 0.3 repeating)\n poolType: PoolType;\n swapFee: number;\n owner: string;\n poolSymbol: string;\n poolName: string;\n amplification: number;\n weightsDuplicationThreshold?: number;\n oracles: Oracle[]; // NOTE: the default state for oracles should be 0x0 address for each token with cache duration of ~100\n}\ninterface UseCreatePoolReturn {\n generatedPoolName: string;\n generatedPoolSymbol: string;\n isDupePool: boolean;\n dupePool?: SubgraphPoolFragment | null;\n createPoolArgs: any;\n isLoadingPools: boolean;\n errorLoadingPools: boolean;\n}\n\nexport enum OracleMode {\n None = \"None\",\n Custom = \"Custom\",\n}\n\nexport interface Oracle {\n mode: OracleMode;\n address: string;\n tokenAddress: string;\n cacheDuration: number;\n}\n\nconst createStablePoolArgs = ({\n poolCreationHelper,\n poolCreateTokens,\n initialLiquidityTokens,\n swapFeePercentage,\n salt,\n poolName,\n poolSymbol,\n owner,\n amplification,\n oracles,\n message,\n actionType,\n gasLimit = DEFAULT_METAMASK_GAS_LIMIT,\n}: {\n poolCreationHelper: Address;\n poolCreateTokens: Token[];\n initialLiquidityTokens: TokenInput[];\n swapFeePercentage: bigint;\n salt: string;\n poolName: string;\n poolSymbol: string;\n owner: string;\n amplification: number;\n oracles: Oracle[];\n message: string;\n actionType: TransactionActionType;\n gasLimit?: bigint;\n}) => {\n // Map and sort pool creation token addresses NOTE: we should never see BERA in this array.\n const sortedPoolCreateAddresses = poolCreateTokens\n .map((token) => token.address.toLowerCase())\n .sort((a, b) => (a < b ? -1 : 1));\n\n const combinedData = sortedPoolCreateAddresses.map((address) => {\n // Match with initial liquidity tokens\n const liquidityToken = initialLiquidityTokens.find(\n (token) =>\n token.address.toLowerCase() === address ||\n (isToken(address, \"WBERA\") && isToken(token.address, \"BERA\")),\n );\n\n const amountIn = liquidityToken\n ? parseUnits(liquidityToken.amount, liquidityToken.decimals)\n : 0n; // FIXME we need to throw errors from here if zipping fails.\n\n // Match with oracles\n const oracle = oracles.find(\n (oracle) => oracle.tokenAddress.toLowerCase() === address.toLowerCase(),\n );\n const rateProvider = oracle ? oracle.address : zeroAddress;\n const cacheDuration = oracle ? BigInt(oracle.cacheDuration) : BigInt(100);\n\n return { amountIn, rateProvider, cacheDuration };\n });\n\n // Extract results into separate arrays\n const sortedAmountsIn = combinedData.map((data) => data.amountIn);\n const sortedRateProviders = combinedData.map((data) => data.rateProvider);\n const sortedCacheDurations = combinedData.map((data) => data.cacheDuration);\n\n // Determine if native token (BERA) is included, and if so calculate its value, that is the value of this tx\n const nativeTokenIndex = initialLiquidityTokens.findIndex((token) =>\n isToken(token.address, \"BERA\"),\n );\n const value =\n nativeTokenIndex !== -1\n ? parseUnits(\n initialLiquidityTokens[nativeTokenIndex].amount,\n initialLiquidityTokens[nativeTokenIndex].decimals,\n )\n : 0n;\n const joinWBERAPoolWithBERA = value > 0n;\n\n return {\n address: poolCreationHelper,\n abi: balancerPoolCreationHelperAbi,\n functionName: \"createAndJoinStablePool\",\n params: [\n poolName,\n poolSymbol,\n sortedPoolCreateAddresses,\n BigInt(amplification),\n sortedRateProviders,\n sortedCacheDurations,\n false, // Exempt from yield protocol fee NOTE: this should be false for stable pools if rate providers are 0x0\n swapFeePercentage,\n sortedAmountsIn,\n owner as `0x${string}`,\n salt,\n joinWBERAPoolWithBERA,\n ],\n message,\n actionType,\n value,\n gasLimit,\n track: {\n eventName: \"hub_pool_create\",\n eventData: {\n poolName: poolName,\n poolSymbol: poolSymbol,\n },\n },\n } as IContractWrite<\n typeof balancerPoolCreationHelperAbi,\n \"createAndJoinStablePool\"\n >;\n};\n\nconst createWeightedPoolArgs = ({\n poolCreationHelper,\n poolCreateTokens,\n initialLiquidityTokens,\n normalizedWeights,\n swapFeePercentage,\n salt,\n poolName,\n poolSymbol,\n owner,\n message,\n actionType,\n gasLimit = DEFAULT_METAMASK_GAS_LIMIT,\n}: {\n poolCreationHelper: Address;\n poolCreateTokens: Token[];\n initialLiquidityTokens: TokenInput[];\n normalizedWeights: bigint[];\n swapFeePercentage: bigint;\n salt: string;\n poolName: string;\n poolSymbol: string;\n owner: string;\n message: string;\n actionType: TransactionActionType;\n gasLimit?: bigint;\n}) => {\n // When joining weighted pools with BERA, we allow it as a joinPoolToken but never as a createPoolToken.\n const createPoolTokens: string[] = [];\n const joinPoolTokens: string[] = [];\n const sortedWeights: bigint[] = [];\n const sortedAmountsIn: bigint[] = [];\n\n poolCreateTokens\n .map((token, index) => {\n return {\n createToken: token.address,\n joinToken: initialLiquidityTokens[index].address, // NOTE: this will allow native token as a join token\n weight: normalizedWeights[index],\n amountIn: parseUnits(\n initialLiquidityTokens[index].amount,\n initialLiquidityTokens[index].decimals,\n ),\n };\n })\n .sort((a, b) =>\n a.createToken.toLowerCase() < b.createToken.toLowerCase() ? -1 : 1,\n )\n .forEach((item) => {\n createPoolTokens.push(item.createToken);\n joinPoolTokens.push(item.joinToken);\n sortedWeights.push(item.weight);\n sortedAmountsIn.push(item.amountIn);\n });\n\n // Determine if native token (BERA) is involved and calculate its value, that is the value of this tx\n const nativeTokenIndex = joinPoolTokens.indexOf(zeroAddress);\n const value =\n nativeTokenIndex !== -1 ? sortedAmountsIn[nativeTokenIndex] : 0n;\n\n return {\n address: poolCreationHelper,\n abi: balancerPoolCreationHelperAbi,\n functionName: \"createAndJoinWeightedPool\",\n params: [\n poolName,\n poolSymbol,\n createPoolTokens,\n joinPoolTokens,\n sortedWeights,\n Array(createPoolTokens.length).fill(zeroAddress),\n swapFeePercentage,\n sortedAmountsIn,\n owner as `0x${string}`,\n salt,\n ],\n message,\n actionType,\n value,\n gasLimit,\n track: {\n eventName: \"hub_pool_create\",\n eventData: {\n poolName: poolName,\n poolSymbol: poolSymbol,\n },\n },\n } as IContractWrite<\n typeof balancerPoolCreationHelperAbi,\n \"createAndJoinWeightedPool\"\n >;\n};\n\nexport const useCreatePool = ({\n poolCreateTokens,\n initialLiquidityTokens,\n normalizedWeights,\n poolType,\n poolName,\n poolSymbol,\n swapFee,\n owner,\n amplification,\n oracles,\n weightsDuplicationThreshold = DEFAULT_WEIGHTS_DUPLICATION_THRESHOLD,\n ...baseArgs\n}: UseCreatePoolProps): UseCreatePoolReturn => {\n // 1. identify if the pool is a duplicate\n const {\n data: dupePool,\n error: errorLoadingPools,\n isLoading: isLoadingPools,\n } = useSWRImmutable<SubgraphPoolFragment | null>(\n [\n \"useCreatePool__deduped_pool\",\n poolCreateTokens,\n poolType,\n normalizedWeights,\n ],\n async () => {\n if (poolCreateTokens.length === 0 || !poolType) {\n return null;\n }\n const bexSubgraphClient = getApolloClient(\"bex.subgraph\", {});\n try {\n // NOTE: it should not be possible for native token to be in poolCreateTokens\n const tokensSorted = wrapNativeTokens(poolCreateTokens)\n .map((token) => token.address.toLowerCase())\n .sort((a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1));\n\n // fetch pools of the same type as the one we are creating\n const res = await bexSubgraphClient.query<GetDedupedSubgraphPoolsQuery>(\n {\n query: GetDedupedSubgraphPools,\n variables: {\n tokens: tokensSorted,\n type: poolType,\n },\n },\n );\n\n const matchingPools = res.data.pools.filter((pool) => {\n return pool.tokens?.every((token) =>\n poolType === PoolType.Weighted\n ? // in weighted pools, a dupe is if tokens and weights match within tolerance FIXME: we aren't getting weighted pools returned here\n tokensSorted.includes(token.address) &&\n Math.abs(\n Number(token.weight) -\n Number(\n formatUnits(\n normalizedWeights[tokensSorted.indexOf(token.address)],\n 18,\n ),\n ),\n ) < weightsDuplicationThreshold\n : // in composable pools a dupe is if the tokens match, handling that the LP token is in the tokens list\n tokensSorted.includes(token.address) ||\n token.address === pool.address,\n );\n });\n\n return matchingPools?.at(0) ?? null;\n } catch {\n return null;\n }\n },\n );\n\n // Generated names\n const { generatedPoolName, generatedPoolSymbol } = useMemo(() => {\n if (!poolCreateTokens) {\n return {\n generatedPoolName: \"\",\n generatedPoolSymbol: \"\",\n };\n }\n const generatedPoolName = generatePoolName(poolCreateTokens);\n const generatedPoolSymbol = generatePoolSymbol(\n poolCreateTokens,\n normalizedWeights,\n poolType,\n );\n\n return {\n generatedPoolName,\n generatedPoolSymbol,\n };\n }, [poolCreateTokens, normalizedWeights, poolType]);\n\n // Pool create tx\n const createPoolArgs = useMemo(() => {\n if (\n !owner ||\n poolName === \"\" ||\n poolSymbol === \"\" ||\n poolCreateTokens.length !== initialLiquidityTokens.length ||\n poolCreateTokens.length === 0\n ) {\n return null;\n }\n\n const swapFeePercentage = parseUnits(swapFee.toString(), 16);\n const salt = keccak256(Buffer.from(`${poolName}-${owner}`));\n const { config: chainConfig } = parseBaseArgs(baseArgs);\n\n if (poolType === PoolType.Weighted) {\n return createWeightedPoolArgs({\n poolCreationHelper: chainConfig.bex.poolCreationHelper,\n poolCreateTokens,\n initialLiquidityTokens,\n normalizedWeights,\n swapFeePercentage,\n salt,\n poolName,\n poolSymbol,\n owner,\n message: `Create pool ${poolName}`,\n actionType: TransactionActionType.CREATE_POOL,\n });\n }\n\n if (\n poolType === PoolType.ComposableStable ||\n poolType === PoolType.MetaStable\n ) {\n return createStablePoolArgs({\n poolCreationHelper: chainConfig.bex.poolCreationHelper,\n poolCreateTokens,\n initialLiquidityTokens,\n swapFeePercentage,\n salt,\n poolName,\n poolSymbol,\n owner,\n amplification,\n oracles,\n message: `Create pool ${poolName}`,\n actionType: TransactionActionType.CREATE_POOL,\n });\n }\n\n return null;\n }, [\n poolCreateTokens,\n initialLiquidityTokens,\n normalizedWeights,\n poolType,\n swapFee,\n poolName,\n poolSymbol,\n owner,\n amplification,\n oracles,\n ]);\n\n return {\n generatedPoolName,\n generatedPoolSymbol,\n isDupePool: !!dupePool,\n dupePool,\n createPoolArgs,\n isLoadingPools,\n errorLoadingPools,\n };\n};\n","import { PoolType } from \"@berachain-foundation/berancer-sdk\";\nimport { formatUnits } from \"viem\";\n\nimport type { Token } from \"~/types\";\n\n// Utility function to sort tokens by their address without modifying the original array\nconst sortTokensByAddress = (tokens: Token[]): Token[] => {\n return [...tokens].sort((a, b) =>\n a.address.toLowerCase().localeCompare(b.address.toLowerCase()),\n );\n};\n\nexport const generatePoolName = (tokens: Token[]): string => {\n if (tokens.length === 0) {\n return \"\";\n }\n return sortTokensByAddress(tokens)\n .map((token) => token.symbol)\n .join(\" | \");\n};\n\nexport const generatePoolSymbol = (\n tokens: Token[],\n weights: bigint[],\n poolType: PoolType,\n): string => {\n let poolTypeString: string;\n\n switch (poolType) {\n case PoolType.ComposableStable:\n poolTypeString = \"STABLE\";\n break;\n default:\n poolTypeString = poolType.toString().toUpperCase();\n break;\n }\n\n if (poolType === PoolType.Weighted) {\n if (weights.length === 0) {\n return \"\";\n }\n return `${sortTokensByAddress(tokens)\n .map((token, index) => {\n const weight = weights[index];\n const weightPercentage =\n Number.parseFloat(formatUnits(weight, 18)) * 100;\n return `${weightPercentage.toFixed(0)}${token.symbol}`;\n })\n .join(\"-\")}-${poolTypeString}`;\n }\n return `${sortTokensByAddress(tokens)\n .map((token) => token.symbol)\n .join(\"-\")}-${poolTypeString}`;\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getIsTokenExploited } from \"~/actions/dex/getIsTokenExploited\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { Token } from \"~/types\";\n\nexport const useExploitedTokensQueryKey = (tokens: Token[] | undefined) => {\n const filteredTokens = tokens?.filter((token) => token.address);\n if (!filteredTokens || filteredTokens.length === 0) {\n return null;\n }\n return [\"useExploitedTokens\", filteredTokens] as const;\n};\n/**\n * This hook checks if any of provided tokens might have been exploited by frontrunning its deployment.\n *\n * @see {@link getIsTokenExploited} for more details\n * @returns a record of tokens and whether they might have been exploited\n */\nexport const useExploitedTokens = ({\n tokens,\n}: {\n tokens: Token[] | undefined;\n}) => {\n const QUERY_KEY = useExploitedTokensQueryKey(tokens);\n const publicClient = usePublicClient();\n const swrResponse = useSWR(\n publicClient ? QUERY_KEY : null,\n async ([, tokens]) => {\n assertPublicClient(publicClient);\n\n const exploitedTokens = await Promise.all(\n tokens.map((token) =>\n getIsTokenExploited({\n token,\n publicClient,\n }),\n ),\n );\n\n return exploitedTokens.reduce<Record<Address, boolean>>(\n (acc, curr, idx) => {\n if (curr !== undefined) {\n acc[tokens[idx].address] = curr;\n }\n return acc;\n },\n {},\n );\n },\n );\n\n return { ...swrResponse, refresh: () => swrResponse.mutate() };\n};\n","import BigNumber from \"bignumber.js\";\nimport { erc20Abi, formatUnits, type PublicClient } from \"viem\";\n\nimport {\n GetExploitedTokens,\n type GetExploitedTokensQuery,\n type GetExploitedTokensQueryVariables,\n} from \"@berachain/graphql/dex/subgraph\";\n\nimport type { Token } from \"~/types\";\nimport { getApolloClient } from \"../clients/getApolloClient\";\n\n/**\n * 0.01% of the total supply\n */\nconst BEX_EXPLOITED_TOKEN_THRESHOLD = 0.0001 as const;\n\n/**\n * This function checks if a token was exploited by frontrunning its deployment\n * and creating a large amount of balance in the BEX's vault internal balance.\n *\n * There is a vulnerability on Balancer V2 that might lead an hacker to create a lot of internal balance of a token before it's\n * actually deployed. In this function we're checking if wallet has an internal balance of more than BEX_EXPLOITED_TOKEN_THRESHOLD\n *\n * @see https://forum.balancer.fi/t/balancer-v2-token-frontrun-vulnerability-disclosure/6309\n * @returns true if the token might have been exploited, false otherwise\n */\nexport async function getIsTokenExploited({\n token,\n publicClient,\n ...args\n}: BeraJS.BaseFunctionArgs & {\n token: Token;\n publicClient: PublicClient;\n}) {\n const bexSubgraphClient = getApolloClient(\"bex.subgraph\", args);\n\n const totalSupply = await publicClient.readContract({\n address: token.address,\n abi: erc20Abi,\n functionName: \"totalSupply\",\n });\n const balanceThreshold = BigNumber(\n formatUnits(totalSupply, token.decimals),\n ).multipliedBy(BEX_EXPLOITED_TOKEN_THRESHOLD);\n\n const { data } = await bexSubgraphClient.query<\n GetExploitedTokensQuery,\n GetExploitedTokensQueryVariables\n >({\n query: GetExploitedTokens,\n variables: {\n token: token.address,\n balance: balanceThreshold.toFixed(),\n },\n });\n\n if (data.userInternalBalances.length > 0) {\n return true;\n }\n\n return false;\n}\n","import useSWR from \"swr\";\n\nimport { getGlobalLiquidityAndSwapVolume } from \"~/actions/dex/getGlobalLiquidityAndSwapVolume\";\n\nexport const useGlobalLiquidityAndSwapVolume = () => {\n const response = useSWR(\"useGlobalLiquidityAndSwapVolume\", async () =>\n getGlobalLiquidityAndSwapVolume(),\n );\n\n return {\n ...response,\n data: {\n totalLiquidity: Number(\n response.data?.protocolMetricsAggregated.totalLiquidity,\n ),\n swapVolume24h: Number(\n response.data?.protocolMetricsAggregated.swapVolume24h,\n ),\n },\n refresh: () => response.mutate(),\n };\n};\n","import { useEffect, useState } from \"react\";\nimport { PoolType } from \"@berachain-foundation/berancer-sdk\";\n\nimport {\n PoolCreationStep,\n type TokenCurrentPriceMap,\n type TokenWithAmount,\n} from \"~/types\";\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 BigNumber from \"bignumber.js\";\nimport { type Address, formatEther, isAddressEqual } from \"viem\";\n\nimport type { MinimalPoolFragment } from \"@berachain/graphql/dex/api\";\n\nimport { useRewardVaultBalanceFromStakingToken } from \"~/hooks/pol/useRewardVaultBalanceFromStakingToken\";\nimport { usePollBalance } from \"~/hooks/tokens/usePollBalance\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n IUserPosition,\n} from \"~/types\";\n\ntype IUseLpPositionArgs = {\n pool: MinimalPoolFragment | undefined;\n vaultAddress?: Address | undefined;\n};\n\n/**\n * Given a pool and used within an initialized viem context, returns the user's position\n */\nexport const useLpPosition = (\n { pool, vaultAddress }: IUseLpPositionArgs,\n options?: DefaultHookOptions,\n): DefaultHookReturnType<IUserPosition> => {\n const { data: userPosition, ...rest } = usePollBalance({\n address: pool?.address,\n });\n\n const { data: userVaultTokenBalance, refresh: refreshVaultDeposit } =\n useRewardVaultBalanceFromStakingToken(\n {\n stakingToken: pool?.address,\n rewardVaultAddress: vaultAddress ?? pool?.rewardVault?.vaultAddress,\n },\n options,\n );\n\n const actualPoolShares = pool\n ? Number.parseFloat(pool?.dynamicData?.totalShares ?? \"0\")\n : 0;\n\n const tvlInUsd = pool?.dynamicData?.totalLiquidity\n ? Number(pool?.dynamicData?.totalLiquidity ?? 0)\n : null;\n\n const lpTokenPrice =\n actualPoolShares && tvlInUsd ? tvlInUsd / Number(actualPoolShares) : 0;\n\n const tokenRatioPerLp = pool?.tokens?.map((token) => {\n return {\n address: token.address,\n ratio: actualPoolShares\n ? Number(token.balance) / Number(actualPoolShares)\n : 0,\n };\n });\n\n return {\n data: {\n lpTokenPrice,\n lpBalance: userPosition\n ? {\n ...userPosition,\n usdValue: userPosition\n ? Number(userPosition.formattedBalance) * lpTokenPrice\n : undefined,\n }\n : undefined,\n tokenBalances: pool?.tokens?.map((token) => {\n const tokenRatio =\n tokenRatioPerLp?.find((tr) =>\n isAddressEqual(tr.address as Address, token.address as Address),\n )?.ratio ?? 0;\n\n const userBalance = tokenRatio\n ? BigNumber(userPosition?.formattedBalance ?? \"0\").times(tokenRatio)\n : BigNumber(0);\n const price = Number(token.balanceUSD) / Number(token.balance);\n\n return {\n balance: userBalance?.isGreaterThan(0)\n ? BigInt(\n userBalance\n .times(10 ** token.decimals!)\n .toFixed(0)\n .toString(),\n )\n : 0n,\n formattedBalance: userBalance.toString(),\n address: token.address,\n usdValue:\n Number.isNaN(price) || !userBalance\n ? undefined\n : Number.parseFloat(userBalance.toString()) * price,\n };\n }),\n stakedBalance: userVaultTokenBalance?.address\n ? {\n address: userVaultTokenBalance.address,\n balance: userVaultTokenBalance.balance,\n // Pools always use the 18 decimals\n formattedBalance: formatEther(userVaultTokenBalance.balance),\n usdValue:\n Number(formatEther(userVaultTokenBalance.balance)) * lpTokenPrice,\n }\n : undefined,\n },\n ...rest,\n refresh: () => {\n rest.refresh?.();\n refreshVaultDeposit();\n },\n };\n};\n","import useSWR from \"swr\";\nimport { type Address, isAddress, zeroAddress } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { rewardVaultAbi } from \"~/abi/pol/rewardVault\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { useRewardVaultFromToken } from \"./useRewardVaultFromToken\";\n\n// NOTE: this is entirely on-chain\nexport const useRewardVaultBalanceFromStakingToken = (\n {\n stakingToken,\n rewardVaultAddress: _rewardVaultAddress,\n }: {\n stakingToken: Address | undefined;\n rewardVaultAddress?: Address;\n },\n options?: DefaultHookOptions,\n) => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n\n const isEnabled = options?.opts?.isEnabled ?? true;\n const {\n data: rewardVaultAddress = _rewardVaultAddress,\n error,\n mutate: mutateRewardVaultAddress,\n isLoading: isLoadingRewardVaultAddress,\n } = useRewardVaultFromToken(\n {\n tokenAddress: stakingToken,\n },\n {\n isEnabled: !_rewardVaultAddress && isEnabled,\n },\n );\n\n const swrResponse = useSWR(\n rewardVaultAddress &&\n account &&\n publicClient &&\n isAddress(rewardVaultAddress) &&\n isAddress(account) &&\n isEnabled\n ? [\"useVaultBalanceFromStakingToken\", rewardVaultAddress, account]\n : null,\n\n async ([, rewardVaultAddress, account]) => {\n assertPublicClient(publicClient);\n\n if (rewardVaultAddress === zeroAddress) {\n return {\n address: rewardVaultAddress,\n balance: 0n,\n };\n }\n\n const balance = await publicClient.readContract({\n address: rewardVaultAddress,\n abi: rewardVaultAbi,\n functionName: \"balanceOf\",\n args: [account],\n });\n\n return {\n address: rewardVaultAddress,\n balance: balance,\n };\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n mutateRewardVaultAddress();\n swrResponse.mutate();\n },\n isLoading: swrResponse.isLoading || isLoadingRewardVaultAddress,\n };\n};\n","import useSWRImmutable from \"swr/immutable\";\nimport { type Address, isAddress, zeroAddress } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { rewardVaultFactoryAbi } from \"~/abi/pol/rewardVaultFactory\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport const useRewardVaultFromToken = (\n {\n tokenAddress,\n }: {\n tokenAddress: Address | string | undefined;\n },\n {\n isEnabled = true,\n }: {\n isEnabled?: boolean;\n } = {},\n) => {\n const publicClient = usePublicClient();\n\n const QUERY_KEY: readonly [string, Address] | null =\n publicClient && tokenAddress && isAddress(tokenAddress) && isEnabled\n ? [\"useRewardVaultFromToken\", tokenAddress]\n : null;\n\n const swrResponse = useSWRImmutable<\n Address | undefined,\n any,\n typeof QUERY_KEY\n >(QUERY_KEY, async ([, tokenAddress]) => {\n if (!tokenAddress) {\n throw new Error(\"useRewardVaultFromToken needs a valid token address\");\n }\n\n assertPublicClient(publicClient);\n\n const { config } = parseBaseArgs({\n chainId: publicClient.chain.id,\n });\n\n const res = await publicClient.readContract({\n address: config.pol.factory,\n abi: rewardVaultFactoryAbi,\n functionName: \"getVault\",\n args: [tokenAddress],\n });\n\n return res === zeroAddress ? undefined : res;\n });\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\nimport {\n type Address,\n erc20Abi,\n formatEther,\n formatUnits,\n isAddress,\n zeroAddress,\n} from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookReturnType } from \"~/types\";\nimport type { BalanceToken } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { beraToken, isToken } from \"~/utils/tokens\";\nimport { useTokenInformation } from \"./useTokenInformation\";\n\nexport function usePollBalance(\n {\n address: addressString,\n owner,\n chainId = defaultChainId,\n }: {\n /**\n * Token address to get the balance of\n */\n address: string | undefined;\n owner?: Address | undefined;\n chainId?: number;\n },\n options?: DefaultHookOptions,\n): Omit<DefaultHookReturnType<BalanceToken | undefined>, \"mutate\"> {\n let address = addressString;\n //enso has the native token as ethAddress, we need to convert it to zeroAddress\n if (isToken(address, \"ETH\")) {\n address = zeroAddress as Address;\n }\n const publicClient = usePublicClient({ chainId });\n const { address: account } = useBeraWallet();\n const assetOwner = owner ?? account;\n\n const QUERY_KEY =\n (options?.opts?.isEnabled ?? true) &&\n publicClient &&\n assetOwner &&\n isAddress(assetOwner) &&\n address &&\n isAddress(address)\n ? ([\"usePollBalance\", assetOwner, address, chainId] as const)\n : null;\n\n const { data: tokenInformation, isLoading: isLoadingTokenInformation } =\n useTokenInformation({ address, chainId });\n\n const isNativeToken = isToken(address, \"BERA\");\n\n const { isLoading, data, error, ...rest } = useSWR(\n QUERY_KEY,\n async ([, assetOwner, address]) => {\n assertPublicClient(publicClient);\n\n if (!isToken(address, \"BERA\")) {\n return await publicClient.readContract({\n address: address as `0x${string}`,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [assetOwner],\n });\n }\n return await publicClient.getBalance({\n address: assetOwner,\n });\n },\n {\n refreshInterval: POLLING.FAST,\n },\n );\n\n const formattedBalance =\n !error && data\n ? isToken(address, \"BERA\")\n ? formatEther(data as bigint)\n : tokenInformation && !isLoadingTokenInformation\n ? formatUnits(data, tokenInformation.decimals)\n : undefined\n : undefined;\n\n const tokenBalance = {\n balance: data ?? 0n,\n formattedBalance: formattedBalance ?? \"0\",\n address: address as `0x${string}`,\n decimals: isNativeToken\n ? beraToken.decimals\n : (tokenInformation?.decimals ?? 0),\n symbol: isNativeToken ? beraToken.symbol : (tokenInformation?.symbol ?? \"\"),\n name: isNativeToken ? beraToken.name : (tokenInformation?.name ?? \"\"),\n } satisfies BalanceToken;\n\n return {\n ...rest,\n refresh: () => {\n rest.mutate();\n },\n isLoading: isLoading || isNativeToken ? isLoadingTokenInformation : false,\n error: error || !isNativeToken ? error : undefined,\n data: tokenBalance,\n };\n}\n","import useSWRImmutable from \"swr/immutable\";\nimport { isAddress, zeroAddress } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getTokenInformation } from \"~/actions/tokens/getTokenInformation\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType, Token } from \"~/types\";\nimport { beraToken, isToken } from \"~/utils/tokens\";\n\nexport type UseTokenInformationResponse = DefaultHookReturnType<\n Token | undefined\n>;\n\nexport type UseTokenInformationArgs = {\n address: string | undefined;\n chainId?: number;\n};\nexport const useTokenInformation = (\n args: UseTokenInformationArgs,\n options?: DefaultHookOptions,\n): UseTokenInformationResponse => {\n const publicClient = usePublicClient({\n chainId: args.chainId,\n });\n const QUERY_KEY =\n args?.address && publicClient && isAddress(args.address)\n ? ([\"useTokenInformation\", args.address, args.chainId] as const)\n : null;\n const swrResponse = useSWRImmutable<Token | undefined, any, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([_, address]) => {\n if (isToken(address, \"BERA\")) {\n return {\n address: zeroAddress,\n decimals: beraToken.decimals,\n name: beraToken.name,\n symbol: beraToken.symbol,\n } satisfies Token;\n }\n\n // We already checked for publicClient in the QUERY_KEY\n // so we can safely assume that publicClient is defined\n // but we need this for correct type inference\n assertPublicClient(publicClient);\n\n return await getTokenInformation({\n address,\n publicClient,\n });\n },\n { ...options?.opts },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","\"use client\";\n\nimport { useMemo } from \"react\";\nimport { ZERO_ADDRESS } from \"@berachain-foundation/berancer-sdk\";\nimport BigNumber from \"bignumber.js\";\nimport { type Address, isAddressEqual, parseUnits } from \"viem\";\n\nimport { BeraError } from \"~/errors/BeraError\";\nimport { usePollAllowances } from \"~/hooks/tokens/usePollAllowances\";\nimport type { AllowanceToken, TokenInput } from \"~/types\";\n\ntype NeedsApprovalToken = AllowanceToken & {\n maxAmountIn: bigint;\n};\n\nfunction calculateMaxAmountIn({\n amount,\n decimals,\n slippage,\n}: {\n amount: string;\n decimals: number;\n slippage: number | undefined;\n}) {\n const amountInWei = parseUnits(amount, decimals);\n const slippageInWei = parseUnits((slippage ?? 0).toString(), decimals);\n return (\n amountInWei + (amountInWei * slippageInWei) / BigInt(100 * 10 ** decimals)\n );\n}\n\nexport const useMultipleTokenApprovalsWithSlippage = (\n tokenInput: TokenInput[],\n spender: Address | undefined,\n slippage?: number,\n) => {\n const tokens = useMemo(\n () =>\n tokenInput\n .filter((token) => token.address !== ZERO_ADDRESS)\n .filter((token: TokenInput) => token !== undefined)\n .filter((token) => BigNumber(token.amount).gt(0)),\n [tokenInput],\n );\n\n const {\n data: allowances,\n refresh,\n isLoading,\n } = usePollAllowances({\n spender: spender,\n tokens,\n });\n\n const needsApproval = useMemo<NeedsApprovalToken[]>(\n () =>\n allowances\n ?.map<NeedsApprovalToken | undefined>((allowance) => {\n const token = tokens.find((token: TokenInput) =>\n isAddressEqual(token.address, allowance.address),\n );\n\n if (!token) {\n // Since we're checking the allowances, the tokens should be present\n throw new BeraError({\n message:\n \"Token not found when matching allowance in useMultipleTokenApprovalsWithSlippage\",\n cause: {\n allowance,\n tokens,\n },\n });\n }\n\n const maxAmountIn = calculateMaxAmountIn({ ...token, slippage });\n\n if (allowance.allowance === 0n || allowance.allowance < maxAmountIn) {\n return { ...allowance, maxAmountIn };\n }\n\n return undefined;\n })\n .filter((token) => token !== undefined) ?? [],\n [allowances, slippage, tokens],\n );\n\n return {\n needsApproval,\n refresh,\n isLoading,\n };\n};\n","import useSWR from \"swr\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getAllowances } from \"~/actions/tokens/getAllowances\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { Token } from \"~/types\";\nimport type {\n AllowanceToken,\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"~/types/global\";\n\nexport type UsePollAllowancesArgs = {\n spender: string | undefined;\n tokens: Token[];\n};\nexport interface UsePollAllowancesResponse\n extends DefaultHookReturnType<AllowanceToken[] | undefined> {}\n\n/**\n *\n * @brief Allows the user to poll the allowances of a given token array.\n *\n * @param contract the address of the ERC20 token contract\n * @param tokens the list of tokens to poll allowances for\n */\nexport const usePollAllowances = (\n args: UsePollAllowancesArgs,\n options?: DefaultHookOptions,\n): UsePollAllowancesResponse => {\n const publicClient = usePublicClient();\n const { address: account } = useBeraWallet();\n const QUERY_KEY =\n publicClient && account && args?.tokens && args?.spender\n ? ([\"usePollAllowances\", account, args?.tokens, args?.spender] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, account, tokens, spender]) => {\n return getAllowances({\n tokens,\n account,\n spender,\n publicClient,\n });\n },\n {\n ...options?.opts,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.NORMAL,\n },\n );\n\n return {\n ...swrResponse,\n\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","import { useMemo } from \"react\";\nimport useSWRImmutable from \"swr/immutable\";\nimport { type Address, formatUnits, isAddress } from \"viem\";\n\nimport type { SubgraphPoolFragment } from \"@berachain/graphql/dex/subgraph\";\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getOnChainPool } from \"~/actions/dex/getOnChainPool\";\nimport { useMultipleTokenInformation } from \"~/hooks/tokens/useMultipleTokenInformation\";\nimport { useTokenCurrentPrices } from \"~/hooks/tokens/useTokenCurrentPrices\";\n\nexport function useOnChainPoolDataQueryKey(\n args: { poolId: string } | { address: Address },\n) {\n const address = \"poolId\" in args ? args.poolId?.slice(0, 42) : args.address;\n\n const isAddressValid = isAddress(address);\n\n const isValid = isAddressValid;\n\n return isValid && address ? ([\"useOnChainPoolData\", address] as const) : null;\n}\n\nexport interface OnChainPoolFragment extends SubgraphPoolFragment {\n // Reference: https://github.com/balancer/docs-developers/blob/main/references/valuing-balancer-lp-tokens/pools/stablepools.md#getamplificationparameter\n amplificationParameter:\n | {\n currentFormattedValue: number | undefined;\n }\n | undefined;\n}\n\nexport function useOnChainPoolData(poolId: string) {\n const publicClient = usePublicClient();\n\n const address = poolId?.slice(0, 42) as Address;\n\n const QUERY_KEY = useOnChainPoolDataQueryKey({ poolId });\n const {\n data: poolData,\n error,\n isLoading,\n mutate,\n } = useSWRImmutable(\n // FIXME: why are we using useSWRImmutable when we fetch tokenSupply and swapFee?\n publicClient ? QUERY_KEY : null,\n async ([, poolId]) => {\n return getOnChainPool({\n poolId,\n // @ts-expect-error viem types\n publicClient,\n });\n },\n );\n\n const { data: tokenInformation, isLoading: isTokenInformationLoading } =\n useMultipleTokenInformation({\n addresses: poolData?.poolTokens[0],\n });\n\n const { data: tokenPrices, isLoading: isTokenPricesLoading } =\n useTokenCurrentPrices({\n addressIn: poolData?.poolTokens[0],\n });\n\n const pool = useMemo(() => {\n if (!poolData || !tokenInformation) {\n return undefined;\n }\n\n const pool: OnChainPoolFragment = {\n address: address.toLowerCase() as Address,\n id: poolId.toLowerCase() as string,\n type: poolData.type,\n factory: poolData.factory,\n totalShares: poolData.totalSupply,\n totalLiquidity: \"0\", // overwritten below\n swapFee: poolData.swapFee,\n createTime: 0,\n name: poolData.name,\n tokens: tokenInformation.map((token, idx) => ({\n address: token.address.toLowerCase() as Address,\n name: token.name,\n decimals: token.decimals,\n symbol: token.symbol,\n index: idx,\n weight: poolData.weights?.[idx] ?? undefined,\n balance: formatUnits(\n BigInt(poolData.poolTokens[1][idx]),\n token.decimals,\n ),\n token: {\n __typename: \"Token\",\n token,\n latestUSDPrice: tokenPrices?.[token.address],\n },\n })),\n amplificationParameter: poolData?.amplificationParameter && {\n // For example, if value is 300000n and precision is 1000n, the user-set amplification parameter would be 300000n / 1000n = 300n.\n currentFormattedValue:\n Number(poolData.amplificationParameter[0]) /\n Number(poolData.amplificationParameter[2]),\n },\n };\n\n const totalLiquidity = pool.tokens?.reduce((acc, token) => {\n const tokenUSDPrice = Number(\n tokenPrices?.[token.address.toLowerCase()]?.price ?? 0,\n );\n if (!tokenUSDPrice) return acc;\n return acc + tokenUSDPrice * Number(token.balance);\n }, 0);\n\n pool.totalLiquidity = totalLiquidity?.toString() ?? \"\";\n\n return pool;\n }, [poolData, tokenInformation, tokenPrices, address, poolId]);\n\n return {\n data: pool,\n error,\n isLoading: isLoading || isTokenInformationLoading || isTokenPricesLoading,\n mutate,\n refresh: () => mutate(),\n };\n}\n","import useSWRImmutable from \"swr/immutable\";\nimport { isAddress } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getTokenInformation } from \"~/actions/tokens/getTokenInformation\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType, Token } from \"~/types\";\n\nexport type UseMultipleTokenInformationResponse = DefaultHookReturnType<\n Token[]\n>;\n\nexport type useMultipleTokenInformationArgs = {\n addresses: string[] | readonly string[] | undefined;\n};\nexport const useMultipleTokenInformation = (\n args: useMultipleTokenInformationArgs,\n options?: DefaultHookOptions,\n): UseMultipleTokenInformationResponse => {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n publicClient && args.addresses\n ? ([\"useMultipleTokenInformation\", args.addresses] as const)\n : null;\n\n const swrResponse = useSWRImmutable<Token[], unknown, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([, addresses]) => {\n // We already checked for publicClient in the QUERY_KEY\n // so we can safely assume that publicClient is defined\n // but we need this for correct type inference\n assertPublicClient(publicClient);\n\n return Promise.all(\n addresses.map(async (address) => {\n if (!address || !isAddress(address, { strict: false })) {\n throw new Error(\"Invalid address\");\n }\n\n const tk = await getTokenInformation({\n address: address,\n publicClient,\n });\n\n if (!tk) {\n throw new Error(`Token ${address} not found`);\n }\n\n return tk;\n }),\n );\n },\n { ...options?.opts },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { getTokenCurrentPrices } from \"~/actions/prices/getTokenCurrentPrices\";\nimport { POLLING } from \"~/enum/polling\";\nimport { useTokens } from \"~/hooks/tokens/useTokens\";\nimport type { TokenCurrentPriceMap } from \"~/types\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\nimport { isToken } from \"~/utils/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): DefaultHookReturnType<TokenCurrentPriceMap> {\n const { tokenList } = useTokens();\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 = addressIn?.some(\n (a) => tokenList?.findIndex((tk) => isToken(tk, a as Address)) === -1,\n )\n ? addressIn\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 swrResponse = useSWR(\n QUERY_KEY,\n async ([, addresses]) => {\n return getTokenCurrentPrices({ addressIn: addresses });\n },\n options.opts,\n );\n\n return {\n ...swrResponse,\n refresh: () => void swrResponse.mutate(),\n };\n}\n","import { useContext } from \"react\";\n\nimport { TokenContext } from \"~/contexts/TokensProvider\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport type { FormatTokenListReturnType } from \"~/utils/formatTokenList\";\n\nexport function useTokens() {\n const context = useContext(TokenContext);\n if (!context) {\n throw new BeraError({\n message: \"useTokens must be used within a TokensProvider\",\n level: \"fatal\",\n });\n }\n return {\n ...context,\n /**\n * @deprecated use useTokens().tokenList instead\n */\n data: {\n tokenList: context.tokenList,\n customTokenList: context.userTokens,\n featuredTokenList: context.featuredTokens,\n } satisfies FormatTokenListReturnType,\n };\n}\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { balancerVaultAbi } from \"~/abi/bex/balancerVault\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\n/**\n * Hook for fetching relayer approval status with SWR\n *\n * @returns SWR data spread and refresh function\n */\nexport const usePollPoolCreationRelayerApproval = (\n options?: DefaultHookOptions,\n) => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n account && publicClient\n ? ([\n \"usePollPoolCreationRelayerApproval\",\n account,\n publicClient.chain.id,\n ] as const)\n : null;\n\n const swrResponse = useSWR<boolean>(\n QUERY_KEY,\n async ([, account]) => {\n assertPublicClient(publicClient);\n\n const { config } = parseBaseArgs({ chainId: publicClient.chain.id });\n const approved = await publicClient.readContract({\n address: config.bex.vault,\n abi: balancerVaultAbi,\n functionName: \"hasApprovedRelayer\",\n args: [account as Address, config.bex.poolCreationHelper],\n });\n\n return approved;\n },\n { ...options?.opts },\n );\n\n const refreshPoolCreationApproval = () => {\n swrResponse.mutate();\n };\n\n return { ...swrResponse, refreshPoolCreationApproval };\n};\n","import { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport type { Hex } from \"viem\";\n\nimport { getSubgraphPool } from \"~/actions/dex/getSubgraphPool\";\nimport { POLLING } from \"~/enum/polling\";\nimport { useApiPool } from \"./useApiPool\";\nimport { useOnChainPoolData } from \"./useOnChainPoolData\";\n\nexport function useSubgraphPoolQueryKey({ poolId }: { poolId: string }) {\n return poolId ? [\"usePool-subgraph\", poolId] : null;\n}\n\nexport const usePool = ({ poolId }: { poolId: Hex }) => {\n const bexSubgraphPool = useSWR(\n useSubgraphPoolQueryKey({ poolId }),\n async ([, poolId]) => getSubgraphPool({ poolId }),\n {\n refreshInterval: POLLING.NORMAL,\n },\n );\n\n const balancerApiPool = useApiPool({ poolId });\n\n const {\n data: onChainPool,\n isLoading: isOnChainPoolLoading,\n refresh: refreshOnChainPool,\n } = useOnChainPoolData(poolId);\n\n const pool = useMemo(() => {\n // Until we load the data from the subgraph we'll push up the on-chain data.\n if (!bexSubgraphPool.data) return onChainPool;\n\n const merge = { ...bexSubgraphPool.data };\n\n if (onChainPool) {\n merge.swapFee = onChainPool.swapFee;\n merge.totalShares = onChainPool.totalShares;\n merge.createTime = onChainPool.createTime ?? merge.createTime;\n }\n\n return merge;\n }, [onChainPool, bexSubgraphPool]);\n\n return {\n data: [pool, balancerApiPool.data, onChainPool] as const,\n isLoading:\n balancerApiPool.isLoading ||\n bexSubgraphPool.isLoading ||\n isOnChainPoolLoading,\n isError: balancerApiPool.error || bexSubgraphPool.error,\n refresh: () => {\n balancerApiPool.refresh();\n bexSubgraphPool.mutate();\n refreshOnChainPool();\n },\n };\n};\n","import useSWRImmutable from \"swr/immutable\";\n\nimport type { GqlPoolEventType } from \"@berachain/graphql/dex/api\";\n\nimport { getPoolEvents } from \"~/actions/dex/getPoolEvents\";\nimport { POLLING } from \"~/enum\";\n\nexport const usePoolEvents = ({\n poolId,\n typeInArray,\n}: {\n poolId: string | undefined;\n typeInArray: GqlPoolEventType[];\n}) => {\n return useSWRImmutable(\n poolId ? ([\"usePoolEvents\", poolId, typeInArray] as const) : null,\n async ([, poolId, typeInArray]) => getPoolEvents({ poolId, typeInArray }),\n {\n refreshInterval: POLLING.SLOW,\n },\n );\n};\n","import useSWR from \"swr\";\n\nimport type {\n GqlChain,\n PoolHistoricalDataFragment,\n} from \"@berachain/graphql/dex/api\";\n\nimport { getPoolHistoricalData } from \"~/actions/dex/getPoolHistoricalData\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\ntype UsePoolHistoricalDataArgs = {\n poolId: string | undefined;\n};\n\nexport const usePoolHistoricalData = (\n { poolId, ...baseArgs }: UsePoolHistoricalDataArgs & BeraJS.BaseFunctionArgs,\n options?: DefaultHookOptions,\n): DefaultHookReturnType<PoolHistoricalDataFragment[] | undefined> => {\n const { config } = parseBaseArgs(baseArgs);\n const QUERY_KEY = poolId\n ? ([\"usePoolHistoricalData\", poolId] as const)\n : null;\n\n const swrResponse = useSWR<\n PoolHistoricalDataFragment[] | undefined,\n any,\n typeof QUERY_KEY\n >(\n QUERY_KEY,\n async ([, poolId]) => {\n return await getPoolHistoricalData({\n poolId,\n chain: config.bex.chainName as GqlChain,\n });\n },\n options?.opts,\n );\n\n return {\n ...swrResponse,\n refresh: () => void swrResponse.mutate(),\n };\n};\n","import { useMemo } from \"react\";\nimport useSWR from \"swr\";\n\nimport type { GetPoolsQueryVariables } from \"@berachain/graphql/dex/api\";\nimport { useBeraWallet } from \"@berachain/wagmi/hooks\";\n\nimport { getAllPools } from \"~/actions/dex/getAllPools\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { DefaultHookOptions } from \"~/types\";\nimport { useAllUserPools } from \"./useAllUserPools\";\n\nexport const usePoolsQueryKey = ({\n query,\n}: {\n query?: GetPoolsQueryVariables;\n} = {}) => {\n return [\"useAllPools\", query];\n};\n/**\n * Returns all pools from bex api, including user's pools if logged in\n * @todo add subgraph fallback\n */\nexport const usePools = (\n query: GetPoolsQueryVariables,\n options?: DefaultHookOptions,\n) => {\n const { address: account } = useBeraWallet();\n const {\n data: userPools,\n isLoading: isUserPoolsLoading,\n mutate: mutateUserPools,\n } = useAllUserPools({\n userAddress: account,\n chain: query.chain,\n });\n\n const {\n data: pools,\n isLoading: isPoolsLoading,\n mutate: mutatePools,\n } = useSWR(\n usePoolsQueryKey({ query }),\n async ([_, query]) => {\n return getAllPools(query as GetPoolsQueryVariables);\n },\n {\n refreshInterval: POLLING.SLOW,\n ...options?.opts,\n },\n );\n\n const mergedPools = useMemo(() => {\n if (!pools || !userPools?.pools?.length) return pools?.pools ?? [];\n const userPoolsById = Object.fromEntries(\n userPools.pools.map((pool) => [pool.id.toLowerCase(), pool]),\n );\n return pools.pools\n .map((pool) => ({\n ...pool,\n ...(userPoolsById[pool.id.toLowerCase()] || {}),\n }))\n .filter(Boolean);\n }, [pools, userPools]);\n\n const pagination = useMemo(() => {\n return {\n page: Math.ceil((query?.skip ?? 0) / (query?.first ?? 10)),\n pageSize: query?.first,\n count: Math.ceil((pools?.count ?? 0) / (query?.first ?? 10)),\n };\n }, [pools, query.skip, query.first]);\n\n return {\n pools: mergedPools ?? [],\n walletPools: pools?.pools ?? [],\n isLoading: isPoolsLoading || isUserPoolsLoading,\n refresh: () => {\n mutatePools();\n mutateUserPools();\n },\n pagination,\n };\n};\n","\"use client\";\n\nimport useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getConvertToAssets } from \"~/actions\";\nimport { POLLING } from \"~/enum/polling\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type {\n BalanceTokenWithMetadata,\n GetZapTransactionResponse,\n} from \"~/types\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { computePriceImpact } from \"~/utils/math\";\nimport { isToken } from \"~/utils/tokens\";\nimport { useEnsoZap } from \"./useEnsoZap\";\n\ntype UseBendTransactionRequestsArgs = {\n /*\n * The input token to swap from\n */\n tokenIn?: Pick<\n BalanceTokenWithMetadata,\n \"address\" | \"decimals\" | \"price\" | \"formattedBalance\" | \"chainId\"\n >;\n /*\n * The loan token to swap to\n */\n loanTokenAddress: Address;\n /*\n * The price of the loan token\n */\n loanTokenPrice: number | undefined;\n /*\n * The bend vault to swap to\n */\n bendVault: Address;\n /*\n * The reward vault to swap to\n */\n rewardVault?: Address;\n /*\n * The amount of input token to swap\n */\n amount?: string;\n /*\n * The slippage tolerance to use for the route in percentage\n */\n slippage?: number;\n /*\n * The chain id to use for the public client\n */\n chainId?: number;\n};\n\n/**\n * Get the bend transaction requests for swapping tokens using Enso.\n * @param {UseBendTransactionRequestsArgs} props - The props for the hook see {@link UseBendTransactionRequestsArgs}\n * @returns {DefaultHookReturnType<GetZapTransactionResponse> & {tokens: BalanceTokenWithMetadata[], refresh: () => void}}\n *\n * The bend transaction response data with polling enabled, see {@link GetZapTransactionResponse} and {@link BalanceTokenWithMetadata}\n * @remarks The hook is only enabled when all parameters are provided and amount is greater than 0\n * @see {@link useEnsoZap}\n */\nexport function useBendTransactionRequests(\n {\n tokenIn,\n loanTokenAddress,\n loanTokenPrice,\n bendVault,\n rewardVault,\n amount,\n slippage,\n chainId,\n }: UseBendTransactionRequestsArgs,\n options?: DefaultHookOptions,\n) {\n const { tokens, refreshTokens } = useEnsoZap({\n chainId,\n });\n\n // this is using a dummy amount to get the gas\n // this allows us to not wait on the user input for fees\n const { data: dataForGas, error: errorForGas } =\n useBendTransactionRequestsHelper(\n {\n tokenIn,\n loanTokenAddress,\n loanTokenPrice,\n bendVault,\n rewardVault,\n amount: tokenIn?.formattedBalance,\n slippage,\n chainId: tokenIn?.chainId,\n },\n options,\n );\n\n // sum the value of the transactions\n const transactionValue =\n dataForGas?.transactions?.reduce(\n (acc, transaction) => acc + BigInt(transaction.value ?? 0n),\n 0n,\n ) ?? 0n;\n\n const nativeToken = tokens?.find(\n (token) => isToken(token, \"ETH\") && token.chainId === tokenIn?.chainId,\n );\n\n // enso is charging a fee, we need to subtract the value of the transaction from the chain token balance to get fee\n const nativeFee =\n BigInt(transactionValue) - BigInt(nativeToken?.balance ?? 0n);\n\n const swrResponse = useBendTransactionRequestsHelper(\n {\n tokenIn,\n loanTokenAddress,\n loanTokenPrice,\n bendVault,\n rewardVault,\n amount,\n slippage,\n chainId,\n },\n options,\n );\n\n return {\n ...swrResponse,\n nativeFee,\n error: errorForGas || swrResponse.error,\n tokens,\n refresh: () => {\n swrResponse.mutate();\n refreshTokens();\n },\n };\n}\n\nexport function useBendTransactionRequestsHelper(\n {\n tokenIn,\n loanTokenAddress,\n loanTokenPrice,\n bendVault,\n rewardVault,\n amount,\n slippage,\n chainId,\n }: UseBendTransactionRequestsArgs,\n options?: DefaultHookOptions,\n) {\n const { address: fromAddress } = useBeraWallet();\n const { getBendTransactionRequests } = useEnsoZap({\n chainId,\n });\n const isEnabled =\n !!tokenIn &&\n !!loanTokenAddress &&\n !!bendVault &&\n !!amount &&\n !!fromAddress &&\n !isToken(loanTokenAddress, tokenIn?.address) &&\n tokenIn.chainId &&\n Number(amount) > 0 &&\n !!slippage;\n const publicClient = usePublicClient({\n chainId,\n });\n const publicClientBeraChain = usePublicClient();\n const QUERY_KEY = isEnabled\n ? ([\n \"useBendTransactionRequests\",\n tokenIn,\n loanTokenAddress,\n loanTokenPrice,\n bendVault,\n rewardVault,\n amount,\n slippage,\n ] as const)\n : null;\n\n return useSWR(\n QUERY_KEY,\n async ([\n ,\n tokenIn,\n loanTokenAddress,\n loanTokenPrice,\n bendVault,\n rewardVault,\n amount,\n slippage,\n ]) => {\n if (!publicClient || !publicClientBeraChain) {\n throw new InvalidArgumentError({\n property: \"publicClient\",\n value: publicClient,\n expected: \"PublicClient\",\n });\n }\n\n const response = await getBendTransactionRequests({\n amount,\n tokenIn: tokenIn,\n loanToken: loanTokenAddress,\n bendVault,\n rewardVault,\n slippage,\n });\n\n const amountOutObject = response.bundle.amountsOut;\n const address = rewardVault\n ? (rewardVault.toLowerCase() as Address)\n : (bendVault.toLowerCase() as Address);\n const amountOut = amountOutObject[address];\n const supplyAmount = await getConvertToAssets({\n sharesAmount: BigInt(amountOut),\n vaultAddress: bendVault,\n publicClient: publicClientBeraChain,\n });\n\n const priceImpact =\n tokenIn?.price && loanTokenPrice\n ? computePriceImpact(\n tokenIn?.price?.toString(),\n loanTokenPrice?.toString(),\n amount,\n supplyAmount.formatted,\n )\n : undefined;\n\n return {\n supplyAmount,\n priceImpact,\n ...response,\n };\n },\n {\n ...options?.opts,\n refreshInterval: POLLING.NORMAL,\n },\n );\n}\n","\"use client\";\n\nimport { useCallback } from \"react\";\nimport type { BundleData, EnsoClient } from \"@ensofinance/sdk\";\nimport { getPublicClient } from \"@wagmi/core\";\nimport useSWR from \"swr\";\nimport { type Address, isAddress, parseUnits } from \"viem\";\n\nimport { defaultChainId as berachainChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { getBendTransactionRequests as getBendTransactionRequestsHelper } from \"~/actions/enso/bend\";\nimport { getZapTransactionRequests as getZapTransactionRequestsHelper } from \"~/actions/enso/zap\";\nimport type {\n BalanceToken,\n BalanceTokenWithMetadata,\n GetZapTransactionResponse,\n} from \"~/types\";\n\nexport type { GetZapTransactionResponse, BundleData, BalanceTokenWithMetadata };\n\nimport { getEnsoClient } from \"~/actions/clients/getEnsoClient\";\nimport { getEnsoUserToken } from \"~/actions/enso/getEnsoUserToken\";\nimport { POLLING } from \"~/enum/polling\";\nimport {\n assertAddress,\n assertDefined,\n assertPublicClient,\n} from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\n\nfunction useEnsoBalances(\n { ensoClient, chainId }: { ensoClient: EnsoClient; chainId?: number },\n options?: DefaultHookOptions,\n) {\n const { address: fromAddress } = useBeraWallet();\n const wagmiConfig = useConfig();\n const isEnabled = !!fromAddress && isAddress(fromAddress);\n\n const QUERY_KEY =\n isEnabled && wagmiConfig\n ? ([\"useEnsoBalances\", fromAddress, chainId] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, fromAddress, chainId]): Promise<BalanceTokenWithMetadata[]> =>\n getEnsoUserToken({\n account: fromAddress,\n wagmiConfig,\n chainId: chainId ?? \"all\",\n ensoClient,\n }),\n {\n refreshInterval: POLLING.FAST,\n isEnabled,\n ...options?.opts,\n },\n );\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n\n/**\n * Get the enso client.\n * @returns {EnsoClient} The enso client, see {@link EnsoClient}\n * @see {@link useEnsoBalances}\n * @see {@link useTokens}\n */\nexport function useEnsoZap({ chainId }: { chainId?: number }) {\n const { address: fromAddress } = useBeraWallet();\n const wagmiConfig = useConfig();\n const ensoClient = getEnsoClient();\n const { data: tokens, refresh: refreshTokens } = useEnsoBalances({\n ensoClient,\n chainId,\n });\n\n const getZapTransactionRequests = useCallback(\n async ({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n }: {\n tokenIn?: Pick<BalanceToken, \"address\" | \"decimals\" | \"chainId\">;\n tokenOut: Address;\n amount: string;\n slippage: number;\n }): Promise<GetZapTransactionResponse> => {\n assertAddress(fromAddress, \"fromAddress\");\n assertAddress(tokenIn?.address, \"tokenInAddress\");\n assertDefined(tokenIn?.chainId, \"tokenInChainId\");\n const publicClient = getPublicClient(wagmiConfig, {\n chainId: tokenIn.chainId,\n });\n assertPublicClient(publicClient);\n const rawAmount = parseUnits(amount, tokenIn.decimals).toString();\n\n return getZapTransactionRequestsHelper({\n fromAddress,\n amountIn: rawAmount,\n tokenIn: tokenIn?.address,\n tokenOut,\n chainId: tokenIn.chainId,\n ensoClient,\n destinationChainId: berachainChainId,\n slippage,\n publicClient,\n });\n },\n [fromAddress, ensoClient, wagmiConfig],\n );\n\n const getBendTransactionRequests = useCallback(\n async ({\n tokenIn,\n amount,\n loanToken,\n bendVault,\n rewardVault,\n slippage,\n }: {\n tokenIn?: Pick<BalanceToken, \"address\" | \"decimals\" | \"chainId\">;\n amount: string;\n loanToken: Address;\n bendVault: Address;\n rewardVault?: Address;\n slippage: number;\n }): Promise<GetZapTransactionResponse> => {\n assertAddress(fromAddress, \"fromAddress\");\n assertAddress(tokenIn?.address, \"tokenInAddress\");\n assertDefined(tokenIn?.chainId, \"tokenInChainId\");\n const publicClient = getPublicClient(wagmiConfig, {\n chainId: tokenIn.chainId,\n });\n assertPublicClient(publicClient);\n const rawAmount = parseUnits(amount, tokenIn.decimals).toString();\n\n return getBendTransactionRequestsHelper({\n fromAddress,\n amountIn: rawAmount,\n tokenIn: tokenIn.address,\n loanToken,\n bendVault,\n rewardVault,\n chainId: tokenIn.chainId,\n ensoClient,\n destinationChainId: berachainChainId,\n slippage,\n publicClient,\n });\n },\n [fromAddress, ensoClient, wagmiConfig],\n );\n\n return {\n tokens,\n getBendTransactionRequests,\n getZapTransactionRequests,\n refreshTokens,\n };\n}\n","import type { BundleAction, EnsoClient } from \"@ensofinance/sdk\";\nimport { type Address, ethAddress, type PublicClient, zeroAddress } from \"viem\";\n\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type { GetZapTransactionResponse, Quantity } from \"~/types\";\nimport { getTransactionsFromBundle } from \"./util\";\n\nexport interface GetBendTransactionRequestsArgs {\n fromAddress: Address;\n amountIn: Quantity;\n tokenIn: Address;\n loanToken: Address;\n bendVault: Address;\n rewardVault?: Address;\n chainId: number;\n ensoClient: EnsoClient;\n destinationChainId?: number;\n slippage: number;\n publicClient: PublicClient;\n}\n\nexport async function getBendTransactionRequests({\n fromAddress,\n amountIn,\n tokenIn,\n loanToken,\n bendVault,\n rewardVault,\n chainId,\n ensoClient,\n destinationChainId,\n slippage,\n publicClient,\n}: GetBendTransactionRequestsArgs): Promise<GetZapTransactionResponse> {\n if (!fromAddress) {\n throw new InvalidArgumentError({\n property: \"fromAddress\",\n value: fromAddress,\n expected: \"string\",\n });\n }\n if (loanToken === zeroAddress) loanToken = ethAddress;\n\n const bundleActions: BundleAction[] = [\n {\n protocol: \"enso\",\n action: \"route\",\n args: {\n tokenIn,\n tokenOut: loanToken,\n amountIn,\n slippage: slippage * 100, // Enso expects slippage in basis points\n },\n },\n ];\n /**\n * If the zap is cross chain, we need to add the destination chain id and the refund receiver.\n *\n * Enso still need to update the sdk types to support this.\n */\n if (destinationChainId && destinationChainId !== chainId) {\n bundleActions[0].args = {\n ...bundleActions[0].args,\n //@ts-expect-error enso are releasing a fix in the next 2 weeks for this.\n destinationChainId: destinationChainId,\n refundReceiver: fromAddress,\n };\n }\n // vault output is the vault address\n // vaults are in morpho-blue-vaults-v1\n // markets are here morpho-markets-v1\"\n bundleActions.push({\n protocol: \"erc4626\",\n action: \"deposit\",\n args: {\n amountIn: { useOutputOfCallAt: 0 },\n tokenIn: loanToken,\n primaryAddress: bendVault,\n tokenOut: bendVault,\n },\n });\n if (rewardVault) {\n bundleActions.push(\n {\n protocol: \"enso\",\n action: \"balance\",\n args: {\n token: bendVault,\n },\n },\n {\n protocol: \"erc20\",\n action: \"approve\",\n args: {\n amount: { useOutputOfCallAt: 2 },\n spender: rewardVault,\n token: bendVault,\n },\n },\n {\n protocol: \"enso\",\n action: \"call\",\n args: {\n address: rewardVault,\n args: [fromAddress, { useOutputOfCallAt: 2 }],\n method: \"stakeOnBehalf\",\n abi: \"function stakeOnBehalf(address account, uint256 amount) external\",\n },\n },\n {\n protocol: \"enso\",\n action: \"balance\",\n args: {\n token: rewardVault,\n },\n },\n );\n }\n\n const bundle = await ensoClient.getBundleData(\n {\n fromAddress: fromAddress,\n receiver: fromAddress,\n spender: fromAddress,\n chainId: chainId,\n routingStrategy: \"router\",\n },\n bundleActions,\n );\n const transactions = await getTransactionsFromBundle({\n fromAddress,\n amountIn,\n tokenIn,\n chainId,\n ensoClient,\n bundle,\n publicClient,\n });\n return {\n bundle,\n transactions,\n };\n}\n","import { type Address, erc20Abi, ethAddress } from \"viem\";\n\nimport type { GetZapTransactions, GetZapTransactionsArgs } from \"~/types\";\n\n/**\n * Get the zap transactions for a given bundle.\n * @param args - The arguments for the zap transactions.\n * @returns The the zap transaction & approval transaction if required.\n */\nexport const getTransactionsFromBundle = async ({\n fromAddress,\n amountIn,\n tokenIn,\n chainId,\n ensoClient,\n bundle,\n publicClient,\n}: GetZapTransactionsArgs): Promise<GetZapTransactions> => {\n const transactions: GetZapTransactions = [];\n /**\n * If the token is not the native token, we need to check if approval is required.\n */\n if (tokenIn !== ethAddress) {\n const approvalRequest = await ensoClient.getApprovalData({\n fromAddress,\n tokenAddress: tokenIn,\n chainId,\n amount: amountIn,\n });\n\n // check if approval is actually required by checking current allowance\n let requiresApproval = true;\n if (publicClient) {\n const currentAllowance = await publicClient.readContract({\n address: tokenIn as Address,\n abi: erc20Abi,\n functionName: \"allowance\",\n args: [fromAddress, approvalRequest.spender],\n });\n requiresApproval = currentAllowance < BigInt(amountIn);\n }\n\n // Only add approval transaction if it's actually required\n if (requiresApproval) {\n transactions.push({\n to: approvalRequest.tx.to,\n data: approvalRequest.tx.data as `0x${string}`,\n value: approvalRequest.tx.value as unknown as bigint,\n gasLimit: BigInt(approvalRequest.gas),\n });\n }\n }\n transactions.push({\n to: bundle.tx.to,\n data: bundle.tx.data as `0x${string}`,\n value: bundle.tx.value as unknown as bigint,\n gasLimit: BigInt(bundle.gas),\n });\n return transactions;\n};\n","import type { BundleAction } from \"@ensofinance/sdk\";\nimport { ethAddress, zeroAddress } from \"viem\";\n\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type {\n GetZapTransactionRequestsArgs,\n GetZapTransactionResponse,\n} from \"~/types\";\nimport { getTransactionsFromBundle } from \"./util\";\n\nexport async function getZapTransactionRequests({\n fromAddress,\n amountIn,\n tokenIn,\n tokenOut,\n chainId,\n ensoClient,\n destinationChainId,\n slippage,\n publicClient,\n}: GetZapTransactionRequestsArgs): Promise<GetZapTransactionResponse> {\n if (!fromAddress) {\n throw new InvalidArgumentError({\n property: \"fromAddress\",\n value: fromAddress,\n expected: \"address\",\n });\n }\n if (tokenOut === zeroAddress) tokenOut = ethAddress;\n\n const bundleAction: BundleAction = {\n protocol: \"enso\",\n action: \"route\",\n args: {\n tokenIn,\n tokenOut,\n amountIn,\n slippage: slippage * 100, // Enso expects slippage in basis points\n },\n };\n /**\n * If the zap is cross chain, we need to add the destination chain id and the refund receiver.\n *\n * Enso still need to update the sdk types to support this.\n */\n if (destinationChainId && destinationChainId !== chainId) {\n bundleAction.args = {\n ...bundleAction.args,\n //@ts-expect-error enso are releasing a fix in the next 2 weeks for this.\n destinationChainId: destinationChainId,\n refundReceiver: fromAddress,\n };\n }\n\n const bundle = await ensoClient.getBundleData(\n {\n fromAddress: fromAddress,\n receiver: fromAddress,\n spender: fromAddress,\n chainId: chainId,\n routingStrategy: \"router\",\n },\n [bundleAction],\n );\n const transactions = await getTransactionsFromBundle({\n fromAddress,\n amountIn,\n tokenIn,\n chainId,\n ensoClient,\n bundle,\n publicClient,\n });\n return {\n bundle,\n transactions,\n };\n}\n","import { EnsoClient } from \"@ensofinance/sdk\";\n\nimport { appConfig } from \"@berachain/config/internal\";\n\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nconst isProduction =\n process.env.NODE_ENV !== \"development\" && process.env.NODE_ENV !== \"test\";\n\nexport function getEnsoClient({\n useProxy = isProduction,\n ...args\n}: BeraJS.BaseFunctionArgs & { useProxy?: boolean } = {}) {\n const { config } = parseBaseArgs(args);\n return new EnsoClient({\n baseURL: useProxy\n ? `${config.bex.aggregatorsProxyUrl}/enso/api/v1/`\n : undefined,\n apiKey: useProxy\n ? // no API key since proxy has CORS for .berachain.com domains\n \"\"\n : appConfig.apiKeys.public.enso,\n });\n}\n","import type { EnsoClient } from \"@ensofinance/sdk\";\nimport * as Sentry from \"@sentry/nextjs\";\nimport { type Config, getChains, multicall } from \"@wagmi/core\";\nimport { type Address, formatUnits } from \"viem\";\n\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport { initBeraError } from \"~/errors/initBeraError\";\nimport type { BalanceTokenWithMetadata } from \"~/types/dex\";\nimport { getBalanceCall } from \"../tokens/getWalletBalances\";\n\n/**\n * Get user balances for each supported chain.\n *\n * This uses enso's balance endpoint to get the balances and RPC to get fresh balances.\n */\nexport async function getEnsoUserToken({\n account,\n wagmiConfig,\n chainId,\n ensoClient,\n}: {\n account: Address;\n wagmiConfig: Config;\n chainId: number | \"all\";\n ensoClient: EnsoClient;\n}): Promise<BalanceTokenWithMetadata[]> {\n const ensoBalances = await ensoClient.getBalances({\n useEoa: true,\n chainId: chainId ?? \"all\",\n eoaAddress: account,\n });\n\n const tokens: BalanceTokenWithMetadata[] = ensoBalances.map((balance) => ({\n name: balance.name,\n symbol: balance.symbol,\n decimals: balance.decimals,\n address: balance.token,\n logoURI: balance.logoUri,\n balance: BigInt(balance.amount),\n formattedBalance: formatUnits(BigInt(balance.amount), balance.decimals),\n chainId: Number(\n // @ts-expect-error - balance.chainId is defined just not typed by enso\n balance.chainId,\n ),\n price: Number(balance.price),\n }));\n\n const tokenByChainId = Object.groupBy(tokens, (a) => a.chainId ?? 0);\n\n const balances = await Promise.allSettled(\n Object.entries(tokenByChainId).map(async ([chainId, chainTokens]) => {\n if (!chainTokens) return undefined;\n const chainConfig = getChains(wagmiConfig).find(\n (chain) => chain.id === Number(chainId),\n );\n\n if (!chainConfig) {\n // if we've queried a chain that is not supported, we need to return undefined\n return undefined;\n }\n\n const multicall3 = chainConfig.contracts?.multicall3;\n\n const multicallAddress = multicall3?.address;\n\n if (!multicallAddress) {\n // if multicall is not supported on this chain, we need to use the enso balance\n // first let's report the error, as this is likely unexpected\n Sentry.captureException(\n new InvalidArgumentError({\n property: \"multicallAddress\",\n value: multicallAddress,\n expected: \"Address\",\n chainId: Number(chainId),\n }),\n );\n\n // we can return the tokens as is, as the balance is already set from the enso client\n return chainTokens;\n }\n\n const balances = await multicall(wagmiConfig, {\n chainId: Number(chainId),\n contracts: chainTokens.map((token) =>\n getBalanceCall({\n token,\n account,\n multicallAddress,\n }),\n ),\n allowFailure: true,\n });\n\n const tokensWithBalances: BalanceTokenWithMetadata[] = [];\n\n for (let index = 0; index < chainTokens.length; index++) {\n const token = chainTokens[index];\n if (balances[index].status === \"success\") {\n tokensWithBalances.push({\n ...token,\n balance: balances[index].result as bigint,\n formattedBalance: formatUnits(\n balances[index].result as bigint,\n token.decimals,\n ),\n });\n } else {\n console.error(\"error getting balance\", balances[index].error);\n captureException(initBeraError({ cause: balances[index].error }));\n // uses enso balance as fallback\n tokensWithBalances.push(token);\n }\n }\n\n return tokensWithBalances;\n }),\n );\n\n const flattenedBalances: BalanceTokenWithMetadata[] = [];\n for (const result of balances) {\n if (result.status === \"fulfilled\") {\n flattenedBalances.push(...(result.value ?? []));\n } else {\n captureException(initBeraError({ cause: result.reason }));\n }\n }\n\n return flattenedBalances.sort((a, b) => {\n const aValue = Number(a.formattedBalance) * (a.price ?? 0);\n const bValue = Number(b.formattedBalance) * (b.price ?? 0);\n return bValue - aValue;\n });\n}\n","\"use client\";\n\nimport useSWR from \"swr\";\n\nimport { POLLING } from \"~/enum/polling\";\nimport { assertAddress, assertAmount, assertDefined } from \"~/errors/assert\";\nimport type {\n BalanceToken,\n BalanceTokenWithMetadata,\n GetZapTransactionResponse,\n} from \"~/types\";\nimport { useEnsoZap } from \"./useEnsoZap\";\n\n/**\n * Get the zap transaction requests for swapping tokens using Enso.\n * @param {Pick<BalanceToken, \"address\" | \"decimals\">} tokenIn - The input token to swap from\n * @param {Pick<BalanceToken, \"address\" | \"decimals\">} tokenOut - The output token to swap to\n * @param {string} amount - The amount of input token to swap\n * @param {number} slippage - The slippage tolerance to use for the route in percentage\n * @returns {DefaultHookReturnType<GetZapTransactionResponse> & {tokens: BalanceTokenWithMetadata[], refresh: () => void}}\n *\n * The zap transaction response data with polling enabled, see {@link GetZapTransactionResponse} and {@link BalanceTokenWithMetadata}\n * @remarks The hook is only enabled when all parameters are provided and amount is greater than 0\n * @see {@link useEnsoZap}\n */\nexport const useZapTransactionRequests = ({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n chainId,\n}: {\n tokenIn?: Pick<BalanceToken, \"address\" | \"decimals\">;\n tokenOut?: Pick<BalanceToken, \"address\" | \"decimals\">;\n amount?: string;\n slippage?: number;\n chainId?: number;\n}) => {\n const { getZapTransactionRequests, refreshTokens, tokens } = useEnsoZap({\n chainId,\n });\n const isEnabled =\n !!tokenIn && !!tokenOut && !!amount && Number(amount) > 0 && !!slippage;\n const QUERY_KEY = isEnabled\n ? ([\n \"useZapTransactionRequests\",\n tokenIn,\n tokenOut,\n amount,\n slippage,\n ] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, tokenIn, tokenOut, amount, slippage]) => {\n assertDefined(tokenIn, \"tokenIn\");\n assertAddress(tokenOut?.address, \"tokenOutAddress\");\n assertAmount(amount, \"amount\");\n assertAmount(slippage, \"slippage\");\n return getZapTransactionRequests({\n amount,\n tokenIn: tokenIn,\n tokenOut: tokenOut.address,\n slippage,\n });\n },\n {\n refreshInterval: POLLING.NORMAL,\n isEnabled: isEnabled,\n },\n );\n return {\n ...swrResponse,\n tokens,\n refresh: () => {\n swrResponse.mutate();\n refreshTokens();\n },\n };\n};\n","\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\n\nimport { getProposalParams } from \"~/actions/governance/getProposalParams\";\nimport {\n type CustomProposal,\n type CustomProposalErrors,\n type GovernanceTopic,\n type PROPOSAL_GENRE,\n ProposalTypeEnum,\n type SafeProposalAction,\n} from \"../../types\";\n\nconst defaultAction = {\n type: ProposalTypeEnum.CUSTOM_PROPOSAL,\n target: \"\",\n ABI: \"\",\n value: 0n,\n functionSignature: \"\",\n args: [],\n input: \"ABI\",\n rawCalldata: \"0x\",\n message: \"\",\n} satisfies SafeProposalAction;\n\nexport const useCreateProposal = ({\n initialData = {},\n currentTopic,\n onError,\n}: {\n initialData?: any;\n currentTopic: GovernanceTopic;\n onError: (e: CustomProposalErrors) => void;\n}) => {\n const [proposal, setProposal] = useState<CustomProposal>({\n title: \"\",\n description: \"\",\n forumLink: \"\",\n actions: [defaultAction],\n ...initialData,\n topic: new Set(),\n });\n\n useEffect(() => {\n setProposal((p) => ({\n ...p,\n topic: new Set<PROPOSAL_GENRE>([currentTopic.id]),\n }));\n }, [currentTopic]);\n\n const addProposalAction = useCallback(() => {\n setProposal((p) => ({ ...p, actions: [...p.actions, defaultAction] }));\n }, []);\n\n const removeProposalAction = useCallback(\n (idx: number) => {\n setProposal((p) => {\n const actions = [...p.actions];\n actions.splice(idx, 1);\n return { ...p, actions };\n });\n },\n [setProposal],\n );\n\n const computeParamsAndErrors = useCallback(() => {\n if (!proposal) {\n return;\n }\n\n const computedParams = getProposalParams({\n proposal,\n currentTopic,\n onError,\n });\n\n return computedParams;\n }, [proposal, currentTopic]);\n\n return {\n proposal,\n setProposal,\n addProposalAction,\n removeProposalAction,\n computeParamsAndErrors,\n };\n};\n","import matter from \"gray-matter\";\nimport {\n type Address,\n encodeFunctionData,\n erc20Abi,\n parseAbiItem,\n toHex,\n} from \"viem\";\n\nimport { beraChefAbi } from \"~/abi/pol/beraChef\";\nimport { rewardVaultAbi } from \"~/abi/pol/rewardVault\";\nimport {\n type CustomProposal,\n type CustomProposalActionErrors,\n type CustomProposalErrors,\n type GovernanceTopic,\n ProposalErrorCodes,\n ProposalTypeEnum,\n} from \"~/types\";\nimport { hasAnyTruthyValues } from \"~/utils/hasAnyTruthyValues\";\nimport { checkProposalField } from \"./checkProposalField\";\nimport { getBodyErrors } from \"./getBodyErrors\";\n\nexport const getProposalParams = ({\n proposal,\n currentTopic,\n onError,\n}: {\n /**\n * The proposal to get the parameters for\n */\n proposal: CustomProposal;\n /**\n * The current topic\n */\n currentTopic: GovernanceTopic;\n /**\n * Callback to handle errors\n */\n onError?: (e: CustomProposalErrors) => void;\n}) => {\n const e: CustomProposalErrors = getBodyErrors(proposal, currentTopic);\n\n const actions: Address[] = [];\n\n e.actions = proposal.actions.map((action, idx) => {\n const errors: CustomProposalActionErrors = {};\n errors.target = checkProposalField({\n fieldOrType: \"address\",\n value: action.target,\n });\n\n if (action.type === ProposalTypeEnum.CUSTOM_PROPOSAL) {\n if (action.input === \"ABI\") {\n errors.ABI = checkProposalField({\n fieldOrType: \"abi\",\n value: action.ABI,\n });\n if (!action.functionSignature) {\n errors.functionSignature = ProposalErrorCodes.REQUIRED;\n } else {\n try {\n const parsedSignatureAbi = parseAbiItem(action.functionSignature);\n if (parsedSignatureAbi.type !== \"function\") {\n console.error(\n \"parsedSignatureAbi is not a function\",\n parsedSignatureAbi,\n );\n\n errors.functionSignature = ProposalErrorCodes.INVALID_ABI;\n } else {\n errors.args = parsedSignatureAbi.inputs.map((input, index) => {\n try {\n if (\"components\" in input) {\n return checkProposalField({\n // @ts-expect-error this is not typed, will throw if not valid\n fieldOrType: input.type,\n value: action.args?.[index],\n components: input.components,\n });\n }\n\n return checkProposalField({\n // @ts-expect-error this is not typed, will throw if not valid\n fieldOrType: input.type,\n value: action.args?.[index],\n });\n } catch {\n return null;\n }\n });\n\n if (!errors.args.some((v) => v)) {\n actions[idx] = encodeFunctionData({\n abi: [parsedSignatureAbi],\n args: action.args,\n });\n }\n }\n } catch {\n errors.functionSignature = ProposalErrorCodes.INVALID_ABI;\n }\n }\n } else if (action.input === \"rawCalldata\") {\n errors.rawCalldata = checkProposalField({\n fieldOrType: \"hex\",\n value: action.rawCalldata,\n });\n actions[idx] = action.rawCalldata!;\n } else if (action.input === \"message\") {\n errors.message = checkProposalField({\n fieldOrType: \"string\",\n value: action.message,\n });\n actions[idx] = toHex(action.message!);\n } else {\n throw new Error(\"Invalid input type\");\n }\n } else if (\n action.type === ProposalTypeEnum.WHITELIST_REWARD_VAULT ||\n action.type === ProposalTypeEnum.BLACKLIST_REWARD_VAULT\n ) {\n errors.vault = checkProposalField({\n fieldOrType: \"address\",\n value: action.vault,\n });\n\n if (!errors.vault) {\n const whiteList =\n action.type === ProposalTypeEnum.WHITELIST_REWARD_VAULT;\n\n actions[idx] = encodeFunctionData({\n abi: beraChefAbi,\n functionName: \"setVaultWhitelistedStatus\",\n args: [action.vault!, whiteList, \"\"],\n });\n }\n } else if (\n action.type === ProposalTypeEnum.WHITELIST_REWARD_VAULT_INCENTIVE\n ) {\n errors.token = checkProposalField({\n fieldOrType: \"address\",\n value: action.token,\n });\n\n errors.minIncentiveRate = checkProposalField({\n fieldOrType: \"uint256\",\n value: action.minIncentiveRate,\n });\n\n errors.managerAddress = checkProposalField({\n fieldOrType: \"address\",\n value: action.managerAddress,\n });\n\n if (!errors.token && !errors.minIncentiveRate && !errors.managerAddress) {\n actions[idx] = encodeFunctionData({\n abi: rewardVaultAbi,\n functionName: \"whitelistIncentiveToken\",\n args: [\n action.token!,\n BigInt(action.minIncentiveRate!),\n action.managerAddress!,\n ],\n });\n }\n } else if (action.type === ProposalTypeEnum.ERC20_TRANSFER) {\n errors.amount = checkProposalField({\n fieldOrType: \"uint256\",\n value: action.amount,\n });\n errors.to = checkProposalField({\n fieldOrType: \"address\",\n value: action.to,\n });\n if (!errors.amount && !errors.to) {\n actions[idx] = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"transfer\",\n args: [action.to!, BigInt(action.amount!)],\n });\n }\n }\n\n const hasErrors = hasAnyTruthyValues(errors);\n\n if (!hasErrors) {\n return null;\n }\n\n return errors;\n });\n\n onError?.(e);\n\n if (\n Object.getOwnPropertyNames(e)\n .map((name) => e[name as keyof typeof e])\n .some((v) => {\n if (Array.isArray(v)) {\n return v.filter((v) => v).length > 0;\n }\n\n if (v === null) {\n return false;\n }\n\n return !!v;\n })\n ) {\n console.warn(\"Proposal has errors\", e);\n return;\n }\n\n if (actions.length === 0) {\n throw new Error(\"No actions submitted in proposal\");\n }\n\n const link = new URL(proposal.forumLink);\n\n const description = matter.stringify(proposal.description, {\n title: proposal.title,\n topics: Array.from(proposal.topic.values()),\n forumLink: link.toString(),\n version: \"1.0.0\",\n \"content-encoding\": \"utf-8\",\n \"content-type\": \"text/markdown\",\n actions: proposal.actions.map((action) => {\n const actionMetadata: Record<string, string> = {\n type: action.type,\n };\n\n if (action.type === ProposalTypeEnum.CUSTOM_PROPOSAL) {\n actionMetadata.inputType = action.input!;\n }\n\n return actionMetadata;\n }),\n });\n\n return [\n proposal.actions.map((action) => action.target as `0x${string}`),\n proposal.actions.map((action) => action.value ?? 0n),\n actions,\n description,\n ] as const;\n};\n","export function hasAnyTruthyValues<T extends Record<string, any>>(\n obj: T,\n): boolean {\n return Object.values(obj).some((value) => {\n if (Array.isArray(value)) {\n return value.some((item) =>\n typeof item === \"object\" && item !== null\n ? hasAnyTruthyValues(item)\n : !!item,\n );\n }\n if (typeof value === \"object\" && value !== null) {\n return hasAnyTruthyValues(value);\n }\n return !!value;\n });\n}\n","import useSWRImmutable from \"swr/immutable\";\nimport { type Address, formatUnits } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { bgtAbi } from \"~/abi/pol/bgt\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { useProposalSnapshot } from \"./useProposalSnapshot\";\n\n/**\n * Returns the amount of voting power that a wallet had when the voting period began.\n * {@link https://docs.openzeppelin.com/contracts/5.x/api/governance#Votes-getPastVotes-address-uint256-}\n */\nexport const useGetPastVotes = (\n args: {\n wallet?: Address;\n } & (\n | {\n proposalId?: bigint;\n timepoint: number | bigint;\n }\n | {\n proposalId: bigint;\n timepoint?: number | bigint;\n }\n ),\n) => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n\n const wallet = args.wallet || account;\n\n const { data: snapshot } = useProposalSnapshot({\n proposalId: args.proposalId,\n });\n\n const ts = args.timepoint || snapshot;\n\n const QUERY_KEY =\n ts && publicClient && wallet\n ? ([\"useGetPastVotes\", ts, wallet] as const)\n : null;\n\n return useSWRImmutable(QUERY_KEY, async ([, ts, wallet]) => {\n assertPublicClient(publicClient);\n const { config } = parseBaseArgs({\n chainId: publicClient.chain.id,\n });\n if (Number(ts) > Date.now() / 1000) {\n throw new Error(\"timepoint is in the future\");\n }\n\n const votes = await publicClient.readContract({\n abi: bgtAbi,\n address: config.tokens.bgt,\n functionName: \"getPastVotes\",\n args: [wallet, BigInt(ts)],\n });\n\n return formatUnits(votes, 18);\n });\n};\n","import type { SWRResponse } from \"swr\";\nimport useSWRImmutable from \"swr/immutable\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { governanceAbi } from \"~/abi/governance/governance\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\n/**\n * Timepoint used to retrieve user’s votes and quorum. If using block\n * number (as per Compound’s Comp), the snapshot is performed at\n * the end of this block. Hence, voting for this proposal starts at the beginning of the following block.\n *\n * {@link https://docs.openzeppelin.com/contracts/5.x/api/governance#IGovernor-proposalSnapshot-uint256-}\n */\nexport const useProposalSnapshot = ({\n proposalId,\n}: {\n proposalId: number | bigint | string | undefined;\n}): SWRResponse<string> => {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n publicClient && proposalId\n ? ([\"useProposalSnapshot\", proposalId] as const)\n : null;\n\n return useSWRImmutable(QUERY_KEY, async ([, proposalId]) => {\n assertPublicClient(publicClient);\n\n const { config } = parseBaseArgs({\n chainId: publicClient.chain.id,\n });\n const snapshot = await publicClient.readContract({\n abi: governanceAbi,\n address: config.governance.governor,\n functionName: \"proposalSnapshot\",\n args: [BigInt(proposalId)],\n });\n\n return snapshot.toString();\n });\n};\n","import useSWR from \"swr\";\nimport { type Address, isAddress } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { governanceAbi } from \"~/abi/governance/governance\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport const useHasVoted = ({\n proposalId,\n wallet,\n}: {\n proposalId: string;\n wallet?: Address;\n}) => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n\n const address = wallet || account;\n return useSWR(\n publicClient && address && isAddress(address)\n ? ([\"useHasVoted\", proposalId, address] as const)\n : null,\n ([, proposalId, address]) => {\n assertPublicClient(publicClient);\n const { config } = parseBaseArgs({\n chainId: publicClient.chain.id,\n });\n return publicClient.readContract({\n address: config.governance.governor,\n abi: governanceAbi,\n functionName: \"hasVoted\",\n args: [BigInt(proposalId), address],\n });\n },\n );\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { governanceTimelockAbi } from \"~/abi/governance/governanceTimelock\";\nimport { CANCELLER_ROLE } from \"~/actions/governance/constants\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport const useIsCanceller = ({\n account,\n ...baseArgs\n}: {\n account: Address | undefined;\n} & BeraJS.BaseFunctionArgs) => {\n const publicClient = usePublicClient();\n const { config: chainConfig } = parseBaseArgs(baseArgs);\n\n const QUERY_KEY =\n account && publicClient ? ([\"useCancellerRole\", account] as const) : null;\n\n return useSWR(\n QUERY_KEY,\n async ([, account]) => {\n assertPublicClient(publicClient);\n\n const canceller = await publicClient.readContract({\n abi: governanceTimelockAbi,\n address: chainConfig.governance.timelock,\n functionName: \"hasRole\",\n args: [CANCELLER_ROLE, account],\n });\n\n return canceller;\n },\n {\n refreshInterval: POLLING.SLOW,\n revalidateOnFocus: false,\n },\n );\n};\n","/**\n * keccak256(\"CANCELLER_ROLE\")\n *\n * @see https://beratrail.io/address/0xD4e9dD9bb5acC31B550b618701c836fAEF6E0eE1/contract/80094/readContract#F1\n */\nexport const CANCELLER_ROLE =\n \"0xfd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783\";\n","import { useEffect, useMemo, useState } from \"react\";\nimport useSWRInfinite, { type SWRInfiniteResponse } from \"swr/infinite\";\n\nimport {\n type OrderDirection,\n type Proposal_Filter,\n Proposal_OrderBy,\n type ProposalSelectionFragment,\n ProposalStatus,\n} from \"@berachain/graphql/governance\";\n\nimport { getAllProposals } from \"~/actions/governance/getAllProposals\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { DefaultHookOptions } from \"~/types\";\n\nconst DEFAULT_PER_PAGE = 10;\n\nconst fromUiStatusToSubgraphStatuses = (\n status: ProposalStatus,\n): ProposalStatus[] => {\n switch (status) {\n case ProposalStatus.QuorumNotReached:\n return [ProposalStatus.Active, ProposalStatus.Pending];\n case ProposalStatus.PendingQueue:\n case ProposalStatus.Defeated:\n return [ProposalStatus.Active];\n case ProposalStatus.PendingExecution:\n return [ProposalStatus.InQueue];\n default:\n return [status];\n }\n};\n\ntype UsePollAllProposalsArgs = {\n topic: string;\n where?: Proposal_Filter;\n perPage?: number;\n orderBy?: Proposal_OrderBy;\n orderDirection?: OrderDirection;\n status_in?: ProposalStatus[];\n text?: string;\n autoRefreshProposals?: boolean;\n};\n\ntype ProposalResult = {\n data: ProposalSelectionFragment[][];\n hasMore: boolean;\n} & Omit<SWRInfiniteResponse<ProposalSelectionFragment[]>, \"data\">;\n\ntype PollAllProposalsKey =\n | [\n \"usePollAllProposals\",\n number,\n string,\n Proposal_Filter | undefined,\n ProposalStatus[] | undefined,\n Proposal_OrderBy | undefined,\n OrderDirection | undefined,\n number,\n string | undefined,\n ]\n | null;\n\nexport function usePollAllProposalsQueryKey(\n topic: string,\n args: Partial<UsePollAllProposalsArgs> = {},\n): (\n pageIndex: number,\n previousPageData?: ProposalSelectionFragment[],\n) => PollAllProposalsKey {\n const subgraphPageSize = 2 * (args.perPage ?? DEFAULT_PER_PAGE);\n\n return (pageIndex, previousPageData) => {\n if (\n pageIndex !== 0 &&\n previousPageData &&\n previousPageData.length < subgraphPageSize\n ) {\n return null;\n }\n\n const statuses = args.status_in\n ?.flatMap(fromUiStatusToSubgraphStatuses)\n .filter((s, i, arr) => arr.indexOf(s) === i);\n\n return [\n \"usePollAllProposals\",\n pageIndex,\n topic,\n args.where,\n statuses,\n args.orderBy,\n args.orderDirection,\n subgraphPageSize,\n args.text,\n ];\n };\n}\n\n/**\n * Fetch all proposals for a given topic\n */\nexport function usePollAllProposals(\n args: UsePollAllProposalsArgs,\n options?: DefaultHookOptions & { autoRefresh?: boolean },\n): ProposalResult {\n const autoRefreshProposals = options?.autoRefresh ?? false;\n\n const perPage = args.perPage ?? DEFAULT_PER_PAGE;\n const subgraphPageSize = 2 * perPage;\n\n const getKey = usePollAllProposalsQueryKey(args.topic, args);\n\n async function fetcher(key: PollAllProposalsKey) {\n if (!key) return [];\n const [\n ,\n pageIndex,\n topic,\n where,\n statuses,\n orderBy,\n orderDirection,\n pageSize,\n text,\n ] = key;\n\n const proposals = await getAllProposals({\n where: {\n topics_contains: [topic],\n status_in: statuses?.length ? statuses : undefined,\n ...where,\n },\n orderBy,\n orderDirection,\n text,\n perPage: pageSize,\n offset: pageIndex * pageSize,\n });\n\n return (proposals ?? []).filter(Boolean) as ProposalSelectionFragment[];\n }\n\n const swr = useSWRInfinite<ProposalSelectionFragment[], PollAllProposalsKey>(\n getKey,\n fetcher,\n {\n // Increase initialSize in order to prefetch more proposals at a time.\n initialSize: 1,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.SLOW,\n ...options?.opts,\n },\n );\n\n const data = useMemo(() => {\n if (!swr.data) return [];\n\n const flattened = swr.data\n .flat()\n .filter((p) => {\n if (!p) return false;\n if (!args.status_in?.length) return true;\n return args.status_in.includes(p.status);\n })\n .sort((a, b) => {\n if (!args.text) return 0;\n if (args.orderBy === Proposal_OrderBy.CreatedAt) {\n const result = Number(b.createdAt) - Number(a.createdAt);\n return args.orderDirection === \"asc\" ? result : -result;\n }\n return 0;\n });\n\n const chunked: ProposalSelectionFragment[][] = [];\n for (let i = 0; i < flattened.length; i += perPage) {\n chunked.push(flattened.slice(i, i + perPage));\n }\n return chunked;\n }, [swr.data, args, perPage]);\n\n const lastPage = swr.data?.[swr.data.length - 1];\n const hasMore = !!lastPage && lastPage.length === subgraphPageSize;\n\n const [timestamp, setTimestamp] = useState(Date.now() / 1000);\n\n useEffect(() => {\n if (!autoRefreshProposals) return;\n const interval = setInterval(() => {\n setTimestamp(Date.now() / 1000);\n }, POLLING.FAST);\n\n return () => clearInterval(interval);\n }, [autoRefreshProposals]);\n\n useEffect(() => {\n if (!swr.data) return;\n\n let shouldMutate = false;\n for (const proposal of swr.data.flat()) {\n switch (proposal.status) {\n case ProposalStatus.Pending:\n if (timestamp >= Number(proposal.voteStartAt)) {\n shouldMutate = true;\n }\n break;\n case ProposalStatus.Active:\n if (timestamp >= Number(proposal.voteEndAt)) {\n shouldMutate = true;\n }\n break;\n case ProposalStatus.InQueue:\n if (Date.now() / 1000 + 1 >= Number(proposal.queueEnd)) {\n shouldMutate = true;\n }\n break;\n default:\n break;\n }\n if (shouldMutate) break;\n }\n\n if (shouldMutate) {\n swr.mutate();\n }\n }, [swr.data, timestamp]);\n\n return {\n ...swr,\n data,\n hasMore,\n };\n}\n","import { useEffect, useState } from \"react\";\nimport useSWR from \"swr\";\n\nimport {\n ProposalStatus,\n type ProposalWithVotesFragment,\n} from \"@berachain/graphql/governance\";\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getProposalDetails } from \"~/actions/governance/getProposalDetails\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport interface UsePollProposalResponse\n extends DefaultHookReturnType<ProposalWithVotesFragment> {}\n\n/**\n * Polls a proposal and returns the proposal details.\n * Pulls data from the subgraph and onchain.\n *\n * @param proposalId - The ID of the proposal to poll\n * @param options - Optional configuration options\n * @param options.autoRefresh - If true, the data will be refreshed automatically based on the block number and status threshold\n * @returns {UsePollProposalResponse} Object containing:\n * - data: ProposalWithVotesFragment | undefined - The proposal data if successful\n * - error: Error | undefined - Error object if request failed\n * - isLoading: boolean - True while data is being fetched\n * - isValidating: boolean - True while data is being revalidated\n * - mutate: () => Promise<ProposalWithVotesFragment | undefined> - Function to manually refresh the data\n * - refresh: () => Promise<void> - Function to manually refresh the data\n */\nexport const usePollProposal = (\n proposalId: string,\n options?: DefaultHookOptions & { autoRefresh?: boolean },\n): UsePollProposalResponse => {\n const autoRefreshProposal = options?.autoRefresh ?? false;\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n proposalId && publicClient\n ? ([\"usePollProposal\", proposalId] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n ([, proposalId]) => {\n assertPublicClient(publicClient);\n\n return getProposalDetails({ proposalId, client: publicClient });\n },\n {\n ...options?.opts,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.SLOW,\n },\n );\n\n const [timestamp, setTimestamp] = useState(Date.now());\n\n useEffect(() => {\n if (!autoRefreshProposal) return;\n const interval = setInterval(() => {\n setTimestamp(Date.now() / 1000);\n }, POLLING.FAST);\n\n return () => clearInterval(interval);\n }, []);\n\n useEffect(() => {\n if (swrResponse.data === undefined) return;\n\n switch (swrResponse.data.status) {\n case ProposalStatus.Pending:\n if (timestamp >= Number(swrResponse.data.voteStartAt)) {\n swrResponse.mutate();\n }\n break;\n case ProposalStatus.Active:\n if (timestamp >= Number(swrResponse.data.voteEndAt)) {\n swrResponse.mutate();\n }\n break;\n case ProposalStatus.InQueue:\n if (Date.now() / 1000 + 1 >= Number(swrResponse.data.queueEnd)) {\n swrResponse.mutate();\n }\n break;\n }\n }, [swrResponse.data?.status, timestamp]);\n\n // const votes = swrResponse.data?.votes.nodes ?? [];\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","import useSWR from \"swr\";\nimport { type Address, formatEther } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { governanceAbi } from \"~/abi/governance/governance\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookReturnType } from \"~/types\";\n\nexport const usePollProposalThreshold = (\n governorAddress: Address,\n): DefaultHookReturnType<{ votesThreshold: string }> => {\n const publicClient = usePublicClient();\n\n const QUERY_KEY = publicClient\n ? ([\"usePollProposalThreshold\", governorAddress] as const)\n : null;\n\n const swrResponse = useSWR<{ votesThreshold: string }, any, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([, governorAddress]) => {\n assertPublicClient(publicClient);\n\n const votesThreshold = await publicClient.readContract({\n address: governorAddress,\n abi: governanceAbi,\n functionName: \"proposalThreshold\",\n });\n return { votesThreshold: formatEther(votesThreshold) };\n },\n {\n refreshInterval: POLLING.SLOW,\n },\n );\n\n return {\n ...swrResponse,\n refresh: swrResponse.mutate,\n };\n};\n","import useSWRInfinite, { type SWRInfiniteKeyLoader } from \"swr/infinite\";\n\nimport type { GetProposalVotesQueryVariables } from \"@berachain/graphql/governance\";\n\nimport { getProposalVotes } from \"~/actions/governance/getProposalVotes\";\n\ntype UsePollProposalVotesArgs = Omit<\n GetProposalVotesQueryVariables,\n \"offset\" | \"limit\"\n>;\n\n// const ACTUAL_PER_PAGE = 500;\n\nconst DEFAULT_LIMIT = 1000;\n/**\n * Fetches all the votes for a proposal from the Subgraph\n * @param args - The arguments to pass to the query\n * @param total - The total amount of pages of votes to fetch\n */\nexport const usePollProposalVotes = (\n args: UsePollProposalVotesArgs,\n total: number,\n) => {\n return useSWRInfinite(\n usePollProposalVotesQueryKey(args, total),\n async ([_key, page]: [string, number]) => {\n return getProposalVotes({\n variables: {\n ...args,\n limit: DEFAULT_LIMIT,\n offset: DEFAULT_LIMIT * page,\n },\n });\n },\n {\n parallel: true,\n // Fetches all the data at once, we limit the number of pages by providing a total\n initialSize: Number.POSITIVE_INFINITY,\n },\n );\n};\n\nexport const usePollProposalVotesQueryKey =\n (\n { ...args }: UsePollProposalVotesArgs,\n total: number,\n ): SWRInfiniteKeyLoader =>\n (\n pageIndex: number,\n // previousPageData: Awaited<ReturnType<typeof getProposalVotes>>,\n ) => {\n if (pageIndex > Math.floor(total / DEFAULT_LIMIT)) {\n return null;\n }\n\n return [\n \"usePollProposalVotes\",\n pageIndex,\n DEFAULT_LIMIT,\n args.proposalId,\n args.orderBy,\n args.orderDirection,\n ];\n };\n","import useSWR from \"swr\";\nimport { type Address, formatEther } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { bgtAbi } from \"~/abi/pol/bgt\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport const usePollUserDelegates = (\n options?: DefaultHookOptions,\n): DefaultHookReturnType<{\n delegate: Address;\n currentVotes: string | undefined;\n}> => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n const QUERY_KEY = account\n ? ([\"usePollUserDelegates\", account] as const)\n : null;\n\n const swrResponse = useSWR<\n { delegate: Address; currentVotes: string | undefined },\n any,\n typeof QUERY_KEY\n >(\n QUERY_KEY,\n async ([, account]) => {\n assertPublicClient(publicClient);\n const { config } = parseBaseArgs({\n chainId: publicClient.chain.id,\n });\n if (!publicClient || !account) {\n throw new Error(\"usePollUserDelegates needs publicClient and account\");\n }\n\n // use promise all to better catch errors and have type safety\n const [delegate, currentVotes] = await Promise.all([\n publicClient.readContract({\n address: config.tokens.bgt,\n abi: bgtAbi,\n functionName: \"delegates\",\n args: [account],\n }),\n publicClient.readContract({\n address: config.tokens.bgt,\n abi: bgtAbi,\n functionName: \"getVotes\",\n args: [account],\n }),\n ]);\n\n return {\n delegate: delegate,\n currentVotes: formatEther(currentVotes),\n };\n },\n {\n ...options?.opts,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.SLOW,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","import useSWR, { type SWRResponse } from \"swr\";\nimport type { Address } from \"viem\";\n\nimport type { ProposalWithVotesFragment } from \"@berachain/graphql/governance\";\nimport { usePublicClient, useTransactionReceipt } from \"@berachain/wagmi/hooks\";\n\nimport { getProposalFromTx } from \"~/actions/governance/getProposalFromTx\";\n\nexport const useProposalFromTx = (\n txHash?: Address,\n): SWRResponse<ProposalWithVotesFragment | null> => {\n const { data: tx } = useTransactionReceipt({\n hash: txHash,\n });\n\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n tx && publicClient ? ([\"useProposalFromTx\", txHash] as const) : null;\n\n const swrResponse = useSWR(QUERY_KEY, async ([, txHash]) => {\n if (!tx) {\n throw new Error(\"Transaction not found\");\n }\n\n // This might happen for some render order issues.\n // Since tx is read by the external scope, it might be outdated.\n // Throwing an error here will cause the hook to re-run with the latest tx object.\n if (tx.transactionHash !== txHash) {\n throw new Error(\"Transaction hash mismatch\");\n }\n\n return getProposalFromTx({ tx, publicClient });\n });\n\n return swrResponse;\n};\n","import type { SWRResponse } from \"swr\";\nimport useSWRImmutable from \"swr/immutable\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { ProposalState } from \"~/types\";\nimport { governanceAbi } from \"../../abi/governance/governance\";\n\nconst ProposalStateMap: Record<ProposalState, string> = {\n [ProposalState.Pending]: \"pending\",\n [ProposalState.Active]: \"active\",\n [ProposalState.Canceled]: \"canceled\",\n [ProposalState.Defeated]: \"defeated\",\n [ProposalState.Succeeded]: \"succeeded\",\n [ProposalState.Queued]: \"queued\",\n [ProposalState.Expired]: \"expired\",\n [ProposalState.Executed]: \"executed\",\n};\n\nexport const useProposalState = ({\n proposalId,\n governorAddress,\n}: {\n proposalId: number | bigint | string | undefined;\n governorAddress: Address;\n}): SWRResponse<string> => {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n governorAddress && publicClient && proposalId\n ? ([\"useProposalState\", proposalId] as const)\n : null;\n\n return useSWRImmutable(QUERY_KEY, async ([, proposalId]) => {\n assertPublicClient(publicClient);\n\n const snapshot = (await publicClient.readContract({\n abi: governanceAbi,\n address: governorAddress,\n functionName: \"state\",\n args: [BigInt(proposalId)],\n })) as ProposalState;\n\n return ProposalStateMap[snapshot];\n });\n};\n","import useSWR, { type SWRResponse } from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { governanceTimelockAbi } from \"../../abi/governance/governanceTimelock\";\n\nconst TimelockOperationState = {\n 0: \"unset\",\n 1: \"waiting\",\n 2: \"ready\",\n 3: \"done\",\n} as const;\n\n/**\n * Fetches the state of a proposal timelock\n * @returns state of the proposal timelock (unset, waiting, ready, done)\n */\nexport const useProposalTimelockState = ({\n proposalTimelockId,\n timelockAddress,\n}: {\n proposalTimelockId: Address | undefined;\n timelockAddress: Address;\n}): SWRResponse<\n (typeof TimelockOperationState)[keyof typeof TimelockOperationState]\n> => {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n timelockAddress && publicClient && proposalTimelockId\n ? ([\n \"useProposalTimelockState\",\n proposalTimelockId,\n timelockAddress,\n ] as const)\n : null;\n\n return useSWR(\n QUERY_KEY,\n async ([, proposalTimelockId, timelockAddress]) => {\n assertPublicClient(publicClient);\n\n const snapshot = await publicClient.readContract({\n abi: governanceTimelockAbi,\n address: timelockAddress,\n functionName: \"getOperationState\",\n args: [proposalTimelockId],\n });\n\n return TimelockOperationState[\n snapshot as keyof typeof TimelockOperationState\n ];\n },\n {\n refreshInterval: POLLING.SLOW,\n },\n );\n};\n","import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getQuorum } from \"~/actions/governance/getQuorum\";\n\n/**\n * Queries the quorum for a given timestamp.\n *\n * @returns current quorum if timestamp is in the future.\n */\nexport function useQuorum(\n { at }: { at: number | string },\n {\n isEnabled = true,\n }: {\n isEnabled?: boolean;\n },\n) {\n const now = Math.floor(Date.now() / 1000);\n const publicClient = usePublicClient();\n const QUERY_KEY =\n isEnabled && publicClient\n ? ([\n \"useQuorum\",\n // Using Now because we cannot query quorum in the future, so no need to have different query keys.\n Number(at) > now ? \"now\" : at,\n ] as const)\n : null;\n\n const response = useSWR(QUERY_KEY, async ([, at]) => {\n if (at === \"now\") {\n return getQuorum({ publicClient });\n }\n return getQuorum({ at, publicClient });\n });\n\n return {\n ...response,\n data: response.data ? Number(response.data) : undefined,\n };\n}\n","import type { GetPublicClientReturnType } from \"@wagmi/core\";\nimport { formatEther, type PublicClient } from \"viem\";\n\nimport { governanceAbi } from \"~/abi/governance/governance\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\n/**\n * Queries the quorum for a given timestamp.\n *\n * @returns current quorum if timestamp is in the future.\n */\nexport async function getQuorum({\n at,\n publicClient,\n ...args\n}: {\n /**\n * Timestamp in seconds\n */\n at?: number | string;\n publicClient: PublicClient | GetPublicClientReturnType;\n} & BeraJS.BaseFunctionArgs): Promise<string> {\n const { config } = parseBaseArgs(args);\n assertPublicClient(publicClient);\n\n const quorum = await publicClient.readContract({\n address: config.governance.governor,\n abi: governanceAbi,\n functionName: \"quorum\",\n // Needs to be pending or you'll get a ERC5805FutureLookup error when reading current quorum\n // this is because now will always be in the future compared to the latest block\n blockTag: \"pending\",\n args: [BigInt(at ?? Math.floor(Date.now() / 1000))],\n });\n\n return formatEther(quorum);\n}\n","import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getGlobalCapLimit } from \"~/actions/honey/getGlobalCapLimit\";\nimport { useHoneyConfig } from \"~/contexts/HoneyConfigProvider\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType, Token } from \"~/types\";\nimport { usePythLatestPrices } from \"./usePythLatestPrices\";\n\nexport interface UseCappedGloballyResponse\n extends DefaultHookReturnType<boolean | undefined> {}\n\nexport const useCappedGlobally = (\n {\n asset,\n amount,\n isMint,\n isBasketModeEnabled,\n }: {\n asset: Token | undefined;\n amount: string | undefined;\n isMint: boolean;\n isBasketModeEnabled: boolean | undefined;\n },\n options?: DefaultHookOptions,\n): UseCappedGloballyResponse => {\n const publicClient = usePublicClient();\n const { priceFeedMap, flags } = useHoneyConfig();\n const { data: latestPrices } = usePythLatestPrices(\n {\n priceFeedMap:\n asset?.address && priceFeedMap\n ? { [asset.address]: priceFeedMap[asset.address] }\n : undefined,\n },\n {\n opts: {\n isEnabled: flags.isPythWrapperEnabled && !!asset?.address,\n },\n },\n );\n const QUERY_KEY =\n amount &&\n asset &&\n ((flags.isPythWrapperEnabled && !!latestPrices?.prices.length) ||\n !flags.isPythWrapperEnabled)\n ? ([\n \"useCappedGlobally\",\n amount,\n asset,\n latestPrices,\n flags.isPythWrapperEnabled,\n isBasketModeEnabled,\n ] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([\n _,\n amount,\n asset,\n latestPrices,\n isPythWrapperEnabled,\n isBasketModeEnabled,\n ]) => {\n if (isBasketModeEnabled) {\n return false;\n }\n assertPublicClient(publicClient);\n\n return await getGlobalCapLimit({\n client: publicClient,\n asset,\n amount: isMint ? amount : `-${amount}`,\n isMint,\n latestPrices,\n isPythWrapperEnabled,\n });\n },\n {\n ...options?.opts,\n refreshInterval: 0,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => void swrResponse.mutate(),\n };\n};\n","import useSWR, { type SWRResponse } from \"swr\";\n\nimport { getPythLatestPrices } from \"~/actions\";\nimport type { PythLatestUpdates } from \"~/actions/honey/getPythLatestPrices\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport type { PythPriceFeedMap } from \"~/types/honeySwap\";\n\n/**\n * Hook to fetch the latest Pyth price updates for specified pair addresses\n * @param {Object} params - The parameters object\n * @param {Address[] | undefined} params.pairMainAddress - Array of pair addresses to fetch price updates for\n * @returns {SWRResponse<PythLatestUpdates>} SWR response containing the latest Pyth price updates\n * @example\n * ```ts\n * const { data, error } = usePythLatestPrices({\n * pairMainAddress: [\"0x123...\", \"0x456...\"]\n * });\n * ```\n */\nexport function usePythLatestPrices(\n {\n priceFeedMap,\n }: {\n priceFeedMap: PythPriceFeedMap | undefined;\n },\n options?: DefaultHookOptions,\n): SWRResponse<PythLatestUpdates> {\n const priceFeedIds = priceFeedMap ? Object.values(priceFeedMap) : null;\n\n const QUERY_KEY =\n (options?.opts?.isEnabled ?? true) && priceFeedIds\n ? ([\"usePythLatestPrices\", priceFeedIds] as const)\n : null;\n\n const swrResponse = useSWR(QUERY_KEY, async ([_, priceFeeds]) => {\n const data = await getPythLatestPrices({ priceFeedId: priceFeeds });\n return data;\n });\n\n return swrResponse;\n}\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getRelativeCapLimit } from \"~/actions/honey/getRelativeCapLimit\";\nimport { useHoneyConfig } from \"~/contexts/HoneyConfigProvider\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport interface UseCappedRelativelyResponse\n extends DefaultHookReturnType<boolean | undefined> {}\n\nexport const useCappedRelatively = (\n {\n asset,\n amount,\n isMint,\n isBasketModeEnabled,\n }: {\n asset: Address | undefined;\n amount: string | undefined;\n isMint: boolean;\n isBasketModeEnabled: boolean | undefined;\n },\n options?: DefaultHookOptions,\n): UseCappedRelativelyResponse => {\n const publicClient = usePublicClient();\n const { collateralList, referenceCollateral } = useHoneyConfig();\n const QUERY_KEY =\n asset && amount\n ? ([\n \"useCappedRelatively\",\n asset,\n amount,\n collateralList,\n referenceCollateral,\n ] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([_, asset, amount, collaterals, referenceCollateral]) => {\n if (isBasketModeEnabled) {\n return false;\n }\n assertPublicClient(publicClient);\n\n if (!isMint) {\n const newAmount = `-${amount}`;\n\n if (referenceCollateral.address !== asset) {\n return false;\n }\n\n const isCapped = await Promise.all(\n collaterals.map((coll) =>\n getRelativeCapLimit({\n client: publicClient,\n asset: coll.address,\n amount: newAmount,\n isMint,\n referenceCollateral,\n }),\n ),\n );\n return isCapped.some((isCapped) => isCapped);\n }\n\n return await getRelativeCapLimit({\n client: publicClient,\n asset,\n amount,\n isMint,\n referenceCollateral,\n });\n },\n {\n refreshInterval: 0,\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => void swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getCollateralWeights } from \"~/actions/honey/getCollateralWeights\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType, Token } from \"~/types\";\n\nexport interface UseCollateralWeightsResponse\n extends DefaultHookReturnType<Record<Address, bigint> | undefined> {}\n\nexport const useCollateralWeights = (\n {\n collateralList,\n }: {\n collateralList: Token[] | undefined;\n },\n options?: DefaultHookOptions,\n): UseCollateralWeightsResponse => {\n const publicClient = usePublicClient();\n const QUERY_KEY =\n publicClient && collateralList\n ? ([\"useCollateralWeights\", collateralList] as const)\n : undefined;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([_, collateralList]) => {\n assertPublicClient(publicClient);\n\n return await getCollateralWeights({\n client: publicClient,\n collateralList,\n });\n },\n {\n ...options?.opts,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.NORMAL,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => void swrResponse.mutate(),\n };\n};\n","import { useMemo } from \"react\";\nimport BigNumber from \"bignumber.js\";\n\nimport type { GetHoneyVaultsBalanceResponse } from \"~/actions/honey/getHoneyVaultsBalance\";\nimport {\n type TokenWithOrder,\n useHoneyConfig,\n} from \"~/contexts/HoneyConfigProvider\";\nimport type { BalanceToken, Token } from \"~/types/dex\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { useCappedGlobally } from \"./useCappedGlobally\";\nimport { useCappedRelatively } from \"./useCappedRelatively\";\nimport { useHoneyBalances } from \"./useHoneyBalances\";\nimport type { IHoneySwapState } from \"./useHoneySwapState\";\nimport { useHoneyVaultsBalance } from \"./useHoneyVaultsBalance\";\nimport { useIsBadCollateralAsset } from \"./useIsBadCollateralAsset\";\n\n/**\n * Interface defining the state props that we need without the entire IHoneySwapState\n */\ntype HoneyAlertStateProps = Pick<\n IHoneySwapState,\n | \"actionType\"\n | \"fromAmount\"\n | \"toAmount\"\n | \"collaterals\"\n | \"isBasketModeEnabled\"\n>;\n\n/**\n * Interface defining the alert states returned by the useHoneyAlerts hook\n */\ninterface HoneyAlertsReturn {\n /** Indicates if the vault's liquidity is completely depleted (balance <= 1) */\n isLiquidityDepleted: boolean;\n isLiquidityDepletedCollaterals: Token[] | undefined;\n /** Indicates if the requested redeem amount exceeds available liquidity in the vault*/\n isRedeemMoreThanLiquidity: boolean;\n isRedeemMoreThanLiquidityCollaterals: Token[] | undefined;\n /** Indicates if the vault's liquidity is low (balance <= 1000) */\n isLowLiquidity: boolean;\n isLiquidityLowCollaterals: Token[] | undefined;\n /** Indicates if the selected collateral is flagged as bad (blacklisted or depegged) */\n isDepegged: boolean;\n /** Indicates if the selected collateral is blacklisted */\n isBlacklisted: boolean;\n /** Indicates if the input amount exceeds the global cap limit */\n isCappedGlobally: boolean | undefined;\n /** Indicates if the input amount exceeds the relative cap limit */\n isCappedRelatively: boolean | undefined;\n /** Indicates if the input amount exceeds the balance of the user */\n isExceedingBalance: boolean;\n}\n\n/**\n * Checks if the vault's liquidity is below a specified threshold\n * @param {Object} params - The parameters object\n * @param {number} params.lowerThan - The threshold value to compare against\n * @param {GetHoneyVaultsBalanceResponse[] | undefined} params.vaultsBalances - The current balance of the vaults\n * @param {HoneyAlertStateProps} params.state - The current state of the Honey swap operation\n * @returns {Object} Object containing the result of the check and the collaterals that are below the threshold\n * @returns {boolean} isLow - True if liquidity is below the threshold, false otherwise\n * @returns {Token[]} isLiquidityLowCollaterals - The collaterals that are below the threshold\n */\nconst getIsLiquidityLowerThan = ({\n lowerThan,\n vaultsBalances,\n state,\n collateralList,\n}: {\n lowerThan: number;\n state: HoneyAlertStateProps;\n vaultsBalances: GetHoneyVaultsBalanceResponse[] | undefined;\n collateralList: TokenWithOrder[];\n}): { isLow: boolean; isLiquidityLowCollaterals: Token[] } => {\n const isMint = state.actionType === \"mint\";\n if (!isMint && !state.isBasketModeEnabled) {\n const redeemedVaultBalance = vaultsBalances?.find(\n (vault) =>\n vault.address.toLowerCase() ===\n state.collaterals[0].address.toLowerCase(),\n );\n const isLow = new BigNumber(\n redeemedVaultBalance?.formattedBalance ?? \"0\",\n ).lte(lowerThan);\n // Get what collaterals are below the threshold to suggest others to the user\n const isLiquidityLowCollaterals = collateralList.filter((coll) => {\n const vaultBalance = vaultsBalances?.find(\n (vault) => vault.address.toLowerCase() === coll.address.toLowerCase(),\n );\n return new BigNumber(vaultBalance?.formattedBalance ?? \"0\").lte(\n lowerThan,\n );\n });\n return {\n isLow,\n isLiquidityLowCollaterals,\n };\n }\n return {\n isLow: false,\n isLiquidityLowCollaterals: [],\n };\n};\n\n/**\n * Checks if the requested redeem amount exceeds the available liquidity in the vault\n * @param {Object} params - The parameters object\n * @param {Record<`0x${string}`, BalanceToken> | undefined} params.honeyBalances - The current honey balances\n * @param {GetHoneyVaultsBalanceResponse | undefined} params.redeemedVaultBalance - The current vault balance\n * @param {HoneyAlertStateProps} params.state - The current state of the Honey swap operation\n * @returns {Object} Object containing the result of the check and the collaterals that exceed the liquidity\n * @returns {boolean} isMore - True if redeem amount exceeds liquidity, false otherwise\n * @returns {Token[]} isRedeemMoreThanLiquidityCollaterals - The collaterals that exceed the liquidity\n */\nconst getRedeemMoreThanLiquidity = ({\n vaultsBalances,\n redeemedVaultBalance,\n state,\n collateralList,\n}: {\n vaultsBalances: GetHoneyVaultsBalanceResponse[] | undefined;\n redeemedVaultBalance: GetHoneyVaultsBalanceResponse | undefined;\n collateralList: TokenWithOrder[];\n state: HoneyAlertStateProps;\n}) => {\n const isMint = state.actionType === \"mint\";\n if (!isMint && vaultsBalances && redeemedVaultBalance) {\n // if basket mode is enabled, check all collateral balances and amount to redeem\n const isRedeemMoreThanLiquidityCollaterals = collateralList.filter(\n (coll) => {\n const vaultBalance = vaultsBalances.find(\n (vault) => vault.address.toLowerCase() === coll.address.toLowerCase(),\n );\n const amountToRedeem = state.toAmount[state.collaterals.indexOf(coll)];\n return new BigNumber(vaultBalance?.formattedBalance ?? \"0\").lt(\n amountToRedeem ?? \"0\",\n );\n },\n );\n return {\n isMore: !!isRedeemMoreThanLiquidityCollaterals.find(\n (coll) =>\n coll.address.toLowerCase() ===\n state.collaterals[0].address.toLowerCase(),\n ),\n isRedeemMoreThanLiquidityCollaterals,\n };\n }\n return { isMore: false, isRedeemMoreThanLiquidityCollaterals: undefined };\n};\n\n/**\n * Checks if the input amount exceeds the user's balance\n * @param {Object} params - The parameters object\n * @param {HoneyAlertStateProps} params.state - The current state of the Honey swap operation\n * @param {Record<`0x${string}`, BalanceToken> | undefined} params.honeyBalances - The current honey balances\n * @returns {boolean} True if input amount exceeds balance, false otherwise\n */\nfunction getExceedingBalance({\n state,\n honeyBalances,\n ...args\n}: BeraJS.BaseFunctionArgs & {\n state: HoneyAlertStateProps;\n honeyBalances: Record<`0x${string}`, BalanceToken> | undefined;\n}): boolean {\n const { config } = parseBaseArgs(args);\n const isMint = state.actionType === \"mint\";\n if (!isMint && honeyBalances) {\n return new BigNumber(state.fromAmount[0]).gt(\n honeyBalances[config.honey.token]?.formattedBalance ?? \"0\",\n );\n }\n if (\n isMint &&\n honeyBalances &&\n state.isBasketModeEnabled !== undefined &&\n state.collaterals.length > 0\n ) {\n if (!state.isBasketModeEnabled) {\n return new BigNumber(\n honeyBalances[state.collaterals[0].address]?.formattedBalance,\n ).lt(state.fromAmount[0]);\n }\n return state.collaterals.some((coll, idx) => {\n const amount = state.fromAmount[idx];\n return new BigNumber(honeyBalances[coll.address]?.formattedBalance).lt(\n amount,\n );\n });\n }\n return false;\n}\n\n/**\n * Hook that monitors various alert conditions for Honey swap operations\n *\n * This hook tracks multiple states that could affect swap operations:\n * - Liquidity levels in vaults (depleted, low)\n * - Collateral quality (blacklisted, depegged)\n * - Cap limits for transactions (global, relative)\n * - Balance checks\n *\n * @param {Object} params - The parameters object\n * @param {HoneyAlertStateProps} params.state - The current state of the Honey swap operation\n * @returns {HoneyAlertsReturn} Object containing various alert states\n\n */\nexport const useHoneyAlerts = ({\n actionType,\n collaterals,\n fromAmount,\n toAmount,\n isBasketModeEnabled,\n}: HoneyAlertStateProps): HoneyAlertsReturn => {\n const state = {\n actionType,\n collaterals,\n fromAmount,\n toAmount,\n isBasketModeEnabled,\n };\n const isMint = actionType === \"mint\";\n\n // ===== BAD COLLATERAL =====\n // Check if selected collaterals are flagged as bad (blacklisted or depegged)\n const { data } = useIsBadCollateralAsset({\n collateral: collaterals[0],\n });\n const { collateralList } = useHoneyConfig();\n const { isBlacklisted, isDepegged } = data ?? {\n isBlacklisted: false,\n isDepegged: false,\n };\n\n // ===== CAP LIMITS =====\n // Check if the input amount exceeds the cap limit\n const { data: isCappedGlobally } = useCappedGlobally({\n asset: collaterals[0],\n amount: isMint ? fromAmount[0] : toAmount[0],\n isMint,\n isBasketModeEnabled,\n });\n const { data: isCappedRelatively } = useCappedRelatively({\n asset: collaterals[0]?.address,\n amount: isMint ? fromAmount[0] : toAmount[0],\n isMint,\n isBasketModeEnabled,\n });\n\n // ===== BALANCES =====\n const { data: honeyBalances } = useHoneyBalances();\n const { data: vaultsBalances } = useHoneyVaultsBalance();\n\n const redeemedCollateral = collaterals[0]?.address;\n const redeemedVaultBalance = vaultsBalances?.find(\n (vault) => vault.address.toLowerCase() === redeemedCollateral.toLowerCase(),\n );\n\n // ===== LIQUIDITY ALERTS =====\n const [isLiquidityDepleted, isLowLiquidity] = useMemo(() => {\n const isDepleted = getIsLiquidityLowerThan({\n lowerThan: 1,\n vaultsBalances,\n state,\n collateralList,\n });\n const isLow = getIsLiquidityLowerThan({\n lowerThan: 1000,\n vaultsBalances,\n state,\n collateralList,\n });\n return [isDepleted, isLow];\n }, [vaultsBalances, state]);\n\n const {\n isMore: isRedeemMoreThanLiquidity,\n isRedeemMoreThanLiquidityCollaterals,\n } = useMemo(() => {\n return getRedeemMoreThanLiquidity({\n vaultsBalances,\n redeemedVaultBalance,\n state,\n collateralList,\n });\n }, [vaultsBalances, redeemedVaultBalance, state, collateralList]);\n\n // ===== EXCEEDING BALANCE ALERTS =====\n const isExceedingBalance = useMemo(\n () =>\n getExceedingBalance({\n state,\n honeyBalances,\n }),\n [state, honeyBalances],\n );\n\n return {\n isLiquidityDepleted: isLiquidityDepleted.isLow,\n isLiquidityDepletedCollaterals:\n isLiquidityDepleted.isLiquidityLowCollaterals,\n isRedeemMoreThanLiquidity,\n isRedeemMoreThanLiquidityCollaterals,\n isLowLiquidity: isLowLiquidity.isLow,\n isLiquidityLowCollaterals: isLowLiquidity.isLiquidityLowCollaterals,\n isBlacklisted: state.isBasketModeEnabled ? false : isBlacklisted,\n isDepegged: state.isBasketModeEnabled ? false : isDepegged,\n isCappedGlobally,\n isCappedRelatively,\n isExceedingBalance,\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getWalletBalances } from \"~/actions/tokens/getWalletBalances\";\nimport { useHoneyConfig } from \"~/contexts/HoneyConfigProvider\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { BalanceToken } from \"~/types/dex\";\nimport type { DefaultHookReturnType } from \"~/types/global\";\nimport { getHoneyToken } from \"~/utils/tokens\";\n\n/**\n * Hook that fetches and maintains balances for HONEY token and collateral tokens\n *\n * This hook:\n * - Fetches balances for all collateral tokens and the HONEY token\n * - Updates balances at regular intervals (10s)\n * - Returns a map of token addresses to their respective balances\n * - Provides a refresh function to manually trigger balance updates\n *\n * The hook requires:\n * - A connected wallet account\n * - A public client\n * - BeraJS configuration\n * - A list of collateral tokens\n *\n * @returns {DefaultHookReturnType<Record<Address, BalanceToken>>} Object containing:\n * - data: Map of token addresses to their balances\n * - error: Any error that occurred during fetching\n * - isLoading: Loading state\n * - refresh: Function to manually refresh balances\n */\nexport const useHoneyBalances = (): DefaultHookReturnType<\n Record<Address, BalanceToken>\n> => {\n const publicClient = usePublicClient();\n const { address: account } = useBeraWallet();\n const { collateralList } = useHoneyConfig(); // needed\n\n const QUERY_KEY =\n account && collateralList && publicClient\n ? ([\"useHoneyBalances\", account, collateralList] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([_, account, collateralList]) => {\n assertPublicClient(publicClient);\n\n const tokenList = [...(collateralList ?? []), getHoneyToken({})];\n\n const tokenBalances = await getWalletBalances({\n account,\n tokenList,\n publicClient,\n });\n\n const balancesMap = tokenBalances?.reduce(\n (acc, balance) => {\n acc[balance.address] = balance;\n return acc;\n },\n {} as Record<Address, BalanceToken>,\n );\n\n return balancesMap;\n },\n {\n refreshInterval: POLLING.FAST,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport {\n type GetHoneyVaultsBalanceResponse,\n getHoneyVaultsBalance,\n} from \"~/actions/honey/getHoneyVaultsBalance\";\nimport { useHoneyConfig } from \"~/contexts/HoneyConfigProvider\";\nimport { POLLING } from \"~/enum\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\n\nexport const useHoneyVaultsBalance = (\n options?: DefaultHookOptions,\n): DefaultHookReturnType<GetHoneyVaultsBalanceResponse[]> => {\n const publicClient = usePublicClient();\n const { collateralList } = useHoneyConfig();\n const QUERY_KEY =\n collateralList && publicClient\n ? ([\"useHoneyVaultsBalance\", collateralList] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([_, collateralList]) => {\n assertPublicClient(publicClient);\n\n return await getHoneyVaultsBalance({\n client: publicClient,\n collateralList,\n });\n },\n { ...options?.opts, refreshInterval: POLLING.NORMAL },\n );\n\n return {\n ...swrResponse,\n refresh: () => void swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport {\n type IsBadCollateralResponse,\n isBadCollateralAsset,\n} from \"~/actions/honey/isBadCollateralAsset\";\nimport { useHoneyConfig } from \"~/contexts/HoneyConfigProvider\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType, Token } from \"~/types\";\nimport { usePythLatestPrices } from \"./usePythLatestPrices\";\n\nexport interface UseIsBadCollateralResponse\n extends DefaultHookReturnType<IsBadCollateralResponse | undefined> {}\n\nexport const useIsBadCollateralAsset = (\n { collateral }: { collateral: Token | undefined },\n options?: DefaultHookOptions,\n): UseIsBadCollateralResponse => {\n const publicClient = usePublicClient();\n const { priceFeedMap, flags } = useHoneyConfig();\n const { data: latestPrices } = usePythLatestPrices(\n {\n priceFeedMap: collateral?.address\n ? {\n [collateral.address]: priceFeedMap[collateral.address],\n }\n : undefined,\n },\n {\n opts: {\n isEnabled: flags.isPythWrapperEnabled && !!collateral?.address,\n },\n },\n );\n const QUERY_KEY =\n publicClient &&\n collateral &&\n ((flags.isPythWrapperEnabled && !!latestPrices?.prices.length) ||\n !flags.isPythWrapperEnabled)\n ? ([\n \"useIsBadCollateralAsset\",\n collateral,\n latestPrices,\n flags.isPythWrapperEnabled,\n ] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([_, collateral, latestPrices, isPythWrapperEnabled]) => {\n assertPublicClient(publicClient);\n\n return await isBadCollateralAsset({\n client: publicClient,\n collateral,\n latestPrices,\n isPythWrapperEnabled,\n });\n },\n {\n ...options?.opts,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.NORMAL,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => void swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\n\nimport { getChartData } from \"~/actions/honey/getChartData\";\n\nexport function useHoneyChartData({ days }: { days: number }) {\n const swrResponse = useSWR(\n [\"useHoneyChartData\", days] as const,\n async ([_, days]) => {\n return await getChartData({ days });\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","import BigNumber from \"bignumber.js\";\nimport useSWR from \"swr\";\n\nimport { getHoneyGlobalData } from \"../../actions/honey/getHoneyGlobalData\";\n\nexport function useHoneyGlobalData() {\n const response = useSWR([\"useHoneyGlobalData\"], () => getHoneyGlobalData());\n\n const dailyVolume = response.data?.honeySnapshots.reduce(\n (acc, curr) => new BigNumber(curr.totalVolume).plus(acc),\n new BigNumber(0),\n );\n\n return {\n ...response,\n data: {\n ...response.data,\n dailyVolume,\n },\n refresh: () => response.mutate(),\n };\n}\n","import { useEffect, useReducer } from \"react\";\nimport { formatUnits } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport {\n type TokenWithOrder,\n useHoneyConfig,\n} from \"~/contexts/HoneyConfigProvider\";\nimport { HoneySwapAction, type HoneySwapActions } from \"~/types/honeySwap\";\nimport { isToken } from \"~/utils/tokens\";\nimport { useIsBasketModeEnabled } from \"./useIsBasketModeEnabled\";\n\nexport interface IHoneySwapState {\n actionType: \"mint\" | \"redeem\";\n /**\n * List of current collaterals\n */\n collaterals: TokenWithOrder[];\n fromAmount: string[];\n toAmount: string[];\n isBasketModeEnabled: boolean | undefined;\n isTyping: boolean;\n isSubmitting: boolean;\n isLoading: boolean;\n}\n\nconst defaultState: IHoneySwapState = {\n actionType: \"mint\",\n collaterals: [],\n fromAmount: [],\n toAmount: [],\n isBasketModeEnabled: false,\n isTyping: false,\n isSubmitting: false,\n isLoading: false,\n};\n\nexport function reducer(\n state: IHoneySwapState,\n action: HoneySwapActions,\n): IHoneySwapState {\n switch (action.type) {\n case HoneySwapAction.RESET_AMOUNTS:\n return {\n ...state,\n fromAmount: [],\n toAmount: [],\n };\n case HoneySwapAction.ACTION_TYPE_CHANGE:\n // updates the action type and resets the amounts\n return reducer(\n {\n ...state,\n actionType: action.value,\n },\n { type: HoneySwapAction.RESET_AMOUNTS },\n );\n case HoneySwapAction.COLLATERALS_CHANGE:\n return {\n ...state,\n collaterals: action.value,\n fromAmount: [],\n toAmount: [],\n };\n case HoneySwapAction.FROM_AMOUNT_CHANGE: {\n const newFromAmount = state.fromAmount;\n newFromAmount[action.index] = action.value;\n return {\n ...state,\n fromAmount: newFromAmount,\n };\n }\n case HoneySwapAction.TO_AMOUNT_CHANGE: {\n const newToAmount = state.toAmount;\n newToAmount[action.index] = action.value;\n return {\n ...state,\n toAmount: newToAmount,\n };\n }\n case HoneySwapAction.PREVIEW_CHANGE: {\n const preview = action.value;\n const isMint = state.actionType === \"mint\";\n /**\n * Changed asset ---\n * Do not change the amount of the asset used for the preview\n * There currently is an issue in the contracts where the preview is returning\n * a different value if is made from the collaterals rather than honey, only in redeem mode\n * */\n\n // if the token is the one changed do not replace it with the preview value,\n // if its mint then use fromAmount or toAmount accordingly,\n // if the preview value is \"0\" then replace it with \"\" (empty string)\n const collateralsAmount = state.collaterals.map((coll, idx) => {\n // The index in toAmount & fromAmount is based on the contract ordered collateral addresses\n // const idx = coll.order;\n if (action.changedAsset === coll.address) {\n if (isMint) {\n return state.fromAmount[idx];\n }\n return state.toAmount[idx];\n }\n if (preview.collaterals[coll.address]) {\n return formatUnits(preview.collaterals[coll.address], coll.decimals);\n }\n return state.isBasketModeEnabled ? \"0\" : \"\";\n });\n\n const honey = isToken(action.changedAsset, \"HONEY\", {\n chainId: defaultChainId,\n })\n ? isMint\n ? state.toAmount[0]\n : state.fromAmount[0]\n : !preview.honey\n ? state.isBasketModeEnabled\n ? \"0\"\n : \"\"\n : formatUnits(preview.honey, 18);\n\n return {\n ...state,\n fromAmount: isMint ? collateralsAmount : [honey],\n toAmount: isMint ? [honey] : collateralsAmount,\n };\n }\n case HoneySwapAction.IS_BASKET_MODE_ENABLED_CHANGE:\n return {\n ...state,\n isBasketModeEnabled: action.value,\n fromAmount: [],\n toAmount: [],\n };\n case HoneySwapAction.IS_TYPING_CHANGE:\n return {\n ...state,\n isTyping: action.value,\n };\n case HoneySwapAction.IS_SUBMITTING_CHANGE:\n return {\n ...state,\n isSubmitting: action.value,\n };\n case HoneySwapAction.IS_LOADING_CHANGE:\n return {\n ...state,\n isLoading: action.value,\n };\n default:\n throw new Error(`Unknown action type: ${action}`);\n }\n}\n\nexport const useHoneySwapState = () => {\n const { collateralList } = useHoneyConfig();\n const [state, dispatch] = useReducer(\n reducer,\n defaultState,\n (initialState) => {\n const collaterals = collateralList;\n return {\n ...initialState,\n collaterals,\n } satisfies IHoneySwapState;\n },\n );\n\n const { data: isBasketModeEnabled } = useIsBasketModeEnabled({\n state,\n });\n\n /**\n * This is for timed updates\n * Ex: BasketMode check\n * */\n useEffect(() => {\n // UPDATE FOR BASKET MODE CHANGE\n if (\n isBasketModeEnabled !== undefined &&\n state.isBasketModeEnabled !== isBasketModeEnabled\n ) {\n // start loading\n dispatch({\n type: HoneySwapAction.IS_LOADING_CHANGE,\n value: true,\n });\n\n dispatch({\n type: HoneySwapAction.IS_BASKET_MODE_ENABLED_CHANGE,\n value: isBasketModeEnabled,\n });\n\n dispatch({\n type: HoneySwapAction.IS_LOADING_CHANGE,\n value: false,\n });\n }\n }, [isBasketModeEnabled]);\n\n return { state, dispatch };\n};\n","import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { isBasketModeEnabled } from \"~/actions/honey/isBasketModeEnabled\";\nimport { useHoneyConfig } from \"~/contexts/HoneyConfigProvider\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\nimport type { IHoneySwapState } from \"./useHoneySwapState\";\nimport { usePythLatestPrices } from \"./usePythLatestPrices\";\n\nexport function useIsBasketModeEnabled(\n { state }: { state: IHoneySwapState },\n options?: DefaultHookOptions,\n): DefaultHookReturnType<boolean | undefined> {\n const publicClient = usePublicClient();\n const { priceFeedMap, flags, collateralList } = useHoneyConfig();\n const { data: latestPrices } = usePythLatestPrices(\n {\n priceFeedMap,\n },\n {\n opts: {\n isEnabled: flags.isPythWrapperEnabled && !!collateralList.length,\n },\n },\n );\n const isMint = state.actionType === \"mint\";\n const QUERY_KEY =\n publicClient &&\n state &&\n collateralList.length > 0 &&\n ((flags.isPythWrapperEnabled && !!latestPrices?.prices.length) ||\n !flags.isPythWrapperEnabled)\n ? ([\n \"useIsBasketModeEnabled\",\n isMint,\n latestPrices,\n flags.isPythWrapperEnabled,\n collateralList,\n ] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([_, isMint, latestPrices, isPythWrapperEnabled, collateralList]) => {\n assertPublicClient(publicClient);\n\n const isActive = await isBasketModeEnabled({\n client: publicClient,\n isMint,\n collateralList,\n latestPrices,\n isPythWrapperEnabled,\n });\n\n return isActive;\n },\n {\n ...options?.opts,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.FAST,\n },\n );\n return {\n ...swrResponse,\n data: swrResponse.data,\n refresh: () => void swrResponse.mutate(),\n };\n}\n","import useSWRImmutable from \"swr/immutable\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getPythUpdateFee } from \"~/actions/pyth/getUpdateFee\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { getPythDefaultUpdateFee } from \"~/utils/pythHoneyUtils\";\n\nexport const usePythUpdateFee = (\n {\n pythPriceFeedCalldata,\n tokenListLength,\n }: {\n pythPriceFeedCalldata: Address[] | undefined;\n tokenListLength: number;\n },\n options?: DefaultHookOptions,\n) => {\n const publicClient = usePublicClient();\n const QUERY_KEY =\n (options?.opts?.isEnabled ?? true) &&\n pythPriceFeedCalldata &&\n pythPriceFeedCalldata.length > 0\n ? ([\"usePythUpdateFee\", pythPriceFeedCalldata] as const)\n : null;\n const { data = getPythDefaultUpdateFee(tokenListLength), isLoading } =\n useSWRImmutable(QUERY_KEY, async ([_, pythPriceFeedCalldata]) => {\n assertPublicClient(publicClient);\n\n return await getPythUpdateFee({\n client: publicClient,\n priceFeedId: pythPriceFeedCalldata,\n });\n });\n\n return {\n QUERY_KEY,\n data,\n isLoading,\n };\n};\n","import { useMemo } from \"react\";\n\nimport {\n type GetBgtAprSimulationArgs,\n type GetBgtAprSimulationResult,\n getBgtAprSimulation,\n} from \"~/actions/pol/getBgtAprSimulation\";\n\nexport function useBgtAprSimulation(args: GetBgtAprSimulationArgs | undefined):\n | GetBgtAprSimulationResult\n /**\n * Returns undefined if still loading\n */\n | undefined {\n return useMemo(() => {\n if (!args) {\n return undefined;\n }\n\n return getBgtAprSimulation(args);\n }, [args]);\n}\n","import useSWR from \"swr\";\nimport { formatEther } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { bgtAbi } from \"~/abi/pol/bgt\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\n// TODO: REFACTOR ON REDEPLOY\nexport const useBgtUnstakedBalance = (\n options?: DefaultHookOptions,\n): DefaultHookReturnType<string | undefined> => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n const QUERY_KEY =\n account && publicClient\n ? ([\"useBgtUnstakedBalance\", account] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, account]) => {\n assertPublicClient(publicClient);\n\n const { config } = parseBaseArgs({\n chainId: publicClient.chain.id,\n });\n\n const bgtBalance = await publicClient.readContract({\n address: config.tokens.bgt,\n abi: bgtAbi,\n functionName: \"unboostedBalanceOf\",\n args: [account],\n });\n return formatEther(bgtBalance);\n },\n {\n ...options,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.NORMAL,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\nimport { formatUnits } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getUserVaultsReward } from \"~/actions/pol/getUserVaultsReward\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport const useClaimableFees = () => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n const QUERY_KEY =\n account && publicClient ? ([\"useClaimableFees\", account] as const) : null;\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, account]) => {\n assertPublicClient(publicClient);\n const { config } = parseBaseArgs({\n chainId: publicClient.chain.id,\n });\n const vaultReward = await getUserVaultsReward({\n account,\n vaultAddress: config.pol.staker,\n publicClient,\n });\n return formatUnits(vaultReward, 18);\n },\n {\n refreshInterval: POLLING.SLOW * 2,\n },\n );\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","import useSWR from \"swr\";\n\nimport {\n GetStakeBeraVaultEarningsByOwner,\n type GetStakeBeraVaultEarningsByOwnerQuery,\n type GetStakeBeraVaultEarningsByOwnerQueryVariables,\n} from \"@berachain/graphql/pol/api\";\nimport { useBeraWallet } from \"@berachain/wagmi/hooks\";\n\nimport { getApolloClient } from \"~/actions/clients/getApolloClient\";\nimport { POLLING } from \"~/enum/polling\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n TokenWithMetadata,\n} from \"~/types\";\n\ntype UseEarnedStakedBeraVaultArgs = {\n /**\n * The token that the user has staked\n */\n receiptToken: TokenWithMetadata;\n};\nexport function useEarnedStakedBeraVault(\n { receiptToken }: UseEarnedStakedBeraVaultArgs,\n opt?: DefaultHookOptions,\n): DefaultHookReturnType<string> {\n const { address: account } = useBeraWallet();\n\n const QUERY_KEY =\n receiptToken.address && account\n ? ([\"useEarnedStakedBeraVault\", receiptToken.address, account] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([_, , account]) => {\n const bexApiGraphqlClient = getApolloClient(\"api\", {});\n const response = await bexApiGraphqlClient.query<\n GetStakeBeraVaultEarningsByOwnerQuery,\n GetStakeBeraVaultEarningsByOwnerQueryVariables\n >({\n query: GetStakeBeraVaultEarningsByOwner,\n variables: {\n owner: account,\n },\n });\n return response.data?.polGetStakeBeraVaultEarningsByOwner?.earnings;\n },\n {\n refreshInterval: POLLING.SLOW,\n ...opt?.opts,\n },\n );\n return {\n ...swrResponse,\n refresh: swrResponse.mutate,\n };\n}\n","import type { GqlRewardVaultDynamicData } from \"@berachain/graphql/dex/api\";\nimport {\n type GqlRewardVaultFilter,\n GqlRewardVaultOrderBy,\n GqlRewardVaultOrderDirection,\n} from \"@berachain/graphql/pol/api\";\n\nimport { useRewardVaults } from \"./useRewardVaults\";\n\n/**\n * Hook that fetches and returns the highest APR (Annual Percentage Rate) from reward vaults.\n *\n * @param {`0x${string}`[]} [params.filteringVaults=[]] - Optional array of vault addresses to filter by\n *\n * @returns {Object} An object containing:\n * - highestApr: The highest APR value from the reward vaults\n * - refresh: Function to manually refresh the data\n * - ...swrResponse: All properties from the underlying SWR response\n *\n * @example\n * const { highestApr } = useHighestVaultsAPR({\n * filteringVaults: ['0x123...', '0x456...']\n * });\n */\nexport const useHighestVaultsAPR = (\n where: GqlRewardVaultFilter = {},\n { isEnabled = true }: { isEnabled?: boolean } = {},\n): {\n highestApr: GqlRewardVaultDynamicData[\"apr\"] | undefined;\n isLoading: boolean;\n refresh: () => void;\n} => {\n const swrResponse = useRewardVaults(\n {\n filter: {\n orderBy: GqlRewardVaultOrderBy.Apr,\n orderDirection: GqlRewardVaultOrderDirection.Desc,\n pageSize: 1,\n where,\n },\n },\n {\n opts: {\n refreshInterval: 0,\n revalidateOnFocus: false,\n refreshWhenOffline: false,\n isEnabled,\n },\n },\n );\n\n return {\n isLoading: swrResponse.isLoading,\n highestApr: swrResponse.data?.gaugeList[0].dynamicData?.apr,\n refresh: swrResponse.mutate,\n };\n};\n","import useSWR from \"swr\";\n\nimport type { GetVaultsQueryVariables } from \"@berachain/graphql/pol/api\";\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getRewardVaults } from \"~/actions/pol/getRewardVaults\";\nimport type { DefaultHookOptions } from \"~/types\";\n\nexport const useRewardVaultsQueryKey = (\n filter?: GetVaultsQueryVariables,\n onChainIncentives = false,\n) => {\n return [\"useRewardVaults\", filter, onChainIncentives] as const;\n};\n\nexport const useRewardVaults = (\n args: {\n filter?: GetVaultsQueryVariables;\n onChainIncentives?: boolean;\n },\n options?: DefaultHookOptions,\n) => {\n const QUERY_KEY = useRewardVaultsQueryKey(\n args.filter,\n args.onChainIncentives,\n );\n const publicClient = usePublicClient();\n const swrResponse = useSWR(\n (options?.opts?.isEnabled ?? true) ? QUERY_KEY : null,\n async ([, filter, onChainIncentives]) => {\n return await getRewardVaults({\n filter: filter,\n publicClient: onChainIncentives ? publicClient : undefined,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: swrResponse.mutate,\n };\n};\n","import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { type GlobalData, getGlobalData } from \"~/actions/pol/getGlobalData\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport const usePollGlobalData = (\n options?: DefaultHookOptions,\n): DefaultHookReturnType<GlobalData> => {\n const publicClient = usePublicClient();\n\n const swrResponse = useSWR<GlobalData>(\n publicClient ? \"usePollGlobalData\" : null,\n async () => {\n assertPublicClient(publicClient);\n\n return getGlobalData(publicClient);\n },\n {\n revalidateOnFocus: false,\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: swrResponse.mutate,\n };\n};\n","import useSWRImmutable from \"swr/immutable\";\n\nimport { type GetMarkets, getMarkets } from \"~/actions/pol/getMarkets\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport interface UsePollMarketsResponse\n extends DefaultHookReturnType<GetMarkets> {}\n\nexport const usePollMarketsQueryKey = () => {\n return \"usePollMarkets\";\n};\n\nexport const usePollMarkets = (\n options?: DefaultHookOptions,\n): UsePollMarketsResponse => {\n const QUERY_KEY = usePollMarketsQueryKey();\n const swrResponse = useSWRImmutable<GetMarkets, any, typeof QUERY_KEY>(\n QUERY_KEY,\n async () => {\n const res = await getMarkets();\n return res;\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWRImmutable from \"swr/immutable\";\nimport { type Address, isAddress } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport {\n getSWBeraWithdrawal,\n type StakedBeraWithdrawal,\n} from \"~/actions/pol/getSWBeraWithdrawal\";\nimport { POLLING } from \"~/enum\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types\";\n\nexport function useQueuedBeraUnlock(\n {\n receiptTokenAddress,\n account,\n version,\n }: {\n receiptTokenAddress?: Address | string;\n account?: Address | string;\n version: \"V1\" | \"V2\";\n },\n options?: DefaultHookOptions,\n) {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n receiptTokenAddress &&\n isAddress(receiptTokenAddress) &&\n account &&\n publicClient &&\n isAddress(account) &&\n version\n ? ([\n \"useQueuedBeraUnlock\",\n receiptTokenAddress,\n account,\n version,\n ] as const)\n : null;\n\n const swrResponse = useSWRImmutable<\n StakedBeraWithdrawal[],\n any,\n typeof QUERY_KEY\n >(\n QUERY_KEY,\n async ([, receiptTokenAddress, account, version]) => {\n assertPublicClient(publicClient);\n\n const unlock = await getSWBeraWithdrawal(\n receiptTokenAddress,\n account,\n publicClient,\n version,\n );\n return unlock;\n },\n {\n refreshInterval: POLLING.FAST,\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","import useSWR from \"swr\";\nimport { type Address, isAddress } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getRewardTokenToBeraRate } from \"~/actions/pol/getRewardTokenToBeraRate\";\nimport { assertPublicClient, InvalidArgumentError } from \"~/errors\";\nimport type { DefaultHookOptions } from \"~/types\";\n\nexport const useRewardTokenToBeraRate = (\n {\n address,\n }: {\n address: Address | undefined;\n },\n opt?: DefaultHookOptions,\n) => {\n const QUERY_KEY = address\n ? ([\"useRewardTokenToBeraRate\", address] as const)\n : null;\n const publicClient = usePublicClient();\n\n return useSWR(\n QUERY_KEY,\n async ([_, address]) => {\n if (!address || !isAddress(address)) {\n throw new InvalidArgumentError({\n property: \"address\",\n value: address,\n expected: \"Address\",\n });\n }\n\n assertPublicClient(publicClient);\n\n return getRewardTokenToBeraRate({\n address: address as `0x${string}`,\n publicClient,\n });\n },\n {\n ...opt?.opts,\n },\n );\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport type { ApiVaultFragment } from \"@berachain/graphql/pol/api\";\n\nimport { getRewardVault } from \"~/actions/pol/getRewardVault\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\nimport { useOnChainRewardVault } from \"./useOnChainRewardVault\";\n\nexport interface UseRewardVaultResponse\n extends DefaultHookReturnType<ApiVaultFragment> {}\n\nexport const useRewardVaultQueryKey = (address: Address | undefined) =>\n address\n ? ([\"useRewardVault\", address.toLowerCase() as Address] as const)\n : null;\n\nexport const useRewardVault = (\n id: Address | undefined,\n options?: DefaultHookOptions,\n): UseRewardVaultResponse => {\n const QUERY_KEY = useRewardVaultQueryKey(id);\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([_, id]) => getRewardVault({ address: id }),\n {\n ...options?.opts,\n },\n );\n\n const isOnChainEnabled =\n options?.opts?.isEnabled ??\n ((!!swrResponse.error || !swrResponse.isLoading) && !swrResponse.data);\n\n const onChainRewardVault = useOnChainRewardVault(\n { address: id },\n { opts: { ...options?.opts, isEnabled: isOnChainEnabled } },\n );\n\n return {\n data: onChainRewardVault.data ?? swrResponse.data,\n error: onChainRewardVault.error ?? swrResponse.error,\n isLoading: onChainRewardVault.isLoading || swrResponse.isLoading,\n isValidating: onChainRewardVault.isValidating ?? swrResponse.isValidating,\n refresh: () => {\n swrResponse.mutate();\n onChainRewardVault.mutate();\n },\n };\n};\n","import useSWR from \"swr\";\nimport { type Address, erc20Abi, formatUnits, isAddress } from \"viem\";\n\nimport type { ApiVaultFragment } from \"@berachain/graphql/pol/api\";\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { beraChefAbi } from \"~/abi/pol/beraChef\";\nimport { getRewardVaultIncentives } from \"~/actions/pol/getRewardVaultIncentives\";\nimport { getRewardVaultStakingToken } from \"~/actions/pol/getRewardVaultStakingToken\";\nimport { getStakingTokenInformation } from \"~/actions/pol/getStakingTokenInformation\";\nimport { getTokenInformation } from \"~/actions/tokens/getTokenInformation\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport const useOnChainRewardVaultQueryKey = (address: Address | undefined) =>\n address && isAddress(address)\n ? ([\"onChainRewardVault\", address.toLowerCase() as Address] as const)\n : null;\n\nexport const useOnChainRewardVault = (\n {\n address,\n }: {\n address: Address | undefined;\n },\n opt: DefaultHookOptions,\n) => {\n const publicClient = usePublicClient();\n const isEnabled = opt.opts?.isEnabled ?? true;\n\n const QUERY_KEY = useOnChainRewardVaultQueryKey(address);\n\n return useSWR<\n ApiVaultFragment,\n unknown,\n ReturnType<typeof useOnChainRewardVaultQueryKey>\n >(isEnabled && publicClient ? QUERY_KEY : null, async ([, address]) => {\n assertPublicClient(publicClient);\n const { config } = parseBaseArgs({\n chainId: publicClient.chain.id,\n });\n\n const stakingTokenAddress = await getRewardVaultStakingToken({\n address,\n publicClient: publicClient,\n });\n\n const [incentives, isWhitelisted, stakingTokenAmount] = await Promise.all([\n getRewardVaultIncentives({\n address,\n stakingToken: stakingTokenAddress,\n publicClient,\n }),\n publicClient.readContract({\n address: config.pol.beraChef,\n abi: beraChefAbi,\n functionName: \"isWhitelistedVault\",\n args: [address],\n }),\n publicClient.readContract({\n address: stakingTokenAddress,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [address],\n }),\n ]);\n\n const [stakingToken, incentiveTokens] = await Promise.all([\n getStakingTokenInformation({\n address: stakingTokenAddress,\n publicClient: publicClient,\n }),\n Promise.all(\n incentives.map((add) =>\n getTokenInformation({\n address: add.token,\n publicClient: publicClient,\n }),\n ),\n ),\n ]);\n\n if (!stakingToken) {\n throw new Error(\"Staking token not found\");\n }\n\n return {\n id: address,\n address,\n vaultAddress: address,\n stakingToken: {\n address: stakingTokenAddress,\n name: stakingToken.name ?? \"\",\n symbol: stakingToken.symbol ?? \"\",\n decimals: stakingToken.decimals ?? 0,\n },\n stakingTokenAmount: formatUnits(\n stakingTokenAmount,\n stakingToken.decimals ?? 18,\n ),\n isVaultWhitelisted: isWhitelisted,\n activeIncentives: incentives.map((incentive, idx) => ({\n active: !!incentive.remainingAmount,\n remainingAmount: incentive.remainingAmount,\n remainingAmountUsd: \"0\",\n incentiveRate: incentive.incentiveRate,\n incentiveRateUsd: \"0\",\n tokenAddress: incentive.token,\n token: incentiveTokens[idx]!,\n })),\n } satisfies ApiVaultFragment;\n });\n};\n","import type { GetPublicClientReturnType } from \"@wagmi/core\";\nimport { type Address, erc20Abi, formatUnits } from \"viem\";\n\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { Token } from \"~/types\";\n\nexport interface GetStakingTokenInformation {\n address: Address;\n publicClient: GetPublicClientReturnType;\n}\n\nexport type GetStakingTokenInformationResponse = Partial<Token> | undefined;\n\nexport async function getStakingTokenInformation({\n address,\n publicClient,\n}: GetStakingTokenInformation): Promise<GetStakingTokenInformationResponse> {\n assertPublicClient(publicClient);\n\n const [decimals, name, symbol, totalSupply] = await publicClient.multicall({\n contracts: [\n {\n address,\n abi: erc20Abi,\n functionName: \"decimals\",\n },\n {\n address: address,\n abi: erc20Abi,\n functionName: \"name\",\n },\n {\n address: address,\n abi: erc20Abi,\n functionName: \"symbol\",\n },\n {\n address: address,\n abi: erc20Abi,\n functionName: \"totalSupply\",\n },\n ],\n allowFailure: true,\n });\n\n const token = {\n address: address,\n decimals: decimals.result,\n name: name.result,\n symbol: symbol.result,\n totalSupply:\n totalSupply.result !== undefined\n ? decimals.status === \"success\"\n ? formatUnits(totalSupply.result, decimals.result)\n : totalSupply.result.toString()\n : undefined,\n };\n\n return token;\n}\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getRewardVaultIncentives } from \"~/actions/pol/getRewardVaultIncentives\";\nimport { assertPublicClient } from \"~/errors/assert\";\n\nexport function useRewardVaultIncentives({\n address,\n stakingToken,\n}: {\n address: Address | undefined;\n stakingToken: Address | undefined;\n}) {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n publicClient && address && stakingToken\n ? ([\"useRewardVaultIncentives\", address, stakingToken] as const)\n : null;\n\n const swrResponse = useSWR(QUERY_KEY, async ([, address, stakingToken]) => {\n assertPublicClient(publicClient);\n\n return await getRewardVaultIncentives({\n address,\n stakingToken,\n publicClient,\n });\n });\n\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n}\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getRewardVaultRewards } from \"~/actions/pol/getRewardVaultRewards\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\n\nexport const useRewardVaultRewards = (\n address: Address,\n options?: DefaultHookOptions,\n) => {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n publicClient && address\n ? ([\"useRewardVaultRewards\", address] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, address]) => {\n assertPublicClient(publicClient);\n\n return await getRewardVaultRewards(address, publicClient);\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","import useSWR from \"swr\";\n\nimport type { GetSWberaVaultSnapshotsQuery } from \"@berachain/graphql/pol/api\";\n\nimport {\n type GetStakedBeraSnapshotsArgs,\n getStakedBeraSnapshots,\n} from \"~/actions/pol/getStakedBeraSnapshots\";\nimport type { DefaultHookReturnType } from \"~/types/global\";\n\nexport const useStakedBeraSnapshots = ({\n range,\n}: GetStakedBeraSnapshotsArgs): DefaultHookReturnType<\n GetSWberaVaultSnapshotsQuery[\"polGetSWberaVaultSnapshots\"]\n> => {\n const QUERY_KEY = range ? ([\"useStakedBeraSnapshots\", range] as const) : null;\n const swrResponse = useSWR(QUERY_KEY, ([, range]) =>\n getStakedBeraSnapshots({\n range,\n }),\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getUserVaultInfo } from \"~/actions/\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\nimport type { UserVaultInfo } from \"~/types/pol\";\n\nexport const useUserVaultInfo = (\n args: {\n vaultAddress: Address | undefined;\n },\n options?: DefaultHookOptions,\n): DefaultHookReturnType<UserVaultInfo> => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n const QUERY_KEY =\n account && publicClient && args.vaultAddress\n ? ([\"useUserVaultInfo\", account, args.vaultAddress] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, account, vaultAddress]) => {\n assertPublicClient(publicClient);\n\n return getUserVaultInfo({\n account,\n vaultAddress,\n publicClient,\n });\n },\n {\n ...options,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.NORMAL,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport {\n type GetUserVaultsResponse,\n getUserVaults,\n} from \"~/actions/pol/getUserVaults\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\n\nexport const useUserVaults = (\n options?: DefaultHookOptions,\n): DefaultHookReturnType<GetUserVaultsResponse> => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n const QUERY_KEY =\n account && publicClient ? ([\"useUserVaults\", account] as const) : null;\n const swrResponse = useSWR<GetUserVaultsResponse, unknown, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([, account]) => {\n assertPublicClient(publicClient);\n\n return await getUserVaults({\n account,\n publicClient,\n });\n },\n {\n ...options,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.NORMAL,\n keepPreviousData: true,\n },\n );\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getRewardVaultStakingToken } from \"~/actions/pol/getRewardVaultStakingToken\";\nimport { assertPublicClient } from \"~/errors/assert\";\n\nexport interface RewardVault {\n stakeToken: Address;\n address: Address;\n}\nexport const useVaultAddress = (vaultAddress: Address) => {\n const publicClient = usePublicClient();\n const QUERY_KEY =\n vaultAddress && publicClient\n ? ([\"useVaultAddress\", vaultAddress] as const)\n : null;\n\n return useSWR(QUERY_KEY, async ([, vaultAddress]) => {\n assertPublicClient(publicClient);\n\n const [stakeToken] = await Promise.all([\n getRewardVaultStakingToken({\n address: vaultAddress,\n publicClient: publicClient,\n }),\n ]);\n return { stakeToken, address: vaultAddress };\n });\n};\n","import useSWR from \"swr\";\n\nimport type { GetVaultHistoryQuery } from \"@berachain/graphql/pol/api\";\n\nimport {\n type GetVaultHistoryArgs,\n getVaultHistory,\n} from \"~/actions/pol/getVaultHistory\";\nimport type { DefaultHookReturnType } from \"~/types/global\";\n\nexport const useVaultHistory = ({\n vault,\n range,\n resolution,\n}: GetVaultHistoryArgs): DefaultHookReturnType<\n GetVaultHistoryQuery[\"polGetRewardVaultSnapshots\"]\n> => {\n const QUERY_KEY = vault\n ? ([\"useVaultHistory\", vault, range, resolution] as const)\n : null;\n const swrResponse = useSWR(QUERY_KEY, ([, vault, range, resolution]) =>\n getVaultHistory({ vault, range, resolution }),\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport type { ApiValidatorFragment } from \"@berachain/graphql/pol/api\";\n\nimport { getVaultValidators } from \"~/actions/pol/getVaultValidators\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport interface UsePollValidatorInfoResponse\n extends DefaultHookReturnType<ApiValidatorFragment[] | undefined> {}\n\nexport const useVaultValidators = (\n id: Address,\n options?: DefaultHookOptions,\n): UsePollValidatorInfoResponse => {\n const QUERY_KEY = id ? ([\"useVaultValidators\", id] as const) : null;\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, address]) => {\n return await getVaultValidators({\n address,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import { zeroAddress } from \"viem\";\n\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { useTokenCurrentPrice } from \"./useTokenCurrentPrice\";\n\n/**\n * Shorthand for `useTokenCurrentPrice` with the Bera token address.\n * @returns\n */\nexport function useBeraCurrentPrice(opts?: DefaultHookOptions) {\n return useTokenCurrentPrice({ address: zeroAddress }, opts);\n}\n","import type { DefaultHookReturnType, TokenPriceInfo } from \"~/types\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { useTokenCurrentPrices } from \"./useTokenCurrentPrices\";\n\nexport function useTokenCurrentPrice(\n { address }: { address: `0x${string}` | undefined },\n options?: DefaultHookOptions,\n): DefaultHookReturnType<TokenPriceInfo> {\n const swrResponse = useTokenCurrentPrices(\n {\n addressIn: address ? [address] : undefined,\n },\n options,\n );\n return {\n ...swrResponse,\n data: address ? swrResponse.data?.[address.toLowerCase()] : undefined,\n };\n}\n","import { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getWalletBalances } from \"~/actions/tokens/getWalletBalances\";\nimport { POLLING } from \"~/enum/polling\";\nimport { useTokens } from \"~/hooks/tokens/useTokens\";\nimport type {\n BalanceToken,\n DefaultHookOptions,\n DefaultHookReturnType,\n Token,\n} from \"~/types\";\n\nexport type UsePollWalletBalancesArgs = {\n /**\n * If provided, the tokens will be used instead of the default token list.\n */\n tokens?: Token[];\n walletAddress?: Address;\n};\nexport interface UsePollBalancesResponse\n extends DefaultHookReturnType<BalanceToken[] | undefined> {}\n\nexport function usePollWalletBalances(\n args?: UsePollWalletBalancesArgs,\n options?: DefaultHookOptions,\n): UsePollBalancesResponse {\n const publicClient = usePublicClient();\n\n const { address: connectedAccount } = useBeraWallet();\n\n const { tokenList } = useTokens();\n\n const wallet = args?.walletAddress ?? connectedAccount;\n\n const tokens = useMemo(() => {\n return new Map<string, Token>(\n (args?.tokens ?? tokenList)?.map((t) => [t.address.toLowerCase(), t]) ??\n [],\n );\n }, [tokenList, args?.tokens]);\n\n const QUERY_KEY =\n publicClient && tokenList !== undefined && wallet\n ? ([\n \"usePollWalletBalances\",\n wallet,\n // TODO: adding the whole list to the query is very inefficient, we should only add the tokens addresses\n Array.from(tokens.values()),\n ] as const)\n : null;\n\n const swrResponse = useSWR<BalanceToken[] | undefined, any, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([, wallet, tokenList]) => {\n return getWalletBalances({\n account: wallet,\n tokenList,\n publicClient,\n });\n },\n {\n refreshInterval: POLLING.NORMAL,\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n}\n","import useSWRImmutable from \"swr/immutable\";\nimport { isAddress, zeroAddress } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getStakingTokenInformation } from \"~/actions/pol/getStakingTokenInformation\";\nimport type { DefaultHookOptions, DefaultHookReturnType, Token } from \"~/types\";\nimport { beraToken, isToken } from \"~/utils/tokens\";\n\nexport type UseStakingTokenInformationResponse = DefaultHookReturnType<\n Partial<Token> | undefined\n>;\n\nexport type useStakingTokenInformationArgs = {\n address: string | undefined;\n};\nexport const useStakingTokenInformation = (\n args: useStakingTokenInformationArgs,\n options?: DefaultHookOptions,\n): UseStakingTokenInformationResponse => {\n const publicClient = usePublicClient();\n const QUERY_KEY =\n args?.address && publicClient && isAddress(args.address)\n ? ([\"useStakingTokenInformation\", args.address] as const)\n : null;\n const swrResponse = useSWRImmutable<\n Partial<Token> | undefined,\n any,\n typeof QUERY_KEY\n >(\n QUERY_KEY,\n async ([_, address]) => {\n if (isToken(address, \"BERA\")) {\n return {\n address: zeroAddress,\n decimals: beraToken.decimals,\n name: beraToken.name,\n symbol: beraToken.symbol,\n };\n }\n\n return await getStakingTokenInformation({\n address,\n publicClient,\n });\n },\n { ...options?.opts },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","import useSWR from \"swr\";\nimport { type Address, erc20Abi } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { assertPublicClient } from \"~/errors/assert\";\n\nexport function useTotalSupply({ address }: { address: Address | undefined }) {\n const publicClient = usePublicClient();\n return useSWR(\n address && publicClient ? [\"useTotalSupply\", address] : null,\n ([, address]) => {\n assertPublicClient(publicClient);\n return publicClient.readContract({\n address,\n abi: erc20Abi,\n functionName: \"totalSupply\",\n args: [],\n });\n },\n );\n}\n","import { useCallback } from \"react\";\n\nimport { useBeraWagmi } from \"@berachain/wagmi/hooks\";\n\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport { useTransactionStore } from \"./TransactionStoreContext\";\nimport type { NewTransaction } from \"./transactionStore\";\n\nexport function useAddRecentTransaction(): (\n transaction: NewTransaction,\n) => void {\n const store = useTransactionStore();\n const { account } = useBeraWagmi();\n const address = account?.wallet?.address;\n return useCallback(\n (transaction: NewTransaction) => {\n if (!address) {\n throw new InvalidArgumentError({\n property: \"address\",\n value: address,\n expected: \"Address\",\n });\n }\n\n store.addTransaction(address, transaction);\n },\n [store, address],\n );\n}\n","import { useEffect, useState } from \"react\";\n\nimport { useBeraWallet } from \"@berachain/wagmi/hooks\";\n\nimport { useTransactionStore } from \"./TransactionStoreContext\";\nimport type { Transaction } from \"./transactionStore\";\n\nexport function useRecentTransactions(): Transaction[] {\n const store = useTransactionStore();\n const { address } = useBeraWallet();\n\n const [transactions, setTransactions] = useState(() =>\n store && address ? store.getTransactions(address) : [],\n );\n\n useEffect(() => {\n if (store && address) {\n setTransactions(store.getTransactions(address));\n\n return store.onChange(() => {\n setTransactions(store.getTransactions(address));\n });\n }\n }, [store, address]);\n\n return transactions;\n}\n","import useSWRImmutable from \"swr/immutable\";\n\nimport { useBlockNumber, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getBlockTimestamp } from \"~/actions/misc/getBlockTimestamp\";\nimport { useBlockTime } from \"~/contexts/block-time-provider\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { msToSeconds, seconds } from \"~/utils/time\";\n\n/**\n *\n * @returns Timestamp in seconds\n */\nexport function useBlockToTimestamp(\n inputBlock: number | bigint | string,\n): number | undefined {\n const publicClient = usePublicClient();\n const { config } = parseBaseArgs({ chainId: publicClient?.chain.id });\n const { data: currentBlock, isLoading } = useBlockNumber({\n cacheTime: seconds(config.averageBlockTime),\n });\n\n const { data: block } = useSWRImmutable(\n currentBlock && publicClient && Number(inputBlock) > 0\n ? [\"useBlockToTimestamp\", inputBlock, currentBlock]\n : null,\n async ([, inputBlock, currentBlock]) => {\n assertPublicClient(publicClient);\n return getBlockTimestamp({\n block: inputBlock,\n currentBlock,\n blockTime: blockDuration,\n publicClient,\n });\n },\n );\n\n const blockDuration = useBlockTime();\n\n if (block) {\n return Number(block.timestamp);\n }\n\n if (isLoading || !currentBlock) return undefined;\n\n return Math.floor(\n msToSeconds(Date.now()) +\n blockDuration * (Number(inputBlock) - Number(currentBlock)),\n );\n}\n","import { useCallback, useReducer } from \"react\";\nimport type { Abi, ContractFunctionArgs, ContractFunctionName } from \"viem\";\n\nimport { useBeraWagmi, useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { beraWriteContract } from \"~/actions/transactions/beraWriteContract\";\nimport { useBeraFlag } from \"~/contexts/BeraFlags/BeraFlags\";\nimport { TransactionFailedError } from \"~/errors/TransactionFailedError\";\nimport type { IContractWrite } from \"~/types/global\";\nimport { ActionEnum, initialState, reducer } from \"./stateReducer\";\nimport type { IUseContractWriteArgs, UseContractWriteApi } from \"./types\";\n\nfunction useBeraContractWrite({\n onlyPermissionless,\n onSuccess,\n onError,\n onLoading,\n onWarning,\n onSubmission,\n}: IUseContractWriteArgs & {\n /**\n * Whether to allow only permissionless transactions.\n *\n * This is useful when UI is reading data for another account compared to the connected account.\n */\n onlyPermissionless?: boolean;\n} = {}): UseContractWriteApi {\n const [state, dispatch] = useReducer(reducer, initialState);\n\n const { account, onSmartAccountRejection } = useBeraWagmi();\n const wagmiConfig = useConfig();\n\n /**\n * We are using a longer timeout for wallets with EIP-7702 (safe wallet) because it takes longer to confirm the transaction.\n * 10 minutes for safe wallets\n * 2 minutes for EOA wallets\n * */\n const txConfirmationTimeout = account?.wallet?.isContract\n ? 60_000 * 10\n : 120_000;\n\n // Reset the state of the hook to the initial state\n const reset = useCallback(() => {\n dispatch({ type: ActionEnum.RESET });\n }, []);\n\n const enableSimulateCalls = useBeraFlag(\"enableSimulateCalls\");\n\n const write = useCallback(\n <\n abi extends Abi | undefined = undefined,\n functionName extends abi extends Abi\n ? ContractFunctionName<abi>\n : never = abi extends Abi ? ContractFunctionName<abi> : never,\n params extends abi extends Abi\n ? ContractFunctionArgs<abi, \"payable\" | \"nonpayable\", functionName>\n : never = abi extends Abi\n ? ContractFunctionArgs<abi, \"payable\" | \"nonpayable\", functionName>\n : never,\n >(\n writeArgs: IContractWrite<abi, functionName, params>,\n ) => {\n if (onlyPermissionless && !writeArgs.permissionless) {\n const er = new TransactionFailedError({\n message:\n \"Trying to send a non-permissionless transaction with an overridden account\",\n displayMessage:\n \"You can't send this transaction with an overridden account. Please reset the account in the settings popover.\",\n level: \"info\",\n input: writeArgs,\n });\n onWarning?.(er, writeArgs);\n onError?.(er, writeArgs);\n\n throw er;\n }\n return beraWriteContract({\n wagmiConfig,\n ...(writeArgs as IContractWrite),\n txConfirmationTimeout,\n enableSimulateCalls,\n onLoading(...args) {\n dispatch({ type: ActionEnum.LOADING });\n // can't use ...args because of typing issues\n writeArgs.onLoading?.(writeArgs);\n onLoading?.(...args);\n },\n onWarning(...args) {\n // can't use ...args because of typing issues\n writeArgs.onWarning?.(args[0], writeArgs);\n onWarning?.(...args);\n },\n onSubmission(...args) {\n dispatch({ type: ActionEnum.SUBMITTING });\n // can't use ...args because of typing issues\n writeArgs.onSubmission?.(args[0], writeArgs);\n onSubmission?.(...args);\n },\n onSuccess(...args) {\n dispatch({ type: ActionEnum.SUCCESS });\n // can't use ...args because of typing issues\n writeArgs.onSuccess?.(args[0], writeArgs);\n onSuccess?.(...args);\n },\n onError(...args) {\n dispatch({ type: ActionEnum.ERROR });\n writeArgs.onError?.(args[0], writeArgs);\n if (args[0].reason === \"AtomicReadyWalletRejectedUpgradeError\") {\n onSmartAccountRejection();\n }\n onError?.(...args);\n },\n });\n },\n [\n wagmiConfig,\n onLoading,\n onWarning,\n onSubmission,\n onSuccess,\n onError,\n onlyPermissionless,\n enableSimulateCalls,\n ],\n );\n\n return {\n isLoading: state.confirmState === \"loading\",\n isSubmitting: state.confirmState === \"submitting\",\n isSuccess: state.confirmState === \"success\",\n isError: state.confirmState === \"fail\",\n write,\n reset,\n };\n}\n\nexport default useBeraContractWrite;\n","type LoadingState = \"idle\" | \"loading\" | \"success\" | \"fail\" | \"submitting\";\n\nexport enum ActionEnum {\n ERROR = \"confirm_error\",\n SUCCESS = \"confirm_receipt\",\n LOADING = \"confirm_sending\",\n SUBMITTING = \"confirm_submitting\",\n RESET = \"confirm_reset\",\n}\n\ntype Action =\n | { type: ActionEnum.LOADING }\n | { type: ActionEnum.SUCCESS }\n | { type: ActionEnum.ERROR }\n | { type: ActionEnum.SUBMITTING }\n | { type: ActionEnum.RESET };\n\ninterface State {\n confirmState: LoadingState;\n txnHash: string;\n message: string;\n}\n\nexport const initialState: State = {\n confirmState: \"idle\",\n txnHash: \"\",\n message: \"\",\n};\n\nexport const reducer = (state: State, actions: Action): State => {\n switch (actions.type) {\n case ActionEnum.LOADING:\n return {\n ...state,\n confirmState: \"loading\",\n };\n case ActionEnum.SUCCESS:\n return {\n ...state,\n confirmState: \"success\",\n };\n case ActionEnum.ERROR:\n return {\n ...state,\n confirmState: \"fail\",\n };\n case ActionEnum.SUBMITTING:\n return {\n ...state,\n confirmState: \"submitting\",\n };\n // NOTE: if we are resetting the state of the useTxn/useWriteContract hook, we need to reset the state to the initial state\n case ActionEnum.RESET:\n return {\n ...initialState,\n };\n default:\n return state;\n }\n};\n","import useSWRImmutable from \"swr/immutable\";\nimport { isAddress, zeroAddress } from \"viem\";\n\nimport { chainId } from \"@berachain/config/internal\";\n\nimport { beraFetchJson } from \"~/utils/beraFetch\";\n\ninterface SuccessResponse {\n status: \"1\";\n message: \"OK\";\n result: string;\n}\n\ninterface ErrorResponse {\n status: \"0\";\n message: \"NOTOK\";\n result: string;\n}\n\ntype ApiResponse = SuccessResponse | ErrorResponse;\n\nasync function fetchVerifiedAbi(address: string): Promise<string> {\n const data = await beraFetchJson<ApiResponse>({\n url: `https://api.routescan.io/v2/network/testnet/evm/${chainId}/etherscan/api?module=contract&action=getabi&address=${address}`,\n type: \"rest\",\n name: \"RouteScan\",\n });\n\n if (data.status === \"0\") {\n throw new Error(data.result);\n }\n\n return data.result;\n}\n\nexport const useGetVerifiedAbi = (address?: string) => {\n return useSWRImmutable<string>(\n address &&\n isAddress(address) &&\n // Address zero can't be a contract for sure\n address !== zeroAddress\n ? ([\"useGetVerifiedAbi\", address] as const)\n : null,\n () => (address ? fetchVerifiedAbi(address) : Promise.resolve(\"\")),\n {},\n );\n};\n","\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\n\ntype UseHistoryStateOptions<T> = {\n key: string;\n defaultValue: T;\n};\n\n/**\n * useHistoryState is a hook that allows storing state in the browser's history state\n * it is useful for storing state that you want to persist across pages\n * It is indexed by the key parameter to be able to store multiple states on the same page and\n * also to not override nextjs usage of the history state\n * @param {string} key - the key to store the state under\n * @param {T} defaultValue - the default value to use if the state is not found\n * @returns {T} state - the current state\n * @returns {function} setHistoryState - a function to set the state\n */\nexport function useHistoryState<T>({\n key,\n defaultValue,\n}: UseHistoryStateOptions<T>) {\n // function to get current state from history\n const getCurrentState = useCallback((): T => {\n if (typeof window === \"undefined\") {\n return defaultValue;\n }\n const existing = window.history.state?.[key];\n const state = existing !== undefined ? existing : defaultValue;\n return state;\n }, [key, defaultValue]);\n\n // use useState to trigger re-renders\n const [state, setState] = useState<T>(getCurrentState());\n\n const setHistoryState = useCallback(\n (value: T | ((prev: T) => T)) => {\n const currentState = getCurrentState();\n\n const newValue = value instanceof Function ? value(currentState) : value;\n\n const historyState = window.history.state || {};\n const newHistoryState = { ...historyState, [key]: newValue };\n\n // always use replaceState for updates to avoid creating new history entries\n window.history.replaceState(newHistoryState, \"\");\n setState(newValue);\n },\n [key, getCurrentState],\n );\n\n useEffect(() => {\n const existing = window.history.state?.[key];\n if (existing === undefined) {\n // if no existing state, create initial history entry\n const currentState = window.history.state || {};\n const newState = { ...currentState, [key]: defaultValue };\n window.history.replaceState(newState, \"\");\n }\n }, [key, defaultValue]);\n\n return [state, setHistoryState] as const;\n}\n","import { useEffect, useRef } from \"react\";\n\n/**\n * Returns the previous value of a variable before the render\n * @param value - the value to return the previous value for\n */\nexport function usePrevious<T>(value: T): T | undefined {\n const ref = useRef<T | undefined>(undefined);\n useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n}\n","import useSWR from \"swr\";\n\nimport type {\n GetValidatorsQuery,\n GetValidatorsQueryVariables,\n GqlChain,\n} from \"@berachain/graphql/pol/api\";\n\nimport { getAllValidators } from \"~/actions/validators/getAllValidators\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport const useAllValidatorsQueryKey = ({\n variables,\n}: {\n variables?: GetValidatorsQueryVariables;\n} = {}) => {\n return [\"useAllValidators\", variables];\n};\n\nexport const useAllValidators = (\n variables: GetValidatorsQueryVariables & BeraJS.BaseFunctionArgs,\n options?: DefaultHookOptions,\n): DefaultHookReturnType<GetValidatorsQuery | undefined> => {\n const { config } = parseBaseArgs(variables);\n const swrResponse = useSWR<GetValidatorsQuery | undefined>(\n useAllValidatorsQueryKey({ variables }),\n async ([, variables]) => {\n const result = await getAllValidators({\n variables: {\n chain: config.bex.chainName as GqlChain,\n ...variables,\n },\n });\n return result;\n },\n {\n refreshInterval: POLLING.SLOW,\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\n\nimport { getApiEnrichedAllocation } from \"~/actions/validators/getApiEnrichedAllocation\";\nimport type { ValidatorRewardAllocation } from \"~/actions/validators/getValidatorRewardAllocation\";\n\nexport function useApiEnrichedAllocation({\n allocation,\n}: {\n allocation: ValidatorRewardAllocation | undefined;\n}) {\n return useSWR(\n allocation ? [\"useApiEnrichedAllocation\", allocation] : null,\n ([, allocation]) => {\n return getApiEnrichedAllocation({ allocation });\n },\n );\n}\n","import useSWR from \"swr\";\nimport { type Address, isHex } from \"viem\";\n\nimport type { GetValidatorQuery } from \"@berachain/graphql/pol/api\";\n\nimport { getApiValidator } from \"~/actions/validators/getApiValidator\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport interface UsePollValidatorInfoResponse\n extends DefaultHookReturnType<GetValidatorQuery> {}\n\nexport const useApiValidatorQueryKey = (id: Address) =>\n id ? ([\"useApiValidator\", id] as const) : null;\n\nexport const useApiValidator = (\n id: Address,\n options?: DefaultHookOptions,\n): UsePollValidatorInfoResponse => {\n const QUERY_KEY = useApiValidatorQueryKey(id);\n const isEnabled = options?.opts?.isEnabled ?? true;\n const swrResponse = useSWR(\n isEnabled && id ? QUERY_KEY : null,\n async ([, id]) => {\n if (!id || !isHex(id)) throw new Error(`Invalid validator ID: ${id}`);\n\n return getApiValidator({ id });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getBaselineRewardAllocation } from \"~/actions/validators/getBaselineRewardAllocation\";\nimport { assertPublicClient } from \"~/errors/assert\";\n\nexport function useBaselineRewardAllocation() {\n const publicClient = usePublicClient();\n return useSWR(publicClient ? [\"baselineRewardAllocation\"] : null, () => {\n assertPublicClient(publicClient);\n return getBaselineRewardAllocation({\n publicClient,\n });\n });\n}\n","export const rewardAllocationFactoryAbi = [\n { inputs: [], stateMutability: \"nonpayable\", type: \"constructor\" },\n { inputs: [], name: \"AccessControlBadConfirmation\", type: \"error\" },\n {\n inputs: [\n { internalType: \"address\", name: \"account\", type: \"address\" },\n { internalType: \"bytes32\", name: \"neededRole\", type: \"bytes32\" },\n ],\n name: \"AccessControlUnauthorizedAccount\",\n type: \"error\",\n },\n {\n inputs: [{ internalType: \"address\", name: \"target\", type: \"address\" }],\n name: \"AddressEmptyCode\",\n type: \"error\",\n },\n { inputs: [], name: \"AmountGreaterThanReward\", type: \"error\" },\n { inputs: [], name: \"AmountLessThanMinIncentiveRate\", type: \"error\" },\n { inputs: [], name: \"CannotRecoverIncentiveToken\", type: \"error\" },\n { inputs: [], name: \"CannotRecoverRewardToken\", type: \"error\" },\n { inputs: [], name: \"CannotRecoverStakingToken\", type: \"error\" },\n { inputs: [], name: \"CommissionChangeAlreadyQueued\", type: \"error\" },\n { inputs: [], name: \"CommissionNotQueuedOrDelayNotPassed\", type: \"error\" },\n { inputs: [], name: \"DepositNotMultipleOfGwei\", type: \"error\" },\n { inputs: [], name: \"DepositValueTooHigh\", type: \"error\" },\n { inputs: [], name: \"DonateAmountLessThanPayoutAmount\", type: \"error\" },\n {\n inputs: [{ internalType: \"address\", name: \"receiver\", type: \"address\" }],\n name: \"DuplicateReceiver\",\n type: \"error\",\n },\n { inputs: [], name: \"DurationChangeNotAllowed\", type: \"error\" },\n {\n inputs: [\n { internalType: \"address\", name: \"implementation\", type: \"address\" },\n ],\n name: \"ERC1967InvalidImplementation\",\n type: \"error\",\n },\n { inputs: [], name: \"ERC1967NonPayable\", type: \"error\" },\n { inputs: [], name: \"FailedCall\", type: \"error\" },\n { inputs: [], name: \"IncentiveRateTooHigh\", type: \"error\" },\n { inputs: [], name: \"IndexOutOfRange\", type: \"error\" },\n { inputs: [], name: \"InsolventReward\", type: \"error\" },\n { inputs: [], name: \"InsufficientDelegateStake\", type: \"error\" },\n { inputs: [], name: \"InsufficientDeposit\", type: \"error\" },\n { inputs: [], name: \"InsufficientIncentiveTokens\", type: \"error\" },\n { inputs: [], name: \"InsufficientNativeValue\", type: \"error\" },\n { inputs: [], name: \"InsufficientSelfStake\", type: \"error\" },\n { inputs: [], name: \"InsufficientStake\", type: \"error\" },\n { inputs: [], name: \"InvalidActivateBoostDelay\", type: \"error\" },\n { inputs: [], name: \"InvalidArray\", type: \"error\" },\n { inputs: [], name: \"InvalidBaseRate\", type: \"error\" },\n { inputs: [], name: \"InvalidBoostMultiplier\", type: \"error\" },\n { inputs: [], name: \"InvalidCommissionChangeDelay\", type: \"error\" },\n { inputs: [], name: \"InvalidCommissionValue\", type: \"error\" },\n { inputs: [], name: \"InvalidCredentialsLength\", type: \"error\" },\n { inputs: [], name: \"InvalidDistribution\", type: \"error\" },\n { inputs: [], name: \"InvalidDropBoostDelay\", type: \"error\" },\n { inputs: [], name: \"InvalidIncentiveFeeRate\", type: \"error\" },\n { inputs: [], name: \"InvalidIncentiveRate\", type: \"error\" },\n { inputs: [], name: \"InvalidInitialization\", type: \"error\" },\n { inputs: [], name: \"InvalidMaxIncentiveTokensCount\", type: \"error\" },\n { inputs: [], name: \"InvalidMaxWeightPerVault\", type: \"error\" },\n { inputs: [], name: \"InvalidMerkleRoot\", type: \"error\" },\n { inputs: [], name: \"InvalidMinBoostedRewardRate\", type: \"error\" },\n { inputs: [], name: \"InvalidProof\", type: \"error\" },\n { inputs: [], name: \"InvalidPubKeyLength\", type: \"error\" },\n {\n inputs: [],\n name: \"InvalidRewardAllocationInactivityBlockSpan\",\n type: \"error\",\n },\n { inputs: [], name: \"InvalidRewardAllocationWeights\", type: \"error\" },\n { inputs: [], name: \"InvalidRewardClaimDelay\", type: \"error\" },\n { inputs: [], name: \"InvalidRewardConvexity\", type: \"error\" },\n { inputs: [], name: \"InvalidRewardDuration\", type: \"error\" },\n { inputs: [], name: \"InvalidRewardRate\", type: \"error\" },\n { inputs: [], name: \"InvalidSignatureLength\", type: \"error\" },\n { inputs: [], name: \"InvalidStartBlock\", type: \"error\" },\n { inputs: [], name: \"InvalidToken\", type: \"error\" },\n { inputs: [], name: \"InvalidWeight\", type: \"error\" },\n { inputs: [], name: \"InvalidateDefaultRewardAllocation\", type: \"error\" },\n { inputs: [], name: \"InvariantCheckFailed\", type: \"error\" },\n { inputs: [], name: \"MaxNumWeightsPerRewardAllocationIsZero\", type: \"error\" },\n { inputs: [], name: \"MethodNotAllowed\", type: \"error\" },\n { inputs: [], name: \"MinIncentiveRateIsZero\", type: \"error\" },\n { inputs: [], name: \"NonTransferable\", type: \"error\" },\n { inputs: [], name: \"NotAContract\", type: \"error\" },\n { inputs: [], name: \"NotApprovedSender\", type: \"error\" },\n { inputs: [], name: \"NotBGT\", type: \"error\" },\n { inputs: [], name: \"NotBlockRewardController\", type: \"error\" },\n { inputs: [], name: \"NotDelegate\", type: \"error\" },\n { inputs: [], name: \"NotDistributor\", type: \"error\" },\n { inputs: [], name: \"NotEnoughBalance\", type: \"error\" },\n { inputs: [], name: \"NotEnoughBoostedBalance\", type: \"error\" },\n { inputs: [], name: \"NotEnoughTime\", type: \"error\" },\n { inputs: [], name: \"NotFactoryVault\", type: \"error\" },\n { inputs: [], name: \"NotFeeCollector\", type: \"error\" },\n { inputs: [], name: \"NotIncentiveManager\", type: \"error\" },\n { inputs: [], name: \"NotInitializing\", type: \"error\" },\n { inputs: [], name: \"NotNewOperator\", type: \"error\" },\n { inputs: [], name: \"NotOperator\", type: \"error\" },\n { inputs: [], name: \"NotRewardAllocator\", type: \"error\" },\n { inputs: [], name: \"NotRewardDurationManager\", type: \"error\" },\n { inputs: [], name: \"NotRewardVaultManager\", type: \"error\" },\n { inputs: [], name: \"NotSystemAddress\", type: \"error\" },\n { inputs: [], name: \"NotWBERAStakerVault\", type: \"error\" },\n { inputs: [], name: \"NotWhitelistedVault\", type: \"error\" },\n { inputs: [], name: \"OnlyNFTOwnerAllowed\", type: \"error\" },\n { inputs: [], name: \"OnlySystemCallAllowed\", type: \"error\" },\n { inputs: [], name: \"OperatorAlreadySet\", type: \"error\" },\n { inputs: [], name: \"PayoutAmountIsZero\", type: \"error\" },\n { inputs: [], name: \"RewardAllocationAlreadyQueued\", type: \"error\" },\n { inputs: [], name: \"RewardAllocationBlockDelayTooLarge\", type: \"error\" },\n { inputs: [], name: \"RewardCycleNotEnded\", type: \"error\" },\n { inputs: [], name: \"RewardDurationCoolDownPeriodNotPassed\", type: \"error\" },\n { inputs: [], name: \"RewardInactive\", type: \"error\" },\n { inputs: [], name: \"RewardsDurationIsZero\", type: \"error\" },\n { inputs: [], name: \"StakeAmountIsZero\", type: \"error\" },\n { inputs: [], name: \"TimestampAlreadyProcessed\", type: \"error\" },\n { inputs: [], name: \"TokenAlreadyWhitelistedOrLimitReached\", type: \"error\" },\n { inputs: [], name: \"TokenNotWhitelisted\", type: \"error\" },\n { inputs: [], name: \"TooManyWeights\", type: \"error\" },\n { inputs: [], name: \"TotalSupplyOverflow\", type: \"error\" },\n { inputs: [], name: \"UUPSUnauthorizedCallContext\", type: \"error\" },\n {\n inputs: [{ internalType: \"bytes32\", name: \"slot\", type: \"bytes32\" }],\n name: \"UUPSUnsupportedProxiableUUID\",\n type: \"error\",\n },\n { inputs: [], name: \"UnauthorizedETHTransfer\", type: \"error\" },\n { inputs: [], name: \"WithdrawAmountIsZero\", type: \"error\" },\n { inputs: [], name: \"WithdrawalAlreadyRequested\", type: \"error\" },\n { inputs: [], name: \"WithdrawalNotReady\", type: \"error\" },\n { inputs: [], name: \"WithdrawalNotRequested\", type: \"error\" },\n { inputs: [], name: \"ZeroAddress\", type: \"error\" },\n { inputs: [], name: \"ZeroOperatorOnFirstDeposit\", type: \"error\" },\n { inputs: [], name: \"ZeroPercentageWeight\", type: \"error\" },\n {\n anonymous: false,\n inputs: [\n {\n components: [\n { internalType: \"address\", name: \"receiver\", type: \"address\" },\n {\n internalType: \"uint96\",\n name: \"percentageNumerator\",\n type: \"uint96\",\n },\n ],\n indexed: false,\n internalType: \"struct IBeraChef.Weight[]\",\n name: \"weights\",\n type: \"tuple[]\",\n },\n ],\n name: \"BaselineAllocationSet\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: \"uint64\",\n name: \"version\",\n type: \"uint64\",\n },\n ],\n name: \"Initialized\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: \"bytes32\", name: \"role\", type: \"bytes32\" },\n {\n indexed: true,\n internalType: \"bytes32\",\n name: \"previousAdminRole\",\n type: \"bytes32\",\n },\n {\n indexed: true,\n internalType: \"bytes32\",\n name: \"newAdminRole\",\n type: \"bytes32\",\n },\n ],\n name: \"RoleAdminChanged\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: \"bytes32\", name: \"role\", type: \"bytes32\" },\n {\n indexed: true,\n internalType: \"address\",\n name: \"account\",\n type: \"address\",\n },\n {\n indexed: true,\n internalType: \"address\",\n name: \"sender\",\n type: \"address\",\n },\n ],\n name: \"RoleGranted\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, internalType: \"bytes32\", name: \"role\", type: \"bytes32\" },\n {\n indexed: true,\n internalType: \"address\",\n name: \"account\",\n type: \"address\",\n },\n {\n indexed: true,\n internalType: \"address\",\n name: \"sender\",\n type: \"address\",\n },\n ],\n name: \"RoleRevoked\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"address\",\n name: \"implementation\",\n type: \"address\",\n },\n ],\n name: \"Upgraded\",\n type: \"event\",\n },\n {\n inputs: [],\n name: \"ALLOCATION_SETTER_ROLE\",\n outputs: [{ internalType: \"bytes32\", name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"DEFAULT_ADMIN_ROLE\",\n outputs: [{ internalType: \"bytes32\", name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"UPGRADE_INTERFACE_VERSION\",\n outputs: [{ internalType: \"string\", name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"beraChef\",\n outputs: [\n { internalType: \"contract IBeraChef\", name: \"\", type: \"address\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"getBaselineAllocation\",\n outputs: [\n {\n components: [\n { internalType: \"uint64\", name: \"startBlock\", type: \"uint64\" },\n {\n components: [\n { internalType: \"address\", name: \"receiver\", type: \"address\" },\n {\n internalType: \"uint96\",\n name: \"percentageNumerator\",\n type: \"uint96\",\n },\n ],\n internalType: \"struct IBeraChef.Weight[]\",\n name: \"weights\",\n type: \"tuple[]\",\n },\n ],\n internalType: \"struct IBeraChef.RewardAllocation\",\n name: \"\",\n type: \"tuple\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"bytes32\", name: \"role\", type: \"bytes32\" }],\n name: \"getRoleAdmin\",\n outputs: [{ internalType: \"bytes32\", name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"bytes32\", name: \"role\", type: \"bytes32\" },\n { internalType: \"address\", name: \"account\", type: \"address\" },\n ],\n name: \"grantRole\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"bytes32\", name: \"role\", type: \"bytes32\" },\n { internalType: \"address\", name: \"account\", type: \"address\" },\n ],\n name: \"hasRole\",\n outputs: [{ internalType: \"bool\", name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"address\", name: \"_governance\", type: \"address\" },\n { internalType: \"address\", name: \"_beraChef\", type: \"address\" },\n ],\n name: \"initialize\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"proxiableUUID\",\n outputs: [{ internalType: \"bytes32\", name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"bytes32\", name: \"role\", type: \"bytes32\" },\n { internalType: \"address\", name: \"callerConfirmation\", type: \"address\" },\n ],\n name: \"renounceRole\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"bytes32\", name: \"role\", type: \"bytes32\" },\n { internalType: \"address\", name: \"account\", type: \"address\" },\n ],\n name: \"revokeRole\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n { internalType: \"address\", name: \"receiver\", type: \"address\" },\n {\n internalType: \"uint96\",\n name: \"percentageNumerator\",\n type: \"uint96\",\n },\n ],\n internalType: \"struct IBeraChef.Weight[]\",\n name: \"weights\",\n type: \"tuple[]\",\n },\n ],\n name: \"setBaselineAllocation\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ internalType: \"bytes4\", name: \"interfaceId\", type: \"bytes4\" }],\n name: \"supportsInterface\",\n outputs: [{ internalType: \"bool\", name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"address\", name: \"newImplementation\", type: \"address\" },\n { internalType: \"bytes\", name: \"data\", type: \"bytes\" },\n ],\n name: \"upgradeToAndCall\",\n outputs: [],\n stateMutability: \"payable\",\n type: \"function\",\n },\n] as const;\n","import type { PublicClient } from \"viem\";\n\nimport { rewardAllocationFactoryAbi } from \"~/abi/pol/rewardAllocationFactory\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { formatValidatorRewardAllocation } from \"./getValidatorRewardAllocation\";\n\nexport async function getBaselineRewardAllocation({\n publicClient,\n ...args\n}: BeraJS.BaseFunctionArgs & { publicClient: PublicClient }) {\n const { config } = parseBaseArgs(args);\n\n const raw = await publicClient.readContract({\n abi: rewardAllocationFactoryAbi,\n address: config.pol.rewardAllocationFactory,\n functionName: \"getBaselineAllocation\",\n });\n const block =\n raw.startBlock !== 0n\n ? await publicClient.getBlock({\n blockNumber: raw.startBlock,\n })\n : { timestamp: 0 };\n\n return formatValidatorRewardAllocation(raw, Number(block.timestamp));\n}\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport type { GetValidatorBlockStatsQuery } from \"@berachain/graphql/pol/subgraph\";\n\nimport { getDailyValidatorBlockStats } from \"~/actions/validators/getDailyValidatorBlockStats\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { DefaultHookReturnType } from \"~/types\";\n\nexport const useDailyValidatorBlockStats = ({\n pubKey,\n first = 1,\n}: {\n pubKey: Address | undefined;\n first?: number;\n}): DefaultHookReturnType<GetValidatorBlockStatsQuery> => {\n const QUERY_KEY = pubKey\n ? ([\"useDailyValidatorBlockStats\", pubKey, first] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, pubKey, first]) => {\n return await getDailyValidatorBlockStats({\n pubKey: pubKey,\n first,\n });\n },\n {\n refreshInterval: POLLING.SLOW,\n },\n );\n\n return { ...swrResponse, refresh: () => swrResponse.mutate() };\n};\n","import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getDefaultRewardAllocation } from \"~/actions/validators/getDefaultRewardAllocation\";\nimport type { ValidatorRewardAllocation } from \"~/actions/validators/getValidatorRewardAllocation\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\n\nexport function useDefaultRewardAllocation(options?: DefaultHookOptions) {\n const publicClient = usePublicClient();\n const QUERY_KEY = publicClient ? [\"useDefaultRewardAllocation\"] : null;\n\n const swrResponse = useSWR<ValidatorRewardAllocation | undefined>(\n QUERY_KEY,\n async () => {\n assertPublicClient(publicClient);\n\n return await getDefaultRewardAllocation({\n client: publicClient,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","import useSWRImmutable from \"swr/immutable\";\nimport type { Address } from \"viem\";\n\nimport { getManagedValidatorByAccount } from \"~/actions/validators/getManagedValidatorByAccount\";\nimport type { DefaultHookOptions } from \"~/types\";\n\n/**\n * Return the validators managed by the account\n * Roles:\n * - Validator Operator\n * - Validator Reward Allocator\n * @param address\n * @param options\n * @returns\n */\nexport const useManagedValidatorByAccount = (\n { account }: { account: Address | undefined },\n options?: DefaultHookOptions,\n) => {\n const QUERY_KEY = account\n ? ([\"useManagedValidatorByAccount\", account] as const)\n : null;\n\n const swrResponse = useSWRImmutable(\n QUERY_KEY,\n async ([, account]) => {\n return await getManagedValidatorByAccount({\n account,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport type { Address, PublicClient } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getValidatorOperatorAddress } from \"~/actions/validators/getValidatorOperatorAddress\";\nimport { getValidatorRewardAllocatorAddress } from \"~/actions/validators/getValidatorRewardAllocatorAddress\";\nimport { useBeraFlag } from \"~/contexts/BeraFlags/BeraFlags\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport type ManagedValidatorRole = {\n operator: Address | null;\n rewardAllocator: Address | null;\n hasOperatorRole: boolean;\n hasRewardAllocatorRole: boolean;\n};\n\nfunction isOperator(\n account: Address | undefined,\n validatorRoles: Pick<ManagedValidatorRole, \"operator\"> | undefined,\n): boolean {\n if (!account || !validatorRoles) return false;\n if (validatorRoles.operator?.toLowerCase() === account.toLowerCase()) {\n return true;\n }\n return false;\n}\n\n// If the account is the operator and the reward allocator is undefined, then the account is a reward allocator\nfunction isRewardAllocator(\n account: Address | undefined,\n validatorRoles:\n | Pick<ManagedValidatorRole, \"rewardAllocator\" | \"operator\">\n | undefined,\n): boolean {\n if (!account || !validatorRoles) return false;\n\n // If reward allocator is set, check for it\n if (validatorRoles.rewardAllocator) {\n return (\n validatorRoles.rewardAllocator.toLowerCase() === account.toLowerCase()\n );\n }\n\n // If the account is the operator and the reward allocator is undefined, then the account is also a reward allocator\n return isOperator(account, validatorRoles);\n}\n\nexport function useManagedValidatorRole(\n {\n pubKey,\n account: accountAddress,\n }: { pubKey: Address | undefined; account?: Address | undefined },\n options?: DefaultHookOptions,\n): DefaultHookReturnType<ManagedValidatorRole | undefined> {\n const publicClient = usePublicClient();\n const mockValidatorOperator = useBeraFlag(\"mockValidatorOperator\");\n const mockValidatorRewardAllocator = useBeraFlag(\n \"mockValidatorRewardAllocator\",\n );\n const QUERY_KEY =\n publicClient && pubKey\n ? ([\"useManagedValidatorRole\", pubKey] as const)\n : null;\n\n const { address: connectedAccount } = useBeraWallet();\n\n const account = accountAddress ?? connectedAccount;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, pubKey]) => {\n assertPublicClient(publicClient);\n\n const [operator, rewardAllocator] = await Promise.all([\n getValidatorOperatorAddress({\n client: publicClient as PublicClient,\n pubKey,\n }),\n getValidatorRewardAllocatorAddress({\n client: publicClient as PublicClient,\n pubKey,\n }),\n ]);\n return {\n operator: operator ?? null,\n rewardAllocator,\n };\n },\n {\n ...options?.opts,\n },\n );\n\n // Check for account roles\n const hasOperatorRole = useMemo(() => {\n return mockValidatorOperator || isOperator(account, swrResponse.data);\n }, [account, mockValidatorOperator, swrResponse.data]);\n const hasRewardAllocatorRole = useMemo(() => {\n return (\n mockValidatorRewardAllocator ||\n isRewardAllocator(account, swrResponse.data)\n );\n }, [account, mockValidatorRewardAllocator, swrResponse.data]);\n\n return {\n ...swrResponse,\n data: swrResponse.data\n ? {\n ...swrResponse.data,\n hasOperatorRole,\n hasRewardAllocatorRole,\n }\n : undefined,\n refresh: () => swrResponse.mutate(),\n };\n}\n","import { type Address, type PublicClient, zeroAddress } from \"viem\";\n\nimport { beraChefAbi } from \"~/abi/pol/beraChef\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport type ValidatorRewardAllocatorAddress = Address;\n\n/**\n * Get the reward allocator address for a validator\n * @param param0\n * @returns\n */\nexport async function getValidatorRewardAllocatorAddress({\n client,\n pubKey,\n ...args\n}: {\n client: PublicClient;\n pubKey: Address;\n} & BeraJS.BaseFunctionArgs): Promise<ValidatorRewardAllocatorAddress | null> {\n const { config } = parseBaseArgs(args);\n\n try {\n const result = await client.readContract({\n address: config.pol.beraChef,\n abi: beraChefAbi,\n functionName: \"valRewardAllocator\",\n args: [pubKey],\n });\n if (result === zeroAddress) {\n return null;\n }\n return result as ValidatorRewardAllocatorAddress;\n } catch (e) {\n console.log(\"getValidatorRewardAllocatorAddress:\", e);\n throw e;\n }\n}\n","import useSWR from \"swr\";\nimport { type Address, keccak256 } from \"viem\";\n\nimport type { ApiValidatorFragment } from \"@berachain/graphql/pol/api\";\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { beaconDepositAbi } from \"~/abi/pol/beaconDeposit\";\nimport { beraChefAbi } from \"~/abi/pol/beraChef\";\nimport { bgtAbi } from \"~/abi/pol/bgt\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport const useOnChainValidator = (\n { pubkey }: { pubkey: Address },\n options: DefaultHookOptions,\n): DefaultHookReturnType<Partial<ApiValidatorFragment>> => {\n const publicClient = usePublicClient();\n const QUERY_KEY = pubkey ? ([\"useOnChainValidator\", pubkey] as const) : null;\n const isEnabled = options.opts?.isEnabled ?? true;\n const swrResponse = useSWR(\n isEnabled && publicClient ? QUERY_KEY : null,\n async ([, pubkey]) => {\n assertPublicClient(publicClient);\n\n const { config } = parseBaseArgs({\n chainId: publicClient.chain.id,\n });\n\n const [operator, boostees, _rewardAllocation] = await Promise.all([\n publicClient.readContract({\n address: config.depositContract,\n abi: beaconDepositAbi,\n functionName: \"getOperator\",\n args: [pubkey],\n }),\n publicClient?.readContract({\n address: config.tokens.bgt,\n abi: bgtAbi,\n functionName: \"boostees\",\n args: [pubkey],\n }),\n publicClient.readContract({\n address: config.pol.beraChef,\n abi: beraChefAbi,\n functionName: \"getActiveRewardAllocation\",\n args: [pubkey],\n }),\n ]);\n\n return {\n id: keccak256(pubkey),\n pubkey,\n operator,\n votingPower: Number(boostees),\n } as Partial<ApiValidatorFragment>;\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getStakingPoolBatch } from \"~/actions/validators/getStakingPoolBatch\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport const useStakingPoolBatch = ({\n valPubKey,\n options,\n}: {\n valPubKey: Address;\n options?: DefaultHookOptions;\n}): DefaultHookReturnType<number | undefined> => {\n const publicClient = usePublicClient();\n const isEnabled = options?.opts?.isEnabled ?? true;\n const QUERY_KEY =\n isEnabled && publicClient && valPubKey\n ? ([\"useStakingPoolBatch\", valPubKey] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, valPubKey]) => {\n assertPublicClient(publicClient);\n\n return await getStakingPoolBatch({\n client: publicClient,\n valPubKey,\n });\n },\n {\n refreshInterval: POLLING.FAST,\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport {\n GetUserValidatorInformation,\n type GetUserValidatorInformationQuery,\n type GetUserValidatorInformationQueryVariables,\n} from \"@berachain/graphql/pol/subgraph\";\nimport { useBeraWallet } from \"@berachain/wagmi/hooks\";\n\nimport { getApolloClient } from \"~/actions/clients/getApolloClient\";\n\nexport const useSubgraphUserValidators = ({\n account: _account,\n}: {\n account?: Address;\n} = {}) => {\n const { address: account } = useBeraWallet();\n\n const queriedAccount = _account ?? account;\n const QUERY_KEY = queriedAccount\n ? ([\"useSubgraphUserValidators\", queriedAccount] as const)\n : null;\n return useSWR(QUERY_KEY, async ([, account]) => {\n const bgtClient = getApolloClient(\"pol.subgraph\", {});\n const { data } = await bgtClient.query<\n GetUserValidatorInformationQuery,\n GetUserValidatorInformationQueryVariables\n >({\n query: GetUserValidatorInformation,\n variables: { address: account },\n });\n\n return data.userValidatorInformations;\n });\n};\n","import useSWR from \"swr\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport {\n getUserActiveValidators,\n type ValidatorWithUserBoost,\n} from \"~/actions/validators/getUserActiveValidators\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\n\nexport interface UseUserActiveValidatorsResponse\n extends DefaultHookReturnType<ValidatorWithUserBoost[] | undefined> {}\n\nexport const useUserActiveValidators = (\n options?: DefaultHookOptions,\n): UseUserActiveValidatorsResponse => {\n const { address: account } = useBeraWallet();\n const publicClient = usePublicClient();\n const QUERY_KEY =\n publicClient && account\n ? ([\"useUserActiveValidators\", account] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, account]) => {\n return await getUserActiveValidators({\n account,\n publicClient,\n });\n },\n {\n ...options,\n refreshInterval: options?.opts?.refreshInterval ?? POLLING.SLOW,\n keepPreviousData: true,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse?.mutate?.(),\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport {\n getUserBoostsOnValidator,\n type UserBoostsOnValidator,\n} from \"~/actions/validators/getUserBoostsOnValidator\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { DefaultHookReturnType } from \"~/types\";\n\nexport const useUserBoostsOnValidator = ({\n pubkey,\n ...args\n}: {\n pubkey: Address | undefined;\n account?: Address;\n}): DefaultHookReturnType<UserBoostsOnValidator> => {\n const { address: connectedAccount } = useBeraWallet();\n\n const publicClient = usePublicClient();\n const account = args.account ?? connectedAccount;\n\n const QUERY_KEY =\n account && pubkey\n ? ([\"useUserBoostsOnValidator\", pubkey, account] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, pubkey, account]) => {\n return await getUserBoostsOnValidator({\n account,\n pubkey: pubkey!,\n publicClient,\n });\n },\n {\n refreshInterval: POLLING.NORMAL,\n },\n );\n\n return { ...swrResponse, refresh: () => swrResponse.mutate() };\n};\n","import { useCallback, useMemo } from \"react\";\nimport * as Sentry from \"@sentry/nextjs\";\nimport useSWR from \"swr\";\n\nimport { useBeraWallet } from \"@berachain/wagmi/hooks\";\n\nimport { getRewardProofsByValidator } from \"~/actions/pol/getRewardProofsByValidator\";\nimport { getUserClaimableIncentives } from \"~/actions/pol/getUserClaimableIncentives\";\nimport { POLLING } from \"~/enum\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type { BribeBoostRewardProof, DefaultHookReturnType } from \"~/types\";\nimport { formatIncentivesTokenMap } from \"~/utils/formatIncentivesTokenMap\";\nexport interface UseUserClaimableIncentivesReturnType\n extends DefaultHookReturnType<BribeBoostRewardProof[]> {\n tokenMap?: Set<string> | undefined;\n}\n\nexport const useUserClaimableIncentives =\n (): UseUserClaimableIncentivesReturnType => {\n const { address: account } = useBeraWallet();\n\n const REWARDS_QUERY_KEY = account\n ? ([\"useUserClaimableIncentives\", account] as const)\n : null;\n\n const allRewardsResponse = useSWR(\n REWARDS_QUERY_KEY,\n async ([, account]) => {\n if (!account) {\n throw new BeraError({\n message: \"useUserClaimableIncentives needs a logged in account\",\n level: \"error\",\n });\n }\n\n // Get all reward tokens and all claimable validator associated with the account\n return await getUserClaimableIncentives({\n account,\n });\n },\n {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n revalidateIfStale: false,\n refreshInterval: POLLING.SLOW,\n },\n );\n\n const allRewards = allRewardsResponse?.data;\n const tokenMap = useMemo(() => {\n // Return empty set if no incentives data or still loading\n if (!allRewards) {\n return undefined;\n }\n\n // If the data is not an array, capture an error\n if (!Array.isArray(allRewards)) {\n Sentry.captureException(\n new BeraError({\n message: \"Incorrect aggregated incentives data receieved.\",\n level: \"error\",\n }),\n {\n extra: {\n allRewards,\n account: account,\n },\n },\n );\n return undefined;\n }\n\n return formatIncentivesTokenMap(allRewards);\n }, [allRewards, account]);\n\n const QUERY_KEY =\n account && allRewards\n ? ([\"useUserClaimableIncentives\", account, allRewards] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, account, allRewards]) => {\n if (!account) {\n throw new InvalidArgumentError({\n property: \"account\",\n value: account,\n expected: \"Address\",\n });\n }\n\n // Return empty set if no incentives data or still loading\n if (!allRewards) {\n return [];\n }\n\n if (!Array.isArray(allRewards)) {\n // If the data is unexpected, throw an error\n throw new InvalidArgumentError({\n message:\n \"Incorrect aggregated incentives data receieved to calculate proofs.\",\n property: \"allRewards\",\n value: allRewards,\n expected: \"Array\",\n level: \"error\",\n });\n }\n\n const validatorsSet = new Set(allRewards.map((item) => item.validator));\n const validatorAddresses = Array.from(validatorsSet);\n\n // Get total count of rewards for each validator in increments of MAX_PROOFS_SIZE_PER_INCENTIVE_CLAIM\n return await Promise.all(\n validatorAddresses.map(async (validator) => {\n const proofsData = await getRewardProofsByValidator({\n account: account,\n validator: validator as `0x${string}`,\n page: 1,\n perPage: 10_000,\n });\n\n return {\n ...proofsData,\n validator: validator,\n };\n }),\n );\n },\n {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n revalidateIfStale: false,\n refreshInterval: POLLING.SLOW,\n },\n );\n\n const refresh = useCallback(() => {\n allRewardsResponse?.mutate();\n swrResponse?.mutate();\n }, [allRewardsResponse, swrResponse]);\n\n return {\n ...swrResponse,\n isLoading: allRewardsResponse?.isLoading || swrResponse?.isLoading,\n tokenMap,\n refresh,\n };\n };\n","import type { BribeBoostRewardItem } from \"~/types/bribe-boost\";\n\nexport const formatIncentivesTokenMap = (\n allRewards: BribeBoostRewardItem[],\n) => {\n const tokenMap = new Set<string>();\n\n allRewards.forEach((item: BribeBoostRewardItem) => {\n if (Array.isArray(item.rewards)) {\n item.rewards.forEach((reward) => {\n if (reward.token) {\n tokenMap.add(reward.token);\n }\n });\n }\n });\n\n return tokenMap;\n};\n","import useSWRImmutable from \"swr/immutable\";\nimport type { Address } from \"viem\";\n\nimport { getUserStakingPositions } from \"~/actions/validators/getUserStakingPositions\";\n\n/**\n * Hook to fetch and manage user staking positions for validators\n *\n * This hook retrieves staking positions for a given account and optionally filters\n * by a specific validator address.\n *\n * @param params - Configuration parameters for the hook\n * @param params.account - The user's wallet address to fetch staking positions for\n * @param params.validatorAddress - Optional validator address to filter positions by\n *\n *\n * @example\n * ```tsx\n * // Fetch all staking positions for a user\n * const { data, isLoading, error } = useUserStakingPositions({\n * account: userAddress\n * });\n *\n * // Fetch staking positions for a specific validator\n * const { data, isLoading, error } = useUserStakingPositions({\n * account: userAddress,\n * validatorAddress: \"0x1234...\"\n * });\n * ```\n */\nexport const useUserStakingPositions = ({\n account,\n validatorAddress,\n}: {\n account: Address | undefined;\n validatorAddress?: Address;\n}) => {\n const queryClient = account\n ? ([\"useUserStakingPositions\", account, validatorAddress] as const)\n : null;\n const swrResponse = useSWRImmutable(\n queryClient,\n async ([_, account, validatorAddress]) => {\n const userStakingPolls = await getUserStakingPositions(account);\n if (validatorAddress) {\n return userStakingPolls.filter(\n (pool) =>\n pool.validatorAddress.toLowerCase() ===\n validatorAddress.toLowerCase(),\n );\n }\n return userStakingPolls;\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n};\n","import { type Address, keccak256 } from \"viem\";\n\nimport type { GqlValidatorDynamicData } from \"@berachain/graphql/dex/api\";\nimport type { ApiValidatorFragment } from \"@berachain/graphql/pol/api\";\n\nimport type { DefaultHookOptions } from \"~/types\";\nimport { useApiValidator } from \"./useApiValidator\";\nimport { useOnChainValidator } from \"./useOnChainValidator\";\n\nexport function useValidator(\n { pubkey }: { pubkey: Address },\n options: DefaultHookOptions,\n) {\n const {\n data: { validator: indexerValidator, uptime } = {},\n isLoading: isIndexerValidatorLoading,\n error: indexerValidatorError,\n } = useApiValidator(keccak256(pubkey), options);\n\n const {\n data: onChainValidator,\n isLoading: isOnChainValidatorLoading,\n error: onChainValidatorError,\n } = useOnChainValidator({ pubkey }, options);\n\n return {\n data: {\n uptime,\n validator:\n indexerValidator || onChainValidator\n ? ({\n ...indexerValidator,\n ...onChainValidator,\n operator:\n onChainValidator?.operator ?? indexerValidator?.operator,\n dynamicData: {\n activeBoostAmount:\n onChainValidator?.dynamicData?.activeBoostAmount ??\n indexerValidator?.dynamicData?.activeBoostAmount ??\n \"\",\n queuedBoostAmount:\n indexerValidator?.dynamicData?.queuedBoostAmount ?? \"\",\n usersActiveBoostCount:\n indexerValidator?.dynamicData?.usersActiveBoostCount ?? 0,\n usersQueuedBoostCount:\n indexerValidator?.dynamicData?.usersQueuedBoostCount ?? 0,\n allTimeDistributedBGTAmount:\n indexerValidator?.dynamicData?.allTimeDistributedBGTAmount ??\n \"0\",\n rewardRate:\n onChainValidator?.dynamicData?.rewardRate ??\n indexerValidator?.dynamicData?.rewardRate ??\n \"\",\n stakedBeraAmount:\n indexerValidator?.dynamicData?.stakedBeraAmount ?? \"\",\n lastDayDistributedBGTAmount:\n indexerValidator?.dynamicData?.lastDayDistributedBGTAmount ??\n \"\",\n activeBoostAmountRank:\n indexerValidator?.dynamicData?.activeBoostAmountRank ?? 0,\n\n boostApr: (indexerValidator?.dynamicData?.boostApr ??\n // todo: remove 'as' once BE has migrated types\n 0) as GqlValidatorDynamicData[\"boostApr\"],\n commissionOnIncentives:\n indexerValidator?.dynamicData?.commissionOnIncentives ?? 0,\n },\n id: (onChainValidator?.id ?? indexerValidator?.id) as Address,\n pubkey: (onChainValidator?.pubkey ??\n indexerValidator?.pubkey) as Address,\n metadata:\n onChainValidator?.metadata ?? indexerValidator?.metadata,\n rewardAllocationWeights:\n onChainValidator?.rewardAllocationWeights ??\n indexerValidator?.rewardAllocationWeights ??\n [],\n } satisfies ApiValidatorFragment)\n : null,\n },\n isLoading: isIndexerValidatorLoading || isOnChainValidatorLoading,\n error: indexerValidatorError || onChainValidatorError,\n };\n}\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport type { GetValidatorAnalyticsQuery } from \"@berachain/graphql/pol/subgraph\";\n\nimport { getValidatorAnalytics } from \"~/actions/validators/getValidatorAnalytics\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { DefaultHookReturnType } from \"~/types\";\n\nexport function useValidatorAnalytics({\n pubkey,\n dayRange,\n}: {\n pubkey: Address | undefined;\n dayRange: number;\n}): DefaultHookReturnType<GetValidatorAnalyticsQuery> {\n const QUERY_KEY =\n pubkey && dayRange\n ? ([\"useValidatorAnalytics\", pubkey, dayRange] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, pubkey, dayRange]) => {\n return await getValidatorAnalytics({\n pubkey: pubkey,\n dayRange,\n });\n },\n {\n refreshInterval: POLLING.SLOW,\n },\n );\n\n return { ...swrResponse, refresh: () => swrResponse.mutate() };\n}\n","import useSWR from \"swr\";\nimport type { Address, PublicClient } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getValidatorCommission } from \"~/actions/validators/getValidatorCommission\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport const useValidatorCommission = (\n pubKey: Address,\n options?: DefaultHookOptions,\n): DefaultHookReturnType<number | undefined | null> => {\n const publicClient = usePublicClient();\n const QUERY_KEY =\n publicClient && pubKey\n ? ([\"useValidatorCommission\", pubKey] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, pubKey]) => {\n return await getValidatorCommission({\n client: publicClient as PublicClient,\n pubKey: pubKey,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import type { ApiValidatorMinimalFragment } from \"@berachain/graphql/pol/api\";\n\nimport { getValidatorEstimatedBgtPerYear } from \"~/actions/validators/getValidatorEstimatedBgtPerYear\";\nimport { useBlockTime } from \"~/contexts/block-time-provider\";\nimport { usePollGlobalData } from \"~/hooks/pol/usePollGlobalData\";\n\nexport const useValidatorEstimatedBgtPerYear = (\n validator: ApiValidatorMinimalFragment,\n): { data: number | undefined; isLoading: boolean } => {\n const { data: globalData, isLoading } = usePollGlobalData();\n\n const blockTime = useBlockTime();\n\n return {\n data: globalData\n ? getValidatorEstimatedBgtPerYear(\n validator,\n Number(globalData?.totalStakedBeraAmount),\n blockTime,\n )\n : undefined,\n isLoading,\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport {\n getValidatorQueuedCommission,\n type ValidatorQueuedCommission,\n} from \"~/actions/validators/getValidatorQueuedCommission\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport function useValidatorQueuedCommission(\n pubKey: Address,\n options?: DefaultHookOptions,\n): DefaultHookReturnType<ValidatorQueuedCommission | undefined | null> {\n const publicClient = usePublicClient();\n const QUERY_KEY =\n publicClient && pubKey\n ? ([\"useValidatorQueuedCommission\", pubKey] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, pubKey]) => {\n assertPublicClient(publicClient);\n return await getValidatorQueuedCommission({\n client: publicClient,\n pubKey,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","import useSWR from \"swr\";\nimport type { Address, PublicClient } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport {\n getValidatorQueuedOperatorAddress,\n type ValidatorQueuedOperatorAddress,\n} from \"~/actions/validators/getValidatorQueuedOperatorAddress\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport const useValidatorQueuedOperatorAddress = (\n pubKey: Address,\n options?: DefaultHookOptions,\n): DefaultHookReturnType<ValidatorQueuedOperatorAddress | undefined> => {\n const publicClient = usePublicClient();\n const QUERY_KEY =\n publicClient && pubKey\n ? ([\"useValidatorQueuedOperatorAddress\", pubKey] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, pubKey]) => {\n return await getValidatorQueuedOperatorAddress({\n client: publicClient as PublicClient,\n pubKey,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\nimport type { Address, PublicClient } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getValidatorQueuedRewardAllocation } from \"~/actions/validators/getValidatorQueuedRewardAllocation\";\nimport type { ValidatorRewardAllocation } from \"~/actions/validators/getValidatorRewardAllocation\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types\";\n\nexport const useValidatorQueuedRewardAllocation = (\n pubKey: Address,\n options?: DefaultHookOptions,\n): DefaultHookReturnType<ValidatorRewardAllocation | undefined> => {\n const publicClient = usePublicClient();\n const QUERY_KEY =\n publicClient && pubKey\n ? ([\"useValidatorQueuedRewardAllocation\", pubKey] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, pubKey]) => {\n return await getValidatorQueuedRewardAllocation({\n client: publicClient as PublicClient,\n pubKey,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n};\n","import useSWR from \"swr\";\nimport type { Address, PublicClient } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getValidatorRewardAllocation } from \"~/actions/validators/getValidatorRewardAllocation\";\nimport type { DefaultHookOptions } from \"~/types\";\n\nexport function useValidatorRewardAllocation(\n pubKey: Address,\n options?: DefaultHookOptions,\n) {\n const publicClient = usePublicClient();\n const QUERY_KEY =\n publicClient && pubKey\n ? ([\"useValidatorRewardAllocation\", pubKey] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, pubKey]) => {\n return await getValidatorRewardAllocation({\n client: publicClient as PublicClient,\n pubKey,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n"],"mappings":"0yCAAA,OAAOA,OAAY,MAEnB,OAAS,mBAAAC,OAAuB,yBAMzB,IAAMC,GAAwB,CACnC,CACE,aAAAC,EACA,aAAAC,EACA,aAAAC,CACF,EACAC,IACG,CACH,IAAMC,EAAeC,GAAgB,CAAE,QAASH,CAAa,CAAC,EACxDI,EAAcC,GAClBH,GAAgBJ,GAAgBC,EAC5B,CAAC,wBAAyBD,EAAcC,EAAcC,CAAY,EAClE,KACJ,MAAO,CAACM,EAAGR,EAAcC,CAAY,KACnCQ,EAAmBL,CAAY,EAExBM,GAAmB,CACxB,aAAAV,EACA,aAAAC,EACA,aAAAG,CACF,CAAC,GAEH,CACE,GAAGD,GAAS,IACd,CACF,EAEA,MAAO,CACL,GAAGG,EACH,QAAS,IAAM,CACbA,EAAY,OAAO,CACrB,CACF,CACF,ECzCA,OAAS,WAAAK,OAAe,QACxB,OAAOC,MAAuC,MAC9C,OAA0C,cAAAC,GAAY,eAAAC,OAAmB,OAEzE,OAAS,kBAAAC,OAAsB,6BAE/B,OAAS,iBAAAC,GAAe,mBAAAC,OAAuB,yBCN/C,OAEE,YAAAC,GAEA,QAAAC,GACA,YAAAC,GACA,SAAAC,GACA,eAAAC,OACK,qCACP,UAAYC,OAAY,iBACxB,OAAS,sBAAAC,GAAoB,eAAAC,GAAa,eAAAC,OAAmB,OAE7D,OAAS,kBAAAC,OAAsB,oBAC/B,OAAS,WAAAC,OAAe,6BAiBxB,IAAMC,GAAmB,IACnBC,GAAwB,IACxBC,GAAWC,GAAS,QAEpBC,GAAN,cAA4BC,CAAe,CACzC,iBACA,gBAAkB,CAACC,GAAQ,QAASA,GAAQ,OAAO,EAC1C,IAAMC,GAAe,KAAK,OAAO,GAAG,EACpC,KAAO,UAKR,qBAAqBC,EAA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aultAddress","vaultChainId","options","publicClient","usePublicClient","swrResponse","useSWR","_","assertPublicClient","getConvertToAssets","useMemo","useSWR","parseUnits","zeroAddress","defaultChainId","useBeraWallet","usePublicClient","Slippage","Swap","SwapKind","Token","TokenAmount","Sentry","decodeFunctionData","formatEther","zeroAddress","getUriFromLink","ChainId","DEFAULT_DEADLINE","STALE_PRICE_THRESHOLD","swapKind","SwapKind","BexAggregator","BaseAggregator","ChainId","getUriFromLink","address","isToken","priceImpact","onChainAmount","sorPaths","sorAmount","queryData","deltaFromSorAmount","formatEther","error","BeraError","p","args","balancerApi","BalancerApi","tokenIn","tokenOut","tokenInDecimals","tokenOutDecimals","amount","slippage","account","zeroAddress","publicClient","assertPublicClient","InvalidArgumentError","wberaIsBera","tokenInV3","Token","tokenOutV3","tokenAmount","TokenAmount","RequestError","swap","Swap","queryOutput","formattedQuote","callData","Slippage","params","functionName","decodeFunctionData","balancerVaultAbi","bex","ChainId","RedeemBgtAggregator","BaseAggregator","ChainId","tokenIn","amount","isToken","InvalidArgumentError","bgtRedeem","zeroAddress","ChainId","EnsoAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","url","quote","inputData","outputData","aggregatorData","aggregatorsRouterAbi","enso","zeroAddress","ChainId","BASE_URL","FlyAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","url","params","quoteData","formattedQuote","txUrl","txParams","txData","inputData","outputData","aggregatorData","aggregatorsRouterAbi","isToken","fly","formatUnits","parseUnits","zeroAddress","ChainId","HaikuAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","tokenInDecimals","tokenOutDecimals","aggregatorsFeeBps","proxyAggregatorsThroughVercel","referrer","rewardVault","BeraError","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","quoteBody","formatUnits","proxyPath","quoteData","formattedQuote","parseUnits","solveData","inputData","outputData","aggregatorData","aggregatorsRouterAbi","haiku","BigNumber","formatUnits","ChainId","_getPreviewMethod","isMint","HoneyNativeAggregator","_HoneyNativeAggregator","BaseAggregator","ChainId","getHoneyToken","tokenIn","tokenOut","honeyNativeState","args","isToken","isRedeem","coll","amount","publicClient","account","collaterals","InvalidArgumentError","assertPublicClient","BeraError","hubOrderedCollaterals","collateral","honeyVaultBalances","isBasketMode","getHoneyVaultsBalance","isBasketModeEnabled","collateralVaultBalance","collateralIdx","honeyFormattedAmountIn","formatUnits","quoteParams","quoteData","getHoneyPreview","honeyQuote","collateralsQuote","BigNumber","payload","getSwapPayload","honeyNative","zeroAddress","ChainId","KyberSwapAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","isTokenInNative","isTokenOutNative","tokenInAddress","tokenOutAddress","inputAmountAfterFees","url","routeData","formattedQuote","buildRouteBody","params","buildUrl","key","value","buildData","inputData","outputData","aggregatorData","aggregatorsRouterAbi","kyberswap","zeroAddress","ChainId","OogaboogaAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","params","quote","formattedQuote","inputData","outputData","aggregatorData","aggregatorsRouterAbi","oogabooga","zeroAddress","ChainId","OpenOceanAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","tokenInDecimals","publicClient","rewardVault","assertPublicClient","InvalidArgumentError","inputAmountAfterFees","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","gasPrice","quoteParams","quoteResponse","quoteData","isNotFound","message","RequestError","formattedQuote","inputData","outputData","aggregatorData","aggregatorsRouterAbi","openOcean","ChainId","WBeraAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","isToken","BeraError","isWrap","wberaAbi","wberaSwap","AGGREGATORS","oogabooga","fly","kyberswap","openOcean","haiku","enso","bex","honeyNative","USE_AGGREGATORS_QUOTES_QUERY_KEY","getQueryKey","name","account","args","feeBps","options","activeAggregators","honeyNativeState","bgtRedeem","isToken","defaultChainId","tokenIn","tokenOut","tokenInDecimals","tokenOutDecimals","amount","slippage","referrer","rewardVault","parsedAmount","parseUnits","isEnabledOnConfig","getQueryFn","aggregator","publicClient","proxyAggregatorsThroughVercel","aggregatorsFeeBps","honeyCollaterals","useAggregatorsQuotes","useBeraWallet","useBeraFlag","usePublicClient","useAggregatorsRouterFeeBps","collaterals","honeyProtocol","isWrapOrUnwrap","isBgtRedeem","isHoneyNative","useMemo","HoneyNativeAggregator","isNativeSwap","config","parseBaseArgs","isMAEnabled","zeroAddress","swrOptions","err","key","revalidate","revalidateOpts","BeraError","BaseAggregator","RequestError","seconds","oogaBogaResult","useSWR","flyResult","kyberswapResult","openOceanResult","haikuResult","ensoResult","bexProtocol","useBexStatus","bexResult","wberaSwapResult","wberaSwap","bgtRedeemResult","honeyResult","results","i","error","result","loadingAggregatorsNames","r","quotes","data","isLoading","useSWRImmutable","zeroAddress","usePublicClient","useAggregatorsRouterFeeBps","publicClient","usePublicClient","config","parseBaseArgs","swrResponse","useSWRImmutable","zeroAddress","aggregatorsRouter","fee","aggregatorsRouterAbi","useSWR","useAllUserPoolsQueryKey","query","useAllUserPools","options","swrResponse","useSWR","_","params","getAllPools","useSWR","isAddress","useApiPoolQueryKey","poolId","account","useApiPool","res","useSWR","isAddress","InvalidArgumentError","getApiPool","useMemo","PoolType","useSWRImmutable","formatUnits","keccak256","parseUnits","zeroAddress","GetDedupedSubgraphPools","PoolType","formatUnits","sortTokensByAddress","tokens","a","b","generatePoolName","token","generatePoolSymbol","weights","poolType","poolTypeString","index","weight","DEFAULT_WEIGHTS_DUPLICATION_THRESHOLD","OracleMode","createStablePoolArgs","poolCreationHelper","poolCreateTokens","initialLiquidityTokens","swapFeePercentage","salt","poolName","poolSymbol","owner","amplification","oracles","message","actionType","gasLimit","DEFAULT_METAMASK_GAS_LIMIT","sortedPoolCreateAddresses","token","a","b","combinedData","address","liquidityToken","isToken","amountIn","parseUnits","oracle","rateProvider","zeroAddress","cacheDuration","sortedAmountsIn","data","sortedRateProviders","sortedCacheDurations","nativeTokenIndex","value","joinWBERAPoolWithBERA","balancerPoolCreationHelperAbi","createWeightedPoolArgs","normalizedWeights","createPoolTokens","joinPoolTokens","sortedWeights","index","item","useCreatePool","poolType","swapFee","weightsDuplicationThreshold","baseArgs","dupePool","errorLoadingPools","isLoadingPools","useSWRImmutable","bexSubgraphClient","getApolloClient","tokensSorted","wrapNativeTokens","GetDedupedSubgraphPools","pool","PoolType","formatUnits","generatedPoolName","generatedPoolSymbol","useMemo","generatePoolName","generatePoolSymbol","createPoolArgs","keccak256","chainConfig","parseBaseArgs","useSWR","usePublicClient","BigNumber","erc20Abi","formatUnits","GetExploitedTokens","BEX_EXPLOITED_TOKEN_THRESHOLD","getIsTokenExploited","token","publicClient","args","bexSubgraphClient","getApolloClient","totalSupply","erc20Abi","balanceThreshold","BigNumber","formatUnits","data","GetExploitedTokens","useExploitedTokensQueryKey","tokens","filteredTokens","token","useExploitedTokens","QUERY_KEY","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","getIsTokenExploited","acc","curr","idx","useSWR","useGlobalLiquidityAndSwapVolume","response","useSWR","getGlobalLiquidityAndSwapVolume","useEffect","useState","PoolType","DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT","useLiquidityMismatch","currentStep","tokenPrices","isLoadingTokenPrices","tokens","weights","weightsError","poolType","liquidityMismatchTolerancePercent","oracles","liquidityMismatchInfo","setLiquidityMismatchInfo","useState","useEffect","token","oracle","totalLiquidityUSD","tokenUSDAmounts","numTokens","tokenUSDPrices","wrapNativeTokens","tokenPriceUSD","tokenAmountUSD","price","PoolType","normalizedUSDPrices","priceUSD","value","totalLossUSD","expectedPerTokenLiquidityUSD","index","weightProportion","expectedValueUSD","isTotalLoss","totalLossPercentage","BigNumber","formatEther","isAddressEqual","useSWR","isAddress","zeroAddress","useBeraWallet","usePublicClient","useSWRImmutable","isAddress","zeroAddress","usePublicClient","useRewardVaultFromToken","tokenAddress","isEnabled","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","assertPublicClient","config","parseBaseArgs","res","rewardVaultFactoryAbi","zeroAddress","useRewardVaultBalanceFromStakingToken","stakingToken","_rewardVaultAddress","options","account","useBeraWallet","publicClient","usePublicClient","isEnabled","rewardVaultAddress","error","mutateRewardVaultAddress","isLoadingRewardVaultAddress","useRewardVaultFromToken","swrResponse","useSWR","isAddress","assertPublicClient","zeroAddress","balance","rewardVaultAbi","useSWR","erc20Abi","formatEther","formatUnits","isAddress","zeroAddress","defaultChainId","useBeraWallet","usePublicClient","useSWRImmutable","isAddress","zeroAddress","usePublicClient","useTokenInformation","args","options","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","_","address","isToken","zeroAddress","beraToken","assertPublicClient","getTokenInformation","usePollBalance","addressString","owner","chainId","defaultChainId","options","address","isToken","zeroAddress","publicClient","usePublicClient","account","useBeraWallet","assetOwner","QUERY_KEY","isAddress","tokenInformation","isLoadingTokenInformation","useTokenInformation","isNativeToken","isLoading","data","error","rest","useSWR","assertPublicClient","erc20Abi","formattedBalance","formatEther","formatUnits","tokenBalance","beraToken","useLpPosition","pool","vaultAddress","options","userPosition","rest","usePollBalance","userVaultTokenBalance","refreshVaultDeposit","useRewardVaultBalanceFromStakingToken","actualPoolShares","tvlInUsd","lpTokenPrice","tokenRatioPerLp","token","tokenRatio","tr","isAddressEqual","userBalance","BigNumber","price","formatEther","useMemo","ZERO_ADDRESS","BigNumber","isAddressEqual","parseUnits","useSWR","useBeraWallet","usePublicClient","usePollAllowances","args","options","publicClient","usePublicClient","account","useBeraWallet","QUERY_KEY","swrResponse","useSWR","tokens","spender","getAllowances","calculateMaxAmountIn","amount","decimals","slippage","amountInWei","parseUnits","slippageInWei","useMultipleTokenApprovalsWithSlippage","tokenInput","spender","tokens","useMemo","token","ZERO_ADDRESS","BigNumber","allowances","refresh","isLoading","usePollAllowances","allowance","isAddressEqual","BeraError","maxAmountIn","useMemo","useSWRImmutable","formatUnits","isAddress","usePublicClient","useSWRImmutable","isAddress","usePublicClient","useMultipleTokenInformation","args","options","publicClient","usePublicClient","QUERY_KEY","swrResponse","useSWRImmutable","addresses","assertPublicClient","address","isAddress","tk","getTokenInformation","useSWR","useContext","useTokens","context","useContext","TokenContext","BeraError","useTokenCurrentPrices","addressIn","options","tokenList","useTokens","addresses","tk","isToken","token","QUERY_KEY","swrResponse","useSWR","getTokenCurrentPrices","useOnChainPoolDataQueryKey","args","address","isAddress","useOnChainPoolData","poolId","publicClient","usePublicClient","QUERY_KEY","poolData","error","isLoading","mutate","useSWRImmutable","getOnChainPool","tokenInformation","isTokenInformationLoading","useMultipleTokenInformation","tokenPrices","isTokenPricesLoading","useTokenCurrentPrices","useMemo","pool","token","idx","formatUnits","totalLiquidity","acc","tokenUSDPrice","useSWR","useBeraWallet","usePublicClient","usePollPoolCreationRelayerApproval","options","account","useBeraWallet","publicClient","usePublicClient","QUERY_KEY","swrResponse","useSWR","assertPublicClient","config","parseBaseArgs","balancerVaultAbi","useMemo","useSWR","useSubgraphPoolQueryKey","poolId","usePool","bexSubgraphPool","useSWR","getSubgraphPool","balancerApiPool","useApiPool","onChainPool","isOnChainPoolLoading","refreshOnChainPool","useOnChainPoolData","useMemo","merge","useSWRImmutable","usePoolEvents","poolId","typeInArray","useSWRImmutable","getPoolEvents","useSWR","usePoolHistoricalData","poolId","baseArgs","options","config","parseBaseArgs","swrResponse","useSWR","getPoolHistoricalData","useMemo","useSWR","useBeraWallet","usePoolsQueryKey","query","usePools","options","account","useBeraWallet","userPools","isUserPoolsLoading","mutateUserPools","useAllUserPools","pools","isPoolsLoading","mutatePools","useSWR","_","getAllPools","mergedPools","useMemo","userPoolsById","pool","pagination","useSWR","useBeraWallet","usePublicClient","useCallback","getPublicClient","useSWR","isAddress","parseUnits","berachainChainId","useBeraWallet","useConfig","ethAddress","zeroAddress","erc20Abi","ethAddress","getTransactionsFromBundle","fromAddress","amountIn","tokenIn","chainId","ensoClient","bundle","publicClient","transactions","approvalRequest","requiresApproval","getBendTransactionRequests","fromAddress","amountIn","tokenIn","loanToken","bendVault","rewardVault","chainId","ensoClient","destinationChainId","slippage","publicClient","InvalidArgumentError","zeroAddress","ethAddress","bundleActions","bundle","transactions","getTransactionsFromBundle","ethAddress","zeroAddress","getZapTransactionRequests","fromAddress","amountIn","tokenIn","tokenOut","chainId","ensoClient","destinationChainId","slippage","publicClient","InvalidArgumentError","zeroAddress","ethAddress","bundleAction","bundle","transactions","getTransactionsFromBundle","EnsoClient","appConfig","isProduction","getEnsoClient","useProxy","args","config","parseBaseArgs","EnsoClient","appConfig","Sentry","getChains","multicall","formatUnits","getEnsoUserToken","account","wagmiConfig","chainId","ensoClient","tokens","balance","formatUnits","tokenByChainId","a","balances","chainTokens","chainConfig","getChains","chain","multicallAddress","InvalidArgumentError","multicall","token","getBalanceCall","tokensWithBalances","index","initBeraError","flattenedBalances","result","b","aValue","useEnsoBalances","ensoClient","chainId","options","fromAddress","useBeraWallet","wagmiConfig","useConfig","isEnabled","isAddress","swrResponse","useSWR","getEnsoUserToken","useEnsoZap","getEnsoClient","tokens","refreshTokens","getZapTransactionRequests","useCallback","tokenIn","tokenOut","amount","slippage","assertAddress","assertDefined","publicClient","getPublicClient","assertPublicClient","rawAmount","parseUnits","berachainChainId","getBendTransactionRequests","loanToken","bendVault","rewardVault","useBendTransactionRequests","tokenIn","loanTokenAddress","loanTokenPrice","bendVault","rewardVault","amount","slippage","chainId","options","tokens","refreshTokens","useEnsoZap","dataForGas","errorForGas","useBendTransactionRequestsHelper","transactionValue","acc","transaction","nativeToken","token","isToken","nativeFee","swrResponse","fromAddress","useBeraWallet","getBendTransactionRequests","isEnabled","publicClient","usePublicClient","publicClientBeraChain","useSWR","InvalidArgumentError","response","amountOutObject","address","amountOut","supplyAmount","getConvertToAssets","priceImpact","computePriceImpact","useSWR","useZapTransactionRequests","tokenIn","tokenOut","amount","slippage","chainId","getZapTransactionRequests","refreshTokens","tokens","useEnsoZap","isEnabled","swrResponse","useSWR","assertDefined","assertAddress","assertAmount","useCallback","useEffect","useState","matter","encodeFunctionData","erc20Abi","parseAbiItem","toHex","hasAnyTruthyValues","obj","value","item","getProposalParams","proposal","currentTopic","onError","e","getBodyErrors","actions","action","idx","errors","checkProposalField","parsedSignatureAbi","parseAbiItem","input","index","v","encodeFunctionData","toHex","whiteList","beraChefAbi","rewardVaultAbi","erc20Abi","hasAnyTruthyValues","name","link","description","matter","actionMetadata","defaultAction","useCreateProposal","initialData","currentTopic","onError","proposal","setProposal","useState","useEffect","p","addProposalAction","useCallback","removeProposalAction","idx","actions","computeParamsAndErrors","getProposalParams","useSWRImmutable","formatUnits","useBeraWallet","usePublicClient","useSWRImmutable","usePublicClient","useProposalSnapshot","proposalId","publicClient","usePublicClient","useSWRImmutable","assertPublicClient","config","parseBaseArgs","governanceAbi","useGetPastVotes","args","account","useBeraWallet","publicClient","usePublicClient","wallet","snapshot","useProposalSnapshot","ts","useSWRImmutable","assertPublicClient","config","parseBaseArgs","votes","bgtAbi","formatUnits","useSWR","isAddress","useBeraWallet","usePublicClient","useHasVoted","proposalId","wallet","account","useBeraWallet","publicClient","usePublicClient","address","useSWR","isAddress","assertPublicClient","config","parseBaseArgs","governanceAbi","useSWR","usePublicClient","CANCELLER_ROLE","useIsCanceller","account","baseArgs","publicClient","usePublicClient","chainConfig","parseBaseArgs","useSWR","assertPublicClient","governanceTimelockAbi","CANCELLER_ROLE","useEffect","useMemo","useState","useSWRInfinite","Proposal_OrderBy","ProposalStatus","DEFAULT_PER_PAGE","fromUiStatusToSubgraphStatuses","status","ProposalStatus","usePollAllProposalsQueryKey","topic","args","subgraphPageSize","pageIndex","previousPageData","statuses","s","arr","usePollAllProposals","options","autoRefreshProposals","perPage","getKey","fetcher","key","where","orderBy","orderDirection","pageSize","text","getAllProposals","swr","useSWRInfinite","data","useMemo","flattened","p","a","b","Proposal_OrderBy","result","chunked","i","lastPage","hasMore","timestamp","setTimestamp","useState","useEffect","interval","shouldMutate","proposal","useEffect","useState","useSWR","ProposalStatus","usePublicClient","usePollProposal","proposalId","options","autoRefreshProposal","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","getProposalDetails","timestamp","setTimestamp","useState","useEffect","interval","ProposalStatus","useSWR","formatEther","usePublicClient","usePollProposalThreshold","governorAddress","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","votesThreshold","governanceAbi","formatEther","useSWRInfinite","DEFAULT_LIMIT","usePollProposalVotes","args","total","useSWRInfinite","usePollProposalVotesQueryKey","_key","page","getProposalVotes","pageIndex","useSWR","formatEther","useBeraWallet","usePublicClient","usePollUserDelegates","options","account","useBeraWallet","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","config","parseBaseArgs","delegate","currentVotes","bgtAbi","formatEther","useSWR","usePublicClient","useTransactionReceipt","useProposalFromTx","txHash","tx","useTransactionReceipt","publicClient","usePublicClient","useSWR","getProposalFromTx","useSWRImmutable","usePublicClient","ProposalStateMap","useProposalState","proposalId","governorAddress","publicClient","usePublicClient","useSWRImmutable","assertPublicClient","snapshot","governanceAbi","useSWR","usePublicClient","TimelockOperationState","useProposalTimelockState","proposalTimelockId","timelockAddress","publicClient","usePublicClient","useSWR","assertPublicClient","snapshot","governanceTimelockAbi","useSWR","usePublicClient","formatEther","getQuorum","at","publicClient","args","config","parseBaseArgs","assertPublicClient","quorum","governanceAbi","formatEther","useQuorum","at","isEnabled","now","publicClient","usePublicClient","QUERY_KEY","response","useSWR","getQuorum","useSWR","usePublicClient","useSWR","usePythLatestPrices","priceFeedMap","options","priceFeedIds","QUERY_KEY","useSWR","_","priceFeeds","getPythLatestPrices","useCappedGlobally","asset","amount","isMint","isBasketModeEnabled","options","publicClient","usePublicClient","priceFeedMap","flags","useHoneyConfig","latestPrices","usePythLatestPrices","QUERY_KEY","swrResponse","useSWR","_","isPythWrapperEnabled","assertPublicClient","getGlobalCapLimit","useSWR","usePublicClient","useCappedRelatively","asset","amount","isMint","isBasketModeEnabled","options","publicClient","usePublicClient","collateralList","referenceCollateral","useHoneyConfig","swrResponse","useSWR","_","collaterals","assertPublicClient","newAmount","coll","getRelativeCapLimit","isCapped","useSWR","usePublicClient","useCollateralWeights","collateralList","options","publicClient","usePublicClient","swrResponse","useSWR","_","assertPublicClient","getCollateralWeights","useMemo","BigNumber","useSWR","useBeraWallet","usePublicClient","useHoneyBalances","publicClient","usePublicClient","account","useBeraWallet","collateralList","useHoneyConfig","swrResponse","useSWR","_","assertPublicClient","tokenList","getHoneyToken","getWalletBalances","acc","balance","useSWR","usePublicClient","useHoneyVaultsBalance","options","publicClient","usePublicClient","collateralList","useHoneyConfig","swrResponse","useSWR","_","assertPublicClient","getHoneyVaultsBalance","useSWR","usePublicClient","useIsBadCollateralAsset","collateral","options","publicClient","usePublicClient","priceFeedMap","flags","useHoneyConfig","latestPrices","usePythLatestPrices","QUERY_KEY","swrResponse","useSWR","_","isPythWrapperEnabled","assertPublicClient","isBadCollateralAsset","getIsLiquidityLowerThan","lowerThan","vaultsBalances","state","collateralList","redeemedVaultBalance","vault","isLow","BigNumber","isLiquidityLowCollaterals","coll","vaultBalance","getRedeemMoreThanLiquidity","isRedeemMoreThanLiquidityCollaterals","amountToRedeem","getExceedingBalance","honeyBalances","args","config","parseBaseArgs","isMint","idx","amount","useHoneyAlerts","actionType","collaterals","fromAmount","toAmount","isBasketModeEnabled","data","useIsBadCollateralAsset","useHoneyConfig","isBlacklisted","isDepegged","isCappedGlobally","useCappedGlobally","isCappedRelatively","useCappedRelatively","useHoneyBalances","useHoneyVaultsBalance","redeemedCollateral","isLiquidityDepleted","isLowLiquidity","useMemo","isDepleted","isRedeemMoreThanLiquidity","isExceedingBalance","useSWR","useHoneyChartData","days","swrResponse","useSWR","_","getChartData","BigNumber","useSWR","useHoneyGlobalData","response","useSWR","getHoneyGlobalData","dailyVolume","acc","curr","BigNumber","useEffect","useReducer","formatUnits","defaultChainId","useSWR","usePublicClient","useIsBasketModeEnabled","state","options","publicClient","usePublicClient","priceFeedMap","flags","collateralList","useHoneyConfig","latestPrices","usePythLatestPrices","isMint","QUERY_KEY","swrResponse","useSWR","_","isPythWrapperEnabled","assertPublicClient","isBasketModeEnabled","defaultState","reducer","state","action","newFromAmount","newToAmount","preview","isMint","collateralsAmount","coll","idx","formatUnits","honey","isToken","defaultChainId","useHoneySwapState","collateralList","useHoneyConfig","dispatch","useReducer","initialState","isBasketModeEnabled","useIsBasketModeEnabled","useEffect","useSWRImmutable","usePublicClient","usePythUpdateFee","pythPriceFeedCalldata","tokenListLength","options","publicClient","usePublicClient","QUERY_KEY","data","getPythDefaultUpdateFee","isLoading","useSWRImmutable","_","assertPublicClient","getPythUpdateFee","useMemo","useBgtAprSimulation","args","useMemo","getBgtAprSimulation","useSWR","formatEther","useBeraWallet","usePublicClient","useBgtUnstakedBalance","options","account","useBeraWallet","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","config","parseBaseArgs","bgtBalance","bgtAbi","formatEther","useSWR","formatUnits","useBeraWallet","usePublicClient","useClaimableFees","account","useBeraWallet","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","config","parseBaseArgs","vaultReward","getUserVaultsReward","formatUnits","useSWR","GetStakeBeraVaultEarningsByOwner","useBeraWallet","useEarnedStakedBeraVault","receiptToken","opt","account","useBeraWallet","QUERY_KEY","swrResponse","useSWR","_","getApolloClient","GetStakeBeraVaultEarningsByOwner","GqlRewardVaultOrderBy","GqlRewardVaultOrderDirection","useSWR","usePublicClient","useRewardVaultsQueryKey","filter","onChainIncentives","useRewardVaults","args","options","QUERY_KEY","publicClient","usePublicClient","swrResponse","useSWR","getRewardVaults","useHighestVaultsAPR","where","isEnabled","swrResponse","useRewardVaults","GqlRewardVaultOrderBy","GqlRewardVaultOrderDirection","useSWR","usePublicClient","usePollGlobalData","options","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","getGlobalData","useSWRImmutable","usePollMarketsQueryKey","usePollMarkets","options","QUERY_KEY","swrResponse","useSWRImmutable","getMarkets","useSWRImmutable","isAddress","usePublicClient","useQueuedBeraUnlock","receiptTokenAddress","account","version","options","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","assertPublicClient","getSWBeraWithdrawal","useSWR","isAddress","usePublicClient","useRewardTokenToBeraRate","address","opt","QUERY_KEY","publicClient","usePublicClient","useSWR","_","isAddress","InvalidArgumentError","assertPublicClient","getRewardTokenToBeraRate","useSWR","useSWR","erc20Abi","formatUnits","isAddress","usePublicClient","erc20Abi","formatUnits","getStakingTokenInformation","address","publicClient","assertPublicClient","decimals","name","symbol","totalSupply","erc20Abi","formatUnits","useOnChainRewardVaultQueryKey","address","isAddress","useOnChainRewardVault","opt","publicClient","usePublicClient","isEnabled","QUERY_KEY","useSWR","assertPublicClient","config","parseBaseArgs","stakingTokenAddress","getRewardVaultStakingToken","incentives","isWhitelisted","stakingTokenAmount","getRewardVaultIncentives","beraChefAbi","erc20Abi","stakingToken","incentiveTokens","getStakingTokenInformation","add","getTokenInformation","formatUnits","incentive","idx","useRewardVaultQueryKey","address","useRewardVault","id","options","QUERY_KEY","swrResponse","useSWR","_","getRewardVault","isOnChainEnabled","onChainRewardVault","useOnChainRewardVault","useSWR","usePublicClient","useRewardVaultIncentives","address","stakingToken","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","getRewardVaultIncentives","useSWR","usePublicClient","useRewardVaultRewards","address","options","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","getRewardVaultRewards","useSWR","useStakedBeraSnapshots","range","swrResponse","useSWR","getStakedBeraSnapshots","useSWR","useBeraWallet","usePublicClient","useUserVaultInfo","args","options","account","useBeraWallet","publicClient","usePublicClient","QUERY_KEY","swrResponse","useSWR","vaultAddress","assertPublicClient","getUserVaultInfo","useSWR","useBeraWallet","usePublicClient","useUserVaults","options","account","useBeraWallet","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","getUserVaults","useSWR","usePublicClient","useVaultAddress","vaultAddress","publicClient","usePublicClient","useSWR","assertPublicClient","stakeToken","getRewardVaultStakingToken","useSWR","useVaultHistory","vault","range","resolution","swrResponse","useSWR","getVaultHistory","useSWR","useVaultValidators","id","options","swrResponse","useSWR","address","getVaultValidators","zeroAddress","useTokenCurrentPrice","address","options","swrResponse","useTokenCurrentPrices","useBeraCurrentPrice","opts","useTokenCurrentPrice","zeroAddress","useMemo","useSWR","useBeraWallet","usePublicClient","usePollWalletBalances","args","options","publicClient","usePublicClient","connectedAccount","useBeraWallet","tokenList","useTokens","wallet","tokens","useMemo","t","QUERY_KEY","swrResponse","useSWR","getWalletBalances","useSWRImmutable","isAddress","zeroAddress","usePublicClient","useStakingTokenInformation","args","options","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","_","address","isToken","zeroAddress","beraToken","getStakingTokenInformation","useSWR","erc20Abi","usePublicClient","useTotalSupply","address","publicClient","usePublicClient","useSWR","assertPublicClient","erc20Abi","useCallback","useBeraWagmi","useAddRecentTransaction","store","useTransactionStore","account","useBeraWagmi","address","useCallback","transaction","InvalidArgumentError","useEffect","useState","useBeraWallet","useRecentTransactions","store","useTransactionStore","address","useBeraWallet","transactions","setTransactions","useState","useEffect","useSWRImmutable","useBlockNumber","usePublicClient","useBlockToTimestamp","inputBlock","publicClient","usePublicClient","config","parseBaseArgs","currentBlock","isLoading","useBlockNumber","seconds","block","useSWRImmutable","assertPublicClient","getBlockTimestamp","blockDuration","useBlockTime","msToSeconds","useCallback","useReducer","useBeraWagmi","useConfig","initialState","reducer","state","actions","useBeraContractWrite","onlyPermissionless","onSuccess","onError","onLoading","onWarning","onSubmission","state","dispatch","useReducer","reducer","initialState","account","onSmartAccountRejection","useBeraWagmi","wagmiConfig","useConfig","txConfirmationTimeout","reset","useCallback","enableSimulateCalls","useBeraFlag","write","writeArgs","er","TransactionFailedError","beraWriteContract","args","useBeraContractWrite_default","useSWRImmutable","isAddress","zeroAddress","chainId","fetchVerifiedAbi","address","data","beraFetchJson","chainId","useGetVerifiedAbi","useSWRImmutable","isAddress","zeroAddress","useCallback","useEffect","useState","useHistoryState","key","defaultValue","getCurrentState","existing","state","setState","setHistoryState","value","currentState","newValue","newHistoryState","newState","useEffect","useRef","usePrevious","value","ref","useSWR","useAllValidatorsQueryKey","variables","useAllValidators","options","config","parseBaseArgs","swrResponse","useSWR","getAllValidators","useSWR","useApiEnrichedAllocation","allocation","useSWR","getApiEnrichedAllocation","useSWR","isHex","useApiValidatorQueryKey","id","useApiValidator","options","QUERY_KEY","isEnabled","swrResponse","useSWR","isHex","getApiValidator","useSWR","usePublicClient","rewardAllocationFactoryAbi","getBaselineRewardAllocation","publicClient","args","config","parseBaseArgs","raw","rewardAllocationFactoryAbi","block","formatValidatorRewardAllocation","useBaselineRewardAllocation","publicClient","usePublicClient","useSWR","assertPublicClient","getBaselineRewardAllocation","useSWR","useDailyValidatorBlockStats","pubKey","first","swrResponse","useSWR","getDailyValidatorBlockStats","useSWR","usePublicClient","useDefaultRewardAllocation","options","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","getDefaultRewardAllocation","useSWRImmutable","useManagedValidatorByAccount","account","options","swrResponse","useSWRImmutable","getManagedValidatorByAccount","useMemo","useSWR","useBeraWallet","usePublicClient","zeroAddress","getValidatorRewardAllocatorAddress","client","pubKey","args","config","parseBaseArgs","result","beraChefAbi","zeroAddress","e","isOperator","account","validatorRoles","isRewardAllocator","useManagedValidatorRole","pubKey","accountAddress","options","publicClient","usePublicClient","mockValidatorOperator","useBeraFlag","mockValidatorRewardAllocator","QUERY_KEY","connectedAccount","useBeraWallet","swrResponse","useSWR","assertPublicClient","operator","rewardAllocator","getValidatorOperatorAddress","getValidatorRewardAllocatorAddress","hasOperatorRole","useMemo","hasRewardAllocatorRole","useSWR","keccak256","usePublicClient","useOnChainValidator","pubkey","options","publicClient","usePublicClient","QUERY_KEY","isEnabled","swrResponse","useSWR","assertPublicClient","config","parseBaseArgs","operator","boostees","_rewardAllocation","beaconDepositAbi","bgtAbi","beraChefAbi","keccak256","useSWR","usePublicClient","useStakingPoolBatch","valPubKey","options","publicClient","usePublicClient","QUERY_KEY","swrResponse","useSWR","assertPublicClient","getStakingPoolBatch","useSWR","GetUserValidatorInformation","useBeraWallet","useSubgraphUserValidators","_account","account","useBeraWallet","queriedAccount","useSWR","bgtClient","getApolloClient","data","GetUserValidatorInformation","useSWR","useBeraWallet","usePublicClient","useUserActiveValidators","options","account","useBeraWallet","publicClient","usePublicClient","swrResponse","useSWR","getUserActiveValidators","useSWR","useBeraWallet","usePublicClient","useUserBoostsOnValidator","pubkey","args","connectedAccount","useBeraWallet","publicClient","usePublicClient","account","swrResponse","useSWR","getUserBoostsOnValidator","useCallback","useMemo","Sentry","useSWR","useBeraWallet","formatIncentivesTokenMap","allRewards","tokenMap","item","reward","useUserClaimableIncentives","account","useBeraWallet","allRewardsResponse","useSWR","BeraError","getUserClaimableIncentives","allRewards","tokenMap","useMemo","formatIncentivesTokenMap","swrResponse","InvalidArgumentError","validatorsSet","item","validatorAddresses","validator","getRewardProofsByValidator","refresh","useCallback","useSWRImmutable","useUserStakingPositions","account","validatorAddress","swrResponse","useSWRImmutable","_","userStakingPolls","getUserStakingPositions","pool","keccak256","useValidator","pubkey","options","indexerValidator","uptime","isIndexerValidatorLoading","indexerValidatorError","useApiValidator","keccak256","onChainValidator","isOnChainValidatorLoading","onChainValidatorError","useOnChainValidator","useSWR","useValidatorAnalytics","pubkey","dayRange","swrResponse","useSWR","getValidatorAnalytics","useSWR","usePublicClient","useValidatorCommission","pubKey","options","publicClient","usePublicClient","swrResponse","useSWR","getValidatorCommission","useValidatorEstimatedBgtPerYear","validator","globalData","isLoading","usePollGlobalData","blockTime","useBlockTime","getValidatorEstimatedBgtPerYear","useSWR","usePublicClient","useValidatorQueuedCommission","pubKey","options","publicClient","usePublicClient","swrResponse","useSWR","assertPublicClient","getValidatorQueuedCommission","useSWR","usePublicClient","useValidatorQueuedOperatorAddress","pubKey","options","publicClient","usePublicClient","swrResponse","useSWR","getValidatorQueuedOperatorAddress","useSWR","usePublicClient","useValidatorQueuedRewardAllocation","pubKey","options","publicClient","usePublicClient","swrResponse","useSWR","getValidatorQueuedRewardAllocation","useSWR","usePublicClient","useValidatorRewardAllocation","pubKey","options","publicClient","usePublicClient","swrResponse","useSWR","getValidatorRewardAllocation"]}
|