@defisaver/positions-sdk 1.0.11-fluid-dev10 → 1.0.11-fluid-dev12

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 (80) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/README.md +69 -69
  4. package/cjs/fluid/index.js +60 -20
  5. package/cjs/helpers/fluidHelpers/index.js +21 -2
  6. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  7. package/cjs/types/fluid.d.ts +4 -0
  8. package/esm/fluid/index.js +60 -20
  9. package/esm/helpers/fluidHelpers/index.js +21 -2
  10. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  11. package/esm/types/fluid.d.ts +4 -0
  12. package/package.json +54 -54
  13. package/src/aaveV2/index.ts +227 -227
  14. package/src/aaveV3/index.ts +624 -624
  15. package/src/assets/index.ts +60 -60
  16. package/src/chickenBonds/index.ts +123 -123
  17. package/src/compoundV2/index.ts +220 -220
  18. package/src/compoundV3/index.ts +291 -291
  19. package/src/config/contracts.js +1155 -1155
  20. package/src/constants/index.ts +6 -6
  21. package/src/contracts.ts +135 -135
  22. package/src/curveUsd/index.ts +239 -239
  23. package/src/eulerV2/index.ts +303 -303
  24. package/src/exchange/index.ts +17 -17
  25. package/src/fluid/index.ts +1289 -1241
  26. package/src/helpers/aaveHelpers/index.ts +203 -203
  27. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  28. package/src/helpers/compoundHelpers/index.ts +248 -248
  29. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  30. package/src/helpers/eulerHelpers/index.ts +234 -234
  31. package/src/helpers/fluidHelpers/index.ts +325 -294
  32. package/src/helpers/index.ts +11 -11
  33. package/src/helpers/liquityV2Helpers/index.ts +80 -80
  34. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  35. package/src/helpers/makerHelpers/index.ts +94 -94
  36. package/src/helpers/morphoBlueHelpers/index.ts +367 -367
  37. package/src/helpers/sparkHelpers/index.ts +154 -154
  38. package/src/index.ts +52 -52
  39. package/src/liquity/index.ts +116 -116
  40. package/src/liquityV2/index.ts +295 -295
  41. package/src/llamaLend/index.ts +275 -275
  42. package/src/maker/index.ts +117 -117
  43. package/src/markets/aave/index.ts +152 -152
  44. package/src/markets/aave/marketAssets.ts +46 -46
  45. package/src/markets/compound/index.ts +213 -213
  46. package/src/markets/compound/marketsAssets.ts +82 -82
  47. package/src/markets/curveUsd/index.ts +69 -69
  48. package/src/markets/euler/index.ts +26 -26
  49. package/src/markets/fluid/index.ts +2454 -2454
  50. package/src/markets/index.ts +27 -27
  51. package/src/markets/liquityV2/index.ts +54 -54
  52. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  53. package/src/markets/llamaLend/index.ts +235 -235
  54. package/src/markets/morphoBlue/index.ts +895 -895
  55. package/src/markets/spark/index.ts +29 -29
  56. package/src/markets/spark/marketAssets.ts +10 -10
  57. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  58. package/src/morphoAaveV2/index.ts +256 -256
  59. package/src/morphoAaveV3/index.ts +630 -630
  60. package/src/morphoBlue/index.ts +202 -202
  61. package/src/multicall/index.ts +33 -33
  62. package/src/services/priceService.ts +130 -130
  63. package/src/services/utils.ts +59 -59
  64. package/src/setup.ts +8 -8
  65. package/src/spark/index.ts +460 -460
  66. package/src/staking/staking.ts +217 -217
  67. package/src/types/aave.ts +275 -275
  68. package/src/types/chickenBonds.ts +45 -45
  69. package/src/types/common.ts +84 -84
  70. package/src/types/compound.ts +133 -133
  71. package/src/types/curveUsd.ts +119 -119
  72. package/src/types/euler.ts +173 -173
  73. package/src/types/fluid.ts +330 -325
  74. package/src/types/index.ts +11 -11
  75. package/src/types/liquity.ts +30 -30
  76. package/src/types/liquityV2.ts +119 -119
  77. package/src/types/llamaLend.ts +155 -155
  78. package/src/types/maker.ts +50 -50
  79. package/src/types/morphoBlue.ts +194 -194
  80. package/src/types/spark.ts +135 -135
@@ -1,1242 +1,1290 @@
1
- import Web3 from 'web3';
2
- import Dec from 'decimal.js';
3
- import {
4
- assetAmountInEth,
5
- AssetData, getAssetInfo, getAssetInfoByAddress,
6
- } from '@defisaver/tokens';
7
- import { EthAddress, NetworkNumber } from '../types/common';
8
- import {
9
- FluidAggregatedVaultData,
10
- FluidAssetData, FluidAssetsData,
11
- FluidMarketData,
12
- FluidMarketInfo,
13
- FluidUsedAsset,
14
- FluidUsedAssets,
15
- FluidVaultData,
16
- FluidVaultType, InnerFluidMarketData,
17
- } from '../types';
18
- import { DFSFeedRegistryContract, FeedRegistryContract, FluidViewContract } from '../contracts';
19
- import { getEthAmountForDecimals, isMainnetNetwork } from '../services/utils';
20
- import {
21
- getFluidAggregatedData,
22
- mergeAssetData,
23
- mergeUsedAssets,
24
- parseDexBorrowData,
25
- parseDexSupplyData,
26
- } from '../helpers/fluidHelpers';
27
- import { FluidView } from '../types/contracts/generated';
28
- import { chunkAndMulticall } from '../multicall';
29
- import { getFluidMarketInfoById, getFluidVersionsDataForNetwork, getFTokenAddress } from '../markets';
30
- import { USD_QUOTE } from '../constants';
31
- import {
32
- getChainlinkAssetAddress,
33
- getWeETHChainLinkPriceCalls,
34
- getWstETHChainLinkPriceCalls,
35
- getWstETHPriceFluid,
36
- parseWeETHPriceCalls,
37
- parseWstETHPriceCalls,
38
- } from '../services/priceService';
39
- import { getStakingApy, STAKING_ASSETS } from '../staking';
40
-
41
- export const EMPTY_USED_ASSET = {
42
- isSupplied: false,
43
- isBorrowed: false,
44
- supplied: '0',
45
- suppliedUsd: '0',
46
- borrowed: '0',
47
- borrowedUsd: '0',
48
- symbol: '',
49
- collateral: false,
50
- };
51
-
52
- const parseVaultType = (vaultType: number) => {
53
- switch (vaultType) {
54
- case 10000: return FluidVaultType.T1;
55
- case 20000: return FluidVaultType.T2;
56
- case 30000: return FluidVaultType.T3;
57
- case 40000: return FluidVaultType.T4;
58
- default: return FluidVaultType.Unknown;
59
- }
60
- };
61
-
62
- const getChainLinkPricesForTokens = async (
63
- tokens: string[],
64
- network: NetworkNumber,
65
- web3: Web3,
66
- ): Promise<{ [key: string]: string }> => {
67
- const isMainnet = isMainnetNetwork(network);
68
-
69
- const noDuplicateTokens = new Array(...new Set(tokens));
70
-
71
- const calls = noDuplicateTokens.flatMap((address) => {
72
- const assetInfo = getAssetInfoByAddress(address, network);
73
- const isTokenUSDA = assetInfo.symbol === 'USDA';
74
- if (isTokenUSDA) return;
75
- const chainLinkFeedAddress = getChainlinkAssetAddress(assetInfo.symbol, network);
76
-
77
- if (assetInfo.symbol === 'wstETH') return getWstETHChainLinkPriceCalls(web3, network);
78
- if (assetInfo.symbol === 'weETH') return getWeETHChainLinkPriceCalls(web3, network);
79
-
80
- if (isMainnet) {
81
- const feedRegistryContract = FeedRegistryContract(web3, NetworkNumber.Eth);
82
- return ({
83
- target: feedRegistryContract.options.address,
84
- abiItem: feedRegistryContract.options.jsonInterface.find(({ name }) => name === 'latestAnswer'),
85
- params: [chainLinkFeedAddress, USD_QUOTE],
86
- });
87
- }
88
-
89
- const feedRegistryContract = DFSFeedRegistryContract(web3, network);
90
- return ({
91
- target: feedRegistryContract.options.address,
92
- abiItem: feedRegistryContract.options.jsonInterface.find(({ name }) => name === 'latestRoundData'),
93
- params: [chainLinkFeedAddress, USD_QUOTE],
94
- });
95
- });
96
-
97
- const prices = await chunkAndMulticall(calls, 10, 'latest', web3, network);
98
- let offset = 0; // wstETH has 3 calls, while others have only 1, so we need to keep track
99
-
100
- return noDuplicateTokens.reduce((acc, token, i) => {
101
- const assetInfo = getAssetInfoByAddress(token, network);
102
- switch (assetInfo.symbol) {
103
- case 'USDA':
104
- acc[token] = '100000000';
105
- break;
106
-
107
- case 'wstETH': {
108
- const {
109
- ethPrice,
110
- wstETHRate,
111
- } = parseWstETHPriceCalls(prices[i + offset][0], prices[i + offset + 1], prices[i + offset + 2][0]);
112
- offset += 2;
113
- acc[token] = new Dec(ethPrice).mul(wstETHRate).toString();
114
- break;
115
- }
116
-
117
- case 'weETH': {
118
- const {
119
- ethPrice,
120
- weETHRate,
121
- } = parseWeETHPriceCalls(prices[i + offset][0], prices[i + offset + 1], prices[i + offset + 2][0]);
122
- offset += 2;
123
- acc[token] = new Dec(ethPrice).mul(weETHRate).toString();
124
- break;
125
- }
126
-
127
- default:
128
- acc[token] = new Dec(prices[i + offset].answer).div(1e8).toString();
129
- break;
130
- }
131
- return acc;
132
- }, {} as { [key: string]: string });
133
- };
134
-
135
-
136
- const getTokenPriceFromChainlink = async (asset: AssetData, network: NetworkNumber, web3: Web3) => {
137
- const isTokenUSDA = asset.symbol === 'USDA';
138
- const isMainnet = isMainnetNetwork(network);
139
- const loanTokenFeedAddress = getChainlinkAssetAddress(asset.symbol, network);
140
-
141
- let loanTokenPrice;
142
- if (asset.symbol === 'wstETH') {
143
- // need to handle wstETH for l2s inside getWstETHPrice
144
- loanTokenPrice = await getWstETHPriceFluid(web3, network);
145
- } else if (isMainnet) {
146
- const feedRegistryContract = FeedRegistryContract(web3, NetworkNumber.Eth);
147
- loanTokenPrice = isTokenUSDA ? '100000000' : await feedRegistryContract.methods.latestAnswer(loanTokenFeedAddress, USD_QUOTE).call();
148
- } else {
149
- // Currently only base network is supported
150
- const feedRegistryContract = DFSFeedRegistryContract(web3, network);
151
- const roundPriceData = isTokenUSDA ? { answer: '100000000' } : await feedRegistryContract.methods.latestRoundData(loanTokenFeedAddress, USD_QUOTE).call();
152
- loanTokenPrice = roundPriceData.answer;
153
- }
154
-
155
- return new Dec(loanTokenPrice).div(1e8).toString();
156
- };
157
-
158
- const parseT1MarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
159
- const collAsset = getAssetInfoByAddress(data.supplyToken0, network);
160
- const debtAsset = getAssetInfoByAddress(data.borrowToken0, network);
161
-
162
- const supplyRate = new Dec(data.supplyRateVault).div(100).toString();
163
- const borrowRate = new Dec(data.borrowRateVault).div(100).toString();
164
-
165
- const oracleScaleFactor = new Dec(27).add(debtAsset.decimals).sub(collAsset.decimals).toString();
166
- const oracleScale = new Dec(10).pow(oracleScaleFactor).toString();
167
- const oraclePrice = new Dec(data.oraclePriceOperate).div(oracleScale).toString();
168
- const debtPriceParsed = await getTokenPriceFromChainlink(debtAsset, network, web3);
169
-
170
- const collAssetData: FluidAssetData = {
171
- symbol: collAsset.symbol,
172
- address: collAsset.address,
173
- price: new Dec(debtPriceParsed).mul(oraclePrice).toString(),
174
- totalSupply: data.totalSupplyVault,
175
- totalBorrow: data.totalBorrowVault,
176
- canBeSupplied: true,
177
- canBeBorrowed: false,
178
- supplyRate,
179
- borrowRate: '0',
180
- };
181
-
182
- if (STAKING_ASSETS.includes(collAsset.symbol)) {
183
- collAssetData.incentiveSupplyApy = await getStakingApy(collAsset.symbol, mainnetWeb3);
184
- collAssetData.incentiveSupplyToken = collAsset.symbol;
185
- }
186
-
187
- const debtAssetData: FluidAssetData = {
188
- symbol: debtAsset.symbol,
189
- address: debtAsset.address,
190
- price: debtPriceParsed,
191
- totalSupply: data.totalSupplyVault,
192
- totalBorrow: data.totalBorrowVault,
193
- canBeSupplied: false,
194
- canBeBorrowed: true,
195
- supplyRate: '0',
196
- borrowRate,
197
- };
198
- if (STAKING_ASSETS.includes(debtAssetData.symbol)) {
199
- debtAssetData.incentiveBorrowApy = await getStakingApy(debtAsset.symbol, mainnetWeb3);
200
- debtAssetData.incentiveBorrowToken = debtAsset.symbol;
201
- }
202
-
203
- if (STAKING_ASSETS.includes(debtAssetData.symbol)) {
204
- debtAssetData.incentiveBorrowApy = await getStakingApy(debtAsset.symbol, mainnetWeb3);
205
- debtAssetData.incentiveBorrowToken = debtAsset.symbol;
206
- }
207
-
208
- const assetsData = {
209
- [collAsset.symbol]: collAssetData,
210
- [debtAsset.symbol]: debtAssetData,
211
- };
212
- const marketInfo = getFluidMarketInfoById(+data.vaultId, network);
213
- const totalSupplyVault = getEthAmountForDecimals(data.totalSupplyVault, collAsset.decimals);
214
- const totalBorrowVault = getEthAmountForDecimals(data.totalBorrowVault, debtAsset.decimals);
215
-
216
- const liqRatio = new Dec(data.liquidationThreshold).div(100).toString();
217
- const liquidationMaxLimit = new Dec(data.liquidationMaxLimit).div(100).toString();
218
- const liqFactor = new Dec(data.liquidationThreshold).div(10_000).toString();
219
-
220
- const marketData = {
221
- vaultId: +data.vaultId,
222
- vaultValue: marketInfo?.value,
223
- isSmartColl: data.isSmartColl,
224
- isSmartDebt: data.isSmartDebt,
225
- marketAddress: data.vault,
226
- vaultType: parseVaultType(+data.vaultType),
227
- oracle: data.oracle,
228
- liquidationPenaltyPercent: new Dec(data.liquidationPenalty).div(100).toString(),
229
- collFactor: new Dec(data.collateralFactor).div(10000).toString(), // we want actual factor, not in %, so we divide by 10000 instead of 100
230
- liquidationRatio: liqRatio,
231
- liqFactor,
232
- minRatio: new Dec(1).div(liqFactor).mul(100).toString(),
233
- collAsset0: collAsset.symbol,
234
- debtAsset0: debtAsset.symbol,
235
- totalPositions: data.totalPositions,
236
- totalSupplyVault,
237
- totalBorrowVault,
238
- totalSupplyVaultUsd: new Dec(totalSupplyVault).mul(collAssetData.price).toString(),
239
- totalBorrowVaultUsd: new Dec(totalBorrowVault).mul(debtAssetData.price).toString(),
240
- withdrawalLimit: getEthAmountForDecimals(data.withdrawalLimit, collAsset.decimals),
241
- withdrawableUntilLimit: getEthAmountForDecimals(data.withdrawableUntilLimit, collAsset.decimals),
242
- withdrawable: getEthAmountForDecimals(data.withdrawable, collAsset.decimals),
243
- borrowLimit: getEthAmountForDecimals(data.borrowLimit, debtAsset.decimals),
244
- borrowableUntilLimit: getEthAmountForDecimals(data.borrowableUntilLimit, debtAsset.decimals),
245
- borrowable: getEthAmountForDecimals(data.borrowable, debtAsset.decimals),
246
- borrowLimitUtilization: getEthAmountForDecimals(data.borrowLimitUtilization, debtAsset.decimals),
247
- maxBorrowLimit: getEthAmountForDecimals(data.maxBorrowLimit, debtAsset.decimals),
248
- baseBorrowLimit: getEthAmountForDecimals(data.baseBorrowLimit, debtAsset.decimals),
249
- minimumBorrowing: getEthAmountForDecimals(data.minimumBorrowing, debtAsset.decimals),
250
- liquidationMaxLimit,
251
- borrowRate,
252
- supplyRate,
253
- oraclePrice,
254
- };
255
-
256
- return {
257
- assetsData,
258
- marketData,
259
- } as FluidMarketData;
260
- };
261
-
262
- const getMarketRateForDex = (token1PerShare: string, token0PerShare: string, rate0: string, rate1: string) => {
263
- const sharesCombined = new Dec(token1PerShare).plus(token0PerShare);
264
-
265
- const rate0PerShare = new Dec(rate0).mul(token0PerShare).div(sharesCombined).toString();
266
-
267
- const rate1PerShare = new Dec(rate1).mul(token1PerShare).div(sharesCombined).toString();
268
-
269
- return new Dec(rate0PerShare).plus(rate1PerShare).toString();
270
- };
271
-
272
- const parseT2MarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
273
- const collAsset0 = getAssetInfoByAddress(data.supplyToken0, network);
274
- const collAsset1 = getAssetInfoByAddress(data.supplyToken1, network);
275
- const debtAsset = getAssetInfoByAddress(data.borrowToken0, network);
276
-
277
- // 18 because collateral is represented in shares for which they use 18 decimals
278
- const oracleScaleFactor = new Dec(27).add(debtAsset.decimals).sub(18).toString();
279
- const oracleScale = new Dec(10).pow(oracleScaleFactor).toString();
280
- const oraclePrice = new Dec(data.oraclePriceOperate).div(oracleScale).toString();
281
-
282
- const prices = await getChainLinkPricesForTokens([collAsset0.address, collAsset1.address, debtAsset.address], network, web3);
283
-
284
- const {
285
- supplyDexFee,
286
- totalSupplyShares,
287
- supplyRate1,
288
- totalSupplyToken1,
289
- token0PerSupplyShare,
290
- token1PerSupplyShare,
291
- totalSupplyToken0,
292
- maxSupplyShares,
293
- withdrawableToken0,
294
- withdrawable0,
295
- withdrawableToken1,
296
- withdrawable1,
297
- supplyRate0,
298
- utilizationSupply0,
299
- utilizationSupply1,
300
- withdrawableShares,
301
- reservesSupplyToken0,
302
- reservesSupplyToken1,
303
- } = parseDexSupplyData(data.dexSupplyData, collAsset0.symbol, collAsset1.symbol);
304
-
305
- const collFirstAssetData: Partial<FluidAssetData> = {
306
- symbol: collAsset0.symbol,
307
- address: collAsset0.address,
308
- price: prices[collAsset0.address],
309
- totalSupply: new Dec(totalSupplyShares).mul(token0PerSupplyShare).toString(),
310
- canBeSupplied: true,
311
- supplyRate: supplyRate0,
312
- utilization: utilizationSupply0,
313
- withdrawable: withdrawable0,
314
- tokenPerSupplyShare: token0PerSupplyShare,
315
- supplyReserves: reservesSupplyToken0,
316
- };
317
- if (STAKING_ASSETS.includes(collFirstAssetData.symbol!)) {
318
- collFirstAssetData.incentiveSupplyApy = await getStakingApy(collAsset0.symbol, mainnetWeb3);
319
- collFirstAssetData.incentiveSupplyToken = collAsset0.symbol;
320
- }
321
-
322
- const collSecondAssetData: Partial<FluidAssetData> = {
323
- symbol: collAsset1.symbol,
324
- address: collAsset1.address,
325
- price: prices[collAsset1.address],
326
- totalSupply: new Dec(totalSupplyShares).mul(token1PerSupplyShare).toString(),
327
- canBeSupplied: true,
328
- supplyRate: supplyRate1,
329
- withdrawable: withdrawable1,
330
- utilization: utilizationSupply1,
331
- tokenPerSupplyShare: token1PerSupplyShare,
332
- supplyReserves: reservesSupplyToken1,
333
- };
334
- if (STAKING_ASSETS.includes(collFirstAssetData.symbol!)) {
335
- collFirstAssetData.incentiveSupplyApy = await getStakingApy(collAsset1.symbol, mainnetWeb3);
336
- collFirstAssetData.incentiveSupplyToken = collAsset1.symbol;
337
- }
338
-
339
- const marketSupplyRate = getMarketRateForDex(token1PerSupplyShare, token0PerSupplyShare, supplyRate0, supplyRate1);
340
-
341
- const borrowRate = new Dec(data.borrowRateVault).div(100).toString();
342
- const debtAssetData: Partial<FluidAssetData> = {
343
- symbol: debtAsset.symbol,
344
- price: prices[debtAsset.address],
345
- address: debtAsset.address,
346
- totalBorrow: data.totalBorrowVault,
347
- canBeBorrowed: true,
348
- borrowRate,
349
- };
350
- if (STAKING_ASSETS.includes(debtAssetData.symbol!)) {
351
- debtAssetData.incentiveBorrowApy = await getStakingApy(debtAsset.symbol, mainnetWeb3);
352
- debtAssetData.incentiveBorrowToken = debtAsset.symbol;
353
- }
354
-
355
- const assetsData: FluidAssetsData = ([
356
- [collAsset0.symbol, collFirstAssetData],
357
- [collAsset1.symbol, collSecondAssetData],
358
- [debtAsset.symbol, debtAssetData],
359
- ] as [string, FluidAssetData][])
360
- .reduce((acc, [symbol, partialData]) => ({
361
- ...acc,
362
- [symbol]: mergeAssetData(acc[symbol], partialData),
363
- }), {} as Record<string, FluidAssetData>) as FluidAssetsData;
364
-
365
- const marketInfo = getFluidMarketInfoById(+data.vaultId, network);
366
-
367
- const totalBorrowVault = getEthAmountForDecimals(data.totalBorrowVault, debtAsset.decimals);
368
-
369
- const liqRatio = new Dec(data.liquidationThreshold).div(100).toString();
370
- const liquidationMaxLimit = new Dec(data.liquidationMaxLimit).div(100).toString();
371
- const liqFactor = new Dec(data.liquidationThreshold).div(10_000).toString();
372
-
373
- const totalSupplySharesInVault = assetAmountInEth(data.totalSupplyVault);
374
- const collSharePrice = new Dec(oraclePrice).mul(prices[debtAsset.address]).toString();
375
- const totalSupplyVaultUsd = new Dec(totalSupplySharesInVault).mul(collSharePrice).toString();
376
- const maxSupplySharesUsd = new Dec(maxSupplyShares).mul(collSharePrice).toString();
377
-
378
- const withdrawableUSD = new Dec(withdrawableShares).mul(collSharePrice).toString();
379
-
380
- const marketData = {
381
- vaultId: +data.vaultId,
382
- vaultValue: marketInfo?.value,
383
- isSmartColl: data.isSmartColl,
384
- isSmartDebt: data.isSmartDebt,
385
- marketAddress: data.vault,
386
- vaultType: parseVaultType(+data.vaultType),
387
- oracle: data.oracle,
388
- liquidationPenaltyPercent: new Dec(data.liquidationPenalty).div(100).toString(),
389
- collFactor: new Dec(data.collateralFactor).div(10000).toString(), // we want actual factor, not in %, so we divide by 10000 instead of 100
390
- liquidationRatio: liqRatio,
391
- liqFactor,
392
- minRatio: new Dec(1).div(liqFactor).mul(100).toString(),
393
- collAsset0: collAsset0.symbol,
394
- collAsset1: collAsset1.symbol,
395
- debtAsset0: debtAsset.symbol,
396
- totalPositions: data.totalPositions,
397
- totalSupplyVault: totalSupplyShares,
398
- totalBorrowVault,
399
- totalSupplyVaultUsd,
400
- collSharePrice,
401
- totalBorrowVaultUsd: new Dec(totalBorrowVault).mul(assetsData[debtAsset.symbol].price).toString(),
402
- borrowLimit: getEthAmountForDecimals(data.borrowLimit, debtAsset.decimals),
403
- borrowableUntilLimit: getEthAmountForDecimals(data.borrowableUntilLimit, debtAsset.decimals),
404
- borrowable: getEthAmountForDecimals(data.borrowable, debtAsset.decimals),
405
- borrowLimitUtilization: getEthAmountForDecimals(data.borrowLimitUtilization, debtAsset.decimals),
406
- maxBorrowLimit: getEthAmountForDecimals(data.maxBorrowLimit, debtAsset.decimals),
407
- baseBorrowLimit: getEthAmountForDecimals(data.baseBorrowLimit, debtAsset.decimals),
408
- minimumBorrowing: getEthAmountForDecimals(data.minimumBorrowing, debtAsset.decimals),
409
- liquidationMaxLimit,
410
- borrowRate,
411
- supplyRate: marketSupplyRate,
412
- totalSupplyToken0,
413
- totalSupplyToken1,
414
- withdrawableToken0,
415
- withdrawableToken1,
416
- withdrawableUSD,
417
- withdrawable: withdrawableShares,
418
- widthdrawableDex: new Dec(maxSupplyShares).minus(totalSupplyShares).toString(),
419
- maxSupplyShares,
420
- maxSupplySharesUsd,
421
- collDexFee: supplyDexFee,
422
- oraclePrice,
423
- };
424
-
425
- return {
426
- assetsData,
427
- marketData,
428
- } as FluidMarketData;
429
- };
430
-
431
-
432
- const parseT3MarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
433
- const collAsset = getAssetInfoByAddress(data.supplyToken0, network);
434
- const debtAsset0 = getAssetInfoByAddress(data.borrowToken0, network);
435
- const debtAsset1 = getAssetInfoByAddress(data.borrowToken1, network);
436
-
437
- const {
438
- borrowableShares,
439
- maxBorrowShares,
440
- borrowDexFee,
441
- utilizationBorrow0,
442
- utilizationBorrow1,
443
- borrowable0,
444
- borrowable1,
445
- borrowRate0,
446
- borrowRate1,
447
- totalBorrowShares,
448
- token0PerBorrowShare,
449
- token1PerBorrowShare,
450
- borrowableToken0,
451
- borrowableToken1,
452
- totalBorrowToken0,
453
- totalBorrowToken1,
454
- reservesBorrowToken0,
455
- reservesBorrowToken1,
456
- } = parseDexBorrowData(data.dexBorrowData, debtAsset0.symbol, debtAsset1.symbol);
457
-
458
- // 18 because debt is represented in shares for which they use 18 decimals
459
- const oracleScaleFactor = new Dec(27).add(18).sub(collAsset.decimals).toString();
460
- const oracleScale = new Dec(10).pow(oracleScaleFactor).toString();
461
- const oraclePrice = new Dec(1).div(new Dec(data.oraclePriceOperate).div(oracleScale)).toString();
462
-
463
- const prices = await getChainLinkPricesForTokens([collAsset.address, debtAsset0.address, debtAsset1.address], network, web3);
464
-
465
- const supplyRate = new Dec(data.supplyRateVault).div(100).toString();
466
- const collAssetData: Partial<FluidAssetData> = {
467
- symbol: collAsset.symbol,
468
- address: collAsset.address,
469
- price: prices[collAsset.address],
470
- totalSupply: data.totalSupplyVault,
471
- canBeSupplied: true,
472
- supplyRate,
473
- };
474
- if (STAKING_ASSETS.includes(collAssetData.symbol!)) {
475
- collAssetData.incentiveSupplyApy = await getStakingApy(collAsset.symbol, mainnetWeb3);
476
- collAssetData.incentiveSupplyToken = collAsset.symbol;
477
- }
478
-
479
- const debtAsset0Data: Partial<FluidAssetData> = {
480
- symbol: debtAsset0.symbol,
481
- address: debtAsset0.address,
482
- price: prices[debtAsset0.address],
483
- totalBorrow: new Dec(totalBorrowShares).mul(token0PerBorrowShare).toString(),
484
- canBeBorrowed: true,
485
- borrowRate: borrowRate0,
486
- borrowable: borrowable0,
487
- utilization: utilizationBorrow0,
488
- tokenPerBorrowShare: token0PerBorrowShare,
489
- borrowReserves: reservesBorrowToken0,
490
- };
491
- if (STAKING_ASSETS.includes(debtAsset0Data.symbol!)) {
492
- debtAsset0Data.incentiveSupplyApy = await getStakingApy(debtAsset0.symbol, mainnetWeb3);
493
- debtAsset0Data.incentiveSupplyToken = debtAsset0.symbol;
494
- }
495
-
496
- const debtAsset1Data: Partial<FluidAssetData> = {
497
- symbol: debtAsset1.symbol,
498
- address: debtAsset1.address,
499
- price: prices[debtAsset1.address],
500
- totalBorrow: new Dec(totalBorrowShares).mul(token1PerBorrowShare).toString(),
501
- canBeBorrowed: true,
502
- borrowRate: borrowRate1,
503
- borrowable: borrowable1,
504
- utilization: utilizationBorrow1,
505
- tokenPerBorrowShare: token1PerBorrowShare,
506
- borrowReserves: reservesBorrowToken1,
507
- };
508
- if (STAKING_ASSETS.includes(debtAsset1Data.symbol!)) {
509
- debtAsset1Data.incentiveSupplyApy = await getStakingApy(debtAsset1.symbol, mainnetWeb3);
510
- debtAsset1Data.incentiveSupplyToken = debtAsset1.symbol;
511
- }
512
- const marketBorrowRate = getMarketRateForDex(token1PerBorrowShare, token0PerBorrowShare, borrowRate0, borrowRate1);
513
-
514
- const assetsData: FluidAssetsData = ([
515
- [collAsset.symbol, collAssetData],
516
- [debtAsset0.symbol, debtAsset0Data],
517
- [debtAsset1.symbol, debtAsset1Data],
518
- ] as [string, FluidAssetData][])
519
- .reduce((acc, [symbol, partialData]) => ({
520
- ...acc,
521
- [symbol]: mergeAssetData(acc[symbol], partialData),
522
- }), {} as Record<string, FluidAssetData>) as FluidAssetsData;
523
-
524
- const marketInfo = getFluidMarketInfoById(+data.vaultId, network);
525
-
526
- const totalSupplyVault = getEthAmountForDecimals(data.totalSupplyVault, collAsset.decimals);
527
-
528
- const liqRatio = new Dec(data.liquidationThreshold).div(100).toString();
529
- const liquidationMaxLimit = new Dec(data.liquidationMaxLimit).div(100).toString();
530
- const liqFactor = new Dec(data.liquidationThreshold).div(10_000).toString();
531
-
532
- const debtSharePrice = new Dec(oraclePrice).mul(prices[collAsset.address]).toString();
533
-
534
- const totalBorrowSharesInVault = assetAmountInEth(data.totalBorrowVault);
535
-
536
- const totalBorrowVaultUsd = new Dec(totalBorrowSharesInVault).mul(debtSharePrice).toString();
537
-
538
- const borrowableUSD = new Dec(borrowableShares).mul(debtSharePrice).toString();
539
- const maxBorrowSharesUsd = new Dec(maxBorrowShares).mul(debtSharePrice).toString();
540
-
541
- const marketData = {
542
- vaultId: +data.vaultId,
543
- vaultValue: marketInfo?.value,
544
- isSmartColl: data.isSmartColl,
545
- isSmartDebt: data.isSmartDebt,
546
- marketAddress: data.vault,
547
- vaultType: parseVaultType(+data.vaultType),
548
- oracle: data.oracle,
549
- liquidationPenaltyPercent: new Dec(data.liquidationPenalty).div(100).toString(),
550
- collFactor: new Dec(data.collateralFactor).div(10000).toString(), // we want actual factor, not in %, so we divide by 10000 instead of 100
551
- liquidationRatio: liqRatio,
552
- liqFactor,
553
- minRatio: new Dec(1).div(liqFactor).mul(100).toString(),
554
- collAsset0: collAsset.symbol,
555
- debtAsset0: debtAsset0.symbol,
556
- debtAsset1: debtAsset1.symbol,
557
- totalPositions: data.totalPositions,
558
- totalSupplyVault,
559
- totalBorrowVault: totalBorrowShares,
560
- totalSupplyVaultUsd: new Dec(totalSupplyVault).mul(assetsData[collAsset.symbol].price).toString(),
561
- totalBorrowVaultUsd,
562
- withdrawalLimit: getEthAmountForDecimals(data.withdrawalLimit, collAsset.decimals),
563
- withdrawableUntilLimit: getEthAmountForDecimals(data.withdrawableUntilLimit, collAsset.decimals),
564
- withdrawable: getEthAmountForDecimals(data.withdrawable, collAsset.decimals),
565
- liquidationMaxLimit,
566
- borrowRate: marketBorrowRate,
567
- supplyRate,
568
- borrowableToken0,
569
- borrowableToken1,
570
- totalBorrowToken0,
571
- totalBorrowToken1,
572
- borrowableUSD,
573
- borrowable: borrowableShares,
574
- borrowableDex: new Dec(maxBorrowShares).minus(totalBorrowShares).toString(),
575
- maxBorrowShares,
576
- maxBorrowSharesUsd,
577
- borrowDexFee,
578
- debtSharePrice,
579
- oraclePrice,
580
- };
581
-
582
- return {
583
- assetsData,
584
- marketData,
585
- } as FluidMarketData;
586
- };
587
-
588
- const parseT4MarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
589
- const collAsset0 = getAssetInfoByAddress(data.supplyToken0, network);
590
- const collAsset1 = getAssetInfoByAddress(data.supplyToken1, network);
591
- const debtAsset0 = getAssetInfoByAddress(data.borrowToken0, network);
592
- const debtAsset1 = getAssetInfoByAddress(data.borrowToken1, network);
593
- const quoteToken = getAssetInfoByAddress(data.dexBorrowData.quoteToken, network);
594
-
595
- // 27 - 18 + 18
596
- const oracleScaleFactor = new Dec(27).toString();
597
- const oracleScale = new Dec(10).pow(oracleScaleFactor).toString();
598
- const oraclePrice = new Dec(data.oraclePriceOperate).div(oracleScale).toString();
599
-
600
- const prices = await getChainLinkPricesForTokens(
601
- [collAsset0.address, collAsset1.address, debtAsset0.address, debtAsset1.address],
602
- network, web3);
603
-
604
- const {
605
- supplyDexFee,
606
- totalSupplyShares,
607
- supplyRate1,
608
- token0PerSupplyShare,
609
- token1PerSupplyShare,
610
- totalSupplyToken0,
611
- totalSupplyToken1,
612
- maxSupplyShares,
613
- withdrawableToken0,
614
- withdrawable0,
615
- withdrawableToken1,
616
- withdrawable1,
617
- supplyRate0,
618
- utilizationSupply0,
619
- utilizationSupply1,
620
- withdrawableShares,
621
- reservesSupplyToken0,
622
- reservesSupplyToken1,
623
- } = parseDexSupplyData(data.dexSupplyData, collAsset0.symbol, collAsset1.symbol);
624
-
625
- const {
626
- borrowableShares,
627
- maxBorrowShares,
628
- borrowDexFee,
629
- utilizationBorrow0,
630
- utilizationBorrow1,
631
- borrowable0,
632
- borrowable1,
633
- borrowRate0,
634
- borrowRate1,
635
- totalBorrowShares,
636
- token0PerBorrowShare,
637
- token1PerBorrowShare,
638
- borrowableToken0,
639
- borrowableToken1,
640
- totalBorrowToken0,
641
- totalBorrowToken1,
642
- quoteTokensPerShare,
643
- reservesBorrowToken0,
644
- reservesBorrowToken1,
645
- } = parseDexBorrowData(data.dexBorrowData, debtAsset0.symbol, debtAsset1.symbol);
646
-
647
- const collAsset0Data: Partial<FluidAssetData> = {
648
- symbol: collAsset0.symbol,
649
- address: collAsset0.address,
650
- price: prices[collAsset0.address],
651
- totalSupply: new Dec(totalSupplyShares).mul(token0PerSupplyShare).toString(),
652
- canBeSupplied: true,
653
- supplyRate: supplyRate0,
654
- utilization: utilizationSupply0,
655
- withdrawable: withdrawable0,
656
- tokenPerSupplyShare: token0PerSupplyShare,
657
- supplyReserves: reservesSupplyToken0,
658
- };
659
- if (STAKING_ASSETS.includes(collAsset0Data.symbol!)) {
660
- collAsset0Data.incentiveSupplyApy = await getStakingApy(collAsset0.symbol, mainnetWeb3);
661
- collAsset0Data.incentiveSupplyToken = collAsset0.symbol;
662
- }
663
-
664
- const collAsset1Data: Partial<FluidAssetData> = {
665
- symbol: collAsset1.symbol,
666
- address: collAsset1.address,
667
- price: prices[collAsset1.address],
668
- totalSupply: new Dec(totalSupplyShares).mul(token1PerSupplyShare).toString(),
669
- canBeSupplied: true,
670
- supplyRate: supplyRate1,
671
- withdrawable: withdrawable1,
672
- utilization: utilizationSupply1,
673
- tokenPerSupplyShare: token1PerSupplyShare,
674
- supplyReserves: reservesSupplyToken1,
675
- };
676
- if (STAKING_ASSETS.includes(collAsset1Data.symbol!)) {
677
- collAsset1Data.incentiveSupplyApy = await getStakingApy(collAsset1.symbol, mainnetWeb3);
678
- collAsset1Data.incentiveSupplyToken = collAsset1.symbol;
679
- }
680
-
681
- const debtAsset0Data: Partial<FluidAssetData> = {
682
- symbol: debtAsset0.symbol,
683
- address: debtAsset0.address,
684
- price: prices[debtAsset0.address],
685
- totalBorrow: new Dec(totalBorrowShares).mul(token0PerBorrowShare).toString(),
686
- canBeBorrowed: true,
687
- borrowRate: borrowRate0,
688
- borrowable: borrowable0,
689
- utilization: utilizationBorrow0,
690
- tokenPerBorrowShare: token0PerBorrowShare,
691
- borrowReserves: reservesBorrowToken0,
692
- };
693
- if (STAKING_ASSETS.includes(debtAsset0Data.symbol!)) {
694
- debtAsset0Data.incentiveSupplyApy = await getStakingApy(debtAsset0.symbol, mainnetWeb3);
695
- debtAsset0Data.incentiveSupplyToken = debtAsset0.symbol;
696
- }
697
-
698
- const debtAsset1Data: Partial<FluidAssetData> = {
699
- symbol: debtAsset1.symbol,
700
- address: debtAsset1.address,
701
- price: prices[debtAsset1.address],
702
- totalBorrow: new Dec(totalBorrowShares).mul(token1PerBorrowShare).toString(),
703
- canBeBorrowed: true,
704
- borrowRate: borrowRate1,
705
- borrowable: borrowable1,
706
- utilization: utilizationBorrow1,
707
- tokenPerBorrowShare: token1PerBorrowShare,
708
- borrowReserves: reservesBorrowToken1,
709
- };
710
- if (STAKING_ASSETS.includes(debtAsset1Data.symbol!)) {
711
- debtAsset1Data.incentiveSupplyApy = await getStakingApy(debtAsset1.symbol, mainnetWeb3);
712
- debtAsset1Data.incentiveSupplyToken = debtAsset1.symbol;
713
- }
714
-
715
- const marketBorrowRate = getMarketRateForDex(token1PerBorrowShare, token0PerBorrowShare, borrowRate0, borrowRate1);
716
- const marketSupplyRate = getMarketRateForDex(token1PerSupplyShare, token0PerSupplyShare, supplyRate0, supplyRate1);
717
-
718
- const assetsData: FluidAssetsData = ([
719
- [collAsset0.symbol, collAsset0Data],
720
- [collAsset1.symbol, collAsset1Data],
721
- [debtAsset0.symbol, debtAsset0Data],
722
- [debtAsset1.symbol, debtAsset1Data],
723
- ] as [string, FluidAssetData][])
724
- .reduce((acc, [symbol, partialData]) => ({
725
- ...acc,
726
- [symbol]: mergeAssetData(acc[symbol], partialData),
727
- }), {} as Record<string, FluidAssetData>) as FluidAssetsData;
728
-
729
- const marketInfo = getFluidMarketInfoById(+data.vaultId, network);
730
-
731
- const liqRatio = new Dec(data.liquidationThreshold).div(100).toString();
732
- const liquidationMaxLimit = new Dec(data.liquidationMaxLimit).div(100).toString();
733
- const liqFactor = new Dec(data.liquidationThreshold).div(10_000).toString();
734
-
735
- const totalBorrowSharesInVault = assetAmountInEth(data.totalBorrowVault);
736
- const debtSharePrice = new Dec(quoteTokensPerShare).mul(prices[quoteToken.address]).toString();
737
- const totalBorrowVaultUsd = new Dec(totalBorrowSharesInVault).mul(debtSharePrice).toString();
738
- const maxBorrowSharesUsd = new Dec(maxBorrowShares).mul(debtSharePrice).toString();
739
- const borrowableUSD = new Dec(borrowableShares).mul(debtSharePrice).toString();
740
-
741
- const totalSupplySharesInVault = assetAmountInEth(data.totalSupplyVault);
742
- const collSharePrice = new Dec(oraclePrice).mul(debtSharePrice).toString();
743
- const totalSupplyVaultUsd = new Dec(totalSupplySharesInVault).mul(collSharePrice).toString();
744
- const maxSupplySharesUsd = new Dec(maxSupplyShares).mul(collSharePrice).toString();
745
- const withdrawableUSD = new Dec(withdrawableShares).mul(collSharePrice).toString();
746
-
747
- const marketData = {
748
- vaultId: +data.vaultId,
749
- vaultValue: marketInfo?.value,
750
- isSmartColl: data.isSmartColl,
751
- isSmartDebt: data.isSmartDebt,
752
- marketAddress: data.vault,
753
- vaultType: parseVaultType(+data.vaultType),
754
- oracle: data.oracle,
755
- liquidationPenaltyPercent: new Dec(data.liquidationPenalty).div(100).toString(),
756
- collFactor: new Dec(data.collateralFactor).div(10000).toString(), // we want actual factor, not in %, so we divide by 10000 instead of 100
757
- liquidationRatio: liqRatio,
758
- liqFactor,
759
- minRatio: new Dec(1).div(liqFactor).mul(100).toString(),
760
- collAsset0: collAsset0.symbol,
761
- collAsset1: collAsset1.symbol,
762
- debtAsset0: debtAsset0.symbol,
763
- debtAsset1: debtAsset1.symbol,
764
- totalPositions: data.totalPositions,
765
- totalSupplyVault: totalSupplyShares,
766
- totalBorrowVault: totalBorrowShares,
767
- totalSupplyVaultUsd,
768
- totalBorrowVaultUsd,
769
- liquidationMaxLimit,
770
- borrowRate: marketBorrowRate,
771
- supplyRate: marketSupplyRate,
772
- borrowableToken0,
773
- borrowableToken1,
774
- totalBorrowToken0,
775
- totalBorrowToken1,
776
- borrowableUSD,
777
- borrowable: borrowableShares,
778
- borrowableDex: new Dec(maxBorrowShares).minus(totalBorrowShares).toString(),
779
- maxBorrowShares,
780
- maxBorrowSharesUsd,
781
- borrowDexFee,
782
- totalSupplyToken0,
783
- totalSupplyToken1,
784
- withdrawableToken0,
785
- withdrawableToken1,
786
- withdrawableUSD,
787
- withdrawable: withdrawableShares,
788
- widthdrawableDex: new Dec(maxSupplyShares).minus(totalSupplyShares).toString(),
789
- maxSupplyShares,
790
- maxSupplySharesUsd,
791
- collDexFee: supplyDexFee,
792
- collSharePrice,
793
- debtSharePrice,
794
- oraclePrice,
795
- };
796
-
797
- return {
798
- assetsData,
799
- marketData,
800
- } as FluidMarketData;
801
- };
802
-
803
- const parseMarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
804
- const vaultType = parseVaultType(+data.vaultType);
805
- switch (vaultType) {
806
- case FluidVaultType.T1:
807
- return parseT1MarketData(web3, data, network, mainnetWeb3);
808
- case FluidVaultType.T2:
809
- return parseT2MarketData(web3, data, network, mainnetWeb3);
810
- case FluidVaultType.T3:
811
- return parseT3MarketData(web3, data, network, mainnetWeb3);
812
- case FluidVaultType.T4:
813
- return parseT4MarketData(web3, data, network, mainnetWeb3);
814
- default:
815
- throw new Error(`Unknown vault type: ${vaultType}`);
816
- }
817
- };
818
-
819
- export const EMPTY_FLUID_DATA = {
820
- usedAssets: {},
821
- suppliedUsd: '0',
822
- borrowedUsd: '0',
823
- borrowLimitUsd: '0',
824
- leftToBorrowUsd: '0',
825
- ratio: '0',
826
- minRatio: '0',
827
- netApy: '0',
828
- incentiveUsd: '0',
829
- totalInterestUsd: '0',
830
- isSubscribedToAutomation: false,
831
- automationResubscribeRequired: false,
832
- lastUpdated: Date.now(),
833
- };
834
-
835
- const parseT1UserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData): FluidVaultData => {
836
- const {
837
- assetsData,
838
- marketData,
839
- } = vaultData;
840
-
841
- const payload = {
842
- owner: userPositionData.owner,
843
- vaultId: marketData.vaultId,
844
- ...EMPTY_FLUID_DATA,
845
- lastUpdated: Date.now(),
846
- };
847
- const collAsset = getAssetInfo(marketData.collAsset0);
848
- const debtAsset = getAssetInfo(marketData.debtAsset0);
849
-
850
- // for T2 and T4 - this is the number of shares
851
- const supplied = getEthAmountForDecimals(userPositionData.supply, collAsset.decimals);
852
- const borrowed = getEthAmountForDecimals(userPositionData.borrow, debtAsset.decimals);
853
-
854
- const collUsedAsset: FluidUsedAsset = {
855
- ...EMPTY_USED_ASSET,
856
- symbol: collAsset.symbol,
857
- collateral: true,
858
- supplied,
859
- suppliedUsd: new Dec(supplied).mul(assetsData[collAsset.symbol].price).toString(),
860
- isSupplied: new Dec(supplied).gt(0),
861
- };
862
-
863
- const debtUsedAsset: FluidUsedAsset = {
864
- ...EMPTY_USED_ASSET,
865
- symbol: debtAsset.symbol,
866
- collateral: false,
867
- borrowed,
868
- borrowedUsd: new Dec(borrowed).mul(assetsData[debtAsset.symbol].price).toString(),
869
- isBorrowed: new Dec(borrowed).gt(0),
870
- };
871
-
872
- const usedAssets: FluidUsedAssets = {
873
- [collAsset.symbol]: collUsedAsset,
874
- [debtAsset.symbol]: debtUsedAsset,
875
- };
876
-
877
- return {
878
- ...payload,
879
- usedAssets,
880
- ...(getFluidAggregatedData({
881
- usedAssets,
882
- assetsData,
883
- marketData,
884
- }) as FluidAggregatedVaultData),
885
- };
886
- };
887
-
888
- const parseT2UserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData): FluidVaultData => {
889
- const {
890
- assetsData,
891
- marketData,
892
- } = vaultData;
893
-
894
- const payload = {
895
- owner: userPositionData.owner,
896
- vaultId: marketData.vaultId,
897
- ...EMPTY_FLUID_DATA,
898
- lastUpdated: Date.now(),
899
- };
900
-
901
- const collAsset0 = getAssetInfo(marketData.collAsset0);
902
- const collAsset1 = getAssetInfo(marketData.collAsset1);
903
- const debtAsset = getAssetInfo(marketData.debtAsset0);
904
-
905
- const supplyShares = getEthAmountForDecimals(userPositionData.supply, 18); // this is supplied in coll shares
906
- const borrowed = getEthAmountForDecimals(userPositionData.borrow, debtAsset.decimals); // this is actual token borrow
907
-
908
- const supplied0 = new Dec(supplyShares).mul(assetsData[collAsset0.symbol].tokenPerSupplyShare!).toString();
909
- const supplied1 = new Dec(supplyShares).mul(assetsData[collAsset1.symbol].tokenPerSupplyShare!).toString();
910
-
911
- const collUsedAsset0: Partial<FluidUsedAsset> = {
912
- symbol: collAsset0.symbol,
913
- collateral: true,
914
- supplied: supplied0,
915
- suppliedUsd: new Dec(supplied0).mul(assetsData[collAsset0.symbol].price).toString(),
916
- isSupplied: new Dec(supplied0).gt(0),
917
- };
918
-
919
- const collUsedAsset1: Partial<FluidUsedAsset> = {
920
- symbol: collAsset1.symbol,
921
- collateral: true,
922
- supplied: supplied1,
923
- suppliedUsd: new Dec(supplied1).mul(assetsData[collAsset1.symbol].price).toString(),
924
- isSupplied: new Dec(supplied1).gt(0),
925
- };
926
-
927
- const debtUsedAsset: Partial<FluidUsedAsset> = {
928
- symbol: debtAsset.symbol,
929
- borrowed,
930
- borrowedUsd: new Dec(borrowed).mul(assetsData[debtAsset.symbol].price).toString(),
931
- isBorrowed: new Dec(borrowed).gt(0),
932
- };
933
-
934
- const usedAssets: FluidUsedAssets = ([
935
- [collAsset0.symbol, collUsedAsset0],
936
- [collAsset1.symbol, collUsedAsset1],
937
- [debtAsset.symbol, debtUsedAsset],
938
- ] as [string, FluidUsedAsset][])
939
- .reduce((acc, [symbol, partialData]) => {
940
- acc[symbol] = mergeUsedAssets(acc[symbol], partialData);
941
- return acc;
942
- }, {} as Record<string, FluidUsedAsset>) as FluidUsedAssets;
943
-
944
- return {
945
- ...payload,
946
- usedAssets,
947
- supplyShares,
948
- ...(getFluidAggregatedData({
949
- usedAssets,
950
- assetsData,
951
- marketData,
952
- }, supplyShares) as FluidAggregatedVaultData),
953
- };
954
- };
955
-
956
- const parseT3UserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData): FluidVaultData => {
957
- const {
958
- assetsData,
959
- marketData,
960
- } = vaultData;
961
-
962
- const payload = {
963
- owner: userPositionData.owner,
964
- vaultId: marketData.vaultId,
965
- ...EMPTY_FLUID_DATA,
966
- lastUpdated: Date.now(),
967
- };
968
-
969
- const collAsset = getAssetInfo(marketData.collAsset0);
970
- const debtAsset0 = getAssetInfo(marketData.debtAsset0);
971
- const debtAsset1 = getAssetInfo(marketData.debtAsset1);
972
-
973
- const supplied = getEthAmountForDecimals(userPositionData.supply, collAsset.decimals); // this is actual token supply
974
- const borrowShares = getEthAmountForDecimals(userPositionData.borrow, 18); // this is actual token borrow
975
-
976
- const borrowed0 = new Dec(borrowShares).mul(assetsData[debtAsset0.symbol].tokenPerBorrowShare!).toString();
977
- const borrowed1 = new Dec(borrowShares).mul(assetsData[debtAsset1.symbol].tokenPerBorrowShare!).toString();
978
-
979
- const collUsedAsset: Partial<FluidUsedAsset> = {
980
- symbol: collAsset.symbol,
981
- collateral: true,
982
- supplied,
983
- suppliedUsd: new Dec(supplied).mul(assetsData[collAsset.symbol].price).toString(),
984
- isSupplied: new Dec(supplied).gt(0),
985
- };
986
-
987
- const debtUsedAsset0: Partial<FluidUsedAsset> = {
988
- symbol: debtAsset0.symbol,
989
- borrowed: borrowed0,
990
- borrowedUsd: new Dec(borrowed0).mul(assetsData[debtAsset0.symbol].price).toString(),
991
- isBorrowed: new Dec(borrowed0).gt(0),
992
- };
993
-
994
- const debtUsedAsset1: Partial<FluidUsedAsset> = {
995
- symbol: debtAsset1.symbol,
996
- borrowed: borrowed1,
997
- borrowedUsd: new Dec(borrowed1).mul(assetsData[debtAsset1.symbol].price).toString(),
998
- isBorrowed: new Dec(borrowed1).gt(0),
999
- };
1000
-
1001
- const usedAssets: FluidUsedAssets = ([
1002
- [collAsset.symbol, collUsedAsset],
1003
- [debtAsset0.symbol, debtUsedAsset0],
1004
- [debtAsset1.symbol, debtUsedAsset1],
1005
- ] as [string, FluidUsedAsset][])
1006
- .reduce((acc, [symbol, partialData]) => {
1007
- acc[symbol] = mergeUsedAssets(acc[symbol], partialData);
1008
- return acc;
1009
- }, {} as Record<string, FluidUsedAsset>) as FluidUsedAssets;
1010
-
1011
-
1012
- return {
1013
- ...payload,
1014
- usedAssets,
1015
- borrowShares,
1016
- ...(getFluidAggregatedData({
1017
- usedAssets,
1018
- assetsData,
1019
- marketData,
1020
- }, '', borrowShares) as FluidAggregatedVaultData),
1021
- };
1022
- };
1023
-
1024
- const parseT4UserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData): FluidVaultData => {
1025
- const {
1026
- assetsData,
1027
- marketData,
1028
- } = vaultData;
1029
-
1030
- const payload = {
1031
- owner: userPositionData.owner,
1032
- vaultId: marketData.vaultId,
1033
- ...EMPTY_FLUID_DATA,
1034
- lastUpdated: Date.now(),
1035
- };
1036
-
1037
- const collAsset0 = getAssetInfo(marketData.collAsset0);
1038
- const collAsset1 = getAssetInfo(marketData.collAsset1);
1039
- const debtAsset0 = getAssetInfo(marketData.debtAsset0);
1040
- const debtAsset1 = getAssetInfo(marketData.debtAsset1);
1041
-
1042
- const supplyShares = getEthAmountForDecimals(userPositionData.supply, 18); // this is actual token supply
1043
- const borrowShares = getEthAmountForDecimals(userPositionData.borrow, 18); // this is actual token borrow
1044
-
1045
- const supplied0 = new Dec(supplyShares).mul(assetsData[collAsset0.symbol].tokenPerSupplyShare!).toString();
1046
- const supplied1 = new Dec(supplyShares).mul(assetsData[collAsset1.symbol].tokenPerSupplyShare!).toString();
1047
-
1048
- const borrowed0 = new Dec(borrowShares).mul(assetsData[debtAsset0.symbol].tokenPerBorrowShare!).toString();
1049
- const borrowed1 = new Dec(borrowShares).mul(assetsData[debtAsset1.symbol].tokenPerBorrowShare!).toString();
1050
-
1051
- const collUsedAsset0: Partial<FluidUsedAsset> = {
1052
- symbol: collAsset0.symbol,
1053
- collateral: true,
1054
- supplied: supplied0,
1055
- suppliedUsd: new Dec(supplied0).mul(assetsData[collAsset0.symbol].price).toString(),
1056
- isSupplied: new Dec(supplied0).gt(0),
1057
- };
1058
- const collUsedAsset1: Partial<FluidUsedAsset> = {
1059
- symbol: collAsset1.symbol,
1060
- collateral: true,
1061
- supplied: supplied1,
1062
- suppliedUsd: new Dec(supplied1).mul(assetsData[collAsset1.symbol].price).toString(),
1063
- isSupplied: new Dec(supplied1).gt(0),
1064
- };
1065
-
1066
- const debtUsedAsset0: Partial<FluidUsedAsset> = {
1067
- symbol: debtAsset0.symbol,
1068
- borrowed: borrowed0,
1069
- borrowedUsd: new Dec(borrowed0).mul(assetsData[debtAsset0.symbol].price).toString(),
1070
- isBorrowed: new Dec(borrowed0).gt(0),
1071
- };
1072
- const debtUsedAsset1: Partial<FluidUsedAsset> = {
1073
- symbol: debtAsset1.symbol,
1074
- borrowed: borrowed1,
1075
- borrowedUsd: new Dec(borrowed1).mul(assetsData[debtAsset1.symbol].price).toString(),
1076
- isBorrowed: new Dec(borrowed1).gt(0),
1077
- };
1078
-
1079
- const usedAssets: FluidUsedAssets = ([
1080
- [collAsset0.symbol, collUsedAsset0],
1081
- [collAsset1.symbol, collUsedAsset1],
1082
- [debtAsset0.symbol, debtUsedAsset0],
1083
- [debtAsset1.symbol, debtUsedAsset1],
1084
- ] as [string, FluidUsedAsset][])
1085
- .reduce((acc, [symbol, partialData]) => {
1086
- acc[symbol] = mergeUsedAssets(acc[symbol], partialData);
1087
- return acc;
1088
- }, {} as Record<string, FluidUsedAsset>) as FluidUsedAssets;
1089
-
1090
- return {
1091
- ...payload,
1092
- usedAssets,
1093
- supplyShares,
1094
- borrowShares,
1095
- ...(getFluidAggregatedData({
1096
- usedAssets,
1097
- assetsData,
1098
- marketData,
1099
- }, supplyShares, borrowShares) as FluidAggregatedVaultData),
1100
- };
1101
- };
1102
-
1103
- const parseUserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData) => {
1104
- const vaultType = vaultData.marketData.vaultType;
1105
- switch (vaultType) {
1106
- case FluidVaultType.T1:
1107
- return parseT1UserData(userPositionData, vaultData);
1108
- case FluidVaultType.T2:
1109
- return parseT2UserData(userPositionData, vaultData);
1110
- case FluidVaultType.T3:
1111
- return parseT3UserData(userPositionData, vaultData);
1112
- case FluidVaultType.T4:
1113
- return parseT4UserData(userPositionData, vaultData);
1114
- default:
1115
- throw new Error(`Unknown vault type: ${vaultType}`);
1116
- }
1117
- };
1118
-
1119
- export const getFluidMarketData = async (web3: Web3, network: NetworkNumber, market: FluidMarketInfo, mainnetWeb3: Web3) => {
1120
- const view = FluidViewContract(web3, network);
1121
-
1122
- const data = await view.methods.getVaultData(market.marketAddress).call();
1123
-
1124
- return parseMarketData(web3, data, network, mainnetWeb3);
1125
- };
1126
-
1127
- export const getFluidVaultIdsForUser = async (web3: Web3,
1128
- network:NetworkNumber,
1129
- user: EthAddress): Promise<string[]> => {
1130
- const view = FluidViewContract(web3, network);
1131
-
1132
- return view.methods.getUserNftIds(user).call();
1133
- };
1134
-
1135
-
1136
- export const getFluidPosition = async (
1137
- web3: Web3,
1138
- network: NetworkNumber,
1139
- vaultId: string,
1140
- extractedState: {
1141
- assetsData: FluidAssetsData
1142
- marketData: InnerFluidMarketData,
1143
- },
1144
- ): Promise<FluidVaultData> => {
1145
- const view = FluidViewContract(web3, network);
1146
-
1147
- const data = await view.methods.getPositionByNftId(vaultId).call();
1148
-
1149
- const userPositionData = data[0];
1150
-
1151
- return parseUserData(userPositionData, extractedState);
1152
- };
1153
-
1154
- export const getFluidPositionWithMarket = async (web3: Web3, network: NetworkNumber, vaultId: string, mainnetWeb3: Web3) => {
1155
- const view = FluidViewContract(web3, network);
1156
- const data = await view.methods.getPositionByNftId(vaultId).call();
1157
- const marketData = await parseMarketData(web3, data.vault, network, mainnetWeb3);
1158
- const userData = parseUserData(data.position, marketData);
1159
-
1160
- return {
1161
- userData,
1162
- marketData,
1163
- };
1164
- };
1165
-
1166
- export const getAllFluidMarketDataChunked = async (network: NetworkNumber, web3: Web3, mainnetWeb3: Web3) => {
1167
- const versions = getFluidVersionsDataForNetwork(network);
1168
- const view = FluidViewContract(web3, network);
1169
- const calls = versions.map((version) => ({
1170
- target: view.options.address,
1171
- abiItem: view.options.jsonInterface.find((item) => item.name === 'getVaultData'),
1172
- params: [version.marketAddress],
1173
- }));
1174
-
1175
- const data = await chunkAndMulticall(calls, 10, 'latest', web3, network);
1176
- // @ts-ignore
1177
- return Promise.all(data.map(async (item, i) => parseMarketData(web3, item.vaultData, network, mainnetWeb3)));
1178
- };
1179
-
1180
- export const getFluidTokenData = async (web3: Web3, network: NetworkNumber, token: string) => {
1181
- const view = FluidViewContract(web3, network);
1182
- const fTokenAddress = getFTokenAddress(token, network);
1183
- const data = await view.methods.getFTokenData(fTokenAddress).call();
1184
- const supplyRate = new Dec(data.supplyRate).div(100).toString();
1185
- const rewardsRate = new Dec(data.rewardsRate).div(1e12).toString();
1186
- const decimals = data.decimals;
1187
-
1188
- const depositRate = new Dec(getEthAmountForDecimals(data.convertToShares, decimals)).toString();
1189
- const withdrawRate = new Dec(getEthAmountForDecimals(data.convertToAssets, decimals)).toString();
1190
-
1191
- return {
1192
- fTokenAddress,
1193
- fTokenSymbol: data.symbol,
1194
- decimals,
1195
- totalDeposited: getEthAmountForDecimals(data.totalAssets, decimals),
1196
- withdrawable: getEthAmountForDecimals(data.withdrawable, decimals),
1197
- apy: new Dec(supplyRate).add(rewardsRate).toString(),
1198
- depositRate,
1199
- withdrawRate,
1200
- };
1201
- };
1202
-
1203
- export const getFluidDepositData = async (web3: Web3, network: NetworkNumber, token: string, address: EthAddress) => {
1204
- const view = FluidViewContract(web3, network);
1205
- const fTokenAddress = getFTokenAddress(token, network);
1206
- const { fTokenData, userPosition } = await view.methods.getUserEarnPositionWithFToken(fTokenAddress, address).call();
1207
-
1208
- const supplyRate = new Dec(fTokenData.supplyRate).div(100).toString();
1209
- const rewardsRate = new Dec(fTokenData.rewardsRate).div(1e12).toString();
1210
- const decimals = fTokenData.decimals;
1211
-
1212
- const depositRate = new Dec(getEthAmountForDecimals(fTokenData.convertToShares, decimals)).toString();
1213
- const withdrawRate = new Dec(getEthAmountForDecimals(fTokenData.convertToAssets, decimals)).toString();
1214
-
1215
- return {
1216
- fTokenAddress,
1217
- fTokenSymbol: fTokenData.symbol,
1218
- decimals,
1219
- totalDeposited: getEthAmountForDecimals(fTokenData.totalAssets, decimals),
1220
- withdrawable: getEthAmountForDecimals(fTokenData.withdrawable, decimals),
1221
- apy: new Dec(supplyRate).add(rewardsRate).toString(),
1222
- depositRate,
1223
- withdrawRate,
1224
- deposited: getEthAmountForDecimals(userPosition.underlyingAssets, decimals),
1225
- depositedShares: getEthAmountForDecimals(userPosition.fTokenShares, decimals),
1226
- };
1227
- };
1228
-
1229
- export const getUserPositions = async (web3: Web3, network: NetworkNumber, user: EthAddress, mainnetWeb3: Web3) => {
1230
- const view = FluidViewContract(web3, network);
1231
-
1232
- const data = await view.methods.getUserPositions(user).call();
1233
-
1234
- const parsedMarketData = await Promise.all(data.vaults.map(async (vaultData) => parseMarketData(web3, vaultData, network, mainnetWeb3)));
1235
-
1236
- const userData = data.positions.map((position, i) => ({ ...parseUserData(position, parsedMarketData[i]), nftId: position.nftId }));
1237
-
1238
- return parsedMarketData.map((market, i) => ({
1239
- marketData: market,
1240
- userData: userData[i],
1241
- }));
1
+ import Web3 from 'web3';
2
+ import Dec from 'decimal.js';
3
+ import {
4
+ assetAmountInEth,
5
+ AssetData, getAssetInfo, getAssetInfoByAddress,
6
+ } from '@defisaver/tokens';
7
+ import { EthAddress, NetworkNumber } from '../types/common';
8
+ import {
9
+ FluidAggregatedVaultData,
10
+ FluidAssetData, FluidAssetsData,
11
+ FluidMarketData,
12
+ FluidMarketInfo,
13
+ FluidUsedAsset,
14
+ FluidUsedAssets,
15
+ FluidVaultData,
16
+ FluidVaultType, InnerFluidMarketData,
17
+ } from '../types';
18
+ import { DFSFeedRegistryContract, FeedRegistryContract, FluidViewContract } from '../contracts';
19
+ import { getEthAmountForDecimals, isMainnetNetwork } from '../services/utils';
20
+ import {
21
+ getFluidAggregatedData,
22
+ mergeAssetData,
23
+ mergeUsedAssets,
24
+ parseDexBorrowData,
25
+ parseDexSupplyData,
26
+ } from '../helpers/fluidHelpers';
27
+ import { FluidView } from '../types/contracts/generated';
28
+ import { chunkAndMulticall } from '../multicall';
29
+ import { getFluidMarketInfoById, getFluidVersionsDataForNetwork, getFTokenAddress } from '../markets';
30
+ import { USD_QUOTE } from '../constants';
31
+ import {
32
+ getChainlinkAssetAddress,
33
+ getWeETHChainLinkPriceCalls,
34
+ getWstETHChainLinkPriceCalls,
35
+ getWstETHPriceFluid,
36
+ parseWeETHPriceCalls,
37
+ parseWstETHPriceCalls,
38
+ } from '../services/priceService';
39
+ import { getStakingApy, STAKING_ASSETS } from '../staking';
40
+
41
+ export const EMPTY_USED_ASSET = {
42
+ isSupplied: false,
43
+ isBorrowed: false,
44
+ supplied: '0',
45
+ suppliedUsd: '0',
46
+ borrowed: '0',
47
+ borrowedUsd: '0',
48
+ symbol: '',
49
+ collateral: false,
50
+ };
51
+
52
+ const parseVaultType = (vaultType: number) => {
53
+ switch (vaultType) {
54
+ case 10000: return FluidVaultType.T1;
55
+ case 20000: return FluidVaultType.T2;
56
+ case 30000: return FluidVaultType.T3;
57
+ case 40000: return FluidVaultType.T4;
58
+ default: return FluidVaultType.Unknown;
59
+ }
60
+ };
61
+
62
+ const getChainLinkPricesForTokens = async (
63
+ tokens: string[],
64
+ network: NetworkNumber,
65
+ web3: Web3,
66
+ ): Promise<{ [key: string]: string }> => {
67
+ const isMainnet = isMainnetNetwork(network);
68
+
69
+ const noDuplicateTokens = new Array(...new Set(tokens));
70
+
71
+ const calls = noDuplicateTokens.flatMap((address) => {
72
+ const assetInfo = getAssetInfoByAddress(address, network);
73
+ const isTokenUSDA = assetInfo.symbol === 'USDA';
74
+ if (isTokenUSDA) return;
75
+ const chainLinkFeedAddress = getChainlinkAssetAddress(assetInfo.symbol, network);
76
+
77
+ if (assetInfo.symbol === 'wstETH') return getWstETHChainLinkPriceCalls(web3, network);
78
+ if (assetInfo.symbol === 'weETH') return getWeETHChainLinkPriceCalls(web3, network);
79
+
80
+ if (isMainnet) {
81
+ const feedRegistryContract = FeedRegistryContract(web3, NetworkNumber.Eth);
82
+ return ({
83
+ target: feedRegistryContract.options.address,
84
+ abiItem: feedRegistryContract.options.jsonInterface.find(({ name }) => name === 'latestAnswer'),
85
+ params: [chainLinkFeedAddress, USD_QUOTE],
86
+ });
87
+ }
88
+
89
+ const feedRegistryContract = DFSFeedRegistryContract(web3, network);
90
+ return ({
91
+ target: feedRegistryContract.options.address,
92
+ abiItem: feedRegistryContract.options.jsonInterface.find(({ name }) => name === 'latestRoundData'),
93
+ params: [chainLinkFeedAddress, USD_QUOTE],
94
+ });
95
+ });
96
+
97
+ const prices = await chunkAndMulticall(calls, 10, 'latest', web3, network);
98
+ let offset = 0; // wstETH has 3 calls, while others have only 1, so we need to keep track
99
+
100
+ return noDuplicateTokens.reduce((acc, token, i) => {
101
+ const assetInfo = getAssetInfoByAddress(token, network);
102
+ switch (assetInfo.symbol) {
103
+ case 'USDA':
104
+ acc[token] = '100000000';
105
+ break;
106
+
107
+ case 'wstETH': {
108
+ const {
109
+ ethPrice,
110
+ wstETHRate,
111
+ } = parseWstETHPriceCalls(prices[i + offset][0], prices[i + offset + 1], prices[i + offset + 2][0]);
112
+ offset += 2;
113
+ acc[token] = new Dec(ethPrice).mul(wstETHRate).toString();
114
+ break;
115
+ }
116
+
117
+ case 'weETH': {
118
+ const {
119
+ ethPrice,
120
+ weETHRate,
121
+ } = parseWeETHPriceCalls(prices[i + offset][0], prices[i + offset + 1], prices[i + offset + 2][0]);
122
+ offset += 2;
123
+ acc[token] = new Dec(ethPrice).mul(weETHRate).toString();
124
+ break;
125
+ }
126
+
127
+ default:
128
+ acc[token] = new Dec(prices[i + offset].answer).div(1e8).toString();
129
+ break;
130
+ }
131
+ return acc;
132
+ }, {} as { [key: string]: string });
133
+ };
134
+
135
+
136
+ const getTokenPriceFromChainlink = async (asset: AssetData, network: NetworkNumber, web3: Web3) => {
137
+ const isTokenUSDA = asset.symbol === 'USDA';
138
+ const isMainnet = isMainnetNetwork(network);
139
+ const loanTokenFeedAddress = getChainlinkAssetAddress(asset.symbol, network);
140
+
141
+ let loanTokenPrice;
142
+ if (asset.symbol === 'wstETH') {
143
+ // need to handle wstETH for l2s inside getWstETHPrice
144
+ loanTokenPrice = await getWstETHPriceFluid(web3, network);
145
+ } else if (isMainnet) {
146
+ const feedRegistryContract = FeedRegistryContract(web3, NetworkNumber.Eth);
147
+ loanTokenPrice = isTokenUSDA ? '100000000' : await feedRegistryContract.methods.latestAnswer(loanTokenFeedAddress, USD_QUOTE).call();
148
+ } else {
149
+ // Currently only base network is supported
150
+ const feedRegistryContract = DFSFeedRegistryContract(web3, network);
151
+ const roundPriceData = isTokenUSDA ? { answer: '100000000' } : await feedRegistryContract.methods.latestRoundData(loanTokenFeedAddress, USD_QUOTE).call();
152
+ loanTokenPrice = roundPriceData.answer;
153
+ }
154
+
155
+ return new Dec(loanTokenPrice).div(1e8).toString();
156
+ };
157
+
158
+ const getMarketRateForDex = (token1PerShare: string, token0PerShare: string, rate0: string, rate1: string, price0: string, price1: string) => {
159
+ const token0PerShareUsd = new Dec(token0PerShare).mul(price0).toString();
160
+ const token1PerShareUsd = new Dec(token1PerShare).mul(price1).toString();
161
+ const sharesCombinedUsd = new Dec(token0PerShareUsd).plus(token1PerShareUsd);
162
+
163
+ const rate0PerShare = new Dec(rate0).mul(token0PerShareUsd).div(sharesCombinedUsd).toString();
164
+
165
+ const rate1PerShare = new Dec(rate1).mul(token1PerShareUsd).div(sharesCombinedUsd).toString();
166
+
167
+ return new Dec(rate0PerShare).plus(rate1PerShare).toString();
168
+ };
169
+
170
+ const getAdditionalMarketRateForDex = (token1PerShare: string, token0PerShare: string, incentiveSupplyRate0: string, incentiveSupplyRate1: string, price0: string, price1: string) => {
171
+ const token0PerShareUsd = new Dec(token0PerShare).mul(price0).toString();
172
+ const token1PerShareUsd = new Dec(token1PerShare).mul(price1).toString();
173
+ const sharesCombinedUsd = new Dec(token0PerShareUsd).plus(token1PerShareUsd);
174
+
175
+ const rate0PerShare = incentiveSupplyRate0 ? new Dec(incentiveSupplyRate0).mul(token0PerShareUsd).div(sharesCombinedUsd).toString() : 0;
176
+
177
+ const rate1PerShare = incentiveSupplyRate1 ? new Dec(incentiveSupplyRate1).mul(token1PerShareUsd).div(sharesCombinedUsd).toString() : 0;
178
+
179
+ return new Dec(rate0PerShare).plus(rate1PerShare).toString();
180
+ };
181
+
182
+ const getTradingApy = async (poolAddress: EthAddress) => {
183
+ const res = await fetch(`https://api.fluid.instadapp.io/v2/1/dexes/${poolAddress}/apy`);
184
+ if (!res.ok) {
185
+ return '0';
186
+ }
187
+ const data = await res.json();
188
+ return new Dec(data.tradingApy).div(100).toString();
189
+ };
190
+
191
+ const parseT1MarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
192
+ const collAsset = getAssetInfoByAddress(data.supplyToken0, network);
193
+ const debtAsset = getAssetInfoByAddress(data.borrowToken0, network);
194
+
195
+ const supplyRate = new Dec(data.supplyRateVault).div(100).toString();
196
+ const borrowRate = new Dec(data.borrowRateVault).div(100).toString();
197
+
198
+ const oracleScaleFactor = new Dec(27).add(debtAsset.decimals).sub(collAsset.decimals).toString();
199
+ const oracleScale = new Dec(10).pow(oracleScaleFactor).toString();
200
+ const oraclePrice = new Dec(data.oraclePriceOperate).div(oracleScale).toString();
201
+ const debtPriceParsed = await getTokenPriceFromChainlink(debtAsset, network, web3);
202
+
203
+ const collAssetData: FluidAssetData = {
204
+ symbol: collAsset.symbol,
205
+ address: collAsset.address,
206
+ price: new Dec(debtPriceParsed).mul(oraclePrice).toString(),
207
+ totalSupply: data.totalSupplyVault,
208
+ totalBorrow: data.totalBorrowVault,
209
+ canBeSupplied: true,
210
+ canBeBorrowed: false,
211
+ supplyRate,
212
+ borrowRate: '0',
213
+ };
214
+
215
+ if (STAKING_ASSETS.includes(collAsset.symbol)) {
216
+ collAssetData.incentiveSupplyApy = await getStakingApy(collAsset.symbol, mainnetWeb3);
217
+ collAssetData.incentiveSupplyToken = collAsset.symbol;
218
+ }
219
+
220
+ const incentiveSupplyRate = collAssetData.incentiveSupplyApy;
221
+
222
+ const debtAssetData: FluidAssetData = {
223
+ symbol: debtAsset.symbol,
224
+ address: debtAsset.address,
225
+ price: debtPriceParsed,
226
+ totalSupply: data.totalSupplyVault,
227
+ totalBorrow: data.totalBorrowVault,
228
+ canBeSupplied: false,
229
+ canBeBorrowed: true,
230
+ supplyRate: '0',
231
+ borrowRate,
232
+ };
233
+ if (STAKING_ASSETS.includes(debtAssetData.symbol)) {
234
+ debtAssetData.incentiveBorrowApy = await getStakingApy(debtAsset.symbol, mainnetWeb3);
235
+ debtAssetData.incentiveBorrowToken = debtAsset.symbol;
236
+ }
237
+
238
+ const incentiveBorrowRate = debtAssetData.incentiveBorrowApy;
239
+
240
+ const assetsData = {
241
+ [collAsset.symbol]: collAssetData,
242
+ [debtAsset.symbol]: debtAssetData,
243
+ };
244
+ const marketInfo = getFluidMarketInfoById(+data.vaultId, network);
245
+ const totalSupplyVault = getEthAmountForDecimals(data.totalSupplyVault, collAsset.decimals);
246
+ const totalBorrowVault = getEthAmountForDecimals(data.totalBorrowVault, debtAsset.decimals);
247
+
248
+ const liqRatio = new Dec(data.liquidationThreshold).div(100).toString();
249
+ const liquidationMaxLimit = new Dec(data.liquidationMaxLimit).div(100).toString();
250
+ const liqFactor = new Dec(data.liquidationThreshold).div(10_000).toString();
251
+
252
+ const marketData = {
253
+ vaultId: +data.vaultId,
254
+ vaultValue: marketInfo?.value,
255
+ isSmartColl: data.isSmartColl,
256
+ isSmartDebt: data.isSmartDebt,
257
+ marketAddress: data.vault,
258
+ vaultType: parseVaultType(+data.vaultType),
259
+ oracle: data.oracle,
260
+ liquidationPenaltyPercent: new Dec(data.liquidationPenalty).div(100).toString(),
261
+ collFactor: new Dec(data.collateralFactor).div(10000).toString(), // we want actual factor, not in %, so we divide by 10000 instead of 100
262
+ liquidationRatio: liqRatio,
263
+ liqFactor,
264
+ minRatio: new Dec(1).div(liqFactor).mul(100).toString(),
265
+ collAsset0: collAsset.symbol,
266
+ debtAsset0: debtAsset.symbol,
267
+ totalPositions: data.totalPositions,
268
+ totalSupplyVault,
269
+ totalBorrowVault,
270
+ totalSupplyVaultUsd: new Dec(totalSupplyVault).mul(collAssetData.price).toString(),
271
+ totalBorrowVaultUsd: new Dec(totalBorrowVault).mul(debtAssetData.price).toString(),
272
+ withdrawalLimit: getEthAmountForDecimals(data.withdrawalLimit, collAsset.decimals),
273
+ withdrawableUntilLimit: getEthAmountForDecimals(data.withdrawableUntilLimit, collAsset.decimals),
274
+ withdrawable: getEthAmountForDecimals(data.withdrawable, collAsset.decimals),
275
+ borrowLimit: getEthAmountForDecimals(data.borrowLimit, debtAsset.decimals),
276
+ borrowableUntilLimit: getEthAmountForDecimals(data.borrowableUntilLimit, debtAsset.decimals),
277
+ borrowable: getEthAmountForDecimals(data.borrowable, debtAsset.decimals),
278
+ borrowLimitUtilization: getEthAmountForDecimals(data.borrowLimitUtilization, debtAsset.decimals),
279
+ maxBorrowLimit: getEthAmountForDecimals(data.maxBorrowLimit, debtAsset.decimals),
280
+ baseBorrowLimit: getEthAmountForDecimals(data.baseBorrowLimit, debtAsset.decimals),
281
+ minimumBorrowing: getEthAmountForDecimals(data.minimumBorrowing, debtAsset.decimals),
282
+ liquidationMaxLimit,
283
+ borrowRate,
284
+ supplyRate,
285
+ incentiveSupplyRate,
286
+ incentiveBorrowRate,
287
+ oraclePrice,
288
+ };
289
+
290
+ return {
291
+ assetsData,
292
+ marketData,
293
+ } as FluidMarketData;
294
+ };
295
+
296
+ const parseT2MarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
297
+ const collAsset0 = getAssetInfoByAddress(data.supplyToken0, network);
298
+ const collAsset1 = getAssetInfoByAddress(data.supplyToken1, network);
299
+ const debtAsset = getAssetInfoByAddress(data.borrowToken0, network);
300
+
301
+ // 18 because collateral is represented in shares for which they use 18 decimals
302
+ const oracleScaleFactor = new Dec(27).add(debtAsset.decimals).sub(18).toString();
303
+ const oracleScale = new Dec(10).pow(oracleScaleFactor).toString();
304
+ const oraclePrice = new Dec(data.oraclePriceOperate).div(oracleScale).toString();
305
+
306
+ const prices = await getChainLinkPricesForTokens([collAsset0.address, collAsset1.address, debtAsset.address], network, web3);
307
+
308
+ const {
309
+ supplyDexFee,
310
+ totalSupplyShares,
311
+ supplyRate1,
312
+ totalSupplyToken1,
313
+ token0PerSupplyShare,
314
+ token1PerSupplyShare,
315
+ totalSupplyToken0,
316
+ maxSupplyShares,
317
+ withdrawableToken0,
318
+ withdrawable0,
319
+ withdrawableToken1,
320
+ withdrawable1,
321
+ supplyRate0,
322
+ utilizationSupply0,
323
+ utilizationSupply1,
324
+ withdrawableShares,
325
+ reservesSupplyToken0,
326
+ reservesSupplyToken1,
327
+ } = parseDexSupplyData(data.dexSupplyData, collAsset0.symbol, collAsset1.symbol);
328
+
329
+ const collFirstAssetData: Partial<FluidAssetData> = {
330
+ symbol: collAsset0.symbol,
331
+ address: collAsset0.address,
332
+ price: prices[collAsset0.address],
333
+ totalSupply: new Dec(totalSupplyShares).mul(token0PerSupplyShare).toString(),
334
+ canBeSupplied: true,
335
+ supplyRate: supplyRate0,
336
+ utilization: utilizationSupply0,
337
+ withdrawable: withdrawable0,
338
+ tokenPerSupplyShare: token0PerSupplyShare,
339
+ supplyReserves: reservesSupplyToken0,
340
+ };
341
+ if (STAKING_ASSETS.includes(collFirstAssetData.symbol!)) {
342
+ collFirstAssetData.incentiveSupplyApy = await getStakingApy(collAsset0.symbol, mainnetWeb3);
343
+ collFirstAssetData.incentiveSupplyToken = collAsset0.symbol;
344
+ }
345
+
346
+ const collSecondAssetData: Partial<FluidAssetData> = {
347
+ symbol: collAsset1.symbol,
348
+ address: collAsset1.address,
349
+ price: prices[collAsset1.address],
350
+ totalSupply: new Dec(totalSupplyShares).mul(token1PerSupplyShare).toString(),
351
+ canBeSupplied: true,
352
+ supplyRate: supplyRate1,
353
+ withdrawable: withdrawable1,
354
+ utilization: utilizationSupply1,
355
+ tokenPerSupplyShare: token1PerSupplyShare,
356
+ supplyReserves: reservesSupplyToken1,
357
+ };
358
+ if (STAKING_ASSETS.includes(collSecondAssetData.symbol!)) {
359
+ collSecondAssetData.incentiveSupplyApy = await getStakingApy(collAsset1.symbol, mainnetWeb3);
360
+ collSecondAssetData.incentiveSupplyToken = collAsset1.symbol;
361
+ }
362
+
363
+ const marketSupplyRate = getMarketRateForDex(token1PerSupplyShare, token0PerSupplyShare, supplyRate0, supplyRate1, collFirstAssetData.price!, collSecondAssetData.price!);
364
+ const incentiveSupplyRate = getAdditionalMarketRateForDex(token1PerSupplyShare, token0PerSupplyShare, collFirstAssetData.incentiveSupplyApy!, collSecondAssetData.incentiveSupplyApy!, collFirstAssetData.price!, collSecondAssetData.price!);
365
+ const tradingSupplyRate = await getTradingApy(data.dexSupplyData.dexPool);
366
+
367
+ const borrowRate = new Dec(data.borrowRateVault).div(100).toString();
368
+ const debtAssetData: Partial<FluidAssetData> = {
369
+ symbol: debtAsset.symbol,
370
+ price: prices[debtAsset.address],
371
+ address: debtAsset.address,
372
+ totalBorrow: data.totalBorrowVault,
373
+ canBeBorrowed: true,
374
+ borrowRate,
375
+ };
376
+ if (STAKING_ASSETS.includes(debtAssetData.symbol!)) {
377
+ debtAssetData.incentiveBorrowApy = await getStakingApy(debtAsset.symbol, mainnetWeb3);
378
+ debtAssetData.incentiveBorrowToken = debtAsset.symbol;
379
+ }
380
+
381
+ const incentiveBorrowRate = debtAssetData.incentiveBorrowApy;
382
+
383
+ const assetsData: FluidAssetsData = ([
384
+ [collAsset0.symbol, collFirstAssetData],
385
+ [collAsset1.symbol, collSecondAssetData],
386
+ [debtAsset.symbol, debtAssetData],
387
+ ] as [string, FluidAssetData][])
388
+ .reduce((acc, [symbol, partialData]) => ({
389
+ ...acc,
390
+ [symbol]: mergeAssetData(acc[symbol], partialData),
391
+ }), {} as Record<string, FluidAssetData>) as FluidAssetsData;
392
+
393
+ const marketInfo = getFluidMarketInfoById(+data.vaultId, network);
394
+
395
+ const totalBorrowVault = getEthAmountForDecimals(data.totalBorrowVault, debtAsset.decimals);
396
+
397
+ const liqRatio = new Dec(data.liquidationThreshold).div(100).toString();
398
+ const liquidationMaxLimit = new Dec(data.liquidationMaxLimit).div(100).toString();
399
+ const liqFactor = new Dec(data.liquidationThreshold).div(10_000).toString();
400
+
401
+ const totalSupplySharesInVault = assetAmountInEth(data.totalSupplyVault);
402
+ const collSharePrice = new Dec(oraclePrice).mul(prices[debtAsset.address]).toString();
403
+ const totalSupplyVaultUsd = new Dec(totalSupplySharesInVault).mul(collSharePrice).toString();
404
+ const maxSupplySharesUsd = new Dec(maxSupplyShares).mul(collSharePrice).toString();
405
+
406
+ const withdrawableUSD = new Dec(withdrawableShares).mul(collSharePrice).toString();
407
+
408
+ const marketData = {
409
+ vaultId: +data.vaultId,
410
+ vaultValue: marketInfo?.value,
411
+ isSmartColl: data.isSmartColl,
412
+ isSmartDebt: data.isSmartDebt,
413
+ marketAddress: data.vault,
414
+ vaultType: parseVaultType(+data.vaultType),
415
+ oracle: data.oracle,
416
+ liquidationPenaltyPercent: new Dec(data.liquidationPenalty).div(100).toString(),
417
+ collFactor: new Dec(data.collateralFactor).div(10000).toString(), // we want actual factor, not in %, so we divide by 10000 instead of 100
418
+ liquidationRatio: liqRatio,
419
+ liqFactor,
420
+ minRatio: new Dec(1).div(liqFactor).mul(100).toString(),
421
+ collAsset0: collAsset0.symbol,
422
+ collAsset1: collAsset1.symbol,
423
+ debtAsset0: debtAsset.symbol,
424
+ totalPositions: data.totalPositions,
425
+ totalSupplyVault: totalSupplyShares,
426
+ totalBorrowVault,
427
+ totalSupplyVaultUsd,
428
+ collSharePrice,
429
+ totalBorrowVaultUsd: new Dec(totalBorrowVault).mul(assetsData[debtAsset.symbol].price).toString(),
430
+ borrowLimit: getEthAmountForDecimals(data.borrowLimit, debtAsset.decimals),
431
+ borrowableUntilLimit: getEthAmountForDecimals(data.borrowableUntilLimit, debtAsset.decimals),
432
+ borrowable: getEthAmountForDecimals(data.borrowable, debtAsset.decimals),
433
+ borrowLimitUtilization: getEthAmountForDecimals(data.borrowLimitUtilization, debtAsset.decimals),
434
+ maxBorrowLimit: getEthAmountForDecimals(data.maxBorrowLimit, debtAsset.decimals),
435
+ baseBorrowLimit: getEthAmountForDecimals(data.baseBorrowLimit, debtAsset.decimals),
436
+ minimumBorrowing: getEthAmountForDecimals(data.minimumBorrowing, debtAsset.decimals),
437
+ liquidationMaxLimit,
438
+ borrowRate,
439
+ supplyRate: marketSupplyRate,
440
+ incentiveSupplyRate,
441
+ incentiveBorrowRate,
442
+ totalSupplyToken0,
443
+ totalSupplyToken1,
444
+ withdrawableToken0,
445
+ withdrawableToken1,
446
+ withdrawableUSD,
447
+ withdrawable: withdrawableShares,
448
+ withdrawableDex: new Dec(maxSupplyShares).minus(totalSupplyShares).toString(),
449
+ maxSupplyShares,
450
+ maxSupplySharesUsd,
451
+ collDexFee: supplyDexFee,
452
+ oraclePrice,
453
+ tradingSupplyRate,
454
+ tradingBorrowRate: '0',
455
+ };
456
+
457
+ return {
458
+ assetsData,
459
+ marketData,
460
+ } as FluidMarketData;
461
+ };
462
+
463
+ const parseT3MarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
464
+ const collAsset = getAssetInfoByAddress(data.supplyToken0, network);
465
+ const debtAsset0 = getAssetInfoByAddress(data.borrowToken0, network);
466
+ const debtAsset1 = getAssetInfoByAddress(data.borrowToken1, network);
467
+
468
+ const {
469
+ borrowableShares,
470
+ maxBorrowShares,
471
+ borrowDexFee,
472
+ utilizationBorrow0,
473
+ utilizationBorrow1,
474
+ borrowable0,
475
+ borrowable1,
476
+ borrowRate0,
477
+ borrowRate1,
478
+ totalBorrowShares,
479
+ token0PerBorrowShare,
480
+ token1PerBorrowShare,
481
+ borrowableToken0,
482
+ borrowableToken1,
483
+ totalBorrowToken0,
484
+ totalBorrowToken1,
485
+ reservesBorrowToken0,
486
+ reservesBorrowToken1,
487
+ } = parseDexBorrowData(data.dexBorrowData, debtAsset0.symbol, debtAsset1.symbol);
488
+
489
+ // 18 because debt is represented in shares for which they use 18 decimals
490
+ const oracleScaleFactor = new Dec(27).add(18).sub(collAsset.decimals).toString();
491
+ const oracleScale = new Dec(10).pow(oracleScaleFactor).toString();
492
+ const oraclePrice = new Dec(1).div(new Dec(data.oraclePriceOperate).div(oracleScale)).toString();
493
+
494
+ const prices = await getChainLinkPricesForTokens([collAsset.address, debtAsset0.address, debtAsset1.address], network, web3);
495
+
496
+ const supplyRate = new Dec(data.supplyRateVault).div(100).toString();
497
+ const collAssetData: Partial<FluidAssetData> = {
498
+ symbol: collAsset.symbol,
499
+ address: collAsset.address,
500
+ price: prices[collAsset.address],
501
+ totalSupply: data.totalSupplyVault,
502
+ canBeSupplied: true,
503
+ supplyRate,
504
+ };
505
+ if (STAKING_ASSETS.includes(collAssetData.symbol!)) {
506
+ collAssetData.incentiveSupplyApy = await getStakingApy(collAsset.symbol, mainnetWeb3);
507
+ collAssetData.incentiveSupplyToken = collAsset.symbol;
508
+ }
509
+
510
+ const incentiveSupplyRate = collAssetData.incentiveSupplyApy;
511
+
512
+ const debtAsset0Data: Partial<FluidAssetData> = {
513
+ symbol: debtAsset0.symbol,
514
+ address: debtAsset0.address,
515
+ price: prices[debtAsset0.address],
516
+ totalBorrow: new Dec(totalBorrowShares).mul(token0PerBorrowShare).toString(),
517
+ canBeBorrowed: true,
518
+ borrowRate: borrowRate0,
519
+ borrowable: borrowable0,
520
+ utilization: utilizationBorrow0,
521
+ tokenPerBorrowShare: token0PerBorrowShare,
522
+ borrowReserves: reservesBorrowToken0,
523
+ };
524
+ if (STAKING_ASSETS.includes(debtAsset0Data.symbol!)) {
525
+ debtAsset0Data.incentiveSupplyApy = await getStakingApy(debtAsset0.symbol, mainnetWeb3);
526
+ debtAsset0Data.incentiveSupplyToken = debtAsset0.symbol;
527
+ }
528
+
529
+ const debtAsset1Data: Partial<FluidAssetData> = {
530
+ symbol: debtAsset1.symbol,
531
+ address: debtAsset1.address,
532
+ price: prices[debtAsset1.address],
533
+ totalBorrow: new Dec(totalBorrowShares).mul(token1PerBorrowShare).toString(),
534
+ canBeBorrowed: true,
535
+ borrowRate: borrowRate1,
536
+ borrowable: borrowable1,
537
+ utilization: utilizationBorrow1,
538
+ tokenPerBorrowShare: token1PerBorrowShare,
539
+ borrowReserves: reservesBorrowToken1,
540
+ };
541
+ if (STAKING_ASSETS.includes(debtAsset1Data.symbol!)) {
542
+ debtAsset1Data.incentiveSupplyApy = await getStakingApy(debtAsset1.symbol, mainnetWeb3);
543
+ debtAsset1Data.incentiveSupplyToken = debtAsset1.symbol;
544
+ }
545
+ const marketBorrowRate = getMarketRateForDex(token1PerBorrowShare, token0PerBorrowShare, borrowRate0, borrowRate1, debtAsset0Data.price!, debtAsset1Data.price!);
546
+ const incentiveBorrowRate = getAdditionalMarketRateForDex(token1PerBorrowShare, token0PerBorrowShare, debtAsset0Data.incentiveSupplyApy!, debtAsset1Data.incentiveSupplyApy!, debtAsset0Data.price!, debtAsset1Data.price!);
547
+ const tradingBorrowRate = await getTradingApy(data.dexBorrowData.dexPool);
548
+
549
+ const assetsData: FluidAssetsData = ([
550
+ [collAsset.symbol, collAssetData],
551
+ [debtAsset0.symbol, debtAsset0Data],
552
+ [debtAsset1.symbol, debtAsset1Data],
553
+ ] as [string, FluidAssetData][])
554
+ .reduce((acc, [symbol, partialData]) => ({
555
+ ...acc,
556
+ [symbol]: mergeAssetData(acc[symbol], partialData),
557
+ }), {} as Record<string, FluidAssetData>) as FluidAssetsData;
558
+
559
+ const marketInfo = getFluidMarketInfoById(+data.vaultId, network);
560
+
561
+ const totalSupplyVault = getEthAmountForDecimals(data.totalSupplyVault, collAsset.decimals);
562
+
563
+ const liqRatio = new Dec(data.liquidationThreshold).div(100).toString();
564
+ const liquidationMaxLimit = new Dec(data.liquidationMaxLimit).div(100).toString();
565
+ const liqFactor = new Dec(data.liquidationThreshold).div(10_000).toString();
566
+
567
+ const debtSharePrice = new Dec(oraclePrice).mul(prices[collAsset.address]).toString();
568
+
569
+ const totalBorrowSharesInVault = assetAmountInEth(data.totalBorrowVault);
570
+
571
+ const totalBorrowVaultUsd = new Dec(totalBorrowSharesInVault).mul(debtSharePrice).toString();
572
+
573
+ const borrowableUSD = new Dec(borrowableShares).mul(debtSharePrice).toString();
574
+ const maxBorrowSharesUsd = new Dec(maxBorrowShares).mul(debtSharePrice).toString();
575
+
576
+ const marketData = {
577
+ vaultId: +data.vaultId,
578
+ vaultValue: marketInfo?.value,
579
+ isSmartColl: data.isSmartColl,
580
+ isSmartDebt: data.isSmartDebt,
581
+ marketAddress: data.vault,
582
+ vaultType: parseVaultType(+data.vaultType),
583
+ oracle: data.oracle,
584
+ liquidationPenaltyPercent: new Dec(data.liquidationPenalty).div(100).toString(),
585
+ collFactor: new Dec(data.collateralFactor).div(10000).toString(), // we want actual factor, not in %, so we divide by 10000 instead of 100
586
+ liquidationRatio: liqRatio,
587
+ liqFactor,
588
+ minRatio: new Dec(1).div(liqFactor).mul(100).toString(),
589
+ collAsset0: collAsset.symbol,
590
+ debtAsset0: debtAsset0.symbol,
591
+ debtAsset1: debtAsset1.symbol,
592
+ totalPositions: data.totalPositions,
593
+ totalSupplyVault,
594
+ totalBorrowVault: totalBorrowShares,
595
+ totalSupplyVaultUsd: new Dec(totalSupplyVault).mul(assetsData[collAsset.symbol].price).toString(),
596
+ totalBorrowVaultUsd,
597
+ withdrawalLimit: getEthAmountForDecimals(data.withdrawalLimit, collAsset.decimals),
598
+ withdrawableUntilLimit: getEthAmountForDecimals(data.withdrawableUntilLimit, collAsset.decimals),
599
+ withdrawable: getEthAmountForDecimals(data.withdrawable, collAsset.decimals),
600
+ liquidationMaxLimit,
601
+ borrowRate: marketBorrowRate,
602
+ supplyRate,
603
+ incentiveBorrowRate,
604
+ incentiveSupplyRate,
605
+ tradingBorrowRate,
606
+ tradingSupplyRate: '0',
607
+ borrowableToken0,
608
+ borrowableToken1,
609
+ totalBorrowToken0,
610
+ totalBorrowToken1,
611
+ borrowableUSD,
612
+ borrowable: borrowableShares,
613
+ borrowableDex: new Dec(maxBorrowShares).minus(totalBorrowShares).toString(),
614
+ maxBorrowShares,
615
+ maxBorrowSharesUsd,
616
+ borrowDexFee,
617
+ debtSharePrice,
618
+ oraclePrice,
619
+ };
620
+
621
+ return {
622
+ assetsData,
623
+ marketData,
624
+ } as FluidMarketData;
625
+ };
626
+
627
+ const parseT4MarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
628
+ const collAsset0 = getAssetInfoByAddress(data.supplyToken0, network);
629
+ const collAsset1 = getAssetInfoByAddress(data.supplyToken1, network);
630
+ const debtAsset0 = getAssetInfoByAddress(data.borrowToken0, network);
631
+ const debtAsset1 = getAssetInfoByAddress(data.borrowToken1, network);
632
+ const quoteToken = getAssetInfoByAddress(data.dexBorrowData.quoteToken, network);
633
+
634
+ // 27 - 18 + 18
635
+ const oracleScaleFactor = new Dec(27).toString();
636
+ const oracleScale = new Dec(10).pow(oracleScaleFactor).toString();
637
+ const oraclePrice = new Dec(data.oraclePriceOperate).div(oracleScale).toString();
638
+
639
+ const prices = await getChainLinkPricesForTokens(
640
+ [collAsset0.address, collAsset1.address, debtAsset0.address, debtAsset1.address],
641
+ network, web3);
642
+
643
+ const {
644
+ supplyDexFee,
645
+ totalSupplyShares,
646
+ supplyRate1,
647
+ token0PerSupplyShare,
648
+ token1PerSupplyShare,
649
+ totalSupplyToken0,
650
+ totalSupplyToken1,
651
+ maxSupplyShares,
652
+ withdrawableToken0,
653
+ withdrawable0,
654
+ withdrawableToken1,
655
+ withdrawable1,
656
+ supplyRate0,
657
+ utilizationSupply0,
658
+ utilizationSupply1,
659
+ withdrawableShares,
660
+ reservesSupplyToken0,
661
+ reservesSupplyToken1,
662
+ } = parseDexSupplyData(data.dexSupplyData, collAsset0.symbol, collAsset1.symbol);
663
+
664
+ const {
665
+ borrowableShares,
666
+ maxBorrowShares,
667
+ borrowDexFee,
668
+ utilizationBorrow0,
669
+ utilizationBorrow1,
670
+ borrowable0,
671
+ borrowable1,
672
+ borrowRate0,
673
+ borrowRate1,
674
+ totalBorrowShares,
675
+ token0PerBorrowShare,
676
+ token1PerBorrowShare,
677
+ borrowableToken0,
678
+ borrowableToken1,
679
+ totalBorrowToken0,
680
+ totalBorrowToken1,
681
+ quoteTokensPerShare,
682
+ reservesBorrowToken0,
683
+ reservesBorrowToken1,
684
+ } = parseDexBorrowData(data.dexBorrowData, debtAsset0.symbol, debtAsset1.symbol);
685
+
686
+ const collAsset0Data: Partial<FluidAssetData> = {
687
+ symbol: collAsset0.symbol,
688
+ address: collAsset0.address,
689
+ price: prices[collAsset0.address],
690
+ totalSupply: new Dec(totalSupplyShares).mul(token0PerSupplyShare).toString(),
691
+ canBeSupplied: true,
692
+ supplyRate: supplyRate0,
693
+ utilization: utilizationSupply0,
694
+ withdrawable: withdrawable0,
695
+ tokenPerSupplyShare: token0PerSupplyShare,
696
+ supplyReserves: reservesSupplyToken0,
697
+ };
698
+ if (STAKING_ASSETS.includes(collAsset0Data.symbol!)) {
699
+ collAsset0Data.incentiveSupplyApy = await getStakingApy(collAsset0.symbol, mainnetWeb3);
700
+ collAsset0Data.incentiveSupplyToken = collAsset0.symbol;
701
+ }
702
+
703
+ const collAsset1Data: Partial<FluidAssetData> = {
704
+ symbol: collAsset1.symbol,
705
+ address: collAsset1.address,
706
+ price: prices[collAsset1.address],
707
+ totalSupply: new Dec(totalSupplyShares).mul(token1PerSupplyShare).toString(),
708
+ canBeSupplied: true,
709
+ supplyRate: supplyRate1,
710
+ withdrawable: withdrawable1,
711
+ utilization: utilizationSupply1,
712
+ tokenPerSupplyShare: token1PerSupplyShare,
713
+ supplyReserves: reservesSupplyToken1,
714
+ };
715
+ if (STAKING_ASSETS.includes(collAsset1Data.symbol!)) {
716
+ collAsset1Data.incentiveSupplyApy = await getStakingApy(collAsset1.symbol, mainnetWeb3);
717
+ collAsset1Data.incentiveSupplyToken = collAsset1.symbol;
718
+ }
719
+
720
+ const debtAsset0Data: Partial<FluidAssetData> = {
721
+ symbol: debtAsset0.symbol,
722
+ address: debtAsset0.address,
723
+ price: prices[debtAsset0.address],
724
+ totalBorrow: new Dec(totalBorrowShares).mul(token0PerBorrowShare).toString(),
725
+ canBeBorrowed: true,
726
+ borrowRate: borrowRate0,
727
+ borrowable: borrowable0,
728
+ utilization: utilizationBorrow0,
729
+ tokenPerBorrowShare: token0PerBorrowShare,
730
+ borrowReserves: reservesBorrowToken0,
731
+ };
732
+ if (STAKING_ASSETS.includes(debtAsset0Data.symbol!)) {
733
+ debtAsset0Data.incentiveSupplyApy = await getStakingApy(debtAsset0.symbol, mainnetWeb3);
734
+ debtAsset0Data.incentiveSupplyToken = debtAsset0.symbol;
735
+ }
736
+
737
+ const debtAsset1Data: Partial<FluidAssetData> = {
738
+ symbol: debtAsset1.symbol,
739
+ address: debtAsset1.address,
740
+ price: prices[debtAsset1.address],
741
+ totalBorrow: new Dec(totalBorrowShares).mul(token1PerBorrowShare).toString(),
742
+ canBeBorrowed: true,
743
+ borrowRate: borrowRate1,
744
+ borrowable: borrowable1,
745
+ utilization: utilizationBorrow1,
746
+ tokenPerBorrowShare: token1PerBorrowShare,
747
+ borrowReserves: reservesBorrowToken1,
748
+ };
749
+ if (STAKING_ASSETS.includes(debtAsset1Data.symbol!)) {
750
+ debtAsset1Data.incentiveSupplyApy = await getStakingApy(debtAsset1.symbol, mainnetWeb3);
751
+ debtAsset1Data.incentiveSupplyToken = debtAsset1.symbol;
752
+ }
753
+ const marketInfo = getFluidMarketInfoById(+data.vaultId, network);
754
+
755
+ const marketBorrowRate = getMarketRateForDex(token1PerBorrowShare, token0PerBorrowShare, borrowRate0, borrowRate1, debtAsset0Data.price!, debtAsset1Data.price!);
756
+ const incentiveBorrowRate = getAdditionalMarketRateForDex(token1PerBorrowShare, token0PerBorrowShare, debtAsset0Data.incentiveSupplyApy!, debtAsset1Data.incentiveSupplyApy!, debtAsset0Data.price!, debtAsset1Data.price!);
757
+ const tradingBorrowRate = await getTradingApy(data.dexBorrowData.dexPool);
758
+
759
+ const marketSupplyRate = getMarketRateForDex(token1PerSupplyShare, token0PerSupplyShare, supplyRate0, supplyRate1, collAsset0Data.price!, collAsset1Data.price!);
760
+ const incentiveSupplyRate = getAdditionalMarketRateForDex(token1PerSupplyShare, token0PerSupplyShare, collAsset0Data.incentiveSupplyApy!, collAsset1Data.incentiveSupplyApy!, collAsset0Data.price!, collAsset1Data.price!);
761
+ const tradingSupplyRate = await getTradingApy(data.dexSupplyData.dexPool);
762
+
763
+ const assetsData: FluidAssetsData = ([
764
+ [collAsset0.symbol, collAsset0Data],
765
+ [collAsset1.symbol, collAsset1Data],
766
+ [debtAsset0.symbol, debtAsset0Data],
767
+ [debtAsset1.symbol, debtAsset1Data],
768
+ ] as [string, FluidAssetData][])
769
+ .reduce((acc, [symbol, partialData]) => ({
770
+ ...acc,
771
+ [symbol]: mergeAssetData(acc[symbol], partialData),
772
+ }), {} as Record<string, FluidAssetData>) as FluidAssetsData;
773
+
774
+
775
+ const liqRatio = new Dec(data.liquidationThreshold).div(100).toString();
776
+ const liquidationMaxLimit = new Dec(data.liquidationMaxLimit).div(100).toString();
777
+ const liqFactor = new Dec(data.liquidationThreshold).div(10_000).toString();
778
+
779
+ const totalBorrowSharesInVault = assetAmountInEth(data.totalBorrowVault);
780
+ const debtSharePrice = new Dec(quoteTokensPerShare).mul(prices[quoteToken.address]).toString();
781
+ const totalBorrowVaultUsd = new Dec(totalBorrowSharesInVault).mul(debtSharePrice).toString();
782
+ const maxBorrowSharesUsd = new Dec(maxBorrowShares).mul(debtSharePrice).toString();
783
+ const borrowableUSD = new Dec(borrowableShares).mul(debtSharePrice).toString();
784
+
785
+ const totalSupplySharesInVault = assetAmountInEth(data.totalSupplyVault);
786
+ const collSharePrice = new Dec(oraclePrice).mul(debtSharePrice).toString();
787
+ const totalSupplyVaultUsd = new Dec(totalSupplySharesInVault).mul(collSharePrice).toString();
788
+ const maxSupplySharesUsd = new Dec(maxSupplyShares).mul(collSharePrice).toString();
789
+ const withdrawableUSD = new Dec(withdrawableShares).mul(collSharePrice).toString();
790
+
791
+ const marketData = {
792
+ vaultId: +data.vaultId,
793
+ vaultValue: marketInfo?.value,
794
+ isSmartColl: data.isSmartColl,
795
+ isSmartDebt: data.isSmartDebt,
796
+ marketAddress: data.vault,
797
+ vaultType: parseVaultType(+data.vaultType),
798
+ oracle: data.oracle,
799
+ liquidationPenaltyPercent: new Dec(data.liquidationPenalty).div(100).toString(),
800
+ collFactor: new Dec(data.collateralFactor).div(10000).toString(), // we want actual factor, not in %, so we divide by 10000 instead of 100
801
+ liquidationRatio: liqRatio,
802
+ liqFactor,
803
+ minRatio: new Dec(1).div(liqFactor).mul(100).toString(),
804
+ collAsset0: collAsset0.symbol,
805
+ collAsset1: collAsset1.symbol,
806
+ debtAsset0: debtAsset0.symbol,
807
+ debtAsset1: debtAsset1.symbol,
808
+ totalPositions: data.totalPositions,
809
+ totalSupplyVault: totalSupplyShares,
810
+ totalBorrowVault: totalBorrowShares,
811
+ totalSupplyVaultUsd,
812
+ totalBorrowVaultUsd,
813
+ liquidationMaxLimit,
814
+ borrowRate: marketBorrowRate,
815
+ incentiveBorrowRate,
816
+ supplyRate: marketSupplyRate,
817
+ incentiveSupplyRate,
818
+ borrowableToken0,
819
+ borrowableToken1,
820
+ totalBorrowToken0,
821
+ totalBorrowToken1,
822
+ borrowableUSD,
823
+ borrowable: borrowableShares,
824
+ borrowableDex: new Dec(maxBorrowShares).minus(totalBorrowShares).toString(),
825
+ maxBorrowShares,
826
+ maxBorrowSharesUsd,
827
+ borrowDexFee,
828
+ totalSupplyToken0,
829
+ totalSupplyToken1,
830
+ withdrawableToken0,
831
+ withdrawableToken1,
832
+ withdrawableUSD,
833
+ withdrawable: withdrawableShares,
834
+ withdrawableDex: new Dec(maxSupplyShares).minus(totalSupplyShares).toString(),
835
+ maxSupplyShares,
836
+ maxSupplySharesUsd,
837
+ collDexFee: supplyDexFee,
838
+ collSharePrice,
839
+ debtSharePrice,
840
+ oraclePrice,
841
+ tradingBorrowRate,
842
+ tradingSupplyRate,
843
+ };
844
+
845
+ return {
846
+ assetsData,
847
+ marketData,
848
+ } as FluidMarketData;
849
+ };
850
+
851
+ const parseMarketData = async (web3: Web3, data: FluidView.VaultDataStructOutputStruct, network: NetworkNumber, mainnetWeb3: Web3) => {
852
+ const vaultType = parseVaultType(+data.vaultType);
853
+ switch (vaultType) {
854
+ case FluidVaultType.T1:
855
+ return parseT1MarketData(web3, data, network, mainnetWeb3);
856
+ case FluidVaultType.T2:
857
+ return parseT2MarketData(web3, data, network, mainnetWeb3);
858
+ case FluidVaultType.T3:
859
+ return parseT3MarketData(web3, data, network, mainnetWeb3);
860
+ case FluidVaultType.T4:
861
+ return parseT4MarketData(web3, data, network, mainnetWeb3);
862
+ default:
863
+ throw new Error(`Unknown vault type: ${vaultType}`);
864
+ }
865
+ };
866
+
867
+ export const EMPTY_FLUID_DATA = {
868
+ usedAssets: {},
869
+ suppliedUsd: '0',
870
+ borrowedUsd: '0',
871
+ borrowLimitUsd: '0',
872
+ leftToBorrowUsd: '0',
873
+ ratio: '0',
874
+ minRatio: '0',
875
+ netApy: '0',
876
+ incentiveUsd: '0',
877
+ totalInterestUsd: '0',
878
+ isSubscribedToAutomation: false,
879
+ automationResubscribeRequired: false,
880
+ lastUpdated: Date.now(),
881
+ };
882
+
883
+ const parseT1UserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData): FluidVaultData => {
884
+ const {
885
+ assetsData,
886
+ marketData,
887
+ } = vaultData;
888
+
889
+ const payload = {
890
+ owner: userPositionData.owner,
891
+ vaultId: marketData.vaultId,
892
+ ...EMPTY_FLUID_DATA,
893
+ lastUpdated: Date.now(),
894
+ };
895
+ const collAsset = getAssetInfo(marketData.collAsset0);
896
+ const debtAsset = getAssetInfo(marketData.debtAsset0);
897
+
898
+ // for T2 and T4 - this is the number of shares
899
+ const supplied = getEthAmountForDecimals(userPositionData.supply, collAsset.decimals);
900
+ const borrowed = getEthAmountForDecimals(userPositionData.borrow, debtAsset.decimals);
901
+
902
+ const collUsedAsset: FluidUsedAsset = {
903
+ ...EMPTY_USED_ASSET,
904
+ symbol: collAsset.symbol,
905
+ collateral: true,
906
+ supplied,
907
+ suppliedUsd: new Dec(supplied).mul(assetsData[collAsset.symbol].price).toString(),
908
+ isSupplied: new Dec(supplied).gt(0),
909
+ };
910
+
911
+ const debtUsedAsset: FluidUsedAsset = {
912
+ ...EMPTY_USED_ASSET,
913
+ symbol: debtAsset.symbol,
914
+ collateral: false,
915
+ borrowed,
916
+ borrowedUsd: new Dec(borrowed).mul(assetsData[debtAsset.symbol].price).toString(),
917
+ isBorrowed: new Dec(borrowed).gt(0),
918
+ };
919
+
920
+ const usedAssets: FluidUsedAssets = {
921
+ [collAsset.symbol]: collUsedAsset,
922
+ [debtAsset.symbol]: debtUsedAsset,
923
+ };
924
+
925
+ return {
926
+ ...payload,
927
+ usedAssets,
928
+ ...(getFluidAggregatedData({
929
+ usedAssets,
930
+ assetsData,
931
+ marketData,
932
+ }) as FluidAggregatedVaultData),
933
+ };
934
+ };
935
+
936
+ const parseT2UserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData): FluidVaultData => {
937
+ const {
938
+ assetsData,
939
+ marketData,
940
+ } = vaultData;
941
+
942
+ const payload = {
943
+ owner: userPositionData.owner,
944
+ vaultId: marketData.vaultId,
945
+ ...EMPTY_FLUID_DATA,
946
+ lastUpdated: Date.now(),
947
+ };
948
+
949
+ const collAsset0 = getAssetInfo(marketData.collAsset0);
950
+ const collAsset1 = getAssetInfo(marketData.collAsset1);
951
+ const debtAsset = getAssetInfo(marketData.debtAsset0);
952
+
953
+ const supplyShares = getEthAmountForDecimals(userPositionData.supply, 18); // this is supplied in coll shares
954
+ const borrowed = getEthAmountForDecimals(userPositionData.borrow, debtAsset.decimals); // this is actual token borrow
955
+
956
+ const supplied0 = new Dec(supplyShares).mul(assetsData[collAsset0.symbol].tokenPerSupplyShare!).toString();
957
+ const supplied1 = new Dec(supplyShares).mul(assetsData[collAsset1.symbol].tokenPerSupplyShare!).toString();
958
+
959
+ const collUsedAsset0: Partial<FluidUsedAsset> = {
960
+ symbol: collAsset0.symbol,
961
+ collateral: true,
962
+ supplied: supplied0,
963
+ suppliedUsd: new Dec(supplied0).mul(assetsData[collAsset0.symbol].price).toString(),
964
+ isSupplied: new Dec(supplied0).gt(0),
965
+ };
966
+
967
+ const collUsedAsset1: Partial<FluidUsedAsset> = {
968
+ symbol: collAsset1.symbol,
969
+ collateral: true,
970
+ supplied: supplied1,
971
+ suppliedUsd: new Dec(supplied1).mul(assetsData[collAsset1.symbol].price).toString(),
972
+ isSupplied: new Dec(supplied1).gt(0),
973
+ };
974
+
975
+ const debtUsedAsset: Partial<FluidUsedAsset> = {
976
+ symbol: debtAsset.symbol,
977
+ borrowed,
978
+ borrowedUsd: new Dec(borrowed).mul(assetsData[debtAsset.symbol].price).toString(),
979
+ isBorrowed: new Dec(borrowed).gt(0),
980
+ };
981
+
982
+ const usedAssets: FluidUsedAssets = ([
983
+ [collAsset0.symbol, collUsedAsset0],
984
+ [collAsset1.symbol, collUsedAsset1],
985
+ [debtAsset.symbol, debtUsedAsset],
986
+ ] as [string, FluidUsedAsset][])
987
+ .reduce((acc, [symbol, partialData]) => {
988
+ acc[symbol] = mergeUsedAssets(acc[symbol], partialData);
989
+ return acc;
990
+ }, {} as Record<string, FluidUsedAsset>) as FluidUsedAssets;
991
+
992
+ return {
993
+ ...payload,
994
+ usedAssets,
995
+ supplyShares,
996
+ ...(getFluidAggregatedData({
997
+ usedAssets,
998
+ assetsData,
999
+ marketData,
1000
+ }, supplyShares) as FluidAggregatedVaultData),
1001
+ };
1002
+ };
1003
+
1004
+ const parseT3UserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData): FluidVaultData => {
1005
+ const {
1006
+ assetsData,
1007
+ marketData,
1008
+ } = vaultData;
1009
+
1010
+ const payload = {
1011
+ owner: userPositionData.owner,
1012
+ vaultId: marketData.vaultId,
1013
+ ...EMPTY_FLUID_DATA,
1014
+ lastUpdated: Date.now(),
1015
+ };
1016
+
1017
+ const collAsset = getAssetInfo(marketData.collAsset0);
1018
+ const debtAsset0 = getAssetInfo(marketData.debtAsset0);
1019
+ const debtAsset1 = getAssetInfo(marketData.debtAsset1);
1020
+
1021
+ const supplied = getEthAmountForDecimals(userPositionData.supply, collAsset.decimals); // this is actual token supply
1022
+ const borrowShares = getEthAmountForDecimals(userPositionData.borrow, 18); // this is actual token borrow
1023
+
1024
+ const borrowed0 = new Dec(borrowShares).mul(assetsData[debtAsset0.symbol].tokenPerBorrowShare!).toString();
1025
+ const borrowed1 = new Dec(borrowShares).mul(assetsData[debtAsset1.symbol].tokenPerBorrowShare!).toString();
1026
+
1027
+ const collUsedAsset: Partial<FluidUsedAsset> = {
1028
+ symbol: collAsset.symbol,
1029
+ collateral: true,
1030
+ supplied,
1031
+ suppliedUsd: new Dec(supplied).mul(assetsData[collAsset.symbol].price).toString(),
1032
+ isSupplied: new Dec(supplied).gt(0),
1033
+ };
1034
+
1035
+ const debtUsedAsset0: Partial<FluidUsedAsset> = {
1036
+ symbol: debtAsset0.symbol,
1037
+ borrowed: borrowed0,
1038
+ borrowedUsd: new Dec(borrowed0).mul(assetsData[debtAsset0.symbol].price).toString(),
1039
+ isBorrowed: new Dec(borrowed0).gt(0),
1040
+ };
1041
+
1042
+ const debtUsedAsset1: Partial<FluidUsedAsset> = {
1043
+ symbol: debtAsset1.symbol,
1044
+ borrowed: borrowed1,
1045
+ borrowedUsd: new Dec(borrowed1).mul(assetsData[debtAsset1.symbol].price).toString(),
1046
+ isBorrowed: new Dec(borrowed1).gt(0),
1047
+ };
1048
+
1049
+ const usedAssets: FluidUsedAssets = ([
1050
+ [collAsset.symbol, collUsedAsset],
1051
+ [debtAsset0.symbol, debtUsedAsset0],
1052
+ [debtAsset1.symbol, debtUsedAsset1],
1053
+ ] as [string, FluidUsedAsset][])
1054
+ .reduce((acc, [symbol, partialData]) => {
1055
+ acc[symbol] = mergeUsedAssets(acc[symbol], partialData);
1056
+ return acc;
1057
+ }, {} as Record<string, FluidUsedAsset>) as FluidUsedAssets;
1058
+
1059
+
1060
+ return {
1061
+ ...payload,
1062
+ usedAssets,
1063
+ borrowShares,
1064
+ ...(getFluidAggregatedData({
1065
+ usedAssets,
1066
+ assetsData,
1067
+ marketData,
1068
+ }, '', borrowShares) as FluidAggregatedVaultData),
1069
+ };
1070
+ };
1071
+
1072
+ const parseT4UserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData): FluidVaultData => {
1073
+ const {
1074
+ assetsData,
1075
+ marketData,
1076
+ } = vaultData;
1077
+
1078
+ const payload = {
1079
+ owner: userPositionData.owner,
1080
+ vaultId: marketData.vaultId,
1081
+ ...EMPTY_FLUID_DATA,
1082
+ lastUpdated: Date.now(),
1083
+ };
1084
+
1085
+ const collAsset0 = getAssetInfo(marketData.collAsset0);
1086
+ const collAsset1 = getAssetInfo(marketData.collAsset1);
1087
+ const debtAsset0 = getAssetInfo(marketData.debtAsset0);
1088
+ const debtAsset1 = getAssetInfo(marketData.debtAsset1);
1089
+
1090
+ const supplyShares = getEthAmountForDecimals(userPositionData.supply, 18); // this is actual token supply
1091
+ const borrowShares = getEthAmountForDecimals(userPositionData.borrow, 18); // this is actual token borrow
1092
+
1093
+ const supplied0 = new Dec(supplyShares).mul(assetsData[collAsset0.symbol].tokenPerSupplyShare!).toString();
1094
+ const supplied1 = new Dec(supplyShares).mul(assetsData[collAsset1.symbol].tokenPerSupplyShare!).toString();
1095
+
1096
+ const borrowed0 = new Dec(borrowShares).mul(assetsData[debtAsset0.symbol].tokenPerBorrowShare!).toString();
1097
+ const borrowed1 = new Dec(borrowShares).mul(assetsData[debtAsset1.symbol].tokenPerBorrowShare!).toString();
1098
+
1099
+ const collUsedAsset0: Partial<FluidUsedAsset> = {
1100
+ symbol: collAsset0.symbol,
1101
+ collateral: true,
1102
+ supplied: supplied0,
1103
+ suppliedUsd: new Dec(supplied0).mul(assetsData[collAsset0.symbol].price).toString(),
1104
+ isSupplied: new Dec(supplied0).gt(0),
1105
+ };
1106
+ const collUsedAsset1: Partial<FluidUsedAsset> = {
1107
+ symbol: collAsset1.symbol,
1108
+ collateral: true,
1109
+ supplied: supplied1,
1110
+ suppliedUsd: new Dec(supplied1).mul(assetsData[collAsset1.symbol].price).toString(),
1111
+ isSupplied: new Dec(supplied1).gt(0),
1112
+ };
1113
+
1114
+ const debtUsedAsset0: Partial<FluidUsedAsset> = {
1115
+ symbol: debtAsset0.symbol,
1116
+ borrowed: borrowed0,
1117
+ borrowedUsd: new Dec(borrowed0).mul(assetsData[debtAsset0.symbol].price).toString(),
1118
+ isBorrowed: new Dec(borrowed0).gt(0),
1119
+ };
1120
+ const debtUsedAsset1: Partial<FluidUsedAsset> = {
1121
+ symbol: debtAsset1.symbol,
1122
+ borrowed: borrowed1,
1123
+ borrowedUsd: new Dec(borrowed1).mul(assetsData[debtAsset1.symbol].price).toString(),
1124
+ isBorrowed: new Dec(borrowed1).gt(0),
1125
+ };
1126
+
1127
+ const usedAssets: FluidUsedAssets = ([
1128
+ [collAsset0.symbol, collUsedAsset0],
1129
+ [collAsset1.symbol, collUsedAsset1],
1130
+ [debtAsset0.symbol, debtUsedAsset0],
1131
+ [debtAsset1.symbol, debtUsedAsset1],
1132
+ ] as [string, FluidUsedAsset][])
1133
+ .reduce((acc, [symbol, partialData]) => {
1134
+ acc[symbol] = mergeUsedAssets(acc[symbol], partialData);
1135
+ return acc;
1136
+ }, {} as Record<string, FluidUsedAsset>) as FluidUsedAssets;
1137
+
1138
+ return {
1139
+ ...payload,
1140
+ usedAssets,
1141
+ supplyShares,
1142
+ borrowShares,
1143
+ ...(getFluidAggregatedData({
1144
+ usedAssets,
1145
+ assetsData,
1146
+ marketData,
1147
+ }, supplyShares, borrowShares) as FluidAggregatedVaultData),
1148
+ };
1149
+ };
1150
+
1151
+ const parseUserData = (userPositionData: FluidView.UserPositionStructOutputStruct, vaultData: FluidMarketData) => {
1152
+ const vaultType = vaultData.marketData.vaultType;
1153
+ switch (vaultType) {
1154
+ case FluidVaultType.T1:
1155
+ return parseT1UserData(userPositionData, vaultData);
1156
+ case FluidVaultType.T2:
1157
+ return parseT2UserData(userPositionData, vaultData);
1158
+ case FluidVaultType.T3:
1159
+ return parseT3UserData(userPositionData, vaultData);
1160
+ case FluidVaultType.T4:
1161
+ return parseT4UserData(userPositionData, vaultData);
1162
+ default:
1163
+ throw new Error(`Unknown vault type: ${vaultType}`);
1164
+ }
1165
+ };
1166
+
1167
+ export const getFluidMarketData = async (web3: Web3, network: NetworkNumber, market: FluidMarketInfo, mainnetWeb3: Web3) => {
1168
+ const view = FluidViewContract(web3, network);
1169
+
1170
+ const data = await view.methods.getVaultData(market.marketAddress).call();
1171
+
1172
+ return parseMarketData(web3, data, network, mainnetWeb3);
1173
+ };
1174
+
1175
+ export const getFluidVaultIdsForUser = async (web3: Web3,
1176
+ network:NetworkNumber,
1177
+ user: EthAddress): Promise<string[]> => {
1178
+ const view = FluidViewContract(web3, network);
1179
+
1180
+ return view.methods.getUserNftIds(user).call();
1181
+ };
1182
+
1183
+
1184
+ export const getFluidPosition = async (
1185
+ web3: Web3,
1186
+ network: NetworkNumber,
1187
+ vaultId: string,
1188
+ extractedState: {
1189
+ assetsData: FluidAssetsData
1190
+ marketData: InnerFluidMarketData,
1191
+ },
1192
+ ): Promise<FluidVaultData> => {
1193
+ const view = FluidViewContract(web3, network);
1194
+
1195
+ const data = await view.methods.getPositionByNftId(vaultId).call();
1196
+
1197
+ const userPositionData = data[0];
1198
+
1199
+ return parseUserData(userPositionData, extractedState);
1200
+ };
1201
+
1202
+ export const getFluidPositionWithMarket = async (web3: Web3, network: NetworkNumber, vaultId: string, mainnetWeb3: Web3) => {
1203
+ const view = FluidViewContract(web3, network);
1204
+ const data = await view.methods.getPositionByNftId(vaultId).call();
1205
+ const marketData = await parseMarketData(web3, data.vault, network, mainnetWeb3);
1206
+ const userData = parseUserData(data.position, marketData);
1207
+
1208
+ return {
1209
+ userData,
1210
+ marketData,
1211
+ };
1212
+ };
1213
+
1214
+ export const getAllFluidMarketDataChunked = async (network: NetworkNumber, web3: Web3, mainnetWeb3: Web3) => {
1215
+ const versions = getFluidVersionsDataForNetwork(network);
1216
+ const view = FluidViewContract(web3, network);
1217
+ const calls = versions.map((version) => ({
1218
+ target: view.options.address,
1219
+ abiItem: view.options.jsonInterface.find((item) => item.name === 'getVaultData'),
1220
+ params: [version.marketAddress],
1221
+ }));
1222
+
1223
+ const data = await chunkAndMulticall(calls, 10, 'latest', web3, network);
1224
+ // @ts-ignore
1225
+ return Promise.all(data.map(async (item, i) => parseMarketData(web3, item.vaultData, network, mainnetWeb3)));
1226
+ };
1227
+
1228
+ export const getFluidTokenData = async (web3: Web3, network: NetworkNumber, token: string) => {
1229
+ const view = FluidViewContract(web3, network);
1230
+ const fTokenAddress = getFTokenAddress(token, network);
1231
+ const data = await view.methods.getFTokenData(fTokenAddress).call();
1232
+ const supplyRate = new Dec(data.supplyRate).div(100).toString();
1233
+ const rewardsRate = new Dec(data.rewardsRate).div(1e12).toString();
1234
+ const decimals = data.decimals;
1235
+
1236
+ const depositRate = new Dec(getEthAmountForDecimals(data.convertToShares, decimals)).toString();
1237
+ const withdrawRate = new Dec(getEthAmountForDecimals(data.convertToAssets, decimals)).toString();
1238
+
1239
+ return {
1240
+ fTokenAddress,
1241
+ fTokenSymbol: data.symbol,
1242
+ decimals,
1243
+ totalDeposited: getEthAmountForDecimals(data.totalAssets, decimals),
1244
+ withdrawable: getEthAmountForDecimals(data.withdrawable, decimals),
1245
+ apy: new Dec(supplyRate).add(rewardsRate).toString(),
1246
+ depositRate,
1247
+ withdrawRate,
1248
+ };
1249
+ };
1250
+
1251
+ export const getFluidDepositData = async (web3: Web3, network: NetworkNumber, token: string, address: EthAddress) => {
1252
+ const view = FluidViewContract(web3, network);
1253
+ const fTokenAddress = getFTokenAddress(token, network);
1254
+ const { fTokenData, userPosition } = await view.methods.getUserEarnPositionWithFToken(fTokenAddress, address).call();
1255
+
1256
+ const supplyRate = new Dec(fTokenData.supplyRate).div(100).toString();
1257
+ const rewardsRate = new Dec(fTokenData.rewardsRate).div(1e12).toString();
1258
+ const decimals = fTokenData.decimals;
1259
+
1260
+ const depositRate = new Dec(getEthAmountForDecimals(fTokenData.convertToShares, decimals)).toString();
1261
+ const withdrawRate = new Dec(getEthAmountForDecimals(fTokenData.convertToAssets, decimals)).toString();
1262
+
1263
+ return {
1264
+ fTokenAddress,
1265
+ fTokenSymbol: fTokenData.symbol,
1266
+ decimals,
1267
+ totalDeposited: getEthAmountForDecimals(fTokenData.totalAssets, decimals),
1268
+ withdrawable: getEthAmountForDecimals(fTokenData.withdrawable, decimals),
1269
+ apy: new Dec(supplyRate).add(rewardsRate).toString(),
1270
+ depositRate,
1271
+ withdrawRate,
1272
+ deposited: getEthAmountForDecimals(userPosition.underlyingAssets, decimals),
1273
+ depositedShares: getEthAmountForDecimals(userPosition.fTokenShares, decimals),
1274
+ };
1275
+ };
1276
+
1277
+ export const getUserPositions = async (web3: Web3, network: NetworkNumber, user: EthAddress, mainnetWeb3: Web3) => {
1278
+ const view = FluidViewContract(web3, network);
1279
+
1280
+ const data = await view.methods.getUserPositions(user).call();
1281
+
1282
+ const parsedMarketData = await Promise.all(data.vaults.map(async (vaultData) => parseMarketData(web3, vaultData, network, mainnetWeb3)));
1283
+
1284
+ const userData = data.positions.map((position, i) => ({ ...parseUserData(position, parsedMarketData[i]), nftId: position.nftId }));
1285
+
1286
+ return parsedMarketData.map((market, i) => ({
1287
+ marketData: market,
1288
+ userData: userData[i],
1289
+ }));
1242
1290
  };