@berachain/berajs 0.2.4 → 0.2.6-patch.1

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.
Files changed (463) hide show
  1. package/README.md +0 -0
  2. package/dist/abi/exports.cjs +1 -1
  3. package/dist/abi/exports.cjs.map +1 -1
  4. package/dist/abi/exports.d.cts +17 -1
  5. package/dist/abi/exports.d.ts +17 -1
  6. package/dist/abi/exports.mjs +1 -1
  7. package/dist/abi/exports.mjs.map +1 -1
  8. package/dist/actions/exports.cjs +1 -1
  9. package/dist/actions/exports.cjs.map +1 -1
  10. package/dist/actions/exports.d.cts +9 -38
  11. package/dist/actions/exports.d.ts +9 -38
  12. package/dist/actions/exports.mjs +1 -1
  13. package/dist/actions/exports.mjs.map +1 -1
  14. package/dist/chunk-2YBHAMDV.cjs +2 -0
  15. package/dist/chunk-2YBHAMDV.cjs.map +1 -0
  16. package/dist/chunk-57RINXU6.cjs +2 -0
  17. package/dist/chunk-57RINXU6.cjs.map +1 -0
  18. package/dist/{chunk-AX2YQQFQ.mjs → chunk-74QD4JAH.mjs} +2 -2
  19. package/dist/chunk-74QD4JAH.mjs.map +1 -0
  20. package/dist/chunk-74WA35RI.cjs +2 -0
  21. package/dist/chunk-74WA35RI.cjs.map +1 -0
  22. package/dist/{chunk-7WRTK7RJ.mjs → chunk-BEKH5EYT.mjs} +2 -2
  23. package/dist/chunk-BEKH5EYT.mjs.map +1 -0
  24. package/dist/{chunk-FCWDGE62.cjs → chunk-CF3LFNXG.cjs} +2 -2
  25. package/dist/chunk-CF3LFNXG.cjs.map +1 -0
  26. package/dist/chunk-COMMLZ3O.mjs +2 -0
  27. package/dist/chunk-COMMLZ3O.mjs.map +1 -0
  28. package/dist/chunk-DDEQFR3M.cjs +2 -0
  29. package/dist/chunk-DDEQFR3M.cjs.map +1 -0
  30. package/dist/{chunk-6LDOG5RL.cjs → chunk-DK42F2ZM.cjs} +2 -2
  31. package/dist/chunk-DK42F2ZM.cjs.map +1 -0
  32. package/dist/{chunk-7SMWQ6SN.mjs → chunk-FM3WDBFH.mjs} +2 -2
  33. package/dist/chunk-FM3WDBFH.mjs.map +1 -0
  34. package/dist/chunk-HWOGQSNL.cjs +4 -0
  35. package/dist/chunk-HWOGQSNL.cjs.map +1 -0
  36. package/dist/chunk-I7M43BB4.cjs +2 -0
  37. package/dist/chunk-I7M43BB4.cjs.map +1 -0
  38. package/dist/chunk-IBJOI5SN.mjs +4 -0
  39. package/dist/chunk-IBJOI5SN.mjs.map +1 -0
  40. package/dist/chunk-IDFMLLDY.mjs +2 -0
  41. package/dist/chunk-IDFMLLDY.mjs.map +1 -0
  42. package/dist/{chunk-YZV5LKIP.cjs → chunk-LNVR4BW6.cjs} +2 -2
  43. package/dist/chunk-LNVR4BW6.cjs.map +1 -0
  44. package/dist/chunk-MJZHJFZO.mjs +2 -0
  45. package/dist/{chunk-YNO7BCCM.mjs.map → chunk-MJZHJFZO.mjs.map} +1 -1
  46. package/dist/chunk-MK5NS5B5.mjs +2 -0
  47. package/dist/chunk-MK5NS5B5.mjs.map +1 -0
  48. package/dist/{chunk-C6ZGUO4H.cjs → chunk-NMH7LHPW.cjs} +2 -2
  49. package/dist/chunk-NMH7LHPW.cjs.map +1 -0
  50. package/dist/chunk-NVHV2LDK.cjs +2 -0
  51. package/dist/chunk-NVHV2LDK.cjs.map +1 -0
  52. package/dist/chunk-OGBD5YOG.mjs +2 -0
  53. package/dist/chunk-OGBD5YOG.mjs.map +1 -0
  54. package/dist/chunk-OIYXOKTT.cjs.map +1 -1
  55. package/dist/chunk-OUD27MU7.cjs.map +1 -1
  56. package/dist/chunk-PLIH6KQM.mjs +2 -0
  57. package/dist/chunk-PLIH6KQM.mjs.map +1 -0
  58. package/dist/chunk-QRAIGQF2.mjs +2 -0
  59. package/dist/chunk-QRAIGQF2.mjs.map +1 -0
  60. package/dist/chunk-RWOICHRW.cjs +2 -0
  61. package/dist/chunk-RWOICHRW.cjs.map +1 -0
  62. package/dist/chunk-T5FSQ3YE.mjs +2 -0
  63. package/dist/chunk-T5FSQ3YE.mjs.map +1 -0
  64. package/dist/chunk-WRFDB3QJ.cjs.map +1 -1
  65. package/dist/chunk-XNJLSA6P.cjs.map +1 -1
  66. package/dist/contexts/exports.cjs +1 -1
  67. package/dist/contexts/exports.cjs.map +1 -1
  68. package/dist/contexts/exports.d.cts +1 -1
  69. package/dist/contexts/exports.d.ts +1 -1
  70. package/dist/contexts/exports.mjs +1 -1
  71. package/dist/contexts/exports.mjs.map +1 -1
  72. package/dist/{defaultFlags-d0kPbT0i.d.cts → defaultFlags-D6KfkTZx.d.cts} +1 -1
  73. package/dist/{defaultFlags-d0kPbT0i.d.ts → defaultFlags-D6KfkTZx.d.ts} +1 -1
  74. package/dist/enum/exports.cjs +1 -1
  75. package/dist/enum/exports.cjs.map +1 -1
  76. package/dist/enum/exports.d.cts +1 -1
  77. package/dist/enum/exports.d.ts +1 -1
  78. package/dist/enum/exports.mjs +1 -1
  79. package/dist/errors/exports.cjs +1 -1
  80. package/dist/errors/exports.cjs.map +1 -1
  81. package/dist/errors/exports.d.cts +8 -3
  82. package/dist/errors/exports.d.ts +8 -3
  83. package/dist/errors/exports.mjs +1 -1
  84. package/dist/{getValidatorQueuedOperatorAddress-DZgrPmZ2.d.cts → getValidatorQueuedOperatorAddress-BdDYHycN.d.cts} +15 -4
  85. package/dist/{getValidatorQueuedOperatorAddress-CqR6cyqC.d.ts → getValidatorQueuedOperatorAddress-CmiPJmsr.d.ts} +15 -4
  86. package/dist/{global.d-BeYWDreg.d.ts → global.d-3GQMgC9k.d.ts} +1 -1
  87. package/dist/{global.d-DghRxpHd.d.cts → global.d-CwT1Phzf.d.cts} +1 -1
  88. package/dist/hooks/exports.cjs +3 -3
  89. package/dist/hooks/exports.cjs.map +1 -1
  90. package/dist/hooks/exports.d.cts +54 -75
  91. package/dist/hooks/exports.d.ts +54 -75
  92. package/dist/hooks/exports.mjs +3 -3
  93. package/dist/hooks/exports.mjs.map +1 -1
  94. package/dist/{txnEnum-DxPRHSJt.d.cts → txnEnum-CCuQUFlh.d.cts} +7 -0
  95. package/dist/{txnEnum-DxPRHSJt.d.ts → txnEnum-CCuQUFlh.d.ts} +7 -0
  96. package/dist/types/exports.cjs.map +1 -1
  97. package/dist/types/exports.d.cts +37 -4
  98. package/dist/types/exports.d.ts +37 -4
  99. package/dist/utils/exports.cjs +1 -1
  100. package/dist/utils/exports.cjs.map +1 -1
  101. package/dist/utils/exports.d.cts +2 -2
  102. package/dist/utils/exports.d.ts +2 -2
  103. package/dist/utils/exports.mjs +1 -1
  104. package/dist/utils/exports.mjs.map +1 -1
  105. package/package.json +25 -25
  106. package/src/abi/enso/ensoWalletV2Factory.ts +9 -0
  107. package/src/abi/exports.ts +1 -0
  108. package/src/abi/pyth/pyth.ts +0 -0
  109. package/src/actions/clients/BeraApolloClient.ts +3 -3
  110. package/src/actions/clients/getApolloClient.ts +5 -5
  111. package/src/actions/clients/getEnsoClient.ts +1 -1
  112. package/src/actions/dex/__tests__/aggregators.unit.test.ts +3 -3
  113. package/src/actions/dex/__tests__/getOnChainPool.unit.test.ts +1 -1
  114. package/src/actions/dex/aggregators/base.ts +12 -8
  115. package/src/actions/dex/aggregators/bex.ts +8 -8
  116. package/src/actions/dex/aggregators/bgt.ts +4 -4
  117. package/src/actions/dex/aggregators/enso/enso.ts +28 -20
  118. package/src/actions/dex/aggregators/enso/ensoErc4626.debug.test.ts +1 -1
  119. package/src/actions/dex/aggregators/enso/ensoErc4626.ts +7 -4
  120. package/src/actions/dex/aggregators/erc4626.ts +10 -6
  121. package/src/actions/dex/aggregators/fly.ts +9 -5
  122. package/src/actions/dex/aggregators/haiku.integration.test.ts +3 -3
  123. package/src/actions/dex/aggregators/haiku.ts +9 -5
  124. package/src/actions/dex/aggregators/honey.ts +15 -15
  125. package/src/actions/dex/aggregators/kyberswap.ts +8 -4
  126. package/src/actions/dex/aggregators/oogabooga.ts +8 -4
  127. package/src/actions/dex/aggregators/openOcean.ts +12 -8
  128. package/src/actions/dex/aggregators/wbera.ts +8 -4
  129. package/src/actions/dex/b-sdk.ts +2 -2
  130. package/src/actions/dex/getAllPools.ts +2 -2
  131. package/src/actions/dex/getApiPool.ts +2 -2
  132. package/src/actions/dex/getGlobalLiquidityAndSwapVolume.ts +2 -2
  133. package/src/actions/dex/getIsTokenExploited.ts +1 -1
  134. package/src/actions/dex/getOnChainPool.ts +3 -3
  135. package/src/actions/dex/getPoolEvents.ts +2 -2
  136. package/src/actions/dex/getPoolHistoricalData.ts +2 -2
  137. package/src/actions/dex/getVaultPausedState.ts +1 -1
  138. package/src/actions/enso/__tests__/getBendDemultiplyBundle.action.unit.test.ts +175 -0
  139. package/src/actions/enso/__tests__/getBendDemultiplyBundle.unit.test.ts +150 -0
  140. package/src/actions/enso/__tests__/getBendMultiplyBundle.action.unit.test.ts +138 -0
  141. package/src/actions/enso/__tests__/getBendMultiplyBundle.unit.test.ts +194 -0
  142. package/src/actions/enso/{getEnsoUserTokensWithBalances.debug.test.ts → __tests__/getEnsoUserTokensWithBalances.debug.test.ts} +3 -3
  143. package/src/actions/enso/__tests__/helpers.ts +42 -0
  144. package/src/actions/enso/__tests__/util.unit.test.ts +95 -0
  145. package/src/actions/enso/flashloan.ts +127 -0
  146. package/src/actions/enso/getBendDemultiplyBundle.ts +325 -0
  147. package/src/actions/enso/getBendMultiplyBundle.ts +348 -0
  148. package/src/actions/enso/getEnsoSwapBundle.ts +2 -2
  149. package/src/actions/enso/getEnsoUserTokensWithBalances.ts +5 -5
  150. package/src/actions/enso/util.ts +150 -5
  151. package/src/actions/exports.ts +0 -2
  152. package/src/actions/governance/__tests__/checkProposalField.unit.test.ts +2 -2
  153. package/src/actions/governance/__tests__/getDecodedFunctionData.integration.test.ts +2 -2
  154. package/src/actions/governance/__tests__/getQuorum.integration.test.ts +2 -2
  155. package/src/actions/governance/checkProposalField.ts +1 -1
  156. package/src/actions/governance/computeActualStatus.ts +1 -1
  157. package/src/actions/governance/getAllProposals.ts +1 -1
  158. package/src/actions/governance/getBodyErrors.ts +1 -1
  159. package/src/actions/governance/getProposalDetails.ts +1 -1
  160. package/src/actions/governance/getProposalFromTx.ts +1 -1
  161. package/src/actions/governance/getProposalParams.ts +3 -3
  162. package/src/actions/governance/getProposalVotes.ts +1 -1
  163. package/src/actions/governance/getQuorum.ts +2 -2
  164. package/src/actions/honey/getCollateralWeights.ts +2 -2
  165. package/src/actions/honey/getGlobalCapLimit.ts +4 -4
  166. package/src/actions/honey/getHoneyCollaterals.ts +5 -5
  167. package/src/actions/honey/getHoneyFees.ts +1 -1
  168. package/src/actions/honey/getHoneyPausedState.ts +1 -1
  169. package/src/actions/honey/getHoneyPreview.ts +3 -3
  170. package/src/actions/honey/getHoneyRootPriceOracle.ts +1 -1
  171. package/src/actions/honey/getHoneyVaultsBalance.ts +2 -2
  172. package/src/actions/honey/getRelativeCapLimit.ts +3 -3
  173. package/src/actions/honey/getSharesWithoutFees.ts +1 -1
  174. package/src/actions/honey/getSwapPayload.ts +6 -6
  175. package/src/actions/honey/isBadCollateralAsset.ts +2 -2
  176. package/src/actions/honey/isBasketModeEnabled.ts +2 -2
  177. package/src/actions/honey/tests/pyth.integration.test.ts +3 -3
  178. package/src/actions/misc/getBlockTimestamp.ts +2 -2
  179. package/src/actions/pol/__tests__/getAllValidators.integration.test.ts +2 -2
  180. package/src/actions/pol/__tests__/rewardVaults.integration.test.ts +1 -1
  181. package/src/actions/pol/getBGTGlobalInfo.ts +2 -2
  182. package/src/actions/pol/getBgtAprSimulation.ts +1 -1
  183. package/src/actions/pol/getBgtAprSimultaion.unit.test.ts +1 -1
  184. package/src/actions/pol/getBgtTokenTotalBoosts.ts +2 -2
  185. package/src/actions/pol/getBgtTokenTotalSupply.ts +2 -2
  186. package/src/actions/pol/getBlockTime.debug.test.ts +13 -0
  187. package/src/actions/pol/getBlockTime.ts +14 -23
  188. package/src/actions/pol/getEarnedStakedBeraVault.ts +3 -3
  189. package/src/actions/pol/getGlobalCuttingBoard.ts +0 -0
  190. package/src/actions/pol/getGlobalData.ts +2 -2
  191. package/src/actions/pol/getIncentiveFeeClaimStats.ts +4 -4
  192. package/src/actions/pol/getLSTStakeConfig.ts +5 -5
  193. package/src/actions/pol/getMarkets.ts +2 -2
  194. package/src/actions/pol/getRewardProofsByValidator.ts +4 -4
  195. package/src/actions/pol/getRewardTokenToBeraRate.ts +1 -1
  196. package/src/actions/pol/getRewardVault.ts +3 -3
  197. package/src/actions/pol/getRewardVaultBeaconImplementation.integration.test.ts +1 -1
  198. package/src/actions/pol/getRewardVaultBeaconImplementation.ts +3 -3
  199. package/src/actions/pol/getRewardVaultDurationConstants.integration.test.ts +1 -1
  200. package/src/actions/pol/getRewardVaultDurationConstants.ts +1 -1
  201. package/src/actions/pol/getRewardVaultFromToken.ts +1 -1
  202. package/src/actions/pol/getRewardVaultIncentives.ts +2 -2
  203. package/src/actions/pol/getRewardVaultRewards.ts +1 -1
  204. package/src/actions/pol/getRewardVaults.ts +1 -1
  205. package/src/actions/pol/getSWBeraVaultMetadata.ts +20 -22
  206. package/src/actions/pol/getSWBeraWithdrawal.ts +4 -4
  207. package/src/actions/pol/getStakedBeraAPR.ts +2 -2
  208. package/src/actions/pol/getStakedBeraSnapshots.ts +2 -2
  209. package/src/actions/pol/getStakingDailyAssets.ts +3 -3
  210. package/src/actions/pol/getStakingTokenInformation.ts +2 -2
  211. package/src/actions/pol/getTotalStakedAmount.ts +1 -1
  212. package/src/actions/pol/getUserClaimableIncentives.ts +4 -4
  213. package/src/actions/pol/getUserVaultInfo.ts +1 -1
  214. package/src/actions/pol/getUserVaults.ts +4 -4
  215. package/src/actions/pol/getUserVaultsBalance.ts +1 -1
  216. package/src/actions/pol/getUserVaultsReward.ts +0 -0
  217. package/src/actions/pol/getVaultHistory.ts +2 -2
  218. package/src/actions/pol/getVaultValidators.ts +1 -1
  219. package/src/actions/pol/getVaultsSupply.ts +0 -0
  220. package/src/actions/prices/__tests__/prices.integration.test.ts +2 -2
  221. package/src/actions/prices/getTokenCurrentPrices.ts +5 -5
  222. package/src/actions/pyth/getHoneyPythFeeds.ts +2 -2
  223. package/src/actions/pyth/getUpdateFee.ts +2 -2
  224. package/src/actions/tokens/getAllowances.ts +2 -2
  225. package/src/actions/tokens/getTokenInformation.ts +2 -2
  226. package/src/actions/tokens/getTokens.ts +3 -3
  227. package/src/actions/tokens/getUnderlyingToken.ts +4 -4
  228. package/src/actions/tokens/getWalletBalances.integration.test.ts +1 -1
  229. package/src/actions/tokens/getWalletBalances.ts +4 -4
  230. package/src/actions/transactions/beraWriteContract.integration.test.ts +6 -6
  231. package/src/actions/transactions/beraWriteContract.ts +12 -12
  232. package/src/actions/validators/getActiveBoostAndCommissionChangeDelay.integration.test.ts +1 -1
  233. package/src/actions/validators/getActiveBoostAndCommissionChangeDelay.ts +1 -1
  234. package/src/actions/validators/getAllValidators.ts +2 -2
  235. package/src/actions/validators/getApiValidator.ts +2 -2
  236. package/src/actions/validators/getBaselineRewardAllocation.ts +1 -1
  237. package/src/actions/validators/getDailyValidatorBlockStats.ts +1 -1
  238. package/src/actions/validators/getDefaultRewardAllocation.ts +1 -1
  239. package/src/actions/validators/getUserActiveValidators.ts +31 -33
  240. package/src/actions/validators/getUserBoosts.ts +12 -8
  241. package/src/actions/validators/getUserBoostsOnValidator.ts +15 -3
  242. package/src/actions/validators/getUserStakingPositions.ts +1 -1
  243. package/src/actions/validators/getValidatorAnalytics.ts +2 -2
  244. package/src/actions/validators/getValidatorCommission.ts +1 -1
  245. package/src/actions/validators/getValidatorEstimatedBgtPerYear.ts +1 -1
  246. package/src/actions/validators/getValidatorOperatorAddress.ts +1 -1
  247. package/src/actions/validators/getValidatorQueuedCommission.ts +1 -1
  248. package/src/actions/validators/getValidatorQueuedOperatorAddress.ts +1 -1
  249. package/src/actions/validators/getValidatorQueuedRewardAllocation.ts +1 -1
  250. package/src/actions/validators/getValidatorRewardAllocation.ts +1 -1
  251. package/src/actions/validators/getValidatorRewardAllocatorAddress.ts +1 -1
  252. package/src/actions/validators/utils/__tests__/validatorUtils.integration.test.ts +4 -4
  253. package/src/contexts/BeraFlags/defaultFlags.ts +4 -0
  254. package/src/contexts/BexStatusProvider.tsx +1 -1
  255. package/src/contexts/HoneyConfigProvider.tsx +3 -3
  256. package/src/contexts/SwrFallback.tsx +2 -2
  257. package/src/contexts/TokensProvider.tsx +3 -3
  258. package/src/contexts/block-time-provider.tsx +1 -1
  259. package/src/contexts/exports.ts +0 -0
  260. package/src/data/contracts.ts +10 -0
  261. package/src/enum/exports.ts +0 -0
  262. package/src/enum/polling.ts +0 -0
  263. package/src/enum/txnEnum.ts +9 -0
  264. package/src/errors/BeraMonitoring.ts +2 -2
  265. package/src/errors/BeraTracing.ts +2 -2
  266. package/src/errors/RequestError.ts +1 -1
  267. package/src/errors/assert.ts +18 -0
  268. package/src/errors/getErrorMessage.ts +0 -0
  269. package/src/errors/getRevertReason.integration.test.ts +7 -7
  270. package/src/errors/getRevertReason.ts +1 -1
  271. package/src/errors/parseViemError.ts +1 -1
  272. package/src/hooks/bend/useGetConvertToAssets.ts +4 -4
  273. package/src/hooks/dex/useAggregatorsQuotes.ts +19 -19
  274. package/src/hooks/dex/useAggregatorsRouterFeeBps.ts +2 -2
  275. package/src/hooks/dex/useAllUserPools.ts +3 -3
  276. package/src/hooks/dex/useApiPool.ts +3 -3
  277. package/src/hooks/dex/useBexStatus.ts +1 -1
  278. package/src/hooks/dex/useCreatePool.ts +9 -9
  279. package/src/hooks/dex/useExploitedTokens.ts +3 -3
  280. package/src/hooks/dex/useGlobalLiquidityAndSwapVolume.ts +1 -1
  281. package/src/hooks/dex/useLiquidityMismatch.ts +3 -3
  282. package/src/hooks/dex/useLpPosition.ts +7 -4
  283. package/src/hooks/dex/useMultipleTokenApprovalsWithSlippage.ts +4 -4
  284. package/src/hooks/dex/useOnChainPoolData.ts +3 -3
  285. package/src/hooks/dex/usePollPoolCreationRelayerApproval.ts +3 -3
  286. package/src/hooks/dex/usePool.ts +7 -40
  287. package/src/hooks/dex/usePoolEvents.ts +2 -2
  288. package/src/hooks/dex/usePoolHistoricalData.ts +6 -3
  289. package/src/hooks/dex/usePools.ts +3 -3
  290. package/src/hooks/dex/usePriceImpact.ts +2 -2
  291. package/src/hooks/dex/useSingleAggregatorQuote.ts +13 -13
  292. package/src/hooks/enso/useBendDemultiply.ts +158 -0
  293. package/src/hooks/enso/useBendMultiply.ts +163 -0
  294. package/src/hooks/enso/useBendZapSupply.ts +7 -7
  295. package/src/hooks/enso/useEnsoSwapBundle.ts +6 -6
  296. package/src/hooks/enso/useEnsoUserTokensWithBalances.ts +5 -5
  297. package/src/hooks/enso/useEnsoWalletV2Address.ts +38 -0
  298. package/src/hooks/enso/useIsBendAuthorized.ts +47 -0
  299. package/src/hooks/enso/useZapStakeBera.ts +4 -4
  300. package/src/hooks/exports.ts +4 -3
  301. package/src/hooks/governance/useCreateProposal.ts +3 -3
  302. package/src/hooks/governance/useGetPastVotes.ts +2 -2
  303. package/src/hooks/governance/useHasVoted.ts +2 -2
  304. package/src/hooks/governance/useIsCanceller.ts +4 -4
  305. package/src/hooks/governance/usePollAllProposals.ts +3 -3
  306. package/src/hooks/governance/usePollProposal.ts +7 -4
  307. package/src/hooks/governance/usePollProposalThreshold.ts +3 -3
  308. package/src/hooks/governance/usePollProposalVotes.ts +1 -1
  309. package/src/hooks/governance/usePollUserDelegates.ts +7 -4
  310. package/src/hooks/governance/useProposalFromTx.ts +1 -1
  311. package/src/hooks/governance/useProposalSnapshot.ts +2 -2
  312. package/src/hooks/governance/useProposalState.ts +2 -2
  313. package/src/hooks/governance/useProposalTimelockState.ts +2 -2
  314. package/src/hooks/governance/useQuorum.ts +1 -1
  315. package/src/hooks/honey/useCappedGlobally.ts +8 -5
  316. package/src/hooks/honey/useCappedRelatively.ts +7 -4
  317. package/src/hooks/honey/useCollateralWeights.ts +8 -5
  318. package/src/hooks/honey/useHoneyAlerts.ts +5 -5
  319. package/src/hooks/honey/useHoneyBalances.ts +7 -7
  320. package/src/hooks/honey/useHoneyChartData.ts +1 -1
  321. package/src/hooks/honey/useHoneySwapState.ts +4 -4
  322. package/src/hooks/honey/useHoneyVaultsBalance.ts +8 -5
  323. package/src/hooks/honey/useIsBadCollateralAsset.ts +9 -6
  324. package/src/hooks/honey/useIsBasketModeEnabled.ts +8 -5
  325. package/src/hooks/honey/usePythLatestPrices.ts +4 -4
  326. package/src/hooks/perps/usePythUpdateFee.ts +4 -4
  327. package/src/hooks/pol/useBgtAprSimulation.ts +1 -1
  328. package/src/hooks/pol/useBgtUnstakedBalance.ts +7 -4
  329. package/src/hooks/pol/useClaimableFees.ts +4 -4
  330. package/src/hooks/pol/useOnChainRewardVault.ts +7 -7
  331. package/src/hooks/pol/usePollGlobalData.ts +9 -3
  332. package/src/hooks/pol/usePollMarkets.ts +5 -2
  333. package/src/hooks/pol/useQueuedBeraUnlock.ts +4 -4
  334. package/src/hooks/pol/useRewardTokenToBeraRate.ts +4 -4
  335. package/src/hooks/pol/useRewardVault.ts +5 -2
  336. package/src/hooks/pol/useRewardVaultBalanceFromStakingToken.ts +2 -2
  337. package/src/hooks/pol/useRewardVaultFromToken.ts +2 -2
  338. package/src/hooks/pol/useRewardVaultIncentives.ts +2 -2
  339. package/src/hooks/pol/useRewardVaultRewards.ts +3 -3
  340. package/src/hooks/pol/useRewardVaults.ts +2 -2
  341. package/src/hooks/pol/useStakedAPR.ts +3 -3
  342. package/src/hooks/pol/useStakedData.ts +10 -10
  343. package/src/hooks/pol/useStakedSnapshots.ts +3 -3
  344. package/src/hooks/pol/useStakingVaultsMetadata.ts +40 -0
  345. package/src/hooks/pol/useTotalStakedAmount.ts +2 -2
  346. package/src/hooks/pol/useUserVaultInfo.ts +8 -5
  347. package/src/hooks/pol/useUserVaults.ts +7 -4
  348. package/src/hooks/pol/useVaultAddress.ts +2 -2
  349. package/src/hooks/pol/useVaultHistory.ts +2 -2
  350. package/src/hooks/pol/useVaultValidators.ts +5 -2
  351. package/src/hooks/tokens/useBeraCurrentPrice.ts +1 -1
  352. package/src/hooks/tokens/useMultipleTokenInformation.ts +7 -4
  353. package/src/hooks/tokens/usePollAllowances.ts +7 -4
  354. package/src/hooks/tokens/usePollBalance.ts +8 -5
  355. package/src/hooks/tokens/usePollWalletBalances.ts +8 -5
  356. package/src/hooks/tokens/useStakingTokenInformation.ts +7 -4
  357. package/src/hooks/tokens/useTokenCurrentPrice.ts +1 -1
  358. package/src/hooks/tokens/useTokenCurrentPrices.ts +6 -6
  359. package/src/hooks/tokens/useTokenInformation.ts +8 -5
  360. package/src/hooks/tokens/useTokenPrice.ts +1 -1
  361. package/src/hooks/tokens/useTokenPrices.ts +4 -4
  362. package/src/hooks/tokens/useTokens.ts +3 -3
  363. package/src/hooks/tokens/useTotalSupply.ts +1 -1
  364. package/src/hooks/tokens/useUnderlyingAsset.ts +3 -3
  365. package/src/hooks/useBlockToTimestamp.ts +5 -5
  366. package/src/hooks/useContractWrite/index.ts +0 -0
  367. package/src/hooks/useContractWrite/stateReducer.ts +0 -0
  368. package/src/hooks/useContractWrite/types.ts +2 -2
  369. package/src/hooks/useContractWrite/useBeraContractWrite.ts +5 -6
  370. package/src/hooks/useGetVerifiedAbi.ts +1 -1
  371. package/src/hooks/usePrevious.ts +0 -0
  372. package/src/hooks/validators/useAllValidators.ts +7 -4
  373. package/src/hooks/validators/useApiEnrichedAllocation.ts +2 -2
  374. package/src/hooks/validators/useApiValidator.ts +5 -2
  375. package/src/hooks/validators/useBaselineRewardAllocation.ts +2 -2
  376. package/src/hooks/validators/useDailyValidatorBlockStats.ts +3 -3
  377. package/src/hooks/validators/useDefaultRewardAllocation.ts +4 -4
  378. package/src/hooks/validators/useManagedValidatorRole.ts +8 -5
  379. package/src/hooks/validators/useOnChainValidator.ts +6 -3
  380. package/src/hooks/validators/useStakingPoolBatch.ts +7 -4
  381. package/src/hooks/validators/useUserActiveValidators.ts +6 -3
  382. package/src/hooks/validators/useUserBoostsOnValidator.ts +3 -3
  383. package/src/hooks/validators/useUserClaimableIncentives.ts +9 -9
  384. package/src/hooks/validators/useUserStakingPositions.ts +1 -1
  385. package/src/hooks/validators/useValidator.ts +1 -1
  386. package/src/hooks/validators/useValidatorAnalytics.ts +3 -3
  387. package/src/hooks/validators/useValidatorCommission.ts +5 -2
  388. package/src/hooks/validators/useValidatorEstimatedBgtPerYear.ts +3 -3
  389. package/src/hooks/validators/useValidatorQueuedCommission.ts +6 -3
  390. package/src/hooks/validators/useValidatorQueuedOperatorAddress.ts +5 -2
  391. package/src/hooks/validators/useValidatorQueuedRewardAllocation.ts +6 -3
  392. package/src/hooks/validators/useValidatorRewardAllocation.ts +2 -2
  393. package/src/types/dex.d.ts +1 -1
  394. package/src/types/enso.d.ts +34 -0
  395. package/src/types/exports.ts +0 -0
  396. package/src/types/global.d.ts +3 -3
  397. package/src/types/governance.d.ts +1 -1
  398. package/src/types/honeySwap.d.ts +3 -3
  399. package/src/types/staking.d.ts +0 -0
  400. package/src/utils/beraFetch.ts +1 -1
  401. package/src/utils/createEmitter.ts +1 -1
  402. package/src/utils/exports.ts +0 -0
  403. package/src/utils/filter.ts +0 -0
  404. package/src/utils/formatIncentivesTokenMap.ts +1 -1
  405. package/src/utils/formatInputTokenValue.ts +0 -0
  406. package/src/utils/formatNumber.ts +0 -0
  407. package/src/utils/getContractName.ts +1 -1
  408. package/src/utils/getHoneySwapMessage.test.ts +1 -1
  409. package/src/utils/getHoneySwapMessage.ts +1 -1
  410. package/src/utils/parseBaseArgs.ts +1 -1
  411. package/src/utils/parseBaseArgs.unit.test.ts +1 -1
  412. package/src/utils/parseWhiskToken.ts +1 -1
  413. package/src/utils/poolNamings.ts +1 -1
  414. package/src/utils/tokens.ts +2 -2
  415. package/src/utils/tokens.unit.test.ts +1 -1
  416. package/src/utils/truncateHash.ts +0 -0
  417. package/.claude/skills/berajs/SKILL.md +0 -222
  418. package/.claude/skills/berajs/references/dex.md +0 -235
  419. package/.claude/skills/berajs/references/pol.md +0 -194
  420. package/.claude/skills/berajs/references/staking.md +0 -198
  421. package/.claude/skills/berajs/references/tokens.md +0 -170
  422. package/LICENSE +0 -21
  423. package/dist/chunk-22J3YJDN.cjs +0 -2
  424. package/dist/chunk-22J3YJDN.cjs.map +0 -1
  425. package/dist/chunk-2LL3P5PN.mjs +0 -2
  426. package/dist/chunk-2LL3P5PN.mjs.map +0 -1
  427. package/dist/chunk-4GU2O2OW.cjs +0 -4
  428. package/dist/chunk-4GU2O2OW.cjs.map +0 -1
  429. package/dist/chunk-55L7STYD.mjs +0 -2
  430. package/dist/chunk-55L7STYD.mjs.map +0 -1
  431. package/dist/chunk-5XWELBWR.mjs +0 -2
  432. package/dist/chunk-5XWELBWR.mjs.map +0 -1
  433. package/dist/chunk-6LDOG5RL.cjs.map +0 -1
  434. package/dist/chunk-7LNBSOVV.cjs +0 -2
  435. package/dist/chunk-7LNBSOVV.cjs.map +0 -1
  436. package/dist/chunk-7SMWQ6SN.mjs.map +0 -1
  437. package/dist/chunk-7WRTK7RJ.mjs.map +0 -1
  438. package/dist/chunk-AX2YQQFQ.mjs.map +0 -1
  439. package/dist/chunk-BS6K7HGH.cjs +0 -2
  440. package/dist/chunk-BS6K7HGH.cjs.map +0 -1
  441. package/dist/chunk-C3FHGFLK.mjs +0 -2
  442. package/dist/chunk-C3FHGFLK.mjs.map +0 -1
  443. package/dist/chunk-C6ZGUO4H.cjs.map +0 -1
  444. package/dist/chunk-FCWDGE62.cjs.map +0 -1
  445. package/dist/chunk-RW3JFPED.mjs +0 -4
  446. package/dist/chunk-RW3JFPED.mjs.map +0 -1
  447. package/dist/chunk-S3EAKCVM.cjs +0 -2
  448. package/dist/chunk-S3EAKCVM.cjs.map +0 -1
  449. package/dist/chunk-SWMJQOH6.cjs +0 -2
  450. package/dist/chunk-SWMJQOH6.cjs.map +0 -1
  451. package/dist/chunk-THATXCJK.mjs +0 -2
  452. package/dist/chunk-THATXCJK.mjs.map +0 -1
  453. package/dist/chunk-VXL2ZZ4X.cjs +0 -2
  454. package/dist/chunk-VXL2ZZ4X.cjs.map +0 -1
  455. package/dist/chunk-YNO7BCCM.mjs +0 -2
  456. package/dist/chunk-YXLFOEZN.mjs +0 -2
  457. package/dist/chunk-YXLFOEZN.mjs.map +0 -1
  458. package/dist/chunk-YZV5LKIP.cjs.map +0 -1
  459. package/src/actions/dex/getSubgraphPool.ts +0 -30
  460. package/src/actions/validators/getManagedValidatorByAccount.ts +0 -32
  461. package/src/hooks/pol/useSWBeraVaultMetadata.ts +0 -35
  462. package/src/hooks/validators/useManagedValidatorByAccount.ts +0 -40
  463. package/src/hooks/validators/useSubgraphUserValidators.ts +0 -36
@@ -1 +1 @@
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/enso.ts","../../src/actions/dex/aggregators/erc4626.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/tokens/useUnderlyingAsset.ts","../../src/actions/tokens/getUnderlyingToken.ts","../../src/hooks/dex/useSingleAggregatorQuote.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/dex/usePriceImpact.ts","../../src/hooks/tokens/useTokenPrices.ts","../../src/hooks/enso/useBendZapSupply.ts","../../src/actions/dex/aggregators/enso/ensoErc4626.ts","../../src/hooks/enso/useEnsoSwapBundle.ts","../../src/actions/enso/getEnsoSwapBundle.ts","../../src/actions/enso/util.ts","../../src/hooks/tokens/usePollWalletBalances.ts","../../src/hooks/enso/useZapStakeBera.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/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/useStakedAPR.ts","../../src/utils/filter.ts","../../src/hooks/pol/useStakedData.ts","../../src/hooks/pol/useStakedSnapshots.ts","../../src/actions/pol/getStakingDailyAssets.ts","../../src/hooks/pol/useSWBeraVaultMetadata.ts","../../src/hooks/pol/useTotalStakedAmount.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/useStakingTokenInformation.ts","../../src/hooks/tokens/useTokenPrice.ts","../../src/hooks/tokens/useTotalSupply.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/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 } from \"~/actions/bend/getConvertToAssets\";\nimport { getConvertToAssets } from \"~/actions/bend/getConvertToAssets\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\n\nexport const useGetConvertToAssets = (\n {\n sharesAmount,\n vaultAddress,\n vaultChainId,\n }: Omit<GetConvertToAssetsProps, \"publicClient\"> & { vaultChainId?: number },\n options?: DefaultHookOptions,\n) => {\n const publicClient = usePublicClient({ chainId: vaultChainId });\n const swrResponse = useSWR(\n publicClient && sharesAmount && vaultAddress\n ? [\"useGetConvertToAssets\", sharesAmount, vaultAddress, vaultChainId]\n : null,\n async ([_, sharesAmount, vaultAddress]) => {\n assertPublicClient(publicClient);\n\n return getConvertToAssets({\n sharesAmount,\n vaultAddress,\n publicClient,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n};\n","import { useMemo } from \"react\";\nimport { type Address, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { bex } from \"~/actions/dex/aggregators/bex\";\nimport { bgtRedeem } from \"~/actions/dex/aggregators/bgt\";\nimport { enso } from \"~/actions/dex/aggregators/enso/enso\";\nimport { erc4626Deposit } from \"~/actions/dex/aggregators/erc4626\";\nimport { fly } from \"~/actions/dex/aggregators/fly\";\nimport { haiku } from \"~/actions/dex/aggregators/haiku\";\nimport { honeyNative } from \"~/actions/dex/aggregators/honey\";\nimport { kyberswap } from \"~/actions/dex/aggregators/kyberswap\";\nimport { oogabooga } from \"~/actions/dex/aggregators/oogabooga\";\nimport { openOcean } from \"~/actions/dex/aggregators/openOcean\";\nimport { wberaSwap } from \"~/actions/dex/aggregators/wbera\";\nimport { useBeraFlag } from \"~/contexts/BeraFlags/BeraFlags\";\nimport type { HoneyConfigContextReturn } from \"~/contexts/HoneyConfigProvider\";\nimport type { SwapReferrer } from \"~/enum/dex\";\nimport { useAggregatorsRouterFeeBps } from \"~/hooks/dex/useAggregatorsRouterFeeBps\";\nimport type { IRawAggregatorQuote, MinimalERC20 } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { isToken } from \"~/utils/tokens\";\nimport { useUnderlyingAsset } from \"../tokens/useUnderlyingAsset\";\nimport { useBexStatus } from \"./useBexStatus\";\nimport {\n getAggregatorsSWROptions,\n raw_useSingleAggregatorQuote,\n} from \"./useSingleAggregatorQuote\";\n\nconst AGGREGATORS = [\n oogabooga,\n fly,\n kyberswap,\n openOcean,\n haiku,\n enso,\n bex,\n honeyNative,\n erc4626Deposit,\n];\n\ntype IUseAggregatorsQuotesArgs = BeraJS.BaseFunctionArgs & {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n amount: string;\n slippage: number;\n referrer?: SwapReferrer;\n rewardVault?: Address;\n /**\n * Useful cause the collaterals are provided byt he honeyContext and this way we can\n * use the Provider only in the swap page where is needed.\n *\n * The collaterals for the honey mint/redeem aggregator.\n */\n honeyNativeState?: Pick<\n HoneyConfigContextReturn,\n \"collateralList\" | \"protocol\"\n >;\n};\n\nexport function useAggregatorsQuotes(\n args: IUseAggregatorsQuotesArgs,\n options?: DefaultHookOptions,\n) {\n const { address: account } = useBeraWallet();\n const proxyAggregatorsThroughVercel = useBeraFlag(\n \"proxyAggregatorsThroughVercel\",\n );\n const activeAggregators = useBeraFlag(\"aggregators\");\n const publicClient = usePublicClient();\n const { data: feeBps } = useAggregatorsRouterFeeBps();\n\n const isWrapOrUnwrap =\n (isToken(args.tokenIn.address, \"BERA\") ||\n isToken(args.tokenIn.address, \"WBERA\")) &&\n (isToken(args.tokenOut.address, \"BERA\") ||\n isToken(args.tokenOut.address, \"WBERA\"));\n\n const isBgtRedeem = isToken(args.tokenIn.address, \"BGT\", {\n chainId: defaultChainId,\n });\n\n const { data: underlyingToken } = useUnderlyingAsset({\n token: args.tokenOut,\n });\n\n /**\n * Whether it's a native swap (wrap/unwrap) or BGT redeem\n */\n const isNativeSwap = isWrapOrUnwrap || isBgtRedeem;\n\n const { config } = parseBaseArgs(args);\n\n const isMAEnabled = config.bex.aggregatorsRouter !== zeroAddress;\n\n const swrOptions = getAggregatorsSWROptions(options);\n\n const sharedArgs = {\n activeAggregators,\n isMAEnabled,\n underlyingToken,\n isNativeSwap,\n account,\n publicClient,\n proxyAggregatorsThroughVercel,\n feeBps,\n } as const;\n\n // we're using independent useSWRs so we can show quotes as they come\n // instead of waiting for all of them to load\n const oogaBogaResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: oogabooga,\n },\n { opts: swrOptions },\n );\n\n const flyResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: fly,\n },\n { opts: swrOptions },\n );\n\n const erc4626Result = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: erc4626Deposit,\n },\n { opts: swrOptions },\n );\n\n const kyberswapResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: kyberswap,\n },\n { opts: swrOptions },\n );\n\n const openOceanResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: openOcean,\n },\n { opts: swrOptions },\n );\n\n const haikuResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: haiku,\n },\n { opts: swrOptions },\n );\n\n const ensoResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: enso,\n },\n { opts: swrOptions },\n );\n\n const { protocol: bexProtocol } = useBexStatus();\n\n const bexResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: bex,\n },\n { opts: { ...swrOptions, isEnabled: bexProtocol.isPaused === false } },\n );\n\n const wberaSwapResult = raw_useSingleAggregatorQuote({\n ...sharedArgs,\n ...args,\n aggregator: wberaSwap,\n });\n\n const bgtRedeemResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: bgtRedeem,\n },\n { opts: swrOptions },\n );\n\n const honeyResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: honeyNative,\n },\n { opts: swrOptions },\n );\n\n const results = isWrapOrUnwrap\n ? [wberaSwapResult]\n : isBgtRedeem\n ? [bgtRedeemResult]\n : [\n oogaBogaResult,\n erc4626Result,\n flyResult,\n kyberswapResult,\n openOceanResult,\n haikuResult,\n ensoResult,\n honeyResult,\n bexProtocol.isPaused === false ? bexResult : null,\n ].filter((i): i is NonNullable<typeof i> => i !== null);\n\n const data = useMemo(() => {\n const error = results.reduce<(typeof results)[number][\"error\"]>(\n (error, result) => error || result.error,\n undefined,\n );\n\n const loadingAggregatorsNames = results\n .map((r, i) =>\n r.isLoading\n ? isNativeSwap\n ? wberaSwap.name\n : AGGREGATORS[i].name\n : null,\n )\n .filter(Boolean);\n\n const quotes = results\n .filter(\n (result) =>\n result !== undefined &&\n !result.isLoading &&\n !result.error &&\n result.data?.amountOut,\n )\n .map(({ data }) => data) as IRawAggregatorQuote[];\n\n const isLoading = quotes.length === 0 && loadingAggregatorsNames.length > 0;\n return { quotes, loadingAggregatorsNames, isLoading, error };\n }, [results]);\n\n return {\n ...data,\n refresh: () => results.map((r) => r.mutate()),\n };\n}\n","import {\n type Address,\n Slippage,\n type SorSwapResult,\n Swap,\n SwapKind,\n Token,\n TokenAmount,\n} from \"@berachain-foundation/berancer-sdk\";\nimport { decodeFunctionData, formatEther, zeroAddress } from \"viem\";\n\nimport { getUriFromLink } from \"@berachain/config\";\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { vaultAbi as balancerVaultAbi } from \"@berachain/abis/bex/vault\";\n\nimport { BalancerApi } from \"~/actions/dex/b-sdk\";\nimport { Aggregators } from \"~/enum/dex\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { BeraMonitoring } from \"~/errors/BeraMonitoring\";\nimport { RequestError } from \"~/errors/RequestError\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\nimport { isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\n// Constants\nconst DEFAULT_DEADLINE = 60 * 5; // default transaction deadline in seconds\nconst STALE_PRICE_THRESHOLD = 0.05; // 5% threshold for stale prices\nconst swapKind = SwapKind.GivenIn;\n\nclass BexAggregator extends BaseAggregator {\n name = Aggregators.HubPools;\n supportedChains = [ChainId.MAINNET, ChainId.BEPOLIA];\n readonly url = getUriFromLink(this.config.api);\n readonly type = \"graphql\";\n\n /**\n * Helper function to convert zero address to wrapped token address\n */\n private convertZeroToWrapped(address: Address): Address {\n return isToken(address, \"BERA\") ? this.config.tokens.wbera : address;\n }\n\n /**\n * Helper to calculate price impact percentage\n */\n private calculatePriceImpact(priceImpact: {\n error: string | null;\n priceImpact?: string;\n }): number {\n if (priceImpact.error) {\n console.error(\"Swap price impact error\", priceImpact);\n return 0;\n }\n\n return Number(priceImpact.priceImpact);\n }\n\n /**\n * Helper to check for stale SOR prices\n */\n private checkStalePrices({\n onChainAmount,\n sorPaths,\n sorAmount,\n queryData,\n }: {\n onChainAmount: TokenAmount;\n sorPaths: { pools: string[] }[];\n sorAmount: string;\n queryData: IAggregatorArgs;\n }): void {\n // Check for stale prices\n const deltaFromSorAmount =\n Number.parseFloat(formatEther(onChainAmount.scale18)) /\n Number.parseFloat(sorAmount);\n\n if (Math.abs(1 - deltaFromSorAmount) > STALE_PRICE_THRESHOLD) {\n console.warn(\n \"SOR returned stale prices. Delta from return amount is more than 5%\",\n {\n deltaFromSorAmount,\n },\n );\n\n const error = new BeraError({\n reason: \"SOR_STALE_PRICES\",\n level: \"warning\",\n message:\n \"SOR returned stale prices. Delta from return amount is more than 5%\",\n extra: {\n deltaFromSorAmount,\n pools: sorPaths.map((p) => p.pools),\n onChainAmount: formatEther(onChainAmount.scale18),\n sorAmount,\n queryData,\n },\n fingerprint: [\"SOR_STALE_PRICES\"],\n });\n BeraMonitoring.captureException(error);\n }\n }\n\n async getQuote(args: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n const balancerApi = new BalancerApi(\n this.url,\n // @ts-expect-error b-sdk has more chains than berajs\n this.chainId,\n );\n const {\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n publicClient,\n } = args;\n this.assertChainSupport({ tokenIn, tokenOut });\n\n assertPublicClient(publicClient);\n\n const wberaIsBera = isToken(tokenIn, \"BERA\") || isToken(tokenOut, \"BERA\");\n\n // Initialize tokens\n const tokenInV3 = new Token(\n this.chainId,\n this.convertZeroToWrapped(tokenIn.address),\n tokenIn.decimals,\n );\n const tokenOutV3 = new Token(\n this.chainId,\n this.convertZeroToWrapped(tokenOut.address),\n tokenOut.decimals,\n );\n\n const tokenAmount = TokenAmount.fromRawAmount(\n tokenInV3,\n amount as `${number}`,\n );\n\n // swap paths\n const {\n paths: sorPaths,\n priceImpact,\n returnAmount: sorAmount,\n }: SorSwapResult = await balancerApi.sorSwapPaths.fetchSorSwapPaths({\n // @ts-expect-error b-sdk has more chains than berajs\n chainId: this.chainId,\n tokenIn: tokenInV3.address,\n tokenOut: tokenOutV3.address,\n swapKind,\n swapAmount: tokenAmount,\n });\n\n if (!sorPaths?.length) {\n throw new RequestError({\n response: undefined,\n endpoint: {\n url: this.url,\n name: this.name,\n type: this.type,\n },\n reason: BaseAggregator.PATH_NOT_FOUND_REASON,\n chainId: this.chainId,\n payload: {\n tokenIn: tokenInV3.address,\n tokenOut: tokenOutV3.address,\n swapKind,\n swapAmount: tokenAmount,\n },\n message: `No swap paths returned from Balancer API`,\n });\n }\n\n // execute swap query\n const swap = new Swap({\n chainId: this.chainId,\n paths: sorPaths,\n swapKind,\n userData: \"0x\" as `0x${string}`,\n });\n const queryOutput = await swap.query(publicClient.transport.url);\n\n if (!(\"expectedAmountOut\" in queryOutput)) {\n throw new Error(\"No Bex paths found\");\n }\n\n this.checkStalePrices({\n onChainAmount: queryOutput.expectedAmountOut,\n sorPaths,\n sorAmount,\n queryData: args,\n });\n\n // format quote response\n return {\n amountOut: queryOutput.expectedAmountOut.amount.toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: queryOutput.to,\n }),\n name: this.name,\n priceImpactPercentage: this.calculatePriceImpact(priceImpact),\n swapFeeBps: 0,\n getCalldata: ({ account }) => {\n // generate user transaction data\n const callData = swap.buildCall({\n slippage: Slippage.fromPercentage(slippage.toString() as `${number}`),\n deadline: BigInt(Math.round(Date.now() / 1000) + DEFAULT_DEADLINE),\n queryOutput,\n sender: account as Address,\n recipient: account as Address,\n wethIsEth: wberaIsBera,\n });\n\n const { args: params, functionName } = decodeFunctionData({\n abi: balancerVaultAbi,\n data: callData.callData,\n });\n\n return {\n params,\n functionName,\n abi: balancerVaultAbi,\n address: callData.to,\n value: callData.value || BigInt(0),\n };\n },\n };\n }\n}\n\nexport const bex = new BexAggregator();\n","import { ChainId } from \"@berachain/config/internal\";\n\nimport { Aggregators } from \"~/enum/dex\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n MinimalERC20,\n} from \"~/types/dex\";\nimport { beraToken, isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\nclass RedeemBgtAggregator extends BaseAggregator {\n name = Aggregators.RedeemBgt;\n supportedChains = [ChainId.MAINNET, ChainId.BEPOLIA];\n readonly type = \"rpc\";\n\n checkChainSupport({\n tokenIn,\n tokenOut,\n }: {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n }): boolean {\n if (!super.checkChainSupport({ tokenIn, tokenOut })) {\n return false;\n }\n\n return (\n // only supported on same chain\n tokenIn.chainId === tokenOut.chainId &&\n isToken(tokenIn, \"BGT\", { chainId: tokenIn.chainId }) &&\n isToken(tokenOut, \"BERA\")\n );\n }\n // handles native swaps: wrap and unwrap\n async getQuote({\n tokenIn,\n amount,\n }: Omit<\n IAggregatorArgs,\n \"slippage\" | \"feeBps\" | \"tokenOut\" | \"account\"\n >): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({\n tokenIn,\n tokenOut: { ...beraToken, chainId: tokenIn.chainId },\n });\n\n if (!isToken(tokenIn, \"BGT\", { config: this.config })) {\n throw new InvalidArgumentError({\n property: \"tokenIn\",\n value: tokenIn,\n expected: \"BGT\",\n level: \"warning\",\n });\n }\n\n return {\n amountOut: amount,\n amountIn: amount,\n allowanceRequirements: [],\n name: Aggregators.RedeemBgt,\n isNativeSwap: true,\n swapFeeBps: 0,\n // not adding calldata here because it depends on the connected wallet\n // bgt redeem requires a receiver address\n // moreover this is a sensitive operation, better be sure of what data is being sent\n // by controlling it on the consumer side\n } as const;\n }\n}\n\nexport const bgtRedeem = new RedeemBgtAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { metaAggregatorAbi as aggregatorsRouterAbi } from \"@berachain/abis/meta-aggregator/metaAggregator\";\n\nimport { Aggregators } from \"~/enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\nimport { BaseAggregator } from \"../base\";\n\nclass EnsoAggregator extends BaseAggregator {\n name = Aggregators.Enso;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n needsAccountForQuote = true;\n\n notFoundMessages: string[] = [\n \"Could not build shortcuts for route\",\n \"Could not quote shortcuts for route\",\n \"Swap not found for a required underlying of defi route,\",\n \"No route found from\",\n ];\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=enso`\n : `${this.config.bex.aggregatorsProxyUrl}/enso/api/v1/shortcuts/route?`;\n\n const url = new URL(this.url);\n url.searchParams.set(\n \"fromAddress\",\n this.config.bex.aggregatorsRouterExecutor,\n );\n url.searchParams.set(\"receiver\", this.config.bex.aggregatorsRouterExecutor);\n url.searchParams.set(\"spender\", this.config.bex.aggregatorsRouterExecutor);\n url.searchParams.set(\"amountIn\", inputAmountAfterFees);\n url.searchParams.set(\"tokenIn\", tokenInAddress);\n url.searchParams.set(\"tokenOut\", tokenOutAddress);\n url.searchParams.set(\"chainId\", ChainId.MAINNET.toString());\n url.searchParams.set(\"slippage\", (Number(slippage) * 100).toString());\n url.searchParams.set(\"refundReceiver\", account);\n\n const response = await this.fetch(url);\n\n const quote = await response.json();\n\n const inputData = this.getInputData({\n tokenIn: tokenInAddress,\n amountIn: amount,\n isNative: isTokenInNative,\n });\n\n const outputData = {\n tokenOut: tokenOutAddress,\n receiver: account,\n minAmountOut: this.getMinAmountOut(quote.amountOut.toString(), slippage),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quote.tx?.to,\n data: quote.tx?.data,\n };\n\n return {\n amountOut: quote.amountOut.toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n getCalldata: () => ({\n params: [\n inputData,\n outputData,\n aggregatorData,\n {\n rewardVault: rewardVault ?? zeroAddress,\n isSwapAndStake: !!rewardVault,\n },\n ],\n functionName: \"swap\",\n abi: aggregatorsRouterAbi,\n // send full amount to router first, which will deduct the swap fee before executing trade\n value: isTokenInNative ? BigInt(amount) : BigInt(\"0\"),\n address: this.config.bex.aggregatorsRouter,\n }),\n };\n }\n}\n\nexport const enso = new EnsoAggregator();\n","import { erc4626Abi, formatUnits } from \"viem\";\n\nimport { wberaStakerVaultAbi as stakeBeraVaultAbi } from \"@berachain/abis/pol/wberaStakerVault\";\n\nimport { ContractName } from \"~/enum/contracts\";\nimport { Aggregators } from \"~/enum/dex\";\nimport { assertDefined, assertPublicClient } from \"~/errors/assert\";\nimport type { IAggregatorArgs, IRawAggregatorQuote, Token } from \"~/types/dex\";\nimport type { IContractWrite } from \"~/types/global\";\nimport { isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\n/**\n * Aggregator that handles direct deposits into ERC4626 vault tokens.\n * Instead of routing through a DEX, this deposits the underlying asset directly\n * into the vault contract (e.g. WBERA → swBERA, HONEY → iBERA, or Bend vault underlying → vault token).\n *\n * Special-cases native BERA → swBERA via `depositNative` (no approval needed).\n */\nclass ERC4626Aggregator extends BaseAggregator {\n name = Aggregators.ERC4626;\n supportedChains = null;\n readonly type = \"rpc\";\n\n /**\n * Returns true when tokenOut is an ERC4626 vault whose underlying asset matches tokenIn,\n * or when depositing native BERA into swBERA.\n */\n checkChainSupport({\n tokenIn,\n tokenOut,\n underlyingToken,\n }: {\n tokenIn: Token;\n tokenOut: Token;\n underlyingToken?: Token;\n }): boolean {\n const result =\n super.checkChainSupport({ tokenIn, tokenOut, underlyingToken }) &&\n !!underlyingToken &&\n underlyingToken?.chainId === tokenOut.chainId &&\n (isToken(underlyingToken, tokenIn) ||\n // this is a special case for the swbera vault\n (isToken(tokenIn, \"BERA\") && isToken(tokenOut, \"SWBERA\")));\n\n return result;\n }\n\n /**\n * Fetches a deposit quote by calling `convertToShares` on the vault.\n * Returns calldata for either `deposit` (ERC20) or `depositNative` (BERA → swBERA).\n */\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n underlyingToken,\n publicClient,\n }: Omit<\n IAggregatorArgs,\n \"slippage\" | \"feeBps\"\n >): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut, underlyingToken });\n\n assertDefined(underlyingToken, \"underlyingToken\");\n assertPublicClient(publicClient);\n\n const rawOutputAmount = await publicClient.readContract({\n address: tokenOut.address,\n abi: erc4626Abi,\n functionName: \"convertToShares\",\n args: [BigInt(amount)],\n });\n\n const isSwBeraNative =\n isToken(tokenOut, \"SWBERA\") && isToken(tokenIn, \"BERA\");\n\n return {\n amountOut: rawOutputAmount.toString(),\n amountIn: amount,\n allowanceRequirements: isSwBeraNative\n ? []\n : [\n {\n token: tokenIn,\n spender: tokenOut.address,\n amount: {\n raw: amount,\n formatted: formatUnits(BigInt(amount), tokenIn.decimals),\n },\n },\n ],\n name: Aggregators.ERC4626,\n isNativeSwap: false,\n swapFeeBps: 0,\n getCalldata: ({ account }) =>\n isSwBeraNative\n ? ({\n abi: stakeBeraVaultAbi,\n address: tokenOut.address,\n functionName: \"depositNative\",\n params: [BigInt(amount), account],\n value: BigInt(amount),\n } satisfies Omit<\n IContractWrite<typeof stakeBeraVaultAbi, \"depositNative\">,\n \"message\" | \"actionType\"\n >)\n : ({\n abi: erc4626Abi,\n address: tokenOut.address,\n functionName: \"deposit\",\n contractName: ContractName.ERC4626,\n params: [BigInt(amount), account],\n value: 0n,\n } satisfies Omit<\n IContractWrite<typeof erc4626Abi, \"deposit\">,\n \"message\" | \"actionType\"\n >),\n };\n }\n}\n\nexport const erc4626Deposit = new ERC4626Aggregator();\n","import { type Address, type Hex, zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { metaAggregatorAbi as aggregatorsRouterAbi } from \"@berachain/abis/meta-aggregator/metaAggregator\";\n\nimport { Aggregators } from \"~/enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\nimport { isToken } from \"~/utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\nconst BASE_URL = \"https://api.fly.trade/aggregator\";\n\nclass FlyAggregator extends BaseAggregator {\n name = Aggregators.Fly;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n\n notFoundMessages: string[] = [\n \"Couldn't recognize to token\",\n \"Couldn't recognize from 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,\n aggregatorsFeeBps,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n 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 // 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 allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps ?? 0,\n };\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\n this.url = txUrl.toString();\n\n const txParams = new URLSearchParams({\n quoteId: quoteData.id,\n estimateGas: \"false\",\n });\n\n txUrl.search = txParams.toString();\n\n const txResponse = await this.fetch(txUrl);\n\n const txData: {\n to: Address;\n data: Hex;\n } = await txResponse.json();\n\n return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\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 return {\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}\n\nexport const fly = new FlyAggregator();\n","import { formatUnits, parseUnits, zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { metaAggregatorAbi as aggregatorsRouterAbi } from \"@berachain/abis/meta-aggregator/metaAggregator\";\n\nimport { Aggregators, SwapReferrer } from \"~/enum/dex\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } 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 aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n referrer,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n if (tokenIn.decimals === undefined || tokenOut.decimals === undefined) {\n throw new BeraError({\n message: \"Missing required params\",\n level: \"error\",\n });\n }\n\n this.assertChainSupport({ tokenIn, tokenOut });\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n // 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 tokenIn.decimals,\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 tokenOut.decimals,\n ).toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n };\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 return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\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(\n formattedQuote.amountOut,\n slippage,\n ),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: solveData.to,\n data: solveData.data,\n };\n return {\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}\n\nexport const haiku = new HaikuAggregator();\n","import { type Address, formatUnits } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\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 { Aggregators } from \"~/enum/dex\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n Token,\n 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 /**\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 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 checkChainSupport({\n tokenIn,\n tokenOut,\n honeyNativeState,\n }: {\n tokenIn: Token;\n tokenOut: Token;\n honeyNativeState?: Pick<HoneyConfigContextReturn, \"collateralList\">;\n }): boolean {\n return (\n super.checkChainSupport({ tokenIn, tokenOut }) &&\n tokenIn.chainId === tokenOut.chainId &&\n this.isHoneyNativeSwap({\n tokenIn: tokenIn.address,\n tokenOut: tokenOut.address,\n honeyNativeState,\n })\n );\n }\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n publicClient,\n account,\n honeyNativeState,\n }: IHoneyNativeArgs): Promise<IRawAggregatorQuote | 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.assertChainSupport({ tokenIn, tokenOut });\n\n const isMint = isToken(tokenOut, this.honeyToken);\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(collateral.address, isMint ? tokenIn.address : tokenOut.address),\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?.balance.formatted ?? \"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 = 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 collateralList: hubOrderedCollaterals,\n publicClient,\n priceFeedMap: undefined,\n isPythWrapperEnabled: false,\n });\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 allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: Aggregators.Honey,\n swapFeeBps: 0,\n getCalldata: ({ account }) => {\n return payload({ account });\n },\n };\n }\n}\n\nexport const honeyNative = new HoneyNativeAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { metaAggregatorAbi as aggregatorsRouterAbi } from \"@berachain/abis/meta-aggregator/metaAggregator\";\n\nimport { Aggregators } from \"~/enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\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 aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n const {\n isTokenInNative,\n isTokenOutNative,\n tokenInAddress,\n tokenOutAddress,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=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 name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n } satisfies IRawAggregatorQuote;\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 return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\n const outputData = {\n tokenOut: tokenOutAddress,\n receiver: account,\n minAmountOut: this.getMinAmountOut(\n formattedQuote.amountOut,\n slippage,\n ),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: buildData.data.routerAddress,\n data: buildData.data.data,\n };\n return {\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}\n\nexport const kyberswap = new KyberSwapAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { metaAggregatorAbi as aggregatorsRouterAbi } from \"@berachain/abis/meta-aggregator/metaAggregator\";\n\nimport { Aggregators } from \"~/enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\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 aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n 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 allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n spender: this.config.bex.aggregatorsRouter,\n rawAmount: amount,\n }),\n name: this.name,\n priceImpactPercentage: quote.priceImpact,\n swapFeeBps: aggregatorsFeeBps!,\n } satisfies IRawAggregatorQuote;\n\n return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\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(\n formattedQuote.amountOut,\n slippage,\n ),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quote.tx?.to,\n data: quote.tx?.data,\n };\n return {\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}\n\nexport const oogabooga = new OogaboogaAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { metaAggregatorAbi as aggregatorsRouterAbi } from \"@berachain/abis/meta-aggregator/metaAggregator\";\n\nimport { Aggregators } from \"~/enum/dex\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport { RequestError } from \"~/errors/RequestError\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\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 publicClient,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n assertPublicClient(publicClient);\n\n if (!tokenIn.decimals) {\n throw new InvalidArgumentError({\n property: \"tokenIn.decimals\",\n value: tokenIn.decimals,\n expected: \"number\",\n chainId: this.chainId,\n });\n }\n\n this.assertChainSupport({ tokenIn, tokenOut });\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.address, tokenOut.address);\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 allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n };\n\n return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\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(\n formattedQuote.amountOut,\n slippage,\n ),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quoteData.data.to,\n data: quoteData.data.data,\n };\n return {\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}\n\nexport const openOcean = new OpenOceanAggregator();\n","import { ChainId } from \"@berachain/config/internal\";\n\nimport { wberaAbi } from \"@berachain/abis/wbera\";\n\nimport { Aggregators } from \"~/enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote, Token } from \"~/types/dex\";\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 checkChainSupport({\n tokenIn,\n tokenOut,\n }: {\n tokenIn: Token;\n tokenOut: Token;\n }): boolean {\n if (\n // same chain\n tokenIn.chainId !== tokenOut.chainId ||\n // must be one of our chains\n !super.checkChainSupport({ tokenIn, tokenOut })\n ) {\n return false;\n }\n\n return (\n (isToken(tokenIn, \"BERA\") && isToken(tokenOut, \"WBERA\")) ||\n (isToken(tokenIn, \"WBERA\") && isToken(tokenOut, \"BERA\"))\n );\n }\n\n // handles native swaps: wrap and unwrap\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n }: Omit<\n IAggregatorArgs,\n \"slippage\" | \"feeBps\"\n >): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const isWrap = isToken(tokenIn, \"BERA\") && isToken(tokenOut, \"WBERA\");\n\n return {\n amountOut: amount,\n amountIn: amount,\n allowanceRequirements: [],\n name: isWrap ? Aggregators.Wrap : Aggregators.Unwrap,\n isNativeSwap: true,\n swapFeeBps: 0,\n getCalldata: () => {\n return 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}\n\nexport const wberaSwap = new WBeraAggregator();\n","import useSWRImmutable from \"swr/immutable\";\nimport { type PublicClient, zeroAddress } from \"viem\";\n\nimport { metaAggregatorAbi as aggregatorsRouterAbi } from \"@berachain/abis/meta-aggregator/metaAggregator\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 useSWRImmutable from \"swr/immutable\";\n\nimport { useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { getUnderlyingToken } from \"~/actions/tokens/getUnderlyingToken\";\nimport type { MinimalERC20 } from \"~/types/dex\";\nimport { isToken } from \"~/utils/tokens\";\n\n/**\n * SWR hook that resolves the underlying asset of an ERC4626 vault token.\n * Returns `null` for non-vault tokens. Results are cached immutably since\n * a vault's underlying asset doesn't change.\n */\nexport function useUnderlyingAsset({ token }: { token: MinimalERC20 }) {\n const wagmiConfig = useConfig();\n\n return useSWRImmutable(\n token && wagmiConfig && !isToken(token, \"BERA\")\n ? [\"useUnderlyingAsset\", token]\n : null,\n async ([, token]) => getUnderlyingToken({ token, wagmiConfig }),\n );\n}\n","import { type Config, getPublicClient } from \"@wagmi/core\";\nimport { erc4626Abi } from \"viem\";\n\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { initBeraError } from \"~/errors/initBeraError\";\nimport type { MinimalERC20 } from \"~/types/dex\";\nimport { isToken } from \"~/utils/tokens\";\nimport { getTokenInformation } from \"./getTokenInformation\";\n\n/**\n * Attempts to resolve the underlying asset of an ERC4626 vault by calling `asset()`.\n * Returns the full token info if the token is an ERC4626 vault, or `null` if it isn't\n * (i.e. the `asset()` call reverts). Skips the native gas token (BERA) since it can't be a vault.\n */\nexport async function getUnderlyingToken({\n token,\n wagmiConfig,\n}: {\n token: MinimalERC20;\n wagmiConfig: Config;\n}) {\n try {\n if (isToken(token, \"BERA\")) {\n // gas token can't have an underlying token\n return null;\n }\n\n const publicClient = getPublicClient(wagmiConfig, {\n chainId: token.chainId,\n });\n\n assertPublicClient(publicClient);\n\n const address = await publicClient.readContract({\n address: token.address,\n abi: erc4626Abi,\n functionName: \"asset\",\n });\n\n return await getTokenInformation({\n address: address,\n publicClient,\n chainId: token.chainId,\n });\n } catch (e) {\n const err = initBeraError({ cause: e });\n if (err.reason === 'The contract function \"asset\" reverted.') {\n return null;\n }\n\n throw err;\n }\n}\n","import useSWR, { type SWRConfiguration } from \"swr\";\nimport { type Address, type PublicClient, parseUnits, zeroAddress } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { BaseAggregator } from \"~/actions/dex/aggregators/base\";\nimport { useBeraFlag } from \"~/contexts/BeraFlags/BeraFlags\";\nimport type {\n HoneyConfigContextReturn,\n TokenWithOrder,\n} from \"~/contexts/HoneyConfigProvider\";\nimport { Aggregators, type SwapReferrer } from \"~/enum/dex\";\nimport { POLLING } from \"~/enum/polling\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { RequestError } from \"~/errors/RequestError\";\nimport { useAggregatorsRouterFeeBps } from \"~/hooks/dex/useAggregatorsRouterFeeBps\";\nimport type { MinimalERC20 } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\nimport { seconds } from \"~/utils/time\";\nimport { isToken } from \"~/utils/tokens\";\n\nexport type IUseAggregatorsQuotesArgs = BeraJS.BaseFunctionArgs & {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n amount: string;\n slippage: number;\n referrer?: SwapReferrer;\n rewardVault?: Address;\n /**\n * Useful cause the collaterals are provided byt he honeyContext and this way we can\n * use the Provider only in the swap page where is needed.\n *\n * The collaterals for the honey mint/redeem aggregator.\n */\n honeyNativeState?: Pick<\n HoneyConfigContextReturn,\n \"collateralList\" | \"protocol\"\n >;\n underlyingToken?: MinimalERC20 | null;\n};\n\ntype IQueryKey = readonly [\n string, // \"useAggregatorsQuotes\n string, // name\n MinimalERC20, // tokenIn\n MinimalERC20, // tokenOut\n string, // parsedAmount\n number, // slippage\n Address | undefined, // account\n number | undefined, // feeBps\n SwapReferrer | undefined, // referrer\n Address | undefined, // rewardVault\n MinimalERC20 | null | undefined, // underlyingToken\n TokenWithOrder[] | undefined, // collateralList\n];\n\nexport const USE_AGGREGATORS_QUOTES_QUERY_KEY = \"useAggregatorsQuotes\";\n\n/**\n * Builds the SWR cache key for a single aggregator quote request.\n * Returns `null` (disabling the query) when the aggregator is unsupported,\n * disabled via config flags, or missing required dependencies like feeBps.\n */\nfunction getQueryKey({\n aggregator,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n isMAEnabled,\n}: {\n aggregator: BaseAggregator;\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 isMAEnabled: boolean;\n}): IQueryKey | null {\n if (options?.opts?.isEnabled !== undefined && !options?.opts?.isEnabled) {\n return null;\n }\n\n if (!Number(args.amount)) {\n return null;\n }\n if (\n !aggregator.checkChainSupport({\n tokenIn: args.tokenIn,\n tokenOut: args.tokenOut,\n underlyingToken: args.underlyingToken,\n honeyNativeState: args.honeyNativeState,\n })\n ) {\n return null;\n }\n\n const name = aggregator.name;\n\n const usesMAContract = ![\n Aggregators.HubPools,\n Aggregators.Honey,\n Aggregators.Wrap,\n Aggregators.Unwrap,\n Aggregators.ERC4626,\n ].includes(name);\n\n if (!isMAEnabled && usesMAContract) {\n return null;\n }\n const { tokenIn, tokenOut, amount, slippage, referrer, rewardVault } = args;\n\n const parsedAmount = parseUnits(amount, tokenIn.decimals).toString();\n\n const isEnabledOnConfig =\n // always enable wrap and unwrap\n aggregator.name === Aggregators.Wrap ||\n aggregator.name === Aggregators.RedeemBgt ||\n aggregator.name === Aggregators.Honey ||\n !activeAggregators ||\n activeAggregators.includes(name.toLowerCase().replaceAll(\" \", \"\"));\n\n if (!isEnabledOnConfig) {\n return null;\n }\n if (\n aggregator.name === Aggregators.Honey &&\n args.honeyNativeState?.protocol.isPaused\n ) {\n // if the honey protocol is paused, don't query any quotes\n return null;\n }\n\n const needsUnderlyingToken =\n aggregator.name === Aggregators.ERC4626 ||\n aggregator.name === Aggregators.EnsoErc4626;\n\n if (usesMAContract && feeBps === undefined) {\n return null;\n }\n\n return [\n USE_AGGREGATORS_QUOTES_QUERY_KEY,\n name,\n tokenIn,\n tokenOut,\n parsedAmount,\n slippage,\n aggregator.needsAccountForQuote ? account : undefined,\n usesMAContract ? feeBps : 0,\n referrer,\n rewardVault,\n needsUnderlyingToken ? args.underlyingToken : undefined,\n aggregator.name === Aggregators.Honey\n ? args.honeyNativeState?.collateralList\n : undefined,\n ];\n}\n\n/**\n * Creates the SWR fetcher that calls `aggregator.getQuote()` with\n * the parameters extracted from the query key tuple.\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 referrer,\n rewardVault,\n underlyingToken,\n honeyCollaterals,\n ]: IQueryKey) =>\n aggregator.getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account,\n aggregatorsFeeBps,\n publicClient,\n proxyAggregatorsThroughVercel,\n referrer,\n rewardVault,\n underlyingToken,\n honeyNativeState: {\n collateralList: honeyCollaterals ?? [],\n },\n });\n}\n\n/**\n * this hook is used internally to avoid caling the same hook and checks\n * on every useSingleAggregatorQuote call, when called inside useAggregatorsQuotes.\n *\n * @internal\n */\nexport function raw_useSingleAggregatorQuote(\n {\n feeBps,\n publicClient,\n account,\n proxyAggregatorsThroughVercel,\n activeAggregators,\n isMAEnabled,\n ...args\n }: IUseAggregatorsQuotesArgs & {\n account: Address | undefined;\n aggregator: BaseAggregator;\n feeBps: number | undefined;\n activeAggregators: string[] | undefined;\n isMAEnabled: boolean;\n publicClient: PublicClient | undefined;\n proxyAggregatorsThroughVercel: boolean | undefined;\n },\n options?: DefaultHookOptions,\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 return useSWR(\n getQueryKey({\n aggregator: args.aggregator,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n isMAEnabled,\n }),\n getQueryFn({\n aggregator: args.aggregator,\n proxyAggregatorsThroughVercel,\n publicClient,\n }),\n options?.opts,\n );\n}\n\n/**\n * Returns shared SWR options for aggregator quote polling, including\n * custom error retry logic that stops retrying on \"path not found\" and 403 errors.\n */\nexport function getAggregatorsSWROptions(\n options?: DefaultHookOptions,\n): SWRConfiguration {\n return {\n refreshInterval: POLLING.FAST, // every 10s\n errorRetryCount: 3,\n ...options?.opts,\n // biome-ignore lint/nursery/useMaxParams: the function is defined in the SWRConfiguration type\n onErrorRetry(err, key, config, revalidate, revalidateOpts) {\n options?.opts?.onErrorRetry?.(\n err,\n key,\n config,\n revalidate,\n revalidateOpts,\n );\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\n/**\n * Standalone hook for fetching a quote from a single aggregator.\n * Resolves wallet, fee, and feature flag context internally — use this\n * when you need a quote outside of the `useAggregatorsQuotes` multi-quote flow.\n */\nexport function useSingleAggregatorQuote(\n args: IUseAggregatorsQuotesArgs & { aggregator: BaseAggregator },\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\n const { data: feeBps } = useAggregatorsRouterFeeBps();\n\n if (args.aggregator.name !== Aggregators.Wrap) {\n const isWrapOrUnwrap =\n (isToken(args.tokenIn.address, \"BERA\") ||\n isToken(args.tokenIn.address, \"WBERA\")) &&\n (isToken(args.tokenOut.address, \"BERA\") ||\n isToken(args.tokenOut.address, \"WBERA\"));\n\n if (!isWrapOrUnwrap) {\n return null;\n }\n }\n\n const { config } = parseBaseArgs(args);\n\n const isMAEnabled = config.bex.aggregatorsRouter !== zeroAddress;\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 return raw_useSingleAggregatorQuote(\n {\n ...args,\n aggregator: args.aggregator,\n feeBps,\n activeAggregators,\n account,\n isMAEnabled,\n publicClient,\n proxyAggregatorsThroughVercel,\n },\n { ...options, opts: getAggregatorsSWROptions(options) },\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/global\";\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/InvalidArgumentError\";\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 { poolCreationHelperAbi as balancerPoolCreationHelperAbi } from \"@berachain/abis/bex/poolCreationHelper\";\n\nimport {\n GetDedupedSubgraphPools,\n type GetDedupedSubgraphPoolsQuery,\n type SubgraphPoolFragment,\n} from \"@berachain/graphql/dex/subgraph\";\n\nimport { getApolloClient } from \"~/actions/clients/getApolloClient\";\nimport { TransactionActionType } from \"~/enum/txnEnum\";\nimport type { Token, TokenWithAmount } from \"~/types/dex\";\nimport type { IContractWrite } from \"~/types/global\";\nimport { DEFAULT_METAMASK_GAS_LIMIT } from \"~/utils/constants\";\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: TokenWithAmount[];\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: TokenWithAmount[];\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: TokenWithAmount[];\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/dex\";\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/dex\";\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 { erc20Abi, formatUnits, type PublicClient } from \"viem\";\n\nimport {\n GetExploitedTokens,\n type GetExploitedTokensQuery,\n type GetExploitedTokensQueryVariables,\n} from \"@berachain/graphql/dex/subgraph\";\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport type { Token } from \"~/types/dex\";\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 { PoolCreationStep } from \"~/enum/dex\";\nimport type { TokenCurrentPriceMap, TokenWithAmount } from \"~/types/dex\";\nimport { wrapNativeTokens } from \"~/utils/tokenWrapping\";\nimport { type Oracle, OracleMode } from \"./useCreatePool\";\n\nconst DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT = 0.05; // 5%\n\nexport type LiquidityMismatchInfo = {\n title: string | null;\n message: string | null;\n suggestWeighted?: boolean;\n};\n\ninterface UseLiquidityMismatchParams {\n currentStep: PoolCreationStep;\n tokenPrices?: TokenCurrentPriceMap;\n isLoadingTokenPrices: boolean;\n tokens: TokenWithAmount[] | null;\n weights: bigint[] | null;\n weightsError: string | null;\n poolType: PoolType;\n liquidityMismatchTolerancePercent?: number;\n oracles: Oracle[];\n}\n\n/**\n * Hook for detecting liquidity mismatches.\n *\n * @param {PoolCreationStep} currentStep - The current step of the pool creation process.\n * @param {Record<string, number>} tokenPrices - The current token prices.\n * @param {boolean} isLoadingTokenPrices - Whether the token prices are still loading.\n * @param {Array<{ address: string, amount: number }>} tokens - The tokens in the pool, including their addresses and amounts.\n * @param {Record<string, number>} weights - The per-token weights in the pool we are creating.\n * @param {string | null} weightsError - An error message for the weights indicating that the weights are invalid.\n * @param {string} poolType - The type of pool being created.\n * @param {number} liquidityMismatchTolerancePercent - The tolerance for liquidity mismatches in percent.\n * @returns {Object} The liquidity mismatch info.\n */\nexport const useLiquidityMismatch = ({\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent = DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT,\n oracles,\n}: UseLiquidityMismatchParams): LiquidityMismatchInfo => {\n // NOTE: would be nice to use Maps/Records more in here, as the zipping/unzipping is cumbersome.\n // NOTE: if we pull in string literal for currentStep things would also be a bit clearer in here.\n const [liquidityMismatchInfo, setLiquidityMismatchInfo] =\n useState<LiquidityMismatchInfo>({ title: null, message: null });\n\n useEffect(() => {\n // If we are either using custom rate-providing oracles or have incorrect/loading token prices, we cant do validation.\n if (\n !tokenPrices ||\n isLoadingTokenPrices ||\n !tokens ||\n !weights ||\n weightsError ||\n tokens.some((token) => !token.address) ||\n oracles.some((oracle) => oracle.mode === OracleMode.Custom) // Oracles give prices on their own, we dont support that here yet.\n ) {\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Calculate some basic metrics we'll use to determine per-token contributions and model potential losses from arbitrage.\n let totalLiquidityUSD = 0;\n const tokenUSDAmounts: number[] = [];\n const numTokens = tokens.length;\n const wrappedTokens = wrapNativeTokens(tokens);\n const tokenUSDPrices = wrappedTokens.map((token) => {\n const tokenPriceUSD =\n tokenPrices[token.address.toLowerCase()]?.price ?? 0;\n if (!tokenPriceUSD || tokenPriceUSD === 0) {\n tokenUSDAmounts.push(0);\n return null;\n }\n const tokenAmountUSD = tokenPriceUSD * Number.parseFloat(token.amount);\n tokenUSDAmounts.push(tokenAmountUSD);\n totalLiquidityUSD += tokenAmountUSD;\n return tokenPriceUSD;\n });\n\n // Doesn't matter what step it is, if we have missing token prices for tokens we have selected, we cant issue a real warning.\n if (\n tokenUSDPrices.some((price) => price === null) ||\n tokenUSDPrices.length !== numTokens\n ) {\n setLiquidityMismatchInfo({\n title: \"Missing token price data\",\n message: `One or more token(s) do not have valid market price data. Please verify that token market prices align with the pool\n weightings and your initial liquidity amounts.`,\n });\n return;\n }\n\n // Step 1 - During token selection we check for a deviation in the quote prices of the tokens selected (for stable pools).\n if (\n currentStep === PoolCreationStep.SELECT_TOKENS &&\n poolType === PoolType.ComposableStable\n ) {\n const normalizedUSDPrices = tokenUSDPrices.map(\n (priceUSD) => priceUSD! / tokenUSDPrices[0]!, // always normalize on the first token's price\n );\n const maxDifference =\n Math.max(...normalizedUSDPrices) - Math.min(...normalizedUSDPrices);\n\n if (maxDifference > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n title: \"Selected tokens have a significant price deviation\",\n message: \"Did you mean to create a Weighted pool instead?\",\n suggestWeighted: true,\n });\n } else {\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n\n return;\n }\n\n // Validation During Liquidity Input and onwards.\n if (\n totalLiquidityUSD === 0 ||\n tokenUSDAmounts.some((value) => value === 0)\n ) {\n // User has not yet entered fully their liquidity values, so return early.\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Simulate arbitrage for the pool to determine potential losses from arbitrageurs.\n // NOTE: we assume shortfalls and excesses are losses, but in reality the actual losses would be more complex to realise.\n // Balancer does this similarily https://github.com/balancer/frontend-v2/blob/8563b8d33b6bff266148bd48d7ebc89f921374f4/src/components/cards/CreatePool/InitialLiquidity.vue#L75\n let totalLossUSD = 0;\n if (poolType === PoolType.ComposableStable) {\n const expectedPerTokenLiquidityUSD = totalLiquidityUSD / numTokens;\n tokenUSDAmounts.forEach((value) => {\n totalLossUSD += Math.abs(expectedPerTokenLiquidityUSD - value);\n });\n } else if (poolType === PoolType.Weighted) {\n tokenUSDAmounts.forEach((value, index) => {\n const weightProportion = Number(weights[index]) / 1e18;\n const expectedValueUSD = totalLiquidityUSD * weightProportion;\n totalLossUSD += Math.abs(expectedValueUSD - value);\n });\n }\n\n // We'll show a total loss if it's 90% or more\n const isTotalLoss = totalLossUSD >= totalLiquidityUSD * 0.9;\n totalLossUSD = Math.min(totalLossUSD, totalLiquidityUSD);\n const totalLossPercentage = totalLossUSD / totalLiquidityUSD;\n\n if (totalLossPercentage > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n // If it's a total loss we dont display a percentage\n title: isTotalLoss\n ? \"You could lose all of your initial liquidity\"\n : `You could lose $${totalLossUSD.toFixed(2)} (~${(\n totalLossPercentage * 100\n ).toFixed(2)}%)`,\n message: `Based on the market token prices, the value of tokens does not align with the specified pool weights. \n This discrepancy could expose you to potential losses from arbitrageurs. ${\n poolType === PoolType.ComposableStable\n ? \"Did you mean to create a Weighted pool instead?\"\n : \"\"\n }`,\n suggestWeighted: poolType === PoolType.ComposableStable,\n });\n } else {\n // All good bb bb\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n }, [\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent,\n oracles,\n ]);\n return liquidityMismatchInfo;\n};\n","import { type Address, formatEther, isAddressEqual } from \"viem\";\n\nimport type { MinimalPoolFragment } from \"@berachain/graphql/dex/api\";\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport { useRewardVaultBalanceFromStakingToken } from \"~/hooks/pol/useRewardVaultBalanceFromStakingToken\";\nimport { usePollBalance } from \"~/hooks/tokens/usePollBalance\";\nimport type { IUserPosition } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\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.balance.formatted) * 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?.balance.formatted ?? \"0\").times(tokenRatio)\n : BigNumber(0);\n const price = Number(token.balanceUSD) / Number(token.balance);\n\n return {\n ...token,\n\n balance: {\n raw: userBalance?.isGreaterThan(0)\n ? userBalance\n .times(10 ** token.decimals!)\n .toFixed(0)\n .toString()\n : \"0\",\n formatted: userBalance.toString(),\n },\n price,\n usdValue:\n Number.isNaN(price) || !userBalance\n ? undefined\n : Number.parseFloat(userBalance.toString()) * price,\n };\n }),\n stakedBalance: userVaultTokenBalance?.address\n ? {\n ...userVaultTokenBalance,\n balance: {\n raw: userVaultTokenBalance.balance.toString(),\n // Pools always use the 18 decimals\n formatted: formatEther(userVaultTokenBalance.balance),\n },\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 { rewardVaultAbi } from \"@berachain/abis/pol/rewards/rewardVault\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { rewardVaultFactoryAbi } from \"@berachain/abis/pol/rewards/rewardVaultFactory\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { BalanceToken } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } 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 chainId,\n balance: data\n ? {\n raw: data.toString(),\n formatted: formattedBalance ?? \"0\",\n }\n : { raw: \"0\", formatted: \"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 { defaultChainId } from \"@berachain/config/internal\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getTokenInformation } from \"~/actions/tokens/getTokenInformation\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { Token } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\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 function 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, chainId = defaultChainId]) => {\n if (isToken(address, \"BERA\")) {\n return {\n address: zeroAddress,\n decimals: beraToken.decimals,\n name: beraToken.name,\n symbol: beraToken.symbol,\n chainId,\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 chainId,\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 { parseUnits, zeroAddress } from \"viem\";\n\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport { BeraError } from \"~/errors/BeraError\";\nimport { usePollAllowances } from \"~/hooks/tokens/usePollAllowances\";\nimport type { AllowanceQueryItem, AllowanceToken } from \"~/types/dex\";\nimport { isToken } from \"~/utils/tokens\";\n\ntype NeedsApprovalToken = AllowanceToken & {\n maxAmountIn: bigint;\n};\n\nfunction calculateMaxAmountIn({\n amount,\n decimals,\n slippage,\n}: {\n amount: bigint;\n decimals: number;\n slippage: number | undefined;\n}) {\n const slippageInWei = parseUnits((slippage ?? 0).toString(), decimals);\n return amount + (amount * slippageInWei) / BigInt(100 * 10 ** decimals);\n}\n\nexport function useMultipleTokenApprovalsWithSlippage(\n tokenInput: AllowanceQueryItem[],\n options?: {\n slippage?: number;\n },\n) {\n const { slippage } = options ?? {};\n\n const items = useMemo(\n () =>\n tokenInput\n .filter((token) => token.token.address !== zeroAddress)\n .filter((token) => BigNumber(token.amount.formatted).gt(0)),\n [tokenInput],\n );\n\n const {\n data: allowances,\n refresh,\n isLoading,\n } = usePollAllowances({\n items,\n });\n\n const needsApproval = useMemo<NeedsApprovalToken[]>(\n () =>\n allowances\n ?.map<NeedsApprovalToken | undefined>((allowance) => {\n const item = items.find((item) =>\n isToken(item.token.address, allowance.token),\n );\n\n if (!item) {\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 items,\n },\n });\n }\n\n const maxAmountIn = calculateMaxAmountIn({\n decimals: item.token.decimals,\n amount: BigInt(item.amount.raw),\n slippage,\n });\n\n if (BigNumber(allowance.allowance.raw).lt(maxAmountIn)) {\n return {\n ...item,\n needsApproval: true,\n maxAmountIn,\n allowance: {\n raw: allowance.allowance.raw,\n formatted: allowance.allowance.formatted,\n },\n };\n }\n\n return undefined;\n })\n .filter((token) => token !== undefined) ?? [],\n [allowances, slippage, items],\n );\n\n return {\n needsApproval,\n refresh,\n isLoading,\n };\n}\n","import useSWR from \"swr\";\n\nimport { useBeraWallet, useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { getAllowances } from \"~/actions/tokens/getAllowances\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { AllowanceQueryItem, AllowanceToken } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\n\nexport type UsePollAllowancesArgs = {\n items: AllowanceQueryItem[];\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 * @param chainId the chain ID to check allowances on\n */\nexport function usePollAllowances(\n args: UsePollAllowancesArgs,\n options?: DefaultHookOptions,\n): UsePollAllowancesResponse {\n const config = useConfig();\n\n const { address: account } = useBeraWallet();\n const QUERY_KEY =\n config && account && args?.items\n ? ([\"usePollAllowances\", account, args?.items] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, account, items]) => {\n return getAllowances({\n items,\n account,\n config,\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 { defaultChainId } from \"@berachain/config/internal\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getTokenInformation } from \"~/actions/tokens/getTokenInformation\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { Token } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\n\nexport type UseMultipleTokenInformationResponse = DefaultHookReturnType<\n Token[]\n>;\n\nexport type useMultipleTokenInformationArgs = {\n addresses: string[] | readonly string[] | undefined;\n chainId?: number;\n};\nexport function useMultipleTokenInformation(\n args: useMultipleTokenInformationArgs,\n options?: DefaultHookOptions,\n): UseMultipleTokenInformationResponse {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n publicClient && args.addresses\n ? ([\n \"useMultipleTokenInformation\",\n args.addresses,\n args.chainId ?? defaultChainId,\n ] as const)\n : null;\n\n const swrResponse = useSWRImmutable<Token[], unknown, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([, addresses, chainId]) => {\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 chainId,\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 { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport { type Address, isAddress, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { getTokenCurrentPrices } from \"~/actions/prices/getTokenCurrentPrices\";\nimport { POLLING } from \"~/enum/polling\";\nimport { useTokens } from \"~/hooks/tokens/useTokens\";\nimport type { TokenCurrentPriceMap, TokenWithPrice } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { isToken } from \"~/utils/tokens\";\n\n/**\n * @deprecated use useTokenPrices instead that supports multichain tokens\n */\nexport function useTokenCurrentPrices(\n {\n addressIn,\n }: {\n addressIn?: string[] | readonly string[];\n } = {},\n options: DefaultHookOptions = {\n opts: {\n refreshInterval: POLLING.NORMAL,\n revalidateOnFocus: true,\n },\n },\n) {\n const { tokenList, ensoTokens } = useTokens();\n\n /**\n * Berachain or Bepolia Tokens. All tokens from other chains are excluded since API doesn't price them.\n */\n const beraAddresses = useMemo<Address[]>(() => {\n const addresses: Address[] = [];\n\n if (addressIn) {\n addresses.push(\n ...(addressIn.filter((a): a is Address => isAddress(a)) as Address[]),\n );\n }\n return addresses.map((a) => a.toLowerCase() as Address);\n }, [tokenList]);\n\n const hasAddressesNotInTokenList = useMemo(() => {\n const tokenSet = new Set(\n tokenList?.map((token) => token.address.toLowerCase() as Address),\n );\n // Native BERA (zero address) is priced via WBERA in getTokenCurrentPrices.\n // Treat zero address as \"known\" whenever WBERA exists in token list.\n if (tokenList.some((token) => isToken(token, \"WBERA\"))) {\n tokenSet.add(zeroAddress);\n }\n\n return beraAddresses?.some((a) => !tokenSet.has(a));\n }, [beraAddresses, tokenList]);\n\n /**\n * If no addressIn is provided, use default token list\n * If all addressIn are in the token list, use default token list\n * If some addressIn are not in the token list, use addressIn\n */\n const addresses = hasAddressesNotInTokenList\n ? beraAddresses\n : tokenList.map((token) => token.address);\n\n const QUERY_KEY =\n addresses && (options.opts?.isEnabled ?? true)\n ? ([\n \"useTokenCurrentPrices\",\n addresses.map((a) => a.toLowerCase() as Address),\n ] as const)\n : null;\n\n const apiResponse = useSWR(\n QUERY_KEY,\n async ([, addresses]) => {\n // this only works for Berachain tokens\n return getTokenCurrentPrices({ addressIn: addresses });\n },\n options.opts,\n );\n\n const ensoMatchingPrices = useMemo<TokenCurrentPriceMap>(() => {\n if (!ensoTokens) return {};\n\n const ensoPricesMap = new Map<number, Map<Address, TokenWithPrice>>([\n [defaultChainId, new Map()],\n ]);\n\n for (const token of ensoTokens) {\n if (token.price === undefined || token.chainId !== defaultChainId)\n continue;\n\n ensoPricesMap\n .get(defaultChainId)\n ?.set(token.address.toLowerCase() as Address, {\n ...token,\n price: token.price,\n chainId: defaultChainId,\n });\n }\n\n return Object.fromEntries(\n addresses.map((address) => {\n const price = ensoPricesMap.get(defaultChainId)?.get(address)?.price;\n\n if (!price) return [null, null];\n\n return [\n address.toLowerCase() as Address,\n {\n price,\n chainId: defaultChainId,\n updatedAt: Date.now(),\n },\n ];\n }),\n );\n }, [ensoTokens]);\n\n const data = useMemo(\n () => ({\n ...ensoMatchingPrices,\n // in this deprecated hook, we let api override enso prices, since there's no multichain support\n ...apiResponse.data,\n }),\n [ensoMatchingPrices, apiResponse.data],\n );\n\n return {\n ...apiResponse,\n data,\n };\n}\n","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\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 { vaultAbi as balancerVaultAbi } from \"@berachain/abis/bex/vault\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\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/polling\";\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/global\";\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","import { useMemo } from \"react\";\n\nimport type { Token } from \"~/types/dex\";\nimport { computePriceImpact } from \"~/utils/math\";\nimport { useTokenPrices } from \"../tokens/useTokenPrices\";\n\nexport function usePriceImpact({\n tokenIn,\n tokenOut,\n formattedAmountIn,\n formattedAmountOut,\n}: {\n tokenIn: Token | undefined;\n tokenOut: Token | undefined;\n formattedAmountIn: string | undefined;\n formattedAmountOut: string | undefined;\n}) {\n const { getTokenPrice, isLoading } = useTokenPrices({\n tokens: tokenIn && tokenOut ? [tokenIn, tokenOut] : undefined,\n });\n const priceImpact = useMemo(() => {\n if (!tokenIn || !tokenOut || !formattedAmountIn || !formattedAmountOut)\n return undefined;\n\n const tokenInPrice = getTokenPrice(tokenIn);\n const tokenOutPrice = getTokenPrice(tokenOut);\n\n if (!tokenInPrice || !tokenOutPrice) return null;\n return computePriceImpact(\n tokenInPrice.toString(),\n tokenOutPrice.toString(),\n formattedAmountIn,\n formattedAmountOut,\n );\n }, [tokenIn, tokenOut, formattedAmountIn, formattedAmountOut]);\n return {\n data: priceImpact,\n isLoading,\n };\n}\n","import { useCallback, useMemo } from \"react\";\nimport type { Address } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { POLLING } from \"~/enum/polling\";\nimport { useTokens } from \"~/hooks/tokens/useTokens\";\nimport type { Token } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { useTokenCurrentPrices } from \"./useTokenCurrentPrices\";\n\nexport type TokenPriceInput = Pick<Token, \"address\" | \"chainId\">;\n\nexport type TokenPriceOutput = TokenPriceInput & {\n price: number;\n};\nexport type TokenPriceMap = Record<number, Record<Address, number>>;\n\nexport function useTokenPrices(\n {\n tokens,\n }: {\n tokens?: TokenPriceInput[];\n } = {},\n options: DefaultHookOptions = {\n opts: {\n refreshInterval: POLLING.NORMAL,\n revalidateOnFocus: true,\n },\n },\n) {\n const { ensoTokens } = useTokens();\n\n const apiResponse = useTokenCurrentPrices(\n {\n addressIn: tokens\n ?.filter((token) => token.chainId === defaultChainId)\n .map((token) => token.address),\n },\n options,\n );\n\n const data = useMemo(() => {\n const prices: TokenPriceOutput[] = [];\n\n if (!tokens) {\n return [];\n }\n\n const tokenMap = new Map<number, Map<Address, TokenPriceInput>>();\n\n for (const token of tokens) {\n const chainId = token.chainId ?? defaultChainId;\n if (!tokenMap.has(chainId)) {\n tokenMap.set(chainId, new Map<Address, TokenPriceInput>());\n }\n tokenMap.get(chainId)?.set(token.address.toLowerCase() as Address, token);\n }\n\n if (apiResponse.data) {\n for (const [address, price] of Object.entries(apiResponse.data)) {\n if (\n price &&\n tokenMap\n .get(price.chainId ?? defaultChainId)\n ?.get(address.toLowerCase() as Address) &&\n price.price !== undefined\n ) {\n const token = tokenMap\n .get(price.chainId ?? defaultChainId)\n ?.get(address.toLowerCase() as Address);\n\n if (!token) {\n continue;\n }\n\n prices.push({\n ...token,\n chainId: price.chainId,\n price: price.price,\n });\n }\n }\n }\n\n if (ensoTokens) {\n for (const tk of ensoTokens) {\n if (tk.price !== undefined && tk.chainId !== undefined) {\n prices.push({\n ...tk,\n chainId: tk.chainId,\n price: tk.price,\n });\n }\n }\n }\n\n return prices;\n }, [apiResponse.data, ensoTokens, tokens]);\n\n const priceMap = useMemo<TokenPriceMap>(() => {\n const map: TokenPriceMap = {};\n for (const item of data) {\n const chainId = item.chainId ?? defaultChainId;\n if (!map[chainId]) {\n map[chainId] = {} as Record<Address, number>;\n }\n map[chainId][item.address.toLowerCase() as Address] = item.price;\n }\n\n return map;\n }, [data]);\n\n const getTokenPrice = useCallback(\n (token?: TokenPriceInput) => {\n if (!token) return undefined;\n const price =\n priceMap[token.chainId ?? defaultChainId]?.[\n token.address?.toLowerCase() as Address\n ] ?? undefined;\n\n return price;\n },\n [priceMap],\n );\n\n return {\n isLoading: apiResponse.isLoading,\n data,\n priceMap,\n getTokenPrice,\n };\n}\n","\"use client\";\n\nimport useSWR from \"swr\";\nimport { type Address, formatEther, parseUnits, zeroAddress } from \"viem\";\n\nimport { defaultChainId as berachainChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { ensoErc4626 } from \"~/actions/dex/aggregators/enso/ensoErc4626\";\nimport { POLLING } from \"~/enum/polling\";\nimport {\n assertAddress,\n assertDefined,\n assertPublicClient,\n} from \"~/errors/assert\";\nimport { usePollBalance } from \"~/hooks/tokens/usePollBalance\";\nimport type { BalanceToken, MinimalERC20 } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { isToken } from \"~/utils/tokens\";\nimport { useGetConvertToAssets } from \"../bend/useGetConvertToAssets\";\nimport { usePriceImpact } from \"../dex/usePriceImpact\";\nimport { useTokenPrices } from \"../tokens/useTokenPrices\";\n\ntype UseBendZapSupplyArgs = {\n /*\n * The input token to swap from\n */\n tokenIn?: BalanceToken;\n /*\n * The loan token to swap to\n */\n loanToken: MinimalERC20;\n /*\n * The bend vault to swap to\n */\n bendVault: MinimalERC20;\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\n/**\n * Get the bend zap supply transaction requests for swapping tokens using Enso.\n * @param {UseBendZapSupplyArgs} props - The props for the hook see {@link UseBendZapSupplyArgs}\n * @returns {DefaultHookReturnType<GetZapTransactionResponse> & {tokens: BalanceToken[], refresh: () => void}}\n *\n * The bend transaction response data with polling enabled, see {@link GetZapTransactionResponse} and {@link BalanceToken}\n * @remarks The hook is only enabled when all parameters are provided and amount is greater than 0\n */\nexport function useBendZapSupply(\n {\n tokenIn,\n loanToken,\n bendVault,\n rewardVault,\n amount,\n slippage,\n }: UseBendZapSupplyArgs,\n options?: DefaultHookOptions,\n) {\n const { getTokenPrice } = useTokenPrices({\n tokens: tokenIn && loanToken ? [tokenIn, loanToken] : undefined,\n });\n\n const swrResponse = useBendZapSupplyHelper(\n {\n tokenIn,\n loanToken,\n bendVault,\n rewardVault,\n amount: amount\n ? parseUnits(amount, tokenIn?.decimals ?? 18).toString()\n : undefined,\n slippage,\n },\n options,\n );\n\n const { data: zapSupplyAmount } = useGetConvertToAssets({\n sharesAmount: BigInt(swrResponse.data?.amountOut ?? 0),\n vaultAddress: bendVault.address,\n });\n\n const { data: priceImpact } = usePriceImpact({\n tokenIn: tokenIn,\n tokenOut: loanToken,\n formattedAmountIn: amount,\n formattedAmountOut: zapSupplyAmount?.formatted ?? \"0\",\n });\n\n const isCrossChain = tokenIn?.chainId && tokenIn.chainId !== berachainChainId;\n\n // fetch native token balance for source chain (needed for bridge fee check)\n const { data: nativeBalanceData, isLoading: isNativeBalanceLoading } =\n usePollBalance(\n {\n address: zeroAddress,\n chainId: isCrossChain ? tokenIn?.chainId : undefined,\n },\n { opts: { isEnabled: !!isCrossChain } },\n );\n\n // for cross-chain zaps, check if transaction value exceeds native token balance\n // (tx.value includes bridge fees that must be paid in native token)\n const transactionValue =\n swrResponse.data?.getCalldata?.({ account: zeroAddress })?.value ?? 0n;\n\n // check if user has enough native token for bridge fees\n const nativeBalance = nativeBalanceData?.balance ?? {\n raw: \"0\",\n formatted: \"0\",\n };\n const hasInsufficientNativeBalance =\n isCrossChain &&\n transactionValue > 0n &&\n !isNativeBalanceLoading &&\n transactionValue > BigInt(nativeBalance.raw);\n\n // formatted native fee for gas reserve display\n const nativeFee =\n isCrossChain && transactionValue > 0n\n ? formatEther(transactionValue)\n : undefined;\n\n return {\n ...swrResponse,\n zapSupplyAmount,\n priceImpact,\n hasInsufficientNativeBalance,\n isCrossChain,\n nativeFee,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n}\n\nexport function useBendZapSupplyHelper(\n {\n tokenIn,\n loanToken,\n bendVault,\n rewardVault,\n amount,\n slippage,\n }: UseBendZapSupplyArgs,\n options?: DefaultHookOptions,\n) {\n const { address: fromAddress } = useBeraWallet();\n\n const isEnabled =\n !!tokenIn &&\n !!loanToken &&\n !!bendVault &&\n !!amount &&\n !!fromAddress &&\n !isToken(loanToken.address, tokenIn.address) &&\n tokenIn.chainId &&\n Number(amount) > 0 &&\n !!slippage;\n\n const publicClientBeraChain = usePublicClient();\n const QUERY_KEY = isEnabled\n ? ([\n \"useBendZapSupply\",\n tokenIn,\n loanToken,\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 loanToken,\n bendVault,\n rewardVault,\n amount,\n slippage,\n ]) => {\n assertPublicClient(publicClientBeraChain);\n assertAddress(fromAddress, \"fromAddress\");\n assertAddress(tokenIn?.address, \"tokenInAddress\");\n assertDefined(tokenIn?.chainId, \"tokenInChainId\");\n\n return await ensoErc4626.getQuote({\n tokenIn,\n tokenOut: bendVault,\n underlyingToken: loanToken,\n amount,\n slippage,\n account: fromAddress,\n rewardVault,\n });\n },\n {\n ...options?.opts,\n refreshInterval: POLLING.NORMAL,\n },\n );\n}\n","import type { BundleAction } from \"@ensofinance/sdk\";\nimport { type Address, ethAddress, type Hex, zeroAddress } from \"viem\";\n\nimport { getEnsoClient } from \"~/actions/clients/getEnsoClient\";\nimport { Aggregators } from \"~/enum/dex\";\nimport { assertAddress } from \"~/errors/assert\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"~/types/dex\";\nimport { BaseAggregator } from \"../base\";\n\nclass EnsoErc4626Aggregator extends BaseAggregator {\n name = Aggregators.EnsoErc4626;\n supportedChains = null;\n readonly type = \"rest\";\n needsAccountForQuote = true;\n\n notFoundMessages: string[] = [\n \"Could not build shortcuts for route\",\n \"Could not quote shortcuts for route\",\n \"Swap not found for a required underlying of defi route,\",\n \"No route found from\",\n ];\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n underlyingToken,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n assertAddress(account, \"account\");\n\n const ensoClient = getEnsoClient({\n useProxy: !proxyAggregatorsThroughVercel,\n });\n\n if (tokenIn.address === zeroAddress) tokenIn.address = ethAddress;\n if (tokenOut.address === zeroAddress) tokenOut.address = ethAddress;\n\n /**\n * This is the token that will be swapped by enso, but might not be the same as the token out.\n *\n * If an underlying token is provided, we'll swap to that and then deposit it into the vault,\n * assuming that token out is an ERC4626 vault.\n */\n const zapTokenOut = underlyingToken ?? tokenOut;\n\n const bundleActions: BundleAction[] = [\n // this is the base route action, which will swap the token in to the zap token out\n // it handles cross-chain swaps and refunds the user if the swap fails\n // this might even be the only action if no underlying token or reward vault is provided\n {\n protocol: \"enso\",\n action: \"route\",\n args: {\n tokenIn: tokenIn.address,\n tokenOut: zapTokenOut.address,\n destinationChainId:\n // must be undefined if the token is the same chain\n tokenIn.chainId === zapTokenOut.chainId\n ? undefined\n : zapTokenOut.chainId,\n refundReceiver: account,\n amountIn: amount,\n slippage: slippage * 100, // Enso expects slippage in basis points\n },\n },\n ];\n\n if (underlyingToken) {\n // deposit the underlying token into the vault\n // this works both for Staked BERA/iBera and Bend Vaults\n bundleActions.push({\n protocol: \"erc4626\",\n action: \"deposit\",\n args: {\n amountIn: { useOutputOfCallAt: 0 },\n tokenIn: underlyingToken.address,\n primaryAddress: tokenOut.address,\n tokenOut: tokenOut.address,\n },\n });\n }\n\n if (rewardVault) {\n // if an address is provided, funds will be staked into the reward vault\n\n // offset dynamically reads length of bundleActions array to get the output of the previous call\n const offset = bundleActions.length;\n bundleActions.push(\n {\n protocol: \"enso\",\n action: \"balance\",\n args: {\n token: tokenOut.address,\n },\n },\n {\n protocol: \"erc20\",\n action: \"approve\",\n args: {\n amount: { useOutputOfCallAt: offset },\n spender: rewardVault,\n token: tokenOut.address,\n },\n },\n {\n protocol: \"enso\",\n action: \"call\",\n args: {\n address: rewardVault,\n args: [account, { useOutputOfCallAt: offset }],\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: account,\n receiver: account,\n spender: account,\n chainId: tokenIn.chainId,\n routingStrategy: \"router\",\n },\n bundleActions,\n );\n\n const tokenOutAddress = (rewardVault?.toLowerCase() ??\n tokenOut.address.toLowerCase()) as Address;\n\n const amountOut =\n // @ts-expect-error enso has not typed this but is returned sometimes from API.\n bundle.minAmountsOut[tokenOutAddress] ??\n bundle.amountsOut[tokenOutAddress] ??\n \"0\";\n\n return {\n amountOut,\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: bundle.tx.to,\n }),\n name: this.name,\n swapFeeBps: 0,\n priceImpactPercentage: bundle.priceImpact\n ? bundle.priceImpact / 100\n : null,\n getCalldata: () => ({\n address: bundle.tx.to,\n data: bundle.tx.data as Hex,\n value: BigInt(bundle.tx.value ?? 0),\n // not returning gas limit because it's usually underestimated by enso.\n // gasLimit: BigInt(bundle.gas),\n }),\n };\n }\n}\n\nexport const ensoErc4626 = new EnsoErc4626Aggregator();\n","\"use client\";\n\nimport { getPublicClient } from \"@wagmi/core\";\nimport useSWR from \"swr\";\nimport { parseUnits } from \"viem\";\n\nimport { defaultChainId as berachainChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { getEnsoClient } from \"~/actions/clients/getEnsoClient\";\nimport { getEnsoSwapBundle } from \"~/actions/enso/getEnsoSwapBundle\";\nimport { POLLING } from \"~/enum/polling\";\nimport {\n assertAddress,\n assertAmount,\n assertDefined,\n assertPublicClient,\n} from \"~/errors/assert\";\nimport type { BalanceToken, MinimalERC20 } from \"~/types/dex\";\nimport type { GetZapTransactionResponse } from \"~/types/enso\";\nimport { usePollWalletBalances } from \"../tokens/usePollWalletBalances\";\n\n/**\n * Get the swap bundle 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: BalanceToken[], refresh: () => void}}\n *\n * The zap transaction response data with polling enabled, see {@link GetZapTransactionResponse} and {@link BalanceToken}\n * @remarks The hook is only enabled when all parameters are provided and amount is greater than 0\n */\nexport function useEnsoSwapBundle({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n}: {\n tokenIn?: Pick<MinimalERC20, \"address\" | \"decimals\" | \"chainId\">;\n tokenOut?: Pick<MinimalERC20, \"address\" | \"decimals\">;\n amount?: string;\n slippage?: number;\n}) {\n const { address: fromAddress } = useBeraWallet();\n const wagmiConfig = useConfig();\n const ensoClient = getEnsoClient();\n\n const { refresh: refreshBalances } = usePollWalletBalances();\n\n const isEnabled =\n !!tokenIn &&\n !!tokenOut &&\n !!amount &&\n Number(amount) > 0 &&\n !!slippage &&\n !!fromAddress &&\n !!tokenIn.chainId;\n\n const QUERY_KEY = isEnabled\n ? ([\"useEnsoSwapBundle\", tokenIn, tokenOut, amount, slippage] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, tokenIn, tokenOut, amount, slippage]) => {\n assertAddress(fromAddress, \"fromAddress\");\n assertAddress(tokenIn?.address, \"tokenInAddress\");\n assertDefined(tokenIn?.chainId, \"tokenInChainId\");\n assertAddress(tokenOut?.address, \"tokenOutAddress\");\n assertAmount(amount, \"amount\");\n assertAmount(slippage, \"slippage\");\n\n const publicClient = getPublicClient(wagmiConfig, {\n chainId: tokenIn.chainId,\n });\n assertPublicClient(publicClient);\n\n const rawAmount = parseUnits(amount, tokenIn.decimals).toString();\n\n return getEnsoSwapBundle({\n fromAddress,\n amountIn: rawAmount,\n tokenIn: tokenIn.address,\n tokenOut: tokenOut.address,\n chainId: tokenIn.chainId,\n ensoClient,\n destinationChainId: berachainChainId,\n slippage,\n publicClient,\n });\n },\n {\n refreshInterval: POLLING.NORMAL,\n isEnabled: isEnabled,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n refreshBalances();\n },\n };\n}\n","import type { BundleAction } from \"@ensofinance/sdk\";\nimport { ethAddress, zeroAddress } from \"viem\";\n\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type {\n GetEnsoSwapBundleArgs,\n GetZapTransactionResponse,\n} from \"~/types/enso\";\nimport { getTransactionsFromBundle } from \"./util\";\n\nexport async function getEnsoSwapBundle({\n fromAddress,\n amountIn,\n tokenIn,\n tokenOut,\n chainId,\n ensoClient,\n destinationChainId,\n slippage,\n publicClient,\n}: GetEnsoSwapBundleArgs): 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 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 { type Address, erc20Abi, ethAddress } from \"viem\";\n\nimport type { GetZapTransactions, GetZapTransactionsArgs } from \"~/types/enso\";\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 { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport {\n useBeraWallet,\n useConfig,\n usePublicClient,\n} from \"@berachain/wagmi/hooks\";\n\nimport { getWalletBalances } from \"~/actions/tokens/getWalletBalances\";\nimport { POLLING } from \"~/enum/polling\";\nimport { useTokens } from \"~/hooks/tokens/useTokens\";\nimport type { BalanceToken, Token } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\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 const wagmiConfig = useConfig();\n const { address: connectedAccount } = useBeraWallet();\n\n const { tokenList, refresh } = 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 wagmiConfig,\n });\n },\n {\n refreshInterval: POLLING.NORMAL,\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse?.mutate?.();\n refresh();\n },\n };\n}\n","\"use client\";\n\nimport useSWR from \"swr\";\nimport { formatUnits, parseUnits } from \"viem\";\n\nimport { chainConfigs, defaultChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet } from \"@berachain/wagmi/hooks\";\n\nimport { ensoErc4626 } from \"~/actions/dex/aggregators/enso/ensoErc4626\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { MinimalERC20 } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { usePriceImpact } from \"../dex/usePriceImpact\";\n\ntype UseZapStakeBeraArgs = {\n inputToken: MinimalERC20 | undefined;\n amount: string;\n underlyingToken: MinimalERC20 | undefined;\n slippage?: number;\n inputTokenPrice?: number;\n tokenOut: MinimalERC20;\n};\n\n/**\n * hook to get zap stake BERA transaction data from enso.\n * supports cross-chain zaps from any chain to berachain staking.\n */\nexport function useZapStakeBera(\n {\n inputToken,\n amount,\n underlyingToken,\n slippage,\n tokenOut,\n }: UseZapStakeBeraArgs,\n options?: DefaultHookOptions,\n) {\n const { address: account } = useBeraWallet();\n // enso route simulation needs a real EOA-like address; zeroAddress can fail simulation.\n // use the connected wallet when available, otherwise fallback to our configured aggregator executor.\n const quoteAccount =\n account ?? chainConfigs[defaultChainId].bex.aggregatorsRouterExecutor;\n\n const isEnabled =\n !!inputToken &&\n !!amount &&\n Number(amount) > 0 &&\n !!inputToken.chainId &&\n !!underlyingToken &&\n !!slippage;\n\n const QUERY_KEY = isEnabled\n ? ([\n \"useZapStakeBera\",\n inputToken,\n amount,\n quoteAccount,\n slippage,\n underlyingToken,\n tokenOut,\n ] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([\n ,\n inputToken,\n amount,\n quoteAccount,\n slippage,\n underlyingToken,\n tokenOut,\n ]) => {\n const rawAmount = parseUnits(amount, inputToken.decimals).toString();\n\n return ensoErc4626.getQuote({\n account: quoteAccount,\n amount: rawAmount,\n tokenIn: inputToken,\n underlyingToken: underlyingToken,\n tokenOut: tokenOut,\n slippage,\n });\n },\n {\n ...options?.opts,\n refreshInterval: POLLING.NORMAL,\n },\n );\n const { data: priceImpactPercentage } = usePriceImpact({\n tokenIn: inputToken,\n tokenOut: tokenOut,\n formattedAmountIn: amount,\n formattedAmountOut: formatUnits(\n BigInt(swrResponse.data?.amountOut ?? \"0\"),\n tokenOut.decimals,\n ),\n });\n\n return {\n ...swrResponse,\n data: {\n ...swrResponse.data,\n priceImpactPercentage,\n isCrossChain: inputToken && tokenOut.chainId !== inputToken?.chainId,\n },\n refresh: () => {\n swrResponse.mutate();\n },\n };\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\n\nimport { getProposalParams } from \"~/actions/governance/getProposalParams\";\nimport { ProposalTypeEnum } from \"~/enum/governance\";\nimport type {\n CustomProposal,\n CustomProposalErrors,\n GovernanceTopic,\n PROPOSAL_GENRE,\n SafeProposalAction,\n} from \"~/types/governance\";\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 \"@berachain/abis/pol/rewards/beraChef\";\nimport { rewardVaultAbi } from \"@berachain/abis/pol/rewards/rewardVault\";\n\nimport { ProposalErrorCodes, ProposalTypeEnum } from \"~/enum/governance\";\nimport type {\n CustomProposal,\n CustomProposalActionErrors,\n CustomProposalErrors,\n GovernanceTopic,\n} from \"~/types/governance\";\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 { bgtAbi } from \"@berachain/abis/pol/bgt\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { timeLockAbi as governanceTimelockAbi } from \"@berachain/abis/gov/timeLock\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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/global\";\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/global\";\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 { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookReturnType } from \"~/types/global\";\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 { bgtAbi } from \"@berachain/abis/pol/bgt\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\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 { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { ProposalState } from \"~/enum/governance\";\nimport { assertPublicClient } from \"~/errors/assert\";\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 { timeLockAbi as governanceTimelockAbi } from \"@berachain/abis/gov/timeLock\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\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 function 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 { formatEther, type PublicClient } from \"viem\";\n\nimport { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\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 | undefined;\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 { Token } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\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 type { PythLatestUpdates } from \"~/actions/honey/getPythLatestPrices\";\nimport { getPythLatestPrices } 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/global\";\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 { Token } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\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\";\n\nimport BigNumber from \"@berachain/utils/pkg/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 { isToken } from \"~/utils/tokens\";\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?.balance.formatted ?? \"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?.balance.formatted ?? \"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?.balance.formatted ?? \"0\").lt(\n amountToRedeem ?? \"0\",\n );\n },\n );\n return {\n isMore: !!isRedeemMoreThanLiquidityCollaterals.find((coll) =>\n isToken(coll, state.collaterals[0]),\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]?.balance.formatted ?? \"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]?.balance.formatted,\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]?.balance.formatted).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 {\n useBeraWallet,\n useConfig,\n usePublicClient,\n} 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 const wagmiConfig = useConfig();\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 wagmiConfig,\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/polling\";\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 { Token } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\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 useSWR from \"swr\";\n\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\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 } from \"~/enum/honey\";\nimport 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/global\";\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 { bgtAbi } from \"@berachain/abis/pol/bgt\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 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/global\";\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/global\";\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/global\";\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/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions } from \"~/types/global\";\n\nexport function useQueuedBeraUnlock(\n {\n receiptTokenAddresses,\n account,\n version,\n }: {\n receiptTokenAddresses: Address[];\n account?: Address | string;\n version: \"V1\" | \"V2\";\n },\n options?: DefaultHookOptions,\n) {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n receiptTokenAddresses &&\n account &&\n publicClient &&\n isAddress(account) &&\n version\n ? ([\n \"useQueuedBeraUnlock\",\n receiptTokenAddresses,\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 ([, receiptTokenAddresses, account, version]) => {\n assertPublicClient(publicClient);\n\n return await Promise.all(\n receiptTokenAddresses.map(async (receiptTokenAddress) => {\n return await getSWBeraWithdrawal({\n contractAddress: receiptTokenAddress,\n accountAddress: account,\n publicClient,\n version,\n });\n }),\n ).then((results) => results.flat());\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 { defaultChainId } from \"@berachain/config/internal\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getRewardTokenToBeraRate } from \"~/actions/pol/getRewardTokenToBeraRate\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type { DefaultHookOptions } from \"~/types/global\";\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({ chainId: defaultChainId });\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/global\";\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 { beraChefAbi } from \"@berachain/abis/pol/rewards/beraChef\";\n\nimport type { ApiVaultFragment } from \"@berachain/graphql/pol/api\";\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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/global\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nconst 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 chainId: publicClient.chain.id,\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 Address, erc20Abi, formatUnits, type PublicClient } from \"viem\";\n\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { Token } from \"~/types/dex\";\n\nexport interface GetStakingTokenInformation {\n address: Address;\n publicClient: PublicClient | undefined;\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 { GqlVaultSnapshotDataRange } from \"@berachain/graphql/dex/api\";\n\nimport { getStakedBeraSnapshots } from \"~/actions/pol/getStakedBeraSnapshots\";\nimport type { DefaultHookReturnType } from \"~/types/global\";\nimport { dailyResolution } from \"~/utils/filter\";\n\ntype UseStakedAPR = {\n _timestamp: number;\n apr: string;\n}[];\nexport function useStakedAPR({\n range,\n}: {\n range: GqlVaultSnapshotDataRange;\n}): DefaultHookReturnType<UseStakedAPR> {\n const QUERY_KEY = range ? ([\"useStakedAPR\", range] as const) : null;\n const swrResponse = useSWR(QUERY_KEY, async ([, range]) => {\n const unsortedStakedBeraSnapshots = await getStakedBeraSnapshots({\n range,\n });\n\n const sortedStakedBeraSnapshots = dailyResolution(\n unsortedStakedBeraSnapshots.sort((a, b) => a.timestamp - b.timestamp),\n );\n\n return sortedStakedBeraSnapshots.map((item) => ({\n _timestamp: item.timestamp,\n apr: item.apr,\n }));\n });\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","/**\n * Filters data to get one data point per day\n * @param data - The data to filter\n * @returns The filtered data\n */\nexport const dailyResolution = <\n T extends { timestamp?: number; _timestamp?: number },\n>(\n data: T[],\n) => {\n // Filter to get one data point per day\n const dailyData: T[] = [];\n let lastDay = \"\";\n\n for (const item of data) {\n if (!item.timestamp && !item._timestamp) continue;\n // Convert Unix timestamp (seconds) to milliseconds for Date constructor\n const timestampMs = (item?.timestamp ?? item?._timestamp ?? 0) * 1000;\n const currentDay = new Date(timestampMs);\n const currentDayStr = currentDay.toDateString();\n if (currentDayStr !== lastDay) {\n const newTimestamp =\n new Date(currentDay.setHours(0, 0, 0, 0)).getTime() / 1000;\n dailyData.push({\n ...item,\n timestamp: newTimestamp,\n _timestamp: newTimestamp,\n });\n lastDay = currentDayStr;\n }\n }\n\n return dailyData;\n};\n","import { useMemo } from \"react\";\nimport useSWR from \"swr\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport { getEarnedStakedBeraVault } from \"~/actions/pol/getEarnedStakedBeraVault\";\nimport { getRewardTokenToBeraRate } from \"~/actions/pol/getRewardTokenToBeraRate\";\nimport { getStakedBeraAPR } from \"~/actions/pol/getStakedBeraAPR\";\nimport { useBeraFlag } from \"~/contexts/BeraFlags/BeraFlags\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\nimport { usePollWalletBalances } from \"~/hooks/tokens/usePollWalletBalances\";\nimport { useTokenPrices } from \"~/hooks/tokens/useTokenPrices\";\nimport type { StakedBeraAsset } from \"~/types/pol\";\nimport type { StakingConfig } from \"~/types/staking\";\n\n/**\n * Fetches staked asset data in two phases for progressive loading:\n *\n * 1. APR — independent fetch, resolves quickly, shared by both phases.\n * 2. Balances (fast path) — wallet balances (via usePollWalletBalances),\n * token prices (via useTokenPrices), and exchange rates.\n * Provides staked amounts and USD values immediately (earnings are 0).\n * 3. Positions (slow path) — adds earnings data from the vault.\n * Provides the full picture with earned amounts and USD values.\n *\n * Consumers can show `balances` right away and swap in `data` once positions resolve.\n */\nexport const useStakedData = (stakingConfigs: StakingConfig[]) => {\n const window = useBeraFlag(\"swberaAprWindow\");\n\n const publicClient = usePublicClient();\n const { address: account } = useBeraWallet();\n\n const receiptTokens = useMemo(\n () => stakingConfigs.map((config) => config.receiptToken),\n [stakingConfigs],\n );\n const inputTokens = useMemo(\n () => stakingConfigs.map((config) => config.inputTokens[0]),\n [stakingConfigs],\n );\n\n // APR — only updates every ~12 hours on BE\n const aprKey = window ? ([\"useStakedData:apr\", window] as const) : null;\n const { data: apr } = useSWR(\n aprKey,\n async ([, window]) => getStakedBeraAPR({ window }),\n { refreshInterval: POLLING.NORMAL },\n );\n\n const { data: walletBalances, isLoading: isLoadingBalances } =\n usePollWalletBalances({ tokens: receiptTokens });\n\n // NOT BERA PRICE, INPUT TOKEN PRICE\n const { getTokenPrice } = useTokenPrices({ tokens: inputTokens });\n\n // exchange rates from receipt token → input token (on-chain reads)\n const exchangeRatesKey =\n publicClient && receiptTokens.length > 0\n ? ([\"useStakedData:exchangeRates\", receiptTokens] as const)\n : null;\n\n const { data: exchangeRates } = useSWR(\n exchangeRatesKey,\n async ([, receiptTokens]) => {\n assertPublicClient(publicClient);\n return Promise.all(\n receiptTokens.map((token) =>\n getRewardTokenToBeraRate({\n address: token.address,\n publicClient,\n }),\n ),\n );\n },\n { refreshInterval: POLLING.NORMAL },\n );\n\n // balances (fast path) — derived from hooks above, no extra requests\n const balances = useMemo<StakedBeraAsset[] | undefined>(() => {\n if (!walletBalances || !exchangeRates) return undefined;\n\n return stakingConfigs.map((config, i): StakedBeraAsset => {\n const inputToken = config.inputTokens[0];\n const stakedBalance =\n walletBalances.find((b) => b.address === config.receiptToken.address)\n ?.balance.raw ?? \"0\";\n const exchangeRate = exchangeRates[i] ?? 0;\n const inputTokenPrice = getTokenPrice(inputToken) ?? 0;\n\n const total = new BigNumber(stakedBalance).multipliedBy(exchangeRate);\n const stakedAmount = total.dividedBy(10 ** inputToken.decimals);\n const stakedAmountUsd = stakedAmount.multipliedBy(inputTokenPrice);\n\n return {\n token: inputToken,\n apr: apr ?? 0,\n stakedAmount: stakedAmount.toNumber(),\n stakedAmountUsd: stakedAmountUsd.toNumber(),\n earnedAmount: 0,\n earnedAmountUsd: 0,\n isLoadingEarnings: true,\n };\n });\n }, [walletBalances, exchangeRates, stakingConfigs, apr, getTokenPrice]);\n\n // positions (slow path) — fetch earnings and exchange rates from the vault\n const positionsKey =\n account && publicClient && stakingConfigs.length > 0\n ? ([\"useStakedData:positions\", account, stakingConfigs] as const)\n : null;\n\n const {\n data: positionsRaw,\n isLoading: isLoadingPositions,\n isValidating: isValidatingPositions,\n } = useSWR(\n positionsKey,\n async ([, account, stakingConfigs]) => {\n assertPublicClient(publicClient);\n\n return Promise.all(\n stakingConfigs.map(async (stakingConfig) => {\n const stakingToken = stakingConfig.receiptToken;\n\n const [earnings, exchangeRate] = await Promise.all([\n getEarnedStakedBeraVault({\n address: stakingToken.address,\n account,\n }),\n getRewardTokenToBeraRate({\n address: stakingToken.address,\n publicClient,\n }),\n ]);\n\n return { earnings, exchangeRate };\n }),\n );\n },\n { refreshInterval: POLLING.FAST },\n );\n\n // derive full StakedBeraAsset[] from raw positions + shared hooks\n const data = useMemo<StakedBeraAsset[] | undefined>(() => {\n if (!positionsRaw || !walletBalances) return undefined;\n\n return stakingConfigs.map((config, i): StakedBeraAsset => {\n const inputToken = config.inputTokens[0];\n const stakingToken = config.receiptToken;\n const { earnings, exchangeRate: exchangeRateRaw } = positionsRaw[i];\n\n const inputTokenPrice = getTokenPrice(inputToken) ?? 0;\n const stakedBalance =\n walletBalances.find((b) => b.address === stakingToken.address)?.balance\n .raw ?? \"0\";\n const exchangeRate = exchangeRateRaw ?? 0;\n\n const unrealisedGains = new BigNumber(earnings.earningsTotal).minus(\n earnings.earningsRealized,\n );\n const total = new BigNumber(stakedBalance).multipliedBy(exchangeRate);\n const deposited = total.minus(unrealisedGains);\n\n const stakedAmount = deposited.dividedBy(10 ** inputToken.decimals);\n const earnedAmount = unrealisedGains.dividedBy(10 ** inputToken.decimals);\n const stakedAmountUsd = stakedAmount.multipliedBy(inputTokenPrice);\n const earnedAmountUsd = earnedAmount.multipliedBy(inputTokenPrice);\n\n return {\n token: inputToken,\n apr: apr ?? 0,\n stakedAmount: stakedAmount.toNumber(),\n earnedAmount: earnedAmount.toNumber(),\n stakedAmountUsd: stakedAmountUsd.toNumber(),\n earnedAmountUsd: earnedAmountUsd.toNumber(),\n };\n });\n }, [positionsRaw, walletBalances, stakingConfigs, apr, getTokenPrice]);\n\n return {\n /** Fast path: staked amounts + USD values (no earnings) */\n balances,\n /** Slow path: full enriched positions with earnings */\n data,\n /** True only when both balances and positions are still loading */\n isLoading: isLoadingBalances && isLoadingPositions,\n isLoadingBalances,\n isLoadingPositions,\n isValidatingPositions,\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { getStakingDailyAssets } from \"~/actions/pol/getStakingDailyAssets\";\nimport type { DefaultHookReturnType } from \"~/types/global\";\nimport { dailyResolution } from \"~/utils/filter\";\n\ntype UseStakedBeraSnapshot = Record<\n Address,\n {\n _timestamp: number;\n total_assets: string;\n }[]\n>;\nexport function useStakedSnapshots({\n range,\n addresses,\n}: {\n addresses: Address[];\n range: 30 | 60 | 90;\n}): DefaultHookReturnType<UseStakedBeraSnapshot> {\n const QUERY_KEY = range\n ? ([\"useStakedSnapshots\", range, addresses] as const)\n : null;\n const swrResponse = useSWR(QUERY_KEY, async ([, range, addresses]) => {\n const [...sortedStakingDailyAssetsArray] = await Promise.all([\n ...addresses.map(async (address) => {\n const unstakingDailyAssets = await getStakingDailyAssets({\n address,\n range,\n });\n const sortedStakingDailyAssets = dailyResolution(\n unstakingDailyAssets.sort((a, b) => a._timestamp - b._timestamp),\n );\n return {\n [address]: sortedStakingDailyAssets,\n };\n }),\n ]);\n\n // Merge all address data into a single object\n return sortedStakingDailyAssetsArray.reduce(\n (acc, addressData) => ({ ...acc, ...addressData }),\n {} as Record<Address, { _timestamp: number; total_assets: string }[]>,\n );\n });\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","import type { Address } from \"viem\";\n\nimport { beraFetchJson } from \"~/utils/beraFetch\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport async function getStakingDailyAssets({\n address,\n range,\n}: {\n address: Address;\n range: 30 | 60 | 90;\n}): Promise<{ _timestamp: number; total_assets: string }[]> {\n const now = new Date();\n const startDayDate = new Date(\n now.getTime() - Number(range) * 24 * 60 * 60 * 1000,\n );\n\n const { config } = parseBaseArgs({});\n const url = `${config.bonder}/vaults/${address}/total-assets-by-day?start=${startDayDate.toISOString().split(\"T\")[0]}`;\n return beraFetchJson<{ _timestamp: number; total_assets: string }[]>({\n url,\n type: \"rest\",\n });\n}\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getSWBeraVaultMetadata } from \"~/actions/pol/getSWBeraVaultMetadata\";\nimport { useBlockTime } from \"~/contexts/block-time-provider\";\nimport { POLLING } from \"~/enum/polling\";\nimport { assertPublicClient } from \"~/errors/assert\";\n\nexport const useSWBeraVaultMetadata = (receiptTokenAddress?: Address) => {\n const publicClient = usePublicClient();\n const blockTime = useBlockTime();\n const QUERY_KEY =\n receiptTokenAddress && publicClient && blockTime\n ? ([\n \"useStakingVaultMetadata\",\n receiptTokenAddress,\n publicClient,\n blockTime,\n ] as const)\n : null;\n return useSWR(\n QUERY_KEY,\n async ([, address, publicClient, blockTime]) => {\n assertPublicClient(publicClient);\n return getSWBeraVaultMetadata({\n address,\n publicClient,\n blockTime,\n });\n },\n { refreshInterval: POLLING.FAST },\n );\n};\n","import useSWR from \"swr\";\n\nimport type { Address } from \"@berachain/config\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getTotalStakedAmount } from \"~/actions/pol/getTotalStakedAmount\";\nimport type { DefaultHookReturnType } from \"~/types/global\";\n\nexport function useTotalStakedAmount({\n vaultAddresses,\n}: {\n vaultAddresses: Address[];\n}): DefaultHookReturnType<Record<Address, bigint>> {\n const publicClient = usePublicClient();\n\n const swrResponse = useSWR(\n vaultAddresses && publicClient\n ? [\"useTotalStakedAmount\", vaultAddresses]\n : null,\n ([, vaultAddresses]) => {\n return getTotalStakedAmount({ vaultAddresses, 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 { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getUserVaultInfo } from \"~/actions/pol/getUserVaultInfo\";\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/global\";\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 { DefaultHookOptions } from \"~/types/global\";\nimport { useTokenCurrentPrices } from \"./useTokenCurrentPrices\";\n\n/**\n * @deprecated use useTokenPrice instead\n */\nexport function useTokenCurrentPrice(\n { address }: { address: `0x${string}` | undefined },\n options?: DefaultHookOptions,\n) {\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 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 { Token } from \"~/types/dex\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\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 type { Address } from \"viem\";\n\nimport type { DefaultHookOptions } from \"~/types/global\";\nimport { type TokenPriceInput, useTokenPrices } from \"./useTokenPrices\";\n\nexport function useTokenPrice(\n { token }: { token: TokenPriceInput | undefined },\n options?: DefaultHookOptions,\n) {\n const { isLoading, priceMap } = useTokenPrices(\n { tokens: token ? [token] : undefined },\n options,\n );\n\n return {\n data: token\n ? priceMap[token.chainId]?.[token.address.toLowerCase() as Address]\n : undefined,\n isLoading,\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 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 { IUseContractWriteArgs } from \"~/hooks/useContractWrite/types\";\nimport type { IContractWrite } from \"~/types/global\";\nimport { ActionEnum, initialState, reducer } from \"./stateReducer\";\nimport type { 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/global\";\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/global\";\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","import type { PublicClient } from \"viem\";\n\nimport { rewardAllocatorFactoryAbi as rewardAllocationFactoryAbi } from \"@berachain/abis/pol/rewards/rewardAllocatorFactory\";\n\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/global\";\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/global\";\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/global\";\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 \"@berachain/abis/pol/rewards/beraChef\";\n\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 { beaconDepositAbi } from \"@berachain/abis/pol/beaconDeposit\";\nimport { bgtAbi } from \"@berachain/abis/pol/bgt\";\nimport { beraChefAbi } from \"@berachain/abis/pol/rewards/beraChef\";\n\nimport type { ApiValidatorFragment } from \"@berachain/graphql/pol/api\";\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { assertPublicClient } from \"~/errors/assert\";\nimport type { DefaultHookOptions, DefaultHookReturnType } from \"~/types/global\";\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/global\";\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\ninterface 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/global\";\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 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/polling\";\nimport { BeraError } from \"~/errors/BeraError\";\nimport { BeraMonitoring } from \"~/errors/BeraMonitoring\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport type { BribeBoostRewardProof } from \"~/types/bribe-boost\";\nimport type { DefaultHookReturnType } from \"~/types/global\";\nimport { formatIncentivesTokenMap } from \"~/utils/formatIncentivesTokenMap\";\n\ninterface 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 BeraMonitoring.captureException(\n new BeraError({\n message: \"Incorrect aggregated incentives data receieved.\",\n level: \"error\",\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/global\";\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/global\";\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/global\";\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/global\";\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/global\";\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/global\";\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/global\";\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":"szCAAA,OAAOA,OAAY,MAEnB,OAAS,mBAAAC,OAAuB,yBAOzB,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,C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xC,KAIJ,MAAO,CAAC,CAAEA,CAAM,IACP,MAAMM,GAA6B,CACxC,OAAQJ,EACR,OAAAF,CACF,CAAC,EAEH,CACE,GAAGC,GAAS,IACd,CACF,EAEA,MAAO,CACL,GAAGG,EACH,QAAS,IAAMA,EAAY,OAAO,CACpC,CACF","names":["useSWR","usePublicClient","useGetConvertToAssets","sharesAmount","vaultAddress","vaultChainId","options","publicClient","usePublicClient","swrResponse","useSWR","_","assertPublicClient","getConvertToAssets","useMemo","zeroAddress","defaultChainId","useBeraWallet","usePublicClient","Slippage","Swap","SwapKind","Token","TokenAmount","decodeFunctionData","formatEther","zeroAddress","getUriFromLink","ChainId","balancerVaultAbi","DEFAULT_DEADLINE","STALE_PRICE_THRESHOLD","swapKind","SwapKind","BexAggregator","BaseAggregator","ChainId","getUriFromLink","address","isToken","priceImpact","onChainAmount","sorPaths","sorAmount","queryData","deltaFromSorAmount","formatEther","error","BeraError","p","BeraMonitoring","args","balancerApi","BalancerApi","tokenIn","tokenOut","amount","slippage","account","zeroAddress","publicClient","assertPublicClient","wberaIsBera","tokenInV3","Token","tokenOutV3","tokenAmount","TokenAmount","RequestError","swap","Swap","queryOutput","callData","Slippage","params","functionName","decodeFunctionData","balancerVaultAbi","bex","ChainId","RedeemBgtAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","isToken","amount","beraToken","InvalidArgumentError","bgtRedeem","zeroAddress","ChainId","aggregatorsRouterAbi","EnsoAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","url","quote","inputData","outputData","aggregatorData","aggregatorsRouterAbi","enso","erc4626Abi","formatUnits","stakeBeraVaultAbi","ERC4626Aggregator","BaseAggregator","tokenIn","tokenOut","underlyingToken","isToken","amount","publicClient","assertDefined","assertPublicClient","rawOutputAmount","erc4626Abi","isSwBeraNative","formatUnits","account","stakeBeraVaultAbi","erc4626Deposit","zeroAddress","ChainId","aggregatorsRouterAbi","BASE_URL","FlyAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","aggregatorsFeeBps","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","url","params","quoteData","formattedQuote","txUrl","txParams","txData","inputData","outputData","aggregatorData","zeroAddress","aggregatorsRouterAbi","isToken","fly","formatUnits","parseUnits","zeroAddress","ChainId","aggregatorsRouterAbi","HaikuAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","aggregatorsFeeBps","proxyAggregatorsThroughVercel","referrer","rewardVault","BeraError","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","quoteBody","formatUnits","proxyPath","quoteData","formattedQuote","parseUnits","solveData","account","inputData","outputData","aggregatorData","zeroAddress","aggregatorsRouterAbi","haiku","formatUnits","ChainId","BigNumber","_getPreviewMethod","isMint","HoneyNativeAggregator","BaseAggregator","ChainId","getHoneyToken","tokenIn","tokenOut","honeyNativeState","args","isToken","isRedeem","coll","amount","publicClient","account","collaterals","InvalidArgumentError","assertPublicClient","hubOrderedCollaterals","collateral","BeraError","honeyVaultBalances","isBasketMode","getHoneyVaultsBalance","isBasketModeEnabled","collateralVaultBalance","collateralIdx","honeyFormattedAmountIn","formatUnits","quoteParams","quoteData","getHoneyPreview","honeyQuote","collateralsQuote","BigNumber","payload","getSwapPayload","honeyNative","zeroAddress","ChainId","aggregatorsRouterAbi","KyberSwapAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","isTokenInNative","isTokenOutNative","tokenInAddress","tokenOutAddress","inputAmountAfterFees","url","routeData","formattedQuote","buildRouteBody","params","buildUrl","key","value","buildData","inputData","account","outputData","aggregatorData","zeroAddress","aggregatorsRouterAbi","kyberswap","zeroAddress","ChainId","aggregatorsRouterAbi","OogaboogaAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","params","quote","formattedQuote","account","inputData","outputData","aggregatorData","zeroAddress","aggregatorsRouterAbi","oogabooga","zeroAddress","ChainId","aggregatorsRouterAbi","OpenOceanAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","publicClient","rewardVault","assertPublicClient","InvalidArgumentError","inputAmountAfterFees","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","gasPrice","quoteParams","quoteResponse","quoteData","isNotFound","message","RequestError","formattedQuote","inputData","outputData","aggregatorData","aggregatorsRouterAbi","openOcean","ChainId","wberaAbi","WBeraAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","isToken","amount","isWrap","wberaAbi","wberaSwap","useSWRImmutable","zeroAddress","aggregatorsRouterAbi","usePublicClient","useAggregatorsRouterFeeBps","publicClient","usePublicClient","config","parseBaseArgs","swrResponse","useSWRImmutable","zeroAddress","aggregatorsRouter","fee","aggregatorsRouterAbi","useSWRImmutable","useConfig","getPublicClient","erc4626Abi","getUnderlyingToken","token","wagmiConfig","isToken","publicClient","getPublicClient","assertPublicClient","address","erc4626Abi","getTokenInformation","e","err","initBeraError","useUnderlyingAsset","token","wagmiConfig","useConfig","useSWRImmutable","isToken","getUnderlyingToken","useSWR","parseUnits","zeroAddress","useBeraWallet","usePublicClient","USE_AGGREGATORS_QUOTES_QUERY_KEY","getQueryKey","aggregator","account","args","feeBps","options","activeAggregators","isMAEnabled","name","usesMAContract","tokenIn","tokenOut","amount","slippage","referrer","rewardVault","parsedAmount","parseUnits","needsUnderlyingToken","getQueryFn","publicClient","proxyAggregatorsThroughVercel","aggregatorsFeeBps","underlyingToken","honeyCollaterals","raw_useSingleAggregatorQuote","useSWR","getAggregatorsSWROptions","err","key","config","revalidate","revalidateOpts","BeraError","BaseAggregator","RequestError","seconds","useSingleAggregatorQuote","useBeraWallet","useBeraFlag","usePublicClient","useAggregatorsRouterFeeBps","isToken","parseBaseArgs","zeroAddress","AGGREGATORS","oogabooga","fly","kyberswap","openOcean","haiku","enso","bex","honeyNative","erc4626Deposit","useAggregatorsQuotes","args","options","account","useBeraWallet","proxyAggregatorsThroughVercel","useBeraFlag","activeAggregators","publicClient","usePublicClient","feeBps","useAggregatorsRouterFeeBps","isWrapOrUnwrap","isToken","isBgtRedeem","defaultChainId","underlyingToken","useUnderlyingAsset","isNativeSwap","config","parseBaseArgs","isMAEnabled","zeroAddress","swrOptions","getAggregatorsSWROptions","sharedArgs","oogaBogaResult","raw_useSingleAggregatorQuote","flyResult","erc4626Result","kyberswapResult","openOceanResult","haikuResult","ensoResult","bexProtocol","useBexStatus","bexResult","wberaSwapResult","wberaSwap","bgtRedeemResult","bgtRedeem","honeyResult","results","i","useMemo","error","result","loadingAggregatorsNames","r","quotes","data","isLoading","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","balancerPoolCreationHelperAbi","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","erc20Abi","formatUnits","GetExploitedTokens","BigNumber","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","formatEther","isAddressEqual","BigNumber","useSWR","isAddress","zeroAddress","rewardVaultAbi","useBeraWallet","usePublicClient","useSWRImmutable","isAddress","zeroAddress","rewardVaultFactoryAbi","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","defaultChainId","usePublicClient","useTokenInformation","args","options","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","_","address","chainId","defaultChainId","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","parseUnits","zeroAddress","BigNumber","useSWR","useBeraWallet","useConfig","usePollAllowances","args","options","config","useConfig","account","useBeraWallet","QUERY_KEY","swrResponse","useSWR","items","getAllowances","calculateMaxAmountIn","amount","decimals","slippage","slippageInWei","parseUnits","useMultipleTokenApprovalsWithSlippage","tokenInput","options","items","useMemo","token","zeroAddress","BigNumber","allowances","refresh","isLoading","usePollAllowances","allowance","item","isToken","BeraError","maxAmountIn","useMemo","useSWRImmutable","formatUnits","isAddress","usePublicClient","useSWRImmutable","isAddress","defaultChainId","usePublicClient","useMultipleTokenInformation","args","options","publicClient","usePublicClient","QUERY_KEY","defaultChainId","swrResponse","useSWRImmutable","addresses","chainId","assertPublicClient","address","isAddress","tk","getTokenInformation","useMemo","useSWR","isAddress","zeroAddress","defaultChainId","useContext","useTokens","context","useContext","TokenContext","BeraError","useTokenCurrentPrices","addressIn","options","tokenList","ensoTokens","useTokens","beraAddresses","useMemo","addresses","a","isAddress","tokenSet","token","isToken","zeroAddress","QUERY_KEY","apiResponse","useSWR","getTokenCurrentPrices","ensoMatchingPrices","ensoPricesMap","defaultChainId","address","price","data","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","balancerVaultAbi","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","useMemo","useCallback","useMemo","defaultChainId","useTokenPrices","tokens","options","ensoTokens","useTokens","apiResponse","useTokenCurrentPrices","token","defaultChainId","data","useMemo","prices","tokenMap","chainId","address","price","tk","priceMap","map","item","getTokenPrice","useCallback","usePriceImpact","tokenIn","tokenOut","formattedAmountIn","formattedAmountOut","getTokenPrice","isLoading","useTokenPrices","useMemo","tokenInPrice","tokenOutPrice","computePriceImpact","useSWR","formatEther","parseUnits","zeroAddress","berachainChainId","useBeraWallet","usePublicClient","ethAddress","zeroAddress","EnsoErc4626Aggregator","BaseAggregator","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","underlyingToken","assertAddress","ensoClient","getEnsoClient","ethAddress","zapTokenOut","bundleActions","offset","bundle","tokenOutAddress","ensoErc4626","useBendZapSupply","tokenIn","loanToken","bendVault","rewardVault","amount","slippage","options","getTokenPrice","useTokenPrices","swrResponse","useBendZapSupplyHelper","parseUnits","zapSupplyAmount","useGetConvertToAssets","priceImpact","usePriceImpact","isCrossChain","berachainChainId","nativeBalanceData","isNativeBalanceLoading","usePollBalance","zeroAddress","transactionValue","nativeBalance","hasInsufficientNativeBalance","nativeFee","formatEther","fromAddress","useBeraWallet","isEnabled","isToken","publicClientBeraChain","usePublicClient","useSWR","assertPublicClient","assertAddress","assertDefined","ensoErc4626","getPublicClient","useSWR","parseUnits","berachainChainId","useBeraWallet","useConfig","ethAddress","zeroAddress","erc20Abi","ethAddress","getTransactionsFromBundle","fromAddress","amountIn","tokenIn","chainId","ensoClient","bundle","publicClient","transactions","approvalRequest","requiresApproval","getEnsoSwapBundle","fromAddress","amountIn","tokenIn","tokenOut","chainId","ensoClient","destinationChainId","slippage","publicClient","InvalidArgumentError","zeroAddress","ethAddress","bundleAction","bundle","transactions","getTransactionsFromBundle","useMemo","useSWR","useBeraWallet","useConfig","usePublicClient","usePollWalletBalances","args","options","publicClient","usePublicClient","wagmiConfig","useConfig","connectedAccount","useBeraWallet","tokenList","refresh","useTokens","wallet","tokens","useMemo","t","QUERY_KEY","swrResponse","useSWR","getWalletBalances","useEnsoSwapBundle","tokenIn","tokenOut","amount","slippage","fromAddress","useBeraWallet","wagmiConfig","useConfig","ensoClient","getEnsoClient","refreshBalances","usePollWalletBalances","isEnabled","swrResponse","useSWR","assertAddress","assertDefined","assertAmount","publicClient","getPublicClient","assertPublicClient","rawAmount","parseUnits","getEnsoSwapBundle","berachainChainId","useSWR","formatUnits","parseUnits","chainConfigs","defaultChainId","useBeraWallet","useZapStakeBera","inputToken","amount","underlyingToken","slippage","tokenOut","options","account","useBeraWallet","quoteAccount","chainConfigs","defaultChainId","QUERY_KEY","swrResponse","useSWR","rawAmount","parseUnits","ensoErc4626","priceImpactPercentage","usePriceImpact","formatUnits","useCallback","useEffect","useState","matter","encodeFunctionData","erc20Abi","parseAbiItem","toHex","beraChefAbi","rewardVaultAbi","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","bgtAbi","useBeraWallet","usePublicClient","useSWRImmutable","governanceAbi","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","governanceAbi","useBeraWallet","usePublicClient","useHasVoted","proposalId","wallet","account","useBeraWallet","publicClient","usePublicClient","address","useSWR","isAddress","assertPublicClient","config","parseBaseArgs","governanceAbi","useSWR","governanceTimelockAbi","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","i","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","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","governanceAbi","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","bgtAbi","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","governanceAbi","usePublicClient","ProposalStateMap","useProposalState","proposalId","governorAddress","publicClient","usePublicClient","useSWRImmutable","assertPublicClient","snapshot","governanceAbi","useSWR","governanceTimelockAbi","usePublicClient","TimelockOperationState","useProposalTimelockState","proposalTimelockId","timelockAddress","publicClient","usePublicClient","useSWR","assertPublicClient","snapshot","governanceTimelockAbi","useSWR","usePublicClient","formatEther","governanceAbi","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","useConfig","usePublicClient","useHoneyBalances","publicClient","usePublicClient","account","useBeraWallet","collateralList","useHoneyConfig","wagmiConfig","useConfig","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","isToken","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","useSWR","BigNumber","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","bgtAbi","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","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","receiptTokenAddresses","account","version","options","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","assertPublicClient","receiptTokenAddress","getSWBeraWithdrawal","results","useSWR","isAddress","defaultChainId","usePublicClient","useRewardTokenToBeraRate","address","opt","QUERY_KEY","publicClient","usePublicClient","defaultChainId","useSWR","_","isAddress","InvalidArgumentError","assertPublicClient","getRewardTokenToBeraRate","useSWR","useSWR","erc20Abi","formatUnits","isAddress","beraChefAbi","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","dailyResolution","data","dailyData","lastDay","item","timestampMs","currentDay","currentDayStr","newTimestamp","useStakedAPR","range","swrResponse","useSWR","unsortedStakedBeraSnapshots","getStakedBeraSnapshots","dailyResolution","a","b","item","useMemo","useSWR","useBeraWallet","usePublicClient","BigNumber","useStakedData","stakingConfigs","window","useBeraFlag","publicClient","usePublicClient","account","useBeraWallet","receiptTokens","useMemo","config","inputTokens","aprKey","apr","useSWR","getStakedBeraAPR","walletBalances","isLoadingBalances","usePollWalletBalances","getTokenPrice","useTokenPrices","exchangeRatesKey","exchangeRates","assertPublicClient","token","getRewardTokenToBeraRate","balances","i","inputToken","stakedBalance","b","exchangeRate","inputTokenPrice","stakedAmount","BigNumber","stakedAmountUsd","positionsKey","positionsRaw","isLoadingPositions","isValidatingPositions","stakingConfig","stakingToken","earnings","getEarnedStakedBeraVault","data","exchangeRateRaw","unrealisedGains","earnedAmount","earnedAmountUsd","useSWR","getStakingDailyAssets","address","range","now","startDayDate","config","parseBaseArgs","url","beraFetchJson","useStakedSnapshots","range","addresses","swrResponse","useSWR","sortedStakingDailyAssetsArray","address","unstakingDailyAssets","getStakingDailyAssets","sortedStakingDailyAssets","dailyResolution","a","b","acc","addressData","useSWR","usePublicClient","useSWBeraVaultMetadata","receiptTokenAddress","publicClient","usePublicClient","blockTime","useBlockTime","useSWR","address","assertPublicClient","getSWBeraVaultMetadata","useSWR","usePublicClient","useTotalStakedAmount","vaultAddresses","publicClient","usePublicClient","swrResponse","useSWR","getTotalStakedAmount","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","useSWRImmutable","isAddress","zeroAddress","usePublicClient","useStakingTokenInformation","args","options","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","_","address","isToken","zeroAddress","beraToken","getStakingTokenInformation","useTokenPrice","token","options","isLoading","priceMap","useTokenPrices","useSWR","erc20Abi","usePublicClient","useTotalSupply","address","publicClient","usePublicClient","useSWR","assertPublicClient","erc20Abi","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","beraChefAbi","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","beaconDepositAbi","bgtAbi","beraChefAbi","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","useSWR","useBeraWallet","formatIncentivesTokenMap","allRewards","tokenMap","item","reward","useUserClaimableIncentives","account","useBeraWallet","allRewardsResponse","useSWR","BeraError","getUserClaimableIncentives","allRewards","tokenMap","useMemo","BeraMonitoring","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"]}
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/enso.ts","../../src/actions/dex/aggregators/erc4626.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/tokens/useUnderlyingAsset.ts","../../src/actions/tokens/getUnderlyingToken.ts","../../src/hooks/dex/useAggregatorsRouterFeeBps.ts","../../src/hooks/dex/useSingleAggregatorQuote.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/dex/usePriceImpact.ts","../../src/hooks/tokens/useTokenPrices.ts","../../src/hooks/enso/useBendDemultiply.ts","../../src/actions/enso/getBendDemultiplyBundle.ts","../../src/actions/enso/flashloan.ts","../../src/actions/enso/util.ts","../../src/hooks/enso/useEnsoWalletV2Address.ts","../../src/hooks/enso/useIsBendAuthorized.ts","../../src/hooks/enso/useBendMultiply.ts","../../src/actions/enso/getBendMultiplyBundle.ts","../../src/hooks/enso/useBendZapSupply.ts","../../src/actions/dex/aggregators/enso/ensoErc4626.ts","../../src/hooks/enso/useEnsoSwapBundle.ts","../../src/actions/enso/getEnsoSwapBundle.ts","../../src/hooks/tokens/usePollWalletBalances.ts","../../src/hooks/enso/useZapStakeBera.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/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/useStakedAPR.ts","../../src/utils/filter.ts","../../src/hooks/pol/useStakedData.ts","../../src/hooks/pol/useStakedSnapshots.ts","../../src/actions/pol/getStakingDailyAssets.ts","../../src/hooks/pol/useStakingVaultsMetadata.ts","../../src/hooks/pol/useTotalStakedAmount.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/useStakingTokenInformation.ts","../../src/hooks/tokens/useTokenPrice.ts","../../src/hooks/tokens/useTotalSupply.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/actions/validators/getBaselineRewardAllocation.ts","../../src/hooks/validators/useDailyValidatorBlockStats.ts","../../src/hooks/validators/useDefaultRewardAllocation.ts","../../src/hooks/validators/useManagedValidatorRole.ts","../../src/actions/validators/getValidatorRewardAllocatorAddress.ts","../../src/hooks/validators/useOnChainValidator.ts","../../src/hooks/validators/useStakingPoolBatch.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 } from \"../../actions/bend/getConvertToAssets\";\nimport { getConvertToAssets } from \"../../actions/bend/getConvertToAssets\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { DefaultHookOptions } from \"../../types/global\";\n\nexport const useGetConvertToAssets = (\n {\n sharesAmount,\n vaultAddress,\n vaultChainId,\n }: Omit<GetConvertToAssetsProps, \"publicClient\"> & { vaultChainId?: number },\n options?: DefaultHookOptions,\n) => {\n const publicClient = usePublicClient({ chainId: vaultChainId });\n const swrResponse = useSWR(\n publicClient && sharesAmount && vaultAddress\n ? [\"useGetConvertToAssets\", sharesAmount, vaultAddress, vaultChainId]\n : null,\n async ([_, sharesAmount, vaultAddress]) => {\n assertPublicClient(publicClient);\n\n return getConvertToAssets({\n sharesAmount,\n vaultAddress,\n publicClient,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n};\n","import { useMemo } from \"react\";\nimport { type Address, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { bex } from \"../../actions/dex/aggregators/bex\";\nimport { bgtRedeem } from \"../../actions/dex/aggregators/bgt\";\nimport { enso } from \"../../actions/dex/aggregators/enso/enso\";\nimport { erc4626Deposit } from \"../../actions/dex/aggregators/erc4626\";\nimport { fly } from \"../../actions/dex/aggregators/fly\";\nimport { haiku } from \"../../actions/dex/aggregators/haiku\";\nimport { honeyNative } from \"../../actions/dex/aggregators/honey\";\nimport { kyberswap } from \"../../actions/dex/aggregators/kyberswap\";\nimport { oogabooga } from \"../../actions/dex/aggregators/oogabooga\";\nimport { openOcean } from \"../../actions/dex/aggregators/openOcean\";\nimport { wberaSwap } from \"../../actions/dex/aggregators/wbera\";\nimport { useBeraFlag } from \"../../contexts/BeraFlags/BeraFlags\";\nimport type { HoneyConfigContextReturn } from \"../../contexts/HoneyConfigProvider\";\nimport type { SwapReferrer } from \"../../enum/dex\";\nimport type { IRawAggregatorQuote, MinimalERC20 } from \"../../types/dex\";\nimport type { DefaultHookOptions } from \"../../types/global\";\nimport { parseBaseArgs } from \"../../utils/parseBaseArgs\";\nimport { isToken } from \"../../utils/tokens\";\nimport { useUnderlyingAsset } from \"../tokens/useUnderlyingAsset\";\nimport { useAggregatorsRouterFeeBps } from \"./useAggregatorsRouterFeeBps\";\nimport { useBexStatus } from \"./useBexStatus\";\nimport {\n getAggregatorsSWROptions,\n raw_useSingleAggregatorQuote,\n} from \"./useSingleAggregatorQuote\";\n\nconst AGGREGATORS = [\n oogabooga,\n fly,\n kyberswap,\n openOcean,\n haiku,\n enso,\n bex,\n honeyNative,\n erc4626Deposit,\n];\n\ntype IUseAggregatorsQuotesArgs = BeraJS.BaseFunctionArgs & {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n amount: string;\n slippage: number;\n referrer?: SwapReferrer;\n rewardVault?: Address;\n /**\n * Useful cause the collaterals are provided byt he honeyContext and this way we can\n * use the Provider only in the swap page where is needed.\n *\n * The collaterals for the honey mint/redeem aggregator.\n */\n honeyNativeState?: Pick<\n HoneyConfigContextReturn,\n \"collateralList\" | \"protocol\"\n >;\n};\n\nexport function useAggregatorsQuotes(\n args: IUseAggregatorsQuotesArgs,\n options?: DefaultHookOptions,\n) {\n const { address: account } = useBeraWallet();\n const proxyAggregatorsThroughVercel = useBeraFlag(\n \"proxyAggregatorsThroughVercel\",\n );\n const activeAggregators = useBeraFlag(\"aggregators\");\n const publicClient = usePublicClient();\n const { data: feeBps } = useAggregatorsRouterFeeBps();\n\n const isWrapOrUnwrap =\n (isToken(args.tokenIn.address, \"BERA\") ||\n isToken(args.tokenIn.address, \"WBERA\")) &&\n (isToken(args.tokenOut.address, \"BERA\") ||\n isToken(args.tokenOut.address, \"WBERA\"));\n\n const isBgtRedeem = isToken(args.tokenIn.address, \"BGT\", {\n chainId: defaultChainId,\n });\n\n const { data: underlyingToken } = useUnderlyingAsset({\n token: args.tokenOut,\n });\n\n /**\n * Whether it's a native swap (wrap/unwrap) or BGT redeem\n */\n const isNativeSwap = isWrapOrUnwrap || isBgtRedeem;\n\n const { config } = parseBaseArgs(args);\n\n const isMAEnabled = config.bex.aggregatorsRouter !== zeroAddress;\n\n const swrOptions = getAggregatorsSWROptions(options);\n\n const sharedArgs = {\n activeAggregators,\n isMAEnabled,\n underlyingToken,\n isNativeSwap,\n account,\n publicClient,\n proxyAggregatorsThroughVercel,\n feeBps,\n } as const;\n\n // we're using independent useSWRs so we can show quotes as they come\n // instead of waiting for all of them to load\n const oogaBogaResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: oogabooga,\n },\n { opts: swrOptions },\n );\n\n const flyResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: fly,\n },\n { opts: swrOptions },\n );\n\n const erc4626Result = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: erc4626Deposit,\n },\n { opts: swrOptions },\n );\n\n const kyberswapResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: kyberswap,\n },\n { opts: swrOptions },\n );\n\n const openOceanResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: openOcean,\n },\n { opts: swrOptions },\n );\n\n const haikuResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: haiku,\n },\n { opts: swrOptions },\n );\n\n const ensoResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: enso,\n },\n { opts: swrOptions },\n );\n\n const { protocol: bexProtocol } = useBexStatus();\n\n const bexResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: bex,\n },\n { opts: { ...swrOptions, isEnabled: bexProtocol.isPaused === false } },\n );\n\n const wberaSwapResult = raw_useSingleAggregatorQuote({\n ...sharedArgs,\n ...args,\n aggregator: wberaSwap,\n });\n\n const bgtRedeemResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: bgtRedeem,\n },\n { opts: swrOptions },\n );\n\n const honeyResult = raw_useSingleAggregatorQuote(\n {\n ...sharedArgs,\n ...args,\n aggregator: honeyNative,\n },\n { opts: swrOptions },\n );\n\n const results = isWrapOrUnwrap\n ? [wberaSwapResult]\n : isBgtRedeem\n ? [bgtRedeemResult]\n : [\n oogaBogaResult,\n erc4626Result,\n flyResult,\n kyberswapResult,\n openOceanResult,\n haikuResult,\n ensoResult,\n honeyResult,\n bexProtocol.isPaused === false ? bexResult : null,\n ].filter((i): i is NonNullable<typeof i> => i !== null);\n\n const data = useMemo(() => {\n const error = results.reduce<(typeof results)[number][\"error\"]>(\n (error, result) => error || result.error,\n undefined,\n );\n\n const loadingAggregatorsNames = results\n .map((r, i) =>\n r.isLoading\n ? isNativeSwap\n ? wberaSwap.name\n : AGGREGATORS[i].name\n : null,\n )\n .filter(Boolean);\n\n const quotes = results\n .filter(\n (result) =>\n result !== undefined &&\n !result.isLoading &&\n !result.error &&\n result.data?.amountOut,\n )\n .map(({ data }) => data) as IRawAggregatorQuote[];\n\n const isLoading = quotes.length === 0 && loadingAggregatorsNames.length > 0;\n return { quotes, loadingAggregatorsNames, isLoading, error };\n }, [results]);\n\n return {\n ...data,\n refresh: () => results.map((r) => r.mutate()),\n };\n}\n","import {\n type Address,\n Slippage,\n type SorSwapResult,\n Swap,\n SwapKind,\n Token,\n TokenAmount,\n} from \"@berachain-foundation/berancer-sdk\";\nimport { decodeFunctionData, formatEther, zeroAddress } from \"viem\";\n\nimport { getUriFromLink } from \"@berachain/config\";\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport { vaultAbi as balancerVaultAbi } from \"@berachain/abis/bex/vault\";\n\nimport { Aggregators } from \"../../../enum/dex\";\nimport { assertPublicClient } from \"../../../errors/assert\";\nimport { BeraError } from \"../../../errors/BeraError\";\nimport { BeraMonitoring } from \"../../../errors/BeraMonitoring\";\nimport { RequestError } from \"../../../errors/RequestError\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"../../../types/dex\";\nimport { isToken } from \"../../../utils/tokens\";\nimport { BalancerApi } from \"../b-sdk\";\nimport { BaseAggregator } from \"./base\";\n\n// Constants\nconst DEFAULT_DEADLINE = 60 * 5; // default transaction deadline in seconds\nconst STALE_PRICE_THRESHOLD = 0.05; // 5% threshold for stale prices\nconst swapKind = SwapKind.GivenIn;\n\nclass BexAggregator extends BaseAggregator {\n name = Aggregators.HubPools;\n supportedChains = [ChainId.MAINNET, ChainId.BEPOLIA];\n readonly url = getUriFromLink(this.config.api);\n readonly type = \"graphql\";\n\n /**\n * Helper function to convert zero address to wrapped token address\n */\n private convertZeroToWrapped(address: Address): Address {\n return isToken(address, \"BERA\") ? this.config.tokens.wbera : address;\n }\n\n /**\n * Helper to calculate price impact percentage\n */\n private calculatePriceImpact(priceImpact: {\n error: string | null;\n priceImpact?: string;\n }): number {\n if (priceImpact.error) {\n console.error(\"Swap price impact error\", priceImpact);\n return 0;\n }\n\n return Number(priceImpact.priceImpact);\n }\n\n /**\n * Helper to check for stale SOR prices\n */\n private checkStalePrices({\n onChainAmount,\n sorPaths,\n sorAmount,\n queryData,\n }: {\n onChainAmount: TokenAmount;\n sorPaths: { pools: string[] }[];\n sorAmount: string;\n queryData: IAggregatorArgs;\n }): void {\n // Check for stale prices\n const deltaFromSorAmount =\n Number.parseFloat(formatEther(onChainAmount.scale18)) /\n Number.parseFloat(sorAmount);\n\n if (Math.abs(1 - deltaFromSorAmount) > STALE_PRICE_THRESHOLD) {\n console.warn(\n \"SOR returned stale prices. Delta from return amount is more than 5%\",\n {\n deltaFromSorAmount,\n },\n );\n\n const error = new BeraError({\n reason: \"SOR_STALE_PRICES\",\n level: \"warning\",\n message:\n \"SOR returned stale prices. Delta from return amount is more than 5%\",\n extra: {\n deltaFromSorAmount,\n pools: sorPaths.map((p) => p.pools),\n onChainAmount: formatEther(onChainAmount.scale18),\n sorAmount,\n queryData,\n },\n fingerprint: [\"SOR_STALE_PRICES\"],\n });\n BeraMonitoring.captureException(error);\n }\n }\n\n async getQuote(args: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n const balancerApi = new BalancerApi(\n this.url,\n // @ts-expect-error b-sdk has more chains than berajs\n this.chainId,\n );\n const {\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n publicClient,\n } = args;\n this.assertChainSupport({ tokenIn, tokenOut });\n\n assertPublicClient(publicClient);\n\n const wberaIsBera = isToken(tokenIn, \"BERA\") || isToken(tokenOut, \"BERA\");\n\n // Initialize tokens\n const tokenInV3 = new Token(\n this.chainId,\n this.convertZeroToWrapped(tokenIn.address),\n tokenIn.decimals,\n );\n const tokenOutV3 = new Token(\n this.chainId,\n this.convertZeroToWrapped(tokenOut.address),\n tokenOut.decimals,\n );\n\n const tokenAmount = TokenAmount.fromRawAmount(\n tokenInV3,\n amount as `${number}`,\n );\n\n // swap paths\n const {\n paths: sorPaths,\n priceImpact,\n returnAmount: sorAmount,\n }: SorSwapResult = await balancerApi.sorSwapPaths.fetchSorSwapPaths({\n // @ts-expect-error b-sdk has more chains than berajs\n chainId: this.chainId,\n tokenIn: tokenInV3.address,\n tokenOut: tokenOutV3.address,\n swapKind,\n swapAmount: tokenAmount,\n });\n\n if (!sorPaths?.length) {\n throw new RequestError({\n response: undefined,\n endpoint: {\n url: this.url,\n name: this.name,\n type: this.type,\n },\n reason: BaseAggregator.PATH_NOT_FOUND_REASON,\n chainId: this.chainId,\n payload: {\n tokenIn: tokenInV3.address,\n tokenOut: tokenOutV3.address,\n swapKind,\n swapAmount: tokenAmount,\n },\n message: `No swap paths returned from Balancer API`,\n });\n }\n\n // execute swap query\n const swap = new Swap({\n chainId: this.chainId,\n paths: sorPaths,\n swapKind,\n userData: \"0x\" as `0x${string}`,\n });\n const queryOutput = await swap.query(publicClient.transport.url);\n\n if (!(\"expectedAmountOut\" in queryOutput)) {\n throw new Error(\"No Bex paths found\");\n }\n\n this.checkStalePrices({\n onChainAmount: queryOutput.expectedAmountOut,\n sorPaths,\n sorAmount,\n queryData: args,\n });\n\n // format quote response\n return {\n amountOut: queryOutput.expectedAmountOut.amount.toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: queryOutput.to,\n }),\n name: this.name,\n priceImpactPercentage: this.calculatePriceImpact(priceImpact),\n swapFeeBps: 0,\n getCalldata: ({ account }) => {\n // generate user transaction data\n const callData = swap.buildCall({\n slippage: Slippage.fromPercentage(slippage.toString() as `${number}`),\n deadline: BigInt(Math.round(Date.now() / 1000) + DEFAULT_DEADLINE),\n queryOutput,\n sender: account as Address,\n recipient: account as Address,\n wethIsEth: wberaIsBera,\n });\n\n const { args: params, functionName } = decodeFunctionData({\n abi: balancerVaultAbi,\n data: callData.callData,\n });\n\n return {\n params,\n functionName,\n abi: balancerVaultAbi,\n address: callData.to,\n value: callData.value || BigInt(0),\n };\n },\n };\n }\n}\n\nexport const bex = new BexAggregator();\n","import { ChainId } from \"@berachain/config/internal\";\n\nimport { Aggregators } from \"../../../enum/dex\";\nimport { InvalidArgumentError } from \"../../../errors/InvalidArgumentError\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n MinimalERC20,\n} from \"../../../types/dex\";\nimport { beraToken, isToken } from \"../../../utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\nclass RedeemBgtAggregator extends BaseAggregator {\n name = Aggregators.RedeemBgt;\n supportedChains = [ChainId.MAINNET, ChainId.BEPOLIA];\n readonly type = \"rpc\";\n\n checkChainSupport({\n tokenIn,\n tokenOut,\n }: {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n }): boolean {\n if (!super.checkChainSupport({ tokenIn, tokenOut })) {\n return false;\n }\n\n return (\n // only supported on same chain\n tokenIn.chainId === tokenOut.chainId &&\n isToken(tokenIn, \"BGT\", { chainId: tokenIn.chainId }) &&\n isToken(tokenOut, \"BERA\")\n );\n }\n // handles native swaps: wrap and unwrap\n async getQuote({\n tokenIn,\n amount,\n }: Omit<\n IAggregatorArgs,\n \"slippage\" | \"feeBps\" | \"tokenOut\" | \"account\"\n >): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({\n tokenIn,\n tokenOut: { ...beraToken, chainId: tokenIn.chainId },\n });\n\n if (!isToken(tokenIn, \"BGT\", { config: this.config })) {\n throw new InvalidArgumentError({\n property: \"tokenIn\",\n value: tokenIn,\n expected: \"BGT\",\n level: \"warning\",\n });\n }\n\n return {\n amountOut: amount,\n amountIn: amount,\n allowanceRequirements: [],\n name: Aggregators.RedeemBgt,\n isNativeSwap: true,\n swapFeeBps: 0,\n // not adding calldata here because it depends on the connected wallet\n // bgt redeem requires a receiver address\n // moreover this is a sensitive operation, better be sure of what data is being sent\n // by controlling it on the consumer side\n } as const;\n }\n}\n\nexport const bgtRedeem = new RedeemBgtAggregator();\n","import { zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport aggregatorsRouterAbi from \"@berachain/abis/meta-aggregator/metaAggregatorV2\";\n\nimport { Aggregators } from \"../../../../enum/dex\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n} from \"../../../../types/dex\";\nimport type { IContractWrite } from \"../../../../types/global\";\nimport { BaseAggregator } from \"../base\";\n\nclass EnsoAggregator extends BaseAggregator {\n name = Aggregators.Enso;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n needsAccountForQuote = true;\n\n notFoundMessages: string[] = [\n \"Could not build shortcuts for route\",\n \"Could not quote shortcuts for route\",\n \"Swap not found for a required underlying of defi route,\",\n \"No route found from\",\n ];\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=enso`\n : `${this.config.bex.aggregatorsProxyUrl}/enso/api/v1/shortcuts/route?`;\n\n const url = new URL(this.url);\n url.searchParams.set(\n \"fromAddress\",\n this.config.bex.aggregatorsRouterExecutor,\n );\n url.searchParams.set(\"receiver\", this.config.bex.aggregatorsRouterExecutor);\n url.searchParams.set(\"spender\", this.config.bex.aggregatorsRouterExecutor);\n url.searchParams.set(\"amountIn\", inputAmountAfterFees);\n url.searchParams.set(\"tokenIn\", tokenInAddress);\n url.searchParams.set(\"tokenOut\", tokenOutAddress);\n url.searchParams.set(\"chainId\", ChainId.MAINNET.toString());\n url.searchParams.set(\"slippage\", (Number(slippage) * 100).toString());\n url.searchParams.set(\"refundReceiver\", account);\n\n const response = await this.fetch(url);\n\n const quote = await response.json();\n\n const inputData = this.getInputData({\n tokenIn: tokenInAddress,\n amountIn: amount,\n isNative: isTokenInNative,\n });\n\n const outputData = {\n tokenOut: tokenOutAddress,\n receiver: account,\n minAmountOut: this.getMinAmountOut(quote.amountOut.toString(), slippage),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quote.tx?.to,\n data: quote.tx?.data,\n };\n\n return {\n amountOut: quote.amountOut.toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n getCalldata: () =>\n ({\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 }) satisfies Omit<\n IContractWrite<typeof aggregatorsRouterAbi, \"swap\">,\n \"message\" | \"actionType\"\n >,\n };\n }\n}\n\nexport const enso = new EnsoAggregator();\n","import { erc4626Abi, formatUnits } from \"viem\";\n\nimport { wberaStakerVaultAbi as stakeBeraVaultAbi } from \"@berachain/abis/pol/wberaStakerVault\";\n\nimport { ContractName } from \"../../../enum/contracts\";\nimport { Aggregators } from \"../../../enum/dex\";\nimport { assertDefined, assertPublicClient } from \"../../../errors/assert\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n Token,\n} from \"../../../types/dex\";\nimport type { IContractWrite } from \"../../../types/global\";\nimport { isToken } from \"../../../utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\n/**\n * Aggregator that handles direct deposits into ERC4626 vault tokens.\n * Instead of routing through a DEX, this deposits the underlying asset directly\n * into the vault contract (e.g. WBERA → swBERA, HONEY → iBERA, or Bend vault underlying → vault token).\n *\n * Special-cases native BERA → swBERA via `depositNative` (no approval needed).\n */\nclass ERC4626Aggregator extends BaseAggregator {\n name = Aggregators.ERC4626;\n supportedChains = null;\n readonly type = \"rpc\";\n\n /**\n * Returns true when tokenOut is an ERC4626 vault whose underlying asset matches tokenIn,\n * or when depositing native BERA into swBERA.\n */\n checkChainSupport({\n tokenIn,\n tokenOut,\n underlyingToken,\n }: {\n tokenIn: Token;\n tokenOut: Token;\n underlyingToken?: Token;\n }): boolean {\n const result =\n super.checkChainSupport({ tokenIn, tokenOut, underlyingToken }) &&\n !!underlyingToken &&\n underlyingToken?.chainId === tokenOut.chainId &&\n (isToken(underlyingToken, tokenIn) ||\n // this is a special case for the swbera vault\n (isToken(tokenIn, \"BERA\") && isToken(tokenOut, \"SWBERA\")));\n\n return result;\n }\n\n /**\n * Fetches a deposit quote by calling `convertToShares` on the vault.\n * Returns calldata for either `deposit` (ERC20) or `depositNative` (BERA → swBERA).\n */\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n underlyingToken,\n publicClient,\n }: Omit<\n IAggregatorArgs,\n \"slippage\" | \"feeBps\"\n >): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut, underlyingToken });\n\n assertDefined(underlyingToken, \"underlyingToken\");\n assertPublicClient(publicClient);\n\n const rawOutputAmount = await publicClient.readContract({\n address: tokenOut.address,\n abi: erc4626Abi,\n functionName: \"convertToShares\",\n args: [BigInt(amount)],\n });\n\n const isSwBeraNative =\n isToken(tokenOut, \"SWBERA\") && isToken(tokenIn, \"BERA\");\n\n return {\n amountOut: rawOutputAmount.toString(),\n amountIn: amount,\n allowanceRequirements: isSwBeraNative\n ? []\n : [\n {\n token: tokenIn,\n spender: tokenOut.address,\n amount: {\n raw: amount,\n formatted: formatUnits(BigInt(amount), tokenIn.decimals),\n },\n },\n ],\n name: Aggregators.ERC4626,\n isNativeSwap: false,\n swapFeeBps: 0,\n getCalldata: ({ account }) =>\n isSwBeraNative\n ? ({\n abi: stakeBeraVaultAbi,\n address: tokenOut.address,\n functionName: \"depositNative\",\n params: [BigInt(amount), account],\n value: BigInt(amount),\n } satisfies Omit<\n IContractWrite<typeof stakeBeraVaultAbi, \"depositNative\">,\n \"message\" | \"actionType\"\n >)\n : ({\n abi: erc4626Abi,\n address: tokenOut.address,\n functionName: \"deposit\",\n contractName: ContractName.ERC4626,\n params: [BigInt(amount), account],\n value: 0n,\n } satisfies Omit<\n IContractWrite<typeof erc4626Abi, \"deposit\">,\n \"message\" | \"actionType\"\n >),\n };\n }\n}\n\nexport const erc4626Deposit = new ERC4626Aggregator();\n","import { type Address, type Hex, zeroAddress } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport aggregatorsRouterAbi from \"@berachain/abis/meta-aggregator/metaAggregatorV2\";\n\nimport { Aggregators } from \"../../../enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"../../../types/dex\";\nimport type { IContractWrite } from \"../../../types/global\";\nimport { isToken } from \"../../../utils/tokens\";\nimport { BaseAggregator } from \"./base\";\n\nconst BASE_URL = \"https://api.fly.trade/aggregator\";\n\nclass FlyAggregator extends BaseAggregator {\n name = Aggregators.Fly;\n supportedChains = [ChainId.MAINNET];\n readonly type = \"rest\";\n\n notFoundMessages: string[] = [\n \"Couldn't recognize to token\",\n \"Couldn't recognize from 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,\n aggregatorsFeeBps,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n 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 // 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 allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps ?? 0,\n };\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\n this.url = txUrl.toString();\n\n const txParams = new URLSearchParams({\n quoteId: quoteData.id,\n estimateGas: \"false\",\n });\n\n txUrl.search = txParams.toString();\n\n const txResponse = await this.fetch(txUrl);\n\n const txData: {\n to: Address;\n data: Hex;\n } = await txResponse.json();\n\n return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\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 return {\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 } satisfies Omit<\n IContractWrite<typeof aggregatorsRouterAbi, \"swap\">,\n \"message\" | \"actionType\"\n >;\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 \"@berachain/abis/meta-aggregator/metaAggregatorV2\";\n\nimport { Aggregators, SwapReferrer } from \"../../../enum/dex\";\nimport { BeraError } from \"../../../errors/BeraError\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"../../../types/dex\";\nimport type { IContractWrite } from \"../../../types/global\";\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 aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n referrer,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n if (tokenIn.decimals === undefined || tokenOut.decimals === undefined) {\n throw new BeraError({\n message: \"Missing required params\",\n level: \"error\",\n });\n }\n\n this.assertChainSupport({ tokenIn, tokenOut });\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n // 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 tokenIn.decimals,\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 tokenOut.decimals,\n ).toString(),\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n };\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 return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\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(\n formattedQuote.amountOut,\n slippage,\n ),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: solveData.to,\n data: solveData.data,\n };\n return {\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 } satisfies Omit<\n IContractWrite<typeof aggregatorsRouterAbi, \"swap\">,\n \"message\" | \"actionType\"\n >;\n },\n };\n }\n}\n\nexport const haiku = new HaikuAggregator();\n","import { type Address, formatUnits } from \"viem\";\n\nimport { ChainId } from \"@berachain/config/internal\";\n\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport type { HoneyConfigContextReturn } from \"../../../contexts/HoneyConfigProvider\";\nimport { Aggregators } from \"../../../enum/dex\";\nimport { assertPublicClient } from \"../../../errors/assert\";\nimport { BeraError } from \"../../../errors/BeraError\";\nimport { InvalidArgumentError } from \"../../../errors/InvalidArgumentError\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n Token,\n TokenWithMetadata,\n} from \"../../../types/dex\";\nimport { getHoneyToken, isToken } from \"../../../utils/tokens\";\nimport {\n getHoneyPreview,\n type HoneyPreviewArgs,\n HoneyPreviewMethod,\n} from \"../../honey/getHoneyPreview\";\nimport { getHoneyVaultsBalance } from \"../../honey/getHoneyVaultsBalance\";\nimport { getSwapPayload } from \"../../honey/getSwapPayload\";\nimport { isBasketModeEnabled } from \"../../honey/isBasketModeEnabled\";\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 /**\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 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 checkChainSupport({\n tokenIn,\n tokenOut,\n honeyNativeState,\n }: {\n tokenIn: Token;\n tokenOut: Token;\n honeyNativeState?: Pick<HoneyConfigContextReturn, \"collateralList\">;\n }): boolean {\n return (\n super.checkChainSupport({ tokenIn, tokenOut }) &&\n tokenIn.chainId === tokenOut.chainId &&\n this.isHoneyNativeSwap({\n tokenIn: tokenIn.address,\n tokenOut: tokenOut.address,\n honeyNativeState,\n })\n );\n }\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n publicClient,\n account,\n honeyNativeState,\n }: IHoneyNativeArgs): Promise<IRawAggregatorQuote | 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.assertChainSupport({ tokenIn, tokenOut });\n\n const isMint = isToken(tokenOut, this.honeyToken);\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(collateral.address, isMint ? tokenIn.address : tokenOut.address),\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?.balance.formatted ?? \"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 = 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 collateralList: hubOrderedCollaterals,\n publicClient,\n priceFeedMap: undefined,\n isPythWrapperEnabled: false,\n });\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 allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: Aggregators.Honey,\n swapFeeBps: 0,\n getCalldata: ({ account }) => {\n return payload({ account });\n },\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 \"@berachain/abis/meta-aggregator/metaAggregatorV2\";\n\nimport { Aggregators } from \"../../../enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"../../../types/dex\";\nimport type { IContractWrite } from \"../../../types/global\";\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 aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n const {\n isTokenInNative,\n isTokenOutNative,\n tokenInAddress,\n tokenOutAddress,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n this.url = proxyAggregatorsThroughVercel\n ? `/api/aggregators?aggregator=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 name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n } satisfies IRawAggregatorQuote;\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 return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\n const outputData = {\n tokenOut: tokenOutAddress,\n receiver: account,\n minAmountOut: this.getMinAmountOut(\n formattedQuote.amountOut,\n slippage,\n ),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: buildData.data.routerAddress,\n data: buildData.data.data,\n };\n return {\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 } satisfies Omit<\n IContractWrite<typeof aggregatorsRouterAbi, \"swap\">,\n \"message\" | \"actionType\"\n >;\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 \"@berachain/abis/meta-aggregator/metaAggregatorV2\";\n\nimport { Aggregators } from \"../../../enum/dex\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"../../../types/dex\";\nimport type { IContractWrite } from \"../../../types/global\";\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 aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const {\n tokenInAddress,\n tokenOutAddress,\n isTokenInNative,\n isTokenOutNative,\n } = this.parseAddresses(tokenIn.address, tokenOut.address);\n\n const inputAmountAfterFees = this.getAmountAfterFees(\n amount,\n aggregatorsFeeBps,\n );\n\n 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 allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n spender: this.config.bex.aggregatorsRouter,\n rawAmount: amount,\n }),\n name: this.name,\n priceImpactPercentage: quote.priceImpact,\n swapFeeBps: aggregatorsFeeBps!,\n } satisfies IRawAggregatorQuote;\n\n return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\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(\n formattedQuote.amountOut,\n slippage,\n ),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quote.tx?.to,\n data: quote.tx?.data,\n };\n return {\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 } satisfies Omit<\n IContractWrite<typeof aggregatorsRouterAbi, \"swap\">,\n \"message\" | \"actionType\"\n >;\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 \"@berachain/abis/meta-aggregator/metaAggregatorV2\";\n\nimport { Aggregators } from \"../../../enum/dex\";\nimport { assertPublicClient } from \"../../../errors/assert\";\nimport { InvalidArgumentError } from \"../../../errors/InvalidArgumentError\";\nimport { RequestError } from \"../../../errors/RequestError\";\nimport type { IAggregatorArgs, IRawAggregatorQuote } from \"../../../types/dex\";\nimport type { IContractWrite } from \"../../../types/global\";\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 publicClient,\n rewardVault,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n assertPublicClient(publicClient);\n\n if (!tokenIn.decimals) {\n throw new InvalidArgumentError({\n property: \"tokenIn.decimals\",\n value: tokenIn.decimals,\n expected: \"number\",\n chainId: this.chainId,\n });\n }\n\n this.assertChainSupport({ tokenIn, tokenOut });\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.address, tokenOut.address);\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 allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: this.config.bex.aggregatorsRouter,\n }),\n name: this.name,\n swapFeeBps: aggregatorsFeeBps!,\n };\n\n return {\n ...formattedQuote,\n getCalldata: ({ account }) => {\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(\n formattedQuote.amountOut,\n slippage,\n ),\n isNative: isTokenOutNative,\n };\n\n const aggregatorData = {\n aggregator: quoteData.data.to,\n data: quoteData.data.data,\n };\n return {\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 } satisfies Omit<\n IContractWrite<typeof aggregatorsRouterAbi, \"swap\">,\n \"message\" | \"actionType\"\n >;\n },\n };\n }\n}\n\nexport const openOcean = new OpenOceanAggregator();\n","import { ChainId } from \"@berachain/config/internal\";\n\nimport { wberaAbi } from \"@berachain/abis/wbera\";\n\nimport { Aggregators } from \"../../../enum/dex\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n Token,\n} from \"../../../types/dex\";\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 checkChainSupport({\n tokenIn,\n tokenOut,\n }: {\n tokenIn: Token;\n tokenOut: Token;\n }): boolean {\n if (\n // same chain\n tokenIn.chainId !== tokenOut.chainId ||\n // must be one of our chains\n !super.checkChainSupport({ tokenIn, tokenOut })\n ) {\n return false;\n }\n\n return (\n (isToken(tokenIn, \"BERA\") && isToken(tokenOut, \"WBERA\")) ||\n (isToken(tokenIn, \"WBERA\") && isToken(tokenOut, \"BERA\"))\n );\n }\n\n // handles native swaps: wrap and unwrap\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n }: Omit<\n IAggregatorArgs,\n \"slippage\" | \"feeBps\"\n >): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n const isWrap = isToken(tokenIn, \"BERA\") && isToken(tokenOut, \"WBERA\");\n\n return {\n amountOut: amount,\n amountIn: amount,\n allowanceRequirements: [],\n name: isWrap ? Aggregators.Wrap : Aggregators.Unwrap,\n isNativeSwap: true,\n swapFeeBps: 0,\n getCalldata: () => {\n return 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}\n\nexport const wberaSwap = new WBeraAggregator();\n","import useSWRImmutable from \"swr/immutable\";\n\nimport { useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { getUnderlyingToken } from \"../../actions/tokens/getUnderlyingToken\";\nimport type { MinimalERC20 } from \"../../types/dex\";\nimport { isToken } from \"../../utils/tokens\";\n\n/**\n * SWR hook that resolves the underlying asset of an ERC4626 vault token.\n * Returns `null` for non-vault tokens. Results are cached immutably since\n * a vault's underlying asset doesn't change.\n */\nexport function useUnderlyingAsset({ token }: { token: MinimalERC20 }) {\n const wagmiConfig = useConfig();\n\n return useSWRImmutable(\n token && wagmiConfig && !isToken(token, \"BERA\")\n ? [\"useUnderlyingAsset\", token]\n : null,\n async ([, token]) => getUnderlyingToken({ token, wagmiConfig }),\n );\n}\n","import { type Config, getPublicClient } from \"@wagmi/core\";\nimport { erc4626Abi } from \"viem\";\n\nimport { assertPublicClient } from \"../../errors/assert\";\nimport { initBeraError } from \"../../errors/initBeraError\";\nimport type { MinimalERC20 } from \"../../types/dex\";\nimport { isToken } from \"../../utils/tokens\";\nimport { getTokenInformation } from \"./getTokenInformation\";\n\n/**\n * Attempts to resolve the underlying asset of an ERC4626 vault by calling `asset()`.\n * Returns the full token info if the token is an ERC4626 vault, or `null` if it isn't\n * (i.e. the `asset()` call reverts). Skips the native gas token (BERA) since it can't be a vault.\n */\nexport async function getUnderlyingToken({\n token,\n wagmiConfig,\n}: {\n token: MinimalERC20;\n wagmiConfig: Config;\n}) {\n try {\n if (isToken(token, \"BERA\")) {\n // gas token can't have an underlying token\n return null;\n }\n\n const publicClient = getPublicClient(wagmiConfig, {\n chainId: token.chainId,\n });\n\n assertPublicClient(publicClient);\n\n const address = await publicClient.readContract({\n address: token.address,\n abi: erc4626Abi,\n functionName: \"asset\",\n });\n\n return await getTokenInformation({\n address: address,\n publicClient,\n chainId: token.chainId,\n });\n } catch (e) {\n const err = initBeraError({ cause: e });\n if (err.reason === 'The contract function \"asset\" reverted.') {\n return null;\n }\n\n throw err;\n }\n}\n","import useSWRImmutable from \"swr/immutable\";\nimport { type PublicClient, zeroAddress } from \"viem\";\n\nimport aggregatorsRouterAbi from \"@berachain/abis/meta-aggregator/metaAggregatorV2\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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, { type SWRConfiguration } from \"swr\";\nimport { type Address, type PublicClient, parseUnits, zeroAddress } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { BaseAggregator } from \"../../actions/dex/aggregators/base\";\nimport { useBeraFlag } from \"../../contexts/BeraFlags/BeraFlags\";\nimport type {\n HoneyConfigContextReturn,\n TokenWithOrder,\n} from \"../../contexts/HoneyConfigProvider\";\nimport { Aggregators, type SwapReferrer } from \"../../enum/dex\";\nimport { POLLING } from \"../../enum/polling\";\nimport { BeraError } from \"../../errors/BeraError\";\nimport { RequestError } from \"../../errors/RequestError\";\nimport type { MinimalERC20 } from \"../../types/dex\";\nimport type { DefaultHookOptions } from \"../../types/global\";\nimport { parseBaseArgs } from \"../../utils/parseBaseArgs\";\nimport { seconds } from \"../../utils/time\";\nimport { isToken } from \"../../utils/tokens\";\nimport { useAggregatorsRouterFeeBps } from \"./useAggregatorsRouterFeeBps\";\n\nexport type IUseAggregatorsQuotesArgs = BeraJS.BaseFunctionArgs & {\n tokenIn: MinimalERC20;\n tokenOut: MinimalERC20;\n amount: string;\n slippage: number;\n referrer?: SwapReferrer;\n rewardVault?: Address;\n /**\n * Useful cause the collaterals are provided byt he honeyContext and this way we can\n * use the Provider only in the swap page where is needed.\n *\n * The collaterals for the honey mint/redeem aggregator.\n */\n honeyNativeState?: Pick<\n HoneyConfigContextReturn,\n \"collateralList\" | \"protocol\"\n >;\n underlyingToken?: MinimalERC20 | null;\n};\n\ntype IQueryKey = readonly [\n string, // \"useAggregatorsQuotes\n string, // name\n MinimalERC20, // tokenIn\n MinimalERC20, // tokenOut\n string, // parsedAmount\n number, // slippage\n Address | undefined, // account\n number | undefined, // feeBps\n SwapReferrer | undefined, // referrer\n Address | undefined, // rewardVault\n MinimalERC20 | null | undefined, // underlyingToken\n TokenWithOrder[] | undefined, // collateralList\n];\n\nexport const USE_AGGREGATORS_QUOTES_QUERY_KEY = \"useAggregatorsQuotes\";\n\n/**\n * Builds the SWR cache key for a single aggregator quote request.\n * Returns `null` (disabling the query) when the aggregator is unsupported,\n * disabled via config flags, or missing required dependencies like feeBps.\n */\nfunction getQueryKey({\n aggregator,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n isMAEnabled,\n}: {\n aggregator: BaseAggregator;\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 isMAEnabled: boolean;\n}): IQueryKey | null {\n if (options?.opts?.isEnabled !== undefined && !options?.opts?.isEnabled) {\n return null;\n }\n\n if (!Number(args.amount)) {\n return null;\n }\n if (\n !aggregator.checkChainSupport({\n tokenIn: args.tokenIn,\n tokenOut: args.tokenOut,\n underlyingToken: args.underlyingToken,\n honeyNativeState: args.honeyNativeState,\n })\n ) {\n return null;\n }\n\n const name = aggregator.name;\n\n const usesMAContract = ![\n Aggregators.HubPools,\n Aggregators.Honey,\n Aggregators.Wrap,\n Aggregators.Unwrap,\n Aggregators.ERC4626,\n ].includes(name);\n\n if (!isMAEnabled && usesMAContract) {\n return null;\n }\n const { tokenIn, tokenOut, amount, slippage, referrer, rewardVault } = args;\n\n const parsedAmount = parseUnits(amount, tokenIn.decimals).toString();\n\n const isEnabledOnConfig =\n // always enable wrap and unwrap\n aggregator.name === Aggregators.Wrap ||\n aggregator.name === Aggregators.RedeemBgt ||\n aggregator.name === Aggregators.Honey ||\n !activeAggregators ||\n activeAggregators.includes(name.toLowerCase().replaceAll(\" \", \"\"));\n\n if (!isEnabledOnConfig) {\n return null;\n }\n if (\n aggregator.name === Aggregators.Honey &&\n args.honeyNativeState?.protocol.isPaused\n ) {\n // if the honey protocol is paused, don't query any quotes\n return null;\n }\n\n const needsUnderlyingToken =\n aggregator.name === Aggregators.ERC4626 ||\n aggregator.name === Aggregators.EnsoErc4626;\n\n if (usesMAContract && feeBps === undefined) {\n return null;\n }\n\n return [\n USE_AGGREGATORS_QUOTES_QUERY_KEY,\n name,\n tokenIn,\n tokenOut,\n parsedAmount,\n slippage,\n aggregator.needsAccountForQuote ? account : undefined,\n usesMAContract ? feeBps : 0,\n referrer,\n rewardVault,\n needsUnderlyingToken ? args.underlyingToken : undefined,\n aggregator.name === Aggregators.Honey\n ? args.honeyNativeState?.collateralList\n : undefined,\n ];\n}\n\n/**\n * Creates the SWR fetcher that calls `aggregator.getQuote()` with\n * the parameters extracted from the query key tuple.\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 referrer,\n rewardVault,\n underlyingToken,\n honeyCollaterals,\n ]: IQueryKey) =>\n aggregator.getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account,\n aggregatorsFeeBps,\n publicClient,\n proxyAggregatorsThroughVercel,\n referrer,\n rewardVault,\n underlyingToken,\n honeyNativeState: {\n collateralList: honeyCollaterals ?? [],\n },\n });\n}\n\n/**\n * this hook is used internally to avoid caling the same hook and checks\n * on every useSingleAggregatorQuote call, when called inside useAggregatorsQuotes.\n *\n * @internal\n */\nexport function raw_useSingleAggregatorQuote(\n {\n feeBps,\n publicClient,\n account,\n proxyAggregatorsThroughVercel,\n activeAggregators,\n isMAEnabled,\n ...args\n }: IUseAggregatorsQuotesArgs & {\n account: Address | undefined;\n aggregator: BaseAggregator;\n feeBps: number | undefined;\n activeAggregators: string[] | undefined;\n isMAEnabled: boolean;\n publicClient: PublicClient | undefined;\n proxyAggregatorsThroughVercel: boolean | undefined;\n },\n options?: DefaultHookOptions,\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 return useSWR(\n getQueryKey({\n aggregator: args.aggregator,\n account,\n args,\n feeBps,\n options,\n activeAggregators,\n isMAEnabled,\n }),\n getQueryFn({\n aggregator: args.aggregator,\n proxyAggregatorsThroughVercel,\n publicClient,\n }),\n options?.opts,\n );\n}\n\n/**\n * Returns shared SWR options for aggregator quote polling, including\n * custom error retry logic that stops retrying on \"path not found\" and 403 errors.\n */\nexport function getAggregatorsSWROptions(\n options?: DefaultHookOptions,\n): SWRConfiguration {\n return {\n refreshInterval: POLLING.FAST, // every 10s\n errorRetryCount: 3,\n ...options?.opts,\n // biome-ignore lint/nursery/useMaxParams: the function is defined in the SWRConfiguration type\n onErrorRetry(err, key, config, revalidate, revalidateOpts) {\n options?.opts?.onErrorRetry?.(\n err,\n key,\n config,\n revalidate,\n revalidateOpts,\n );\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\n/**\n * Standalone hook for fetching a quote from a single aggregator.\n * Resolves wallet, fee, and feature flag context internally — use this\n * when you need a quote outside of the `useAggregatorsQuotes` multi-quote flow.\n */\nexport function useSingleAggregatorQuote(\n args: IUseAggregatorsQuotesArgs & { aggregator: BaseAggregator },\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\n const { data: feeBps } = useAggregatorsRouterFeeBps();\n\n if (args.aggregator.name !== Aggregators.Wrap) {\n const isWrapOrUnwrap =\n (isToken(args.tokenIn.address, \"BERA\") ||\n isToken(args.tokenIn.address, \"WBERA\")) &&\n (isToken(args.tokenOut.address, \"BERA\") ||\n isToken(args.tokenOut.address, \"WBERA\"));\n\n if (!isWrapOrUnwrap) {\n return null;\n }\n }\n\n const { config } = parseBaseArgs(args);\n\n const isMAEnabled = config.bex.aggregatorsRouter !== zeroAddress;\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 return raw_useSingleAggregatorQuote(\n {\n ...args,\n aggregator: args.aggregator,\n feeBps,\n activeAggregators,\n account,\n isMAEnabled,\n publicClient,\n proxyAggregatorsThroughVercel,\n },\n { ...options, opts: getAggregatorsSWROptions(options) },\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/global\";\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/InvalidArgumentError\";\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 { poolCreationHelperAbi as balancerPoolCreationHelperAbi } from \"@berachain/abis/bex/poolCreationHelper\";\n\nimport {\n GetDedupedSubgraphPools,\n type GetDedupedSubgraphPoolsQuery,\n type SubgraphPoolFragment,\n} from \"@berachain/graphql/dex/subgraph\";\n\nimport { getApolloClient } from \"../../actions/clients/getApolloClient\";\nimport { TransactionActionType } from \"../../enum/txnEnum\";\nimport type { Token, TokenWithAmount } from \"../../types/dex\";\nimport type { IContractWrite } from \"../../types/global\";\nimport { DEFAULT_METAMASK_GAS_LIMIT } from \"../../utils/constants\";\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: TokenWithAmount[];\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: TokenWithAmount[];\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: TokenWithAmount[];\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/dex\";\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/dex\";\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 { erc20Abi, formatUnits, type PublicClient } from \"viem\";\n\nimport {\n GetExploitedTokens,\n type GetExploitedTokensQuery,\n type GetExploitedTokensQueryVariables,\n} from \"@berachain/graphql/dex/subgraph\";\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport type { Token } from \"../../types/dex\";\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 { PoolCreationStep } from \"../../enum/dex\";\nimport type { TokenCurrentPriceMap, TokenWithAmount } from \"../../types/dex\";\nimport { wrapNativeTokens } from \"../../utils/tokenWrapping\";\nimport { type Oracle, OracleMode } from \"./useCreatePool\";\n\nconst DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT = 0.05; // 5%\n\nexport type LiquidityMismatchInfo = {\n title: string | null;\n message: string | null;\n suggestWeighted?: boolean;\n};\n\ninterface UseLiquidityMismatchParams {\n currentStep: PoolCreationStep;\n tokenPrices?: TokenCurrentPriceMap;\n isLoadingTokenPrices: boolean;\n tokens: TokenWithAmount[] | null;\n weights: bigint[] | null;\n weightsError: string | null;\n poolType: PoolType;\n liquidityMismatchTolerancePercent?: number;\n oracles: Oracle[];\n}\n\n/**\n * Hook for detecting liquidity mismatches.\n *\n * @param {PoolCreationStep} currentStep - The current step of the pool creation process.\n * @param {Record<string, number>} tokenPrices - The current token prices.\n * @param {boolean} isLoadingTokenPrices - Whether the token prices are still loading.\n * @param {Array<{ address: string, amount: number }>} tokens - The tokens in the pool, including their addresses and amounts.\n * @param {Record<string, number>} weights - The per-token weights in the pool we are creating.\n * @param {string | null} weightsError - An error message for the weights indicating that the weights are invalid.\n * @param {string} poolType - The type of pool being created.\n * @param {number} liquidityMismatchTolerancePercent - The tolerance for liquidity mismatches in percent.\n * @returns {Object} The liquidity mismatch info.\n */\nexport const useLiquidityMismatch = ({\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent = DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT,\n oracles,\n}: UseLiquidityMismatchParams): LiquidityMismatchInfo => {\n // NOTE: would be nice to use Maps/Records more in here, as the zipping/unzipping is cumbersome.\n // NOTE: if we pull in string literal for currentStep things would also be a bit clearer in here.\n const [liquidityMismatchInfo, setLiquidityMismatchInfo] =\n useState<LiquidityMismatchInfo>({ title: null, message: null });\n\n useEffect(() => {\n // If we are either using custom rate-providing oracles or have incorrect/loading token prices, we cant do validation.\n if (\n !tokenPrices ||\n isLoadingTokenPrices ||\n !tokens ||\n !weights ||\n weightsError ||\n tokens.some((token) => !token.address) ||\n oracles.some((oracle) => oracle.mode === OracleMode.Custom) // Oracles give prices on their own, we dont support that here yet.\n ) {\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Calculate some basic metrics we'll use to determine per-token contributions and model potential losses from arbitrage.\n let totalLiquidityUSD = 0;\n const tokenUSDAmounts: number[] = [];\n const numTokens = tokens.length;\n const wrappedTokens = wrapNativeTokens(tokens);\n const tokenUSDPrices = wrappedTokens.map((token) => {\n const tokenPriceUSD =\n tokenPrices[token.address.toLowerCase()]?.price ?? 0;\n if (!tokenPriceUSD || tokenPriceUSD === 0) {\n tokenUSDAmounts.push(0);\n return null;\n }\n const tokenAmountUSD = tokenPriceUSD * Number.parseFloat(token.amount);\n tokenUSDAmounts.push(tokenAmountUSD);\n totalLiquidityUSD += tokenAmountUSD;\n return tokenPriceUSD;\n });\n\n // Doesn't matter what step it is, if we have missing token prices for tokens we have selected, we cant issue a real warning.\n if (\n tokenUSDPrices.some((price) => price === null) ||\n tokenUSDPrices.length !== numTokens\n ) {\n setLiquidityMismatchInfo({\n title: \"Missing token price data\",\n message: `One or more token(s) do not have valid market price data. Please verify that token market prices align with the pool\n weightings and your initial liquidity amounts.`,\n });\n return;\n }\n\n // Step 1 - During token selection we check for a deviation in the quote prices of the tokens selected (for stable pools).\n if (\n currentStep === PoolCreationStep.SELECT_TOKENS &&\n poolType === PoolType.ComposableStable\n ) {\n const normalizedUSDPrices = tokenUSDPrices.map(\n (priceUSD) => priceUSD! / tokenUSDPrices[0]!, // always normalize on the first token's price\n );\n const maxDifference =\n Math.max(...normalizedUSDPrices) - Math.min(...normalizedUSDPrices);\n\n if (maxDifference > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n title: \"Selected tokens have a significant price deviation\",\n message: \"Did you mean to create a Weighted pool instead?\",\n suggestWeighted: true,\n });\n } else {\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n\n return;\n }\n\n // Validation During Liquidity Input and onwards.\n if (\n totalLiquidityUSD === 0 ||\n tokenUSDAmounts.some((value) => value === 0)\n ) {\n // User has not yet entered fully their liquidity values, so return early.\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Simulate arbitrage for the pool to determine potential losses from arbitrageurs.\n // NOTE: we assume shortfalls and excesses are losses, but in reality the actual losses would be more complex to realise.\n // Balancer does this similarily https://github.com/balancer/frontend-v2/blob/8563b8d33b6bff266148bd48d7ebc89f921374f4/src/components/cards/CreatePool/InitialLiquidity.vue#L75\n let totalLossUSD = 0;\n if (poolType === PoolType.ComposableStable) {\n const expectedPerTokenLiquidityUSD = totalLiquidityUSD / numTokens;\n tokenUSDAmounts.forEach((value) => {\n totalLossUSD += Math.abs(expectedPerTokenLiquidityUSD - value);\n });\n } else if (poolType === PoolType.Weighted) {\n tokenUSDAmounts.forEach((value, index) => {\n const weightProportion = Number(weights[index]) / 1e18;\n const expectedValueUSD = totalLiquidityUSD * weightProportion;\n totalLossUSD += Math.abs(expectedValueUSD - value);\n });\n }\n\n // We'll show a total loss if it's 90% or more\n const isTotalLoss = totalLossUSD >= totalLiquidityUSD * 0.9;\n totalLossUSD = Math.min(totalLossUSD, totalLiquidityUSD);\n const totalLossPercentage = totalLossUSD / totalLiquidityUSD;\n\n if (totalLossPercentage > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n // If it's a total loss we dont display a percentage\n title: isTotalLoss\n ? \"You could lose all of your initial liquidity\"\n : `You could lose $${totalLossUSD.toFixed(2)} (~${(\n totalLossPercentage * 100\n ).toFixed(2)}%)`,\n message: `Based on the market token prices, the value of tokens does not align with the specified pool weights. \n This discrepancy could expose you to potential losses from arbitrageurs. ${\n poolType === PoolType.ComposableStable\n ? \"Did you mean to create a Weighted pool instead?\"\n : \"\"\n }`,\n suggestWeighted: poolType === PoolType.ComposableStable,\n });\n } else {\n // All good bb bb\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n }, [\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent,\n oracles,\n ]);\n return liquidityMismatchInfo;\n};\n","import { type Address, formatEther, isAddressEqual } from \"viem\";\n\nimport type { MinimalPoolFragment } from \"@berachain/graphql/dex/api\";\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport type { IUserPosition } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\nimport { useRewardVaultBalanceFromStakingToken } from \"../pol/useRewardVaultBalanceFromStakingToken\";\nimport { usePollBalance } from \"../tokens/usePollBalance\";\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.balance.formatted) * 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?.balance.formatted ?? \"0\").times(tokenRatio)\n : BigNumber(0);\n const price = Number(token.balanceUSD) / Number(token.balance);\n\n return {\n ...token,\n\n balance: {\n raw: userBalance?.isGreaterThan(0)\n ? userBalance\n .times(10 ** token.decimals!)\n .toFixed(0)\n .toString()\n : \"0\",\n formatted: userBalance.toString(),\n },\n price,\n usdValue:\n Number.isNaN(price) || !userBalance\n ? undefined\n : Number.parseFloat(userBalance.toString()) * price,\n };\n }),\n stakedBalance: userVaultTokenBalance?.address\n ? {\n ...userVaultTokenBalance,\n balance: {\n raw: userVaultTokenBalance.balance.toString(),\n // Pools always use the 18 decimals\n formatted: formatEther(userVaultTokenBalance.balance),\n },\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 { rewardVaultAbi } from \"@berachain/abis/pol/rewards/rewardVault\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { rewardVaultFactoryAbi } from \"@berachain/abis/pol/rewards/rewardVaultFactory\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { BalanceToken } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} 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 chainId,\n balance: data\n ? {\n raw: data.toString(),\n formatted: formattedBalance ?? \"0\",\n }\n : { raw: \"0\", formatted: \"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 { defaultChainId } from \"@berachain/config/internal\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getTokenInformation } from \"../../actions/tokens/getTokenInformation\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { Token } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 function 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, chainId = defaultChainId]) => {\n if (isToken(address, \"BERA\")) {\n return {\n address: zeroAddress,\n decimals: beraToken.decimals,\n name: beraToken.name,\n symbol: beraToken.symbol,\n chainId,\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 chainId,\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 { parseUnits, zeroAddress } from \"viem\";\n\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport { BeraError } from \"../../errors/BeraError\";\nimport type { AllowanceQueryItem, AllowanceToken } from \"../../types/dex\";\nimport { isToken } from \"../../utils/tokens\";\nimport { usePollAllowances } from \"../tokens/usePollAllowances\";\n\ntype NeedsApprovalToken = AllowanceToken & {\n maxAmountIn: bigint;\n};\n\nfunction calculateMaxAmountIn({\n amount,\n decimals,\n slippage,\n}: {\n amount: bigint;\n decimals: number;\n slippage: number | undefined;\n}) {\n const slippageInWei = parseUnits((slippage ?? 0).toString(), decimals);\n return amount + (amount * slippageInWei) / BigInt(100 * 10 ** decimals);\n}\n\nexport function useMultipleTokenApprovalsWithSlippage(\n tokenInput: AllowanceQueryItem[],\n options?: {\n slippage?: number;\n },\n) {\n const { slippage } = options ?? {};\n\n const items = useMemo(\n () =>\n tokenInput\n .filter((token) => token.token.address !== zeroAddress)\n .filter((token) => BigNumber(token.amount.formatted).gt(0)),\n [tokenInput],\n );\n\n const {\n data: allowances,\n refresh,\n isLoading,\n } = usePollAllowances({\n items,\n });\n\n const needsApproval = useMemo<NeedsApprovalToken[]>(\n () =>\n allowances\n ?.map<NeedsApprovalToken | undefined>((allowance) => {\n const item = items.find((item) =>\n isToken(item.token.address, allowance.token),\n );\n\n if (!item) {\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 items,\n },\n });\n }\n\n const maxAmountIn = calculateMaxAmountIn({\n decimals: item.token.decimals,\n amount: BigInt(item.amount.raw),\n slippage,\n });\n\n if (BigNumber(allowance.allowance.raw).lt(maxAmountIn)) {\n return {\n ...item,\n needsApproval: true,\n maxAmountIn,\n allowance: {\n raw: allowance.allowance.raw,\n formatted: allowance.allowance.formatted,\n },\n };\n }\n\n return undefined;\n })\n .filter((token) => token !== undefined) ?? [],\n [allowances, slippage, items],\n );\n\n return {\n needsApproval,\n refresh,\n isLoading,\n };\n}\n","import useSWR from \"swr\";\n\nimport { useBeraWallet, useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { getAllowances } from \"../../actions/tokens/getAllowances\";\nimport { POLLING } from \"../../enum/polling\";\nimport type { AllowanceQueryItem, AllowanceToken } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\n\nexport type UsePollAllowancesArgs = {\n items: AllowanceQueryItem[];\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 * @param chainId the chain ID to check allowances on\n */\nexport function usePollAllowances(\n args: UsePollAllowancesArgs,\n options?: DefaultHookOptions,\n): UsePollAllowancesResponse {\n const config = useConfig();\n\n const { address: account } = useBeraWallet();\n const QUERY_KEY =\n config && account && args?.items\n ? ([\"usePollAllowances\", account, args?.items] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, account, items]) => {\n return getAllowances({\n items,\n account,\n config,\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 \"../tokens/useMultipleTokenInformation\";\nimport { useTokenCurrentPrices } from \"../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 { defaultChainId } from \"@berachain/config/internal\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getTokenInformation } from \"../../actions/tokens/getTokenInformation\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { Token } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\n\nexport type UseMultipleTokenInformationResponse = DefaultHookReturnType<\n Token[]\n>;\n\nexport type useMultipleTokenInformationArgs = {\n addresses: string[] | readonly string[] | undefined;\n chainId?: number;\n};\nexport function useMultipleTokenInformation(\n args: useMultipleTokenInformationArgs,\n options?: DefaultHookOptions,\n): UseMultipleTokenInformationResponse {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n publicClient && args.addresses\n ? ([\n \"useMultipleTokenInformation\",\n args.addresses,\n args.chainId ?? defaultChainId,\n ] as const)\n : null;\n\n const swrResponse = useSWRImmutable<Token[], unknown, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([, addresses, chainId]) => {\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 chainId,\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 { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport { type Address, isAddress, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { getTokenCurrentPrices } from \"../../actions/prices/getTokenCurrentPrices\";\nimport { POLLING } from \"../../enum/polling\";\nimport type { TokenCurrentPriceMap, TokenWithPrice } from \"../../types/dex\";\nimport type { DefaultHookOptions } from \"../../types/global\";\nimport { isToken } from \"../../utils/tokens\";\nimport { useTokens } from \"./useTokens\";\n\n/**\n * @deprecated use useTokenPrices instead that supports multichain tokens\n */\nexport function useTokenCurrentPrices(\n {\n addressIn,\n }: {\n addressIn?: string[] | readonly string[];\n } = {},\n options: DefaultHookOptions = {\n opts: {\n refreshInterval: POLLING.NORMAL,\n revalidateOnFocus: true,\n },\n },\n) {\n const { tokenList, ensoTokens } = useTokens();\n\n /**\n * Berachain or Bepolia Tokens. All tokens from other chains are excluded since API doesn't price them.\n */\n const beraAddresses = useMemo<Address[]>(() => {\n const addresses: Address[] = [];\n\n if (addressIn) {\n addresses.push(\n ...(addressIn.filter((a): a is Address => isAddress(a)) as Address[]),\n );\n }\n return addresses.map((a) => a.toLowerCase() as Address);\n }, [tokenList]);\n\n const hasAddressesNotInTokenList = useMemo(() => {\n const tokenSet = new Set(\n tokenList?.map((token) => token.address.toLowerCase() as Address),\n );\n // Native BERA (zero address) is priced via WBERA in getTokenCurrentPrices.\n // Treat zero address as \"known\" whenever WBERA exists in token list.\n if (tokenList.some((token) => isToken(token, \"WBERA\"))) {\n tokenSet.add(zeroAddress);\n }\n\n return beraAddresses?.some((a) => !tokenSet.has(a));\n }, [beraAddresses, tokenList]);\n\n /**\n * If no addressIn is provided, use default token list\n * If all addressIn are in the token list, use default token list\n * If some addressIn are not in the token list, use addressIn\n */\n const addresses = hasAddressesNotInTokenList\n ? beraAddresses\n : tokenList.map((token) => token.address);\n\n const QUERY_KEY =\n addresses && (options.opts?.isEnabled ?? true)\n ? ([\n \"useTokenCurrentPrices\",\n addresses.map((a) => a.toLowerCase() as Address),\n ] as const)\n : null;\n\n const apiResponse = useSWR(\n QUERY_KEY,\n async ([, addresses]) => {\n // this only works for Berachain tokens\n return getTokenCurrentPrices({ addressIn: addresses });\n },\n options.opts,\n );\n\n const ensoMatchingPrices = useMemo<TokenCurrentPriceMap>(() => {\n if (!ensoTokens) return {};\n\n const ensoPricesMap = new Map<number, Map<Address, TokenWithPrice>>([\n [defaultChainId, new Map()],\n ]);\n\n for (const token of ensoTokens) {\n if (token.price === undefined || token.chainId !== defaultChainId)\n continue;\n\n ensoPricesMap\n .get(defaultChainId)\n ?.set(token.address.toLowerCase() as Address, {\n ...token,\n price: token.price,\n chainId: defaultChainId,\n });\n }\n\n return Object.fromEntries(\n addresses.map((address) => {\n const price = ensoPricesMap.get(defaultChainId)?.get(address)?.price;\n\n if (!price) return [null, null];\n\n return [\n address.toLowerCase() as Address,\n {\n price,\n chainId: defaultChainId,\n updatedAt: Date.now(),\n },\n ];\n }),\n );\n }, [ensoTokens]);\n\n const data = useMemo(\n () => ({\n ...ensoMatchingPrices,\n // in this deprecated hook, we let api override enso prices, since there's no multichain support\n ...apiResponse.data,\n }),\n [ensoMatchingPrices, apiResponse.data],\n );\n\n return {\n ...apiResponse,\n data,\n };\n}\n","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\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 { vaultAbi as balancerVaultAbi } from \"@berachain/abis/bex/vault\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { DefaultHookOptions } from \"../../types/global\";\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 type { Hex } from \"viem\";\n\nimport { useApiPool } from \"./useApiPool\";\nimport { useOnChainPoolData } from \"./useOnChainPoolData\";\n\nexport function usePool({ poolId }: { poolId: Hex }) {\n const balancerApiPool = useApiPool({ poolId });\n\n const {\n data: onChainPool,\n isLoading: isOnChainPoolLoading,\n refresh: refreshOnChainPool,\n error: onChainPoolError,\n } = useOnChainPoolData(poolId);\n\n return {\n data: [undefined, balancerApiPool.data, onChainPool] as const,\n isLoading: balancerApiPool.isLoading || isOnChainPoolLoading,\n isError: balancerApiPool.error || onChainPoolError,\n refresh: () => {\n balancerApiPool.refresh();\n\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/polling\";\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} 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/global\";\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","import { useMemo } from \"react\";\n\nimport type { Token } from \"../../types/dex\";\nimport { computePriceImpact } from \"../../utils/math\";\nimport { useTokenPrices } from \"../tokens/useTokenPrices\";\n\nexport function usePriceImpact({\n tokenIn,\n tokenOut,\n formattedAmountIn,\n formattedAmountOut,\n}: {\n tokenIn: Token | undefined;\n tokenOut: Token | undefined;\n formattedAmountIn: string | undefined;\n formattedAmountOut: string | undefined;\n}) {\n const { getTokenPrice, isLoading } = useTokenPrices({\n tokens: tokenIn && tokenOut ? [tokenIn, tokenOut] : undefined,\n });\n const priceImpact = useMemo(() => {\n if (!tokenIn || !tokenOut || !formattedAmountIn || !formattedAmountOut)\n return undefined;\n\n const tokenInPrice = getTokenPrice(tokenIn);\n const tokenOutPrice = getTokenPrice(tokenOut);\n\n if (!tokenInPrice || !tokenOutPrice) return null;\n return computePriceImpact(\n tokenInPrice.toString(),\n tokenOutPrice.toString(),\n formattedAmountIn,\n formattedAmountOut,\n );\n }, [tokenIn, tokenOut, formattedAmountIn, formattedAmountOut]);\n return {\n data: priceImpact,\n isLoading,\n };\n}\n","import { useCallback, useMemo } from \"react\";\nimport type { Address } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { POLLING } from \"../../enum/polling\";\nimport type { Token } from \"../../types/dex\";\nimport type { DefaultHookOptions } from \"../../types/global\";\nimport { useTokenCurrentPrices } from \"./useTokenCurrentPrices\";\nimport { useTokens } from \"./useTokens\";\n\nexport type TokenPriceInput = Pick<Token, \"address\" | \"chainId\">;\n\nexport type TokenPriceOutput = TokenPriceInput & {\n price: number;\n};\nexport type TokenPriceMap = Record<number, Record<Address, number>>;\n\nexport function useTokenPrices(\n {\n tokens,\n }: {\n tokens?: TokenPriceInput[];\n } = {},\n options: DefaultHookOptions = {\n opts: {\n refreshInterval: POLLING.NORMAL,\n revalidateOnFocus: true,\n },\n },\n) {\n const { ensoTokens } = useTokens();\n\n const apiResponse = useTokenCurrentPrices(\n {\n addressIn: tokens\n ?.filter((token) => token.chainId === defaultChainId)\n .map((token) => token.address),\n },\n options,\n );\n\n const data = useMemo(() => {\n const prices: TokenPriceOutput[] = [];\n\n if (!tokens) {\n return [];\n }\n\n const tokenMap = new Map<number, Map<Address, TokenPriceInput>>();\n\n for (const token of tokens) {\n const chainId = token.chainId ?? defaultChainId;\n if (!tokenMap.has(chainId)) {\n tokenMap.set(chainId, new Map<Address, TokenPriceInput>());\n }\n tokenMap.get(chainId)?.set(token.address.toLowerCase() as Address, token);\n }\n\n if (apiResponse.data) {\n for (const [address, price] of Object.entries(apiResponse.data)) {\n if (\n price &&\n tokenMap\n .get(price.chainId ?? defaultChainId)\n ?.get(address.toLowerCase() as Address) &&\n price.price !== undefined\n ) {\n const token = tokenMap\n .get(price.chainId ?? defaultChainId)\n ?.get(address.toLowerCase() as Address);\n\n if (!token) {\n continue;\n }\n\n prices.push({\n ...token,\n chainId: price.chainId,\n price: price.price,\n });\n }\n }\n }\n\n if (ensoTokens) {\n for (const tk of ensoTokens) {\n if (tk.price !== undefined && tk.chainId !== undefined) {\n prices.push({\n ...tk,\n chainId: tk.chainId,\n price: tk.price,\n });\n }\n }\n }\n\n return prices;\n }, [apiResponse.data, ensoTokens, tokens]);\n\n const priceMap = useMemo<TokenPriceMap>(() => {\n const map: TokenPriceMap = {};\n for (const item of data) {\n const chainId = item.chainId ?? defaultChainId;\n if (!map[chainId]) {\n map[chainId] = {} as Record<Address, number>;\n }\n map[chainId][item.address.toLowerCase() as Address] = item.price;\n }\n\n return map;\n }, [data]);\n\n const getTokenPrice = useCallback(\n (token?: TokenPriceInput) => {\n if (!token) return undefined;\n const price =\n priceMap[token.chainId ?? defaultChainId]?.[\n token.address?.toLowerCase() as Address\n ] ?? undefined;\n\n return price;\n },\n [priceMap],\n );\n\n return {\n isLoading: apiResponse.isLoading,\n data,\n priceMap,\n getTokenPrice,\n };\n}\n","\"use client\";\n\nimport useSWR from \"swr\";\nimport type { Address, Hex } from \"viem\";\nimport { parseUnits } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport {\n useBeraWagmi,\n useBeraWallet,\n usePublicClient,\n} from \"@berachain/wagmi/hooks\";\n\nimport { getEnsoClient } from \"../../actions/clients/getEnsoClient\";\nimport { getBendDemultiplyBundle } from \"../../actions/enso/getBendDemultiplyBundle\";\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { Token } from \"../../types/dex\";\nimport type { BendDemultiplyBundleResponse } from \"../../types/enso\";\nimport type { DefaultHookOptions } from \"../../types/global\";\nimport { useEnsoWalletV2Address } from \"./useEnsoWalletV2Address\";\nimport { useIsBendAuthorized } from \"./useIsBendAuthorized\";\n\nexport type UseBendDemultiply = {\n collateralToken?: Token;\n loanToken?: Token;\n marketId?: Hex;\n primaryAddress?: Address;\n repayAmount?: string;\n slippage?: number;\n chainId?: number;\n collateralPriceInLoanAsset?: string;\n currentCollateral?: string;\n currentDebt?: string;\n};\n\nexport function useBendDemultiply(\n {\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n repayAmount,\n slippage,\n chainId,\n collateralPriceInLoanAsset,\n currentCollateral,\n currentDebt,\n }: UseBendDemultiply,\n options?: DefaultHookOptions,\n) {\n const { address: fromAddress } = useBeraWallet();\n const { account: { chainId: accountChainId } = {} } = useBeraWagmi();\n\n const chainIdToUse = chainId ?? accountChainId ?? defaultChainId;\n const publicClient = usePublicClient({ chainId: chainIdToUse });\n const { data: ensoWalletV2Address } = useEnsoWalletV2Address({\n chainId: chainIdToUse,\n });\n const { data: isAuthorized } = useIsBendAuthorized({\n chainId: chainIdToUse,\n primaryAddress,\n ensoWalletV2Address,\n });\n\n const QUERY_KEY =\n collateralToken &&\n loanToken &&\n marketId &&\n primaryAddress &&\n repayAmount &&\n ensoWalletV2Address &&\n isAuthorized !== undefined &&\n collateralToken.address !== loanToken.address &&\n Number(repayAmount) > 0 &&\n slippage !== undefined &&\n collateralPriceInLoanAsset !== undefined &&\n currentCollateral &&\n currentDebt &&\n Number(currentDebt) > 0 &&\n fromAddress &&\n (options?.opts?.isEnabled ?? true)\n ? ([\n \"useBendDemultiply\",\n fromAddress,\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n chainIdToUse,\n repayAmount,\n slippage,\n collateralPriceInLoanAsset,\n currentCollateral,\n currentDebt,\n ensoWalletV2Address,\n isAuthorized,\n ] as const)\n : null;\n\n return useSWR<BendDemultiplyBundleResponse, unknown, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([\n _,\n fromAddress,\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n chainId,\n repayAmount,\n slippage,\n collateralPriceInLoanAsset,\n currentCollateral,\n currentDebt,\n ensoWalletV2Address,\n isAuthorized,\n ]) => {\n assertPublicClient(publicClient);\n\n const rawRepayAmount = parseUnits(\n repayAmount,\n loanToken.decimals,\n ).toString();\n const rawCurrentCollateral = parseUnits(\n currentCollateral,\n collateralToken.decimals,\n ).toString();\n const rawCurrentDebt = parseUnits(\n currentDebt,\n loanToken.decimals,\n ).toString();\n\n return getBendDemultiplyBundle({\n fromAddress,\n repayAmount: rawRepayAmount,\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n chainId,\n ensoClient: getEnsoClient(),\n slippage,\n publicClient,\n collateralPriceInLoanAsset,\n currentCollateral: rawCurrentCollateral,\n currentDebt: rawCurrentDebt,\n ensoWalletV2Address,\n isAuthorized,\n });\n },\n {\n ...options?.opts,\n refreshInterval: POLLING.NORMAL,\n },\n );\n}\n","import type { BundleAction, EnsoClient } from \"@ensofinance/sdk\";\nimport { type Address, formatUnits, type Hex, type PublicClient } from \"viem\";\n\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport { assertAddress, assertPositive } from \"../../errors/assert\";\nimport { InvalidArgumentError } from \"../../errors/InvalidArgumentError\";\nimport type { Token } from \"../../types/dex\";\nimport type { BendDemultiplyBundleResponse } from \"../../types/enso\";\nimport { assembleBendFlashloanTransactions } from \"./flashloan\";\nimport { computeSwapOutputRatio, toEnsoAddress } from \"./util\";\n\n// full-repay cleanup needs a non-trivial leftover debt balance after `repay`.\n// without this proportional buffer, enso may fail to route near-zero dust.\nconst FULL_REPAY_CLEANUP_BUFFER_BPS = 25n; // 0.25%\nconst BPS_DIVISOR = 10_000n;\n\nexport interface GetBendDemultiplyBundleArgs {\n fromAddress: Address;\n repayAmount: string;\n collateralToken: Token;\n loanToken: Token;\n marketId: Hex;\n primaryAddress: Address;\n chainId: number;\n ensoClient: EnsoClient;\n slippage: number;\n publicClient: PublicClient;\n collateralPriceInLoanAsset: string;\n currentCollateral: string;\n currentDebt: string;\n ensoWalletV2Address: Address;\n isAuthorized: boolean;\n}\n\n/**\n * Calculate the collateral amount to flashloan and sell in order to repay\n * the target debt amount.\n *\n * collateralNeeded = repayAmount / (collateralPrice * swapOutputRatio)\n *\n * This is the inverse of the multiply direction: we need enough collateral\n * that, after swapping to the loan token with slippage, covers the repay\n * amount. The result is clamped to `currentCollateral` (can't withdraw\n * more than exists in the position).\n */\nexport function calculateDemultiplyCollateralAmount({\n repayAmount,\n collateralPriceInLoanAsset,\n collateralToken,\n loanToken,\n slippage,\n currentCollateral,\n}: {\n repayAmount: string;\n collateralPriceInLoanAsset: string;\n collateralToken: Token;\n loanToken: Token;\n slippage: number;\n currentCollateral: string;\n}): string {\n const swapOutputRatio = computeSwapOutputRatio(slippage);\n const collateralPrice = new BigNumber(collateralPriceInLoanAsset);\n\n if (collateralPrice.lte(0)) {\n throw new InvalidArgumentError({\n property: \"collateralPriceInLoanAsset\",\n value: collateralPriceInLoanAsset,\n expected: \"a value greater than zero\",\n });\n }\n\n const loanDecimalsMul = new BigNumber(10).pow(loanToken.decimals);\n const collateralDecimalsMul = new BigNumber(10).pow(collateralToken.decimals);\n\n const repayAmountHuman = new BigNumber(repayAmount).dividedBy(\n loanDecimalsMul,\n );\n\n const flashloanCollateralHuman = repayAmountHuman\n .dividedBy(collateralPrice)\n .dividedBy(swapOutputRatio);\n\n const flashloanCollateralRaw = flashloanCollateralHuman\n .multipliedBy(collateralDecimalsMul)\n .integerValue(BigNumber.ROUND_UP);\n\n if (flashloanCollateralRaw.lte(0)) return \"0\";\n\n return BigNumber.minimum(\n flashloanCollateralRaw,\n new BigNumber(currentCollateral),\n ).toFixed(0);\n}\n\n/**\n * Estimate the position change after executing a demultiply.\n *\n * Unlike multiply, these values represent *reductions* from the current\n * position — the caller subtracts them to get the new totals.\n * Returns human-readable (formatted) values for display.\n */\nexport function getPositionEstimate({\n repayAmount,\n collateralToWithdraw,\n collateralToken,\n loanToken,\n}: {\n repayAmount: string;\n collateralToWithdraw: string;\n collateralToken: Token;\n loanToken: Token;\n}): BendDemultiplyBundleResponse[\"positionEstimate\"] {\n return {\n finalCollateral: formatUnits(\n BigInt(collateralToWithdraw),\n collateralToken.decimals,\n ),\n totalBorrow: formatUnits(BigInt(repayAmount), loanToken.decimals),\n };\n}\n\nexport async function getBendDemultiplyBundle({\n fromAddress,\n repayAmount,\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n chainId,\n ensoClient,\n slippage,\n publicClient,\n collateralPriceInLoanAsset,\n currentCollateral,\n currentDebt,\n ensoWalletV2Address,\n isAuthorized,\n}: GetBendDemultiplyBundleArgs): Promise<BendDemultiplyBundleResponse> {\n assertAddress(fromAddress, \"fromAddress\");\n assertPositive(repayAmount, \"repayAmount\");\n assertPositive(currentDebt, \"currentDebt\");\n\n const rawRepayAmount = BigInt(repayAmount);\n const rawCurrentDebt = BigInt(currentDebt);\n const isFullRepayment = rawRepayAmount >= rawCurrentDebt;\n\n const collateralAddress = toEnsoAddress(collateralToken.address);\n const loanAddress = toEnsoAddress(loanToken.address);\n\n // proportional extra debt amount (in raw units) reserved for full-repay cleanup.\n const rawCleanupDebtAmountFromBps =\n (rawRepayAmount * FULL_REPAY_CLEANUP_BUFFER_BPS + (BPS_DIVISOR - 1n)) /\n BPS_DIVISOR;\n const rawFullRepaymentCleanupDebtAmount = isFullRepayment\n ? rawCleanupDebtAmountFromBps\n : 0n;\n // on full repay, quote flashloan collateral against repay + cleanup buffer.\n // this intentionally creates remaining debt token in the callback so it can\n // be swapped back to collateral and re-deposited.\n const rawTargetRepayForFlashloanQuote = (\n rawRepayAmount + rawFullRepaymentCleanupDebtAmount\n ).toString();\n\n const collateralToWithdraw = calculateDemultiplyCollateralAmount({\n repayAmount: rawTargetRepayForFlashloanQuote,\n collateralPriceInLoanAsset,\n collateralToken,\n loanToken,\n slippage,\n currentCollateral,\n });\n const isFlashloanCollateralClamped =\n BigInt(collateralToWithdraw) >= BigInt(currentCollateral);\n // if flashloan collateral is clamped by current collateral, skip cleanup to\n // avoid adding extra callback steps when there is no safe collateral headroom.\n const shouldRunFullRepaymentCleanup =\n isFullRepayment &&\n rawFullRepaymentCleanupDebtAmount > 0n &&\n !isFlashloanCollateralClamped;\n\n if (BigInt(collateralToWithdraw) <= 0n) {\n throw new InvalidArgumentError({\n property: \"collateralToWithdraw\",\n value: collateralToWithdraw,\n expected: \"positive amount\",\n });\n }\n\n const baseCallbackActions = [\n // [0] Swap flashloaned collateral into loan tokens\n {\n protocol: \"enso\",\n action: \"route\",\n args: {\n tokenIn: collateralAddress,\n tokenOut: loanAddress,\n amountIn: collateralToWithdraw,\n slippage: slippage * 100,\n },\n },\n // [1] Repay debt using the swapped loan tokens\n {\n protocol: \"bend\",\n action: \"repay\",\n args: {\n primaryAddress,\n positionId: marketId,\n tokenIn: loanAddress,\n amountIn: { useOutputOfCallAt: 0 },\n onBehalfOf: fromAddress,\n },\n },\n ];\n\n // On full repayment: swap leftover debt-token dust back to collateral and\n // re-deposit it, so dust isn't left in the user's wallet.\n // Cleanup indices are computed dynamically from baseCallbackActions length.\n const cleanupStartIdx = baseCallbackActions.length;\n const fullRepaymentCleanupActions = shouldRunFullRepaymentCleanup\n ? [\n // Read remaining debt token balance after repay\n {\n protocol: \"enso\",\n action: \"balance\",\n args: {\n token: loanAddress,\n },\n },\n // Swap remaining debt tokens back to collateral\n {\n protocol: \"enso\",\n action: \"route\",\n args: {\n tokenIn: loanAddress,\n tokenOut: collateralAddress,\n amountIn: {\n useOutputOfCallAt: cleanupStartIdx,\n },\n slippage: slippage * 100,\n },\n },\n // Re-deposit recovered collateral into Bend\n {\n protocol: \"bend\",\n action: \"deposit\",\n args: {\n primaryAddress,\n positionId: marketId,\n tokenIn: collateralAddress,\n amountIn: {\n useOutputOfCallAt: cleanupStartIdx + 1,\n },\n onBehalfOf: fromAddress,\n },\n },\n ]\n : [];\n\n const callbackActions = [\n ...baseCallbackActions,\n ...fullRepaymentCleanupActions,\n // Final action: withdraw collateral to repay the flashloan\n {\n protocol: \"bend\",\n action: \"withdraw\",\n args: {\n primaryAddress,\n positionId: marketId,\n tokenOut: collateralAddress,\n amountOut: collateralToWithdraw,\n onBehalfOf: fromAddress,\n },\n },\n ];\n\n const flashloanActions = [\n {\n protocol: \"bend\",\n action: \"flashloan\",\n args: {\n flashloanToken: collateralAddress,\n flashloanAmount: collateralToWithdraw,\n tokenOut: loanAddress,\n callback: callbackActions,\n },\n },\n ];\n\n // @ts-expect-error Enso SDK BundleAction typing does not include Bend flashloan action shape yet.\n const bundleActions: BundleAction[] = flashloanActions;\n\n const bundle = await ensoClient.getBundleData(\n {\n fromAddress,\n receiver: fromAddress,\n spender: fromAddress,\n chainId,\n routingStrategy: \"ensowallet-v2\",\n },\n bundleActions,\n );\n\n const { transactions } = await assembleBendFlashloanTransactions({\n fromAddress,\n amountIn: \"0\",\n tokenIn: collateralToken,\n primaryAddress,\n bundle,\n publicClient,\n ensoWalletV2Address,\n isAuthorized,\n });\n\n return {\n bundle,\n transactions,\n positionEstimate: getPositionEstimate({\n repayAmount,\n collateralToWithdraw,\n collateralToken,\n loanToken,\n }),\n };\n}\n","import type { BundleData } from \"@ensofinance/sdk\";\nimport {\n type Address,\n encodeFunctionData,\n getAddress,\n type PublicClient,\n} from \"viem\";\n\nimport { morphoAbi } from \"@berachain/abis/bend/morpho\";\n\nimport { ensoWalletV2FactoryAbi } from \"../../abi/enso/ensoWalletV2Factory\";\nimport { assertDefined } from \"../../errors/assert\";\nimport type { AllowanceQueryItem, MinimalERC20 } from \"../../types/dex\";\nimport type { GetZapTransactions, Quantity } from \"../../types/enso\";\nimport { parseBaseArgs } from \"../../utils/parseBaseArgs\";\nimport { getEnsoWalletTransactionsWithApproval } from \"./util\";\n\nexport async function getEnsoWalletV2Address({\n publicClient,\n ensoWalletV2Factory,\n accountAddress,\n}: {\n publicClient: PublicClient;\n ensoWalletV2Factory: Address;\n accountAddress: Address;\n}): Promise<Address> {\n return publicClient.readContract({\n address: ensoWalletV2Factory,\n abi: ensoWalletV2FactoryAbi,\n functionName: \"getAddress\",\n args: [accountAddress],\n }) as Promise<Address>;\n}\n\nexport async function getIsBendAuthorized({\n publicClient,\n primaryAddress,\n accountAddress,\n ensoWalletV2Address,\n}: {\n publicClient: PublicClient;\n primaryAddress: Address;\n accountAddress: Address;\n ensoWalletV2Address: Address;\n}): Promise<boolean> {\n return publicClient.readContract({\n address: primaryAddress,\n abi: morphoAbi,\n functionName: \"isAuthorized\",\n args: [accountAddress, ensoWalletV2Address],\n }) as Promise<boolean>;\n}\n\n/**\n * Assemble the final transaction list for a Bend flashloan bundle.\n *\n * Handles:\n * 1. ERC-20 approval for the Enso wallet (if tokenIn is not native and\n * allowance is insufficient)\n * 2. Morpho setAuthorization transaction (if not yet authorized)\n * 3. The bundle execution transaction itself\n *\n * @returns `{ transactions, approvals, ensoWalletFlashloanAdapter }`\n */\nexport async function assembleBendFlashloanTransactions({\n fromAddress,\n amountIn,\n tokenIn,\n primaryAddress,\n bundle,\n publicClient,\n ensoWalletV2Address,\n isAuthorized,\n}: {\n fromAddress: Address;\n amountIn: Quantity;\n tokenIn: MinimalERC20;\n primaryAddress: Address;\n bundle: BundleData;\n publicClient: PublicClient;\n ensoWalletV2Address: Address;\n isAuthorized: boolean;\n}): Promise<{\n transactions: GetZapTransactions;\n approvals: AllowanceQueryItem[];\n ensoWalletFlashloanAdapter: Address;\n}> {\n const { config } = parseBaseArgs({});\n const { walletFlashloanAdapter: ensoWalletFlashloanAdapter } = config.enso;\n assertDefined(\n ensoWalletFlashloanAdapter,\n \"config.enso.walletFlashloanAdapter\",\n );\n\n const { transactions: ensoTransactions, approval } =\n await getEnsoWalletTransactionsWithApproval({\n fromAddress,\n amountIn,\n tokenIn,\n bundle,\n publicClient,\n });\n\n const transactions: GetZapTransactions = [];\n\n if (!isAuthorized) {\n transactions.push({\n to: primaryAddress,\n data: encodeFunctionData({\n abi: morphoAbi,\n functionName: \"setAuthorization\",\n args: [ensoWalletV2Address, true],\n }),\n value: 0n,\n });\n }\n\n transactions.push(...ensoTransactions);\n\n const approvals: AllowanceQueryItem[] = approval ? [approval] : [];\n\n return {\n transactions,\n approvals,\n ensoWalletFlashloanAdapter: getAddress(ensoWalletFlashloanAdapter),\n };\n}\n","import {\n type Address,\n encodeFunctionData,\n erc20Abi,\n ethAddress,\n formatUnits,\n getAddress,\n zeroAddress,\n} from \"viem\";\n\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport { InvalidArgumentError } from \"../../errors/InvalidArgumentError\";\nimport type { AllowanceQueryItem, Token } from \"../../types/dex\";\nimport type {\n GetEnsoWalletTransactionsWithApprovalArgs,\n GetZapTransactions,\n GetZapTransactionsArgs,\n} from \"../../types/enso\";\n\n/**\n * Convert a token address to Enso-compatible format.\n * Enso uses the special `ethAddress` sentinel for native tokens instead of `zeroAddress`.\n */\nexport function toEnsoAddress(address: Address): Address {\n return address === zeroAddress ? ethAddress : address;\n}\n\nfunction toBigIntOrUndefined(\n value: string | number | bigint | null | undefined,\n): bigint | undefined {\n if (value === null || value === undefined) {\n return undefined;\n }\n return typeof value === \"bigint\" ? value : BigInt(value);\n}\n\n/**\n * Get the zap transactions for a given bundle.\n * @param args - The arguments for the zap transactions.\n * @returns 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 const approvalValue = toBigIntOrUndefined(approvalRequest.tx.value) ?? 0n;\n transactions.push({\n to: approvalRequest.tx.to,\n data: approvalRequest.tx.data as `0x${string}`,\n value: approvalValue,\n gasLimit: BigInt(approvalRequest.gas),\n });\n }\n }\n const bundleValue = toBigIntOrUndefined(bundle.tx.value) ?? 0n;\n transactions.push({\n to: bundle.tx.to,\n data: bundle.tx.data as `0x${string}`,\n value: bundleValue,\n gasLimit: BigInt(bundle.gas),\n });\n return transactions;\n};\n\n/**\n * Get ensowallet transactions for a bundle with approval handling.\n * Checks allowance on the ensowallet spender and prepends approval when needed.\n * @param args - The arguments for transaction generation.\n * @returns The bundle transaction and optional approval transaction.\n */\nexport const getEnsoWalletTransactionsWithApproval = async ({\n fromAddress,\n amountIn,\n tokenIn,\n bundle,\n publicClient,\n}: GetEnsoWalletTransactionsWithApprovalArgs): Promise<{\n transactions: GetZapTransactions;\n approval: AllowanceQueryItem | null;\n}> => {\n const transactions: GetZapTransactions = [];\n const spender = getAddress(bundle.tx.to);\n let approval: AllowanceQueryItem | null = null;\n\n /**\n * If the token is not the native token, we need to check if approval is required.\n */\n const tokenInAddress = toEnsoAddress(tokenIn.address);\n if (tokenInAddress !== ethAddress) {\n // Check current allowance\n const currentAllowance = await publicClient.readContract({\n address: tokenIn.address as Address,\n abi: erc20Abi,\n functionName: \"allowance\",\n args: [fromAddress, spender],\n });\n\n const amountInBigInt = BigInt(amountIn);\n const requiresApproval = currentAllowance < amountInBigInt;\n\n // Only add approval transaction if it's actually required\n if (requiresApproval) {\n const raw = amountInBigInt.toString();\n approval = {\n token: tokenIn,\n amount: {\n raw,\n formatted: formatUnits(amountInBigInt, tokenIn.decimals),\n },\n spender,\n };\n\n const approvalData = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"approve\",\n args: [spender, amountInBigInt],\n });\n\n transactions.push({\n to: tokenIn.address,\n data: approvalData,\n value: 0n,\n });\n }\n }\n const bundleValue = toBigIntOrUndefined(bundle.tx.value) ?? 0n;\n transactions.push({\n to: bundle.tx.to,\n data: bundle.tx.data as `0x${string}`,\n value: bundleValue,\n gasLimit: bundle.gas ? BigInt(bundle.gas) : undefined,\n });\n return { transactions, approval };\n};\n\n/**\n * Compute the fraction of swap output retained after accounting for slippage.\n *\n * @param slippage Slippage tolerance as a percentage (e.g. 0.5 means 0.5%).\n * @returns `1 - slippage/100`. Throws if the result is non-positive.\n */\nexport function computeSwapOutputRatio(slippage: number): BigNumber {\n const slippageRatio = new BigNumber(slippage).dividedBy(100);\n const ratio = new BigNumber(1).minus(slippageRatio);\n\n if (ratio.lte(0)) {\n throw new InvalidArgumentError({\n property: \"slippage\",\n value: slippage,\n expected: \"a value lower than 100\",\n });\n }\n\n return ratio;\n}\n\n/**\n * Convert a human-readable collateral-to-loan price into a raw-unit ratio.\n *\n * The result expresses how many raw loan-token units correspond to one raw\n * collateral-token unit:\n *\n * rawPrice = formattedPrice * (10^loanDecimals) / (10^collateralDecimals)\n */\nexport function computeRawCollateralToLoanPrice(\n formattedPrice: BigNumber,\n collateralToken: Token,\n loanToken: Token,\n): BigNumber {\n return formattedPrice\n .multipliedBy(new BigNumber(10).pow(loanToken.decimals))\n .dividedBy(new BigNumber(10).pow(collateralToken.decimals));\n}\n","\"use client\";\n\nimport useSWR from \"swr\";\nimport type { Address } from \"viem\";\nimport { getAddress } from \"viem\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getEnsoWalletV2Address } from \"../../actions/enso/flashloan\";\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport { parseBaseArgs } from \"../../utils/parseBaseArgs\";\n\nexport function useEnsoWalletV2Address({ chainId }: { chainId: number }) {\n const { address: fromAddress } = useBeraWallet();\n const publicClient = usePublicClient({ chainId });\n\n const { config } = parseBaseArgs({});\n const ensoWalletV2Factory = config.enso.walletV2Factory;\n\n const QUERY_KEY =\n fromAddress && ensoWalletV2Factory\n ? ([\"useEnsoWalletV2Address\", fromAddress, ensoWalletV2Factory] as const)\n : null;\n\n return useSWR<Address, unknown, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([_, accountAddress, factory]) => {\n assertPublicClient(publicClient);\n return getEnsoWalletV2Address({\n publicClient,\n ensoWalletV2Factory: getAddress(factory),\n accountAddress,\n });\n },\n { refreshInterval: POLLING.SLOW },\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 { getIsBendAuthorized } from \"../../actions/enso/flashloan\";\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\n\nexport function useIsBendAuthorized({\n chainId,\n primaryAddress,\n ensoWalletV2Address,\n}: {\n chainId: number;\n primaryAddress?: Address;\n ensoWalletV2Address?: Address;\n}) {\n const { address: fromAddress } = useBeraWallet();\n const publicClient = usePublicClient({ chainId });\n\n const QUERY_KEY =\n fromAddress && primaryAddress && ensoWalletV2Address\n ? ([\n \"useIsBendAuthorized\",\n fromAddress,\n primaryAddress,\n ensoWalletV2Address,\n ] as const)\n : null;\n\n return useSWR<boolean, unknown, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([_, accountAddress, primaryAddress, ensoWalletV2Address]) => {\n assertPublicClient(publicClient);\n return getIsBendAuthorized({\n publicClient,\n primaryAddress,\n accountAddress,\n ensoWalletV2Address,\n });\n },\n { refreshInterval: POLLING.SLOW },\n );\n}\n","\"use client\";\n\nimport useSWR from \"swr\";\nimport type { Address, Hex } from \"viem\";\nimport { parseUnits } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport {\n useBeraWagmi,\n useBeraWallet,\n usePublicClient,\n} from \"@berachain/wagmi/hooks\";\n\nimport { getEnsoClient } from \"../../actions/clients/getEnsoClient\";\nimport { getBendMultiplyBundle } from \"../../actions/enso/getBendMultiplyBundle\";\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { Token } from \"../../types/dex\";\nimport type { BendMultiplyBundleResponse } from \"../../types/enso\";\nimport type { DefaultHookOptions } from \"../../types/global\";\nimport { useEnsoWalletV2Address } from \"./useEnsoWalletV2Address\";\nimport { useIsBendAuthorized } from \"./useIsBendAuthorized\";\n\nexport type UseBendMultiply = {\n collateralToken?: Token;\n loanToken?: Token;\n marketId?: Hex;\n primaryAddress?: Address;\n formattedSupplyCollateralAmount?: string;\n formattedCurrentCollateralAmount?: string;\n formattedCurrentBorrowAmount?: string;\n leverageMultiplier?: number;\n slippage?: number;\n chainId?: number;\n formattedCollateralPriceInLoanAsset?: string;\n};\n\nexport function useBendMultiply(\n {\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n formattedSupplyCollateralAmount,\n formattedCurrentCollateralAmount,\n formattedCurrentBorrowAmount,\n leverageMultiplier,\n slippage,\n chainId,\n formattedCollateralPriceInLoanAsset,\n }: UseBendMultiply,\n options?: DefaultHookOptions,\n) {\n const { address: fromAddress } = useBeraWallet();\n const { account: { chainId: accountChainId } = {} } = useBeraWagmi();\n\n const chainIdToUse = chainId ?? accountChainId ?? defaultChainId;\n const publicClient = usePublicClient({ chainId: chainIdToUse });\n const { data: ensoWalletV2Address } = useEnsoWalletV2Address({\n chainId: chainIdToUse,\n });\n const { data: isAuthorized } = useIsBendAuthorized({\n chainId: chainIdToUse,\n primaryAddress,\n ensoWalletV2Address,\n });\n\n const QUERY_KEY =\n collateralToken &&\n loanToken &&\n marketId &&\n primaryAddress &&\n ensoWalletV2Address &&\n isAuthorized !== undefined &&\n collateralToken.address !== loanToken.address &&\n slippage !== undefined &&\n leverageMultiplier !== undefined &&\n formattedCollateralPriceInLoanAsset !== undefined &&\n (Number(formattedSupplyCollateralAmount ?? 0) > 0 ||\n (leverageMultiplier > 1 &&\n (Number(formattedCurrentCollateralAmount ?? 0) > 0 ||\n Number(formattedSupplyCollateralAmount ?? 0) > 0))) &&\n fromAddress &&\n (options?.opts?.isEnabled ?? true)\n ? ([\n \"useBendMultiply\",\n fromAddress,\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n chainIdToUse,\n formattedSupplyCollateralAmount ?? \"\",\n formattedCurrentCollateralAmount ?? \"\",\n formattedCurrentBorrowAmount ?? \"\",\n leverageMultiplier,\n slippage,\n formattedCollateralPriceInLoanAsset,\n ensoWalletV2Address,\n isAuthorized,\n ] as const)\n : null;\n\n return useSWR<BendMultiplyBundleResponse, unknown, typeof QUERY_KEY>(\n QUERY_KEY,\n async ([\n _,\n fromAddress,\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n chainId,\n formattedSupplyCollateralAmount,\n formattedCurrentCollateralAmount,\n formattedCurrentBorrowAmount,\n leverageMultiplier,\n slippage,\n formattedCollateralPriceInLoanAsset,\n ensoWalletV2Address,\n isAuthorized,\n ]) => {\n assertPublicClient(publicClient);\n\n const rawSupplyCollateralAmount = parseUnits(\n formattedSupplyCollateralAmount || \"0\",\n collateralToken.decimals,\n ).toString();\n const rawCurrentCollateralAmount = parseUnits(\n formattedCurrentCollateralAmount || \"0\",\n collateralToken.decimals,\n ).toString();\n const rawCurrentBorrowAmount = parseUnits(\n formattedCurrentBorrowAmount || \"0\",\n loanToken.decimals,\n ).toString();\n\n return getBendMultiplyBundle({\n fromAddress,\n rawSupplyCollateralAmount,\n rawCurrentCollateralAmount,\n rawCurrentBorrowAmount,\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n chainId,\n ensoClient: getEnsoClient(),\n slippage,\n leverageMultiplier,\n publicClient,\n formattedCollateralPriceInLoanAsset,\n ensoWalletV2Address,\n isAuthorized,\n });\n },\n {\n ...options?.opts,\n refreshInterval: POLLING.NORMAL,\n },\n );\n}\n","import type { BundleAction, EnsoClient } from \"@ensofinance/sdk\";\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport { assertAddress } from \"../../errors/assert\";\nimport { InvalidArgumentError } from \"../../errors/InvalidArgumentError\";\nimport type { Token } from \"../../types/dex\";\nimport type { BendMultiplyBundleResponse } from \"../../types/enso\";\nimport { assembleBendFlashloanTransactions } from \"./flashloan\";\nimport {\n computeRawCollateralToLoanPrice,\n computeSwapOutputRatio,\n toEnsoAddress,\n} from \"./util\";\n\nexport interface GetBendMultiplyBundleArgs {\n fromAddress: Address;\n rawSupplyCollateralAmount: string;\n rawCurrentCollateralAmount: string;\n rawCurrentBorrowAmount: string;\n collateralToken: Token;\n loanToken: Token;\n marketId: Hex;\n primaryAddress: Address;\n chainId: number;\n ensoClient: EnsoClient;\n slippage: number;\n leverageMultiplier: number;\n publicClient: PublicClient;\n formattedCollateralPriceInLoanAsset: string;\n ensoWalletV2Address: Address;\n isAuthorized: boolean;\n}\n\n/**\n * Calculate the loan amount needed to reach a target leverage multiplier.\n *\n * The closed-form formula accounts for the recursive nature of leveraged\n * looping: each borrowed amount is swapped to collateral (losing value to\n * slippage), then deposited, which increases borrowing capacity.\n *\n * targetLtv = 1 - 1/leverage\n * rawPrice = collateral-to-loan price in raw token units\n * denominator = 1 - targetLtv * swapOutputRatio\n *\n * borrowAmount = (targetLtv * collateralBase * rawPrice - currentBorrow)\n * / denominator\n *\n * The denominator corrects for the recursive loop: each unit of loan token\n * that survives the swap (after slippage) becomes new collateral that\n * enables further borrowing. When denominator <= 0, the leverage target is\n * unreachable at the current slippage tolerance.\n */\nexport function calculateMultiplyBorrowAmount({\n rawSupplyCollateralAmount,\n rawCurrentCollateralAmount,\n rawCurrentBorrowAmount,\n formattedCollateralPriceInLoanAsset,\n collateralToken,\n loanToken,\n leverageMultiplier,\n slippage,\n}: {\n rawSupplyCollateralAmount: string;\n rawCurrentCollateralAmount: string;\n rawCurrentBorrowAmount: string;\n formattedCollateralPriceInLoanAsset: string;\n collateralToken: Token;\n loanToken: Token;\n leverageMultiplier: number;\n slippage: number;\n}): string {\n const normalizedLeverage = Math.max(leverageMultiplier, 1);\n if (normalizedLeverage <= 1) return \"0\";\n\n const swapOutputRatio = computeSwapOutputRatio(slippage);\n const formattedCollateralPrice = new BigNumber(\n formattedCollateralPriceInLoanAsset,\n );\n\n if (formattedCollateralPrice.lte(0)) {\n throw new InvalidArgumentError({\n property: \"formattedCollateralPriceInLoanAsset\",\n value: formattedCollateralPriceInLoanAsset,\n expected: \"a value greater than zero\",\n });\n }\n\n const rawCollateralToLoanPrice = computeRawCollateralToLoanPrice(\n formattedCollateralPrice,\n collateralToken,\n loanToken,\n );\n\n const targetLtv = new BigNumber(1).minus(\n new BigNumber(1).dividedBy(normalizedLeverage),\n );\n const rawCollateralBase = new BigNumber(rawCurrentCollateralAmount).plus(\n rawSupplyCollateralAmount,\n );\n const rawCurrentBorrow = new BigNumber(rawCurrentBorrowAmount);\n\n // Denominator accounts for the recursive multiplier effect of re-deposited\n // swap proceeds. A non-positive value means slippage eats all new collateral.\n const denominator = new BigNumber(1).minus(\n targetLtv.multipliedBy(swapOutputRatio),\n );\n\n if (denominator.lte(0)) {\n throw new InvalidArgumentError({\n property: \"leverageMultiplier\",\n value: leverageMultiplier,\n expected: \"a lower leverage target for current slippage\",\n });\n }\n\n const requiredRawBorrow = targetLtv\n .multipliedBy(rawCollateralBase)\n .multipliedBy(rawCollateralToLoanPrice)\n .minus(rawCurrentBorrow)\n .dividedBy(denominator);\n\n if (requiredRawBorrow.lte(0)) return \"0\";\n\n const rawBorrowAmount = requiredRawBorrow.integerValue(BigNumber.ROUND_UP);\n if (rawBorrowAmount.lte(0)) return \"0\";\n\n return rawBorrowAmount.toFixed(0);\n}\n\n/**\n * Estimate the position after executing a multiply loop.\n *\n * For a deposit-only (rawBorrowAmount = 0) scenario, final collateral is just\n * the supplied amount. When borrowing, the loan is swapped to collateral\n * (accounting for slippage) and added to the supplied amount.\n *\n * Returns human-readable (formatted) values for display.\n */\nexport function getPositionEstimate({\n rawSupplyCollateralAmount,\n collateralToken,\n loanToken,\n rawBorrowAmount,\n formattedCollateralPriceInLoanAsset,\n slippage,\n}: {\n rawSupplyCollateralAmount: string;\n collateralToken: Token;\n loanToken: Token;\n rawBorrowAmount: string;\n formattedCollateralPriceInLoanAsset: string;\n slippage: number;\n}): BendMultiplyBundleResponse[\"positionEstimate\"] {\n const collateralDecimalsMul = new BigNumber(10).pow(collateralToken.decimals);\n const loanDecimalsMul = new BigNumber(10).pow(loanToken.decimals);\n const rawSupplyCollateral = new BigNumber(rawSupplyCollateralAmount);\n const rawBorrow = new BigNumber(rawBorrowAmount);\n\n if (rawBorrow.lte(0)) {\n return {\n finalCollateral: rawSupplyCollateral\n .dividedBy(collateralDecimalsMul)\n .toFixed(),\n totalBorrow: \"0\",\n };\n }\n\n const swapOutputRatio = computeSwapOutputRatio(slippage);\n const rawCollateralToLoanPrice = computeRawCollateralToLoanPrice(\n new BigNumber(formattedCollateralPriceInLoanAsset),\n collateralToken,\n loanToken,\n );\n\n // Collateral gained from swapping the borrowed loan tokens (after slippage)\n const rawLoopCollateral = rawCollateralToLoanPrice.lte(0)\n ? new BigNumber(0)\n : rawBorrow\n .multipliedBy(swapOutputRatio)\n .dividedBy(rawCollateralToLoanPrice);\n\n const finalFormattedCollateral = rawSupplyCollateral\n .plus(rawLoopCollateral)\n .dividedBy(collateralDecimalsMul);\n const totalFormattedBorrow = rawBorrow.dividedBy(loanDecimalsMul);\n\n return {\n finalCollateral: finalFormattedCollateral.toFixed(),\n totalBorrow: totalFormattedBorrow.toFixed(),\n };\n}\n\nexport async function getBendMultiplyBundle({\n fromAddress,\n rawSupplyCollateralAmount,\n rawCurrentCollateralAmount,\n rawCurrentBorrowAmount,\n collateralToken,\n loanToken,\n marketId,\n primaryAddress,\n chainId,\n ensoClient,\n slippage,\n leverageMultiplier,\n publicClient,\n formattedCollateralPriceInLoanAsset,\n ensoWalletV2Address,\n isAuthorized,\n}: GetBendMultiplyBundleArgs): Promise<BendMultiplyBundleResponse> {\n assertAddress(fromAddress, \"fromAddress\");\n\n const collateralAddress = toEnsoAddress(collateralToken.address);\n const loanAddress = toEnsoAddress(loanToken.address);\n\n const rawBorrowAmount = calculateMultiplyBorrowAmount({\n rawSupplyCollateralAmount,\n rawCurrentCollateralAmount,\n rawCurrentBorrowAmount,\n formattedCollateralPriceInLoanAsset,\n collateralToken,\n loanToken,\n leverageMultiplier,\n slippage,\n });\n\n // -- Callback action indices for `useOutputOfCallAt` references.\n // These MUST match the array position of each action in the callback below.\n const CALLBACK_IDX_ROUTE_LOAN_TO_COLLATERAL = 0;\n const CALLBACK_IDX_BALANCE_COLLATERAL = 1;\n\n const depositOnlyActions = [\n {\n protocol: \"bend\",\n action: \"deposit\",\n args: {\n primaryAddress,\n positionId: marketId,\n tokenIn: collateralAddress,\n amountIn: rawSupplyCollateralAmount,\n onBehalfOf: fromAddress,\n },\n },\n ];\n\n const flashloanActions = [\n {\n protocol: \"bend\",\n action: \"flashloan\",\n args: {\n flashloanToken: loanAddress,\n flashloanAmount: rawBorrowAmount,\n tokenIn: collateralAddress,\n amountIn: rawSupplyCollateralAmount,\n tokenOut: loanAddress,\n callback: [\n // [0] Swap the flashloaned loan tokens into collateral\n {\n protocol: \"enso\",\n action: \"route\",\n args: {\n tokenIn: loanAddress,\n tokenOut: collateralAddress,\n amountIn: rawBorrowAmount,\n slippage: slippage * 100,\n },\n },\n // [1] Check collateral balance after swap\n {\n protocol: \"enso\",\n action: \"balance\",\n args: {\n token: collateralAddress,\n },\n },\n // [2] Deposit all collateral (from balance check) into Bend\n {\n protocol: \"bend\",\n action: \"deposit\",\n args: {\n primaryAddress,\n positionId: marketId,\n tokenIn: collateralAddress,\n amountIn: {\n useOutputOfCallAt: CALLBACK_IDX_BALANCE_COLLATERAL,\n },\n onBehalfOf: fromAddress,\n },\n },\n // [3] Borrow loan tokens to repay the flashloan\n {\n protocol: \"bend\",\n action: \"borrow\",\n args: {\n primaryAddress,\n positionId: marketId,\n collateral: collateralAddress,\n tokenOut: loanAddress,\n amountOut: rawBorrowAmount,\n onBehalfOf: fromAddress,\n },\n },\n ],\n },\n },\n ];\n\n // @ts-expect-error Enso SDK BundleAction typing does not include Bend flashloan action shape yet.\n const bundleActions: BundleAction[] =\n rawBorrowAmount === \"0\" ? depositOnlyActions : flashloanActions;\n\n const bundle = await ensoClient.getBundleData(\n {\n fromAddress,\n receiver: fromAddress,\n spender: fromAddress,\n chainId,\n routingStrategy: \"ensowallet-v2\",\n },\n bundleActions,\n );\n\n const { transactions } = await assembleBendFlashloanTransactions({\n fromAddress,\n amountIn: rawSupplyCollateralAmount,\n tokenIn: collateralToken,\n primaryAddress,\n bundle,\n publicClient,\n ensoWalletV2Address,\n isAuthorized,\n });\n\n return {\n bundle,\n transactions,\n positionEstimate: getPositionEstimate({\n rawSupplyCollateralAmount,\n collateralToken,\n loanToken,\n rawBorrowAmount,\n formattedCollateralPriceInLoanAsset,\n slippage,\n }),\n };\n}\n","\"use client\";\n\nimport useSWR from \"swr\";\nimport { type Address, formatEther, parseUnits, zeroAddress } from \"viem\";\n\nimport { defaultChainId as berachainChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { ensoErc4626 } from \"../../actions/dex/aggregators/enso/ensoErc4626\";\nimport { POLLING } from \"../../enum/polling\";\nimport {\n assertAddress,\n assertDefined,\n assertPublicClient,\n} from \"../../errors/assert\";\nimport type { BalanceToken, MinimalERC20 } from \"../../types/dex\";\nimport type { DefaultHookOptions } from \"../../types/global\";\nimport { isToken } from \"../../utils/tokens\";\nimport { useGetConvertToAssets } from \"../bend/useGetConvertToAssets\";\nimport { usePriceImpact } from \"../dex/usePriceImpact\";\nimport { usePollBalance } from \"../tokens/usePollBalance\";\nimport { useTokenPrices } from \"../tokens/useTokenPrices\";\n\ntype UseBendZapSupplyArgs = {\n /*\n * The input token to swap from\n */\n tokenIn?: BalanceToken;\n /*\n * The loan token to swap to\n */\n loanToken: MinimalERC20;\n /*\n * The bend vault to swap to\n */\n bendVault: MinimalERC20;\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\n/**\n * Get the bend zap supply transaction requests for swapping tokens using Enso.\n * @param {UseBendZapSupplyArgs} props - The props for the hook see {@link UseBendZapSupplyArgs}\n * @returns {DefaultHookReturnType<GetZapTransactionResponse> & {tokens: BalanceToken[], refresh: () => void}}\n *\n * The bend transaction response data with polling enabled, see {@link GetZapTransactionResponse} and {@link BalanceToken}\n * @remarks The hook is only enabled when all parameters are provided and amount is greater than 0\n */\nexport function useBendZapSupply(\n {\n tokenIn,\n loanToken,\n bendVault,\n rewardVault,\n amount,\n slippage,\n }: UseBendZapSupplyArgs,\n options?: DefaultHookOptions,\n) {\n const { getTokenPrice } = useTokenPrices({\n tokens: tokenIn && loanToken ? [tokenIn, loanToken] : undefined,\n });\n\n const swrResponse = useBendZapSupplyHelper(\n {\n tokenIn,\n loanToken,\n bendVault,\n rewardVault,\n amount: amount\n ? parseUnits(amount, tokenIn?.decimals ?? 18).toString()\n : undefined,\n slippage,\n },\n options,\n );\n\n const { data: zapSupplyAmount } = useGetConvertToAssets({\n sharesAmount: BigInt(swrResponse.data?.amountOut ?? 0),\n vaultAddress: bendVault.address,\n });\n\n const { data: priceImpact } = usePriceImpact({\n tokenIn: tokenIn,\n tokenOut: loanToken,\n formattedAmountIn: amount,\n formattedAmountOut: zapSupplyAmount?.formatted ?? \"0\",\n });\n\n const isCrossChain = tokenIn?.chainId && tokenIn.chainId !== berachainChainId;\n\n // fetch native token balance for source chain (needed for bridge fee check)\n const { data: nativeBalanceData, isLoading: isNativeBalanceLoading } =\n usePollBalance(\n {\n address: zeroAddress,\n chainId: isCrossChain ? tokenIn?.chainId : undefined,\n },\n { opts: { isEnabled: !!isCrossChain } },\n );\n\n // for cross-chain zaps, check if transaction value exceeds native token balance\n // (tx.value includes bridge fees that must be paid in native token)\n const transactionValue =\n swrResponse.data?.getCalldata?.({ account: zeroAddress })?.value ?? 0n;\n\n // check if user has enough native token for bridge fees\n const nativeBalance = nativeBalanceData?.balance ?? {\n raw: \"0\",\n formatted: \"0\",\n };\n const hasInsufficientNativeBalance =\n isCrossChain &&\n transactionValue > 0n &&\n !isNativeBalanceLoading &&\n transactionValue > BigInt(nativeBalance.raw);\n\n // formatted native fee for gas reserve display\n const nativeFee =\n isCrossChain && transactionValue > 0n\n ? formatEther(transactionValue)\n : undefined;\n\n return {\n ...swrResponse,\n zapSupplyAmount,\n priceImpact,\n hasInsufficientNativeBalance,\n isCrossChain,\n nativeFee,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n}\n\nexport function useBendZapSupplyHelper(\n {\n tokenIn,\n loanToken,\n bendVault,\n rewardVault,\n amount,\n slippage,\n }: UseBendZapSupplyArgs,\n options?: DefaultHookOptions,\n) {\n const { address: fromAddress } = useBeraWallet();\n\n const isEnabled =\n !!tokenIn &&\n !!loanToken &&\n !!bendVault &&\n !!amount &&\n !!fromAddress &&\n !isToken(loanToken.address, tokenIn.address) &&\n tokenIn.chainId &&\n Number(amount) > 0 &&\n !!slippage;\n\n const publicClientBeraChain = usePublicClient();\n const QUERY_KEY = isEnabled\n ? ([\n \"useBendZapSupply\",\n tokenIn,\n loanToken,\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 loanToken,\n bendVault,\n rewardVault,\n amount,\n slippage,\n ]) => {\n assertPublicClient(publicClientBeraChain);\n assertAddress(fromAddress, \"fromAddress\");\n assertAddress(tokenIn?.address, \"tokenInAddress\");\n assertDefined(tokenIn?.chainId, \"tokenInChainId\");\n\n return await ensoErc4626.getQuote({\n tokenIn,\n tokenOut: bendVault,\n underlyingToken: loanToken,\n amount,\n slippage,\n account: fromAddress,\n rewardVault,\n });\n },\n {\n ...options?.opts,\n refreshInterval: POLLING.NORMAL,\n },\n );\n}\n","import type { BundleAction } from \"@ensofinance/sdk\";\nimport { type Address, ethAddress, type Hex, zeroAddress } from \"viem\";\n\nimport { Aggregators } from \"../../../../enum/dex\";\nimport { assertAddress } from \"../../../../errors/assert\";\nimport type {\n IAggregatorArgs,\n IRawAggregatorQuote,\n} from \"../../../../types/dex\";\nimport { getEnsoClient } from \"../../../clients/getEnsoClient\";\nimport { BaseAggregator } from \"../base\";\n\nclass EnsoErc4626Aggregator extends BaseAggregator {\n name = Aggregators.EnsoErc4626;\n supportedChains = null;\n readonly type = \"rest\";\n needsAccountForQuote = true;\n\n notFoundMessages: string[] = [\n \"Could not build shortcuts for route\",\n \"Could not quote shortcuts for route\",\n \"Swap not found for a required underlying of defi route,\",\n \"No route found from\",\n ];\n\n async getQuote({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n account = zeroAddress,\n aggregatorsFeeBps,\n proxyAggregatorsThroughVercel = false,\n rewardVault,\n underlyingToken,\n }: IAggregatorArgs): Promise<IRawAggregatorQuote> {\n this.assertChainSupport({ tokenIn, tokenOut });\n\n assertAddress(account, \"account\");\n\n const ensoClient = getEnsoClient({\n useProxy: !proxyAggregatorsThroughVercel,\n });\n\n if (tokenIn.address === zeroAddress) tokenIn.address = ethAddress;\n if (tokenOut.address === zeroAddress) tokenOut.address = ethAddress;\n\n /**\n * This is the token that will be swapped by enso, but might not be the same as the token out.\n *\n * If an underlying token is provided, we'll swap to that and then deposit it into the vault,\n * assuming that token out is an ERC4626 vault.\n */\n const zapTokenOut = underlyingToken ?? tokenOut;\n\n const bundleActions: BundleAction[] = [\n // this is the base route action, which will swap the token in to the zap token out\n // it handles cross-chain swaps and refunds the user if the swap fails\n // this might even be the only action if no underlying token or reward vault is provided\n {\n protocol: \"enso\",\n action: \"route\",\n args: {\n tokenIn: tokenIn.address,\n tokenOut: zapTokenOut.address,\n destinationChainId:\n // must be undefined if the token is the same chain\n tokenIn.chainId === zapTokenOut.chainId\n ? undefined\n : zapTokenOut.chainId,\n refundReceiver: account,\n amountIn: amount,\n slippage: slippage * 100, // Enso expects slippage in basis points\n },\n },\n ];\n\n if (underlyingToken) {\n // deposit the underlying token into the vault\n // this works both for Staked BERA/iBera and Bend Vaults\n bundleActions.push({\n protocol: \"erc4626\",\n action: \"deposit\",\n args: {\n amountIn: { useOutputOfCallAt: 0 },\n tokenIn: underlyingToken.address,\n primaryAddress: tokenOut.address,\n tokenOut: tokenOut.address,\n },\n });\n }\n\n if (rewardVault) {\n // if an address is provided, funds will be staked into the reward vault\n\n // offset dynamically reads length of bundleActions array to get the output of the previous call\n const offset = bundleActions.length;\n bundleActions.push(\n {\n protocol: \"enso\",\n action: \"balance\",\n args: {\n token: tokenOut.address,\n },\n },\n {\n protocol: \"erc20\",\n action: \"approve\",\n args: {\n amount: { useOutputOfCallAt: offset },\n spender: rewardVault,\n token: tokenOut.address,\n },\n },\n {\n protocol: \"enso\",\n action: \"call\",\n args: {\n address: rewardVault,\n args: [account, { useOutputOfCallAt: offset }],\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: account,\n receiver: account,\n spender: account,\n chainId: tokenIn.chainId,\n routingStrategy: \"router\",\n },\n bundleActions,\n );\n\n const tokenOutAddress = (rewardVault?.toLowerCase() ??\n tokenOut.address.toLowerCase()) as Address;\n\n const amountOut =\n // @ts-expect-error enso has not typed this but is returned sometimes from API.\n bundle.minAmountsOut[tokenOutAddress] ??\n bundle.amountsOut[tokenOutAddress] ??\n \"0\";\n\n return {\n amountOut,\n amountIn: amount,\n allowanceRequirements: this.parseAllowanceRequirements({\n tokenIn,\n rawAmount: amount,\n spender: bundle.tx.to,\n }),\n name: this.name,\n swapFeeBps: 0,\n priceImpactPercentage: bundle.priceImpact\n ? bundle.priceImpact / 100\n : null,\n getCalldata: () => ({\n address: bundle.tx.to,\n data: bundle.tx.data as Hex,\n value: BigInt(bundle.tx.value ?? 0),\n // not returning gas limit because it's usually underestimated by enso.\n // gasLimit: BigInt(bundle.gas),\n }),\n };\n }\n}\n\nexport const ensoErc4626 = new EnsoErc4626Aggregator();\n","\"use client\";\n\nimport { getPublicClient } from \"@wagmi/core\";\nimport useSWR from \"swr\";\nimport { parseUnits } from \"viem\";\n\nimport { defaultChainId as berachainChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { getEnsoClient } from \"../../actions/clients/getEnsoClient\";\nimport { getEnsoSwapBundle } from \"../../actions/enso/getEnsoSwapBundle\";\nimport { POLLING } from \"../../enum/polling\";\nimport {\n assertAddress,\n assertAmount,\n assertDefined,\n assertPublicClient,\n} from \"../../errors/assert\";\nimport type { BalanceToken, MinimalERC20 } from \"../../types/dex\";\nimport type { GetZapTransactionResponse } from \"../../types/enso\";\nimport { usePollWalletBalances } from \"../tokens/usePollWalletBalances\";\n\n/**\n * Get the swap bundle 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: BalanceToken[], refresh: () => void}}\n *\n * The zap transaction response data with polling enabled, see {@link GetZapTransactionResponse} and {@link BalanceToken}\n * @remarks The hook is only enabled when all parameters are provided and amount is greater than 0\n */\nexport function useEnsoSwapBundle({\n tokenIn,\n tokenOut,\n amount,\n slippage,\n}: {\n tokenIn?: Pick<MinimalERC20, \"address\" | \"decimals\" | \"chainId\">;\n tokenOut?: Pick<MinimalERC20, \"address\" | \"decimals\">;\n amount?: string;\n slippage?: number;\n}) {\n const { address: fromAddress } = useBeraWallet();\n const wagmiConfig = useConfig();\n const ensoClient = getEnsoClient();\n\n const { refresh: refreshBalances } = usePollWalletBalances();\n\n const isEnabled =\n !!tokenIn &&\n !!tokenOut &&\n !!amount &&\n Number(amount) > 0 &&\n !!slippage &&\n !!fromAddress &&\n !!tokenIn.chainId;\n\n const QUERY_KEY = isEnabled\n ? ([\"useEnsoSwapBundle\", tokenIn, tokenOut, amount, slippage] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, tokenIn, tokenOut, amount, slippage]) => {\n assertAddress(fromAddress, \"fromAddress\");\n assertAddress(tokenIn?.address, \"tokenInAddress\");\n assertDefined(tokenIn?.chainId, \"tokenInChainId\");\n assertAddress(tokenOut?.address, \"tokenOutAddress\");\n assertAmount(amount, \"amount\");\n assertAmount(slippage, \"slippage\");\n\n const publicClient = getPublicClient(wagmiConfig, {\n chainId: tokenIn.chainId,\n });\n assertPublicClient(publicClient);\n\n const rawAmount = parseUnits(amount, tokenIn.decimals).toString();\n\n return getEnsoSwapBundle({\n fromAddress,\n amountIn: rawAmount,\n tokenIn: tokenIn.address,\n tokenOut: tokenOut.address,\n chainId: tokenIn.chainId,\n ensoClient,\n destinationChainId: berachainChainId,\n slippage,\n publicClient,\n });\n },\n {\n refreshInterval: POLLING.NORMAL,\n isEnabled: isEnabled,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n refreshBalances();\n },\n };\n}\n","import type { BundleAction } from \"@ensofinance/sdk\";\nimport { ethAddress, zeroAddress } from \"viem\";\n\nimport { InvalidArgumentError } from \"../../errors/InvalidArgumentError\";\nimport type {\n GetEnsoSwapBundleArgs,\n GetZapTransactionResponse,\n} from \"../../types/enso\";\nimport { getTransactionsFromBundle } from \"./util\";\n\nexport async function getEnsoSwapBundle({\n fromAddress,\n amountIn,\n tokenIn,\n tokenOut,\n chainId,\n ensoClient,\n destinationChainId,\n slippage,\n publicClient,\n}: GetEnsoSwapBundleArgs): 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 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 { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport {\n useBeraWallet,\n useConfig,\n usePublicClient,\n} from \"@berachain/wagmi/hooks\";\n\nimport { getWalletBalances } from \"../../actions/tokens/getWalletBalances\";\nimport { POLLING } from \"../../enum/polling\";\nimport type { BalanceToken, Token } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\nimport { useTokens } from \"./useTokens\";\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 const wagmiConfig = useConfig();\n const { address: connectedAccount } = useBeraWallet();\n\n const { tokenList, refresh } = 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 wagmiConfig,\n });\n },\n {\n refreshInterval: POLLING.NORMAL,\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse?.mutate?.();\n refresh();\n },\n };\n}\n","\"use client\";\n\nimport useSWR from \"swr\";\nimport { formatUnits, parseUnits } from \"viem\";\n\nimport { chainConfigs, defaultChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet } from \"@berachain/wagmi/hooks\";\n\nimport { ensoErc4626 } from \"../../actions/dex/aggregators/enso/ensoErc4626\";\nimport { POLLING } from \"../../enum/polling\";\nimport type { MinimalERC20 } from \"../../types/dex\";\nimport type { DefaultHookOptions } from \"../../types/global\";\nimport { usePriceImpact } from \"../dex/usePriceImpact\";\n\ntype UseZapStakeBeraArgs = {\n inputToken: MinimalERC20 | undefined;\n amount: string;\n underlyingToken: MinimalERC20 | undefined;\n slippage?: number;\n inputTokenPrice?: number;\n tokenOut: MinimalERC20;\n};\n\n/**\n * hook to get zap stake BERA transaction data from enso.\n * supports cross-chain zaps from any chain to berachain staking.\n */\nexport function useZapStakeBera(\n {\n inputToken,\n amount,\n underlyingToken,\n slippage,\n tokenOut,\n }: UseZapStakeBeraArgs,\n options?: DefaultHookOptions,\n) {\n const { address: account } = useBeraWallet();\n // enso route simulation needs a real EOA-like address; zeroAddress can fail simulation.\n // use the connected wallet when available, otherwise fallback to our configured aggregator executor.\n const quoteAccount =\n account ?? chainConfigs[defaultChainId].bex.aggregatorsRouterExecutor;\n\n const isEnabled =\n !!inputToken &&\n !!amount &&\n Number(amount) > 0 &&\n !!inputToken.chainId &&\n !!underlyingToken &&\n !!slippage;\n\n const QUERY_KEY = isEnabled\n ? ([\n \"useZapStakeBera\",\n inputToken,\n amount,\n quoteAccount,\n slippage,\n underlyingToken,\n tokenOut,\n ] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([\n ,\n inputToken,\n amount,\n quoteAccount,\n slippage,\n underlyingToken,\n tokenOut,\n ]) => {\n const rawAmount = parseUnits(amount, inputToken.decimals).toString();\n\n return ensoErc4626.getQuote({\n account: quoteAccount,\n amount: rawAmount,\n tokenIn: inputToken,\n underlyingToken: underlyingToken,\n tokenOut: tokenOut,\n slippage,\n });\n },\n {\n ...options?.opts,\n refreshInterval: POLLING.NORMAL,\n },\n );\n const { data: priceImpactPercentage } = usePriceImpact({\n tokenIn: inputToken,\n tokenOut: tokenOut,\n formattedAmountIn: amount,\n formattedAmountOut: formatUnits(\n BigInt(swrResponse.data?.amountOut ?? \"0\"),\n tokenOut.decimals,\n ),\n });\n\n return {\n ...swrResponse,\n data: {\n ...swrResponse.data,\n priceImpactPercentage,\n isCrossChain: inputToken && tokenOut.chainId !== inputToken?.chainId,\n },\n refresh: () => {\n swrResponse.mutate();\n },\n };\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\n\nimport { getProposalParams } from \"../../actions/governance/getProposalParams\";\nimport { ProposalTypeEnum } from \"../../enum/governance\";\nimport type {\n CustomProposal,\n CustomProposalErrors,\n GovernanceTopic,\n PROPOSAL_GENRE,\n SafeProposalAction,\n} from \"../../types/governance\";\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 \"@berachain/abis/pol/rewards/beraChef\";\nimport { rewardVaultAbi } from \"@berachain/abis/pol/rewards/rewardVault\";\n\nimport { ProposalErrorCodes, ProposalTypeEnum } from \"../../enum/governance\";\nimport type {\n CustomProposal,\n CustomProposalActionErrors,\n CustomProposalErrors,\n GovernanceTopic,\n} from \"../../types/governance\";\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 { bgtAbi } from \"@berachain/abis/pol/bgt\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\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 { timeLockAbi as governanceTimelockAbi } from \"@berachain/abis/gov/timeLock\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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/global\";\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { DefaultHookReturnType } from \"../../types/global\";\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 { bgtAbi } from \"@berachain/abis/pol/bgt\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { ProposalState } from \"../../enum/governance\";\nimport { assertPublicClient } from \"../../errors/assert\";\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 { timeLockAbi as governanceTimelockAbi } from \"@berachain/abis/gov/timeLock\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\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 function 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 { formatEther, type PublicClient } from \"viem\";\n\nimport { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\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 | undefined;\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 { Token } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 type { PythLatestUpdates } from \"../../actions/honey/getPythLatestPrices\";\nimport { getPythLatestPrices } 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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 { Token } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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\";\n\nimport BigNumber from \"@berachain/utils/pkg/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 { isToken } from \"../../utils/tokens\";\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?.balance.formatted ?? \"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?.balance.formatted ?? \"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?.balance.formatted ?? \"0\").lt(\n amountToRedeem ?? \"0\",\n );\n },\n );\n return {\n isMore: !!isRedeemMoreThanLiquidityCollaterals.find((coll) =>\n isToken(coll, state.collaterals[0]),\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]?.balance.formatted ?? \"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]?.balance.formatted,\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]?.balance.formatted).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 {\n useBeraWallet,\n useConfig,\n usePublicClient,\n} 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 const wagmiConfig = useConfig();\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 wagmiConfig,\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/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} 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 { Token } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 useSWR from \"swr\";\n\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\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 } from \"../../enum/honey\";\nimport 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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 { bgtAbi } from \"@berachain/abis/pol/bgt\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} 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 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/global\";\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 {\n type GlobalData,\n getGlobalData,\n} from \"../../actions/pol/getGlobalData\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { DefaultHookOptions } from \"../../types/global\";\n\nexport function useQueuedBeraUnlock(\n {\n receiptTokenAddresses,\n account,\n version,\n }: {\n receiptTokenAddresses: Address[];\n account?: Address | string;\n version: \"V1\" | \"V2\";\n },\n options?: DefaultHookOptions,\n) {\n const publicClient = usePublicClient();\n\n const QUERY_KEY =\n receiptTokenAddresses &&\n account &&\n publicClient &&\n isAddress(account) &&\n version\n ? ([\n \"useQueuedBeraUnlock\",\n receiptTokenAddresses,\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 ([, receiptTokenAddresses, account, version]) => {\n assertPublicClient(publicClient);\n\n return await Promise.all(\n receiptTokenAddresses.map(async (receiptTokenAddress) => {\n return await getSWBeraWithdrawal({\n contractAddress: receiptTokenAddress,\n accountAddress: account,\n publicClient,\n version,\n });\n }),\n ).then((results) => results.flat());\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 { defaultChainId } from \"@berachain/config/internal\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getRewardTokenToBeraRate } from \"../../actions/pol/getRewardTokenToBeraRate\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport { InvalidArgumentError } from \"../../errors/InvalidArgumentError\";\nimport type { DefaultHookOptions } from \"../../types/global\";\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({ chainId: defaultChainId });\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 { beraChefAbi } from \"@berachain/abis/pol/rewards/beraChef\";\n\nimport type { ApiVaultFragment } from \"@berachain/graphql/pol/api\";\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\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/global\";\nimport { parseBaseArgs } from \"../../utils/parseBaseArgs\";\n\nconst 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 chainId: publicClient.chain.id,\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 Address, erc20Abi, formatUnits, type PublicClient } from \"viem\";\n\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { Token } from \"../../types/dex\";\n\nexport interface GetStakingTokenInformation {\n address: Address;\n publicClient: PublicClient | undefined;\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 { GqlVaultSnapshotDataRange } from \"@berachain/graphql/dex/api\";\n\nimport { getStakedBeraSnapshots } from \"../../actions/pol/getStakedBeraSnapshots\";\nimport type { DefaultHookReturnType } from \"../../types/global\";\nimport { dailyResolution } from \"../../utils/filter\";\n\ntype UseStakedAPR = {\n _timestamp: number;\n apr: string;\n}[];\nexport function useStakedAPR({\n range,\n}: {\n range: GqlVaultSnapshotDataRange;\n}): DefaultHookReturnType<UseStakedAPR> {\n const QUERY_KEY = range ? ([\"useStakedAPR\", range] as const) : null;\n const swrResponse = useSWR(QUERY_KEY, async ([, range]) => {\n const unsortedStakedBeraSnapshots = await getStakedBeraSnapshots({\n range,\n });\n\n const sortedStakedBeraSnapshots = dailyResolution(\n unsortedStakedBeraSnapshots.sort((a, b) => a.timestamp - b.timestamp),\n );\n\n return sortedStakedBeraSnapshots.map((item) => ({\n _timestamp: item.timestamp,\n apr: item.apr,\n }));\n });\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","/**\n * Filters data to get one data point per day\n * @param data - The data to filter\n * @returns The filtered data\n */\nexport const dailyResolution = <\n T extends { timestamp?: number; _timestamp?: number },\n>(\n data: T[],\n) => {\n // Filter to get one data point per day\n const dailyData: T[] = [];\n let lastDay = \"\";\n\n for (const item of data) {\n if (!item.timestamp && !item._timestamp) continue;\n // Convert Unix timestamp (seconds) to milliseconds for Date constructor\n const timestampMs = (item?.timestamp ?? item?._timestamp ?? 0) * 1000;\n const currentDay = new Date(timestampMs);\n const currentDayStr = currentDay.toDateString();\n if (currentDayStr !== lastDay) {\n const newTimestamp =\n new Date(currentDay.setHours(0, 0, 0, 0)).getTime() / 1000;\n dailyData.push({\n ...item,\n timestamp: newTimestamp,\n _timestamp: newTimestamp,\n });\n lastDay = currentDayStr;\n }\n }\n\n return dailyData;\n};\n","import { useMemo } from \"react\";\nimport useSWR from \"swr\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\nimport BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\nimport { getEarnedStakedBeraVault } from \"../../actions/pol/getEarnedStakedBeraVault\";\nimport { getRewardTokenToBeraRate } from \"../../actions/pol/getRewardTokenToBeraRate\";\nimport { getStakedBeraAPR } from \"../../actions/pol/getStakedBeraAPR\";\nimport { useBeraFlag } from \"../../contexts/BeraFlags/BeraFlags\";\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { StakedBeraAsset } from \"../../types/pol\";\nimport type { StakingConfig } from \"../../types/staking\";\nimport { usePollWalletBalances } from \"../tokens/usePollWalletBalances\";\nimport { useTokenPrices } from \"../tokens/useTokenPrices\";\n\n/**\n * Fetches staked asset data in two phases for progressive loading:\n *\n * 1. APR — independent fetch, resolves quickly, shared by both phases.\n * 2. Balances (fast path) — wallet balances (via usePollWalletBalances),\n * token prices (via useTokenPrices), and exchange rates.\n * Provides staked amounts and USD values immediately (earnings are 0).\n * 3. Positions (slow path) — adds earnings data from the vault.\n * Provides the full picture with earned amounts and USD values.\n *\n * Consumers can show `balances` right away and swap in `data` once positions resolve.\n */\nexport const useStakedData = (stakingConfigs: StakingConfig[]) => {\n const window = useBeraFlag(\"swberaAprWindow\");\n\n const publicClient = usePublicClient();\n const { address: account } = useBeraWallet();\n\n const receiptTokens = useMemo(\n () => stakingConfigs.map((config) => config.receiptToken),\n [stakingConfigs],\n );\n const inputTokens = useMemo(\n () => stakingConfigs.map((config) => config.inputTokens[0]),\n [stakingConfigs],\n );\n\n // APR — only updates every ~12 hours on BE\n const aprKey = window ? ([\"useStakedData:apr\", window] as const) : null;\n const { data: apr } = useSWR(\n aprKey,\n async ([, window]) => getStakedBeraAPR({ window }),\n { refreshInterval: POLLING.NORMAL },\n );\n\n const { data: walletBalances, isLoading: isLoadingBalances } =\n usePollWalletBalances({ tokens: receiptTokens });\n\n // NOT BERA PRICE, INPUT TOKEN PRICE\n const { getTokenPrice } = useTokenPrices({ tokens: inputTokens });\n\n // exchange rates from receipt token → input token (on-chain reads)\n const exchangeRatesKey =\n publicClient && receiptTokens.length > 0\n ? ([\"useStakedData:exchangeRates\", receiptTokens] as const)\n : null;\n\n const { data: exchangeRates } = useSWR(\n exchangeRatesKey,\n async ([, receiptTokens]) => {\n assertPublicClient(publicClient);\n return Promise.all(\n receiptTokens.map((token) =>\n getRewardTokenToBeraRate({\n address: token.address,\n publicClient,\n }),\n ),\n );\n },\n { refreshInterval: POLLING.NORMAL },\n );\n\n // balances (fast path) — derived from hooks above, no extra requests\n const balances = useMemo<StakedBeraAsset[] | undefined>(() => {\n if (!walletBalances || !exchangeRates) return undefined;\n\n return stakingConfigs.map((config, i): StakedBeraAsset => {\n const inputToken = config.inputTokens[0];\n const stakedBalance =\n walletBalances.find((b) => b.address === config.receiptToken.address)\n ?.balance.raw ?? \"0\";\n const exchangeRate = exchangeRates[i] ?? 0;\n const inputTokenPrice = getTokenPrice(inputToken) ?? 0;\n\n const total = new BigNumber(stakedBalance).multipliedBy(exchangeRate);\n const stakedAmount = total.dividedBy(10 ** inputToken.decimals);\n const stakedAmountUsd = stakedAmount.multipliedBy(inputTokenPrice);\n\n return {\n token: inputToken,\n apr: apr ?? 0,\n stakedAmount: stakedAmount.toNumber(),\n stakedAmountUsd: stakedAmountUsd.toNumber(),\n earnedAmount: 0,\n earnedAmountUsd: 0,\n isLoadingEarnings: true,\n };\n });\n }, [walletBalances, exchangeRates, stakingConfigs, apr, getTokenPrice]);\n\n // positions (slow path) — fetch earnings and exchange rates from the vault\n const positionsKey =\n account && publicClient && stakingConfigs.length > 0\n ? ([\"useStakedData:positions\", account, stakingConfigs] as const)\n : null;\n\n const {\n data: positionsRaw,\n isLoading: isLoadingPositions,\n isValidating: isValidatingPositions,\n } = useSWR(\n positionsKey,\n async ([, account, stakingConfigs]) => {\n assertPublicClient(publicClient);\n\n return Promise.all(\n stakingConfigs.map(async (stakingConfig) => {\n const stakingToken = stakingConfig.receiptToken;\n\n const [earnings, exchangeRate] = await Promise.all([\n getEarnedStakedBeraVault({\n address: stakingToken.address,\n account,\n }),\n getRewardTokenToBeraRate({\n address: stakingToken.address,\n publicClient,\n }),\n ]);\n\n return { earnings, exchangeRate };\n }),\n );\n },\n { refreshInterval: POLLING.FAST },\n );\n\n // derive full StakedBeraAsset[] from raw positions + shared hooks\n const data = useMemo<StakedBeraAsset[] | undefined>(() => {\n if (!positionsRaw || !walletBalances) return undefined;\n\n return stakingConfigs.map((config, i): StakedBeraAsset => {\n const inputToken = config.inputTokens[0];\n const stakingToken = config.receiptToken;\n const { earnings, exchangeRate: exchangeRateRaw } = positionsRaw[i];\n\n const inputTokenPrice = getTokenPrice(inputToken) ?? 0;\n const stakedBalance =\n walletBalances.find((b) => b.address === stakingToken.address)?.balance\n .raw ?? \"0\";\n const exchangeRate = exchangeRateRaw ?? 0;\n\n const unrealisedGains = new BigNumber(earnings.earningsTotal).minus(\n earnings.earningsRealized,\n );\n const total = new BigNumber(stakedBalance).multipliedBy(exchangeRate);\n const deposited = total.minus(unrealisedGains);\n\n const stakedAmount = deposited.dividedBy(10 ** inputToken.decimals);\n const earnedAmount = unrealisedGains.dividedBy(10 ** inputToken.decimals);\n const stakedAmountUsd = stakedAmount.multipliedBy(inputTokenPrice);\n const earnedAmountUsd = earnedAmount.multipliedBy(inputTokenPrice);\n\n return {\n token: inputToken,\n apr: apr ?? 0,\n stakedAmount: stakedAmount.toNumber(),\n earnedAmount: earnedAmount.toNumber(),\n stakedAmountUsd: stakedAmountUsd.toNumber(),\n earnedAmountUsd: earnedAmountUsd.toNumber(),\n };\n });\n }, [positionsRaw, walletBalances, stakingConfigs, apr, getTokenPrice]);\n\n return {\n /** Fast path: staked amounts + USD values (no earnings) */\n balances,\n /** Slow path: full enriched positions with earnings */\n data,\n /** True only when both balances and positions are still loading */\n isLoading: isLoadingBalances && isLoadingPositions,\n isLoadingBalances,\n isLoadingPositions,\n isValidatingPositions,\n };\n};\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { getStakingDailyAssets } from \"../../actions/pol/getStakingDailyAssets\";\nimport type { DefaultHookReturnType } from \"../../types/global\";\nimport { dailyResolution } from \"../../utils/filter\";\n\ntype UseStakedBeraSnapshot = Record<\n Address,\n {\n _timestamp: number;\n total_assets: string;\n }[]\n>;\nexport function useStakedSnapshots({\n range,\n addresses,\n}: {\n addresses: Address[];\n range: 30 | 60 | 90;\n}): DefaultHookReturnType<UseStakedBeraSnapshot> {\n const QUERY_KEY = range\n ? ([\"useStakedSnapshots\", range, addresses] as const)\n : null;\n const swrResponse = useSWR(QUERY_KEY, async ([, range, addresses]) => {\n const [...sortedStakingDailyAssetsArray] = await Promise.all([\n ...addresses.map(async (address) => {\n const unstakingDailyAssets = await getStakingDailyAssets({\n address,\n range,\n });\n const sortedStakingDailyAssets = dailyResolution(\n unstakingDailyAssets.sort((a, b) => a._timestamp - b._timestamp),\n );\n return {\n [address]: sortedStakingDailyAssets,\n };\n }),\n ]);\n\n // Merge all address data into a single object\n return sortedStakingDailyAssetsArray.reduce(\n (acc, addressData) => ({ ...acc, ...addressData }),\n {} as Record<Address, { _timestamp: number; total_assets: string }[]>,\n );\n });\n\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","import type { Address } from \"viem\";\n\nimport { beraFetchJson } from \"../../utils/beraFetch\";\nimport { parseBaseArgs } from \"../../utils/parseBaseArgs\";\n\nexport async function getStakingDailyAssets({\n address,\n range,\n}: {\n address: Address;\n range: 30 | 60 | 90;\n}): Promise<{ _timestamp: number; total_assets: string }[]> {\n const now = new Date();\n const startDayDate = new Date(\n now.getTime() - Number(range) * 24 * 60 * 60 * 1000,\n );\n\n const { config } = parseBaseArgs({});\n const url = `${config.staking}/vaults/${address}/total-assets-by-day?start=${startDayDate.toISOString().split(\"T\")[0]}`;\n return beraFetchJson<{ _timestamp: number; total_assets: string }[]>({\n url,\n type: \"rest\",\n });\n}\n","import useSWR from \"swr\";\nimport type { Address } from \"viem\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getSWBeraVaultMetadata } from \"../../actions/pol/getSWBeraVaultMetadata\";\nimport { useBlockTime } from \"../../contexts/block-time-provider\";\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\n\nexport type StakingVaultEntry = {\n address: Address;\n underlyingAsset: Address;\n};\n\nexport const useStakingVaultsMetadata = (vaults: StakingVaultEntry[] = []) => {\n const publicClient = usePublicClient();\n const blockTime = useBlockTime();\n const QUERY_KEY =\n vaults.length > 0 && publicClient && blockTime\n ? ([\"useStakingVaultMetadata\", vaults, publicClient, blockTime] as const)\n : null;\n return useSWR(\n QUERY_KEY,\n async ([, vaults, publicClient, blockTime]) => {\n assertPublicClient(publicClient);\n return Promise.all(\n vaults.map((vault) =>\n getSWBeraVaultMetadata({\n address: vault.address,\n underlyingAsset: vault.underlyingAsset,\n publicClient,\n blockTime,\n }),\n ),\n );\n },\n { refreshInterval: POLLING.FAST },\n );\n};\n","import useSWR from \"swr\";\n\nimport type { Address } from \"@berachain/config\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getTotalStakedAmount } from \"../../actions/pol/getTotalStakedAmount\";\nimport type { DefaultHookReturnType } from \"../../types/global\";\n\nexport function useTotalStakedAmount({\n vaultAddresses,\n}: {\n vaultAddresses: Address[];\n}): DefaultHookReturnType<Record<Address, bigint>> {\n const publicClient = usePublicClient();\n\n const swrResponse = useSWR(\n vaultAddresses && publicClient\n ? [\"useTotalStakedAmount\", vaultAddresses]\n : null,\n ([, vaultAddresses]) => {\n return getTotalStakedAmount({ vaultAddresses, 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 { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { getUserVaultInfo } from \"../../actions/pol/getUserVaultInfo\";\nimport { POLLING } from \"../../enum/polling\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} 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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} 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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 { DefaultHookOptions } from \"../../types/global\";\nimport { useTokenCurrentPrices } from \"./useTokenCurrentPrices\";\n\n/**\n * @deprecated use useTokenPrice instead\n */\nexport function useTokenCurrentPrice(\n { address }: { address: `0x${string}` | undefined },\n options?: DefaultHookOptions,\n) {\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 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 { Token } from \"../../types/dex\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 type { Address } from \"viem\";\n\nimport type { DefaultHookOptions } from \"../../types/global\";\nimport { type TokenPriceInput, useTokenPrices } from \"./useTokenPrices\";\n\nexport function useTokenPrice(\n { token }: { token: TokenPriceInput | undefined },\n options?: DefaultHookOptions,\n) {\n const { isLoading, priceMap } = useTokenPrices(\n { tokens: token ? [token] : undefined },\n options,\n );\n\n return {\n data: token\n ? priceMap[token.chainId]?.[token.address.toLowerCase() as Address]\n : undefined,\n isLoading,\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 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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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","import type { PublicClient } from \"viem\";\n\nimport { rewardAllocatorFactoryAbi as rewardAllocationFactoryAbi } from \"@berachain/abis/pol/rewards/rewardAllocatorFactory\";\n\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/global\";\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 { 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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 \"@berachain/abis/pol/rewards/beraChef\";\n\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 { beaconDepositAbi } from \"@berachain/abis/pol/beaconDeposit\";\nimport { bgtAbi } from \"@berachain/abis/pol/bgt\";\nimport { beraChefAbi } from \"@berachain/abis/pol/rewards/beraChef\";\n\nimport type { ApiValidatorFragment } from \"@berachain/graphql/pol/api\";\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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\";\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\n\ninterface 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/global\";\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 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/polling\";\nimport { BeraError } from \"../../errors/BeraError\";\nimport { BeraMonitoring } from \"../../errors/BeraMonitoring\";\nimport { InvalidArgumentError } from \"../../errors/InvalidArgumentError\";\nimport type { BribeBoostRewardProof } from \"../../types/bribe-boost\";\nimport type { DefaultHookReturnType } from \"../../types/global\";\nimport { formatIncentivesTokenMap } from \"../../utils/formatIncentivesTokenMap\";\n\ninterface 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 BeraMonitoring.captureException(\n new BeraError({\n message: \"Incorrect aggregated incentives data receieved.\",\n level: \"error\",\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/global\";\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/global\";\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 \"../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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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 {\n DefaultHookOptions,\n DefaultHookReturnType,\n} from \"../../types/global\";\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/global\";\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":"y2CAAA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nB,OAAS,mBAAAC,OAAuB,yBASzB,IAAMC,GAAqC,CAChDC,EACAC,IACiE,CACjE,IAAMC,EAAeC,GAAgB,EAM/BC,EAAcC,GAJlBH,GAAgBF,EACX,CAAC,qCAAsCA,CAAM,EAC9C,KAIJ,MAAO,CAAC,CAAEA,CAAM,IACP,MAAMM,GAAmC,CAC9C,OAAQJ,EACR,OAAAF,CACF,CAAC,EAEH,CACE,GAAGC,GAAS,IACd,CACF,EAEA,MAAO,CACL,GAAGG,EACH,QAAS,IAAMA,EAAY,OAAO,CACpC,CACF,ECvCA,OAAOG,OAAY,MAGnB,OAAS,mBAAAC,OAAuB,yBAKzB,SAASC,GACdC,EACAC,EACA,CACA,IAAMC,EAAeC,GAAgB,EAM/BC,EAAcC,GAJlBH,GAAgBF,EACX,CAAC,+BAAgCA,CAAM,EACxC,KAIJ,MAAO,CAAC,CAAEA,CAAM,IACP,MAAMM,GAA6B,CACxC,OAAQJ,EACR,OAAAF,CACF,CAAC,EAEH,CACE,GAAGC,GAAS,IACd,CACF,EAEA,MAAO,CACL,GAAGG,EACH,QAAS,IAAMA,EAAY,OAAO,CACpC,CACF","names":["useSWR","usePublicClient","useGetConvertToAssets","sharesAmount","vaultAddress","vaultChainId","options","publicClient","usePublicClient","swrResponse","useSWR","_","assertPublicClient","getConvertToAssets","useMemo","zeroAddress","defaultChainId","useBeraWallet","usePublicClient","Slippage","Swap","SwapKind","Token","TokenAmount","decodeFunctionData","formatEther","zeroAddress","getUriFromLink","ChainId","balancerVaultAbi","DEFAULT_DEADLINE","STALE_PRICE_THRESHOLD","swapKind","SwapKind","BexAggregator","BaseAggregator","ChainId","getUriFromLink","address","isToken","priceImpact","onChainAmount","sorPaths","sorAmount","queryData","deltaFromSorAmount","formatEther","error","BeraError","p","BeraMonitoring","args","balancerApi","BalancerApi","tokenIn","tokenOut","amount","slippage","account","zeroAddress","publicClient","assertPublicClient","wberaIsBera","tokenInV3","Token","tokenOutV3","tokenAmount","TokenAmount","RequestError","swap","Swap","queryOutput","callData","Slippage","params","functionName","decodeFunctionData","balancerVaultAbi","bex","ChainId","RedeemBgtAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","isToken","amount","beraToken","InvalidArgumentError","bgtRedeem","zeroAddress","ChainId","aggregatorsRouterAbi","EnsoAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","url","quote","inputData","outputData","aggregatorData","aggregatorsRouterAbi","enso","erc4626Abi","formatUnits","stakeBeraVaultAbi","ERC4626Aggregator","BaseAggregator","tokenIn","tokenOut","underlyingToken","isToken","amount","publicClient","assertDefined","assertPublicClient","rawOutputAmount","erc4626Abi","isSwBeraNative","formatUnits","account","stakeBeraVaultAbi","erc4626Deposit","zeroAddress","ChainId","aggregatorsRouterAbi","BASE_URL","FlyAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","aggregatorsFeeBps","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","url","params","quoteData","formattedQuote","txUrl","txParams","txData","inputData","outputData","aggregatorData","zeroAddress","aggregatorsRouterAbi","isToken","fly","formatUnits","parseUnits","zeroAddress","ChainId","aggregatorsRouterAbi","HaikuAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","aggregatorsFeeBps","proxyAggregatorsThroughVercel","referrer","rewardVault","BeraError","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","quoteBody","formatUnits","proxyPath","quoteData","formattedQuote","parseUnits","solveData","account","inputData","outputData","aggregatorData","zeroAddress","aggregatorsRouterAbi","haiku","formatUnits","ChainId","_getPreviewMethod","isMint","HoneyNativeAggregator","BaseAggregator","ChainId","getHoneyToken","tokenIn","tokenOut","honeyNativeState","args","isToken","isRedeem","coll","amount","publicClient","account","collaterals","InvalidArgumentError","assertPublicClient","hubOrderedCollaterals","collateral","BeraError","honeyVaultBalances","isBasketMode","getHoneyVaultsBalance","isBasketModeEnabled","collateralVaultBalance","collateralIdx","honeyFormattedAmountIn","formatUnits","quoteParams","quoteData","getHoneyPreview","honeyQuote","collateralsQuote","bignumber_js_default","payload","getSwapPayload","honeyNative","zeroAddress","ChainId","aggregatorsRouterAbi","KyberSwapAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","isTokenInNative","isTokenOutNative","tokenInAddress","tokenOutAddress","inputAmountAfterFees","url","routeData","formattedQuote","buildRouteBody","params","buildUrl","key","value","buildData","inputData","account","outputData","aggregatorData","zeroAddress","aggregatorsRouterAbi","kyberswap","zeroAddress","ChainId","aggregatorsRouterAbi","OogaboogaAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees","params","quote","formattedQuote","account","inputData","outputData","aggregatorData","zeroAddress","aggregatorsRouterAbi","oogabooga","zeroAddress","ChainId","aggregatorsRouterAbi","OpenOceanAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","publicClient","rewardVault","assertPublicClient","InvalidArgumentError","inputAmountAfterFees","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","gasPrice","quoteParams","quoteResponse","quoteData","isNotFound","message","RequestError","formattedQuote","inputData","outputData","aggregatorData","aggregatorsRouterAbi","openOcean","ChainId","wberaAbi","WBeraAggregator","BaseAggregator","ChainId","tokenIn","tokenOut","isToken","amount","isWrap","wberaAbi","wberaSwap","useSWRImmutable","useConfig","getPublicClient","erc4626Abi","getUnderlyingToken","token","wagmiConfig","isToken","publicClient","getPublicClient","assertPublicClient","address","erc4626Abi","getTokenInformation","e","err","initBeraError","useUnderlyingAsset","token","wagmiConfig","useConfig","useSWRImmutable","isToken","getUnderlyingToken","useSWRImmutable","zeroAddress","aggregatorsRouterAbi","usePublicClient","useAggregatorsRouterFeeBps","publicClient","usePublicClient","config","parseBaseArgs","swrResponse","useSWRImmutable","zeroAddress","aggregatorsRouter","fee","aggregatorsRouterAbi","useSWR","parseUnits","zeroAddress","useBeraWallet","usePublicClient","USE_AGGREGATORS_QUOTES_QUERY_KEY","getQueryKey","aggregator","account","args","feeBps","options","activeAggregators","isMAEnabled","name","usesMAContract","tokenIn","tokenOut","amount","slippage","referrer","rewardVault","parsedAmount","parseUnits","needsUnderlyingToken","getQueryFn","publicClient","proxyAggregatorsThroughVercel","aggregatorsFeeBps","underlyingToken","honeyCollaterals","raw_useSingleAggregatorQuote","useSWR","getAggregatorsSWROptions","err","key","config","revalidate","revalidateOpts","BeraError","BaseAggregator","RequestError","seconds","useSingleAggregatorQuote","useBeraWallet","useBeraFlag","usePublicClient","useAggregatorsRouterFeeBps","isToken","parseBaseArgs","zeroAddress","AGGREGATORS","oogabooga","fly","kyberswap","openOcean","haiku","enso","bex","honeyNative","erc4626Deposit","useAggregatorsQuotes","args","options","account","useBeraWallet","proxyAggregatorsThroughVercel","useBeraFlag","activeAggregators","publicClient","usePublicClient","feeBps","useAggregatorsRouterFeeBps","isWrapOrUnwrap","isToken","isBgtRedeem","defaultChainId","underlyingToken","useUnderlyingAsset","isNativeSwap","config","parseBaseArgs","isMAEnabled","zeroAddress","swrOptions","getAggregatorsSWROptions","sharedArgs","oogaBogaResult","raw_useSingleAggregatorQuote","flyResult","erc4626Result","kyberswapResult","openOceanResult","haikuResult","ensoResult","bexProtocol","useBexStatus","bexResult","wberaSwapResult","wberaSwap","bgtRedeemResult","bgtRedeem","honeyResult","results","i","useMemo","error","result","loadingAggregatorsNames","r","quotes","data","isLoading","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","balancerPoolCreationHelperAbi","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","erc20Abi","formatUnits","GetExploitedTokens","BEX_EXPLOITED_TOKEN_THRESHOLD","getIsTokenExploited","token","publicClient","args","bexSubgraphClient","getApolloClient","totalSupply","erc20Abi","balanceThreshold","bignumber_js_default","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","formatEther","isAddressEqual","useSWR","isAddress","zeroAddress","rewardVaultAbi","useBeraWallet","usePublicClient","useSWRImmutable","isAddress","zeroAddress","rewardVaultFactoryAbi","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","defaultChainId","usePublicClient","useTokenInformation","args","options","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","_","address","chainId","defaultChainId","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_js_default","price","formatEther","useMemo","parseUnits","zeroAddress","useSWR","useBeraWallet","useConfig","usePollAllowances","args","options","config","useConfig","account","useBeraWallet","QUERY_KEY","swrResponse","useSWR","items","getAllowances","calculateMaxAmountIn","amount","decimals","slippage","slippageInWei","parseUnits","useMultipleTokenApprovalsWithSlippage","tokenInput","options","items","useMemo","token","zeroAddress","bignumber_js_default","allowances","refresh","isLoading","usePollAllowances","allowance","item","isToken","BeraError","maxAmountIn","useMemo","useSWRImmutable","formatUnits","isAddress","usePublicClient","useSWRImmutable","isAddress","defaultChainId","usePublicClient","useMultipleTokenInformation","args","options","publicClient","usePublicClient","QUERY_KEY","defaultChainId","swrResponse","useSWRImmutable","addresses","chainId","assertPublicClient","address","isAddress","tk","getTokenInformation","useMemo","useSWR","isAddress","zeroAddress","defaultChainId","useContext","useTokens","context","useContext","TokenContext","BeraError","useTokenCurrentPrices","addressIn","options","tokenList","ensoTokens","useTokens","beraAddresses","useMemo","addresses","a","isAddress","tokenSet","token","isToken","zeroAddress","QUERY_KEY","apiResponse","useSWR","getTokenCurrentPrices","ensoMatchingPrices","ensoPricesMap","defaultChainId","address","price","data","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","balancerVaultAbi","useBeraWallet","usePublicClient","usePollPoolCreationRelayerApproval","options","account","useBeraWallet","publicClient","usePublicClient","QUERY_KEY","swrResponse","useSWR","assertPublicClient","config","parseBaseArgs","balancerVaultAbi","usePool","poolId","balancerApiPool","useApiPool","onChainPool","isOnChainPoolLoading","refreshOnChainPool","onChainPoolError","useOnChainPoolData","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","useMemo","useCallback","useMemo","defaultChainId","useTokenPrices","tokens","options","ensoTokens","useTokens","apiResponse","useTokenCurrentPrices","token","defaultChainId","data","useMemo","prices","tokenMap","chainId","address","price","tk","priceMap","map","item","getTokenPrice","useCallback","usePriceImpact","tokenIn","tokenOut","formattedAmountIn","formattedAmountOut","getTokenPrice","isLoading","useTokenPrices","useMemo","tokenInPrice","tokenOutPrice","computePriceImpact","useSWR","parseUnits","defaultChainId","useBeraWagmi","useBeraWallet","usePublicClient","formatUnits","encodeFunctionData","getAddress","morphoAbi","encodeFunctionData","erc20Abi","ethAddress","formatUnits","getAddress","zeroAddress","toEnsoAddress","address","zeroAddress","ethAddress","toBigIntOrUndefined","value","getTransactionsFromBundle","fromAddress","amountIn","tokenIn","chainId","ensoClient","bundle","publicClient","transactions","approvalRequest","requiresApproval","erc20Abi","approvalValue","bundleValue","getEnsoWalletTransactionsWithApproval","spender","getAddress","approval","currentAllowance","amountInBigInt","raw","formatUnits","approvalData","encodeFunctionData","computeSwapOutputRatio","slippage","slippageRatio","bignumber_js_default","ratio","InvalidArgumentError","computeRawCollateralToLoanPrice","formattedPrice","collateralToken","loanToken","getEnsoWalletV2Address","publicClient","ensoWalletV2Factory","accountAddress","ensoWalletV2FactoryAbi","getIsBendAuthorized","primaryAddress","ensoWalletV2Address","morphoAbi","assembleBendFlashloanTransactions","fromAddress","amountIn","tokenIn","bundle","isAuthorized","config","parseBaseArgs","ensoWalletFlashloanAdapter","assertDefined","ensoTransactions","approval","getEnsoWalletTransactionsWithApproval","transactions","encodeFunctionData","getAddress","FULL_REPAY_CLEANUP_BUFFER_BPS","BPS_DIVISOR","calculateDemultiplyCollateralAmount","repayAmount","collateralPriceInLoanAsset","collateralToken","loanToken","slippage","currentCollateral","swapOutputRatio","computeSwapOutputRatio","collateralPrice","bignumber_js_default","InvalidArgumentError","loanDecimalsMul","collateralDecimalsMul","flashloanCollateralRaw","getPositionEstimate","collateralToWithdraw","formatUnits","getBendDemultiplyBundle","fromAddress","marketId","primaryAddress","chainId","ensoClient","publicClient","currentDebt","ensoWalletV2Address","isAuthorized","assertAddress","assertPositive","rawRepayAmount","rawCurrentDebt","isFullRepayment","collateralAddress","toEnsoAddress","loanAddress","rawCleanupDebtAmountFromBps","rawFullRepaymentCleanupDebtAmount","rawTargetRepayForFlashloanQuote","isFlashloanCollateralClamped","shouldRunFullRepaymentCleanup","baseCallbackActions","cleanupStartIdx","fullRepaymentCleanupActions","callbackActions","bundleActions","bundle","transactions","assembleBendFlashloanTransactions","useSWR","getAddress","useBeraWallet","usePublicClient","useEnsoWalletV2Address","chainId","fromAddress","useBeraWallet","publicClient","usePublicClient","config","parseBaseArgs","ensoWalletV2Factory","useSWR","_","accountAddress","factory","assertPublicClient","getEnsoWalletV2Address","getAddress","useSWR","useBeraWallet","usePublicClient","useIsBendAuthorized","chainId","primaryAddress","ensoWalletV2Address","fromAddress","useBeraWallet","publicClient","usePublicClient","useSWR","_","accountAddress","assertPublicClient","getIsBendAuthorized","useBendDemultiply","collateralToken","loanToken","marketId","primaryAddress","repayAmount","slippage","chainId","collateralPriceInLoanAsset","currentCollateral","currentDebt","options","fromAddress","useBeraWallet","accountChainId","useBeraWagmi","chainIdToUse","defaultChainId","publicClient","usePublicClient","ensoWalletV2Address","useEnsoWalletV2Address","isAuthorized","useIsBendAuthorized","QUERY_KEY","useSWR","_","assertPublicClient","rawRepayAmount","parseUnits","rawCurrentCollateral","rawCurrentDebt","getBendDemultiplyBundle","getEnsoClient","useSWR","parseUnits","defaultChainId","useBeraWagmi","useBeraWallet","usePublicClient","calculateMultiplyBorrowAmount","rawSupplyCollateralAmount","rawCurrentCollateralAmount","rawCurrentBorrowAmount","formattedCollateralPriceInLoanAsset","collateralToken","loanToken","leverageMultiplier","slippage","normalizedLeverage","swapOutputRatio","computeSwapOutputRatio","formattedCollateralPrice","bignumber_js_default","InvalidArgumentError","rawCollateralToLoanPrice","computeRawCollateralToLoanPrice","targetLtv","rawCollateralBase","rawCurrentBorrow","denominator","requiredRawBorrow","rawBorrowAmount","getPositionEstimate","collateralDecimalsMul","loanDecimalsMul","rawSupplyCollateral","rawBorrow","rawLoopCollateral","finalFormattedCollateral","totalFormattedBorrow","getBendMultiplyBundle","fromAddress","marketId","primaryAddress","chainId","ensoClient","publicClient","ensoWalletV2Address","isAuthorized","assertAddress","collateralAddress","toEnsoAddress","loanAddress","CALLBACK_IDX_ROUTE_LOAN_TO_COLLATERAL","CALLBACK_IDX_BALANCE_COLLATERAL","depositOnlyActions","flashloanActions","bundleActions","bundle","transactions","assembleBendFlashloanTransactions","useBendMultiply","collateralToken","loanToken","marketId","primaryAddress","formattedSupplyCollateralAmount","formattedCurrentCollateralAmount","formattedCurrentBorrowAmount","leverageMultiplier","slippage","chainId","formattedCollateralPriceInLoanAsset","options","fromAddress","useBeraWallet","accountChainId","useBeraWagmi","chainIdToUse","defaultChainId","publicClient","usePublicClient","ensoWalletV2Address","useEnsoWalletV2Address","isAuthorized","useIsBendAuthorized","QUERY_KEY","useSWR","_","assertPublicClient","rawSupplyCollateralAmount","parseUnits","rawCurrentCollateralAmount","rawCurrentBorrowAmount","getBendMultiplyBundle","getEnsoClient","useSWR","formatEther","parseUnits","zeroAddress","berachainChainId","useBeraWallet","usePublicClient","ethAddress","zeroAddress","EnsoErc4626Aggregator","BaseAggregator","tokenIn","tokenOut","amount","slippage","account","zeroAddress","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","underlyingToken","assertAddress","ensoClient","getEnsoClient","ethAddress","zapTokenOut","bundleActions","offset","bundle","tokenOutAddress","ensoErc4626","useBendZapSupply","tokenIn","loanToken","bendVault","rewardVault","amount","slippage","options","getTokenPrice","useTokenPrices","swrResponse","useBendZapSupplyHelper","parseUnits","zapSupplyAmount","useGetConvertToAssets","priceImpact","usePriceImpact","isCrossChain","berachainChainId","nativeBalanceData","isNativeBalanceLoading","usePollBalance","zeroAddress","transactionValue","nativeBalance","hasInsufficientNativeBalance","nativeFee","formatEther","fromAddress","useBeraWallet","isEnabled","isToken","publicClientBeraChain","usePublicClient","useSWR","assertPublicClient","assertAddress","assertDefined","ensoErc4626","getPublicClient","useSWR","parseUnits","berachainChainId","useBeraWallet","useConfig","ethAddress","zeroAddress","getEnsoSwapBundle","fromAddress","amountIn","tokenIn","tokenOut","chainId","ensoClient","destinationChainId","slippage","publicClient","InvalidArgumentError","zeroAddress","ethAddress","bundleAction","bundle","transactions","getTransactionsFromBundle","useMemo","useSWR","useBeraWallet","useConfig","usePublicClient","usePollWalletBalances","args","options","publicClient","usePublicClient","wagmiConfig","useConfig","connectedAccount","useBeraWallet","tokenList","refresh","useTokens","wallet","tokens","useMemo","t","QUERY_KEY","swrResponse","useSWR","getWalletBalances","useEnsoSwapBundle","tokenIn","tokenOut","amount","slippage","fromAddress","useBeraWallet","wagmiConfig","useConfig","ensoClient","getEnsoClient","refreshBalances","usePollWalletBalances","isEnabled","swrResponse","useSWR","assertAddress","assertDefined","assertAmount","publicClient","getPublicClient","assertPublicClient","rawAmount","parseUnits","getEnsoSwapBundle","berachainChainId","useSWR","formatUnits","parseUnits","chainConfigs","defaultChainId","useBeraWallet","useZapStakeBera","inputToken","amount","underlyingToken","slippage","tokenOut","options","account","useBeraWallet","quoteAccount","chainConfigs","defaultChainId","QUERY_KEY","swrResponse","useSWR","rawAmount","parseUnits","ensoErc4626","priceImpactPercentage","usePriceImpact","formatUnits","useCallback","useEffect","useState","matter","encodeFunctionData","erc20Abi","parseAbiItem","toHex","beraChefAbi","rewardVaultAbi","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","bgtAbi","useBeraWallet","usePublicClient","useSWRImmutable","governanceAbi","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","governanceAbi","useBeraWallet","usePublicClient","useHasVoted","proposalId","wallet","account","useBeraWallet","publicClient","usePublicClient","address","useSWR","isAddress","assertPublicClient","config","parseBaseArgs","governanceAbi","useSWR","governanceTimelockAbi","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","i","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","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","governanceAbi","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","bgtAbi","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","governanceAbi","usePublicClient","ProposalStateMap","useProposalState","proposalId","governorAddress","publicClient","usePublicClient","useSWRImmutable","assertPublicClient","snapshot","governanceAbi","useSWR","governanceTimelockAbi","usePublicClient","TimelockOperationState","useProposalTimelockState","proposalTimelockId","timelockAddress","publicClient","usePublicClient","useSWR","assertPublicClient","snapshot","governanceTimelockAbi","useSWR","usePublicClient","formatEther","governanceAbi","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","useSWR","useBeraWallet","useConfig","usePublicClient","useHoneyBalances","publicClient","usePublicClient","account","useBeraWallet","collateralList","useHoneyConfig","wagmiConfig","useConfig","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_js_default","isLiquidityLowCollaterals","coll","vaultBalance","getRedeemMoreThanLiquidity","isRedeemMoreThanLiquidityCollaterals","amountToRedeem","isToken","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","useSWR","useHoneyGlobalData","response","useSWR","getHoneyGlobalData","dailyVolume","acc","curr","bignumber_js_default","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","bgtAbi","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","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","receiptTokenAddresses","account","version","options","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","assertPublicClient","receiptTokenAddress","getSWBeraWithdrawal","results","useSWR","isAddress","defaultChainId","usePublicClient","useRewardTokenToBeraRate","address","opt","QUERY_KEY","publicClient","usePublicClient","defaultChainId","useSWR","_","isAddress","InvalidArgumentError","assertPublicClient","getRewardTokenToBeraRate","useSWR","useSWR","erc20Abi","formatUnits","isAddress","beraChefAbi","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","dailyResolution","data","dailyData","lastDay","item","timestampMs","currentDay","currentDayStr","newTimestamp","useStakedAPR","range","swrResponse","useSWR","unsortedStakedBeraSnapshots","getStakedBeraSnapshots","dailyResolution","a","b","item","useMemo","useSWR","useBeraWallet","usePublicClient","useStakedData","stakingConfigs","window","useBeraFlag","publicClient","usePublicClient","account","useBeraWallet","receiptTokens","useMemo","config","inputTokens","aprKey","apr","useSWR","getStakedBeraAPR","walletBalances","isLoadingBalances","usePollWalletBalances","getTokenPrice","useTokenPrices","exchangeRatesKey","exchangeRates","assertPublicClient","token","getRewardTokenToBeraRate","balances","i","inputToken","stakedBalance","b","exchangeRate","inputTokenPrice","stakedAmount","bignumber_js_default","stakedAmountUsd","positionsKey","positionsRaw","isLoadingPositions","isValidatingPositions","stakingConfig","stakingToken","earnings","getEarnedStakedBeraVault","data","exchangeRateRaw","unrealisedGains","earnedAmount","earnedAmountUsd","useSWR","getStakingDailyAssets","address","range","now","startDayDate","config","parseBaseArgs","url","beraFetchJson","useStakedSnapshots","range","addresses","swrResponse","useSWR","sortedStakingDailyAssetsArray","address","unstakingDailyAssets","getStakingDailyAssets","sortedStakingDailyAssets","dailyResolution","a","b","acc","addressData","useSWR","usePublicClient","useStakingVaultsMetadata","vaults","publicClient","usePublicClient","blockTime","useBlockTime","QUERY_KEY","useSWR","assertPublicClient","vault","getSWBeraVaultMetadata","useSWR","usePublicClient","useTotalStakedAmount","vaultAddresses","publicClient","usePublicClient","swrResponse","useSWR","getTotalStakedAmount","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","useSWRImmutable","isAddress","zeroAddress","usePublicClient","useStakingTokenInformation","args","options","publicClient","usePublicClient","QUERY_KEY","isAddress","swrResponse","useSWRImmutable","_","address","isToken","zeroAddress","beraToken","getStakingTokenInformation","useTokenPrice","token","options","isLoading","priceMap","useTokenPrices","useSWR","erc20Abi","usePublicClient","useTotalSupply","address","publicClient","usePublicClient","useSWR","assertPublicClient","erc20Abi","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","useMemo","useSWR","useBeraWallet","usePublicClient","zeroAddress","beraChefAbi","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","beaconDepositAbi","bgtAbi","beraChefAbi","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","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","useSWR","useBeraWallet","formatIncentivesTokenMap","allRewards","tokenMap","item","reward","useUserClaimableIncentives","account","useBeraWallet","allRewardsResponse","useSWR","BeraError","getUserClaimableIncentives","allRewards","tokenMap","useMemo","BeraMonitoring","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"]}