@defisaver/positions-sdk 0.0.198 → 0.0.199-dev-1

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 (133) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/README.md +69 -69
  4. package/cjs/config/contracts.d.ts +126 -4
  5. package/cjs/config/contracts.js +14 -0
  6. package/cjs/contracts.d.ts +1 -0
  7. package/cjs/contracts.js +2 -1
  8. package/cjs/helpers/index.d.ts +1 -0
  9. package/cjs/helpers/index.js +2 -1
  10. package/cjs/helpers/liquityV2Helpers/index.d.ts +12 -0
  11. package/cjs/helpers/liquityV2Helpers/index.js +63 -0
  12. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  13. package/cjs/index.d.ts +2 -1
  14. package/cjs/index.js +3 -1
  15. package/cjs/liquityV2/index.d.ts +18 -0
  16. package/cjs/liquityV2/index.js +186 -0
  17. package/cjs/markets/aave/marketAssets.js +2 -4
  18. package/cjs/markets/index.d.ts +1 -0
  19. package/cjs/markets/index.js +3 -1
  20. package/cjs/markets/liquityV2/index.d.ts +10 -0
  21. package/cjs/markets/liquityV2/index.js +47 -0
  22. package/cjs/moneymarket/moneymarketCommonService.js +1 -1
  23. package/cjs/types/contracts/generated/LiquityV2CollSurplusPool.d.ts +64 -0
  24. package/cjs/types/contracts/generated/LiquityV2CollSurplusPool.js +5 -0
  25. package/cjs/types/contracts/generated/LiquityV2TroveNFT.d.ts +73 -0
  26. package/cjs/types/contracts/generated/LiquityV2TroveNFT.js +5 -0
  27. package/cjs/types/contracts/generated/LiquityV2View.d.ts +244 -0
  28. package/cjs/types/contracts/generated/LiquityV2View.js +5 -0
  29. package/cjs/types/contracts/generated/index.d.ts +3 -0
  30. package/cjs/types/index.d.ts +1 -0
  31. package/cjs/types/index.js +1 -0
  32. package/cjs/types/liquityV2.d.ts +111 -0
  33. package/cjs/types/liquityV2.js +24 -0
  34. package/esm/config/contracts.d.ts +126 -4
  35. package/esm/config/contracts.js +14 -0
  36. package/esm/contracts.d.ts +1 -0
  37. package/esm/contracts.js +1 -0
  38. package/esm/helpers/index.d.ts +1 -0
  39. package/esm/helpers/index.js +1 -0
  40. package/esm/helpers/liquityV2Helpers/index.d.ts +12 -0
  41. package/esm/helpers/liquityV2Helpers/index.js +55 -0
  42. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  43. package/esm/index.d.ts +2 -1
  44. package/esm/index.js +2 -1
  45. package/esm/liquityV2/index.d.ts +18 -0
  46. package/esm/liquityV2/index.js +175 -0
  47. package/esm/markets/aave/marketAssets.js +2 -4
  48. package/esm/markets/index.d.ts +1 -0
  49. package/esm/markets/index.js +1 -0
  50. package/esm/markets/liquityV2/index.d.ts +10 -0
  51. package/esm/markets/liquityV2/index.js +40 -0
  52. package/esm/moneymarket/moneymarketCommonService.js +1 -1
  53. package/esm/types/contracts/generated/LiquityV2CollSurplusPool.d.ts +64 -0
  54. package/esm/types/contracts/generated/LiquityV2CollSurplusPool.js +4 -0
  55. package/esm/types/contracts/generated/LiquityV2TroveNFT.d.ts +73 -0
  56. package/esm/types/contracts/generated/LiquityV2TroveNFT.js +4 -0
  57. package/esm/types/contracts/generated/LiquityV2View.d.ts +244 -0
  58. package/esm/types/contracts/generated/LiquityV2View.js +4 -0
  59. package/esm/types/contracts/generated/index.d.ts +3 -0
  60. package/esm/types/index.d.ts +1 -0
  61. package/esm/types/index.js +1 -0
  62. package/esm/types/liquityV2.d.ts +111 -0
  63. package/esm/types/liquityV2.js +21 -0
  64. package/package.json +49 -49
  65. package/src/aaveV2/index.ts +227 -227
  66. package/src/aaveV3/index.ts +625 -625
  67. package/src/assets/index.ts +60 -60
  68. package/src/chickenBonds/index.ts +123 -123
  69. package/src/compoundV2/index.ts +220 -220
  70. package/src/compoundV3/index.ts +291 -291
  71. package/src/config/contracts.js +1109 -1095
  72. package/src/constants/index.ts +6 -6
  73. package/src/contracts.ts +133 -132
  74. package/src/curveUsd/index.ts +229 -229
  75. package/src/eulerV2/index.ts +303 -303
  76. package/src/exchange/index.ts +17 -17
  77. package/src/helpers/aaveHelpers/index.ts +198 -198
  78. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  79. package/src/helpers/compoundHelpers/index.ts +246 -246
  80. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  81. package/src/helpers/eulerHelpers/index.ts +232 -232
  82. package/src/helpers/index.ts +10 -9
  83. package/src/helpers/liquityV2Helpers/index.ts +80 -0
  84. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  85. package/src/helpers/makerHelpers/index.ts +94 -94
  86. package/src/helpers/morphoBlueHelpers/index.ts +365 -365
  87. package/src/helpers/sparkHelpers/index.ts +150 -150
  88. package/src/index.ts +50 -48
  89. package/src/liquity/index.ts +116 -116
  90. package/src/liquityV2/index.ts +219 -0
  91. package/src/llamaLend/index.ts +275 -275
  92. package/src/maker/index.ts +117 -117
  93. package/src/markets/aave/index.ts +152 -152
  94. package/src/markets/aave/marketAssets.ts +44 -46
  95. package/src/markets/compound/index.ts +213 -213
  96. package/src/markets/compound/marketsAssets.ts +82 -82
  97. package/src/markets/curveUsd/index.ts +69 -69
  98. package/src/markets/euler/index.ts +26 -26
  99. package/src/markets/index.ts +24 -24
  100. package/src/markets/liquityV2/index.ts +44 -0
  101. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  102. package/src/markets/llamaLend/index.ts +235 -235
  103. package/src/markets/morphoBlue/index.ts +895 -895
  104. package/src/markets/spark/index.ts +29 -29
  105. package/src/markets/spark/marketAssets.ts +10 -10
  106. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  107. package/src/morphoAaveV2/index.ts +256 -256
  108. package/src/morphoAaveV3/index.ts +631 -631
  109. package/src/morphoBlue/index.ts +204 -204
  110. package/src/multicall/index.ts +22 -22
  111. package/src/services/dsrService.ts +15 -15
  112. package/src/services/priceService.ts +62 -62
  113. package/src/services/utils.ts +56 -56
  114. package/src/setup.ts +8 -8
  115. package/src/spark/index.ts +461 -461
  116. package/src/staking/staking.ts +220 -220
  117. package/src/types/aave.ts +271 -271
  118. package/src/types/chickenBonds.ts +45 -45
  119. package/src/types/common.ts +84 -84
  120. package/src/types/compound.ts +131 -131
  121. package/src/types/contracts/generated/LiquityV2CollSurplusPool.ts +130 -0
  122. package/src/types/contracts/generated/LiquityV2TroveNFT.ts +150 -0
  123. package/src/types/contracts/generated/LiquityV2View.ts +315 -0
  124. package/src/types/contracts/generated/index.ts +3 -0
  125. package/src/types/curveUsd.ts +118 -118
  126. package/src/types/euler.ts +171 -171
  127. package/src/types/index.ts +10 -9
  128. package/src/types/liquity.ts +30 -30
  129. package/src/types/liquityV2.ts +119 -0
  130. package/src/types/llamaLend.ts +155 -155
  131. package/src/types/maker.ts +50 -50
  132. package/src/types/morphoBlue.ts +192 -192
  133. package/src/types/spark.ts +131 -131
@@ -1,461 +1,461 @@
1
- import Web3 from 'web3';
2
- import Dec from 'decimal.js';
3
- import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
4
- import {
5
- Blockish, EthAddress, NetworkNumber, PositionBalances,
6
- } from '../types/common';
7
- import {
8
- ethToWeth, getAbiItem, isLayer2Network, wethToEth, wethToEthByAddress,
9
- } from '../services/utils';
10
- import {
11
- calculateNetApy, getStakingApy, STAKING_ASSETS,
12
- } from '../staking';
13
- import { getDsrApy } from '../services/dsrService';
14
- import {
15
- SparkIncentiveDataProviderContract,
16
- SparkViewContract,
17
- getConfigContractAbi,
18
- createContractWrapper,
19
- } from '../contracts';
20
- import {
21
- SparkEModeCategoryDataMapping,
22
- SparkAssetData,
23
- SparkAssetsData,
24
- SparkMarketData,
25
- SparkMarketsData,
26
- SparkPositionData,
27
- SparkUsedAsset,
28
- SparkUsedAssets,
29
- } from '../types';
30
- import { multicall } from '../multicall';
31
- import { sparkGetAggregatedPositionData, sparkIsInIsolationMode } from '../helpers/sparkHelpers';
32
- import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
33
- import { SPARK_V1 } from '../markets/spark';
34
-
35
- export const sparkEmodeCategoriesMapping = (extractedState: { assetsData: SparkAssetsData }, usedAssets: SparkUsedAssets) => {
36
- const { assetsData } = extractedState;
37
- const usedAssetsValues = Object.values(usedAssets);
38
-
39
- const categoriesMapping: { [key: number]: SparkEModeCategoryDataMapping } = {};
40
- Object.values(assetsData).forEach((a) => {
41
- const borrowingOnlyFromCategory = a.eModeCategory === 0
42
- ? true
43
- : !usedAssetsValues.filter(u => u.isBorrowed && u.eModeCategory !== a.eModeCategory).length;
44
- const afterEnteringCategory = sparkGetAggregatedPositionData({
45
- ...extractedState, usedAssets, eModeCategory: a.eModeCategory,
46
- });
47
- const willStayOverCollateralized = new Dec(afterEnteringCategory.ratio).eq(0) || new Dec(afterEnteringCategory.ratio).gt(afterEnteringCategory.liqPercent);
48
- const enteringTerms = [borrowingOnlyFromCategory, willStayOverCollateralized];
49
-
50
- categoriesMapping[a.eModeCategory] = {
51
- enteringTerms,
52
- canEnterCategory: !enteringTerms.includes(false),
53
- id: a.eModeCategory,
54
- data: a.eModeCategoryData,
55
- assets: a.eModeCategory === 0 ? [] : [...(categoriesMapping[a.eModeCategory]?.assets || []), a.symbol],
56
- enabledData: {
57
- ratio: afterEnteringCategory.ratio,
58
- liqRatio: afterEnteringCategory.liqRatio,
59
- liqPercent: afterEnteringCategory.liqPercent,
60
- collRatio: afterEnteringCategory.collRatio,
61
- },
62
- };
63
- });
64
- return categoriesMapping;
65
- };
66
-
67
- export const getSparkMarketsData = async (web3: Web3, network: NetworkNumber, selectedMarket: SparkMarketData, mainnetWeb3: Web3): Promise<SparkMarketsData> => {
68
- const marketAddress = selectedMarket.providerAddress;
69
-
70
- let rewardInfo: any[] = [];
71
- if (network === 10) {
72
- const sparkIncentivesContract = SparkIncentiveDataProviderContract(web3, network);
73
- rewardInfo = await sparkIncentivesContract.methods.getReservesIncentivesData(marketAddress).call();
74
- rewardInfo = rewardInfo.reduce((all, market) => {
75
- // eslint-disable-next-line no-param-reassign
76
- all[market.underlyingAsset] = market;
77
- return all;
78
- }, {});
79
- }
80
-
81
- const loanInfoContract = SparkViewContract(web3, network);
82
-
83
- const loanInfo = await loanInfoContract.methods.getFullTokensInfo(
84
- marketAddress,
85
- selectedMarket.assets.map(a => getAssetInfo(ethToWeth(a)).address),
86
- ).call();
87
-
88
- const assetsData: SparkAssetData[] = await Promise.all(loanInfo
89
- .map(async (market, i) => {
90
- const symbol = selectedMarket.assets[i];
91
-
92
- const borrowCapInWei = new Dec(assetAmountInWei(market.borrowCap.toString(), symbol));
93
- let marketLiquidity = borrowCapInWei.lt(new Dec(market.totalSupply))
94
- ? assetAmountInEth(borrowCapInWei
95
- .sub(market.totalBorrow.toString())
96
- .toString(), symbol)
97
- : assetAmountInEth(new Dec(market.totalSupply.toString())
98
- .sub(market.totalBorrow.toString())
99
- .toString(), symbol);
100
-
101
- if (new Dec(marketLiquidity).lt(0)) {
102
- marketLiquidity = '0';
103
- }
104
- return ({
105
- symbol: selectedMarket.assets[i],
106
- isIsolated: new Dec(market.debtCeilingForIsolationMode).gt(0),
107
- debtCeilingForIsolationMode: new Dec(market.debtCeilingForIsolationMode).div(100).toString(),
108
- isSiloed: market.isSiloedForBorrowing,
109
- eModeCategory: +market.emodeCategory,
110
- isolationModeTotalDebt: new Dec(market.isolationModeTotalDebt).div(100).toString(),
111
- assetId: Number(market.assetId),
112
- underlyingTokenAddress: market.underlyingTokenAddress,
113
- supplyRate: aprToApy(new Dec(market.supplyRate.toString()).div(1e25).toString()),
114
- borrowRate: aprToApy(new Dec(market.borrowRateVariable.toString()).div(1e25).toString()),
115
- borrowRateStable: aprToApy(new Dec(market.borrowRateStable.toString()).div(1e25).toString()),
116
- collateralFactor: new Dec(market.collateralFactor.toString()).div(10000).toString(),
117
- liquidationRatio: new Dec(market.liquidationRatio.toString()).div(10000).toString(),
118
- marketLiquidity,
119
- utilization: new Dec(market.totalBorrow.toString()).times(100).div(new Dec(market.totalSupply.toString())).toString(),
120
- usageAsCollateralEnabled: market.usageAsCollateralEnabled,
121
- supplyCap: market.supplyCap,
122
- borrowCap: market.borrowCap,
123
- totalSupply: assetAmountInEth(market.totalSupply.toString(), selectedMarket.assets[i]),
124
- isInactive: !market.isActive,
125
- isFrozen: market.isFrozen,
126
- isPaused: market.isPaused,
127
- canBeBorrowed: market.isActive && !market.isPaused && !market.isFrozen && market.borrowingEnabled,
128
- canBeSupplied: market.isActive && !market.isPaused && !market.isFrozen,
129
- canBeWithdrawn: market.isActive && !market.isPaused,
130
- canBePayBacked: market.isActive && !market.isPaused,
131
- disabledStableBorrowing: !market.stableBorrowRateEnabled,
132
- totalBorrow: assetAmountInEth(market.totalBorrow.toString(), selectedMarket.assets[i]),
133
- totalBorrowVar: assetAmountInEth(market.totalBorrowVar.toString(), selectedMarket.assets[i]),
134
- price: new Dec(market.price.toString()).div(1e8).toString(), // is actually price in USD
135
- isolationModeBorrowingEnabled: market.isolationModeBorrowingEnabled,
136
- isFlashLoanEnabled: market.isFlashLoanEnabled,
137
- aTokenAddress: market.aTokenAddress,
138
- eModeCategoryData: {
139
- label: market.label,
140
- liquidationBonus: new Dec(market.liquidationBonus).div(10000).toString(),
141
- liquidationRatio: new Dec(market.liquidationThreshold).div(10000).toString(),
142
- collateralFactor: new Dec(market.ltv).div(10000).toString(),
143
- priceSource: market.priceSource,
144
- },
145
- });
146
- }));
147
-
148
- await Promise.all(assetsData.map(async (market) => {
149
- /* eslint-disable no-param-reassign */
150
- const rewardForMarket = (rewardInfo as any)[market.underlyingTokenAddress];
151
- if (STAKING_ASSETS.includes(market.symbol)) {
152
- market.incentiveSupplyApy = await getStakingApy(market.symbol, mainnetWeb3);
153
- market.incentiveSupplyToken = market.symbol;
154
- if (!market.supplyIncentives) {
155
- market.supplyIncentives = [];
156
- }
157
-
158
- market.supplyIncentives.push({
159
- apy: market.incentiveSupplyApy || '0',
160
- token: market.symbol,
161
- });
162
- }
163
-
164
- if (market.symbol === 'sDAI') {
165
- market.incentiveSupplyApy = await getDsrApy(web3, network);
166
- market.incentiveSupplyToken = 'sDAI';
167
- }
168
-
169
- if (market.canBeBorrowed && market.incentiveSupplyApy) {
170
- market.incentiveBorrowApy = market.incentiveSupplyApy;
171
- market.incentiveBorrowToken = market.incentiveSupplyToken;
172
- if (!market.borrowIncentives) {
173
- market.borrowIncentives = [];
174
- }
175
- market.borrowIncentives.push({
176
- apy: market.incentiveBorrowApy,
177
- token: market.incentiveBorrowToken!!,
178
- });
179
- }
180
-
181
- if (!rewardForMarket) return;
182
- (rewardForMarket.aIncentiveData.rewardsTokenInformation as any[]).forEach(supplyRewardData => {
183
- if (supplyRewardData) {
184
- if (supplyRewardData.emissionEndTimestamp * 1000 < Date.now()) return;
185
- market.incentiveSupplyToken = supplyRewardData.rewardTokenSymbol;
186
- const supplyEmissionPerSecond = supplyRewardData.emissionPerSecond;
187
- const supplyRewardPrice = new Dec(supplyRewardData.rewardPriceFeed).div(10 ** supplyRewardData.priceFeedDecimals)
188
- .toString();
189
- const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** supplyRewardData.rewardTokenDecimals) / 100)
190
- .mul(365 * 24 * 3600)
191
- .mul(supplyRewardPrice)
192
- .div(market.price)
193
- .div(market.totalSupply)
194
- .toString();
195
- market.incentiveSupplyApy = new Dec(market.incentiveSupplyApy || '0').add(rewardApy).toString();
196
-
197
- if (!market.supplyIncentives) {
198
- market.supplyIncentives = [];
199
- }
200
- market.supplyIncentives.push({
201
- token: supplyRewardData.rewardTokenSymbol,
202
- apy: rewardApy,
203
- });
204
- }
205
- });
206
- (rewardForMarket.vIncentiveData.rewardsTokenInformation as any[]).forEach(borrowRewardData => {
207
- if (borrowRewardData) {
208
- if (borrowRewardData.emissionEndTimestamp * 1000 < Date.now()) return;
209
- market.incentiveBorrowToken = borrowRewardData.rewardTokenSymbol;
210
- const supplyEmissionPerSecond = borrowRewardData.emissionPerSecond;
211
- const supplyRewardPrice = new Dec(borrowRewardData.rewardPriceFeed).div(10 ** borrowRewardData.priceFeedDecimals)
212
- .toString();
213
- const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** borrowRewardData.rewardTokenDecimals) / 100)
214
- .mul(365 * 24 * 3600)
215
- .mul(supplyRewardPrice)
216
- .div(market.price)
217
- .div(market.totalBorrowVar)
218
- .toString();
219
- market.incentiveBorrowApy = new Dec(market.incentiveBorrowApy || '0').add(rewardApy).toString();
220
-
221
- if (!market.borrowIncentives) {
222
- market.borrowIncentives = [];
223
- }
224
- market.borrowIncentives.push({
225
- token: borrowRewardData.rewardTokenSymbol,
226
- apy: rewardApy,
227
- });
228
- }
229
- });
230
- /* eslint-enable no-param-reassign */
231
- }));
232
-
233
- const payload: SparkAssetsData = {};
234
- // Sort by market size
235
- assetsData
236
- .sort((a, b) => {
237
- const aMarket = new Dec(a.price).times(a.totalSupply).toString();
238
- const bMarket = new Dec(b.price).times(b.totalSupply).toString();
239
-
240
- return new Dec(bMarket).minus(aMarket).toNumber();
241
- })
242
- .forEach((assetData: SparkAssetData, i) => {
243
- payload[assetData.symbol] = { ...assetData, sortIndex: i };
244
- });
245
-
246
- return { assetsData: payload };
247
- };
248
-
249
- export const EMPTY_SPARK_DATA = {
250
- usedAssets: {},
251
- suppliedUsd: '0',
252
- borrowedUsd: '0',
253
- borrowLimitUsd: '0',
254
- leftToBorrowUsd: '0',
255
- ratio: '0',
256
- minRatio: '0',
257
- netApy: '0',
258
- incentiveUsd: '0',
259
- totalInterestUsd: '0',
260
- eModeCategory: 0,
261
- isInIsolationMode: false,
262
- isInSiloedMode: false,
263
- collRatio: '0',
264
- suppliedCollateralUsd: '0',
265
- totalSupplied: '0',
266
- eModeCategories: [],
267
- };
268
-
269
- export const getSparkAccountBalances = async (web3: Web3, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
270
- let balances: PositionBalances = {
271
- collateral: {},
272
- debt: {},
273
- };
274
-
275
- if (!address) {
276
- return balances;
277
- }
278
-
279
- const loanInfoContract = SparkViewContract(web3, network, block);
280
-
281
- const market = SPARK_V1(network);
282
- const marketAddress = market.providerAddress;
283
- // @ts-ignore
284
- const protocolDataProviderContract = createContractWrapper(web3, network, market.protocolData, market.protocolDataAddress);
285
-
286
- const reserveTokens = await protocolDataProviderContract.methods.getAllReservesTokens().call({}, block);
287
- const symbols = reserveTokens.map(({ symbol }: { symbol: string }) => symbol);
288
- const _addresses = reserveTokens.map(({ tokenAddress }: { tokenAddress: EthAddress }) => tokenAddress);
289
-
290
-
291
- // split addresses in half to avoid gas limit by multicall
292
- const middleAddressIndex = Math.floor(_addresses.length / 2);
293
-
294
- const multicallData = [
295
- {
296
- target: loanInfoContract.options.address,
297
- abiItem: loanInfoContract.options.jsonInterface.find(({ name }) => name === 'getTokenBalances'),
298
- params: [marketAddress, address, _addresses.slice(0, middleAddressIndex)],
299
- },
300
- {
301
- target: loanInfoContract.options.address,
302
- abiItem: loanInfoContract.options.jsonInterface.find(({ name }) => name === 'getTokenBalances'),
303
- params: [marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)],
304
- },
305
- ];
306
-
307
- const multicallRes = await multicall(multicallData, web3, network, block);
308
-
309
- const loanInfo = [...multicallRes[0][0], ...multicallRes[1][0]];
310
-
311
- loanInfo.forEach((tokenInfo: any, i: number) => {
312
- const asset = wethToEth(symbols[i]);
313
- const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
314
-
315
- balances = {
316
- collateral: {
317
- ...balances.collateral,
318
- [addressMapping ? assetAddr : asset]: tokenInfo.balance.toString(),
319
- },
320
- debt: {
321
- ...balances.debt,
322
- [addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString(),
323
- },
324
- };
325
- });
326
-
327
- return balances;
328
- };
329
-
330
- export const getSparkAccountData = async (web3: Web3, network: NetworkNumber, address: string, extractedState: { selectedMarket: SparkMarketData, assetsData: SparkAssetsData }) => {
331
- const {
332
- selectedMarket: market, assetsData,
333
- } = extractedState;
334
- let payload: SparkPositionData = {
335
- ...EMPTY_SPARK_DATA,
336
- lastUpdated: Date.now(),
337
- };
338
- if (!address) {
339
- // structure that this function returns is complex and dynamic so i didnt want to hardcode it in EMPTY_SPARK_DATA
340
- // This case only triggers if user doesnt have proxy and data is refetched once proxy is created
341
- // TODO when refactoring spark figure out if this is the best solution.
342
- payload.eModeCategories = sparkEmodeCategoriesMapping(extractedState, {});
343
-
344
- return payload;
345
- }
346
-
347
- const loanInfoContract = SparkViewContract(web3, network);
348
- const marketAddress = market.providerAddress;
349
- const _addresses = market.assets.map((a) => getAssetInfo(ethToWeth(a)).address);
350
-
351
- const middleAddressIndex = Math.floor(_addresses.length / 2); // split addresses in half to avoid gas limit by multicall
352
-
353
- const LendingPoolAbi = getConfigContractAbi(market.lendingPool);
354
-
355
- const multicallData = [
356
- {
357
- target: market.lendingPoolAddress,
358
- abiItem: LendingPoolAbi.find(({ name }) => name === 'getUserEMode'),
359
- params: [address],
360
- },
361
- {
362
- target: loanInfoContract.options.address,
363
- abiItem: getAbiItem(loanInfoContract.options.jsonInterface, 'getTokenBalances'),
364
- params: [marketAddress, address, _addresses.slice(0, middleAddressIndex)],
365
- },
366
- {
367
- target: loanInfoContract.options.address,
368
- abiItem: getAbiItem(loanInfoContract.options.jsonInterface, 'getTokenBalances'),
369
- params: [marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)],
370
- },
371
- ];
372
-
373
- const multicallRes = await multicall(multicallData, web3, network);
374
-
375
- const loanInfo = [...multicallRes[1][0], ...multicallRes[2][0]];
376
-
377
- const usedAssets = {} as SparkUsedAssets;
378
- loanInfo.forEach((tokenInfo, i) => {
379
- const asset = market.assets[i];
380
- const isSupplied = tokenInfo.balance.toString() !== '0';
381
- const isBorrowed = tokenInfo.borrowsStable.toString() !== '0' || tokenInfo.borrowsVariable.toString() !== '0';
382
- if (!isSupplied && !isBorrowed) return;
383
-
384
- const supplied = assetAmountInEth(tokenInfo.balance.toString(), asset);
385
- const borrowedStable = assetAmountInEth(tokenInfo.borrowsStable.toString(), asset);
386
- const borrowedVariable = assetAmountInEth(tokenInfo.borrowsVariable.toString(), asset);
387
- const enabledAsCollateral = assetsData[asset].usageAsCollateralEnabled ? tokenInfo.enabledAsCollateral : false;
388
- let interestMode;
389
- if (borrowedVariable === '0' && borrowedStable !== '0') {
390
- interestMode = '1';
391
- } else if (borrowedVariable !== '0' && borrowedStable === '0') {
392
- interestMode = '2';
393
- } else {
394
- interestMode = 'both';
395
- }
396
- if (!usedAssets[asset]) usedAssets[asset] = {} as SparkUsedAsset;
397
- usedAssets[asset] = {
398
- ...usedAssets[asset],
399
- symbol: asset,
400
- supplied,
401
- suppliedUsd: new Dec(supplied).mul(assetsData[asset].price).toString(),
402
- isSupplied,
403
- collateral: enabledAsCollateral,
404
- stableBorrowRate: aprToApy(new Dec(tokenInfo.stableBorrowRate).div(1e25).toString()),
405
- borrowedStable,
406
- borrowedVariable,
407
- borrowedUsdStable: new Dec(borrowedStable).mul(assetsData[asset].price).toString(),
408
- borrowedUsdVariable: new Dec(borrowedVariable).mul(assetsData[asset].price).toString(),
409
- borrowed: new Dec(borrowedStable).add(borrowedVariable).toString(),
410
- borrowedUsd: new Dec(new Dec(borrowedVariable).add(borrowedStable)).mul(assetsData[asset].price).toString(),
411
- isBorrowed,
412
- eModeCategory: assetsData[asset].eModeCategory,
413
- interestMode,
414
- };
415
- });
416
-
417
- payload.eModeCategory = +multicallRes[0][0];
418
- payload = {
419
- ...payload,
420
- usedAssets,
421
- ...sparkGetAggregatedPositionData({
422
- ...extractedState, usedAssets, eModeCategory: payload.eModeCategory,
423
- }),
424
- };
425
- payload.eModeCategories = sparkEmodeCategoriesMapping(extractedState, usedAssets);
426
- payload.isInIsolationMode = sparkIsInIsolationMode({ usedAssets, assetsData });
427
- payload.isInSiloedMode = sparkIsInIsolationMode({ usedAssets, assetsData });
428
-
429
- payload.ratio = payload.borrowedUsd && payload.borrowedUsd !== '0'
430
- ? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString()
431
- : '0';
432
- payload.minRatio = '100';
433
- payload.collRatio = payload.borrowedUsd && payload.borrowedUsd !== '0'
434
- ? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString()
435
- : '0';
436
-
437
- // Calculate borrow limits per asset
438
- Object.values(payload.usedAssets).forEach((item) => {
439
- if (item.isBorrowed) {
440
- // eslint-disable-next-line no-param-reassign
441
- item.stableLimit = calculateBorrowingAssetLimit(item.borrowedUsdStable, payload.borrowLimitUsd);
442
- // eslint-disable-next-line no-param-reassign
443
- item.variableLimit = calculateBorrowingAssetLimit(item.borrowedUsdVariable, payload.borrowLimitUsd);
444
- // eslint-disable-next-line no-param-reassign
445
- item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
446
- }
447
- });
448
-
449
- const { netApy, incentiveUsd, totalInterestUsd } = calculateNetApy({ usedAssets, assetsData });
450
- payload.netApy = netApy;
451
- payload.incentiveUsd = incentiveUsd;
452
- payload.totalInterestUsd = totalInterestUsd;
453
-
454
- return payload;
455
- };
456
-
457
- export const getSparkFullPositionData = async (web3: Web3, network: NetworkNumber, address: string, market: SparkMarketData, mainnetWeb3: Web3): Promise<SparkPositionData> => {
458
- const marketData = await getSparkMarketsData(web3, network, market, mainnetWeb3);
459
- const positionData = await getSparkAccountData(web3, network, address, { assetsData: marketData.assetsData, selectedMarket: market });
460
- return positionData;
461
- };
1
+ import Web3 from 'web3';
2
+ import Dec from 'decimal.js';
3
+ import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
4
+ import {
5
+ Blockish, EthAddress, NetworkNumber, PositionBalances,
6
+ } from '../types/common';
7
+ import {
8
+ ethToWeth, getAbiItem, isLayer2Network, wethToEth, wethToEthByAddress,
9
+ } from '../services/utils';
10
+ import {
11
+ calculateNetApy, getStakingApy, STAKING_ASSETS,
12
+ } from '../staking';
13
+ import { getDsrApy } from '../services/dsrService';
14
+ import {
15
+ SparkIncentiveDataProviderContract,
16
+ SparkViewContract,
17
+ getConfigContractAbi,
18
+ createContractWrapper,
19
+ } from '../contracts';
20
+ import {
21
+ SparkEModeCategoryDataMapping,
22
+ SparkAssetData,
23
+ SparkAssetsData,
24
+ SparkMarketData,
25
+ SparkMarketsData,
26
+ SparkPositionData,
27
+ SparkUsedAsset,
28
+ SparkUsedAssets,
29
+ } from '../types';
30
+ import { multicall } from '../multicall';
31
+ import { sparkGetAggregatedPositionData, sparkIsInIsolationMode } from '../helpers/sparkHelpers';
32
+ import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
33
+ import { SPARK_V1 } from '../markets/spark';
34
+
35
+ export const sparkEmodeCategoriesMapping = (extractedState: { assetsData: SparkAssetsData }, usedAssets: SparkUsedAssets) => {
36
+ const { assetsData } = extractedState;
37
+ const usedAssetsValues = Object.values(usedAssets);
38
+
39
+ const categoriesMapping: { [key: number]: SparkEModeCategoryDataMapping } = {};
40
+ Object.values(assetsData).forEach((a) => {
41
+ const borrowingOnlyFromCategory = a.eModeCategory === 0
42
+ ? true
43
+ : !usedAssetsValues.filter(u => u.isBorrowed && u.eModeCategory !== a.eModeCategory).length;
44
+ const afterEnteringCategory = sparkGetAggregatedPositionData({
45
+ ...extractedState, usedAssets, eModeCategory: a.eModeCategory,
46
+ });
47
+ const willStayOverCollateralized = new Dec(afterEnteringCategory.ratio).eq(0) || new Dec(afterEnteringCategory.ratio).gt(afterEnteringCategory.liqPercent);
48
+ const enteringTerms = [borrowingOnlyFromCategory, willStayOverCollateralized];
49
+
50
+ categoriesMapping[a.eModeCategory] = {
51
+ enteringTerms,
52
+ canEnterCategory: !enteringTerms.includes(false),
53
+ id: a.eModeCategory,
54
+ data: a.eModeCategoryData,
55
+ assets: a.eModeCategory === 0 ? [] : [...(categoriesMapping[a.eModeCategory]?.assets || []), a.symbol],
56
+ enabledData: {
57
+ ratio: afterEnteringCategory.ratio,
58
+ liqRatio: afterEnteringCategory.liqRatio,
59
+ liqPercent: afterEnteringCategory.liqPercent,
60
+ collRatio: afterEnteringCategory.collRatio,
61
+ },
62
+ };
63
+ });
64
+ return categoriesMapping;
65
+ };
66
+
67
+ export const getSparkMarketsData = async (web3: Web3, network: NetworkNumber, selectedMarket: SparkMarketData, mainnetWeb3: Web3): Promise<SparkMarketsData> => {
68
+ const marketAddress = selectedMarket.providerAddress;
69
+
70
+ let rewardInfo: any[] = [];
71
+ if (network === 10) {
72
+ const sparkIncentivesContract = SparkIncentiveDataProviderContract(web3, network);
73
+ rewardInfo = await sparkIncentivesContract.methods.getReservesIncentivesData(marketAddress).call();
74
+ rewardInfo = rewardInfo.reduce((all, market) => {
75
+ // eslint-disable-next-line no-param-reassign
76
+ all[market.underlyingAsset] = market;
77
+ return all;
78
+ }, {});
79
+ }
80
+
81
+ const loanInfoContract = SparkViewContract(web3, network);
82
+
83
+ const loanInfo = await loanInfoContract.methods.getFullTokensInfo(
84
+ marketAddress,
85
+ selectedMarket.assets.map(a => getAssetInfo(ethToWeth(a)).address),
86
+ ).call();
87
+
88
+ const assetsData: SparkAssetData[] = await Promise.all(loanInfo
89
+ .map(async (market, i) => {
90
+ const symbol = selectedMarket.assets[i];
91
+
92
+ const borrowCapInWei = new Dec(assetAmountInWei(market.borrowCap.toString(), symbol));
93
+ let marketLiquidity = borrowCapInWei.lt(new Dec(market.totalSupply))
94
+ ? assetAmountInEth(borrowCapInWei
95
+ .sub(market.totalBorrow.toString())
96
+ .toString(), symbol)
97
+ : assetAmountInEth(new Dec(market.totalSupply.toString())
98
+ .sub(market.totalBorrow.toString())
99
+ .toString(), symbol);
100
+
101
+ if (new Dec(marketLiquidity).lt(0)) {
102
+ marketLiquidity = '0';
103
+ }
104
+ return ({
105
+ symbol: selectedMarket.assets[i],
106
+ isIsolated: new Dec(market.debtCeilingForIsolationMode).gt(0),
107
+ debtCeilingForIsolationMode: new Dec(market.debtCeilingForIsolationMode).div(100).toString(),
108
+ isSiloed: market.isSiloedForBorrowing,
109
+ eModeCategory: +market.emodeCategory,
110
+ isolationModeTotalDebt: new Dec(market.isolationModeTotalDebt).div(100).toString(),
111
+ assetId: Number(market.assetId),
112
+ underlyingTokenAddress: market.underlyingTokenAddress,
113
+ supplyRate: aprToApy(new Dec(market.supplyRate.toString()).div(1e25).toString()),
114
+ borrowRate: aprToApy(new Dec(market.borrowRateVariable.toString()).div(1e25).toString()),
115
+ borrowRateStable: aprToApy(new Dec(market.borrowRateStable.toString()).div(1e25).toString()),
116
+ collateralFactor: new Dec(market.collateralFactor.toString()).div(10000).toString(),
117
+ liquidationRatio: new Dec(market.liquidationRatio.toString()).div(10000).toString(),
118
+ marketLiquidity,
119
+ utilization: new Dec(market.totalBorrow.toString()).times(100).div(new Dec(market.totalSupply.toString())).toString(),
120
+ usageAsCollateralEnabled: market.usageAsCollateralEnabled,
121
+ supplyCap: market.supplyCap,
122
+ borrowCap: market.borrowCap,
123
+ totalSupply: assetAmountInEth(market.totalSupply.toString(), selectedMarket.assets[i]),
124
+ isInactive: !market.isActive,
125
+ isFrozen: market.isFrozen,
126
+ isPaused: market.isPaused,
127
+ canBeBorrowed: market.isActive && !market.isPaused && !market.isFrozen && market.borrowingEnabled,
128
+ canBeSupplied: market.isActive && !market.isPaused && !market.isFrozen,
129
+ canBeWithdrawn: market.isActive && !market.isPaused,
130
+ canBePayBacked: market.isActive && !market.isPaused,
131
+ disabledStableBorrowing: !market.stableBorrowRateEnabled,
132
+ totalBorrow: assetAmountInEth(market.totalBorrow.toString(), selectedMarket.assets[i]),
133
+ totalBorrowVar: assetAmountInEth(market.totalBorrowVar.toString(), selectedMarket.assets[i]),
134
+ price: new Dec(market.price.toString()).div(1e8).toString(), // is actually price in USD
135
+ isolationModeBorrowingEnabled: market.isolationModeBorrowingEnabled,
136
+ isFlashLoanEnabled: market.isFlashLoanEnabled,
137
+ aTokenAddress: market.aTokenAddress,
138
+ eModeCategoryData: {
139
+ label: market.label,
140
+ liquidationBonus: new Dec(market.liquidationBonus).div(10000).toString(),
141
+ liquidationRatio: new Dec(market.liquidationThreshold).div(10000).toString(),
142
+ collateralFactor: new Dec(market.ltv).div(10000).toString(),
143
+ priceSource: market.priceSource,
144
+ },
145
+ });
146
+ }));
147
+
148
+ await Promise.all(assetsData.map(async (market) => {
149
+ /* eslint-disable no-param-reassign */
150
+ const rewardForMarket = (rewardInfo as any)[market.underlyingTokenAddress];
151
+ if (STAKING_ASSETS.includes(market.symbol)) {
152
+ market.incentiveSupplyApy = await getStakingApy(market.symbol, mainnetWeb3);
153
+ market.incentiveSupplyToken = market.symbol;
154
+ if (!market.supplyIncentives) {
155
+ market.supplyIncentives = [];
156
+ }
157
+
158
+ market.supplyIncentives.push({
159
+ apy: market.incentiveSupplyApy || '0',
160
+ token: market.symbol,
161
+ });
162
+ }
163
+
164
+ if (market.symbol === 'sDAI') {
165
+ market.incentiveSupplyApy = await getDsrApy(web3, network);
166
+ market.incentiveSupplyToken = 'sDAI';
167
+ }
168
+
169
+ if (market.canBeBorrowed && market.incentiveSupplyApy) {
170
+ market.incentiveBorrowApy = market.incentiveSupplyApy;
171
+ market.incentiveBorrowToken = market.incentiveSupplyToken;
172
+ if (!market.borrowIncentives) {
173
+ market.borrowIncentives = [];
174
+ }
175
+ market.borrowIncentives.push({
176
+ apy: market.incentiveBorrowApy,
177
+ token: market.incentiveBorrowToken!!,
178
+ });
179
+ }
180
+
181
+ if (!rewardForMarket) return;
182
+ (rewardForMarket.aIncentiveData.rewardsTokenInformation as any[]).forEach(supplyRewardData => {
183
+ if (supplyRewardData) {
184
+ if (supplyRewardData.emissionEndTimestamp * 1000 < Date.now()) return;
185
+ market.incentiveSupplyToken = supplyRewardData.rewardTokenSymbol;
186
+ const supplyEmissionPerSecond = supplyRewardData.emissionPerSecond;
187
+ const supplyRewardPrice = new Dec(supplyRewardData.rewardPriceFeed).div(10 ** supplyRewardData.priceFeedDecimals)
188
+ .toString();
189
+ const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** supplyRewardData.rewardTokenDecimals) / 100)
190
+ .mul(365 * 24 * 3600)
191
+ .mul(supplyRewardPrice)
192
+ .div(market.price)
193
+ .div(market.totalSupply)
194
+ .toString();
195
+ market.incentiveSupplyApy = new Dec(market.incentiveSupplyApy || '0').add(rewardApy).toString();
196
+
197
+ if (!market.supplyIncentives) {
198
+ market.supplyIncentives = [];
199
+ }
200
+ market.supplyIncentives.push({
201
+ token: supplyRewardData.rewardTokenSymbol,
202
+ apy: rewardApy,
203
+ });
204
+ }
205
+ });
206
+ (rewardForMarket.vIncentiveData.rewardsTokenInformation as any[]).forEach(borrowRewardData => {
207
+ if (borrowRewardData) {
208
+ if (borrowRewardData.emissionEndTimestamp * 1000 < Date.now()) return;
209
+ market.incentiveBorrowToken = borrowRewardData.rewardTokenSymbol;
210
+ const supplyEmissionPerSecond = borrowRewardData.emissionPerSecond;
211
+ const supplyRewardPrice = new Dec(borrowRewardData.rewardPriceFeed).div(10 ** borrowRewardData.priceFeedDecimals)
212
+ .toString();
213
+ const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** borrowRewardData.rewardTokenDecimals) / 100)
214
+ .mul(365 * 24 * 3600)
215
+ .mul(supplyRewardPrice)
216
+ .div(market.price)
217
+ .div(market.totalBorrowVar)
218
+ .toString();
219
+ market.incentiveBorrowApy = new Dec(market.incentiveBorrowApy || '0').add(rewardApy).toString();
220
+
221
+ if (!market.borrowIncentives) {
222
+ market.borrowIncentives = [];
223
+ }
224
+ market.borrowIncentives.push({
225
+ token: borrowRewardData.rewardTokenSymbol,
226
+ apy: rewardApy,
227
+ });
228
+ }
229
+ });
230
+ /* eslint-enable no-param-reassign */
231
+ }));
232
+
233
+ const payload: SparkAssetsData = {};
234
+ // Sort by market size
235
+ assetsData
236
+ .sort((a, b) => {
237
+ const aMarket = new Dec(a.price).times(a.totalSupply).toString();
238
+ const bMarket = new Dec(b.price).times(b.totalSupply).toString();
239
+
240
+ return new Dec(bMarket).minus(aMarket).toNumber();
241
+ })
242
+ .forEach((assetData: SparkAssetData, i) => {
243
+ payload[assetData.symbol] = { ...assetData, sortIndex: i };
244
+ });
245
+
246
+ return { assetsData: payload };
247
+ };
248
+
249
+ export const EMPTY_SPARK_DATA = {
250
+ usedAssets: {},
251
+ suppliedUsd: '0',
252
+ borrowedUsd: '0',
253
+ borrowLimitUsd: '0',
254
+ leftToBorrowUsd: '0',
255
+ ratio: '0',
256
+ minRatio: '0',
257
+ netApy: '0',
258
+ incentiveUsd: '0',
259
+ totalInterestUsd: '0',
260
+ eModeCategory: 0,
261
+ isInIsolationMode: false,
262
+ isInSiloedMode: false,
263
+ collRatio: '0',
264
+ suppliedCollateralUsd: '0',
265
+ totalSupplied: '0',
266
+ eModeCategories: [],
267
+ };
268
+
269
+ export const getSparkAccountBalances = async (web3: Web3, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
270
+ let balances: PositionBalances = {
271
+ collateral: {},
272
+ debt: {},
273
+ };
274
+
275
+ if (!address) {
276
+ return balances;
277
+ }
278
+
279
+ const loanInfoContract = SparkViewContract(web3, network, block);
280
+
281
+ const market = SPARK_V1(network);
282
+ const marketAddress = market.providerAddress;
283
+ // @ts-ignore
284
+ const protocolDataProviderContract = createContractWrapper(web3, network, market.protocolData, market.protocolDataAddress);
285
+
286
+ const reserveTokens = await protocolDataProviderContract.methods.getAllReservesTokens().call({}, block);
287
+ const symbols = reserveTokens.map(({ symbol }: { symbol: string }) => symbol);
288
+ const _addresses = reserveTokens.map(({ tokenAddress }: { tokenAddress: EthAddress }) => tokenAddress);
289
+
290
+
291
+ // split addresses in half to avoid gas limit by multicall
292
+ const middleAddressIndex = Math.floor(_addresses.length / 2);
293
+
294
+ const multicallData = [
295
+ {
296
+ target: loanInfoContract.options.address,
297
+ abiItem: loanInfoContract.options.jsonInterface.find(({ name }) => name === 'getTokenBalances'),
298
+ params: [marketAddress, address, _addresses.slice(0, middleAddressIndex)],
299
+ },
300
+ {
301
+ target: loanInfoContract.options.address,
302
+ abiItem: loanInfoContract.options.jsonInterface.find(({ name }) => name === 'getTokenBalances'),
303
+ params: [marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)],
304
+ },
305
+ ];
306
+
307
+ const multicallRes = await multicall(multicallData, web3, network, block);
308
+
309
+ const loanInfo = [...multicallRes[0][0], ...multicallRes[1][0]];
310
+
311
+ loanInfo.forEach((tokenInfo: any, i: number) => {
312
+ const asset = wethToEth(symbols[i]);
313
+ const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
314
+
315
+ balances = {
316
+ collateral: {
317
+ ...balances.collateral,
318
+ [addressMapping ? assetAddr : asset]: tokenInfo.balance.toString(),
319
+ },
320
+ debt: {
321
+ ...balances.debt,
322
+ [addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString(),
323
+ },
324
+ };
325
+ });
326
+
327
+ return balances;
328
+ };
329
+
330
+ export const getSparkAccountData = async (web3: Web3, network: NetworkNumber, address: string, extractedState: { selectedMarket: SparkMarketData, assetsData: SparkAssetsData }) => {
331
+ const {
332
+ selectedMarket: market, assetsData,
333
+ } = extractedState;
334
+ let payload: SparkPositionData = {
335
+ ...EMPTY_SPARK_DATA,
336
+ lastUpdated: Date.now(),
337
+ };
338
+ if (!address) {
339
+ // structure that this function returns is complex and dynamic so i didnt want to hardcode it in EMPTY_SPARK_DATA
340
+ // This case only triggers if user doesnt have proxy and data is refetched once proxy is created
341
+ // TODO when refactoring spark figure out if this is the best solution.
342
+ payload.eModeCategories = sparkEmodeCategoriesMapping(extractedState, {});
343
+
344
+ return payload;
345
+ }
346
+
347
+ const loanInfoContract = SparkViewContract(web3, network);
348
+ const marketAddress = market.providerAddress;
349
+ const _addresses = market.assets.map((a) => getAssetInfo(ethToWeth(a)).address);
350
+
351
+ const middleAddressIndex = Math.floor(_addresses.length / 2); // split addresses in half to avoid gas limit by multicall
352
+
353
+ const LendingPoolAbi = getConfigContractAbi(market.lendingPool);
354
+
355
+ const multicallData = [
356
+ {
357
+ target: market.lendingPoolAddress,
358
+ abiItem: LendingPoolAbi.find(({ name }) => name === 'getUserEMode'),
359
+ params: [address],
360
+ },
361
+ {
362
+ target: loanInfoContract.options.address,
363
+ abiItem: getAbiItem(loanInfoContract.options.jsonInterface, 'getTokenBalances'),
364
+ params: [marketAddress, address, _addresses.slice(0, middleAddressIndex)],
365
+ },
366
+ {
367
+ target: loanInfoContract.options.address,
368
+ abiItem: getAbiItem(loanInfoContract.options.jsonInterface, 'getTokenBalances'),
369
+ params: [marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)],
370
+ },
371
+ ];
372
+
373
+ const multicallRes = await multicall(multicallData, web3, network);
374
+
375
+ const loanInfo = [...multicallRes[1][0], ...multicallRes[2][0]];
376
+
377
+ const usedAssets = {} as SparkUsedAssets;
378
+ loanInfo.forEach((tokenInfo, i) => {
379
+ const asset = market.assets[i];
380
+ const isSupplied = tokenInfo.balance.toString() !== '0';
381
+ const isBorrowed = tokenInfo.borrowsStable.toString() !== '0' || tokenInfo.borrowsVariable.toString() !== '0';
382
+ if (!isSupplied && !isBorrowed) return;
383
+
384
+ const supplied = assetAmountInEth(tokenInfo.balance.toString(), asset);
385
+ const borrowedStable = assetAmountInEth(tokenInfo.borrowsStable.toString(), asset);
386
+ const borrowedVariable = assetAmountInEth(tokenInfo.borrowsVariable.toString(), asset);
387
+ const enabledAsCollateral = assetsData[asset].usageAsCollateralEnabled ? tokenInfo.enabledAsCollateral : false;
388
+ let interestMode;
389
+ if (borrowedVariable === '0' && borrowedStable !== '0') {
390
+ interestMode = '1';
391
+ } else if (borrowedVariable !== '0' && borrowedStable === '0') {
392
+ interestMode = '2';
393
+ } else {
394
+ interestMode = 'both';
395
+ }
396
+ if (!usedAssets[asset]) usedAssets[asset] = {} as SparkUsedAsset;
397
+ usedAssets[asset] = {
398
+ ...usedAssets[asset],
399
+ symbol: asset,
400
+ supplied,
401
+ suppliedUsd: new Dec(supplied).mul(assetsData[asset].price).toString(),
402
+ isSupplied,
403
+ collateral: enabledAsCollateral,
404
+ stableBorrowRate: aprToApy(new Dec(tokenInfo.stableBorrowRate).div(1e25).toString()),
405
+ borrowedStable,
406
+ borrowedVariable,
407
+ borrowedUsdStable: new Dec(borrowedStable).mul(assetsData[asset].price).toString(),
408
+ borrowedUsdVariable: new Dec(borrowedVariable).mul(assetsData[asset].price).toString(),
409
+ borrowed: new Dec(borrowedStable).add(borrowedVariable).toString(),
410
+ borrowedUsd: new Dec(new Dec(borrowedVariable).add(borrowedStable)).mul(assetsData[asset].price).toString(),
411
+ isBorrowed,
412
+ eModeCategory: assetsData[asset].eModeCategory,
413
+ interestMode,
414
+ };
415
+ });
416
+
417
+ payload.eModeCategory = +multicallRes[0][0];
418
+ payload = {
419
+ ...payload,
420
+ usedAssets,
421
+ ...sparkGetAggregatedPositionData({
422
+ ...extractedState, usedAssets, eModeCategory: payload.eModeCategory,
423
+ }),
424
+ };
425
+ payload.eModeCategories = sparkEmodeCategoriesMapping(extractedState, usedAssets);
426
+ payload.isInIsolationMode = sparkIsInIsolationMode({ usedAssets, assetsData });
427
+ payload.isInSiloedMode = sparkIsInIsolationMode({ usedAssets, assetsData });
428
+
429
+ payload.ratio = payload.borrowedUsd && payload.borrowedUsd !== '0'
430
+ ? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString()
431
+ : '0';
432
+ payload.minRatio = '100';
433
+ payload.collRatio = payload.borrowedUsd && payload.borrowedUsd !== '0'
434
+ ? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString()
435
+ : '0';
436
+
437
+ // Calculate borrow limits per asset
438
+ Object.values(payload.usedAssets).forEach((item) => {
439
+ if (item.isBorrowed) {
440
+ // eslint-disable-next-line no-param-reassign
441
+ item.stableLimit = calculateBorrowingAssetLimit(item.borrowedUsdStable, payload.borrowLimitUsd);
442
+ // eslint-disable-next-line no-param-reassign
443
+ item.variableLimit = calculateBorrowingAssetLimit(item.borrowedUsdVariable, payload.borrowLimitUsd);
444
+ // eslint-disable-next-line no-param-reassign
445
+ item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
446
+ }
447
+ });
448
+
449
+ const { netApy, incentiveUsd, totalInterestUsd } = calculateNetApy({ usedAssets, assetsData });
450
+ payload.netApy = netApy;
451
+ payload.incentiveUsd = incentiveUsd;
452
+ payload.totalInterestUsd = totalInterestUsd;
453
+
454
+ return payload;
455
+ };
456
+
457
+ export const getSparkFullPositionData = async (web3: Web3, network: NetworkNumber, address: string, market: SparkMarketData, mainnetWeb3: Web3): Promise<SparkPositionData> => {
458
+ const marketData = await getSparkMarketsData(web3, network, market, mainnetWeb3);
459
+ const positionData = await getSparkAccountData(web3, network, address, { assetsData: marketData.assetsData, selectedMarket: market });
460
+ return positionData;
461
+ };