@defisaver/positions-sdk 2.0.12 → 2.0.14

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 (74) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/README.md +64 -64
  4. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  5. package/cjs/markets/aave/marketAssets.js +1 -1
  6. package/cjs/staking/staking.js +3 -1
  7. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  8. package/esm/markets/aave/marketAssets.js +1 -1
  9. package/esm/staking/staking.js +3 -1
  10. package/package.json +47 -47
  11. package/src/aaveV2/index.ts +236 -236
  12. package/src/aaveV3/index.ts +488 -488
  13. package/src/compoundV2/index.ts +240 -240
  14. package/src/compoundV3/index.ts +270 -270
  15. package/src/config/contracts.ts +1107 -1107
  16. package/src/constants/index.ts +6 -6
  17. package/src/contracts.ts +107 -107
  18. package/src/curveUsd/index.ts +250 -250
  19. package/src/eulerV2/index.ts +314 -314
  20. package/src/exchange/index.ts +25 -25
  21. package/src/fluid/index.ts +1568 -1568
  22. package/src/helpers/aaveHelpers/index.ts +170 -170
  23. package/src/helpers/compoundHelpers/index.ts +261 -261
  24. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  25. package/src/helpers/eulerHelpers/index.ts +259 -259
  26. package/src/helpers/fluidHelpers/index.ts +324 -324
  27. package/src/helpers/index.ts +10 -10
  28. package/src/helpers/liquityV2Helpers/index.ts +80 -80
  29. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  30. package/src/helpers/makerHelpers/index.ts +52 -52
  31. package/src/helpers/morphoBlueHelpers/index.ts +390 -390
  32. package/src/helpers/sparkHelpers/index.ts +155 -155
  33. package/src/index.ts +45 -45
  34. package/src/liquity/index.ts +104 -104
  35. package/src/liquityV2/index.ts +408 -408
  36. package/src/llamaLend/index.ts +296 -296
  37. package/src/maker/index.ts +223 -223
  38. package/src/markets/aave/index.ts +116 -116
  39. package/src/markets/aave/marketAssets.ts +49 -49
  40. package/src/markets/compound/index.ts +227 -227
  41. package/src/markets/compound/marketsAssets.ts +90 -90
  42. package/src/markets/curveUsd/index.ts +69 -69
  43. package/src/markets/euler/index.ts +26 -26
  44. package/src/markets/fluid/index.ts +2456 -2456
  45. package/src/markets/index.ts +25 -25
  46. package/src/markets/liquityV2/index.ts +102 -102
  47. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  48. package/src/markets/llamaLend/index.ts +235 -235
  49. package/src/markets/morphoBlue/index.ts +895 -895
  50. package/src/markets/spark/index.ts +29 -29
  51. package/src/markets/spark/marketAssets.ts +11 -11
  52. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  53. package/src/morphoBlue/index.ts +222 -222
  54. package/src/portfolio/index.ts +285 -285
  55. package/src/services/priceService.ts +159 -159
  56. package/src/services/utils.ts +63 -63
  57. package/src/services/viem.ts +32 -32
  58. package/src/setup.ts +8 -8
  59. package/src/spark/index.ts +456 -456
  60. package/src/staking/staking.ts +194 -193
  61. package/src/types/aave.ts +194 -194
  62. package/src/types/common.ts +88 -88
  63. package/src/types/compound.ts +136 -136
  64. package/src/types/curveUsd.ts +121 -121
  65. package/src/types/euler.ts +174 -174
  66. package/src/types/fluid.ts +450 -450
  67. package/src/types/index.ts +11 -11
  68. package/src/types/liquity.ts +30 -30
  69. package/src/types/liquityV2.ts +126 -126
  70. package/src/types/llamaLend.ts +157 -157
  71. package/src/types/maker.ts +63 -63
  72. package/src/types/morphoBlue.ts +194 -194
  73. package/src/types/portfolio.ts +60 -60
  74. package/src/types/spark.ts +137 -137
@@ -1,194 +1,195 @@
1
- import Dec from 'decimal.js';
2
- import memoize from 'memoizee';
3
- import { MMAssetsData, MMUsedAssets } from '../types/common';
4
- import { BLOCKS_IN_A_YEAR } from '../constants';
5
- import { DEFAULT_TIMEOUT } from '../services/utils';
6
-
7
- const getSsrApy = async () => {
8
- try {
9
- const res = await fetch('https://fe.defisaver.com/api/sky/data',
10
- { signal: AbortSignal.timeout(DEFAULT_TIMEOUT) });
11
- const data = await res.json();
12
- return new Dec(data.data.skyData[0].sky_savings_rate_apy).mul(100).toString();
13
- } catch (e) {
14
- console.error('External API Failure: Failed to fetch SSR APY from external API', e);
15
- return '0';
16
- }
17
- };
18
-
19
- const getSuperOETHApy = async () => {
20
- try {
21
- const res = await fetch('https://origin.squids.live/origin-squid/graphql', {
22
- method: 'POST',
23
- headers: {
24
- 'Content-Type': 'application/json',
25
- },
26
- body: JSON.stringify({
27
- query: '\n query OTokenApy($chainId: Int!, $token: String!) {\n oTokenApies(\n limit: 1\n orderBy: timestamp_DESC\n where: {chainId_eq: $chainId, otoken_containsInsensitive: $token}\n ) {\n apy7DayAvg\n apy14DayAvg\n apy30DayAvg\n apr\n apy\n }\n}\n ',
28
- variables: {
29
- token: '0xdbfefd2e8460a6ee4955a68582f85708baea60a3',
30
- chainId: 8453,
31
- },
32
- }),
33
- signal: AbortSignal.timeout(DEFAULT_TIMEOUT),
34
- });
35
-
36
- const data = await res.json();
37
- return new Dec(data.data.oTokenApies[0].apy).mul(100).toString();
38
- } catch (e) {
39
- console.error('External API Failure: Failed to fetch Super OETH APY from external API', e);
40
- return '0';
41
- }
42
- };
43
-
44
- const getApyFromDfsApi = async (asset: string) => {
45
- try {
46
- const res = await fetch(`https://fe.defisaver.com/api/staking/apy?asset=${asset}`,
47
- { signal: AbortSignal.timeout(DEFAULT_TIMEOUT) });
48
- if (!res.ok) throw new Error(`Failed to fetch APY for ${asset}`);
49
- const data = await res.json();
50
- return String(data.apy);
51
- } catch (e) {
52
- console.error(`External API Failure: Failed to fetch APY for ${asset} from DFS API`, e);
53
- return '0';
54
- }
55
- };
56
-
57
- export const STAKING_ASSETS = ['cbETH', 'wstETH', 'cbETH', 'rETH', 'sDAI', 'weETH', 'sUSDe', 'osETH', 'ezETH', 'ETHx', 'rsETH', 'pufETH', 'wrsETH', 'wsuperOETHb', 'sUSDS', 'tETH', 'PT sUSDe Sep', 'PT USDe Sep', 'PT sUSDe Nov'];
58
-
59
- export const getStakingApy = memoize(async (asset: string) => {
60
- try {
61
- if (asset === 'stETH' || asset === 'wstETH') return await getApyFromDfsApi('wstETH');
62
- if (asset === 'cbETH') return await getApyFromDfsApi('cbETH');
63
- if (asset === 'rETH') return await getApyFromDfsApi('rETH');
64
- if (asset === 'sDAI') return await getApyFromDfsApi('sDAI');
65
- if (asset === 'sUSDe') return await getApyFromDfsApi('sUSDe');
66
- if (asset === 'weETH') return await getApyFromDfsApi('weETH');
67
- if (asset === 'ezETH') return await getApyFromDfsApi('ezETH');
68
- if (asset === 'osETH') return await getApyFromDfsApi('osETH');
69
- if (asset === 'ETHx') return await getApyFromDfsApi('ETHx');
70
- if (asset === 'rsETH' || asset === 'wrsETH') return await getApyFromDfsApi('rsETH');
71
- if (asset === 'pufETH') return await getApyFromDfsApi('pufETH');
72
- if (asset === 'wsuperOETHb') return await getSuperOETHApy();
73
- if (asset === 'sUSDS') return await getSsrApy();
74
- if (asset === 'PT eUSDe May') return await getApyFromDfsApi('PT eUSDe May');
75
- if (asset === 'PT sUSDe July') return await getApyFromDfsApi('PT sUSDe July');
76
- if (asset === 'PT USDe July') return await getApyFromDfsApi('PT USDe July');
77
- if (asset === 'PT eUSDe Aug') return await getApyFromDfsApi('PT eUSDe Aug');
78
- if (asset === 'PT sUSDe Sep') return await getApyFromDfsApi('PT sUSDe Sep');
79
- if (asset === 'PT USDe Sep') return await getApyFromDfsApi('PT USDe Sep');
80
- if (asset === 'tETH') return await getApyFromDfsApi('tETH');
81
- if (asset === 'USDe') return await getApyFromDfsApi('USDe');
82
- if (asset === 'PT sUSDe Nov') return await getApyFromDfsApi('PT sUSDe Nov');
83
- } catch (e) {
84
- console.error(`Failed to fetch APY for ${asset}`);
85
- }
86
- return '0';
87
- }, { promise: true, maxAge: 2 * 60 * 1000 });
88
-
89
- export const calculateInterestEarned = (principal: string, interest: string, type: string, apy = false) => {
90
- let interval = 1;
91
-
92
- if (+interest === 0) return 0;
93
-
94
- if (type === 'month') interval = 1 / 12;
95
- if (type === 'week') interval = 1 / 52.1429;
96
-
97
- if (apy) {
98
- // interest rate already compounded
99
- return (+principal * (1 + (+interest / 100 * interval))) - +principal;
100
- }
101
-
102
- return (+principal * (((1 + (+interest / 100) / BLOCKS_IN_A_YEAR)) ** (BLOCKS_IN_A_YEAR * interval))) - +principal; // eslint-disable-line
103
- };
104
-
105
- export const isEligibleForEthenaUSDeRewards = (usedAssets: MMUsedAssets) => {
106
- const USDeUSDAmountSupplied = usedAssets.USDe?.suppliedUsd || '0';
107
- const sUSDeUSDAmountSupplied = usedAssets.sUSDe?.suppliedUsd || '0';
108
- const anythingElseSupplied = Object.values(usedAssets).some((asset) => asset.symbol !== 'USDe' && asset.symbol !== 'sUSDe' && asset.isSupplied);
109
- if (anythingElseSupplied) return { isEligible: false, eligibleUSDAmount: '0' };
110
- const totalAmountSupplied = new Dec(USDeUSDAmountSupplied).add(sUSDeUSDAmountSupplied).toString();
111
- const percentageInUSDe = new Dec(USDeUSDAmountSupplied).div(totalAmountSupplied).toNumber();
112
- if (percentageInUSDe < 0.45 || percentageInUSDe > 0.55) return { isEligible: false, eligibleUSDAmount: '0' }; // 45% - 55% of total amount supplied must be in USDe
113
- const percentageInSUSDe = new Dec(sUSDeUSDAmountSupplied).div(totalAmountSupplied).toNumber();
114
- if (percentageInSUSDe < 0.45 || percentageInSUSDe > 0.55) return { isEligible: false, eligibleUSDAmount: '0' }; // 45% - 55% of total amount supplied must be in sUSDe
115
-
116
- const allowedBorrowAssets = ['USDC', 'USDT', 'USDS'];
117
- const anythingBorrowedNotAllowed = Object.values(usedAssets).some((asset) => asset.isBorrowed && !allowedBorrowAssets.includes(asset.symbol));
118
- if (anythingBorrowedNotAllowed) return { isEligible: false, eligibleUSDAmount: '0' };
119
-
120
- const totalAmountBorrowed = Object.values(usedAssets).reduce((acc, asset) => {
121
- if (asset.isBorrowed) {
122
- return acc.add(asset.borrowedUsd);
123
- }
124
- return acc;
125
- }, new Dec(0)).toString();
126
-
127
- const borrowPercentage = new Dec(totalAmountBorrowed).div(totalAmountSupplied).toNumber();
128
- if (borrowPercentage < 0.5) return { isEligible: false, eligibleUSDAmount: '0' }; // must be looped at least once
129
-
130
- const halfAmountSupplied = new Dec(totalAmountSupplied).div(2).toString();
131
- const USDeAmountEligibleForRewards = Dec.min(USDeUSDAmountSupplied, halfAmountSupplied).toString(); // rewards are given to amount of USDe supplied up to half of total amount supplied
132
-
133
- return { isEligible: true, eligibleUSDAmount: USDeAmountEligibleForRewards };
134
- };
135
-
136
- export const calculateNetApy = ({
137
- usedAssets, assetsData, isMorpho = false, isAave = false,
138
- }: { usedAssets: MMUsedAssets, assetsData: MMAssetsData, isMorpho?: boolean, isAave?: boolean }) => {
139
- const { isEligible, eligibleUSDAmount } = isAave ? isEligibleForEthenaUSDeRewards(usedAssets) : { isEligible: true, eligibleUSDAmount: '0' };
140
- const sumValues = Object.values(usedAssets).reduce((_acc, usedAsset) => {
141
- const acc = { ..._acc };
142
- const assetData = assetsData[usedAsset.symbol];
143
-
144
- if (usedAsset.isSupplied) {
145
- const amount = usedAsset.suppliedUsd;
146
- acc.suppliedUsd = new Dec(acc.suppliedUsd).add(amount).toString();
147
- const rate = isMorpho
148
- ? usedAsset.supplyRate === '0' ? assetData.supplyRateP2P : usedAsset.supplyRate
149
- : assetData.supplyRate;
150
- const supplyInterest = calculateInterestEarned(amount, rate as string, 'year', true);
151
- acc.supplyInterest = new Dec(acc.supplyInterest).add(supplyInterest.toString()).toString();
152
- if (assetData.incentiveSupplyApy) {
153
- // take COMP/AAVE yield into account
154
- const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveSupplyApy, 'year', true);
155
- acc.incentiveUsd = new Dec(acc.incentiveUsd).add(incentiveInterest).toString();
156
- }
157
-
158
- if (usedAsset.symbol === 'USDe' && isEligible) {
159
- // @ts-ignore
160
- const incentiveInterest = calculateInterestEarned(eligibleUSDAmount, assetData.supplyIncentives?.[0]?.apy || '0', 'year', true);
161
- acc.incentiveUsd = new Dec(acc.incentiveUsd).add(incentiveInterest).toString();
162
- }
163
- }
164
-
165
- if (usedAsset.isBorrowed) {
166
- const amount = usedAsset.borrowedUsd;
167
- acc.borrowedUsd = new Dec(acc.borrowedUsd).add(amount).toString();
168
- const rate = isMorpho
169
- ? usedAsset.borrowRate === '0' ? assetData.borrowRateP2P : usedAsset.borrowRate
170
- : (usedAsset?.interestMode === '1' ? usedAsset.stableBorrowRate : assetData.borrowRate);
171
- const borrowInterest = calculateInterestEarned(amount, rate as string, 'year', true);
172
- acc.borrowInterest = new Dec(acc.borrowInterest).sub(borrowInterest.toString()).toString();
173
- if (assetData.incentiveBorrowApy) {
174
- // take COMP/AAVE yield into account
175
- const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveBorrowApy, 'year', true);
176
- acc.incentiveUsd = new Dec(acc.incentiveUsd).sub(incentiveInterest).toString();
177
- }
178
- }
179
-
180
- return acc;
181
- }, {
182
- borrowInterest: '0', supplyInterest: '0', incentiveUsd: '0', borrowedUsd: '0', suppliedUsd: '0',
183
- });
184
-
185
- const {
186
- borrowedUsd, suppliedUsd, borrowInterest, supplyInterest, incentiveUsd,
187
- } = sumValues;
188
-
189
- const totalInterestUsd = new Dec(borrowInterest).add(supplyInterest).add(incentiveUsd).toString();
190
- const balance = new Dec(suppliedUsd).sub(borrowedUsd);
191
- const netApy = new Dec(totalInterestUsd).div(balance).times(100).toString();
192
-
193
- return { netApy, totalInterestUsd, incentiveUsd };
1
+ import Dec from 'decimal.js';
2
+ import memoize from 'memoizee';
3
+ import { MMAssetsData, MMUsedAssets } from '../types/common';
4
+ import { BLOCKS_IN_A_YEAR } from '../constants';
5
+ import { DEFAULT_TIMEOUT } from '../services/utils';
6
+
7
+ const getSsrApy = async () => {
8
+ try {
9
+ const res = await fetch('https://fe.defisaver.com/api/sky/data',
10
+ { signal: AbortSignal.timeout(DEFAULT_TIMEOUT) });
11
+ const data = await res.json();
12
+ return new Dec(data.data.skyData[0].sky_savings_rate_apy).mul(100).toString();
13
+ } catch (e) {
14
+ console.error('External API Failure: Failed to fetch SSR APY from external API', e);
15
+ return '0';
16
+ }
17
+ };
18
+
19
+ const getSuperOETHApy = async () => {
20
+ try {
21
+ const res = await fetch('https://origin.squids.live/origin-squid/graphql', {
22
+ method: 'POST',
23
+ headers: {
24
+ 'Content-Type': 'application/json',
25
+ },
26
+ body: JSON.stringify({
27
+ query: '\n query OTokenApy($chainId: Int!, $token: String!) {\n oTokenApies(\n limit: 1\n orderBy: timestamp_DESC\n where: {chainId_eq: $chainId, otoken_containsInsensitive: $token}\n ) {\n apy7DayAvg\n apy14DayAvg\n apy30DayAvg\n apr\n apy\n }\n}\n ',
28
+ variables: {
29
+ token: '0xdbfefd2e8460a6ee4955a68582f85708baea60a3',
30
+ chainId: 8453,
31
+ },
32
+ }),
33
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT),
34
+ });
35
+
36
+ const data = await res.json();
37
+ return new Dec(data.data.oTokenApies[0].apy).mul(100).toString();
38
+ } catch (e) {
39
+ console.error('External API Failure: Failed to fetch Super OETH APY from external API', e);
40
+ return '0';
41
+ }
42
+ };
43
+
44
+ const getApyFromDfsApi = async (asset: string) => {
45
+ try {
46
+ const res = await fetch(`https://fe.defisaver.com/api/staking/apy?asset=${asset}`,
47
+ { signal: AbortSignal.timeout(DEFAULT_TIMEOUT) });
48
+ if (!res.ok) throw new Error(`Failed to fetch APY for ${asset}`);
49
+ const data = await res.json();
50
+ return String(data.apy);
51
+ } catch (e) {
52
+ console.error(`External API Failure: Failed to fetch APY for ${asset} from DFS API`, e);
53
+ return '0';
54
+ }
55
+ };
56
+
57
+ export const STAKING_ASSETS = ['cbETH', 'wstETH', 'cbETH', 'rETH', 'sDAI', 'weETH', 'sUSDe', 'osETH', 'ezETH', 'ETHx', 'rsETH', 'pufETH', 'wrsETH', 'wsuperOETHb', 'sUSDS', 'tETH', 'PT sUSDe Sep', 'PT USDe Sep', 'PT sUSDe Nov', 'PT USDe Nov'];
58
+
59
+ export const getStakingApy = memoize(async (asset: string) => {
60
+ try {
61
+ if (asset === 'stETH' || asset === 'wstETH') return await getApyFromDfsApi('wstETH');
62
+ if (asset === 'cbETH') return await getApyFromDfsApi('cbETH');
63
+ if (asset === 'rETH') return await getApyFromDfsApi('rETH');
64
+ if (asset === 'sDAI') return await getApyFromDfsApi('sDAI');
65
+ if (asset === 'sUSDe') return await getApyFromDfsApi('sUSDe');
66
+ if (asset === 'weETH') return await getApyFromDfsApi('weETH');
67
+ if (asset === 'ezETH') return await getApyFromDfsApi('ezETH');
68
+ if (asset === 'osETH') return await getApyFromDfsApi('osETH');
69
+ if (asset === 'ETHx') return await getApyFromDfsApi('ETHx');
70
+ if (asset === 'rsETH' || asset === 'wrsETH') return await getApyFromDfsApi('rsETH');
71
+ if (asset === 'pufETH') return await getApyFromDfsApi('pufETH');
72
+ if (asset === 'wsuperOETHb') return await getSuperOETHApy();
73
+ if (asset === 'sUSDS') return await getSsrApy();
74
+ if (asset === 'PT eUSDe May') return await getApyFromDfsApi('PT eUSDe May');
75
+ if (asset === 'PT sUSDe July') return await getApyFromDfsApi('PT sUSDe July');
76
+ if (asset === 'PT USDe July') return await getApyFromDfsApi('PT USDe July');
77
+ if (asset === 'PT eUSDe Aug') return await getApyFromDfsApi('PT eUSDe Aug');
78
+ if (asset === 'PT sUSDe Sep') return await getApyFromDfsApi('PT sUSDe Sep');
79
+ if (asset === 'PT USDe Sep') return await getApyFromDfsApi('PT USDe Sep');
80
+ if (asset === 'tETH') return await getApyFromDfsApi('tETH');
81
+ if (asset === 'USDe') return await getApyFromDfsApi('USDe');
82
+ if (asset === 'PT sUSDe Nov') return await getApyFromDfsApi('PT sUSDe Nov');
83
+ if (asset === 'PT USDe Nov') return await getApyFromDfsApi('PT USDe Nov');
84
+ } catch (e) {
85
+ console.error(`Failed to fetch APY for ${asset}`);
86
+ }
87
+ return '0';
88
+ }, { promise: true, maxAge: 2 * 60 * 1000 });
89
+
90
+ export const calculateInterestEarned = (principal: string, interest: string, type: string, apy = false) => {
91
+ let interval = 1;
92
+
93
+ if (+interest === 0) return 0;
94
+
95
+ if (type === 'month') interval = 1 / 12;
96
+ if (type === 'week') interval = 1 / 52.1429;
97
+
98
+ if (apy) {
99
+ // interest rate already compounded
100
+ return (+principal * (1 + (+interest / 100 * interval))) - +principal;
101
+ }
102
+
103
+ return (+principal * (((1 + (+interest / 100) / BLOCKS_IN_A_YEAR)) ** (BLOCKS_IN_A_YEAR * interval))) - +principal; // eslint-disable-line
104
+ };
105
+
106
+ export const isEligibleForEthenaUSDeRewards = (usedAssets: MMUsedAssets) => {
107
+ const USDeUSDAmountSupplied = usedAssets.USDe?.suppliedUsd || '0';
108
+ const sUSDeUSDAmountSupplied = usedAssets.sUSDe?.suppliedUsd || '0';
109
+ const anythingElseSupplied = Object.values(usedAssets).some((asset) => asset.symbol !== 'USDe' && asset.symbol !== 'sUSDe' && asset.isSupplied);
110
+ if (anythingElseSupplied) return { isEligible: false, eligibleUSDAmount: '0' };
111
+ const totalAmountSupplied = new Dec(USDeUSDAmountSupplied).add(sUSDeUSDAmountSupplied).toString();
112
+ const percentageInUSDe = new Dec(USDeUSDAmountSupplied).div(totalAmountSupplied).toNumber();
113
+ if (percentageInUSDe < 0.45 || percentageInUSDe > 0.55) return { isEligible: false, eligibleUSDAmount: '0' }; // 45% - 55% of total amount supplied must be in USDe
114
+ const percentageInSUSDe = new Dec(sUSDeUSDAmountSupplied).div(totalAmountSupplied).toNumber();
115
+ if (percentageInSUSDe < 0.45 || percentageInSUSDe > 0.55) return { isEligible: false, eligibleUSDAmount: '0' }; // 45% - 55% of total amount supplied must be in sUSDe
116
+
117
+ const allowedBorrowAssets = ['USDC', 'USDT', 'USDS'];
118
+ const anythingBorrowedNotAllowed = Object.values(usedAssets).some((asset) => asset.isBorrowed && !allowedBorrowAssets.includes(asset.symbol));
119
+ if (anythingBorrowedNotAllowed) return { isEligible: false, eligibleUSDAmount: '0' };
120
+
121
+ const totalAmountBorrowed = Object.values(usedAssets).reduce((acc, asset) => {
122
+ if (asset.isBorrowed) {
123
+ return acc.add(asset.borrowedUsd);
124
+ }
125
+ return acc;
126
+ }, new Dec(0)).toString();
127
+
128
+ const borrowPercentage = new Dec(totalAmountBorrowed).div(totalAmountSupplied).toNumber();
129
+ if (borrowPercentage < 0.5) return { isEligible: false, eligibleUSDAmount: '0' }; // must be looped at least once
130
+
131
+ const halfAmountSupplied = new Dec(totalAmountSupplied).div(2).toString();
132
+ const USDeAmountEligibleForRewards = Dec.min(USDeUSDAmountSupplied, halfAmountSupplied).toString(); // rewards are given to amount of USDe supplied up to half of total amount supplied
133
+
134
+ return { isEligible: true, eligibleUSDAmount: USDeAmountEligibleForRewards };
135
+ };
136
+
137
+ export const calculateNetApy = ({
138
+ usedAssets, assetsData, isMorpho = false, isAave = false,
139
+ }: { usedAssets: MMUsedAssets, assetsData: MMAssetsData, isMorpho?: boolean, isAave?: boolean }) => {
140
+ const { isEligible, eligibleUSDAmount } = isAave ? isEligibleForEthenaUSDeRewards(usedAssets) : { isEligible: true, eligibleUSDAmount: '0' };
141
+ const sumValues = Object.values(usedAssets).reduce((_acc, usedAsset) => {
142
+ const acc = { ..._acc };
143
+ const assetData = assetsData[usedAsset.symbol];
144
+
145
+ if (usedAsset.isSupplied) {
146
+ const amount = usedAsset.suppliedUsd;
147
+ acc.suppliedUsd = new Dec(acc.suppliedUsd).add(amount).toString();
148
+ const rate = isMorpho
149
+ ? usedAsset.supplyRate === '0' ? assetData.supplyRateP2P : usedAsset.supplyRate
150
+ : assetData.supplyRate;
151
+ const supplyInterest = calculateInterestEarned(amount, rate as string, 'year', true);
152
+ acc.supplyInterest = new Dec(acc.supplyInterest).add(supplyInterest.toString()).toString();
153
+ if (assetData.incentiveSupplyApy) {
154
+ // take COMP/AAVE yield into account
155
+ const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveSupplyApy, 'year', true);
156
+ acc.incentiveUsd = new Dec(acc.incentiveUsd).add(incentiveInterest).toString();
157
+ }
158
+
159
+ if (usedAsset.symbol === 'USDe' && isEligible) {
160
+ // @ts-ignore
161
+ const incentiveInterest = calculateInterestEarned(eligibleUSDAmount, assetData.supplyIncentives?.[0]?.apy || '0', 'year', true);
162
+ acc.incentiveUsd = new Dec(acc.incentiveUsd).add(incentiveInterest).toString();
163
+ }
164
+ }
165
+
166
+ if (usedAsset.isBorrowed) {
167
+ const amount = usedAsset.borrowedUsd;
168
+ acc.borrowedUsd = new Dec(acc.borrowedUsd).add(amount).toString();
169
+ const rate = isMorpho
170
+ ? usedAsset.borrowRate === '0' ? assetData.borrowRateP2P : usedAsset.borrowRate
171
+ : (usedAsset?.interestMode === '1' ? usedAsset.stableBorrowRate : assetData.borrowRate);
172
+ const borrowInterest = calculateInterestEarned(amount, rate as string, 'year', true);
173
+ acc.borrowInterest = new Dec(acc.borrowInterest).sub(borrowInterest.toString()).toString();
174
+ if (assetData.incentiveBorrowApy) {
175
+ // take COMP/AAVE yield into account
176
+ const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveBorrowApy, 'year', true);
177
+ acc.incentiveUsd = new Dec(acc.incentiveUsd).sub(incentiveInterest).toString();
178
+ }
179
+ }
180
+
181
+ return acc;
182
+ }, {
183
+ borrowInterest: '0', supplyInterest: '0', incentiveUsd: '0', borrowedUsd: '0', suppliedUsd: '0',
184
+ });
185
+
186
+ const {
187
+ borrowedUsd, suppliedUsd, borrowInterest, supplyInterest, incentiveUsd,
188
+ } = sumValues;
189
+
190
+ const totalInterestUsd = new Dec(borrowInterest).add(supplyInterest).add(incentiveUsd).toString();
191
+ const balance = new Dec(suppliedUsd).sub(borrowedUsd);
192
+ const netApy = new Dec(totalInterestUsd).div(balance).times(100).toString();
193
+
194
+ return { netApy, totalInterestUsd, incentiveUsd };
194
195
  };