@defisaver/positions-sdk 2.0.12 → 2.0.14-dev-portfolio

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 (170) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/CLAUDE.md +32 -0
  4. package/README.md +64 -64
  5. package/cjs/aaveV2/index.js +1 -0
  6. package/cjs/aaveV3/index.d.ts +12 -0
  7. package/cjs/aaveV3/index.js +93 -1
  8. package/cjs/claiming/aaveV3.d.ts +9 -0
  9. package/cjs/claiming/aaveV3.js +148 -0
  10. package/cjs/claiming/compV3.d.ts +15 -0
  11. package/cjs/claiming/compV3.js +34 -0
  12. package/cjs/claiming/index.d.ts +6 -0
  13. package/cjs/claiming/index.js +46 -0
  14. package/cjs/claiming/king.d.ts +4 -0
  15. package/cjs/claiming/king.js +72 -0
  16. package/cjs/claiming/morphoBlue.d.ts +6 -0
  17. package/cjs/claiming/morphoBlue.js +113 -0
  18. package/cjs/claiming/spark.d.ts +6 -0
  19. package/cjs/claiming/spark.js +188 -0
  20. package/cjs/config/contracts.d.ts +2667 -0
  21. package/cjs/config/contracts.js +103 -2
  22. package/cjs/constants/index.d.ts +4 -0
  23. package/cjs/constants/index.js +6 -2
  24. package/cjs/contracts.d.ts +2882 -23
  25. package/cjs/contracts.js +10 -1
  26. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  27. package/cjs/index.d.ts +2 -1
  28. package/cjs/index.js +3 -1
  29. package/cjs/liquity/index.d.ts +11 -0
  30. package/cjs/liquity/index.js +39 -1
  31. package/cjs/liquityV2/index.d.ts +8 -0
  32. package/cjs/liquityV2/index.js +161 -0
  33. package/cjs/markets/aave/marketAssets.js +1 -1
  34. package/cjs/markets/compound/marketsAssets.js +2 -2
  35. package/cjs/markets/spark/marketAssets.js +1 -1
  36. package/cjs/morphoBlue/index.d.ts +5 -0
  37. package/cjs/morphoBlue/index.js +38 -4
  38. package/cjs/portfolio/index.d.ts +6 -1
  39. package/cjs/portfolio/index.js +256 -10
  40. package/cjs/services/utils.d.ts +5 -0
  41. package/cjs/services/utils.js +33 -1
  42. package/cjs/services/viem.d.ts +12 -12
  43. package/cjs/spark/index.js +1 -0
  44. package/cjs/staking/staking.js +3 -1
  45. package/cjs/types/claiming.d.ts +93 -0
  46. package/cjs/types/claiming.js +27 -0
  47. package/cjs/umbrella/index.d.ts +5 -0
  48. package/cjs/umbrella/index.js +50 -0
  49. package/cjs/umbrella/umbrellaUtils.d.ts +22 -0
  50. package/cjs/umbrella/umbrellaUtils.js +34 -0
  51. package/esm/aaveV2/index.js +1 -0
  52. package/esm/aaveV3/index.d.ts +12 -0
  53. package/esm/aaveV3/index.js +91 -1
  54. package/esm/claiming/aaveV3.d.ts +9 -0
  55. package/esm/claiming/aaveV3.js +139 -0
  56. package/esm/claiming/compV3.d.ts +15 -0
  57. package/esm/claiming/compV3.js +30 -0
  58. package/esm/claiming/index.d.ts +6 -0
  59. package/esm/claiming/index.js +6 -0
  60. package/esm/claiming/king.d.ts +4 -0
  61. package/esm/claiming/king.js +64 -0
  62. package/esm/claiming/morphoBlue.d.ts +6 -0
  63. package/esm/claiming/morphoBlue.js +104 -0
  64. package/esm/claiming/spark.d.ts +6 -0
  65. package/esm/claiming/spark.js +179 -0
  66. package/esm/config/contracts.d.ts +2667 -0
  67. package/esm/config/contracts.js +102 -1
  68. package/esm/constants/index.d.ts +4 -0
  69. package/esm/constants/index.js +5 -1
  70. package/esm/contracts.d.ts +2882 -23
  71. package/esm/contracts.js +9 -0
  72. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  73. package/esm/index.d.ts +2 -1
  74. package/esm/index.js +2 -1
  75. package/esm/liquity/index.d.ts +11 -0
  76. package/esm/liquity/index.js +38 -1
  77. package/esm/liquityV2/index.d.ts +8 -0
  78. package/esm/liquityV2/index.js +162 -1
  79. package/esm/markets/aave/marketAssets.js +1 -1
  80. package/esm/markets/compound/marketsAssets.js +2 -2
  81. package/esm/markets/spark/marketAssets.js +1 -1
  82. package/esm/morphoBlue/index.d.ts +5 -0
  83. package/esm/morphoBlue/index.js +38 -5
  84. package/esm/portfolio/index.d.ts +6 -1
  85. package/esm/portfolio/index.js +260 -14
  86. package/esm/services/utils.d.ts +5 -0
  87. package/esm/services/utils.js +31 -0
  88. package/esm/services/viem.d.ts +12 -12
  89. package/esm/spark/index.js +1 -0
  90. package/esm/staking/staking.js +3 -1
  91. package/esm/types/claiming.d.ts +93 -0
  92. package/esm/types/claiming.js +24 -0
  93. package/esm/umbrella/index.d.ts +5 -0
  94. package/esm/umbrella/index.js +46 -0
  95. package/esm/umbrella/umbrellaUtils.d.ts +22 -0
  96. package/esm/umbrella/umbrellaUtils.js +28 -0
  97. package/package.json +47 -47
  98. package/src/aaveV2/index.ts +237 -236
  99. package/src/aaveV3/index.ts +586 -488
  100. package/src/claiming/aaveV3.ts +163 -0
  101. package/src/claiming/compV3.ts +23 -0
  102. package/src/claiming/index.ts +13 -0
  103. package/src/claiming/king.ts +66 -0
  104. package/src/claiming/morphoBlue.ts +119 -0
  105. package/src/claiming/spark.ts +226 -0
  106. package/src/compoundV2/index.ts +240 -240
  107. package/src/compoundV3/index.ts +270 -270
  108. package/src/config/contracts.ts +1208 -1108
  109. package/src/constants/index.ts +10 -6
  110. package/src/contracts.ts +121 -108
  111. package/src/curveUsd/index.ts +250 -250
  112. package/src/eulerV2/index.ts +314 -314
  113. package/src/exchange/index.ts +25 -25
  114. package/src/fluid/index.ts +1568 -1568
  115. package/src/helpers/aaveHelpers/index.ts +170 -170
  116. package/src/helpers/compoundHelpers/index.ts +261 -261
  117. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  118. package/src/helpers/eulerHelpers/index.ts +259 -259
  119. package/src/helpers/fluidHelpers/index.ts +324 -324
  120. package/src/helpers/index.ts +10 -10
  121. package/src/helpers/liquityV2Helpers/index.ts +80 -80
  122. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  123. package/src/helpers/makerHelpers/index.ts +52 -52
  124. package/src/helpers/morphoBlueHelpers/index.ts +390 -390
  125. package/src/helpers/sparkHelpers/index.ts +155 -155
  126. package/src/index.ts +47 -45
  127. package/src/liquity/index.ts +160 -105
  128. package/src/liquityV2/index.ts +583 -408
  129. package/src/llamaLend/index.ts +296 -296
  130. package/src/maker/index.ts +223 -223
  131. package/src/markets/aave/index.ts +116 -116
  132. package/src/markets/aave/marketAssets.ts +49 -49
  133. package/src/markets/compound/index.ts +227 -227
  134. package/src/markets/compound/marketsAssets.ts +90 -90
  135. package/src/markets/curveUsd/index.ts +69 -69
  136. package/src/markets/euler/index.ts +26 -26
  137. package/src/markets/fluid/index.ts +2456 -2456
  138. package/src/markets/index.ts +25 -25
  139. package/src/markets/liquityV2/index.ts +102 -102
  140. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  141. package/src/markets/llamaLend/index.ts +235 -235
  142. package/src/markets/morphoBlue/index.ts +895 -895
  143. package/src/markets/spark/index.ts +29 -29
  144. package/src/markets/spark/marketAssets.ts +11 -11
  145. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  146. package/src/morphoBlue/index.ts +259 -222
  147. package/src/portfolio/index.ts +533 -285
  148. package/src/services/priceService.ts +159 -159
  149. package/src/services/utils.ts +100 -64
  150. package/src/services/viem.ts +32 -32
  151. package/src/setup.ts +8 -8
  152. package/src/spark/index.ts +457 -456
  153. package/src/staking/staking.ts +194 -193
  154. package/src/types/aave.ts +194 -194
  155. package/src/types/claiming.ts +109 -0
  156. package/src/types/common.ts +88 -88
  157. package/src/types/compound.ts +136 -136
  158. package/src/types/curveUsd.ts +121 -121
  159. package/src/types/euler.ts +174 -174
  160. package/src/types/fluid.ts +450 -450
  161. package/src/types/index.ts +11 -11
  162. package/src/types/liquity.ts +30 -30
  163. package/src/types/liquityV2.ts +126 -126
  164. package/src/types/llamaLend.ts +157 -157
  165. package/src/types/maker.ts +63 -63
  166. package/src/types/morphoBlue.ts +194 -194
  167. package/src/types/portfolio.ts +60 -60
  168. package/src/types/spark.ts +137 -137
  169. package/src/umbrella/index.ts +70 -0
  170. package/src/umbrella/umbrellaUtils.ts +30 -0
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.getKingRewards = exports.fetchKingRewards = void 0;
16
+ const decimal_js_1 = __importDefault(require("decimal.js"));
17
+ const tokens_1 = require("@defisaver/tokens");
18
+ const contracts_1 = require("../contracts");
19
+ const claiming_1 = require("../types/claiming");
20
+ const fetchKingRewards = (walletAddress) => __awaiter(void 0, void 0, void 0, function* () {
21
+ try {
22
+ const res = yield fetch(`https://fe.defisaver.com/api/etherfi/get-king-rewards/${walletAddress}`, { signal: AbortSignal.timeout(5000) });
23
+ if (!res.ok)
24
+ throw new Error(yield res.text());
25
+ return yield res.json();
26
+ }
27
+ catch (err) {
28
+ console.error('External API Error: Error fetching KING rewards:', err);
29
+ return { Amount: '0', Root: '', Proofs: [] };
30
+ }
31
+ });
32
+ exports.fetchKingRewards = fetchKingRewards;
33
+ const getKingRewards = (provider, network, walletAddresses) => __awaiter(void 0, void 0, void 0, function* () {
34
+ // Fetch all API data in parallel (these are external API calls, can't be batched with multicall)
35
+ const apiDataPromises = walletAddresses.map(address => (0, exports.fetchKingRewards)(address));
36
+ const apiDataArray = yield Promise.all(apiDataPromises);
37
+ // Batch all contract calls using multicall
38
+ const contract = (0, contracts_1.UUPSViem)(provider, network);
39
+ const cumulativePromises = walletAddresses.map(address => contract.read.cumulativeClaimed([address]));
40
+ const cumulativeResults = yield Promise.all(cumulativePromises);
41
+ // Process results
42
+ const results = {};
43
+ for (let i = 0; i < walletAddresses.length; i++) {
44
+ const walletAddress = walletAddresses[i];
45
+ const data = apiDataArray[i];
46
+ const cumulative = cumulativeResults[i];
47
+ const allRewardsAmount = (0, tokens_1.assetAmountInEth)(data.Amount, 'KING');
48
+ const claimedAmount = (0, tokens_1.assetAmountInEth)(cumulative.toString(), 'KING');
49
+ const amountToClaim = new decimal_js_1.default(allRewardsAmount).sub(claimedAmount);
50
+ if (amountToClaim.lessThanOrEqualTo('0')) {
51
+ results[walletAddress.toLowerCase()] = [];
52
+ }
53
+ else {
54
+ results[walletAddress.toLowerCase()] = [{
55
+ symbol: 'KING',
56
+ underlyingSymbol: 'KING',
57
+ tokenAddress: '0x8F08B70456eb22f6109F57b8fafE862ED28E6040',
58
+ amount: amountToClaim.toString(),
59
+ walletAddress,
60
+ label: 'weETH',
61
+ claimType: claiming_1.ClaimType.KING_REWARDS,
62
+ additionalClaimFields: {
63
+ allRewardsAmount,
64
+ merkleRoot: data.Root,
65
+ merkleProofs: data.Proofs,
66
+ },
67
+ }];
68
+ }
69
+ }
70
+ return results;
71
+ });
72
+ exports.getKingRewards = getKingRewards;
@@ -0,0 +1,6 @@
1
+ import { Client } from 'viem';
2
+ import { ClaimableToken } from '../types/claiming';
3
+ import { EthAddress, NetworkNumber } from '../types/common';
4
+ export declare const getMorphoUnderlyingSymbol: (_symbol: string) => any;
5
+ export declare const getMorphoBlueRewardsInfo: (address: EthAddress) => Promise<any>;
6
+ export declare const fetchMorphoBlueRewards: (provider: Client, network: NetworkNumber, walletAddresses: EthAddress[]) => Promise<Record<string, ClaimableToken[]>>;
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.fetchMorphoBlueRewards = exports.getMorphoBlueRewardsInfo = exports.getMorphoUnderlyingSymbol = void 0;
16
+ const tokens_1 = require("@defisaver/tokens");
17
+ const decimal_js_1 = __importDefault(require("decimal.js"));
18
+ const claiming_1 = require("../types/claiming");
19
+ const contracts_1 = require("../contracts");
20
+ const utils_1 = require("../services/utils");
21
+ const MORPHO_ALLOWED_CONTRACTS = [
22
+ '0x330eefa8a787552DC5cAd3C3cA644844B1E61Ddb',
23
+ '0x678dDC1d07eaa166521325394cDEb1E4c086DF43',
24
+ '0x2efd4625d0c149ebadf118ec5446c6de24d916a4',
25
+ ];
26
+ const MORPHO_ALLOWED_TOKENS = [
27
+ 'MORPHO',
28
+ 'MORPHO Legacy',
29
+ ];
30
+ const getMorphoUnderlyingSymbol = (_symbol) => {
31
+ if (_symbol === 'MORPHO Legacy')
32
+ return 'MORPHO';
33
+ return (0, utils_1.wethToEth)(_symbol);
34
+ };
35
+ exports.getMorphoUnderlyingSymbol = getMorphoUnderlyingSymbol;
36
+ const getMorphoBlueRewardsInfo = (address) => __awaiter(void 0, void 0, void 0, function* () {
37
+ if (!address)
38
+ return { claimable: '0' };
39
+ const res = yield fetch(`https://rewards.morpho.org/v1/users/${address}/distributions`, { signal: AbortSignal.timeout(3000) });
40
+ if (!res.ok)
41
+ throw new Error(yield res.text());
42
+ return res.json();
43
+ });
44
+ exports.getMorphoBlueRewardsInfo = getMorphoBlueRewardsInfo;
45
+ const fetchMorphoBlueRewards = (provider, network, walletAddresses) => __awaiter(void 0, void 0, void 0, function* () {
46
+ var _a;
47
+ // Fetch all API data in parallel (these are external API calls, can't be batched with multicall)
48
+ const apiDataPromises = walletAddresses.map(address => (0, exports.getMorphoBlueRewardsInfo)(address));
49
+ const apiDataArray = yield Promise.all(apiDataPromises);
50
+ // Process API data to get claimable tokens for each wallet
51
+ const allClaimableTokens = [];
52
+ const contractCallsData = [];
53
+ for (let i = 0; i < walletAddresses.length; i++) {
54
+ const walletAddress = walletAddresses[i];
55
+ const data = apiDataArray[i];
56
+ const claimableTokens = ((_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.reduce((acc, reward) => {
57
+ var _a, _b, _c;
58
+ const token = (0, tokens_1.getAssetInfoByAddress)(reward.asset.address);
59
+ if (!MORPHO_ALLOWED_CONTRACTS.includes((_a = reward === null || reward === void 0 ? void 0 : reward.distributor) === null || _a === void 0 ? void 0 : _a.address) || !MORPHO_ALLOWED_TOKENS.includes(token.symbol)) {
60
+ return acc;
61
+ }
62
+ // Store contract call data for batching
63
+ contractCallsData.push({
64
+ walletAddress,
65
+ tokenAddress: reward.asset.address,
66
+ distributor: (_b = reward === null || reward === void 0 ? void 0 : reward.distributor) === null || _b === void 0 ? void 0 : _b.address,
67
+ });
68
+ return [
69
+ ...acc,
70
+ {
71
+ symbol: token.symbol,
72
+ underlyingSymbol: (0, exports.getMorphoUnderlyingSymbol)(token.symbol),
73
+ tokenAddress: reward.asset.address,
74
+ amount: (0, tokens_1.assetAmountInEth)(reward.claimable, token.symbol),
75
+ walletAddress,
76
+ label: token.symbol,
77
+ claimType: claiming_1.ClaimType.MORPHO,
78
+ additionalClaimFields: {
79
+ originalAmount: reward.claimable,
80
+ distributor: (_c = reward === null || reward === void 0 ? void 0 : reward.distributor) === null || _c === void 0 ? void 0 : _c.address,
81
+ merkleProofs: reward === null || reward === void 0 ? void 0 : reward.proof,
82
+ isLegacy: token.symbol === 'MORPHO Legacy',
83
+ txData: reward === null || reward === void 0 ? void 0 : reward.tx_data,
84
+ },
85
+ }
86
+ ];
87
+ }, [])) || [];
88
+ allClaimableTokens.push({ walletAddress, tokens: claimableTokens });
89
+ }
90
+ // Batch all contract calls using multicall
91
+ const contractPromises = contractCallsData.map(({ walletAddress, tokenAddress, distributor }) => {
92
+ const distributorContract = (0, contracts_1.createViemContractFromConfigFunc)('MorphoDistributor', distributor)(provider, network);
93
+ return distributorContract.read.claimed([walletAddress, tokenAddress]);
94
+ });
95
+ const contractResults = yield Promise.all(contractPromises);
96
+ // Process results
97
+ const results = {};
98
+ let contractCallIndex = 0;
99
+ for (const { walletAddress, tokens } of allClaimableTokens) {
100
+ const updatedTokens = [];
101
+ for (let i = 0; i < tokens.length; i++) {
102
+ const claimableToken = tokens[i];
103
+ const claimed = (0, tokens_1.assetAmountInEth)(contractResults[contractCallIndex].toString(), claimableToken.underlyingSymbol);
104
+ contractCallIndex++;
105
+ const updatedToken = Object.assign({}, claimableToken);
106
+ updatedToken.amount = new decimal_js_1.default(claimableToken.amount).sub(claimed).toString();
107
+ updatedTokens.push(updatedToken);
108
+ }
109
+ results[walletAddress.toLowerCase()] = updatedTokens.filter((claimableToken) => new decimal_js_1.default(claimableToken.amount).gt(0));
110
+ }
111
+ return results;
112
+ });
113
+ exports.fetchMorphoBlueRewards = fetchMorphoBlueRewards;
@@ -0,0 +1,6 @@
1
+ import { Client } from 'viem';
2
+ import { EthAddress, NetworkNumber } from '../types/common';
3
+ import { SparkRewardsClaimableToken } from '../types/claiming';
4
+ export declare const fetchSpkAirdropRewards: (walletAddress: EthAddress) => Promise<any>;
5
+ export declare const fetchSparkAirdropRewards: (provider: Client, network: NetworkNumber, walletAddresses: EthAddress[]) => Promise<Record<string, any[]>>;
6
+ export declare const fetchSparkRewards: (provider: Client, network: NetworkNumber, walletAddress: EthAddress, marketAddress: EthAddress) => Promise<SparkRewardsClaimableToken[]>;
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.fetchSparkRewards = exports.fetchSparkAirdropRewards = exports.fetchSpkAirdropRewards = void 0;
16
+ const tokens_1 = require("@defisaver/tokens");
17
+ const decimal_js_1 = __importDefault(require("decimal.js"));
18
+ const contracts_1 = require("../contracts");
19
+ const claiming_1 = require("../types/claiming");
20
+ const utils_1 = require("../services/utils");
21
+ const IGNITION_REWARDS = '0xCBA0C0a2a0B6Bb11233ec4EA85C5bFfea33e724d';
22
+ const PFL3_REWARDS = '0x7ac96180C4d6b2A328D3a19ac059D0E7Fc3C6d41';
23
+ const fetchSpkAirdropRewards = (walletAddress) => __awaiter(void 0, void 0, void 0, function* () {
24
+ try {
25
+ const res = yield fetch(`https://fe.defisaver.com/api/spark/get-spk-airdrop-rewards/${walletAddress}`, { signal: AbortSignal.timeout(3000) });
26
+ if (!res.ok)
27
+ throw new Error(yield res.text());
28
+ return yield res.json();
29
+ }
30
+ catch (err) {
31
+ console.error('External API Error: Error fetching SPK airdrop rewards:', err);
32
+ return [];
33
+ }
34
+ });
35
+ exports.fetchSpkAirdropRewards = fetchSpkAirdropRewards;
36
+ const getCumulativeClaimedSpkAirdrop = (provider, network, data) => __awaiter(void 0, void 0, void 0, function* () {
37
+ const contractIgnition = (0, contracts_1.createViemContractFromConfigFunc)('SparkAirdrop', IGNITION_REWARDS)(provider, network);
38
+ const contractPFL = (0, contracts_1.createViemContractFromConfigFunc)('SparkAirdrop', PFL3_REWARDS)(provider, network);
39
+ const cumulativeAmounts = yield Promise.all(data.map((airdrop) => {
40
+ const { user, tokenAddress, epoch, type, } = airdrop;
41
+ const contract = type === claiming_1.SparkAirdropType.SPARK_IGNITION ? contractIgnition : contractPFL;
42
+ return contract.read.cumulativeClaimed([user, tokenAddress, BigInt(epoch)]);
43
+ }));
44
+ return cumulativeAmounts.map((amount, i) => (0, tokens_1.assetAmountInEth)(amount.toString(), (0, tokens_1.getAssetInfoByAddress)(data[i].tokenAddress).symbol).toString());
45
+ });
46
+ const fetchSparkAirdropRewards = (provider, network, walletAddresses) => __awaiter(void 0, void 0, void 0, function* () {
47
+ // Fetch all API data in parallel (these are external API calls, can't be batched with multicall)
48
+ const apiDataPromises = walletAddresses.map(address => (0, exports.fetchSpkAirdropRewards)(address));
49
+ const apiDataArray = yield Promise.all(apiDataPromises);
50
+ // Process API data and collect contract call data
51
+ const allClaimData = [];
52
+ const contractCallsData = [];
53
+ for (let i = 0; i < walletAddresses.length; i++) {
54
+ const walletAddress = walletAddresses[i];
55
+ const data = apiDataArray[i];
56
+ const falseResponse = !data;
57
+ const emptyResponse = data && data.length === 0;
58
+ const singleResponseWithoutAmount = data && data.length === 1 && !+data[0].amount;
59
+ if (falseResponse || emptyResponse || singleResponseWithoutAmount) {
60
+ allClaimData.push({ walletAddress, data: [] });
61
+ continue;
62
+ }
63
+ // Filter out IGNITION_REWARDS since they are no longer active
64
+ const filteredData = data.filter((rewardInfo) => rewardInfo.type !== claiming_1.SparkAirdropType.SPARK_IGNITION);
65
+ allClaimData.push({ walletAddress, data: filteredData });
66
+ // Collect contract call data
67
+ filteredData.forEach((airdropInfo) => {
68
+ contractCallsData.push({
69
+ user: airdropInfo.wallet_address,
70
+ tokenAddress: airdropInfo.token_address,
71
+ epoch: airdropInfo.epoch,
72
+ type: airdropInfo.type,
73
+ });
74
+ });
75
+ }
76
+ // Batch all contract calls
77
+ const cumulativeClaimedAmounts = yield getCumulativeClaimedSpkAirdrop(provider, network, contractCallsData);
78
+ // Process results
79
+ const results = {};
80
+ let contractCallIndex = 0;
81
+ for (const { walletAddress, data } of allClaimData) {
82
+ if (data.length === 0) {
83
+ results[walletAddress.toLowerCase()] = [];
84
+ continue;
85
+ }
86
+ const processedRewards = [];
87
+ for (let i = 0; i < data.length; i++) {
88
+ const rewardInfo = data[i];
89
+ const assetInfo = (0, tokens_1.getAssetInfoByAddress)(rewardInfo.token_address);
90
+ const claimedAmount = cumulativeClaimedAmounts[contractCallIndex];
91
+ contractCallIndex++;
92
+ const amount = new decimal_js_1.default(rewardInfo.amount_normalized).minus(claimedAmount).toString();
93
+ if (new decimal_js_1.default(amount).gt('0')) {
94
+ processedRewards.push({
95
+ symbol: assetInfo.symbol,
96
+ underlyingSymbol: assetInfo.symbol,
97
+ amount,
98
+ claimType: claiming_1.ClaimType.SPARK_AIRDROP,
99
+ tokenAddress: rewardInfo.token_address,
100
+ walletAddress: rewardInfo.wallet_address,
101
+ label: 'Spark Airdrop',
102
+ additionalClaimFields: {
103
+ merkleRoot: rewardInfo.root_hash,
104
+ merkleProofs: rewardInfo.proof,
105
+ epoch: rewardInfo.epoch,
106
+ rewardType: rewardInfo.type,
107
+ allRewardsAmount: rewardInfo.amount_normalized,
108
+ },
109
+ });
110
+ }
111
+ }
112
+ results[walletAddress.toLowerCase()] = processedRewards;
113
+ }
114
+ return results;
115
+ });
116
+ exports.fetchSparkAirdropRewards = fetchSparkAirdropRewards;
117
+ const fetchSparkRewards = (provider, network, walletAddress, marketAddress) => __awaiter(void 0, void 0, void 0, function* () {
118
+ const contract = (0, contracts_1.SparkIncentiveDataProviderContractViem)(provider, network);
119
+ const tokensData = yield contract.read.getUserReservesIncentivesData([marketAddress, walletAddress]);
120
+ const allTokensDataArrays = tokensData.reduce((acc, val) => {
121
+ acc.push(val.aTokenIncentivesUserData.userRewardsInformation);
122
+ acc.push(val.vTokenIncentivesUserData.userRewardsInformation);
123
+ return acc;
124
+ }, []);
125
+ const allATokens = tokensData.reduce((acc, val) => {
126
+ acc.push(val.aTokenIncentivesUserData.tokenAddress);
127
+ acc.push(val.vTokenIncentivesUserData.tokenAddress);
128
+ return acc;
129
+ }, []);
130
+ const rewardsPerAAsset = yield Promise.all(allATokens.map((token) => {
131
+ const sparkRewardsContract = (0, contracts_1.SparkRewardsControllerViem)(provider, network);
132
+ return sparkRewardsContract.read.getAllUserRewards([[token], walletAddress]);
133
+ }));
134
+ // match amounts to token symbol, parse decimal amounts
135
+ const rewardsPerAAssetWithInfo = rewardsPerAAsset.map((rewardForAAsset, aaIndex) => {
136
+ const rewardsList = rewardForAAsset[0];
137
+ const amounts = rewardForAAsset[1];
138
+ const rewardsDataArraysForAAsset = allTokensDataArrays[aaIndex];
139
+ const aTokenAddress = allATokens[aaIndex];
140
+ return rewardsList.map((rewardTokenAddress, rewardIndex) => {
141
+ var _a, _b;
142
+ const dataArrIndex = rewardsDataArraysForAAsset.findIndex((arr) => (0, utils_1.compareAddresses)(arr.rewardTokenAddress, rewardTokenAddress));
143
+ const amountWei = amounts[rewardIndex];
144
+ const amount = (0, utils_1.getEthAmountForDecimals)(amountWei.toString(), (_a = rewardsDataArraysForAAsset[dataArrIndex]) === null || _a === void 0 ? void 0 : _a.rewardTokenDecimals);
145
+ const symbol = ((_b = rewardsDataArraysForAAsset[dataArrIndex]) === null || _b === void 0 ? void 0 : _b.rewardTokenSymbol) || '';
146
+ const underlyingAsset = symbol;
147
+ return ({
148
+ amount,
149
+ symbol,
150
+ underlyingAsset,
151
+ rewardTokenAddress,
152
+ aTokenAddress,
153
+ });
154
+ });
155
+ });
156
+ // sum all unclaimed rewards of all markets per each token
157
+ // (e.g. how much awstETH is claimable in total from both aUSDC and awstETH markets)
158
+ const totalUnclaimedPerRewardToken = {};
159
+ rewardsPerAAssetWithInfo
160
+ .flat()
161
+ .forEach(({ amount, symbol, underlyingAsset, rewardTokenAddress, aTokenAddress, }) => {
162
+ if (+amount > 0) {
163
+ if (!totalUnclaimedPerRewardToken[symbol]) {
164
+ totalUnclaimedPerRewardToken[symbol] = {
165
+ amount, symbol, underlyingAsset, rewardTokenAddress, aTokenAddresses: [aTokenAddress],
166
+ };
167
+ }
168
+ else {
169
+ totalUnclaimedPerRewardToken[symbol].amount =
170
+ new decimal_js_1.default(totalUnclaimedPerRewardToken[symbol].amount).add(amount).toString();
171
+ totalUnclaimedPerRewardToken[symbol].aTokenAddresses.push(aTokenAddress);
172
+ }
173
+ }
174
+ }, []);
175
+ return Object.values(totalUnclaimedPerRewardToken).map((reward) => ({
176
+ symbol: reward.symbol,
177
+ amount: reward.amount,
178
+ claimType: claiming_1.ClaimType.SPARK_REWARDS,
179
+ tokenAddress: reward.rewardTokenAddress,
180
+ underlyingSymbol: reward.underlyingAsset,
181
+ walletAddress,
182
+ label: 'Spark',
183
+ additionalClaimFields: {
184
+ sparkAssetAddresses: reward.aTokenAddresses,
185
+ },
186
+ }));
187
+ });
188
+ exports.fetchSparkRewards = fetchSparkRewards;