@berachain/berajs 0.2.8-beta.9 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/dist/{BeraError-_mQdkanr.d.cts → BeraError-7-A5JYy_.d.ts} +31 -2
  2. package/dist/{HoneyConfigProvider-DVP_9KZn.d.ts → HoneyConfigProvider-Dkj-_a5x.d.ts} +1 -1
  3. package/dist/{RequestError-BRIiJgHk.d.ts → RequestError-DBOIV65x.d.ts} +1 -1
  4. package/dist/abi/exports.mjs +4452 -2
  5. package/dist/actions/clients/exports.d.ts +78 -0
  6. package/dist/actions/clients/exports.mjs +21 -0
  7. package/dist/actions/exports.d.ts +154 -207
  8. package/dist/actions/exports.mjs +853 -2
  9. package/dist/actions/governance/exports.d.ts +140 -0
  10. package/dist/actions/governance/exports.mjs +226 -0
  11. package/dist/actions/server/exports.d.ts +13 -0
  12. package/dist/actions/server/exports.mjs +27 -0
  13. package/dist/chunk-3JJLQ2JX.mjs +211 -0
  14. package/dist/chunk-7YVNSDXG.mjs +86 -0
  15. package/dist/chunk-AUOPN6NK.mjs +96 -0
  16. package/dist/chunk-BGMRHTBQ.mjs +23 -0
  17. package/dist/chunk-CDK4YV3D.mjs +571 -0
  18. package/dist/chunk-DKMAIU74.mjs +62 -0
  19. package/dist/chunk-DQRH5VE3.mjs +25 -0
  20. package/dist/chunk-E7YFXBBQ.mjs +349 -0
  21. package/dist/chunk-GUURQAME.mjs +326 -0
  22. package/dist/chunk-GY6B3PD5.mjs +89 -0
  23. package/dist/chunk-HQCOU6GY.mjs +243 -0
  24. package/dist/chunk-HYDP32P6.mjs +135 -0
  25. package/dist/chunk-IXIBY5FP.mjs +80 -0
  26. package/dist/chunk-KHXJDYA4.mjs +1776 -0
  27. package/dist/chunk-NBYLMO2L.mjs +14 -0
  28. package/dist/chunk-O2NQFKJK.mjs +170 -0
  29. package/dist/chunk-P5WXXULM.mjs +54 -0
  30. package/dist/chunk-QBBOWFMH.mjs +4129 -0
  31. package/dist/chunk-QVHEM4BG.mjs +35 -0
  32. package/dist/chunk-SGIJVHZO.mjs +12 -0
  33. package/dist/chunk-SZ5C44L5.mjs +35 -0
  34. package/dist/chunk-WNBWX23Q.mjs +426 -0
  35. package/dist/chunk-Y6THHG77.mjs +126 -0
  36. package/dist/chunk-ZLTMIFCZ.mjs +165 -0
  37. package/dist/contexts/exports.d.ts +2 -2
  38. package/dist/contexts/exports.mjs +85 -2
  39. package/dist/enum/exports.d.ts +1 -1
  40. package/dist/enum/exports.mjs +46 -2
  41. package/dist/enum/governance/exports.d.ts +60 -0
  42. package/dist/enum/governance/exports.mjs +14 -0
  43. package/dist/errors/exports.d.ts +4 -3
  44. package/dist/errors/exports.mjs +48 -2
  45. package/dist/getApolloClient-BcUTGFUb.d.ts +40 -0
  46. package/dist/{getValidatorQueuedOperatorAddress-BcyxE9uw.d.ts → getValidatorQueuedOperatorAddress-DphU3qhE.d.ts} +2 -2
  47. package/dist/{global.d-5w_lvl2J.d.ts → global.d-BuGDKh4k.d.ts} +4 -240
  48. package/dist/hooks/exports.d.ts +83 -226
  49. package/dist/hooks/exports.mjs +7463 -4
  50. package/dist/hooks/governance/exports.d.ts +181 -0
  51. package/dist/hooks/governance/exports.mjs +888 -0
  52. package/dist/pol.d-Dw5SQcRX.d.ts +153 -0
  53. package/dist/{txnEnum-7_o92X3N.d.cts → txnEnum-ByI5dtDi.d.ts} +2 -60
  54. package/dist/types/exports.d.ts +9 -9
  55. package/dist/types/exports.mjs +0 -1
  56. package/dist/types/governance/exports.d.ts +109 -0
  57. package/dist/types/governance/exports.mjs +0 -0
  58. package/dist/{useHoneySwapState-B494PQDl.d.ts → useHoneySwapState-vFmuFF0g.d.ts} +1 -1
  59. package/dist/utils/exports.d.ts +15 -6
  60. package/dist/utils/exports.mjs +827 -2
  61. package/package.json +49 -13
  62. package/src/actions/__test/transports.ts +61 -0
  63. package/src/actions/clients/exports.ts +7 -0
  64. package/src/actions/clients/fetchBeep.ts +34 -0
  65. package/src/actions/clients/fetchOpenApi.ts +93 -0
  66. package/src/actions/clients/fetchOpenApi.unit.test.ts +223 -0
  67. package/src/actions/clients/fetchRailwayBackend.ts +34 -0
  68. package/src/actions/clients/getApolloClient.ts +58 -23
  69. package/src/actions/clients/getEnsoClient.ts +20 -9
  70. package/src/actions/dex/aggregators/enso/enso.ts +27 -17
  71. package/src/actions/dex/aggregators/enso/ensoErc4626.ts +2 -2
  72. package/src/actions/dex/aggregators/kyberswap.ts +18 -23
  73. package/src/actions/enso/__tests__/getEnsoUserTokensWithBalances.debug.test.ts +3 -6
  74. package/src/actions/enso/getEnsoUserTokensWithBalances.ts +18 -0
  75. package/src/actions/exports.ts +5 -9
  76. package/src/actions/governance/exports.ts +9 -0
  77. package/src/actions/governance/getAllProposals.ts +10 -65
  78. package/src/actions/governance/getProposalDetails.ts +6 -33
  79. package/src/actions/governance/getProposalVotes.ts +8 -15
  80. package/src/actions/honey/getChartData.ts +27 -21
  81. package/src/actions/honey/getHoney24hVolume.ts +19 -22
  82. package/src/actions/honey/getPythLatestPrices.ts +7 -0
  83. package/src/actions/pol/__tests__/rewardVaults.integration.test.ts +1 -1
  84. package/src/actions/pol/getAutoclaimedIncentives.ts +41 -0
  85. package/src/actions/pol/getAutoclaimedIncentivesTxHash.ts +41 -0
  86. package/src/actions/pol/getBeraTokenTotalSupply.ts +45 -0
  87. package/src/actions/pol/getBgtIncentiveDistributorPaused.ts +28 -0
  88. package/src/actions/pol/getEarnedStakedBeraVault.ts +20 -20
  89. package/src/actions/pol/getGlobalData.ts +1 -0
  90. package/src/actions/pol/getHeroEarnVaults.ts +62 -0
  91. package/src/actions/pol/getIncentiveFeeClaimStats.ts +19 -38
  92. package/src/actions/pol/getRewardVaults.ts +4 -4
  93. package/src/actions/pol/getSWBeraVaultMetadata.ts +1 -1
  94. package/src/actions/pol/getStakingDailyAssets.ts +18 -17
  95. package/src/actions/server/exports.ts +1 -0
  96. package/src/actions/server/getDailyValidatorBlockStats.ts +33 -0
  97. package/src/actions/tokens/getWalletBalances.integration.test.ts +3 -6
  98. package/src/actions/transactions/beraWriteContract.integration.test.ts +3 -6
  99. package/src/actions/validators/getDailyValidatorBlockStats.ts +25 -24
  100. package/src/actions/validators/getValidatorAnalytics.ts +20 -21
  101. package/src/actions/validators/getValidatorIncentiveDistribution.ts +33 -0
  102. package/src/actions/validators/utils/getValidatorBoostApy.ts +1 -1
  103. package/src/enum/contracts.ts +1 -0
  104. package/src/enum/exports.ts +0 -1
  105. package/src/enum/governance/exports.ts +1 -0
  106. package/src/errors/BeraError.ts +47 -7
  107. package/src/errors/BeraTracing.unit.test.ts +65 -0
  108. package/src/errors/RequestError.ts +25 -4
  109. package/src/errors/RequestError.unit.test.ts +55 -0
  110. package/src/errors/errorMap.ts +8 -0
  111. package/src/errors/exports.ts +5 -0
  112. package/src/errors/getRevertReason.integration.test.ts +3 -3
  113. package/src/errors/spanStatus.ts +78 -0
  114. package/src/errors/spanStatus.unit.test.ts +62 -0
  115. package/src/hooks/dex/useCreatePool.ts +1 -88
  116. package/src/hooks/dex/useOnChainPoolData.ts +27 -2
  117. package/src/hooks/dex/usePriceImpact.ts +12 -5
  118. package/src/hooks/enso/useBendDemultiply.ts +9 -1
  119. package/src/hooks/enso/useBendMultiply.ts +9 -1
  120. package/src/hooks/enso/useBendZapSupply.ts +26 -7
  121. package/src/hooks/enso/useEnsoSwapBundle.ts +17 -3
  122. package/src/hooks/enso/useEnsoUserTokensWithBalances.ts +13 -2
  123. package/src/hooks/exports.ts +3 -15
  124. package/src/hooks/governance/exports.ts +14 -0
  125. package/src/hooks/pol/useAutoclaimedIncentives.ts +40 -0
  126. package/src/hooks/pol/useAutoclaimedIncentivesTxHash.ts +45 -0
  127. package/src/hooks/pol/useStakedAPR.ts +2 -2
  128. package/src/hooks/pol/useStakedSnapshots.ts +5 -9
  129. package/src/hooks/validators/useValidator.ts +6 -8
  130. package/src/hooks/validators/useValidatorIncentiveDistribution.ts +39 -0
  131. package/src/types/bribe-boost.d.ts +19 -0
  132. package/src/types/exports.ts +0 -1
  133. package/src/types/governance/exports.ts +1 -0
  134. package/src/utils/beraFetch.ts +9 -3
  135. package/src/utils/exports.ts +1 -0
  136. package/src/utils/getServerSideClient.ts +4 -2
  137. package/src/utils/polyfillAbortSignalAny.ts +53 -0
  138. package/src/utils/polyfillAbortSignalAny.unit.test.ts +81 -0
  139. package/src/utils/sanitizeRpcUrl.ts +22 -0
  140. package/src/utils/tracedTransport.ts +35 -0
  141. package/dist/BeraError-_mQdkanr.d.ts +0 -94
  142. package/dist/BexStatusProvider-DRymVlQf.d.cts +0 -70
  143. package/dist/HoneyConfigProvider-DfkjmzEf.d.cts +0 -390
  144. package/dist/RequestError-DSUzJ1Iy.d.cts +0 -144
  145. package/dist/abi/exports.cjs +0 -2
  146. package/dist/abi/exports.cjs.map +0 -1
  147. package/dist/abi/exports.d.cts +0 -6574
  148. package/dist/abi/exports.mjs.map +0 -1
  149. package/dist/actions/exports.cjs +0 -2
  150. package/dist/actions/exports.cjs.map +0 -1
  151. package/dist/actions/exports.d.cts +0 -1650
  152. package/dist/actions/exports.mjs.map +0 -1
  153. package/dist/chunk-45HIEVNI.cjs +0 -4
  154. package/dist/chunk-45HIEVNI.cjs.map +0 -1
  155. package/dist/chunk-47ILYVHC.mjs +0 -2
  156. package/dist/chunk-47ILYVHC.mjs.map +0 -1
  157. package/dist/chunk-575OK77P.mjs +0 -2
  158. package/dist/chunk-575OK77P.mjs.map +0 -1
  159. package/dist/chunk-5NVZG5N6.mjs +0 -2
  160. package/dist/chunk-5NVZG5N6.mjs.map +0 -1
  161. package/dist/chunk-6DIA6PXV.cjs +0 -2
  162. package/dist/chunk-6DIA6PXV.cjs.map +0 -1
  163. package/dist/chunk-6JJIZCVY.cjs +0 -2
  164. package/dist/chunk-6JJIZCVY.cjs.map +0 -1
  165. package/dist/chunk-7F72ZH4Q.mjs +0 -2
  166. package/dist/chunk-7F72ZH4Q.mjs.map +0 -1
  167. package/dist/chunk-AUA42YIG.mjs +0 -4
  168. package/dist/chunk-AUA42YIG.mjs.map +0 -1
  169. package/dist/chunk-BC2WX6O6.cjs +0 -2
  170. package/dist/chunk-BC2WX6O6.cjs.map +0 -1
  171. package/dist/chunk-CJOZC5Z2.cjs +0 -2
  172. package/dist/chunk-CJOZC5Z2.cjs.map +0 -1
  173. package/dist/chunk-D6L7LTA2.cjs +0 -2
  174. package/dist/chunk-D6L7LTA2.cjs.map +0 -1
  175. package/dist/chunk-DDEQFR3M.cjs +0 -2
  176. package/dist/chunk-DDEQFR3M.cjs.map +0 -1
  177. package/dist/chunk-GXV2JA36.mjs +0 -2
  178. package/dist/chunk-GXV2JA36.mjs.map +0 -1
  179. package/dist/chunk-ISYNEDET.mjs +0 -2
  180. package/dist/chunk-ISYNEDET.mjs.map +0 -1
  181. package/dist/chunk-JDDRTHFG.mjs +0 -2
  182. package/dist/chunk-JDDRTHFG.mjs.map +0 -1
  183. package/dist/chunk-JDZGYU5T.mjs +0 -2
  184. package/dist/chunk-JDZGYU5T.mjs.map +0 -1
  185. package/dist/chunk-LVOXBZMA.cjs +0 -2
  186. package/dist/chunk-LVOXBZMA.cjs.map +0 -1
  187. package/dist/chunk-MK5NS5B5.mjs +0 -2
  188. package/dist/chunk-MK5NS5B5.mjs.map +0 -1
  189. package/dist/chunk-NAXAZJJY.mjs +0 -2
  190. package/dist/chunk-NAXAZJJY.mjs.map +0 -1
  191. package/dist/chunk-NLVWRMGD.mjs +0 -2
  192. package/dist/chunk-NLVWRMGD.mjs.map +0 -1
  193. package/dist/chunk-OGBD5YOG.mjs +0 -2
  194. package/dist/chunk-OGBD5YOG.mjs.map +0 -1
  195. package/dist/chunk-OGJMSGB2.mjs +0 -2
  196. package/dist/chunk-OGJMSGB2.mjs.map +0 -1
  197. package/dist/chunk-OIYXOKTT.cjs +0 -2
  198. package/dist/chunk-OIYXOKTT.cjs.map +0 -1
  199. package/dist/chunk-OUD27MU7.cjs +0 -2
  200. package/dist/chunk-OUD27MU7.cjs.map +0 -1
  201. package/dist/chunk-PRLVZIKD.mjs +0 -2
  202. package/dist/chunk-PRLVZIKD.mjs.map +0 -1
  203. package/dist/chunk-Q2SNRLW3.cjs +0 -2
  204. package/dist/chunk-Q2SNRLW3.cjs.map +0 -1
  205. package/dist/chunk-REWME3FY.cjs +0 -2
  206. package/dist/chunk-REWME3FY.cjs.map +0 -1
  207. package/dist/chunk-RJN36GBU.mjs +0 -2
  208. package/dist/chunk-RJN36GBU.mjs.map +0 -1
  209. package/dist/chunk-RWOICHRW.cjs +0 -2
  210. package/dist/chunk-RWOICHRW.cjs.map +0 -1
  211. package/dist/chunk-S4CDSVLK.cjs +0 -2
  212. package/dist/chunk-S4CDSVLK.cjs.map +0 -1
  213. package/dist/chunk-SFEULGSX.cjs +0 -2
  214. package/dist/chunk-SFEULGSX.cjs.map +0 -1
  215. package/dist/chunk-WBTS6KFG.mjs +0 -2
  216. package/dist/chunk-WBTS6KFG.mjs.map +0 -1
  217. package/dist/chunk-WRFDB3QJ.cjs +0 -2
  218. package/dist/chunk-WRFDB3QJ.cjs.map +0 -1
  219. package/dist/chunk-XNJLSA6P.cjs +0 -2
  220. package/dist/chunk-XNJLSA6P.cjs.map +0 -1
  221. package/dist/contexts/exports.cjs +0 -2
  222. package/dist/contexts/exports.cjs.map +0 -1
  223. package/dist/contexts/exports.d.cts +0 -66
  224. package/dist/contexts/exports.mjs.map +0 -1
  225. package/dist/defaultFlags-D6KfkTZx.d.cts +0 -10
  226. package/dist/dex-C_BB0b0O.d.cts +0 -37
  227. package/dist/enum/exports.cjs +0 -2
  228. package/dist/enum/exports.cjs.map +0 -1
  229. package/dist/enum/exports.d.cts +0 -23
  230. package/dist/enum/exports.mjs.map +0 -1
  231. package/dist/errors/exports.cjs +0 -2
  232. package/dist/errors/exports.cjs.map +0 -1
  233. package/dist/errors/exports.d.cts +0 -327
  234. package/dist/errors/exports.mjs.map +0 -1
  235. package/dist/getValidatorQueuedOperatorAddress-Cql_D50j.d.cts +0 -562
  236. package/dist/global.d-B7IeayVX.d.cts +0 -474
  237. package/dist/honey-CYm0RWf4.d.cts +0 -14
  238. package/dist/hooks/exports.cjs +0 -4
  239. package/dist/hooks/exports.cjs.map +0 -1
  240. package/dist/hooks/exports.d.cts +0 -1734
  241. package/dist/hooks/exports.mjs.map +0 -1
  242. package/dist/polling-BKnyavLI.d.cts +0 -8
  243. package/dist/txnEnum-7_o92X3N.d.ts +0 -164
  244. package/dist/types/exports.cjs +0 -1
  245. package/dist/types/exports.cjs.map +0 -1
  246. package/dist/types/exports.d.cts +0 -90
  247. package/dist/types/exports.mjs.map +0 -1
  248. package/dist/useHoneySwapState-D6vpv19r.d.cts +0 -32
  249. package/dist/utils/exports.cjs +0 -2
  250. package/dist/utils/exports.cjs.map +0 -1
  251. package/dist/utils/exports.d.cts +0 -420
  252. package/dist/utils/exports.mjs.map +0 -1
  253. package/src/actions/dex/getIsTokenExploited.ts +0 -63
  254. package/src/hooks/dex/useExploitedTokens.ts +0 -57
@@ -0,0 +1,4129 @@
1
+ import {
2
+ fetchBeep,
3
+ fetchRailwayBackend
4
+ } from "./chunk-P5WXXULM.mjs";
5
+ import {
6
+ getApolloClient
7
+ } from "./chunk-3JJLQ2JX.mjs";
8
+ import {
9
+ pythAbi
10
+ } from "./chunk-CDK4YV3D.mjs";
11
+ import {
12
+ NotFoundError,
13
+ TransactionFailedError
14
+ } from "./chunk-AUOPN6NK.mjs";
15
+ import {
16
+ BeraMonitoring,
17
+ initBeraError
18
+ } from "./chunk-7YVNSDXG.mjs";
19
+ import {
20
+ assertAddress,
21
+ assertDefined,
22
+ assertPublicClient
23
+ } from "./chunk-GY6B3PD5.mjs";
24
+ import {
25
+ CAP_LIMIT_BUFFER,
26
+ DEFAULT_METAMASK_GAS_LIMIT,
27
+ bignumber_js_default,
28
+ formatTimeLeft,
29
+ getPythDefaultUpdateFee,
30
+ getSafeNumber,
31
+ getTestClient,
32
+ msToSeconds,
33
+ seconds,
34
+ yearsInSeconds
35
+ } from "./chunk-E7YFXBBQ.mjs";
36
+ import {
37
+ beraFetch,
38
+ beraFetchJson,
39
+ getErrorResponse
40
+ } from "./chunk-Y6THHG77.mjs";
41
+ import {
42
+ beraToken,
43
+ getHoneyToken,
44
+ isToken
45
+ } from "./chunk-IXIBY5FP.mjs";
46
+ import {
47
+ parseBaseArgs
48
+ } from "./chunk-DQRH5VE3.mjs";
49
+ import {
50
+ RequestError
51
+ } from "./chunk-ZLTMIFCZ.mjs";
52
+ import {
53
+ BeraError,
54
+ InvalidArgumentError,
55
+ commonAbiErrors,
56
+ parseDecodedError,
57
+ parseViemError
58
+ } from "./chunk-KHXJDYA4.mjs";
59
+
60
+ // src/actions/bend/getConvertToAssets.ts
61
+ import { formatEther } from "viem";
62
+ import { metaMorphoV11Abi as metaMorphoAbi } from "@berachain/abis/bend-metamorpho/metaMorphoV11";
63
+ async function getConvertToAssets({
64
+ sharesAmount,
65
+ vaultAddress,
66
+ publicClient
67
+ }) {
68
+ const convertToAssets = await publicClient.readContract({
69
+ address: vaultAddress,
70
+ abi: metaMorphoAbi,
71
+ functionName: "convertToAssets",
72
+ args: [sharesAmount]
73
+ });
74
+ return { raw: convertToAssets, formatted: formatEther(convertToAssets) };
75
+ }
76
+
77
+ // src/actions/dex/aggregators/base.ts
78
+ import { formatUnits, isAddress, zeroAddress } from "viem";
79
+ var BaseAggregator = class _BaseAggregator {
80
+ static PATH_NOT_FOUND_REASON = "NO_SWAP_PATHS";
81
+ needsAccountForQuote = false;
82
+ notFoundMessages = [];
83
+ config;
84
+ chainId;
85
+ constructor(args = {}) {
86
+ const { config, chainId } = parseBaseArgs(args);
87
+ this.config = config;
88
+ this.chainId = chainId;
89
+ }
90
+ /**
91
+ * Identifies the url of the last sent request. Might not have all query params.
92
+ * Mainly used for error reporting.
93
+ */
94
+ url = "";
95
+ /**
96
+ * return wbera for native tokens to accomodate the aggregator's router logic
97
+ */
98
+ parseAddresses(tokenIn, tokenOut) {
99
+ if (!isAddress(tokenIn) || !isAddress(tokenOut)) {
100
+ throw new BeraError({
101
+ message: `Invalid address: ${tokenIn} or ${tokenOut}`,
102
+ level: "error"
103
+ });
104
+ }
105
+ return {
106
+ tokenInAddress: isToken(tokenIn, "BERA") ? this.config.tokens.wbera : tokenIn,
107
+ tokenOutAddress: isToken(tokenOut, "BERA") ? this.config.tokens.wbera : tokenOut,
108
+ isTokenInNative: isToken(tokenIn, "BERA"),
109
+ isTokenOutNative: isToken(tokenOut, "BERA")
110
+ };
111
+ }
112
+ /**
113
+ * Calculate input amount after fees.
114
+ *
115
+ * @returns Amount in wad format
116
+ */
117
+ getAmountAfterFees(amount, aggregatorsFeeBps) {
118
+ if (aggregatorsFeeBps === void 0) {
119
+ throw new BeraError({
120
+ message: "aggregatorsFeeBps is required",
121
+ level: "error"
122
+ });
123
+ }
124
+ const fees = new bignumber_js_default(amount).times(aggregatorsFeeBps).dividedBy(1e4).toFixed(0, bignumber_js_default.ROUND_DOWN);
125
+ return new bignumber_js_default(amount).minus(fees).toFixed(0, bignumber_js_default.ROUND_DOWN);
126
+ }
127
+ /**
128
+ * Formats input data for aggregator swaps
129
+ */
130
+ getInputData({
131
+ tokenIn,
132
+ amountIn,
133
+ isNative,
134
+ isPermit2Approval = false,
135
+ permit2SpenderAddress
136
+ }) {
137
+ return {
138
+ tokenIn,
139
+ amountIn: BigInt(amountIn),
140
+ isNative,
141
+ isPermit2Approval,
142
+ permit2SpenderAddress: permit2SpenderAddress ?? zeroAddress
143
+ };
144
+ }
145
+ /**
146
+ * Calculate min amount out
147
+ */
148
+ getMinAmountOut(amountOut, slippage) {
149
+ if (slippage === void 0) {
150
+ throw new BeraError({
151
+ message: "slippage is required",
152
+ level: "error"
153
+ });
154
+ }
155
+ const minAmountOut = new bignumber_js_default(amountOut).times(1 - slippage / 100);
156
+ if (minAmountOut.isNaN() || minAmountOut.isZero()) {
157
+ return 0n;
158
+ }
159
+ return BigInt(minAmountOut.toFixed(0));
160
+ }
161
+ parseAllowanceRequirements({
162
+ tokenIn,
163
+ rawAmount,
164
+ spender
165
+ }) {
166
+ return isToken(tokenIn, "BERA") ? [] : [
167
+ {
168
+ token: tokenIn,
169
+ amount: {
170
+ raw: rawAmount,
171
+ formatted: formatUnits(BigInt(rawAmount), tokenIn.decimals)
172
+ },
173
+ spender
174
+ }
175
+ ];
176
+ }
177
+ /**
178
+ * Check if chain is supported
179
+ */
180
+ checkChainSupport({
181
+ tokenIn,
182
+ tokenOut
183
+ }) {
184
+ if (this.supportedChains === null) {
185
+ return true;
186
+ }
187
+ return this.supportedChains.includes(tokenIn.chainId) && this.supportedChains.includes(tokenOut.chainId);
188
+ }
189
+ assertChainSupport({
190
+ tokenIn,
191
+ tokenOut,
192
+ underlyingToken
193
+ }) {
194
+ if (!this.checkChainSupport({ tokenIn, tokenOut, underlyingToken })) {
195
+ throw new BeraError({
196
+ message: `${this.name} does not support tokens chain ID: ${tokenIn.chainId} and ${tokenOut.chainId}`,
197
+ level: "error"
198
+ });
199
+ }
200
+ }
201
+ async fetch(url, options) {
202
+ try {
203
+ return await beraFetch(
204
+ { url, name: this.name, type: this.type },
205
+ {
206
+ method: "GET",
207
+ headers: {
208
+ "Content-Type": "application/json"
209
+ },
210
+ ...options
211
+ }
212
+ );
213
+ } catch (err) {
214
+ const error = initBeraError({ cause: err });
215
+ if (this.notFoundMessages.some((message) => error.message.includes(message))) {
216
+ error.reason = _BaseAggregator.PATH_NOT_FOUND_REASON;
217
+ }
218
+ throw error;
219
+ }
220
+ }
221
+ };
222
+
223
+ // src/actions/dex/b-sdk.ts
224
+ import {
225
+ API_CHAIN_NAMES,
226
+ BALANCER_QUERIES,
227
+ BALANCER_RELAYER,
228
+ BalancerApi,
229
+ CHAINS,
230
+ COMPOSABLE_STABLE_POOL_FACTORY,
231
+ NATIVE_ASSETS,
232
+ Token,
233
+ VAULT,
234
+ WEIGHTED_POOL_FACTORY_BALANCER_V2
235
+ } from "@berachain-foundation/berancer-sdk";
236
+ import { zeroAddress as zeroAddress2 } from "viem";
237
+ import { berachain, berachainBepolia } from "viem/chains";
238
+ import { chainConfigs } from "@berachain/config/internal";
239
+ for (const chain of Object.keys(chainConfigs)) {
240
+ const { config, chainId } = parseBaseArgs({
241
+ chainId: Number(chain)
242
+ });
243
+ API_CHAIN_NAMES[chainId] = config.bex.chainName;
244
+ CHAINS[chainId] = chainId === berachain.id ? berachain : berachainBepolia;
245
+ BALANCER_RELAYER[chainId] = config.bex.relayer;
246
+ VAULT[chainId] = config.bex.vault;
247
+ BALANCER_QUERIES[chainId] = config.bex.queries;
248
+ WEIGHTED_POOL_FACTORY_BALANCER_V2[chainId] = zeroAddress2;
249
+ COMPOSABLE_STABLE_POOL_FACTORY[chainId] = zeroAddress2;
250
+ const nativeToken = new Token(
251
+ chainId,
252
+ zeroAddress2,
253
+ beraToken.decimals,
254
+ beraToken.name,
255
+ beraToken.symbol,
256
+ config.tokens.wbera
257
+ );
258
+ NATIVE_ASSETS[chainId] = nativeToken;
259
+ }
260
+
261
+ // src/actions/dex/getAllPools.ts
262
+ import {
263
+ GetPools
264
+ } from "@berachain/graphql/dex/api";
265
+ import {
266
+ GqlPoolOrderBy,
267
+ GqlPoolOrderDirection
268
+ } from "@berachain/graphql/pol/api";
269
+ async function getAllPools({
270
+ textSearch,
271
+ chain,
272
+ first,
273
+ orderBy,
274
+ orderDirection,
275
+ skip,
276
+ fetchPolicy,
277
+ userAddress,
278
+ blacklistedPoolIds,
279
+ ...args
280
+ } = {}) {
281
+ const { config } = parseBaseArgs(args);
282
+ const bexApiGraphqlClient = getApolloClient("api", args);
283
+ const pools = await bexApiGraphqlClient.query({
284
+ query: GetPools,
285
+ variables: {
286
+ textSearch,
287
+ chain: chain ?? config.bex.chainName,
288
+ first,
289
+ orderBy: orderBy ?? GqlPoolOrderBy.TotalLiquidity,
290
+ orderDirection: orderDirection ?? GqlPoolOrderDirection.Desc,
291
+ skip,
292
+ userAddress,
293
+ blacklistedPoolIds
294
+ },
295
+ fetchPolicy
296
+ });
297
+ return {
298
+ pools: pools.data.poolGetPools ?? [],
299
+ count: pools.data.count ?? 0
300
+ };
301
+ }
302
+
303
+ // src/actions/dex/getApiPool.ts
304
+ import {
305
+ GetPool
306
+ } from "@berachain/graphql/dex/api";
307
+ async function getApiPool({
308
+ poolId,
309
+ account,
310
+ ...args
311
+ }) {
312
+ const { config } = parseBaseArgs(args);
313
+ const bexApiGraphqlClient = getApolloClient("api", args);
314
+ const pool = await bexApiGraphqlClient.query({
315
+ query: GetPool,
316
+ variables: {
317
+ id: poolId,
318
+ userAddress: account,
319
+ chain: config.bex.chainName
320
+ },
321
+ fetchPolicy: "no-cache"
322
+ // If we cache it seems to return an empty response
323
+ });
324
+ const data = pool.data.poolGetPool;
325
+ if (!data) {
326
+ throw new Error(`Pool not found for id: ${poolId} and user ${account}`);
327
+ }
328
+ return data;
329
+ }
330
+
331
+ // src/actions/dex/getGlobalLiquidityAndSwapVolume.ts
332
+ import {
333
+ GetGlobalLiquidityAndSwapVolume
334
+ } from "@berachain/graphql/dex/api";
335
+ async function getGlobalLiquidityAndSwapVolume(args = {}) {
336
+ const { config } = parseBaseArgs(args);
337
+ const bexApiGraphqlClient = getApolloClient("api", args);
338
+ const response = await bexApiGraphqlClient.query({
339
+ query: GetGlobalLiquidityAndSwapVolume,
340
+ variables: {
341
+ chain: config.bex.chainName
342
+ }
343
+ });
344
+ return response.data;
345
+ }
346
+
347
+ // src/actions/dex/getPoolPausedState.ts
348
+ import { weightedPoolV4Abi_V2 } from "@berachain-foundation/berancer-sdk";
349
+ async function getPoolPausedState({
350
+ publicClient,
351
+ poolAddress
352
+ }) {
353
+ const abi = weightedPoolV4Abi_V2;
354
+ const results = await publicClient.multicall({
355
+ contracts: [
356
+ {
357
+ address: poolAddress,
358
+ abi,
359
+ functionName: "inRecoveryMode"
360
+ },
361
+ {
362
+ address: poolAddress,
363
+ abi,
364
+ functionName: "getPausedState"
365
+ }
366
+ ],
367
+ allowFailure: false
368
+ // NOTE: this disallows partial failures of the multicall
369
+ });
370
+ return {
371
+ isPoolInRecoveryMode: results[0],
372
+ isPoolPaused: results[1][0]
373
+ };
374
+ }
375
+
376
+ // src/actions/dex/getOnChainPool.ts
377
+ import {
378
+ stablePoolAbi_V3,
379
+ vaultV2Abi,
380
+ weightedPoolFactoryAbi_V3,
381
+ weightedPoolV4Abi_V2 as weightedPoolV4Abi_V22
382
+ } from "@berachain-foundation/berancer-sdk";
383
+ import {
384
+ erc20Abi,
385
+ formatEther as formatEther2,
386
+ formatUnits as formatUnits2,
387
+ isAddress as isAddress2,
388
+ isHex
389
+ } from "viem";
390
+ import { GqlPoolType } from "@berachain/graphql/pol/api";
391
+ async function getOnChainPool({
392
+ poolId,
393
+ publicClient,
394
+ ...args
395
+ }) {
396
+ const { config } = parseBaseArgs(args);
397
+ const address = poolId.slice(0, 42);
398
+ if (!isAddress2(address) || !isHex(poolId)) {
399
+ throw new InvalidArgumentError({
400
+ property: "poolId",
401
+ value: poolId,
402
+ expected: "Hex"
403
+ });
404
+ }
405
+ try {
406
+ const [
407
+ name,
408
+ poolTokens,
409
+ totalSupply,
410
+ swapFee,
411
+ _version,
412
+ _decimals,
413
+ isComposableStable,
414
+ isWeighted,
415
+ poolPausedState
416
+ ] = await Promise.all([
417
+ publicClient.readContract({
418
+ address,
419
+ abi: erc20Abi,
420
+ functionName: "name"
421
+ }),
422
+ publicClient.readContract({
423
+ address: config.bex.vault,
424
+ abi: vaultV2Abi,
425
+ functionName: "getPoolTokens",
426
+ args: [poolId]
427
+ }),
428
+ publicClient.readContract({
429
+ address,
430
+ abi: erc20Abi,
431
+ functionName: "totalSupply"
432
+ }),
433
+ publicClient.readContract({
434
+ address,
435
+ abi: weightedPoolV4Abi_V22,
436
+ functionName: "getSwapFeePercentage"
437
+ }),
438
+ publicClient.readContract({
439
+ address,
440
+ abi: weightedPoolV4Abi_V22,
441
+ functionName: "version"
442
+ }),
443
+ publicClient.readContract({
444
+ address,
445
+ abi: weightedPoolV4Abi_V22,
446
+ functionName: "decimals"
447
+ }),
448
+ publicClient.readContract({
449
+ address: config.bex.factories.composableStable,
450
+ abi: weightedPoolFactoryAbi_V3,
451
+ functionName: "isPoolFromFactory",
452
+ args: [address]
453
+ }),
454
+ publicClient.readContract({
455
+ address: config.bex.factories.weighted,
456
+ abi: weightedPoolFactoryAbi_V3,
457
+ functionName: "isPoolFromFactory",
458
+ args: [address]
459
+ }),
460
+ getPoolPausedState({ publicClient, poolAddress: address })
461
+ ]);
462
+ const decimals = Number(_decimals);
463
+ const version = JSON.parse(_version);
464
+ let virtualSupply;
465
+ let weights;
466
+ let amplificationParameter;
467
+ if (isComposableStable) {
468
+ [virtualSupply, amplificationParameter] = await Promise.all([
469
+ publicClient.readContract({
470
+ address,
471
+ abi: [
472
+ {
473
+ type: "function",
474
+ name: "getActualSupply",
475
+ stateMutability: "view",
476
+ inputs: [],
477
+ outputs: [
478
+ {
479
+ type: "uint256"
480
+ }
481
+ ]
482
+ }
483
+ ],
484
+ functionName: "getActualSupply"
485
+ }),
486
+ // NOTE: it is possible to pull this from the subgraph, but not using GqlPoolBase, we'd have to query a specific pool type.
487
+ publicClient.readContract({
488
+ address,
489
+ abi: stablePoolAbi_V3,
490
+ functionName: "getAmplificationParameter"
491
+ })
492
+ ]);
493
+ } else if (version.name === "WeightedPool") {
494
+ weights = await publicClient.readContract({
495
+ address,
496
+ abi: weightedPoolV4Abi_V22,
497
+ functionName: "getNormalizedWeights"
498
+ });
499
+ }
500
+ if (!isComposableStable && !isWeighted) {
501
+ throw new Error(`Pool ${address} is not a valid BEX pool`);
502
+ }
503
+ return {
504
+ name,
505
+ address,
506
+ id: poolId,
507
+ poolTokens: [
508
+ poolTokens[0],
509
+ poolTokens[1].map(String),
510
+ Number(poolTokens[2])
511
+ ],
512
+ totalSupply: formatUnits2(virtualSupply ?? totalSupply, decimals),
513
+ swapFee: formatEther2(swapFee),
514
+ decimals,
515
+ weights: weights?.map((weight) => formatEther2(weight)),
516
+ version,
517
+ factory: isComposableStable ? config.bex.factories.composableStable : config.bex.factories.weighted,
518
+ type: isComposableStable ? GqlPoolType.Stable : GqlPoolType.Weighted,
519
+ amplificationParameter: amplificationParameter ? [
520
+ // raw value
521
+ Number(amplificationParameter[0]),
522
+ // is updating
523
+ amplificationParameter[1],
524
+ // precision factor
525
+ Number(amplificationParameter[2])
526
+ ] : void 0,
527
+ pausedState: poolPausedState
528
+ };
529
+ } catch (e) {
530
+ throw initBeraError({ cause: e });
531
+ }
532
+ }
533
+
534
+ // src/actions/dex/getPoolEvents.ts
535
+ import {
536
+ GetPoolEvents
537
+ } from "@berachain/graphql/dex/api";
538
+ async function getPoolEvents({
539
+ poolId,
540
+ typeInArray,
541
+ ...args
542
+ }) {
543
+ const { config } = parseBaseArgs(args);
544
+ const bexApiGraphqlClient = getApolloClient("api", args);
545
+ const response = await bexApiGraphqlClient.query({
546
+ query: GetPoolEvents,
547
+ variables: {
548
+ poolId,
549
+ typeIn: typeInArray,
550
+ chain: config.bex.chainName
551
+ }
552
+ });
553
+ return response.data;
554
+ }
555
+
556
+ // src/actions/dex/getPoolHistoricalData.ts
557
+ import { isHex as isHex2 } from "viem";
558
+ import {
559
+ GetPoolHistoricalData
560
+ } from "@berachain/graphql/dex/api";
561
+ async function getPoolHistoricalData({
562
+ poolId,
563
+ chain,
564
+ ...args
565
+ }) {
566
+ if (!poolId || !isHex2(poolId))
567
+ throw new InvalidArgumentError({
568
+ property: "poolId",
569
+ value: poolId,
570
+ expected: "hex string"
571
+ });
572
+ const bexApiGraphqlClient = getApolloClient("api", args);
573
+ const { data } = await bexApiGraphqlClient.query({
574
+ query: GetPoolHistoricalData,
575
+ variables: { poolId, chain }
576
+ });
577
+ return data.poolGetSnapshots;
578
+ }
579
+
580
+ // src/actions/honey/getChartData.ts
581
+ async function getChartData({
582
+ days
583
+ }) {
584
+ if (typeof window === "undefined") {
585
+ throw new BeraError({
586
+ message: "getChartData is browser-only; call from a Client Component / SWR hook",
587
+ level: "error"
588
+ });
589
+ }
590
+ const params = new URLSearchParams({ interval: "day", first: String(days) });
591
+ const honeySnapshots = await beraFetchJson({
592
+ url: `/api/honey/snapshots?${params}`,
593
+ name: "honey-snapshots",
594
+ type: "rest"
595
+ });
596
+ return { honeySnapshots };
597
+ }
598
+
599
+ // src/actions/honey/getCollateralWeights.ts
600
+ import { honeyFactoryAbi } from "@berachain/abis/honey/honeyFactory";
601
+ async function getCollateralWeights({
602
+ client,
603
+ collateralList,
604
+ ...args
605
+ }) {
606
+ const { config } = parseBaseArgs(args);
607
+ try {
608
+ const collateralWeights = await client.readContract({
609
+ address: config.honey.factory,
610
+ abi: honeyFactoryAbi,
611
+ functionName: "getWeights"
612
+ });
613
+ const weightsWithAddress = collateralList.reduce(
614
+ (agg, key, idx) => Object.assign(agg, { [key.address]: collateralWeights[idx] }),
615
+ {}
616
+ );
617
+ return weightsWithAddress;
618
+ } catch (e) {
619
+ console.log(e);
620
+ throw e;
621
+ }
622
+ }
623
+
624
+ // src/actions/tokens/getTokenInformation.ts
625
+ import { erc20Abi as erc20Abi2 } from "viem";
626
+ async function getTokenInformation({
627
+ address,
628
+ publicClient,
629
+ chainId
630
+ }) {
631
+ try {
632
+ assertPublicClient(publicClient);
633
+ const [decimals, name, symbol] = await Promise.all([
634
+ publicClient.readContract({
635
+ address,
636
+ abi: erc20Abi2,
637
+ functionName: "decimals"
638
+ }),
639
+ publicClient.readContract({
640
+ address,
641
+ abi: erc20Abi2,
642
+ functionName: "name"
643
+ }),
644
+ publicClient.readContract({
645
+ address,
646
+ abi: erc20Abi2,
647
+ functionName: "symbol"
648
+ })
649
+ ]);
650
+ return {
651
+ address,
652
+ decimals,
653
+ name,
654
+ symbol,
655
+ chainId
656
+ };
657
+ } catch (e) {
658
+ throw initBeraError({ cause: e });
659
+ }
660
+ }
661
+
662
+ // src/actions/honey/getHoneyCollaterals.ts
663
+ import { honeyFactoryAbi as honeyFactoryAbi2 } from "@berachain/abis/honey/honeyFactory";
664
+ async function getHoneyCollaterals({
665
+ client,
666
+ tokenData,
667
+ preferredCollateralOrder,
668
+ ...args
669
+ }) {
670
+ const { config } = parseBaseArgs(args);
671
+ const [amountOfCollaterals, referenceCollateralAddress] = await Promise.all([
672
+ client.readContract({
673
+ address: config.honey.factory,
674
+ abi: honeyFactoryAbi2,
675
+ functionName: "numRegisteredAssets"
676
+ }),
677
+ client.readContract({
678
+ address: config.honey.factory,
679
+ abi: honeyFactoryAbi2,
680
+ functionName: "referenceCollateral"
681
+ })
682
+ ]);
683
+ const promiseList = [];
684
+ for (let i = 0; i < amountOfCollaterals; i++) {
685
+ promiseList.push(
686
+ client.readContract({
687
+ address: config.honey.factory,
688
+ abi: honeyFactoryAbi2,
689
+ functionName: "registeredAssets",
690
+ args: [BigInt(i)]
691
+ })
692
+ );
693
+ }
694
+ const collaterals = await Promise.all(promiseList);
695
+ const collateralsTokens = await Promise.all(
696
+ collaterals.map((coll) => {
697
+ const token = tokenData?.find((token2) => isToken(token2, coll));
698
+ if (token) {
699
+ return token;
700
+ }
701
+ return getTokenInformation({
702
+ address: coll,
703
+ chainId: config.chainId,
704
+ publicClient: client
705
+ });
706
+ })
707
+ );
708
+ const collateralTokens = collateralsTokens.filter((coll) => !!coll).sort((a, b) => {
709
+ return collaterals.indexOf(a.address) - collaterals.indexOf(b.address);
710
+ }).map((coll, idx) => ({
711
+ ...coll,
712
+ order: idx
713
+ }));
714
+ if (preferredCollateralOrder?.length) {
715
+ const newCollateralOrder = [];
716
+ for (const override of preferredCollateralOrder) {
717
+ const newFirstCollateral = collateralTokens.find(
718
+ (coll) => isToken(coll.address, override.address)
719
+ );
720
+ if (newFirstCollateral) {
721
+ newCollateralOrder.push(newFirstCollateral);
722
+ collateralTokens.splice(
723
+ collateralTokens.indexOf(newFirstCollateral),
724
+ 1
725
+ );
726
+ }
727
+ }
728
+ collateralTokens.unshift(...newCollateralOrder);
729
+ }
730
+ const referenceCollateral = collateralTokens.find(
731
+ (coll) => isToken(coll, referenceCollateralAddress)
732
+ );
733
+ if (!collateralTokens) {
734
+ throw new Error("Collateral tokens not found");
735
+ }
736
+ if (!referenceCollateral) {
737
+ throw new Error("Reference collateral address not found");
738
+ }
739
+ return {
740
+ collaterals: collateralTokens,
741
+ referenceCollateral
742
+ };
743
+ }
744
+
745
+ // src/actions/honey/isBadCollateralAsset.ts
746
+ import { parseUnits } from "viem";
747
+ import { honeyFactoryAbi as honeyFactoryAbi3 } from "@berachain/abis/honey/honeyFactory";
748
+ import { honeyFactoryReaderAbi } from "@berachain/abis/honey/honeyFactoryReader";
749
+ async function isBadCollateralAsset({
750
+ client,
751
+ collateral,
752
+ latestPrices,
753
+ isPythWrapperEnabled,
754
+ ...args
755
+ }) {
756
+ const { config } = parseBaseArgs(args);
757
+ try {
758
+ const isBadCollateralCall = client.readContract({
759
+ address: config.honey.factory,
760
+ abi: honeyFactoryAbi3,
761
+ functionName: "isBadCollateralAsset",
762
+ args: [collateral.address]
763
+ });
764
+ let isPeggedCall = client.readContract({
765
+ address: config.honey.factory,
766
+ abi: honeyFactoryAbi3,
767
+ functionName: "isPegged",
768
+ args: [collateral.address]
769
+ });
770
+ if (isPythWrapperEnabled && latestPrices) {
771
+ const prices = latestPrices.prices.map((price) => parseUnits(price, 18));
772
+ isPeggedCall = client.readContract({
773
+ address: config.honey.reader,
774
+ abi: honeyFactoryReaderAbi,
775
+ functionName: "isPeggedWithPrice",
776
+ args: [collateral.address, prices[0]]
777
+ });
778
+ }
779
+ const [badCollateralResult, isPeggedResult] = await Promise.all([
780
+ isBadCollateralCall,
781
+ isPeggedCall
782
+ ]);
783
+ return {
784
+ isBlacklisted: badCollateralResult,
785
+ isDepegged: !isPeggedResult
786
+ // invert the result to get the correct value
787
+ };
788
+ } catch (e) {
789
+ console.log(e);
790
+ throw e;
791
+ }
792
+ }
793
+
794
+ // src/actions/honey/getGlobalCapLimit.ts
795
+ import { parseEther as parseEther2 } from "viem";
796
+ import { honeyFactoryAbi as honeyFactoryAbi5 } from "@berachain/abis/honey/honeyFactory";
797
+
798
+ // src/actions/honey/getSharesWithoutFees.ts
799
+ import { parseEther } from "viem";
800
+ import { collateralVaultAbi } from "@berachain/abis/honey/collateralVault";
801
+ import { honeyFactoryAbi as honeyFactoryAbi4 } from "@berachain/abis/honey/honeyFactory";
802
+ async function getSharesWithoutFees({
803
+ client,
804
+ asset,
805
+ amount,
806
+ ...args
807
+ }) {
808
+ const { config } = parseBaseArgs(args);
809
+ try {
810
+ const [vault, fees] = await Promise.all([
811
+ client.readContract({
812
+ address: config.honey.factory,
813
+ abi: honeyFactoryAbi4,
814
+ functionName: "vaults",
815
+ args: [asset]
816
+ }),
817
+ client.readContract({
818
+ address: config.honey.factory,
819
+ abi: honeyFactoryAbi4,
820
+ functionName: "collectedFees",
821
+ args: [config.honey.factory, asset]
822
+ })
823
+ ]);
824
+ const balance = await client.readContract({
825
+ address: vault,
826
+ abi: collateralVaultAbi,
827
+ functionName: "balanceOf",
828
+ args: [config.honey.factory]
829
+ });
830
+ return balance + parseEther(amount ?? "0") - fees;
831
+ } catch (e) {
832
+ console.log(e);
833
+ throw e;
834
+ }
835
+ }
836
+
837
+ // src/actions/honey/getGlobalCapLimit.ts
838
+ var ONE_HUNDRED_PERCENT = parseEther2("1");
839
+ async function getGlobalCapLimit({
840
+ client,
841
+ asset,
842
+ amount,
843
+ isMint,
844
+ isPythWrapperEnabled,
845
+ latestPrices,
846
+ ...args
847
+ }) {
848
+ const { config } = parseBaseArgs(args);
849
+ try {
850
+ const globalCap = await client.readContract({
851
+ address: config.honey.factory,
852
+ abi: honeyFactoryAbi5,
853
+ functionName: "globalCap"
854
+ });
855
+ if (globalCap >= ONE_HUNDRED_PERCENT) {
856
+ return false;
857
+ }
858
+ const [{ collaterals: registeredAssets }, weights] = await Promise.all([
859
+ getHoneyCollaterals({
860
+ client
861
+ }),
862
+ getWeights({ client, asset, amount, latestPrices, isPythWrapperEnabled })
863
+ ]);
864
+ if (!weights) {
865
+ return void 0;
866
+ }
867
+ for (const idx in weights) {
868
+ if (isMint && isToken(registeredAssets[idx], asset) || !isMint && isToken(registeredAssets[idx], asset)) {
869
+ const weight = weights[idx];
870
+ if (weight > globalCap - CAP_LIMIT_BUFFER) {
871
+ return true;
872
+ }
873
+ }
874
+ }
875
+ return false;
876
+ } catch (e) {
877
+ console.log(e);
878
+ throw e;
879
+ }
880
+ }
881
+ async function getWeights({
882
+ client,
883
+ asset,
884
+ amount,
885
+ latestPrices,
886
+ isPythWrapperEnabled
887
+ }) {
888
+ const { collaterals: registeredAssets } = await getHoneyCollaterals({
889
+ client
890
+ });
891
+ let sum = 0n;
892
+ const weights = [];
893
+ for (const singleAsset of registeredAssets) {
894
+ const isBad = await isBadCollateralAsset({
895
+ client,
896
+ collateral: asset,
897
+ latestPrices,
898
+ isPythWrapperEnabled
899
+ });
900
+ if (isBad?.isBlacklisted || isBad?.isDepegged) {
901
+ continue;
902
+ }
903
+ const share = await getSharesWithoutFees({
904
+ client,
905
+ asset: singleAsset.address,
906
+ amount: isToken(singleAsset, asset) ? amount : "0"
907
+ });
908
+ if (!share) {
909
+ continue;
910
+ }
911
+ sum += share;
912
+ weights.push(share);
913
+ }
914
+ if (sum === 0n) {
915
+ return weights;
916
+ }
917
+ for (const idx in registeredAssets) {
918
+ weights[idx] = parseEther2(weights[idx].toString()) / sum;
919
+ }
920
+ return weights;
921
+ }
922
+
923
+ // src/actions/honey/getHoney24hVolume.ts
924
+ async function getHoney24hVolume() {
925
+ if (typeof window === "undefined") {
926
+ throw new BeraError({
927
+ message: "getHoney24hVolume is browser-only; call from a Client Component / SWR hook",
928
+ level: "error"
929
+ });
930
+ }
931
+ const params = new URLSearchParams({ interval: "hour", first: "24" });
932
+ const snapshots = await beraFetchJson({
933
+ url: `/api/honey/snapshots?${params}`,
934
+ name: "honey-snapshots",
935
+ type: "rest"
936
+ });
937
+ return snapshots.reduce(
938
+ (acc, curr) => new bignumber_js_default(curr.totalVolume).plus(acc),
939
+ new bignumber_js_default(0)
940
+ );
941
+ }
942
+
943
+ // src/actions/honey/getHoneyPreview.ts
944
+ import { parseUnits as parseUnits2 } from "viem";
945
+ import { honeyFactoryReaderAbi as honeyFactoryReaderAbi2 } from "@berachain/abis/honey/honeyFactoryReader";
946
+ var HoneyPreviewMethod = /* @__PURE__ */ ((HoneyPreviewMethod2) => {
947
+ HoneyPreviewMethod2["Mint"] = "previewMintHoney";
948
+ HoneyPreviewMethod2["MintWithPrice"] = "previewMintHoneyWithPrices";
949
+ HoneyPreviewMethod2["RequiredCollateral"] = "previewMintCollaterals";
950
+ HoneyPreviewMethod2["RequiredCollateralWithPrice"] = "previewMintCollateralsWithPrices";
951
+ HoneyPreviewMethod2["Redeem"] = "previewRedeemCollaterals";
952
+ HoneyPreviewMethod2["RedeemWithPrice"] = "previewRedeemCollateralsWithPrices";
953
+ HoneyPreviewMethod2["HoneyToRedeem"] = "previewRedeemHoney";
954
+ HoneyPreviewMethod2["HoneyToRedeemWithPrice"] = "previewRedeemHoneyWithPrices";
955
+ return HoneyPreviewMethod2;
956
+ })(HoneyPreviewMethod || {});
957
+ async function getHoneyPreview({
958
+ client,
959
+ collateral,
960
+ collateralList,
961
+ amount,
962
+ method,
963
+ latestPrices,
964
+ isPythWrapperEnabled,
965
+ ...baseArgs
966
+ }) {
967
+ const { config } = parseBaseArgs(baseArgs);
968
+ try {
969
+ const isAmountHoney = method === "previewMintHoney" /* Mint */ || method === "previewRedeemHoney" /* HoneyToRedeem */ || method === "previewMintHoneyWithPrices" /* MintWithPrice */ || method === "previewRedeemHoneyWithPrices" /* HoneyToRedeemWithPrice */;
970
+ const formattedAmount = parseUnits2(
971
+ amount,
972
+ isAmountHoney ? collateral.decimals : 18
973
+ );
974
+ let formattedResult;
975
+ let args = [collateral.address, formattedAmount];
976
+ if (isPythWrapperEnabled && latestPrices) {
977
+ const prices = latestPrices.prices.map((price) => parseUnits2(price, 18));
978
+ args = [collateral.address, formattedAmount, prices];
979
+ }
980
+ if (isAmountHoney) {
981
+ const result = await client.readContract({
982
+ address: config.honey.reader,
983
+ abi: honeyFactoryReaderAbi2,
984
+ functionName: method,
985
+ args
986
+ });
987
+ formattedResult = {
988
+ collaterals: result[0],
989
+ honey: result[1]
990
+ };
991
+ } else {
992
+ const result = await client.readContract({
993
+ address: config.honey.reader,
994
+ abi: honeyFactoryReaderAbi2,
995
+ functionName: method,
996
+ args
997
+ });
998
+ formattedResult = {
999
+ collaterals: result,
1000
+ honey: formattedAmount
1001
+ };
1002
+ }
1003
+ const amountsWithAddress = collateralList.reduce(
1004
+ (agg, key) => {
1005
+ const idx = key.order;
1006
+ if (key.address === collateral.address && formattedResult.collaterals[idx] === BigInt(0)) {
1007
+ return Object.assign(agg, {
1008
+ [key.address]: formattedResult.collaterals[0]
1009
+ });
1010
+ }
1011
+ return Object.assign(agg, {
1012
+ [key.address]: formattedResult.collaterals[idx]
1013
+ });
1014
+ },
1015
+ {}
1016
+ );
1017
+ if (amountsWithAddress[collateral.address] === BigInt(0)) {
1018
+ amountsWithAddress[collateral.address] = formattedResult.collaterals[0];
1019
+ }
1020
+ return {
1021
+ collaterals: amountsWithAddress,
1022
+ honey: formattedResult.honey
1023
+ };
1024
+ } catch (e) {
1025
+ console.log("error", e);
1026
+ throw e;
1027
+ }
1028
+ }
1029
+
1030
+ // src/actions/honey/getHoneyVaultsBalance.ts
1031
+ import { formatUnits as formatUnits3 } from "viem";
1032
+ import { collateralVaultAbi as collateralVaultAbi2 } from "@berachain/abis/honey/collateralVault";
1033
+ import { honeyFactoryAbi as honeyFactoryAbi6 } from "@berachain/abis/honey/honeyFactory";
1034
+ async function getHoneyVaultsBalance({
1035
+ client,
1036
+ collateralList,
1037
+ honeyFactoryAddress,
1038
+ ...args
1039
+ }) {
1040
+ const { config } = parseBaseArgs(args);
1041
+ const factory = honeyFactoryAddress ?? config.honey.factory;
1042
+ const vaults = await Promise.all(
1043
+ collateralList.map(async (coll) => {
1044
+ const vault = await client.readContract({
1045
+ address: config.honey.factory,
1046
+ abi: honeyFactoryAbi6,
1047
+ functionName: "vaults",
1048
+ args: [coll.address]
1049
+ });
1050
+ const [
1051
+ shares,
1052
+ // this is most likely 0 since we're sending fees to PolFeeCollector
1053
+ // here for future proofing
1054
+ feeShares,
1055
+ // if balance is held in a custodian, we need to return the custodian address
1056
+ [isCustodian, custodianAddress]
1057
+ ] = await Promise.all([
1058
+ client.readContract({
1059
+ address: vault,
1060
+ abi: collateralVaultAbi2,
1061
+ functionName: "balanceOf",
1062
+ args: [factory]
1063
+ }),
1064
+ client.readContract({
1065
+ address: factory,
1066
+ abi: honeyFactoryAbi6,
1067
+ functionName: "collectedAssetFees",
1068
+ args: [coll.address]
1069
+ }),
1070
+ client.readContract({
1071
+ address: vault,
1072
+ abi: collateralVaultAbi2,
1073
+ functionName: "custodyInfo"
1074
+ })
1075
+ ]);
1076
+ const balance = await client.readContract({
1077
+ address: vault,
1078
+ abi: collateralVaultAbi2,
1079
+ functionName: "convertToAssets",
1080
+ args: [shares - feeShares]
1081
+ });
1082
+ return {
1083
+ ...coll,
1084
+ balance: {
1085
+ raw: balance.toString(),
1086
+ formatted: formatUnits3(balance, coll.decimals)
1087
+ },
1088
+ vault: isCustodian ? custodianAddress : vault
1089
+ };
1090
+ })
1091
+ );
1092
+ return vaults;
1093
+ }
1094
+
1095
+ // src/actions/honey/getPythLatestPrices.ts
1096
+ import { HermesClient } from "@pythnetwork/hermes-client";
1097
+ import { formatUnits as formatUnits4 } from "viem";
1098
+
1099
+ // src/utils/polyfillAbortSignalAny.ts
1100
+ function polyfillAbortSignalAny() {
1101
+ if (typeof AbortSignal === "undefined") return;
1102
+ if (typeof AbortSignal.any === "function") return;
1103
+ AbortSignal.any = (signals) => {
1104
+ const controller = new AbortController();
1105
+ for (const signal of signals) {
1106
+ if (signal.aborted) {
1107
+ controller.abort(signal.reason);
1108
+ return controller.signal;
1109
+ }
1110
+ }
1111
+ const listeners = [];
1112
+ const cleanup = () => {
1113
+ for (let i = 0; i < signals.length; i++) {
1114
+ signals[i].removeEventListener("abort", listeners[i]);
1115
+ }
1116
+ };
1117
+ for (const signal of signals) {
1118
+ const onAbort = () => {
1119
+ if (!controller.signal.aborted) controller.abort(signal.reason);
1120
+ cleanup();
1121
+ };
1122
+ listeners.push(onAbort);
1123
+ signal.addEventListener("abort", onAbort);
1124
+ }
1125
+ return controller.signal;
1126
+ };
1127
+ }
1128
+
1129
+ // src/actions/honey/getPythLatestPrices.ts
1130
+ var pythEndpoint = "https://hermes.pyth.network";
1131
+ polyfillAbortSignalAny();
1132
+ async function getPythLatestPrices({
1133
+ priceFeedId
1134
+ }) {
1135
+ const hermesClient = new HermesClient(pythEndpoint, {});
1136
+ const updates = await hermesClient.getLatestPriceUpdates(priceFeedId, {
1137
+ encoding: "hex",
1138
+ parsed: true
1139
+ });
1140
+ return {
1141
+ calldata: updates.binary.data.map((d) => `0x${d}`),
1142
+ prices: updates.parsed?.flatMap(
1143
+ (p) => formatUnits4(BigInt(p.price.price), p.price.expo * -1)
1144
+ ) ?? []
1145
+ };
1146
+ }
1147
+
1148
+ // src/actions/honey/getRelativeCapLimit.ts
1149
+ import { parseEther as parseEther3 } from "viem";
1150
+ import { honeyFactoryAbi as honeyFactoryAbi7 } from "@berachain/abis/honey/honeyFactory";
1151
+ async function getRelativeCapLimit({
1152
+ client,
1153
+ asset,
1154
+ amount,
1155
+ isMint,
1156
+ referenceCollateral,
1157
+ ...args
1158
+ }) {
1159
+ const { config } = parseBaseArgs(args);
1160
+ if (asset === referenceCollateral.address) {
1161
+ return false;
1162
+ }
1163
+ try {
1164
+ const [assetRelativeCap] = await Promise.all([
1165
+ client.readContract({
1166
+ address: config.honey.factory,
1167
+ abi: honeyFactoryAbi7,
1168
+ functionName: "relativeCap",
1169
+ args: [asset]
1170
+ })
1171
+ ]);
1172
+ const [assetBalance, referenceCollateralBalance] = await Promise.all([
1173
+ getSharesWithoutFees({
1174
+ client,
1175
+ asset,
1176
+ amount: isMint ? amount : void 0
1177
+ }),
1178
+ getSharesWithoutFees({
1179
+ client,
1180
+ asset: referenceCollateral.address,
1181
+ amount: isMint ? void 0 : amount
1182
+ })
1183
+ ]);
1184
+ if (referenceCollateralBalance === 0n) {
1185
+ return assetBalance !== 0n;
1186
+ }
1187
+ const weight = parseEther3((assetBalance ?? 0n).toString()) / (referenceCollateralBalance ?? 0n);
1188
+ if (weight >= assetRelativeCap - CAP_LIMIT_BUFFER) {
1189
+ return true;
1190
+ }
1191
+ return false;
1192
+ } catch (e) {
1193
+ console.log(e);
1194
+ throw e;
1195
+ }
1196
+ }
1197
+
1198
+ // src/actions/pyth/getUpdateFee.ts
1199
+ async function getPythUpdateFee({
1200
+ client,
1201
+ priceFeedId,
1202
+ ...args
1203
+ }) {
1204
+ const { config } = parseBaseArgs(args);
1205
+ try {
1206
+ const result = await client.readContract({
1207
+ address: config.external.pyth,
1208
+ abi: pythAbi,
1209
+ functionName: "getUpdateFee",
1210
+ args: [priceFeedId]
1211
+ });
1212
+ return result;
1213
+ } catch (e) {
1214
+ console.error("getPythUpdateFee", e);
1215
+ throw e;
1216
+ }
1217
+ }
1218
+
1219
+ // src/actions/honey/getSwapPayload.ts
1220
+ import {
1221
+ parseUnits as parseUnits3
1222
+ } from "viem";
1223
+ import { honeyFactoryAbi as honeyFactoryAbi8 } from "@berachain/abis/honey/honeyFactory";
1224
+ import { honeyFactoryPythWrapperAbi as pythWrapperAbi } from "@berachain/abis/honey/honeyFactoryPythWrapper";
1225
+ var getSwapPayload = async ({
1226
+ state,
1227
+ publicClient,
1228
+ priceFeedMap,
1229
+ collateralList,
1230
+ isPythWrapperEnabled,
1231
+ ...args
1232
+ }) => {
1233
+ const { config } = parseBaseArgs(args);
1234
+ const honeyToken = getHoneyToken(args);
1235
+ const { actionType, fromAmount, collaterals, isBasketModeEnabled: isBasketModeEnabled2 } = state;
1236
+ const destinationContractAddress = isPythWrapperEnabled ? config.honey.pythWrapper : config.honey.factory;
1237
+ const pairMainAddress = collateralList.map((coll) => coll.address);
1238
+ if (fromAmount[0] && !!pairMainAddress.length) {
1239
+ const isMint = actionType === "mint";
1240
+ if (isPythWrapperEnabled && publicClient && priceFeedMap) {
1241
+ const latestPrices = await getPythLatestPrices({
1242
+ priceFeedId: Object.values(priceFeedMap)
1243
+ });
1244
+ const calldata = latestPrices.calldata;
1245
+ let pythUpdateFee = 0n;
1246
+ try {
1247
+ pythUpdateFee = await getPythUpdateFee({
1248
+ client: publicClient,
1249
+ priceFeedId: calldata
1250
+ });
1251
+ } catch {
1252
+ pythUpdateFee = getPythDefaultUpdateFee(collaterals.length);
1253
+ }
1254
+ return ({ account }) => {
1255
+ const pythPayload = [
1256
+ calldata,
1257
+ collaterals[0]?.address,
1258
+ parseUnits3(
1259
+ fromAmount[0],
1260
+ (isMint ? collaterals[0]?.decimals : honeyToken?.decimals) ?? 18
1261
+ ),
1262
+ account,
1263
+ !!isBasketModeEnabled2
1264
+ ];
1265
+ return {
1266
+ address: destinationContractAddress,
1267
+ abi: pythWrapperAbi,
1268
+ functionName: isMint ? "mint" : "redeem",
1269
+ params: pythPayload,
1270
+ value: pythUpdateFee
1271
+ };
1272
+ };
1273
+ }
1274
+ return ({ account }) => {
1275
+ const defaultPayload = [
1276
+ collaterals[0]?.address,
1277
+ parseUnits3(
1278
+ fromAmount[0],
1279
+ (isMint ? collaterals[0]?.decimals : honeyToken?.decimals) ?? 18
1280
+ ),
1281
+ account,
1282
+ !!isBasketModeEnabled2
1283
+ ];
1284
+ return {
1285
+ value: 0n,
1286
+ address: destinationContractAddress,
1287
+ abi: honeyFactoryAbi8,
1288
+ functionName: isMint ? "mint" : "redeem",
1289
+ params: defaultPayload
1290
+ };
1291
+ };
1292
+ }
1293
+ throw new Error("Something went wrong while creating the Honey swap payload");
1294
+ };
1295
+
1296
+ // src/actions/honey/isBasketModeEnabled.ts
1297
+ import { parseUnits as parseUnits4 } from "viem";
1298
+ import { honeyFactoryAbi as honeyFactoryAbi9 } from "@berachain/abis/honey/honeyFactory";
1299
+ import { honeyFactoryReaderAbi as honeyFactoryReaderAbi3 } from "@berachain/abis/honey/honeyFactoryReader";
1300
+ async function isBasketModeEnabled({
1301
+ client,
1302
+ isMint,
1303
+ collateralList,
1304
+ latestPrices,
1305
+ isPythWrapperEnabled,
1306
+ ...args
1307
+ }) {
1308
+ const { config } = parseBaseArgs(args);
1309
+ if (isPythWrapperEnabled && latestPrices) {
1310
+ if (collateralList.length === 0) return void 0;
1311
+ const prices = latestPrices.prices.map((price) => parseUnits4(price, 18));
1312
+ const isActive2 = await client.readContract({
1313
+ address: config.honey.reader,
1314
+ abi: honeyFactoryReaderAbi3,
1315
+ functionName: "isBasketModeEnabledWithPrices",
1316
+ args: [isMint, prices]
1317
+ });
1318
+ return isActive2;
1319
+ }
1320
+ const isActive = await client.readContract({
1321
+ address: config.honey.factory,
1322
+ abi: honeyFactoryAbi9,
1323
+ functionName: "isBasketModeEnabled",
1324
+ args: [isMint]
1325
+ });
1326
+ return isActive;
1327
+ }
1328
+
1329
+ // src/actions/misc/getBlockTimestamp.ts
1330
+ async function getBlockTimestamp({
1331
+ block,
1332
+ currentBlock,
1333
+ blockTime,
1334
+ publicClient
1335
+ }) {
1336
+ assertDefined(block, "block");
1337
+ assertPublicClient(publicClient);
1338
+ if (currentBlock > block) {
1339
+ const blockData = await publicClient.getBlock({
1340
+ blockNumber: BigInt(block),
1341
+ includeTransactions: false
1342
+ });
1343
+ return {
1344
+ timestamp: Number(blockData.timestamp)
1345
+ };
1346
+ }
1347
+ const ts = msToSeconds(Date.now()) + blockTime * (Number(block) - Number(currentBlock));
1348
+ return {
1349
+ timestamp: ts
1350
+ };
1351
+ }
1352
+
1353
+ // src/actions/pol/getAutoclaimedIncentives.ts
1354
+ async function getAutoclaimedIncentives({
1355
+ account,
1356
+ ...args
1357
+ }) {
1358
+ const { config } = parseBaseArgs(args);
1359
+ try {
1360
+ return await beraFetchJson(
1361
+ {
1362
+ url: `${config.pol.bribeBoostApi}/api/v1/wallets/${account.toLowerCase()}/autoclaimed`,
1363
+ name: "pol-autoclaimed-incentives",
1364
+ type: "rest"
1365
+ },
1366
+ { cache: "no-store" }
1367
+ );
1368
+ } catch (error) {
1369
+ if (error instanceof RequestError && error.statusCode === 404) {
1370
+ return null;
1371
+ }
1372
+ throw error;
1373
+ }
1374
+ }
1375
+
1376
+ // src/actions/pol/getAutoclaimedIncentivesTxHash.ts
1377
+ async function getAutoclaimedIncentivesTxHash({
1378
+ account,
1379
+ ...args
1380
+ }) {
1381
+ const { config } = parseBaseArgs(args);
1382
+ try {
1383
+ return await beraFetchJson(
1384
+ {
1385
+ url: `${config.pol.bribeBoostApi}/api/v1/wallets/${account.toLowerCase()}/autoclaimed/txhash`,
1386
+ name: "pol-autoclaimed-incentives-txhash",
1387
+ type: "rest"
1388
+ },
1389
+ { cache: "no-store" }
1390
+ );
1391
+ } catch (error) {
1392
+ if (error instanceof RequestError && error.statusCode === 404) {
1393
+ return null;
1394
+ }
1395
+ throw error;
1396
+ }
1397
+ }
1398
+
1399
+ // src/actions/pol/getRewardVaultRewards.ts
1400
+ import { formatUnits as formatUnits5 } from "viem";
1401
+ import { rewardVaultAbi } from "@berachain/abis/pol/rewards/rewardVault";
1402
+ var RewardVaultDistributionMode = /* @__PURE__ */ ((RewardVaultDistributionMode2) => {
1403
+ RewardVaultDistributionMode2["Duration"] = "duration";
1404
+ RewardVaultDistributionMode2["TargetRate"] = "targetRate";
1405
+ RewardVaultDistributionMode2["TargetApr"] = "targetApr";
1406
+ return RewardVaultDistributionMode2;
1407
+ })(RewardVaultDistributionMode || {});
1408
+ async function getRewardVaultRewards(address, publicClient) {
1409
+ const [
1410
+ rewardsDuration,
1411
+ manager,
1412
+ rewardRate,
1413
+ periodFinish,
1414
+ targetRewardsPerSecond,
1415
+ minRewardDurationForTargetRate
1416
+ ] = await Promise.all([
1417
+ publicClient.readContract({
1418
+ address,
1419
+ abi: rewardVaultAbi,
1420
+ functionName: "rewardsDuration"
1421
+ }),
1422
+ publicClient.readContract({
1423
+ address,
1424
+ abi: rewardVaultAbi,
1425
+ functionName: "rewardVaultManager"
1426
+ }),
1427
+ publicClient.readContract({
1428
+ address,
1429
+ abi: rewardVaultAbi,
1430
+ functionName: "rewardRate"
1431
+ }),
1432
+ publicClient.readContract({
1433
+ address,
1434
+ abi: rewardVaultAbi,
1435
+ functionName: "periodFinish"
1436
+ }),
1437
+ publicClient.readContract({
1438
+ address,
1439
+ abi: rewardVaultAbi,
1440
+ functionName: "targetRewardsPerSecond"
1441
+ }),
1442
+ publicClient.readContract({
1443
+ address,
1444
+ abi: rewardVaultAbi,
1445
+ functionName: "minRewardDurationForTargetRate"
1446
+ })
1447
+ ]);
1448
+ const availableRewards = rewardRate * (periodFinish - BigInt(msToSeconds(Date.now()))) / 10n ** 18n;
1449
+ return {
1450
+ rewardsDuration: Number(rewardsDuration),
1451
+ mode: targetRewardsPerSecond === 0n ? "duration" /* Duration */ : "targetRate" /* TargetRate */,
1452
+ manager,
1453
+ // 36 decimals for the reward rate
1454
+ rewardRate: formatUnits5(rewardRate, 36),
1455
+ periodFinish: Number(periodFinish),
1456
+ // 36 decimals for the reward rate
1457
+ availableRewards: formatUnits5(availableRewards, 18),
1458
+ minRewardDurationForTargetRate: Number(minRewardDurationForTargetRate),
1459
+ targetRewardsPerSecond: formatUnits5(targetRewardsPerSecond, 36)
1460
+ };
1461
+ }
1462
+
1463
+ // src/actions/pol/getBgtAprSimulation.ts
1464
+ function _getApr(tvl, bgtPrice, rewardRate) {
1465
+ return tvl ? rewardRate * bgtPrice * yearsInSeconds(1) / tvl : null;
1466
+ }
1467
+ function _getRewardRate(apr, bgtPrice, tvl) {
1468
+ return tvl ? apr * tvl / (bgtPrice * yearsInSeconds(1)) : 0;
1469
+ }
1470
+ function getBgtAprSimulation({
1471
+ availableRewards,
1472
+ periodFinish,
1473
+ tvl,
1474
+ bgtPrice,
1475
+ MIN_REWARD_DURATION,
1476
+ MAX_REWARD_DURATION,
1477
+ ...args
1478
+ }) {
1479
+ const currentTime = msToSeconds(Date.now());
1480
+ if (currentTime > periodFinish) {
1481
+ return {
1482
+ apr: 0,
1483
+ duration: 0,
1484
+ rewardRate: 0,
1485
+ targetRate: null,
1486
+ periodFinish: 0,
1487
+ mode: null
1488
+ };
1489
+ }
1490
+ if (args.mode === "targetRate" || args.mode === "targetApr") {
1491
+ let rewardRate;
1492
+ const {
1493
+ minRewardDurationForTargetRate: _providedMinRewardDurationForTargetRate,
1494
+ currentDuration
1495
+ } = args;
1496
+ if (args.mode === "targetRate") {
1497
+ rewardRate = args.rewardRate;
1498
+ } else {
1499
+ rewardRate = _getRewardRate(args.apr, bgtPrice, tvl);
1500
+ }
1501
+ if (rewardRate === 0) {
1502
+ const newDuration = Math.min(currentDuration, MAX_REWARD_DURATION);
1503
+ const rewardRate2 = availableRewards ? availableRewards / newDuration : 0;
1504
+ return {
1505
+ apr: _getApr(tvl, bgtPrice, rewardRate2),
1506
+ // When switching to duration mode, the current duration will be used if it's in the allowed range.
1507
+ // Current duration on chain can never be lower than MIN_REWARD_DURATION, so we just check the max.
1508
+ duration: newDuration,
1509
+ rewardRate: rewardRate2,
1510
+ targetRate: null,
1511
+ periodFinish: newDuration + currentTime,
1512
+ mode: "duration" /* Duration */
1513
+ };
1514
+ }
1515
+ const minRewardDurationForTargetRate = (
1516
+ // minRewardDurationForTargetRate might be zero the first time the target rate is set.
1517
+ // If it's not set, we use the max reward duration.
1518
+ _providedMinRewardDurationForTargetRate || MIN_REWARD_DURATION
1519
+ );
1520
+ const duration2 = availableRewards ? availableRewards / rewardRate : 0;
1521
+ if (duration2 < minRewardDurationForTargetRate) {
1522
+ const rewardRate2 = availableRewards ? availableRewards / minRewardDurationForTargetRate : 0;
1523
+ return {
1524
+ apr: _getApr(tvl, bgtPrice, rewardRate2),
1525
+ duration: minRewardDurationForTargetRate,
1526
+ rewardRate: rewardRate2,
1527
+ targetRate: rewardRate2.toString(),
1528
+ periodFinish: minRewardDurationForTargetRate + currentTime,
1529
+ mode: null
1530
+ };
1531
+ }
1532
+ return {
1533
+ apr: _getApr(tvl, bgtPrice, rewardRate),
1534
+ duration: duration2,
1535
+ rewardRate,
1536
+ targetRate: rewardRate.toString(),
1537
+ periodFinish: duration2 + currentTime,
1538
+ mode: null
1539
+ };
1540
+ }
1541
+ const { duration } = args;
1542
+ const newRewardRate = availableRewards / duration;
1543
+ const apr = _getApr(tvl, bgtPrice, newRewardRate);
1544
+ return {
1545
+ apr,
1546
+ mode: null,
1547
+ targetRate: null,
1548
+ duration,
1549
+ rewardRate: newRewardRate,
1550
+ periodFinish: duration + currentTime
1551
+ };
1552
+ }
1553
+
1554
+ // src/actions/pol/getEarnedStakedBeraVault.ts
1555
+ async function getEarnedStakedBeraVault({
1556
+ address,
1557
+ account,
1558
+ ...args
1559
+ }) {
1560
+ const { config } = parseBaseArgs(args);
1561
+ if (!config.beep) {
1562
+ return fetchRailwayBackend(
1563
+ "/vaults/{vault}/earnings/{owner}",
1564
+ { path: { vault: address, owner: account } },
1565
+ args
1566
+ );
1567
+ }
1568
+ return fetchBeep(
1569
+ "/v0/stake/{vault}/earnings/{owner}",
1570
+ { path: { vault: address, owner: account } },
1571
+ args
1572
+ );
1573
+ }
1574
+
1575
+ // src/actions/pol/getRewardVaults.ts
1576
+ import { formatUnits as formatUnits6 } from "viem";
1577
+ import { rewardVaultAbi as rewardVaultAbi2 } from "@berachain/abis/pol/rewards/rewardVault";
1578
+ import {
1579
+ GetVaults
1580
+ } from "@berachain/graphql/pol/api";
1581
+ async function getRewardVaults({
1582
+ filter,
1583
+ publicClient,
1584
+ ...args
1585
+ } = {}) {
1586
+ const bexApiGraphqlClient = getApolloClient("api", args);
1587
+ const res = await bexApiGraphqlClient.query({
1588
+ query: GetVaults,
1589
+ variables: filter
1590
+ });
1591
+ const incentives = await Promise.allSettled(
1592
+ res.data.polGetRewardVaults.vaults.map(async (vault) => {
1593
+ if (!publicClient) return void 0;
1594
+ return Promise.allSettled(
1595
+ vault.activeIncentives.map(
1596
+ (incentive) => publicClient.readContract({
1597
+ abi: rewardVaultAbi2,
1598
+ address: vault.address,
1599
+ functionName: "incentives",
1600
+ args: [incentive.tokenAddress]
1601
+ })
1602
+ )
1603
+ );
1604
+ })
1605
+ );
1606
+ const vaults = res.data.polGetRewardVaults.vaults.map((vault, index) => {
1607
+ let totalIncentiveInUsdc = 0;
1608
+ const incentivesArray = vault.activeIncentives.map((apiIncentive, incIdx) => {
1609
+ const tokenPrice = Number(apiIncentive.remainingAmountUsd) && Number(apiIncentive.remainingAmount) ? Number(apiIncentive.remainingAmountUsd) / Number(apiIncentive.remainingAmount) : 0;
1610
+ const remainingAmount = incentives[index]?.status === "fulfilled" && incentives[index]?.value?.[incIdx]?.status === "fulfilled" ? formatUnits6(
1611
+ BigInt(incentives[index].value[incIdx].value[2]),
1612
+ apiIncentive.token.decimals
1613
+ ) : apiIncentive.remainingAmount;
1614
+ totalIncentiveInUsdc += Number(remainingAmount) * Number(tokenPrice);
1615
+ return {
1616
+ ...apiIncentive,
1617
+ remainingAmount
1618
+ };
1619
+ });
1620
+ return {
1621
+ ...vault,
1622
+ dynamicData: {
1623
+ ...vault.dynamicData,
1624
+ allTimeRewards: vault.dynamicData?.allTimeRewards ?? "0",
1625
+ rewardCapturePercentage: vault.dynamicData?.rewardCapturePercentage ?? 0,
1626
+ activeIncentivesValueUsd: totalIncentiveInUsdc.toString(),
1627
+ activeIncentivesRateUsd: vault.dynamicData?.activeIncentivesRateUsd ?? "0",
1628
+ rewardCapturePerBlock: vault.dynamicData?.rewardCapturePerBlock ?? 0
1629
+ },
1630
+ activeIncentives: incentivesArray
1631
+ };
1632
+ });
1633
+ return {
1634
+ pagination: res.data.polGetRewardVaults.pagination,
1635
+ gaugeList: vaults
1636
+ };
1637
+ }
1638
+
1639
+ // src/actions/pol/getBGTGlobalInfo.ts
1640
+ import {
1641
+ GlobalData
1642
+ } from "@berachain/graphql/pol/api";
1643
+ async function getBGTGlobalInfo(args = {}) {
1644
+ const { config } = parseBaseArgs(args);
1645
+ const bexApiGraphqlClient = getApolloClient("api", args);
1646
+ const apiRes = await bexApiGraphqlClient.query({
1647
+ query: GlobalData,
1648
+ variables: {
1649
+ chain: config.bex.chainName
1650
+ }
1651
+ });
1652
+ const data = apiRes.data;
1653
+ return {
1654
+ ...data.polGetGlobalInfo,
1655
+ top3EmittingValidators: apiRes.data.top3EmittingValidators.validators,
1656
+ allValidatorsCount: apiRes.data.allValidatorsCount.pagination.totalCount
1657
+ };
1658
+ }
1659
+
1660
+ // src/actions/pol/getBgtTokenTotalBoosts.ts
1661
+ import { formatEther as formatEther3 } from "viem";
1662
+ import { bgtAbi } from "@berachain/abis/pol/bgt";
1663
+ async function getBgtTokenTotalBoosts({
1664
+ publicClient,
1665
+ ...args
1666
+ }) {
1667
+ const { config } = parseBaseArgs(args);
1668
+ assertPublicClient(publicClient);
1669
+ try {
1670
+ const result = await publicClient.readContract({
1671
+ address: config.tokens.bgt,
1672
+ abi: bgtAbi,
1673
+ functionName: "totalBoosts",
1674
+ args: []
1675
+ });
1676
+ return formatEther3(result);
1677
+ } catch (error) {
1678
+ console.log(error);
1679
+ throw error;
1680
+ }
1681
+ }
1682
+
1683
+ // src/actions/pol/getBgtTokenTotalSupply.ts
1684
+ import { erc20Abi as erc20Abi3, formatEther as formatEther4 } from "viem";
1685
+ async function getBgtTokenTotalSupply({
1686
+ publicClient,
1687
+ ...args
1688
+ }) {
1689
+ const { config } = parseBaseArgs(args);
1690
+ assertPublicClient(publicClient);
1691
+ try {
1692
+ const result = await publicClient.readContract({
1693
+ address: config.tokens.bgt,
1694
+ abi: erc20Abi3,
1695
+ functionName: "totalSupply",
1696
+ args: []
1697
+ });
1698
+ return formatEther4(result ?? 0n);
1699
+ } catch (error) {
1700
+ console.log(error);
1701
+ throw error;
1702
+ }
1703
+ }
1704
+
1705
+ // src/actions/pol/getGlobalCuttingBoard.ts
1706
+ import {
1707
+ GqlRewardVaultOrderBy,
1708
+ GqlRewardVaultOrderDirection
1709
+ } from "@berachain/graphql/pol/api";
1710
+ async function getGlobalCuttingBoard(threshold) {
1711
+ const { gaugeList } = await getRewardVaults({
1712
+ filter: {
1713
+ // TODO sort by bgt capture percentage
1714
+ orderBy: GqlRewardVaultOrderBy.Apr,
1715
+ orderDirection: GqlRewardVaultOrderDirection.Desc,
1716
+ pageSize: threshold,
1717
+ where: {
1718
+ includeNonWhitelisted: false
1719
+ }
1720
+ }
1721
+ });
1722
+ return gaugeList;
1723
+ }
1724
+
1725
+ // src/actions/pol/getGlobalData.ts
1726
+ async function getGlobalData(publicClient) {
1727
+ const [
1728
+ globalDataRes,
1729
+ globalCuttingBoardRes,
1730
+ bgtTotalSupplyRes,
1731
+ bgtTotalBoostsRes
1732
+ ] = await Promise.allSettled([
1733
+ getBGTGlobalInfo(),
1734
+ getGlobalCuttingBoard(300),
1735
+ getBgtTokenTotalSupply({
1736
+ publicClient
1737
+ }),
1738
+ getBgtTokenTotalBoosts({
1739
+ publicClient
1740
+ })
1741
+ ]);
1742
+ if (globalDataRes.status === "rejected") {
1743
+ BeraMonitoring.captureException(
1744
+ initBeraError({ cause: globalDataRes.reason, level: "warning" })
1745
+ );
1746
+ }
1747
+ if (globalCuttingBoardRes.status === "rejected") {
1748
+ BeraMonitoring.captureException(
1749
+ initBeraError({ cause: globalCuttingBoardRes.reason, level: "warning" })
1750
+ );
1751
+ }
1752
+ if (bgtTotalSupplyRes.status === "rejected") {
1753
+ BeraMonitoring.captureException(
1754
+ initBeraError({ cause: bgtTotalSupplyRes.reason, level: "warning" })
1755
+ );
1756
+ }
1757
+ if (bgtTotalBoostsRes.status === "rejected") {
1758
+ BeraMonitoring.captureException(
1759
+ initBeraError({ cause: bgtTotalBoostsRes.reason, level: "warning" })
1760
+ );
1761
+ }
1762
+ return {
1763
+ bgtTotalSupply: bgtTotalSupplyRes.status === "fulfilled" ? bgtTotalSupplyRes.value : void 0,
1764
+ globalCuttingBoard: globalCuttingBoardRes.status === "fulfilled" ? globalCuttingBoardRes.value : [],
1765
+ bgtTotalBoosts: bgtTotalBoostsRes.status === "fulfilled" ? bgtTotalBoostsRes.value : void 0,
1766
+ ...globalDataRes.status === "fulfilled" ? globalDataRes.value : {}
1767
+ };
1768
+ }
1769
+
1770
+ // src/actions/pol/getIncentiveFeeClaimStats.ts
1771
+ async function getIncentiveFeeClaimStats() {
1772
+ if (typeof window === "undefined") {
1773
+ throw new BeraError({
1774
+ message: "getIncentiveFeeClaimStats is browser-only; call from a Client Component / SWR hook",
1775
+ level: "error"
1776
+ });
1777
+ }
1778
+ return beraFetchJson({
1779
+ url: "/api/pol/incentive-fee-claims",
1780
+ name: "pol-incentive-fee-claims",
1781
+ type: "rest"
1782
+ });
1783
+ }
1784
+
1785
+ // src/actions/pol/getMarkets.ts
1786
+ async function getMarkets(args = {}) {
1787
+ const { config } = parseBaseArgs(args);
1788
+ try {
1789
+ const markets = await fetch(config.lists.rewardVaultList);
1790
+ const temp = await markets.json();
1791
+ if (!temp.protocols) {
1792
+ throw new Error("Missing protocols in market list");
1793
+ }
1794
+ return {
1795
+ marketList: temp.protocols,
1796
+ marketDictionary: temp.protocols.reduce(
1797
+ (acc, item) => {
1798
+ acc[item.name] = item;
1799
+ return acc;
1800
+ },
1801
+ {}
1802
+ )
1803
+ };
1804
+ } catch (error) {
1805
+ console.error("Error fetching validator information", error);
1806
+ throw error;
1807
+ }
1808
+ }
1809
+
1810
+ // src/actions/pol/getRewardProofsByValidator.ts
1811
+ async function getRewardProofsByValidator({
1812
+ account,
1813
+ validator,
1814
+ page = 1,
1815
+ perPage = 1e3,
1816
+ ...args
1817
+ }) {
1818
+ const { config } = parseBaseArgs(args);
1819
+ const result = await fetch(
1820
+ `${config.pol.bribeBoostApi}/api/v1/wallets/${account.toLowerCase()}/proofs/validator/${validator.toLowerCase()}?page=${page}&per_page=${perPage}`,
1821
+ {
1822
+ cache: "no-store"
1823
+ }
1824
+ );
1825
+ if (!result.ok) {
1826
+ const error = await getErrorResponse(result);
1827
+ throw new BeraError({
1828
+ message: "Failed to fetch proofs on server",
1829
+ cause: {
1830
+ error,
1831
+ result,
1832
+ account,
1833
+ validator
1834
+ },
1835
+ reason: error?.reason
1836
+ });
1837
+ }
1838
+ const data = await result.json();
1839
+ return data;
1840
+ }
1841
+
1842
+ // src/actions/pol/getRewardTokenToBeraRate.ts
1843
+ import { formatUnits as formatUnits7, parseUnits as parseUnits5 } from "viem";
1844
+ import { wberaStakerVaultAbi as stakeBeraVaultAbi } from "@berachain/abis/pol/wberaStakerVault";
1845
+ async function getRewardTokenToBeraRate({
1846
+ address,
1847
+ publicClient
1848
+ }) {
1849
+ assertPublicClient(publicClient);
1850
+ return publicClient.readContract({
1851
+ address,
1852
+ abi: stakeBeraVaultAbi,
1853
+ functionName: "previewRedeem",
1854
+ args: [parseUnits5("1", 18)]
1855
+ }).then((rate) => Number(formatUnits7(rate, 18))).catch(() => 0);
1856
+ }
1857
+
1858
+ // src/actions/pol/getRewardVault.ts
1859
+ import {
1860
+ GetRewardVault
1861
+ } from "@berachain/graphql/pol/api";
1862
+ async function getRewardVault({
1863
+ address,
1864
+ chainName,
1865
+ ...args
1866
+ }) {
1867
+ const { config } = parseBaseArgs(args);
1868
+ const resolvedChainName = chainName ?? config.bex.chainName;
1869
+ const bexApiGraphqlClient = getApolloClient("api", args);
1870
+ const { data } = await bexApiGraphqlClient.query({
1871
+ query: GetRewardVault,
1872
+ variables: {
1873
+ vaultId: address,
1874
+ chain: resolvedChainName
1875
+ }
1876
+ });
1877
+ if (!data?.rewardVault) {
1878
+ throw new NotFoundError({
1879
+ resource: "Reward vault",
1880
+ id: address,
1881
+ chainId: config.chainId
1882
+ });
1883
+ }
1884
+ return data.rewardVault;
1885
+ }
1886
+
1887
+ // src/actions/pol/getRewardVaultIncentives.ts
1888
+ import { isSameAddress } from "@berachain-foundation/berancer-sdk";
1889
+ import {
1890
+ erc20Abi as erc20Abi4,
1891
+ formatUnits as formatUnits8
1892
+ } from "viem";
1893
+ import { rewardVaultAbi as rewardVaultAbi3 } from "@berachain/abis/pol/rewards/rewardVault";
1894
+ function multicallResult(result, fallback) {
1895
+ return result.status === "success" ? result.result : fallback;
1896
+ }
1897
+ async function getRewardVaultIncentives({
1898
+ address,
1899
+ stakingToken,
1900
+ publicClient
1901
+ }) {
1902
+ const whitelistedTokens = await publicClient.readContract({
1903
+ address,
1904
+ abi: rewardVaultAbi3,
1905
+ functionName: "getWhitelistedTokens"
1906
+ });
1907
+ const hasStakingTokenAsIncentiveToken = whitelistedTokens.findIndex(
1908
+ (token) => isSameAddress(stakingToken, token)
1909
+ ) !== -1;
1910
+ const totalSupply = hasStakingTokenAsIncentiveToken ? await publicClient.readContract({
1911
+ address,
1912
+ abi: rewardVaultAbi3,
1913
+ functionName: "totalSupply"
1914
+ }) : 0n;
1915
+ const incentives = await Promise.allSettled(
1916
+ whitelistedTokens.map(async (token) => {
1917
+ const [incentiveInfo, decimals, name, symbol, totalBalance] = await publicClient.multicall({
1918
+ allowFailure: true,
1919
+ contracts: [
1920
+ {
1921
+ address,
1922
+ abi: rewardVaultAbi3,
1923
+ functionName: "incentives",
1924
+ args: [token]
1925
+ },
1926
+ {
1927
+ address: token,
1928
+ abi: erc20Abi4,
1929
+ functionName: "decimals"
1930
+ },
1931
+ {
1932
+ address: token,
1933
+ abi: erc20Abi4,
1934
+ functionName: "name"
1935
+ },
1936
+ {
1937
+ address: token,
1938
+ abi: erc20Abi4,
1939
+ functionName: "symbol"
1940
+ },
1941
+ {
1942
+ address: token,
1943
+ abi: erc20Abi4,
1944
+ functionName: "balanceOf",
1945
+ args: [address]
1946
+ }
1947
+ ]
1948
+ });
1949
+ if (incentiveInfo.status === "failure") {
1950
+ throw new BeraError({
1951
+ cause: incentiveInfo.error,
1952
+ message: "Failed to get incentive info. This is not possible.",
1953
+ level: "error",
1954
+ extra: {
1955
+ token,
1956
+ address
1957
+ }
1958
+ });
1959
+ }
1960
+ const [minIncentiveRate, incentiveRate, remainingAmount, manager] = incentiveInfo.result;
1961
+ const decimalsResult = multicallResult(decimals, 18);
1962
+ return {
1963
+ token,
1964
+ manager,
1965
+ minIncentiveRate: formatUnits8(minIncentiveRate, decimalsResult),
1966
+ incentiveRate: formatUnits8(incentiveRate, decimalsResult),
1967
+ remainingAmount: formatUnits8(remainingAmount, decimalsResult),
1968
+ name: multicallResult(name, void 0),
1969
+ symbol: multicallResult(symbol, void 0),
1970
+ decimals: decimalsResult,
1971
+ pendingAmount: isSameAddress(stakingToken, token) ? formatUnits8(
1972
+ multicallResult(totalBalance, 0n) - totalSupply - remainingAmount,
1973
+ decimalsResult
1974
+ ) : formatUnits8(
1975
+ multicallResult(totalBalance, 0n) - remainingAmount,
1976
+ decimalsResult
1977
+ )
1978
+ };
1979
+ })
1980
+ );
1981
+ incentives.forEach((result, index) => {
1982
+ if (result.status === "rejected") {
1983
+ BeraMonitoring.captureException(
1984
+ new BeraError({
1985
+ reason: result.reason,
1986
+ message: "Incorrect incentives token received.",
1987
+ level: "error",
1988
+ extra: {
1989
+ token: whitelistedTokens[index],
1990
+ address,
1991
+ error: result.reason
1992
+ }
1993
+ })
1994
+ );
1995
+ }
1996
+ });
1997
+ return incentives.map((result) => result.status === "fulfilled" ? result.value : null).filter((incentive) => incentive !== null);
1998
+ }
1999
+
2000
+ // src/actions/pol/getRewardVaultStakingToken.ts
2001
+ import { rewardVaultAbi as rewardVaultAbi4 } from "@berachain/abis/pol/rewards/rewardVault";
2002
+ async function getRewardVaultStakingToken({
2003
+ address,
2004
+ publicClient
2005
+ }) {
2006
+ const vaultAddress = await publicClient.readContract({
2007
+ address,
2008
+ abi: rewardVaultAbi4,
2009
+ functionName: "stakeToken"
2010
+ });
2011
+ return vaultAddress;
2012
+ }
2013
+
2014
+ // src/actions/pol/getStakedBeraAPR.ts
2015
+ import {
2016
+ GetSWberaVaultMetadata,
2017
+ GqlSWberaVaultMetadataResolution
2018
+ } from "@berachain/graphql/pol/api";
2019
+ function getResolution(window2) {
2020
+ if (window2 === "DAY") {
2021
+ return GqlSWberaVaultMetadataResolution.OneDay;
2022
+ }
2023
+ return GqlSWberaVaultMetadataResolution.SevenDays;
2024
+ }
2025
+ async function getStakedBeraAPR({
2026
+ window: window2,
2027
+ ...args
2028
+ }) {
2029
+ const { config } = parseBaseArgs(args);
2030
+ const bexApiGraphqlClient = getApolloClient("api", args);
2031
+ try {
2032
+ const data = await bexApiGraphqlClient.query({
2033
+ query: GetSWberaVaultMetadata,
2034
+ variables: {
2035
+ chain: config.bex.chainName,
2036
+ resolution: getResolution(window2 ?? "DAY")
2037
+ }
2038
+ });
2039
+ const { apr } = data.data.polGetSWberaVaultMetadata;
2040
+ return Number(apr);
2041
+ } catch (error) {
2042
+ console.error("Failed to get SW Bera APR", error);
2043
+ throw error;
2044
+ }
2045
+ }
2046
+
2047
+ // src/actions/pol/getStakedBeraSnapshots.ts
2048
+ import {
2049
+ GetSWberaVaultSnapshots,
2050
+ GqlVaultSnapshotDataRange
2051
+ } from "@berachain/graphql/pol/api";
2052
+ async function getStakedBeraSnapshots({
2053
+ chain,
2054
+ range = GqlVaultSnapshotDataRange.ThirtyDays,
2055
+ ...args
2056
+ } = {}) {
2057
+ const { config } = parseBaseArgs(args);
2058
+ const bexApiGraphqlClient = getApolloClient("api", args);
2059
+ try {
2060
+ const data = await bexApiGraphqlClient.query({
2061
+ query: GetSWberaVaultSnapshots,
2062
+ variables: {
2063
+ chain: chain ?? config.bex.chainName,
2064
+ range
2065
+ }
2066
+ });
2067
+ return data.data.polGetSWberaVaultSnapshots;
2068
+ } catch (error) {
2069
+ console.error("Failed to get SW Bera Snapshots", error);
2070
+ throw error;
2071
+ }
2072
+ }
2073
+
2074
+ // src/actions/pol/getStakeWithdrawalCooldown.ts
2075
+ import { wberaStakerVaultAbi as stakeBeraVaultAbi2 } from "@berachain/abis/pol/wberaStakerVault";
2076
+ async function getStakeWithdrawalCooldown({
2077
+ publicClient,
2078
+ address
2079
+ }) {
2080
+ const lockPeriod = await publicClient.readContract({
2081
+ address,
2082
+ abi: stakeBeraVaultAbi2,
2083
+ functionName: "WITHDRAWAL_COOLDOWN"
2084
+ });
2085
+ return Number(lockPeriod);
2086
+ }
2087
+
2088
+ // src/actions/pol/getSWBeraVaultMetadata.ts
2089
+ import { erc20Abi as erc20Abi5, erc4626Abi } from "viem";
2090
+ async function getSWBeraVaultMetadata({
2091
+ address,
2092
+ underlyingAsset,
2093
+ publicClient,
2094
+ blockTime
2095
+ }) {
2096
+ assertPublicClient(publicClient);
2097
+ const hoursWindow = 26;
2098
+ try {
2099
+ const currentBlock = await publicClient.getBlock({ blockTag: "latest" });
2100
+ const blocksPerWindow = Math.floor(hoursWindow * 60 * 60 / blockTime);
2101
+ const blockWindowAgo = currentBlock.number - BigInt(blocksPerWindow);
2102
+ const [
2103
+ curretTotalAssets,
2104
+ currentTotalSupply,
2105
+ currentOneShareWorth,
2106
+ currentTVL,
2107
+ totalAssets24HoursAgo,
2108
+ totalSupply24HoursAgo,
2109
+ oneShareWorthWindowAgo,
2110
+ tvl24HoursAgo,
2111
+ underlyingTotalSupply,
2112
+ lockPeriod,
2113
+ incentiveFeeClaimStats
2114
+ ] = await Promise.all([
2115
+ publicClient.readContract({
2116
+ address,
2117
+ abi: erc4626Abi,
2118
+ functionName: "totalAssets"
2119
+ }),
2120
+ publicClient.readContract({
2121
+ address,
2122
+ abi: erc4626Abi,
2123
+ functionName: "totalSupply"
2124
+ }),
2125
+ publicClient.readContract({
2126
+ address,
2127
+ abi: erc4626Abi,
2128
+ functionName: "previewRedeem",
2129
+ args: [10n ** 18n],
2130
+ blockNumber: currentBlock.number
2131
+ }),
2132
+ publicClient.readContract({
2133
+ address: underlyingAsset,
2134
+ abi: erc20Abi5,
2135
+ functionName: "balanceOf",
2136
+ args: [address]
2137
+ }),
2138
+ publicClient.readContract({
2139
+ address,
2140
+ abi: erc4626Abi,
2141
+ functionName: "totalAssets",
2142
+ blockNumber: blockWindowAgo
2143
+ }),
2144
+ publicClient.readContract({
2145
+ address,
2146
+ abi: erc20Abi5,
2147
+ functionName: "totalSupply",
2148
+ blockNumber: blockWindowAgo
2149
+ }),
2150
+ publicClient.readContract({
2151
+ address,
2152
+ abi: erc4626Abi,
2153
+ functionName: "previewRedeem",
2154
+ args: [10n ** 18n],
2155
+ blockNumber: blockWindowAgo
2156
+ }),
2157
+ publicClient.readContract({
2158
+ address: underlyingAsset,
2159
+ abi: erc20Abi5,
2160
+ functionName: "balanceOf",
2161
+ args: [address],
2162
+ blockNumber: blockWindowAgo
2163
+ }),
2164
+ publicClient.readContract({
2165
+ address: underlyingAsset,
2166
+ abi: erc20Abi5,
2167
+ functionName: "totalSupply"
2168
+ }),
2169
+ getStakeWithdrawalCooldown({
2170
+ publicClient,
2171
+ address
2172
+ }),
2173
+ getIncentiveFeeClaimStats()
2174
+ ]);
2175
+ const exchangeRateWindowAgo = new bignumber_js_default(
2176
+ oneShareWorthWindowAgo.toString()
2177
+ );
2178
+ const currentExchangeRate = new bignumber_js_default(currentOneShareWorth.toString());
2179
+ return {
2180
+ address,
2181
+ current: {
2182
+ exchangeRate: currentExchangeRate.toString(),
2183
+ totalSupply: new bignumber_js_default(currentTotalSupply.toString()).dividedBy(1e18).toString(),
2184
+ totalAssets: new bignumber_js_default(curretTotalAssets.toString()).dividedBy(1e18).toString(),
2185
+ tvl: new bignumber_js_default(currentTVL.toString()).dividedBy(1e18).toString()
2186
+ },
2187
+ previous: {
2188
+ exchangeRate: exchangeRateWindowAgo.toString(),
2189
+ totalSupply: new bignumber_js_default(totalSupply24HoursAgo.toString()).dividedBy(1e18).toString(),
2190
+ totalAssets: new bignumber_js_default(totalAssets24HoursAgo.toString()).dividedBy(1e18).toString(),
2191
+ tvl: new bignumber_js_default(tvl24HoursAgo.toString()).dividedBy(1e18).toString()
2192
+ },
2193
+ totalWBeraIssued: new bignumber_js_default(underlyingTotalSupply.toString()).dividedBy(1e18).toString(),
2194
+ lockPeriod,
2195
+ totalBuyBacks: incentiveFeeClaimStats.sumAllClaims,
2196
+ totalBuyBacksInLast24Hours: incentiveFeeClaimStats.sumClaimsInLast24Hours
2197
+ };
2198
+ } catch (error) {
2199
+ console.error("Failed to get SW Bera Vault Metadata", error);
2200
+ throw error;
2201
+ }
2202
+ }
2203
+
2204
+ // src/actions/pol/getSWBeraWithdrawal.ts
2205
+ import { wberaStakerVaultAbi as stakeBeraVaultAbi3 } from "@berachain/abis/pol/wberaStakerVault";
2206
+ function getTimeUntil(targetTime) {
2207
+ const currentTime = Date.now();
2208
+ const timeDiff = targetTime * 1e3 - currentTime;
2209
+ if (timeDiff <= 0) {
2210
+ return;
2211
+ }
2212
+ const totalSeconds = msToSeconds(timeDiff);
2213
+ return formatTimeLeft(totalSeconds, true, true);
2214
+ }
2215
+ async function getSWBeraWithdrawal({
2216
+ contractAddress,
2217
+ accountAddress,
2218
+ publicClient,
2219
+ version
2220
+ }) {
2221
+ const withdrawalRequests = [];
2222
+ function withdrawalRequestV1Helper(withdrawalRequest, lockPeriod) {
2223
+ const [assets, _shares, timestamp] = withdrawalRequest;
2224
+ const withdrawalAmount = assets;
2225
+ const readyTime = Number(timestamp) + Number(lockPeriod);
2226
+ const currentTime = msToSeconds(Date.now());
2227
+ const timeLeft = readyTime - currentTime;
2228
+ if (withdrawalAmount > 0) {
2229
+ const timeRemaining = getTimeUntil(timeLeft <= 0 ? 0 : readyTime);
2230
+ withdrawalRequests.push({
2231
+ receiptTokenAddress: contractAddress,
2232
+ withdrawalAmount,
2233
+ timeRemaining
2234
+ });
2235
+ }
2236
+ }
2237
+ switch (version) {
2238
+ case "V1": {
2239
+ const [withdrawalRequest, lockPeriod] = await Promise.all([
2240
+ publicClient.readContract({
2241
+ address: contractAddress,
2242
+ abi: stakeBeraVaultAbi3,
2243
+ functionName: "withdrawalRequests",
2244
+ args: [accountAddress]
2245
+ }),
2246
+ getStakeWithdrawalCooldown({
2247
+ publicClient,
2248
+ address: contractAddress
2249
+ })
2250
+ ]);
2251
+ withdrawalRequestV1Helper(withdrawalRequest, lockPeriod);
2252
+ return withdrawalRequests;
2253
+ }
2254
+ case "V2": {
2255
+ const [withdrawalRequestIds, lockPeriod] = await Promise.all([
2256
+ publicClient.readContract({
2257
+ address: contractAddress,
2258
+ abi: stakeBeraVaultAbi3,
2259
+ functionName: "getERC721WithdrawalRequestIds",
2260
+ args: [accountAddress]
2261
+ }),
2262
+ getStakeWithdrawalCooldown({
2263
+ publicClient,
2264
+ address: contractAddress
2265
+ })
2266
+ ]);
2267
+ if (isToken(contractAddress, "SWBERA")) {
2268
+ const withdrawalRequestV1 = await publicClient.readContract({
2269
+ address: contractAddress,
2270
+ abi: stakeBeraVaultAbi3,
2271
+ functionName: "withdrawalRequests",
2272
+ args: [accountAddress]
2273
+ });
2274
+ withdrawalRequestV1Helper(withdrawalRequestV1, lockPeriod);
2275
+ }
2276
+ const withdrawalResults = await Promise.all(
2277
+ withdrawalRequestIds.map(
2278
+ async (withdrawalRequestId) => {
2279
+ const withdrawalRequest = await publicClient.readContract({
2280
+ address: contractAddress,
2281
+ abi: stakeBeraVaultAbi3,
2282
+ functionName: "getERC721WithdrawalRequest",
2283
+ args: [withdrawalRequestId]
2284
+ });
2285
+ const { assets, requestTime: timestamp } = withdrawalRequest;
2286
+ if (!assets || !timestamp)
2287
+ throw new Error("Invalid withdrawal request");
2288
+ const withdrawalAmount = assets;
2289
+ const readyTime = Number(timestamp) + Number(lockPeriod);
2290
+ const currentTime = msToSeconds(Date.now());
2291
+ const timeLeft = readyTime - currentTime;
2292
+ if (withdrawalAmount > 0) {
2293
+ const timeRemaining = getTimeUntil(timeLeft <= 0 ? 0 : readyTime);
2294
+ return {
2295
+ withdrawalAmount,
2296
+ timeRemaining,
2297
+ withdrawalRequestId,
2298
+ receiptTokenAddress: contractAddress
2299
+ };
2300
+ }
2301
+ return null;
2302
+ }
2303
+ )
2304
+ );
2305
+ const filteredRequests = withdrawalResults.filter(
2306
+ (request) => request !== null
2307
+ );
2308
+ withdrawalRequests.push(...filteredRequests);
2309
+ return withdrawalRequests;
2310
+ }
2311
+ }
2312
+ }
2313
+
2314
+ // src/actions/pol/getTotalStakedAmount.ts
2315
+ import { wberaStakerVaultAbi as stakeBeraVaultAbi4 } from "@berachain/abis/pol/wberaStakerVault";
2316
+ async function getTotalStakedAmount({
2317
+ vaultAddresses,
2318
+ publicClient
2319
+ }) {
2320
+ assertPublicClient(publicClient);
2321
+ try {
2322
+ const totalAssets = await Promise.all(
2323
+ vaultAddresses.map(async (address) => {
2324
+ return publicClient.readContract({
2325
+ address,
2326
+ abi: stakeBeraVaultAbi4,
2327
+ functionName: "totalAssets"
2328
+ });
2329
+ })
2330
+ );
2331
+ const stakedAmount = vaultAddresses.reduce(
2332
+ (acc, address, index) => {
2333
+ acc[address] = totalAssets[index];
2334
+ return acc;
2335
+ },
2336
+ {}
2337
+ );
2338
+ return stakedAmount;
2339
+ } catch (error) {
2340
+ console.error("Failed to get total staked amount", error);
2341
+ throw error;
2342
+ }
2343
+ }
2344
+
2345
+ // src/actions/pol/getUserClaimableIncentives.ts
2346
+ async function getUserClaimableIncentives({
2347
+ account,
2348
+ ...args
2349
+ }) {
2350
+ const { config } = parseBaseArgs(args);
2351
+ const result = await fetch(
2352
+ `${config.pol.bribeBoostApi}/api/v1/wallets/${account.toLowerCase()}/rewards/aggregation`,
2353
+ {
2354
+ cache: "no-store"
2355
+ }
2356
+ );
2357
+ if (!result.ok) {
2358
+ const error = await getErrorResponse(result);
2359
+ throw new BeraError({
2360
+ message: "Failed to fetch incentives on server",
2361
+ cause: { error, result, account },
2362
+ reason: error?.error
2363
+ });
2364
+ }
2365
+ return result.json();
2366
+ }
2367
+
2368
+ // src/actions/pol/getUserVaultsReward.ts
2369
+ import { rewardVaultAbi as rewardVaultAbi5 } from "@berachain/abis/pol/rewards/rewardVault";
2370
+ async function getUserVaultsReward({
2371
+ account,
2372
+ vaultAddress,
2373
+ publicClient
2374
+ }) {
2375
+ if (!publicClient) throw new Error("Missing public client");
2376
+ if (!account) throw new Error("Missing user account");
2377
+ if (!vaultAddress) throw new Error("Missing vault address");
2378
+ return publicClient.readContract({
2379
+ address: vaultAddress,
2380
+ abi: rewardVaultAbi5,
2381
+ functionName: "earned",
2382
+ args: [account]
2383
+ });
2384
+ }
2385
+
2386
+ // src/actions/pol/getUserVaultInfo.ts
2387
+ import { formatEther as formatEther5 } from "viem";
2388
+
2389
+ // src/actions/pol/getUserVaultsBalance.ts
2390
+ import { rewardVaultAbi as rewardVaultAbi6 } from "@berachain/abis/pol/rewards/rewardVault";
2391
+ async function getUserVaultsBalance({
2392
+ account,
2393
+ vaultAddress,
2394
+ publicClient
2395
+ }) {
2396
+ assertPublicClient(publicClient);
2397
+ assertAddress(account, "account");
2398
+ assertAddress(vaultAddress, "vaultAddress");
2399
+ try {
2400
+ const [balance, delegated] = await Promise.all([
2401
+ publicClient.readContract({
2402
+ address: vaultAddress,
2403
+ abi: rewardVaultAbi6,
2404
+ functionName: "balanceOf",
2405
+ args: [account]
2406
+ }),
2407
+ publicClient.readContract({
2408
+ address: vaultAddress,
2409
+ abi: rewardVaultAbi6,
2410
+ functionName: "getTotalDelegateStaked",
2411
+ args: [account]
2412
+ })
2413
+ ]);
2414
+ return { balance, delegated };
2415
+ } catch (error) {
2416
+ console.log(error);
2417
+ throw error;
2418
+ }
2419
+ }
2420
+
2421
+ // src/actions/pol/getVaultsSupply.ts
2422
+ import { rewardVaultAbi as rewardVaultAbi7 } from "@berachain/abis/pol/rewards/rewardVault";
2423
+ async function getVaultsSupply({
2424
+ vaultAddress,
2425
+ publicClient
2426
+ }) {
2427
+ if (!publicClient) throw new Error("Missing public client");
2428
+ if (!vaultAddress) throw new Error("Missing vault address");
2429
+ try {
2430
+ const result = await publicClient.readContract({
2431
+ address: vaultAddress,
2432
+ abi: rewardVaultAbi7,
2433
+ functionName: "totalSupply",
2434
+ args: []
2435
+ });
2436
+ return result;
2437
+ } catch (error) {
2438
+ console.log(error);
2439
+ throw error;
2440
+ }
2441
+ }
2442
+
2443
+ // src/actions/pol/getUserVaultInfo.ts
2444
+ async function getUserVaultInfo({
2445
+ account,
2446
+ vaultAddress,
2447
+ publicClient
2448
+ }) {
2449
+ const [userBalance, userReward, totalSupply] = await Promise.all([
2450
+ getUserVaultsBalance({
2451
+ account,
2452
+ vaultAddress,
2453
+ publicClient
2454
+ }),
2455
+ getUserVaultsReward({
2456
+ account,
2457
+ vaultAddress,
2458
+ publicClient
2459
+ }),
2460
+ getVaultsSupply({
2461
+ vaultAddress,
2462
+ publicClient
2463
+ })
2464
+ ]);
2465
+ const withdrawableBalance = userBalance.balance - userBalance.delegated;
2466
+ const percentage = totalSupply > 0n ? Number(
2467
+ Number.parseFloat(formatEther5(userBalance.balance)) / Number.parseFloat(formatEther5(totalSupply))
2468
+ ).toString() : "0";
2469
+ return {
2470
+ balance: userBalance.balance,
2471
+ delegatedBalance: userBalance.delegated,
2472
+ withdrawableBalance,
2473
+ rewards: formatEther5(userReward),
2474
+ percentage
2475
+ };
2476
+ }
2477
+
2478
+ // src/actions/pol/getUserVaults.ts
2479
+ import { formatUnits as formatUnits9 } from "viem";
2480
+ import { rewardVaultAbi as rewardVaultAbi8 } from "@berachain/abis/pol/rewards/rewardVault";
2481
+ import {
2482
+ GetUserVaults
2483
+ } from "@berachain/graphql/pol/api";
2484
+ async function getUserVaults({
2485
+ account,
2486
+ publicClient,
2487
+ ...args
2488
+ }) {
2489
+ const { config } = parseBaseArgs(args);
2490
+ const bexApiGraphqlClient = getApolloClient("api", args);
2491
+ const res = await bexApiGraphqlClient.query({
2492
+ query: GetUserVaults,
2493
+ variables: {
2494
+ userId: account,
2495
+ chain: config.bex.chainName
2496
+ }
2497
+ });
2498
+ const deposits = res.data?.userVaultDeposits?.deposits;
2499
+ if (!deposits) {
2500
+ return {
2501
+ totalBgtRewards: "0",
2502
+ vaults: [],
2503
+ totalStakedValue: 0
2504
+ };
2505
+ }
2506
+ const [earnedResult, balanceResult] = await Promise.all([
2507
+ // Fetch pending BGT rewards for each vault
2508
+ publicClient.multicall({
2509
+ allowFailure: false,
2510
+ contracts: deposits.map(
2511
+ (deposit) => ({
2512
+ address: deposit.vaultAddress,
2513
+ abi: rewardVaultAbi8,
2514
+ functionName: "earned",
2515
+ args: [account]
2516
+ })
2517
+ )
2518
+ }),
2519
+ // Fetch user balance of each vault
2520
+ publicClient.multicall({
2521
+ allowFailure: false,
2522
+ contracts: deposits.map(
2523
+ (deposit) => ({
2524
+ address: deposit.vaultAddress,
2525
+ abi: rewardVaultAbi8,
2526
+ functionName: "balanceOf",
2527
+ args: [account]
2528
+ })
2529
+ )
2530
+ })
2531
+ ]);
2532
+ const { userVaults, total } = deposits.reduce(
2533
+ (acc, deposit, index) => {
2534
+ const item = earnedResult[index];
2535
+ const balanceItem = balanceResult[index];
2536
+ acc.total += item;
2537
+ if (!deposit.vault) {
2538
+ BeraMonitoring.captureException(
2539
+ new BeraError({
2540
+ message: "Deposit data from API is missing vault",
2541
+ level: "error",
2542
+ extra: {
2543
+ deposit
2544
+ }
2545
+ })
2546
+ );
2547
+ console.error("Deposit data from API is missing vault", deposit);
2548
+ return acc;
2549
+ }
2550
+ if (item > 0n || balanceItem > 0n) {
2551
+ const stakingTokenPrice = deposit.vault.dynamicData?.tvl && // If staked amount is 0, we don't want to divide by 0
2552
+ Number(deposit.vault.stakingTokenAmount) !== 0 ? Number(deposit.vault.dynamicData?.tvl ?? 0) / Number(deposit.vault.stakingTokenAmount) : null;
2553
+ acc.userVaults.push({
2554
+ ...deposit,
2555
+ vault: deposit.vault,
2556
+ unclaimedBgt: formatUnits9(item, 18),
2557
+ formattedBalance: formatUnits9(
2558
+ balanceItem,
2559
+ deposit.vault.stakingToken.decimals
2560
+ ),
2561
+ stakingTokenPrice
2562
+ });
2563
+ }
2564
+ return acc;
2565
+ },
2566
+ {
2567
+ userVaults: [],
2568
+ total: 0n
2569
+ }
2570
+ );
2571
+ const sortedUserVaults = [...userVaults].sort((a, b) => {
2572
+ if (a.vault.isVaultWhitelisted && !b.vault.isVaultWhitelisted) {
2573
+ return -1;
2574
+ }
2575
+ if (!a.vault.isVaultWhitelisted && b.vault.isVaultWhitelisted) {
2576
+ return 1;
2577
+ }
2578
+ const aUnclaimed = Number.parseFloat(a.unclaimedBgt);
2579
+ const bUnclaimed = Number.parseFloat(b.unclaimedBgt);
2580
+ return bUnclaimed - aUnclaimed;
2581
+ });
2582
+ const totalStakedValue = sortedUserVaults.reduce((acc, vault) => {
2583
+ const tvl = Number(vault.vault.dynamicData?.tvl ?? 0);
2584
+ if (tvl === 0) {
2585
+ return acc;
2586
+ }
2587
+ const stakingTokenAmount = Number.parseFloat(
2588
+ vault.vault.stakingTokenAmount
2589
+ );
2590
+ const stakingTokenPrice = tvl / stakingTokenAmount;
2591
+ return acc + stakingTokenPrice * Number(vault.formattedBalance);
2592
+ }, 0);
2593
+ return {
2594
+ totalStakedValue,
2595
+ totalBgtRewards: formatUnits9(total, 18),
2596
+ vaults: sortedUserVaults
2597
+ };
2598
+ }
2599
+
2600
+ // src/actions/pol/getVaultHistory.ts
2601
+ import {
2602
+ GetVaultHistory
2603
+ } from "@berachain/graphql/pol/api";
2604
+ async function getVaultHistory({
2605
+ vault,
2606
+ chain,
2607
+ ...args
2608
+ }) {
2609
+ const { config } = parseBaseArgs(args);
2610
+ const bexApiGraphqlClient = getApolloClient("api", args);
2611
+ const result = await bexApiGraphqlClient.query({
2612
+ query: GetVaultHistory,
2613
+ variables: {
2614
+ ...args,
2615
+ vaultId: vault,
2616
+ chain: chain ?? config.bex.chainName
2617
+ }
2618
+ });
2619
+ return result.data.polGetRewardVaultSnapshots;
2620
+ }
2621
+
2622
+ // src/actions/pol/getVaultValidators.ts
2623
+ import {
2624
+ GetVaultValidators
2625
+ } from "@berachain/graphql/pol/api";
2626
+ async function getVaultValidators({
2627
+ address,
2628
+ onlyActiveValidators,
2629
+ ...args
2630
+ }) {
2631
+ const bexApiGraphqlClient = getApolloClient("api", args);
2632
+ const result = await bexApiGraphqlClient.query({
2633
+ query: GetVaultValidators,
2634
+ variables: { vaultId: address, isActive: onlyActiveValidators }
2635
+ });
2636
+ return result.data.validators.validators ?? [];
2637
+ }
2638
+
2639
+ // src/actions/prices/getTokenCurrentPrices.ts
2640
+ import { getAddress, zeroAddress as zeroAddress3 } from "viem";
2641
+ import {
2642
+ GetTokenCurrentPrices
2643
+ } from "@berachain/graphql/dex/api";
2644
+ async function getTokenCurrentPrices({
2645
+ addressIn: _addressIn,
2646
+ ...args
2647
+ }) {
2648
+ const { config, chainId } = parseBaseArgs(args);
2649
+ const addressIn = _addressIn.map((a) => a.toLowerCase()).filter((addr, idx, arr) => addr && arr.indexOf(addr) === idx);
2650
+ const bexApiGraphqlClient = getApolloClient("api", args);
2651
+ const { data } = await bexApiGraphqlClient.query({
2652
+ query: GetTokenCurrentPrices,
2653
+ variables: {
2654
+ chains: [config.bex.chainName],
2655
+ addressIn
2656
+ }
2657
+ });
2658
+ return data.tokenGetCurrentPrices.reduce(
2659
+ (map, tokenInformation) => {
2660
+ if (!tokenInformation.price || !tokenInformation.address) {
2661
+ return map;
2662
+ }
2663
+ const formattedAddress = tokenInformation.address;
2664
+ map[getAddress(formattedAddress)] = {
2665
+ price: getSafeNumber(tokenInformation.price.toString()),
2666
+ updatedAt: tokenInformation.updatedAt,
2667
+ chainId
2668
+ };
2669
+ map[formattedAddress.toLowerCase()] = {
2670
+ price: getSafeNumber(tokenInformation.price.toString()),
2671
+ updatedAt: tokenInformation.updatedAt,
2672
+ chainId
2673
+ };
2674
+ if (isToken(formattedAddress, "WBERA")) {
2675
+ map[zeroAddress3] = {
2676
+ price: getSafeNumber(tokenInformation.price.toString()),
2677
+ updatedAt: tokenInformation.updatedAt,
2678
+ chainId
2679
+ };
2680
+ map[config.tokens.bgt.toLowerCase()] = {
2681
+ price: getSafeNumber(tokenInformation.price.toString()),
2682
+ updatedAt: tokenInformation.updatedAt,
2683
+ chainId
2684
+ };
2685
+ map[config.tokens.bgt] = {
2686
+ price: getSafeNumber(tokenInformation.price.toString()),
2687
+ updatedAt: tokenInformation.updatedAt,
2688
+ chainId
2689
+ };
2690
+ }
2691
+ return map;
2692
+ },
2693
+ {}
2694
+ );
2695
+ }
2696
+
2697
+ // src/actions/tokens/getAllowances.ts
2698
+ import { getPublicClient } from "@wagmi/core";
2699
+ import {
2700
+ erc20Abi as erc20Abi6,
2701
+ formatUnits as formatUnits10
2702
+ } from "viem";
2703
+ async function getAllowances({
2704
+ items: itemsList,
2705
+ account,
2706
+ config
2707
+ }) {
2708
+ assertDefined(itemsList, "items");
2709
+ assertDefined(config, "config");
2710
+ assertDefined(account, "account");
2711
+ const tokensByChainId = Object.groupBy(
2712
+ itemsList,
2713
+ (item) => item.token.chainId
2714
+ );
2715
+ const res = await Promise.allSettled(
2716
+ Object.entries(tokensByChainId).map(async ([chainId, items]) => {
2717
+ if (!items) return [];
2718
+ const publicClient = getPublicClient(config, {
2719
+ chainId: Number(chainId)
2720
+ });
2721
+ assertPublicClient(publicClient, `publicClient ${chainId}`);
2722
+ const result = await publicClient.multicall({
2723
+ contracts: items.map(
2724
+ (item) => ({
2725
+ address: item.token.address,
2726
+ abi: erc20Abi6,
2727
+ functionName: "allowance",
2728
+ args: [account, item.spender]
2729
+ })
2730
+ )
2731
+ });
2732
+ const allowances = result.map((item, index) => {
2733
+ const token = items[index];
2734
+ if (item.error) {
2735
+ return void 0;
2736
+ }
2737
+ const resultAllowanceToken = {
2738
+ token: token.token,
2739
+ spender: token.spender,
2740
+ amount: token.amount,
2741
+ allowance: {
2742
+ raw: item.result.toString(),
2743
+ formatted: formatUnits10(item.result, token.token.decimals)
2744
+ },
2745
+ needsApproval: item.result < BigInt(token.amount.raw)
2746
+ };
2747
+ return resultAllowanceToken;
2748
+ });
2749
+ return allowances.filter((i) => Boolean(i));
2750
+ })
2751
+ );
2752
+ return res.flatMap(
2753
+ (result) => result.status === "fulfilled" ? result.value : void 0
2754
+ ).filter((i) => Boolean(i));
2755
+ }
2756
+
2757
+ // src/actions/transactions/beraWriteContract.ts
2758
+ import {
2759
+ getPublicClient as getPublicClient2,
2760
+ getWalletClient,
2761
+ switchChain
2762
+ } from "@wagmi/core";
2763
+ import {
2764
+ BaseError,
2765
+ createWalletClient,
2766
+ decodeErrorResult,
2767
+ HttpRequestError,
2768
+ http
2769
+ } from "viem";
2770
+ import { ChainId, defaultChainId } from "@berachain/config/internal";
2771
+
2772
+ // src/errors/getRevertReason.ts
2773
+ import {
2774
+ AbiFunctionSignatureNotFoundError,
2775
+ decodeFunctionData
2776
+ } from "viem";
2777
+ async function getRevertReason({
2778
+ publicClient,
2779
+ abi: providedAbi,
2780
+ ...params
2781
+ }) {
2782
+ const abi = [...commonAbiErrors, ...providedAbi ?? []];
2783
+ let blockNumber;
2784
+ let to;
2785
+ let account;
2786
+ let value;
2787
+ let data;
2788
+ let functionName;
2789
+ let args;
2790
+ if ("txHash" in params) {
2791
+ const tx = await publicClient.getTransaction({
2792
+ hash: params.txHash
2793
+ });
2794
+ if (!tx.to)
2795
+ throw new InvalidArgumentError({
2796
+ property: "tx",
2797
+ value: tx,
2798
+ expected: "Transaction",
2799
+ message: "Trying to get revert reason for a contract creation"
2800
+ });
2801
+ data = tx.input;
2802
+ to = tx.to;
2803
+ account = tx.from;
2804
+ value = tx.value;
2805
+ blockNumber = tx.blockNumber;
2806
+ } else {
2807
+ blockNumber = params.blockNumber;
2808
+ to = params.to;
2809
+ account = params.account;
2810
+ value = params.value;
2811
+ if ("data" in params) {
2812
+ data = params.data;
2813
+ } else if ("functionName" in params && "args" in params) {
2814
+ functionName = params.functionName;
2815
+ args = params.args;
2816
+ } else if (!value) {
2817
+ throw new InvalidArgumentError({
2818
+ property: "dataOrFunctionNameAndArgs",
2819
+ value: params,
2820
+ expected: "Hex or FunctionName and Args"
2821
+ });
2822
+ }
2823
+ }
2824
+ try {
2825
+ if (!abi) {
2826
+ if (data) {
2827
+ await publicClient.call({
2828
+ data,
2829
+ to,
2830
+ account,
2831
+ blockNumber,
2832
+ value
2833
+ });
2834
+ } else {
2835
+ throw new Error("Data is required if abi is not provided");
2836
+ }
2837
+ }
2838
+ if ("functionName" in params && "args" in params && params.functionName) {
2839
+ functionName = params.functionName;
2840
+ args = params.args;
2841
+ } else if (data) {
2842
+ if (!abi) {
2843
+ const res = await publicClient.call({
2844
+ data,
2845
+ to,
2846
+ account,
2847
+ blockNumber,
2848
+ value
2849
+ });
2850
+ throw new Error(
2851
+ `Getting revert reason for successful simulation. Data: ${data}`,
2852
+ { cause: res }
2853
+ );
2854
+ }
2855
+ try {
2856
+ const decoded = decodeFunctionData({
2857
+ abi,
2858
+ data
2859
+ });
2860
+ functionName = decoded.functionName;
2861
+ args = decoded.args;
2862
+ } catch (e) {
2863
+ if (e instanceof AbiFunctionSignatureNotFoundError) {
2864
+ await publicClient.call({
2865
+ data,
2866
+ to,
2867
+ account,
2868
+ blockNumber,
2869
+ value
2870
+ });
2871
+ }
2872
+ throw new Error("Data is required if abi is not provided");
2873
+ }
2874
+ } else {
2875
+ throw new Error("No data or function name and args provided");
2876
+ }
2877
+ if (abi && functionName) {
2878
+ await publicClient.simulateContract({
2879
+ functionName,
2880
+ args,
2881
+ abi,
2882
+ address: to,
2883
+ account,
2884
+ blockNumber
2885
+ });
2886
+ throw new TransactionFailedError({
2887
+ message: `Getting revert reason for successful simulation`,
2888
+ functionName,
2889
+ to,
2890
+ txHash: "txHash" in params ? params.txHash : void 0,
2891
+ input: params
2892
+ });
2893
+ }
2894
+ throw new Error("No data or function name and args provided");
2895
+ } catch (error) {
2896
+ if (error instanceof Error) {
2897
+ return parseViemError({ error, abi, revertIfUnknown: true });
2898
+ }
2899
+ throw error;
2900
+ }
2901
+ }
2902
+
2903
+ // src/actions/transactions/beraWriteContract.ts
2904
+ var defaultPollingInterval = seconds(1);
2905
+ var increaseByPercentage = (value, percentage) => {
2906
+ return value * (100n + BigInt(percentage)) / 100n;
2907
+ };
2908
+ function parseNonce({
2909
+ nonceResult,
2910
+ onWarning
2911
+ }) {
2912
+ if (nonceResult.status === "fulfilled") {
2913
+ if (nonceResult.value && nonceResult.value > Number.MAX_SAFE_INTEGER) {
2914
+ onWarning?.(
2915
+ new BeraError({
2916
+ message: "Nonce is too large. No nonce will be provided to avoid IntegerOutOfRangeError.",
2917
+ cause: nonceResult.value,
2918
+ level: "debug"
2919
+ })
2920
+ );
2921
+ return void 0;
2922
+ }
2923
+ return nonceResult.value;
2924
+ }
2925
+ return void 0;
2926
+ }
2927
+ function isImpersonateAccount(chainId = defaultChainId) {
2928
+ return chainId === ChainId.BEPOLIA ? process.env.NEXT_PUBLIC_80069_ANVIL_IMPERSONATE_ACCOUNT === "true" : process.env.NEXT_PUBLIC_80094_ANVIL_IMPERSONATE_ACCOUNT === "true";
2929
+ }
2930
+ async function beraWriteContract(args) {
2931
+ if (process.env.NODE_ENV === "development" && !args.contractName && // let's avoid this for eip5972 calls
2932
+ args.address && !("calls" in args || args.calls)) {
2933
+ console.warn(
2934
+ "beraWriteContract: Contract name is required. Either update the contract mapping in devrel or provide a contract name in ContractName enum",
2935
+ "This is a development error and will be thrown in development mode only."
2936
+ );
2937
+ throw new InvalidArgumentError({
2938
+ property: "contractName",
2939
+ value: args.contractName,
2940
+ expected: "ContractName",
2941
+ displayMessage: `[DEV] Contract name is required as it's not mapped in the devrel's contract mapping ${args.address}`,
2942
+ level: "error"
2943
+ });
2944
+ }
2945
+ const {
2946
+ address,
2947
+ calls,
2948
+ value,
2949
+ gasLimit,
2950
+ onLoading,
2951
+ onSuccess,
2952
+ onWarning,
2953
+ onError,
2954
+ onSubmission,
2955
+ wagmiConfig,
2956
+ walletClient: _walletClient,
2957
+ account: argsAccount,
2958
+ txConfirmationTimeout = 12e4,
2959
+ chainId = defaultChainId,
2960
+ impersonateAccount = isImpersonateAccount(chainId),
2961
+ errorsAbi: _errorsAbi = [],
2962
+ pollingInterval = defaultPollingInterval,
2963
+ ...rest
2964
+ } = args;
2965
+ onLoading?.(args);
2966
+ const data = "data" in rest ? rest.data : void 0;
2967
+ const globalAbi = [
2968
+ ...commonAbiErrors,
2969
+ ..._errorsAbi,
2970
+ ..."abi" in rest && rest.abi && Array.isArray(rest.abi) ? rest.abi : []
2971
+ ];
2972
+ let walletClient = _walletClient;
2973
+ if (!wagmiConfig) {
2974
+ onError?.(
2975
+ new InvalidArgumentError({
2976
+ property: "wagmiConfig",
2977
+ value: wagmiConfig,
2978
+ expected: "Config"
2979
+ }),
2980
+ args
2981
+ );
2982
+ return;
2983
+ }
2984
+ const isLocalAccount = walletClient?.account?.type === "local";
2985
+ if (!isLocalAccount) {
2986
+ try {
2987
+ await switchChain(wagmiConfig, { chainId });
2988
+ } catch (e) {
2989
+ const error = e;
2990
+ onError?.(
2991
+ new BeraError({
2992
+ cause: error,
2993
+ displayMessage: "There was an error switching to the chain."
2994
+ }),
2995
+ args
2996
+ );
2997
+ return;
2998
+ }
2999
+ }
3000
+ if (!walletClient) {
3001
+ try {
3002
+ walletClient = await getWalletClient(wagmiConfig, { chainId });
3003
+ } catch (e) {
3004
+ onError?.(
3005
+ new BeraError({
3006
+ cause: e,
3007
+ displayMessage: "There was an error connecting to the wallet."
3008
+ }),
3009
+ args
3010
+ );
3011
+ return;
3012
+ }
3013
+ }
3014
+ if (!walletClient) {
3015
+ onError?.(
3016
+ new InvalidArgumentError({
3017
+ displayMessage: "There was an error connecting to the wallet.",
3018
+ property: "walletClient",
3019
+ value: walletClient,
3020
+ expected: "WalletClient"
3021
+ }),
3022
+ args
3023
+ );
3024
+ return;
3025
+ }
3026
+ const account = argsAccount || walletClient.account;
3027
+ if (!account) {
3028
+ onError?.(
3029
+ new InvalidArgumentError({
3030
+ property: "account",
3031
+ value: account,
3032
+ expected: "Account"
3033
+ }),
3034
+ args
3035
+ );
3036
+ return;
3037
+ }
3038
+ const accountAddress = typeof account === "string" ? account : account.address;
3039
+ const publicClient = getPublicClient2(wagmiConfig, {
3040
+ chainId
3041
+ });
3042
+ try {
3043
+ assertPublicClient(publicClient);
3044
+ } catch (error) {
3045
+ onError?.(error, args);
3046
+ return;
3047
+ }
3048
+ if (impersonateAccount) {
3049
+ const testClient = getTestClient(chainId);
3050
+ await testClient.impersonateAccount({
3051
+ address: accountAddress
3052
+ });
3053
+ walletClient = createWalletClient({
3054
+ transport: http(testClient.transport.url),
3055
+ account,
3056
+ chain: walletClient.chain
3057
+ });
3058
+ }
3059
+ let txHash;
3060
+ const input = {
3061
+ calls: "calls" in rest ? rest.calls : void 0,
3062
+ params: "params" in rest ? rest.params : void 0,
3063
+ value,
3064
+ data: "data" in rest ? rest.data : void 0
3065
+ };
3066
+ try {
3067
+ const noncePromise = publicClient.getTransactionCount({
3068
+ address: accountAddress,
3069
+ /**
3070
+ * We won't use pending any more because if someone previously send a txn with a higher nonce, this won't be executed
3071
+ * unless all the previous nonces are executed.
3072
+ *
3073
+ * This will lead to a UX issue where the user thinks the txn was not sent because it's pending forever.
3074
+ *
3075
+ * The only case where pending is needed is if chain is halted or the user is sending multiple transactions at the same time.
3076
+ * However, it's less likely to happen.
3077
+ *
3078
+ * A lot of waitForTransactionReceipt were timing out, and maybe it was related to that.
3079
+ */
3080
+ blockTag: "latest"
3081
+ }).catch(() => void 0);
3082
+ const sharedTxProperties = {
3083
+ account: accountAddress,
3084
+ to: address,
3085
+ address,
3086
+ chainId,
3087
+ value
3088
+ };
3089
+ if (calls) {
3090
+ const parsedCalls = calls.map((call) => {
3091
+ if ("abi" in call && Array.isArray(globalAbi)) {
3092
+ globalAbi.push(...call.abi);
3093
+ }
3094
+ if ("data" in call) {
3095
+ return {
3096
+ to: call.address,
3097
+ data: call.data,
3098
+ value: call.value ?? 0n
3099
+ };
3100
+ }
3101
+ if ("abi" in call && "functionName" in call) {
3102
+ const params = "params" in call ? call.params : void 0;
3103
+ return {
3104
+ to: call.address,
3105
+ abi: call.abi,
3106
+ functionName: call.functionName,
3107
+ args: params,
3108
+ value: call.value ?? 0n
3109
+ };
3110
+ }
3111
+ return {
3112
+ to: call.address,
3113
+ value: call.value ?? 0n
3114
+ };
3115
+ });
3116
+ if (args.enableSimulateCalls) {
3117
+ const res = await publicClient.simulateCalls({
3118
+ calls: parsedCalls,
3119
+ account
3120
+ });
3121
+ const failedCallIndex = res.results.findIndex(
3122
+ (result) => result.status === "failure"
3123
+ );
3124
+ if (failedCallIndex !== -1) {
3125
+ if (res.block.number === null) {
3126
+ throw new InvalidArgumentError({
3127
+ property: "blockNumber",
3128
+ value: res.block.number,
3129
+ expected: "bigint",
3130
+ message: "Block number is null"
3131
+ });
3132
+ }
3133
+ const failedCall = res.results[failedCallIndex];
3134
+ const { reason: decodedReason } = failedCall.data && failedCall.data !== "0x" ? {
3135
+ reason: parseDecodedError(
3136
+ decodeErrorResult({
3137
+ data: failedCall.data,
3138
+ abi: globalAbi
3139
+ })
3140
+ )
3141
+ } : parseViemError({
3142
+ error: failedCall.error,
3143
+ revertIfUnknown: false,
3144
+ abi: globalAbi
3145
+ });
3146
+ onError?.(
3147
+ new TransactionFailedError({
3148
+ cause: failedCall.error,
3149
+ txHash,
3150
+ chainId,
3151
+ reason: decodedReason,
3152
+ abi: globalAbi,
3153
+ input,
3154
+ blockNumber: res.block.number
3155
+ }),
3156
+ args
3157
+ );
3158
+ return;
3159
+ }
3160
+ }
3161
+ if (process.env.NODE_ENV === "test") {
3162
+ throw new InvalidArgumentError({
3163
+ displayMessage: "Batch calls are not supported in test environment",
3164
+ expected: "not test",
3165
+ property: "NODE_ENV",
3166
+ value: process.env.NODE_ENV,
3167
+ level: "fatal"
3168
+ });
3169
+ }
3170
+ const request = await walletClient.sendCalls({
3171
+ calls: parsedCalls,
3172
+ account,
3173
+ // This is needed to ensure that the transaction is atomic
3174
+ // If this was not set, we might have a list of receipts instead of a single one
3175
+ forceAtomic: true
3176
+ });
3177
+ onSubmission?.({ id: request.id }, args);
3178
+ const callStatus = await walletClient.waitForCallsStatus({
3179
+ id: request.id,
3180
+ pollingInterval,
3181
+ timeout: txConfirmationTimeout
3182
+ });
3183
+ if (callStatus.status === "success") {
3184
+ const receipt = callStatus.receipts?.[0];
3185
+ if (!receipt) {
3186
+ throw new BeraError({
3187
+ message: "Call status is success but no receipt was found",
3188
+ cause: callStatus,
3189
+ level: "error",
3190
+ reason: "CALL_STATUS_SUCCESS_BUT_NO_RECEIPT"
3191
+ });
3192
+ }
3193
+ onSuccess?.(receipt, args);
3194
+ return receipt;
3195
+ }
3196
+ console.error("wallet_sendCalls: Call failed", callStatus);
3197
+ throw new TransactionFailedError({
3198
+ cause: callStatus,
3199
+ level: "error",
3200
+ input,
3201
+ txHash,
3202
+ abi: globalAbi,
3203
+ chainId
3204
+ });
3205
+ }
3206
+ if (data) {
3207
+ const [simulationResult, estimatedGas, nonceResult] = await Promise.allSettled([
3208
+ publicClient.call({
3209
+ ...sharedTxProperties,
3210
+ data
3211
+ }),
3212
+ gasLimit ?? publicClient.estimateGas({
3213
+ ...sharedTxProperties,
3214
+ data
3215
+ }),
3216
+ noncePromise
3217
+ ]);
3218
+ if (simulationResult.status === "rejected") {
3219
+ throw simulationResult.reason;
3220
+ }
3221
+ const gas = estimatedGas.status === "fulfilled" ? increaseByPercentage(estimatedGas.value, 10) : DEFAULT_METAMASK_GAS_LIMIT;
3222
+ txHash = await walletClient.sendTransaction({
3223
+ data,
3224
+ to: address,
3225
+ account,
3226
+ gas,
3227
+ chainId,
3228
+ nonce: parseNonce({
3229
+ nonceResult,
3230
+ onWarning(e) {
3231
+ onWarning?.(e, args);
3232
+ }
3233
+ }),
3234
+ value
3235
+ });
3236
+ onSubmission?.({ txHash }, args);
3237
+ } else if ("abi" in rest && "functionName" in rest) {
3238
+ const { abi, functionName } = rest;
3239
+ const params = "params" in rest ? rest.params : void 0;
3240
+ const [simulationResult, gasEstimateResult, nonceResult] = await Promise.allSettled([
3241
+ // @ts-expect-error nested type issues. Be careful when changing this.
3242
+ publicClient.simulateContract({
3243
+ ...sharedTxProperties,
3244
+ abi: globalAbi,
3245
+ functionName,
3246
+ args: params,
3247
+ account
3248
+ }),
3249
+ // Only estimate gas if no gasLimit is provided
3250
+ gasLimit ?? // @ts-expect-error nested type issues. Be careful when changing this.
3251
+ publicClient.estimateContractGas({
3252
+ ...sharedTxProperties,
3253
+ abi: globalAbi,
3254
+ functionName,
3255
+ args: params
3256
+ }),
3257
+ noncePromise
3258
+ ]);
3259
+ if (simulationResult.status === "rejected") {
3260
+ throw simulationResult.reason;
3261
+ }
3262
+ const estimatedGas = gasLimit ?? (gasEstimateResult.status === "fulfilled" ? increaseByPercentage(gasEstimateResult.value, 10) : DEFAULT_METAMASK_GAS_LIMIT);
3263
+ txHash = await walletClient.writeContract({
3264
+ ...simulationResult.value.request,
3265
+ chainId,
3266
+ gas: estimatedGas,
3267
+ nonce: parseNonce({
3268
+ nonceResult,
3269
+ onWarning(e) {
3270
+ onWarning?.(e, args);
3271
+ }
3272
+ })
3273
+ });
3274
+ onSubmission?.({ txHash }, args);
3275
+ } else {
3276
+ const [nonceResult] = await Promise.allSettled([noncePromise]);
3277
+ txHash = await walletClient.sendTransaction({
3278
+ chainId,
3279
+ to: address,
3280
+ value,
3281
+ account,
3282
+ nonce: parseNonce({
3283
+ nonceResult,
3284
+ onWarning(e) {
3285
+ onWarning?.(e, args);
3286
+ }
3287
+ })
3288
+ });
3289
+ onSubmission?.({ txHash }, args);
3290
+ }
3291
+ if (process.env.NODE_ENV === "test") {
3292
+ const testClient = getTestClient(chainId);
3293
+ await testClient.mine({ blocks: 1 });
3294
+ }
3295
+ const confirmationReceipt = await publicClient.waitForTransactionReceipt({
3296
+ hash: txHash,
3297
+ pollingInterval,
3298
+ timeout: txConfirmationTimeout,
3299
+ confirmations: 1
3300
+ });
3301
+ if (confirmationReceipt.status === "success") {
3302
+ onSuccess?.(confirmationReceipt, args);
3303
+ } else {
3304
+ const revertReason = await getRevertReason({
3305
+ publicClient,
3306
+ blockNumber: confirmationReceipt.blockNumber,
3307
+ to: address,
3308
+ account: accountAddress,
3309
+ abi: globalAbi,
3310
+ args: "params" in rest ? rest.params : void 0,
3311
+ functionName: "functionName" in rest ? rest.functionName : void 0,
3312
+ value,
3313
+ data
3314
+ });
3315
+ if (process.env.NODE_ENV === "test") {
3316
+ console.error("beraWriteContract: Revert reason", revertReason);
3317
+ }
3318
+ onError?.(
3319
+ new TransactionFailedError({
3320
+ reason: revertReason.reason,
3321
+ txHash,
3322
+ receipt: confirmationReceipt,
3323
+ to: address,
3324
+ functionName: "functionName" in rest ? rest.functionName : void 0,
3325
+ input,
3326
+ chainId,
3327
+ abi: globalAbi,
3328
+ blockNumber: confirmationReceipt.blockNumber
3329
+ }),
3330
+ args
3331
+ );
3332
+ }
3333
+ return confirmationReceipt;
3334
+ } catch (e) {
3335
+ if (e instanceof BeraError) {
3336
+ onError?.(e, args);
3337
+ } else if (e instanceof Error) {
3338
+ const viemError = parseViemError({
3339
+ error: e,
3340
+ revertIfUnknown: false,
3341
+ abi: globalAbi
3342
+ });
3343
+ if (viemError && viemError.rootCause instanceof BaseError && "url" in viemError.rootCause) {
3344
+ onError?.(
3345
+ new RequestError({
3346
+ cause: viemError.rootCause,
3347
+ response: void 0,
3348
+ endpoint: {
3349
+ url: viemError.rootCause.url,
3350
+ type: "rpc"
3351
+ },
3352
+ statusCode: viemError.rootCause instanceof HttpRequestError ? viemError.rootCause.status : void 0
3353
+ }),
3354
+ args
3355
+ );
3356
+ return;
3357
+ }
3358
+ onError?.(
3359
+ new TransactionFailedError({
3360
+ cause: e,
3361
+ to: address,
3362
+ txHash,
3363
+ chainId,
3364
+ abi: globalAbi,
3365
+ functionName: "functionName" in rest ? rest.functionName : void 0,
3366
+ input
3367
+ }),
3368
+ args
3369
+ );
3370
+ } else {
3371
+ onError?.(
3372
+ new TransactionFailedError({
3373
+ cause: e,
3374
+ txHash,
3375
+ to: address,
3376
+ chainId,
3377
+ functionName: "functionName" in rest ? rest.functionName : void 0,
3378
+ input,
3379
+ abi: globalAbi
3380
+ }),
3381
+ args
3382
+ );
3383
+ }
3384
+ }
3385
+ }
3386
+
3387
+ // src/actions/validators/getAllValidators.ts
3388
+ import {
3389
+ GetValidators
3390
+ } from "@berachain/graphql/pol/api";
3391
+ async function getAllValidators({
3392
+ variables = {},
3393
+ ...args
3394
+ } = {}) {
3395
+ const { config } = parseBaseArgs(args);
3396
+ const bexApiGraphqlClient = getApolloClient("api", args);
3397
+ const result = await bexApiGraphqlClient.query({
3398
+ query: GetValidators,
3399
+ variables: {
3400
+ chain: config.bex.chainName,
3401
+ ...variables
3402
+ }
3403
+ });
3404
+ return result.data;
3405
+ }
3406
+
3407
+ // src/actions/validators/getApiEnrichedAllocation.ts
3408
+ import { isAddressEqual } from "viem";
3409
+ async function getApiEnrichedAllocation({
3410
+ allocation
3411
+ }) {
3412
+ const vaults = await getRewardVaults({
3413
+ filter: {
3414
+ where: {
3415
+ vaultAddressIn: allocation.weights.map((weight) => weight.receiver)
3416
+ }
3417
+ }
3418
+ });
3419
+ const startBlock = allocation?.start.blockNumber ?? 0;
3420
+ return allocation?.weights.map(
3421
+ (allocation2) => {
3422
+ return {
3423
+ percentage: allocation2.percentage,
3424
+ receiver: allocation2.receiver,
3425
+ startBlock,
3426
+ receivingVault: vaults?.gaugeList.find(
3427
+ (vault) => isAddressEqual(vault.address, allocation2.receiver)
3428
+ )
3429
+ };
3430
+ }
3431
+ );
3432
+ }
3433
+
3434
+ // src/actions/validators/getApiValidator.ts
3435
+ import {
3436
+ GetValidator
3437
+ } from "@berachain/graphql/pol/api";
3438
+ async function getApiValidator({
3439
+ id,
3440
+ ...args
3441
+ }) {
3442
+ const { config } = parseBaseArgs(args);
3443
+ const bexApiGraphqlClient = getApolloClient("api", args);
3444
+ const results = await bexApiGraphqlClient.query({
3445
+ query: GetValidator,
3446
+ variables: {
3447
+ id,
3448
+ chain: config.bex.chainName
3449
+ }
3450
+ });
3451
+ return results.data;
3452
+ }
3453
+
3454
+ // src/actions/validators/getDailyValidatorBlockStats.ts
3455
+ async function getDailyValidatorBlockStats({
3456
+ pubKey,
3457
+ first = 1
3458
+ }) {
3459
+ if (typeof window === "undefined") {
3460
+ throw new BeraError({
3461
+ message: "getDailyValidatorBlockStats is browser-only; for RSC use @berachain/berajs/actions/server",
3462
+ level: "error"
3463
+ });
3464
+ }
3465
+ const params = new URLSearchParams({
3466
+ pubkey: pubKey,
3467
+ first: String(first)
3468
+ });
3469
+ return beraFetchJson({
3470
+ url: `/api/pol/validator-block-stats?${params}`,
3471
+ name: "pol-validator-block-stats",
3472
+ type: "rest"
3473
+ });
3474
+ }
3475
+
3476
+ // src/actions/validators/getValidatorRewardAllocation.ts
3477
+ import { beraChefAbi } from "@berachain/abis/pol/rewards/beraChef";
3478
+ function formatValidatorRewardAllocation(raw, startTs) {
3479
+ return {
3480
+ start: {
3481
+ blockNumber: Number(raw.startBlock),
3482
+ timestamp: raw.startBlock !== 0n ? startTs : 0
3483
+ },
3484
+ weights: raw.weights.map((weight) => ({
3485
+ receiver: weight.receiver,
3486
+ percentage: Number(weight.percentageNumerator) / 1e4
3487
+ }))
3488
+ };
3489
+ }
3490
+ function isSameRewardAllocation(a, b) {
3491
+ return a.start.blockNumber === b.start.blockNumber && a.weights.every(
3492
+ (weight, index) => weight.percentage === b.weights[index].percentage
3493
+ );
3494
+ }
3495
+ async function getValidatorRewardAllocation({
3496
+ client,
3497
+ pubKey,
3498
+ ...args
3499
+ }) {
3500
+ const { config } = parseBaseArgs(args);
3501
+ try {
3502
+ const [rawActiveRewardAllocation, rawSetRewardAllocation] = await Promise.all([
3503
+ client.readContract({
3504
+ address: config.pol.beraChef,
3505
+ abi: beraChefAbi,
3506
+ functionName: "getActiveRewardAllocation",
3507
+ args: [pubKey]
3508
+ }),
3509
+ client.readContract({
3510
+ address: config.pol.beraChef,
3511
+ abi: beraChefAbi,
3512
+ functionName: "getSetActiveRewardAllocation",
3513
+ args: [pubKey]
3514
+ })
3515
+ ]);
3516
+ const [lastRaUpdateActive, lastRaUpdateSet] = await Promise.all([
3517
+ rawActiveRewardAllocation.startBlock !== 0n ? client.getBlock({
3518
+ blockNumber: BigInt(rawActiveRewardAllocation.startBlock)
3519
+ }) : { timestamp: 0 },
3520
+ rawSetRewardAllocation.startBlock !== 0n ? client.getBlock({
3521
+ blockNumber: BigInt(rawSetRewardAllocation.startBlock)
3522
+ }) : { timestamp: 0 }
3523
+ ]);
3524
+ const activeRewardAllocation = formatValidatorRewardAllocation(
3525
+ rawActiveRewardAllocation,
3526
+ Number(lastRaUpdateActive.timestamp)
3527
+ );
3528
+ const setRewardAllocation = formatValidatorRewardAllocation(
3529
+ rawSetRewardAllocation,
3530
+ Number(lastRaUpdateSet.timestamp)
3531
+ );
3532
+ let isBaseline = false;
3533
+ if (setRewardAllocation.start.blockNumber === 0) {
3534
+ isBaseline = true;
3535
+ } else {
3536
+ isBaseline = !isSameRewardAllocation(
3537
+ setRewardAllocation,
3538
+ activeRewardAllocation
3539
+ );
3540
+ }
3541
+ return {
3542
+ activeRewardAllocation,
3543
+ setRewardAllocation,
3544
+ isBaseline,
3545
+ isNeverSet: setRewardAllocation?.start.blockNumber === 0
3546
+ };
3547
+ } catch (e) {
3548
+ console.log("getValidatorRewardAllocation:", e);
3549
+ throw e;
3550
+ }
3551
+ }
3552
+
3553
+ // src/actions/validators/getDefaultRewardAllocation.ts
3554
+ import { beraChefAbi as beraChefAbi2 } from "@berachain/abis/pol/rewards/beraChef";
3555
+ function isDefaultRewardAllocation(rewardAllocation) {
3556
+ return rewardAllocation.start.blockNumber === 0;
3557
+ }
3558
+ async function getDefaultRewardAllocation({
3559
+ client,
3560
+ ...args
3561
+ }) {
3562
+ const { config } = parseBaseArgs(args);
3563
+ const rawDefaultRewardAllocation = await client.readContract({
3564
+ address: config.pol.beraChef,
3565
+ abi: beraChefAbi2,
3566
+ functionName: "getDefaultRewardAllocation",
3567
+ args: []
3568
+ });
3569
+ return formatValidatorRewardAllocation(
3570
+ { ...rawDefaultRewardAllocation, startBlock: 0n },
3571
+ 0
3572
+ );
3573
+ }
3574
+
3575
+ // src/actions/validators/getStakingPoolBatch.ts
3576
+ async function getStakingPoolBatch({
3577
+ client,
3578
+ valPubKey
3579
+ }) {
3580
+ return 5614;
3581
+ }
3582
+
3583
+ // src/actions/validators/getUserBoostsOnValidator.ts
3584
+ import { formatEther as formatEther6 } from "viem";
3585
+ import { bgtAbi as bgtAbi2 } from "@berachain/abis/pol/bgt";
3586
+ async function getUserBoostsOnValidator({
3587
+ account,
3588
+ pubkey,
3589
+ publicClient,
3590
+ ...args
3591
+ }) {
3592
+ const { config } = parseBaseArgs(args);
3593
+ if (!account) {
3594
+ throw new Error("account is required");
3595
+ }
3596
+ if (!publicClient) {
3597
+ throw new Error("publicClient is required");
3598
+ }
3599
+ const [activeBoostAmount, queuedBoostAmount, queuedDropBoostAmount] = await Promise.all([
3600
+ publicClient.readContract({
3601
+ address: config.tokens.bgt,
3602
+ abi: bgtAbi2,
3603
+ functionName: "boosted",
3604
+ args: [account, pubkey]
3605
+ }),
3606
+ publicClient.readContract({
3607
+ address: config.tokens.bgt,
3608
+ abi: bgtAbi2,
3609
+ functionName: "boostedQueue",
3610
+ args: [account, pubkey]
3611
+ }),
3612
+ publicClient.readContract({
3613
+ address: config.tokens.bgt,
3614
+ abi: bgtAbi2,
3615
+ functionName: "dropBoostQueue",
3616
+ args: [account, pubkey]
3617
+ })
3618
+ ]);
3619
+ const droppableBoostAmount = activeBoostAmount - queuedDropBoostAmount[1];
3620
+ return {
3621
+ pubkey,
3622
+ droppableBoostAmount: formatEther6(droppableBoostAmount),
3623
+ activeBoostAmount: formatEther6(activeBoostAmount),
3624
+ queuedBoostAmount: formatEther6(queuedBoostAmount[1]),
3625
+ queuedDropBoostAmount: formatEther6(queuedDropBoostAmount[1]),
3626
+ queuedBoostStartBlock: queuedBoostAmount[0],
3627
+ queuedDropBoostStartBlock: queuedDropBoostAmount[0],
3628
+ hasPendingBoosts: queuedBoostAmount[1] > 0n || queuedDropBoostAmount[1] > 0n,
3629
+ hasActiveBoosts: activeBoostAmount > 0n,
3630
+ hasDroppableBoosts: droppableBoostAmount > 0n
3631
+ };
3632
+ }
3633
+
3634
+ // src/actions/validators/getUserActiveValidators.ts
3635
+ import { formatEther as formatEther7, parseEther as parseEther4 } from "viem";
3636
+
3637
+ // src/actions/validators/getUserBoosts.ts
3638
+ import {
3639
+ GetUserValidatorInformation
3640
+ } from "@berachain/graphql/pol/api";
3641
+ async function getUserBoosts({
3642
+ account,
3643
+ ...args
3644
+ }) {
3645
+ const { config } = parseBaseArgs(args);
3646
+ const apiClient = getApolloClient("api", args);
3647
+ return apiClient.query({
3648
+ query: GetUserValidatorInformation,
3649
+ variables: {
3650
+ address: account.toLowerCase(),
3651
+ chain: config.bex.chainName
3652
+ }
3653
+ });
3654
+ }
3655
+
3656
+ // src/actions/validators/getUserActiveValidators.ts
3657
+ async function getUserActiveValidators({
3658
+ account,
3659
+ publicClient,
3660
+ chain,
3661
+ ...args
3662
+ }) {
3663
+ const { config } = parseBaseArgs(args);
3664
+ const resolvedChain = chain ?? config.bex.chainName;
3665
+ const userBoosts = await getUserBoosts({ account });
3666
+ const [validatorInfoList, onChainBoosts] = await Promise.all([
3667
+ getAllValidators({
3668
+ variables: {
3669
+ chain: resolvedChain,
3670
+ where: {
3671
+ idIn: userBoosts.data.polGetValidatorBoosts.boosts.map(
3672
+ (t) => t.validatorId
3673
+ )
3674
+ }
3675
+ }
3676
+ }),
3677
+ Promise.all(
3678
+ userBoosts.data.polGetValidatorBoosts.boosts.filter(
3679
+ (t) => (
3680
+ // there's an edge case here where api doesn't return the pubkey
3681
+ // because the user might have boosted a pubkey that doesn't exist
3682
+ // api doesn't return the pubkey in this case, but we're choosing to filter them out
3683
+ !!t.validator
3684
+ )
3685
+ ).map(
3686
+ (t) => getUserBoostsOnValidator({
3687
+ account,
3688
+ pubkey: t.validator.pubkey,
3689
+ publicClient
3690
+ })
3691
+ )
3692
+ )
3693
+ ]);
3694
+ return validatorInfoList?.validators.validators.map((validator) => {
3695
+ const userDeposited = onChainBoosts.find(
3696
+ (data) => data.pubkey.toLowerCase() === validator.pubkey.toLowerCase()
3697
+ );
3698
+ if (!userDeposited) {
3699
+ throw new Error("User deposited not found");
3700
+ }
3701
+ const droppableBoostAmount = parseEther4(userDeposited?.activeBoostAmount ?? "0") - parseEther4(userDeposited?.queuedDropBoostAmount);
3702
+ return {
3703
+ ...validator,
3704
+ userBoosts: {
3705
+ pubkey: userDeposited.pubkey,
3706
+ activeBoostAmount: userDeposited?.activeBoostAmount,
3707
+ queuedBoostAmount: userDeposited?.queuedBoostAmount,
3708
+ queuedBoostStartBlock: Number(userDeposited?.queuedBoostStartBlock),
3709
+ queuedDropBoostAmount: userDeposited?.queuedDropBoostAmount,
3710
+ queuedDropBoostStartBlock: Number(
3711
+ userDeposited?.queuedDropBoostStartBlock
3712
+ ),
3713
+ droppableBoostAmount: formatEther7(droppableBoostAmount),
3714
+ hasPendingBoosts: Number(userDeposited?.queuedBoostAmount) > 0 || Number(userDeposited?.queuedDropBoostAmount) > 0,
3715
+ hasActiveBoosts: Number(userDeposited?.activeBoostAmount) > 0,
3716
+ hasDroppableBoosts: droppableBoostAmount > 0n
3717
+ }
3718
+ };
3719
+ });
3720
+ }
3721
+
3722
+ // src/actions/validators/getUserStakingPositions.ts
3723
+ var snowTestWalletPositions = [
3724
+ {
3725
+ validatorAddress: "0x8f51e63d9921a461be29e73dca1c2385e1adc5943fbb36ded4ba96025ee8a783184d1118da08171f6ea831153c878a6d",
3726
+ earning: 0.045,
3727
+ staked: {
3728
+ amount: 16114000000000000000n,
3729
+ formattedAmount: "161.14"
3730
+ },
3731
+ rewards: {
3732
+ amount: 15214000000000000000n,
3733
+ formattedAmount: "152.14"
3734
+ }
3735
+ },
3736
+ {
3737
+ staked: {
3738
+ amount: 141514000000000000000n,
3739
+ formattedAmount: "1415.14"
3740
+ },
3741
+ validatorAddress: "0x97b21253b17f4e814fe7505c15c18e68c85ab2477274ad370a762df50e3eb4cb1a48451e089bc22e158d7448549a8ab9",
3742
+ earning: 0.045,
3743
+ rewards: {
3744
+ amount: 15414000000000000000n,
3745
+ formattedAmount: "154.14"
3746
+ },
3747
+ queueData: {
3748
+ stake: [
3749
+ {
3750
+ amount: 16159000000000000000n,
3751
+ formattedAmount: "161.59"
3752
+ }
3753
+ ],
3754
+ unstake: [
3755
+ {
3756
+ amount: 16159000000000000000n,
3757
+ formattedAmount: "161.59",
3758
+ timestamp: msToSeconds(Date.now() - 72e6)
3759
+ }
3760
+ ]
3761
+ }
3762
+ },
3763
+ {
3764
+ staked: {
3765
+ amount: 141514000000000000000n,
3766
+ formattedAmount: "1415.14"
3767
+ },
3768
+ validatorAddress: "0xa2705d6b27891f3f5651f26547d1bb79e256f95f249d1ad717cef087d77d38b037e5d6dbaa2538930fd0731ec9b02f3a",
3769
+ earning: 0.145,
3770
+ rewards: {
3771
+ amount: 15414000000000000000n,
3772
+ formattedAmount: "154.14"
3773
+ },
3774
+ queueData: {
3775
+ unstake: [
3776
+ {
3777
+ amount: 16159000000000000000n,
3778
+ formattedAmount: "161.59",
3779
+ timestamp: msToSeconds(Date.now() - 72e6)
3780
+ }
3781
+ ]
3782
+ }
3783
+ },
3784
+ {
3785
+ staked: {
3786
+ amount: 141514000000000000000n,
3787
+ formattedAmount: "1415.14"
3788
+ },
3789
+ validatorAddress: "0xa2705d6b27891f3f5651f26547d1bb79e256f95f249d1ad717cef087d77d38b037e5d6dbaa2538930fd0731ec9b02f3a",
3790
+ earning: 0.145,
3791
+ rewards: {
3792
+ amount: 15414000000000000000n,
3793
+ formattedAmount: "154.14"
3794
+ },
3795
+ queueData: {
3796
+ unstake: [
3797
+ {
3798
+ amount: 16159000000000000000n,
3799
+ formattedAmount: "161.59",
3800
+ timestamp: msToSeconds(Date.now() - 72e6)
3801
+ }
3802
+ ]
3803
+ }
3804
+ },
3805
+ {
3806
+ staked: {
3807
+ amount: 141514000000000000000n,
3808
+ formattedAmount: "1415.14"
3809
+ },
3810
+ validatorAddress: "0xa2705d6b27891f3f5651f26547d1bb79e256f95f249d1ad717cef087d77d38b037e5d6dbaa2538930fd0731ec9b02f3a",
3811
+ earning: 0.145,
3812
+ rewards: {
3813
+ amount: 15414000000000000000n,
3814
+ formattedAmount: "154.14"
3815
+ },
3816
+ queueData: {
3817
+ unstake: [
3818
+ {
3819
+ amount: 16159000000000000000n,
3820
+ formattedAmount: "161.59",
3821
+ timestamp: msToSeconds(Date.now() - 72e6)
3822
+ }
3823
+ ]
3824
+ }
3825
+ },
3826
+ {
3827
+ staked: {
3828
+ amount: 141514000000000000000n,
3829
+ formattedAmount: "1415.14"
3830
+ },
3831
+ validatorAddress: "0xa2705d6b27891f3f5651f26547d1bb79e256f95f249d1ad717cef087d77d38b037e5d6dbaa2538930fd0731ec9b02f3a",
3832
+ earning: 0.145,
3833
+ rewards: {
3834
+ amount: 15414000000000000000n,
3835
+ formattedAmount: "154.14"
3836
+ },
3837
+ queueData: {
3838
+ unstake: [
3839
+ {
3840
+ amount: 16159000000000000000n,
3841
+ formattedAmount: "161.59",
3842
+ timestamp: msToSeconds(Date.now() - 72e6)
3843
+ }
3844
+ ]
3845
+ }
3846
+ },
3847
+ {
3848
+ staked: {
3849
+ amount: 141514000000000000000n,
3850
+ formattedAmount: "1415.14"
3851
+ },
3852
+ validatorAddress: "0xa2705d6b27891f3f5651f26547d1bb79e256f95f249d1ad717cef087d77d38b037e5d6dbaa2538930fd0731ec9b02f3a",
3853
+ earning: 0.145,
3854
+ rewards: {
3855
+ amount: 15414000000000000000n,
3856
+ formattedAmount: "154.14"
3857
+ },
3858
+ queueData: {
3859
+ unstake: [
3860
+ {
3861
+ amount: 16159000000000000000n,
3862
+ formattedAmount: "161.59",
3863
+ timestamp: msToSeconds(Date.now() - 72e6)
3864
+ }
3865
+ ]
3866
+ }
3867
+ },
3868
+ {
3869
+ staked: {
3870
+ amount: 241514000000000000000n,
3871
+ formattedAmount: "2415.14"
3872
+ },
3873
+ validatorAddress: "0xa4e4b63514f54d61da5197359f11ff1fc2930788ba2ffdd30c2fc059cbe0221020197bf9446b16ac347f36c7517a8686",
3874
+ earning: 0.145,
3875
+ rewards: {
3876
+ amount: 15414000000000000000n,
3877
+ formattedAmount: "154.14"
3878
+ },
3879
+ queueData: {
3880
+ unstake: [
3881
+ {
3882
+ amount: 1159000000000000000n,
3883
+ formattedAmount: "11.59",
3884
+ timestamp: msToSeconds(Date.now() - 36e6)
3885
+ }
3886
+ ]
3887
+ }
3888
+ },
3889
+ {
3890
+ validatorAddress: "0xb0511ec039591e98bd4e183ba70b85572214a7ad8ca1a43e96ad3495d3821054927bc542e5482ec9733e35b7ef0b1f03",
3891
+ earning: 0.045,
3892
+ staked: {
3893
+ amount: 141514000000000000000n,
3894
+ formattedAmount: "1415.14"
3895
+ },
3896
+ rewards: {
3897
+ amount: 15414000000000000000n,
3898
+ formattedAmount: "154.14"
3899
+ },
3900
+ queueData: {
3901
+ stake: [
3902
+ {
3903
+ amount: 1159000000000000000n,
3904
+ formattedAmount: "11.59"
3905
+ }
3906
+ ]
3907
+ }
3908
+ }
3909
+ ];
3910
+ async function getUserStakingPositions(account) {
3911
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
3912
+ if (account === "0x4C368fFE3650379d6318C8d4630bc51f8Ad12bB6") {
3913
+ return snowTestWalletPositions;
3914
+ }
3915
+ return [];
3916
+ }
3917
+
3918
+ // src/actions/validators/getValidatorAnalytics.ts
3919
+ async function getValidatorAnalytics({
3920
+ pubkey,
3921
+ dayRange
3922
+ }) {
3923
+ if (typeof window === "undefined") {
3924
+ throw new BeraError({
3925
+ message: "getValidatorAnalytics is browser-only; call from a Client Component / SWR hook",
3926
+ level: "error"
3927
+ });
3928
+ }
3929
+ const params = new URLSearchParams({
3930
+ pubkey,
3931
+ dayRange: String(dayRange)
3932
+ });
3933
+ return beraFetchJson({
3934
+ url: `/api/pol/validator-analytics?${params}`,
3935
+ name: "pol-validator-analytics",
3936
+ type: "rest"
3937
+ });
3938
+ }
3939
+
3940
+ // src/actions/validators/getValidatorCommission.ts
3941
+ import { beraChefAbi as beraChefAbi3 } from "@berachain/abis/pol/rewards/beraChef";
3942
+ async function getValidatorCommission({
3943
+ client,
3944
+ pubKey,
3945
+ ...args
3946
+ }) {
3947
+ const { config } = parseBaseArgs(args);
3948
+ const result = await client.readContract({
3949
+ address: config.pol.beraChef,
3950
+ abi: beraChefAbi3,
3951
+ functionName: "getValCommissionOnIncentiveTokens",
3952
+ args: [pubKey]
3953
+ });
3954
+ return Number(result ?? 0n) / 1e4;
3955
+ }
3956
+
3957
+ // src/actions/validators/getValidatorEstimatedBgtPerYear.ts
3958
+ var getValidatorEstimatedBgtPerYear = (validator, totalStakedBeraAmount, blockTime) => {
3959
+ if (!totalStakedBeraAmount || !validator) return 0;
3960
+ const estimatedBlocksPerYear = yearsInSeconds(1) / blockTime;
3961
+ const estimatedValidatorBlocksPerYear = totalStakedBeraAmount ? estimatedBlocksPerYear * (Number(validator.dynamicData?.stakedBeraAmount) / totalStakedBeraAmount) : 0;
3962
+ return estimatedValidatorBlocksPerYear * Number.parseFloat(validator.dynamicData?.rewardRate ?? "0");
3963
+ };
3964
+
3965
+ // src/actions/validators/getValidatorOperatorAddress.ts
3966
+ import { beaconDepositAbi } from "@berachain/abis/pol/beaconDeposit";
3967
+ async function getValidatorOperatorAddress({
3968
+ client,
3969
+ pubKey,
3970
+ ...args
3971
+ }) {
3972
+ const { config } = parseBaseArgs(args);
3973
+ try {
3974
+ const result = await client.readContract({
3975
+ address: config.depositContract,
3976
+ abi: beaconDepositAbi,
3977
+ functionName: "getOperator",
3978
+ args: [pubKey]
3979
+ });
3980
+ return result;
3981
+ } catch (e) {
3982
+ console.log("getValidatorOperatorAddress:", e);
3983
+ throw e;
3984
+ }
3985
+ }
3986
+
3987
+ // src/actions/validators/getValidatorQueuedCommission.ts
3988
+ import { beraChefAbi as beraChefAbi4 } from "@berachain/abis/pol/rewards/beraChef";
3989
+ async function getValidatorQueuedCommission({
3990
+ client,
3991
+ pubKey,
3992
+ ...args
3993
+ }) {
3994
+ const { config } = parseBaseArgs(args);
3995
+ const result = await client.readContract({
3996
+ address: config.pol.beraChef,
3997
+ abi: beraChefAbi4,
3998
+ functionName: "getValQueuedCommissionOnIncentiveTokens",
3999
+ args: [pubKey]
4000
+ });
4001
+ return {
4002
+ blockNumberLast: result.blockNumberLast,
4003
+ commissionRate: Number(result.commissionRate) / 1e4
4004
+ };
4005
+ }
4006
+
4007
+ // src/actions/validators/getValidatorQueuedOperatorAddress.ts
4008
+ import { beaconDepositAbi as beaconDepositAbi2 } from "@berachain/abis/pol/beaconDeposit";
4009
+ async function getValidatorQueuedOperatorAddress({
4010
+ client,
4011
+ pubKey,
4012
+ ...args
4013
+ }) {
4014
+ const { config } = parseBaseArgs(args);
4015
+ try {
4016
+ const result = await client.readContract({
4017
+ address: config.depositContract,
4018
+ abi: beaconDepositAbi2,
4019
+ functionName: "queuedOperator",
4020
+ args: [pubKey]
4021
+ });
4022
+ return result;
4023
+ } catch (e) {
4024
+ console.log("getValidatorQueuedOperatorAddress:", e);
4025
+ throw e;
4026
+ }
4027
+ }
4028
+
4029
+ // src/actions/validators/getValidatorQueuedRewardAllocation.ts
4030
+ import { beraChefAbi as beraChefAbi5 } from "@berachain/abis/pol/rewards/beraChef";
4031
+ async function getValidatorQueuedRewardAllocation({
4032
+ client,
4033
+ pubKey,
4034
+ ...args
4035
+ }) {
4036
+ const { config } = parseBaseArgs(args);
4037
+ try {
4038
+ const result = await client.readContract({
4039
+ address: config.pol.beraChef,
4040
+ abi: beraChefAbi5,
4041
+ functionName: "getQueuedRewardAllocation",
4042
+ args: [pubKey]
4043
+ });
4044
+ return formatValidatorRewardAllocation(result, 0);
4045
+ } catch (e) {
4046
+ console.log("getValidatorQueuedRewardAllocation:", e);
4047
+ throw e;
4048
+ }
4049
+ }
4050
+
4051
+ export {
4052
+ getConvertToAssets,
4053
+ BaseAggregator,
4054
+ BalancerApi,
4055
+ getAllPools,
4056
+ getApiPool,
4057
+ getGlobalLiquidityAndSwapVolume,
4058
+ getPoolPausedState,
4059
+ getOnChainPool,
4060
+ getPoolEvents,
4061
+ getPoolHistoricalData,
4062
+ getChartData,
4063
+ getCollateralWeights,
4064
+ getTokenInformation,
4065
+ getHoneyCollaterals,
4066
+ isBadCollateralAsset,
4067
+ getGlobalCapLimit,
4068
+ getHoney24hVolume,
4069
+ HoneyPreviewMethod,
4070
+ getHoneyPreview,
4071
+ getHoneyVaultsBalance,
4072
+ getPythLatestPrices,
4073
+ getRelativeCapLimit,
4074
+ getPythUpdateFee,
4075
+ getSwapPayload,
4076
+ isBasketModeEnabled,
4077
+ getBlockTimestamp,
4078
+ getAutoclaimedIncentives,
4079
+ getAutoclaimedIncentivesTxHash,
4080
+ RewardVaultDistributionMode,
4081
+ getRewardVaultRewards,
4082
+ getBgtAprSimulation,
4083
+ getEarnedStakedBeraVault,
4084
+ getRewardVaults,
4085
+ getGlobalData,
4086
+ getIncentiveFeeClaimStats,
4087
+ getMarkets,
4088
+ getRewardProofsByValidator,
4089
+ getRewardTokenToBeraRate,
4090
+ getRewardVault,
4091
+ getRewardVaultIncentives,
4092
+ getRewardVaultStakingToken,
4093
+ getStakedBeraAPR,
4094
+ getStakedBeraSnapshots,
4095
+ getStakeWithdrawalCooldown,
4096
+ getSWBeraVaultMetadata,
4097
+ getSWBeraWithdrawal,
4098
+ getTotalStakedAmount,
4099
+ getUserClaimableIncentives,
4100
+ getUserVaultsReward,
4101
+ getUserVaultInfo,
4102
+ getUserVaults,
4103
+ getVaultHistory,
4104
+ getVaultValidators,
4105
+ getTokenCurrentPrices,
4106
+ getAllowances,
4107
+ isImpersonateAccount,
4108
+ beraWriteContract,
4109
+ getAllValidators,
4110
+ getApiEnrichedAllocation,
4111
+ getApiValidator,
4112
+ getDailyValidatorBlockStats,
4113
+ formatValidatorRewardAllocation,
4114
+ isSameRewardAllocation,
4115
+ getValidatorRewardAllocation,
4116
+ isDefaultRewardAllocation,
4117
+ getDefaultRewardAllocation,
4118
+ getStakingPoolBatch,
4119
+ getUserBoostsOnValidator,
4120
+ getUserActiveValidators,
4121
+ getUserStakingPositions,
4122
+ getValidatorAnalytics,
4123
+ getValidatorCommission,
4124
+ getValidatorEstimatedBgtPerYear,
4125
+ getValidatorOperatorAddress,
4126
+ getValidatorQueuedCommission,
4127
+ getValidatorQueuedOperatorAddress,
4128
+ getValidatorQueuedRewardAllocation
4129
+ };