@defisaver/positions-sdk 2.1.4 → 2.1.5

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 (90) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/CLAUDE.md +32 -0
  4. package/README.md +64 -64
  5. package/cjs/curveUsd/index.js +2 -1
  6. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  7. package/cjs/types/curveUsd.d.ts +2 -0
  8. package/esm/curveUsd/index.js +2 -1
  9. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  10. package/esm/types/curveUsd.d.ts +2 -0
  11. package/package.json +47 -47
  12. package/src/aaveV2/index.ts +240 -240
  13. package/src/aaveV3/index.ts +614 -614
  14. package/src/aaveV3/merit.ts +94 -94
  15. package/src/aaveV3/merkl.ts +74 -74
  16. package/src/claiming/aaveV3.ts +154 -154
  17. package/src/claiming/compV3.ts +22 -22
  18. package/src/claiming/index.ts +12 -12
  19. package/src/claiming/king.ts +66 -66
  20. package/src/claiming/morphoBlue.ts +118 -118
  21. package/src/claiming/spark.ts +225 -225
  22. package/src/compoundV2/index.ts +244 -244
  23. package/src/compoundV3/index.ts +274 -274
  24. package/src/config/contracts.ts +1228 -1228
  25. package/src/constants/index.ts +10 -10
  26. package/src/contracts.ts +120 -120
  27. package/src/curveUsd/index.ts +254 -250
  28. package/src/eulerV2/index.ts +324 -324
  29. package/src/exchange/index.ts +25 -25
  30. package/src/fluid/index.ts +1638 -1638
  31. package/src/helpers/aaveHelpers/index.ts +185 -185
  32. package/src/helpers/compoundHelpers/index.ts +283 -283
  33. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  34. package/src/helpers/eulerHelpers/index.ts +222 -222
  35. package/src/helpers/fluidHelpers/index.ts +326 -326
  36. package/src/helpers/index.ts +10 -10
  37. package/src/helpers/liquityV2Helpers/index.ts +82 -82
  38. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  39. package/src/helpers/makerHelpers/index.ts +52 -52
  40. package/src/helpers/morphoBlueHelpers/index.ts +396 -396
  41. package/src/helpers/sparkHelpers/index.ts +155 -155
  42. package/src/index.ts +47 -47
  43. package/src/liquity/index.ts +159 -159
  44. package/src/liquityV2/index.ts +657 -657
  45. package/src/llamaLend/index.ts +305 -305
  46. package/src/maker/index.ts +223 -223
  47. package/src/markets/aave/index.ts +116 -116
  48. package/src/markets/aave/marketAssets.ts +49 -49
  49. package/src/markets/compound/index.ts +227 -227
  50. package/src/markets/compound/marketsAssets.ts +90 -90
  51. package/src/markets/curveUsd/index.ts +69 -69
  52. package/src/markets/euler/index.ts +26 -26
  53. package/src/markets/fluid/index.ts +2456 -2456
  54. package/src/markets/index.ts +25 -25
  55. package/src/markets/liquityV2/index.ts +102 -102
  56. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  57. package/src/markets/llamaLend/index.ts +235 -235
  58. package/src/markets/morphoBlue/index.ts +895 -895
  59. package/src/markets/spark/index.ts +29 -29
  60. package/src/markets/spark/marketAssets.ts +11 -11
  61. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  62. package/src/morphoBlue/index.ts +274 -274
  63. package/src/portfolio/index.ts +570 -570
  64. package/src/services/priceService.ts +159 -159
  65. package/src/services/utils.ts +99 -99
  66. package/src/services/viem.ts +32 -32
  67. package/src/setup.ts +8 -8
  68. package/src/spark/index.ts +445 -445
  69. package/src/staking/eligibility.ts +59 -59
  70. package/src/staking/index.ts +1 -1
  71. package/src/staking/staking.ts +170 -170
  72. package/src/types/aave.ts +189 -189
  73. package/src/types/claiming.ts +109 -109
  74. package/src/types/common.ts +105 -105
  75. package/src/types/compound.ts +136 -136
  76. package/src/types/curveUsd.ts +123 -121
  77. package/src/types/euler.ts +175 -175
  78. package/src/types/fluid.ts +448 -448
  79. package/src/types/index.ts +13 -13
  80. package/src/types/liquity.ts +30 -30
  81. package/src/types/liquityV2.ts +126 -126
  82. package/src/types/llamaLend.ts +159 -159
  83. package/src/types/maker.ts +63 -63
  84. package/src/types/merit.ts +1 -1
  85. package/src/types/merkl.ts +70 -70
  86. package/src/types/morphoBlue.ts +194 -194
  87. package/src/types/portfolio.ts +60 -60
  88. package/src/types/spark.ts +135 -135
  89. package/src/umbrella/index.ts +69 -69
  90. package/src/umbrella/umbrellaUtils.ts +29 -29
@@ -1,658 +1,658 @@
1
- import Dec from 'decimal.js';
2
- import { assetAmountInEth, getAssetInfo } from '@defisaver/tokens';
3
- import { Client, PublicClient } from 'viem';
4
- import {
5
- createViemContractFromConfigFunc,
6
- LiquityV2LegacyViewContractViem,
7
- LiquityV2sBoldVaultViem,
8
- LiquityV2ViewContractViem,
9
- } from '../contracts';
10
- import {
11
- EthAddress, EthereumProvider, IncentiveKind, NetworkNumber, HexString,
12
- } from '../types/common';
13
- import {
14
- LIQUITY_V2_TROVE_STATUS_ENUM,
15
- LiquityV2AssetsData, LiquityV2MarketData, LiquityV2MarketInfo, LiquityV2TroveData, LiquityV2UsedAssets,
16
- LiquityV2Versions,
17
- } from '../types';
18
- import { getStakingApy, STAKING_ASSETS } from '../staking';
19
- import { getLiquityV2AggregatedPositionData } from '../helpers/liquityV2Helpers';
20
- import {
21
- compareAddresses,
22
- ethToWeth,
23
- getEthAmountForDecimals,
24
- MAXUINT,
25
- } from '../services/utils';
26
- import { SECONDS_PER_YEAR, ZERO_ADDRESS } from '../constants';
27
- import { LiquityV2Markets } from '../markets';
28
- import { getViemProvider } from '../services/viem';
29
-
30
- export type SPYieldGainParameters = {
31
- P: string;
32
- aggWeightedDebtSum: string;
33
- currentScale: string;
34
- lastAggUpdateTime: string;
35
- totalBoldDeposits: string;
36
- yieldGainsPending: string;
37
- };
38
-
39
- const getLiquityV2ViewContract = (provider: Client, network: NetworkNumber, isLegacy: boolean) => {
40
- if (isLegacy) return LiquityV2LegacyViewContractViem(provider, network);
41
- return LiquityV2ViewContractViem(provider, network);
42
- };
43
-
44
-
45
- export const _getLiquityV2MarketData = async (provider: Client, network: NetworkNumber, selectedMarket: LiquityV2MarketInfo): Promise<LiquityV2MarketData> => {
46
- const {
47
- marketAddress, debtToken, collateralToken, isLegacy,
48
- } = selectedMarket;
49
- const viewContract = getLiquityV2ViewContract(provider, network, isLegacy);
50
- const data = await viewContract.read.getMarketData([marketAddress]);
51
- const hintHelperAddress = data.hintHelpers;
52
- const troveNFTAddress = data.troveNFT;
53
- const borrowerOperationsAddress = data.borrowerOperations;
54
- const troveManagerAddress = data.troveManager;
55
- const stabilityPoolAddress = data.stabilityPool;
56
- const collSurplusPoolAddress = data.collSurplusPool;
57
- const activePoolAddress = data.activePool;
58
-
59
- const minCollRatio = new Dec(data.MCR).div(1e16).toString();
60
- const criticalCollRatio = new Dec(data.CCR).div(1e18).toString();
61
- // @ts-ignore
62
- const batchCollRatio = new Dec(data.BCR ?? '0').div(1e16).toString();
63
-
64
- const totalMarketBorrow = assetAmountInEth(data.entireSystemDebt.toString());
65
- const totalMarketSupply = assetAmountInEth(data.entireSystemColl.toString());
66
- const collPrice = assetAmountInEth(data.collPrice.toString());
67
-
68
- const totalCollRatio = new Dec(totalMarketSupply).mul(collPrice).div(totalMarketBorrow).toString();
69
- const leftToBorrowGlobal = new Dec(totalMarketSupply).mul(collPrice).div(criticalCollRatio).sub(totalMarketBorrow)
70
- .toString();
71
- const minCollAmountForCurrentBorrow = new Dec(totalMarketBorrow).mul(criticalCollRatio).div(collPrice).toString();
72
- const leftToWithdrawGlobal = new Dec(totalMarketSupply).sub(minCollAmountForCurrentBorrow).toString();
73
-
74
- const assetsData: LiquityV2AssetsData = {};
75
- assetsData[debtToken] = {
76
- symbol: debtToken,
77
- address: getAssetInfo(debtToken, network).address,
78
- price: '1',
79
- totalSupply: '0',
80
- totalBorrow: totalMarketBorrow,
81
- canBeSupplied: false,
82
- canBeBorrowed: true,
83
- leftToBorrowGlobal,
84
- leftToWithdrawGlobal: '0',
85
- supplyIncentives: [],
86
- borrowIncentives: [],
87
- };
88
- assetsData[collateralToken] = {
89
- symbol: collateralToken,
90
- address: getAssetInfo(ethToWeth(collateralToken), network).address,
91
- price: collPrice,
92
- totalSupply: totalMarketSupply,
93
- totalBorrow: '0',
94
- canBeSupplied: true,
95
- canBeBorrowed: false,
96
- leftToBorrowGlobal: '0',
97
- leftToWithdrawGlobal,
98
- supplyIncentives: [],
99
- borrowIncentives: [],
100
- };
101
- if (STAKING_ASSETS.includes(collateralToken)) {
102
- assetsData[collateralToken].supplyIncentives.push({
103
- apy: await getStakingApy(collateralToken),
104
- token: collateralToken,
105
- incentiveKind: IncentiveKind.Staking,
106
- description: `Native ${collateralToken} yield.`,
107
- });
108
- }
109
-
110
- return {
111
- assetsData,
112
- marketData: {
113
- minCollRatio,
114
- totalCollRatio: new Dec(totalCollRatio).mul(100).toString(),
115
- criticalCollRatio: new Dec(criticalCollRatio).mul(100).toString(),
116
- batchCollRatio,
117
- isUnderCollateralized: new Dec(totalCollRatio).lt(criticalCollRatio),
118
- hintHelperAddress,
119
- troveNFTAddress,
120
- borrowerOperationsAddress,
121
- troveManagerAddress,
122
- stabilityPoolAddress,
123
- collSurplusPoolAddress,
124
- activePoolAddress,
125
- },
126
- };
127
- };
128
-
129
- export const getLiquityV2MarketData = async (
130
- provider: EthereumProvider,
131
- network: NetworkNumber,
132
- selectedMarket: LiquityV2MarketInfo,
133
- ): Promise<LiquityV2MarketData> => _getLiquityV2MarketData(getViemProvider(provider, network), network, selectedMarket);
134
-
135
- const getUserTroves = async (
136
- provider: Client,
137
- network: NetworkNumber,
138
- isLegacy: boolean,
139
- account: EthAddress,
140
- marketAddress: EthAddress,
141
- startIndex = 0,
142
- endIndex = 100,
143
- troves: { troveId: string, ownedByUser: boolean }[] = [],
144
- ): Promise<{ troves: { troveId: string, ownedByUser: boolean }[], nextFreeTroveIndex: string }> => {
145
- const viewContract = getLiquityV2ViewContract(provider, network, isLegacy);
146
- const result = await viewContract.read.getUserTroves([account, marketAddress, BigInt(startIndex), BigInt(endIndex)]);
147
- const newStartIndex = endIndex + 1;
148
- const nextFreeTroveIndex = result[1].toString();
149
- const existingTroves = [...troves, ...result[0].map((trove: any) => ({ ...trove, troveId: trove.troveId.toString() }))];
150
- if (nextFreeTroveIndex !== '-1') return { troves: existingTroves.filter((trove) => trove.ownedByUser), nextFreeTroveIndex };
151
- return getUserTroves(provider, network, isLegacy, account, marketAddress, newStartIndex, newStartIndex + 100, existingTroves);
152
- };
153
-
154
- const nftContractCreationBlockMapping = {
155
- [LiquityV2Versions.LiquityV2Eth]: 22516079,
156
- [LiquityV2Versions.LiquityV2WstEth]: 22516099,
157
- [LiquityV2Versions.LiquityV2REth]: 22516118,
158
- // legacy
159
- [LiquityV2Versions.LiquityV2EthLegacy]: 21686215,
160
- [LiquityV2Versions.LiquityV2WstEthLegacy]: 21686238,
161
- [LiquityV2Versions.LiquityV2REthLegacy]: 21686257,
162
- };
163
-
164
- const getTransferredTroves = async (provider: PublicClient, network: NetworkNumber, troveNFTAddress: EthAddress, limitBlocksForEventFetching: boolean, market: LiquityV2Versions, account: EthAddress): Promise<{ troveId: string }[]> => {
165
- const nftContract = createViemContractFromConfigFunc('LiquityV2TroveNFT', troveNFTAddress)(provider, network);
166
- const nftContractCreationBlock = nftContractCreationBlockMapping[market];
167
- const currentBlock = +(await provider.getBlockNumber()).toString();
168
- const _events = await nftContract.getEvents.Transfer({}, { fromBlock: limitBlocksForEventFetching ? BigInt(currentBlock - 1000) : BigInt(nftContractCreationBlock) });
169
- const events = _events.map((event) => ({
170
- from: event.args.from, to: event.args.to, tokenId: event.args.tokenId!.toString(), blockNumber: +(event.blockNumber.toString()),
171
- }));
172
- const userTransferredTroves = events.filter((event) => compareAddresses(event.to, account));
173
-
174
- // check if the last know transfer address is the user
175
- userTransferredTroves.forEach((event, index) => {
176
- const otherTransfers = events.filter((e) => event.blockNumber < e.blockNumber && e.tokenId === event.tokenId);
177
- // @ts-ignore
178
- userTransferredTroves[index].invalid = !!otherTransfers.length;
179
- });
180
- // @ts-ignore
181
- return userTransferredTroves.filter((event) => !event.invalid).map((event) => ({ troveId: event.tokenId }));
182
- };
183
-
184
- export const _getLiquityV2UserTroveIds = async (provider: PublicClient, network: NetworkNumber, selectedMarket: LiquityV2MarketInfo, troveNFTAddress: EthAddress, limitBlocksForEventFetching: boolean, account: EthAddress): Promise<{ troves: { troveId: string }[], nextFreeTroveIndex: string }> => {
185
- const [{ troves: userTroves, nextFreeTroveIndex }, userTransferredTroves] = await Promise.all([
186
- getUserTroves(provider, network, selectedMarket.isLegacy, account, selectedMarket.marketAddress),
187
- getTransferredTroves(provider, network, troveNFTAddress, limitBlocksForEventFetching, selectedMarket.value, account),
188
- ]);
189
- const troves = [...userTroves.map(({ troveId }) => ({ troveId })), ...userTransferredTroves];
190
- const filteredTroves = troves.filter((value, index, self) => index === self.findIndex((t) => (
191
- t.troveId === value.troveId
192
- )),
193
- );
194
- const troveIds = filteredTroves.map((trove) => trove.troveId);
195
- const troveIdsSet = new Set(troveIds);
196
- const troveIdsArray = Array.from(troveIdsSet);
197
- const trovesNoDuplicates = troveIdsArray.map((troveId) => troves.find((trove) => trove.troveId === troveId)) as { troveId: string }[];
198
- return { troves: trovesNoDuplicates, nextFreeTroveIndex };
199
- };
200
-
201
- export const getLiquityV2UserTroveIds = async (
202
- provider: EthereumProvider,
203
- network: NetworkNumber,
204
- selectedMarket: LiquityV2MarketInfo,
205
- troveNFTAddress: EthAddress,
206
- limitBlocksForEventFetching: boolean,
207
- account: EthAddress,
208
- ): Promise<{ troves: { troveId: string }[], nextFreeTroveIndex: string }> => _getLiquityV2UserTroveIds(getViemProvider(provider, network), network, selectedMarket, troveNFTAddress, limitBlocksForEventFetching, account);
209
-
210
- const getDebtInFrontForSingleMarketLiquityV2 = async (
211
- provider: Client,
212
- network: NetworkNumber,
213
- isLegacy: boolean,
214
- marketAddress: EthAddress,
215
- troveId: string,
216
- accumulatedSum = '0',
217
- iterations = 2000,
218
- ): Promise<string> => {
219
- const viewContract = getLiquityV2ViewContract(provider, network, isLegacy);
220
- const res = await viewContract.read.getDebtInFront([marketAddress, BigInt(troveId), BigInt(accumulatedSum), BigInt(iterations)]);
221
- const next = res[0].toString();
222
- const debt = res[1].toString();
223
- if (next === '0') return assetAmountInEth(debt);
224
- return getDebtInFrontForSingleMarketLiquityV2(provider, network, isLegacy, marketAddress, next, debt, iterations);
225
- };
226
-
227
- const getDebtInFrontForInterestRateSingleMarketLiquityV2 = async (
228
- provider: Client,
229
- network: NetworkNumber,
230
- isLegacy: boolean,
231
- marketAddress: EthAddress,
232
- interestRate: string,
233
- troveId = '0',
234
- accumulatedSum = '0',
235
- iterations = 2000,
236
- ): Promise<string> => {
237
- const viewContract = getLiquityV2ViewContract(provider, network, isLegacy);
238
- if (+interestRate === 0 || !interestRate) return '0';
239
- const interestRateWei = new Dec(interestRate).times(1e16).toFixed(0).toString();
240
- const res = await viewContract.read.getDebtInFrontByInterestRate([marketAddress, BigInt(troveId), BigInt(accumulatedSum), BigInt(iterations), BigInt(interestRateWei)]);
241
- const next = res[0].toString();
242
- const debt = res[1].toString();
243
- if (next === '0') return assetAmountInEth(debt);
244
- return getDebtInFrontForInterestRateSingleMarketLiquityV2(provider, network, isLegacy, marketAddress, interestRate, next, debt, iterations);
245
- };
246
-
247
- const getUnbackedDebtForSingleMarket = async (totalBorrowed: string, provider: Client, network: NetworkNumber, stabilityPoolAddress: EthAddress) => {
248
- const stabilityPoolContract = createViemContractFromConfigFunc('LiquityV2StabilityPool', stabilityPoolAddress)(provider, network);
249
- const totalBoldDeposits = await stabilityPoolContract.read.getTotalBoldDeposits();
250
- const totalBoldDepositsInEth = assetAmountInEth(totalBoldDeposits.toString());
251
-
252
- return Dec.max(new Dec(totalBorrowed).sub(totalBoldDepositsInEth), 0).toString();
253
- };
254
-
255
- const getAllMarketsUnbackedDebts = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, isLegacy: boolean, provider: Client, network: NetworkNumber): Promise<Record<LiquityV2Versions, string>> => {
256
- const allMarketsUnbackedDebt = await Promise.all(Object.entries(markets).map(async ([version, market]) => {
257
- const { assetsData, marketData } = market;
258
- const { debtToken, isLegacy: isLegacyMarket } = LiquityV2Markets(network)[version as LiquityV2Versions];
259
- if (isLegacyMarket !== isLegacy) return [version, '0'];
260
- const unbackedDebt = await getUnbackedDebtForSingleMarket(assetsData[debtToken].totalBorrow, provider, network, marketData.stabilityPoolAddress);
261
- return [version, unbackedDebt];
262
- }));
263
-
264
- return Object.fromEntries(allMarketsUnbackedDebt) as Record<LiquityV2Versions, string>;
265
- };
266
-
267
- const calculateDebtInFrontLiquityV2 = (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, allMarketsUnbackedDebts: Record<LiquityV2Versions, string>, interestRateDebtInFront: string): string => {
268
- const selectedMarketUnbackedDebt = new Dec(allMarketsUnbackedDebts[selectedMarket]);
269
- const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
270
- if (selectedMarketUnbackedDebt.eq(0)) return interestRateDebtInFront;
271
-
272
- const amountBeingReedemedOnEachMarket = Object.entries(markets).map(([version, market]) => {
273
- const { isLegacy: isLegacyMarket } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
274
- if (version === selectedMarket && isLegacyMarket !== isLegacy) return new Dec(interestRateDebtInFront);
275
- const { assetsData } = market;
276
- const { debtToken } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
277
- const unbackedDebt = new Dec(allMarketsUnbackedDebts[version as LiquityV2Versions]);
278
- const totalBorrow = new Dec(assetsData[debtToken].totalBorrow);
279
- const amountToReedem = new Dec(interestRateDebtInFront).mul(unbackedDebt).div(selectedMarketUnbackedDebt);
280
- return Dec.min(amountToReedem, totalBorrow);
281
- });
282
-
283
- return amountBeingReedemedOnEachMarket.reduce((acc, val) => acc.plus(val), new Dec(0)).toString();
284
- };
285
-
286
- const getDebtInFrontLiquityV2 = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, viewContract: any, troveId: string) => {
287
- const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
288
- const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(markets, isLegacy, provider, network);
289
- const interestRateDebtInFront = await getDebtInFrontForSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, troveId);
290
-
291
- return calculateDebtInFrontLiquityV2(markets, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
292
- };
293
-
294
- /**
295
- * @param markets
296
- * @param selectedMarket
297
- * @param provider
298
- * @param network
299
- * @param viewContract
300
- * @param interestRate
301
- * @param debtInFrontBeingMoved - amound of debt being repositioned if interest rate is being increased (prevents including it as debt in front)
302
- */
303
- const _getDebtInFrontForInterestRateLiquityV2 = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, isLegacy: boolean, interestRate: string, debtInFrontBeingMoved: string = '0') => {
304
- const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(markets, isLegacy, provider, network);
305
- const interestRateDebtInFront = new Dec(await getDebtInFrontForInterestRateSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, interestRate))
306
- .sub(debtInFrontBeingMoved);
307
-
308
- return calculateDebtInFrontLiquityV2(markets, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
309
- };
310
-
311
- export const getDebtInFrontForInterestRateLiquityV2 = async (
312
- markets: Record<LiquityV2Versions, LiquityV2MarketData>,
313
- selectedMarket: LiquityV2Versions,
314
- provider: EthereumProvider,
315
- network: NetworkNumber,
316
- isLegacy: boolean,
317
- interestRate: string,
318
- debtInFrontBeingMoved: string = '0',
319
- ) => _getDebtInFrontForInterestRateLiquityV2(markets, selectedMarket, getViemProvider(provider, network), network, isLegacy, interestRate, debtInFrontBeingMoved);
320
-
321
- export const _getLiquityV2TroveData = async (
322
- provider: Client,
323
- network: NetworkNumber,
324
- {
325
- selectedMarket,
326
- assetsData,
327
- troveId,
328
- allMarketsData,
329
- }:
330
- {
331
- selectedMarket: LiquityV2MarketInfo,
332
- assetsData: LiquityV2AssetsData,
333
- troveId: string,
334
- allMarketsData: Record<LiquityV2Versions, LiquityV2MarketData>,
335
- },
336
- fetchDebtInFront: boolean = true,
337
- ): Promise<LiquityV2TroveData> => {
338
- const viewContract = getLiquityV2ViewContract(provider, network, selectedMarket.isLegacy);
339
- const { minCollRatio, batchCollRatio } = allMarketsData[selectedMarket.value].marketData;
340
- const { collateralToken, marketAddress, debtToken } = selectedMarket;
341
- const [_data, debtInFront] = await Promise.all([
342
- viewContract.read.getTroveInfo([marketAddress, BigInt(troveId)]),
343
- fetchDebtInFront ? getDebtInFrontLiquityV2(allMarketsData, selectedMarket.value, provider, network, selectedMarket.isLegacy, troveId) : Promise.resolve('0'),
344
- ]);
345
- const data = {
346
- ..._data,
347
- TCRatio: _data.TCRatio.toString() === MAXUINT ? '0' : _data.TCRatio.toString(), // mistake on contract side when debt is 0
348
- };
349
- const usedAssets: LiquityV2UsedAssets = {};
350
-
351
- const debtAssetData = assetsData[debtToken];
352
- const borrowed = assetAmountInEth(data.debtAmount.toString());
353
- usedAssets[debtToken] = {
354
- symbol: debtToken,
355
- supplied: '0',
356
- suppliedUsd: '0',
357
- borrowed,
358
- borrowedUsd: new Dec(borrowed).mul(debtAssetData.price).toString(),
359
- isBorrowed: true,
360
- isSupplied: false,
361
- };
362
-
363
- const collAssetData = assetsData[collateralToken];
364
- const suppliedColl = assetAmountInEth(data.collAmount.toString());
365
- usedAssets[collateralToken] = {
366
- symbol: collateralToken,
367
- supplied: suppliedColl,
368
- suppliedUsd: new Dec(suppliedColl).mul(collAssetData.price).toString(),
369
- borrowed: '0',
370
- borrowedUsd: '0',
371
- isBorrowed: false,
372
- isSupplied: true,
373
- collateral: true,
374
- };
375
-
376
- const collRatio = new Dec(data.TCRatio).div(1e16).toString();
377
- const interestRate = new Dec(data.annualInterestRate).div(1e16).toString();
378
- const interestBatchManager = data.interestBatchManager;
379
- const lastInterestRateAdjTime = data.lastInterestRateAdjTime.toString();
380
-
381
- const hasInterestBatchManager = !compareAddresses(interestBatchManager, ZERO_ADDRESS);
382
- const liqRatio = hasInterestBatchManager ? new Dec(minCollRatio).add(batchCollRatio).toString() : minCollRatio;
383
-
384
- const payload: LiquityV2TroveData = {
385
- usedAssets,
386
- troveId,
387
- interestRate,
388
- interestBatchManager,
389
- debtInFront,
390
- lastInterestRateAdjTime,
391
- liqRatio,
392
- troveStatus: LIQUITY_V2_TROVE_STATUS_ENUM[parseInt(data.status.toString(), 10)],
393
- ...getLiquityV2AggregatedPositionData({
394
- usedAssets, assetsData, minCollRatio: liqRatio, interestRate,
395
- }),
396
- collRatio,
397
- };
398
-
399
- return payload;
400
- };
401
-
402
- export const getLiquityV2TroveData = async (
403
- provider: EthereumProvider,
404
- network: NetworkNumber,
405
- {
406
- selectedMarket,
407
- assetsData,
408
- troveId,
409
- allMarketsData,
410
- }:
411
- {
412
- selectedMarket: LiquityV2MarketInfo,
413
- assetsData: LiquityV2AssetsData,
414
- troveId: string,
415
- allMarketsData: Record<LiquityV2Versions, LiquityV2MarketData>,
416
- },
417
- fetchDebtInFront: boolean = true,
418
- ): Promise<LiquityV2TroveData> => _getLiquityV2TroveData(
419
- getViemProvider(provider, network),
420
- network,
421
- {
422
- selectedMarket,
423
- assetsData,
424
- troveId,
425
- allMarketsData,
426
- },
427
- fetchDebtInFront,
428
- );
429
-
430
- export const getLiquityV2ClaimableCollateral = async (collSurplusPoolAddress: EthAddress, account: EthAddress, provider: EthereumProvider, network: NetworkNumber): Promise<string> => {
431
- const client = getViemProvider(provider, network);
432
- const collSurplusPoolContract = createViemContractFromConfigFunc('LiquityV2CollSurplusPool', collSurplusPoolAddress)(client, network);
433
- const claimableCollateral = await collSurplusPoolContract.read.getCollateral([account]);
434
- return claimableCollateral.toString();
435
- };
436
-
437
- const stabilityPoolAddrForMarket: Record<LiquityV2Versions, EthAddress> = {
438
- [LiquityV2Versions.LiquityV2Eth]: '0x5721cbbd64fc7Ae3Ef44A0A3F9a790A9264Cf9BF',
439
- [LiquityV2Versions.LiquityV2WstEth]: '0x9502b7c397e9aa22fe9db7ef7daf21cd2aebe56b',
440
- [LiquityV2Versions.LiquityV2REth]: '0xd442e41019b7f5c4dd78f50dc03726c446148695',
441
- [LiquityV2Versions.LiquityV2EthLegacy]: ZERO_ADDRESS,
442
- [LiquityV2Versions.LiquityV2REthLegacy]: ZERO_ADDRESS,
443
- [LiquityV2Versions.LiquityV2WstEthLegacy]: ZERO_ADDRESS,
444
- };
445
- const activePoolAddrForMarket: Record<LiquityV2Versions, EthAddress> = {
446
- [LiquityV2Versions.LiquityV2Eth]: '0xeB5A8C825582965f1d84606E078620a84ab16AfE',
447
- [LiquityV2Versions.LiquityV2WstEth]: '0x531a8f99c70d6a56a7cee02d6b4281650d7919a0',
448
- [LiquityV2Versions.LiquityV2REth]: '0x9074d72cc82dad1e13e454755aa8f144c479532f',
449
- [LiquityV2Versions.LiquityV2EthLegacy]: ZERO_ADDRESS,
450
- [LiquityV2Versions.LiquityV2WstEthLegacy]: ZERO_ADDRESS,
451
- [LiquityV2Versions.LiquityV2REthLegacy]: ZERO_ADDRESS,
452
- };
453
-
454
- function ceilDiv(a: string, b: string) {
455
- return new Dec(a).add(new Dec(b).sub(1)).div(b).toString();
456
- }
457
- const SP_YIELD_SPLIT = new Dec(75).mul(10 ** 16).toString(); // 75%
458
-
459
- const calcPendingSPYield = (
460
- aggWeightedDebtSum: string,
461
- lastAggUpdateTime: string,
462
- currentTime: string,
463
- ) => {
464
- const a = new Dec(aggWeightedDebtSum).mul(
465
- new Dec(currentTime).sub(new Dec(lastAggUpdateTime)),
466
- ).toString();
467
- const b = new Dec(SECONDS_PER_YEAR).mul(1000).mul(1e18).toString();
468
- return new Dec(ceilDiv(a, b)).mul(SP_YIELD_SPLIT).div(1e18).toString();
469
- };
470
-
471
-
472
- const calculateStabilityPoolApy = (
473
- spYieldGainParams: SPYieldGainParameters,
474
- ) => {
475
- const {
476
- aggWeightedDebtSum, totalBoldDeposits, lastAggUpdateTime, yieldGainsPending,
477
- } = spYieldGainParams;
478
-
479
- if (new Dec(totalBoldDeposits).eq(0)) {
480
- return '0';
481
- }
482
-
483
- const now = Date.now().toString();
484
- const lastAggUpdateTimeScaled = new Dec(lastAggUpdateTime).mul(1000).toString();
485
-
486
- const pendingSPYield = new Dec(calcPendingSPYield(
487
- aggWeightedDebtSum,
488
- lastAggUpdateTimeScaled,
489
- now,
490
- )).add(yieldGainsPending).toString();
491
-
492
- const annualizedYield = new Dec(pendingSPYield).mul(SECONDS_PER_YEAR).mul(1000).div(new Dec(now).minus(lastAggUpdateTimeScaled))
493
- .toString();
494
- return new Dec(annualizedYield).div(totalBoldDeposits).mul(100).toString();
495
- };
496
-
497
- const getYBoldApyApi = async () => {
498
- try {
499
- const url = 'https://ydaemon.yearn.fi/1/vaults/0x23346B04a7f55b8760E5860AA5A77383D63491cD?strategiesDetails=withDetails&strategiesCondition=inQueue';
500
-
501
- const yBoldData = await fetch(url)
502
- .then(res => res.json())
503
- .catch(console.error);
504
-
505
- return new Dec(yBoldData.apr.netAPR).mul(100).toString();
506
- } catch (error) {
507
- console.error('External API Failure: YBold ', error);
508
- return '0';
509
- }
510
- };
511
-
512
- export type sBoldYieldParameters = {
513
- WETH: string;
514
- wsETH: string;
515
- rETH: string;
516
- };
517
-
518
- const calculateSPApy = (
519
- spYieldGainParams: sBoldYieldParameters, spAPYs: { apyEth: Dec.Value; apyWstEth: Dec.Value; apyREth: Dec.Value; },
520
- ) => {
521
- const {
522
- WETH, wsETH, rETH,
523
- } = spYieldGainParams;
524
-
525
- const apy = new Dec(WETH).mul(spAPYs.apyEth).add(new Dec(wsETH).mul(spAPYs.apyWstEth)).add(new Dec(rETH).mul(spAPYs.apyREth))
526
- .toString();
527
- return apy;
528
- };
529
-
530
- export const getLiquityV2Staking = async (provider: Client, network: NetworkNumber, market: LiquityV2Versions, user: EthAddress) => {
531
- const stabilityPoolView = createViemContractFromConfigFunc('LiquityV2StabilityPool', stabilityPoolAddrForMarket[market])(provider, network);
532
- const activePoolView = createViemContractFromConfigFunc('LiquityV2ActivePool', activePoolAddrForMarket[market])(provider, network);
533
-
534
- const debtTokenInfo = getAssetInfo(LiquityV2Markets(network)[market].debtToken, network);
535
- const debtTokenContract = createViemContractFromConfigFunc('Erc20', debtTokenInfo.address as HexString)(provider, network);
536
-
537
- const [
538
- stabilityRewardColl,
539
- stabilityRewardYield,
540
- compoundedBoldDeposit,
541
- totalBoldDeposits,
542
- P,
543
- currentScale,
544
- yieldGainsPending,
545
- debtTokenBalance,
546
-
547
- aggWeightedDebtSum,
548
- lastAggUpdateTime,
549
- ] = await Promise.all([
550
- stabilityPoolView.read.getDepositorCollGain([user]),
551
- stabilityPoolView.read.getDepositorYieldGain([user]),
552
- stabilityPoolView.read.getCompoundedBoldDeposit([user]),
553
- stabilityPoolView.read.getTotalBoldDeposits(),
554
- stabilityPoolView.read.P(),
555
- stabilityPoolView.read.currentScale(),
556
- stabilityPoolView.read.getYieldGainsPending(),
557
- debtTokenContract.read.balanceOf([user]),
558
-
559
- activePoolView.read.aggWeightedDebtSum(),
560
- activePoolView.read.lastAggUpdateTime(),
561
- ]);
562
-
563
- const stabilityPoolYieldParams: SPYieldGainParameters = {
564
- aggWeightedDebtSum: aggWeightedDebtSum.toString(),
565
- lastAggUpdateTime: lastAggUpdateTime.toString(),
566
- P: P.toString(),
567
- currentScale: currentScale.toString(),
568
- yieldGainsPending: yieldGainsPending.toString(),
569
- totalBoldDeposits: totalBoldDeposits.toString(),
570
- };
571
-
572
- const stabilityPoolApy = calculateStabilityPoolApy(stabilityPoolYieldParams);
573
-
574
- const stakedBOLDBalanceForUser = getEthAmountForDecimals(compoundedBoldDeposit.toString(), 18);
575
- const stabilityRewardCollForUser = getEthAmountForDecimals(stabilityRewardColl.toString(), 18);
576
- const stabilityRewardYieldForUser = getEthAmountForDecimals(stabilityRewardYield.toString(), 18);
577
-
578
- return {
579
- totalBOLDDeposited: getEthAmountForDecimals(totalBoldDeposits.toString(), 18),
580
- stakedBOLDBalance: stakedBOLDBalanceForUser,
581
- stabilityRewardColl: stabilityRewardCollForUser,
582
- stabilityRewardYield: stabilityRewardYieldForUser,
583
- showStakingBalances: !!(+stakedBOLDBalanceForUser || +stabilityRewardCollForUser || +stabilityRewardYieldForUser),
584
- debtTokenBalance: getEthAmountForDecimals(debtTokenBalance.toString(), debtTokenInfo.decimals),
585
- stabilityPoolApy,
586
- };
587
- };
588
-
589
- export const getLiquitySAndYBold = async (provider: Client, network: NetworkNumber, markets: any, user: EthAddress) => {
590
- const sBold = LiquityV2sBoldVaultViem(provider, network);
591
- const yBold = createViemContractFromConfigFunc('Erc4626', '0x9F4330700a36B29952869fac9b33f45EEdd8A3d8')(provider, network);
592
- const stYBold = createViemContractFromConfigFunc('Erc4626', '0x23346B04a7f55b8760E5860AA5A77383D63491cD')(provider, network);
593
- const spAPYs = {
594
- apyEth: markets[LiquityV2Versions.LiquityV2Eth].data.stabilityPoolApy,
595
- apyWstEth: markets[LiquityV2Versions.LiquityV2WstEth].data.stabilityPoolApy,
596
- apyREth: markets[LiquityV2Versions.LiquityV2REth].data.stabilityPoolApy,
597
- };
598
-
599
- const [
600
- sBoldTotalAssets,
601
- sBoldConvertToShares,
602
- sBoldMaxWithdraw,
603
-
604
- wethApy,
605
- wsETHApy,
606
- rETHApy,
607
-
608
- yBoldTotalAssets,
609
- yBoldMaxWithdraw,
610
- stYBoldConvertToShares,
611
-
612
- yBoldApy,
613
-
614
- sBoldBalance,
615
- yBoldBalance,
616
- stYBoldBalance,
617
- ] = await Promise.all([
618
- sBold.read.totalAssets(),
619
- sBold.read.convertToShares([BigInt(1e18)]),
620
- sBold.read.maxWithdraw([user]),
621
-
622
- sBold.read.sps([BigInt(0)]),
623
- sBold.read.sps([BigInt(1)]),
624
- sBold.read.sps([BigInt(2)]),
625
-
626
- yBold.read.totalAssets(),
627
- yBold.read.maxWithdraw([user]),
628
- stYBold.read.convertToShares([BigInt(1e18)]),
629
- getYBoldApyApi(),
630
-
631
- sBold.read.balanceOf([user]),
632
- yBold.read.balanceOf([user]),
633
- stYBold.read.balanceOf([user]),
634
- ]);
635
-
636
- const spMarketRes = {
637
- WETH: new Dec(wethApy[1]).div(10000).toString(),
638
- wsETH: new Dec(wsETHApy[1]).div(10000).toString(),
639
- rETH: new Dec(rETHApy[1]).div(10000).toString(),
640
- };
641
-
642
- const spApy = calculateSPApy(spMarketRes, spAPYs);
643
-
644
- return {
645
- spApy,
646
- yBoldApy,
647
- totalBoldDepositedSBold: assetAmountInEth(sBoldTotalAssets.toString(), 'sBOLD'),
648
- boldRateSBold: assetAmountInEth(sBoldConvertToShares.toString(), 'sBOLD'),
649
- maxWithdrawSBold: assetAmountInEth(sBoldMaxWithdraw.toString(), 'sBOLD'),
650
- totalBoldDepositedYBold: assetAmountInEth(yBoldTotalAssets.toString(), 'yBOLD'),
651
- boldRateYBold: assetAmountInEth(stYBoldConvertToShares.toString(), 'yBOLD'),
652
- maxWithdrawYBold: assetAmountInEth(yBoldMaxWithdraw.toString(), 'yBOLD'),
653
-
654
- sBoldBalance: assetAmountInEth(sBoldBalance.toString(), 'sBOLD'),
655
- yBoldBalance: assetAmountInEth(yBoldBalance.toString(), 'yBOLD'),
656
- stYBoldBalance: assetAmountInEth(stYBoldBalance.toString(), 'yBOLD'),
657
- };
1
+ import Dec from 'decimal.js';
2
+ import { assetAmountInEth, getAssetInfo } from '@defisaver/tokens';
3
+ import { Client, PublicClient } from 'viem';
4
+ import {
5
+ createViemContractFromConfigFunc,
6
+ LiquityV2LegacyViewContractViem,
7
+ LiquityV2sBoldVaultViem,
8
+ LiquityV2ViewContractViem,
9
+ } from '../contracts';
10
+ import {
11
+ EthAddress, EthereumProvider, IncentiveKind, NetworkNumber, HexString,
12
+ } from '../types/common';
13
+ import {
14
+ LIQUITY_V2_TROVE_STATUS_ENUM,
15
+ LiquityV2AssetsData, LiquityV2MarketData, LiquityV2MarketInfo, LiquityV2TroveData, LiquityV2UsedAssets,
16
+ LiquityV2Versions,
17
+ } from '../types';
18
+ import { getStakingApy, STAKING_ASSETS } from '../staking';
19
+ import { getLiquityV2AggregatedPositionData } from '../helpers/liquityV2Helpers';
20
+ import {
21
+ compareAddresses,
22
+ ethToWeth,
23
+ getEthAmountForDecimals,
24
+ MAXUINT,
25
+ } from '../services/utils';
26
+ import { SECONDS_PER_YEAR, ZERO_ADDRESS } from '../constants';
27
+ import { LiquityV2Markets } from '../markets';
28
+ import { getViemProvider } from '../services/viem';
29
+
30
+ export type SPYieldGainParameters = {
31
+ P: string;
32
+ aggWeightedDebtSum: string;
33
+ currentScale: string;
34
+ lastAggUpdateTime: string;
35
+ totalBoldDeposits: string;
36
+ yieldGainsPending: string;
37
+ };
38
+
39
+ const getLiquityV2ViewContract = (provider: Client, network: NetworkNumber, isLegacy: boolean) => {
40
+ if (isLegacy) return LiquityV2LegacyViewContractViem(provider, network);
41
+ return LiquityV2ViewContractViem(provider, network);
42
+ };
43
+
44
+
45
+ export const _getLiquityV2MarketData = async (provider: Client, network: NetworkNumber, selectedMarket: LiquityV2MarketInfo): Promise<LiquityV2MarketData> => {
46
+ const {
47
+ marketAddress, debtToken, collateralToken, isLegacy,
48
+ } = selectedMarket;
49
+ const viewContract = getLiquityV2ViewContract(provider, network, isLegacy);
50
+ const data = await viewContract.read.getMarketData([marketAddress]);
51
+ const hintHelperAddress = data.hintHelpers;
52
+ const troveNFTAddress = data.troveNFT;
53
+ const borrowerOperationsAddress = data.borrowerOperations;
54
+ const troveManagerAddress = data.troveManager;
55
+ const stabilityPoolAddress = data.stabilityPool;
56
+ const collSurplusPoolAddress = data.collSurplusPool;
57
+ const activePoolAddress = data.activePool;
58
+
59
+ const minCollRatio = new Dec(data.MCR).div(1e16).toString();
60
+ const criticalCollRatio = new Dec(data.CCR).div(1e18).toString();
61
+ // @ts-ignore
62
+ const batchCollRatio = new Dec(data.BCR ?? '0').div(1e16).toString();
63
+
64
+ const totalMarketBorrow = assetAmountInEth(data.entireSystemDebt.toString());
65
+ const totalMarketSupply = assetAmountInEth(data.entireSystemColl.toString());
66
+ const collPrice = assetAmountInEth(data.collPrice.toString());
67
+
68
+ const totalCollRatio = new Dec(totalMarketSupply).mul(collPrice).div(totalMarketBorrow).toString();
69
+ const leftToBorrowGlobal = new Dec(totalMarketSupply).mul(collPrice).div(criticalCollRatio).sub(totalMarketBorrow)
70
+ .toString();
71
+ const minCollAmountForCurrentBorrow = new Dec(totalMarketBorrow).mul(criticalCollRatio).div(collPrice).toString();
72
+ const leftToWithdrawGlobal = new Dec(totalMarketSupply).sub(minCollAmountForCurrentBorrow).toString();
73
+
74
+ const assetsData: LiquityV2AssetsData = {};
75
+ assetsData[debtToken] = {
76
+ symbol: debtToken,
77
+ address: getAssetInfo(debtToken, network).address,
78
+ price: '1',
79
+ totalSupply: '0',
80
+ totalBorrow: totalMarketBorrow,
81
+ canBeSupplied: false,
82
+ canBeBorrowed: true,
83
+ leftToBorrowGlobal,
84
+ leftToWithdrawGlobal: '0',
85
+ supplyIncentives: [],
86
+ borrowIncentives: [],
87
+ };
88
+ assetsData[collateralToken] = {
89
+ symbol: collateralToken,
90
+ address: getAssetInfo(ethToWeth(collateralToken), network).address,
91
+ price: collPrice,
92
+ totalSupply: totalMarketSupply,
93
+ totalBorrow: '0',
94
+ canBeSupplied: true,
95
+ canBeBorrowed: false,
96
+ leftToBorrowGlobal: '0',
97
+ leftToWithdrawGlobal,
98
+ supplyIncentives: [],
99
+ borrowIncentives: [],
100
+ };
101
+ if (STAKING_ASSETS.includes(collateralToken)) {
102
+ assetsData[collateralToken].supplyIncentives.push({
103
+ apy: await getStakingApy(collateralToken),
104
+ token: collateralToken,
105
+ incentiveKind: IncentiveKind.Staking,
106
+ description: `Native ${collateralToken} yield.`,
107
+ });
108
+ }
109
+
110
+ return {
111
+ assetsData,
112
+ marketData: {
113
+ minCollRatio,
114
+ totalCollRatio: new Dec(totalCollRatio).mul(100).toString(),
115
+ criticalCollRatio: new Dec(criticalCollRatio).mul(100).toString(),
116
+ batchCollRatio,
117
+ isUnderCollateralized: new Dec(totalCollRatio).lt(criticalCollRatio),
118
+ hintHelperAddress,
119
+ troveNFTAddress,
120
+ borrowerOperationsAddress,
121
+ troveManagerAddress,
122
+ stabilityPoolAddress,
123
+ collSurplusPoolAddress,
124
+ activePoolAddress,
125
+ },
126
+ };
127
+ };
128
+
129
+ export const getLiquityV2MarketData = async (
130
+ provider: EthereumProvider,
131
+ network: NetworkNumber,
132
+ selectedMarket: LiquityV2MarketInfo,
133
+ ): Promise<LiquityV2MarketData> => _getLiquityV2MarketData(getViemProvider(provider, network), network, selectedMarket);
134
+
135
+ const getUserTroves = async (
136
+ provider: Client,
137
+ network: NetworkNumber,
138
+ isLegacy: boolean,
139
+ account: EthAddress,
140
+ marketAddress: EthAddress,
141
+ startIndex = 0,
142
+ endIndex = 100,
143
+ troves: { troveId: string, ownedByUser: boolean }[] = [],
144
+ ): Promise<{ troves: { troveId: string, ownedByUser: boolean }[], nextFreeTroveIndex: string }> => {
145
+ const viewContract = getLiquityV2ViewContract(provider, network, isLegacy);
146
+ const result = await viewContract.read.getUserTroves([account, marketAddress, BigInt(startIndex), BigInt(endIndex)]);
147
+ const newStartIndex = endIndex + 1;
148
+ const nextFreeTroveIndex = result[1].toString();
149
+ const existingTroves = [...troves, ...result[0].map((trove: any) => ({ ...trove, troveId: trove.troveId.toString() }))];
150
+ if (nextFreeTroveIndex !== '-1') return { troves: existingTroves.filter((trove) => trove.ownedByUser), nextFreeTroveIndex };
151
+ return getUserTroves(provider, network, isLegacy, account, marketAddress, newStartIndex, newStartIndex + 100, existingTroves);
152
+ };
153
+
154
+ const nftContractCreationBlockMapping = {
155
+ [LiquityV2Versions.LiquityV2Eth]: 22516079,
156
+ [LiquityV2Versions.LiquityV2WstEth]: 22516099,
157
+ [LiquityV2Versions.LiquityV2REth]: 22516118,
158
+ // legacy
159
+ [LiquityV2Versions.LiquityV2EthLegacy]: 21686215,
160
+ [LiquityV2Versions.LiquityV2WstEthLegacy]: 21686238,
161
+ [LiquityV2Versions.LiquityV2REthLegacy]: 21686257,
162
+ };
163
+
164
+ const getTransferredTroves = async (provider: PublicClient, network: NetworkNumber, troveNFTAddress: EthAddress, limitBlocksForEventFetching: boolean, market: LiquityV2Versions, account: EthAddress): Promise<{ troveId: string }[]> => {
165
+ const nftContract = createViemContractFromConfigFunc('LiquityV2TroveNFT', troveNFTAddress)(provider, network);
166
+ const nftContractCreationBlock = nftContractCreationBlockMapping[market];
167
+ const currentBlock = +(await provider.getBlockNumber()).toString();
168
+ const _events = await nftContract.getEvents.Transfer({}, { fromBlock: limitBlocksForEventFetching ? BigInt(currentBlock - 1000) : BigInt(nftContractCreationBlock) });
169
+ const events = _events.map((event) => ({
170
+ from: event.args.from, to: event.args.to, tokenId: event.args.tokenId!.toString(), blockNumber: +(event.blockNumber.toString()),
171
+ }));
172
+ const userTransferredTroves = events.filter((event) => compareAddresses(event.to, account));
173
+
174
+ // check if the last know transfer address is the user
175
+ userTransferredTroves.forEach((event, index) => {
176
+ const otherTransfers = events.filter((e) => event.blockNumber < e.blockNumber && e.tokenId === event.tokenId);
177
+ // @ts-ignore
178
+ userTransferredTroves[index].invalid = !!otherTransfers.length;
179
+ });
180
+ // @ts-ignore
181
+ return userTransferredTroves.filter((event) => !event.invalid).map((event) => ({ troveId: event.tokenId }));
182
+ };
183
+
184
+ export const _getLiquityV2UserTroveIds = async (provider: PublicClient, network: NetworkNumber, selectedMarket: LiquityV2MarketInfo, troveNFTAddress: EthAddress, limitBlocksForEventFetching: boolean, account: EthAddress): Promise<{ troves: { troveId: string }[], nextFreeTroveIndex: string }> => {
185
+ const [{ troves: userTroves, nextFreeTroveIndex }, userTransferredTroves] = await Promise.all([
186
+ getUserTroves(provider, network, selectedMarket.isLegacy, account, selectedMarket.marketAddress),
187
+ getTransferredTroves(provider, network, troveNFTAddress, limitBlocksForEventFetching, selectedMarket.value, account),
188
+ ]);
189
+ const troves = [...userTroves.map(({ troveId }) => ({ troveId })), ...userTransferredTroves];
190
+ const filteredTroves = troves.filter((value, index, self) => index === self.findIndex((t) => (
191
+ t.troveId === value.troveId
192
+ )),
193
+ );
194
+ const troveIds = filteredTroves.map((trove) => trove.troveId);
195
+ const troveIdsSet = new Set(troveIds);
196
+ const troveIdsArray = Array.from(troveIdsSet);
197
+ const trovesNoDuplicates = troveIdsArray.map((troveId) => troves.find((trove) => trove.troveId === troveId)) as { troveId: string }[];
198
+ return { troves: trovesNoDuplicates, nextFreeTroveIndex };
199
+ };
200
+
201
+ export const getLiquityV2UserTroveIds = async (
202
+ provider: EthereumProvider,
203
+ network: NetworkNumber,
204
+ selectedMarket: LiquityV2MarketInfo,
205
+ troveNFTAddress: EthAddress,
206
+ limitBlocksForEventFetching: boolean,
207
+ account: EthAddress,
208
+ ): Promise<{ troves: { troveId: string }[], nextFreeTroveIndex: string }> => _getLiquityV2UserTroveIds(getViemProvider(provider, network), network, selectedMarket, troveNFTAddress, limitBlocksForEventFetching, account);
209
+
210
+ const getDebtInFrontForSingleMarketLiquityV2 = async (
211
+ provider: Client,
212
+ network: NetworkNumber,
213
+ isLegacy: boolean,
214
+ marketAddress: EthAddress,
215
+ troveId: string,
216
+ accumulatedSum = '0',
217
+ iterations = 2000,
218
+ ): Promise<string> => {
219
+ const viewContract = getLiquityV2ViewContract(provider, network, isLegacy);
220
+ const res = await viewContract.read.getDebtInFront([marketAddress, BigInt(troveId), BigInt(accumulatedSum), BigInt(iterations)]);
221
+ const next = res[0].toString();
222
+ const debt = res[1].toString();
223
+ if (next === '0') return assetAmountInEth(debt);
224
+ return getDebtInFrontForSingleMarketLiquityV2(provider, network, isLegacy, marketAddress, next, debt, iterations);
225
+ };
226
+
227
+ const getDebtInFrontForInterestRateSingleMarketLiquityV2 = async (
228
+ provider: Client,
229
+ network: NetworkNumber,
230
+ isLegacy: boolean,
231
+ marketAddress: EthAddress,
232
+ interestRate: string,
233
+ troveId = '0',
234
+ accumulatedSum = '0',
235
+ iterations = 2000,
236
+ ): Promise<string> => {
237
+ const viewContract = getLiquityV2ViewContract(provider, network, isLegacy);
238
+ if (+interestRate === 0 || !interestRate) return '0';
239
+ const interestRateWei = new Dec(interestRate).times(1e16).toFixed(0).toString();
240
+ const res = await viewContract.read.getDebtInFrontByInterestRate([marketAddress, BigInt(troveId), BigInt(accumulatedSum), BigInt(iterations), BigInt(interestRateWei)]);
241
+ const next = res[0].toString();
242
+ const debt = res[1].toString();
243
+ if (next === '0') return assetAmountInEth(debt);
244
+ return getDebtInFrontForInterestRateSingleMarketLiquityV2(provider, network, isLegacy, marketAddress, interestRate, next, debt, iterations);
245
+ };
246
+
247
+ const getUnbackedDebtForSingleMarket = async (totalBorrowed: string, provider: Client, network: NetworkNumber, stabilityPoolAddress: EthAddress) => {
248
+ const stabilityPoolContract = createViemContractFromConfigFunc('LiquityV2StabilityPool', stabilityPoolAddress)(provider, network);
249
+ const totalBoldDeposits = await stabilityPoolContract.read.getTotalBoldDeposits();
250
+ const totalBoldDepositsInEth = assetAmountInEth(totalBoldDeposits.toString());
251
+
252
+ return Dec.max(new Dec(totalBorrowed).sub(totalBoldDepositsInEth), 0).toString();
253
+ };
254
+
255
+ const getAllMarketsUnbackedDebts = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, isLegacy: boolean, provider: Client, network: NetworkNumber): Promise<Record<LiquityV2Versions, string>> => {
256
+ const allMarketsUnbackedDebt = await Promise.all(Object.entries(markets).map(async ([version, market]) => {
257
+ const { assetsData, marketData } = market;
258
+ const { debtToken, isLegacy: isLegacyMarket } = LiquityV2Markets(network)[version as LiquityV2Versions];
259
+ if (isLegacyMarket !== isLegacy) return [version, '0'];
260
+ const unbackedDebt = await getUnbackedDebtForSingleMarket(assetsData[debtToken].totalBorrow, provider, network, marketData.stabilityPoolAddress);
261
+ return [version, unbackedDebt];
262
+ }));
263
+
264
+ return Object.fromEntries(allMarketsUnbackedDebt) as Record<LiquityV2Versions, string>;
265
+ };
266
+
267
+ const calculateDebtInFrontLiquityV2 = (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, allMarketsUnbackedDebts: Record<LiquityV2Versions, string>, interestRateDebtInFront: string): string => {
268
+ const selectedMarketUnbackedDebt = new Dec(allMarketsUnbackedDebts[selectedMarket]);
269
+ const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
270
+ if (selectedMarketUnbackedDebt.eq(0)) return interestRateDebtInFront;
271
+
272
+ const amountBeingReedemedOnEachMarket = Object.entries(markets).map(([version, market]) => {
273
+ const { isLegacy: isLegacyMarket } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
274
+ if (version === selectedMarket && isLegacyMarket !== isLegacy) return new Dec(interestRateDebtInFront);
275
+ const { assetsData } = market;
276
+ const { debtToken } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
277
+ const unbackedDebt = new Dec(allMarketsUnbackedDebts[version as LiquityV2Versions]);
278
+ const totalBorrow = new Dec(assetsData[debtToken].totalBorrow);
279
+ const amountToReedem = new Dec(interestRateDebtInFront).mul(unbackedDebt).div(selectedMarketUnbackedDebt);
280
+ return Dec.min(amountToReedem, totalBorrow);
281
+ });
282
+
283
+ return amountBeingReedemedOnEachMarket.reduce((acc, val) => acc.plus(val), new Dec(0)).toString();
284
+ };
285
+
286
+ const getDebtInFrontLiquityV2 = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, viewContract: any, troveId: string) => {
287
+ const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
288
+ const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(markets, isLegacy, provider, network);
289
+ const interestRateDebtInFront = await getDebtInFrontForSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, troveId);
290
+
291
+ return calculateDebtInFrontLiquityV2(markets, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
292
+ };
293
+
294
+ /**
295
+ * @param markets
296
+ * @param selectedMarket
297
+ * @param provider
298
+ * @param network
299
+ * @param viewContract
300
+ * @param interestRate
301
+ * @param debtInFrontBeingMoved - amound of debt being repositioned if interest rate is being increased (prevents including it as debt in front)
302
+ */
303
+ const _getDebtInFrontForInterestRateLiquityV2 = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, isLegacy: boolean, interestRate: string, debtInFrontBeingMoved: string = '0') => {
304
+ const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(markets, isLegacy, provider, network);
305
+ const interestRateDebtInFront = new Dec(await getDebtInFrontForInterestRateSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, interestRate))
306
+ .sub(debtInFrontBeingMoved);
307
+
308
+ return calculateDebtInFrontLiquityV2(markets, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
309
+ };
310
+
311
+ export const getDebtInFrontForInterestRateLiquityV2 = async (
312
+ markets: Record<LiquityV2Versions, LiquityV2MarketData>,
313
+ selectedMarket: LiquityV2Versions,
314
+ provider: EthereumProvider,
315
+ network: NetworkNumber,
316
+ isLegacy: boolean,
317
+ interestRate: string,
318
+ debtInFrontBeingMoved: string = '0',
319
+ ) => _getDebtInFrontForInterestRateLiquityV2(markets, selectedMarket, getViemProvider(provider, network), network, isLegacy, interestRate, debtInFrontBeingMoved);
320
+
321
+ export const _getLiquityV2TroveData = async (
322
+ provider: Client,
323
+ network: NetworkNumber,
324
+ {
325
+ selectedMarket,
326
+ assetsData,
327
+ troveId,
328
+ allMarketsData,
329
+ }:
330
+ {
331
+ selectedMarket: LiquityV2MarketInfo,
332
+ assetsData: LiquityV2AssetsData,
333
+ troveId: string,
334
+ allMarketsData: Record<LiquityV2Versions, LiquityV2MarketData>,
335
+ },
336
+ fetchDebtInFront: boolean = true,
337
+ ): Promise<LiquityV2TroveData> => {
338
+ const viewContract = getLiquityV2ViewContract(provider, network, selectedMarket.isLegacy);
339
+ const { minCollRatio, batchCollRatio } = allMarketsData[selectedMarket.value].marketData;
340
+ const { collateralToken, marketAddress, debtToken } = selectedMarket;
341
+ const [_data, debtInFront] = await Promise.all([
342
+ viewContract.read.getTroveInfo([marketAddress, BigInt(troveId)]),
343
+ fetchDebtInFront ? getDebtInFrontLiquityV2(allMarketsData, selectedMarket.value, provider, network, selectedMarket.isLegacy, troveId) : Promise.resolve('0'),
344
+ ]);
345
+ const data = {
346
+ ..._data,
347
+ TCRatio: _data.TCRatio.toString() === MAXUINT ? '0' : _data.TCRatio.toString(), // mistake on contract side when debt is 0
348
+ };
349
+ const usedAssets: LiquityV2UsedAssets = {};
350
+
351
+ const debtAssetData = assetsData[debtToken];
352
+ const borrowed = assetAmountInEth(data.debtAmount.toString());
353
+ usedAssets[debtToken] = {
354
+ symbol: debtToken,
355
+ supplied: '0',
356
+ suppliedUsd: '0',
357
+ borrowed,
358
+ borrowedUsd: new Dec(borrowed).mul(debtAssetData.price).toString(),
359
+ isBorrowed: true,
360
+ isSupplied: false,
361
+ };
362
+
363
+ const collAssetData = assetsData[collateralToken];
364
+ const suppliedColl = assetAmountInEth(data.collAmount.toString());
365
+ usedAssets[collateralToken] = {
366
+ symbol: collateralToken,
367
+ supplied: suppliedColl,
368
+ suppliedUsd: new Dec(suppliedColl).mul(collAssetData.price).toString(),
369
+ borrowed: '0',
370
+ borrowedUsd: '0',
371
+ isBorrowed: false,
372
+ isSupplied: true,
373
+ collateral: true,
374
+ };
375
+
376
+ const collRatio = new Dec(data.TCRatio).div(1e16).toString();
377
+ const interestRate = new Dec(data.annualInterestRate).div(1e16).toString();
378
+ const interestBatchManager = data.interestBatchManager;
379
+ const lastInterestRateAdjTime = data.lastInterestRateAdjTime.toString();
380
+
381
+ const hasInterestBatchManager = !compareAddresses(interestBatchManager, ZERO_ADDRESS);
382
+ const liqRatio = hasInterestBatchManager ? new Dec(minCollRatio).add(batchCollRatio).toString() : minCollRatio;
383
+
384
+ const payload: LiquityV2TroveData = {
385
+ usedAssets,
386
+ troveId,
387
+ interestRate,
388
+ interestBatchManager,
389
+ debtInFront,
390
+ lastInterestRateAdjTime,
391
+ liqRatio,
392
+ troveStatus: LIQUITY_V2_TROVE_STATUS_ENUM[parseInt(data.status.toString(), 10)],
393
+ ...getLiquityV2AggregatedPositionData({
394
+ usedAssets, assetsData, minCollRatio: liqRatio, interestRate,
395
+ }),
396
+ collRatio,
397
+ };
398
+
399
+ return payload;
400
+ };
401
+
402
+ export const getLiquityV2TroveData = async (
403
+ provider: EthereumProvider,
404
+ network: NetworkNumber,
405
+ {
406
+ selectedMarket,
407
+ assetsData,
408
+ troveId,
409
+ allMarketsData,
410
+ }:
411
+ {
412
+ selectedMarket: LiquityV2MarketInfo,
413
+ assetsData: LiquityV2AssetsData,
414
+ troveId: string,
415
+ allMarketsData: Record<LiquityV2Versions, LiquityV2MarketData>,
416
+ },
417
+ fetchDebtInFront: boolean = true,
418
+ ): Promise<LiquityV2TroveData> => _getLiquityV2TroveData(
419
+ getViemProvider(provider, network),
420
+ network,
421
+ {
422
+ selectedMarket,
423
+ assetsData,
424
+ troveId,
425
+ allMarketsData,
426
+ },
427
+ fetchDebtInFront,
428
+ );
429
+
430
+ export const getLiquityV2ClaimableCollateral = async (collSurplusPoolAddress: EthAddress, account: EthAddress, provider: EthereumProvider, network: NetworkNumber): Promise<string> => {
431
+ const client = getViemProvider(provider, network);
432
+ const collSurplusPoolContract = createViemContractFromConfigFunc('LiquityV2CollSurplusPool', collSurplusPoolAddress)(client, network);
433
+ const claimableCollateral = await collSurplusPoolContract.read.getCollateral([account]);
434
+ return claimableCollateral.toString();
435
+ };
436
+
437
+ const stabilityPoolAddrForMarket: Record<LiquityV2Versions, EthAddress> = {
438
+ [LiquityV2Versions.LiquityV2Eth]: '0x5721cbbd64fc7Ae3Ef44A0A3F9a790A9264Cf9BF',
439
+ [LiquityV2Versions.LiquityV2WstEth]: '0x9502b7c397e9aa22fe9db7ef7daf21cd2aebe56b',
440
+ [LiquityV2Versions.LiquityV2REth]: '0xd442e41019b7f5c4dd78f50dc03726c446148695',
441
+ [LiquityV2Versions.LiquityV2EthLegacy]: ZERO_ADDRESS,
442
+ [LiquityV2Versions.LiquityV2REthLegacy]: ZERO_ADDRESS,
443
+ [LiquityV2Versions.LiquityV2WstEthLegacy]: ZERO_ADDRESS,
444
+ };
445
+ const activePoolAddrForMarket: Record<LiquityV2Versions, EthAddress> = {
446
+ [LiquityV2Versions.LiquityV2Eth]: '0xeB5A8C825582965f1d84606E078620a84ab16AfE',
447
+ [LiquityV2Versions.LiquityV2WstEth]: '0x531a8f99c70d6a56a7cee02d6b4281650d7919a0',
448
+ [LiquityV2Versions.LiquityV2REth]: '0x9074d72cc82dad1e13e454755aa8f144c479532f',
449
+ [LiquityV2Versions.LiquityV2EthLegacy]: ZERO_ADDRESS,
450
+ [LiquityV2Versions.LiquityV2WstEthLegacy]: ZERO_ADDRESS,
451
+ [LiquityV2Versions.LiquityV2REthLegacy]: ZERO_ADDRESS,
452
+ };
453
+
454
+ function ceilDiv(a: string, b: string) {
455
+ return new Dec(a).add(new Dec(b).sub(1)).div(b).toString();
456
+ }
457
+ const SP_YIELD_SPLIT = new Dec(75).mul(10 ** 16).toString(); // 75%
458
+
459
+ const calcPendingSPYield = (
460
+ aggWeightedDebtSum: string,
461
+ lastAggUpdateTime: string,
462
+ currentTime: string,
463
+ ) => {
464
+ const a = new Dec(aggWeightedDebtSum).mul(
465
+ new Dec(currentTime).sub(new Dec(lastAggUpdateTime)),
466
+ ).toString();
467
+ const b = new Dec(SECONDS_PER_YEAR).mul(1000).mul(1e18).toString();
468
+ return new Dec(ceilDiv(a, b)).mul(SP_YIELD_SPLIT).div(1e18).toString();
469
+ };
470
+
471
+
472
+ const calculateStabilityPoolApy = (
473
+ spYieldGainParams: SPYieldGainParameters,
474
+ ) => {
475
+ const {
476
+ aggWeightedDebtSum, totalBoldDeposits, lastAggUpdateTime, yieldGainsPending,
477
+ } = spYieldGainParams;
478
+
479
+ if (new Dec(totalBoldDeposits).eq(0)) {
480
+ return '0';
481
+ }
482
+
483
+ const now = Date.now().toString();
484
+ const lastAggUpdateTimeScaled = new Dec(lastAggUpdateTime).mul(1000).toString();
485
+
486
+ const pendingSPYield = new Dec(calcPendingSPYield(
487
+ aggWeightedDebtSum,
488
+ lastAggUpdateTimeScaled,
489
+ now,
490
+ )).add(yieldGainsPending).toString();
491
+
492
+ const annualizedYield = new Dec(pendingSPYield).mul(SECONDS_PER_YEAR).mul(1000).div(new Dec(now).minus(lastAggUpdateTimeScaled))
493
+ .toString();
494
+ return new Dec(annualizedYield).div(totalBoldDeposits).mul(100).toString();
495
+ };
496
+
497
+ const getYBoldApyApi = async () => {
498
+ try {
499
+ const url = 'https://ydaemon.yearn.fi/1/vaults/0x23346B04a7f55b8760E5860AA5A77383D63491cD?strategiesDetails=withDetails&strategiesCondition=inQueue';
500
+
501
+ const yBoldData = await fetch(url)
502
+ .then(res => res.json())
503
+ .catch(console.error);
504
+
505
+ return new Dec(yBoldData.apr.netAPR).mul(100).toString();
506
+ } catch (error) {
507
+ console.error('External API Failure: YBold ', error);
508
+ return '0';
509
+ }
510
+ };
511
+
512
+ export type sBoldYieldParameters = {
513
+ WETH: string;
514
+ wsETH: string;
515
+ rETH: string;
516
+ };
517
+
518
+ const calculateSPApy = (
519
+ spYieldGainParams: sBoldYieldParameters, spAPYs: { apyEth: Dec.Value; apyWstEth: Dec.Value; apyREth: Dec.Value; },
520
+ ) => {
521
+ const {
522
+ WETH, wsETH, rETH,
523
+ } = spYieldGainParams;
524
+
525
+ const apy = new Dec(WETH).mul(spAPYs.apyEth).add(new Dec(wsETH).mul(spAPYs.apyWstEth)).add(new Dec(rETH).mul(spAPYs.apyREth))
526
+ .toString();
527
+ return apy;
528
+ };
529
+
530
+ export const getLiquityV2Staking = async (provider: Client, network: NetworkNumber, market: LiquityV2Versions, user: EthAddress) => {
531
+ const stabilityPoolView = createViemContractFromConfigFunc('LiquityV2StabilityPool', stabilityPoolAddrForMarket[market])(provider, network);
532
+ const activePoolView = createViemContractFromConfigFunc('LiquityV2ActivePool', activePoolAddrForMarket[market])(provider, network);
533
+
534
+ const debtTokenInfo = getAssetInfo(LiquityV2Markets(network)[market].debtToken, network);
535
+ const debtTokenContract = createViemContractFromConfigFunc('Erc20', debtTokenInfo.address as HexString)(provider, network);
536
+
537
+ const [
538
+ stabilityRewardColl,
539
+ stabilityRewardYield,
540
+ compoundedBoldDeposit,
541
+ totalBoldDeposits,
542
+ P,
543
+ currentScale,
544
+ yieldGainsPending,
545
+ debtTokenBalance,
546
+
547
+ aggWeightedDebtSum,
548
+ lastAggUpdateTime,
549
+ ] = await Promise.all([
550
+ stabilityPoolView.read.getDepositorCollGain([user]),
551
+ stabilityPoolView.read.getDepositorYieldGain([user]),
552
+ stabilityPoolView.read.getCompoundedBoldDeposit([user]),
553
+ stabilityPoolView.read.getTotalBoldDeposits(),
554
+ stabilityPoolView.read.P(),
555
+ stabilityPoolView.read.currentScale(),
556
+ stabilityPoolView.read.getYieldGainsPending(),
557
+ debtTokenContract.read.balanceOf([user]),
558
+
559
+ activePoolView.read.aggWeightedDebtSum(),
560
+ activePoolView.read.lastAggUpdateTime(),
561
+ ]);
562
+
563
+ const stabilityPoolYieldParams: SPYieldGainParameters = {
564
+ aggWeightedDebtSum: aggWeightedDebtSum.toString(),
565
+ lastAggUpdateTime: lastAggUpdateTime.toString(),
566
+ P: P.toString(),
567
+ currentScale: currentScale.toString(),
568
+ yieldGainsPending: yieldGainsPending.toString(),
569
+ totalBoldDeposits: totalBoldDeposits.toString(),
570
+ };
571
+
572
+ const stabilityPoolApy = calculateStabilityPoolApy(stabilityPoolYieldParams);
573
+
574
+ const stakedBOLDBalanceForUser = getEthAmountForDecimals(compoundedBoldDeposit.toString(), 18);
575
+ const stabilityRewardCollForUser = getEthAmountForDecimals(stabilityRewardColl.toString(), 18);
576
+ const stabilityRewardYieldForUser = getEthAmountForDecimals(stabilityRewardYield.toString(), 18);
577
+
578
+ return {
579
+ totalBOLDDeposited: getEthAmountForDecimals(totalBoldDeposits.toString(), 18),
580
+ stakedBOLDBalance: stakedBOLDBalanceForUser,
581
+ stabilityRewardColl: stabilityRewardCollForUser,
582
+ stabilityRewardYield: stabilityRewardYieldForUser,
583
+ showStakingBalances: !!(+stakedBOLDBalanceForUser || +stabilityRewardCollForUser || +stabilityRewardYieldForUser),
584
+ debtTokenBalance: getEthAmountForDecimals(debtTokenBalance.toString(), debtTokenInfo.decimals),
585
+ stabilityPoolApy,
586
+ };
587
+ };
588
+
589
+ export const getLiquitySAndYBold = async (provider: Client, network: NetworkNumber, markets: any, user: EthAddress) => {
590
+ const sBold = LiquityV2sBoldVaultViem(provider, network);
591
+ const yBold = createViemContractFromConfigFunc('Erc4626', '0x9F4330700a36B29952869fac9b33f45EEdd8A3d8')(provider, network);
592
+ const stYBold = createViemContractFromConfigFunc('Erc4626', '0x23346B04a7f55b8760E5860AA5A77383D63491cD')(provider, network);
593
+ const spAPYs = {
594
+ apyEth: markets[LiquityV2Versions.LiquityV2Eth].data.stabilityPoolApy,
595
+ apyWstEth: markets[LiquityV2Versions.LiquityV2WstEth].data.stabilityPoolApy,
596
+ apyREth: markets[LiquityV2Versions.LiquityV2REth].data.stabilityPoolApy,
597
+ };
598
+
599
+ const [
600
+ sBoldTotalAssets,
601
+ sBoldConvertToShares,
602
+ sBoldMaxWithdraw,
603
+
604
+ wethApy,
605
+ wsETHApy,
606
+ rETHApy,
607
+
608
+ yBoldTotalAssets,
609
+ yBoldMaxWithdraw,
610
+ stYBoldConvertToShares,
611
+
612
+ yBoldApy,
613
+
614
+ sBoldBalance,
615
+ yBoldBalance,
616
+ stYBoldBalance,
617
+ ] = await Promise.all([
618
+ sBold.read.totalAssets(),
619
+ sBold.read.convertToShares([BigInt(1e18)]),
620
+ sBold.read.maxWithdraw([user]),
621
+
622
+ sBold.read.sps([BigInt(0)]),
623
+ sBold.read.sps([BigInt(1)]),
624
+ sBold.read.sps([BigInt(2)]),
625
+
626
+ yBold.read.totalAssets(),
627
+ yBold.read.maxWithdraw([user]),
628
+ stYBold.read.convertToShares([BigInt(1e18)]),
629
+ getYBoldApyApi(),
630
+
631
+ sBold.read.balanceOf([user]),
632
+ yBold.read.balanceOf([user]),
633
+ stYBold.read.balanceOf([user]),
634
+ ]);
635
+
636
+ const spMarketRes = {
637
+ WETH: new Dec(wethApy[1]).div(10000).toString(),
638
+ wsETH: new Dec(wsETHApy[1]).div(10000).toString(),
639
+ rETH: new Dec(rETHApy[1]).div(10000).toString(),
640
+ };
641
+
642
+ const spApy = calculateSPApy(spMarketRes, spAPYs);
643
+
644
+ return {
645
+ spApy,
646
+ yBoldApy,
647
+ totalBoldDepositedSBold: assetAmountInEth(sBoldTotalAssets.toString(), 'sBOLD'),
648
+ boldRateSBold: assetAmountInEth(sBoldConvertToShares.toString(), 'sBOLD'),
649
+ maxWithdrawSBold: assetAmountInEth(sBoldMaxWithdraw.toString(), 'sBOLD'),
650
+ totalBoldDepositedYBold: assetAmountInEth(yBoldTotalAssets.toString(), 'yBOLD'),
651
+ boldRateYBold: assetAmountInEth(stYBoldConvertToShares.toString(), 'yBOLD'),
652
+ maxWithdrawYBold: assetAmountInEth(yBoldMaxWithdraw.toString(), 'yBOLD'),
653
+
654
+ sBoldBalance: assetAmountInEth(sBoldBalance.toString(), 'sBOLD'),
655
+ yBoldBalance: assetAmountInEth(yBoldBalance.toString(), 'yBOLD'),
656
+ stYBoldBalance: assetAmountInEth(stYBoldBalance.toString(), 'yBOLD'),
657
+ };
658
658
  };