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