@tokemak/queries 0.5.0 → 0.6.0

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 (36) hide show
  1. package/dist/functions/getAutopoolDayData.d.ts.map +1 -1
  2. package/dist/functions/getAutopoolHistory.d.ts.map +1 -1
  3. package/dist/functions/getAutopools.d.ts +3 -3
  4. package/dist/functions/getAutopools.d.ts.map +1 -1
  5. package/dist/functions/getAutopoolsRebalances.d.ts.map +1 -1
  6. package/dist/functions/getChainAutopools.d.ts +3 -3
  7. package/dist/functions/getChainAutopools.d.ts.map +1 -1
  8. package/dist/functions/getEthPriceAtBlock.d.ts +2 -2
  9. package/dist/functions/getEthPriceAtBlock.d.ts.map +1 -1
  10. package/dist/functions/getMultipleAutopoolRebalances.d.ts.map +1 -1
  11. package/dist/functions/getPoolsAndDestinations.d.ts +2 -2
  12. package/dist/functions/getPoolsAndDestinations.d.ts.map +1 -1
  13. package/dist/functions/getRebalanceStats.d.ts +7 -6
  14. package/dist/functions/getRebalanceStats.d.ts.map +1 -1
  15. package/dist/functions/getTokenPrices.d.ts +1 -1
  16. package/dist/functions/getTokenPrices.d.ts.map +1 -1
  17. package/dist/functions/getUserAutopoolBalanceChanges.d.ts.map +1 -1
  18. package/dist/functions/getUserAutopools.d.ts +1 -1
  19. package/dist/functions/getUserAutopools.d.ts.map +1 -1
  20. package/dist/functions/getUserSAuto.d.ts +1 -1
  21. package/dist/functions/getUserSAuto.d.ts.map +1 -1
  22. package/dist/functions/updateRebalanceStats.d.ts +2 -2
  23. package/dist/functions/updateRebalanceStats.d.ts.map +1 -1
  24. package/dist/index.js +290 -358
  25. package/dist/index.mjs +180 -251
  26. package/dist/safe.d.ts +9 -0
  27. package/dist/safe.d.ts.map +1 -0
  28. package/dist/safe.js +860 -0
  29. package/dist/safe.mjs +848 -0
  30. package/package.json +27 -16
  31. package/dist/functions/getBackupApr.d.ts +0 -2
  32. package/dist/functions/getBackupApr.d.ts.map +0 -1
  33. package/dist/functions/getBackupTokenPrices.d.ts +0 -6
  34. package/dist/functions/getBackupTokenPrices.d.ts.map +0 -1
  35. package/dist/functions/getPoolsAndDestinationsBackup.d.ts +0 -67
  36. package/dist/functions/getPoolsAndDestinationsBackup.d.ts.map +0 -1
package/dist/safe.js ADDED
@@ -0,0 +1,860 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // safe.ts
21
+ var safe_exports = {};
22
+ __export(safe_exports, {
23
+ calculateRebalanceStats: () => calculateRebalanceStats,
24
+ fetchChainRebalances: () => fetchChainRebalances,
25
+ getChainAutopools: () => getChainAutopools,
26
+ getChainAutopoolsApr: () => getChainAutopoolsApr,
27
+ getDefillamaPrice: () => getDefillamaPrice,
28
+ getEthPriceAtBlock: () => getEthPriceAtBlock,
29
+ getGenStratAprs: () => getGenStratAprs,
30
+ getPoolsAndDestinations: () => getPoolsAndDestinations,
31
+ getRebalanceStats: () => getRebalanceStats,
32
+ getTokenPrice: () => getTokenPrice
33
+ });
34
+ module.exports = __toCommonJS(safe_exports);
35
+
36
+ // utils/mergeArraysWithKey.ts
37
+ function mergeArraysWithKey(objectsArray, arraysArray, key) {
38
+ if (objectsArray.length !== arraysArray.length) {
39
+ throw new Error("Both arrays must have the same length.");
40
+ }
41
+ return objectsArray.map((obj, index) => ({
42
+ ...obj,
43
+ [key]: arraysArray[index]
44
+ }));
45
+ }
46
+
47
+ // utils/mergeArrays.ts
48
+ function mergeArrays(objectsArray, objectsToMergeArray) {
49
+ if (objectsArray.length !== objectsToMergeArray.length) {
50
+ throw new Error("Both arrays must have the same length.");
51
+ }
52
+ return objectsArray.map((obj, index) => ({
53
+ ...obj,
54
+ ...objectsToMergeArray[index]
55
+ }));
56
+ }
57
+
58
+ // utils/getChainsForEnv.ts
59
+ var import_constants = require("@tokemak/constants");
60
+ function getChainsForEnv({
61
+ includeTestnet = false
62
+ }) {
63
+ let chains;
64
+ chains = includeTestnet ? [...import_constants.SUPPORTED_DEV_CHAINS] : [...import_constants.SUPPORTED_PROD_CHAINS];
65
+ return chains;
66
+ }
67
+
68
+ // utils/getAutopoolCategory.ts
69
+ var ETH_BASE_ASSETS = ["ETH", "WETH"];
70
+ var USD_BASE_ASSETS = ["USDC", "DOLA", "USDT0"];
71
+ var EUR_BASE_ASSETS = ["EURC"];
72
+ var getAutopoolCategory = (baseAsset) => {
73
+ if (ETH_BASE_ASSETS.includes(baseAsset?.toUpperCase())) {
74
+ return "eth" /* ETH */;
75
+ } else if (USD_BASE_ASSETS.includes(baseAsset?.toUpperCase()) || EUR_BASE_ASSETS.includes(baseAsset?.toUpperCase())) {
76
+ return "stables" /* STABLES */;
77
+ }
78
+ return "crypto" /* CRYPTO */;
79
+ };
80
+
81
+ // utils/convertBaseAssetToTokenPrices.ts
82
+ var convertBaseAssetToTokenPrices = (baseAssetValue, baseAssetPrice, prices) => {
83
+ const baseAssetToTokenPrices = Object.fromEntries(
84
+ Object.entries(prices).map(([tokenSymbol, tokenPrice]) => [
85
+ tokenSymbol,
86
+ baseAssetPrice / tokenPrice
87
+ ])
88
+ );
89
+ return {
90
+ baseAsset: baseAssetValue,
91
+ USD: baseAssetValue * baseAssetPrice,
92
+ ...Object.fromEntries(
93
+ Object.entries(baseAssetToTokenPrices).map(([tokenSymbol, price]) => [
94
+ tokenSymbol.toUpperCase(),
95
+ baseAssetValue * price
96
+ ])
97
+ )
98
+ };
99
+ };
100
+
101
+ // utils/convertBaseAssetToTokenPricesAndDenom.ts
102
+ var convertBaseAssetToTokenPricesAndDenom = (baseAsset, baseAssetPrice, denomPrice, prices) => {
103
+ const baseAssetToDenom = baseAssetPrice / denomPrice;
104
+ return {
105
+ ...convertBaseAssetToTokenPrices(baseAsset, baseAssetPrice, prices),
106
+ denom: baseAsset * baseAssetToDenom
107
+ };
108
+ };
109
+
110
+ // utils/getAutopoolInfo.ts
111
+ var import_tokenlist = require("@tokemak/tokenlist");
112
+ var getAutopoolInfo = (symbol) => {
113
+ const autopool = import_tokenlist.ALL_AUTOPOOLS.find((pool) => pool.symbol === symbol);
114
+ return autopool;
115
+ };
116
+
117
+ // utils/paginateQuery.ts
118
+ async function paginateQuery(queryFn, arrayKey, options = {}) {
119
+ const { first = 1e3, maxPages = 100, onPage } = options;
120
+ const results = [];
121
+ let skip = 0;
122
+ let pageNumber = 0;
123
+ let hasMoreData = true;
124
+ while (hasMoreData && pageNumber < maxPages) {
125
+ const pageResult = await queryFn({ first, skip });
126
+ const pageData = pageResult[arrayKey];
127
+ if (!pageData || Array.isArray(pageData) && pageData.length === 0) {
128
+ hasMoreData = false;
129
+ } else {
130
+ if (Array.isArray(pageData)) {
131
+ const pageArray = pageData;
132
+ results.push(...pageArray);
133
+ if (pageArray.length < first) {
134
+ hasMoreData = false;
135
+ }
136
+ } else {
137
+ return pageData;
138
+ }
139
+ onPage?.(pageData, pageNumber);
140
+ skip += first;
141
+ pageNumber++;
142
+ }
143
+ }
144
+ return results;
145
+ }
146
+
147
+ // functions/getChainAutopools.ts
148
+ var import_utils3 = require("@tokemak/utils");
149
+ var import_viem = require("viem");
150
+
151
+ // constants/tokenOrders.ts
152
+ var UITokenOrder = [
153
+ "ETH",
154
+ "WETH",
155
+ "STETH",
156
+ "WSTETH",
157
+ "RETH",
158
+ "SWETH",
159
+ "FRXETH",
160
+ "SFRXETH",
161
+ "EETH",
162
+ "CBETH",
163
+ "OSETH",
164
+ "PXETH",
165
+ "OETH",
166
+ "EZETH",
167
+ "RSETH",
168
+ "RSWETH",
169
+ "ETHX",
170
+ "RSWETH",
171
+ "PUFETH",
172
+ "USDC",
173
+ "DOLA",
174
+ "USDT",
175
+ "DAI"
176
+ ];
177
+ var protocolOrder = [
178
+ "Balancer",
179
+ "Curve",
180
+ "Aerodrome",
181
+ "Pendle",
182
+ "Aave",
183
+ "Morpho",
184
+ "Fluid"
185
+ ];
186
+
187
+ // functions/getGenStratAprs.ts
188
+ var import_constants2 = require("@tokemak/constants");
189
+ var getGenStratAprs = async ({
190
+ chainId = 1
191
+ }) => {
192
+ try {
193
+ const params = new URLSearchParams({
194
+ chainId: chainId.toString(),
195
+ systemName: "gen3"
196
+ });
197
+ const response = await fetch(`${import_constants2.TOKEMAK_GENSTRAT_APRS_API_URL}?${params}`);
198
+ const data = await response.json();
199
+ if (data && data.success) {
200
+ return data.aprs.reduce((p, c) => {
201
+ if (!p[c.autopoolAddress]) {
202
+ p[c.autopoolAddress] = {};
203
+ }
204
+ for (const d of c.destinations) {
205
+ p[c.autopoolAddress][d.address] = {
206
+ name: d.name,
207
+ apr: d.apr
208
+ };
209
+ }
210
+ return p;
211
+ }, {});
212
+ } else {
213
+ return void 0;
214
+ }
215
+ } catch (error) {
216
+ console.log(error);
217
+ return void 0;
218
+ }
219
+ };
220
+
221
+ // functions/getTokenPrice.ts
222
+ var import_constants3 = require("@tokemak/constants");
223
+
224
+ // functions/getDefillamaPrice.ts
225
+ var getDefillamaPrice = async (tokenAddress) => {
226
+ const response = await fetch(
227
+ `https://coins.llama.fi/prices/current/ethereum:${tokenAddress}`
228
+ );
229
+ const data = await response.json();
230
+ return data.coins[`ethereum:${tokenAddress}`].price;
231
+ };
232
+
233
+ // functions/getTokenPrice.ts
234
+ var getTokenPrice = async ({
235
+ chainId = 1,
236
+ tokenAddress,
237
+ includedSources,
238
+ excludedSources
239
+ }) => {
240
+ try {
241
+ const params = new URLSearchParams({
242
+ chainId: chainId.toString(),
243
+ systemName: "gen3",
244
+ token: tokenAddress
245
+ });
246
+ if (includedSources) {
247
+ params.set("includedSources", includedSources.join(","));
248
+ }
249
+ if (excludedSources) {
250
+ params.set("excludedSources", excludedSources.join(","));
251
+ }
252
+ const response = await fetch(`${import_constants3.TOKEMAK_SWAP_PRICING_URL}?${params}`);
253
+ const data = await response.json();
254
+ return data.price;
255
+ } catch (error) {
256
+ try {
257
+ const defillamaPrice = await getDefillamaPrice(tokenAddress);
258
+ return defillamaPrice;
259
+ } catch (error2) {
260
+ console.log(error2);
261
+ return void 0;
262
+ }
263
+ }
264
+ };
265
+
266
+ // functions/getChainAutopoolsApr.ts
267
+ var import_constants4 = require("@tokemak/constants");
268
+ var getChainAutopoolsApr = async (chainId) => {
269
+ try {
270
+ const response = await fetch(`${import_constants4.AUTOPOOLS_APR_URL}/${chainId}/gen3`, {
271
+ method: "GET",
272
+ headers: {
273
+ "Content-Type": "application/json"
274
+ }
275
+ });
276
+ if (!response.ok) {
277
+ throw new Error(
278
+ `Failed to fetch getChainAutopoolsApr: ${response.status}`
279
+ );
280
+ }
281
+ return await response.json();
282
+ } catch (e) {
283
+ console.error("Failed to fetch getChainAutopoolsApr:", e);
284
+ return void 0;
285
+ }
286
+ };
287
+
288
+ // functions/getChainAutopools.ts
289
+ var import_tokenlist2 = require("@tokemak/tokenlist");
290
+ var import_graph_cli = require("@tokemak/graph-cli");
291
+ var import_chains = require("viem/chains");
292
+
293
+ // functions/getPoolsAndDestinations.ts
294
+ var import_config = require("@tokemak/config");
295
+ var import_abis = require("@tokemak/abis");
296
+ var getPoolsAndDestinations = async (client, { chainId }) => {
297
+ try {
298
+ const { lens } = (0, import_config.getCoreConfig)(chainId);
299
+ const { autoPools, destinations } = await client.readContract({
300
+ address: lens,
301
+ abi: import_abis.lensAbi,
302
+ functionName: "getPoolsAndDestinations"
303
+ });
304
+ const autopoolsAndDestinations = mergeArraysWithKey(
305
+ autoPools,
306
+ destinations,
307
+ "destinations"
308
+ );
309
+ return autopoolsAndDestinations;
310
+ } catch (error) {
311
+ console.error(`Error on ${chainId} in getPoolsAndDestinations:`, error);
312
+ }
313
+ };
314
+
315
+ // functions/getChainAutopools.ts
316
+ var import_constants5 = require("@tokemak/constants");
317
+ var getChainAutopools = async (client, {
318
+ chainId,
319
+ prices
320
+ }) => {
321
+ const { GetVaultAddeds, GetAutopoolsInactiveDestinations } = (0, import_graph_cli.getSdkByChainId)(chainId);
322
+ try {
323
+ const { vaultAddeds } = await GetVaultAddeds();
324
+ const autopoolsAprResponse = await getChainAutopoolsApr(chainId);
325
+ const autopoolsApr = autopoolsAprResponse?.autopools || [];
326
+ const { GetAutopoolsApr } = (0, import_graph_cli.getSdkByChainId)(chainId);
327
+ const { autopools: autopoolsDenomination } = await GetAutopoolsApr();
328
+ const genStratAprs = await getGenStratAprs({
329
+ chainId
330
+ });
331
+ const autopoolsAndDestinations = await getPoolsAndDestinations(client, {
332
+ chainId
333
+ });
334
+ if (!autopoolsAndDestinations) {
335
+ throw new Error(`No autopools and destinations found for ${chainId}`);
336
+ }
337
+ const vaultAddedMapping = vaultAddeds.reduce(
338
+ (acc, vaultAdded) => {
339
+ acc[vaultAdded.vault.toLowerCase()] = Number(vaultAdded.blockTimestamp);
340
+ return acc;
341
+ },
342
+ {}
343
+ );
344
+ const autopools = await Promise.all(
345
+ autopoolsAndDestinations.map(async (autopool) => {
346
+ let baseAsset = (0, import_utils3.getToken)(autopool.baseAsset);
347
+ if (!baseAsset?.symbol) {
348
+ console.error(
349
+ "FIX THIS BEFORE PROD: base asset not found",
350
+ autopool.baseAsset
351
+ );
352
+ }
353
+ let baseAssetPrice = prices[(baseAsset?.symbol || "").toUpperCase()];
354
+ if (!baseAssetPrice) {
355
+ baseAssetPrice = await getTokenPrice({
356
+ chainId: baseAsset.chainId,
357
+ tokenAddress: baseAsset.address
358
+ }) || 0;
359
+ }
360
+ const timestamp = vaultAddedMapping[autopool.poolAddress.toLowerCase()];
361
+ const totalAssets = (0, import_utils3.formatUnitsNum)(
362
+ autopool.totalAssets,
363
+ baseAsset.decimals
364
+ );
365
+ const tvl = totalAssets * baseAssetPrice;
366
+ const totalIdleAssets = (0, import_utils3.formatUnitsNum)(
367
+ autopool.totalIdle,
368
+ baseAsset.decimals
369
+ );
370
+ const exchangeValues = {};
371
+ const destinations = autopool.destinations.map((destination) => {
372
+ const debtValueHeldByVaultEth = (0, import_utils3.formatUnitsNum)(
373
+ destination.debtValueHeldByVault,
374
+ baseAsset.decimals
375
+ );
376
+ if (!exchangeValues[destination.exchangeName.toLowerCase()]) {
377
+ exchangeValues[destination.exchangeName.toLowerCase()] = 0;
378
+ }
379
+ exchangeValues[destination.exchangeName.toLowerCase()] += debtValueHeldByVaultEth;
380
+ const tokensWithValue = mergeArrays(
381
+ destination.underlyingTokens,
382
+ destination.underlyingTokenValueHeld
383
+ );
384
+ let underlyingTokens = tokensWithValue.map((token) => {
385
+ const tokenDetails = (0, import_utils3.getToken)(token.tokenAddress);
386
+ let value = (0, import_utils3.formatUnitsNum)(
387
+ token.valueHeldInEth,
388
+ baseAsset.decimals
389
+ );
390
+ let valueUsd = value * baseAssetPrice;
391
+ return {
392
+ ...tokenDetails,
393
+ valueUsd,
394
+ value
395
+ };
396
+ });
397
+ if (destination.underlyingTokenSymbols.length === 1) {
398
+ const underlyingTokenAddress = tokensWithValue[0].tokenAddress;
399
+ if (underlyingTokenAddress) {
400
+ underlyingTokens = [
401
+ {
402
+ ...(0, import_utils3.getToken)(underlyingTokenAddress, chainId),
403
+ valueUsd: debtValueHeldByVaultEth * baseAssetPrice,
404
+ value: debtValueHeldByVaultEth
405
+ }
406
+ ];
407
+ }
408
+ }
409
+ const isGenStrat = autopool.strategy.toLowerCase() === import_constants5.DEAD_ADDRESS || autopool.strategy === import_constants5.ZERO_ADDRESS;
410
+ return {
411
+ ...destination,
412
+ debtValueHeldByVaultUsd: debtValueHeldByVaultEth * baseAssetPrice,
413
+ debtValueHeldByVaultEth,
414
+ compositeReturn: isGenStrat ? genStratAprs?.[autopool.poolAddress]?.[destination.vaultAddress]?.apr || 0 : (0, import_utils3.formatEtherNum)(destination.compositeReturn),
415
+ debtValueHeldByVaultAllocation: debtValueHeldByVaultEth / totalAssets,
416
+ underlyingTokens,
417
+ poolName: (0, import_utils3.formatPoolName)(destination.lpTokenName),
418
+ exchange: (0, import_utils3.getProtocol)(destination.exchangeName)
419
+ };
420
+ });
421
+ const HIDDEN_DESTINATION_SYMBOLS = ["USR", "WSTUSR"];
422
+ const filteredDestinations = destinations.filter(
423
+ (d) => !d.underlyingTokens.some(
424
+ (t) => HIDDEN_DESTINATION_SYMBOLS.includes(t.symbol?.toUpperCase())
425
+ )
426
+ );
427
+ const uniqueExchanges = Array.from(
428
+ new Set(
429
+ filteredDestinations.map((d) => (0, import_utils3.getProtocol)(d.exchangeName)).filter(Boolean)
430
+ )
431
+ );
432
+ const uniqueExchangesWithValueHeld = uniqueExchanges.map((exchange) => {
433
+ const exchangeName = exchange.name.toLowerCase();
434
+ let exchangeInfo = exchange;
435
+ const value = exchangeValues[exchangeName];
436
+ if (chainId === import_chains.sonic.id) {
437
+ if (exchangeName === "balancerv3" || exchangeName === "balancer") {
438
+ exchangeInfo = import_tokenlist2.BEETS_PROTOCOL;
439
+ }
440
+ }
441
+ return {
442
+ ...exchangeInfo,
443
+ valueUsd: value * baseAssetPrice,
444
+ value,
445
+ allocation: value / totalAssets
446
+ };
447
+ });
448
+ const groupedExchanges = uniqueExchangesWithValueHeld.reduce(
449
+ (acc, exchange) => {
450
+ const exchangeName = exchange.name.toLowerCase();
451
+ const existingExchange = acc.find(
452
+ (e) => e.name.toLowerCase() === exchangeName
453
+ );
454
+ if (existingExchange) {
455
+ existingExchange.valueUsd += exchange.valueUsd;
456
+ existingExchange.value += exchange.value;
457
+ existingExchange.allocation += exchange.allocation;
458
+ } else {
459
+ acc.push(exchange);
460
+ }
461
+ return acc;
462
+ },
463
+ []
464
+ );
465
+ const uniqueTokensWithValueHeldMap = filteredDestinations.flatMap((d) => d.underlyingTokens).reduce(
466
+ (acc, token) => {
467
+ if (acc[token.address]) {
468
+ acc[token.address].valueUsd += token.valueUsd;
469
+ acc[token.address].value += token.value;
470
+ } else {
471
+ acc[token.address] = { ...token };
472
+ }
473
+ return acc;
474
+ },
475
+ {}
476
+ );
477
+ const HIDDEN_TOKEN_SYMBOLS = ["USR", "WSTUSR"];
478
+ const uniqueTokens = Object.values(uniqueTokensWithValueHeldMap).filter(
479
+ (token) => !HIDDEN_TOKEN_SYMBOLS.includes(token.symbol?.toUpperCase())
480
+ ).map((token) => {
481
+ let valueUsd = token.valueUsd;
482
+ let value = token.value;
483
+ const allocation = value / totalAssets;
484
+ return {
485
+ ...token,
486
+ valueUsd,
487
+ value,
488
+ allocation
489
+ };
490
+ });
491
+ let UIBaseAsset = baseAsset;
492
+ if (baseAsset.symbol?.toLowerCase() === import_tokenlist2.WETH_TOKEN.symbol.toLowerCase()) {
493
+ UIBaseAsset = import_tokenlist2.ETH_TOKEN;
494
+ }
495
+ if (baseAsset.symbol?.toLowerCase() === import_tokenlist2.WS_TOKEN.symbol.toLowerCase()) {
496
+ UIBaseAsset = import_tokenlist2.S_TOKEN;
497
+ }
498
+ if (baseAsset.symbol?.toLowerCase() === import_tokenlist2.WXPL_TOKEN.symbol.toLowerCase()) {
499
+ UIBaseAsset = import_tokenlist2.XPL_TOKEN;
500
+ }
501
+ const isNew = (Date.now() / 1e3 - timestamp) / 60 / 60 / 24 < import_constants5.NEW_AUTOPOOL_THRESHOLD_DAYS;
502
+ const aprs = autopoolsApr.find(
503
+ (autopoolApr) => (0, import_viem.getAddress)(autopoolApr.id) === (0, import_viem.getAddress)(autopool.poolAddress)
504
+ );
505
+ const baseApr = aprs?.baseApy !== void 0 ? aprs.baseApy / 100 : void 0;
506
+ let extraApr = 0;
507
+ let extraRewards = [];
508
+ if (aprs?.rewards && aprs.rewards.length > 0) {
509
+ extraRewards = aprs.rewards.map((reward) => {
510
+ const token = (0, import_utils3.getToken)(reward.rewardToken, chainId);
511
+ return {
512
+ ...token,
513
+ apr: reward.rewardApy / 100
514
+ };
515
+ });
516
+ }
517
+ extraApr = extraRewards.reduce((acc, reward) => acc + reward.apr, 0);
518
+ const baseForMath = baseApr ?? 0;
519
+ const combinedApr = baseForMath + extraApr;
520
+ let denominatedToken = import_tokenlist2.ETH_TOKEN;
521
+ let useDenominatedValues = false;
522
+ const denominationData = autopoolsDenomination.find(
523
+ (autopoolDenom) => (0, import_viem.getAddress)(autopoolDenom.id) === (0, import_viem.getAddress)(autopool.poolAddress)
524
+ );
525
+ const denominatedIn = denominationData?.denominatedIn;
526
+ if (denominatedIn?.symbol?.toLowerCase() === "weth") {
527
+ denominatedToken = import_tokenlist2.ETH_TOKEN;
528
+ } else {
529
+ denominatedToken = (0, import_utils3.getToken)(denominatedIn?.id);
530
+ if (denominatedToken) {
531
+ useDenominatedValues = true;
532
+ }
533
+ }
534
+ let denominatedTokenPrice = 0;
535
+ const tokenSymbol = denominatedToken.symbol?.toUpperCase();
536
+ if (tokenSymbol in prices) {
537
+ denominatedTokenPrice = prices[tokenSymbol];
538
+ } else {
539
+ denominatedTokenPrice = await getTokenPrice({
540
+ chainId: denominatedToken.chainId,
541
+ tokenAddress: denominatedToken.address
542
+ }) || 0;
543
+ }
544
+ const navPerShareBaseAsset = (0, import_utils3.formatUnitsNum)(
545
+ autopool.navPerShare,
546
+ baseAsset.decimals
547
+ );
548
+ const assets = convertBaseAssetToTokenPricesAndDenom(
549
+ (0, import_utils3.formatUnitsNum)(autopool.totalAssets, baseAsset.decimals),
550
+ baseAssetPrice,
551
+ denominatedTokenPrice,
552
+ prices
553
+ );
554
+ const navPerShare = convertBaseAssetToTokenPricesAndDenom(
555
+ navPerShareBaseAsset,
556
+ baseAssetPrice,
557
+ denominatedTokenPrice,
558
+ prices
559
+ );
560
+ const idle = convertBaseAssetToTokenPricesAndDenom(
561
+ totalIdleAssets,
562
+ baseAssetPrice,
563
+ denominatedTokenPrice,
564
+ prices
565
+ );
566
+ const idleAllocation = totalIdleAssets / totalAssets;
567
+ const combinedDailyEarnings = convertBaseAssetToTokenPricesAndDenom(
568
+ totalAssets * combinedApr / import_constants5.DAYS_PER_YEAR,
569
+ baseAssetPrice,
570
+ denominatedTokenPrice,
571
+ prices
572
+ );
573
+ const baseDailyEarnings = convertBaseAssetToTokenPricesAndDenom(
574
+ totalAssets * baseForMath / import_constants5.DAYS_PER_YEAR,
575
+ baseAssetPrice,
576
+ denominatedTokenPrice,
577
+ prices
578
+ );
579
+ const tokenOrder = [UIBaseAsset.symbol, ...UITokenOrder].filter(
580
+ (value, index, array) => array.indexOf(value) === index
581
+ );
582
+ const UITokens = uniqueTokens.reduce(
583
+ (acc, token) => {
584
+ try {
585
+ const parentAsset = token.extensions?.parentAsset;
586
+ if (parentAsset) {
587
+ const parentToken = import_tokenlist2.ALL_TOKENS.find(
588
+ (t) => t.symbol.toLowerCase() === parentAsset.toLowerCase()
589
+ );
590
+ if (parentToken && !acc.some(
591
+ (t) => t?.address?.toLowerCase() === parentToken?.address?.toLowerCase()
592
+ )) {
593
+ acc.push({
594
+ ...parentToken,
595
+ valueUsd: 0,
596
+ value: 0,
597
+ allocation: 0
598
+ });
599
+ }
600
+ } else if (!acc.some(
601
+ (t) => t?.address?.toLowerCase() === token?.address?.toLowerCase()
602
+ )) {
603
+ acc.push(token);
604
+ }
605
+ } catch (error) {
606
+ console.warn(
607
+ `Error processing token: ${token?.symbol || "unknown"}`,
608
+ error
609
+ );
610
+ }
611
+ return acc;
612
+ },
613
+ []
614
+ ).sort((a, b) => {
615
+ try {
616
+ const aIndex = tokenOrder.indexOf(a.symbol.toUpperCase());
617
+ const bIndex = tokenOrder.indexOf(b.symbol.toUpperCase());
618
+ if (aIndex !== -1 && bIndex !== -1) {
619
+ return aIndex - bIndex;
620
+ }
621
+ if (aIndex !== -1) return -1;
622
+ if (bIndex !== -1) return 1;
623
+ return 0;
624
+ } catch (error) {
625
+ console.warn("Error sorting tokens:", error);
626
+ return 0;
627
+ }
628
+ });
629
+ const UIExchanges = groupedExchanges.filter((exchange) => {
630
+ try {
631
+ return exchange.type === "Lending Market" || exchange.type === "DEX";
632
+ } catch (error) {
633
+ console.warn(
634
+ `Error filtering exchange: ${exchange?.name || "unknown"}`,
635
+ error
636
+ );
637
+ return false;
638
+ }
639
+ }).sort((a, b) => {
640
+ try {
641
+ const aIndex = protocolOrder.indexOf(a.name);
642
+ const bIndex = protocolOrder.indexOf(b.name);
643
+ return aIndex - bIndex;
644
+ } catch (error) {
645
+ console.warn("Error sorting exchanges:", error);
646
+ return 0;
647
+ }
648
+ });
649
+ const finalUIExchanges = UIExchanges.filter((exchange) => {
650
+ if (exchange.name === "BalancerV3") {
651
+ return !UIExchanges.some((e) => e.name === "Balancer");
652
+ }
653
+ return true;
654
+ });
655
+ const autopoolInfo = getAutopoolInfo(autopool.symbol);
656
+ if (autopoolInfo && !autopoolInfo.description) {
657
+ autopoolInfo.description = `Autopool featuring ${UIBaseAsset.symbol} deployed across integrated DEXs and lending protocols on ${(0, import_utils3.getNetwork)(chainId)?.name}.`;
658
+ }
659
+ return {
660
+ ...autopool,
661
+ tvl,
662
+ totalAssets: assets,
663
+ destinations: filteredDestinations,
664
+ exchanges: groupedExchanges,
665
+ timestamp,
666
+ isNew,
667
+ extraRewarders: denominationData?.rewarder?.extraRewarders,
668
+ autopoolRewarderDisabled: aprs?.autopoolRewarderDisabled ?? false,
669
+ createdAt: new Date(timestamp * 1e3),
670
+ baseAsset: {
671
+ ...baseAsset,
672
+ price: baseAssetPrice
673
+ },
674
+ denomination: {
675
+ ...denominatedToken,
676
+ price: denominatedTokenPrice
677
+ },
678
+ useDenomination: useDenominatedValues,
679
+ UIBaseAsset,
680
+ UITokens,
681
+ UIExchanges: finalUIExchanges,
682
+ tokens: uniqueTokens,
683
+ chain: (0, import_utils3.getNetwork)(chainId),
684
+ apr: {
685
+ base: baseApr ?? null,
686
+ extraAprs: extraRewards,
687
+ combined: combinedApr,
688
+ hasExtraAprs: extraRewards.length > 0
689
+ },
690
+ dailyEarnings: {
691
+ combined: combinedDailyEarnings,
692
+ base: baseDailyEarnings
693
+ },
694
+ navPerShare,
695
+ idle: {
696
+ ...idle,
697
+ allocation: idleAllocation,
698
+ token: UIBaseAsset
699
+ },
700
+ category: getAutopoolCategory(baseAsset.symbol),
701
+ ...autopoolInfo,
702
+ isShutdown: autopool.symbol === "sonicUSD" ? false : autopool.isShutdown
703
+ };
704
+ })
705
+ );
706
+ return autopools;
707
+ } catch (e) {
708
+ console.error(e);
709
+ return [];
710
+ }
711
+ };
712
+
713
+ // functions/getEthPriceAtBlock.ts
714
+ var import_config2 = require("@tokemak/config");
715
+ var import_abis2 = require("@tokemak/abis");
716
+ var import_tokenlist3 = require("@tokemak/tokenlist");
717
+ var getEthPriceAtBlock = async (client, blockNumber, chainId) => {
718
+ const config = (0, import_config2.getCoreConfig)(chainId);
719
+ const rootPriceOracle = config.rootPriceOracle;
720
+ const weth = config.weth;
721
+ const usdc = import_tokenlist3.USDC_TOKEN.extensions?.bridgeInfo?.[chainId]?.tokenAddress || import_tokenlist3.USDC_TOKEN.address;
722
+ const priceAtBlock = await client.readContract({
723
+ address: rootPriceOracle,
724
+ abi: import_abis2.rootPriceOracleAbi,
725
+ functionName: "getPriceInQuote",
726
+ args: [weth, usdc],
727
+ blockNumber
728
+ });
729
+ return priceAtBlock;
730
+ };
731
+
732
+ // functions/getRebalanceStats.ts
733
+ var import_graph_cli2 = require("@tokemak/graph-cli");
734
+ var import_utils5 = require("@tokemak/utils");
735
+ var import_tokenlist4 = require("@tokemak/tokenlist");
736
+ var import_chains2 = require("viem/chains");
737
+ var BATCH_SIZE = 500;
738
+ var fetchChainRebalances = async (chainId) => {
739
+ const { GetAllAutopoolRebalances } = (0, import_graph_cli2.getSdkByChainId)(chainId);
740
+ const allRebalances = await paginateQuery(
741
+ GetAllAutopoolRebalances,
742
+ "autopoolRebalances"
743
+ );
744
+ if (allRebalances.length === 0) {
745
+ return [];
746
+ }
747
+ return allRebalances;
748
+ };
749
+ function inferBaseAssetDecimals(rebalance, chainId) {
750
+ if (BigInt(rebalance.tokenOutValueBaseAsset) === BigInt(rebalance.tokenOutValueInEth)) {
751
+ return 18;
752
+ }
753
+ if (chainId === import_chains2.sonic.id) {
754
+ return rebalance.tokenOut.decimals;
755
+ }
756
+ return import_tokenlist4.USDC_TOKEN.decimals;
757
+ }
758
+ var getRebalanceValueUsd = async (rebalance, chainId, client) => {
759
+ const ethWei = BigInt(rebalance.tokenOutValueInEth || "0");
760
+ if (ethWei === 0n) return null;
761
+ try {
762
+ const price = await getEthPriceAtBlock(
763
+ client,
764
+ BigInt(rebalance.blockNumber),
765
+ chainId
766
+ );
767
+ const ethUsd = Number((0, import_utils5.formatUnitsNum)(price, import_tokenlist4.USDC_TOKEN.decimals));
768
+ const ethAmt = Number((0, import_utils5.formatEtherNum)(ethWei));
769
+ const usd = ethAmt * ethUsd;
770
+ return usd;
771
+ } catch (e) {
772
+ console.warn(`WETH/USDC oracle unavailable for chainId: ${chainId}`);
773
+ return null;
774
+ }
775
+ };
776
+ var processRebalance = async (rebalance, chainId, client) => {
777
+ const baseDecimals = inferBaseAssetDecimals(rebalance, chainId);
778
+ const baseAssetAmount = Number(
779
+ (0, import_utils5.formatUnitsNum)(
780
+ BigInt(rebalance.tokenOutValueBaseAsset || "0"),
781
+ baseDecimals
782
+ )
783
+ );
784
+ const ethPathUsd = await getRebalanceValueUsd(rebalance, chainId, client);
785
+ if (ethPathUsd != null) {
786
+ return {
787
+ autopool: rebalance.autopool,
788
+ timestamp: rebalance.timestamp,
789
+ blockNumber: rebalance.blockNumber,
790
+ chainId,
791
+ valueInUsd: ethPathUsd,
792
+ valueInAsset: baseAssetAmount
793
+ };
794
+ }
795
+ return {
796
+ autopool: rebalance.autopool,
797
+ timestamp: rebalance.timestamp,
798
+ blockNumber: rebalance.blockNumber,
799
+ chainId,
800
+ valueInUsd: baseAssetAmount,
801
+ valueInAsset: baseAssetAmount
802
+ };
803
+ };
804
+ var processRebalancesInBatches = async (rebalances, chainId, client) => {
805
+ const processedRebalances = [];
806
+ for (let i = 0; i < rebalances.length; i += BATCH_SIZE) {
807
+ const batch = rebalances.slice(i, i + BATCH_SIZE);
808
+ const batchPromises = batch.map(
809
+ async (rebalance) => processRebalance(rebalance, chainId, client)
810
+ );
811
+ const batchResults = await Promise.all(batchPromises);
812
+ processedRebalances.push(...batchResults);
813
+ console.log(
814
+ `Processed ${Math.min(i + BATCH_SIZE, rebalances.length)} of ${rebalances.length} rebalances...`
815
+ );
816
+ if (i + BATCH_SIZE < rebalances.length) {
817
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
818
+ }
819
+ }
820
+ return processedRebalances;
821
+ };
822
+ var calculateRebalanceStats = (rebalances) => {
823
+ const totalRebalances = rebalances.length;
824
+ const totalRebalanceVolume = rebalances.reduce(
825
+ (acc, curr) => acc + curr.valueInUsd,
826
+ 0
827
+ );
828
+ return {
829
+ totalRebalances,
830
+ totalRebalanceVolume,
831
+ rebalances
832
+ };
833
+ };
834
+ var getRebalanceStats = async (getClient, {
835
+ includeTestnet = false
836
+ }) => {
837
+ const chains = getChainsForEnv({ includeTestnet });
838
+ const rebalances = await Promise.all(
839
+ chains.map(async (chain) => {
840
+ const rawRebalances = await fetchChainRebalances(chain.chainId);
841
+ const client = getClient(chain.chainId);
842
+ return processRebalancesInBatches(rawRebalances, chain.chainId, client);
843
+ })
844
+ );
845
+ const allRebalances = rebalances.flat();
846
+ return calculateRebalanceStats(allRebalances);
847
+ };
848
+ // Annotate the CommonJS export names for ESM import in node:
849
+ 0 && (module.exports = {
850
+ calculateRebalanceStats,
851
+ fetchChainRebalances,
852
+ getChainAutopools,
853
+ getChainAutopoolsApr,
854
+ getDefillamaPrice,
855
+ getEthPriceAtBlock,
856
+ getGenStratAprs,
857
+ getPoolsAndDestinations,
858
+ getRebalanceStats,
859
+ getTokenPrice
860
+ });