@defisaver/positions-sdk 0.0.16 → 0.0.17

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 (83) hide show
  1. package/cjs/compoundV3/index.d.ts +1 -1
  2. package/cjs/compoundV3/index.js +3 -2
  3. package/cjs/config/contracts.d.ts +72 -184
  4. package/cjs/config/contracts.js +0 -16
  5. package/cjs/helpers/compoundHelpers/index.js +2 -2
  6. package/cjs/markets/curveUsd/index.d.ts +0 -2
  7. package/cjs/markets/curveUsd/index.js +1 -14
  8. package/cjs/types/compound.d.ts +1 -0
  9. package/cjs/types/contracts/generated/index.d.ts +0 -2
  10. package/cjs/types/curveUsd.d.ts +1 -2
  11. package/cjs/types/curveUsd.js +0 -1
  12. package/esm/compoundV3/index.d.ts +1 -1
  13. package/esm/compoundV3/index.js +3 -2
  14. package/esm/config/contracts.d.ts +72 -184
  15. package/esm/config/contracts.js +0 -16
  16. package/esm/helpers/compoundHelpers/index.js +2 -2
  17. package/esm/markets/curveUsd/index.d.ts +0 -2
  18. package/esm/markets/curveUsd/index.js +0 -12
  19. package/esm/types/compound.d.ts +1 -0
  20. package/esm/types/contracts/generated/index.d.ts +0 -2
  21. package/esm/types/curveUsd.d.ts +1 -2
  22. package/esm/types/curveUsd.js +0 -1
  23. package/package.json +40 -40
  24. package/src/aaveV2/index.ts +220 -220
  25. package/src/aaveV3/index.ts +556 -556
  26. package/src/assets/index.ts +60 -60
  27. package/src/chickenBonds/index.ts +123 -123
  28. package/src/compoundV2/index.ts +206 -206
  29. package/src/compoundV3/index.ts +273 -269
  30. package/src/config/contracts.js +651 -651
  31. package/src/constants/index.ts +3 -3
  32. package/src/contracts.ts +100 -100
  33. package/src/curveUsd/index.ts +228 -228
  34. package/src/exchange/index.ts +17 -17
  35. package/src/helpers/aaveHelpers/index.ts +134 -134
  36. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  37. package/src/helpers/compoundHelpers/index.ts +181 -181
  38. package/src/helpers/curveUsdHelpers/index.ts +32 -32
  39. package/src/helpers/index.ts +5 -5
  40. package/src/helpers/makerHelpers/index.ts +94 -94
  41. package/src/helpers/sparkHelpers/index.ts +106 -106
  42. package/src/index.ts +40 -40
  43. package/src/liquity/index.ts +103 -103
  44. package/src/maker/index.ts +101 -101
  45. package/src/markets/aave/index.ts +80 -80
  46. package/src/markets/aave/marketAssets.ts +32 -32
  47. package/src/markets/compound/index.ts +85 -85
  48. package/src/markets/compound/marketsAssets.ts +35 -35
  49. package/src/markets/curveUsd/index.ts +69 -69
  50. package/src/markets/index.ts +3 -3
  51. package/src/markets/spark/index.ts +29 -29
  52. package/src/markets/spark/marketAssets.ts +9 -9
  53. package/src/moneymarket/moneymarketCommonService.ts +75 -75
  54. package/src/morpho/markets.ts +39 -39
  55. package/src/morphoAaveV2/index.ts +254 -254
  56. package/src/morphoAaveV3/index.ts +617 -617
  57. package/src/multicall/index.ts +22 -22
  58. package/src/services/dsrService.ts +15 -15
  59. package/src/services/priceService.ts +21 -21
  60. package/src/services/utils.ts +34 -34
  61. package/src/spark/index.ts +413 -413
  62. package/src/staking/staking.ts +167 -167
  63. package/src/types/aave.ts +256 -256
  64. package/src/types/chickenBonds.ts +45 -45
  65. package/src/types/common.ts +83 -83
  66. package/src/types/compound.ts +122 -121
  67. package/src/types/contracts/generated/index.ts +0 -2
  68. package/src/types/curveUsd.ts +112 -112
  69. package/src/types/index.ts +6 -6
  70. package/src/types/liquity.ts +29 -29
  71. package/src/types/maker.ts +50 -50
  72. package/src/types/spark.ts +106 -106
  73. package/cjs/types/contracts/generated/CrvUSDsfrxETHAmm.d.ts +0 -139
  74. package/cjs/types/contracts/generated/CrvUSDsfrxETHAmm.js +0 -5
  75. package/cjs/types/contracts/generated/CrvUSDsfrxETHController.d.ts +0 -205
  76. package/cjs/types/contracts/generated/CrvUSDsfrxETHController.js +0 -5
  77. package/esm/types/contracts/generated/CrvUSDsfrxETHAmm.d.ts +0 -139
  78. package/esm/types/contracts/generated/CrvUSDsfrxETHAmm.js +0 -4
  79. package/esm/types/contracts/generated/CrvUSDsfrxETHController.d.ts +0 -205
  80. package/esm/types/contracts/generated/CrvUSDsfrxETHController.js +0 -4
  81. package/src/types/contracts/generated/CrvUSDsfrxETHAmm.ts +0 -286
  82. package/src/types/contracts/generated/CrvUSDsfrxETHController.ts +0 -403
  83. package/yarn-error.log +0 -64
@@ -1,255 +1,255 @@
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 { 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;
255
255
  };