@defisaver/positions-sdk 0.0.187 → 0.0.188-dev-markets

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 (126) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/README.md +69 -69
  4. package/cjs/compoundV3/index.js +14 -9
  5. package/cjs/config/contracts.d.ts +572 -216
  6. package/cjs/config/contracts.js +34 -2
  7. package/cjs/contracts.d.ts +2 -0
  8. package/cjs/contracts.js +3 -1
  9. package/cjs/helpers/morphoBlueHelpers/index.js +49 -49
  10. package/cjs/markets/compound/index.d.ts +4 -0
  11. package/cjs/markets/compound/index.js +41 -1
  12. package/cjs/markets/compound/marketsAssets.d.ts +14 -0
  13. package/cjs/markets/compound/marketsAssets.js +17 -3
  14. package/cjs/markets/morphoBlue/index.d.ts +8 -0
  15. package/cjs/markets/morphoBlue/index.js +71 -2
  16. package/cjs/morphoBlue/index.js +27 -10
  17. package/cjs/services/priceService.d.ts +3 -0
  18. package/cjs/services/priceService.js +33 -1
  19. package/cjs/types/compound.d.ts +3 -1
  20. package/cjs/types/compound.js +2 -0
  21. package/cjs/types/contracts/generated/CUSDSv3.d.ts +441 -0
  22. package/cjs/types/contracts/generated/CUSDSv3.js +5 -0
  23. package/cjs/types/contracts/generated/CWstETHv3.d.ts +441 -0
  24. package/cjs/types/contracts/generated/CWstETHv3.js +5 -0
  25. package/cjs/types/contracts/generated/DFSFeedRegistry.d.ts +40 -0
  26. package/cjs/types/contracts/generated/DFSFeedRegistry.js +5 -0
  27. package/cjs/types/contracts/generated/WstETHPriceFeed.d.ts +39 -0
  28. package/cjs/types/contracts/generated/WstETHPriceFeed.js +5 -0
  29. package/cjs/types/contracts/generated/index.d.ts +4 -0
  30. package/cjs/types/morphoBlue.d.ts +5 -1
  31. package/cjs/types/morphoBlue.js +4 -0
  32. package/esm/compoundV3/index.js +15 -10
  33. package/esm/config/contracts.d.ts +572 -216
  34. package/esm/config/contracts.js +34 -2
  35. package/esm/contracts.d.ts +2 -0
  36. package/esm/contracts.js +2 -0
  37. package/esm/helpers/morphoBlueHelpers/index.js +49 -49
  38. package/esm/markets/compound/index.d.ts +4 -0
  39. package/esm/markets/compound/index.js +39 -1
  40. package/esm/markets/compound/marketsAssets.d.ts +14 -0
  41. package/esm/markets/compound/marketsAssets.js +16 -2
  42. package/esm/markets/morphoBlue/index.d.ts +8 -0
  43. package/esm/markets/morphoBlue/index.js +65 -1
  44. package/esm/morphoBlue/index.js +30 -13
  45. package/esm/services/priceService.d.ts +3 -0
  46. package/esm/services/priceService.js +31 -1
  47. package/esm/types/compound.d.ts +3 -1
  48. package/esm/types/compound.js +2 -0
  49. package/esm/types/contracts/generated/CUSDSv3.d.ts +441 -0
  50. package/esm/types/contracts/generated/CUSDSv3.js +4 -0
  51. package/esm/types/contracts/generated/CWstETHv3.d.ts +441 -0
  52. package/esm/types/contracts/generated/CWstETHv3.js +4 -0
  53. package/esm/types/contracts/generated/DFSFeedRegistry.d.ts +40 -0
  54. package/esm/types/contracts/generated/DFSFeedRegistry.js +4 -0
  55. package/esm/types/contracts/generated/WstETHPriceFeed.d.ts +39 -0
  56. package/esm/types/contracts/generated/WstETHPriceFeed.js +4 -0
  57. package/esm/types/contracts/generated/index.d.ts +4 -0
  58. package/esm/types/morphoBlue.d.ts +5 -1
  59. package/esm/types/morphoBlue.js +4 -0
  60. package/package.json +49 -49
  61. package/src/aaveV2/index.ts +227 -227
  62. package/src/aaveV3/index.ts +624 -624
  63. package/src/assets/index.ts +60 -60
  64. package/src/chickenBonds/index.ts +123 -123
  65. package/src/compoundV2/index.ts +220 -220
  66. package/src/compoundV3/index.ts +291 -282
  67. package/src/config/contracts.js +1079 -1047
  68. package/src/constants/index.ts +6 -6
  69. package/src/contracts.ts +132 -130
  70. package/src/curveUsd/index.ts +229 -229
  71. package/src/eulerV2/index.ts +303 -303
  72. package/src/exchange/index.ts +17 -17
  73. package/src/helpers/aaveHelpers/index.ts +198 -198
  74. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  75. package/src/helpers/compoundHelpers/index.ts +246 -246
  76. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  77. package/src/helpers/eulerHelpers/index.ts +232 -232
  78. package/src/helpers/index.ts +8 -8
  79. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  80. package/src/helpers/makerHelpers/index.ts +94 -94
  81. package/src/helpers/morphoBlueHelpers/index.ts +325 -325
  82. package/src/helpers/sparkHelpers/index.ts +150 -150
  83. package/src/index.ts +48 -48
  84. package/src/liquity/index.ts +116 -116
  85. package/src/llamaLend/index.ts +275 -275
  86. package/src/maker/index.ts +117 -117
  87. package/src/markets/aave/index.ts +152 -152
  88. package/src/markets/aave/marketAssets.ts +46 -46
  89. package/src/markets/compound/index.ts +213 -173
  90. package/src/markets/compound/marketsAssets.ts +82 -64
  91. package/src/markets/curveUsd/index.ts +69 -69
  92. package/src/markets/euler/index.ts +26 -26
  93. package/src/markets/index.ts +23 -23
  94. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  95. package/src/markets/llamaLend/index.ts +235 -235
  96. package/src/markets/morphoBlue/index.ts +878 -809
  97. package/src/markets/spark/index.ts +29 -29
  98. package/src/markets/spark/marketAssets.ts +10 -10
  99. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  100. package/src/morphoAaveV2/index.ts +256 -256
  101. package/src/morphoAaveV3/index.ts +630 -630
  102. package/src/morphoBlue/index.ts +188 -171
  103. package/src/multicall/index.ts +22 -22
  104. package/src/services/dsrService.ts +15 -15
  105. package/src/services/priceService.ts +61 -22
  106. package/src/services/utils.ts +56 -56
  107. package/src/setup.ts +8 -8
  108. package/src/spark/index.ts +461 -461
  109. package/src/staking/staking.ts +220 -220
  110. package/src/types/aave.ts +270 -270
  111. package/src/types/chickenBonds.ts +45 -45
  112. package/src/types/common.ts +84 -84
  113. package/src/types/compound.ts +131 -129
  114. package/src/types/contracts/generated/CUSDSv3.ts +685 -0
  115. package/src/types/contracts/generated/CWstETHv3.ts +685 -0
  116. package/src/types/contracts/generated/DFSFeedRegistry.ts +77 -0
  117. package/src/types/contracts/generated/WstETHPriceFeed.ts +59 -0
  118. package/src/types/contracts/generated/index.ts +4 -0
  119. package/src/types/curveUsd.ts +118 -118
  120. package/src/types/euler.ts +171 -171
  121. package/src/types/index.ts +9 -9
  122. package/src/types/liquity.ts +30 -30
  123. package/src/types/llamaLend.ts +155 -155
  124. package/src/types/maker.ts +50 -50
  125. package/src/types/morphoBlue.ts +189 -185
  126. package/src/types/spark.ts +131 -131
@@ -1,256 +1,256 @@
1
- import { assetAmountInEth, getAssetInfoByAddress } from '@defisaver/tokens';
2
- import Dec from 'decimal.js';
3
- import Web3 from 'web3';
4
- import { wethToEthByAddress } from '../services/utils';
5
- import {
6
- Blockish, EthAddress, NetworkNumber, PositionBalances,
7
- } from '../types/common';
8
- import { getStETHApy } from '../staking';
9
- import { MorphoAaveV2ViewContract } from '../contracts';
10
- import {
11
- AavePositionData,
12
- AaveVersions, MorphoAaveV2AssetData, MorphoAaveV2AssetsData, MorphoAaveV2MarketData, MorphoAaveV2PositionData,
13
- } from '../types';
14
- import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
15
- import { EMPTY_AAVE_DATA } from '../aaveV3';
16
- import { aaveAnyGetAggregatedPositionData } from '../helpers/aaveHelpers';
17
- import { getEthPrice } from '../services/priceService';
18
-
19
- export const getMorphoAaveV2MarketsData = async (web3: Web3, network: NetworkNumber, mainnetWeb3: Web3): Promise<MorphoAaveV2MarketData> => {
20
- const ethPrice = await getEthPrice(web3);
21
- const morphoAaveV2ViewContract = MorphoAaveV2ViewContract(web3, network);
22
-
23
- const [contractData, morphoRewardsRes] = await Promise.allSettled([
24
- morphoAaveV2ViewContract.methods.getAllMarketsInfo().call(),
25
- fetch('https://api.morpho.xyz/rewards/distribution'),
26
- ]);
27
-
28
- if (contractData.status !== 'fulfilled') {
29
- throw new Error('Failed to fetch market data.');
30
- }
31
-
32
- const { marketInfo, aaveTokenInfo } = contractData.value;
33
-
34
- const morphoRewardsData = morphoRewardsRes.status === 'fulfilled' ? await morphoRewardsRes.value.json() : null;
35
-
36
- const assetsData: MorphoAaveV2AssetData[] = marketInfo.map((market, index) => {
37
- const aaveInfo = aaveTokenInfo[index];
38
- const { symbol, address } = getAssetInfoByAddress(wethToEthByAddress(aaveInfo.underlyingTokenAddress));
39
-
40
- const morphoReward = morphoRewardsData?.markets?.[aaveInfo.aTokenAddress.toLowerCase()];
41
-
42
- const supplyRateP2P = aprToApy(new Dec(market.p2pSupplyRate).div(1e25).toString());
43
- const borrowRateP2P = aprToApy(new Dec(market.p2pBorrowRate).div(1e25).toString());
44
- const hasDelta = new Dec(borrowRateP2P).minus(supplyRateP2P).gte(0.3);
45
-
46
- return {
47
- symbol,
48
- hasDelta,
49
- aTokenAddress: aaveInfo.aTokenAddress,
50
- underlyingTokenAddress: address,
51
- priceInEth: new Dec(aaveInfo.price).div(1e18).toString(),
52
- price: new Dec(aaveInfo.price).div(1e18).times(ethPrice).toString(),
53
-
54
- supplyRate: aprToApy(new Dec(market.poolSupplyRate).div(1e25).toString()),
55
- supplyRateP2P,
56
- borrowRate: aprToApy(new Dec(market.poolBorrowRate).div(1e25).toString()),
57
- borrowRateP2P,
58
-
59
- totalSupply: assetAmountInEth(aaveInfo.totalSupply, symbol),
60
- totalBorrow: assetAmountInEth(aaveInfo.totalBorrow, symbol),
61
- totalSupplyP2P: assetAmountInEth(market.p2pSupplyAmount, symbol),
62
- totalSupplyPool: assetAmountInEth(market.poolSupplyAmount, symbol),
63
- totalBorrowP2P: assetAmountInEth(market.p2pBorrowAmount, symbol),
64
- totalBorrowPool: assetAmountInEth(market.poolBorrowAmount, symbol),
65
-
66
- collateralFactor: new Dec(aaveInfo.collateralFactor).div(10000).toString(),
67
- liquidationRatio: new Dec(aaveInfo.liquidationRatio).div(10000).toString(),
68
-
69
- isInactive: !aaveInfo.isActive,
70
- isFrozen: aaveInfo.isFrozen,
71
- canBeBorrowed:
72
- aaveInfo.borrowingEnabled
73
- && !aaveInfo.isFrozen
74
- && !(market.pauseStatus.isBorrowPaused || market.pauseStatus.isDeprecated),
75
- canBeWithdrawn: !market.pauseStatus.isWithdrawPaused,
76
- canBePayBacked: !market.pauseStatus.isRepayPaused,
77
- canBeSupplied: !aaveInfo.isFrozen && !(market.pauseStatus.isSupplyPaused || market.pauseStatus.isDeprecated),
78
-
79
- reserveFactor: market.reserveFactor,
80
- pauseStatus: market.pauseStatus,
81
-
82
- incentiveSupplyToken: 'MORPHO',
83
- incentiveBorrowToken: 'MORPHO',
84
- incentiveSupplyApy: new Dec(morphoReward?.supplyRate || 0).div(1e18).toString(),
85
- incentiveBorrowApy: new Dec(morphoReward?.borrowRate || 0).div(1e18).toString(),
86
-
87
- marketLiquidity: assetAmountInEth(new Dec(aaveInfo.totalSupply.toString())
88
- .sub(aaveInfo.totalBorrow.toString())
89
- .toString(), symbol),
90
- utilization: new Dec(aaveInfo.totalBorrow.toString())
91
- .div(new Dec(aaveInfo.totalSupply.toString()))
92
- .times(100)
93
- .toString(),
94
-
95
- totalBorrowVar: '0', // Morpho doesn't have all these, keeping it for compatability
96
- usageAsCollateralEnabled: false,
97
- disabledStableBorrowing: false,
98
- borrowRateStable: '0',
99
- supplyCap: '0', // V2 doesn't have borrow/supply cap but adding it for compatability with V3
100
- borrowCap: '0',
101
- };
102
- });
103
-
104
- const stEthMarket = assetsData.find(({ symbol }) => symbol === 'stETH');
105
- if (stEthMarket) {
106
- stEthMarket.incentiveSupplyApy = await getStETHApy(mainnetWeb3);
107
- stEthMarket.incentiveSupplyToken = 'stETH';
108
- }
109
-
110
- const payload: MorphoAaveV2AssetsData = {};
111
- // Sort by market size
112
- assetsData
113
- .sort((a, b) => {
114
- const aMarket = new Dec(a.price).times(a.totalSupply).toString();
115
- const bMarket = new Dec(b.price).times(b.totalSupply).toString();
116
-
117
- return new Dec(bMarket).minus(aMarket).toNumber();
118
- })
119
- .forEach((assetData: MorphoAaveV2AssetData, i: number) => {
120
- payload[assetData.symbol] = { ...assetData, sortIndex: i };
121
- });
122
-
123
- return { assetsData: payload };
124
- };
125
-
126
- export const getMorphoAaveV2AccountBalances = async (web3: Web3, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
127
- let balances: PositionBalances = {
128
- collateral: {},
129
- debt: {},
130
- };
131
-
132
- if (!address) {
133
- return balances;
134
- }
135
-
136
- const morphoAaveV2ViewContract = MorphoAaveV2ViewContract(web3, network, block);
137
-
138
- const { userBalances } = await morphoAaveV2ViewContract.methods.getUserInfo(address).call({}, block);
139
-
140
- if (userBalances.length === 0) {
141
- return balances;
142
- }
143
-
144
- userBalances.forEach((balance: any) => {
145
- const assetAddr = wethToEthByAddress(balance.underlying, network).toLowerCase();
146
- const { symbol } = getAssetInfoByAddress(assetAddr, network);
147
-
148
- balances = {
149
- collateral: {
150
- ...balances.collateral,
151
- [addressMapping ? assetAddr : symbol]: new Dec(balance.supplyBalanceInP2P).add(balance.supplyBalanceOnPool).toString(),
152
- },
153
- debt: {
154
- ...balances.debt,
155
- [addressMapping ? assetAddr : symbol]: new Dec(balance.borrowBalanceInP2P).add(balance.borrowBalanceOnPool).toString(),
156
- },
157
- };
158
- });
159
-
160
- return balances;
161
- };
162
-
163
- export const getMorphoAaveV2AccountData = async (web3: Web3, network: NetworkNumber, address: string, assetsData: MorphoAaveV2AssetsData): Promise<MorphoAaveV2PositionData> => {
164
- if (!address) {
165
- throw new Error('Address is required.');
166
- }
167
-
168
- let payload: MorphoAaveV2PositionData = {
169
- ...EMPTY_AAVE_DATA,
170
- usedAssets: {},
171
- minRatio: '100',
172
- lastUpdated: Date.now(),
173
- };
174
-
175
- const morphoAaveV2ViewContract = MorphoAaveV2ViewContract(web3, network);
176
-
177
- const { userBalances } = await morphoAaveV2ViewContract.methods.getUserInfo(address).call();
178
-
179
- if (userBalances.length === 0) {
180
- return payload;
181
- }
182
-
183
- userBalances.forEach((market) => {
184
- const { symbol } = getAssetInfoByAddress(wethToEthByAddress(market.underlying));
185
- const suppliedP2P = assetAmountInEth(market.supplyBalanceInP2P, symbol);
186
- const suppliedPool = assetAmountInEth(market.supplyBalanceOnPool, symbol);
187
- const supplied = new Dec(suppliedP2P).add(suppliedPool).toString();
188
- const suppliedMatched = new Dec(suppliedP2P).div(supplied).mul(100).toDP(2)
189
- .toString();
190
-
191
- const assetAavePrice = assetsData[symbol].price;
192
- const borrowedP2P = assetAmountInEth(market.borrowBalanceInP2P, symbol);
193
- const borrowedPool = assetAmountInEth(market.borrowBalanceOnPool, symbol);
194
- const borrowed = new Dec(borrowedP2P).add(borrowedPool).toString();
195
- const borrowedMatched = new Dec(borrowedP2P).div(borrowed).mul(100).toDP(2)
196
- .toString();
197
- const borrowedUsd = new Dec(borrowed).mul(assetAavePrice).toString();
198
-
199
- payload.usedAssets[symbol] = {
200
- symbol,
201
- supplied,
202
- suppliedP2P,
203
- suppliedPool,
204
- suppliedMatched,
205
- borrowed,
206
- borrowedP2P,
207
- borrowedPool,
208
- borrowedMatched,
209
- suppliedUsd: new Dec(supplied).mul(assetAavePrice).toString(),
210
- suppliedP2PUsd: new Dec(suppliedP2P).mul(assetAavePrice).toString(),
211
- suppliedPoolUsd: new Dec(suppliedPool).mul(assetAavePrice).toString(),
212
- borrowedUsd,
213
- borrowedP2PUsd: new Dec(borrowedP2P).mul(assetAavePrice).toString(),
214
- borrowedPoolUsd: new Dec(borrowedPool).mul(assetAavePrice).toString(),
215
- borrowedVariable: borrowed,
216
- borrowedUsdVariable: borrowedUsd,
217
- isSupplied: new Dec(supplied).gt(0),
218
- isBorrowed: new Dec(borrowed).gt(0),
219
- supplyRate: aprToApy(new Dec(market.userSupplyRate).div(1e25).toString()),
220
- borrowRate: aprToApy(new Dec(market.userBorrowRate).div(1e25).toString()),
221
- limit: '0',
222
-
223
- collateral: true, // Morpho doesn't have all these, keeping it for compatability
224
- eModeCategory: 0,
225
- interestMode: '',
226
- stableBorrowRate: '0',
227
- borrowedStable: '0',
228
- borrowedUsdStable: '0',
229
- stableLimit: '0',
230
- variableLimit: '0',
231
- };
232
- });
233
-
234
- payload = {
235
- ...payload,
236
- ...aaveAnyGetAggregatedPositionData({
237
- usedAssets: payload.usedAssets, assetsData, eModeCategory: 0, selectedMarket: { value: AaveVersions.MorphoAaveV2 },
238
- }),
239
- };
240
-
241
- // Calculate borrow limits per asset
242
- Object.values(payload.usedAssets).forEach((item) => {
243
- if (item.isBorrowed) {
244
- // eslint-disable-next-line no-param-reassign
245
- item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
246
- }
247
- });
248
-
249
- return payload;
250
- };
251
-
252
- export const getMorphoAaveV2FullPositionData = async (web3: Web3, network: NetworkNumber, address: string, mainnetWeb3: Web3): Promise<MorphoAaveV2PositionData> => {
253
- const marketData = await getMorphoAaveV2MarketsData(web3, network, mainnetWeb3);
254
- const positionData = await getMorphoAaveV2AccountData(web3, network, address, marketData.assetsData);
255
- return positionData;
256
- };
1
+ import { assetAmountInEth, getAssetInfoByAddress } from '@defisaver/tokens';
2
+ import Dec from 'decimal.js';
3
+ import Web3 from 'web3';
4
+ import { wethToEthByAddress } from '../services/utils';
5
+ import {
6
+ Blockish, EthAddress, NetworkNumber, PositionBalances,
7
+ } from '../types/common';
8
+ import { getStETHApy } from '../staking';
9
+ import { MorphoAaveV2ViewContract } from '../contracts';
10
+ import {
11
+ AavePositionData,
12
+ AaveVersions, MorphoAaveV2AssetData, MorphoAaveV2AssetsData, MorphoAaveV2MarketData, MorphoAaveV2PositionData,
13
+ } from '../types';
14
+ import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
15
+ import { EMPTY_AAVE_DATA } from '../aaveV3';
16
+ import { aaveAnyGetAggregatedPositionData } from '../helpers/aaveHelpers';
17
+ import { getEthPrice } from '../services/priceService';
18
+
19
+ export const getMorphoAaveV2MarketsData = async (web3: Web3, network: NetworkNumber, mainnetWeb3: Web3): Promise<MorphoAaveV2MarketData> => {
20
+ const ethPrice = await getEthPrice(web3);
21
+ const morphoAaveV2ViewContract = MorphoAaveV2ViewContract(web3, network);
22
+
23
+ const [contractData, morphoRewardsRes] = await Promise.allSettled([
24
+ morphoAaveV2ViewContract.methods.getAllMarketsInfo().call(),
25
+ fetch('https://api.morpho.xyz/rewards/distribution'),
26
+ ]);
27
+
28
+ if (contractData.status !== 'fulfilled') {
29
+ throw new Error('Failed to fetch market data.');
30
+ }
31
+
32
+ const { marketInfo, aaveTokenInfo } = contractData.value;
33
+
34
+ const morphoRewardsData = morphoRewardsRes.status === 'fulfilled' ? await morphoRewardsRes.value.json() : null;
35
+
36
+ const assetsData: MorphoAaveV2AssetData[] = marketInfo.map((market, index) => {
37
+ const aaveInfo = aaveTokenInfo[index];
38
+ const { symbol, address } = getAssetInfoByAddress(wethToEthByAddress(aaveInfo.underlyingTokenAddress));
39
+
40
+ const morphoReward = morphoRewardsData?.markets?.[aaveInfo.aTokenAddress.toLowerCase()];
41
+
42
+ const supplyRateP2P = aprToApy(new Dec(market.p2pSupplyRate).div(1e25).toString());
43
+ const borrowRateP2P = aprToApy(new Dec(market.p2pBorrowRate).div(1e25).toString());
44
+ const hasDelta = new Dec(borrowRateP2P).minus(supplyRateP2P).gte(0.3);
45
+
46
+ return {
47
+ symbol,
48
+ hasDelta,
49
+ aTokenAddress: aaveInfo.aTokenAddress,
50
+ underlyingTokenAddress: address,
51
+ priceInEth: new Dec(aaveInfo.price).div(1e18).toString(),
52
+ price: new Dec(aaveInfo.price).div(1e18).times(ethPrice).toString(),
53
+
54
+ supplyRate: aprToApy(new Dec(market.poolSupplyRate).div(1e25).toString()),
55
+ supplyRateP2P,
56
+ borrowRate: aprToApy(new Dec(market.poolBorrowRate).div(1e25).toString()),
57
+ borrowRateP2P,
58
+
59
+ totalSupply: assetAmountInEth(aaveInfo.totalSupply, symbol),
60
+ totalBorrow: assetAmountInEth(aaveInfo.totalBorrow, symbol),
61
+ totalSupplyP2P: assetAmountInEth(market.p2pSupplyAmount, symbol),
62
+ totalSupplyPool: assetAmountInEth(market.poolSupplyAmount, symbol),
63
+ totalBorrowP2P: assetAmountInEth(market.p2pBorrowAmount, symbol),
64
+ totalBorrowPool: assetAmountInEth(market.poolBorrowAmount, symbol),
65
+
66
+ collateralFactor: new Dec(aaveInfo.collateralFactor).div(10000).toString(),
67
+ liquidationRatio: new Dec(aaveInfo.liquidationRatio).div(10000).toString(),
68
+
69
+ isInactive: !aaveInfo.isActive,
70
+ isFrozen: aaveInfo.isFrozen,
71
+ canBeBorrowed:
72
+ aaveInfo.borrowingEnabled
73
+ && !aaveInfo.isFrozen
74
+ && !(market.pauseStatus.isBorrowPaused || market.pauseStatus.isDeprecated),
75
+ canBeWithdrawn: !market.pauseStatus.isWithdrawPaused,
76
+ canBePayBacked: !market.pauseStatus.isRepayPaused,
77
+ canBeSupplied: !aaveInfo.isFrozen && !(market.pauseStatus.isSupplyPaused || market.pauseStatus.isDeprecated),
78
+
79
+ reserveFactor: market.reserveFactor,
80
+ pauseStatus: market.pauseStatus,
81
+
82
+ incentiveSupplyToken: 'MORPHO',
83
+ incentiveBorrowToken: 'MORPHO',
84
+ incentiveSupplyApy: new Dec(morphoReward?.supplyRate || 0).div(1e18).toString(),
85
+ incentiveBorrowApy: new Dec(morphoReward?.borrowRate || 0).div(1e18).toString(),
86
+
87
+ marketLiquidity: assetAmountInEth(new Dec(aaveInfo.totalSupply.toString())
88
+ .sub(aaveInfo.totalBorrow.toString())
89
+ .toString(), symbol),
90
+ utilization: new Dec(aaveInfo.totalBorrow.toString())
91
+ .div(new Dec(aaveInfo.totalSupply.toString()))
92
+ .times(100)
93
+ .toString(),
94
+
95
+ totalBorrowVar: '0', // Morpho doesn't have all these, keeping it for compatability
96
+ usageAsCollateralEnabled: false,
97
+ disabledStableBorrowing: false,
98
+ borrowRateStable: '0',
99
+ supplyCap: '0', // V2 doesn't have borrow/supply cap but adding it for compatability with V3
100
+ borrowCap: '0',
101
+ };
102
+ });
103
+
104
+ const stEthMarket = assetsData.find(({ symbol }) => symbol === 'stETH');
105
+ if (stEthMarket) {
106
+ stEthMarket.incentiveSupplyApy = await getStETHApy(mainnetWeb3);
107
+ stEthMarket.incentiveSupplyToken = 'stETH';
108
+ }
109
+
110
+ const payload: MorphoAaveV2AssetsData = {};
111
+ // Sort by market size
112
+ assetsData
113
+ .sort((a, b) => {
114
+ const aMarket = new Dec(a.price).times(a.totalSupply).toString();
115
+ const bMarket = new Dec(b.price).times(b.totalSupply).toString();
116
+
117
+ return new Dec(bMarket).minus(aMarket).toNumber();
118
+ })
119
+ .forEach((assetData: MorphoAaveV2AssetData, i: number) => {
120
+ payload[assetData.symbol] = { ...assetData, sortIndex: i };
121
+ });
122
+
123
+ return { assetsData: payload };
124
+ };
125
+
126
+ export const getMorphoAaveV2AccountBalances = async (web3: Web3, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
127
+ let balances: PositionBalances = {
128
+ collateral: {},
129
+ debt: {},
130
+ };
131
+
132
+ if (!address) {
133
+ return balances;
134
+ }
135
+
136
+ const morphoAaveV2ViewContract = MorphoAaveV2ViewContract(web3, network, block);
137
+
138
+ const { userBalances } = await morphoAaveV2ViewContract.methods.getUserInfo(address).call({}, block);
139
+
140
+ if (userBalances.length === 0) {
141
+ return balances;
142
+ }
143
+
144
+ userBalances.forEach((balance: any) => {
145
+ const assetAddr = wethToEthByAddress(balance.underlying, network).toLowerCase();
146
+ const { symbol } = getAssetInfoByAddress(assetAddr, network);
147
+
148
+ balances = {
149
+ collateral: {
150
+ ...balances.collateral,
151
+ [addressMapping ? assetAddr : symbol]: new Dec(balance.supplyBalanceInP2P).add(balance.supplyBalanceOnPool).toString(),
152
+ },
153
+ debt: {
154
+ ...balances.debt,
155
+ [addressMapping ? assetAddr : symbol]: new Dec(balance.borrowBalanceInP2P).add(balance.borrowBalanceOnPool).toString(),
156
+ },
157
+ };
158
+ });
159
+
160
+ return balances;
161
+ };
162
+
163
+ export const getMorphoAaveV2AccountData = async (web3: Web3, network: NetworkNumber, address: string, assetsData: MorphoAaveV2AssetsData): Promise<MorphoAaveV2PositionData> => {
164
+ if (!address) {
165
+ throw new Error('Address is required.');
166
+ }
167
+
168
+ let payload: MorphoAaveV2PositionData = {
169
+ ...EMPTY_AAVE_DATA,
170
+ usedAssets: {},
171
+ minRatio: '100',
172
+ lastUpdated: Date.now(),
173
+ };
174
+
175
+ const morphoAaveV2ViewContract = MorphoAaveV2ViewContract(web3, network);
176
+
177
+ const { userBalances } = await morphoAaveV2ViewContract.methods.getUserInfo(address).call();
178
+
179
+ if (userBalances.length === 0) {
180
+ return payload;
181
+ }
182
+
183
+ userBalances.forEach((market) => {
184
+ const { symbol } = getAssetInfoByAddress(wethToEthByAddress(market.underlying));
185
+ const suppliedP2P = assetAmountInEth(market.supplyBalanceInP2P, symbol);
186
+ const suppliedPool = assetAmountInEth(market.supplyBalanceOnPool, symbol);
187
+ const supplied = new Dec(suppliedP2P).add(suppliedPool).toString();
188
+ const suppliedMatched = new Dec(suppliedP2P).div(supplied).mul(100).toDP(2)
189
+ .toString();
190
+
191
+ const assetAavePrice = assetsData[symbol].price;
192
+ const borrowedP2P = assetAmountInEth(market.borrowBalanceInP2P, symbol);
193
+ const borrowedPool = assetAmountInEth(market.borrowBalanceOnPool, symbol);
194
+ const borrowed = new Dec(borrowedP2P).add(borrowedPool).toString();
195
+ const borrowedMatched = new Dec(borrowedP2P).div(borrowed).mul(100).toDP(2)
196
+ .toString();
197
+ const borrowedUsd = new Dec(borrowed).mul(assetAavePrice).toString();
198
+
199
+ payload.usedAssets[symbol] = {
200
+ symbol,
201
+ supplied,
202
+ suppliedP2P,
203
+ suppliedPool,
204
+ suppliedMatched,
205
+ borrowed,
206
+ borrowedP2P,
207
+ borrowedPool,
208
+ borrowedMatched,
209
+ suppliedUsd: new Dec(supplied).mul(assetAavePrice).toString(),
210
+ suppliedP2PUsd: new Dec(suppliedP2P).mul(assetAavePrice).toString(),
211
+ suppliedPoolUsd: new Dec(suppliedPool).mul(assetAavePrice).toString(),
212
+ borrowedUsd,
213
+ borrowedP2PUsd: new Dec(borrowedP2P).mul(assetAavePrice).toString(),
214
+ borrowedPoolUsd: new Dec(borrowedPool).mul(assetAavePrice).toString(),
215
+ borrowedVariable: borrowed,
216
+ borrowedUsdVariable: borrowedUsd,
217
+ isSupplied: new Dec(supplied).gt(0),
218
+ isBorrowed: new Dec(borrowed).gt(0),
219
+ supplyRate: aprToApy(new Dec(market.userSupplyRate).div(1e25).toString()),
220
+ borrowRate: aprToApy(new Dec(market.userBorrowRate).div(1e25).toString()),
221
+ limit: '0',
222
+
223
+ collateral: true, // Morpho doesn't have all these, keeping it for compatability
224
+ eModeCategory: 0,
225
+ interestMode: '',
226
+ stableBorrowRate: '0',
227
+ borrowedStable: '0',
228
+ borrowedUsdStable: '0',
229
+ stableLimit: '0',
230
+ variableLimit: '0',
231
+ };
232
+ });
233
+
234
+ payload = {
235
+ ...payload,
236
+ ...aaveAnyGetAggregatedPositionData({
237
+ usedAssets: payload.usedAssets, assetsData, eModeCategory: 0, selectedMarket: { value: AaveVersions.MorphoAaveV2 },
238
+ }),
239
+ };
240
+
241
+ // Calculate borrow limits per asset
242
+ Object.values(payload.usedAssets).forEach((item) => {
243
+ if (item.isBorrowed) {
244
+ // eslint-disable-next-line no-param-reassign
245
+ item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
246
+ }
247
+ });
248
+
249
+ return payload;
250
+ };
251
+
252
+ export const getMorphoAaveV2FullPositionData = async (web3: Web3, network: NetworkNumber, address: string, mainnetWeb3: Web3): Promise<MorphoAaveV2PositionData> => {
253
+ const marketData = await getMorphoAaveV2MarketsData(web3, network, mainnetWeb3);
254
+ const positionData = await getMorphoAaveV2AccountData(web3, network, address, marketData.assetsData);
255
+ return positionData;
256
+ };