@defisaver/positions-sdk 0.0.20 → 0.0.22

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 (99) hide show
  1. package/README.md +63 -0
  2. package/cjs/aaveV2/index.js +9 -4
  3. package/cjs/aaveV3/index.js +9 -4
  4. package/cjs/compoundV2/index.d.ts +1 -0
  5. package/cjs/compoundV2/index.js +15 -8
  6. package/cjs/config/contracts.d.ts +373 -201
  7. package/cjs/config/contracts.js +22 -0
  8. package/cjs/helpers/aaveHelpers/index.js +0 -5
  9. package/cjs/helpers/compoundHelpers/index.js +2 -2
  10. package/cjs/markets/compound/index.d.ts +2 -0
  11. package/cjs/markets/compound/index.js +60 -13
  12. package/cjs/markets/compound/marketsAssets.d.ts +7 -1
  13. package/cjs/markets/compound/marketsAssets.js +12 -2
  14. package/cjs/morphoAaveV2/index.js +4 -3
  15. package/cjs/morphoAaveV3/index.js +9 -4
  16. package/cjs/spark/index.js +9 -4
  17. package/cjs/types/aave.d.ts +0 -5
  18. package/cjs/types/compound.d.ts +6 -4
  19. package/cjs/types/compound.js +1 -0
  20. package/cjs/types/contracts/generated/CUSDCev3.d.ts +441 -0
  21. package/cjs/types/contracts/generated/CUSDCev3.js +5 -0
  22. package/cjs/types/contracts/generated/CompV3USDCBulkerArb.d.ts +41 -0
  23. package/cjs/types/contracts/generated/CompV3USDCBulkerArb.js +5 -0
  24. package/cjs/types/contracts/generated/index.d.ts +2 -0
  25. package/esm/aaveV2/index.js +11 -6
  26. package/esm/aaveV3/index.js +11 -6
  27. package/esm/compoundV2/index.d.ts +1 -0
  28. package/esm/compoundV2/index.js +13 -7
  29. package/esm/config/contracts.d.ts +373 -201
  30. package/esm/config/contracts.js +22 -0
  31. package/esm/helpers/aaveHelpers/index.js +0 -5
  32. package/esm/helpers/compoundHelpers/index.js +2 -2
  33. package/esm/markets/compound/index.d.ts +2 -0
  34. package/esm/markets/compound/index.js +59 -13
  35. package/esm/markets/compound/marketsAssets.d.ts +7 -1
  36. package/esm/markets/compound/marketsAssets.js +11 -1
  37. package/esm/morphoAaveV2/index.js +4 -3
  38. package/esm/morphoAaveV3/index.js +9 -4
  39. package/esm/spark/index.js +11 -6
  40. package/esm/types/aave.d.ts +0 -5
  41. package/esm/types/compound.d.ts +6 -4
  42. package/esm/types/compound.js +1 -0
  43. package/esm/types/contracts/generated/CUSDCev3.d.ts +441 -0
  44. package/esm/types/contracts/generated/CUSDCev3.js +4 -0
  45. package/esm/types/contracts/generated/CompV3USDCBulkerArb.d.ts +41 -0
  46. package/esm/types/contracts/generated/CompV3USDCBulkerArb.js +4 -0
  47. package/esm/types/contracts/generated/index.d.ts +2 -0
  48. package/package.json +40 -40
  49. package/src/aaveV2/index.ts +226 -220
  50. package/src/aaveV3/index.ts +561 -554
  51. package/src/assets/index.ts +60 -60
  52. package/src/chickenBonds/index.ts +123 -123
  53. package/src/compoundV2/index.ts +219 -206
  54. package/src/compoundV3/index.ts +275 -275
  55. package/src/config/contracts.js +673 -651
  56. package/src/constants/index.ts +3 -3
  57. package/src/contracts.ts +100 -100
  58. package/src/curveUsd/index.ts +228 -228
  59. package/src/exchange/index.ts +17 -17
  60. package/src/helpers/aaveHelpers/index.ts +134 -141
  61. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  62. package/src/helpers/compoundHelpers/index.ts +181 -181
  63. package/src/helpers/curveUsdHelpers/index.ts +32 -32
  64. package/src/helpers/index.ts +5 -5
  65. package/src/helpers/makerHelpers/index.ts +94 -94
  66. package/src/helpers/sparkHelpers/index.ts +106 -106
  67. package/src/index.ts +40 -40
  68. package/src/liquity/index.ts +116 -116
  69. package/src/maker/index.ts +101 -101
  70. package/src/markets/aave/index.ts +80 -80
  71. package/src/markets/aave/marketAssets.ts +32 -32
  72. package/src/markets/compound/index.ts +141 -85
  73. package/src/markets/compound/marketsAssets.ts +46 -35
  74. package/src/markets/curveUsd/index.ts +69 -69
  75. package/src/markets/index.ts +3 -3
  76. package/src/markets/spark/index.ts +29 -29
  77. package/src/markets/spark/marketAssets.ts +9 -9
  78. package/src/moneymarket/moneymarketCommonService.ts +75 -75
  79. package/src/morpho/markets.ts +39 -39
  80. package/src/morphoAaveV2/index.ts +255 -254
  81. package/src/morphoAaveV3/index.ts +619 -614
  82. package/src/multicall/index.ts +22 -22
  83. package/src/services/dsrService.ts +15 -15
  84. package/src/services/priceService.ts +21 -21
  85. package/src/services/utils.ts +34 -34
  86. package/src/spark/index.ts +421 -413
  87. package/src/staking/staking.ts +167 -167
  88. package/src/types/aave.ts +256 -261
  89. package/src/types/chickenBonds.ts +45 -45
  90. package/src/types/common.ts +83 -83
  91. package/src/types/compound.ts +128 -122
  92. package/src/types/contracts/generated/CUSDCev3.ts +685 -0
  93. package/src/types/contracts/generated/CompV3USDCBulkerArb.ts +85 -0
  94. package/src/types/contracts/generated/index.ts +2 -0
  95. package/src/types/curveUsd.ts +112 -112
  96. package/src/types/index.ts +6 -6
  97. package/src/types/liquity.ts +30 -30
  98. package/src/types/maker.ts +50 -50
  99. package/src/types/spark.ts +106 -106
@@ -1,255 +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 { getStETHApr } from '../staking';
9
- import { MorphoAaveV2ViewContract } from '../contracts';
10
- import {
11
- AavePositionData,
12
- AaveVersions, MorphoAaveV2AssetData, MorphoAaveV2AssetsData, MorphoAaveV2MarketData, MorphoAaveV2PositionData,
13
- } from '../types';
14
- import { 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(mainnetWeb3);
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 = new Dec(market.p2pSupplyRate).div(1e25).toString();
43
- const borrowRateP2P = 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: new Dec(market.poolSupplyRate).div(1e25).toString(),
55
- supplyRateP2P,
56
- borrowRate: 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 getStETHApr(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 { symbol, address: assetAddr } = getAssetInfoByAddress(wethToEthByAddress(balance.underlying, network), network);
146
-
147
- balances = {
148
- collateral: {
149
- ...balances.collateral,
150
- [addressMapping ? assetAddr.toLowerCase() : symbol]: new Dec(balance.supplyBalanceInP2P).add(balance.supplyBalanceOnPool).toString(),
151
- },
152
- debt: {
153
- ...balances.debt,
154
- [addressMapping ? assetAddr.toLowerCase() : symbol]: new Dec(balance.borrowBalanceInP2P).add(balance.borrowBalanceOnPool).toString(),
155
- },
156
- };
157
- });
158
-
159
- return balances;
160
- };
161
-
162
- export const getMorphoAaveV2AccountData = async (web3: Web3, network: NetworkNumber, address: string, assetsData: MorphoAaveV2AssetsData): Promise<MorphoAaveV2PositionData> => {
163
- if (!address) {
164
- throw new Error('Address is required.');
165
- }
166
-
167
- let payload: MorphoAaveV2PositionData = {
168
- ...EMPTY_AAVE_DATA,
169
- usedAssets: {},
170
- minRatio: '100',
171
- lastUpdated: Date.now(),
172
- };
173
-
174
- const morphoAaveV2ViewContract = MorphoAaveV2ViewContract(web3, network);
175
-
176
- const { userBalances } = await morphoAaveV2ViewContract.methods.getUserInfo(address).call();
177
-
178
- if (userBalances.length === 0) {
179
- return payload;
180
- }
181
-
182
- userBalances.forEach((market) => {
183
- const { symbol } = getAssetInfoByAddress(wethToEthByAddress(market.underlying));
184
- const suppliedP2P = assetAmountInEth(market.supplyBalanceInP2P, symbol);
185
- const suppliedPool = assetAmountInEth(market.supplyBalanceOnPool, symbol);
186
- const supplied = new Dec(suppliedP2P).add(suppliedPool).toString();
187
- const suppliedMatched = new Dec(suppliedP2P).div(supplied).mul(100).toDP(2)
188
- .toString();
189
-
190
- const assetAavePrice = assetsData[symbol].price;
191
- const borrowedP2P = assetAmountInEth(market.borrowBalanceInP2P, symbol);
192
- const borrowedPool = assetAmountInEth(market.borrowBalanceOnPool, symbol);
193
- const borrowed = new Dec(borrowedP2P).add(borrowedPool).toString();
194
- const borrowedMatched = new Dec(borrowedP2P).div(borrowed).mul(100).toDP(2)
195
- .toString();
196
- const borrowedUsd = new Dec(borrowed).mul(assetAavePrice).toString();
197
-
198
- payload.usedAssets[symbol] = {
199
- symbol,
200
- supplied,
201
- suppliedP2P,
202
- suppliedPool,
203
- suppliedMatched,
204
- borrowed,
205
- borrowedP2P,
206
- borrowedPool,
207
- borrowedMatched,
208
- suppliedUsd: new Dec(supplied).mul(assetAavePrice).toString(),
209
- suppliedP2PUsd: new Dec(suppliedP2P).mul(assetAavePrice).toString(),
210
- suppliedPoolUsd: new Dec(suppliedPool).mul(assetAavePrice).toString(),
211
- borrowedUsd,
212
- borrowedP2PUsd: new Dec(borrowedP2P).mul(assetAavePrice).toString(),
213
- borrowedPoolUsd: new Dec(borrowedPool).mul(assetAavePrice).toString(),
214
- borrowedVariable: borrowed,
215
- borrowedUsdVariable: borrowedUsd,
216
- isSupplied: new Dec(supplied).gt(0),
217
- isBorrowed: new Dec(borrowed).gt(0),
218
- supplyRate: new Dec(market.userSupplyRate).div(1e25).toString(),
219
- borrowRate: new Dec(market.userBorrowRate).div(1e25).toString(),
220
- limit: '0',
221
-
222
- collateral: true, // Morpho doesn't have all these, keeping it for compatability
223
- eModeCategory: 0,
224
- interestMode: '',
225
- stableBorrowRate: '0',
226
- borrowedStable: '0',
227
- borrowedUsdStable: '0',
228
- stableLimit: '0',
229
- variableLimit: '0',
230
- };
231
- });
232
-
233
- payload = {
234
- ...payload,
235
- ...aaveAnyGetAggregatedPositionData({
236
- usedAssets: payload.usedAssets, assetsData, eModeCategory: 0, selectedMarket: { value: AaveVersions.MorphoAaveV2 },
237
- }),
238
- };
239
-
240
- // Calculate borrow limits per asset
241
- Object.values(payload.usedAssets).forEach((item) => {
242
- if (item.isBorrowed) {
243
- // eslint-disable-next-line no-param-reassign
244
- item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
245
- }
246
- });
247
-
248
- return payload;
249
- };
250
-
251
- export const getMorphoAaveV2FullPositionData = async (web3: Web3, network: NetworkNumber, address: string, mainnetWeb3: Web3): Promise<MorphoAaveV2PositionData> => {
252
- const marketData = await getMorphoAaveV2MarketsData(web3, network, mainnetWeb3);
253
- const positionData = await getMorphoAaveV2AccountData(web3, network, address, marketData.assetsData);
254
- return positionData;
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 { getStETHApr } from '../staking';
9
+ import { MorphoAaveV2ViewContract } from '../contracts';
10
+ import {
11
+ AavePositionData,
12
+ AaveVersions, MorphoAaveV2AssetData, MorphoAaveV2AssetsData, MorphoAaveV2MarketData, MorphoAaveV2PositionData,
13
+ } from '../types';
14
+ import { 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(mainnetWeb3);
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 = new Dec(market.p2pSupplyRate).div(1e25).toString();
43
+ const borrowRateP2P = 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: new Dec(market.poolSupplyRate).div(1e25).toString(),
55
+ supplyRateP2P,
56
+ borrowRate: 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 getStETHApr(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: new Dec(market.userSupplyRate).div(1e25).toString(),
220
+ borrowRate: 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;
255
256
  };