@tokemak/queries 0.5.0 → 0.7.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 +20 -18
  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 +4 -2
  12. package/dist/functions/getPoolsAndDestinations.d.ts.map +1 -1
  13. package/dist/functions/getRebalanceStats.d.ts +8 -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 +307 -352
  25. package/dist/index.mjs +197 -245
  26. package/dist/safe.d.ts +9 -0
  27. package/dist/safe.d.ts.map +1 -0
  28. package/dist/safe.js +883 -0
  29. package/dist/safe.mjs +871 -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,883 @@
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, {
297
+ chainId,
298
+ account,
299
+ blockNumber
300
+ }) => {
301
+ try {
302
+ const { lens } = (0, import_config.getCoreConfig)(chainId);
303
+ const { autoPools, destinations } = await client.readContract({
304
+ address: lens,
305
+ abi: import_abis.lensAbi,
306
+ functionName: "getPoolsAndDestinations",
307
+ account,
308
+ blockNumber
309
+ });
310
+ const autopoolsAndDestinations = mergeArraysWithKey(
311
+ autoPools,
312
+ destinations,
313
+ "destinations"
314
+ );
315
+ return autopoolsAndDestinations;
316
+ } catch (error) {
317
+ console.error(`Error on ${chainId} in getPoolsAndDestinations:`, error);
318
+ }
319
+ };
320
+
321
+ // functions/getChainAutopools.ts
322
+ var import_constants5 = require("@tokemak/constants");
323
+ var getChainAutopools = async (client, {
324
+ chainId,
325
+ prices,
326
+ account,
327
+ blockNumber
328
+ }) => {
329
+ const { GetVaultAddeds, GetAutopoolsInactiveDestinations } = (0, import_graph_cli.getSdkByChainId)(chainId);
330
+ try {
331
+ const { vaultAddeds } = await GetVaultAddeds();
332
+ const autopoolsAprResponse = await getChainAutopoolsApr(chainId);
333
+ const autopoolsApr = autopoolsAprResponse?.autopools || [];
334
+ const { GetAutopoolsApr } = (0, import_graph_cli.getSdkByChainId)(chainId);
335
+ const { autopools: autopoolsDenomination } = await GetAutopoolsApr();
336
+ const genStratAprs = await getGenStratAprs({
337
+ chainId
338
+ });
339
+ const autopoolsAndDestinations = await getPoolsAndDestinations(client, {
340
+ chainId,
341
+ account,
342
+ blockNumber
343
+ });
344
+ if (!autopoolsAndDestinations) {
345
+ throw new Error(`No autopools and destinations found for ${chainId}`);
346
+ }
347
+ const vaultAddedMapping = vaultAddeds.reduce(
348
+ (acc, vaultAdded) => {
349
+ acc[vaultAdded.vault.toLowerCase()] = Number(vaultAdded.blockTimestamp);
350
+ return acc;
351
+ },
352
+ {}
353
+ );
354
+ const autopools = await Promise.all(
355
+ autopoolsAndDestinations.map(async (autopool) => {
356
+ let baseAsset = (0, import_utils3.getToken)(autopool.baseAsset);
357
+ if (!baseAsset?.symbol) {
358
+ console.error(
359
+ "FIX THIS BEFORE PROD: base asset not found",
360
+ autopool.baseAsset
361
+ );
362
+ }
363
+ let baseAssetPrice = prices[(baseAsset?.symbol || "").toUpperCase()];
364
+ if (!baseAssetPrice) {
365
+ baseAssetPrice = await getTokenPrice({
366
+ chainId: baseAsset.chainId,
367
+ tokenAddress: baseAsset.address
368
+ }) || 0;
369
+ }
370
+ const timestamp = vaultAddedMapping[autopool.poolAddress.toLowerCase()];
371
+ const totalAssets = (0, import_utils3.formatUnitsNum)(
372
+ autopool.totalAssets,
373
+ baseAsset.decimals
374
+ );
375
+ const tvl = totalAssets * baseAssetPrice;
376
+ const totalIdleAssets = (0, import_utils3.formatUnitsNum)(
377
+ autopool.totalIdle,
378
+ baseAsset.decimals
379
+ );
380
+ const exchangeValues = {};
381
+ const destinations = autopool.destinations.map((destination) => {
382
+ const debtValueHeldByVaultEth = (0, import_utils3.formatUnitsNum)(
383
+ destination.debtValueHeldByVault,
384
+ baseAsset.decimals
385
+ );
386
+ if (!exchangeValues[destination.exchangeName.toLowerCase()]) {
387
+ exchangeValues[destination.exchangeName.toLowerCase()] = 0;
388
+ }
389
+ exchangeValues[destination.exchangeName.toLowerCase()] += debtValueHeldByVaultEth;
390
+ const tokensWithValue = mergeArrays(
391
+ destination.underlyingTokens,
392
+ destination.underlyingTokenValueHeld
393
+ );
394
+ let underlyingTokens = tokensWithValue.map((token) => {
395
+ const tokenDetails = (0, import_utils3.getToken)(token.tokenAddress);
396
+ let value = (0, import_utils3.formatUnitsNum)(
397
+ token.valueHeldInEth,
398
+ baseAsset.decimals
399
+ );
400
+ let valueUsd = value * baseAssetPrice;
401
+ return {
402
+ ...tokenDetails,
403
+ valueUsd,
404
+ value
405
+ };
406
+ });
407
+ if (destination.underlyingTokenSymbols.length === 1) {
408
+ const underlyingTokenAddress = tokensWithValue[0].tokenAddress;
409
+ if (underlyingTokenAddress) {
410
+ underlyingTokens = [
411
+ {
412
+ ...(0, import_utils3.getToken)(underlyingTokenAddress, chainId),
413
+ valueUsd: debtValueHeldByVaultEth * baseAssetPrice,
414
+ value: debtValueHeldByVaultEth
415
+ }
416
+ ];
417
+ }
418
+ }
419
+ const isGenStrat = autopool.strategy.toLowerCase() === import_constants5.DEAD_ADDRESS || autopool.strategy === import_constants5.ZERO_ADDRESS;
420
+ return {
421
+ ...destination,
422
+ debtValueHeldByVaultUsd: debtValueHeldByVaultEth * baseAssetPrice,
423
+ debtValueHeldByVaultEth,
424
+ compositeReturn: isGenStrat ? genStratAprs?.[autopool.poolAddress]?.[destination.vaultAddress]?.apr || 0 : (0, import_utils3.formatEtherNum)(destination.compositeReturn),
425
+ debtValueHeldByVaultAllocation: debtValueHeldByVaultEth / totalAssets,
426
+ underlyingTokens,
427
+ poolName: (0, import_utils3.formatPoolName)(destination.lpTokenName),
428
+ exchange: (0, import_utils3.getProtocol)(destination.exchangeName)
429
+ };
430
+ });
431
+ const HIDDEN_DESTINATION_SYMBOLS = ["USR", "WSTUSR"];
432
+ const filteredDestinations = destinations.filter(
433
+ (d) => !d.underlyingTokens.some(
434
+ (t) => HIDDEN_DESTINATION_SYMBOLS.includes(t.symbol?.toUpperCase())
435
+ )
436
+ );
437
+ const uniqueExchanges = Array.from(
438
+ new Set(
439
+ filteredDestinations.map((d) => (0, import_utils3.getProtocol)(d.exchangeName)).filter(Boolean)
440
+ )
441
+ );
442
+ const uniqueExchangesWithValueHeld = uniqueExchanges.map((exchange) => {
443
+ const exchangeName = exchange.name.toLowerCase();
444
+ let exchangeInfo = exchange;
445
+ const value = exchangeValues[exchangeName];
446
+ if (chainId === import_chains.sonic.id) {
447
+ if (exchangeName === "balancerv3" || exchangeName === "balancer") {
448
+ exchangeInfo = import_tokenlist2.BEETS_PROTOCOL;
449
+ }
450
+ }
451
+ return {
452
+ ...exchangeInfo,
453
+ valueUsd: value * baseAssetPrice,
454
+ value,
455
+ allocation: value / totalAssets
456
+ };
457
+ });
458
+ const groupedExchanges = uniqueExchangesWithValueHeld.reduce(
459
+ (acc, exchange) => {
460
+ const exchangeName = exchange.name.toLowerCase();
461
+ const existingExchange = acc.find(
462
+ (e) => e.name.toLowerCase() === exchangeName
463
+ );
464
+ if (existingExchange) {
465
+ existingExchange.valueUsd += exchange.valueUsd;
466
+ existingExchange.value += exchange.value;
467
+ existingExchange.allocation += exchange.allocation;
468
+ } else {
469
+ acc.push(exchange);
470
+ }
471
+ return acc;
472
+ },
473
+ []
474
+ );
475
+ const uniqueTokensWithValueHeldMap = filteredDestinations.flatMap((d) => d.underlyingTokens).reduce(
476
+ (acc, token) => {
477
+ if (acc[token.address]) {
478
+ acc[token.address].valueUsd += token.valueUsd;
479
+ acc[token.address].value += token.value;
480
+ } else {
481
+ acc[token.address] = { ...token };
482
+ }
483
+ return acc;
484
+ },
485
+ {}
486
+ );
487
+ const HIDDEN_TOKEN_SYMBOLS = ["USR", "WSTUSR"];
488
+ const uniqueTokens = Object.values(uniqueTokensWithValueHeldMap).filter(
489
+ (token) => !HIDDEN_TOKEN_SYMBOLS.includes(token.symbol?.toUpperCase())
490
+ ).map((token) => {
491
+ let valueUsd = token.valueUsd;
492
+ let value = token.value;
493
+ const allocation = value / totalAssets;
494
+ return {
495
+ ...token,
496
+ valueUsd,
497
+ value,
498
+ allocation
499
+ };
500
+ });
501
+ let UIBaseAsset = baseAsset;
502
+ if (baseAsset.symbol?.toLowerCase() === import_tokenlist2.WETH_TOKEN.symbol.toLowerCase()) {
503
+ UIBaseAsset = import_tokenlist2.ETH_TOKEN;
504
+ }
505
+ if (baseAsset.symbol?.toLowerCase() === import_tokenlist2.WS_TOKEN.symbol.toLowerCase()) {
506
+ UIBaseAsset = import_tokenlist2.S_TOKEN;
507
+ }
508
+ if (baseAsset.symbol?.toLowerCase() === import_tokenlist2.WXPL_TOKEN.symbol.toLowerCase()) {
509
+ UIBaseAsset = import_tokenlist2.XPL_TOKEN;
510
+ }
511
+ const isNew = (Date.now() / 1e3 - timestamp) / 60 / 60 / 24 < import_constants5.NEW_AUTOPOOL_THRESHOLD_DAYS;
512
+ const aprs = autopoolsApr.find(
513
+ (autopoolApr) => (0, import_viem.getAddress)(autopoolApr.id) === (0, import_viem.getAddress)(autopool.poolAddress)
514
+ );
515
+ const baseApr = aprs?.baseApy !== void 0 ? aprs.baseApy / 100 : void 0;
516
+ let extraApr = 0;
517
+ let extraRewards = [];
518
+ if (aprs?.rewards && aprs.rewards.length > 0) {
519
+ extraRewards = aprs.rewards.map((reward) => {
520
+ const token = (0, import_utils3.getToken)(reward.rewardToken, chainId);
521
+ return {
522
+ ...token,
523
+ apr: reward.rewardApy / 100
524
+ };
525
+ });
526
+ }
527
+ extraApr = extraRewards.reduce((acc, reward) => acc + reward.apr, 0);
528
+ const baseForMath = baseApr ?? 0;
529
+ const combinedApr = baseForMath + extraApr;
530
+ let denominatedToken = import_tokenlist2.ETH_TOKEN;
531
+ let useDenominatedValues = false;
532
+ const denominationData = autopoolsDenomination.find(
533
+ (autopoolDenom) => (0, import_viem.getAddress)(autopoolDenom.id) === (0, import_viem.getAddress)(autopool.poolAddress)
534
+ );
535
+ const denominatedIn = denominationData?.denominatedIn;
536
+ if (denominatedIn?.symbol?.toLowerCase() === "weth") {
537
+ denominatedToken = import_tokenlist2.ETH_TOKEN;
538
+ } else {
539
+ denominatedToken = (0, import_utils3.getToken)(denominatedIn?.id);
540
+ if (denominatedToken) {
541
+ useDenominatedValues = true;
542
+ }
543
+ }
544
+ let denominatedTokenPrice = 0;
545
+ const tokenSymbol = denominatedToken.symbol?.toUpperCase();
546
+ if (tokenSymbol in prices) {
547
+ denominatedTokenPrice = prices[tokenSymbol];
548
+ } else {
549
+ denominatedTokenPrice = await getTokenPrice({
550
+ chainId: denominatedToken.chainId,
551
+ tokenAddress: denominatedToken.address
552
+ }) || 0;
553
+ }
554
+ const navPerShareBaseAsset = (0, import_utils3.formatUnitsNum)(
555
+ autopool.navPerShare,
556
+ baseAsset.decimals
557
+ );
558
+ const assets = convertBaseAssetToTokenPricesAndDenom(
559
+ (0, import_utils3.formatUnitsNum)(autopool.totalAssets, baseAsset.decimals),
560
+ baseAssetPrice,
561
+ denominatedTokenPrice,
562
+ prices
563
+ );
564
+ const navPerShare = convertBaseAssetToTokenPricesAndDenom(
565
+ navPerShareBaseAsset,
566
+ baseAssetPrice,
567
+ denominatedTokenPrice,
568
+ prices
569
+ );
570
+ const idle = convertBaseAssetToTokenPricesAndDenom(
571
+ totalIdleAssets,
572
+ baseAssetPrice,
573
+ denominatedTokenPrice,
574
+ prices
575
+ );
576
+ const idleAllocation = totalIdleAssets / totalAssets;
577
+ const combinedDailyEarnings = convertBaseAssetToTokenPricesAndDenom(
578
+ totalAssets * combinedApr / import_constants5.DAYS_PER_YEAR,
579
+ baseAssetPrice,
580
+ denominatedTokenPrice,
581
+ prices
582
+ );
583
+ const baseDailyEarnings = convertBaseAssetToTokenPricesAndDenom(
584
+ totalAssets * baseForMath / import_constants5.DAYS_PER_YEAR,
585
+ baseAssetPrice,
586
+ denominatedTokenPrice,
587
+ prices
588
+ );
589
+ const tokenOrder = [UIBaseAsset.symbol, ...UITokenOrder].filter(
590
+ (value, index, array) => array.indexOf(value) === index
591
+ );
592
+ const UITokens = uniqueTokens.reduce(
593
+ (acc, token) => {
594
+ try {
595
+ const parentAsset = token.extensions?.parentAsset;
596
+ if (parentAsset) {
597
+ const parentToken = import_tokenlist2.ALL_TOKENS.find(
598
+ (t) => t.symbol.toLowerCase() === parentAsset.toLowerCase()
599
+ );
600
+ if (parentToken && !acc.some(
601
+ (t) => t?.address?.toLowerCase() === parentToken?.address?.toLowerCase()
602
+ )) {
603
+ acc.push({
604
+ ...parentToken,
605
+ valueUsd: 0,
606
+ value: 0,
607
+ allocation: 0
608
+ });
609
+ }
610
+ } else if (!acc.some(
611
+ (t) => t?.address?.toLowerCase() === token?.address?.toLowerCase()
612
+ )) {
613
+ acc.push(token);
614
+ }
615
+ } catch (error) {
616
+ console.warn(
617
+ `Error processing token: ${token?.symbol || "unknown"}`,
618
+ error
619
+ );
620
+ }
621
+ return acc;
622
+ },
623
+ []
624
+ ).sort((a, b) => {
625
+ try {
626
+ const aIndex = tokenOrder.indexOf(a.symbol.toUpperCase());
627
+ const bIndex = tokenOrder.indexOf(b.symbol.toUpperCase());
628
+ if (aIndex !== -1 && bIndex !== -1) {
629
+ return aIndex - bIndex;
630
+ }
631
+ if (aIndex !== -1) return -1;
632
+ if (bIndex !== -1) return 1;
633
+ return 0;
634
+ } catch (error) {
635
+ console.warn("Error sorting tokens:", error);
636
+ return 0;
637
+ }
638
+ });
639
+ const UIExchanges = groupedExchanges.filter((exchange) => {
640
+ try {
641
+ return exchange.type === "Lending Market" || exchange.type === "DEX";
642
+ } catch (error) {
643
+ console.warn(
644
+ `Error filtering exchange: ${exchange?.name || "unknown"}`,
645
+ error
646
+ );
647
+ return false;
648
+ }
649
+ }).sort((a, b) => {
650
+ try {
651
+ const aIndex = protocolOrder.indexOf(a.name);
652
+ const bIndex = protocolOrder.indexOf(b.name);
653
+ return aIndex - bIndex;
654
+ } catch (error) {
655
+ console.warn("Error sorting exchanges:", error);
656
+ return 0;
657
+ }
658
+ });
659
+ const finalUIExchanges = UIExchanges.filter((exchange) => {
660
+ if (exchange.name === "BalancerV3") {
661
+ return !UIExchanges.some((e) => e.name === "Balancer");
662
+ }
663
+ return true;
664
+ });
665
+ const autopoolInfo = getAutopoolInfo(autopool.symbol);
666
+ if (autopoolInfo && !autopoolInfo.description) {
667
+ autopoolInfo.description = `Autopool featuring ${UIBaseAsset.symbol} deployed across integrated DEXs and lending protocols on ${(0, import_utils3.getNetwork)(chainId)?.name}.`;
668
+ }
669
+ return {
670
+ ...autopool,
671
+ tvl,
672
+ totalAssets: assets,
673
+ destinations: filteredDestinations,
674
+ exchanges: groupedExchanges,
675
+ timestamp,
676
+ isNew,
677
+ extraRewarders: denominationData?.rewarder?.extraRewarders,
678
+ autopoolRewarderDisabled: aprs?.autopoolRewarderDisabled ?? false,
679
+ createdAt: new Date(timestamp * 1e3),
680
+ baseAsset: {
681
+ ...baseAsset,
682
+ price: baseAssetPrice
683
+ },
684
+ denomination: {
685
+ ...denominatedToken,
686
+ price: denominatedTokenPrice
687
+ },
688
+ useDenomination: useDenominatedValues,
689
+ UIBaseAsset,
690
+ UITokens,
691
+ UIExchanges: finalUIExchanges,
692
+ tokens: uniqueTokens,
693
+ chain: (0, import_utils3.getNetwork)(chainId),
694
+ apr: {
695
+ base: baseApr ?? null,
696
+ extraAprs: extraRewards,
697
+ combined: combinedApr,
698
+ hasExtraAprs: extraRewards.length > 0
699
+ },
700
+ dailyEarnings: {
701
+ combined: combinedDailyEarnings,
702
+ base: baseDailyEarnings
703
+ },
704
+ navPerShare,
705
+ idle: {
706
+ ...idle,
707
+ allocation: idleAllocation,
708
+ token: UIBaseAsset
709
+ },
710
+ category: getAutopoolCategory(baseAsset.symbol),
711
+ ...autopoolInfo,
712
+ isShutdown: autopool.symbol === "sonicUSD" ? false : autopool.isShutdown
713
+ };
714
+ })
715
+ );
716
+ return autopools;
717
+ } catch (e) {
718
+ console.error(e);
719
+ return [];
720
+ }
721
+ };
722
+
723
+ // functions/getEthPriceAtBlock.ts
724
+ var import_config2 = require("@tokemak/config");
725
+ var import_abis2 = require("@tokemak/abis");
726
+ var import_tokenlist3 = require("@tokemak/tokenlist");
727
+ var getEthPriceAtBlock = async (client, blockNumber, chainId, account) => {
728
+ const config = (0, import_config2.getCoreConfig)(chainId);
729
+ const rootPriceOracle = config.rootPriceOracle;
730
+ const weth = config.weth;
731
+ const usdc = import_tokenlist3.USDC_TOKEN.extensions?.bridgeInfo?.[chainId]?.tokenAddress || import_tokenlist3.USDC_TOKEN.address;
732
+ const priceAtBlock = await client.readContract({
733
+ address: rootPriceOracle,
734
+ abi: import_abis2.rootPriceOracleAbi,
735
+ functionName: "getPriceInQuote",
736
+ args: [weth, usdc],
737
+ blockNumber,
738
+ account
739
+ });
740
+ return priceAtBlock;
741
+ };
742
+
743
+ // functions/getRebalanceStats.ts
744
+ var import_graph_cli2 = require("@tokemak/graph-cli");
745
+ var import_utils5 = require("@tokemak/utils");
746
+ var import_tokenlist4 = require("@tokemak/tokenlist");
747
+ var import_chains2 = require("viem/chains");
748
+ var BATCH_SIZE = 500;
749
+ var fetchChainRebalances = async (chainId) => {
750
+ const { GetAllAutopoolRebalances } = (0, import_graph_cli2.getSdkByChainId)(chainId);
751
+ const allRebalances = await paginateQuery(
752
+ GetAllAutopoolRebalances,
753
+ "autopoolRebalances"
754
+ );
755
+ if (allRebalances.length === 0) {
756
+ return [];
757
+ }
758
+ return allRebalances;
759
+ };
760
+ function inferBaseAssetDecimals(rebalance, chainId) {
761
+ if (BigInt(rebalance.tokenOutValueBaseAsset) === BigInt(rebalance.tokenOutValueInEth)) {
762
+ return 18;
763
+ }
764
+ if (chainId === import_chains2.sonic.id) {
765
+ return rebalance.tokenOut.decimals;
766
+ }
767
+ return import_tokenlist4.USDC_TOKEN.decimals;
768
+ }
769
+ var getRebalanceValueUsd = async (rebalance, chainId, client, account) => {
770
+ const ethWei = BigInt(rebalance.tokenOutValueInEth || "0");
771
+ if (ethWei === 0n) return null;
772
+ try {
773
+ const price = await getEthPriceAtBlock(
774
+ client,
775
+ BigInt(rebalance.blockNumber),
776
+ chainId,
777
+ account
778
+ );
779
+ const ethUsd = Number((0, import_utils5.formatUnitsNum)(price, import_tokenlist4.USDC_TOKEN.decimals));
780
+ const ethAmt = Number((0, import_utils5.formatEtherNum)(ethWei));
781
+ const usd = ethAmt * ethUsd;
782
+ return usd;
783
+ } catch (e) {
784
+ console.warn(`WETH/USDC oracle unavailable for chainId: ${chainId}`);
785
+ return null;
786
+ }
787
+ };
788
+ var processRebalance = async (rebalance, chainId, client, account) => {
789
+ const baseDecimals = inferBaseAssetDecimals(rebalance, chainId);
790
+ const baseAssetAmount = Number(
791
+ (0, import_utils5.formatUnitsNum)(
792
+ BigInt(rebalance.tokenOutValueBaseAsset || "0"),
793
+ baseDecimals
794
+ )
795
+ );
796
+ const ethPathUsd = await getRebalanceValueUsd(
797
+ rebalance,
798
+ chainId,
799
+ client,
800
+ account
801
+ );
802
+ if (ethPathUsd != null) {
803
+ return {
804
+ autopool: rebalance.autopool,
805
+ timestamp: rebalance.timestamp,
806
+ blockNumber: rebalance.blockNumber,
807
+ chainId,
808
+ valueInUsd: ethPathUsd,
809
+ valueInAsset: baseAssetAmount
810
+ };
811
+ }
812
+ return {
813
+ autopool: rebalance.autopool,
814
+ timestamp: rebalance.timestamp,
815
+ blockNumber: rebalance.blockNumber,
816
+ chainId,
817
+ valueInUsd: baseAssetAmount,
818
+ valueInAsset: baseAssetAmount
819
+ };
820
+ };
821
+ var processRebalancesInBatches = async (rebalances, chainId, client, account) => {
822
+ const processedRebalances = [];
823
+ for (let i = 0; i < rebalances.length; i += BATCH_SIZE) {
824
+ const batch = rebalances.slice(i, i + BATCH_SIZE);
825
+ const batchPromises = batch.map(
826
+ async (rebalance) => processRebalance(rebalance, chainId, client, account)
827
+ );
828
+ const batchResults = await Promise.all(batchPromises);
829
+ processedRebalances.push(...batchResults);
830
+ console.log(
831
+ `Processed ${Math.min(i + BATCH_SIZE, rebalances.length)} of ${rebalances.length} rebalances...`
832
+ );
833
+ if (i + BATCH_SIZE < rebalances.length) {
834
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
835
+ }
836
+ }
837
+ return processedRebalances;
838
+ };
839
+ var calculateRebalanceStats = (rebalances) => {
840
+ const totalRebalances = rebalances.length;
841
+ const totalRebalanceVolume = rebalances.reduce(
842
+ (acc, curr) => acc + curr.valueInUsd,
843
+ 0
844
+ );
845
+ return {
846
+ totalRebalances,
847
+ totalRebalanceVolume,
848
+ rebalances
849
+ };
850
+ };
851
+ var getRebalanceStats = async (getClient, {
852
+ includeTestnet = false,
853
+ account
854
+ }) => {
855
+ const chains = getChainsForEnv({ includeTestnet });
856
+ const rebalances = await Promise.all(
857
+ chains.map(async (chain) => {
858
+ const rawRebalances = await fetchChainRebalances(chain.chainId);
859
+ const client = getClient(chain.chainId);
860
+ return processRebalancesInBatches(
861
+ rawRebalances,
862
+ chain.chainId,
863
+ client,
864
+ account
865
+ );
866
+ })
867
+ );
868
+ const allRebalances = rebalances.flat();
869
+ return calculateRebalanceStats(allRebalances);
870
+ };
871
+ // Annotate the CommonJS export names for ESM import in node:
872
+ 0 && (module.exports = {
873
+ calculateRebalanceStats,
874
+ fetchChainRebalances,
875
+ getChainAutopools,
876
+ getChainAutopoolsApr,
877
+ getDefillamaPrice,
878
+ getEthPriceAtBlock,
879
+ getGenStratAprs,
880
+ getPoolsAndDestinations,
881
+ getRebalanceStats,
882
+ getTokenPrice
883
+ });