@defisaver/positions-sdk 0.0.30 → 0.0.32

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 (113) hide show
  1. package/README.md +63 -63
  2. package/cjs/config/contracts.d.ts +115 -0
  3. package/cjs/config/contracts.js +14 -0
  4. package/cjs/constants/index.d.ts +2 -0
  5. package/cjs/constants/index.js +3 -1
  6. package/cjs/contracts.d.ts +2 -0
  7. package/cjs/contracts.js +3 -1
  8. package/cjs/helpers/index.d.ts +1 -0
  9. package/cjs/helpers/index.js +2 -1
  10. package/cjs/helpers/morphoBlueHelpers/index.d.ts +7 -0
  11. package/cjs/helpers/morphoBlueHelpers/index.js +41 -0
  12. package/cjs/index.d.ts +2 -1
  13. package/cjs/index.js +3 -1
  14. package/cjs/markets/index.d.ts +1 -0
  15. package/cjs/markets/index.js +3 -1
  16. package/cjs/markets/morphoBlue/index.d.ts +6 -0
  17. package/cjs/markets/morphoBlue/index.js +24 -0
  18. package/cjs/morphoBlue/index.d.ts +5 -0
  19. package/cjs/morphoBlue/index.js +153 -0
  20. package/cjs/types/common.d.ts +1 -1
  21. package/cjs/types/contracts/generated/FeedRegistry.d.ts +182 -0
  22. package/cjs/types/contracts/generated/FeedRegistry.js +5 -0
  23. package/cjs/types/contracts/generated/MorphoBlueView.d.ts +122 -0
  24. package/cjs/types/contracts/generated/MorphoBlueView.js +5 -0
  25. package/cjs/types/contracts/generated/index.d.ts +2 -0
  26. package/cjs/types/index.d.ts +1 -0
  27. package/cjs/types/index.js +1 -0
  28. package/cjs/types/morphoBlue.d.ts +74 -0
  29. package/cjs/types/morphoBlue.js +7 -0
  30. package/esm/config/contracts.d.ts +115 -0
  31. package/esm/config/contracts.js +14 -0
  32. package/esm/constants/index.d.ts +2 -0
  33. package/esm/constants/index.js +2 -0
  34. package/esm/contracts.d.ts +2 -0
  35. package/esm/contracts.js +2 -0
  36. package/esm/helpers/index.d.ts +1 -0
  37. package/esm/helpers/index.js +1 -0
  38. package/esm/helpers/morphoBlueHelpers/index.d.ts +7 -0
  39. package/esm/helpers/morphoBlueHelpers/index.js +34 -0
  40. package/esm/index.d.ts +2 -1
  41. package/esm/index.js +2 -1
  42. package/esm/markets/index.d.ts +1 -0
  43. package/esm/markets/index.js +1 -0
  44. package/esm/markets/morphoBlue/index.d.ts +6 -0
  45. package/esm/markets/morphoBlue/index.js +19 -0
  46. package/esm/morphoBlue/index.d.ts +5 -0
  47. package/esm/morphoBlue/index.js +145 -0
  48. package/esm/types/common.d.ts +1 -1
  49. package/esm/types/contracts/generated/FeedRegistry.d.ts +182 -0
  50. package/esm/types/contracts/generated/FeedRegistry.js +4 -0
  51. package/esm/types/contracts/generated/MorphoBlueView.d.ts +122 -0
  52. package/esm/types/contracts/generated/MorphoBlueView.js +4 -0
  53. package/esm/types/contracts/generated/index.d.ts +2 -0
  54. package/esm/types/index.d.ts +1 -0
  55. package/esm/types/index.js +1 -0
  56. package/esm/types/morphoBlue.d.ts +74 -0
  57. package/esm/types/morphoBlue.js +4 -0
  58. package/package.json +40 -40
  59. package/src/aaveV2/index.ts +226 -226
  60. package/src/aaveV3/index.ts +561 -561
  61. package/src/assets/index.ts +60 -60
  62. package/src/chickenBonds/index.ts +123 -123
  63. package/src/compoundV2/index.ts +219 -219
  64. package/src/compoundV3/index.ts +275 -275
  65. package/src/config/contracts.js +690 -676
  66. package/src/constants/index.ts +6 -4
  67. package/src/contracts.ts +131 -127
  68. package/src/curveUsd/index.ts +228 -228
  69. package/src/exchange/index.ts +17 -17
  70. package/src/helpers/aaveHelpers/index.ts +134 -134
  71. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  72. package/src/helpers/compoundHelpers/index.ts +181 -181
  73. package/src/helpers/curveUsdHelpers/index.ts +32 -32
  74. package/src/helpers/index.ts +7 -6
  75. package/src/helpers/makerHelpers/index.ts +94 -94
  76. package/src/helpers/morphoBlueHelpers/index.ts +47 -0
  77. package/src/helpers/sparkHelpers/index.ts +106 -106
  78. package/src/index.ts +42 -40
  79. package/src/liquity/index.ts +116 -116
  80. package/src/maker/index.ts +101 -101
  81. package/src/markets/aave/index.ts +80 -80
  82. package/src/markets/aave/marketAssets.ts +24 -24
  83. package/src/markets/compound/index.ts +141 -141
  84. package/src/markets/compound/marketsAssets.ts +48 -48
  85. package/src/markets/curveUsd/index.ts +69 -69
  86. package/src/markets/index.ts +5 -4
  87. package/src/markets/morphoBlue/index.ts +21 -0
  88. package/src/markets/spark/index.ts +29 -29
  89. package/src/markets/spark/marketAssets.ts +10 -10
  90. package/src/moneymarket/moneymarketCommonService.ts +75 -75
  91. package/src/morphoAaveV2/index.ts +255 -255
  92. package/src/morphoAaveV3/index.ts +619 -619
  93. package/src/morphoBlue/index.ts +166 -0
  94. package/src/multicall/index.ts +22 -22
  95. package/src/services/dsrService.ts +15 -15
  96. package/src/services/priceService.ts +21 -21
  97. package/src/services/utils.ts +34 -34
  98. package/src/spark/index.ts +422 -422
  99. package/src/staking/staking.ts +167 -167
  100. package/src/types/aave.ts +256 -256
  101. package/src/types/chickenBonds.ts +45 -45
  102. package/src/types/common.ts +83 -83
  103. package/src/types/compound.ts +128 -128
  104. package/src/types/contracts/generated/FeedRegistry.ts +337 -0
  105. package/src/types/contracts/generated/MorphoBlueView.ts +171 -0
  106. package/src/types/contracts/generated/index.ts +2 -0
  107. package/src/types/curveUsd.ts +112 -112
  108. package/src/types/index.ts +8 -7
  109. package/src/types/liquity.ts +30 -30
  110. package/src/types/maker.ts +50 -50
  111. package/src/types/morphoBlue.ts +80 -0
  112. package/src/types/spark.ts +106 -106
  113. package/src/morpho/markets.ts +0 -39
@@ -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 { 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;
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;
256
256
  };