@berachain/berajs 0.2.8-beta.9 → 0.2.9

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