@berachain/berajs 0.2.8-beta.9 → 0.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BeraError-_mQdkanr.d.cts → BeraError-7-A5JYy_.d.ts} +31 -2
- package/dist/{HoneyConfigProvider-DVP_9KZn.d.ts → HoneyConfigProvider-Dkj-_a5x.d.ts} +1 -1
- package/dist/{RequestError-BRIiJgHk.d.ts → RequestError-DBOIV65x.d.ts} +1 -1
- package/dist/abi/exports.mjs +4452 -2
- package/dist/actions/clients/exports.d.ts +2 -0
- package/dist/actions/clients/exports.mjs +12 -0
- package/dist/actions/exports.d.ts +104 -189
- package/dist/actions/exports.mjs +853 -2
- package/dist/actions/governance/exports.d.ts +140 -0
- package/dist/actions/governance/exports.mjs +226 -0
- package/dist/actions/server/exports.d.ts +13 -0
- package/dist/actions/server/exports.mjs +27 -0
- package/dist/chunk-3EARVV7K.mjs +414 -0
- package/dist/chunk-4Z4AK6SH.mjs +211 -0
- package/dist/chunk-75M6TF7M.mjs +25 -0
- package/dist/chunk-AFN4CVD3.mjs +326 -0
- package/dist/chunk-BGMRHTBQ.mjs +23 -0
- package/dist/chunk-CDFWPU2R.mjs +473 -0
- package/dist/chunk-CDK4YV3D.mjs +571 -0
- package/dist/chunk-DKMAIU74.mjs +62 -0
- package/dist/chunk-EXIUPSFN.mjs +86 -0
- package/dist/chunk-FFB5LFDW.mjs +35 -0
- package/dist/chunk-HQCOU6GY.mjs +243 -0
- package/dist/chunk-HSSJKHZ4.mjs +135 -0
- package/dist/chunk-J5I45WGQ.mjs +1769 -0
- package/dist/chunk-KQUMKB66.mjs +89 -0
- package/dist/chunk-NBYLMO2L.mjs +14 -0
- package/dist/chunk-NPBQLVL3.mjs +80 -0
- package/dist/chunk-O2NQFKJK.mjs +170 -0
- package/dist/chunk-QJIXTYTZ.mjs +4054 -0
- package/dist/chunk-SGIJVHZO.mjs +12 -0
- package/dist/chunk-SZ5C44L5.mjs +35 -0
- package/dist/chunk-WXXOISTU.mjs +96 -0
- package/dist/chunk-XIYN6AL6.mjs +160 -0
- package/dist/contexts/exports.d.ts +2 -2
- package/dist/contexts/exports.mjs +85 -2
- package/dist/enum/exports.d.ts +1 -1
- package/dist/enum/exports.mjs +46 -2
- package/dist/enum/governance/exports.d.ts +60 -0
- package/dist/enum/governance/exports.mjs +14 -0
- package/dist/errors/exports.d.ts +4 -3
- package/dist/errors/exports.mjs +48 -2
- package/dist/exports-BcUTGFUb.d.ts +40 -0
- package/dist/{getValidatorQueuedOperatorAddress-BcyxE9uw.d.ts → getValidatorQueuedOperatorAddress-Dw5KN5sh.d.ts} +2 -2
- package/dist/{global.d-5w_lvl2J.d.ts → global.d-BuGDKh4k.d.ts} +4 -240
- package/dist/hooks/exports.d.ts +69 -211
- package/dist/hooks/exports.mjs +7434 -4
- package/dist/hooks/governance/exports.d.ts +181 -0
- package/dist/hooks/governance/exports.mjs +888 -0
- package/dist/pol.d-CqPA9K6m.d.ts +142 -0
- package/dist/{txnEnum-7_o92X3N.d.cts → txnEnum-ByI5dtDi.d.ts} +2 -60
- package/dist/types/exports.d.ts +9 -9
- package/dist/types/exports.mjs +0 -1
- package/dist/types/governance/exports.d.ts +109 -0
- package/dist/types/governance/exports.mjs +0 -0
- package/dist/{useHoneySwapState-B494PQDl.d.ts → useHoneySwapState-vFmuFF0g.d.ts} +1 -1
- package/dist/utils/exports.d.ts +15 -6
- package/dist/utils/exports.mjs +825 -2
- package/package.json +49 -13
- package/src/actions/__test/transports.ts +61 -0
- package/src/actions/clients/exports.ts +4 -0
- package/src/actions/clients/getApolloClient.ts +58 -23
- package/src/actions/clients/getEnsoClient.ts +20 -9
- package/src/actions/dex/aggregators/enso/enso.ts +27 -17
- package/src/actions/dex/aggregators/enso/ensoErc4626.ts +2 -2
- package/src/actions/dex/aggregators/kyberswap.ts +18 -23
- package/src/actions/enso/__tests__/getEnsoUserTokensWithBalances.debug.test.ts +3 -6
- package/src/actions/exports.ts +4 -9
- package/src/actions/governance/exports.ts +9 -0
- package/src/actions/governance/getAllProposals.ts +10 -65
- package/src/actions/governance/getProposalDetails.ts +6 -33
- package/src/actions/governance/getProposalVotes.ts +8 -15
- package/src/actions/honey/getChartData.ts +27 -21
- package/src/actions/honey/getHoney24hVolume.ts +19 -22
- package/src/actions/pol/getAutoclaimedIncentives.ts +30 -0
- package/src/actions/pol/getBeraTokenTotalSupply.ts +45 -0
- package/src/actions/pol/getBgtIncentiveDistributorPaused.ts +35 -0
- package/src/actions/pol/getEarnedStakedBeraVault.ts +7 -11
- package/src/actions/pol/getGlobalData.ts +1 -0
- package/src/actions/pol/getHeroEarnVaults.ts +62 -0
- package/src/actions/pol/getIncentiveFeeClaimStats.ts +19 -38
- package/src/actions/pol/getSWBeraVaultMetadata.ts +1 -1
- package/src/actions/pol/getStakingDailyAssets.ts +7 -10
- package/src/actions/server/exports.ts +1 -0
- package/src/actions/server/getDailyValidatorBlockStats.ts +33 -0
- package/src/actions/tokens/getWalletBalances.integration.test.ts +3 -6
- package/src/actions/transactions/beraWriteContract.integration.test.ts +3 -6
- package/src/actions/validators/getDailyValidatorBlockStats.ts +25 -24
- package/src/actions/validators/getValidatorAnalytics.ts +20 -21
- package/src/actions/validators/getValidatorIncentiveDistribution.ts +33 -0
- package/src/enum/contracts.ts +1 -0
- package/src/enum/exports.ts +0 -1
- package/src/enum/governance/exports.ts +1 -0
- package/src/errors/BeraError.ts +47 -7
- package/src/errors/BeraTracing.unit.test.ts +65 -0
- package/src/errors/RequestError.ts +13 -1
- package/src/errors/exports.ts +5 -0
- package/src/errors/getRevertReason.integration.test.ts +3 -3
- package/src/errors/spanStatus.ts +78 -0
- package/src/errors/spanStatus.unit.test.ts +62 -0
- package/src/hooks/dex/useCreatePool.ts +1 -88
- package/src/hooks/dex/useOnChainPoolData.ts +27 -2
- package/src/hooks/dex/usePriceImpact.ts +12 -5
- package/src/hooks/enso/useBendDemultiply.ts +9 -1
- package/src/hooks/enso/useBendMultiply.ts +9 -1
- package/src/hooks/enso/useBendZapSupply.ts +26 -7
- package/src/hooks/enso/useEnsoSwapBundle.ts +17 -3
- package/src/hooks/enso/useEnsoUserTokensWithBalances.ts +13 -2
- package/src/hooks/exports.ts +2 -15
- package/src/hooks/governance/exports.ts +14 -0
- package/src/hooks/pol/useAutoclaimedIncentives.ts +49 -0
- package/src/hooks/pol/useStakedAPR.ts +2 -2
- package/src/hooks/pol/useStakedSnapshots.ts +5 -9
- package/src/hooks/validators/useValidator.ts +2 -0
- package/src/hooks/validators/useValidatorIncentiveDistribution.ts +39 -0
- package/src/types/bribe-boost.d.ts +8 -0
- package/src/types/exports.ts +0 -1
- package/src/types/governance/exports.ts +1 -0
- package/src/utils/beraFetch.ts +9 -3
- package/src/utils/exports.ts +1 -0
- package/src/utils/getServerSideClient.ts +4 -2
- package/src/utils/sanitizeRpcUrl.ts +22 -0
- package/src/utils/tracedTransport.ts +35 -0
- package/dist/BeraError-_mQdkanr.d.ts +0 -94
- package/dist/BexStatusProvider-DRymVlQf.d.cts +0 -70
- package/dist/HoneyConfigProvider-DfkjmzEf.d.cts +0 -390
- package/dist/RequestError-DSUzJ1Iy.d.cts +0 -144
- package/dist/abi/exports.cjs +0 -2
- package/dist/abi/exports.cjs.map +0 -1
- package/dist/abi/exports.d.cts +0 -6574
- package/dist/abi/exports.mjs.map +0 -1
- package/dist/actions/exports.cjs +0 -2
- package/dist/actions/exports.cjs.map +0 -1
- package/dist/actions/exports.d.cts +0 -1650
- package/dist/actions/exports.mjs.map +0 -1
- package/dist/chunk-45HIEVNI.cjs +0 -4
- package/dist/chunk-45HIEVNI.cjs.map +0 -1
- package/dist/chunk-47ILYVHC.mjs +0 -2
- package/dist/chunk-47ILYVHC.mjs.map +0 -1
- package/dist/chunk-575OK77P.mjs +0 -2
- package/dist/chunk-575OK77P.mjs.map +0 -1
- package/dist/chunk-5NVZG5N6.mjs +0 -2
- package/dist/chunk-5NVZG5N6.mjs.map +0 -1
- package/dist/chunk-6DIA6PXV.cjs +0 -2
- package/dist/chunk-6DIA6PXV.cjs.map +0 -1
- package/dist/chunk-6JJIZCVY.cjs +0 -2
- package/dist/chunk-6JJIZCVY.cjs.map +0 -1
- package/dist/chunk-7F72ZH4Q.mjs +0 -2
- package/dist/chunk-7F72ZH4Q.mjs.map +0 -1
- package/dist/chunk-AUA42YIG.mjs +0 -4
- package/dist/chunk-AUA42YIG.mjs.map +0 -1
- package/dist/chunk-BC2WX6O6.cjs +0 -2
- package/dist/chunk-BC2WX6O6.cjs.map +0 -1
- package/dist/chunk-CJOZC5Z2.cjs +0 -2
- package/dist/chunk-CJOZC5Z2.cjs.map +0 -1
- package/dist/chunk-D6L7LTA2.cjs +0 -2
- package/dist/chunk-D6L7LTA2.cjs.map +0 -1
- package/dist/chunk-DDEQFR3M.cjs +0 -2
- package/dist/chunk-DDEQFR3M.cjs.map +0 -1
- package/dist/chunk-GXV2JA36.mjs +0 -2
- package/dist/chunk-GXV2JA36.mjs.map +0 -1
- package/dist/chunk-ISYNEDET.mjs +0 -2
- package/dist/chunk-ISYNEDET.mjs.map +0 -1
- package/dist/chunk-JDDRTHFG.mjs +0 -2
- package/dist/chunk-JDDRTHFG.mjs.map +0 -1
- package/dist/chunk-JDZGYU5T.mjs +0 -2
- package/dist/chunk-JDZGYU5T.mjs.map +0 -1
- package/dist/chunk-LVOXBZMA.cjs +0 -2
- package/dist/chunk-LVOXBZMA.cjs.map +0 -1
- package/dist/chunk-MK5NS5B5.mjs +0 -2
- package/dist/chunk-MK5NS5B5.mjs.map +0 -1
- package/dist/chunk-NAXAZJJY.mjs +0 -2
- package/dist/chunk-NAXAZJJY.mjs.map +0 -1
- package/dist/chunk-NLVWRMGD.mjs +0 -2
- package/dist/chunk-NLVWRMGD.mjs.map +0 -1
- package/dist/chunk-OGBD5YOG.mjs +0 -2
- package/dist/chunk-OGBD5YOG.mjs.map +0 -1
- package/dist/chunk-OGJMSGB2.mjs +0 -2
- package/dist/chunk-OGJMSGB2.mjs.map +0 -1
- package/dist/chunk-OIYXOKTT.cjs +0 -2
- package/dist/chunk-OIYXOKTT.cjs.map +0 -1
- package/dist/chunk-OUD27MU7.cjs +0 -2
- package/dist/chunk-OUD27MU7.cjs.map +0 -1
- package/dist/chunk-PRLVZIKD.mjs +0 -2
- package/dist/chunk-PRLVZIKD.mjs.map +0 -1
- package/dist/chunk-Q2SNRLW3.cjs +0 -2
- package/dist/chunk-Q2SNRLW3.cjs.map +0 -1
- package/dist/chunk-REWME3FY.cjs +0 -2
- package/dist/chunk-REWME3FY.cjs.map +0 -1
- package/dist/chunk-RJN36GBU.mjs +0 -2
- package/dist/chunk-RJN36GBU.mjs.map +0 -1
- package/dist/chunk-RWOICHRW.cjs +0 -2
- package/dist/chunk-RWOICHRW.cjs.map +0 -1
- package/dist/chunk-S4CDSVLK.cjs +0 -2
- package/dist/chunk-S4CDSVLK.cjs.map +0 -1
- package/dist/chunk-SFEULGSX.cjs +0 -2
- package/dist/chunk-SFEULGSX.cjs.map +0 -1
- package/dist/chunk-WBTS6KFG.mjs +0 -2
- package/dist/chunk-WBTS6KFG.mjs.map +0 -1
- package/dist/chunk-WRFDB3QJ.cjs +0 -2
- package/dist/chunk-WRFDB3QJ.cjs.map +0 -1
- package/dist/chunk-XNJLSA6P.cjs +0 -2
- package/dist/chunk-XNJLSA6P.cjs.map +0 -1
- package/dist/contexts/exports.cjs +0 -2
- package/dist/contexts/exports.cjs.map +0 -1
- package/dist/contexts/exports.d.cts +0 -66
- package/dist/contexts/exports.mjs.map +0 -1
- package/dist/defaultFlags-D6KfkTZx.d.cts +0 -10
- package/dist/dex-C_BB0b0O.d.cts +0 -37
- package/dist/enum/exports.cjs +0 -2
- package/dist/enum/exports.cjs.map +0 -1
- package/dist/enum/exports.d.cts +0 -23
- package/dist/enum/exports.mjs.map +0 -1
- package/dist/errors/exports.cjs +0 -2
- package/dist/errors/exports.cjs.map +0 -1
- package/dist/errors/exports.d.cts +0 -327
- package/dist/errors/exports.mjs.map +0 -1
- package/dist/getValidatorQueuedOperatorAddress-Cql_D50j.d.cts +0 -562
- package/dist/global.d-B7IeayVX.d.cts +0 -474
- package/dist/honey-CYm0RWf4.d.cts +0 -14
- package/dist/hooks/exports.cjs +0 -4
- package/dist/hooks/exports.cjs.map +0 -1
- package/dist/hooks/exports.d.cts +0 -1734
- package/dist/hooks/exports.mjs.map +0 -1
- package/dist/polling-BKnyavLI.d.cts +0 -8
- package/dist/txnEnum-7_o92X3N.d.ts +0 -164
- package/dist/types/exports.cjs +0 -1
- package/dist/types/exports.cjs.map +0 -1
- package/dist/types/exports.d.cts +0 -90
- package/dist/types/exports.mjs.map +0 -1
- package/dist/useHoneySwapState-D6vpv19r.d.cts +0 -32
- package/dist/utils/exports.cjs +0 -2
- package/dist/utils/exports.cjs.map +0 -1
- package/dist/utils/exports.d.cts +0 -420
- package/dist/utils/exports.mjs.map +0 -1
- package/src/actions/dex/getIsTokenExploited.ts +0 -63
- package/src/hooks/dex/useExploitedTokens.ts +0 -57
package/dist/hooks/exports.cjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12;var _chunkRWOICHRWcjs = require('../chunk-RWOICHRW.cjs');var _chunk45HIEVNIcjs = require('../chunk-45HIEVNI.cjs');require('../chunk-OUD27MU7.cjs');var _chunkQ2SNRLW3cjs = require('../chunk-Q2SNRLW3.cjs');var _chunkBC2WX6O6cjs = require('../chunk-BC2WX6O6.cjs');require('../chunk-OIYXOKTT.cjs');require('../chunk-D6L7LTA2.cjs');require('../chunk-WRFDB3QJ.cjs');require('../chunk-XNJLSA6P.cjs');var _chunkREWME3FYcjs = require('../chunk-REWME3FY.cjs');var _chunkLVOXBZMAcjs = require('../chunk-LVOXBZMA.cjs');var _chunkCJOZC5Z2cjs = require('../chunk-CJOZC5Z2.cjs');var _chunk6DIA6PXVcjs = require('../chunk-6DIA6PXV.cjs');require('../chunk-DDEQFR3M.cjs');var _chunkSFEULGSXcjs = require('../chunk-SFEULGSX.cjs');require('../chunk-S4CDSVLK.cjs');var _chunk6JJIZCVYcjs = require('../chunk-6JJIZCVY.cjs');var _swr = require('swr'); var _swr2 = _interopRequireDefault(_swr);var _hooks = require('@berachain/wagmi/hooks');var zo=({sharesAmount:e,vaultAddress:t,vaultChainId:o},r)=>{let s=_hooks.usePublicClient.call(void 0, {chainId:o}),n=_swr2.default.call(void 0, s&&e&&t?["useGetConvertToAssets",e,t,o]:null,async([i,a,l])=>(_chunkLVOXBZMAcjs.c.call(void 0, s),_chunk45HIEVNIcjs.a.call(void 0, {sharesAmount:a,vaultAddress:l,publicClient:s})),{..._optionalChain([r, 'optionalAccess', _2 => _2.opts])});return{...n,refresh:()=>{n.mutate()}}};var _react = require('react');var _viem = require('viem');var _internal = require('@berachain/config/internal');var _berancersdk = require('@berachain-foundation/berancer-sdk');var _config = require('@berachain/config');var _vault = require('@berachain/abis/bex/vault');var Ds=300,Ls=.05,Ke=_berancersdk.SwapKind.GivenIn,qe= (_class =class extends _chunk45HIEVNIcjs.e{constructor(...args2) { super(...args2); _class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this); }__init() {this.name="Hub Pools"}__init2() {this.supportedChains=[_internal.ChainId.MAINNET,_internal.ChainId.BEPOLIA]}__init3() {this.url=_config.getUriFromLink.call(void 0, this.config.api)}__init4() {this.type="graphql"}convertZeroToWrapped(t){return _chunkSFEULGSXcjs.e.call(void 0, t,"BERA")?this.config.tokens.wbera:t}calculatePriceImpact(t){return t.error?(console.error("Swap price impact error",t),0):Number(t.priceImpact)}checkStalePrices({onChainAmount:t,sorPaths:o,sorAmount:r,queryData:s}){let n=Number.parseFloat(_viem.formatEther.call(void 0, t.scale18))/Number.parseFloat(r);if(Math.abs(1-n)>Ls){console.warn("SOR returned stale prices. Delta from return amount is more than 5%",{deltaFromSorAmount:n});let i=new (0, _chunk6JJIZCVYcjs.f)({reason:"SOR_STALE_PRICES",level:"warning",message:"SOR returned stale prices. Delta from return amount is more than 5%",extra:{deltaFromSorAmount:n,pools:o.map(a=>a.pools),onChainAmount:_viem.formatEther.call(void 0, t.scale18),sorAmount:r,queryData:s},fingerprint:["SOR_STALE_PRICES"]});_chunkLVOXBZMAcjs.g.captureException(i)}}async getQuote(t){let o=new (0, _chunk45HIEVNIcjs.f)(this.url,this.chainId),{tokenIn:r,tokenOut:s,amount:n,slippage:i,account:a=_viem.zeroAddress,publicClient:l}=t;this.assertChainSupport({tokenIn:r,tokenOut:s}),_chunkLVOXBZMAcjs.c.call(void 0, l);let u=_chunkSFEULGSXcjs.e.call(void 0, r,"BERA")||_chunkSFEULGSXcjs.e.call(void 0, s,"BERA"),m=new (0, _berancersdk.Token)(this.chainId,this.convertZeroToWrapped(r.address),r.decimals),p=new (0, _berancersdk.Token)(this.chainId,this.convertZeroToWrapped(s.address),s.decimals),c=_berancersdk.TokenAmount.fromRawAmount(m,n),{paths:d,priceImpact:f,returnAmount:y}=await o.sorSwapPaths.fetchSorSwapPaths({chainId:this.chainId,tokenIn:m.address,tokenOut:p.address,swapKind:Ke,swapAmount:c});if(!_optionalChain([d, 'optionalAccess', _3 => _3.length]))throw new (0, _chunk6JJIZCVYcjs.g)({response:void 0,endpoint:{url:this.url,name:this.name,type:this.type},reason:_chunk45HIEVNIcjs.e.PATH_NOT_FOUND_REASON,chainId:this.chainId,payload:{tokenIn:m.address,tokenOut:p.address,swapKind:Ke,swapAmount:c},message:"No swap paths returned from Balancer API"});let A=new (0, _berancersdk.Swap)({chainId:this.chainId,paths:d,swapKind:Ke,userData:"0x"}),h=await A.query(l.transport.url);if(!("expectedAmountOut"in h))throw new Error("No Bex paths found");return this.checkStalePrices({onChainAmount:h.expectedAmountOut,sorPaths:d,sorAmount:y,queryData:t}),{amountOut:h.expectedAmountOut.amount.toString(),amountIn:n,allowanceRequirements:this.parseAllowanceRequirements({tokenIn:r,rawAmount:n,spender:h.to}),name:this.name,priceImpactPercentage:this.calculatePriceImpact(f),swapFeeBps:0,getCalldata:({account:R})=>{let b=A.buildCall({slippage:_berancersdk.Slippage.fromPercentage(i.toString()),deadline:BigInt(Math.round(Date.now()/1e3)+Ds),queryOutput:h,sender:R,recipient:R,wethIsEth:u}),{args:P,functionName:w}=_viem.decodeFunctionData.call(void 0, {abi:_vault.vaultAbi,data:b.callData});return{params:P,functionName:w,abi:_vault.vaultAbi,address:b.to,value:b.value||BigInt(0)}}}}}, _class),$e=new qe;var ze= (_class2 =class extends _chunk45HIEVNIcjs.e{constructor(...args3) { super(...args3); _class2.prototype.__init5.call(this);_class2.prototype.__init6.call(this);_class2.prototype.__init7.call(this); }__init5() {this.name="RedeemBgt"}__init6() {this.supportedChains=[_internal.ChainId.MAINNET,_internal.ChainId.BEPOLIA]}__init7() {this.type="rpc"}checkChainSupport({tokenIn:t,tokenOut:o}){return super.checkChainSupport({tokenIn:t,tokenOut:o})?t.chainId===o.chainId&&_chunkSFEULGSXcjs.e.call(void 0, t,"BGT",{chainId:t.chainId})&&_chunkSFEULGSXcjs.e.call(void 0, o,"BERA"):!1}async getQuote({tokenIn:t,amount:o}){if(this.assertChainSupport({tokenIn:t,tokenOut:{..._chunkSFEULGSXcjs.b,chainId:t.chainId}}),!_chunkSFEULGSXcjs.e.call(void 0, t,"BGT",{config:this.config}))throw new (0, _chunk6JJIZCVYcjs.h)({property:"tokenIn",value:t,expected:"BGT",level:"warning"});return{amountOut:o,amountIn:o,allowanceRequirements:[],name:"RedeemBgt",isNativeSwap:!0,swapFeeBps:0}}}, _class2),tr=new ze;var _metaAggregatorV2 = require('@berachain/abis/meta-aggregator/metaAggregatorV2'); var _metaAggregatorV22 = _interopRequireDefault(_metaAggregatorV2);var je= (_class3 =class extends _chunk45HIEVNIcjs.e{constructor(...args4) { super(...args4); _class3.prototype.__init8.call(this);_class3.prototype.__init9.call(this);_class3.prototype.__init10.call(this);_class3.prototype.__init11.call(this);_class3.prototype.__init12.call(this); }__init8() {this.name="Enso"}__init9() {this.supportedChains=[_internal.ChainId.MAINNET]}__init10() {this.type="rest"}__init11() {this.needsAccountForQuote=!0}__init12() {this.notFoundMessages=["Could not build shortcuts for route","Could not quote shortcuts for route","Swap not found for a required underlying of defi route,","No route found from"]}async getQuote({tokenIn:t,tokenOut:o,amount:r,slippage:s,account:n=_viem.zeroAddress,aggregatorsFeeBps:i,proxyAggregatorsThroughVercel:a=!1,rewardVault:l}){this.assertChainSupport({tokenIn:t,tokenOut:o});let{tokenInAddress:u,tokenOutAddress:m,isTokenInNative:p,isTokenOutNative:c}=this.parseAddresses(t.address,o.address),d=this.getAmountAfterFees(r,i);this.url=a?"/api/aggregators?aggregator=enso":`${this.config.bex.aggregatorsProxyUrl}/enso/api/v1/shortcuts/route?`;let f=new URL(this.url);f.searchParams.set("fromAddress",this.config.bex.aggregatorsRouterExecutor),f.searchParams.set("receiver",this.config.bex.aggregatorsRouterExecutor),f.searchParams.set("spender",this.config.bex.aggregatorsRouterExecutor),f.searchParams.set("amountIn",d),f.searchParams.set("tokenIn",u),f.searchParams.set("tokenOut",m),f.searchParams.set("chainId",_internal.ChainId.MAINNET.toString()),f.searchParams.set("slippage",(Number(s)*100).toString()),f.searchParams.set("refundReceiver",n);let A=await(await this.fetch(f)).json(),h=this.getInputData({tokenIn:u,amountIn:r,isNative:p}),R={tokenOut:m,receiver:n,minAmountOut:this.getMinAmountOut(A.amountOut.toString(),s),isNative:c},b={aggregator:_optionalChain([A, 'access', _4 => _4.tx, 'optionalAccess', _5 => _5.to]),data:_optionalChain([A, 'access', _6 => _6.tx, 'optionalAccess', _7 => _7.data])};return{amountOut:A.amountOut.toString(),amountIn:r,allowanceRequirements:this.parseAllowanceRequirements({tokenIn:t,rawAmount:r,spender:this.config.bex.aggregatorsRouter}),name:this.name,swapFeeBps:i,getCalldata:()=>({params:[h,R,b,{rewardVault:_nullishCoalesce(l, () => (_viem.zeroAddress)),isSwapAndStake:!!l}],functionName:"swap",abi:_metaAggregatorV22.default,value:BigInt(p?r:"0"),address:this.config.bex.aggregatorsRouter})}}}, _class3),Ze=new je;var _wberaStakerVault = require('@berachain/abis/pol/wberaStakerVault');var Je= (_class4 =class extends _chunk45HIEVNIcjs.e{constructor(...args5) { super(...args5); _class4.prototype.__init13.call(this);_class4.prototype.__init14.call(this);_class4.prototype.__init15.call(this); }__init13() {this.name="Mint"}__init14() {this.supportedChains=null}__init15() {this.type="rpc"}checkChainSupport({tokenIn:t,tokenOut:o,underlyingToken:r}){return super.checkChainSupport({tokenIn:t,tokenOut:o,underlyingToken:r})&&!!r&&_optionalChain([r, 'optionalAccess', _8 => _8.chainId])===o.chainId&&(_chunkSFEULGSXcjs.e.call(void 0, r,t)||_chunkSFEULGSXcjs.e.call(void 0, t,"BERA")&&_chunkSFEULGSXcjs.e.call(void 0, o,"SWBERA"))}async getQuote({tokenIn:t,tokenOut:o,amount:r,underlyingToken:s,publicClient:n}){this.assertChainSupport({tokenIn:t,tokenOut:o,underlyingToken:s}),_chunkLVOXBZMAcjs.b.call(void 0, s,"underlyingToken"),_chunkLVOXBZMAcjs.c.call(void 0, n);let i=await n.readContract({address:o.address,abi:_viem.erc4626Abi,functionName:"convertToShares",args:[BigInt(r)]}),a=_chunkSFEULGSXcjs.e.call(void 0, o,"SWBERA")&&_chunkSFEULGSXcjs.e.call(void 0, t,"BERA");return{amountOut:i.toString(),amountIn:r,allowanceRequirements:a?[]:[{token:t,spender:o.address,amount:{raw:r,formatted:_viem.formatUnits.call(void 0, BigInt(r),t.decimals)}}],name:"Mint",isNativeSwap:!1,swapFeeBps:0,getCalldata:({account:l})=>a?{abi:_wberaStakerVault.wberaStakerVaultAbi,address:o.address,functionName:"depositNative",params:[BigInt(r),l],value:BigInt(r)}:{abi:_viem.erc4626Abi,address:o.address,functionName:"deposit",contractName:"others.erc4626",params:[BigInt(r),l],value:0n}}}}, _class4),Xe=new Je;var nr="https://api.fly.trade/aggregator",et= (_class5 =class extends _chunk45HIEVNIcjs.e{constructor(...args6) { super(...args6); _class5.prototype.__init16.call(this);_class5.prototype.__init17.call(this);_class5.prototype.__init18.call(this);_class5.prototype.__init19.call(this); }__init16() {this.name="Fly"}__init17() {this.supportedChains=[_internal.ChainId.MAINNET]}__init18() {this.type="rest"}__init19() {this.notFoundMessages=["Couldn't recognize to token","Couldn't recognize from token","There is not enough liquidity. Amount is too high.","Routes were not found"]}async getQuote({tokenIn:t,tokenOut:o,amount:r,slippage:s,account:n,aggregatorsFeeBps:i,rewardVault:a}){this.assertChainSupport({tokenIn:t,tokenOut:o});let{tokenInAddress:l,tokenOutAddress:u,isTokenInNative:m,isTokenOutNative:p}=this.parseAddresses(t.address,o.address),c=this.getAmountAfterFees(r,i),d=new URL(`${nr}/quote`);this.url=d.toString();let f=new URLSearchParams({fromTokenAddress:l,toTokenAddress:u,sellAmount:c,slippage:(s/100).toString(),gasless:"false",network:"berachain"});f.set("fromAddress",this.config.bex.aggregatorsRouterExecutor),f.set("toAddress",this.config.bex.aggregatorsRouterExecutor),d.search=f.toString();let A=await(await this.fetch(d)).json(),h={amountOut:A.amountOut,amountIn:r,allowanceRequirements:this.parseAllowanceRequirements({tokenIn:t,rawAmount:r,spender:this.config.bex.aggregatorsRouter}),name:this.name,swapFeeBps:_nullishCoalesce(i, () => (0))},R=new URL(`${nr}/transaction`);this.url=R.toString();let b=new URLSearchParams({quoteId:A.id,estimateGas:"false"});R.search=b.toString();let w=await(await this.fetch(R)).json();return{...h,getCalldata:({account:I})=>{let T=this.getInputData({tokenIn:l,amountIn:r,isNative:m}),S={tokenOut:u,receiver:I,minAmountOut:this.getMinAmountOut(A.amountOut,s),isNative:p},O={aggregator:_optionalChain([w, 'optionalAccess', _9 => _9.to]),data:_optionalChain([w, 'optionalAccess', _10 => _10.data])};return{params:[T,S,O,{rewardVault:_nullishCoalesce(a, () => (_viem.zeroAddress)),isSwapAndStake:!!a}],functionName:"swap",abi:_metaAggregatorV22.default,value:_chunkSFEULGSXcjs.e.call(void 0, t,"BERA")?BigInt(r):BigInt("0"),address:this.config.bex.aggregatorsRouter}}}}}, _class5),tt=new et;var ot= (_class6 =class extends _chunk45HIEVNIcjs.e{constructor(...args7) { super(...args7); _class6.prototype.__init20.call(this);_class6.prototype.__init21.call(this);_class6.prototype.__init22.call(this);_class6.prototype.__init23.call(this); }__init20() {this.name="Haiku"}__init21() {this.supportedChains=[_internal.ChainId.MAINNET]}__init22() {this.type="rest"}__init23() {this.notFoundMessages=["token not found","Token is not supported","No route found for the given input or the liquidity is not enough","Invalid input amount. Please ensure the total amount of input is greater than 0.001 USD"]}async getQuote({tokenIn:t,tokenOut:o,amount:r,slippage:s,aggregatorsFeeBps:n,proxyAggregatorsThroughVercel:i=!1,referrer:a,rewardVault:l}){if(t.decimals===void 0||o.decimals===void 0)throw new (0, _chunk6JJIZCVYcjs.f)({message:"Missing required params",level:"error"});this.assertChainSupport({tokenIn:t,tokenOut:o});let{tokenInAddress:u,tokenOutAddress:m,isTokenInNative:p,isTokenOutNative:c}=this.parseAddresses(t.address,o.address),d=this.getAmountAfterFees(r,n),f={intent:{allowancesMode:"approve",slippage:s/100,receiver:this.config.bex.aggregatorsRouterExecutor,input_positions:{[`bera:${u}`]:_viem.formatUnits.call(void 0, BigInt(d),t.decimals)},target_weights:{[`bera:${m}`]:1}}},y=a==="ZAP"?"zap-haiku":"haiku";this.url=i?"/api/aggregators?aggregator=haikuQuote":`${this.config.bex.aggregatorsProxyUrl}/${y}/v1/quoteIntent`;let h=await(await this.fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)})).json(),R={amountOut:_viem.parseUnits.call(void 0, h.balances[0].amount,o.decimals).toString(),amountIn:r,allowanceRequirements:this.parseAllowanceRequirements({tokenIn:t,rawAmount:r,spender:this.config.bex.aggregatorsRouter}),name:this.name,swapFeeBps:n};this.url=i?"/api/aggregators?aggregator=haikuSolve":`${this.config.bex.aggregatorsProxyUrl}/${y}/v1/solveIntent`;let P=await(await this.fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({quoteId:h.quoteId})})).json();return{...R,getCalldata:({account:w})=>{let I=this.getInputData({tokenIn:u,amountIn:r,isNative:p,isPermit2Approval:!0,permit2SpenderAddress:this.config.bex.haikuAgentAddress}),T={tokenOut:m,receiver:w,minAmountOut:this.getMinAmountOut(R.amountOut,s),isNative:c},S={aggregator:P.to,data:P.data};return{params:[I,T,S,{rewardVault:_nullishCoalesce(l, () => (_viem.zeroAddress)),isSwapAndStake:!!l}],functionName:"swap",abi:_metaAggregatorV22.default,value:BigInt(p?r:"0"),address:this.config.bex.aggregatorsRouter}}}}}, _class6),rt=new ot;function qs(e){return e?"previewMintHoney":"previewRedeemCollaterals"}var st= (_class7 =class extends _chunk45HIEVNIcjs.e{constructor(...args8) { super(...args8); _class7.prototype.__init24.call(this);_class7.prototype.__init25.call(this);_class7.prototype.__init26.call(this);_class7.prototype.__init27.call(this); }__init24() {this.name="Honey"}__init25() {this.supportedChains=[_internal.ChainId.MAINNET]}__init26() {this.type="rpc"}__init27() {this.honeyToken=_chunkSFEULGSXcjs.d.call(void 0, this)}isHoneyNativeSwap({tokenIn:t,tokenOut:o,honeyNativeState:r,...s}){if(!_optionalChain([r, 'optionalAccess', _11 => _11.collateralList]))return!1;let n=_chunkSFEULGSXcjs.e.call(void 0, o,"HONEY",s),i=_chunkSFEULGSXcjs.e.call(void 0, t,"HONEY",s);return!n&&!i?!1:r.collateralList.some(a=>_chunkSFEULGSXcjs.e.call(void 0, a.address,n?t:o))}checkChainSupport({tokenIn:t,tokenOut:o,honeyNativeState:r}){return super.checkChainSupport({tokenIn:t,tokenOut:o})&&t.chainId===o.chainId&&this.isHoneyNativeSwap({tokenIn:t.address,tokenOut:o.address,honeyNativeState:r})}async getQuote({tokenIn:t,tokenOut:o,amount:r,publicClient:s,account:n,honeyNativeState:i}){let{collateralList:a}=_nullishCoalesce(i, () => ({}));if(!a)throw new (0, _chunk6JJIZCVYcjs.h)({message:"Invalid Honey Context state",property:"collaterals",value:a,expected:"TokenWithOrder[]"});_chunkLVOXBZMAcjs.c.call(void 0, s),this.assertChainSupport({tokenIn:t,tokenOut:o});let l=_chunkSFEULGSXcjs.e.call(void 0, o,this.honeyToken),u=a,m=a.find(I=>_chunkSFEULGSXcjs.e.call(void 0, I.address,l?t.address:o.address));if(!m)throw new (0, _chunk6JJIZCVYcjs.f)({message:"This collateral is not part of the Honey protocol"});let[p,c]=await Promise.all([_chunk45HIEVNIcjs.F.call(void 0, {client:s,collateralList:[m]}),_chunk45HIEVNIcjs.K.call(void 0, {client:s,isMint:l,collateralList:a,latestPrices:void 0,isPythWrapperEnabled:!1})]);if(!p)throw new (0, _chunk6JJIZCVYcjs.f)({message:"Failed to fetch the Honey vault balances"});if(c)return;let d=p[0],f=m.order;u.length>1&&f!==0&&(u.splice(f,1),u.unshift(m));let y=_viem.formatUnits.call(void 0, BigInt(r),l?m.decimals:this.honeyToken.decimals),A={client:s,collateral:m,collateralList:a,amount:y,method:qs(l),latestPrices:void 0,isPythWrapperEnabled:!1},h=await _chunk45HIEVNIcjs.E.call(void 0, A);if(!h)throw new (0, _chunk6JJIZCVYcjs.f)({message:"Failed to fetch the Honey preview"});let{honey:R,collaterals:b}=h;if(!(l?!0:new (0, _chunk6DIA6PXVcjs.a)(_nullishCoalesce(_optionalChain([d, 'optionalAccess', _12 => _12.balance, 'access', _13 => _13.formatted]), () => ("0"))).gte(_viem.formatUnits.call(void 0, b[m.address],m.decimals))))return;let w=await _chunk45HIEVNIcjs.J.call(void 0, {state:{actionType:l?"mint":"redeem",fromAmount:[y],collaterals:u,isBasketModeEnabled:!1},collateralList:u,publicClient:s,priceFeedMap:void 0,isPythWrapperEnabled:!1});if(!w&&n)throw new (0, _chunk6JJIZCVYcjs.f)({message:"Failed to fetch the Honey swap payload"});return{amountIn:r,amountOut:l?R.toString():b[m.address].toString(),allowanceRequirements:this.parseAllowanceRequirements({tokenIn:t,rawAmount:r,spender:this.config.bex.aggregatorsRouter}),name:"Honey",swapFeeBps:0,getCalldata:({account:I})=>w({account:I})}}}, _class7),nt=new st;var at= (_class8 =class extends _chunk45HIEVNIcjs.e{constructor(...args9) { super(...args9); _class8.prototype.__init28.call(this);_class8.prototype.__init29.call(this);_class8.prototype.__init30.call(this);_class8.prototype.__init31.call(this); }__init28() {this.name="KyberSwap"}__init29() {this.supportedChains=[_internal.ChainId.MAINNET]}__init30() {this.type="rest"}__init31() {this.notFoundMessages=["token not found","route not found","amountIn is greater than max allowed"]}async getQuote({tokenIn:t,tokenOut:o,amount:r,slippage:s,aggregatorsFeeBps:n,proxyAggregatorsThroughVercel:i=!1,rewardVault:a}){this.assertChainSupport({tokenIn:t,tokenOut:o});let{isTokenInNative:l,isTokenOutNative:u,tokenInAddress:m,tokenOutAddress:p}=this.parseAddresses(t.address,o.address),c=this.getAmountAfterFees(r,n);this.url=i?"/api/aggregators?aggregator=kyberswapRoutes":`${this.config.bex.aggregatorsProxyUrl}/kyberswap/berachain/api/v1/routes`;let d=new URL(this.url);d.searchParams.set("tokenIn",m),d.searchParams.set("tokenOut",p),d.searchParams.set("amountIn",c),d.searchParams.set("slippageTolerance",(s/100).toString()),d.searchParams.set("to",this.config.bex.aggregatorsRouterExecutor),d.searchParams.set("clientData",JSON.stringify({source:"berachain"}));let y=await(await this.fetch(d)).json(),A={amountOut:y.data.routeSummary.amountOut,amountIn:r,name:this.name,swapFeeBps:n,allowanceRequirements:this.parseAllowanceRequirements({tokenIn:t,rawAmount:r,spender:this.config.bex.aggregatorsRouter})},h={routeSummary:y.data.routeSummary,sender:this.config.bex.aggregatorsRouterExecutor,recipient:this.config.bex.aggregatorsRouterExecutor,slippageTolerance:s*100,deadline:Math.floor(Date.now()/1e3)+300,source:"berachain"},R=d.searchParams.entries(),b=new URL(i?"/api/aggregators?aggregator=kyberswapBuild":`${this.config.bex.aggregatorsProxyUrl}/kyberswap/berachain/api/v1/route/build`);for(let[T,S]of R)b.searchParams.set(T,S);let w=await(await this.fetch(b,{method:"POST",body:JSON.stringify(h)})).json(),I=this.getInputData({tokenIn:m,amountIn:r,isNative:l});return{...A,getCalldata:({account:T})=>{let S={tokenOut:p,receiver:T,minAmountOut:this.getMinAmountOut(A.amountOut,s),isNative:u},O={aggregator:w.data.routerAddress,data:w.data.data};return{params:[I,S,O,{rewardVault:_nullishCoalesce(a, () => (_viem.zeroAddress)),isSwapAndStake:!!a}],functionName:"swap",abi:_metaAggregatorV22.default,value:BigInt(l?r:"0"),address:this.config.bex.aggregatorsRouter}}}}}, _class8),it=new at;var lt= (_class9 =class extends _chunk45HIEVNIcjs.e{constructor(...args10) { super(...args10); _class9.prototype.__init32.call(this);_class9.prototype.__init33.call(this);_class9.prototype.__init34.call(this); }__init32() {this.name="Oogabooga"}__init33() {this.supportedChains=[_internal.ChainId.MAINNET]}__init34() {this.type="rest"}async getQuote({tokenIn:t,tokenOut:o,amount:r,slippage:s,aggregatorsFeeBps:n,proxyAggregatorsThroughVercel:i=!1,rewardVault:a}){this.assertChainSupport({tokenIn:t,tokenOut:o});let{tokenInAddress:l,tokenOutAddress:u,isTokenInNative:m,isTokenOutNative:p}=this.parseAddresses(t.address,o.address),c=this.getAmountAfterFees(r,n),d=new URLSearchParams({tokenIn:l,tokenOut:u,amount:c,slippage:(s/100).toString(),to:this.config.bex.aggregatorsRouterExecutor,referrer:this.config.bex.aggregatorsRouter});this.url=i?`/api/aggregators?aggregator=oogabooga&${d.toString()}`:`${this.config.bex.aggregatorsProxyUrl}/oogabooga/v1/swap?${d.toString()}`;let y=await(await this.fetch(this.url)).json(),A={amountOut:y.assumedAmountOut,amountIn:r,allowanceRequirements:this.parseAllowanceRequirements({tokenIn:t,spender:this.config.bex.aggregatorsRouter,rawAmount:r}),name:this.name,priceImpactPercentage:y.priceImpact,swapFeeBps:n};return{...A,getCalldata:({account:h})=>{let R=this.getInputData({tokenIn:l,amountIn:r,isNative:m}),b={tokenOut:u,receiver:h,minAmountOut:this.getMinAmountOut(A.amountOut,s),isNative:p},P={aggregator:_optionalChain([y, 'access', _14 => _14.tx, 'optionalAccess', _15 => _15.to]),data:_optionalChain([y, 'access', _16 => _16.tx, 'optionalAccess', _17 => _17.data])};return{params:[R,b,P,{rewardVault:_nullishCoalesce(a, () => (_viem.zeroAddress)),isSwapAndStake:!!a}],functionName:"swap",abi:_metaAggregatorV22.default,value:BigInt(m?r:"0"),address:this.config.bex.aggregatorsRouter}}}}}, _class9),ut=new lt;var pt= (_class10 =class extends _chunk45HIEVNIcjs.e{constructor(...args11) { super(...args11); _class10.prototype.__init35.call(this);_class10.prototype.__init36.call(this);_class10.prototype.__init37.call(this);_class10.prototype.__init38.call(this);_class10.prototype.__init39.call(this); }__init35() {this.name="OpenOcean"}__init36() {this.supportedChains=[_internal.ChainId.MAINNET]}__init37() {this.type="rest"}__init38() {this.url="https://open-api.openocean.finance/v4/bera/swap"}__init39() {this.notFoundMessages=["No avail liquidity for the pair"]}async getQuote({tokenIn:t,tokenOut:o,amount:r,slippage:s,account:n=_viem.zeroAddress,aggregatorsFeeBps:i,publicClient:a,rewardVault:l}){if(_chunkLVOXBZMAcjs.c.call(void 0, a),!t.decimals)throw new (0, _chunk6JJIZCVYcjs.h)({property:"tokenIn.decimals",value:t.decimals,expected:"number",chainId:this.chainId});this.assertChainSupport({tokenIn:t,tokenOut:o});let u=this.getAmountAfterFees(r,i),{tokenInAddress:m,tokenOutAddress:p,isTokenInNative:c,isTokenOutNative:d}=this.parseAddresses(t.address,o.address),f=(await a.getGasPrice()).toString(),y=new URLSearchParams({chain:_internal.ChainId.MAINNET.toString(),inTokenAddress:m,outTokenAddress:p,amountDecimals:u,slippage:s<.01?"0.01":s.toString(),account:this.config.bex.aggregatorsRouterExecutor,referrer:this.config.bex.aggregatorsRouter,gasPrice:f}),A=await this.fetch(`${this.url}?${y.toString()}`),h=await A.json();if(h.code!==200||!h.data){let b=this.notFoundMessages.some(P=>h.error.includes(P));throw new (0, _chunk6JJIZCVYcjs.g)({response:A,endpoint:{url:this.url,name:this.name,type:this.type},cause:h,reason:b?_chunk45HIEVNIcjs.e.PATH_NOT_FOUND_REASON:h.error})}let R={amountOut:h.data.outAmount,amountIn:r,allowanceRequirements:this.parseAllowanceRequirements({tokenIn:t,rawAmount:r,spender:this.config.bex.aggregatorsRouter}),name:this.name,swapFeeBps:i};return{...R,getCalldata:({account:b})=>{let P=this.getInputData({tokenIn:m,amountIn:r,isNative:c}),w={tokenOut:p,receiver:b,minAmountOut:this.getMinAmountOut(R.amountOut,s),isNative:d},I={aggregator:h.data.to,data:h.data.data};return{params:[P,w,I,{rewardVault:_nullishCoalesce(l, () => (_viem.zeroAddress)),isSwapAndStake:!!l}],functionName:"swap",abi:_metaAggregatorV22.default,value:BigInt(c?r:"0"),address:this.config.bex.aggregatorsRouter}}}}}, _class10),mt=new pt;var _wbera = require('@berachain/abis/wbera');var dt= (_class11 =class extends _chunk45HIEVNIcjs.e{constructor(...args12) { super(...args12); _class11.prototype.__init40.call(this);_class11.prototype.__init41.call(this);_class11.prototype.__init42.call(this); }__init40() {this.name="Wrap"}__init41() {this.supportedChains=[_internal.ChainId.MAINNET,_internal.ChainId.BEPOLIA]}__init42() {this.type="rpc"}checkChainSupport({tokenIn:t,tokenOut:o}){return t.chainId!==o.chainId||!super.checkChainSupport({tokenIn:t,tokenOut:o})?!1:_chunkSFEULGSXcjs.e.call(void 0, t,"BERA")&&_chunkSFEULGSXcjs.e.call(void 0, o,"WBERA")||_chunkSFEULGSXcjs.e.call(void 0, t,"WBERA")&&_chunkSFEULGSXcjs.e.call(void 0, o,"BERA")}async getQuote({tokenIn:t,tokenOut:o,amount:r}){this.assertChainSupport({tokenIn:t,tokenOut:o});let s=_chunkSFEULGSXcjs.e.call(void 0, t,"BERA")&&_chunkSFEULGSXcjs.e.call(void 0, o,"WBERA");return{amountOut:r,amountIn:r,allowanceRequirements:[],name:s?"Wrap":"Unwrap",isNativeSwap:!0,swapFeeBps:0,getCalldata:()=>s?{abi:_wbera.wberaAbi,address:this.config.tokens.wbera,functionName:"deposit",params:[],value:BigInt(r)}:{abi:_wbera.wberaAbi,address:this.config.tokens.wbera,functionName:"withdraw",params:[BigInt(r)],value:BigInt(0)}}}}, _class11),ct=new dt;var _immutable = require('swr/immutable'); var _immutable2 = _interopRequireDefault(_immutable);var _core = require('@wagmi/core');async function mr({token:e,wagmiConfig:t}){try{if(_chunkSFEULGSXcjs.e.call(void 0, e,"BERA"))return null;let o=_core.getPublicClient.call(void 0, t,{chainId:e.chainId});_chunkLVOXBZMAcjs.c.call(void 0, o);let r=await o.readContract({address:e.address,abi:_viem.erc4626Abi,functionName:"asset"});return _chunk45HIEVNIcjs.y.call(void 0, {address:r,publicClient:o,chainId:e.chainId})}catch(o){let r=_chunkLVOXBZMAcjs.a.call(void 0, {cause:o});if(r.reason==='The contract function "asset" reverted.')return null;throw r}}function dr({token:e}){let t=_hooks.useConfig.call(void 0, );return _immutable2.default.call(void 0, e&&t&&!_chunkSFEULGSXcjs.e.call(void 0, e,"BERA")?["useUnderlyingAsset",e]:null,async([,o])=>mr({token:o,wagmiConfig:t}))}var ke=()=>{let e=_hooks.usePublicClient.call(void 0, ),{config:t}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:_optionalChain([e, 'access', _18 => _18.chain, 'optionalAccess', _19 => _19.id])}),o=_immutable2.default.call(void 0, e&&t.bex.aggregatorsRouter&&t.bex.aggregatorsRouter!==_viem.zeroAddress?["useAggregatorsRouterFeeBps",t.bex.aggregatorsRouter]:null,async([,r])=>{let s=await e.readContract({address:r,abi:_metaAggregatorV22.default,functionName:"SWAP_FEE_RATE"});return Number(s)});return{...o,refresh:o.mutate}};var cr="useAggregatorsQuotes";function gn({aggregator:e,account:t,args:o,feeBps:r,options:s,activeAggregators:n,isMAEnabled:i}){if(_optionalChain([s, 'optionalAccess', _20 => _20.opts, 'optionalAccess', _21 => _21.isEnabled])!==void 0&&!_optionalChain([s, 'optionalAccess', _22 => _22.opts, 'optionalAccess', _23 => _23.isEnabled])||!Number(o.amount)||!e.checkChainSupport({tokenIn:o.tokenIn,tokenOut:o.tokenOut,underlyingToken:o.underlyingToken,honeyNativeState:o.honeyNativeState}))return null;let a=e.name,l=!["Hub Pools","Honey","Wrap","Unwrap","Mint"].includes(a);if(!i&&l)return null;let{tokenIn:u,tokenOut:m,amount:p,slippage:c,referrer:d,rewardVault:f}=o,y=_viem.parseUnits.call(void 0, p,u.decimals).toString();if(!(e.name==="Wrap"||e.name==="RedeemBgt"||e.name==="Honey"||!n||n.includes(a.toLowerCase().replaceAll(" ","")))||e.name==="Honey"&&_optionalChain([o, 'access', _24 => _24.honeyNativeState, 'optionalAccess', _25 => _25.protocol, 'access', _26 => _26.isPaused]))return null;let h=e.name==="Mint"||e.name==="Enso (Mint)";return l&&r===void 0?null:[cr,a,u,m,y,c,e.needsAccountForQuote?t:void 0,l?r:0,d,f,h?o.underlyingToken:void 0,e.name==="Honey"?_optionalChain([o, 'access', _27 => _27.honeyNativeState, 'optionalAccess', _28 => _28.collateralList]):void 0]}function yn({aggregator:e,publicClient:t,proxyAggregatorsThroughVercel:o}){return async([,,r,s,n,i,a,l,u,m,p,c])=>e.getQuote({tokenIn:r,tokenOut:s,amount:n,slippage:i,account:a,aggregatorsFeeBps:l,publicClient:t,proxyAggregatorsThroughVercel:o,referrer:u,rewardVault:m,underlyingToken:p,honeyNativeState:{collateralList:_nullishCoalesce(c, () => ([]))}})}function Q({feeBps:e,publicClient:t,account:o,proxyAggregatorsThroughVercel:r,activeAggregators:s,isMAEnabled:n,...i},a){return _swr2.default.call(void 0, gn({aggregator:i.aggregator,account:o,args:i,feeBps:e,options:a,activeAggregators:s,isMAEnabled:n}),yn({aggregator:i.aggregator,proxyAggregatorsThroughVercel:r,publicClient:t}),_optionalChain([a, 'optionalAccess', _29 => _29.opts]))}function ft(e){return{refreshInterval:1e4,errorRetryCount:3,..._optionalChain([e, 'optionalAccess', _30 => _30.opts]),onErrorRetry(t,o,r,s,n){if(_optionalChain([e, 'optionalAccess', _31 => _31.opts, 'optionalAccess', _32 => _32.onErrorRetry, 'optionalCall', _33 => _33(t,o,r,s,n)]),!(t instanceof _chunk6JJIZCVYcjs.f&&t.reason===_chunk45HIEVNIcjs.e.PATH_NOT_FOUND_REASON)){if(t instanceof _chunk6JJIZCVYcjs.g&&t.statusCode===403){console.warn(o[1],"returned error 403, stopping retries");return}n.retryCount>(_nullishCoalesce(r.errorRetryCount, () => (3)))||setTimeout(()=>{s()},_nullishCoalesce(r.errorRetryInterval, () => (_chunk6DIA6PXVcjs.m.call(void 0, 10))))}}}}function An(e,t){let{address:o}=_hooks.useBeraWallet.call(void 0, ),r=_chunkQ2SNRLW3cjs.c.call(void 0, "proxyAggregatorsThroughVercel"),s=_chunkQ2SNRLW3cjs.c.call(void 0, "aggregators"),n=_hooks.usePublicClient.call(void 0, ),{data:i}=ke();if(e.aggregator.name!=="Wrap"&&!((_chunkSFEULGSXcjs.e.call(void 0, e.tokenIn.address,"BERA")||_chunkSFEULGSXcjs.e.call(void 0, e.tokenIn.address,"WBERA"))&&(_chunkSFEULGSXcjs.e.call(void 0, e.tokenOut.address,"BERA")||_chunkSFEULGSXcjs.e.call(void 0, e.tokenOut.address,"WBERA"))))return null;let{config:a}=_chunkSFEULGSXcjs.a.call(void 0, e),l=a.bex.aggregatorsRouter!==_viem.zeroAddress;return Q({...e,aggregator:e.aggregator,feeBps:i,activeAggregators:s,account:o,isMAEnabled:l,publicClient:n,proxyAggregatorsThroughVercel:r},{...t,opts:ft(t)})}var Pn=[ut,tt,it,mt,rt,Ze,$e,nt,Xe];function Zf(e,t){let{address:o}=_hooks.useBeraWallet.call(void 0, ),r=_chunkQ2SNRLW3cjs.c.call(void 0, "proxyAggregatorsThroughVercel"),s=_chunkQ2SNRLW3cjs.c.call(void 0, "aggregators"),n=_hooks.usePublicClient.call(void 0, ),{data:i}=ke(),a=(_chunkSFEULGSXcjs.e.call(void 0, e.tokenIn.address,"BERA")||_chunkSFEULGSXcjs.e.call(void 0, e.tokenIn.address,"WBERA"))&&(_chunkSFEULGSXcjs.e.call(void 0, e.tokenOut.address,"BERA")||_chunkSFEULGSXcjs.e.call(void 0, e.tokenOut.address,"WBERA")),l=_chunkSFEULGSXcjs.e.call(void 0, e.tokenIn.address,"BGT",{chainId:_internal.defaultChainId}),{data:u}=dr({token:e.tokenOut}),m=a||l,{config:p}=_chunkSFEULGSXcjs.a.call(void 0, e),c=p.bex.aggregatorsRouter!==_viem.zeroAddress,d=ft(t),f={activeAggregators:s,isMAEnabled:c,underlyingToken:u,isNativeSwap:m,account:o,publicClient:n,proxyAggregatorsThroughVercel:r,feeBps:i},y=Q({...f,...e,aggregator:ut},{opts:d}),A=Q({...f,...e,aggregator:tt},{opts:d}),h=Q({...f,...e,aggregator:Xe},{opts:d}),R=Q({...f,...e,aggregator:it},{opts:d}),b=Q({...f,...e,aggregator:mt},{opts:d}),P=Q({...f,...e,aggregator:rt},{opts:d}),w=Q({...f,...e,aggregator:Ze},{opts:d}),{protocol:I}=_chunkQ2SNRLW3cjs.e.call(void 0, ),T=Q({...f,...e,aggregator:$e},{opts:{...d,isEnabled:I.isPaused===!1}}),S=Q({...f,...e,aggregator:ct}),O=Q({...f,...e,aggregator:tr},{opts:d}),U=Q({...f,...e,aggregator:nt},{opts:d}),v=a?[S]:l?[O]:[y,h,A,R,b,P,w,U,I.isPaused===!1?T:null].filter(M=>M!==null);return{..._react.useMemo.call(void 0, ()=>{let M=v.reduce((D,q)=>D||q.error,void 0),$=v.map((D,q)=>D.isLoading?m?ct.name:Pn[q].name:null).filter(Boolean),F=v.filter(D=>D!==void 0&&!D.isLoading&&!D.error&&_optionalChain([D, 'access', _34 => _34.data, 'optionalAccess', _35 => _35.amountOut])).map(({data:D})=>D),G=F.length===0&&$.length>0;return{quotes:F,loadingAggregatorsNames:$,isLoading:G,error:M}},[v]),refresh:()=>v.map(M=>M.mutate())}}var In=({query:e}={})=>["useAllUserPools",e],fr= exports.useAllUserPools =(e,t)=>{let o=_swr2.default.call(void 0, In({query:e}),async([r,s])=>_chunk45HIEVNIcjs.g.call(void 0, {...s,fetchPolicy:"no-cache"}),{refreshInterval:18e4,..._optionalChain([t, 'optionalAccess', _36 => _36.opts])});return{...o,refresh:()=>{o.mutate()}}};var Sn=({poolId:e,account:t})=>e?["usePool-api",e,t]:null;function gr({poolId:e,account:t}){let o=_swr2.default.call(void 0, Sn({poolId:e,account:t}),async([,r,s])=>{if(s&&!_viem.isAddress.call(void 0, s))throw new (0, _chunk6JJIZCVYcjs.h)({property:"account",value:s,expected:"Address"});return _chunk45HIEVNIcjs.h.call(void 0, {poolId:r,account:s})},{refreshInterval:1e5});return{...o,refresh:()=>{o.mutate()}}}var _poolCreationHelper = require('@berachain/abis/bex/poolCreationHelper');var _subgraph = require('@berachain/graphql/dex/subgraph');var gt=e=>[...e].sort((t,o)=>t.address.toLowerCase().localeCompare(o.address.toLowerCase())),Ar=e=>e.length===0?"":gt(e).map(t=>t.symbol).join(" | "),br=(e,t,o)=>{let r;return o===_berancersdk.PoolType.ComposableStable?r="STABLE":r=o.toString().toUpperCase(),o===_berancersdk.PoolType.Weighted?t.length===0?"":`${gt(e).map((s,n)=>{let i=t[n];return`${(Number.parseFloat(_viem.formatUnits.call(void 0, i,18))*100).toFixed(0)}${s.symbol}`}).join("-")}-${r}`:`${gt(e).map(s=>s.symbol).join("-")}-${r}`};var Ln=.005,Un= exports.OracleMode =(o=>(o.None="None",o.Custom="Custom",o))(Un||{}),Hn=({poolCreationHelper:e,poolCreateTokens:t,initialLiquidityTokens:o,swapFeePercentage:r,salt:s,poolName:n,poolSymbol:i,owner:a,amplification:l,oracles:u,message:m,actionType:p,gasLimit:c=_chunk6DIA6PXVcjs.j})=>{let d=t.map(w=>w.address.toLowerCase()).sort((w,I)=>w<I?-1:1),f=d.map(w=>{let I=o.find(v=>v.address.toLowerCase()===w||_chunkSFEULGSXcjs.e.call(void 0, w,"WBERA")&&_chunkSFEULGSXcjs.e.call(void 0, v.address,"BERA")),T=I?_viem.parseUnits.call(void 0, I.amount,I.decimals):0n,S=u.find(v=>v.tokenAddress.toLowerCase()===w.toLowerCase()),O=S?S.address:_viem.zeroAddress,U=BigInt(S?S.cacheDuration:100);return{amountIn:T,rateProvider:O,cacheDuration:U}}),y=f.map(w=>w.amountIn),A=f.map(w=>w.rateProvider),h=f.map(w=>w.cacheDuration),R=o.findIndex(w=>_chunkSFEULGSXcjs.e.call(void 0, w.address,"BERA")),b=R!==-1?_viem.parseUnits.call(void 0, o[R].amount,o[R].decimals):0n,P=b>0n;return{address:e,abi:_poolCreationHelper.poolCreationHelperAbi,functionName:"createAndJoinStablePool",params:[n,i,d,BigInt(l),A,h,!1,r,y,a,s,P],message:m,actionType:p,value:b,gasLimit:c,track:{eventName:"hub_pool_create",eventData:{poolName:n,poolSymbol:i}}}},Nn=({poolCreationHelper:e,poolCreateTokens:t,initialLiquidityTokens:o,normalizedWeights:r,swapFeePercentage:s,salt:n,poolName:i,poolSymbol:a,owner:l,message:u,actionType:m,gasLimit:p=_chunk6DIA6PXVcjs.j})=>{let c=[],d=[],f=[],y=[];t.map((R,b)=>({createToken:R.address,joinToken:o[b].address,weight:r[b],amountIn:_viem.parseUnits.call(void 0, o[b].amount,o[b].decimals)})).sort((R,b)=>R.createToken.toLowerCase()<b.createToken.toLowerCase()?-1:1).forEach(R=>{c.push(R.createToken),d.push(R.joinToken),f.push(R.weight),y.push(R.amountIn)});let A=d.indexOf(_viem.zeroAddress),h=A!==-1?y[A]:0n;return{address:e,abi:_poolCreationHelper.poolCreationHelperAbi,functionName:"createAndJoinWeightedPool",params:[i,a,c,d,f,Array(c.length).fill(_viem.zeroAddress),s,y,l,n],message:u,actionType:m,value:h,gasLimit:p,track:{eventName:"hub_pool_create",eventData:{poolName:i,poolSymbol:a}}}},kg= exports.useCreatePool =({poolCreateTokens:e,initialLiquidityTokens:t,normalizedWeights:o,poolType:r,poolName:s,poolSymbol:n,swapFee:i,owner:a,amplification:l,oracles:u,weightsDuplicationThreshold:m=Ln,...p})=>{let{data:c,error:d,isLoading:f}=_immutable2.default.call(void 0, ["useCreatePool__deduped_pool",e,r,o],async()=>{if(e.length===0||!r)return null;let R=_chunk45HIEVNIcjs.c.call(void 0, "bex.subgraph",{});try{let b=_chunkCJOZC5Z2cjs.b.call(void 0, e).map(I=>I.address.toLowerCase()).sort((I,T)=>I.toLowerCase()<T.toLowerCase()?-1:1);return await _asyncNullishCoalesce(await _asyncOptionalChain([(await R.query({query:_subgraph.GetDedupedSubgraphPools,variables:{tokens:b,type:r}})), 'access', async _37 => _37.data, 'access', async _38 => _38.pools, 'access', async _39 => _39.filter, 'call', async _40 => _40(I=>_optionalChain([I, 'access', _41 => _41.tokens, 'optionalAccess', _42 => _42.every, 'call', _43 => _43(T=>r===_berancersdk.PoolType.Weighted?b.includes(T.address)&&Math.abs(Number(T.weight)-Number(_viem.formatUnits.call(void 0, o[b.indexOf(T.address)],18)))<m:b.includes(T.address)||T.address===I.address)])), 'optionalAccess', async _44 => _44.at, 'call', async _45 => _45(0)]), async () => (null))}catch (e2){return null}}),{generatedPoolName:y,generatedPoolSymbol:A}=_react.useMemo.call(void 0, ()=>{if(!e)return{generatedPoolName:"",generatedPoolSymbol:""};let R=Ar(e),b=br(e,o,r);return{generatedPoolName:R,generatedPoolSymbol:b}},[e,o,r]),h=_react.useMemo.call(void 0, ()=>{if(!a||s===""||n===""||e.length!==t.length||e.length===0)return null;let R=_viem.parseUnits.call(void 0, i.toString(),16),b=_viem.keccak256.call(void 0, Buffer.from(`${s}-${a}`)),{config:P}=_chunkSFEULGSXcjs.a.call(void 0, p);return r===_berancersdk.PoolType.Weighted?Nn({poolCreationHelper:P.bex.poolCreationHelper,poolCreateTokens:e,initialLiquidityTokens:t,normalizedWeights:o,swapFeePercentage:R,salt:b,poolName:s,poolSymbol:n,owner:a,message:`Create pool ${s}`,actionType:"Create Pool"}):r===_berancersdk.PoolType.ComposableStable||r===_berancersdk.PoolType.MetaStable?Hn({poolCreationHelper:P.bex.poolCreationHelper,poolCreateTokens:e,initialLiquidityTokens:t,swapFeePercentage:R,salt:b,poolName:s,poolSymbol:n,owner:a,amplification:l,oracles:u,message:`Create pool ${s}`,actionType:"Create Pool"}):null},[e,t,o,r,i,s,n,a,l,u]);return{generatedPoolName:y,generatedPoolSymbol:A,isDupePool:!!c,dupePool:c,createPoolArgs:h,isLoadingPools:f,errorLoadingPools:d}};var Qn=1e-4;async function wr({token:e,publicClient:t,...o}){let r=_chunk45HIEVNIcjs.c.call(void 0, "bex.subgraph",o),s=await t.readContract({address:e.address,abi:_viem.erc20Abi,functionName:"totalSupply"}),n=_chunk6DIA6PXVcjs.a.call(void 0, _viem.formatUnits.call(void 0, s,e.decimals)).multipliedBy(Qn),{data:i}=await r.query({query:_subgraph.GetExploitedTokens,variables:{token:e.address,balance:n.toFixed()}});return i.userInternalBalances.length>0}var Fn=e=>{let t=_optionalChain([e, 'optionalAccess', _46 => _46.filter, 'call', _47 => _47(o=>o.address)]);return!t||t.length===0?null:["useExploitedTokens",t]},Dg= exports.useExploitedTokens =({tokens:e})=>{let t=Fn(e),o=_hooks.usePublicClient.call(void 0, ),r=_swr2.default.call(void 0, o?t:null,async([,s])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),(await Promise.all(s.map(i=>wr({token:i,publicClient:o})))).reduce((i,a,l)=>(a!==void 0&&(i[s[l].address]=a),i),{})));return{...r,refresh:()=>r.mutate()}};var Kn=()=>{let e=_swr2.default.call(void 0, "useGlobalLiquidityAndSwapVolume",async()=>_chunk45HIEVNIcjs.i.call(void 0, ));return{...e,data:{totalLiquidity:Number(_optionalChain([e, 'access', _48 => _48.data, 'optionalAccess', _49 => _49.protocolMetricsAggregated, 'access', _50 => _50.totalLiquidity])),swapVolume24h:Number(_optionalChain([e, 'access', _51 => _51.data, 'optionalAccess', _52 => _52.protocolMetricsAggregated, 'access', _53 => _53.swapVolume24h]))},refresh:()=>e.mutate()}};var zn=.05,Qg= exports.useLiquidityMismatch =({currentStep:e,tokenPrices:t,isLoadingTokenPrices:o,tokens:r,weights:s,weightsError:n,poolType:i,liquidityMismatchTolerancePercent:a=zn,oracles:l})=>{let[u,m]=_react.useState.call(void 0, {title:null,message:null});return _react.useEffect.call(void 0, ()=>{if(!t||o||!r||!s||n||r.some(b=>!b.address)||l.some(b=>b.mode==="Custom")){m({title:null,message:null});return}let p=0,c=[],d=r.length,y=_chunkCJOZC5Z2cjs.b.call(void 0, r).map(b=>{let P=_nullishCoalesce(_optionalChain([t, 'access', _54 => _54[b.address.toLowerCase()], 'optionalAccess', _55 => _55.price]), () => (0));if(!P||P===0)return c.push(0),null;let w=P*Number.parseFloat(b.amount);return c.push(w),p+=w,P});if(y.some(b=>b===null)||y.length!==d){m({title:"Missing token price data",message:`One or more token(s) do not have valid market price data. Please verify that token market prices align with the pool
|
|
2
|
-
weightings and your initial liquidity amounts.`});return}if(e==="Select Tokens"&&i===_berancersdk.PoolType.ComposableStable){let b=y.map(w=>w/y[0]);Math.max(...b)-Math.min(...b)>a?m({title:"Selected tokens have a significant price deviation",message:"Did you mean to create a Weighted pool instead?",suggestWeighted:!0}):m({title:null,message:null});return}if(p===0||c.some(b=>b===0)){m({title:null,message:null});return}let A=0;if(i===_berancersdk.PoolType.ComposableStable){let b=p/d;c.forEach(P=>{A+=Math.abs(b-P)})}else i===_berancersdk.PoolType.Weighted&&c.forEach((b,P)=>{let w=Number(s[P])/1e18,I=p*w;A+=Math.abs(I-b)});let h=A>=p*.9;A=Math.min(A,p);let R=A/p;R>a?m({title:h?"You could lose all of your initial liquidity":`You could lose $${A.toFixed(2)} (~${(R*100).toFixed(2)}%)`,message:`Based on the market token prices, the value of tokens does not align with the specified pool weights.
|
|
3
|
-
This discrepancy could expose you to potential losses from arbitrageurs. ${i===_berancersdk.PoolType.ComposableStable?"Did you mean to create a Weighted pool instead?":""}`,suggestWeighted:i===_berancersdk.PoolType.ComposableStable}):m({title:null,message:null})},[e,t,o,r,s,n,i,a,l]),u};var _rewardVault = require('@berachain/abis/pol/rewards/rewardVault');var _rewardVaultFactory = require('@berachain/abis/pol/rewards/rewardVaultFactory');var At=({tokenAddress:e},{isEnabled:t=!0}={})=>{let o=_hooks.usePublicClient.call(void 0, ),r=o&&e&&_viem.isAddress.call(void 0, e)&&t?["useRewardVaultFromToken",e]:null,s=_immutable2.default.call(void 0, r,async([,n])=>{if(!n)throw new Error("useRewardVaultFromToken needs a valid token address");_chunkLVOXBZMAcjs.c.call(void 0, o);let{config:i}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:o.chain.id}),a=await o.readContract({address:i.pol.factory,abi:_rewardVaultFactory.rewardVaultFactoryAbi,functionName:"getVault",args:[n]});return a===_viem.zeroAddress?void 0:a});return{...s,refresh:()=>s.mutate()}};var Pr=({stakingToken:e,rewardVaultAddress:t},o)=>{let{address:r}=_hooks.useBeraWallet.call(void 0, ),s=_hooks.usePublicClient.call(void 0, ),n=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _56 => _56.opts, 'optionalAccess', _57 => _57.isEnabled]), () => (!0)),{data:i=t,error:a,mutate:l,isLoading:u}=At({tokenAddress:e},{isEnabled:!t&&n}),m=_swr2.default.call(void 0, i&&r&&s&&_viem.isAddress.call(void 0, i)&&_viem.isAddress.call(void 0, r)&&n?["useVaultBalanceFromStakingToken",i,r]:null,async([,p,c])=>{if(_chunkLVOXBZMAcjs.c.call(void 0, s),p===_viem.zeroAddress)return{address:p,balance:0n};let d=await s.readContract({address:p,abi:_rewardVault.rewardVaultAbi,functionName:"balanceOf",args:[c]});return{address:p,balance:d}});return{...m,refresh:()=>{l(),m.mutate()},isLoading:m.isLoading||u}};function Cr(e,t){let o=_hooks.usePublicClient.call(void 0, {chainId:e.chainId}),r=_optionalChain([e, 'optionalAccess', _58 => _58.address])&&o&&_viem.isAddress.call(void 0, e.address)?["useTokenInformation",e.address,e.chainId]:null,s=_immutable2.default.call(void 0, r,async([n,i,a=_internal.defaultChainId])=>_chunkSFEULGSXcjs.e.call(void 0, i,"BERA")?{address:_viem.zeroAddress,decimals:_chunkSFEULGSXcjs.b.decimals,name:_chunkSFEULGSXcjs.b.name,symbol:_chunkSFEULGSXcjs.b.symbol,chainId:a}:(_chunkLVOXBZMAcjs.c.call(void 0, o),await _chunk45HIEVNIcjs.y.call(void 0, {address:i,publicClient:o,chainId:a})),{..._optionalChain([t, 'optionalAccess', _59 => _59.opts])});return{...s,refresh:()=>_optionalChain([s, 'optionalAccess', _60 => _60.mutate, 'optionalCall', _61 => _61()])}}function Ie({address:e,owner:t,chainId:o=_internal.defaultChainId},r){let s=e;_chunkSFEULGSXcjs.e.call(void 0, s,"ETH")&&(s=_viem.zeroAddress);let n=_hooks.usePublicClient.call(void 0, {chainId:o}),{address:i}=_hooks.useBeraWallet.call(void 0, ),a=_nullishCoalesce(t, () => (i)),l=(_nullishCoalesce(_optionalChain([r, 'optionalAccess', _62 => _62.opts, 'optionalAccess', _63 => _63.isEnabled]), () => (!0)))&&n&&a&&_viem.isAddress.call(void 0, a)&&s&&_viem.isAddress.call(void 0, s)?["usePollBalance",a,s,o]:null,{data:u,isLoading:m}=Cr({address:s,chainId:o}),p=_chunkSFEULGSXcjs.e.call(void 0, s,"BERA"),{isLoading:c,data:d,error:f,...y}=_swr2.default.call(void 0, l,async([,R,b])=>(_chunkLVOXBZMAcjs.c.call(void 0, n),_chunkSFEULGSXcjs.e.call(void 0, b,"BERA")?await n.getBalance({address:R}):await n.readContract({address:b,abi:_viem.erc20Abi,functionName:"balanceOf",args:[R]})),{refreshInterval:1e4}),A=!f&&d?_chunkSFEULGSXcjs.e.call(void 0, s,"BERA")?_viem.formatEther.call(void 0, d):u&&!m?_viem.formatUnits.call(void 0, d,u.decimals):void 0:void 0,h={chainId:o,balance:d?{raw:d.toString(),formatted:_nullishCoalesce(A, () => ("0"))}:{raw:"0",formatted:"0"},address:s,decimals:p?_chunkSFEULGSXcjs.b.decimals:_nullishCoalesce(_optionalChain([u, 'optionalAccess', _64 => _64.decimals]), () => (0)),symbol:p?_chunkSFEULGSXcjs.b.symbol:_nullishCoalesce(_optionalChain([u, 'optionalAccess', _65 => _65.symbol]), () => ("")),name:p?_chunkSFEULGSXcjs.b.name:_nullishCoalesce(_optionalChain([u, 'optionalAccess', _66 => _66.name]), () => (""))};return{...y,refresh:()=>{y.mutate()},isLoading:c||p?m:!1,error:f||!p?f:void 0,data:h}}var Py=({pool:e,vaultAddress:t},o)=>{let{data:r,...s}=Ie({address:_optionalChain([e, 'optionalAccess', _67 => _67.address])}),{data:n,refresh:i}=Pr({stakingToken:_optionalChain([e, 'optionalAccess', _68 => _68.address]),rewardVaultAddress:_nullishCoalesce(t, () => (_optionalChain([e, 'optionalAccess', _69 => _69.rewardVault, 'optionalAccess', _70 => _70.vaultAddress])))},o),a=e?Number.parseFloat(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _71 => _71.dynamicData, 'optionalAccess', _72 => _72.totalShares]), () => ("0"))):0,l=_optionalChain([e, 'optionalAccess', _73 => _73.dynamicData, 'optionalAccess', _74 => _74.totalLiquidity])?Number(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _75 => _75.dynamicData, 'optionalAccess', _76 => _76.totalLiquidity]), () => (0))):null,u=a&&l?l/Number(a):0,m=_optionalChain([e, 'optionalAccess', _77 => _77.tokens, 'optionalAccess', _78 => _78.map, 'call', _79 => _79(p=>({address:p.address,ratio:a?Number(p.balance)/Number(a):0}))]);return{data:{lpTokenPrice:u,lpBalance:r?{...r,usdValue:r?Number(r.balance.formatted)*u:void 0}:void 0,tokenBalances:_optionalChain([e, 'optionalAccess', _80 => _80.tokens, 'optionalAccess', _81 => _81.map, 'call', _82 => _82(p=>{let c=_nullishCoalesce(_optionalChain([m, 'optionalAccess', _83 => _83.find, 'call', _84 => _84(y=>_viem.isAddressEqual.call(void 0, y.address,p.address)), 'optionalAccess', _85 => _85.ratio]), () => (0)),d=c?_chunk6DIA6PXVcjs.a.call(void 0, _nullishCoalesce(_optionalChain([r, 'optionalAccess', _86 => _86.balance, 'access', _87 => _87.formatted]), () => ("0"))).times(c):_chunk6DIA6PXVcjs.a.call(void 0, 0),f=Number(p.balanceUSD)/Number(p.balance);return{...p,balance:{raw:_optionalChain([d, 'optionalAccess', _88 => _88.isGreaterThan, 'call', _89 => _89(0)])?d.times(10**p.decimals).toFixed(0).toString():"0",formatted:d.toString()},price:f,usdValue:Number.isNaN(f)||!d?void 0:Number.parseFloat(d.toString())*f}})]),stakedBalance:_optionalChain([n, 'optionalAccess', _90 => _90.address])?{...n,balance:{raw:n.balance.toString(),formatted:_viem.formatEther.call(void 0, n.balance)},usdValue:Number(_viem.formatEther.call(void 0, n.balance))*u}:void 0},...s,refresh:()=>{_optionalChain([s, 'access', _91 => _91.refresh, 'optionalCall', _92 => _92()]),i()}}};function Tr(e,t){let o=_hooks.useConfig.call(void 0, ),{address:r}=_hooks.useBeraWallet.call(void 0, ),s=o&&r&&_optionalChain([e, 'optionalAccess', _93 => _93.items])?["usePollAllowances",r,_optionalChain([e, 'optionalAccess', _94 => _94.items])]:null,n=_swr2.default.call(void 0, s,async([,i,a])=>_chunk45HIEVNIcjs.ka.call(void 0, {items:a,account:i,config:o}),{..._optionalChain([t, 'optionalAccess', _95 => _95.opts]),refreshInterval:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _96 => _96.opts, 'optionalAccess', _97 => _97.refreshInterval]), () => (1e5))});return{...n,refresh:()=>_optionalChain([n, 'optionalAccess', _98 => _98.mutate, 'optionalCall', _99 => _99()])}}function Ia({amount:e,decimals:t,slippage:o}){let r=_viem.parseUnits.call(void 0, (_nullishCoalesce(o, () => (0))).toString(),t);return e+e*r/BigInt(100*10**t)}function Ea(e,t){let{slippage:o}=_nullishCoalesce(t, () => ({})),r=_react.useMemo.call(void 0, ()=>e.filter(l=>l.token.address!==_viem.zeroAddress).filter(l=>_chunk6DIA6PXVcjs.a.call(void 0, l.amount.formatted).gt(0)),[e]),{data:s,refresh:n,isLoading:i}=Tr({items:r});return{needsApproval:_react.useMemo.call(void 0, ()=>_nullishCoalesce(_optionalChain([s, 'optionalAccess', _100 => _100.map, 'call', _101 => _101(l=>{let u=r.find(p=>_chunkSFEULGSXcjs.e.call(void 0, p.token.address,l.token));if(!u)throw new (0, _chunk6JJIZCVYcjs.f)({message:"Token not found when matching allowance in useMultipleTokenApprovalsWithSlippage",cause:{allowance:l,items:r}});let m=Ia({decimals:u.token.decimals,amount:BigInt(u.amount.raw),slippage:o});if(_chunk6DIA6PXVcjs.a.call(void 0, l.allowance.raw).lt(m))return{...u,needsApproval:!0,maxAmountIn:m,allowance:{raw:l.allowance.raw,formatted:l.allowance.formatted}}}), 'access', _102 => _102.filter, 'call', _103 => _103(l=>l!==void 0)]), () => ([])),[s,o,r]),refresh:n,isLoading:i}}function xr(e,t){let o=_hooks.usePublicClient.call(void 0, ),r=o&&e.addresses?["useMultipleTokenInformation",e.addresses,_nullishCoalesce(e.chainId, () => (_internal.defaultChainId))]:null,s=_immutable2.default.call(void 0, r,async([,n,i])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),Promise.all(n.map(async a=>{if(!a||!_viem.isAddress.call(void 0, a,{strict:!1}))throw new Error("Invalid address");let l=await _chunk45HIEVNIcjs.y.call(void 0, {address:a,publicClient:o,chainId:i});if(!l)throw new Error(`Token ${a} not found`);return l}))),{..._optionalChain([t, 'optionalAccess', _104 => _104.opts])});return{...s,refresh:()=>_optionalChain([s, 'optionalAccess', _105 => _105.mutate, 'optionalCall', _106 => _106()])}}function oe(){let e=_react.useContext.call(void 0, _chunkQ2SNRLW3cjs.n);if(!e)throw new (0, _chunk6JJIZCVYcjs.f)({message:"useTokens must be used within a TokensProvider",level:"fatal"});return{...e,data:{tokenList:e.tokenList,customTokenList:e.userTokens,featuredTokenList:e.featuredTokens}}}function se({addressIn:e}={},t={opts:{refreshInterval:1e5,revalidateOnFocus:!0}}){let{tokenList:o,ensoTokens:r}=oe(),s=_react.useMemo.call(void 0, ()=>{let p=[];return e&&p.push(...e.filter(c=>_viem.isAddress.call(void 0, c))),p.map(c=>c.toLowerCase())},[o]),i=_react.useMemo.call(void 0, ()=>{let p=new Set(_optionalChain([o, 'optionalAccess', _107 => _107.map, 'call', _108 => _108(c=>c.address.toLowerCase())]));return o.some(c=>_chunkSFEULGSXcjs.e.call(void 0, c,"WBERA"))&&p.add(_viem.zeroAddress),_optionalChain([s, 'optionalAccess', _109 => _109.some, 'call', _110 => _110(c=>!p.has(c))])},[s,o])?s:o.map(p=>p.address),a=i&&(_nullishCoalesce(_optionalChain([t, 'access', _111 => _111.opts, 'optionalAccess', _112 => _112.isEnabled]), () => (!0)))?["useTokenCurrentPrices",i.map(p=>p.toLowerCase())]:null,l=_swr2.default.call(void 0, a,async([,p])=>_chunk45HIEVNIcjs.ja.call(void 0, {addressIn:p}),t.opts),u=_react.useMemo.call(void 0, ()=>{if(!r)return{};let p=new Map([[_internal.defaultChainId,new Map]]);for(let c of r)c.price===void 0||c.chainId!==_internal.defaultChainId||_optionalChain([p, 'access', _113 => _113.get, 'call', _114 => _114(_internal.defaultChainId), 'optionalAccess', _115 => _115.set, 'call', _116 => _116(c.address.toLowerCase(),{...c,price:c.price,chainId:_internal.defaultChainId})]);return Object.fromEntries(i.map(c=>{let d=_optionalChain([p, 'access', _117 => _117.get, 'call', _118 => _118(_internal.defaultChainId), 'optionalAccess', _119 => _119.get, 'call', _120 => _120(c), 'optionalAccess', _121 => _121.price]);return d?[c.toLowerCase(),{price:d,chainId:_internal.defaultChainId,updatedAt:Date.now()}]:[null,null]}))},[r]),m=_react.useMemo.call(void 0, ()=>({...u,...l.data}),[u,l.data]);return{...l,data:m}}function _a(e){let t="poolId"in e?_optionalChain([e, 'access', _122 => _122.poolId, 'optionalAccess', _123 => _123.slice, 'call', _124 => _124(0,42)]):e.address;return _viem.isAddress.call(void 0, t)&&t?["useOnChainPoolData",t]:null}function Br(e){let t=_hooks.usePublicClient.call(void 0, ),o=_optionalChain([e, 'optionalAccess', _125 => _125.slice, 'call', _126 => _126(0,42)]),r=_a({poolId:e}),{data:s,error:n,isLoading:i,mutate:a}=_immutable2.default.call(void 0, t?r:null,async([,d])=>_chunk45HIEVNIcjs.k.call(void 0, {poolId:d,publicClient:t})),{data:l,isLoading:u}=xr({addresses:_optionalChain([s, 'optionalAccess', _127 => _127.poolTokens, 'access', _128 => _128[0]])}),{data:m,isLoading:p}=se({addressIn:_optionalChain([s, 'optionalAccess', _129 => _129.poolTokens, 'access', _130 => _130[0]])});return{data:_react.useMemo.call(void 0, ()=>{if(!s||!l)return;let d={address:o.toLowerCase(),id:e.toLowerCase(),type:s.type,factory:s.factory,totalShares:s.totalSupply,totalLiquidity:"0",swapFee:s.swapFee,createTime:0,name:s.name,tokens:l.map((y,A)=>({address:y.address.toLowerCase(),name:y.name,decimals:y.decimals,symbol:y.symbol,index:A,weight:_nullishCoalesce(_optionalChain([s, 'access', _131 => _131.weights, 'optionalAccess', _132 => _132[A]]), () => (void 0)),balance:_viem.formatUnits.call(void 0, BigInt(s.poolTokens[1][A]),y.decimals),token:{__typename:"Token",token:y,latestUSDPrice:_optionalChain([m, 'optionalAccess', _133 => _133[y.address]])}})),amplificationParameter:_optionalChain([s, 'optionalAccess', _134 => _134.amplificationParameter])&&{currentFormattedValue:Number(s.amplificationParameter[0])/Number(s.amplificationParameter[2])}},f=_optionalChain([d, 'access', _135 => _135.tokens, 'optionalAccess', _136 => _136.reduce, 'call', _137 => _137((y,A)=>{let h=Number(_nullishCoalesce(_optionalChain([m, 'optionalAccess', _138 => _138[A.address.toLowerCase()], 'optionalAccess', _139 => _139.price]), () => (0)));return h?y+h*Number(A.balance):y},0)]);return d.totalLiquidity=_nullishCoalesce(_optionalChain([f, 'optionalAccess', _140 => _140.toString, 'call', _141 => _141()]), () => ("")),d},[s,l,m,o,e]),error:n,isLoading:i||u||p,mutate:a,refresh:()=>a()}}var Ga=e=>{let{address:t}=_hooks.useBeraWallet.call(void 0, ),o=_hooks.usePublicClient.call(void 0, ),r=t&&o?["usePollPoolCreationRelayerApproval",t,o.chain.id]:null,s=_swr2.default.call(void 0, r,async([,i])=>{_chunkLVOXBZMAcjs.c.call(void 0, o);let{config:a}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:o.chain.id});return await o.readContract({address:a.bex.vault,abi:_vault.vaultAbi,functionName:"hasApprovedRelayer",args:[i,a.bex.poolCreationHelper]})},{..._optionalChain([e, 'optionalAccess', _142 => _142.opts])});return{...s,refreshPoolCreationApproval:()=>{s.mutate()}}};function AA({poolId:e}){let t=gr({poolId:e}),{data:o,isLoading:r,refresh:s,error:n}=Br(e);return{data:[void 0,t.data,o],isLoading:t.isLoading||r,isError:t.error||n,refresh:()=>{t.refresh(),s()}}}var wA=({poolId:e,typeInArray:t})=>_immutable2.default.call(void 0, e?["usePoolEvents",e,t]:null,async([,o,r])=>_chunk45HIEVNIcjs.l.call(void 0, {poolId:o,typeInArray:r}),{refreshInterval:18e4});var EA=({poolId:e,...t},o)=>{let{config:r}=_chunkSFEULGSXcjs.a.call(void 0, t),n=_swr2.default.call(void 0, e?["usePoolHistoricalData",e]:null,async([,i])=>_chunk45HIEVNIcjs.m.call(void 0, {poolId:i,chain:r.bex.chainName}),_optionalChain([o, 'optionalAccess', _143 => _143.opts]));return{...n,refresh:()=>{n.mutate()}}};var ja=({query:e}={})=>["useAllPools",e],DA= exports.usePools =(e,t)=>{let{address:o}=_hooks.useBeraWallet.call(void 0, ),{data:r,isLoading:s,mutate:n}=fr({userAddress:o,chain:e.chain}),{data:i,isLoading:a,mutate:l}=_swr2.default.call(void 0, ja({query:e}),async([p,c])=>_chunk45HIEVNIcjs.g.call(void 0, c),{refreshInterval:18e4,..._optionalChain([t, 'optionalAccess', _144 => _144.opts])}),u=_react.useMemo.call(void 0, ()=>{if(!i||!_optionalChain([r, 'optionalAccess', _145 => _145.pools, 'optionalAccess', _146 => _146.length]))return _nullishCoalesce(_optionalChain([i, 'optionalAccess', _147 => _147.pools]), () => ([]));let p=Object.fromEntries(r.pools.map(c=>[c.id.toLowerCase(),c]));return i.pools.map(c=>({...c,...p[c.id.toLowerCase()]||{}})).filter(Boolean)},[i,r]),m=_react.useMemo.call(void 0, ()=>({page:Math.ceil((_nullishCoalesce(_optionalChain([e, 'optionalAccess', _148 => _148.skip]), () => (0)))/(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _149 => _149.first]), () => (10)))),pageSize:_optionalChain([e, 'optionalAccess', _150 => _150.first]),count:Math.ceil((_nullishCoalesce(_optionalChain([i, 'optionalAccess', _151 => _151.count]), () => (0)))/(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _152 => _152.first]), () => (10))))}),[i,e.skip,e.first]);return{pools:_nullishCoalesce(u, () => ([])),walletPools:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _153 => _153.pools]), () => ([])),isLoading:a||s,refresh:()=>{l(),n()},pagination:m}};function J({tokens:e}={},t={opts:{refreshInterval:1e5,revalidateOnFocus:!0}}){let{ensoTokens:o}=oe(),r=se({addressIn:_optionalChain([e, 'optionalAccess', _154 => _154.filter, 'call', _155 => _155(a=>a.chainId===_internal.defaultChainId), 'access', _156 => _156.map, 'call', _157 => _157(a=>a.address)])},t),s=_react.useMemo.call(void 0, ()=>{let a=[];if(!e)return[];let l=new Map;for(let u of e){let m=_nullishCoalesce(u.chainId, () => (_internal.defaultChainId));l.has(m)||l.set(m,new Map),_optionalChain([l, 'access', _158 => _158.get, 'call', _159 => _159(m), 'optionalAccess', _160 => _160.set, 'call', _161 => _161(u.address.toLowerCase(),u)])}if(r.data){for(let[u,m]of Object.entries(r.data))if(m&&_optionalChain([l, 'access', _162 => _162.get, 'call', _163 => _163(_nullishCoalesce(m.chainId, () => (_internal.defaultChainId))), 'optionalAccess', _164 => _164.get, 'call', _165 => _165(u.toLowerCase())])&&m.price!==void 0){let p=_optionalChain([l, 'access', _166 => _166.get, 'call', _167 => _167(_nullishCoalesce(m.chainId, () => (_internal.defaultChainId))), 'optionalAccess', _168 => _168.get, 'call', _169 => _169(u.toLowerCase())]);if(!p)continue;a.push({...p,chainId:m.chainId,price:m.price})}}if(o)for(let u of o)u.price!==void 0&&u.chainId!==void 0&&a.push({...u,chainId:u.chainId,price:u.price});return a},[r.data,o,e]),n=_react.useMemo.call(void 0, ()=>{let a={};for(let l of s){let u=_nullishCoalesce(l.chainId, () => (_internal.defaultChainId));a[u]||(a[u]={}),a[u][l.address.toLowerCase()]=l.price}return a},[s]),i=_react.useCallback.call(void 0, a=>a?_nullishCoalesce(_optionalChain([n, 'access', _170 => _170[_nullishCoalesce(a.chainId, () => (_internal.defaultChainId))], 'optionalAccess', _171 => _171[_optionalChain([a, 'access', _172 => _172.address, 'optionalAccess', _173 => _173.toLowerCase, 'call', _174 => _174()])]]), () => (void 0)):void 0,[n]);return{isLoading:r.isLoading,data:s,priceMap:n,getTokenPrice:i}}function Te({tokenIn:e,tokenOut:t,formattedAmountIn:o,formattedAmountOut:r}){let{getTokenPrice:s,isLoading:n}=J({tokens:e&&t?[e,t]:void 0});return{data:_react.useMemo.call(void 0, ()=>{if(!e||!t||!o||!r)return;let a=s(e),l=s(t);return!a||!l?null:_chunkCJOZC5Z2cjs.c.call(void 0, a.toString(),l.toString(),o,r)},[e,t,o,r]),isLoading:n}}var _morpho = require('@berachain/abis/bend/morpho');function X(e){return e===_viem.zeroAddress?_viem.ethAddress:e}function ht(e){if(e!=null)return typeof e=="bigint"?e:BigInt(e)}async function Dr({fromAddress:e,amountIn:t,tokenIn:o,chainId:r,ensoClient:s,bundle:n,publicClient:i}){let a=[];if(o!==_viem.ethAddress){let u=await s.getApprovalData({fromAddress:e,tokenAddress:o,chainId:r,amount:t}),m=!0;if(i&&(m=await i.readContract({address:o,abi:_viem.erc20Abi,functionName:"allowance",args:[e,u.spender]})<BigInt(t)),m){let p=_nullishCoalesce(ht(u.tx.value), () => (0n));a.push({to:u.tx.to,data:u.tx.data,value:p,gasLimit:BigInt(u.gas)})}}let l=_nullishCoalesce(ht(n.tx.value), () => (0n));return a.push({to:n.tx.to,data:n.tx.data,value:l,gasLimit:BigInt(n.gas)}),a}async function Lr({fromAddress:e,amountIn:t,tokenIn:o,bundle:r,publicClient:s}){let n=[],i=_viem.getAddress.call(void 0, r.tx.to),a=null;if(X(o.address)!==_viem.ethAddress){let m=await s.readContract({address:o.address,abi:_viem.erc20Abi,functionName:"allowance",args:[e,i]}),p=BigInt(t);if(m<p){let d=p.toString();a={token:o,amount:{raw:d,formatted:_viem.formatUnits.call(void 0, p,o.decimals)},spender:i};let f=_viem.encodeFunctionData.call(void 0, {abi:_viem.erc20Abi,functionName:"approve",args:[i,p]});n.push({to:o.address,data:f,value:0n})}}let u=_nullishCoalesce(ht(r.tx.value), () => (0n));return n.push({to:r.tx.to,data:r.tx.data,value:u,gasLimit:r.gas?BigInt(r.gas):void 0}),{transactions:n,approval:a}}function ue(e){let t=new (0, _chunk6DIA6PXVcjs.a)(e).dividedBy(100),o=new (0, _chunk6DIA6PXVcjs.a)(1).minus(t);if(o.lte(0))throw new (0, _chunk6JJIZCVYcjs.h)({property:"slippage",value:e,expected:"a value lower than 100"});return o}function wt(e,t,o){return e.multipliedBy(new (0, _chunk6DIA6PXVcjs.a)(10).pow(o.decimals)).dividedBy(new (0, _chunk6DIA6PXVcjs.a)(10).pow(t.decimals))}async function Hr({publicClient:e,ensoWalletV2Factory:t,accountAddress:o}){return e.readContract({address:t,abi:_chunkRWOICHRWcjs.a,functionName:"getAddress",args:[o]})}async function Nr({publicClient:e,primaryAddress:t,accountAddress:o,ensoWalletV2Address:r}){return e.readContract({address:t,abi:_morpho.morphoAbi,functionName:"isAuthorized",args:[o,r]})}async function Se({fromAddress:e,amountIn:t,tokenIn:o,primaryAddress:r,bundle:s,publicClient:n,ensoWalletV2Address:i,isAuthorized:a}){let{config:l}=_chunkSFEULGSXcjs.a.call(void 0, {}),{walletFlashloanAdapter:u}=l.enso;_chunkLVOXBZMAcjs.b.call(void 0, u,"config.enso.walletFlashloanAdapter");let{transactions:m,approval:p}=await Lr({fromAddress:e,amountIn:t,tokenIn:o,bundle:s,publicClient:n}),c=[];return a||c.push({to:r,data:_viem.encodeFunctionData.call(void 0, {abi:_morpho.morphoAbi,functionName:"setAuthorization",args:[i,!0]}),value:0n}),c.push(...m),{transactions:c,approvals:p?[p]:[],ensoWalletFlashloanAdapter:_viem.getAddress.call(void 0, u)}}var ni=25n,Wr=10000n;function ai({repayAmount:e,collateralPriceInLoanAsset:t,collateralToken:o,loanToken:r,slippage:s,currentCollateral:n}){let i=ue(s),a=new (0, _chunk6DIA6PXVcjs.a)(t);if(a.lte(0))throw new (0, _chunk6JJIZCVYcjs.h)({property:"collateralPriceInLoanAsset",value:t,expected:"a value greater than zero"});let l=new (0, _chunk6DIA6PXVcjs.a)(10).pow(r.decimals),u=new (0, _chunk6DIA6PXVcjs.a)(10).pow(o.decimals),c=new (0, _chunk6DIA6PXVcjs.a)(e).dividedBy(l).dividedBy(a).dividedBy(i).multipliedBy(u).integerValue(_chunk6DIA6PXVcjs.a.ROUND_UP);return c.lte(0)?"0":_chunk6DIA6PXVcjs.a.minimum(c,new (0, _chunk6DIA6PXVcjs.a)(n)).toFixed(0)}function ii({repayAmount:e,collateralToWithdraw:t,collateralToken:o,loanToken:r}){return{finalCollateral:_viem.formatUnits.call(void 0, BigInt(t),o.decimals),totalBorrow:_viem.formatUnits.call(void 0, BigInt(e),r.decimals)}}async function _r({fromAddress:e,repayAmount:t,collateralToken:o,loanToken:r,marketId:s,primaryAddress:n,chainId:i,ensoClient:a,slippage:l,publicClient:u,collateralPriceInLoanAsset:m,currentCollateral:p,currentDebt:c,ensoWalletV2Address:d,isAuthorized:f}){_chunkLVOXBZMAcjs.d.call(void 0, e,"fromAddress"),_chunkLVOXBZMAcjs.e.call(void 0, t,"repayAmount"),_chunkLVOXBZMAcjs.e.call(void 0, c,"currentDebt");let y=BigInt(t),A=BigInt(c),h=y>=A,R=X(o.address),b=X(r.address),P=(y*ni+(Wr-1n))/Wr,w=h?P:0n,I=(y+w).toString(),T=ai({repayAmount:I,collateralPriceInLoanAsset:m,collateralToken:o,loanToken:r,slippage:l,currentCollateral:p}),S=BigInt(T)>=BigInt(p),O=h&&w>0n&&!S;if(BigInt(T)<=0n)throw new (0, _chunk6JJIZCVYcjs.h)({property:"collateralToWithdraw",value:T,expected:"positive amount"});let U=[{protocol:"enso",action:"route",args:{tokenIn:R,tokenOut:b,amountIn:T,slippage:l*100}},{protocol:"bend",action:"repay",args:{primaryAddress:n,positionId:s,tokenIn:b,amountIn:{useOutputOfCallAt:0},onBehalfOf:e}}],v=U.length,Y=O?[{protocol:"enso",action:"balance",args:{token:b}},{protocol:"enso",action:"route",args:{tokenIn:b,tokenOut:R,amountIn:{useOutputOfCallAt:v},slippage:l*100}},{protocol:"bend",action:"deposit",args:{primaryAddress:n,positionId:s,tokenIn:R,amountIn:{useOutputOfCallAt:v+1},onBehalfOf:e}}]:[],M=[...U,...Y,{protocol:"bend",action:"withdraw",args:{primaryAddress:n,positionId:s,tokenOut:R,amountOut:T,onBehalfOf:e}}],F=[{protocol:"bend",action:"flashloan",args:{flashloanToken:R,flashloanAmount:T,tokenOut:b,callback:M}}],G=await a.getBundleData({fromAddress:e,receiver:e,spender:e,chainId:i,routingStrategy:"ensowallet-v2"},F),{transactions:D}=await Se({fromAddress:e,amountIn:"0",tokenIn:o,primaryAddress:n,bundle:G,publicClient:u,ensoWalletV2Address:d,isAuthorized:f});return{bundle:G,transactions:D,positionEstimate:ii({repayAmount:t,collateralToWithdraw:T,collateralToken:o,loanToken:r})}}function xe({chainId:e}){let{address:t}=_hooks.useBeraWallet.call(void 0, ),o=_hooks.usePublicClient.call(void 0, {chainId:e}),{config:r}=_chunkSFEULGSXcjs.a.call(void 0, {}),s=r.enso.walletV2Factory;return _swr2.default.call(void 0, t&&s?["useEnsoWalletV2Address",t,s]:null,async([i,a,l])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),Hr({publicClient:o,ensoWalletV2Factory:_viem.getAddress.call(void 0, l),accountAddress:a})),{refreshInterval:18e4})}function Be({chainId:e,primaryAddress:t,ensoWalletV2Address:o}){let{address:r}=_hooks.useBeraWallet.call(void 0, ),s=_hooks.usePublicClient.call(void 0, {chainId:e});return _swr2.default.call(void 0, r&&t&&o?["useIsBendAuthorized",r,t,o]:null,async([i,a,l,u])=>(_chunkLVOXBZMAcjs.c.call(void 0, s),Nr({publicClient:s,primaryAddress:l,accountAddress:a,ensoWalletV2Address:u})),{refreshInterval:18e4})}function xb({collateralToken:e,loanToken:t,marketId:o,primaryAddress:r,repayAmount:s,slippage:n,chainId:i,collateralPriceInLoanAsset:a,currentCollateral:l,currentDebt:u},m){let{address:p}=_hooks.useBeraWallet.call(void 0, ),{account:{chainId:c}={}}=_hooks.useBeraWagmi.call(void 0, ),d=_nullishCoalesce(_nullishCoalesce(i, () => (c)), () => (_internal.defaultChainId)),f=_hooks.usePublicClient.call(void 0, {chainId:d}),{data:y}=xe({chainId:d}),{data:A}=Be({chainId:d,primaryAddress:r,ensoWalletV2Address:y}),h=e&&t&&o&&r&&s&&y&&A!==void 0&&e.address!==t.address&&Number(s)>0&&n!==void 0&&a!==void 0&&l&&u&&Number(u)>0&&p&&(_nullishCoalesce(_optionalChain([m, 'optionalAccess', _175 => _175.opts, 'optionalAccess', _176 => _176.isEnabled]), () => (!0)))?["useBendDemultiply",p,e,t,o,r,d,s,n,a,l,u,y,A]:null;return _swr2.default.call(void 0, h,async([R,b,P,w,I,T,S,O,U,v,Y,M,$,F])=>{_chunkLVOXBZMAcjs.c.call(void 0, f);let G=_viem.parseUnits.call(void 0, O,w.decimals).toString(),D=_viem.parseUnits.call(void 0, Y,P.decimals).toString(),q=_viem.parseUnits.call(void 0, M,w.decimals).toString();return _r({fromAddress:b,repayAmount:G,collateralToken:P,loanToken:w,marketId:I,primaryAddress:T,chainId:S,ensoClient:_chunkBC2WX6O6cjs.a.call(void 0, ),slippage:U,publicClient:f,collateralPriceInLoanAsset:v,currentCollateral:D,currentDebt:q,ensoWalletV2Address:$,isAuthorized:F})},{..._optionalChain([m, 'optionalAccess', _177 => _177.opts]),refreshInterval:1e5})}function Ri({rawSupplyCollateralAmount:e,rawCurrentCollateralAmount:t,rawCurrentBorrowAmount:o,formattedCollateralPriceInLoanAsset:r,collateralToken:s,loanToken:n,leverageMultiplier:i,slippage:a}){let l=Math.max(i,1);if(l<=1)return"0";let u=ue(a),m=new (0, _chunk6DIA6PXVcjs.a)(r);if(m.lte(0))throw new (0, _chunk6JJIZCVYcjs.h)({property:"formattedCollateralPriceInLoanAsset",value:r,expected:"a value greater than zero"});let p=wt(m,s,n),c=new (0, _chunk6DIA6PXVcjs.a)(1).minus(new (0, _chunk6DIA6PXVcjs.a)(1).dividedBy(l)),d=new (0, _chunk6DIA6PXVcjs.a)(t).plus(e),f=new (0, _chunk6DIA6PXVcjs.a)(o),y=new (0, _chunk6DIA6PXVcjs.a)(1).minus(c.multipliedBy(u));if(y.lte(0))throw new (0, _chunk6JJIZCVYcjs.h)({property:"leverageMultiplier",value:i,expected:"a lower leverage target for current slippage"});let A=c.multipliedBy(d).multipliedBy(p).minus(f).dividedBy(y);if(A.lte(0))return"0";let h=A.integerValue(_chunk6DIA6PXVcjs.a.ROUND_UP);return h.lte(0)?"0":h.toFixed(0)}function wi({rawSupplyCollateralAmount:e,collateralToken:t,loanToken:o,rawBorrowAmount:r,formattedCollateralPriceInLoanAsset:s,slippage:n}){let i=new (0, _chunk6DIA6PXVcjs.a)(10).pow(t.decimals),a=new (0, _chunk6DIA6PXVcjs.a)(10).pow(o.decimals),l=new (0, _chunk6DIA6PXVcjs.a)(e),u=new (0, _chunk6DIA6PXVcjs.a)(r);if(u.lte(0))return{finalCollateral:l.dividedBy(i).toFixed(),totalBorrow:"0"};let m=ue(n),p=wt(new (0, _chunk6DIA6PXVcjs.a)(s),t,o),c=p.lte(0)?new (0, _chunk6DIA6PXVcjs.a)(0):u.multipliedBy(m).dividedBy(p),d=l.plus(c).dividedBy(i),f=u.dividedBy(a);return{finalCollateral:d.toFixed(),totalBorrow:f.toFixed()}}async function Qr({fromAddress:e,rawSupplyCollateralAmount:t,rawCurrentCollateralAmount:o,rawCurrentBorrowAmount:r,collateralToken:s,loanToken:n,marketId:i,primaryAddress:a,chainId:l,ensoClient:u,slippage:m,leverageMultiplier:p,publicClient:c,formattedCollateralPriceInLoanAsset:d,ensoWalletV2Address:f,isAuthorized:y}){_chunkLVOXBZMAcjs.d.call(void 0, e,"fromAddress");let A=X(s.address),h=X(n.address),R=Ri({rawSupplyCollateralAmount:t,rawCurrentCollateralAmount:o,rawCurrentBorrowAmount:r,formattedCollateralPriceInLoanAsset:d,collateralToken:s,loanToken:n,leverageMultiplier:p,slippage:m}),b=0,P=1,w=[{protocol:"bend",action:"deposit",args:{primaryAddress:a,positionId:i,tokenIn:A,amountIn:t,onBehalfOf:e}}],T=[{protocol:"bend",action:"flashloan",args:{flashloanToken:h,flashloanAmount:R,...t!=="0"&&{tokenIn:A,amountIn:t},tokenOut:h,callback:[{protocol:"enso",action:"route",args:{tokenIn:h,tokenOut:A,amountIn:R,slippage:m*100}},{protocol:"enso",action:"balance",args:{token:A}},{protocol:"bend",action:"deposit",args:{primaryAddress:a,positionId:i,tokenIn:A,amountIn:{useOutputOfCallAt:P},onBehalfOf:e}},{protocol:"bend",action:"borrow",args:{primaryAddress:a,positionId:i,collateral:A,tokenOut:h,amountOut:R,onBehalfOf:e}}]}}],S=R==="0"?w:T,O=await u.getBundleData({fromAddress:e,receiver:e,spender:e,chainId:l,routingStrategy:"ensowallet-v2"},S),{transactions:U}=await Se({fromAddress:e,amountIn:t,tokenIn:s,primaryAddress:a,bundle:O,publicClient:c,ensoWalletV2Address:f,isAuthorized:y});return{bundle:O,transactions:U,positionEstimate:wi({rawSupplyCollateralAmount:t,collateralToken:s,loanToken:n,rawBorrowAmount:R,formattedCollateralPriceInLoanAsset:d,slippage:m})}}function Kb({collateralToken:e,loanToken:t,marketId:o,primaryAddress:r,formattedSupplyCollateralAmount:s,formattedCurrentCollateralAmount:n,formattedCurrentBorrowAmount:i,leverageMultiplier:a,slippage:l,chainId:u,formattedCollateralPriceInLoanAsset:m},p){let{address:c}=_hooks.useBeraWallet.call(void 0, ),{account:{chainId:d}={}}=_hooks.useBeraWagmi.call(void 0, ),f=_nullishCoalesce(_nullishCoalesce(u, () => (d)), () => (_internal.defaultChainId)),y=_hooks.usePublicClient.call(void 0, {chainId:f}),{data:A}=xe({chainId:f}),{data:h}=Be({chainId:f,primaryAddress:r,ensoWalletV2Address:A}),R=e&&t&&o&&r&&A&&h!==void 0&&e.address!==t.address&&l!==void 0&&a!==void 0&&m!==void 0&&(Number(_nullishCoalesce(s, () => (0)))>0||a>1&&(Number(_nullishCoalesce(n, () => (0)))>0||Number(_nullishCoalesce(s, () => (0)))>0))&&c&&(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _178 => _178.opts, 'optionalAccess', _179 => _179.isEnabled]), () => (!0)))?["useBendMultiply",c,e,t,o,r,f,_nullishCoalesce(s, () => ("")),_nullishCoalesce(n, () => ("")),_nullishCoalesce(i, () => ("")),a,l,m,A,h]:null;return _swr2.default.call(void 0, R,async([b,P,w,I,T,S,O,U,v,Y,M,$,F,G,D])=>{_chunkLVOXBZMAcjs.c.call(void 0, y);let q=_viem.parseUnits.call(void 0, U||"0",w.decimals).toString(),_e=_viem.parseUnits.call(void 0, v||"0",w.decimals).toString(),Ps=_viem.parseUnits.call(void 0, Y||"0",I.decimals).toString();return Qr({fromAddress:P,rawSupplyCollateralAmount:q,rawCurrentCollateralAmount:_e,rawCurrentBorrowAmount:Ps,collateralToken:w,loanToken:I,marketId:T,primaryAddress:S,chainId:O,ensoClient:_chunkBC2WX6O6cjs.a.call(void 0, ),slippage:$,leverageMultiplier:M,publicClient:y,formattedCollateralPriceInLoanAsset:F,ensoWalletV2Address:G,isAuthorized:D})},{..._optionalChain([p, 'optionalAccess', _180 => _180.opts]),refreshInterval:1e5})}var It= (_class12 =class extends _chunk45HIEVNIcjs.e{constructor(...args13) { super(...args13); _class12.prototype.__init43.call(this);_class12.prototype.__init44.call(this);_class12.prototype.__init45.call(this);_class12.prototype.__init46.call(this);_class12.prototype.__init47.call(this); }__init43() {this.name="Enso (Mint)"}__init44() {this.supportedChains=null}__init45() {this.type="rest"}__init46() {this.needsAccountForQuote=!0}__init47() {this.notFoundMessages=["Could not build shortcuts for route","Could not quote shortcuts for route","Swap not found for a required underlying of defi route,","No route found from"]}async getQuote({tokenIn:t,tokenOut:o,amount:r,slippage:s,account:n=_viem.zeroAddress,aggregatorsFeeBps:i,proxyAggregatorsThroughVercel:a=!1,rewardVault:l,underlyingToken:u}){this.assertChainSupport({tokenIn:t,tokenOut:o}),_chunkLVOXBZMAcjs.d.call(void 0, n,"account");let m=_chunkBC2WX6O6cjs.a.call(void 0, {useProxy:!a});t.address===_viem.zeroAddress&&(t.address=_viem.ethAddress),o.address===_viem.zeroAddress&&(o.address=_viem.ethAddress);let p=_nullishCoalesce(u, () => (o)),c=[{protocol:"enso",action:"route",args:{tokenIn:t.address,tokenOut:p.address,destinationChainId:t.chainId===p.chainId?void 0:p.chainId,refundReceiver:n,amountIn:r,slippage:s*100}}];if(u&&c.push({protocol:"erc4626",action:"deposit",args:{amountIn:{useOutputOfCallAt:0},tokenIn:u.address,primaryAddress:o.address,tokenOut:o.address}}),l){let A=c.length;c.push({protocol:"enso",action:"balance",args:{token:o.address}},{protocol:"erc20",action:"approve",args:{amount:{useOutputOfCallAt:A},spender:l,token:o.address}},{protocol:"enso",action:"call",args:{address:l,args:[n,{useOutputOfCallAt:A}],method:"stakeOnBehalf",abi:"function stakeOnBehalf(address account, uint256 amount) external"}},{protocol:"enso",action:"balance",args:{token:l}})}let d=await m.getBundleData({fromAddress:n,receiver:n,spender:n,chainId:t.chainId,routingStrategy:"router"},c),f=_nullishCoalesce(_optionalChain([l, 'optionalAccess', _181 => _181.toLowerCase, 'call', _182 => _182()]), () => (o.address.toLowerCase()));return{amountOut:_nullishCoalesce(_nullishCoalesce(d.minAmountsOut[f], () => (d.amountsOut[f])), () => ("0")),amountIn:r,allowanceRequirements:this.parseAllowanceRequirements({tokenIn:t,rawAmount:r,spender:d.tx.to}),name:this.name,swapFeeBps:0,priceImpactPercentage:d.priceImpact?d.priceImpact/100:null,getCalldata:()=>({address:d.tx.to,data:d.tx.data,value:BigInt(_nullishCoalesce(d.tx.value, () => (0)))})}}}, _class12),ve=new It;function ph({tokenIn:e,loanToken:t,bendVault:o,rewardVault:r,amount:s,slippage:n},i){let{getTokenPrice:a}=J({tokens:e&&t?[e,t]:void 0}),l=Di({tokenIn:e,loanToken:t,bendVault:o,rewardVault:r,amount:s?_viem.parseUnits.call(void 0, s,_nullishCoalesce(_optionalChain([e, 'optionalAccess', _183 => _183.decimals]), () => (18))).toString():void 0,slippage:n},i),{data:u}=zo({sharesAmount:BigInt(_nullishCoalesce(_optionalChain([l, 'access', _184 => _184.data, 'optionalAccess', _185 => _185.amountOut]), () => (0))),vaultAddress:o.address}),{data:m}=Te({tokenIn:e,tokenOut:t,formattedAmountIn:s,formattedAmountOut:_nullishCoalesce(_optionalChain([u, 'optionalAccess', _186 => _186.formatted]), () => ("0"))}),p=_optionalChain([e, 'optionalAccess', _187 => _187.chainId])&&e.chainId!==_internal.defaultChainId,{data:c,isLoading:d}=Ie({address:_viem.zeroAddress,chainId:p?_optionalChain([e, 'optionalAccess', _188 => _188.chainId]):void 0},{opts:{isEnabled:!!p}}),f=_nullishCoalesce(_optionalChain([l, 'access', _189 => _189.data, 'optionalAccess', _190 => _190.getCalldata, 'optionalCall', _191 => _191({account:_viem.zeroAddress}), 'optionalAccess', _192 => _192.value]), () => (0n)),y=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _193 => _193.balance]), () => ({raw:"0",formatted:"0"})),A=p&&f>0n&&!d&&f>BigInt(y.raw),h=p&&f>0n?_viem.formatEther.call(void 0, f):void 0;return{...l,zapSupplyAmount:u,priceImpact:m,hasInsufficientNativeBalance:A,isCrossChain:p,nativeFee:h,refresh:()=>{l.mutate()}}}function Di({tokenIn:e,loanToken:t,bendVault:o,rewardVault:r,amount:s,slippage:n},i){let{address:a}=_hooks.useBeraWallet.call(void 0, ),l=!!e&&!!t&&!!o&&!!s&&!!a&&!_chunkSFEULGSXcjs.e.call(void 0, t.address,e.address)&&e.chainId&&Number(s)>0&&!!n,u=_hooks.usePublicClient.call(void 0, );return _swr2.default.call(void 0, l?["useBendZapSupply",e,t,o,r,s,n]:null,async([,p,c,d,f,y,A])=>(_chunkLVOXBZMAcjs.c.call(void 0, u),_chunkLVOXBZMAcjs.d.call(void 0, a,"fromAddress"),_chunkLVOXBZMAcjs.d.call(void 0, _optionalChain([p, 'optionalAccess', _194 => _194.address]),"tokenInAddress"),_chunkLVOXBZMAcjs.b.call(void 0, _optionalChain([p, 'optionalAccess', _195 => _195.chainId]),"tokenInChainId"),ve.getQuote({tokenIn:p,tokenOut:d,underlyingToken:c,amount:y,slippage:A,account:a,rewardVault:f})),{..._optionalChain([i, 'optionalAccess', _196 => _196.opts]),refreshInterval:1e5})}async function Fr({fromAddress:e,amountIn:t,tokenIn:o,tokenOut:r,chainId:s,ensoClient:n,destinationChainId:i,slippage:a,publicClient:l}){if(!e)throw new (0, _chunk6JJIZCVYcjs.h)({property:"fromAddress",value:e,expected:"address"});r===_viem.zeroAddress&&(r=_viem.ethAddress);let u={protocol:"enso",action:"route",args:{tokenIn:o,tokenOut:r,amountIn:t,slippage:a*100}};i&&i!==s&&(u.args={...u.args,destinationChainId:i,refundReceiver:e});let m=await n.getBundleData({fromAddress:e,receiver:e,spender:e,chainId:s,routingStrategy:"router"},[u]),p=await Dr({fromAddress:e,amountIn:t,tokenIn:o,chainId:s,ensoClient:n,bundle:m,publicClient:l});return{bundle:m,transactions:p}}function Oe(e,t){let o=_hooks.usePublicClient.call(void 0, ),r=_hooks.useConfig.call(void 0, ),{address:s}=_hooks.useBeraWallet.call(void 0, ),{tokenList:n,refresh:i}=oe(),a=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _197 => _197.walletAddress]), () => (s)),l=_react.useMemo.call(void 0, ()=>new Map(_nullishCoalesce(_optionalChain([(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _198 => _198.tokens]), () => (n))), 'optionalAccess', _199 => _199.map, 'call', _200 => _200(p=>[p.address.toLowerCase(),p])]), () => ([]))),[n,_optionalChain([e, 'optionalAccess', _201 => _201.tokens])]),u=o&&n!==void 0&&a?["usePollWalletBalances",a,Array.from(l.values())]:null,m=_swr2.default.call(void 0, u,async([,p,c])=>_chunkBC2WX6O6cjs.c.call(void 0, {account:p,tokenList:c,wagmiConfig:r}),{refreshInterval:1e5,..._optionalChain([t, 'optionalAccess', _202 => _202.opts])});return{...m,refresh:()=>{_optionalChain([m, 'optionalAccess', _203 => _203.mutate, 'optionalCall', _204 => _204()]),i()}}}function vh({tokenIn:e,tokenOut:t,amount:o,slippage:r}){let{address:s}=_hooks.useBeraWallet.call(void 0, ),n=_hooks.useConfig.call(void 0, ),i=_chunkBC2WX6O6cjs.a.call(void 0, ),{refresh:a}=Oe(),l=!!e&&!!t&&!!o&&Number(o)>0&&!!r&&!!s&&!!e.chainId,m=_swr2.default.call(void 0, l?["useEnsoSwapBundle",e,t,o,r]:null,async([,p,c,d,f])=>{_chunkLVOXBZMAcjs.d.call(void 0, s,"fromAddress"),_chunkLVOXBZMAcjs.d.call(void 0, _optionalChain([p, 'optionalAccess', _205 => _205.address]),"tokenInAddress"),_chunkLVOXBZMAcjs.b.call(void 0, _optionalChain([p, 'optionalAccess', _206 => _206.chainId]),"tokenInChainId"),_chunkLVOXBZMAcjs.d.call(void 0, _optionalChain([c, 'optionalAccess', _207 => _207.address]),"tokenOutAddress"),_chunkLVOXBZMAcjs.f.call(void 0, d,"amount"),_chunkLVOXBZMAcjs.f.call(void 0, f,"slippage");let y=_core.getPublicClient.call(void 0, n,{chainId:p.chainId});_chunkLVOXBZMAcjs.c.call(void 0, y);let A=_viem.parseUnits.call(void 0, d,p.decimals).toString();return Fr({fromAddress:s,amountIn:A,tokenIn:p.address,tokenOut:c.address,chainId:p.chainId,ensoClient:i,destinationChainId:_internal.defaultChainId,slippage:f,publicClient:y})},{refreshInterval:1e5,isEnabled:l});return{...m,refresh:()=>{m.mutate(),a()}}}function Wh({inputToken:e,amount:t,underlyingToken:o,slippage:r,tokenOut:s},n){let{address:i}=_hooks.useBeraWallet.call(void 0, ),a=_nullishCoalesce(i, () => (_internal.chainConfigs[_internal.defaultChainId].bex.aggregatorsRouterExecutor)),u=!!e&&!!t&&Number(t)>0&&!!e.chainId&&!!o&&!!r?["useZapStakeBera",e,t,a,r,o,s]:null,m=_swr2.default.call(void 0, u,async([,c,d,f,y,A,h])=>{let R=_viem.parseUnits.call(void 0, d,c.decimals).toString();return ve.getQuote({account:f,amount:R,tokenIn:c,underlyingToken:A,tokenOut:h,slippage:y})},{..._optionalChain([n, 'optionalAccess', _208 => _208.opts]),refreshInterval:1e5}),{data:p}=Te({tokenIn:e,tokenOut:s,formattedAmountIn:t,formattedAmountOut:_viem.formatUnits.call(void 0, BigInt(_nullishCoalesce(_optionalChain([m, 'access', _209 => _209.data, 'optionalAccess', _210 => _210.amountOut]), () => ("0"))),s.decimals)});return{...m,data:{...m.data,priceImpactPercentage:p,isCrossChain:e&&s.chainId!==_optionalChain([e, 'optionalAccess', _211 => _211.chainId])},refresh:()=>{m.mutate()}}}var _graymatter = require('gray-matter'); var _graymatter2 = _interopRequireDefault(_graymatter);var _beraChef = require('@berachain/abis/pol/rewards/beraChef');function De(e){return Object.values(e).some(t=>Array.isArray(t)?t.some(o=>typeof o=="object"&&o!==null?De(o):!!o):typeof t=="object"&&t!==null?De(t):!!t)}function Gr({proposal:e,currentTopic:t,onError:o}){let r=_chunk45HIEVNIcjs.r.call(void 0, {proposal:e,currentTopic:t}),s=[];if(r.actions=e.actions.map((a,l)=>{let u={};if(u.target=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"address",value:a.target}),a.type==="custom-action")if(a.input==="ABI")if(u.ABI=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"abi",value:a.ABI}),!a.functionSignature)u.functionSignature="Required";else try{let p=_viem.parseAbiItem.call(void 0, a.functionSignature);p.type!=="function"?(console.error("parsedSignatureAbi is not a function",p),u.functionSignature="Invalid ABI"):(u.args=p.inputs.map((c,d)=>{try{return"components"in c?_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:c.type,value:_optionalChain([a, 'access', _212 => _212.args, 'optionalAccess', _213 => _213[d]]),components:c.components}):_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:c.type,value:_optionalChain([a, 'access', _214 => _214.args, 'optionalAccess', _215 => _215[d]])})}catch (e3){return null}}),u.args.some(c=>c)||(s[l]=_viem.encodeFunctionData.call(void 0, {abi:[p],args:a.args})))}catch (e4){u.functionSignature="Invalid ABI"}else if(a.input==="rawCalldata")u.rawCalldata=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"hex",value:a.rawCalldata}),s[l]=a.rawCalldata;else if(a.input==="message")u.message=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"string",value:a.message}),s[l]=_viem.toHex.call(void 0, a.message);else throw new Error("Invalid input type");else if(a.type==="whitelist-reward-vault"||a.type==="blacklist-reward-vault"){if(u.vault=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"address",value:a.vault}),!u.vault){let p=a.type==="whitelist-reward-vault";s[l]=_viem.encodeFunctionData.call(void 0, {abi:_beraChef.beraChefAbi,functionName:"setVaultWhitelistedStatus",args:[a.vault,p,""]})}}else a.type==="whitelist-reward-vault-incentive"?(u.token=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"address",value:a.token}),u.minIncentiveRate=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"uint256",value:a.minIncentiveRate}),u.managerAddress=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"address",value:a.managerAddress}),!u.token&&!u.minIncentiveRate&&!u.managerAddress&&(s[l]=_viem.encodeFunctionData.call(void 0, {abi:_rewardVault.rewardVaultAbi,functionName:"whitelistIncentiveToken",args:[a.token,BigInt(a.minIncentiveRate),a.managerAddress]}))):a.type==="erc20-transfer"&&(u.amount=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"uint256",value:a.amount}),u.to=_chunk45HIEVNIcjs.n.call(void 0, {fieldOrType:"address",value:a.to}),!u.amount&&!u.to&&(s[l]=_viem.encodeFunctionData.call(void 0, {abi:_viem.erc20Abi,functionName:"transfer",args:[a.to,BigInt(a.amount)]})));return De(u)?u:null}),_optionalChain([o, 'optionalCall', _216 => _216(r)]),Object.getOwnPropertyNames(r).map(a=>r[a]).some(a=>Array.isArray(a)?a.filter(l=>l).length>0:a===null?!1:!!a)){console.warn("Proposal has errors",r);return}if(s.length===0)throw new Error("No actions submitted in proposal");let n=new URL(e.forumLink),i=_graymatter2.default.stringify(e.description,{title:e.title,topics:Array.from(e.topic.values()),forumLink:n.toString(),version:"1.0.0","content-encoding":"utf-8","content-type":"text/markdown",actions:e.actions.map(a=>{let l={type:a.type};return a.type==="custom-action"&&(l.inputType=a.input),l})});return[e.actions.map(a=>a.target),e.actions.map(a=>_nullishCoalesce(a.value, () => (0n))),s,i]}var Kr={type:"custom-action",target:"",ABI:"",value:0n,functionSignature:"",args:[],input:"ABI",rawCalldata:"0x",message:""},il= exports.useCreateProposal =({initialData:e={},currentTopic:t,onError:o})=>{let[r,s]=_react.useState.call(void 0, {title:"",description:"",forumLink:"",actions:[Kr],...e,topic:new Set});_react.useEffect.call(void 0, ()=>{s(l=>({...l,topic:new Set([t.id])}))},[t]);let n=_react.useCallback.call(void 0, ()=>{s(l=>({...l,actions:[...l.actions,Kr]}))},[]),i=_react.useCallback.call(void 0, l=>{s(u=>{let m=[...u.actions];return m.splice(l,1),{...u,actions:m}})},[s]),a=_react.useCallback.call(void 0, ()=>r?Gr({proposal:r,currentTopic:t,onError:o}):void 0,[r,t]);return{proposal:r,setProposal:s,addProposalAction:n,removeProposalAction:i,computeParamsAndErrors:a}};var _bgt = require('@berachain/abis/pol/bgt');var _berachainGovernance = require('@berachain/abis/gov/berachainGovernance');var qr=({proposalId:e})=>{let t=_hooks.usePublicClient.call(void 0, );return _immutable2.default.call(void 0, t&&e?["useProposalSnapshot",e]:null,async([,r])=>{_chunkLVOXBZMAcjs.c.call(void 0, t);let{config:s}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:t.chain.id});return(await t.readContract({abi:_berachainGovernance.berachainGovernanceAbi,address:s.governance.governor,functionName:"proposalSnapshot",args:[BigInt(r)]})).toString()})};var dR=e=>{let{address:t}=_hooks.useBeraWallet.call(void 0, ),o=_hooks.usePublicClient.call(void 0, ),r=e.wallet||t,{data:s}=qr({proposalId:e.proposalId}),n=e.timepoint||s;return _immutable2.default.call(void 0, n&&o&&r?["useGetPastVotes",n,r]:null,async([,a,l])=>{_chunkLVOXBZMAcjs.c.call(void 0, o);let{config:u}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:o.chain.id});if(Number(a)>Date.now()/1e3)throw new Error("timepoint is in the future");let m=await o.readContract({abi:_bgt.bgtAbi,address:u.tokens.bgt,functionName:"getPastVotes",args:[l,BigInt(a)]});return _viem.formatUnits.call(void 0, m,18)})};var RR=({proposalId:e,wallet:t})=>{let{address:o}=_hooks.useBeraWallet.call(void 0, ),r=_hooks.usePublicClient.call(void 0, ),s=t||o;return _swr2.default.call(void 0, r&&s&&_viem.isAddress.call(void 0, s)?["useHasVoted",e,s]:null,([,n,i])=>{_chunkLVOXBZMAcjs.c.call(void 0, r);let{config:a}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:r.chain.id});return r.readContract({address:a.governance.governor,abi:_berachainGovernance.berachainGovernanceAbi,functionName:"hasVoted",args:[BigInt(n),i]})})};var _timeLock = require('@berachain/abis/gov/timeLock');var $r="0xfd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783";var xR=({account:e,...t})=>{let o=_hooks.usePublicClient.call(void 0, ),{config:r}=_chunkSFEULGSXcjs.a.call(void 0, t);return _swr2.default.call(void 0, e&&o?["useCancellerRole",e]:null,async([,n])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),await o.readContract({abi:_timeLock.timeLockAbi,address:r.governance.timelock,functionName:"hasRole",args:[$r,n]})),{refreshInterval:18e4,revalidateOnFocus:!1})};var _infinite = require('swr/infinite'); var _infinite2 = _interopRequireDefault(_infinite);var _governance = require('@berachain/graphql/governance');var jr=10,Sl=e=>{switch(e){case _governance.ProposalStatus.QuorumNotReached:return[_governance.ProposalStatus.Active,_governance.ProposalStatus.Pending];case _governance.ProposalStatus.PendingQueue:case _governance.ProposalStatus.Defeated:return[_governance.ProposalStatus.Active];case _governance.ProposalStatus.PendingExecution:return[_governance.ProposalStatus.InQueue];default:return[e]}};function xl(e,t={}){let o=2*(_nullishCoalesce(t.perPage, () => (jr)));return(r,s)=>{if(r!==0&&s&&s.length<o)return null;let n=_optionalChain([t, 'access', _217 => _217.status_in, 'optionalAccess', _218 => _218.flatMap, 'call', _219 => _219(Sl), 'access', _220 => _220.filter, 'call', _221 => _221((i,a,l)=>l.indexOf(i)===a)]);return["usePollAllProposals",r,e,t.where,n,t.orderBy,t.orderDirection,o,t.text]}}function UR(e,t){let o=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _222 => _222.autoRefresh]), () => (!1)),r=_nullishCoalesce(e.perPage, () => (jr)),s=2*r,n=xl(e.topic,e);async function i(d){if(!d)return[];let[,f,y,A,h,R,b,P,w]=d;return(await _asyncNullishCoalesce(await _chunk45HIEVNIcjs.q.call(void 0, {where:{topics_contains:[y],status_in:_optionalChain([h, 'optionalAccess', _223 => _223.length])?h:void 0,...A},orderBy:R,orderDirection:b,text:w,perPage:P,offset:f*P}), async () => ([]))).filter(Boolean)}let a=_infinite2.default.call(void 0, n,i,{initialSize:1,refreshInterval:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _224 => _224.opts, 'optionalAccess', _225 => _225.refreshInterval]), () => (18e4)),..._optionalChain([t, 'optionalAccess', _226 => _226.opts])}),l=_react.useMemo.call(void 0, ()=>{if(!a.data)return[];let d=a.data.flat().filter(y=>y?_optionalChain([e, 'access', _227 => _227.status_in, 'optionalAccess', _228 => _228.length])?e.status_in.includes(y.status):!0:!1).sort((y,A)=>{if(!e.text)return 0;if(e.orderBy===_governance.Proposal_OrderBy.CreatedAt){let h=Number(A.createdAt)-Number(y.createdAt);return e.orderDirection==="asc"?h:-h}return 0}),f=[];for(let y=0;y<d.length;y+=r)f.push(d.slice(y,y+r));return f},[a.data,e,r]),u=_optionalChain([a, 'access', _229 => _229.data, 'optionalAccess', _230 => _230[a.data.length-1]]),m=!!u&&u.length===s,[p,c]=_react.useState.call(void 0, Date.now()/1e3);return _react.useEffect.call(void 0, ()=>{if(!o)return;let d=setInterval(()=>{c(Date.now()/1e3)},1e4);return()=>clearInterval(d)},[o]),_react.useEffect.call(void 0, ()=>{if(!a.data)return;let d=!1;for(let f of a.data.flat()){switch(f.status){case _governance.ProposalStatus.Pending:p>=Number(f.voteStartAt)&&(d=!0);break;case _governance.ProposalStatus.Active:p>=Number(f.voteEndAt)&&(d=!0);break;case _governance.ProposalStatus.InQueue:Date.now()/1e3+1>=Number(f.queueEnd)&&(d=!0);break;default:break}if(d)break}d&&a.mutate()},[a.data,p]),{...a,data:l,hasMore:m}}var YR=(e,t)=>{let o=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _231 => _231.autoRefresh]), () => (!1)),r=_hooks.usePublicClient.call(void 0, ),n=_swr2.default.call(void 0, e&&r?["usePollProposal",e]:null,([,l])=>(_chunkLVOXBZMAcjs.c.call(void 0, r),_chunk45HIEVNIcjs.s.call(void 0, {proposalId:l,client:r})),{..._optionalChain([t, 'optionalAccess', _232 => _232.opts]),refreshInterval:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _233 => _233.opts, 'optionalAccess', _234 => _234.refreshInterval]), () => (18e4))}),[i,a]=_react.useState.call(void 0, Date.now());return _react.useEffect.call(void 0, ()=>{if(!o)return;let l=setInterval(()=>{a(Date.now()/1e3)},1e4);return()=>clearInterval(l)},[]),_react.useEffect.call(void 0, ()=>{if(n.data!==void 0)switch(n.data.status){case _governance.ProposalStatus.Pending:i>=Number(n.data.voteStartAt)&&n.mutate();break;case _governance.ProposalStatus.Active:i>=Number(n.data.voteEndAt)&&n.mutate();break;case _governance.ProposalStatus.InQueue:Date.now()/1e3+1>=Number(n.data.queueEnd)&&n.mutate();break}},[_optionalChain([n, 'access', _235 => _235.data, 'optionalAccess', _236 => _236.status]),i]),{...n,refresh:()=>_optionalChain([n, 'optionalAccess', _237 => _237.mutate, 'optionalCall', _238 => _238()])}};var jR=e=>{let t=_hooks.usePublicClient.call(void 0, ),r=_swr2.default.call(void 0, t?["usePollProposalThreshold",e]:null,async([,s])=>{_chunkLVOXBZMAcjs.c.call(void 0, t);let n=await t.readContract({address:s,abi:_berachainGovernance.berachainGovernanceAbi,functionName:"proposalThreshold"});return{votesThreshold:_viem.formatEther.call(void 0, n)}},{refreshInterval:18e4});return{...r,refresh:r.mutate}};var Ue=1e3,ew= exports.usePollProposalVotes =(e,t)=>_infinite2.default.call(void 0, Vl(e,t),async([o,r])=>_chunk45HIEVNIcjs.v.call(void 0, {variables:{...e,limit:Ue,offset:Ue*r}}),{parallel:!0,initialSize:Number.POSITIVE_INFINITY}),Vl= exports.usePollProposalVotesQueryKey =({...e},t)=>o=>o>Math.floor(t/Ue)?null:["usePollProposalVotes",o,Ue,e.proposalId,e.orderBy,e.orderDirection];var lw=e=>{let{address:t}=_hooks.useBeraWallet.call(void 0, ),o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, t?["usePollUserDelegates",t]:null,async([,n])=>{_chunkLVOXBZMAcjs.c.call(void 0, o);let{config:i}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:o.chain.id});if(!o||!n)throw new Error("usePollUserDelegates needs publicClient and account");let[a,l]=await Promise.all([o.readContract({address:i.tokens.bgt,abi:_bgt.bgtAbi,functionName:"delegates",args:[n]}),o.readContract({address:i.tokens.bgt,abi:_bgt.bgtAbi,functionName:"getVotes",args:[n]})]);return{delegate:a,currentVotes:_viem.formatEther.call(void 0, l)}},{..._optionalChain([e, 'optionalAccess', _239 => _239.opts]),refreshInterval:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _240 => _240.opts, 'optionalAccess', _241 => _241.refreshInterval]), () => (18e4))});return{...s,refresh:()=>_optionalChain([s, 'optionalAccess', _242 => _242.mutate, 'optionalCall', _243 => _243()])}};var cw=e=>{let{data:t}=_hooks.useTransactionReceipt.call(void 0, {hash:e}),o=_hooks.usePublicClient.call(void 0, );return _swr2.default.call(void 0, t&&o?["useProposalFromTx",e]:null,async([,n])=>{if(!t)throw new Error("Transaction not found");if(t.transactionHash!==n)throw new Error("Transaction hash mismatch");return _chunk45HIEVNIcjs.u.call(void 0, {tx:t,publicClient:o})})};var zl={0:"pending",1:"active",2:"canceled",3:"defeated",4:"succeeded",5:"queued",6:"expired",7:"executed"},hw= exports.useProposalState =({proposalId:e,governorAddress:t})=>{let o=_hooks.usePublicClient.call(void 0, );return _immutable2.default.call(void 0, t&&o&&e?["useProposalState",e]:null,async([,s])=>{_chunkLVOXBZMAcjs.c.call(void 0, o);let n=await o.readContract({abi:_berachainGovernance.berachainGovernanceAbi,address:t,functionName:"state",args:[BigInt(s)]});return zl[n]})};var Xl={0:"unset",1:"waiting",2:"ready",3:"done"};function Iw({proposalTimelockId:e,timelockAddress:t}){let o=_hooks.usePublicClient.call(void 0, );return _swr2.default.call(void 0, t&&o&&e?["useProposalTimelockState",e,t]:null,async([,s,n])=>{_chunkLVOXBZMAcjs.c.call(void 0, o);let i=await o.readContract({abi:_timeLock.timeLockAbi,address:n,functionName:"getOperationState",args:[s]});return Xl[i]},{refreshInterval:18e4})}async function St({at:e,publicClient:t,...o}){let{config:r}=_chunkSFEULGSXcjs.a.call(void 0, o);_chunkLVOXBZMAcjs.c.call(void 0, t);let s=await t.readContract({address:r.governance.governor,abi:_berachainGovernance.berachainGovernanceAbi,functionName:"quorum",blockTag:"pending",args:[BigInt(_nullishCoalesce(e, () => (Math.floor(Date.now()/1e3))))]});return _viem.formatEther.call(void 0, s)}function Uw({at:e},{isEnabled:t=!0}){let o=Math.floor(Date.now()/1e3),r=_hooks.usePublicClient.call(void 0, ),s=t&&r?["useQuorum",Number(e)>o?"now":e]:null,n=_swr2.default.call(void 0, s,async([,i])=>i==="now"?St({publicClient:r}):St({at:i,publicClient:r}));return{...n,data:n.data?Number(n.data):void 0}}function ae({priceFeedMap:e},t){let o=e?Object.values(e):null,r=(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _244 => _244.opts, 'optionalAccess', _245 => _245.isEnabled]), () => (!0)))&&o?["usePythLatestPrices",o]:null;return _swr2.default.call(void 0, r,async([n,i])=>await _chunk45HIEVNIcjs.G.call(void 0, {priceFeedId:i}))}var Xr=({asset:e,amount:t,isMint:o,isBasketModeEnabled:r},s)=>{let n=_hooks.usePublicClient.call(void 0, ),{priceFeedMap:i,flags:a}=_chunkQ2SNRLW3cjs.l.call(void 0, ),{data:l}=ae({priceFeedMap:_optionalChain([e, 'optionalAccess', _246 => _246.address])&&i?{[e.address]:i[e.address]}:void 0},{opts:{isEnabled:a.isPythWrapperEnabled&&!!_optionalChain([e, 'optionalAccess', _247 => _247.address])}}),u=t&&e&&(a.isPythWrapperEnabled&&_optionalChain([l, 'optionalAccess', _248 => _248.prices, 'access', _249 => _249.length])||!a.isPythWrapperEnabled)?["useCappedGlobally",t,e,l,a.isPythWrapperEnabled,r]:null,m=_swr2.default.call(void 0, u,async([p,c,d,f,y,A])=>A?!1:(_chunkLVOXBZMAcjs.c.call(void 0, n),await _chunk45HIEVNIcjs.B.call(void 0, {client:n,asset:d,amount:o?c:`-${c}`,isMint:o,latestPrices:f,isPythWrapperEnabled:y})),{..._optionalChain([s, 'optionalAccess', _250 => _250.opts]),refreshInterval:0});return{...m,refresh:()=>{m.mutate()}}};var es=({asset:e,amount:t,isMint:o,isBasketModeEnabled:r},s)=>{let n=_hooks.usePublicClient.call(void 0, ),{collateralList:i,referenceCollateral:a}=_chunkQ2SNRLW3cjs.l.call(void 0, ),u=_swr2.default.call(void 0, e&&t?["useCappedRelatively",e,t,i,a]:null,async([m,p,c,d,f])=>{if(r)return!1;if(_chunkLVOXBZMAcjs.c.call(void 0, n),!o){let y=`-${c}`;return f.address!==p?!1:(await Promise.all(d.map(h=>_chunk45HIEVNIcjs.H.call(void 0, {client:n,asset:h.address,amount:y,isMint:o,referenceCollateral:f})))).some(h=>h)}return await _chunk45HIEVNIcjs.H.call(void 0, {client:n,asset:p,amount:c,isMint:o,referenceCollateral:f})},{refreshInterval:0,..._optionalChain([s, 'optionalAccess', _251 => _251.opts])});return{...u,refresh:()=>{u.mutate()}}};var rk=({collateralList:e},t)=>{let o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, o&&e?["useCollateralWeights",e]:void 0,async([n,i])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),await _chunk45HIEVNIcjs.x.call(void 0, {client:o,collateralList:i})),{..._optionalChain([t, 'optionalAccess', _252 => _252.opts]),refreshInterval:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _253 => _253.opts, 'optionalAccess', _254 => _254.refreshInterval]), () => (1e5))});return{...s,refresh:()=>{s.mutate()}}};function ik(){let e=_swr2.default.call(void 0, ["useHoney24hVolume"],()=>_chunk45HIEVNIcjs.C.call(void 0, ),{refreshInterval:18e4});return{...e,refresh:()=>e.mutate()}}var ts=()=>{let e=_hooks.usePublicClient.call(void 0, ),{address:t}=_hooks.useBeraWallet.call(void 0, ),{collateralList:o}=_chunkQ2SNRLW3cjs.l.call(void 0, ),r=_hooks.useConfig.call(void 0, ),n=_swr2.default.call(void 0, t&&o&&e?["useHoneyBalances",t,o]:null,async([i,a,l])=>{_chunkLVOXBZMAcjs.c.call(void 0, e);let u=[..._nullishCoalesce(l, () => ([])),_chunkSFEULGSXcjs.d.call(void 0, {})];return await _asyncOptionalChain([(await _chunkBC2WX6O6cjs.c.call(void 0, {account:a,tokenList:u,wagmiConfig:r})), 'optionalAccess', async _255 => _255.reduce, 'call', async _256 => _256((c,d)=>(c[d.address]=d,c),{})])},{refreshInterval:1e4});return{...n,refresh:()=>n.mutate()}};var os=e=>{let t=_hooks.usePublicClient.call(void 0, ),{collateralList:o}=_chunkQ2SNRLW3cjs.l.call(void 0, ),s=_swr2.default.call(void 0, o&&t?["useHoneyVaultsBalance",o]:null,async([n,i])=>(_chunkLVOXBZMAcjs.c.call(void 0, t),await _chunk45HIEVNIcjs.F.call(void 0, {client:t,collateralList:i})),{..._optionalChain([e, 'optionalAccess', _257 => _257.opts]),refreshInterval:1e5});return{...s,refresh:()=>{s.mutate()}}};var rs=({collateral:e},t)=>{let o=_hooks.usePublicClient.call(void 0, ),{priceFeedMap:r,flags:s}=_chunkQ2SNRLW3cjs.l.call(void 0, ),{data:n}=ae({priceFeedMap:_optionalChain([e, 'optionalAccess', _258 => _258.address])?{[e.address]:r[e.address]}:void 0},{opts:{isEnabled:s.isPythWrapperEnabled&&!!_optionalChain([e, 'optionalAccess', _259 => _259.address])}}),i=o&&e&&(s.isPythWrapperEnabled&&_optionalChain([n, 'optionalAccess', _260 => _260.prices, 'access', _261 => _261.length])||!s.isPythWrapperEnabled)?["useIsBadCollateralAsset",e,n,s.isPythWrapperEnabled]:null,a=_swr2.default.call(void 0, i,async([l,u,m,p])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),await _chunk45HIEVNIcjs.A.call(void 0, {client:o,collateral:u,latestPrices:m,isPythWrapperEnabled:p})),{..._optionalChain([t, 'optionalAccess', _262 => _262.opts]),refreshInterval:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _263 => _263.opts, 'optionalAccess', _264 => _264.refreshInterval]), () => (1e5))});return{...a,refresh:()=>{a.mutate()}}};var ss=({lowerThan:e,vaultsBalances:t,state:o,collateralList:r})=>{if(!(o.actionType==="mint")&&!o.isBasketModeEnabled){let n=_optionalChain([t, 'optionalAccess', _265 => _265.find, 'call', _266 => _266(l=>l.address.toLowerCase()===o.collaterals[0].address.toLowerCase())]),i=new (0, _chunk6DIA6PXVcjs.a)(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _267 => _267.balance, 'access', _268 => _268.formatted]), () => ("0"))).lte(e),a=r.filter(l=>{let u=_optionalChain([t, 'optionalAccess', _269 => _269.find, 'call', _270 => _270(m=>m.address.toLowerCase()===l.address.toLowerCase())]);return new (0, _chunk6DIA6PXVcjs.a)(_nullishCoalesce(_optionalChain([u, 'optionalAccess', _271 => _271.balance, 'access', _272 => _272.formatted]), () => ("0"))).lte(e)});return{isLow:i,isLiquidityLowCollaterals:a}}return{isLow:!1,isLiquidityLowCollaterals:[]}},Ru=({vaultsBalances:e,redeemedVaultBalance:t,state:o,collateralList:r})=>{if(!(o.actionType==="mint")&&e&&t){let n=r.filter(i=>{let a=e.find(u=>u.address.toLowerCase()===i.address.toLowerCase()),l=o.toAmount[o.collaterals.indexOf(i)];return new (0, _chunk6DIA6PXVcjs.a)(_nullishCoalesce(_optionalChain([a, 'optionalAccess', _273 => _273.balance, 'access', _274 => _274.formatted]), () => ("0"))).lt(_nullishCoalesce(l, () => ("0")))});return{isMore:!!n.find(i=>_chunkSFEULGSXcjs.e.call(void 0, i,o.collaterals[0])),isRedeemMoreThanLiquidityCollaterals:n}}return{isMore:!1,isRedeemMoreThanLiquidityCollaterals:void 0}};function wu({state:e,honeyBalances:t,...o}){let{config:r}=_chunkSFEULGSXcjs.a.call(void 0, o),s=e.actionType==="mint";return!s&&t?new (0, _chunk6DIA6PXVcjs.a)(e.fromAmount[0]).gt(_nullishCoalesce(_optionalChain([t, 'access', _275 => _275[r.honey.token], 'optionalAccess', _276 => _276.balance, 'access', _277 => _277.formatted]), () => ("0"))):s&&t&&e.isBasketModeEnabled!==void 0&&e.collaterals.length>0?e.isBasketModeEnabled?e.collaterals.some((n,i)=>{let a=e.fromAmount[i];return new (0, _chunk6DIA6PXVcjs.a)(_optionalChain([t, 'access', _278 => _278[n.address], 'optionalAccess', _279 => _279.balance, 'access', _280 => _280.formatted])).lt(a)}):new (0, _chunk6DIA6PXVcjs.a)(_optionalChain([t, 'access', _281 => _281[e.collaterals[0].address], 'optionalAccess', _282 => _282.balance, 'access', _283 => _283.formatted])).lt(e.fromAmount[0]):!1}var Wk=({actionType:e,collaterals:t,fromAmount:o,toAmount:r,isBasketModeEnabled:s})=>{let n={actionType:e,collaterals:t,fromAmount:o,toAmount:r,isBasketModeEnabled:s},i=e==="mint",{data:a}=rs({collateral:t[0]}),{collateralList:l}=_chunkQ2SNRLW3cjs.l.call(void 0, ),{isBlacklisted:u,isDepegged:m}=_nullishCoalesce(a, () => ({isBlacklisted:!1,isDepegged:!1})),{data:p}=Xr({asset:t[0],amount:i?o[0]:r[0],isMint:i,isBasketModeEnabled:s}),{data:c}=es({asset:_optionalChain([t, 'access', _284 => _284[0], 'optionalAccess', _285 => _285.address]),amount:i?o[0]:r[0],isMint:i,isBasketModeEnabled:s}),{data:d}=ts(),{data:f}=os(),y=_optionalChain([t, 'access', _286 => _286[0], 'optionalAccess', _287 => _287.address]),A=_optionalChain([f, 'optionalAccess', _288 => _288.find, 'call', _289 => _289(I=>I.address.toLowerCase()===y.toLowerCase())]),[h,R]=_react.useMemo.call(void 0, ()=>{let I=ss({lowerThan:1,vaultsBalances:f,state:n,collateralList:l}),T=ss({lowerThan:1e3,vaultsBalances:f,state:n,collateralList:l});return[I,T]},[f,n]),{isMore:b,isRedeemMoreThanLiquidityCollaterals:P}=_react.useMemo.call(void 0, ()=>Ru({vaultsBalances:f,redeemedVaultBalance:A,state:n,collateralList:l}),[f,A,n,l]),w=_react.useMemo.call(void 0, ()=>wu({state:n,honeyBalances:d}),[n,d]);return{isLiquidityDepleted:h.isLow,isLiquidityDepletedCollaterals:h.isLiquidityLowCollaterals,isRedeemMoreThanLiquidity:b,isRedeemMoreThanLiquidityCollaterals:P,isLowLiquidity:R.isLow,isLiquidityLowCollaterals:R.isLiquidityLowCollaterals,isBlacklisted:n.isBasketModeEnabled?!1:u,isDepegged:n.isBasketModeEnabled?!1:m,isCappedGlobally:p,isCappedRelatively:c,isExceedingBalance:w}};function Yk({days:e}){let t=_swr2.default.call(void 0, ["useHoneyChartData",e],async([o,r])=>await _chunk45HIEVNIcjs.w.call(void 0, {days:r}));return{...t,refresh:()=>t.mutate()}}function ns({state:e},t){let o=_hooks.usePublicClient.call(void 0, ),{priceFeedMap:r,flags:s,collateralList:n}=_chunkQ2SNRLW3cjs.l.call(void 0, ),{data:i}=ae({priceFeedMap:r},{opts:{isEnabled:s.isPythWrapperEnabled&&!!n.length}}),a=e.actionType==="mint",l=o&&e&&n.length>0&&(s.isPythWrapperEnabled&&_optionalChain([i, 'optionalAccess', _290 => _290.prices, 'access', _291 => _291.length])||!s.isPythWrapperEnabled)?["useIsBasketModeEnabled",a,i,s.isPythWrapperEnabled,n]:null,u=_swr2.default.call(void 0, l,async([m,p,c,d,f])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),await _chunk45HIEVNIcjs.K.call(void 0, {client:o,isMint:p,collateralList:f,latestPrices:c,isPythWrapperEnabled:d})),{..._optionalChain([t, 'optionalAccess', _292 => _292.opts]),refreshInterval:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _293 => _293.opts, 'optionalAccess', _294 => _294.refreshInterval]), () => (1e4))});return{...u,data:u.data,refresh:()=>{u.mutate()}}}var Su={actionType:"mint",collaterals:[],fromAmount:[],toAmount:[],isBasketModeEnabled:!1,isTyping:!1,isSubmitting:!1,isLoading:!1};function is(e,t){switch(t.type){case"RESET_AMOUNTS":return{...e,fromAmount:[],toAmount:[]};case"ACTION_TYPE_CHANGE":return is({...e,actionType:t.value},{type:"RESET_AMOUNTS"});case"COLLATERALS_CHANGE":return{...e,collaterals:t.value,fromAmount:[],toAmount:[]};case"FROM_AMOUNT_CHANGE":{let o=e.fromAmount;return o[t.index]=t.value,{...e,fromAmount:o}}case"TO_AMOUNT_CHANGE":{let o=e.toAmount;return o[t.index]=t.value,{...e,toAmount:o}}case"PREVIEW_CHANGE":{let o=t.value,r=e.actionType==="mint",s=e.collaterals.map((i,a)=>t.changedAsset===i.address?r?e.fromAmount[a]:e.toAmount[a]:o.collaterals[i.address]?_viem.formatUnits.call(void 0, o.collaterals[i.address],i.decimals):e.isBasketModeEnabled?"0":""),n=_chunkSFEULGSXcjs.e.call(void 0, t.changedAsset,"HONEY",{chainId:_internal.defaultChainId})?r?e.toAmount[0]:e.fromAmount[0]:o.honey?_viem.formatUnits.call(void 0, o.honey,18):e.isBasketModeEnabled?"0":"";return{...e,fromAmount:r?s:[n],toAmount:r?[n]:s}}case"IS_BASKET_MODE_ENABLED_CHANGE":return{...e,isBasketModeEnabled:t.value,fromAmount:[],toAmount:[]};case"IS_TYPING_CHANGE":return{...e,isTyping:t.value};case"IS_SUBMITTING_CHANGE":return{...e,isSubmitting:t.value};case"IS_LOADING_CHANGE":return{...e,isLoading:t.value};default:throw new Error(`Unknown action type: ${t}`)}}var sP=()=>{let{collateralList:e}=_chunkQ2SNRLW3cjs.l.call(void 0, ),[t,o]=_react.useReducer.call(void 0, is,Su,s=>({...s,collaterals:e})),{data:r}=ns({state:t});return _react.useEffect.call(void 0, ()=>{r!==void 0&&t.isBasketModeEnabled!==r&&(o({type:"IS_LOADING_CHANGE",value:!0}),o({type:"IS_BASKET_MODE_ENABLED_CHANGE",value:r}),o({type:"IS_LOADING_CHANGE",value:!1}))},[r]),{state:t,dispatch:o}};var mP=({pythPriceFeedCalldata:e,tokenListLength:t},o)=>{let r=_hooks.usePublicClient.call(void 0, ),s=(_nullishCoalesce(_optionalChain([o, 'optionalAccess', _295 => _295.opts, 'optionalAccess', _296 => _296.isEnabled]), () => (!0)))&&e&&e.length>0?["usePythUpdateFee",e]:null,{data:n=_chunk6DIA6PXVcjs.k.call(void 0, t),isLoading:i}=_immutable2.default.call(void 0, s,async([a,l])=>(_chunkLVOXBZMAcjs.c.call(void 0, r),_chunk45HIEVNIcjs.I.call(void 0, {client:r,priceFeedId:l})));return{QUERY_KEY:s,data:n,isLoading:i}};function gP(e){return _react.useMemo.call(void 0, ()=>{if(e)return _chunk45HIEVNIcjs.O.call(void 0, e)},[e])}var Nu=e=>{let{address:t}=_hooks.useBeraWallet.call(void 0, ),o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, t&&o?["useBgtUnstakedBalance",t]:null,async([,n])=>{_chunkLVOXBZMAcjs.c.call(void 0, o);let{config:i}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:o.chain.id}),a=await o.readContract({address:i.tokens.bgt,abi:_bgt.bgtAbi,functionName:"unboostedBalanceOf",args:[n]});return _viem.formatEther.call(void 0, a)},{...e,refreshInterval:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _297 => _297.opts, 'optionalAccess', _298 => _298.refreshInterval]), () => (1e5))});return{...s,refresh:()=>s.mutate()}};var Mu=()=>{let{address:e}=_hooks.useBeraWallet.call(void 0, ),t=_hooks.usePublicClient.call(void 0, ),r=_swr2.default.call(void 0, e&&t?["useClaimableFees",e]:null,async([,s])=>{_chunkLVOXBZMAcjs.c.call(void 0, t);let{config:n}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:t.chain.id}),i=await _chunk45HIEVNIcjs.ea.call(void 0, {account:s,vaultAddress:n.pol.staker,publicClient:t});return _viem.formatUnits.call(void 0, i,18)},{refreshInterval:18e4*2});return{...r,refresh:()=>_optionalChain([r, 'optionalAccess', _299 => _299.mutate, 'optionalCall', _300 => _300()])}};var _api = require('@berachain/graphql/pol/api');var Gu=(e,t=!1)=>["useRewardVaults",e,t],Bt= exports.useRewardVaults =(e,t)=>{let o=Gu(e.filter,e.onChainIncentives),r=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, _nullishCoalesce(_optionalChain([t, 'optionalAccess', _301 => _301.opts, 'optionalAccess', _302 => _302.isEnabled]), () => (!0))?o:null,async([,n,i])=>await _chunk45HIEVNIcjs.Q.call(void 0, {filter:n,publicClient:i?r:void 0}),{..._optionalChain([t, 'optionalAccess', _303 => _303.opts])});return{...s,refresh:s.mutate}};var NP=(e={},{isEnabled:t=!0}={})=>{let o=Bt({filter:{orderBy:_api.GqlRewardVaultOrderBy.Apr,orderDirection:_api.GqlRewardVaultOrderDirection.Desc,pageSize:1,where:e}},{opts:{refreshInterval:0,revalidateOnFocus:!1,refreshWhenOffline:!1,isEnabled:t}});return{isLoading:o.isLoading,highestApr:_optionalChain([o, 'access', _304 => _304.data, 'optionalAccess', _305 => _305.gaugeList, 'access', _306 => _306[0], 'access', _307 => _307.dynamicData, 'optionalAccess', _308 => _308.apr]),refresh:o.mutate}};var ls=e=>{let t=_hooks.usePublicClient.call(void 0, ),o=_swr2.default.call(void 0, t?"usePollGlobalData":null,async()=>(_chunkLVOXBZMAcjs.c.call(void 0, t),_chunk45HIEVNIcjs.R.call(void 0, t)),{revalidateOnFocus:!1,..._optionalChain([e, 'optionalAccess', _309 => _309.opts])});return{...o,refresh:o.mutate}};var Zu=()=>"usePollMarkets",KP= exports.usePollMarkets =e=>{let t=Zu(),o=_immutable2.default.call(void 0, t,async()=>await _chunk45HIEVNIcjs.T.call(void 0, ),{..._optionalChain([e, 'optionalAccess', _310 => _310.opts])});return{...o,refresh:()=>o.mutate()}};function XP({receiptTokenAddresses:e,account:t,version:o},r){let s=_hooks.usePublicClient.call(void 0, ),n=e&&t&&s&&_viem.isAddress.call(void 0, t)&&o?["useQueuedBeraUnlock",e,t,o]:null,i=_immutable2.default.call(void 0, n,async([,a,l,u])=>(_chunkLVOXBZMAcjs.c.call(void 0, s),await Promise.all(a.map(async m=>await _chunk45HIEVNIcjs.ba.call(void 0, {contractAddress:m,accountAddress:l,publicClient:s,version:u}))).then(m=>m.flat())),{refreshInterval:1e4,..._optionalChain([r, 'optionalAccess', _311 => _311.opts])});return{...i,refresh:()=>i.mutate()}}var lC=({address:e},t)=>{let o=e?["useRewardTokenToBeraRate",e]:null,r=_hooks.usePublicClient.call(void 0, {chainId:_internal.defaultChainId});return _swr2.default.call(void 0, o,async([s,n])=>{if(!n||!_viem.isAddress.call(void 0, n))throw new (0, _chunk6JJIZCVYcjs.h)({property:"address",value:n,expected:"Address"});return _chunkLVOXBZMAcjs.c.call(void 0, r),_chunk45HIEVNIcjs.V.call(void 0, {address:n,publicClient:r})},{..._optionalChain([t, 'optionalAccess', _312 => _312.opts])})};async function Ne({address:e,publicClient:t}){_chunkLVOXBZMAcjs.c.call(void 0, t);let[o,r,s,n]=await t.multicall({contracts:[{address:e,abi:_viem.erc20Abi,functionName:"decimals"},{address:e,abi:_viem.erc20Abi,functionName:"name"},{address:e,abi:_viem.erc20Abi,functionName:"symbol"},{address:e,abi:_viem.erc20Abi,functionName:"totalSupply"}],allowFailure:!0});return{address:e,decimals:o.result,name:r.result,symbol:s.result,totalSupply:n.result!==void 0?o.status==="success"?_viem.formatUnits.call(void 0, n.result,o.result):n.result.toString():void 0}}var dp=e=>e&&_viem.isAddress.call(void 0, e)?["onChainRewardVault",e.toLowerCase()]:null,us=({address:e},t)=>{let o=_hooks.usePublicClient.call(void 0, ),r=_nullishCoalesce(_optionalChain([t, 'access', _313 => _313.opts, 'optionalAccess', _314 => _314.isEnabled]), () => (!0)),s=dp(e);return _swr2.default.call(void 0, r&&o?s:null,async([,n])=>{_chunkLVOXBZMAcjs.c.call(void 0, o);let{config:i}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:o.chain.id}),a=await _chunk45HIEVNIcjs.Y.call(void 0, {address:n,publicClient:o}),[l,u,m]=await Promise.all([_chunk45HIEVNIcjs.X.call(void 0, {address:n,stakingToken:a,publicClient:o}),o.readContract({address:i.pol.beraChef,abi:_beraChef.beraChefAbi,functionName:"isWhitelistedVault",args:[n]}),o.readContract({address:a,abi:_viem.erc20Abi,functionName:"balanceOf",args:[n]})]),[p,c]=await Promise.all([Ne({address:a,publicClient:o}),Promise.all(l.map(d=>_chunk45HIEVNIcjs.y.call(void 0, {address:d.token,chainId:o.chain.id,publicClient:o})))]);if(!p)throw new Error("Staking token not found");return{id:n,address:n,vaultAddress:n,stakingToken:{address:a,name:_nullishCoalesce(p.name, () => ("")),symbol:_nullishCoalesce(p.symbol, () => ("")),decimals:_nullishCoalesce(p.decimals, () => (0))},stakingTokenAmount:_viem.formatUnits.call(void 0, m,_nullishCoalesce(p.decimals, () => (18))),isVaultWhitelisted:u,activeIncentives:l.map((d,f)=>({active:!!d.remainingAmount,remainingAmount:d.remainingAmount,remainingAmountUsd:"0",incentiveRate:d.incentiveRate,incentiveRateUsd:"0",tokenAddress:d.token,token:c[f]}))}})};var fp=e=>e?["useRewardVault",e.toLowerCase()]:null,TC= exports.useRewardVault =(e,t)=>{let o=fp(e),r=_swr2.default.call(void 0, o,async([i,a])=>_chunk45HIEVNIcjs.W.call(void 0, {address:a}),{..._optionalChain([t, 'optionalAccess', _315 => _315.opts])}),s=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _316 => _316.opts, 'optionalAccess', _317 => _317.isEnabled]), () => (((!!r.error||!r.isLoading)&&!r.data))),n=us({address:e},{opts:{..._optionalChain([t, 'optionalAccess', _318 => _318.opts]),isEnabled:s}});return{data:_nullishCoalesce(n.data, () => (r.data)),error:_nullishCoalesce(n.error, () => (r.error)),isLoading:n.isLoading||r.isLoading,isValidating:_nullishCoalesce(n.isValidating, () => (r.isValidating)),refresh:()=>{r.mutate(),n.mutate()}}};function DC({address:e,stakingToken:t}){let o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, o&&e&&t?["useRewardVaultIncentives",e,t]:null,async([,n,i])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),await _chunk45HIEVNIcjs.X.call(void 0, {address:n,stakingToken:i,publicClient:o})));return{...s,refresh:()=>_optionalChain([s, 'optionalAccess', _319 => _319.mutate, 'optionalCall', _320 => _320()])}}var hp=(e,t)=>{let o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, o&&e?["useRewardVaultRewards",e]:null,async([,n])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),await _chunk45HIEVNIcjs.N.call(void 0, n,o)),{..._optionalChain([t, 'optionalAccess', _321 => _321.opts])});return{...s,refresh:()=>_optionalChain([s, 'optionalAccess', _322 => _322.mutate, 'optionalCall', _323 => _323()])}};var Ve=e=>{let t=[],o="";for(let r of e){if(!r.timestamp&&!r._timestamp)continue;let s=(_nullishCoalesce(_nullishCoalesce(_optionalChain([r, 'optionalAccess', _324 => _324.timestamp]), () => (_optionalChain([r, 'optionalAccess', _325 => _325._timestamp]))), () => (0)))*1e3,n=new Date(s),i=n.toDateString();if(i!==o){let a=new Date(n.setHours(0,0,0,0)).getTime()/1e3;t.push({...r,timestamp:a,_timestamp:a}),o=i}}return t};function FC({range:e}){let o=_swr2.default.call(void 0, e?["useStakedAPR",e]:null,async([,r])=>{let s=await _chunk45HIEVNIcjs._.call(void 0, {range:r});return Ve(s.sort((i,a)=>i.timestamp-a.timestamp)).map(i=>({_timestamp:i.timestamp,apr:i.apr}))});return{...o,refresh:()=>o.mutate()}}var rI=e=>{let t=_chunkQ2SNRLW3cjs.c.call(void 0, "swberaAprWindow"),o=_hooks.usePublicClient.call(void 0, ),{address:r}=_hooks.useBeraWallet.call(void 0, ),s=_react.useMemo.call(void 0, ()=>e.map(b=>b.receiptToken),[e]),n=_react.useMemo.call(void 0, ()=>e.map(b=>b.inputTokens[0]),[e]),i=t?["useStakedData:apr",t]:null,{data:a}=_swr2.default.call(void 0, i,async([,b])=>_chunk45HIEVNIcjs.Z.call(void 0, {window:b}),{refreshInterval:1e5}),{data:l,isLoading:u}=Oe({tokens:s}),{getTokenPrice:m}=J({tokens:n}),p=o&&s.length>0?["useStakedData:exchangeRates",s]:null,{data:c}=_swr2.default.call(void 0, p,async([,b])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),Promise.all(b.map(P=>_chunk45HIEVNIcjs.V.call(void 0, {address:P.address,publicClient:o})))),{refreshInterval:1e5}),d=_react.useMemo.call(void 0, ()=>{if(!(!l||!c))return e.map((b,P)=>{let w=b.inputTokens[0],I=_nullishCoalesce(_optionalChain([l, 'access', _326 => _326.find, 'call', _327 => _327(Y=>Y.address===b.receiptToken.address), 'optionalAccess', _328 => _328.balance, 'access', _329 => _329.raw]), () => ("0")),T=_nullishCoalesce(c[P], () => (0)),S=_nullishCoalesce(m(w), () => (0)),U=new (0, _chunk6DIA6PXVcjs.a)(I).multipliedBy(T).dividedBy(10**w.decimals),v=U.multipliedBy(S);return{token:w,apr:_nullishCoalesce(a, () => (0)),stakedAmount:U.toNumber(),stakedAmountUsd:v.toNumber(),earnedAmount:0,earnedAmountUsd:0,isLoadingEarnings:!0}})},[l,c,e,a,m]),f=r&&o&&e.length>0?["useStakedData:positions",r,e]:null,{data:y,isLoading:A,isValidating:h}=_swr2.default.call(void 0, f,async([,b,P])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),Promise.all(P.map(async w=>{let I=w.receiptToken,[T,S]=await Promise.all([_chunk45HIEVNIcjs.P.call(void 0, {address:I.address,account:b}),_chunk45HIEVNIcjs.V.call(void 0, {address:I.address,publicClient:o})]);return{earnings:T,exchangeRate:S}}))),{refreshInterval:1e4}),R=_react.useMemo.call(void 0, ()=>{if(!(!y||!l))return e.map((b,P)=>{let w=b.inputTokens[0],I=b.receiptToken,{earnings:T,exchangeRate:S}=y[P],O=_nullishCoalesce(m(w), () => (0)),U=_nullishCoalesce(_optionalChain([l, 'access', _330 => _330.find, 'call', _331 => _331(_e=>_e.address===I.address), 'optionalAccess', _332 => _332.balance, 'access', _333 => _333.raw]), () => ("0")),v=_nullishCoalesce(S, () => (0)),Y=new (0, _chunk6DIA6PXVcjs.a)(T.earningsTotal).minus(T.earningsRealized),F=new (0, _chunk6DIA6PXVcjs.a)(U).multipliedBy(v).minus(Y).dividedBy(10**w.decimals),G=Y.dividedBy(10**w.decimals),D=F.multipliedBy(O),q=G.multipliedBy(O);return{token:w,apr:_nullishCoalesce(a, () => (0)),stakedAmount:F.toNumber(),earnedAmount:G.toNumber(),stakedAmountUsd:D.toNumber(),earnedAmountUsd:q.toNumber()}})},[y,l,e,a,m]);return{balances:d,data:R,isLoading:u&&A,isLoadingBalances:u,isLoadingPositions:A,isValidatingPositions:h}};async function ps({address:e,range:t}){let o=new Date,r=new Date(o.getTime()-Number(t)*24*60*60*1e3),{config:s}=_chunkSFEULGSXcjs.a.call(void 0, {}),n=`${_config.getUriFromLink.call(void 0, s.staking)}/vaults/${e}/total-assets-by-day?start=${r.toISOString().split("T")[0]}`;return _chunk6DIA6PXVcjs.d.call(void 0, {url:n,name:typeof s.staking=="string"?"backend-railway":s.staking.name,type:"rest"})}function dI({range:e,addresses:t}){let r=_swr2.default.call(void 0, e?["useStakedSnapshots",e,t]:null,async([,s,n])=>{let[...i]=await Promise.all([...n.map(async a=>{let l=await ps({address:a,range:s}),u=Ve(l.sort((m,p)=>m._timestamp-p._timestamp));return{[a]:u}})]);return i.reduce((a,l)=>({...a,...l}),{})});return{...r,refresh:()=>r.mutate()}}var hI=(e=[])=>{let t=_hooks.usePublicClient.call(void 0, ),o=_chunkQ2SNRLW3cjs.g.call(void 0, ),r=e.length>0&&t&&o?["useStakingVaultMetadata",e,t,o]:null;return _swr2.default.call(void 0, r,async([,s,n,i])=>(_chunkLVOXBZMAcjs.c.call(void 0, n),Promise.all(s.map(a=>_chunk45HIEVNIcjs.aa.call(void 0, {address:a.address,underlyingAsset:a.underlyingAsset,publicClient:n,blockTime:i})))),{refreshInterval:1e4})};function CI({vaultAddresses:e}){let t=_hooks.usePublicClient.call(void 0, ),o=_swr2.default.call(void 0, e&&t?["useTotalStakedAmount",e]:null,([,r])=>_chunk45HIEVNIcjs.ca.call(void 0, {vaultAddresses:r,publicClient:t}));return{...o,refresh:()=>o.mutate()}}var Op=(e,t)=>{let{address:o}=_hooks.useBeraWallet.call(void 0, ),r=_hooks.usePublicClient.call(void 0, ),s=o&&r&&e.vaultAddress?["useUserVaultInfo",o,e.vaultAddress]:null,n=_swr2.default.call(void 0, s,async([,i,a])=>(_chunkLVOXBZMAcjs.c.call(void 0, r),_chunk45HIEVNIcjs.fa.call(void 0, {account:i,vaultAddress:a,publicClient:r})),{...t,refreshInterval:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _334 => _334.opts, 'optionalAccess', _335 => _335.refreshInterval]), () => (1e5))});return{...n,refresh:()=>n.mutate()}};var Hp=e=>{let{address:t}=_hooks.useBeraWallet.call(void 0, ),o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, t&&o?["useUserVaults",t]:null,async([,n])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),await _chunk45HIEVNIcjs.ga.call(void 0, {account:n,publicClient:o})),{...e,refreshInterval:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _336 => _336.opts, 'optionalAccess', _337 => _337.refreshInterval]), () => (1e5)),keepPreviousData:!0});return{...s,refresh:()=>_optionalChain([s, 'optionalAccess', _338 => _338.mutate, 'optionalCall', _339 => _339()])}};var _I=e=>{let t=_hooks.usePublicClient.call(void 0, );return _swr2.default.call(void 0, e&&t?["useVaultAddress",e]:null,async([,r])=>{_chunkLVOXBZMAcjs.c.call(void 0, t);let[s]=await Promise.all([_chunk45HIEVNIcjs.Y.call(void 0, {address:r,publicClient:t})]);return{stakeToken:s,address:r}})};var FI=({vault:e,range:t,resolution:o})=>{let s=_swr2.default.call(void 0, e?["useVaultHistory",e,t,o]:null,([,n,i,a])=>_chunk45HIEVNIcjs.ha.call(void 0, {vault:n,range:i,resolution:a}));return{...s,refresh:()=>s.mutate()}};var Qp=(e,t)=>{let r=_swr2.default.call(void 0, e?["useVaultValidators",e]:null,async([,s])=>await _chunk45HIEVNIcjs.ia.call(void 0, {address:s}),{..._optionalChain([t, 'optionalAccess', _340 => _340.opts])});return{...r,refresh:()=>r.mutate()}};function ms({address:e},t){let o=se({addressIn:e?[e]:void 0},t);return{...o,data:e?_optionalChain([o, 'access', _341 => _341.data, 'optionalAccess', _342 => _342[e.toLowerCase()]]):void 0}}function XI(e){return ms({address:_viem.zeroAddress},e)}var aE=(e,t)=>{let o=_hooks.usePublicClient.call(void 0, ),r=_optionalChain([e, 'optionalAccess', _343 => _343.address])&&o&&_viem.isAddress.call(void 0, e.address)?["useStakingTokenInformation",e.address]:null,s=_immutable2.default.call(void 0, r,async([n,i])=>_chunkSFEULGSXcjs.e.call(void 0, i,"BERA")?{address:_viem.zeroAddress,decimals:_chunkSFEULGSXcjs.b.decimals,name:_chunkSFEULGSXcjs.b.name,symbol:_chunkSFEULGSXcjs.b.symbol}:await Ne({address:i,publicClient:o}),{..._optionalChain([t, 'optionalAccess', _344 => _344.opts])});return{...s,refresh:()=>_optionalChain([s, 'optionalAccess', _345 => _345.mutate, 'optionalCall', _346 => _346()])}};function uE({token:e},t){let{isLoading:o,priceMap:r}=J({tokens:e?[e]:void 0},t);return{data:e?_optionalChain([r, 'access', _347 => _347[e.chainId], 'optionalAccess', _348 => _348[e.address.toLowerCase()]]):void 0,isLoading:o}}function gE({address:e}){let t=_hooks.usePublicClient.call(void 0, );return _swr2.default.call(void 0, e&&t?["useTotalSupply",e]:null,([,o])=>(_chunkLVOXBZMAcjs.c.call(void 0, t),t.readContract({address:o,abi:_viem.erc20Abi,functionName:"totalSupply",args:[]})))}function CE(e){let t=_hooks.usePublicClient.call(void 0, ),{config:o}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:_optionalChain([t, 'optionalAccess', _349 => _349.chain, 'access', _350 => _350.id])}),{data:r,isLoading:s}=_hooks.useBlockNumber.call(void 0, {cacheTime:_chunk6DIA6PXVcjs.m.call(void 0, o.averageBlockTime)}),{data:n}=_immutable2.default.call(void 0, r&&t&&Number(e)>0?["useBlockToTimestamp",e,r]:null,async([,a,l])=>(_chunkLVOXBZMAcjs.c.call(void 0, t),_chunk45HIEVNIcjs.L.call(void 0, {block:a,currentBlock:l,blockTime:i,publicClient:t}))),i=_chunkQ2SNRLW3cjs.g.call(void 0, );if(n)return Number(n.timestamp);if(!(s||!r))return Math.floor(_chunk6DIA6PXVcjs.l.call(void 0, Date.now())+i*(Number(e)-Number(r)))}var Ot={confirmState:"idle",txnHash:"",message:""},ds=(e,t)=>{switch(t.type){case"confirm_sending":return{...e,confirmState:"loading"};case"confirm_receipt":return{...e,confirmState:"success"};case"confirm_error":return{...e,confirmState:"fail"};case"confirm_submitting":return{...e,confirmState:"submitting"};case"confirm_reset":return{...Ot};default:return e}};function om({onlyPermissionless:e,onSuccess:t,onError:o,onLoading:r,onWarning:s,onSubmission:n}={}){let[i,a]=_react.useReducer.call(void 0, ds,Ot),{account:l,onSmartAccountRejection:u}=_hooks.useBeraWagmi.call(void 0, ),m=_hooks.useConfig.call(void 0, ),p=_optionalChain([l, 'optionalAccess', _351 => _351.wallet, 'optionalAccess', _352 => _352.isContract])?6e4*10:12e4,c=_react.useCallback.call(void 0, ()=>{a({type:"confirm_reset"})},[]),d=_chunkQ2SNRLW3cjs.c.call(void 0, "enableSimulateCalls"),f=_react.useCallback.call(void 0, y=>{if(e&&!y.permissionless){let A=new (0, _chunkREWME3FYcjs.b)({message:"Trying to send a non-permissionless transaction with an overridden account",displayMessage:"You can't send this transaction with an overridden account. Please reset the account in the settings popover.",level:"info",input:y});throw _optionalChain([s, 'optionalCall', _353 => _353(A,y)]),_optionalChain([o, 'optionalCall', _354 => _354(A,y)]),A}return _chunk45HIEVNIcjs.ma.call(void 0, {wagmiConfig:m,...y,txConfirmationTimeout:p,enableSimulateCalls:d,onLoading(...A){a({type:"confirm_sending"}),_optionalChain([y, 'access', _355 => _355.onLoading, 'optionalCall', _356 => _356(y)]),_optionalChain([r, 'optionalCall', _357 => _357(...A)])},onWarning(...A){_optionalChain([y, 'access', _358 => _358.onWarning, 'optionalCall', _359 => _359(A[0],y)]),_optionalChain([s, 'optionalCall', _360 => _360(...A)])},onSubmission(...A){a({type:"confirm_submitting"}),_optionalChain([y, 'access', _361 => _361.onSubmission, 'optionalCall', _362 => _362(A[0],y)]),_optionalChain([n, 'optionalCall', _363 => _363(...A)])},onSuccess(...A){a({type:"confirm_receipt"}),_optionalChain([y, 'access', _364 => _364.onSuccess, 'optionalCall', _365 => _365(A[0],y)]),_optionalChain([t, 'optionalCall', _366 => _366(...A)])},onError(...A){a({type:"confirm_error"}),_optionalChain([y, 'access', _367 => _367.onError, 'optionalCall', _368 => _368(A[0],y)]),A[0].reason==="AtomicReadyWalletRejectedUpgradeError"&&u(),_optionalChain([o, 'optionalCall', _369 => _369(...A)])}})},[m,r,s,n,t,o,e,d]);return{isLoading:i.confirmState==="loading",isSubmitting:i.confirmState==="submitting",isSuccess:i.confirmState==="success",isError:i.confirmState==="fail",write:f,reset:c}}var rm=om;async function lm(e){let t=await _chunk6DIA6PXVcjs.d.call(void 0, {url:`https://api.routescan.io/v2/network/testnet/evm/${_internal.chainId}/etherscan/api?module=contract&action=getabi&address=${e}`,type:"rest",name:"RouteScan"});if(t.status==="0")throw new Error(t.result);return t.result}var ME=e=>_immutable2.default.call(void 0, e&&_viem.isAddress.call(void 0, e)&&e!==_viem.zeroAddress?["useGetVerifiedAbi",e]:null,()=>e?lm(e):Promise.resolve(""),{});function GE({key:e,defaultValue:t}){let o=_react.useCallback.call(void 0, ()=>{if(typeof window>"u")return t;let i=_optionalChain([window, 'access', _370 => _370.history, 'access', _371 => _371.state, 'optionalAccess', _372 => _372[e]]);return i!==void 0?i:t},[e,t]),[r,s]=_react.useState.call(void 0, o()),n=_react.useCallback.call(void 0, i=>{let a=o(),l=i instanceof Function?i(a):i,m={...window.history.state||{},[e]:l};window.history.replaceState(m,""),s(l)},[e,o]);return _react.useEffect.call(void 0, ()=>{if(_optionalChain([window, 'access', _373 => _373.history, 'access', _374 => _374.state, 'optionalAccess', _375 => _375[e]])===void 0){let l={...window.history.state||{},[e]:t};window.history.replaceState(l,"")}},[e,t]),[r,n]}function $E(e){let t=_react.useRef.call(void 0, void 0);return _react.useEffect.call(void 0, ()=>{t.current=e}),t.current}var fm=({variables:e}={})=>["useAllValidators",e],XE= exports.useAllValidators =(e,t)=>{let{config:o}=_chunkSFEULGSXcjs.a.call(void 0, e),r=_swr2.default.call(void 0, fm({variables:e}),async([,s])=>await _chunk45HIEVNIcjs.na.call(void 0, {variables:{chain:o.bex.chainName,...s}}),{refreshInterval:18e4,..._optionalChain([t, 'optionalAccess', _376 => _376.opts])});return{...r,refresh:()=>r.mutate()}};function rT({allocation:e}){return _swr2.default.call(void 0, e?["useApiEnrichedAllocation",e]:null,([,t])=>_chunk45HIEVNIcjs.oa.call(void 0, {allocation:t}))}var bm=e=>e?["useApiValidator",e]:null,gs= exports.useApiValidator =(e,t)=>{let o=bm(e),r=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _377 => _377.opts, 'optionalAccess', _378 => _378.isEnabled]), () => (!0)),s=_swr2.default.call(void 0, r&&e?o:null,async([,n])=>{if(!n||!_viem.isHex.call(void 0, n))throw new Error(`Invalid validator ID: ${n}`);return _chunk45HIEVNIcjs.pa.call(void 0, {id:n})},{..._optionalChain([t, 'optionalAccess', _379 => _379.opts])});return{...s,refresh:()=>s.mutate()}};var _rewardAllocatorFactory = require('@berachain/abis/pol/rewards/rewardAllocatorFactory');async function ys({publicClient:e,...t}){let{config:o}=_chunkSFEULGSXcjs.a.call(void 0, t),r=await e.readContract({abi:_rewardAllocatorFactory.rewardAllocatorFactoryAbi,address:o.pol.rewardAllocationFactory,functionName:"getBaselineAllocation"}),s=r.startBlock!==0n?await e.getBlock({blockNumber:r.startBlock}):{timestamp:0};return _chunk45HIEVNIcjs.ra.call(void 0, r,Number(s.timestamp))}function AT(){let e=_hooks.usePublicClient.call(void 0, );return _swr2.default.call(void 0, e?["baselineRewardAllocation"]:null,()=>(_chunkLVOXBZMAcjs.c.call(void 0, e),ys({publicClient:e})))}var Pm=({pubKey:e,first:t=1})=>{let r=_swr2.default.call(void 0, e?["useDailyValidatorBlockStats",e,t]:null,async([,s,n])=>await _chunk45HIEVNIcjs.qa.call(void 0, {pubKey:s,first:n}),{refreshInterval:18e4});return{...r,refresh:()=>r.mutate()}};function Em(e){let t=_hooks.usePublicClient.call(void 0, ),r=_swr2.default.call(void 0, t?["useDefaultRewardAllocation"]:null,async()=>(_chunkLVOXBZMAcjs.c.call(void 0, t),await _chunk45HIEVNIcjs.va.call(void 0, {client:t})),{..._optionalChain([e, 'optionalAccess', _380 => _380.opts])});return{...r,refresh:()=>r.mutate()}}async function As({client:e,pubKey:t,...o}){let{config:r}=_chunkSFEULGSXcjs.a.call(void 0, o);try{let s=await e.readContract({address:r.pol.beraChef,abi:_beraChef.beraChefAbi,functionName:"valRewardAllocator",args:[t]});return s===_viem.zeroAddress?null:s}catch(s){throw console.log("getValidatorRewardAllocatorAddress:",s),s}}function hs(e,t){return!e||!t?!1:_optionalChain([t, 'access', _381 => _381.operator, 'optionalAccess', _382 => _382.toLowerCase, 'call', _383 => _383()])===e.toLowerCase()}function Om(e,t){return!e||!t?!1:t.rewardAllocator?t.rewardAllocator.toLowerCase()===e.toLowerCase():hs(e,t)}function Dm({pubKey:e,account:t},o){let r=_hooks.usePublicClient.call(void 0, ),s=_chunkQ2SNRLW3cjs.c.call(void 0, "mockValidatorOperator"),n=_chunkQ2SNRLW3cjs.c.call(void 0, "mockValidatorRewardAllocator"),i=r&&e?["useManagedValidatorRole",e]:null,{address:a}=_hooks.useBeraWallet.call(void 0, ),l=_nullishCoalesce(t, () => (a)),u=_swr2.default.call(void 0, i,async([,c])=>{_chunkLVOXBZMAcjs.c.call(void 0, r);let[d,f]=await Promise.all([_chunk45HIEVNIcjs.Da.call(void 0, {client:r,pubKey:c}),As({client:r,pubKey:c})]);return{operator:_nullishCoalesce(d, () => (null)),rewardAllocator:f}},{..._optionalChain([o, 'optionalAccess', _384 => _384.opts])}),m=_react.useMemo.call(void 0, ()=>s||hs(l,u.data),[l,s,u.data]),p=_react.useMemo.call(void 0, ()=>n||Om(l,u.data),[l,n,u.data]);return{...u,data:u.data?{...u.data,hasOperatorRole:m,hasRewardAllocatorRole:p}:void 0,refresh:()=>u.mutate()}}var _beaconDeposit = require('@berachain/abis/pol/beaconDeposit');var Rs=({pubkey:e},t)=>{let o=_hooks.usePublicClient.call(void 0, ),r=e?["useOnChainValidator",e]:null,s=_nullishCoalesce(_optionalChain([t, 'access', _385 => _385.opts, 'optionalAccess', _386 => _386.isEnabled]), () => (!0)),n=_swr2.default.call(void 0, s&&o?r:null,async([,i])=>{_chunkLVOXBZMAcjs.c.call(void 0, o);let{config:a}=_chunkSFEULGSXcjs.a.call(void 0, {chainId:o.chain.id}),[l,u,m]=await Promise.all([o.readContract({address:a.depositContract,abi:_beaconDeposit.beaconDepositAbi,functionName:"getOperator",args:[i]}),_optionalChain([o, 'optionalAccess', _387 => _387.readContract, 'call', _388 => _388({address:a.tokens.bgt,abi:_bgt.bgtAbi,functionName:"boostees",args:[i]})]),o.readContract({address:a.pol.beraChef,abi:_beraChef.beraChefAbi,functionName:"getActiveRewardAllocation",args:[i]})]);return{id:_viem.keccak256.call(void 0, i),pubkey:i,operator:l,votingPower:Number(u)}});return{...n,refresh:()=>{n.mutate()}}};var JT=({valPubKey:e,options:t})=>{let o=_hooks.usePublicClient.call(void 0, ),s=(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _389 => _389.opts, 'optionalAccess', _390 => _390.isEnabled]), () => (!0)))&&o&&e?["useStakingPoolBatch",e]:null,n=_swr2.default.call(void 0, s,async([,i])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),await _chunk45HIEVNIcjs.wa.call(void 0, {client:o,valPubKey:i})),{refreshInterval:1e4,..._optionalChain([t, 'optionalAccess', _391 => _391.opts])});return{...n,refresh:()=>n.mutate()}};var Gm=e=>{let{address:t}=_hooks.useBeraWallet.call(void 0, ),o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, o&&t?["useUserActiveValidators",t]:null,async([,n])=>await _chunk45HIEVNIcjs.ya.call(void 0, {account:n,publicClient:o}),{...e,refreshInterval:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _392 => _392.opts, 'optionalAccess', _393 => _393.refreshInterval]), () => (18e4)),keepPreviousData:!0});return{...s,refresh:()=>_optionalChain([s, 'optionalAccess', _394 => _394.mutate, 'optionalCall', _395 => _395()])}};var zm=({pubkey:e,...t})=>{let{address:o}=_hooks.useBeraWallet.call(void 0, ),r=_hooks.usePublicClient.call(void 0, ),s=_nullishCoalesce(t.account, () => (o)),i=_swr2.default.call(void 0, s&&e?["useUserBoostsOnValidator",e,s]:null,async([,a,l])=>await _chunk45HIEVNIcjs.xa.call(void 0, {account:l,pubkey:a,publicClient:r}),{refreshInterval:1e5});return{...i,refresh:()=>i.mutate()}};var ws=e=>{let t=new Set;return e.forEach(o=>{Array.isArray(o.rewards)&&o.rewards.forEach(r=>{r.token&&t.add(r.token)})}),t};var Xm=()=>{let{address:e}=_hooks.useBeraWallet.call(void 0, ),o=_swr2.default.call(void 0, e?["useUserClaimableIncentives",e]:null,async([,l])=>{if(!l)throw new (0, _chunk6JJIZCVYcjs.f)({message:"useUserClaimableIncentives needs a logged in account",level:"error"});return await _chunk45HIEVNIcjs.da.call(void 0, {account:l})},{revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,refreshInterval:18e4}),r=_optionalChain([o, 'optionalAccess', _396 => _396.data]),s=_react.useMemo.call(void 0, ()=>{if(r){if(!Array.isArray(r)){_chunkLVOXBZMAcjs.g.captureException(new (0, _chunk6JJIZCVYcjs.f)({message:"Incorrect aggregated incentives data receieved.",level:"error",extra:{allRewards:r,account:e}}));return}return ws(r)}},[r,e]),i=_swr2.default.call(void 0, e&&r?["useUserClaimableIncentives",e,r]:null,async([,l,u])=>{if(!l)throw new (0, _chunk6JJIZCVYcjs.h)({property:"account",value:l,expected:"Address"});if(!u)return[];if(!Array.isArray(u))throw new (0, _chunk6JJIZCVYcjs.h)({message:"Incorrect aggregated incentives data receieved to calculate proofs.",property:"allRewards",value:u,expected:"Array",level:"error"});let m=new Set(u.map(c=>c.validator)),p=Array.from(m);return await Promise.all(p.map(async c=>({...await _chunk45HIEVNIcjs.U.call(void 0, {account:l,validator:c,page:1,perPage:1e4}),validator:c})))},{revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,refreshInterval:18e4}),a=_react.useCallback.call(void 0, ()=>{_optionalChain([o, 'optionalAccess', _397 => _397.mutate, 'call', _398 => _398()]),_optionalChain([i, 'optionalAccess', _399 => _399.mutate, 'call', _400 => _400()])},[o,i]);return{...i,isLoading:_optionalChain([o, 'optionalAccess', _401 => _401.isLoading])||_optionalChain([i, 'optionalAccess', _402 => _402.isLoading]),tokenMap:s,refresh:a}};var wS=({account:e,validatorAddress:t})=>{let r=_immutable2.default.call(void 0, e?["useUserStakingPositions",e,t]:null,async([s,n,i])=>{let a=await _chunk45HIEVNIcjs.za.call(void 0, n);return i?a.filter(l=>l.validatorAddress.toLowerCase()===i.toLowerCase()):a});return{...r,refresh:()=>{r.mutate()}}};function ES({pubkey:e},t){let{data:{validator:o,uptime:r}={},isLoading:s,error:n}=gs(_viem.keccak256.call(void 0, e),t),{data:i,isLoading:a,error:l}=Rs({pubkey:e},t);return{data:{uptime:r,validator:o||i?{...o,...i,operator:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _403 => _403.operator]), () => (_optionalChain([o, 'optionalAccess', _404 => _404.operator]))),dynamicData:{activeBoostAmount:_nullishCoalesce(_nullishCoalesce(_optionalChain([i, 'optionalAccess', _405 => _405.dynamicData, 'optionalAccess', _406 => _406.activeBoostAmount]), () => (_optionalChain([o, 'optionalAccess', _407 => _407.dynamicData, 'optionalAccess', _408 => _408.activeBoostAmount]))), () => ("")),queuedBoostAmount:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _409 => _409.dynamicData, 'optionalAccess', _410 => _410.queuedBoostAmount]), () => ("")),usersActiveBoostCount:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _411 => _411.dynamicData, 'optionalAccess', _412 => _412.usersActiveBoostCount]), () => (0)),usersQueuedBoostCount:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _413 => _413.dynamicData, 'optionalAccess', _414 => _414.usersQueuedBoostCount]), () => (0)),allTimeDistributedBGTAmount:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _415 => _415.dynamicData, 'optionalAccess', _416 => _416.allTimeDistributedBGTAmount]), () => ("0")),rewardRate:_nullishCoalesce(_nullishCoalesce(_optionalChain([i, 'optionalAccess', _417 => _417.dynamicData, 'optionalAccess', _418 => _418.rewardRate]), () => (_optionalChain([o, 'optionalAccess', _419 => _419.dynamicData, 'optionalAccess', _420 => _420.rewardRate]))), () => ("")),stakedBeraAmount:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _421 => _421.dynamicData, 'optionalAccess', _422 => _422.stakedBeraAmount]), () => ("")),lastDayDistributedBGTAmount:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _423 => _423.dynamicData, 'optionalAccess', _424 => _424.lastDayDistributedBGTAmount]), () => ("")),activeBoostAmountRank:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _425 => _425.dynamicData, 'optionalAccess', _426 => _426.activeBoostAmountRank]), () => (0)),boostApr:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _427 => _427.dynamicData, 'optionalAccess', _428 => _428.boostApr]), () => (0)),commissionOnIncentives:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _429 => _429.dynamicData, 'optionalAccess', _430 => _430.commissionOnIncentives]), () => (0))},id:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _431 => _431.id]), () => (_optionalChain([o, 'optionalAccess', _432 => _432.id]))),pubkey:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _433 => _433.pubkey]), () => (_optionalChain([o, 'optionalAccess', _434 => _434.pubkey]))),metadata:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _435 => _435.metadata]), () => (_optionalChain([o, 'optionalAccess', _436 => _436.metadata]))),rewardAllocationWeights:_nullishCoalesce(_nullishCoalesce(_optionalChain([i, 'optionalAccess', _437 => _437.rewardAllocationWeights]), () => (_optionalChain([o, 'optionalAccess', _438 => _438.rewardAllocationWeights]))), () => ([]))}:null},isLoading:s||a,error:n||l}}function rd({pubkey:e,dayRange:t}){let r=_swr2.default.call(void 0, e&&t?["useValidatorAnalytics",e,t]:null,async([,s,n])=>await _chunk45HIEVNIcjs.Aa.call(void 0, {pubkey:s,dayRange:n}),{refreshInterval:18e4});return{...r,refresh:()=>r.mutate()}}var ad=(e,t)=>{let o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, o&&e?["useValidatorCommission",e]:null,async([,n])=>await _chunk45HIEVNIcjs.Ba.call(void 0, {client:o,pubKey:n}),{..._optionalChain([t, 'optionalAccess', _439 => _439.opts])});return{...s,refresh:()=>s.mutate()}};var id=e=>{let{data:t,isLoading:o}=ls(),r=_chunkQ2SNRLW3cjs.g.call(void 0, );return{data:t?_chunk45HIEVNIcjs.Ca.call(void 0, e,Number(_optionalChain([t, 'optionalAccess', _440 => _440.totalStakedBeraAmount])),r):void 0,isLoading:o}};function pd(e,t){let o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, o&&e?["useValidatorQueuedCommission",e]:null,async([,n])=>(_chunkLVOXBZMAcjs.c.call(void 0, o),await _chunk45HIEVNIcjs.Ea.call(void 0, {client:o,pubKey:n})),{..._optionalChain([t, 'optionalAccess', _441 => _441.opts])});return{...s,refresh:()=>s.mutate()}}var cd=(e,t)=>{let o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, o&&e?["useValidatorQueuedOperatorAddress",e]:null,async([,n])=>await _chunk45HIEVNIcjs.Fa.call(void 0, {client:o,pubKey:n}),{..._optionalChain([t, 'optionalAccess', _442 => _442.opts])});return{...s,refresh:()=>s.mutate()}};var yd=(e,t)=>{let o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, o&&e?["useValidatorQueuedRewardAllocation",e]:null,async([,n])=>await _chunk45HIEVNIcjs.Ga.call(void 0, {client:o,pubKey:n}),{..._optionalChain([t, 'optionalAccess', _443 => _443.opts])});return{...s,refresh:()=>s.mutate()}};function hd(e,t){let o=_hooks.usePublicClient.call(void 0, ),s=_swr2.default.call(void 0, o&&e?["useValidatorRewardAllocation",e]:null,async([,n])=>_chunk45HIEVNIcjs.ta.call(void 0, {client:o,pubKey:n}),{..._optionalChain([t, 'optionalAccess', _444 => _444.opts])});return{...s,refresh:()=>s.mutate()}}exports.OracleMode = Un; exports.USE_AGGREGATORS_QUOTES_QUERY_KEY = cr; exports.reducer = is; exports.useAggregatorsQuotes = Zf; exports.useAggregatorsRouterFeeBps = ke; exports.useAllUserPools = fr; exports.useAllUserPoolsQueryKey = In; exports.useAllValidators = XE; exports.useAllValidatorsQueryKey = fm; exports.useApiEnrichedAllocation = rT; exports.useApiPool = gr; exports.useApiPoolQueryKey = Sn; exports.useApiValidator = gs; exports.useApiValidatorQueryKey = bm; exports.useBaselineRewardAllocation = AT; exports.useBendDemultiply = xb; exports.useBendMultiply = Kb; exports.useBendZapSupply = ph; exports.useBendZapSupplyHelper = Di; exports.useBeraContractWrite = rm; exports.useBeraCurrentPrice = XI; exports.useBexStatus = _chunkQ2SNRLW3cjs.e; exports.useBgtAprSimulation = gP; exports.useBgtUnstakedBalance = Nu; exports.useBlockToTimestamp = CE; exports.useCappedGlobally = Xr; exports.useCappedRelatively = es; exports.useClaimableFees = Mu; exports.useCollateralWeights = rk; exports.useCreatePool = kg; exports.useCreateProposal = il; exports.useDailyValidatorBlockStats = Pm; exports.useDefaultRewardAllocation = Em; exports.useEnsoSwapBundle = vh; exports.useEnsoUserTokensWithBalances = _chunkQ2SNRLW3cjs.m; exports.useExploitedTokens = Dg; exports.useExploitedTokensQueryKey = Fn; exports.useGetConvertToAssets = zo; exports.useGetPastVotes = dR; exports.useGetVerifiedAbi = ME; exports.useGlobalLiquidityAndSwapVolume = Kn; exports.useHasVoted = RR; exports.useHighestVaultsAPR = NP; exports.useHistoryState = GE; exports.useHoney24hVolume = ik; exports.useHoneyAlerts = Wk; exports.useHoneyBalances = ts; exports.useHoneyChartData = Yk; exports.useHoneySwapState = sP; exports.useHoneyVaultsBalance = os; exports.useIsBadCollateralAsset = rs; exports.useIsBasketModeEnabled = ns; exports.useIsCanceller = xR; exports.useLiquidityMismatch = Qg; exports.useLpPosition = Py; exports.useManagedValidatorRole = Dm; exports.useMultipleTokenApprovalsWithSlippage = Ea; exports.useMultipleTokenInformation = xr; exports.useOnChainPoolData = Br; exports.useOnChainPoolDataQueryKey = _a; exports.useOnChainValidator = Rs; exports.usePollAllProposals = UR; exports.usePollAllProposalsQueryKey = xl; exports.usePollAllowances = Tr; exports.usePollBalance = Ie; exports.usePollGlobalData = ls; exports.usePollMarkets = KP; exports.usePollMarketsQueryKey = Zu; exports.usePollPoolCreationRelayerApproval = Ga; exports.usePollProposal = YR; exports.usePollProposalThreshold = jR; exports.usePollProposalVotes = ew; exports.usePollProposalVotesQueryKey = Vl; exports.usePollUserDelegates = lw; exports.usePollWalletBalances = Oe; exports.usePool = AA; exports.usePoolEvents = wA; exports.usePoolHistoricalData = EA; exports.usePools = DA; exports.usePoolsQueryKey = ja; exports.usePrevious = $E; exports.usePriceImpact = Te; exports.useProposalFromTx = cw; exports.useProposalSnapshot = qr; exports.useProposalState = hw; exports.useProposalTimelockState = Iw; exports.usePythLatestPrices = ae; exports.usePythUpdateFee = mP; exports.useQueuedBeraUnlock = XP; exports.useQuorum = Uw; exports.useRewardTokenToBeraRate = lC; exports.useRewardVault = TC; exports.useRewardVaultBalanceFromStakingToken = Pr; exports.useRewardVaultFromToken = At; exports.useRewardVaultIncentives = DC; exports.useRewardVaultQueryKey = fp; exports.useRewardVaultRewards = hp; exports.useRewardVaults = Bt; exports.useRewardVaultsQueryKey = Gu; exports.useSingleAggregatorQuote = An; exports.useStakedAPR = FC; exports.useStakedData = rI; exports.useStakedSnapshots = dI; exports.useStakingPoolBatch = JT; exports.useStakingTokenInformation = aE; exports.useStakingVaultsMetadata = hI; exports.useTokenCurrentPrice = ms; exports.useTokenCurrentPrices = se; exports.useTokenInformation = Cr; exports.useTokenPrice = uE; exports.useTokenPrices = J; exports.useTokens = oe; exports.useTotalStakedAmount = CI; exports.useTotalSupply = gE; exports.useUserActiveValidators = Gm; exports.useUserBoostsOnValidator = zm; exports.useUserClaimableIncentives = Xm; exports.useUserStakingPositions = wS; exports.useUserVaultInfo = Op; exports.useUserVaults = Hp; exports.useValidator = ES; exports.useValidatorAnalytics = rd; exports.useValidatorCommission = ad; exports.useValidatorEstimatedBgtPerYear = id; exports.useValidatorQueuedCommission = pd; exports.useValidatorQueuedOperatorAddress = cd; exports.useValidatorQueuedRewardAllocation = yd; exports.useValidatorRewardAllocation = hd; exports.useVaultAddress = _I; exports.useVaultHistory = FI; exports.useVaultValidators = Qp; exports.useZapStakeBera = Wh;
|
|
4
|
-
//# sourceMappingURL=exports.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/pong/coding/monobera/packages/berajs/dist/hooks/exports.cjs","../../src/hooks/bend/useGetConvertToAssets.ts","../../src/hooks/dex/useAggregatorsQuotes.ts","../../src/actions/dex/aggregators/bex.ts","../../src/actions/dex/aggregators/bgt.ts","../../src/actions/dex/aggregators/enso/enso.ts","../../src/hooks/dex/useLiquidityMismatch.ts","../../src/hooks/tokens/useTokenCurrentPrices.ts"],"names":["useGetConvertToAssets","sharesAmount","vaultAddress","vaultChainId","options","publicClient","usePublicClient","swrResponse","useSWR","_","assertPublicClient","getConvertToAssets","DEFAULT_DEADLINE","STALE_PRICE_THRESHOLD","swapKind","SwapKind","BexAggregator","BaseAggregator","ChainId","getUriFromLink","address","isToken","priceImpact","onChainAmount","sorPaths","sorAmount","queryData","deltaFromSorAmount","formatEther","error","BeraError","p","BeraMonitoring","args","balancerApi","BalancerApi","tokenIn","tokenOut","amount","slippage","account","zeroAddress","wberaIsBera","tokenInV3","Token","tokenOutV3","tokenAmount","TokenAmount","RequestError","swap","Swap","queryOutput","callData","Slippage","params","functionName","decodeFunctionData","balancerVaultAbi","bex","RedeemBgtAggregator","beraToken","InvalidArgumentError","bgtRedeem","EnsoAggregator","aggregatorsFeeBps","proxyAggregatorsThroughVercel","rewardVault","tokenInAddress","tokenOutAddress","isTokenInNative","isTokenOutNative","inputAmountAfterFees"],"mappings":"AAAA,wnDAA0C,yDAAsoB,iCAA8B,yDAAiF,yDAAkD,iCAA8B,iCAA8B,iCAA8B,iCAA8B,yDAA2C,yDAAwF,yDAAmD,yDAAkF,iCAA8B,yDAAgE,iCAA8B,yDAAyD,oECAn3C,+CAEa,IAOnBA,EAAAA,CAAwB,CACnC,CACE,YAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CACAC,CAAAA,CAAAA,EACG,CACH,IAAMC,CAAAA,CAAeC,oCAAAA,CAAkB,OAAA,CAASH,CAAa,CAAC,CAAA,CACxDI,CAAAA,CAAcC,2BAAAA,CAClBH,EAAgBJ,CAAAA,EAAgBC,CAAAA,CAC5B,CAAC,uBAAA,CAAyBD,CAAAA,CAAcC,CAAAA,CAAcC,CAAY,CAAA,CAClE,IAAA,CACJ,KAAA,CAAO,CAACM,CAAAA,CAAGR,CAAAA,CAAcC,CAAY,CAAA,CAAA,EAAA,CACnCQ,iCAAAA,CAA+B,CAAA,CAExBC,iCAAAA,CACL,YAAA,CAAAV,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,YAAA,CAAAG,CACF,CAAC,CAAA,CAAA,CAEH,CACE,mBAAGD,CAAAA,6BAAS,MACd,CACF,CAAA,CAEA,MAAO,CACL,GAAGG,CAAAA,CACH,OAAA,CAAS,CAAA,CAAA,EAAM,CACbA,CAAAA,CAAY,MAAA,CAAO,CACrB,CACF,CACF,CAAA,CC1CA,8BAAwB,4BACkB,sDAEX,iECKxB,2CAGwB,kDAGc,IAavCK,EAAAA,CAAmB,GAAA,CACnBC,EAAAA,CAAwB,GAAA,CACxBC,EAAAA,CAAWC,qBAAAA,CAAS,OAAA,CAEpBC,EAAAA,WAAN,MAAA,QAA4BC,mBAAe,0MACzC,IAAA,CAAA,YAAA,gBACA,eAAA,CAAkB,CAACC,iBAAAA,CAAQ,OAAA,CAASA,iBAAAA,CAAQ,OAAO,EAAA,gBAC1C,GAAA,CAAMC,oCAAAA,IAAe,CAAK,MAAA,CAAO,GAAG,EAAA,gBACpC,IAAA,CAAO,UAAA,oBAKR,CAAqBC,CAAAA,CAA2B,CACtD,OAAOC,iCAAAA,CAAQD,CAAS,MAAM,CAAA,CAAI,IAAA,CAAK,MAAA,CAAO,MAAA,CAAO,KAAA,CAAQA,CAC/D,CAKQ,oBAAA,CAAqBE,CAAAA,CAGlB,CACT,OAAIA,CAAAA,CAAY,KAAA,CAAA,CACd,OAAA,CAAQ,KAAA,CAAM,yBAAA,CAA2BA,CAAW,CAAA,CAC7C,CAAA,CAAA,CAGF,MAAA,CAAOA,CAAAA,CAAY,WAAW,CACvC,CAKQ,gBAAA,CAAiB,CACvB,aAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CACF,CAAA,CAKS,CAEP,IAAMC,CAAAA,CACJ,MAAA,CAAO,UAAA,CAAWC,+BAAAA,CAAYL,CAAc,OAAO,CAAC,CAAA,CACpD,MAAA,CAAO,UAAA,CAAWE,CAAS,CAAA,CAE7B,EAAA,CAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAIE,CAAkB,CAAA,CAAId,EAAAA,CAAuB,CAC5D,OAAA,CAAQ,IAAA,CACN,qEAAA,CACA,CACE,kBAAA,CAAAc,CACF,CACF,CAAA,CAEA,IAAME,CAAAA,CAAQ,IAAIC,wBAAAA,CAAU,CAC1B,MAAA,CAAQ,kBAAA,CACR,KAAA,CAAO,SAAA,CACP,OAAA,CACE,qEAAA,CACF,KAAA,CAAO,CACL,kBAAA,CAAAH,CAAAA,CACA,KAAA,CAAOH,CAAAA,CAAS,GAAA,CAAKO,CAAAA,EAAMA,CAAAA,CAAE,KAAK,CAAA,CAClC,aAAA,CAAeH,+BAAAA,CAAYL,CAAc,OAAO,CAAA,CAChD,SAAA,CAAAE,CAAAA,CACA,SAAA,CAAAC,CACF,CAAA,CACA,WAAA,CAAa,CAAC,kBAAkB,CAClC,CAAC,CAAA,CACDM,mBAAAA,CAAe,gBAAA,CAAiBH,CAAK,CACvC,CACF,CAEA,MAAM,QAAA,CAASI,CAAAA,CAAqD,CAClE,IAAMC,CAAAA,CAAc,IAAIC,wBAAAA,CACtB,IAAA,CAAK,GAAA,CAEL,IAAA,CAAK,OACP,CAAA,CACM,CACJ,OAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAAUC,iBAAAA,CACV,YAAA,CAAApC,CACF,CAAA,CAAI4B,CAAAA,CACJ,IAAA,CAAK,kBAAA,CAAmB,CAAE,OAAA,CAAAG,CAAAA,CAAS,QAAA,CAAAC,CAAS,CAAC,CAAA,CAE7C3B,iCAAAA,CAA+B,CAAA,CAE/B,IAAMgC,CAAAA,CAAcrB,iCAAAA,CAAQe,CAAS,MAAM,CAAA,EAAKf,iCAAAA,CAAQgB,CAAU,MAAM,CAAA,CAGlEM,CAAAA,CAAY,IAAIC,uBAAAA,CACpB,IAAA,CAAK,OAAA,CACL,IAAA,CAAK,oBAAA,CAAqBR,CAAAA,CAAQ,OAAO,CAAA,CACzCA,CAAAA,CAAQ,QACV,CAAA,CACMS,CAAAA,CAAa,IAAID,uBAAAA,CACrB,IAAA,CAAK,OAAA,CACL,IAAA,CAAK,oBAAA,CAAqBP,CAAAA,CAAS,OAAO,CAAA,CAC1CA,CAAAA,CAAS,QACX,CAAA,CAEMS,CAAAA,CAAcC,wBAAAA,CAAY,aAAA,CAC9BJ,CAAAA,CACAL,CACF,CAAA,CAGM,CACJ,KAAA,CAAOd,CAAAA,CACP,WAAA,CAAAF,CAAAA,CACA,YAAA,CAAcG,CAChB,CAAA,CAAmB,MAAMS,CAAAA,CAAY,YAAA,CAAa,iBAAA,CAAkB,CAElE,OAAA,CAAS,IAAA,CAAK,OAAA,CACd,OAAA,CAASS,CAAAA,CAAU,OAAA,CACnB,QAAA,CAAUE,CAAAA,CAAW,OAAA,CACrB,QAAA,CAAA/B,EAAAA,CACA,UAAA,CAAYgC,CACd,CAAC,CAAA,CAED,EAAA,CAAI,iBAACtB,CAAAA,6BAAU,QAAA,CACb,MAAM,IAAIwB,wBAAAA,CAAa,CACrB,QAAA,CAAU,KAAA,CAAA,CACV,QAAA,CAAU,CACR,GAAA,CAAK,IAAA,CAAK,GAAA,CACV,IAAA,CAAM,IAAA,CAAK,IAAA,CACX,IAAA,CAAM,IAAA,CAAK,IACb,CAAA,CACA,MAAA,CAAQ/B,mBAAAA,CAAe,qBAAA,CACvB,OAAA,CAAS,IAAA,CAAK,OAAA,CACd,OAAA,CAAS,CACP,OAAA,CAAS0B,CAAAA,CAAU,OAAA,CACnB,QAAA,CAAUE,CAAAA,CAAW,OAAA,CACrB,QAAA,CAAA/B,EAAAA,CACA,UAAA,CAAYgC,CACd,CAAA,CACA,OAAA,CAAS,0CACX,CAAC,CAAA,CAIH,IAAMG,CAAAA,CAAO,IAAIC,sBAAAA,CAAK,CACpB,OAAA,CAAS,IAAA,CAAK,OAAA,CACd,KAAA,CAAO1B,CAAAA,CACP,QAAA,CAAAV,EAAAA,CACA,QAAA,CAAU,IACZ,CAAC,CAAA,CACKqC,CAAAA,CAAc,MAAMF,CAAAA,CAAK,KAAA,CAAM5C,CAAAA,CAAa,SAAA,CAAU,GAAG,CAAA,CAE/D,EAAA,CAAI,CAAA,CAAE,mBAAA,GAAuB8C,CAAAA,CAAAA,CAC3B,MAAM,IAAI,KAAA,CAAM,oBAAoB,CAAA,CAGtC,OAAA,IAAA,CAAK,gBAAA,CAAiB,CACpB,aAAA,CAAeA,CAAAA,CAAY,iBAAA,CAC3B,QAAA,CAAA3B,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,SAAA,CAAWQ,CACb,CAAC,CAAA,CAGM,CACL,SAAA,CAAWkB,CAAAA,CAAY,iBAAA,CAAkB,MAAA,CAAO,QAAA,CAAS,CAAA,CACzD,QAAA,CAAUb,CAAAA,CACV,qBAAA,CAAuB,IAAA,CAAK,0BAAA,CAA2B,CACrD,OAAA,CAAAF,CAAAA,CACA,SAAA,CAAWE,CAAAA,CACX,OAAA,CAASa,CAAAA,CAAY,EACvB,CAAC,CAAA,CACD,IAAA,CAAM,IAAA,CAAK,IAAA,CACX,qBAAA,CAAuB,IAAA,CAAK,oBAAA,CAAqB7B,CAAW,CAAA,CAC5D,UAAA,CAAY,CAAA,CACZ,WAAA,CAAa,CAAC,CAAE,OAAA,CAAAkB,CAAQ,CAAA,CAAA,EAAM,CAE5B,IAAMY,CAAAA,CAAWH,CAAAA,CAAK,SAAA,CAAU,CAC9B,QAAA,CAAUI,qBAAAA,CAAS,cAAA,CAAed,CAAAA,CAAS,QAAA,CAAS,CAAgB,CAAA,CACpE,QAAA,CAAU,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,GAAA,CAAI,CAAA,CAAI,GAAI,CAAA,CAAI3B,EAAgB,CAAA,CACjE,WAAA,CAAAuC,CAAAA,CACA,MAAA,CAAQX,CAAAA,CACR,SAAA,CAAWA,CAAAA,CACX,SAAA,CAAWE,CACb,CAAC,CAAA,CAEK,CAAE,IAAA,CAAMY,CAAAA,CAAQ,YAAA,CAAAC,CAAa,CAAA,CAAIC,sCAAAA,CACrC,GAAA,CAAKC,eAAAA,CACL,IAAA,CAAML,CAAAA,CAAS,QACjB,CAAC,CAAA,CAED,MAAO,CACL,MAAA,CAAAE,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,GAAA,CAAKE,eAAAA,CACL,OAAA,CAASL,CAAAA,CAAS,EAAA,CAClB,KAAA,CAAOA,CAAAA,CAAS,KAAA,EAAS,MAAA,CAAO,CAAC,CACnC,CACF,CACF,CACF,CACF,UAAA,CAEaM,EAAAA,CAAM,IAAI1C,EAAAA,CC3OvB,IAYM2C,EAAAA,YAAN,MAAA,QAAkC1C,mBAAe,2KAC/C,IAAA,CAAA,YAAA,gBACA,eAAA,CAAkB,CAACC,iBAAAA,CAAQ,OAAA,CAASA,iBAAAA,CAAQ,OAAO,EAAA,gBAC1C,IAAA,CAAO,MAAA,iBAEhB,CAAkB,CAChB,OAAA,CAAAkB,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAGY,CACV,OAAK,KAAA,CAAM,iBAAA,CAAkB,CAAE,OAAA,CAAAD,CAAAA,CAAS,QAAA,CAAAC,CAAS,CAAC,CAAA,CAMhDD,CAAAA,CAAQ,OAAA,GAAYC,CAAAA,CAAS,OAAA,EAC7BhB,iCAAAA,CAAQe,CAAS,KAAA,CAAO,CAAE,OAAA,CAASA,CAAAA,CAAQ,OAAQ,CAAC,CAAA,EACpDf,iCAAAA,CAAQgB,CAAU,MAAM,CAAA,CAPjB,CAAA,CASX,CAEA,MAAM,QAAA,CAAS,CACb,OAAA,CAAAD,CAAAA,CACA,MAAA,CAAAE,CACF,CAAA,CAGiC,CAM/B,EAAA,CALA,IAAA,CAAK,kBAAA,CAAmB,CACtB,OAAA,CAAAF,CAAAA,CACA,QAAA,CAAU,CAAE,GAAGwB,mBAAAA,CAAW,OAAA,CAASxB,CAAAA,CAAQ,OAAQ,CACrD,CAAC,CAAA,CAEG,CAACf,iCAAAA,CAAQe,CAAS,KAAA,CAAO,CAAE,MAAA,CAAQ,IAAA,CAAK,MAAO,CAAC,CAAA,CAClD,MAAM,IAAIyB,wBAAAA,CAAqB,CAC7B,QAAA,CAAU,SAAA,CACV,KAAA,CAAOzB,CAAAA,CACP,QAAA,CAAU,KAAA,CACV,KAAA,CAAO,SACT,CAAC,CAAA,CAGH,MAAO,CACL,SAAA,CAAWE,CAAAA,CACX,QAAA,CAAUA,CAAAA,CACV,qBAAA,CAAuB,CAAC,CAAA,CACxB,IAAA,CAAA,WAAA,CACA,YAAA,CAAc,CAAA,CAAA,CACd,UAAA,CAAY,CAKd,CACF,CACF,WAAA,CAEawB,EAAAA,CAAY,IAAIH,EAAAA,CCxE7B,wJAIiC,IAU3BI,EAAAA,YAAN,MAAA,QAA6B9C,mBAAe,wPAC1C,IAAA,CAAA,OAAA,gBACA,eAAA,CAAkB,CAACC,iBAAAA,CAAQ,OAAO,EAAA,iBACzB,IAAA,CAAO,OAAA,iBAChB,oBAAA,CAAuB,CAAA,EAAA,iBAEvB,gBAAA,CAA6B,CAC3B,qCAAA,CACA,qCAAA,CACA,yDAAA,CACA,qBACF,EAAA,MAEM,QAAA,CAAS,CACb,OAAA,CAAAkB,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAAUC,iBAAAA,CACV,iBAAA,CAAAuB,CAAAA,CACA,6BAAA,CAAAC,CAAAA,CAAgC,CAAA,CAAA,CAChC,WAAA,CAAAC,CACF,CAAA,CAAkD,CAChD,IAAA,CAAK,kBAAA,CAAmB,CAAE,OAAA,CAAA9B,CAAAA,CAAS,QAAA,CAAAC,CAAS,CAAC,CAAA,CAE7C,GAAM,CACJ,cAAA,CAAA8B,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CACF,CAAA,CAAI,IAAA,CAAK,cAAA,CAAelC,CAAAA,CAAQ,OAAA,CAASC,CAAAA,CAAS,OAAO,CAAA,CAEnDkC,CAAAA,CAAuB,IAAA,CAAK,kBAAA,CAChCjC,CAAAA,CACA0B,CACF,CAAA,CAEA,IAAA,CAAK,GAAA,CAAMC,CAAAA,CACP,kCAAA,CACA,CAAA,EAAA;ACkHS,gEAAA;ACvKR,mFAAA","file":"/Users/pong/coding/monobera/packages/berajs/dist/hooks/exports.cjs","sourcesContent":[null,"import useSWR from \"swr\";\n\nimport { usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport type { GetConvertToAssetsProps } from \"../../actions/bend/getConvertToAssets\";\nimport { getConvertToAssets } from \"../../actions/bend/getConvertToAssets\";\nimport { assertPublicClient } from \"../../errors/assert\";\nimport type { DefaultHookOptions } from \"../../types/global\";\n\nexport const useGetConvertToAssets = (\n {\n sharesAmount,\n vaultAddress,\n vaultChainId,\n }: Omit<GetConvertToAssetsProps, \"publicClient\"> & { vaultChainId?: number },\n options?: DefaultHookOptions,\n) => {\n const publicClient = usePublicClient({ chainId: vaultChainId });\n const swrResponse = useSWR(\n publicClient && sharesAmount && vaultAddress\n ? [\"useGetConvertToAssets\", sharesAmount, vaultAddress, vaultChainId]\n : null,\n async ([_, sharesAmount, vaultAddress]) => {\n assertPublicClient(publicClient);\n\n return getConvertToAssets({\n sharesAmount,\n vaultAddress,\n publicClient,\n });\n },\n {\n ...options?.opts,\n },\n );\n\n return {\n ...swrResponse,\n refresh: () => {\n swrResponse.mutate();\n },\n };\n};\n","import { useMemo } from \"react\";\nimport { type Address, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { useBeraWallet, usePublicClient } from \"@berachain/wagmi/hooks\";\n\nimport { bex } from \"../../actions/dex/aggregators/bex\";\nimport { bgtRedeem } from \"../../actions/dex/aggregators/bgt\";\nimport { enso } from \"../../actions/dex/aggregators/enso/enso\";\nimport { erc4626Deposit } from \"../../actions/dex/aggregators/erc4626\";\nimport { fly } from \"../../actions/dex/aggregators/fly\";\nimport { haiku } from \"../../actions/dex/aggregators/haiku\";\nimport { honeyNative } from \"../../actions/dex/aggregators/honey\";\nimport { kyberswap } from \"../../actions/dex/aggregators/kyberswap\";\nimport { oogabooga } from \"../../actions/dex/aggregators/oogabooga\";\nimport { openOcean } from \"../../actions/dex/aggregators/openOcean\";\nimport { wberaSwap } from \"../../actions/dex/aggregators/wbera\";\nimport { useBeraFlag } from \"../../contexts/BeraFlags/BeraFlags\";\nimport type { HoneyConfigContextReturn } from \"../../contexts/HoneyConfigProvider\";\nimport type { SwapReferrer } from \"../../enum/dex\";\nimport 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 { useEffect, useState } from \"react\";\nimport { PoolType } from \"@berachain-foundation/berancer-sdk\";\n\nimport { PoolCreationStep } from \"../../enum/dex\";\nimport type { TokenCurrentPriceMap, TokenWithAmount } from \"../../types/dex\";\nimport { wrapNativeTokens } from \"../../utils/tokenWrapping\";\nimport { type Oracle, OracleMode } from \"./useCreatePool\";\n\nconst DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT = 0.05; // 5%\n\nexport type LiquidityMismatchInfo = {\n title: string | null;\n message: string | null;\n suggestWeighted?: boolean;\n};\n\ninterface UseLiquidityMismatchParams {\n currentStep: PoolCreationStep;\n tokenPrices?: TokenCurrentPriceMap;\n isLoadingTokenPrices: boolean;\n tokens: TokenWithAmount[] | null;\n weights: bigint[] | null;\n weightsError: string | null;\n poolType: PoolType;\n liquidityMismatchTolerancePercent?: number;\n oracles: Oracle[];\n}\n\n/**\n * Hook for detecting liquidity mismatches.\n *\n * @param {PoolCreationStep} currentStep - The current step of the pool creation process.\n * @param {Record<string, number>} tokenPrices - The current token prices.\n * @param {boolean} isLoadingTokenPrices - Whether the token prices are still loading.\n * @param {Array<{ address: string, amount: number }>} tokens - The tokens in the pool, including their addresses and amounts.\n * @param {Record<string, number>} weights - The per-token weights in the pool we are creating.\n * @param {string | null} weightsError - An error message for the weights indicating that the weights are invalid.\n * @param {string} poolType - The type of pool being created.\n * @param {number} liquidityMismatchTolerancePercent - The tolerance for liquidity mismatches in percent.\n * @returns {Object} The liquidity mismatch info.\n */\nexport const useLiquidityMismatch = ({\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent = DEFAULT_LIQUIDITY_MISMATCH_TOLERANCE_PERCENT,\n oracles,\n}: UseLiquidityMismatchParams): LiquidityMismatchInfo => {\n // NOTE: would be nice to use Maps/Records more in here, as the zipping/unzipping is cumbersome.\n // NOTE: if we pull in string literal for currentStep things would also be a bit clearer in here.\n const [liquidityMismatchInfo, setLiquidityMismatchInfo] =\n useState<LiquidityMismatchInfo>({ title: null, message: null });\n\n useEffect(() => {\n // If we are either using custom rate-providing oracles or have incorrect/loading token prices, we cant do validation.\n if (\n !tokenPrices ||\n isLoadingTokenPrices ||\n !tokens ||\n !weights ||\n weightsError ||\n tokens.some((token) => !token.address) ||\n oracles.some((oracle) => oracle.mode === OracleMode.Custom) // Oracles give prices on their own, we dont support that here yet.\n ) {\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Calculate some basic metrics we'll use to determine per-token contributions and model potential losses from arbitrage.\n let totalLiquidityUSD = 0;\n const tokenUSDAmounts: number[] = [];\n const numTokens = tokens.length;\n const wrappedTokens = wrapNativeTokens(tokens);\n const tokenUSDPrices = wrappedTokens.map((token) => {\n const tokenPriceUSD =\n tokenPrices[token.address.toLowerCase()]?.price ?? 0;\n if (!tokenPriceUSD || tokenPriceUSD === 0) {\n tokenUSDAmounts.push(0);\n return null;\n }\n const tokenAmountUSD = tokenPriceUSD * Number.parseFloat(token.amount);\n tokenUSDAmounts.push(tokenAmountUSD);\n totalLiquidityUSD += tokenAmountUSD;\n return tokenPriceUSD;\n });\n\n // Doesn't matter what step it is, if we have missing token prices for tokens we have selected, we cant issue a real warning.\n if (\n tokenUSDPrices.some((price) => price === null) ||\n tokenUSDPrices.length !== numTokens\n ) {\n setLiquidityMismatchInfo({\n title: \"Missing token price data\",\n message: `One or more token(s) do not have valid market price data. Please verify that token market prices align with the pool\n weightings and your initial liquidity amounts.`,\n });\n return;\n }\n\n // Step 1 - During token selection we check for a deviation in the quote prices of the tokens selected (for stable pools).\n if (\n currentStep === PoolCreationStep.SELECT_TOKENS &&\n poolType === PoolType.ComposableStable\n ) {\n const normalizedUSDPrices = tokenUSDPrices.map(\n (priceUSD) => priceUSD! / tokenUSDPrices[0]!, // always normalize on the first token's price\n );\n const maxDifference =\n Math.max(...normalizedUSDPrices) - Math.min(...normalizedUSDPrices);\n\n if (maxDifference > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n title: \"Selected tokens have a significant price deviation\",\n message: \"Did you mean to create a Weighted pool instead?\",\n suggestWeighted: true,\n });\n } else {\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n\n return;\n }\n\n // Validation During Liquidity Input and onwards.\n if (\n totalLiquidityUSD === 0 ||\n tokenUSDAmounts.some((value) => value === 0)\n ) {\n // User has not yet entered fully their liquidity values, so return early.\n setLiquidityMismatchInfo({ title: null, message: null });\n return;\n }\n\n // Simulate arbitrage for the pool to determine potential losses from arbitrageurs.\n // NOTE: we assume shortfalls and excesses are losses, but in reality the actual losses would be more complex to realise.\n // Balancer does this similarily https://github.com/balancer/frontend-v2/blob/8563b8d33b6bff266148bd48d7ebc89f921374f4/src/components/cards/CreatePool/InitialLiquidity.vue#L75\n let totalLossUSD = 0;\n if (poolType === PoolType.ComposableStable) {\n const expectedPerTokenLiquidityUSD = totalLiquidityUSD / numTokens;\n tokenUSDAmounts.forEach((value) => {\n totalLossUSD += Math.abs(expectedPerTokenLiquidityUSD - value);\n });\n } else if (poolType === PoolType.Weighted) {\n tokenUSDAmounts.forEach((value, index) => {\n const weightProportion = Number(weights[index]) / 1e18;\n const expectedValueUSD = totalLiquidityUSD * weightProportion;\n totalLossUSD += Math.abs(expectedValueUSD - value);\n });\n }\n\n // We'll show a total loss if it's 90% or more\n const isTotalLoss = totalLossUSD >= totalLiquidityUSD * 0.9;\n totalLossUSD = Math.min(totalLossUSD, totalLiquidityUSD);\n const totalLossPercentage = totalLossUSD / totalLiquidityUSD;\n\n if (totalLossPercentage > liquidityMismatchTolerancePercent) {\n setLiquidityMismatchInfo({\n // If it's a total loss we dont display a percentage\n title: isTotalLoss\n ? \"You could lose all of your initial liquidity\"\n : `You could lose $${totalLossUSD.toFixed(2)} (~${(\n totalLossPercentage * 100\n ).toFixed(2)}%)`,\n message: `Based on the market token prices, the value of tokens does not align with the specified pool weights. \n This discrepancy could expose you to potential losses from arbitrageurs. ${\n poolType === PoolType.ComposableStable\n ? \"Did you mean to create a Weighted pool instead?\"\n : \"\"\n }`,\n suggestWeighted: poolType === PoolType.ComposableStable,\n });\n } else {\n // All good bb bb\n setLiquidityMismatchInfo({ title: null, message: null });\n }\n }, [\n currentStep,\n tokenPrices,\n isLoadingTokenPrices,\n tokens,\n weights,\n weightsError,\n poolType,\n liquidityMismatchTolerancePercent,\n oracles,\n ]);\n return liquidityMismatchInfo;\n};\n","import { useMemo } from \"react\";\nimport useSWR from \"swr\";\nimport { type Address, isAddress, zeroAddress } from \"viem\";\n\nimport { defaultChainId } from \"@berachain/config/internal\";\n\nimport { getTokenCurrentPrices } from \"../../actions/prices/getTokenCurrentPrices\";\nimport { POLLING } from \"../../enum/polling\";\nimport 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"]}
|