@defisaver/positions-sdk 1.0.11-fluid-dev11 → 1.0.11-fluid-dev13

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