@berachain/berajs 0.2.8-beta.2 → 0.2.8-beta.4

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