@berachain/berajs 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{transactionStore-BvStaXf3.d.ts → BexStatusProvider-nS3NcdxI.d.cts} +1 -41
- package/dist/{transactionStore-CQrGYSY2.d.cts → BexStatusProvider-nS3NcdxI.d.ts} +1 -41
- package/dist/abi/exports.cjs.map +1 -1
- package/dist/actions/exports.cjs +1 -1
- package/dist/actions/exports.cjs.map +1 -1
- package/dist/actions/exports.d.cts +4 -5
- package/dist/actions/exports.d.ts +4 -5
- package/dist/actions/exports.mjs +1 -1
- package/dist/{chunk-OS5AJMYJ.cjs → chunk-22J3YJDN.cjs} +2 -2
- package/dist/chunk-22J3YJDN.cjs.map +1 -0
- package/dist/{chunk-MTS5SZLA.mjs → chunk-2LL3P5PN.mjs} +2 -2
- package/dist/chunk-3YXSUBA5.mjs +2 -0
- package/dist/{chunk-H2QSRMVS.mjs.map → chunk-3YXSUBA5.mjs.map} +1 -1
- package/dist/chunk-55L7STYD.mjs +2 -0
- package/dist/chunk-55L7STYD.mjs.map +1 -0
- package/dist/{chunk-BOYZVULX.cjs → chunk-6LDOG5RL.cjs} +2 -2
- package/dist/chunk-6LDOG5RL.cjs.map +1 -0
- package/dist/{chunk-UQUWMHVF.cjs → chunk-7LNBSOVV.cjs} +2 -2
- package/dist/chunk-7LNBSOVV.cjs.map +1 -0
- package/dist/{chunk-ZQRACIGR.mjs → chunk-7SMWQ6SN.mjs} +2 -2
- package/dist/{chunk-7GWTHOLO.mjs → chunk-7WRTK7RJ.mjs} +2 -2
- package/dist/chunk-A4UDYSB6.mjs +4 -0
- package/dist/chunk-A4UDYSB6.mjs.map +1 -0
- package/dist/chunk-AX2YQQFQ.mjs +2 -0
- package/dist/chunk-AX2YQQFQ.mjs.map +1 -0
- package/dist/chunk-C6ZGUO4H.cjs +2 -0
- package/dist/chunk-C6ZGUO4H.cjs.map +1 -0
- package/dist/chunk-CYKCYPFR.cjs.map +1 -1
- package/dist/chunk-ECRMUMTA.mjs +2 -0
- package/dist/chunk-ECRMUMTA.mjs.map +1 -0
- package/dist/{chunk-ZAKA4TGK.cjs → chunk-FCWDGE62.cjs} +2 -2
- package/dist/chunk-FCWDGE62.cjs.map +1 -0
- package/dist/chunk-FL2N3XHK.cjs.map +1 -1
- package/dist/chunk-MUCEYO3E.cjs +4 -0
- package/dist/chunk-MUCEYO3E.cjs.map +1 -0
- package/dist/chunk-OIYXOKTT.cjs.map +1 -1
- package/dist/chunk-P2Q7CMUD.cjs +2 -0
- package/dist/chunk-P2Q7CMUD.cjs.map +1 -0
- package/dist/chunk-PKXAW6MO.cjs +2 -0
- package/dist/chunk-PKXAW6MO.cjs.map +1 -0
- package/dist/chunk-SWMJQOH6.cjs.map +1 -1
- package/dist/{chunk-YQGZMWDT.mjs → chunk-THATXCJK.mjs} +2 -2
- package/dist/chunk-VP7XUOSI.cjs.map +1 -1
- package/dist/chunk-VXL2ZZ4X.cjs.map +1 -1
- package/dist/chunk-WRFDB3QJ.cjs.map +1 -1
- package/dist/chunk-XNJLSA6P.cjs.map +1 -1
- package/dist/chunk-YZV5LKIP.cjs +2 -0
- package/dist/chunk-YZV5LKIP.cjs.map +1 -0
- package/dist/contexts/exports.cjs +1 -1
- package/dist/contexts/exports.cjs.map +1 -1
- package/dist/contexts/exports.d.cts +2 -10
- package/dist/contexts/exports.d.ts +2 -10
- package/dist/contexts/exports.mjs +1 -1
- package/dist/contexts/exports.mjs.map +1 -1
- package/dist/enum/exports.cjs.map +1 -1
- package/dist/enum/exports.d.cts +1 -2
- package/dist/enum/exports.d.ts +1 -2
- package/dist/errors/exports.cjs +1 -1
- package/dist/errors/exports.cjs.map +1 -1
- package/dist/errors/exports.d.cts +25 -2
- package/dist/errors/exports.d.ts +25 -2
- package/dist/errors/exports.mjs +1 -1
- package/dist/{getValidatorQueuedOperatorAddress-It0GsdvQ.d.cts → getValidatorQueuedOperatorAddress-Dstyaomr.d.cts} +1 -1
- package/dist/{getValidatorQueuedOperatorAddress-BX35p2Lv.d.ts → getValidatorQueuedOperatorAddress-RW4OMcD1.d.ts} +1 -1
- package/dist/{global.d-Ba-NIojH.d.cts → global.d-CN6l2b9E.d.cts} +1 -2
- package/dist/{global.d-By70bEv2.d.ts → global.d-wYu8G8IQ.d.ts} +1 -2
- package/dist/hooks/exports.cjs +2 -2
- package/dist/hooks/exports.cjs.map +1 -1
- package/dist/hooks/exports.d.cts +7 -15
- package/dist/hooks/exports.d.ts +7 -15
- package/dist/hooks/exports.mjs +3 -3
- package/dist/hooks/exports.mjs.map +1 -1
- package/dist/{txnEnum-BYNbCxla.d.ts → txnEnum-BlBYhNRl.d.cts} +74 -1
- package/dist/{txnEnum-BYNbCxla.d.cts → txnEnum-BlBYhNRl.d.ts} +74 -1
- package/dist/types/exports.cjs.map +1 -1
- package/dist/types/exports.d.cts +2 -3
- package/dist/types/exports.d.ts +2 -3
- package/dist/utils/exports.cjs +1 -1
- package/dist/utils/exports.cjs.map +1 -1
- package/dist/utils/exports.mjs +1 -1
- package/dist/utils/exports.mjs.map +1 -1
- package/package.json +6 -6
- package/src/actions/dex/aggregators/haiku.ts +1 -1
- package/src/actions/dex/aggregators/oogabooga.ts +1 -1
- package/src/actions/pol/getEarnedStakedBeraVault.ts +1 -1
- package/src/actions/pol/getStakingDailyAssets.ts +4 -1
- package/src/actions/tokens/getWalletBalances.integration.test.ts +1 -1
- package/src/contexts/exports.ts +0 -1
- package/src/data/contracts.ts +1 -1
- package/src/errors/BeraError.ts +11 -2
- package/src/errors/RequestError.ts +27 -1
- package/src/errors/errorMap.ts +7 -6
- package/src/errors/getErrorMessage.ts +59 -20
- package/src/errors/getRevertReason.integration.test.ts +1 -1
- package/src/hooks/exports.ts +0 -4
- package/src/hooks/pol/useStakedData.ts +1 -1
- package/dist/chunk-7SC4VD3U.cjs +0 -2
- package/dist/chunk-7SC4VD3U.cjs.map +0 -1
- package/dist/chunk-BHNQX4XC.mjs +0 -2
- package/dist/chunk-BHNQX4XC.mjs.map +0 -1
- package/dist/chunk-BOYZVULX.cjs.map +0 -1
- package/dist/chunk-C3G5KXCH.mjs +0 -2
- package/dist/chunk-C3G5KXCH.mjs.map +0 -1
- package/dist/chunk-G6NA6NSM.mjs +0 -4
- package/dist/chunk-G6NA6NSM.mjs.map +0 -1
- package/dist/chunk-H2QSRMVS.mjs +0 -2
- package/dist/chunk-IJM76AWK.cjs +0 -4
- package/dist/chunk-IJM76AWK.cjs.map +0 -1
- package/dist/chunk-MUNAP5TM.cjs +0 -2
- package/dist/chunk-MUNAP5TM.cjs.map +0 -1
- package/dist/chunk-OS5AJMYJ.cjs.map +0 -1
- package/dist/chunk-TJWKS54T.mjs +0 -2
- package/dist/chunk-TJWKS54T.mjs.map +0 -1
- package/dist/chunk-UQUWMHVF.cjs.map +0 -1
- package/dist/chunk-UXUWSRVV.cjs +0 -2
- package/dist/chunk-UXUWSRVV.cjs.map +0 -1
- package/dist/chunk-WTCBORPB.cjs +0 -2
- package/dist/chunk-WTCBORPB.cjs.map +0 -1
- package/dist/chunk-ZAKA4TGK.cjs.map +0 -1
- package/dist/contracts-CQIPk0Jc.d.cts +0 -74
- package/dist/contracts-CQIPk0Jc.d.ts +0 -74
- package/src/contexts/TransactionStoreContext.tsx +0 -87
- package/src/hooks/transactions/transactionStore.ts +0 -296
- package/src/hooks/transactions/transactionStore.unit.test.ts +0 -561
- package/src/hooks/transactions/useAddRecentTransaction.ts +0 -29
- package/src/hooks/transactions/useRecentTransactions.ts +0 -27
- package/src/hooks/transactions/useSetTransactionStatus.ts +0 -31
- /package/dist/{chunk-MTS5SZLA.mjs.map → chunk-2LL3P5PN.mjs.map} +0 -0
- /package/dist/{chunk-ZQRACIGR.mjs.map → chunk-7SMWQ6SN.mjs.map} +0 -0
- /package/dist/{chunk-7GWTHOLO.mjs.map → chunk-7WRTK7RJ.mjs.map} +0 -0
- /package/dist/{chunk-YQGZMWDT.mjs.map → chunk-THATXCJK.mjs.map} +0 -0
package/dist/actions/exports.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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; }var _chunkFL2N3XHKcjs = require('../chunk-FL2N3XHK.cjs');var _chunkIJM76AWKcjs = require('../chunk-IJM76AWK.cjs');var _chunkVP7XUOSIcjs = require('../chunk-VP7XUOSI.cjs');var _chunkZAKA4TGKcjs = require('../chunk-ZAKA4TGK.cjs');require('../chunk-OIYXOKTT.cjs');require('../chunk-WRFDB3QJ.cjs');require('../chunk-BOYZVULX.cjs');var _chunkUQUWMHVFcjs = require('../chunk-UQUWMHVF.cjs');var _chunkMUNAP5TMcjs = require('../chunk-MUNAP5TM.cjs');var _chunkOS5AJMYJcjs = require('../chunk-OS5AJMYJ.cjs');require('../chunk-7SC4VD3U.cjs');var _viem = require('viem');async function Jt({vaultAddress:e,publicClient:t}){let r=await t.readContract({address:e,abi:_chunkVP7XUOSIcjs.a,functionName:"maxDeposit",args:[e]});return _viem.formatEther.call(void 0, r)}var _berancersdk = require('@berachain-foundation/berancer-sdk');var Ht=e=>({type:_berancersdk.mapPoolType.call(void 0, e.type),protocolVersion:e.protocolVersion,tokens:e.tokens.map(t=>({...t,address:t.address})),id:e.id,address:e.address});async function Lt({publicClient:e,...t}){let{config:r}=_chunkOS5AJMYJcjs.a.call(void 0, t);return(await e.readContract({address:r.bex.vault,abi:_chunkVP7XUOSIcjs.b,functionName:"getPausedState"}))[0]}var _internal = require('@berachain/config/internal');function Q(e){return e.some(t=>t.name==="implementation"||t.name==="proxyType"||t.type==="constructor"&&_optionalChain([t, 'access', _2 => _2.inputs, 'optionalAccess', _3 => _3[0], 'optionalAccess', _4 => _4.name])==="implementation")}async function V({contractAddress:e,chainId:t,publicClient:r}){let o=`https://api.etherscan.io/v2/api?module=contract&action=getabi&address=${e}&apikey=${_internal.appConfig.apiKeys.private.etherscan}&chainId=${t}`,a=await fetch(o);if(!a.ok)throw new Error(`Failed to fetch ABI: ${a.statusText}`);let n=await a.json();if(n.status==="0")throw new Error(n.result);let p=JSON.parse(n.result);if(!Q(p))return p;let i=await r.getStorageAt({address:e,slot:"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"});if(!i||_viem.trim.call(void 0, i)==="0x00")return p;let s=_viem.pad.call(void 0, _viem.trim.call(void 0, i),{size:20});return V({contractAddress:s,chainId:t,publicClient:r})}async function z({address:e,callData:t,knownAbi:r,chainId:o,publicClient:a}){try{if(_viem.decodeFunctionData.call(void 0, {data:t,abi:r}))return r}catch (e2){}try{return await V({contractAddress:e,chainId:o,publicClient:a})}catch (e3){}}function X(e,t){try{return _viem.decodeFunctionData.call(void 0, {data:e,abi:t})}catch (e4){return}}function j(e,t){return e.find(r=>r.type==="function"&&r.name===t)}function K(e){if(e)try{return _viem.toFunctionSignature.call(void 0, e)}catch(t){console.error(t)}}async function Kt({address:e,callData:t,chainId:r=_internal.defaultChainId,publicClient:o}){let a=[..._chunkVP7XUOSIcjs.i,..._chunkVP7XUOSIcjs.k,..._viem.erc20Abi],n=await z({address:e,callData:t,knownAbi:a,chainId:r,publicClient:o}),p=X(t,n);if(!n||!p)return{args:[]};let i=j(n,p.functionName),s=K(i);return{abiItem:i,functionSignature:s,functionName:p.functionName,args:p.args}}async function rr({client:e,collateralList:t,...r}){let{config:o}=_chunkOS5AJMYJcjs.a.call(void 0, r);try{let a={mint:[],redeem:[]};for(let s of t)a.mint.push(e.readContract({address:o.honey.factory,abi:_chunkVP7XUOSIcjs.e,functionName:"mintRates",args:[s.address]})),a.redeem.push(e.readContract({address:o.honey.factory,abi:_chunkVP7XUOSIcjs.e,functionName:"redeemRates",args:[s.address]}));let[n,p,i]=await Promise.all([Promise.all(a.mint),Promise.all(a.redeem),e.readContract({address:o.honey.factory,abi:_chunkVP7XUOSIcjs.e,functionName:"getWeights"})]);return t.reduce((s,d)=>{let c=t.indexOf(d);return s.single[d.address]={mintFee:1-+_viem.formatUnits.call(void 0, n[c],18),redeemFee:1-+_viem.formatUnits.call(void 0, p[c],18)},s.basket.mintFee+=s.single[d.address].mintFee*+_viem.formatUnits.call(void 0, i[c],18),s.basket.redeemFee+=s.single[d.address].redeemFee*+_viem.formatUnits.call(void 0, i[c],18),s},{single:{},basket:{mintFee:0,redeemFee:0}})}catch(a){throw console.log(a),a}}async function ir({client:e,...t}){let{config:r}=_chunkOS5AJMYJcjs.a.call(void 0, t),o=r.honey.token;return await e.readContract({address:o,abi:_chunkFL2N3XHKcjs.a,functionName:"paused"})}async function pr({pythOracle:e,publicClient:t}){return await t.readContract({address:e,abi:_chunkFL2N3XHKcjs.b,functionName:"pythOracle"})}async function lr({publicClient:e,factory:t,...r}){let{config:o}=_chunkOS5AJMYJcjs.a.call(void 0, r);return await e.readContract({address:_nullishCoalesce(t, () => (o.honey.factory)),abi:_chunkVP7XUOSIcjs.e,functionName:"priceOracle"})}var _chain = require('@berachain/graphql/chain');async function Ar({defaultBlockTime:e,blocksSpan:t,...r}={}){let{config:o}=_chunkOS5AJMYJcjs.a.call(void 0, r),a=_chunkIJM76AWKcjs.c.call(void 0, "blocks.subgraph",r),n=_nullishCoalesce(e, () => (o.averageBlockTime)),p=_nullishCoalesce(t, () => (Math.floor(_chunkMUNAP5TMcjs.p.call(void 0, 1)/n))),s=(await a.query({query:_chain.GetBlocksTimeStamp,variables:{skip:p}})).data;return(_chunkMUNAP5TMcjs.k.call(void 0, Date.now())-Number(_optionalChain([s, 'optionalAccess', _5 => _5.oldest, 'access', _6 => _6[0], 'optionalAccess', _7 => _7.timestamp])))/(Number(_optionalChain([s, 'optionalAccess', _8 => _8.newest, 'access', _9 => _9[0], 'optionalAccess', _10 => _10.number]))-Number(_optionalChain([s, 'optionalAccess', _11 => _11.oldest, 'access', _12 => _12[0], 'optionalAccess', _13 => _13.number])))}async function kr({tokenList:e,publicClient:t,lstStakingVaults:r,...o}){_chunkUQUWMHVFcjs.c.call(void 0, t);let{config:a}=_chunkOS5AJMYJcjs.a.call(void 0, {...o,chainId:_nullishCoalesce(_optionalChain([t, 'access', _14 => _14.chain, 'optionalAccess', _15 => _15.id]), () => (o.chainId))}),n=e.filter(i=>r.includes(i.address));return n.length===0?[]:(await Promise.all(n.map(async i=>({assetTokenAddress:await t.readContract({address:i.address,abi:_chunkFL2N3XHKcjs.d,functionName:"asset"}),stakingToken:i})))).reduce((i,{assetTokenAddress:s,stakingToken:d})=>{let c=e.find(g=>_chunkOS5AJMYJcjs.e.call(void 0, g,s));return c&&i.push({id:d.address,receiptToken:d,inputTokens:[c]}),i},[])}var O=[{inputs:[{internalType:"address",name:"initialOwner",type:"address"},{internalType:"address",name:"initialImplementation",type:"address"}],stateMutability:"payable",type:"constructor"},{inputs:[],name:"NewImplementationHasNoCode",type:"error"},{inputs:[],name:"NewOwnerIsZeroAddress",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"oldOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{inputs:[],name:"implementation",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"}],name:"upgradeTo",outputs:[],stateMutability:"nonpayable",type:"function"}];async function W({publicClient:e,...t}){let{config:r}=_chunkOS5AJMYJcjs.a.call(void 0, t),o=r.pol.factory;_chunkUQUWMHVFcjs.b.call(void 0, e,"publicClient"),_chunkUQUWMHVFcjs.d.call(void 0, r.pol.factory,"factoryAddress");let a=await e.readContract({address:o,abi:_chunkVP7XUOSIcjs.l,functionName:"beacon"});return await e.readContract({address:a,abi:O,functionName:"implementation"})}async function Or({publicClient:e,...t}){_chunkUQUWMHVFcjs.c.call(void 0, e);let r=await W({publicClient:e,...t}),[o,a]=await Promise.all([e.readContract({address:r,abi:_chunkVP7XUOSIcjs.k,functionName:"MIN_REWARD_DURATION"}),e.readContract({address:r,abi:_chunkVP7XUOSIcjs.k,functionName:"MAX_REWARD_DURATION"})]);return{minRewardDuration:Number(o),maxRewardDuration:Number(a)}}async function Hr({tokenAddress:e,publicClient:t,factoryAddress:r,...o}){let{config:a}=_chunkOS5AJMYJcjs.a.call(void 0, o),n=await t.readContract({address:_nullishCoalesce(r, () => (a.pol.factory)),abi:_chunkVP7XUOSIcjs.l,functionName:"getVault",args:[e]});return n===_viem.zeroAddress?null:n}async function Lr({tokenList:e,publicClient:t,...r}){let{config:o}=_chunkOS5AJMYJcjs.a.call(void 0, r);try{let a=await Promise.all(e.map(n=>t.readContract({address:o.honey.pythOracle,abi:_chunkFL2N3XHKcjs.c,functionName:"feeds",args:[n]})));return e.reduce((n,p,i)=>({...n,[p]:a[i]}),{})}catch(a){throw console.error("getPythPriceFeedId",a),a}}async function Xr({url:e,...t}={}){let{config:r}=_chunkOS5AJMYJcjs.a.call(void 0, t);returnawait _asyncNullishCoalesce((await _chunkMUNAP5TMcjs.c.call(void 0, {url:_nullishCoalesce(e, () => (r.lists.tokenList)),type:"rest",name:"GitHub"})).tokens, async () => ([]))}async function eo({publicClient:e,ui:t,...r}){let{config:o}=_chunkOS5AJMYJcjs.a.call(void 0, r),[a,n,p,i,s,d,c,g]=await Promise.all([e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"MAX_COMMISSION_RATE"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"commissionChangeDelay"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"rewardAllocationBlockDelay"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"maxWeightPerVault"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"maxNumWeightsPerRewardAllocation"}),e.readContract({address:o.tokens.bgt,abi:_chunkVP7XUOSIcjs.j,functionName:"dropBoostDelay"}),e.readContract({address:o.tokens.bgt,abi:_chunkVP7XUOSIcjs.j,functionName:"activateBoostDelay"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"rewardAllocationInactivityBlockSpan"})]);return{maxCommissionRate:Number(a)/1e4,boostDelay:Number(c),unboostDelay:Number(d),commissionChangeDelay:Number(n),rewardAllocationBlockDelay:Number(p),maxWeightPerVault:Number(i)/1e4,maxNumWeightsPerRewardAllocation:Number(s),rewardAllocationInactivityBlockSpan:Number(g),ui:t}}function ee(e){return _optionalChain([e, 'optionalAccess', _16 => _16.rewardAllocationWeights, 'optionalAccess', _17 => _17.reduce, 'call', _18 => _18((t,r)=>{if(!r)return t;let o=_nullishCoalesce(_optionalChain([r, 'access', _19 => _19.receivingVault, 'optionalAccess', _20 => _20.activeIncentives, 'access', _21 => _21.filter, 'call', _22 => _22(a=>Number(a.remainingAmount)>0), 'access', _23 => _23.reduce, 'call', _24 => _24((a,n)=>{let p=Number(n.remainingAmountUsd)/Number(n.remainingAmount);return a+Number(n.incentiveRate)*p},0)]), () => (0));return t+o*r.percentage},0)])}function ro({validator:e,bgtPrice:t}){let r=Number(_nullishCoalesce(_optionalChain([e, 'access', _25 => _25.dynamicData, 'optionalAccess', _26 => _26.activeBoostAmount]), () => (0))),o=ee(e);return!o||!r?0:o*Number(_nullishCoalesce(_optionalChain([e, 'access', _27 => _27.dynamicData, 'optionalAccess', _28 => _28.lastDayDistributedBGTAmount]), () => (0)))*365/(r*t)}exports.BalancerApi = _chunkIJM76AWKcjs.f; exports.BaseAggregator = _chunkIJM76AWKcjs.e; exports.BeraApolloClient = _chunkIJM76AWKcjs.b; exports.HoneyPreviewMethod = _chunkIJM76AWKcjs.E; exports.MOCKED_PROPOSAL_STATUSES = _chunkIJM76AWKcjs.p; exports.RewardVaultDistributionMode = _chunkIJM76AWKcjs.N; exports.beraWriteContract = _chunkIJM76AWKcjs.na; exports.checkProposalField = _chunkIJM76AWKcjs.o; exports.computeActualStatus = _chunkIJM76AWKcjs.q; exports.formatValidatorRewardAllocation = _chunkIJM76AWKcjs.sa; exports.getActiveBoostAndCommissionChangeDelay = eo; exports.getAllPools = _chunkIJM76AWKcjs.g; exports.getAllProposals = _chunkIJM76AWKcjs.r; exports.getAllValidators = _chunkIJM76AWKcjs.oa; exports.getAllowances = _chunkIJM76AWKcjs.la; exports.getApiEnrichedAllocation = _chunkIJM76AWKcjs.pa; exports.getApiPool = _chunkIJM76AWKcjs.h; exports.getApiValidator = _chunkIJM76AWKcjs.qa; exports.getApolloClient = _chunkIJM76AWKcjs.c; exports.getBalanceCall = _chunkZAKA4TGKcjs.b; exports.getBgtAprSimulation = _chunkIJM76AWKcjs.P; exports.getBlockTime = Ar; exports.getBlockTimestamp = _chunkIJM76AWKcjs.M; exports.getBodyErrors = _chunkIJM76AWKcjs.s; exports.getChartData = _chunkIJM76AWKcjs.x; exports.getCollateralWeights = _chunkIJM76AWKcjs.y; exports.getConvertToAssets = _chunkIJM76AWKcjs.a; exports.getDailyValidatorBlockStats = _chunkIJM76AWKcjs.ra; exports.getDecodedFunctionData = Kt; exports.getDefaultRewardAllocation = _chunkIJM76AWKcjs.wa; exports.getEarnedStakedBeraVault = _chunkIJM76AWKcjs.Q; exports.getEnsoClient = _chunkZAKA4TGKcjs.a; exports.getGlobalCapLimit = _chunkIJM76AWKcjs.C; exports.getGlobalData = _chunkIJM76AWKcjs.S; exports.getGlobalLiquidityAndSwapVolume = _chunkIJM76AWKcjs.i; exports.getHoneyCollaterals = _chunkIJM76AWKcjs.A; exports.getHoneyFees = rr; exports.getHoneyGlobalData = _chunkIJM76AWKcjs.D; exports.getHoneyPausedState = ir; exports.getHoneyPreview = _chunkIJM76AWKcjs.F; exports.getHoneyPythFeeds = Lr; exports.getHoneyPythOracle = pr; exports.getHoneyRootPriceOracle = lr; exports.getHoneyVaultsBalance = _chunkIJM76AWKcjs.G; exports.getIncentiveFeeClaimStats = _chunkIJM76AWKcjs.T; exports.getLSTStakeConfig = kr; exports.getManagedValidatorByAccount = _chunkIJM76AWKcjs.xa; exports.getMarkets = _chunkIJM76AWKcjs.U; exports.getMaxDeposit = Jt; exports.getOnChainPool = _chunkIJM76AWKcjs.k; exports.getPoolEvents = _chunkIJM76AWKcjs.l; exports.getPoolHistoricalData = _chunkIJM76AWKcjs.m; exports.getPoolPausedState = _chunkIJM76AWKcjs.j; exports.getPoolState = Ht; exports.getProposalDetails = _chunkIJM76AWKcjs.t; exports.getProposalFromTx = _chunkIJM76AWKcjs.v; exports.getProposalVotes = _chunkIJM76AWKcjs.w; exports.getPythLatestPrices = _chunkIJM76AWKcjs.H; exports.getPythUpdateFee = _chunkIJM76AWKcjs.J; exports.getRelativeCapLimit = _chunkIJM76AWKcjs.I; exports.getRewardProofsByValidator = _chunkIJM76AWKcjs.V; exports.getRewardTokenToBeraRate = _chunkIJM76AWKcjs.W; exports.getRewardVault = _chunkIJM76AWKcjs.X; exports.getRewardVaultDurationConstants = Or; exports.getRewardVaultFromToken = Hr; exports.getRewardVaultIncentives = _chunkIJM76AWKcjs.Y; exports.getRewardVaultRewards = _chunkIJM76AWKcjs.O; exports.getRewardVaultStakingToken = _chunkIJM76AWKcjs.Z; exports.getRewardVaults = _chunkIJM76AWKcjs.R; exports.getSWBeraVaultMetadata = _chunkIJM76AWKcjs.ba; exports.getSWBeraWithdrawal = _chunkIJM76AWKcjs.ca; exports.getStakeWithdrawalCooldown = _chunkIJM76AWKcjs.aa; exports.getStakedBeraAPR = _chunkIJM76AWKcjs._; exports.getStakedBeraSnapshots = _chunkIJM76AWKcjs.$; exports.getStakingPoolBatch = _chunkIJM76AWKcjs.ya; exports.getSubgraphPool = _chunkIJM76AWKcjs.n; exports.getSwapPayload = _chunkIJM76AWKcjs.K; exports.getTokenCurrentPrices = _chunkIJM76AWKcjs.ka; exports.getTokenInformation = _chunkIJM76AWKcjs.z; exports.getTokens = Xr; exports.getTotalStakedAmount = _chunkIJM76AWKcjs.da; exports.getUserActiveValidators = _chunkIJM76AWKcjs.Aa; exports.getUserBoostsOnValidator = _chunkIJM76AWKcjs.za; exports.getUserClaimableIncentives = _chunkIJM76AWKcjs.ea; exports.getUserStakingPositions = _chunkIJM76AWKcjs.Ba; exports.getUserVaultInfo = _chunkIJM76AWKcjs.ga; exports.getUserVaults = _chunkIJM76AWKcjs.ha; exports.getUserVaultsReward = _chunkIJM76AWKcjs.fa; exports.getValidatorAnalytics = _chunkIJM76AWKcjs.Ca; exports.getValidatorBoostApy = ro; exports.getValidatorCommission = _chunkIJM76AWKcjs.Da; exports.getValidatorEstimatedBgtPerYear = _chunkIJM76AWKcjs.Ea; exports.getValidatorOperatorAddress = _chunkIJM76AWKcjs.Fa; exports.getValidatorQueuedCommission = _chunkIJM76AWKcjs.Ga; exports.getValidatorQueuedOperatorAddress = _chunkIJM76AWKcjs.Ha; exports.getValidatorQueuedRewardAllocation = _chunkIJM76AWKcjs.Ia; exports.getValidatorReturnPerBgt = ee; exports.getValidatorRewardAllocation = _chunkIJM76AWKcjs.ua; exports.getVaultHistory = _chunkIJM76AWKcjs.ia; exports.getVaultPausedState = Lt; exports.getVaultValidators = _chunkIJM76AWKcjs.ja; exports.getWalletBalances = _chunkZAKA4TGKcjs.c; exports.gql = _chunkIJM76AWKcjs.d; exports.isBadCollateralAsset = _chunkIJM76AWKcjs.B; exports.isBasketModeEnabled = _chunkIJM76AWKcjs.L; exports.isDefaultRewardAllocation = _chunkIJM76AWKcjs.va; exports.isImpersonateAccount = _chunkIJM76AWKcjs.ma; exports.isSameRewardAllocation = _chunkIJM76AWKcjs.ta; exports.parseProposalBody = _chunkIJM76AWKcjs.u;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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; }var _chunkFL2N3XHKcjs = require('../chunk-FL2N3XHK.cjs');var _chunkMUCEYO3Ecjs = require('../chunk-MUCEYO3E.cjs');var _chunkVP7XUOSIcjs = require('../chunk-VP7XUOSI.cjs');var _chunkFCWDGE62cjs = require('../chunk-FCWDGE62.cjs');require('../chunk-OIYXOKTT.cjs');require('../chunk-WRFDB3QJ.cjs');require('../chunk-6LDOG5RL.cjs');var _chunk7LNBSOVVcjs = require('../chunk-7LNBSOVV.cjs');var _chunkPKXAW6MOcjs = require('../chunk-PKXAW6MO.cjs');var _chunk22J3YJDNcjs = require('../chunk-22J3YJDN.cjs');require('../chunk-C6ZGUO4H.cjs');var _viem = require('viem');async function Jt({vaultAddress:e,publicClient:t}){let r=await t.readContract({address:e,abi:_chunkVP7XUOSIcjs.a,functionName:"maxDeposit",args:[e]});return _viem.formatEther.call(void 0, r)}var _berancersdk = require('@berachain-foundation/berancer-sdk');var Ht=e=>({type:_berancersdk.mapPoolType.call(void 0, e.type),protocolVersion:e.protocolVersion,tokens:e.tokens.map(t=>({...t,address:t.address})),id:e.id,address:e.address});async function Lt({publicClient:e,...t}){let{config:r}=_chunk22J3YJDNcjs.a.call(void 0, t);return(await e.readContract({address:r.bex.vault,abi:_chunkVP7XUOSIcjs.b,functionName:"getPausedState"}))[0]}var _internal = require('@berachain/config/internal');function Q(e){return e.some(t=>t.name==="implementation"||t.name==="proxyType"||t.type==="constructor"&&_optionalChain([t, 'access', _2 => _2.inputs, 'optionalAccess', _3 => _3[0], 'optionalAccess', _4 => _4.name])==="implementation")}async function V({contractAddress:e,chainId:t,publicClient:r}){let o=`https://api.etherscan.io/v2/api?module=contract&action=getabi&address=${e}&apikey=${_internal.appConfig.apiKeys.private.etherscan}&chainId=${t}`,a=await fetch(o);if(!a.ok)throw new Error(`Failed to fetch ABI: ${a.statusText}`);let n=await a.json();if(n.status==="0")throw new Error(n.result);let p=JSON.parse(n.result);if(!Q(p))return p;let i=await r.getStorageAt({address:e,slot:"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"});if(!i||_viem.trim.call(void 0, i)==="0x00")return p;let s=_viem.pad.call(void 0, _viem.trim.call(void 0, i),{size:20});return V({contractAddress:s,chainId:t,publicClient:r})}async function z({address:e,callData:t,knownAbi:r,chainId:o,publicClient:a}){try{if(_viem.decodeFunctionData.call(void 0, {data:t,abi:r}))return r}catch (e2){}try{return await V({contractAddress:e,chainId:o,publicClient:a})}catch (e3){}}function X(e,t){try{return _viem.decodeFunctionData.call(void 0, {data:e,abi:t})}catch (e4){return}}function j(e,t){return e.find(r=>r.type==="function"&&r.name===t)}function K(e){if(e)try{return _viem.toFunctionSignature.call(void 0, e)}catch(t){console.error(t)}}async function Kt({address:e,callData:t,chainId:r=_internal.defaultChainId,publicClient:o}){let a=[..._chunkVP7XUOSIcjs.i,..._chunkVP7XUOSIcjs.k,..._viem.erc20Abi],n=await z({address:e,callData:t,knownAbi:a,chainId:r,publicClient:o}),p=X(t,n);if(!n||!p)return{args:[]};let i=j(n,p.functionName),s=K(i);return{abiItem:i,functionSignature:s,functionName:p.functionName,args:p.args}}async function rr({client:e,collateralList:t,...r}){let{config:o}=_chunk22J3YJDNcjs.a.call(void 0, r);try{let a={mint:[],redeem:[]};for(let s of t)a.mint.push(e.readContract({address:o.honey.factory,abi:_chunkVP7XUOSIcjs.e,functionName:"mintRates",args:[s.address]})),a.redeem.push(e.readContract({address:o.honey.factory,abi:_chunkVP7XUOSIcjs.e,functionName:"redeemRates",args:[s.address]}));let[n,p,i]=await Promise.all([Promise.all(a.mint),Promise.all(a.redeem),e.readContract({address:o.honey.factory,abi:_chunkVP7XUOSIcjs.e,functionName:"getWeights"})]);return t.reduce((s,d)=>{let c=t.indexOf(d);return s.single[d.address]={mintFee:1-+_viem.formatUnits.call(void 0, n[c],18),redeemFee:1-+_viem.formatUnits.call(void 0, p[c],18)},s.basket.mintFee+=s.single[d.address].mintFee*+_viem.formatUnits.call(void 0, i[c],18),s.basket.redeemFee+=s.single[d.address].redeemFee*+_viem.formatUnits.call(void 0, i[c],18),s},{single:{},basket:{mintFee:0,redeemFee:0}})}catch(a){throw console.log(a),a}}async function ir({client:e,...t}){let{config:r}=_chunk22J3YJDNcjs.a.call(void 0, t),o=r.honey.token;return await e.readContract({address:o,abi:_chunkFL2N3XHKcjs.a,functionName:"paused"})}async function pr({pythOracle:e,publicClient:t}){return await t.readContract({address:e,abi:_chunkFL2N3XHKcjs.b,functionName:"pythOracle"})}async function lr({publicClient:e,factory:t,...r}){let{config:o}=_chunk22J3YJDNcjs.a.call(void 0, r);return await e.readContract({address:_nullishCoalesce(t, () => (o.honey.factory)),abi:_chunkVP7XUOSIcjs.e,functionName:"priceOracle"})}var _chain = require('@berachain/graphql/chain');async function Ar({defaultBlockTime:e,blocksSpan:t,...r}={}){let{config:o}=_chunk22J3YJDNcjs.a.call(void 0, r),a=_chunkMUCEYO3Ecjs.c.call(void 0, "blocks.subgraph",r),n=_nullishCoalesce(e, () => (o.averageBlockTime)),p=_nullishCoalesce(t, () => (Math.floor(_chunkPKXAW6MOcjs.q.call(void 0, 1)/n))),s=(await a.query({query:_chain.GetBlocksTimeStamp,variables:{skip:p}})).data;return(_chunkPKXAW6MOcjs.l.call(void 0, Date.now())-Number(_optionalChain([s, 'optionalAccess', _5 => _5.oldest, 'access', _6 => _6[0], 'optionalAccess', _7 => _7.timestamp])))/(Number(_optionalChain([s, 'optionalAccess', _8 => _8.newest, 'access', _9 => _9[0], 'optionalAccess', _10 => _10.number]))-Number(_optionalChain([s, 'optionalAccess', _11 => _11.oldest, 'access', _12 => _12[0], 'optionalAccess', _13 => _13.number])))}async function kr({tokenList:e,publicClient:t,lstStakingVaults:r,...o}){_chunk7LNBSOVVcjs.c.call(void 0, t);let{config:a}=_chunk22J3YJDNcjs.a.call(void 0, {...o,chainId:_nullishCoalesce(_optionalChain([t, 'access', _14 => _14.chain, 'optionalAccess', _15 => _15.id]), () => (o.chainId))}),n=e.filter(i=>r.includes(i.address));return n.length===0?[]:(await Promise.all(n.map(async i=>({assetTokenAddress:await t.readContract({address:i.address,abi:_chunkFL2N3XHKcjs.d,functionName:"asset"}),stakingToken:i})))).reduce((i,{assetTokenAddress:s,stakingToken:d})=>{let c=e.find(g=>_chunk22J3YJDNcjs.e.call(void 0, g,s));return c&&i.push({id:d.address,receiptToken:d,inputTokens:[c]}),i},[])}var O=[{inputs:[{internalType:"address",name:"initialOwner",type:"address"},{internalType:"address",name:"initialImplementation",type:"address"}],stateMutability:"payable",type:"constructor"},{inputs:[],name:"NewImplementationHasNoCode",type:"error"},{inputs:[],name:"NewOwnerIsZeroAddress",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"oldOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{inputs:[],name:"implementation",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"}],name:"upgradeTo",outputs:[],stateMutability:"nonpayable",type:"function"}];async function W({publicClient:e,...t}){let{config:r}=_chunk22J3YJDNcjs.a.call(void 0, t),o=r.pol.factory;_chunk7LNBSOVVcjs.b.call(void 0, e,"publicClient"),_chunk7LNBSOVVcjs.d.call(void 0, r.pol.factory,"factoryAddress");let a=await e.readContract({address:o,abi:_chunkVP7XUOSIcjs.l,functionName:"beacon"});return await e.readContract({address:a,abi:O,functionName:"implementation"})}async function Or({publicClient:e,...t}){_chunk7LNBSOVVcjs.c.call(void 0, e);let r=await W({publicClient:e,...t}),[o,a]=await Promise.all([e.readContract({address:r,abi:_chunkVP7XUOSIcjs.k,functionName:"MIN_REWARD_DURATION"}),e.readContract({address:r,abi:_chunkVP7XUOSIcjs.k,functionName:"MAX_REWARD_DURATION"})]);return{minRewardDuration:Number(o),maxRewardDuration:Number(a)}}async function Hr({tokenAddress:e,publicClient:t,factoryAddress:r,...o}){let{config:a}=_chunk22J3YJDNcjs.a.call(void 0, o),n=await t.readContract({address:_nullishCoalesce(r, () => (a.pol.factory)),abi:_chunkVP7XUOSIcjs.l,functionName:"getVault",args:[e]});return n===_viem.zeroAddress?null:n}async function Lr({tokenList:e,publicClient:t,...r}){let{config:o}=_chunk22J3YJDNcjs.a.call(void 0, r);try{let a=await Promise.all(e.map(n=>t.readContract({address:o.honey.pythOracle,abi:_chunkFL2N3XHKcjs.c,functionName:"feeds",args:[n]})));return e.reduce((n,p,i)=>({...n,[p]:a[i]}),{})}catch(a){throw console.error("getPythPriceFeedId",a),a}}async function Xr({url:e,...t}={}){let{config:r}=_chunk22J3YJDNcjs.a.call(void 0, t);returnawait _asyncNullishCoalesce((await _chunkPKXAW6MOcjs.d.call(void 0, {url:_nullishCoalesce(e, () => (r.lists.tokenList)),type:"rest",name:"GitHub"})).tokens, async () => ([]))}async function eo({publicClient:e,ui:t,...r}){let{config:o}=_chunk22J3YJDNcjs.a.call(void 0, r),[a,n,p,i,s,d,c,g]=await Promise.all([e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"MAX_COMMISSION_RATE"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"commissionChangeDelay"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"rewardAllocationBlockDelay"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"maxWeightPerVault"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"maxNumWeightsPerRewardAllocation"}),e.readContract({address:o.tokens.bgt,abi:_chunkVP7XUOSIcjs.j,functionName:"dropBoostDelay"}),e.readContract({address:o.tokens.bgt,abi:_chunkVP7XUOSIcjs.j,functionName:"activateBoostDelay"}),e.readContract({address:o.pol.beraChef,abi:_chunkVP7XUOSIcjs.i,functionName:"rewardAllocationInactivityBlockSpan"})]);return{maxCommissionRate:Number(a)/1e4,boostDelay:Number(c),unboostDelay:Number(d),commissionChangeDelay:Number(n),rewardAllocationBlockDelay:Number(p),maxWeightPerVault:Number(i)/1e4,maxNumWeightsPerRewardAllocation:Number(s),rewardAllocationInactivityBlockSpan:Number(g),ui:t}}function ee(e){return _optionalChain([e, 'optionalAccess', _16 => _16.rewardAllocationWeights, 'optionalAccess', _17 => _17.reduce, 'call', _18 => _18((t,r)=>{if(!r)return t;let o=_nullishCoalesce(_optionalChain([r, 'access', _19 => _19.receivingVault, 'optionalAccess', _20 => _20.activeIncentives, 'access', _21 => _21.filter, 'call', _22 => _22(a=>Number(a.remainingAmount)>0), 'access', _23 => _23.reduce, 'call', _24 => _24((a,n)=>{let p=Number(n.remainingAmountUsd)/Number(n.remainingAmount);return a+Number(n.incentiveRate)*p},0)]), () => (0));return t+o*r.percentage},0)])}function ro({validator:e,bgtPrice:t}){let r=Number(_nullishCoalesce(_optionalChain([e, 'access', _25 => _25.dynamicData, 'optionalAccess', _26 => _26.activeBoostAmount]), () => (0))),o=ee(e);return!o||!r?0:o*Number(_nullishCoalesce(_optionalChain([e, 'access', _27 => _27.dynamicData, 'optionalAccess', _28 => _28.lastDayDistributedBGTAmount]), () => (0)))*365/(r*t)}exports.BalancerApi = _chunkMUCEYO3Ecjs.f; exports.BaseAggregator = _chunkMUCEYO3Ecjs.e; exports.BeraApolloClient = _chunkMUCEYO3Ecjs.b; exports.HoneyPreviewMethod = _chunkMUCEYO3Ecjs.E; exports.MOCKED_PROPOSAL_STATUSES = _chunkMUCEYO3Ecjs.p; exports.RewardVaultDistributionMode = _chunkMUCEYO3Ecjs.N; exports.beraWriteContract = _chunkMUCEYO3Ecjs.na; exports.checkProposalField = _chunkMUCEYO3Ecjs.o; exports.computeActualStatus = _chunkMUCEYO3Ecjs.q; exports.formatValidatorRewardAllocation = _chunkMUCEYO3Ecjs.sa; exports.getActiveBoostAndCommissionChangeDelay = eo; exports.getAllPools = _chunkMUCEYO3Ecjs.g; exports.getAllProposals = _chunkMUCEYO3Ecjs.r; exports.getAllValidators = _chunkMUCEYO3Ecjs.oa; exports.getAllowances = _chunkMUCEYO3Ecjs.la; exports.getApiEnrichedAllocation = _chunkMUCEYO3Ecjs.pa; exports.getApiPool = _chunkMUCEYO3Ecjs.h; exports.getApiValidator = _chunkMUCEYO3Ecjs.qa; exports.getApolloClient = _chunkMUCEYO3Ecjs.c; exports.getBalanceCall = _chunkFCWDGE62cjs.b; exports.getBgtAprSimulation = _chunkMUCEYO3Ecjs.P; exports.getBlockTime = Ar; exports.getBlockTimestamp = _chunkMUCEYO3Ecjs.M; exports.getBodyErrors = _chunkMUCEYO3Ecjs.s; exports.getChartData = _chunkMUCEYO3Ecjs.x; exports.getCollateralWeights = _chunkMUCEYO3Ecjs.y; exports.getConvertToAssets = _chunkMUCEYO3Ecjs.a; exports.getDailyValidatorBlockStats = _chunkMUCEYO3Ecjs.ra; exports.getDecodedFunctionData = Kt; exports.getDefaultRewardAllocation = _chunkMUCEYO3Ecjs.wa; exports.getEarnedStakedBeraVault = _chunkMUCEYO3Ecjs.Q; exports.getEnsoClient = _chunkFCWDGE62cjs.a; exports.getGlobalCapLimit = _chunkMUCEYO3Ecjs.C; exports.getGlobalData = _chunkMUCEYO3Ecjs.S; exports.getGlobalLiquidityAndSwapVolume = _chunkMUCEYO3Ecjs.i; exports.getHoneyCollaterals = _chunkMUCEYO3Ecjs.A; exports.getHoneyFees = rr; exports.getHoneyGlobalData = _chunkMUCEYO3Ecjs.D; exports.getHoneyPausedState = ir; exports.getHoneyPreview = _chunkMUCEYO3Ecjs.F; exports.getHoneyPythFeeds = Lr; exports.getHoneyPythOracle = pr; exports.getHoneyRootPriceOracle = lr; exports.getHoneyVaultsBalance = _chunkMUCEYO3Ecjs.G; exports.getIncentiveFeeClaimStats = _chunkMUCEYO3Ecjs.T; exports.getLSTStakeConfig = kr; exports.getManagedValidatorByAccount = _chunkMUCEYO3Ecjs.xa; exports.getMarkets = _chunkMUCEYO3Ecjs.U; exports.getMaxDeposit = Jt; exports.getOnChainPool = _chunkMUCEYO3Ecjs.k; exports.getPoolEvents = _chunkMUCEYO3Ecjs.l; exports.getPoolHistoricalData = _chunkMUCEYO3Ecjs.m; exports.getPoolPausedState = _chunkMUCEYO3Ecjs.j; exports.getPoolState = Ht; exports.getProposalDetails = _chunkMUCEYO3Ecjs.t; exports.getProposalFromTx = _chunkMUCEYO3Ecjs.v; exports.getProposalVotes = _chunkMUCEYO3Ecjs.w; exports.getPythLatestPrices = _chunkMUCEYO3Ecjs.H; exports.getPythUpdateFee = _chunkMUCEYO3Ecjs.J; exports.getRelativeCapLimit = _chunkMUCEYO3Ecjs.I; exports.getRewardProofsByValidator = _chunkMUCEYO3Ecjs.V; exports.getRewardTokenToBeraRate = _chunkMUCEYO3Ecjs.W; exports.getRewardVault = _chunkMUCEYO3Ecjs.X; exports.getRewardVaultDurationConstants = Or; exports.getRewardVaultFromToken = Hr; exports.getRewardVaultIncentives = _chunkMUCEYO3Ecjs.Y; exports.getRewardVaultRewards = _chunkMUCEYO3Ecjs.O; exports.getRewardVaultStakingToken = _chunkMUCEYO3Ecjs.Z; exports.getRewardVaults = _chunkMUCEYO3Ecjs.R; exports.getSWBeraVaultMetadata = _chunkMUCEYO3Ecjs.ba; exports.getSWBeraWithdrawal = _chunkMUCEYO3Ecjs.ca; exports.getStakeWithdrawalCooldown = _chunkMUCEYO3Ecjs.aa; exports.getStakedBeraAPR = _chunkMUCEYO3Ecjs._; exports.getStakedBeraSnapshots = _chunkMUCEYO3Ecjs.$; exports.getStakingPoolBatch = _chunkMUCEYO3Ecjs.ya; exports.getSubgraphPool = _chunkMUCEYO3Ecjs.n; exports.getSwapPayload = _chunkMUCEYO3Ecjs.K; exports.getTokenCurrentPrices = _chunkMUCEYO3Ecjs.ka; exports.getTokenInformation = _chunkMUCEYO3Ecjs.z; exports.getTokens = Xr; exports.getTotalStakedAmount = _chunkMUCEYO3Ecjs.da; exports.getUserActiveValidators = _chunkMUCEYO3Ecjs.Aa; exports.getUserBoostsOnValidator = _chunkMUCEYO3Ecjs.za; exports.getUserClaimableIncentives = _chunkMUCEYO3Ecjs.ea; exports.getUserStakingPositions = _chunkMUCEYO3Ecjs.Ba; exports.getUserVaultInfo = _chunkMUCEYO3Ecjs.ga; exports.getUserVaults = _chunkMUCEYO3Ecjs.ha; exports.getUserVaultsReward = _chunkMUCEYO3Ecjs.fa; exports.getValidatorAnalytics = _chunkMUCEYO3Ecjs.Ca; exports.getValidatorBoostApy = ro; exports.getValidatorCommission = _chunkMUCEYO3Ecjs.Da; exports.getValidatorEstimatedBgtPerYear = _chunkMUCEYO3Ecjs.Ea; exports.getValidatorOperatorAddress = _chunkMUCEYO3Ecjs.Fa; exports.getValidatorQueuedCommission = _chunkMUCEYO3Ecjs.Ga; exports.getValidatorQueuedOperatorAddress = _chunkMUCEYO3Ecjs.Ha; exports.getValidatorQueuedRewardAllocation = _chunkMUCEYO3Ecjs.Ia; exports.getValidatorReturnPerBgt = ee; exports.getValidatorRewardAllocation = _chunkMUCEYO3Ecjs.ua; exports.getVaultHistory = _chunkMUCEYO3Ecjs.ia; exports.getVaultPausedState = Lt; exports.getVaultValidators = _chunkMUCEYO3Ecjs.ja; exports.getWalletBalances = _chunkFCWDGE62cjs.c; exports.gql = _chunkMUCEYO3Ecjs.d; exports.isBadCollateralAsset = _chunkMUCEYO3Ecjs.B; exports.isBasketModeEnabled = _chunkMUCEYO3Ecjs.L; exports.isDefaultRewardAllocation = _chunkMUCEYO3Ecjs.va; exports.isImpersonateAccount = _chunkMUCEYO3Ecjs.ma; exports.isSameRewardAllocation = _chunkMUCEYO3Ecjs.ta; exports.parseProposalBody = _chunkMUCEYO3Ecjs.u;
|
|
2
2
|
//# sourceMappingURL=exports.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/
|
|
1
|
+
{"version":3,"sources":["/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/actions/exports.cjs","../../src/actions/bend/getMaxDeposit.ts","../../src/actions/dex/getPoolWithState.ts","../../src/actions/dex/getVaultPausedState.ts","../../src/actions/governance/getDecodedFunctionData.ts"],"names":["getMaxDeposit","vaultAddress","publicClient","maxDeposit","metaMorphoAbi","formatEther","getPoolState","apiPool","mapPoolType","pt","getVaultPausedState","args","config","parseBaseArgs","balancerVaultAbi","isProxyABI","abi","item","_getAbi","contractAddress","chainId","url","appConfig"],"mappings":"AAAA,+1BAA8D,yDAA2wB,yDAAoF,yDAA2D,iCAA8B,iCAA8B,iCAA8B,yDAAwD,yDAAwD,yDAAiD,iCAA8B,4BCAprC,MAS7D,SAAsBA,EAAAA,CAAc,CAClC,YAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CAAwC,CACtC,IAAMC,CAAAA,CAAa,MAAMD,CAAAA,CAAa,YAAA,CAAa,CACjD,OAAA,CAASD,CAAAA,CACT,GAAA,CAAKG,mBAAAA,CACL,YAAA,CAAc,YAAA,CACd,IAAA,CAAM,CAACH,CAAY,CACrB,CAAC,CAAA,CACD,OAAOI,+BAAAA,CAAsB,CAC/B,CCpBA,iEAIO,IAKMC,EAAAA,CAAgBC,CAAAA,EAAAA,CACpB,CACL,IAAA,CAAMC,sCAAAA,CAAYD,CAAQ,IAAI,CAAA,CAC9B,eAAA,CAAiBA,CAAAA,CAAQ,eAAA,CACzB,MAAA,CAAQA,CAAAA,CAAQ,MAAA,CAAO,GAAA,CACpBE,CAAAA,EAAAA,CACE,CACC,GAAGA,CAAAA,CACH,OAAA,CAASA,CAAAA,CAAG,OACd,CAAA,CACJ,CAAA,CACA,EAAA,CAAIF,CAAAA,CAAQ,EAAA,CACZ,OAAA,CAASA,CAAAA,CAAQ,OACnB,CAAA,CAAA,CCjBF,MAAA,SAAsBG,EAAAA,CAAoB,CACxC,YAAA,CAAAR,CAAAA,CACA,GAAGS,CACL,CAAA,CAEG,CACD,GAAM,CAAE,MAAA,CAAAC,CAAO,CAAA,CAAIC,iCAAAA,CAAkB,CAAA,CAQrC,MAAA,CANyB,MAAMX,CAAAA,CAAa,YAAA,CAAa,CACvD,OAAA,CAASU,CAAAA,CAAO,GAAA,CAAI,KAAA,CACpB,GAAA,CAAKE,mBAAAA,CACL,YAAA,CAAc,gBAChB,CAAC,CAAA,CAAA,CAEuB,CAAC,CAC3B,CCpBA,sDAa0C,SAMjCC,CAAAA,CAAWC,CAAAA,CAAqB,CACvC,OAAOA,CAAAA,CAAI,IAAA,CACRC,CAAAA,EACCA,CAAAA,CAAK,IAAA,GAAS,gBAAA,EACdA,CAAAA,CAAK,IAAA,GAAS,WAAA,EACbA,CAAAA,CAAK,IAAA,GAAS,aAAA,kBACbA,CAAAA,qBAAK,MAAA,4BAAA,CAAS,CAAC,CAAA,6BAAG,MAAA,GAAS,gBACjC,CACF,CAKA,MAAA,SAAeC,CAAAA,CAAQ,CACrB,eAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,YAAA,CAAAlB,CACF,CAAA,CAIG,CACD,IAAMmB,CAAAA,CAAM,CAAA,sEAAA,EAAyEF,CAAe,CAAA,QAAA,EAAWG,mBAAAA,CAAU,OAAA,CAAQ,OAAA,CAAQ,SAAS,CAAA,SAAA,EAAYF,CAAO,CAAA,CAAA","file":"/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/actions/exports.cjs","sourcesContent":[null,"import { type Address, formatEther, type PublicClient } from \"viem\";\n\nimport { metaMorphoAbi } from \"~/abi/bend/metaMorpho\";\n\ninterface GetMaxDepositProps {\n vaultAddress: Address;\n publicClient: PublicClient;\n}\n\nexport async function getMaxDeposit({\n vaultAddress,\n publicClient,\n}: GetMaxDepositProps): Promise<string> {\n const maxDeposit = await publicClient.readContract({\n address: vaultAddress,\n abi: metaMorphoAbi,\n functionName: \"maxDeposit\",\n args: [vaultAddress],\n });\n return formatEther(maxDeposit);\n}\n","import {\n type MinimalToken,\n mapPoolType,\n type PoolState,\n} from \"@berachain-foundation/berancer-sdk\";\nimport type { Address } from \"viem\";\n\nimport type { MinimalPoolFragment } from \"@berachain/graphql/dex/api\";\n\nexport const getPoolState = (apiPool: MinimalPoolFragment): PoolState => {\n return {\n type: mapPoolType(apiPool.type),\n protocolVersion: apiPool.protocolVersion as 1 | 2 | 3,\n tokens: apiPool.tokens.map<MinimalToken>(\n (pt) =>\n ({\n ...pt,\n address: pt.address as Address,\n }) satisfies MinimalToken,\n ),\n id: apiPool.id as Address,\n address: apiPool.address as Address,\n } satisfies PoolState;\n};\n","import type { PublicClient } from \"viem\";\n\nimport { balancerVaultAbi } from \"~/abi/bex/balancerVault\";\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\nexport async function getVaultPausedState({\n publicClient,\n ...args\n}: BeraJS.BaseFunctionArgs & {\n publicClient: PublicClient;\n}) {\n const { config } = parseBaseArgs(args);\n\n const vaultPausedState = await publicClient.readContract({\n address: config.bex.vault,\n abi: balancerVaultAbi,\n functionName: \"getPausedState\",\n });\n\n return vaultPausedState[0];\n}\n","import {\n type Abi,\n type AbiFunction,\n type AbiItem,\n type Address,\n decodeFunctionData,\n erc20Abi,\n type PublicClient,\n pad,\n toFunctionSignature,\n trim,\n} from \"viem\";\n\nimport { appConfig, defaultChainId } from \"@berachain/config/internal\";\n\nimport { beraChefAbi } from \"~/abi/pol/beraChef\";\nimport { rewardVaultAbi } from \"~/abi/pol/rewardVault\";\n\n// Function to check if ABI contains proxy-related functions\nfunction isProxyABI(abi: Abi[]): boolean {\n return abi.some(\n (item: any) =>\n item.name === \"implementation\" ||\n item.name === \"proxyType\" ||\n (item.type === \"constructor\" &&\n item.inputs?.[0]?.name === \"implementation\"),\n );\n}\n\n/**\n * {@link https://docs.berascan.com/api-endpoints/contracts}\n */\nasync function _getAbi({\n contractAddress,\n chainId,\n publicClient,\n}: {\n contractAddress: Address;\n chainId: number;\n publicClient: PublicClient;\n}) {\n const url = `https://api.etherscan.io/v2/api?module=contract&action=getabi&address=${contractAddress}&apikey=${appConfig.apiKeys.private.etherscan}&chainId=${chainId}`;\n\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch ABI: ${response.statusText}`);\n }\n\n const data = await response.json();\n if (data.status === \"0\") throw new Error(data.result);\n\n const abi = JSON.parse(data.result);\n if (!isProxyABI(abi)) return abi;\n\n const implementationResult = await publicClient.getStorageAt({\n address: contractAddress,\n // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)).\n slot: \"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc\",\n });\n\n // if implementation is not set, it might be a beacon proxy\n if (!implementationResult || trim(implementationResult) === \"0x00\")\n return abi;\n // storage slot has 32 byes (64 characters) but an address only has 20 bytes (40 characters)\n const implementationAddress = pad(trim(implementationResult), { size: 20 });\n return _getAbi({\n contractAddress: implementationAddress as `0x${string}`,\n chainId,\n publicClient,\n });\n}\n\nasync function _getAbiForCallData({\n address,\n callData,\n knownAbi,\n chainId,\n publicClient,\n}: {\n address: Address;\n callData: `0x${string}`;\n knownAbi: AbiItem[];\n chainId: number;\n publicClient: PublicClient;\n}) {\n try {\n if (decodeFunctionData({ data: callData, abi: knownAbi })) {\n return knownAbi;\n }\n } catch {}\n try {\n return await _getAbi({ contractAddress: address, chainId, publicClient });\n } catch {}\n}\n\nfunction _decodeCallData(callData: `0x${string}`, abi: AbiItem[]) {\n try {\n return decodeFunctionData({ data: callData, abi });\n } catch {\n return undefined;\n }\n}\n\nfunction _findAbiItem(abi: AbiItem[], functionName: string) {\n return abi.find(\n (a: AbiItem) => a.type === \"function\" && a.name === functionName,\n ) as AbiFunction | undefined;\n}\n\nfunction _getFunctionSignature(abiItem: AbiFunction | undefined) {\n if (!abiItem) return;\n try {\n return toFunctionSignature(abiItem);\n } catch (error) {\n console.error(error);\n }\n}\n\n/**\n * Decodes the function data from a given contract address and calldata.\n *\n * This function attempts to decode the provided calldata using a known set of ABIs.\n * If the call data cannot be decoded with the known ABIs, it fetches the ABI from the blockexplorer API.\n *\n * @param address - The contract address.\n * @param callData - The calldata to decode, in hexadecimal format.\n * @returns An object containing the decoded ABI item, function signature, function name, and arguments.\n */\nexport async function getDecodedFunctionData({\n address,\n callData,\n chainId = defaultChainId,\n publicClient,\n}: {\n address: Address;\n callData: `0x${string}`;\n chainId?: number;\n publicClient: PublicClient;\n}) {\n const knownAbi = [...beraChefAbi, ...rewardVaultAbi, ...erc20Abi];\n\n const abi = await _getAbiForCallData({\n address,\n callData,\n knownAbi,\n chainId,\n publicClient,\n });\n\n const decodedData = _decodeCallData(callData, abi);\n\n if (!abi || !decodedData) {\n return { args: [] };\n }\n\n const abiItem = _findAbiItem(abi, decodedData.functionName);\n\n const functionSignature = _getFunctionSignature(abiItem);\n\n return {\n abiItem,\n functionSignature,\n functionName: decodedData.functionName,\n args: decodedData.args as unknown[],\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { V as ValidatorRewardAllocation } from '../getValidatorQueuedOperatorAddress-
|
|
2
|
-
export { B as BaseAggregator, f as GetBgtAprSimulationArgs, h as GetBgtAprSimulationResult, G as GetConvertToAssetsProps, s as GetGaugeData, c as GetHoneyVaultsBalanceResponse, m as GetMarkets, q as GetRewardVaultRewardsReturn, x as GetUserVaultsResponse, z as GetVaultHistoryArgs, k as GlobalData, I as IsBadCollateralArgs, e as IsBadCollateralResponse, O as OnChainPool, P as PoolStatus, p as RewardVaultDistributionMode, R as RewardVaultIncentive, S as StakedBeraWithdrawal, E as UserBoostsOnValidator, H as UserStakingPoolPosition, U as UserVault, K as ValidatorQueuedCommission, M as ValidatorQueuedOperatorAddress, Q as ValidatorRewardAllocationRaw, T as ValidatorRewardAllocationUpdate, W as ValidatorRewardAllocationUpdateWithExpiration, C as ValidatorWithUserBoost, u as VaultMetadata, X as formatValidatorRewardAllocation, j as getBgtAprSimulation, g as getConvertToAssets, l as getGlobalData, d as getHoneyVaultsBalance, n as getMarkets, a as getOnChainPool, b as getPoolPausedState, o as getRewardVaultIncentives, r as getRewardVaultRewards, t as getRewardVaults, v as getSWBeraVaultMetadata, w as getSWBeraWithdrawal, D as getUserActiveValidators, F as getUserBoostsOnValidator, J as getUserStakingPositions, y as getUserVaults, L as getValidatorQueuedCommission, N as getValidatorQueuedOperatorAddress, Z as getValidatorRewardAllocation, A as getVaultHistory, i as isBadCollateralAsset, Y as isSameRewardAllocation } from '../getValidatorQueuedOperatorAddress-
|
|
1
|
+
import { V as ValidatorRewardAllocation } from '../getValidatorQueuedOperatorAddress-Dstyaomr.cjs';
|
|
2
|
+
export { B as BaseAggregator, f as GetBgtAprSimulationArgs, h as GetBgtAprSimulationResult, G as GetConvertToAssetsProps, s as GetGaugeData, c as GetHoneyVaultsBalanceResponse, m as GetMarkets, q as GetRewardVaultRewardsReturn, x as GetUserVaultsResponse, z as GetVaultHistoryArgs, k as GlobalData, I as IsBadCollateralArgs, e as IsBadCollateralResponse, O as OnChainPool, P as PoolStatus, p as RewardVaultDistributionMode, R as RewardVaultIncentive, S as StakedBeraWithdrawal, E as UserBoostsOnValidator, H as UserStakingPoolPosition, U as UserVault, K as ValidatorQueuedCommission, M as ValidatorQueuedOperatorAddress, Q as ValidatorRewardAllocationRaw, T as ValidatorRewardAllocationUpdate, W as ValidatorRewardAllocationUpdateWithExpiration, C as ValidatorWithUserBoost, u as VaultMetadata, X as formatValidatorRewardAllocation, j as getBgtAprSimulation, g as getConvertToAssets, l as getGlobalData, d as getHoneyVaultsBalance, n as getMarkets, a as getOnChainPool, b as getPoolPausedState, o as getRewardVaultIncentives, r as getRewardVaultRewards, t as getRewardVaults, v as getSWBeraVaultMetadata, w as getSWBeraWithdrawal, D as getUserActiveValidators, F as getUserBoostsOnValidator, J as getUserStakingPositions, y as getUserVaults, L as getValidatorQueuedCommission, N as getValidatorQueuedOperatorAddress, Z as getValidatorRewardAllocation, A as getVaultHistory, i as isBadCollateralAsset, Y as isSameRewardAllocation } from '../getValidatorQueuedOperatorAddress-Dstyaomr.cjs';
|
|
3
3
|
import { Address, PublicClient, AbiParameter, AbiFunction, TransactionReceipt, Abi, ContractFunctionArgs, ContractFunctionName, WalletCallReceipt } from 'viem';
|
|
4
4
|
import { ApolloClient, OperationVariables, FetchPolicy } from '@apollo/client';
|
|
5
5
|
export { gql } from '@apollo/client';
|
|
@@ -9,9 +9,9 @@ export { BalancerApi } from '@berachain-foundation/berancer-sdk';
|
|
|
9
9
|
import * as _berachain_graphql_dex_api from '@berachain/graphql/dex/api';
|
|
10
10
|
import { GetPoolsQueryVariables, GetGlobalLiquidityAndSwapVolumeQuery, GetPoolEventsQuery, GqlChain, PoolHistoricalDataFragment, MinimalPoolFragment } from '@berachain/graphql/dex/api';
|
|
11
11
|
import { GqlPoolEventType, GqlChain as GqlChain$1, ApiVaultFragment, GqlVaultSnapshotDataRange, GetSWberaVaultSnapshotsQuery, ApiValidatorFragment, GetValidatorsQueryVariables, GetValidatorsQuery, ApiRewardAllocationWeightFragment, GetValidatorQuery, ApiValidatorMinimalFragment } from '@berachain/graphql/pol/api';
|
|
12
|
-
import { a as ProposalErrorCodes, P as ProposalState } from '../
|
|
12
|
+
import { a as ProposalErrorCodes, P as ProposalState } from '../txnEnum-BlBYhNRl.cjs';
|
|
13
13
|
import { ProposalStatus, ProposalSelectionFragment, Proposal_Filter, Proposal_OrderBy, OrderDirection, ProposalWithVotesFragment, GetProposalVotesQueryVariables, GetProposalVotesQuery } from '@berachain/graphql/governance';
|
|
14
|
-
import { C as CustomProposal, G as GovernanceTopic, a as CustomProposalErrors, S as StakingConfig, B as BribeBoostRewardProof, b as BribeBoostRewardItem, U as UserVaultInfo, I as IContractWrite } from '../global.d-
|
|
14
|
+
import { C as CustomProposal, G as GovernanceTopic, a as CustomProposalErrors, S as StakingConfig, B as BribeBoostRewardProof, b as BribeBoostRewardItem, U as UserVaultInfo, I as IContractWrite } from '../global.d-CN6l2b9E.cjs';
|
|
15
15
|
import graymatter from 'gray-matter';
|
|
16
16
|
import { GetChartDataQuery, GetGlobalDataQuery } from '@berachain/graphql/honey';
|
|
17
17
|
import { b as Token, P as PythLatestUpdates, a as TokenWithMetadata, T as TokenWithOrder, h as PythPriceFeedMap, i as TokenCurrentPriceMap, A as AllowanceQueryItem, j as AllowanceToken, M as MinimalERC20, B as BalanceToken } from '../HoneyConfigProvider-Ca3ouozs.cjs';
|
|
@@ -25,7 +25,6 @@ import { GetValidatorBlockStatsQuery, GetValidatorByAccountQuery, GetValidatorAn
|
|
|
25
25
|
import '@berachain/config/internal';
|
|
26
26
|
import '../dex-C_BB0b0O.cjs';
|
|
27
27
|
import 'swr';
|
|
28
|
-
import '../txnEnum-BYNbCxla.cjs';
|
|
29
28
|
import '../BeraError-_mQdkanr.cjs';
|
|
30
29
|
import 'react/jsx-runtime';
|
|
31
30
|
import 'react';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { V as ValidatorRewardAllocation } from '../getValidatorQueuedOperatorAddress-
|
|
2
|
-
export { B as BaseAggregator, f as GetBgtAprSimulationArgs, h as GetBgtAprSimulationResult, G as GetConvertToAssetsProps, s as GetGaugeData, c as GetHoneyVaultsBalanceResponse, m as GetMarkets, q as GetRewardVaultRewardsReturn, x as GetUserVaultsResponse, z as GetVaultHistoryArgs, k as GlobalData, I as IsBadCollateralArgs, e as IsBadCollateralResponse, O as OnChainPool, P as PoolStatus, p as RewardVaultDistributionMode, R as RewardVaultIncentive, S as StakedBeraWithdrawal, E as UserBoostsOnValidator, H as UserStakingPoolPosition, U as UserVault, K as ValidatorQueuedCommission, M as ValidatorQueuedOperatorAddress, Q as ValidatorRewardAllocationRaw, T as ValidatorRewardAllocationUpdate, W as ValidatorRewardAllocationUpdateWithExpiration, C as ValidatorWithUserBoost, u as VaultMetadata, X as formatValidatorRewardAllocation, j as getBgtAprSimulation, g as getConvertToAssets, l as getGlobalData, d as getHoneyVaultsBalance, n as getMarkets, a as getOnChainPool, b as getPoolPausedState, o as getRewardVaultIncentives, r as getRewardVaultRewards, t as getRewardVaults, v as getSWBeraVaultMetadata, w as getSWBeraWithdrawal, D as getUserActiveValidators, F as getUserBoostsOnValidator, J as getUserStakingPositions, y as getUserVaults, L as getValidatorQueuedCommission, N as getValidatorQueuedOperatorAddress, Z as getValidatorRewardAllocation, A as getVaultHistory, i as isBadCollateralAsset, Y as isSameRewardAllocation } from '../getValidatorQueuedOperatorAddress-
|
|
1
|
+
import { V as ValidatorRewardAllocation } from '../getValidatorQueuedOperatorAddress-RW4OMcD1.js';
|
|
2
|
+
export { B as BaseAggregator, f as GetBgtAprSimulationArgs, h as GetBgtAprSimulationResult, G as GetConvertToAssetsProps, s as GetGaugeData, c as GetHoneyVaultsBalanceResponse, m as GetMarkets, q as GetRewardVaultRewardsReturn, x as GetUserVaultsResponse, z as GetVaultHistoryArgs, k as GlobalData, I as IsBadCollateralArgs, e as IsBadCollateralResponse, O as OnChainPool, P as PoolStatus, p as RewardVaultDistributionMode, R as RewardVaultIncentive, S as StakedBeraWithdrawal, E as UserBoostsOnValidator, H as UserStakingPoolPosition, U as UserVault, K as ValidatorQueuedCommission, M as ValidatorQueuedOperatorAddress, Q as ValidatorRewardAllocationRaw, T as ValidatorRewardAllocationUpdate, W as ValidatorRewardAllocationUpdateWithExpiration, C as ValidatorWithUserBoost, u as VaultMetadata, X as formatValidatorRewardAllocation, j as getBgtAprSimulation, g as getConvertToAssets, l as getGlobalData, d as getHoneyVaultsBalance, n as getMarkets, a as getOnChainPool, b as getPoolPausedState, o as getRewardVaultIncentives, r as getRewardVaultRewards, t as getRewardVaults, v as getSWBeraVaultMetadata, w as getSWBeraWithdrawal, D as getUserActiveValidators, F as getUserBoostsOnValidator, J as getUserStakingPositions, y as getUserVaults, L as getValidatorQueuedCommission, N as getValidatorQueuedOperatorAddress, Z as getValidatorRewardAllocation, A as getVaultHistory, i as isBadCollateralAsset, Y as isSameRewardAllocation } from '../getValidatorQueuedOperatorAddress-RW4OMcD1.js';
|
|
3
3
|
import { Address, PublicClient, AbiParameter, AbiFunction, TransactionReceipt, Abi, ContractFunctionArgs, ContractFunctionName, WalletCallReceipt } from 'viem';
|
|
4
4
|
import { ApolloClient, OperationVariables, FetchPolicy } from '@apollo/client';
|
|
5
5
|
export { gql } from '@apollo/client';
|
|
@@ -9,9 +9,9 @@ export { BalancerApi } from '@berachain-foundation/berancer-sdk';
|
|
|
9
9
|
import * as _berachain_graphql_dex_api from '@berachain/graphql/dex/api';
|
|
10
10
|
import { GetPoolsQueryVariables, GetGlobalLiquidityAndSwapVolumeQuery, GetPoolEventsQuery, GqlChain, PoolHistoricalDataFragment, MinimalPoolFragment } from '@berachain/graphql/dex/api';
|
|
11
11
|
import { GqlPoolEventType, GqlChain as GqlChain$1, ApiVaultFragment, GqlVaultSnapshotDataRange, GetSWberaVaultSnapshotsQuery, ApiValidatorFragment, GetValidatorsQueryVariables, GetValidatorsQuery, ApiRewardAllocationWeightFragment, GetValidatorQuery, ApiValidatorMinimalFragment } from '@berachain/graphql/pol/api';
|
|
12
|
-
import { a as ProposalErrorCodes, P as ProposalState } from '../
|
|
12
|
+
import { a as ProposalErrorCodes, P as ProposalState } from '../txnEnum-BlBYhNRl.js';
|
|
13
13
|
import { ProposalStatus, ProposalSelectionFragment, Proposal_Filter, Proposal_OrderBy, OrderDirection, ProposalWithVotesFragment, GetProposalVotesQueryVariables, GetProposalVotesQuery } from '@berachain/graphql/governance';
|
|
14
|
-
import { C as CustomProposal, G as GovernanceTopic, a as CustomProposalErrors, S as StakingConfig, B as BribeBoostRewardProof, b as BribeBoostRewardItem, U as UserVaultInfo, I as IContractWrite } from '../global.d-
|
|
14
|
+
import { C as CustomProposal, G as GovernanceTopic, a as CustomProposalErrors, S as StakingConfig, B as BribeBoostRewardProof, b as BribeBoostRewardItem, U as UserVaultInfo, I as IContractWrite } from '../global.d-wYu8G8IQ.js';
|
|
15
15
|
import graymatter from 'gray-matter';
|
|
16
16
|
import { GetChartDataQuery, GetGlobalDataQuery } from '@berachain/graphql/honey';
|
|
17
17
|
import { b as Token, P as PythLatestUpdates, a as TokenWithMetadata, T as TokenWithOrder, h as PythPriceFeedMap, i as TokenCurrentPriceMap, A as AllowanceQueryItem, j as AllowanceToken, M as MinimalERC20, B as BalanceToken } from '../HoneyConfigProvider-CK6mOKFH.js';
|
|
@@ -25,7 +25,6 @@ import { GetValidatorBlockStatsQuery, GetValidatorByAccountQuery, GetValidatorAn
|
|
|
25
25
|
import '@berachain/config/internal';
|
|
26
26
|
import '../dex-C_BB0b0O.js';
|
|
27
27
|
import 'swr';
|
|
28
|
-
import '../txnEnum-BYNbCxla.js';
|
|
29
28
|
import '../BeraError-_mQdkanr.js';
|
|
30
29
|
import 'react/jsx-runtime';
|
|
31
30
|
import 'react';
|
package/dist/actions/exports.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as w,b as B,c as k,d as N}from"../chunk-F4BKSBEM.mjs";import{$ as Ze,A as ke,Aa as St,B as Ne,Ba as Dt,C as Se,Ca as Ft,D as De,Da as Tt,E as Fe,Ea as Rt,F as Te,Fa as vt,G as Re,Ga as It,H as ve,Ha as Mt,I as Ie,Ia as Vt,J as Me,K as Ve,L as Oe,M as We,N as Je,O as Ge,P as _e,Q as He,R as Ee,S as $e,T as qe,U as Le,V as Ue,W as Qe,X as ze,Y as Xe,Z as je,_ as Ke,a as te,aa as Ye,b as J,ba as et,c as h,ca as tt,d as G,da as rt,e as oe,ea as ot,f as ae,fa as at,g as ne,ga as nt,h as ie,ha as it,i as se,ia as st,j as me,ja as mt,k as pe,ka as pt,l as de,la as dt,m as ce,ma as lt,n as ue,na as ft,o as le,oa as yt,p as fe,pa as bt,q as ye,qa as xt,r as be,ra as gt,s as xe,sa as At,t as ge,ta as ht,u as Ae,ua as Ct,v as he,va as Pt,w as Ce,wa as wt,x as Pe,xa as Bt,y as we,ya as kt,z as Be,za as Nt}from"../chunk-G6NA6NSM.mjs";import{a as C,b as P,e as l,i as u,j as A,k as f,l as y}from"../chunk-Q3SCM6WL.mjs";import{a as re,b as ct,c as ut}from"../chunk-ZQRACIGR.mjs";import"../chunk-NAXAZJJY.mjs";import"../chunk-OGJMSGB2.mjs";import"../chunk-7GWTHOLO.mjs";import{b as F,c as b,d as T}from"../chunk-MTS5SZLA.mjs";import{c as S,k as R,p as v}from"../chunk-TJWKS54T.mjs";import{a as m,e as D}from"../chunk-YQGZMWDT.mjs";import"../chunk-C3G5KXCH.mjs";import{formatEther as _}from"viem";async function Jt({vaultAddress:e,publicClient:t}){let r=await t.readContract({address:e,abi:C,functionName:"maxDeposit",args:[e]});return _(r)}import{mapPoolType as H}from"@berachain-foundation/berancer-sdk";var Ht=e=>({type:H(e.type),protocolVersion:e.protocolVersion,tokens:e.tokens.map(t=>({...t,address:t.address})),id:e.id,address:e.address});async function Lt({publicClient:e,...t}){let{config:r}=m(t);return(await e.readContract({address:r.bex.vault,abi:P,functionName:"getPausedState"}))[0]}import{decodeFunctionData as M,erc20Abi as E,pad as $,toFunctionSignature as q,trim as I}from"viem";import{appConfig as L,defaultChainId as U}from"@berachain/config/internal";function Q(e){return e.some(t=>t.name==="implementation"||t.name==="proxyType"||t.type==="constructor"&&t.inputs?.[0]?.name==="implementation")}async function V({contractAddress:e,chainId:t,publicClient:r}){let o=`https://api.etherscan.io/v2/api?module=contract&action=getabi&address=${e}&apikey=${L.apiKeys.private.etherscan}&chainId=${t}`,a=await fetch(o);if(!a.ok)throw new Error(`Failed to fetch ABI: ${a.statusText}`);let n=await a.json();if(n.status==="0")throw new Error(n.result);let p=JSON.parse(n.result);if(!Q(p))return p;let i=await r.getStorageAt({address:e,slot:"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"});if(!i||I(i)==="0x00")return p;let s=$(I(i),{size:20});return V({contractAddress:s,chainId:t,publicClient:r})}async function z({address:e,callData:t,knownAbi:r,chainId:o,publicClient:a}){try{if(M({data:t,abi:r}))return r}catch{}try{return await V({contractAddress:e,chainId:o,publicClient:a})}catch{}}function X(e,t){try{return M({data:e,abi:t})}catch{return}}function j(e,t){return e.find(r=>r.type==="function"&&r.name===t)}function K(e){if(e)try{return q(e)}catch(t){console.error(t)}}async function Kt({address:e,callData:t,chainId:r=U,publicClient:o}){let a=[...u,...f,...E],n=await z({address:e,callData:t,knownAbi:a,chainId:r,publicClient:o}),p=X(t,n);if(!n||!p)return{args:[]};let i=j(n,p.functionName),s=K(i);return{abiItem:i,functionSignature:s,functionName:p.functionName,args:p.args}}import{formatUnits as x}from"viem";async function rr({client:e,collateralList:t,...r}){let{config:o}=m(r);try{let a={mint:[],redeem:[]};for(let s of t)a.mint.push(e.readContract({address:o.honey.factory,abi:l,functionName:"mintRates",args:[s.address]})),a.redeem.push(e.readContract({address:o.honey.factory,abi:l,functionName:"redeemRates",args:[s.address]}));let[n,p,i]=await Promise.all([Promise.all(a.mint),Promise.all(a.redeem),e.readContract({address:o.honey.factory,abi:l,functionName:"getWeights"})]);return t.reduce((s,d)=>{let c=t.indexOf(d);return s.single[d.address]={mintFee:1-+x(n[c],18),redeemFee:1-+x(p[c],18)},s.basket.mintFee+=s.single[d.address].mintFee*+x(i[c],18),s.basket.redeemFee+=s.single[d.address].redeemFee*+x(i[c],18),s},{single:{},basket:{mintFee:0,redeemFee:0}})}catch(a){throw console.log(a),a}}async function ir({client:e,...t}){let{config:r}=m(t),o=r.honey.token;return await e.readContract({address:o,abi:w,functionName:"paused"})}async function pr({pythOracle:e,publicClient:t}){return await t.readContract({address:e,abi:B,functionName:"pythOracle"})}async function lr({publicClient:e,factory:t,...r}){let{config:o}=m(r);return await e.readContract({address:t??o.honey.factory,abi:l,functionName:"priceOracle"})}import{GetBlocksTimeStamp as Z}from"@berachain/graphql/chain";async function Ar({defaultBlockTime:e,blocksSpan:t,...r}={}){let{config:o}=m(r),a=h("blocks.subgraph",r),n=e??o.averageBlockTime,p=t??Math.floor(v(1)/n),s=(await a.query({query:Z,variables:{skip:p}})).data;return(R(Date.now())-Number(s?.oldest[0]?.timestamp))/(Number(s?.newest[0]?.number)-Number(s?.oldest[0]?.number))}async function kr({tokenList:e,publicClient:t,lstStakingVaults:r,...o}){b(t);let{config:a}=m({...o,chainId:t.chain?.id??o.chainId}),n=e.filter(i=>r.includes(i.address));return n.length===0?[]:(await Promise.all(n.map(async i=>({assetTokenAddress:await t.readContract({address:i.address,abi:N,functionName:"asset"}),stakingToken:i})))).reduce((i,{assetTokenAddress:s,stakingToken:d})=>{let c=e.find(g=>D(g,s));return c&&i.push({id:d.address,receiptToken:d,inputTokens:[c]}),i},[])}var O=[{inputs:[{internalType:"address",name:"initialOwner",type:"address"},{internalType:"address",name:"initialImplementation",type:"address"}],stateMutability:"payable",type:"constructor"},{inputs:[],name:"NewImplementationHasNoCode",type:"error"},{inputs:[],name:"NewOwnerIsZeroAddress",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"oldOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{inputs:[],name:"implementation",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"}],name:"upgradeTo",outputs:[],stateMutability:"nonpayable",type:"function"}];async function W({publicClient:e,...t}){let{config:r}=m(t),o=r.pol.factory;F(e,"publicClient"),T(r.pol.factory,"factoryAddress");let a=await e.readContract({address:o,abi:y,functionName:"beacon"});return await e.readContract({address:a,abi:O,functionName:"implementation"})}async function Or({publicClient:e,...t}){b(e);let r=await W({publicClient:e,...t}),[o,a]=await Promise.all([e.readContract({address:r,abi:f,functionName:"MIN_REWARD_DURATION"}),e.readContract({address:r,abi:f,functionName:"MAX_REWARD_DURATION"})]);return{minRewardDuration:Number(o),maxRewardDuration:Number(a)}}import{zeroAddress as Y}from"viem";async function Hr({tokenAddress:e,publicClient:t,factoryAddress:r,...o}){let{config:a}=m(o),n=await t.readContract({address:r??a.pol.factory,abi:y,functionName:"getVault",args:[e]});return n===Y?null:n}async function Lr({tokenList:e,publicClient:t,...r}){let{config:o}=m(r);try{let a=await Promise.all(e.map(n=>t.readContract({address:o.honey.pythOracle,abi:k,functionName:"feeds",args:[n]})));return e.reduce((n,p,i)=>({...n,[p]:a[i]}),{})}catch(a){throw console.error("getPythPriceFeedId",a),a}}async function Xr({url:e,...t}={}){let{config:r}=m(t);return(await S({url:e??r.lists.tokenList,type:"rest",name:"GitHub"})).tokens??[]}async function eo({publicClient:e,ui:t,...r}){let{config:o}=m(r),[a,n,p,i,s,d,c,g]=await Promise.all([e.readContract({address:o.pol.beraChef,abi:u,functionName:"MAX_COMMISSION_RATE"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"commissionChangeDelay"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"rewardAllocationBlockDelay"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"maxWeightPerVault"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"maxNumWeightsPerRewardAllocation"}),e.readContract({address:o.tokens.bgt,abi:A,functionName:"dropBoostDelay"}),e.readContract({address:o.tokens.bgt,abi:A,functionName:"activateBoostDelay"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"rewardAllocationInactivityBlockSpan"})]);return{maxCommissionRate:Number(a)/1e4,boostDelay:Number(c),unboostDelay:Number(d),commissionChangeDelay:Number(n),rewardAllocationBlockDelay:Number(p),maxWeightPerVault:Number(i)/1e4,maxNumWeightsPerRewardAllocation:Number(s),rewardAllocationInactivityBlockSpan:Number(g),ui:t}}function ee(e){return e?.rewardAllocationWeights?.reduce((t,r)=>{if(!r)return t;let o=r.receivingVault?.activeIncentives.filter(a=>Number(a.remainingAmount)>0).reduce((a,n)=>{let p=Number(n.remainingAmountUsd)/Number(n.remainingAmount);return a+Number(n.incentiveRate)*p},0)??0;return t+o*r.percentage},0)}function ro({validator:e,bgtPrice:t}){let r=Number(e.dynamicData?.activeBoostAmount??0),o=ee(e);return!o||!r?0:o*Number(e.dynamicData?.lastDayDistributedBGTAmount??0)*365/(r*t)}export{ae as BalancerApi,oe as BaseAggregator,J as BeraApolloClient,Fe as HoneyPreviewMethod,fe as MOCKED_PROPOSAL_STATUSES,Je as RewardVaultDistributionMode,ft as beraWriteContract,le as checkProposalField,ye as computeActualStatus,At as formatValidatorRewardAllocation,eo as getActiveBoostAndCommissionChangeDelay,ne as getAllPools,be as getAllProposals,yt as getAllValidators,dt as getAllowances,bt as getApiEnrichedAllocation,ie as getApiPool,xt as getApiValidator,h as getApolloClient,ct as getBalanceCall,_e as getBgtAprSimulation,Ar as getBlockTime,We as getBlockTimestamp,xe as getBodyErrors,Pe as getChartData,we as getCollateralWeights,te as getConvertToAssets,gt as getDailyValidatorBlockStats,Kt as getDecodedFunctionData,wt as getDefaultRewardAllocation,He as getEarnedStakedBeraVault,re as getEnsoClient,Se as getGlobalCapLimit,$e as getGlobalData,se as getGlobalLiquidityAndSwapVolume,ke as getHoneyCollaterals,rr as getHoneyFees,De as getHoneyGlobalData,ir as getHoneyPausedState,Te as getHoneyPreview,Lr as getHoneyPythFeeds,pr as getHoneyPythOracle,lr as getHoneyRootPriceOracle,Re as getHoneyVaultsBalance,qe as getIncentiveFeeClaimStats,kr as getLSTStakeConfig,Bt as getManagedValidatorByAccount,Le as getMarkets,Jt as getMaxDeposit,pe as getOnChainPool,de as getPoolEvents,ce as getPoolHistoricalData,me as getPoolPausedState,Ht as getPoolState,ge as getProposalDetails,he as getProposalFromTx,Ce as getProposalVotes,ve as getPythLatestPrices,Me as getPythUpdateFee,Ie as getRelativeCapLimit,Ue as getRewardProofsByValidator,Qe as getRewardTokenToBeraRate,ze as getRewardVault,Or as getRewardVaultDurationConstants,Hr as getRewardVaultFromToken,Xe as getRewardVaultIncentives,Ge as getRewardVaultRewards,je as getRewardVaultStakingToken,Ee as getRewardVaults,et as getSWBeraVaultMetadata,tt as getSWBeraWithdrawal,Ye as getStakeWithdrawalCooldown,Ke as getStakedBeraAPR,Ze as getStakedBeraSnapshots,kt as getStakingPoolBatch,ue as getSubgraphPool,Ve as getSwapPayload,pt as getTokenCurrentPrices,Be as getTokenInformation,Xr as getTokens,rt as getTotalStakedAmount,St as getUserActiveValidators,Nt as getUserBoostsOnValidator,ot as getUserClaimableIncentives,Dt as getUserStakingPositions,nt as getUserVaultInfo,it as getUserVaults,at as getUserVaultsReward,Ft as getValidatorAnalytics,ro as getValidatorBoostApy,Tt as getValidatorCommission,Rt as getValidatorEstimatedBgtPerYear,vt as getValidatorOperatorAddress,It as getValidatorQueuedCommission,Mt as getValidatorQueuedOperatorAddress,Vt as getValidatorQueuedRewardAllocation,ee as getValidatorReturnPerBgt,Ct as getValidatorRewardAllocation,st as getVaultHistory,Lt as getVaultPausedState,mt as getVaultValidators,ut as getWalletBalances,G as gql,Ne as isBadCollateralAsset,Oe as isBasketModeEnabled,Pt as isDefaultRewardAllocation,lt as isImpersonateAccount,ht as isSameRewardAllocation,Ae as parseProposalBody};
|
|
1
|
+
import{a as w,b as B,c as k,d as N}from"../chunk-F4BKSBEM.mjs";import{$ as Ze,A as ke,Aa as St,B as Ne,Ba as Dt,C as Se,Ca as Ft,D as De,Da as Tt,E as Fe,Ea as Rt,F as Te,Fa as vt,G as Re,Ga as It,H as ve,Ha as Mt,I as Ie,Ia as Vt,J as Me,K as Ve,L as Oe,M as We,N as Je,O as Ge,P as _e,Q as He,R as Ee,S as $e,T as qe,U as Le,V as Ue,W as Qe,X as ze,Y as Xe,Z as je,_ as Ke,a as te,aa as Ye,b as J,ba as et,c as h,ca as tt,d as G,da as rt,e as oe,ea as ot,f as ae,fa as at,g as ne,ga as nt,h as ie,ha as it,i as se,ia as st,j as me,ja as mt,k as pe,ka as pt,l as de,la as dt,m as ce,ma as lt,n as ue,na as ft,o as le,oa as yt,p as fe,pa as bt,q as ye,qa as xt,r as be,ra as gt,s as xe,sa as At,t as ge,ta as ht,u as Ae,ua as Ct,v as he,va as Pt,w as Ce,wa as wt,x as Pe,xa as Bt,y as we,ya as kt,z as Be,za as Nt}from"../chunk-A4UDYSB6.mjs";import{a as C,b as P,e as l,i as u,j as A,k as f,l as y}from"../chunk-Q3SCM6WL.mjs";import{a as re,b as ct,c as ut}from"../chunk-7SMWQ6SN.mjs";import"../chunk-NAXAZJJY.mjs";import"../chunk-OGJMSGB2.mjs";import"../chunk-7WRTK7RJ.mjs";import{b as F,c as b,d as T}from"../chunk-2LL3P5PN.mjs";import{d as S,l as R,q as v}from"../chunk-ECRMUMTA.mjs";import{a as m,e as D}from"../chunk-THATXCJK.mjs";import"../chunk-AX2YQQFQ.mjs";import{formatEther as _}from"viem";async function Jt({vaultAddress:e,publicClient:t}){let r=await t.readContract({address:e,abi:C,functionName:"maxDeposit",args:[e]});return _(r)}import{mapPoolType as H}from"@berachain-foundation/berancer-sdk";var Ht=e=>({type:H(e.type),protocolVersion:e.protocolVersion,tokens:e.tokens.map(t=>({...t,address:t.address})),id:e.id,address:e.address});async function Lt({publicClient:e,...t}){let{config:r}=m(t);return(await e.readContract({address:r.bex.vault,abi:P,functionName:"getPausedState"}))[0]}import{decodeFunctionData as M,erc20Abi as E,pad as $,toFunctionSignature as q,trim as I}from"viem";import{appConfig as L,defaultChainId as U}from"@berachain/config/internal";function Q(e){return e.some(t=>t.name==="implementation"||t.name==="proxyType"||t.type==="constructor"&&t.inputs?.[0]?.name==="implementation")}async function V({contractAddress:e,chainId:t,publicClient:r}){let o=`https://api.etherscan.io/v2/api?module=contract&action=getabi&address=${e}&apikey=${L.apiKeys.private.etherscan}&chainId=${t}`,a=await fetch(o);if(!a.ok)throw new Error(`Failed to fetch ABI: ${a.statusText}`);let n=await a.json();if(n.status==="0")throw new Error(n.result);let p=JSON.parse(n.result);if(!Q(p))return p;let i=await r.getStorageAt({address:e,slot:"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"});if(!i||I(i)==="0x00")return p;let s=$(I(i),{size:20});return V({contractAddress:s,chainId:t,publicClient:r})}async function z({address:e,callData:t,knownAbi:r,chainId:o,publicClient:a}){try{if(M({data:t,abi:r}))return r}catch{}try{return await V({contractAddress:e,chainId:o,publicClient:a})}catch{}}function X(e,t){try{return M({data:e,abi:t})}catch{return}}function j(e,t){return e.find(r=>r.type==="function"&&r.name===t)}function K(e){if(e)try{return q(e)}catch(t){console.error(t)}}async function Kt({address:e,callData:t,chainId:r=U,publicClient:o}){let a=[...u,...f,...E],n=await z({address:e,callData:t,knownAbi:a,chainId:r,publicClient:o}),p=X(t,n);if(!n||!p)return{args:[]};let i=j(n,p.functionName),s=K(i);return{abiItem:i,functionSignature:s,functionName:p.functionName,args:p.args}}import{formatUnits as x}from"viem";async function rr({client:e,collateralList:t,...r}){let{config:o}=m(r);try{let a={mint:[],redeem:[]};for(let s of t)a.mint.push(e.readContract({address:o.honey.factory,abi:l,functionName:"mintRates",args:[s.address]})),a.redeem.push(e.readContract({address:o.honey.factory,abi:l,functionName:"redeemRates",args:[s.address]}));let[n,p,i]=await Promise.all([Promise.all(a.mint),Promise.all(a.redeem),e.readContract({address:o.honey.factory,abi:l,functionName:"getWeights"})]);return t.reduce((s,d)=>{let c=t.indexOf(d);return s.single[d.address]={mintFee:1-+x(n[c],18),redeemFee:1-+x(p[c],18)},s.basket.mintFee+=s.single[d.address].mintFee*+x(i[c],18),s.basket.redeemFee+=s.single[d.address].redeemFee*+x(i[c],18),s},{single:{},basket:{mintFee:0,redeemFee:0}})}catch(a){throw console.log(a),a}}async function ir({client:e,...t}){let{config:r}=m(t),o=r.honey.token;return await e.readContract({address:o,abi:w,functionName:"paused"})}async function pr({pythOracle:e,publicClient:t}){return await t.readContract({address:e,abi:B,functionName:"pythOracle"})}async function lr({publicClient:e,factory:t,...r}){let{config:o}=m(r);return await e.readContract({address:t??o.honey.factory,abi:l,functionName:"priceOracle"})}import{GetBlocksTimeStamp as Z}from"@berachain/graphql/chain";async function Ar({defaultBlockTime:e,blocksSpan:t,...r}={}){let{config:o}=m(r),a=h("blocks.subgraph",r),n=e??o.averageBlockTime,p=t??Math.floor(v(1)/n),s=(await a.query({query:Z,variables:{skip:p}})).data;return(R(Date.now())-Number(s?.oldest[0]?.timestamp))/(Number(s?.newest[0]?.number)-Number(s?.oldest[0]?.number))}async function kr({tokenList:e,publicClient:t,lstStakingVaults:r,...o}){b(t);let{config:a}=m({...o,chainId:t.chain?.id??o.chainId}),n=e.filter(i=>r.includes(i.address));return n.length===0?[]:(await Promise.all(n.map(async i=>({assetTokenAddress:await t.readContract({address:i.address,abi:N,functionName:"asset"}),stakingToken:i})))).reduce((i,{assetTokenAddress:s,stakingToken:d})=>{let c=e.find(g=>D(g,s));return c&&i.push({id:d.address,receiptToken:d,inputTokens:[c]}),i},[])}var O=[{inputs:[{internalType:"address",name:"initialOwner",type:"address"},{internalType:"address",name:"initialImplementation",type:"address"}],stateMutability:"payable",type:"constructor"},{inputs:[],name:"NewImplementationHasNoCode",type:"error"},{inputs:[],name:"NewOwnerIsZeroAddress",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"oldOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{inputs:[],name:"implementation",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"result",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"}],name:"upgradeTo",outputs:[],stateMutability:"nonpayable",type:"function"}];async function W({publicClient:e,...t}){let{config:r}=m(t),o=r.pol.factory;F(e,"publicClient"),T(r.pol.factory,"factoryAddress");let a=await e.readContract({address:o,abi:y,functionName:"beacon"});return await e.readContract({address:a,abi:O,functionName:"implementation"})}async function Or({publicClient:e,...t}){b(e);let r=await W({publicClient:e,...t}),[o,a]=await Promise.all([e.readContract({address:r,abi:f,functionName:"MIN_REWARD_DURATION"}),e.readContract({address:r,abi:f,functionName:"MAX_REWARD_DURATION"})]);return{minRewardDuration:Number(o),maxRewardDuration:Number(a)}}import{zeroAddress as Y}from"viem";async function Hr({tokenAddress:e,publicClient:t,factoryAddress:r,...o}){let{config:a}=m(o),n=await t.readContract({address:r??a.pol.factory,abi:y,functionName:"getVault",args:[e]});return n===Y?null:n}async function Lr({tokenList:e,publicClient:t,...r}){let{config:o}=m(r);try{let a=await Promise.all(e.map(n=>t.readContract({address:o.honey.pythOracle,abi:k,functionName:"feeds",args:[n]})));return e.reduce((n,p,i)=>({...n,[p]:a[i]}),{})}catch(a){throw console.error("getPythPriceFeedId",a),a}}async function Xr({url:e,...t}={}){let{config:r}=m(t);return(await S({url:e??r.lists.tokenList,type:"rest",name:"GitHub"})).tokens??[]}async function eo({publicClient:e,ui:t,...r}){let{config:o}=m(r),[a,n,p,i,s,d,c,g]=await Promise.all([e.readContract({address:o.pol.beraChef,abi:u,functionName:"MAX_COMMISSION_RATE"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"commissionChangeDelay"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"rewardAllocationBlockDelay"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"maxWeightPerVault"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"maxNumWeightsPerRewardAllocation"}),e.readContract({address:o.tokens.bgt,abi:A,functionName:"dropBoostDelay"}),e.readContract({address:o.tokens.bgt,abi:A,functionName:"activateBoostDelay"}),e.readContract({address:o.pol.beraChef,abi:u,functionName:"rewardAllocationInactivityBlockSpan"})]);return{maxCommissionRate:Number(a)/1e4,boostDelay:Number(c),unboostDelay:Number(d),commissionChangeDelay:Number(n),rewardAllocationBlockDelay:Number(p),maxWeightPerVault:Number(i)/1e4,maxNumWeightsPerRewardAllocation:Number(s),rewardAllocationInactivityBlockSpan:Number(g),ui:t}}function ee(e){return e?.rewardAllocationWeights?.reduce((t,r)=>{if(!r)return t;let o=r.receivingVault?.activeIncentives.filter(a=>Number(a.remainingAmount)>0).reduce((a,n)=>{let p=Number(n.remainingAmountUsd)/Number(n.remainingAmount);return a+Number(n.incentiveRate)*p},0)??0;return t+o*r.percentage},0)}function ro({validator:e,bgtPrice:t}){let r=Number(e.dynamicData?.activeBoostAmount??0),o=ee(e);return!o||!r?0:o*Number(e.dynamicData?.lastDayDistributedBGTAmount??0)*365/(r*t)}export{ae as BalancerApi,oe as BaseAggregator,J as BeraApolloClient,Fe as HoneyPreviewMethod,fe as MOCKED_PROPOSAL_STATUSES,Je as RewardVaultDistributionMode,ft as beraWriteContract,le as checkProposalField,ye as computeActualStatus,At as formatValidatorRewardAllocation,eo as getActiveBoostAndCommissionChangeDelay,ne as getAllPools,be as getAllProposals,yt as getAllValidators,dt as getAllowances,bt as getApiEnrichedAllocation,ie as getApiPool,xt as getApiValidator,h as getApolloClient,ct as getBalanceCall,_e as getBgtAprSimulation,Ar as getBlockTime,We as getBlockTimestamp,xe as getBodyErrors,Pe as getChartData,we as getCollateralWeights,te as getConvertToAssets,gt as getDailyValidatorBlockStats,Kt as getDecodedFunctionData,wt as getDefaultRewardAllocation,He as getEarnedStakedBeraVault,re as getEnsoClient,Se as getGlobalCapLimit,$e as getGlobalData,se as getGlobalLiquidityAndSwapVolume,ke as getHoneyCollaterals,rr as getHoneyFees,De as getHoneyGlobalData,ir as getHoneyPausedState,Te as getHoneyPreview,Lr as getHoneyPythFeeds,pr as getHoneyPythOracle,lr as getHoneyRootPriceOracle,Re as getHoneyVaultsBalance,qe as getIncentiveFeeClaimStats,kr as getLSTStakeConfig,Bt as getManagedValidatorByAccount,Le as getMarkets,Jt as getMaxDeposit,pe as getOnChainPool,de as getPoolEvents,ce as getPoolHistoricalData,me as getPoolPausedState,Ht as getPoolState,ge as getProposalDetails,he as getProposalFromTx,Ce as getProposalVotes,ve as getPythLatestPrices,Me as getPythUpdateFee,Ie as getRelativeCapLimit,Ue as getRewardProofsByValidator,Qe as getRewardTokenToBeraRate,ze as getRewardVault,Or as getRewardVaultDurationConstants,Hr as getRewardVaultFromToken,Xe as getRewardVaultIncentives,Ge as getRewardVaultRewards,je as getRewardVaultStakingToken,Ee as getRewardVaults,et as getSWBeraVaultMetadata,tt as getSWBeraWithdrawal,Ye as getStakeWithdrawalCooldown,Ke as getStakedBeraAPR,Ze as getStakedBeraSnapshots,kt as getStakingPoolBatch,ue as getSubgraphPool,Ve as getSwapPayload,pt as getTokenCurrentPrices,Be as getTokenInformation,Xr as getTokens,rt as getTotalStakedAmount,St as getUserActiveValidators,Nt as getUserBoostsOnValidator,ot as getUserClaimableIncentives,Dt as getUserStakingPositions,nt as getUserVaultInfo,it as getUserVaults,at as getUserVaultsReward,Ft as getValidatorAnalytics,ro as getValidatorBoostApy,Tt as getValidatorCommission,Rt as getValidatorEstimatedBgtPerYear,vt as getValidatorOperatorAddress,It as getValidatorQueuedCommission,Mt as getValidatorQueuedOperatorAddress,Vt as getValidatorQueuedRewardAllocation,ee as getValidatorReturnPerBgt,Ct as getValidatorRewardAllocation,st as getVaultHistory,Lt as getVaultPausedState,mt as getVaultValidators,ut as getWalletBalances,G as gql,Ne as isBadCollateralAsset,Oe as isBasketModeEnabled,Pt as isDefaultRewardAllocation,lt as isImpersonateAccount,ht as isSameRewardAllocation,Ae as parseProposalBody};
|
|
2
2
|
//# sourceMappingURL=exports.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkC6ZGUO4Hcjs = require('./chunk-C6ZGUO4H.cjs');var _internal = require('@berachain/config/internal');function i(o){let n=_nullishCoalesce(o.chainId, () => (_internal.defaultChainId)),e=_nullishCoalesce(o.config, () => (_internal.chainConfigs[n]));if(o.chainId&&o.chainId!==e.chainId)throw new (0, _chunkC6ZGUO4Hcjs.h)({property:"chainId",value:n,expected:`config.chainId: ${e.chainId}`});return{config:e,chainId:e.chainId}}var _viem = require('viem');var _mainnet = require('@berachain/config/mainnet');var I={address:_viem.zeroAddress,decimals:18,name:"Bera",symbol:"BERA",logoURI:"https://res.cloudinary.com/duv0g402y/image/upload/v1738720154/brand/berachain-chain-logo.png.png"},l= exports.c ={address:_mainnet.mainnet.tokens.wbera,decimals:18,name:"WBera",symbol:"WBERA"};function R(o){let{config:n,chainId:e}=i(o);return{address:n.honey.token,symbol:"HONEY",name:"Honey",decimals:18,chainId:e}}function b(...o){let[n,e,r]=o;if(n===void 0)return!1;let s=typeof n=="string"?n:n.address;if(typeof e=="string"&&!_viem.isAddress.call(void 0, e)&&!e.startsWith("0x")){if(e==="BERA")return s.toLowerCase()===_viem.zeroAddress;if(e==="WBERA")return s.toLowerCase()===_mainnet.mainnet.tokens.wbera;if(e==="ETH")return s.toLowerCase()===_viem.ethAddress;if(e==="SWBERA")return s.toLowerCase()===_mainnet.mainnet.tokens.swbera.toLowerCase();if(r===void 0)throw new (0, _chunkC6ZGUO4Hcjs.h)({property:"baseArgs",value:r,expected:"BeraJS.BaseFunctionArgs",message:"baseArgs is required when compared to a known token different than BERA or WBERA. Checking against token: "+e+" and token address: "+s});let{config:a}=i(r),c={BGT:a.tokens.bgt,HONEY:a.honey.token,SWBERA:a.tokens.swbera,ETH:_viem.ethAddress};if(e in c)return s.toLowerCase()===c[e].toLowerCase()}let k=typeof e=="object"?e.address:e;return s.toLowerCase()===k.toLowerCase()}exports.a = i; exports.b = I; exports.c = l; exports.d = R; exports.e = b;
|
|
2
|
+
//# sourceMappingURL=chunk-22J3YJDN.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/chunk-22J3YJDN.cjs","../src/utils/parseBaseArgs.ts"],"names":["parseBaseArgs","args","chainId","defaultChainId","config","chainConfigs","InvalidArgumentError"],"mappings":"AAAA,qOAAwC,sDCIjC,SAISA,CAAAA,CAAcC,CAAAA,CAA+B,CAC3D,IAAMC,CAAAA,kBAAUD,CAAAA,CAAK,OAAA,SAAWE,0BAAAA,CAC1BC,CAAAA,kBAAqBH,CAAAA,CAAK,MAAA,SAAUI,sBAAAA,CAAaH,CAAO,GAAA,CAE9D,EAAA,CAAID,CAAAA,CAAK,OAAA,EAAWA,CAAAA,CAAK,OAAA,GAAYG,CAAAA,CAAO,OAAA,CAE1C,MAAM,IAAIE,wBAAAA,CAAqB,CAC7B,QAAA,CAAU,SAAA,CACV,KAAA,CAAOJ,CAAAA,CACP,QAAA,CAAU,CAAA,gBAAA,EAAmBE,CAAAA,CAAO,OAAO,CAAA,CAAA","file":"/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/chunk-22J3YJDN.cjs","sourcesContent":[null,"import {\n type BeraConfig,\n chainConfigs,\n defaultChainId,\n} from \"@berachain/config/internal\";\n\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\n\nexport function parseBaseArgs(args: BeraJS.BaseFunctionArgs) {\n const chainId = args.chainId ?? defaultChainId;\n const config: BeraConfig = args.config ?? chainConfigs[chainId];\n\n if (args.chainId && args.chainId !== config.chainId) {\n // this matches unless the config is explicitly provided\n throw new InvalidArgumentError({\n property: \"chainId\",\n value: chainId,\n expected: `config.chainId: ${config.chainId}`,\n });\n }\n\n return { config, chainId: config.chainId };\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{e as o,f as i,g as a,h as p}from"./chunk-AX2YQQFQ.mjs";import{BaseError as u}from"viem";function k({cause:e,level:t}){if(e instanceof u){let n=o({error:e,revertIfUnknown:!1});if(n.isRequestError&&n.rootCause instanceof u&&"url"in n.rootCause&&typeof n.rootCause.url=="string")return new a({cause:n.rootCause,response:void 0,endpoint:{url:n.rootCause.url,type:"rpc"},level:t})}return e instanceof i?e:new i({cause:e,level:t})}import{isAddress as m}from"viem";function c(e){return e!=null}function x({value:e,property:t,fn:r}){let n=r(e);if(!n.isValid)throw new p({property:t,value:e,expected:n.expectedType})}function s({value:e,property:t,fn:r}){x({value:e,property:t,fn:n=>{let l=c(n),{isValid:E,expectedType:v}=r(n);return{expectedType:v,isValid:l&&E}}})}function y(e,t){s({value:e,property:t,fn:r=>({expectedType:"defined",isValid:c(r)})})}function D(e,t="publicClient"){y(e,t)}function K(e,t){s({value:e,property:t,fn:r=>({expectedType:"Address",isValid:typeof r=="string"&&m(r)})})}function M(e,t){s({value:e,property:t,fn:r=>({expectedType:"number",isValid:(typeof r=="string"||typeof r=="number")&&Number(r)>0})})}function f(){let e={};return{emit(t,...r){for(let n of e[t]||[])n(...r)},events:e,on(t,r){return e[t]||(e[t]=[]),e[t].push(r),()=>{e[t]=e[t]?.filter(n=>r!==n)}}}}var d=f(),_={captureException(e){let t={exception:e,timestamp:Date.now()};d.emit("exception",t)},on(...e){return d.on(...e)}};export{k as a,y as b,D as c,K as d,M as e,_ as f};
|
|
2
|
+
//# sourceMappingURL=chunk-2LL3P5PN.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as t}from"./chunk-ECRMUMTA.mjs";import{c as T,e as a}from"./chunk-THATXCJK.mjs";function m(e){return{...e,...a(e,"BERA")&&T}}function d(e){return e.map(r=>m(r))}var g=(e,r,i,o)=>{if(!e||!r||!i||!o)return 0;let n=new t(e).times(i),s=new t(r).times(o);if(n.lt(.01)||s.lt(.01)||n.isZero()||s.isZero())return 0;let u=s.div(n);return Number(new t(1).minus(u).toFixed())};export{m as a,d as b,g as c};
|
|
2
|
+
//# sourceMappingURL=chunk-3YXSUBA5.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/tokenWrapping.ts","../src/utils/math.ts"],"sourcesContent":["import { isToken, wBeraToken } from \"./tokens\";\n\ntype BaseToken = {\n address: string;\n};\n\nexport function wrapNativeToken<T extends BaseToken>(token: T): T {\n return {\n ...token,\n ...(isToken(token, \"BERA\") && wBeraToken),\n };\n}\n\nexport function wrapNativeTokens<T extends BaseToken>(tokens: T[]): T[] {\n return tokens.map((token) => wrapNativeToken(token));\n}\n","import BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\n/**\n * Compute the price impact of a swap\n * @param {string} tokenInPrice - The price of the input token\n * @param {string} tokenOutPrice - The price of the output token\n * @param {string} inAmount - The amount of the input token\n * @param {string} outAmount - The amount of the output token\n * @returns {number} The price impact of the swap\n */\nexport const computePriceImpact = (\n tokenInPrice: string,\n tokenOutPrice: string,\n inAmount: string,\n outAmount: string,\n): number => {\n if (!tokenInPrice || !tokenOutPrice || !inAmount || !outAmount) return 0;\n\n const usdIn = new BigNumber(tokenInPrice).times(inAmount);\n const usdOut = new BigNumber(tokenOutPrice).times(outAmount);\n\n // is the amount is close to 0, return 0\n if (usdIn.lt(0.01) || usdOut.lt(0.01)) return 0;\n if (usdIn.isZero() || usdOut.isZero()) return 0;\n\n const ratio = usdOut.div(usdIn);\n return Number(new BigNumber(1).minus(ratio).toFixed());\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/utils/tokenWrapping.ts","../src/utils/math.ts"],"sourcesContent":["import { isToken, wBeraToken } from \"./tokens\";\n\ntype BaseToken = {\n address: string;\n};\n\nexport function wrapNativeToken<T extends BaseToken>(token: T): T {\n return {\n ...token,\n ...(isToken(token, \"BERA\") && wBeraToken),\n };\n}\n\nexport function wrapNativeTokens<T extends BaseToken>(tokens: T[]): T[] {\n return tokens.map((token) => wrapNativeToken(token));\n}\n","import BigNumber from \"@berachain/utils/pkg/bignumber.js\";\n\n/**\n * Compute the price impact of a swap\n * @param {string} tokenInPrice - The price of the input token\n * @param {string} tokenOutPrice - The price of the output token\n * @param {string} inAmount - The amount of the input token\n * @param {string} outAmount - The amount of the output token\n * @returns {number} The price impact of the swap\n */\nexport const computePriceImpact = (\n tokenInPrice: string,\n tokenOutPrice: string,\n inAmount: string,\n outAmount: string,\n): number => {\n if (!tokenInPrice || !tokenOutPrice || !inAmount || !outAmount) return 0;\n\n const usdIn = new BigNumber(tokenInPrice).times(inAmount);\n const usdOut = new BigNumber(tokenOutPrice).times(outAmount);\n\n // is the amount is close to 0, return 0\n if (usdIn.lt(0.01) || usdOut.lt(0.01)) return 0;\n if (usdIn.isZero() || usdOut.isZero()) return 0;\n\n const ratio = usdOut.div(usdIn);\n return Number(new BigNumber(1).minus(ratio).toFixed());\n};\n"],"mappings":"yFAMO,SAASA,EAAqCC,EAAa,CAChE,MAAO,CACL,GAAGA,EACH,GAAIC,EAAQD,EAAO,MAAM,GAAKE,CAChC,CACF,CAEO,SAASC,EAAsCC,EAAkB,CACtE,OAAOA,EAAO,IAAKJ,GAAUD,EAAgBC,CAAK,CAAC,CACrD,CCLO,IAAMK,EAAqB,CAChCC,EACAC,EACAC,EACAC,IACW,CACX,GAAI,CAACH,GAAgB,CAACC,GAAiB,CAACC,GAAY,CAACC,EAAW,MAAO,GAEvE,IAAMC,EAAQ,IAAIC,EAAUL,CAAY,EAAE,MAAME,CAAQ,EAClDI,EAAS,IAAID,EAAUJ,CAAa,EAAE,MAAME,CAAS,EAI3D,GADIC,EAAM,GAAG,GAAI,GAAKE,EAAO,GAAG,GAAI,GAChCF,EAAM,OAAO,GAAKE,EAAO,OAAO,EAAG,MAAO,GAE9C,IAAMC,EAAQD,EAAO,IAAIF,CAAK,EAC9B,OAAO,OAAO,IAAIC,EAAU,CAAC,EAAE,MAAME,CAAK,EAAE,QAAQ,CAAC,CACvD","names":["wrapNativeToken","token","isToken","wBeraToken","wrapNativeTokens","tokens","computePriceImpact","tokenInPrice","tokenOutPrice","inAmount","outAmount","usdIn","bignumber_js_default","usdOut","ratio"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as B,b as E}from"./chunk-7SMWQ6SN.mjs";import{a as h,f as g}from"./chunk-2LL3P5PN.mjs";import{a as S}from"./chunk-C3FHGFLK.mjs";import{a as y,b as v,e as m}from"./chunk-THATXCJK.mjs";import{f as P,h as b}from"./chunk-AX2YQQFQ.mjs";import{createContext as N,useContext as O}from"react";import{isFlagEnabled as U}from"@berachain/config/internal/edge-config";import{jsx as Y}from"react/jsx-runtime";var W=N(void 0);function pe({children:e,flags:t,aggregators:a,swberaAprWindow:n="DAY"}){return Y(W.Provider,{value:{...S,...t,aggregators:a?Object.entries(a).filter(([,r])=>U(r)).map(([r])=>r):void 0,swberaAprWindow:n},children:e})}function D(){let e=O(W);if(!e)throw new Error("BeraFlagsProvider not found");return e}function fe(e){return D()[e]}import{createContext as V,useContext as q,useState as K}from"react";import{jsx as Q}from"react/jsx-runtime";var w=V({protocol:{isPaused:!1,factories:{composableStable:"enabled",weighted:"enabled",allPaused:!1}},onPoolChange:()=>{},pool:void 0});function Te(){let e=q(w);if(!e)throw new P({level:"fatal",message:"BexStateContext is not defined"});return e}function he({children:e,isVaultPaused:t,labels:a,factories:n}){let[r,u]=K(),s=(r?.isPaused&&!r?.isInRecoveryMode)??!1,l=t||r?.isPaused;return Q(w.Provider,{value:{protocol:{isPaused:t,factories:{...n,allPaused:n.composableStable==="paused"&&n.weighted==="paused"}},labels:a,onPoolChange:u,pool:r?{...r,disablePoolWithdrawals:!!s,disablePoolDeposits:!!l}:void 0},children:e})}import{createContext as _,useContext as G}from"react";import{mainnet as J}from"@berachain/config/mainnet";import{jsx as z}from"react/jsx-runtime";function ve(){return G(F)}var F=_(J.averageBlockTime);function Ee({children:e,blockTime:t,...a}){let{config:n}=y(a);return z(F.Provider,{value:t??n.averageBlockTime,children:e})}import{createContext as X,useContext as Z}from"react";import{jsx as $}from"react/jsx-runtime";var L=X(void 0);function Fe({children:e,...t}){return $(L.Provider,{value:t,children:e})}function Le(){let e=Z(L);if(!e)throw new Error("useHoneyConfig must be used within a HoneyConfigProvider");return e}import{createContext as re,useMemo as ae}from"react";import{isFlagEnabled as se}from"@berachain/config/internal/edge-config";import oe from"swr";import{useBeraWallet as te,useConfig as ne}from"@berachain/wagmi/hooks";import{getChains as j,multicall as ee}from"@wagmi/core";import{formatUnits as M}from"viem";async function R({account:e,wagmiConfig:t,chainId:a,ensoClient:n}){let u=(await n.getBalances({useEoa:!0,chainId:a??"all",eoaAddress:e})).map(o=>({name:o.name,symbol:o.symbol,decimals:o.decimals,address:m(o.token,"ETH")?v.address:o.token,logoURI:o.logoUri,balance:{raw:o.amount.toString(),formatted:M(BigInt(o.amount),o.decimals)},chainId:Number(o.chainId),price:Number(o.price)})),s=Object.groupBy(u,o=>o.chainId??0),l=await Promise.allSettled(Object.entries(s).map(async([o,i])=>{if(!i)return;let p=j(t).find(d=>d.id===Number(o));if(!p)return;let k=p.contracts?.multicall3?.address;if(!k)return g.captureException(new b({property:"multicallAddress",value:k,expected:"Address",chainId:Number(o)})),i;let f=await ee(t,{chainId:Number(o),contracts:i.map(d=>E({token:d,account:e,multicallAddress:k})),allowFailure:!0}),x=[];for(let d=0;d<i.length;d++){let T=i[d];if(f[d].status==="success"){let C=f[d].result;x.push({...T,balance:{raw:C?.toString()??"0",formatted:M(C??0n,T.decimals)}})}else console.error("error getting balance",f[d].error),g.captureException(h({cause:f[d].error})),x.push(T)}return x})),c=[];for(let o of l)o.status==="fulfilled"?c.push(...o.value??[]):g.captureException(h({cause:o.reason}));return c.sort((o,i)=>{let p=Number(o.balance.formatted)*(o.price??0);return Number(i.balance.formatted)*(i.price??0)-p})}function A({chainId:e}={},t){let{address:a}=te(),n=ne(),r=!!a&&(t?.opts?.isEnabled??!0),s=oe(r&&n?["useEnsoUserTokensWithBalances",a,e]:null,async([,l,c])=>R({account:l,wagmiConfig:n,chainId:c??"all",ensoClient:B()}),{refreshInterval:1e5,isEnabled:r,...t?.opts});return{...s,refresh:()=>s.mutate()}}function H({defaultTokenList:e=[],externalList:t=[]}){if(e.length===0)return{tokenList:t,customTokenList:t,featuredTokenList:[]};let a=e.map(s=>({...s,default:!0})),n=a.filter(s=>s.tags?.some(l=>l==="featured")),r=[...a,...t];return{tokenList:r.filter((s,l)=>r.findIndex(c=>m(c,s))===l),customTokenList:t,featuredTokenList:n}}import{jsx as le}from"react/jsx-runtime";var ie=re(void 0);function je({children:e,defaultTokens:t,edgeConfigTokenList:a,userTokens:n,onAddToken:r,onRemoveToken:u}){let{data:s,refresh:l}=A(),{tokenList:c=[],featuredTokenList:o=[]}=ae(()=>H({defaultTokenList:[...t,...a?.filter(i=>se(i.enabled))],externalList:[...n,...(s??[]).map(i=>({...i,balance:void 0,price:void 0}))]}),[t,n,a,s]);return le(ie.Provider,{value:{tokenList:c,userTokens:n,featuredTokens:o,ensoTokens:s,onAddToken(i){r(i,{defaultTokens:t,userTokens:n,tokenList:c})},onRemoveToken:u,refresh:()=>{l()}},children:e})}export{pe as a,D as b,fe as c,w as d,Te as e,he as f,ve as g,F as h,Ee as i,L as j,Fe as k,Le as l,ie as m,je as n};
|
|
2
|
+
//# sourceMappingURL=chunk-55L7STYD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/contexts/BeraFlags/BeraFlags.tsx","../src/contexts/BexStatusProvider.tsx","../src/contexts/block-time-provider.tsx","../src/contexts/HoneyConfigProvider.tsx","../src/contexts/TokensProvider.tsx","../src/hooks/enso/useEnsoUserTokensWithBalances.ts","../src/actions/enso/getEnsoUserTokensWithBalances.ts","../src/utils/formatTokenList.ts"],"sourcesContent":["import { createContext, useContext } from \"react\";\n\nimport {\n type EdgeConfigSchema,\n isFlagEnabled,\n} from \"@berachain/config/internal/edge-config\";\n\nimport { type BeraFlags, defaultFlags } from \"./defaultFlags\";\n\nexport type { BeraFlags };\n\nexport type BeraFlagsContextReturn = BeraFlags & {\n /**\n * A list of aggregators that are enabled. If not provided, all aggregators are enabled.\n */\n aggregators: string[] | undefined;\n swberaAprWindow: Exclude<\n EdgeConfigSchema[\"pol\"][\"swberaAprWindow\"],\n undefined\n >;\n};\n\nconst BeraFlagContext = createContext<BeraFlagsContextReturn | undefined>(\n undefined,\n);\n\nexport function BeraFlagsProvider({\n children,\n flags,\n aggregators,\n swberaAprWindow = \"DAY\",\n}: {\n children: React.ReactNode;\n flags: BeraFlags;\n aggregators?: NonNullable<EdgeConfigSchema[\"bex\"]>[\"aggregators\"];\n swberaAprWindow?: EdgeConfigSchema[\"pol\"][\"swberaAprWindow\"];\n}) {\n return (\n <BeraFlagContext.Provider\n value={{\n ...defaultFlags,\n ...flags,\n aggregators: aggregators\n ? Object.entries(aggregators)\n .filter(([, value]) => isFlagEnabled(value))\n .map(([key]) => key)\n : undefined,\n swberaAprWindow,\n }}\n >\n {children}\n </BeraFlagContext.Provider>\n );\n}\n\nexport function useBeraFlags() {\n const context = useContext(BeraFlagContext);\n if (!context) {\n throw new Error(\"BeraFlagsProvider not found\");\n }\n return context;\n}\n\nexport function useBeraFlag<T extends keyof BeraFlagsContextReturn>(\n key: T,\n): BeraFlagsContextReturn[T] {\n const flags = useBeraFlags();\n return flags[key];\n}\n","import {\n createContext,\n type Dispatch,\n type PropsWithChildren,\n type SetStateAction,\n useContext,\n useState,\n} from \"react\";\nimport type { Hex } from \"viem\";\n\nimport type { EdgeConfigSchema } from \"@berachain/config/internal/edge-config\";\n\nimport { BeraError } from \"~/errors/BeraError\";\n\ntype FactoryStatus = {\n /**\n * If the composable stable factory is enabled\n */\n composableStable: \"paused\" | \"enabled\";\n /**\n * If the weighted factory is enabled\n */\n weighted: \"paused\" | \"enabled\";\n};\nexport interface BexStatusProviderProps {\n isVaultPaused: boolean;\n pool?: {\n id: Hex;\n isInRecoveryMode: boolean;\n isPaused: boolean;\n };\n factories: FactoryStatus;\n labels?: NonNullable<EdgeConfigSchema[\"bex\"]>[\"emergencyLabels\"];\n}\n\nexport const BexStateContext = createContext<{\n protocol: {\n isPaused: boolean;\n factories: FactoryStatus & { allPaused: boolean };\n };\n onPoolChange: Dispatch<SetStateAction<BexStatusProviderProps[\"pool\"]>>;\n pool?: {\n id: Hex;\n isInRecoveryMode: boolean;\n isPaused: boolean;\n disablePoolWithdrawals: boolean;\n disablePoolDeposits: boolean;\n };\n labels?: NonNullable<EdgeConfigSchema[\"bex\"]>[\"emergencyLabels\"];\n}>({\n protocol: {\n isPaused: false,\n factories: {\n composableStable: \"enabled\",\n weighted: \"enabled\",\n allPaused: false,\n },\n },\n onPoolChange: () => {},\n pool: undefined,\n});\n\n/**\n * @description Determines the status of a pool or vault and returns the appropriate messages and flags to disable functionality.\n * More information here https://www.notion.so/berachain/BEX-RecoveryMode-and-Pause-explained-17c6120abced80e0985dd589b57ff018\n *\n * @returns status flags to enable/disable/notify users across the BEX\n *\n **/\nexport function useBexStatus() {\n const context = useContext(BexStateContext);\n\n if (!context) {\n throw new BeraError({\n level: \"fatal\",\n message: \"BexStateContext is not defined\",\n });\n }\n\n return context;\n}\n\nexport function BexStatusProvider({\n children,\n isVaultPaused,\n labels,\n factories,\n}: PropsWithChildren<BexStatusProviderProps>) {\n const [poolState, setPoolState] = useState<BexStatusProviderProps[\"pool\"]>();\n // Determine whether to disable withdrawals for a pool (vault pause does not impact this)\n const disablePoolWithdrawals =\n (poolState?.isPaused && !poolState?.isInRecoveryMode) ?? false;\n\n // Determine whether to disable deposits for a pool (vault pause does not impact this)\n const disablePoolDeposits = isVaultPaused || poolState?.isPaused;\n\n // TODO: we dont yet support anything to disable staking/unstaking within reward vaults if they get paused\n\n return (\n <BexStateContext.Provider\n value={{\n protocol: {\n isPaused: isVaultPaused,\n factories: {\n ...factories,\n allPaused:\n factories.composableStable === \"paused\" &&\n factories.weighted === \"paused\",\n },\n },\n labels,\n onPoolChange: setPoolState,\n pool: poolState\n ? {\n ...poolState,\n disablePoolWithdrawals: !!disablePoolWithdrawals,\n disablePoolDeposits: !!disablePoolDeposits,\n }\n : undefined,\n }}\n >\n {children}\n </BexStateContext.Provider>\n );\n}\n","import { createContext, type PropsWithChildren, useContext } from \"react\";\n\nimport { mainnet } from \"@berachain/config/mainnet\";\n\nimport { parseBaseArgs } from \"~/utils/parseBaseArgs\";\n\n/**\n * Average berachain block time in seconds\n */\nexport function useBlockTime(): number {\n return useContext(BlockTimeContext);\n}\n\nexport const BlockTimeContext = createContext<number>(\n // this is the default block time for berachain, but actually overridden by the block time provider\n mainnet.averageBlockTime,\n);\n\nexport function BlockTimeProvider({\n children,\n blockTime,\n ...args\n}: PropsWithChildren<{\n blockTime?: number;\n}> &\n BeraJS.BaseFunctionArgs) {\n const { config } = parseBaseArgs(args);\n\n return (\n <BlockTimeContext.Provider value={blockTime ?? config.averageBlockTime}>\n {children}\n </BlockTimeContext.Provider>\n );\n}\n","import { createContext, useContext } from \"react\";\n\nimport type { HoneyFeeMap } from \"~/actions/honey/getHoneyFees\";\nimport type { TokenWithMetadata } from \"~/types/dex\";\nimport type { PythPriceFeedMap } from \"~/types/honeySwap\";\n\nexport const HoneyConfigContext = createContext<\n HoneyConfigContextReturn | undefined\n>(undefined);\n\nexport type TokenWithOrder = TokenWithMetadata & {\n order: number;\n};\nexport interface HoneyConfigContextReturn {\n /**\n * Map of the Pyth price feed ids for each collateral\n */\n priceFeedMap: PythPriceFeedMap;\n /**\n * This is the list of all the collaterals that are supported by the Honey protocol\n */\n collateralList: TokenWithOrder[];\n /**\n * This is the main collateral that is used to calculate the relative cap limit\n */\n referenceCollateral: TokenWithOrder;\n /**\n * An object that maps the redeem/mint rate for each collateral and the weighted rates for the basket mode\n */\n feeMap: HoneyFeeMap;\n flags: {\n /**\n * If true, mint/redeem will also update pyth prices\n */\n isPythWrapperEnabled: boolean;\n };\n /**\n * Honey protocol configs\n */\n protocol: {\n /**\n * Honey protocol paused state\n */\n isPaused: boolean;\n /**\n * The label for the Honey protocol paused message\n */\n pausedBannerLabel?: string;\n };\n}\n\nexport interface HoneyConfigProviderProps extends HoneyConfigContextReturn {\n children: React.ReactNode;\n}\n\nexport function HoneyConfigProvider({\n children,\n ...props\n}: HoneyConfigProviderProps) {\n return (\n <HoneyConfigContext.Provider value={props}>\n {children}\n </HoneyConfigContext.Provider>\n );\n}\n\nexport function useHoneyConfig() {\n const context = useContext(HoneyConfigContext);\n if (!context) {\n throw new Error(\"useHoneyConfig must be used within a HoneyConfigProvider\");\n }\n return context;\n}\n","import { createContext, type PropsWithChildren, useMemo } from \"react\";\n\nimport {\n type EdgeConfigSchema,\n isFlagEnabled,\n} from \"@berachain/config/internal/edge-config\";\n\nimport { useEnsoUserTokensWithBalances } from \"~/hooks/enso/useEnsoUserTokensWithBalances\";\nimport type { BalanceToken, Token, TokenWithMetadata } from \"~/types/dex\";\nimport { formatTokenList } from \"~/utils/formatTokenList\";\n\nexport interface TokensProviderContext {\n tokenList: TokenWithMetadata[];\n userTokens: Token[];\n featuredTokens: TokenWithMetadata[];\n onRemoveToken: (token: Token) => void;\n onAddToken: (token: Token) => void;\n refresh: () => void;\n ensoTokens: BalanceToken[] | undefined;\n}\n\nexport const TokenContext = createContext<TokensProviderContext | undefined>(\n undefined,\n);\n\nexport interface TokensProviderProps\n extends Omit<\n TokensProviderContext,\n \"tokenList\" | \"onAddToken\" | \"featuredTokens\" | \"ensoTokens\"\n > {\n onAddToken: (\n token: Token,\n context: {\n defaultTokens: TokenWithMetadata[];\n userTokens: Token[];\n tokenList: TokenWithMetadata[];\n },\n ) => void;\n defaultTokens: TokenWithMetadata[];\n edgeConfigTokenList: EdgeConfigSchema[\"tokens\"];\n}\n\nexport function TokensProvider({\n children,\n defaultTokens,\n edgeConfigTokenList,\n userTokens,\n onAddToken,\n onRemoveToken,\n}: PropsWithChildren<Omit<TokensProviderProps, \"refresh\">>) {\n const { data: ensoTokens, refresh } = useEnsoUserTokensWithBalances();\n\n const { tokenList = [], featuredTokenList = [] } = useMemo(\n () =>\n formatTokenList({\n defaultTokenList: [\n ...defaultTokens,\n ...(edgeConfigTokenList?.filter((token) =>\n isFlagEnabled(token.enabled),\n ) as TokenWithMetadata[]),\n ],\n externalList: [\n ...userTokens,\n ...(ensoTokens ?? []).map((t) => ({\n ...t,\n balance: undefined,\n price: undefined,\n })),\n ],\n }),\n [defaultTokens, userTokens, edgeConfigTokenList, ensoTokens],\n );\n\n return (\n <TokenContext.Provider\n value={{\n tokenList,\n userTokens,\n featuredTokens: featuredTokenList,\n ensoTokens,\n onAddToken(tk) {\n onAddToken(tk, { defaultTokens, userTokens, tokenList });\n },\n onRemoveToken,\n refresh: () => {\n refresh();\n },\n }}\n >\n {children}\n </TokenContext.Provider>\n );\n}\n","import useSWR from \"swr\";\n\nimport { useBeraWallet, useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { getEnsoClient } from \"~/actions/clients/getEnsoClient\";\nimport { getEnsoUserTokensWithBalances } from \"~/actions/enso/getEnsoUserTokensWithBalances\";\nimport { POLLING } from \"~/enum/polling\";\nimport type { BalanceToken } from \"~/types/dex\";\nimport type { DefaultHookOptions } from \"~/types/global\";\n\nexport function useEnsoUserTokensWithBalances(\n { chainId }: { chainId?: number } = {},\n options?: DefaultHookOptions,\n) {\n const { address: fromAddress } = useBeraWallet();\n const wagmiConfig = useConfig();\n const isEnabled = !!fromAddress && (options?.opts?.isEnabled ?? true);\n\n const QUERY_KEY =\n isEnabled && wagmiConfig\n ? ([\"useEnsoUserTokensWithBalances\", fromAddress, chainId] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, fromAddress, chainId]): Promise<BalanceToken[]> =>\n getEnsoUserTokensWithBalances({\n account: fromAddress,\n wagmiConfig,\n chainId: chainId ?? \"all\",\n ensoClient: getEnsoClient(),\n }),\n {\n refreshInterval: POLLING.NORMAL,\n isEnabled,\n ...options?.opts,\n },\n );\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","import type { EnsoClient } from \"@ensofinance/sdk\";\nimport { type Config, getChains, multicall } from \"@wagmi/core\";\nimport { type Address, formatUnits } from \"viem\";\n\nimport { BeraMonitoring } from \"~/errors/BeraMonitoring\";\nimport { InvalidArgumentError } from \"~/errors/InvalidArgumentError\";\nimport { initBeraError } from \"~/errors/initBeraError\";\nimport type { BalanceToken } from \"~/types/dex\";\nimport { beraToken, isToken } from \"~/utils/tokens\";\nimport { getBalanceCall } from \"../tokens/getWalletBalances\";\n\n/**\n * Get user balances for each supported chain.\n *\n * This uses enso's balance endpoint to get the balances and RPC to get fresh balances.\n */\nexport async function getEnsoUserTokensWithBalances({\n account,\n wagmiConfig,\n chainId,\n ensoClient,\n}: {\n account: Address;\n wagmiConfig: Config;\n chainId: number | \"all\";\n ensoClient: EnsoClient;\n}): Promise<BalanceToken[]> {\n const ensoBalances = await ensoClient.getBalances({\n useEoa: true,\n chainId: chainId ?? \"all\",\n eoaAddress: account,\n });\n\n const tokens: BalanceToken[] = ensoBalances.map(\n (balance) =>\n ({\n name: balance.name,\n symbol: balance.symbol,\n decimals: balance.decimals,\n address: isToken(balance.token, \"ETH\")\n ? beraToken.address\n : balance.token,\n logoURI: balance.logoUri,\n balance: {\n raw: balance.amount.toString(),\n formatted: formatUnits(BigInt(balance.amount), balance.decimals),\n },\n\n chainId: Number(\n // @ts-expect-error - balance.chainId is defined just not typed by enso\n balance.chainId,\n ),\n price: Number(balance.price),\n }) as const satisfies BalanceToken,\n );\n\n const tokenByChainId = Object.groupBy(tokens, (a) => a.chainId ?? 0);\n\n const balances = await Promise.allSettled(\n Object.entries(tokenByChainId).map(async ([chainId, chainTokens]) => {\n if (!chainTokens) return undefined;\n const chainConfig = getChains(wagmiConfig).find(\n (chain) => chain.id === Number(chainId),\n );\n\n if (!chainConfig) {\n // if we've queried a chain that is not supported, we need to return undefined\n return undefined;\n }\n\n const multicall3 = chainConfig.contracts?.multicall3;\n\n const multicallAddress = multicall3?.address;\n\n if (!multicallAddress) {\n // if multicall is not supported on this chain, we need to use the enso balance\n // first let's report the error, as this is likely unexpected\n BeraMonitoring.captureException(\n new InvalidArgumentError({\n property: \"multicallAddress\",\n value: multicallAddress,\n expected: \"Address\",\n chainId: Number(chainId),\n }),\n );\n\n // we can return the tokens as is, as the balance is already set from the enso client\n return chainTokens;\n }\n\n const balances = await multicall(wagmiConfig, {\n chainId: Number(chainId),\n contracts: chainTokens.map((token) =>\n getBalanceCall({\n token,\n account,\n multicallAddress,\n }),\n ),\n allowFailure: true,\n });\n\n const tokensWithBalances: BalanceToken[] = [];\n\n for (let index = 0; index < chainTokens.length; index++) {\n const token = chainTokens[index];\n if (balances[index].status === \"success\") {\n const balance = balances[index].result;\n\n tokensWithBalances.push({\n ...token,\n balance: {\n raw: balance?.toString() ?? \"0\",\n formatted: formatUnits(balance ?? 0n, token.decimals),\n },\n });\n } else {\n console.error(\"error getting balance\", balances[index].error);\n BeraMonitoring.captureException(\n initBeraError({ cause: balances[index].error }),\n );\n // uses enso balance as fallback\n tokensWithBalances.push(token);\n }\n }\n\n return tokensWithBalances;\n }),\n );\n\n const flattenedBalances: BalanceToken[] = [];\n for (const result of balances) {\n if (result.status === \"fulfilled\") {\n flattenedBalances.push(...(result.value ?? []));\n } else {\n BeraMonitoring.captureException(initBeraError({ cause: result.reason }));\n }\n }\n\n return flattenedBalances.sort((a, b) => {\n const aValue = Number(a.balance.formatted) * (a.price ?? 0);\n const bValue = Number(b.balance.formatted) * (b.price ?? 0);\n return bValue - aValue;\n });\n}\n","import type { Token, TokenWithMetadata } from \"../types/dex\";\nimport { isToken } from \"./tokens\";\n\nexport interface FormatTokenListReturnType {\n /**\n * Token list including custom tokens\n */\n tokenList: Token[];\n /**\n * Custom token list (added by the user)\n */\n customTokenList?: Token[];\n /**\n * Featured token list\n */\n featuredTokenList?: Token[];\n}\n\nfunction formatTokenList({\n defaultTokenList = [],\n externalList = [],\n}: {\n defaultTokenList: TokenWithMetadata[];\n externalList?: Token[];\n}): FormatTokenListReturnType {\n if (defaultTokenList.length === 0) {\n return {\n tokenList: externalList,\n customTokenList: externalList,\n featuredTokenList: [],\n };\n }\n\n const defaultList = defaultTokenList.map((token) => {\n return { ...token, default: true };\n });\n\n const featuredTokenList = defaultList.filter((token) => {\n return token.tags?.some((tag) => tag === \"featured\");\n });\n\n const mergedList = [...defaultList, ...externalList];\n\n const uniqueList = mergedList.filter(\n (item, index) => mergedList.findIndex((i) => isToken(i, item)) === index,\n );\n\n return {\n tokenList: uniqueList,\n customTokenList: externalList,\n featuredTokenList,\n };\n}\n\nexport { formatTokenList };\n"],"mappings":"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","names":["createContext","useContext","isFlagEnabled","jsx","BeraFlagContext","createContext","BeraFlagsProvider","children","flags","aggregators","swberaAprWindow","defaultFlags","value","isFlagEnabled","key","useBeraFlags","context","useContext","useBeraFlag","createContext","useContext","useState","jsx","BexStateContext","createContext","useBexStatus","context","useContext","BeraError","BexStatusProvider","children","isVaultPaused","labels","factories","poolState","setPoolState","useState","disablePoolWithdrawals","disablePoolDeposits","createContext","useContext","mainnet","jsx","useBlockTime","useContext","BlockTimeContext","createContext","mainnet","BlockTimeProvider","children","blockTime","args","config","parseBaseArgs","createContext","useContext","jsx","HoneyConfigContext","HoneyConfigProvider","children","props","useHoneyConfig","context","createContext","useMemo","isFlagEnabled","useSWR","useBeraWallet","useConfig","getChains","multicall","formatUnits","getEnsoUserTokensWithBalances","account","wagmiConfig","chainId","ensoClient","tokens","balance","isToken","beraToken","formatUnits","tokenByChainId","a","balances","chainTokens","chainConfig","getChains","chain","multicallAddress","BeraMonitoring","InvalidArgumentError","multicall","token","getBalanceCall","tokensWithBalances","index","initBeraError","flattenedBalances","result","b","aValue","useEnsoUserTokensWithBalances","chainId","options","fromAddress","useBeraWallet","wagmiConfig","useConfig","isEnabled","swrResponse","useSWR","getEnsoUserTokensWithBalances","getEnsoClient","formatTokenList","defaultTokenList","externalList","defaultList","token","featuredTokenList","tag","mergedList","item","index","i","isToken","jsx","TokenContext","createContext","TokensProvider","children","defaultTokens","edgeConfigTokenList","userTokens","onAddToken","onRemoveToken","ensoTokens","refresh","useEnsoUserTokensWithBalances","tokenList","featuredTokenList","useMemo","formatTokenList","token","isFlagEnabled","t","tk"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } var _class;var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } var _class;var _chunkC6ZGUO4Hcjs = require('./chunk-C6ZGUO4H.cjs');var r=[],c= exports.a ={startSpan(e,t){return r.length===0?t():r.reduceRight((o,a)=>()=>a(e,o),t)()},addSpanHandler(e){return r.push(e),()=>{let t=r.indexOf(e);t!==-1&&r.splice(t,1)}}};var i=class extends _chunkC6ZGUO4Hcjs.f{constructor(t){super(t),this.name="NotFoundError",this.level=_nullishCoalesce(t.level, () => ("info")),this.message=`Resource ${t.resource} with id ${t.id} not found`,this.resource=t.resource,this.id=t.id}};var s= (_class =class extends _chunkC6ZGUO4Hcjs.f{__init() {this.blockNumber=null}constructor(t){super(t);_class.prototype.__init.call(this);,this.name="TransactionFailedError",this.txHash=t.txHash||null,this.receipt=t.receipt||null,this.to=t.to,this.functionName=t.functionName,this.blockNumber=_nullishCoalesce(t.blockNumber, () => (null)),this.input=t.input,this.receipt?this.message=`Transaction reverted on chain for reason: ${this.reason}`:this.txHash?this.message=`Transaction reverted after being broadcasted for reason: ${this.reason}`:this.message=`${this.reason}: ${this.message}`,this.tags={...this.tags,"operation.txn.status":t.txHash?"execution":"simulation",...t.tags},this.to&&(this.tags["operation.txn.to"]=this.to),this.functionName&&(this.tags["operation.txn.functionName"]=this.functionName)}}, _class);exports.a = c; exports.b = i; exports.c = s;
|
|
2
|
+
//# sourceMappingURL=chunk-6LDOG5RL.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/chunk-6LDOG5RL.cjs","../src/errors/BeraTracing.ts","../src/errors/NotFoundError.ts","../src/errors/TransactionFailedError.ts"],"names":["_handlers","BeraTracing","context","callback","next","handler","idx","NotFoundError","BeraError","args","TransactionFailedError"],"mappings":"AAAA,iPAAwC,ICqBlCA,CAAAA,CAA2B,CAAC,CAAA,CA0BrBC,CAAAA,aAAc,CAOzB,SAAA,CAAaC,CAAAA,CAAsBC,CAAAA,CAAwC,CACzE,OAAIH,CAAAA,CAAU,MAAA,GAAW,CAAA,CAAUG,CAAAA,CAAS,CAAA,CAGrCH,CAAAA,CAAU,WAAA,CACf,CAACI,CAAAA,CAAMC,CAAAA,CAAAA,EAAY,CAAA,CAAA,EAAMA,CAAAA,CAAQH,CAAAA,CAASE,CAAI,CAAA,CAC9CD,CACF,CAAA,CAAE,CACJ,CAAA,CASA,cAAA,CAAeE,CAAAA,CAAmC,CAChD,OAAAL,CAAAA,CAAU,IAAA,CAAKK,CAAO,CAAA,CACf,CAAA,CAAA,EAAM,CACX,IAAMC,CAAAA,CAAMN,CAAAA,CAAU,OAAA,CAAQK,CAAO,CAAA,CACjCC,CAAAA,GAAQ,CAAA,CAAA,EAAIN,CAAAA,CAAU,MAAA,CAAOM,CAAAA,CAAK,CAAC,CACzC,CACF,CACF,CAAA,CCnEO,IAAMC,CAAAA,CAAN,MAAA,QAA4BC,mBAAU,CAM3C,WAQA,CAAYC,CAAAA,CAA0B,CACpC,KAAA,CAAMA,CAAI,CAAA,CACV,IAAA,CAAK,IAAA,CAAO,eAAA,CACZ,IAAA,CAAK,KAAA,kBAAQA,CAAAA,CAAK,KAAA,SAAS,QAAA,CAC3B,IAAA,CAAK,OAAA,CAAU,CAAA,SAAA,EAAYA,CAAAA,CAAK,QAAQ,CAAA,SAAA,EAAYA,CAAAA,CAAK,EAAE,CAAA,UAAA,CAAA,CAC3D,IAAA,CAAK,QAAA,CAAWA,CAAAA,CAAK,QAAA,CACrB,IAAA,CAAK,EAAA,CAAKA,CAAAA,CAAK,EACjB,CACF,CAAA,CCzBO,IAAMC,CAAAA,WAAN,MAAA,QAAqCF,mBAAU,CAMpD,eAsBA,WAAA,CAA6B,KAAA,WAY7B,CACEC,CAAAA,CAQA,CACA,KAAA,CAAMA,CAAI,qCAAA,CACV,IAAA,CAAK,IAAA,CAAO,wBAAA,CACZ,IAAA,CAAK,MAAA,CAASA,CAAAA,CAAK,MAAA,EAAU,IAAA,CAC7B,IAAA,CAAK,OAAA,CAAUA,CAAAA,CAAK,OAAA,EAAW,IAAA,CAC/B,IAAA,CAAK,EAAA,CAAKA,CAAAA,CAAK,EAAA,CACf,IAAA,CAAK,YAAA,CAAeA,CAAAA,CAAK,YAAA,CACzB,IAAA,CAAK,WAAA,kBAAcA,CAAAA,CAAK,WAAA,SAAe,MAAA,CACvC,IAAA,CAAK,KAAA,CAAQA,CAAAA,CAAK,KAAA,CAEd,IAAA,CAAK,OAAA,CAEP,IAAA,CAAK,OAAA,CAAU,CAAA,0CAAA,EAA6C,IAAA,CAAK,MAAM,CAAA,CAAA","file":"/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/chunk-6LDOG5RL.cjs","sourcesContent":[null,"import type { Unsubscribe } from \"~/utils/createEmitter\";\n\n/**\n * Span context passed to tracing handlers.\n * Compatible with Sentry's StartSpanOptions (name, op, attributes).\n */\nexport type SpanContext = {\n name: string;\n op: string;\n attributes: Record<string, string | number | boolean | undefined>;\n};\n\n/**\n * A function that wraps a callback in a tracing span.\n * Compatible with Sentry.startSpan's signature.\n */\ntype StartSpanFn = <T>(\n context: SpanContext,\n callback: () => Promise<T>,\n) => Promise<T>;\n\nconst _handlers: StartSpanFn[] = [];\n\n/**\n * A generic span-tracing module for berajs.\n *\n * Instead of calling Sentry.startSpan directly, berajs calls\n * `BeraTracing.startSpan()`. Consumer apps subscribe via `.on(\"span\", handler)`\n * and forward spans to their tracing provider (Sentry, Datadog, etc.).\n *\n * Multiple handlers are supported and chain in registration order:\n * the first registered handler is the outermost wrapper.\n *\n * @example\n * ```ts\n * // In berajs code:\n * import { BeraTracing } from \"~/errors/BeraTracing\";\n * const result = await BeraTracing.startSpan(\n * { name: \"GraphQL query\", op: \"graphql.query\", attributes: {} },\n * () => executeQuery(),\n * );\n *\n * // In app instrumentation:\n * import { BeraTracing } from \"@berachain/berajs/errors\";\n * BeraTracing.addSpanHandler(Sentry.startSpan);\n * ```\n */\nexport const BeraTracing = {\n /**\n * Execute a callback, wrapping it in all registered span handlers.\n *\n * Handlers chain so each wraps the next. First registered = outermost wrapper.\n * If no handlers are registered, the callback is executed directly.\n */\n startSpan<T>(context: SpanContext, callback: () => Promise<T>): Promise<T> {\n if (_handlers.length === 0) return callback();\n\n // Chain: h1(ctx, () => h2(ctx, () => h3(ctx, () => callback())))\n return _handlers.reduceRight<() => Promise<T>>(\n (next, handler) => () => handler(context, next),\n callback,\n )();\n },\n\n /**\n * Register a span tracing handler.\n *\n * @param _event - Must be \"span\". Exists for API consistency with BeraMonitoring.\n * @param handler - A StartSpanFn, e.g. Sentry.startSpan.\n * @returns An unsubscribe function to remove the handler.\n */\n addSpanHandler(handler: StartSpanFn): Unsubscribe {\n _handlers.push(handler);\n return () => {\n const idx = _handlers.indexOf(handler);\n if (idx !== -1) _handlers.splice(idx, 1);\n };\n },\n};\n","import { BeraError, type IBeraErrorArgs } from \"./BeraError\";\n\nexport interface INotFoundErrorArgs extends IBeraErrorArgs {\n resource: string;\n id: string;\n chainId: number;\n}\n\n/**\n * Error thrown when a resource is not found.\n */\nexport class NotFoundError extends BeraError {\n /**\n * The name of the resource that was not found.\n *\n * @example \"Reward vault\"\n */\n resource: string;\n /**\n * The id of the resource that was not found.\n *\n * @example \"0x1234567890123456789012345678901234567890\"\n */\n id: string;\n\n constructor(args: INotFoundErrorArgs) {\n super(args);\n this.name = \"NotFoundError\";\n this.level = args.level ?? \"info\";\n this.message = `Resource ${args.resource} with id ${args.id} not found`;\n this.resource = args.resource;\n this.id = args.id;\n }\n}\n","import type { Hex } from \"@berachain-foundation/berancer-sdk\";\nimport type { Address, TransactionReceipt } from \"viem\";\n\nimport { BeraError, type IBeraErrorArgs } from \"./BeraError\";\n\n/**\n * This error is generally thrown by beraWriteContract when a transaction or simulation fails.\n */\nexport class TransactionFailedError extends BeraError {\n /**\n * The hash of the transaction that failed.\n *\n * Null if the error is due to a simulation failure.\n */\n txHash: string | null;\n\n /**\n * The receipt of the transaction that failed.\n *\n * Null if the error is due to a simulation failure.\n */\n receipt: TransactionReceipt | null;\n\n /**\n * The address of the contract that was called.\n */\n to: Address | undefined;\n\n /**\n * The data of the transaction that failed.\n */\n callData: Hex | undefined;\n\n /**\n * The block number of the transaction that failed.\n */\n blockNumber: bigint | null = null;\n\n /**\n * The input of the transaction that failed.\n */\n input: object;\n\n /**\n * The function name of the transaction that failed.\n */\n functionName: string | undefined;\n\n constructor(\n args: IBeraErrorArgs & {\n txHash?: string;\n receipt?: TransactionReceipt;\n to?: Address;\n blockNumber?: bigint;\n functionName?: string;\n input: object;\n },\n ) {\n super(args);\n this.name = \"TransactionFailedError\";\n this.txHash = args.txHash || null;\n this.receipt = args.receipt || null;\n this.to = args.to;\n this.functionName = args.functionName;\n this.blockNumber = args.blockNumber ?? null;\n this.input = args.input;\n\n if (this.receipt) {\n // If we have a receipt, transaction reverted on chain\n this.message = `Transaction reverted on chain for reason: ${this.reason}`;\n } else if (this.txHash) {\n // If we have a tx hash, transaction reverted after being broadcasted but we never got a receipt\n // Might happen for network reasons\n this.message = `Transaction reverted after being broadcasted for reason: ${this.reason}`;\n } else {\n this.message = `${this.reason}: ${this.message}`;\n }\n\n this.tags = {\n ...this.tags,\n \"operation.txn.status\": args.txHash ? \"execution\" : \"simulation\",\n ...args.tags,\n };\n\n if (this.to) {\n this.tags[\"operation.txn.to\"] = this.to;\n }\n\n if (this.functionName) {\n this.tags[\"operation.txn.functionName\"] = this.functionName;\n }\n }\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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; }var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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; }var _chunkC6ZGUO4Hcjs = require('./chunk-C6ZGUO4H.cjs');var _viem = require('viem');function k({cause:e,level:t}){if(e instanceof _viem.BaseError){let n=_chunkC6ZGUO4Hcjs.e.call(void 0, {error:e,revertIfUnknown:!1});if(n.isRequestError&&n.rootCause instanceof _viem.BaseError&&"url"in n.rootCause&&typeof n.rootCause.url=="string")return new (0, _chunkC6ZGUO4Hcjs.g)({cause:n.rootCause,response:void 0,endpoint:{url:n.rootCause.url,type:"rpc"},level:t})}return e instanceof _chunkC6ZGUO4Hcjs.f?e:new (0, _chunkC6ZGUO4Hcjs.f)({cause:e,level:t})}function c(e){return e!=null}function x({value:e,property:t,fn:r}){let n=r(e);if(!n.isValid)throw new (0, _chunkC6ZGUO4Hcjs.h)({property:t,value:e,expected:n.expectedType})}function s({value:e,property:t,fn:r}){x({value:e,property:t,fn:n=>{let l=c(n),{isValid:E,expectedType:v}=r(n);return{expectedType:v,isValid:l&&E}}})}function y(e,t){s({value:e,property:t,fn:r=>({expectedType:"defined",isValid:c(r)})})}function D(e,t="publicClient"){y(e,t)}function K(e,t){s({value:e,property:t,fn:r=>({expectedType:"Address",isValid:typeof r=="string"&&_viem.isAddress.call(void 0, r)})})}function M(e,t){s({value:e,property:t,fn:r=>({expectedType:"number",isValid:(typeof r=="string"||typeof r=="number")&&Number(r)>0})})}function f(){let e={};return{emit(t,...r){for(let n of e[t]||[])n(...r)},events:e,on(t,r){return e[t]||(e[t]=[]),e[t].push(r),()=>{e[t]=_optionalChain([e, 'access', _2 => _2[t], 'optionalAccess', _3 => _3.filter, 'call', _4 => _4(n=>r!==n)])}}}}var d=f(),_= exports.f ={captureException(e){let t={exception:e,timestamp:Date.now()};d.emit("exception",t)},on(...e){return d.on(...e)}};exports.a = k; exports.b = y; exports.c = D; exports.d = K; exports.e = M; exports.f = _;
|
|
2
|
+
//# sourceMappingURL=chunk-7LNBSOVV.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/chunk-7LNBSOVV.cjs","../src/errors/initBeraError.ts","../src/errors/assert.ts","../src/utils/createEmitter.ts","../src/errors/BeraMonitoring.ts"],"names":["initBeraError","error","level","BaseError","parsed","parseViemError","RequestError","BeraError","_isDefined","value","_assert","property","fn","result","InvalidArgumentError","_assertDefined","isDefined","isValid","expectedType","assertDefined","assertPublicClient","assertAddress","isAddress","assertAmount","createEmitter","events","event","args","callback","cb","i","_emitter","BeraMonitoring","exception"],"mappings":"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","file":"/Users/liammcaweeney/Work/bera/monobera/packages/berajs/dist/chunk-7LNBSOVV.cjs","sourcesContent":[null,"import { BaseError } from \"viem\";\n\nimport { BeraError } from \"./BeraError\";\nimport { parseViemError } from \"./parseViemError\";\nimport { RequestError } from \"./RequestError\";\nimport type { SeverityLevel } from \"./severity\";\n\n/**\n * The preferred way to normalize any unknown error into a BeraError.\n *\n * This function acts as a smart factory that picks the correct BeraError subclass:\n *\n * 1. If `cause` is already a `BeraError`, returns it as-is (no double-wrapping).\n * 2. If `cause` is a viem `BaseError`, runs `parseViemError` to classify it:\n * - If the root cause is an `HttpRequestError` (RPC transport failure), wraps it\n * in a `RequestError` with the endpoint URL extracted from the error.\n * 3. Otherwise, wraps in a new `BeraError` — which triggers the automatic reason\n * detection pipeline in the BeraError constructor (parseViemError → errorMap → displayMessage).\n *\n * **Use this instead of `new BeraError({ cause })` when you don't know the error type.**\n * It ensures RequestErrors are correctly classified (important for Sentry filtering\n * and fingerprinting — RequestErrors are skipped from transaction error grouping).\n *\n * @example\n * ```ts\n * try {\n * await someOperation();\n * } catch (error) {\n * // Normalizes to the right subclass, reason auto-detected\n * throw initBeraError({ cause: error });\n * }\n * ```\n *\n * @example\n * ```ts\n * // Reporting to Sentry without rethrowing\n * catch (error) {\n * captureException(initBeraError({ cause: error }));\n * }\n * ```\n */\nexport function initBeraError({\n cause: error,\n level,\n}: {\n cause: unknown;\n /**\n * The severity level of the error, only used if the error is not a BeraError.\n */\n level?: SeverityLevel;\n}): BeraError {\n // ── Step 1: Check if it's a viem BaseError that wraps an RPC transport failure ──\n // parseViemError with revertIfUnknown=false won't throw — it returns { reason: undefined }\n // if the error chain doesn't match any known type.\n if (error instanceof BaseError) {\n const parsed = parseViemError({\n error,\n revertIfUnknown: false,\n });\n if (\n parsed.isRequestError &&\n parsed.rootCause instanceof BaseError &&\n \"url\" in parsed.rootCause &&\n typeof parsed.rootCause.url === \"string\"\n ) {\n // RPC transport failure (e.g. HTTP 502 from the RPC endpoint).\n // Wrapping in RequestError gives it proper endpoint tagging and level=\"warning\".\n return new RequestError({\n cause: parsed.rootCause,\n response: undefined,\n endpoint: {\n url: parsed.rootCause.url as string,\n type: \"rpc\",\n },\n level,\n });\n }\n }\n\n // ── Step 2: Return as-is if already a BeraError, otherwise wrap ──────────\n // The BeraError constructor will run automatic reason detection on the cause.\n const err =\n error instanceof BeraError\n ? error\n : new BeraError({\n cause: error,\n level,\n });\n\n return err;\n}\n","import type { GetPublicClientReturnType } from \"@wagmi/core\";\nimport { type Address, isAddress, type PublicClient } from \"viem\";\n\nimport { InvalidArgumentError } from \"./InvalidArgumentError\";\n\nfunction _isDefined<T>(value: T): value is NonNullable<T> {\n return value !== undefined && value !== null;\n}\n\ntype _AssertFn<T> = (value: T) => { expectedType: string; isValid: boolean };\n\n/**\n * Internal assertion function.\n * @throws An InvalidArgumentError if the value is not valid.\n */\nfunction _assert<T>({\n value,\n property,\n fn,\n}: {\n value: T;\n property: string;\n fn: _AssertFn<T>;\n}) {\n const result = fn(value);\n if (!result.isValid) {\n throw new InvalidArgumentError({\n property,\n value,\n expected: result.expectedType,\n });\n }\n}\n\nfunction _assertDefined<T>({\n value,\n property,\n fn,\n}: {\n value: T;\n property: string;\n fn: (value: T) => { expectedType: string; isValid: boolean };\n}) {\n _assert({\n value,\n property,\n fn: (value) => {\n const isDefined = _isDefined(value);\n const { isValid, expectedType } = fn(value);\n return {\n expectedType,\n isValid: isDefined && isValid,\n };\n },\n });\n}\n\n/**\n * Asserts that a value is defined.\n * @throws An InvalidArgumentError if the value is undefined or null.\n */\nexport function assertDefined<T>(\n /**\n * The value to assert.\n */\n value: T,\n /**\n * The property name.\n */\n property: string,\n): asserts value is NonNullable<T> {\n _assertDefined({\n value,\n property,\n fn: (value) => ({ expectedType: \"defined\", isValid: _isDefined(value) }),\n });\n}\n\n/**\n * Asserts that a value is a PublicClient.\n * @throws An InvalidArgumentError if the value is undefined or not a PublicClient.\n */\nexport function assertPublicClient(\n /**\n * The value to assert.\n */\n value: // it's important to have both types here because it helps with typescript build performance\n PublicClient | GetPublicClientReturnType | undefined,\n /**\n * The property name.\n */\n property: string = \"publicClient\",\n): asserts value is PublicClient {\n // there's no current way to check if a value is a PublicClient, so we just assert it's defined and `value: PublicClient` will do the rest\n assertDefined(value, property);\n}\n\n/**\n * Asserts that a value is an address (20 bytes).\n * @throws An InvalidArgumentError if the value is undefined, null, not a string, or not an address.\n */\nexport function assertAddress(\n /**\n * The value to assert.\n */\n value: string | undefined | null,\n /**\n * The property name.\n */\n property: string,\n): asserts value is Address {\n _assertDefined({\n value,\n property,\n fn: (value) => ({\n expectedType: \"Address\",\n isValid: typeof value === \"string\" && isAddress(value),\n }),\n });\n}\n\n/**\n * Asserts that a value is a number greater than 0.\n * @throws An InvalidArgumentError if the value is undefined, null, not a string or number, or not a number greater than 0.\n */\nexport function assertAmount(\n /**\n * The value to assert.\n */\n value: unknown,\n /**\n * The property name.\n */\n property: string,\n): asserts value is string | number {\n _assertDefined({\n value,\n property,\n fn: (value) => ({\n expectedType: \"number\",\n isValid:\n (typeof value === \"string\" || typeof value === \"number\") &&\n Number(value) > 0,\n }),\n });\n}\n","interface EventsMap {\n [event: string]: any;\n}\n\ninterface DefaultEvents extends EventsMap {\n [event: string]: (...args: any) => void;\n}\n\nexport type Unsubscribe = () => void;\n\nexport interface Emitter<Events extends EventsMap = DefaultEvents> {\n /**\n * Calls each of the listeners registered for a given event.\n *\n * ```js\n * ee.emit('tick', tickType, tickDuration)\n * ```\n *\n * @param event The event name.\n * @param args The arguments for listeners.\n */\n emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): void;\n\n /**\n * Add a listener for a given event.\n *\n * ```js\n * const unbind = ee.on('tick', (tickType, tickDuration) => {\n * count += 1\n * })\n *\n * disable () {\n * unbind()\n * }\n * ```\n *\n * @param event The event name.\n * @param cb The listener function.\n * @returns Unbind listener from event.\n */\n on<K extends keyof Events>(event: K, cb: Events[K]): Unsubscribe;\n events: Partial<{ [E in keyof Events]: Events[E][] }>;\n}\n\n/**\n * An interface for mixins that expose the `on` function (without the emitter\n * bound to `this`)\n *\n * ```js\n * import { createEmitter } from '~utils/createEmitter'\n *\n * class Ticker implements EmitterMixin<Events> {\n * constructor() {\n * this.emitter = createEmitter()\n * }\n * on(...args) {\n * return this.emitter.on(...args)\n * }\n * tick() {\n * this.emitter.emit('tick')\n * }\n * }\n * ```\n */\nexport interface EmitterMixin<Events extends EventsMap = DefaultEvents> {\n on<K extends keyof Events>(event: K, cb: Events[K]): Unsubscribe;\n}\n\n/**\n * Create event emitter.\n *\n * ```js\n * import { createEmitter } from '~/utils/createEmitter'\n *\n * class Ticker {\n * constructor() {\n * this.emitter = createEmitter()\n * }\n * on(...args) {\n * return this.emitter.on(...args)\n * }\n * tick() {\n * this.emitter.emit('tick')\n * }\n * }\n * ```\n *\n * Inspired by {@link https://github.com/ai/nanoevents}\n */\nexport function createEmitter<\n Events extends EventsMap = DefaultEvents,\n>(): Emitter<Events> {\n /**\n * Event names in keys and arrays with listeners in values.\n *\n * ```js\n * emitter1.events = emitter2.events\n * emitter2.events = { }\n * ```\n */\n const events: Partial<{ [E in keyof Events]: Events[E][] }> = {};\n\n return {\n emit(event, ...args) {\n for (const callback of events[event] || []) {\n callback(...args);\n }\n },\n events,\n on(event, cb) {\n if (!events[event]) {\n events[event] = [];\n }\n\n events[event].push(cb);\n\n return () => {\n events[event] = events[event]?.filter((i) => cb !== i);\n };\n },\n };\n}\n","import { createEmitter, type EmitterMixin } from \"~/utils/createEmitter\";\nimport type { BeraError } from \"./BeraError\";\nimport type { SeverityLevel } from \"./severity\";\n\n/**\n * Context passed alongside captured exceptions.\n * Mirrors the subset of Sentry's CaptureContext that berajs actually uses.\n */\nexport interface CaptureContext {\n level: SeverityLevel;\n extra?: Record<string, unknown>;\n tags?: Record<string, string | number | boolean | null | undefined>;\n fingerprint?: string[];\n data?: Record<string, unknown>;\n}\n\nexport interface ErrorEvent {\n exception: BeraError;\n timestamp: number;\n}\n\nconst _emitter = createEmitter<{ exception: (event: ErrorEvent) => void }>();\n\n/**\n * A generic error reporter for berajs.\n *\n * Instead of calling Sentry.captureException directly, berajs calls\n * `BeraMonitoring.captureException()`. Consumer apps subscribe via `.on()` and\n * forward events to their monitoring provider (Sentry, Datadog, etc.).\n *\n * @example\n * ```ts\n * // In berajs code:\n * import { BeraMonitoring } from \"~/errors/BeraMonitoring\";\n * BeraMonitoring.captureExceptionException(error);\n *\n * // In app instrumentation:\n * import { BeraMonitoring } from \"@berachain/berajs/errors\";\n * BeraMonitoring.on((event) => {\n * if (event.type === \"exception\") {\n * Sentry.captureException(event.exception);\n * }\n * });\n * ```\n */\nexport const BeraMonitoring: {\n captureException: (exception: BeraError) => void;\n} & EmitterMixin<{ exception: (event: ErrorEvent) => void }> = {\n /**\n * Capture an exception. Notifies all subscribers.\n */\n captureException(exception: BeraError): void {\n const event: ErrorEvent = {\n exception,\n timestamp: Date.now(),\n };\n _emitter.emit(\"exception\", event);\n },\n /**\n * Subscribe to error events.\n * @returns An unsubscribe function.\n */\n on(...args) {\n return _emitter.on(...args);\n },\n};\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as p}from"./chunk-NAXAZJJY.mjs";import{b as r,c as b,d as u}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as p}from"./chunk-NAXAZJJY.mjs";import{b as r,c as b,d as u}from"./chunk-2LL3P5PN.mjs";import{a as g,e as d}from"./chunk-THATXCJK.mjs";import{EnsoClient as h}from"@ensofinance/sdk";import{appConfig as k}from"@berachain/config/internal";var T=process.env.NODE_ENV!=="development"&&process.env.NODE_ENV!=="test";function U({useProxy:e=T,...n}={}){let{config:a}=g(n);return new h({baseURL:e?`${a.bex.aggregatorsProxyUrl}/enso/api/v1/`:void 0,apiKey:e?"":k.apiKeys.public.enso})}import{getChainId as w,getPublicClient as E}from"@wagmi/core";import{erc20Abi as P,formatUnits as v,isAddress as x}from"viem";function N({token:e,account:n,multicallAddress:a}){return d(e,"BERA")||d(e,"ETH")?{address:a,abi:p,functionName:"getEthBalance",args:[n]}:{address:e.address,abi:P,functionName:"balanceOf",args:[n]}}async function _({account:e,tokenList:n,wagmiConfig:a}){if(r(a,"config"),!e||!n)throw new Error("account or tokenList is not defined");u(e,"account");let C=n.filter(t=>x(t.address)),B=Object.groupBy(C,t=>t.chainId??w(a));return(await Promise.allSettled(Object.entries(B).map(async([t,o])=>{r(o,"tokens");let s=E(a,{chainId:Number(t)});b(s,`publicClient ${t}`),r(s.chain,"publicClient.chain"),r(s.chain.contracts,"publicClient.chain.contracts"),r(s.chain.contracts.multicall3,"publicClient.chain.contracts.multicall3");let{multicall3:c}=s.chain.contracts,f=typeof c=="string"?c:c.address;u(f,"multicall3Address");let A=o.map(i=>N({token:i,account:e,multicallAddress:f}));return(await s.multicall({contracts:A})).map((i,y)=>{let l=o[y];if(i.error)return{...l,balance:{raw:"0",formatted:"0"}};let m=v(i.result,l?.decimals||18);return{...l,balance:{raw:i.result.toString(),formatted:m.includes("e")?"0":m}}})}))).flatMap(t=>t.status==="fulfilled"?t.value:[])}export{U as a,N as b,_ as c};
|
|
2
|
+
//# sourceMappingURL=chunk-7SMWQ6SN.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{f as n}from"./chunk-AX2YQQFQ.mjs";var r=[],c={startSpan(e,t){return r.length===0?t():r.reduceRight((o,a)=>()=>a(e,o),t)()},addSpanHandler(e){return r.push(e),()=>{let t=r.indexOf(e);t!==-1&&r.splice(t,1)}}};var i=class extends n{resource;id;constructor(t){super(t),this.name="NotFoundError",this.level=t.level??"info",this.message=`Resource ${t.resource} with id ${t.id} not found`,this.resource=t.resource,this.id=t.id}};var s=class extends n{txHash;receipt;to;callData;blockNumber=null;input;functionName;constructor(t){super(t),this.name="TransactionFailedError",this.txHash=t.txHash||null,this.receipt=t.receipt||null,this.to=t.to,this.functionName=t.functionName,this.blockNumber=t.blockNumber??null,this.input=t.input,this.receipt?this.message=`Transaction reverted on chain for reason: ${this.reason}`:this.txHash?this.message=`Transaction reverted after being broadcasted for reason: ${this.reason}`:this.message=`${this.reason}: ${this.message}`,this.tags={...this.tags,"operation.txn.status":t.txHash?"execution":"simulation",...t.tags},this.to&&(this.tags["operation.txn.to"]=this.to),this.functionName&&(this.tags["operation.txn.functionName"]=this.functionName)}};export{c as a,i as b,s as c};
|
|
2
|
+
//# sourceMappingURL=chunk-7WRTK7RJ.mjs.map
|