@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,163 @@
1
+ import { Client } from 'viem';
2
+ import Dec from 'decimal.js';
3
+ import { EthAddress, NetworkNumber } from '../types/common';
4
+ import { ClaimableToken, ClaimType } from '../types/claiming';
5
+ import {
6
+ AaveIncentiveDataProviderV3ContractViem,
7
+ AaveRewardsControllerViem,
8
+ } from '../contracts';
9
+ import { compareAddresses, getEthAmountForDecimals, wethToEth } from '../services/utils';
10
+
11
+ type AaveReward = {
12
+ amount: string;
13
+ symbol: string;
14
+ underlyingAsset: string;
15
+ rewardTokenAddress: string;
16
+ aTokenAddresses: string[];
17
+ };
18
+
19
+ /**
20
+ * won't cover all cases
21
+ */
22
+ export const getAaveUnderlyingSymbol = (_symbol = '') => {
23
+ let symbol = _symbol
24
+ .replace(/^aEthLido/, '')
25
+ .replace(/^aEthEtherFi/, '')
26
+ .replace(/^aEth/, '')
27
+ .replace(/^aArb/, '')
28
+ .replace(/^aOpt/, '')
29
+ .replace(/^aBas/, '');
30
+ if (symbol.startsWith('a')) symbol = symbol.slice(1);
31
+ return wethToEth(symbol);
32
+ };
33
+
34
+ const mapAaveRewardsToClaimableTokens = (aaveRewards: AaveReward[], marketAddress: EthAddress, walletAddress: EthAddress) => aaveRewards.map(reward => ({
35
+ symbol: reward.symbol,
36
+ amount: reward.amount,
37
+ claimType: ClaimType.AAVE_REWARDS as const,
38
+ tokenAddress: reward.rewardTokenAddress as EthAddress,
39
+ underlyingSymbol: reward.underlyingAsset,
40
+ walletAddress,
41
+ label: 'AAVE Rewards',
42
+ additionalClaimFields: {
43
+ marketAddress,
44
+ aTokenAddresses: reward.aTokenAddresses,
45
+ isAaveToken: reward.symbol.startsWith('a'),
46
+ },
47
+ }));
48
+
49
+ export async function getUnclaimedRewardsForAllMarkets(
50
+ provider: Client,
51
+ network: NetworkNumber,
52
+ walletAddress: EthAddress,
53
+ marketAddress: EthAddress,
54
+ ): Promise<ClaimableToken[]> {
55
+ const contract = AaveIncentiveDataProviderV3ContractViem(provider, network);
56
+ const tokensData = await contract.read.getUserReservesIncentivesData([marketAddress, walletAddress]);
57
+ const allTokensDataArrays = tokensData.reduce((acc: any[], val) => {
58
+ acc.push(val.aTokenIncentivesUserData.userRewardsInformation);
59
+ acc.push(val.vTokenIncentivesUserData.userRewardsInformation);
60
+ return acc;
61
+ }, []);
62
+ const allATokens = tokensData.reduce((acc, val) => {
63
+ acc.push(val.aTokenIncentivesUserData.tokenAddress);
64
+ acc.push(val.vTokenIncentivesUserData.tokenAddress);
65
+ return acc;
66
+ }, [] as string[]);
67
+ // array of rewards for each market (aToken/vToken)
68
+ // reward can be any token like wstETH, but also aToken like aWETH
69
+ const aaveRewardsController = AaveRewardsControllerViem(provider, network);
70
+ const rewardsPerAAsset = await Promise.all(allATokens.map(
71
+ (token: string) => aaveRewardsController.read.getAllUserRewards([[token as EthAddress], walletAddress])));
72
+
73
+ // match amounts to token symbol, parse decimal amounts
74
+ const rewardsPerAAssetWithInfo = rewardsPerAAsset.map((rewardForAAsset, aaIndex) => {
75
+ const rewardsList = rewardForAAsset[0];
76
+ const amounts = rewardForAAsset[1];
77
+
78
+ const rewardsDataArraysForAAsset = allTokensDataArrays[aaIndex];
79
+ const aTokenAddress = allATokens[aaIndex];
80
+ return rewardsList.map((rewardTokenAddress, rewardIndex) => {
81
+ const dataArrIndex = rewardsDataArraysForAAsset.findIndex((arr: { rewardTokenAddress: string | undefined; }) => compareAddresses(arr.rewardTokenAddress, rewardTokenAddress));
82
+ const amountWei = amounts[rewardIndex];
83
+ const amount = getEthAmountForDecimals(amountWei.toString(), rewardsDataArraysForAAsset[dataArrIndex]?.rewardTokenDecimals);
84
+ const symbol = rewardsDataArraysForAAsset[dataArrIndex]?.rewardTokenSymbol || '';
85
+ const underlyingAsset = getAaveUnderlyingSymbol(symbol);
86
+ return ({
87
+ amount,
88
+ symbol,
89
+ underlyingAsset,
90
+ rewardTokenAddress,
91
+ aTokenAddress,
92
+ });
93
+ });
94
+ });
95
+
96
+ // sum all unclaimed rewards of all markets per each token
97
+ // (e.g. how much awstETH is claimable in total from both aUSDC and awstETH markets)
98
+ const totalUnclaimedPerRewardToken: Record<string, any> = {};
99
+ rewardsPerAAssetWithInfo
100
+ .flat()
101
+ .forEach(({
102
+ amount, symbol, underlyingAsset, rewardTokenAddress, aTokenAddress,
103
+ }) => {
104
+ if (+amount > 0) {
105
+ if (!totalUnclaimedPerRewardToken[symbol]) {
106
+ totalUnclaimedPerRewardToken[symbol] = {
107
+ amount, symbol, underlyingAsset, rewardTokenAddress, aTokenAddresses: [aTokenAddress],
108
+ };
109
+ } else {
110
+ totalUnclaimedPerRewardToken[symbol].amount =
111
+ new Dec(totalUnclaimedPerRewardToken[symbol].amount).add(amount).toString();
112
+ totalUnclaimedPerRewardToken[symbol].aTokenAddresses.push(aTokenAddress);
113
+ }
114
+ }
115
+ }, []);
116
+
117
+ return mapAaveRewardsToClaimableTokens(Object.values(totalUnclaimedPerRewardToken), marketAddress, walletAddress);
118
+ }
119
+
120
+ export async function getMeritUnclaimedRewards(account: EthAddress, network: NetworkNumber, acceptMorpho: boolean = true): Promise<ClaimableToken[]> {
121
+ const res = await fetch(`https://api.merkl.xyz/v4/users/${account}/rewards?chainId=${network}`,
122
+ { signal: AbortSignal.timeout(3000) });
123
+ const data = await res.json();
124
+
125
+ const claimableTokens: ClaimableToken[] = [];
126
+
127
+ data.forEach((item: { rewards: any[]; }) => {
128
+ item.rewards.forEach(reward => {
129
+ const {
130
+ token,
131
+ amount,
132
+ claimed,
133
+ proofs,
134
+ } = reward;
135
+
136
+ const isTokenMorpho = token.symbol === 'MORPHO';
137
+ if (!token || !token.symbol || amount === '0' || (isTokenMorpho && !acceptMorpho)) return;
138
+
139
+ const unclaimedAmount = new Dec(amount).minus(claimed || 0).toString();
140
+ if (unclaimedAmount === '0') return;
141
+
142
+ const unclaimed = getEthAmountForDecimals(unclaimedAmount, token.decimals);
143
+
144
+ claimableTokens.push({
145
+ claimType: ClaimType.AAVE_MERIT_REWARDS,
146
+ amount: unclaimed,
147
+ symbol: token.symbol,
148
+ tokenAddress: token.address,
149
+ walletAddress: account,
150
+ label: 'AAVE Merit Rewards',
151
+ underlyingSymbol: getAaveUnderlyingSymbol(token.symbol),
152
+ additionalClaimFields: {
153
+ accumulated: amount,
154
+ proof: proofs,
155
+ decimals: token.decimals,
156
+ unclaimed: unclaimedAmount,
157
+ },
158
+ });
159
+ });
160
+ });
161
+
162
+ return claimableTokens;
163
+ }
@@ -0,0 +1,23 @@
1
+ import { Client } from 'viem';
2
+ import { assetAmountInEth, getAssetInfoByAddress } from '@defisaver/tokens';
3
+ import { EthAddress, NetworkNumber } from '../types/common';
4
+ import { CompV3ViewContractViem } from '../contracts';
5
+ import { ClaimType } from '../types/claiming';
6
+
7
+ export const getCompoundV3Rewards = async (provider: Client, network: NetworkNumber, user: EthAddress, market: any) => {
8
+ const compV3View = CompV3ViewContractViem(provider, network);
9
+ const rewards = await compV3View.read.getRewardsOwed([market, user]);
10
+ if (!rewards || rewards.owed.toString() === '0' || getAssetInfoByAddress(rewards.token, network).symbol !== 'COMP') return [];
11
+ return [{
12
+ symbol: 'COMP',
13
+ underlyingSymbol: 'COMP',
14
+ tokenAddress: rewards.token,
15
+ amount: assetAmountInEth(rewards.owed.toString() || 0, 'COMP'),
16
+ walletAddress: user,
17
+ label: 'Compound V3',
18
+ claimType: ClaimType.COMPOUND_V3_COMP,
19
+ additionalClaimFields: {
20
+ marketAddress: market,
21
+ },
22
+ }];
23
+ };
@@ -0,0 +1,13 @@
1
+ import * as aaveV3Claim from './aaveV3';
2
+ import * as compV3Claim from './compV3';
3
+ import * as kingV3Claim from './king';
4
+ import * as morphoBlueClaim from './morphoBlue';
5
+ import * as sparkClaim from './spark';
6
+
7
+ export {
8
+ aaveV3Claim,
9
+ compV3Claim,
10
+ kingV3Claim,
11
+ morphoBlueClaim,
12
+ sparkClaim,
13
+ };
@@ -0,0 +1,66 @@
1
+ import Dec from 'decimal.js';
2
+ import { assetAmountInEth } from '@defisaver/tokens';
3
+ import { Client } from 'viem';
4
+ import { UUPSViem } from '../contracts';
5
+ import { EthAddress, HexString, NetworkNumber } from '../types/common';
6
+ import { ClaimType } from '../types/claiming';
7
+
8
+ export const fetchKingRewards = async (walletAddress: EthAddress) => {
9
+ try {
10
+ const res = await fetch(`https://fe.defisaver.com/api/etherfi/get-king-rewards/${walletAddress}`,
11
+ { signal: AbortSignal.timeout(5000) });
12
+
13
+ if (!res.ok) throw new Error(await res.text());
14
+
15
+ return await res.json();
16
+ } catch (err) {
17
+ console.error('External API Error: Error fetching KING rewards:', err);
18
+ return { Amount: '0', Root: '', Proofs: [] };
19
+ }
20
+ };
21
+
22
+ export const getKingRewards = async (provider: Client, network: NetworkNumber, walletAddresses: EthAddress[]) => {
23
+ // Fetch all API data in parallel (these are external API calls, can't be batched with multicall)
24
+ const apiDataPromises = walletAddresses.map(address => fetchKingRewards(address));
25
+ const apiDataArray = await Promise.all(apiDataPromises);
26
+
27
+ // Batch all contract calls using multicall
28
+ const contract = UUPSViem(provider, network);
29
+ const cumulativePromises = walletAddresses.map(address => contract.read.cumulativeClaimed([address]),
30
+ );
31
+ const cumulativeResults = await Promise.all(cumulativePromises);
32
+
33
+ // Process results
34
+ const results: Record<string, any[]> = {};
35
+
36
+ for (let i = 0; i < walletAddresses.length; i++) {
37
+ const walletAddress = walletAddresses[i];
38
+ const data = apiDataArray[i];
39
+ const cumulative = cumulativeResults[i];
40
+
41
+ const allRewardsAmount = assetAmountInEth(data.Amount, 'KING');
42
+ const claimedAmount = assetAmountInEth(cumulative.toString(), 'KING');
43
+ const amountToClaim = new Dec(allRewardsAmount).sub(claimedAmount);
44
+
45
+ if (amountToClaim.lessThanOrEqualTo('0')) {
46
+ results[walletAddress.toLowerCase() as EthAddress] = [];
47
+ } else {
48
+ results[walletAddress.toLowerCase() as EthAddress] = [{
49
+ symbol: 'KING',
50
+ underlyingSymbol: 'KING',
51
+ tokenAddress: '0x8F08B70456eb22f6109F57b8fafE862ED28E6040',
52
+ amount: amountToClaim.toString(),
53
+ walletAddress,
54
+ label: 'weETH',
55
+ claimType: ClaimType.KING_REWARDS,
56
+ additionalClaimFields: {
57
+ allRewardsAmount,
58
+ merkleRoot: data.Root,
59
+ merkleProofs: data.Proofs,
60
+ },
61
+ }];
62
+ }
63
+ }
64
+
65
+ return results;
66
+ };
@@ -0,0 +1,119 @@
1
+ import { assetAmountInEth, getAssetInfoByAddress } from '@defisaver/tokens';
2
+ import { Client } from 'viem';
3
+ import Dec from 'decimal.js';
4
+ import { ClaimableToken, ClaimType, MorphoClaimableToken } from '../types/claiming';
5
+ import { EthAddress, NetworkNumber } from '../types/common';
6
+ import { createViemContractFromConfigFunc } from '../contracts';
7
+ import { wethToEth } from '../services/utils';
8
+
9
+ const MORPHO_ALLOWED_CONTRACTS = [
10
+ '0x330eefa8a787552DC5cAd3C3cA644844B1E61Ddb',
11
+ '0x678dDC1d07eaa166521325394cDEb1E4c086DF43',
12
+ '0x2efd4625d0c149ebadf118ec5446c6de24d916a4',
13
+ ];
14
+
15
+ const MORPHO_ALLOWED_TOKENS = [
16
+ 'MORPHO',
17
+ 'MORPHO Legacy',
18
+ ];
19
+
20
+ export const getMorphoUnderlyingSymbol = (_symbol: string) => {
21
+ if (_symbol === 'MORPHO Legacy') return 'MORPHO';
22
+ return wethToEth(_symbol);
23
+ };
24
+
25
+
26
+ export const getMorphoBlueRewardsInfo = async (address: EthAddress) => {
27
+ if (!address) return { claimable: '0' };
28
+ const res = await fetch(`https://rewards.morpho.org/v1/users/${address}/distributions`,
29
+ { signal: AbortSignal.timeout(3000) });
30
+
31
+ if (!res.ok) throw new Error(await res.text());
32
+
33
+ return res.json();
34
+ };
35
+
36
+ export const fetchMorphoBlueRewards = async (
37
+ provider: Client,
38
+ network: NetworkNumber,
39
+ walletAddresses: EthAddress[],
40
+ ): Promise<Record<string, ClaimableToken[]>> => {
41
+ // Fetch all API data in parallel (these are external API calls, can't be batched with multicall)
42
+ const apiDataPromises = walletAddresses.map(address => getMorphoBlueRewardsInfo(address));
43
+ const apiDataArray = await Promise.all(apiDataPromises);
44
+
45
+ // Process API data to get claimable tokens for each wallet
46
+ const allClaimableTokens: Array<{ walletAddress: EthAddress; tokens: ClaimableToken[] }> = [];
47
+ const contractCallsData: Array<{ walletAddress: EthAddress; tokenAddress: EthAddress; distributor: EthAddress }> = [];
48
+
49
+ for (let i = 0; i < walletAddresses.length; i++) {
50
+ const walletAddress = walletAddresses[i];
51
+ const data = apiDataArray[i];
52
+
53
+ const claimableTokens = data?.data?.reduce((acc: ClaimableToken[], reward: any) => {
54
+ const token = getAssetInfoByAddress(reward.asset.address);
55
+ if (!MORPHO_ALLOWED_CONTRACTS.includes(reward?.distributor?.address) || !MORPHO_ALLOWED_TOKENS.includes(token.symbol)) {
56
+ return acc;
57
+ }
58
+
59
+ // Store contract call data for batching
60
+ contractCallsData.push({
61
+ walletAddress,
62
+ tokenAddress: reward.asset.address,
63
+ distributor: reward?.distributor?.address,
64
+ });
65
+
66
+ return [
67
+ ...acc,
68
+ {
69
+ symbol: token.symbol,
70
+ underlyingSymbol: getMorphoUnderlyingSymbol(token.symbol),
71
+ tokenAddress: reward.asset.address,
72
+ amount: assetAmountInEth(reward.claimable, token.symbol),
73
+ walletAddress,
74
+ label: token.symbol,
75
+ claimType: ClaimType.MORPHO,
76
+ additionalClaimFields: {
77
+ originalAmount: reward.claimable,
78
+ distributor: reward?.distributor?.address,
79
+ merkleProofs: reward?.proof,
80
+ isLegacy: token.symbol === 'MORPHO Legacy',
81
+ txData: reward?.tx_data,
82
+ },
83
+ }];
84
+ }, []) || [];
85
+
86
+ allClaimableTokens.push({ walletAddress, tokens: claimableTokens });
87
+ }
88
+
89
+ // Batch all contract calls using multicall
90
+ const contractPromises = contractCallsData.map(({ walletAddress, tokenAddress, distributor }) => {
91
+ const distributorContract = createViemContractFromConfigFunc('MorphoDistributor', distributor)(provider, network);
92
+ return distributorContract.read.claimed([walletAddress, tokenAddress]);
93
+ });
94
+ const contractResults = await Promise.all(contractPromises);
95
+
96
+ // Process results
97
+ const results: Record<string, ClaimableToken[]> = {};
98
+ let contractCallIndex = 0;
99
+
100
+ for (const { walletAddress, tokens } of allClaimableTokens) {
101
+ const updatedTokens: ClaimableToken[] = [];
102
+
103
+ for (let i = 0; i < tokens.length; i++) {
104
+ const claimableToken = tokens[i];
105
+ const claimed = assetAmountInEth(contractResults[contractCallIndex].toString(), claimableToken.underlyingSymbol);
106
+ contractCallIndex++;
107
+
108
+ const updatedToken = { ...claimableToken };
109
+ updatedToken.amount = new Dec(claimableToken.amount).sub(claimed).toString();
110
+ updatedTokens.push(updatedToken);
111
+ }
112
+
113
+ results[walletAddress.toLowerCase() as EthAddress] = updatedTokens.filter(
114
+ (claimableToken) => new Dec(claimableToken.amount).gt(0),
115
+ );
116
+ }
117
+
118
+ return results;
119
+ };
@@ -0,0 +1,226 @@
1
+ import { assetAmountInEth, getAssetInfoByAddress } from '@defisaver/tokens';
2
+ import Dec from 'decimal.js';
3
+ import { Client } from 'viem';
4
+ import {
5
+ createViemContractFromConfigFunc,
6
+ SparkIncentiveDataProviderContractViem,
7
+ SparkRewardsControllerViem,
8
+ } from '../contracts';
9
+ import { EthAddress, NetworkNumber } from '../types/common';
10
+ import { ClaimType, SparkAirdropType, SparkRewardsClaimableToken } from '../types/claiming';
11
+ import { compareAddresses, getEthAmountForDecimals } from '../services/utils';
12
+
13
+ const IGNITION_REWARDS = '0xCBA0C0a2a0B6Bb11233ec4EA85C5bFfea33e724d';
14
+ const PFL3_REWARDS = '0x7ac96180C4d6b2A328D3a19ac059D0E7Fc3C6d41';
15
+
16
+ export const fetchSpkAirdropRewards = async (walletAddress: EthAddress) => {
17
+ try {
18
+ const res = await fetch(`https://fe.defisaver.com/api/spark/get-spk-airdrop-rewards/${walletAddress}`,
19
+ { signal: AbortSignal.timeout(3000) });
20
+
21
+ if (!res.ok) throw new Error(await res.text());
22
+
23
+ return await res.json();
24
+ } catch (err) {
25
+ console.error('External API Error: Error fetching SPK airdrop rewards:', err);
26
+ return [];
27
+ }
28
+ };
29
+
30
+ type CumulativeClaimedSpkAirdropFuncProp = {
31
+ user: string, tokenAddress: string, epoch: number, type: SparkAirdropType,
32
+ };
33
+
34
+ const getCumulativeClaimedSpkAirdrop = async (provider: Client, network: NetworkNumber, data: CumulativeClaimedSpkAirdropFuncProp[]) => {
35
+ const contractIgnition = createViemContractFromConfigFunc('SparkAirdrop', IGNITION_REWARDS)(provider, network);
36
+ const contractPFL = createViemContractFromConfigFunc('SparkAirdrop', PFL3_REWARDS)(provider, network);
37
+
38
+ const cumulativeAmounts = await Promise.all(data.map((airdrop) => {
39
+ const {
40
+ user, tokenAddress, epoch, type,
41
+ } = airdrop;
42
+ const contract = type === SparkAirdropType.SPARK_IGNITION ? contractIgnition : contractPFL;
43
+ return contract.read.cumulativeClaimed([user as EthAddress, tokenAddress as EthAddress, BigInt(epoch)]);
44
+ }));
45
+
46
+ return cumulativeAmounts.map((amount: bigint, i: number) => assetAmountInEth(amount.toString(), getAssetInfoByAddress(data[i].tokenAddress).symbol).toString());
47
+ };
48
+
49
+ export const fetchSparkAirdropRewards = async (
50
+ provider: Client,
51
+ network: NetworkNumber,
52
+ walletAddresses: EthAddress[],
53
+ ) => {
54
+ // Fetch all API data in parallel (these are external API calls, can't be batched with multicall)
55
+ const apiDataPromises = walletAddresses.map(address => fetchSpkAirdropRewards(address));
56
+ const apiDataArray = await Promise.all(apiDataPromises);
57
+
58
+ // Process API data and collect contract call data
59
+ const allClaimData: Array<{ walletAddress: EthAddress; data: any[] }> = [];
60
+ const contractCallsData: CumulativeClaimedSpkAirdropFuncProp[] = [];
61
+
62
+ for (let i = 0; i < walletAddresses.length; i++) {
63
+ const walletAddress = walletAddresses[i];
64
+ const data = apiDataArray[i];
65
+
66
+ const falseResponse: boolean = !data;
67
+ const emptyResponse: boolean = data && data.length === 0;
68
+ const singleResponseWithoutAmount: boolean = data && data.length === 1 && !+data[0].amount;
69
+
70
+ if (falseResponse || emptyResponse || singleResponseWithoutAmount) {
71
+ allClaimData.push({ walletAddress, data: [] });
72
+ continue;
73
+ }
74
+
75
+ // Filter out IGNITION_REWARDS since they are no longer active
76
+ const filteredData = data.filter((rewardInfo: { type: SparkAirdropType; }) => rewardInfo.type !== SparkAirdropType.SPARK_IGNITION);
77
+
78
+ allClaimData.push({ walletAddress, data: filteredData });
79
+
80
+ // Collect contract call data
81
+ filteredData.forEach((airdropInfo: { wallet_address: any; token_address: any; epoch: any; type: any; }) => {
82
+ contractCallsData.push({
83
+ user: airdropInfo.wallet_address,
84
+ tokenAddress: airdropInfo.token_address,
85
+ epoch: airdropInfo.epoch,
86
+ type: airdropInfo.type,
87
+ });
88
+ });
89
+ }
90
+
91
+ // Batch all contract calls
92
+ const cumulativeClaimedAmounts = await getCumulativeClaimedSpkAirdrop(provider, network, contractCallsData);
93
+
94
+ // Process results
95
+ const results: Record<string, any[]> = {};
96
+ let contractCallIndex = 0;
97
+
98
+ for (const { walletAddress, data } of allClaimData) {
99
+ if (data.length === 0) {
100
+ results[walletAddress.toLowerCase() as EthAddress] = [];
101
+ continue;
102
+ }
103
+
104
+ const processedRewards = [];
105
+ for (let i = 0; i < data.length; i++) {
106
+ const rewardInfo = data[i];
107
+ const assetInfo = getAssetInfoByAddress(rewardInfo.token_address);
108
+ const claimedAmount = cumulativeClaimedAmounts[contractCallIndex];
109
+ contractCallIndex++;
110
+
111
+ const amount = new Dec(rewardInfo.amount_normalized).minus(claimedAmount).toString();
112
+
113
+ if (new Dec(amount).gt('0')) {
114
+ processedRewards.push({
115
+ symbol: assetInfo.symbol,
116
+ underlyingSymbol: assetInfo.symbol,
117
+ amount,
118
+ claimType: ClaimType.SPARK_AIRDROP,
119
+ tokenAddress: rewardInfo.token_address,
120
+ walletAddress: rewardInfo.wallet_address,
121
+ label: 'Spark Airdrop',
122
+ additionalClaimFields: {
123
+ merkleRoot: rewardInfo.root_hash,
124
+ merkleProofs: rewardInfo.proof,
125
+ epoch: rewardInfo.epoch,
126
+ rewardType: rewardInfo.type,
127
+ allRewardsAmount: rewardInfo.amount_normalized,
128
+ },
129
+ });
130
+ }
131
+ }
132
+
133
+ results[walletAddress.toLowerCase() as EthAddress] = processedRewards;
134
+ }
135
+
136
+ return results;
137
+ };
138
+
139
+
140
+ export const fetchSparkRewards = async (
141
+ provider: Client,
142
+ network: NetworkNumber,
143
+ walletAddress: EthAddress,
144
+ marketAddress: EthAddress,
145
+ ): Promise<SparkRewardsClaimableToken[]> => {
146
+ const contract = SparkIncentiveDataProviderContractViem(provider, network);
147
+ const tokensData = await contract.read.getUserReservesIncentivesData([marketAddress, walletAddress]);
148
+ const allTokensDataArrays = tokensData.reduce((acc: any[], val) => {
149
+ acc.push(val.aTokenIncentivesUserData.userRewardsInformation);
150
+ acc.push(val.vTokenIncentivesUserData.userRewardsInformation);
151
+ return acc;
152
+ }, []);
153
+ const allATokens = tokensData.reduce((acc, val) => {
154
+ acc.push(val.aTokenIncentivesUserData.tokenAddress);
155
+ acc.push(val.vTokenIncentivesUserData.tokenAddress);
156
+ return acc;
157
+ }, [] as EthAddress[]);
158
+
159
+ type RewardsPerAAsset = {
160
+ amount: string,
161
+ symbol: string,
162
+ underlyingAsset: string,
163
+ rewardTokenAddress: EthAddress,
164
+ aTokenAddress: string,
165
+ };
166
+ const rewardsPerAAsset = await Promise.all(allATokens.map((token: EthAddress) => {
167
+ const sparkRewardsContract = SparkRewardsControllerViem(provider, network);
168
+ return sparkRewardsContract.read.getAllUserRewards([[token], walletAddress]);
169
+ }));
170
+
171
+ // match amounts to token symbol, parse decimal amounts
172
+ const rewardsPerAAssetWithInfo = rewardsPerAAsset.map((rewardForAAsset, aaIndex) => {
173
+ const rewardsList = rewardForAAsset[0];
174
+ const amounts = rewardForAAsset[1];
175
+ const rewardsDataArraysForAAsset = allTokensDataArrays[aaIndex];
176
+ const aTokenAddress = allATokens[aaIndex];
177
+ return rewardsList.map((rewardTokenAddress: EthAddress, rewardIndex: number) => {
178
+ const dataArrIndex = rewardsDataArraysForAAsset.findIndex((arr: { rewardTokenAddress: string | undefined; }) => compareAddresses(arr.rewardTokenAddress, rewardTokenAddress));
179
+ const amountWei = amounts[rewardIndex];
180
+ const amount = getEthAmountForDecimals(amountWei.toString(), rewardsDataArraysForAAsset[dataArrIndex]?.rewardTokenDecimals);
181
+ const symbol = rewardsDataArraysForAAsset[dataArrIndex]?.rewardTokenSymbol || '';
182
+ const underlyingAsset = symbol;
183
+ return ({
184
+ amount,
185
+ symbol,
186
+ underlyingAsset,
187
+ rewardTokenAddress,
188
+ aTokenAddress,
189
+ });
190
+ }) as RewardsPerAAsset[];
191
+ });
192
+
193
+ // sum all unclaimed rewards of all markets per each token
194
+ // (e.g. how much awstETH is claimable in total from both aUSDC and awstETH markets)
195
+ const totalUnclaimedPerRewardToken: Record<string, any> = {};
196
+ rewardsPerAAssetWithInfo
197
+ .flat()
198
+ .forEach(({
199
+ amount, symbol, underlyingAsset, rewardTokenAddress, aTokenAddress,
200
+ }) => {
201
+ if (+amount > 0) {
202
+ if (!totalUnclaimedPerRewardToken[symbol]) {
203
+ totalUnclaimedPerRewardToken[symbol] = {
204
+ amount, symbol, underlyingAsset, rewardTokenAddress, aTokenAddresses: [aTokenAddress],
205
+ };
206
+ } else {
207
+ totalUnclaimedPerRewardToken[symbol].amount =
208
+ new Dec(totalUnclaimedPerRewardToken[symbol].amount).add(amount).toString();
209
+ totalUnclaimedPerRewardToken[symbol].aTokenAddresses.push(aTokenAddress);
210
+ }
211
+ }
212
+ }, []);
213
+
214
+ return Object.values(totalUnclaimedPerRewardToken).map((reward: any) => ({
215
+ symbol: reward.symbol,
216
+ amount: reward.amount,
217
+ claimType: ClaimType.SPARK_REWARDS,
218
+ tokenAddress: reward.rewardTokenAddress,
219
+ underlyingSymbol: reward.underlyingAsset,
220
+ walletAddress,
221
+ label: 'Spark',
222
+ additionalClaimFields: {
223
+ sparkAssetAddresses: reward.aTokenAddresses,
224
+ },
225
+ }));
226
+ };