@defisaver/positions-sdk 2.1.30 → 2.1.31

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 (106) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/README.md +64 -64
  4. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  5. package/cjs/markets/aave/marketAssets.js +2 -2
  6. package/cjs/savings/morphoVaults/index.js +17 -17
  7. package/cjs/staking/staking.js +3 -1
  8. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  9. package/esm/markets/aave/marketAssets.js +2 -2
  10. package/esm/savings/morphoVaults/index.js +17 -17
  11. package/esm/staking/staking.js +3 -1
  12. package/package.json +48 -48
  13. package/src/aaveV2/index.ts +240 -240
  14. package/src/aaveV3/index.ts +614 -614
  15. package/src/aaveV3/merit.ts +97 -97
  16. package/src/aaveV3/merkl.ts +74 -74
  17. package/src/claiming/aaveV3.ts +154 -154
  18. package/src/claiming/compV3.ts +22 -22
  19. package/src/claiming/ethena.ts +61 -61
  20. package/src/claiming/index.ts +12 -12
  21. package/src/claiming/king.ts +66 -66
  22. package/src/claiming/morphoBlue.ts +118 -118
  23. package/src/claiming/spark.ts +225 -225
  24. package/src/compoundV2/index.ts +244 -244
  25. package/src/compoundV3/index.ts +274 -274
  26. package/src/config/contracts.ts +1284 -1284
  27. package/src/constants/index.ts +10 -10
  28. package/src/contracts.ts +160 -160
  29. package/src/curveUsd/index.ts +254 -254
  30. package/src/eulerV2/index.ts +324 -324
  31. package/src/exchange/index.ts +25 -25
  32. package/src/fluid/index.ts +1800 -1800
  33. package/src/helpers/aaveHelpers/index.ts +187 -187
  34. package/src/helpers/compoundHelpers/index.ts +283 -283
  35. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  36. package/src/helpers/eulerHelpers/index.ts +222 -222
  37. package/src/helpers/fluidHelpers/index.ts +326 -326
  38. package/src/helpers/index.ts +10 -10
  39. package/src/helpers/liquityV2Helpers/index.ts +82 -82
  40. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  41. package/src/helpers/makerHelpers/index.ts +52 -52
  42. package/src/helpers/morphoBlueHelpers/index.ts +396 -396
  43. package/src/helpers/sparkHelpers/index.ts +158 -158
  44. package/src/index.ts +49 -49
  45. package/src/liquity/index.ts +159 -159
  46. package/src/liquityV2/index.ts +703 -703
  47. package/src/llamaLend/index.ts +305 -305
  48. package/src/maker/index.ts +223 -223
  49. package/src/markets/aave/index.ts +118 -118
  50. package/src/markets/aave/marketAssets.ts +54 -54
  51. package/src/markets/compound/index.ts +243 -243
  52. package/src/markets/compound/marketsAssets.ts +97 -97
  53. package/src/markets/curveUsd/index.ts +69 -69
  54. package/src/markets/euler/index.ts +26 -26
  55. package/src/markets/fluid/index.ts +2900 -2900
  56. package/src/markets/index.ts +25 -25
  57. package/src/markets/liquityV2/index.ts +102 -102
  58. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  59. package/src/markets/llamaLend/index.ts +235 -235
  60. package/src/markets/morphoBlue/index.ts +971 -971
  61. package/src/markets/spark/index.ts +29 -29
  62. package/src/markets/spark/marketAssets.ts +12 -12
  63. package/src/moneymarket/moneymarketCommonService.ts +85 -85
  64. package/src/morphoBlue/index.ts +274 -274
  65. package/src/portfolio/index.ts +598 -598
  66. package/src/savings/index.ts +55 -55
  67. package/src/savings/makerDsr/index.ts +53 -53
  68. package/src/savings/makerDsr/options.ts +9 -9
  69. package/src/savings/morphoVaults/index.ts +80 -80
  70. package/src/savings/morphoVaults/options.ts +203 -203
  71. package/src/savings/sparkSavingsVaults/index.ts +60 -60
  72. package/src/savings/sparkSavingsVaults/options.ts +35 -35
  73. package/src/savings/yearnVaults/index.ts +73 -73
  74. package/src/savings/yearnVaults/options.ts +32 -32
  75. package/src/services/priceService.ts +278 -278
  76. package/src/services/utils.ts +115 -115
  77. package/src/services/viem.ts +34 -34
  78. package/src/setup.ts +8 -8
  79. package/src/spark/index.ts +456 -456
  80. package/src/staking/eligibility.ts +53 -53
  81. package/src/staking/index.ts +1 -1
  82. package/src/staking/staking.ts +187 -186
  83. package/src/types/aave.ts +196 -196
  84. package/src/types/claiming.ts +114 -114
  85. package/src/types/common.ts +107 -107
  86. package/src/types/compound.ts +144 -144
  87. package/src/types/curveUsd.ts +123 -123
  88. package/src/types/euler.ts +175 -175
  89. package/src/types/fluid.ts +483 -483
  90. package/src/types/index.ts +14 -14
  91. package/src/types/liquity.ts +30 -30
  92. package/src/types/liquityV2.ts +126 -126
  93. package/src/types/llamaLend.ts +159 -159
  94. package/src/types/maker.ts +63 -63
  95. package/src/types/merit.ts +1 -1
  96. package/src/types/merkl.ts +70 -70
  97. package/src/types/morphoBlue.ts +200 -200
  98. package/src/types/portfolio.ts +60 -60
  99. package/src/types/savings/index.ts +19 -19
  100. package/src/types/savings/makerDsr.ts +13 -13
  101. package/src/types/savings/morphoVaults.ts +33 -33
  102. package/src/types/savings/sparkSavingsVaults.ts +15 -15
  103. package/src/types/savings/yearnVaults.ts +14 -14
  104. package/src/types/spark.ts +133 -133
  105. package/src/umbrella/index.ts +69 -69
  106. package/src/umbrella/umbrellaUtils.ts +29 -29
@@ -1,704 +1,704 @@
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
- export const calculateDebtInFrontLiquityV2 = (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, allMarketsUnbackedDebts: Record<LiquityV2Versions, string>, interestRateDebtInFront: string): string => {
268
- // Sanity check to avoid division by 0. Very unlikely to ever happen.
269
- const selectedMarketTotalBorrow = new Dec(markets[selectedMarket].assetsData[LiquityV2Markets(NetworkNumber.Eth)[selectedMarket].debtToken].totalBorrow);
270
- if (selectedMarketTotalBorrow.eq(0)) return new Dec(0).toString();
271
-
272
- const selectedMarketUnbackedDebt = new Dec(allMarketsUnbackedDebts[selectedMarket]);
273
- const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
274
- const totalUnbackedDebt = Object.values(allMarketsUnbackedDebts).reduce((acc, val) => acc.plus(new Dec(val)), new Dec(0));
275
-
276
- // When totalUnbackedDebt is 0, redemptions will be proportional with the branch size and not to unbacked debt.
277
- // When unbacked debt is 0 for branch, next redemption call won't touch that branch, so in order to estimate total debt in front we will:
278
- // - First add up all the unbacked debt from other branches, as that will be the only debt that will be redeemed on the fist redemption call
279
- // - Perform split the same way as we would do when totalUnbackedDebt == 0, this would represent the second call to the redemption function
280
- if (selectedMarketUnbackedDebt.eq(0)) {
281
- // Special case if the branch debt in front is 0, it means that all debt in front is unbacked debt from other branches.
282
- if (new Dec(interestRateDebtInFront).eq(0)) return totalUnbackedDebt.toString();
283
-
284
- // Then calculate how much of that estimated amount would go to each branch
285
- // Second redemption call - calculate proportional redemption based on updated total debt
286
- const amountBeingRedeemedOnEachMarketByTotalBorrow = Object.entries(markets).map(([version, market]) => {
287
- const { isLegacy: isLegacyMarket } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
288
- if (version === selectedMarket && isLegacyMarket !== isLegacy) return new Dec(interestRateDebtInFront);
289
- const { assetsData } = market;
290
- const { debtToken } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
291
- // For other markets, subtract their unbacked debt as it will be cleared in first redemption call
292
- const marketUnbackedDebt = new Dec(allMarketsUnbackedDebts[version as LiquityV2Versions]);
293
- const totalBorrow = new Dec(assetsData[debtToken].totalBorrow).sub(marketUnbackedDebt);
294
- const amountToRedeem = new Dec(interestRateDebtInFront).mul(totalBorrow).div(selectedMarketTotalBorrow);
295
- return Dec.min(amountToRedeem, totalBorrow);
296
- });
297
-
298
- const redemptionAmount = amountBeingRedeemedOnEachMarketByTotalBorrow.reduce((acc, val) => acc.plus(val), new Dec(0));
299
- return totalUnbackedDebt.plus(redemptionAmount).toString();
300
- }
301
-
302
- const amountBeingRedeemedOnEachMarketByUnbackedDebt = Object.entries(markets).map(([version, market]) => {
303
- const { isLegacy: isLegacyMarket } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
304
- if (version === selectedMarket && isLegacyMarket !== isLegacy) return new Dec(interestRateDebtInFront);
305
- const { assetsData } = market;
306
- const { debtToken } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
307
- const unbackedDebt = new Dec(allMarketsUnbackedDebts[version as LiquityV2Versions]);
308
- const totalBorrow = new Dec(assetsData[debtToken].totalBorrow);
309
- const amountToRedeem = new Dec(interestRateDebtInFront).mul(unbackedDebt).div(selectedMarketUnbackedDebt);
310
- return Dec.min(amountToRedeem, totalBorrow);
311
- });
312
-
313
- return amountBeingRedeemedOnEachMarketByUnbackedDebt.reduce((acc, val) => acc.plus(val), new Dec(0)).toString();
314
- };
315
-
316
- // @dev The amount redeemed on each branch depends on the unbacked debt of every branch (the difference between total borrow and stability pool deposits).
317
- // When new debt is generated on the selected market, the unbacked debt will increase, resulting in a higher redemption amount on that branch.
318
- // This function accepts the new debt that's about to be generated (e.g., trove creation) and estimates the debt in front based on the new state.
319
- export const getDebtInFrontForInterestRateIncludingNewDebtLiquityV2 = async (newDebt: string, markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, interestRate: string) => {
320
- const marketsWithNewDebt = structuredClone(markets);
321
- const selectedMarketDebtToken = LiquityV2Markets(network)[selectedMarket].debtToken;
322
- const currentTotalBorrow = new Dec(marketsWithNewDebt[selectedMarket].assetsData[selectedMarketDebtToken].totalBorrow);
323
- marketsWithNewDebt[selectedMarket].assetsData[selectedMarketDebtToken].totalBorrow = currentTotalBorrow.add(newDebt).toString();
324
-
325
- const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
326
- const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(marketsWithNewDebt, isLegacy, provider, network);
327
- const interestRateDebtInFront = new Dec(await getDebtInFrontForInterestRateSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, interestRate));
328
-
329
- return calculateDebtInFrontLiquityV2(marketsWithNewDebt, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
330
- };
331
-
332
- const getDebtInFrontLiquityV2 = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, viewContract: any, troveId: string) => {
333
- const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
334
- const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(markets, isLegacy, provider, network);
335
- const interestRateDebtInFront = await getDebtInFrontForSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, troveId);
336
-
337
- return calculateDebtInFrontLiquityV2(markets, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
338
- };
339
-
340
- /**
341
- * @param markets
342
- * @param selectedMarket
343
- * @param provider
344
- * @param network
345
- * @param viewContract
346
- * @param interestRate
347
- * @param debtInFrontBeingMoved - amound of debt being repositioned if interest rate is being increased (prevents including it as debt in front)
348
- */
349
- const _getDebtInFrontForInterestRateLiquityV2 = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, isLegacy: boolean, interestRate: string, debtInFrontBeingMoved: string = '0') => {
350
- const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(markets, isLegacy, provider, network);
351
- const interestRateDebtInFront = new Dec(await getDebtInFrontForInterestRateSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, interestRate))
352
- .sub(debtInFrontBeingMoved);
353
-
354
- return calculateDebtInFrontLiquityV2(markets, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
355
- };
356
-
357
- export const getDebtInFrontForInterestRateLiquityV2 = async (
358
- markets: Record<LiquityV2Versions, LiquityV2MarketData>,
359
- selectedMarket: LiquityV2Versions,
360
- provider: EthereumProvider,
361
- network: NetworkNumber,
362
- isLegacy: boolean,
363
- interestRate: string,
364
- debtInFrontBeingMoved: string = '0',
365
- ) => _getDebtInFrontForInterestRateLiquityV2(markets, selectedMarket, getViemProvider(provider, network), network, isLegacy, interestRate, debtInFrontBeingMoved);
366
-
367
- export const _getLiquityV2TroveData = async (
368
- provider: Client,
369
- network: NetworkNumber,
370
- {
371
- selectedMarket,
372
- assetsData,
373
- troveId,
374
- allMarketsData,
375
- }:
376
- {
377
- selectedMarket: LiquityV2MarketInfo,
378
- assetsData: LiquityV2AssetsData,
379
- troveId: string,
380
- allMarketsData: Record<LiquityV2Versions, LiquityV2MarketData>,
381
- },
382
- fetchDebtInFront: boolean = true,
383
- ): Promise<LiquityV2TroveData> => {
384
- const viewContract = getLiquityV2ViewContract(provider, network, selectedMarket.isLegacy);
385
- const { minCollRatio, batchCollRatio } = allMarketsData[selectedMarket.value].marketData;
386
- const { collateralToken, marketAddress, debtToken } = selectedMarket;
387
- const [_data, debtInFront] = await Promise.all([
388
- viewContract.read.getTroveInfo([marketAddress, BigInt(troveId)]),
389
- fetchDebtInFront ? getDebtInFrontLiquityV2(allMarketsData, selectedMarket.value, provider, network, selectedMarket.isLegacy, troveId) : Promise.resolve('0'),
390
- ]);
391
- const data = {
392
- ..._data,
393
- TCRatio: _data.TCRatio.toString() === MAXUINT ? '0' : _data.TCRatio.toString(), // mistake on contract side when debt is 0
394
- };
395
- const usedAssets: LiquityV2UsedAssets = {};
396
-
397
- const debtAssetData = assetsData[debtToken];
398
- const borrowed = assetAmountInEth(data.debtAmount.toString());
399
- usedAssets[debtToken] = {
400
- symbol: debtToken,
401
- supplied: '0',
402
- suppliedUsd: '0',
403
- borrowed,
404
- borrowedUsd: new Dec(borrowed).mul(debtAssetData.price).toString(),
405
- isBorrowed: true,
406
- isSupplied: false,
407
- };
408
-
409
- const collAssetData = assetsData[collateralToken];
410
- const suppliedColl = assetAmountInEth(data.collAmount.toString());
411
- usedAssets[collateralToken] = {
412
- symbol: collateralToken,
413
- supplied: suppliedColl,
414
- suppliedUsd: new Dec(suppliedColl).mul(collAssetData.price).toString(),
415
- borrowed: '0',
416
- borrowedUsd: '0',
417
- isBorrowed: false,
418
- isSupplied: true,
419
- collateral: true,
420
- };
421
-
422
- const collRatio = new Dec(data.TCRatio).div(1e16).toString();
423
- const interestRate = new Dec(data.annualInterestRate).div(1e16).toString();
424
- const interestBatchManager = data.interestBatchManager;
425
- const lastInterestRateAdjTime = data.lastInterestRateAdjTime.toString();
426
-
427
- const hasInterestBatchManager = !compareAddresses(interestBatchManager, ZERO_ADDRESS);
428
- const liqRatio = hasInterestBatchManager ? new Dec(minCollRatio).add(batchCollRatio).toString() : minCollRatio;
429
-
430
- const payload: LiquityV2TroveData = {
431
- usedAssets,
432
- troveId,
433
- interestRate,
434
- interestBatchManager,
435
- debtInFront,
436
- lastInterestRateAdjTime,
437
- liqRatio,
438
- troveStatus: LIQUITY_V2_TROVE_STATUS_ENUM[parseInt(data.status.toString(), 10)],
439
- ...getLiquityV2AggregatedPositionData({
440
- usedAssets, assetsData, minCollRatio: liqRatio, interestRate,
441
- }),
442
- collRatio,
443
- };
444
-
445
- return payload;
446
- };
447
-
448
- export const getLiquityV2TroveData = async (
449
- provider: EthereumProvider,
450
- network: NetworkNumber,
451
- {
452
- selectedMarket,
453
- assetsData,
454
- troveId,
455
- allMarketsData,
456
- }:
457
- {
458
- selectedMarket: LiquityV2MarketInfo,
459
- assetsData: LiquityV2AssetsData,
460
- troveId: string,
461
- allMarketsData: Record<LiquityV2Versions, LiquityV2MarketData>,
462
- },
463
- fetchDebtInFront: boolean = true,
464
- ): Promise<LiquityV2TroveData> => _getLiquityV2TroveData(
465
- getViemProvider(provider, network),
466
- network,
467
- {
468
- selectedMarket,
469
- assetsData,
470
- troveId,
471
- allMarketsData,
472
- },
473
- fetchDebtInFront,
474
- );
475
-
476
- export const getLiquityV2ClaimableCollateral = async (collSurplusPoolAddress: EthAddress, account: EthAddress, provider: EthereumProvider, network: NetworkNumber): Promise<string> => {
477
- const client = getViemProvider(provider, network);
478
- const collSurplusPoolContract = createViemContractFromConfigFunc('LiquityV2CollSurplusPool', collSurplusPoolAddress)(client, network);
479
- const claimableCollateral = await collSurplusPoolContract.read.getCollateral([account]);
480
- return claimableCollateral.toString();
481
- };
482
-
483
- const stabilityPoolAddrForMarket: Record<LiquityV2Versions, EthAddress> = {
484
- [LiquityV2Versions.LiquityV2Eth]: '0x5721cbbd64fc7Ae3Ef44A0A3F9a790A9264Cf9BF',
485
- [LiquityV2Versions.LiquityV2WstEth]: '0x9502b7c397e9aa22fe9db7ef7daf21cd2aebe56b',
486
- [LiquityV2Versions.LiquityV2REth]: '0xd442e41019b7f5c4dd78f50dc03726c446148695',
487
- [LiquityV2Versions.LiquityV2EthLegacy]: ZERO_ADDRESS,
488
- [LiquityV2Versions.LiquityV2REthLegacy]: ZERO_ADDRESS,
489
- [LiquityV2Versions.LiquityV2WstEthLegacy]: ZERO_ADDRESS,
490
- };
491
- const activePoolAddrForMarket: Record<LiquityV2Versions, EthAddress> = {
492
- [LiquityV2Versions.LiquityV2Eth]: '0xeB5A8C825582965f1d84606E078620a84ab16AfE',
493
- [LiquityV2Versions.LiquityV2WstEth]: '0x531a8f99c70d6a56a7cee02d6b4281650d7919a0',
494
- [LiquityV2Versions.LiquityV2REth]: '0x9074d72cc82dad1e13e454755aa8f144c479532f',
495
- [LiquityV2Versions.LiquityV2EthLegacy]: ZERO_ADDRESS,
496
- [LiquityV2Versions.LiquityV2WstEthLegacy]: ZERO_ADDRESS,
497
- [LiquityV2Versions.LiquityV2REthLegacy]: ZERO_ADDRESS,
498
- };
499
-
500
- function ceilDiv(a: string, b: string) {
501
- return new Dec(a).add(new Dec(b).sub(1)).div(b).toString();
502
- }
503
- const SP_YIELD_SPLIT = new Dec(75).mul(10 ** 16).toString(); // 75%
504
-
505
- const calcPendingSPYield = (
506
- aggWeightedDebtSum: string,
507
- lastAggUpdateTime: string,
508
- currentTime: string,
509
- ) => {
510
- const a = new Dec(aggWeightedDebtSum).mul(
511
- new Dec(currentTime).sub(new Dec(lastAggUpdateTime)),
512
- ).toString();
513
- const b = new Dec(SECONDS_PER_YEAR).mul(1000).mul(1e18).toString();
514
- return new Dec(ceilDiv(a, b)).mul(SP_YIELD_SPLIT).div(1e18).toString();
515
- };
516
-
517
-
518
- const calculateStabilityPoolApy = (
519
- spYieldGainParams: SPYieldGainParameters,
520
- ) => {
521
- const {
522
- aggWeightedDebtSum, totalBoldDeposits, lastAggUpdateTime, yieldGainsPending,
523
- } = spYieldGainParams;
524
-
525
- if (new Dec(totalBoldDeposits).eq(0)) {
526
- return '0';
527
- }
528
-
529
- const now = Date.now().toString();
530
- const lastAggUpdateTimeScaled = new Dec(lastAggUpdateTime).mul(1000).toString();
531
-
532
- const pendingSPYield = new Dec(calcPendingSPYield(
533
- aggWeightedDebtSum,
534
- lastAggUpdateTimeScaled,
535
- now,
536
- )).add(yieldGainsPending).toString();
537
-
538
- const annualizedYield = new Dec(pendingSPYield).mul(SECONDS_PER_YEAR).mul(1000).div(new Dec(now).minus(lastAggUpdateTimeScaled))
539
- .toString();
540
- return new Dec(annualizedYield).div(totalBoldDeposits).mul(100).toString();
541
- };
542
-
543
- const getYBoldApyApi = async () => {
544
- try {
545
- const url = 'https://ydaemon.yearn.fi/1/vaults/0x23346B04a7f55b8760E5860AA5A77383D63491cD?strategiesDetails=withDetails&strategiesCondition=inQueue';
546
-
547
- const yBoldData = await fetch(url)
548
- .then(res => res.json())
549
- .catch(console.error);
550
-
551
- return new Dec(yBoldData.apr.netAPR).mul(100).toString();
552
- } catch (error) {
553
- console.error('External API Failure: YBold ', error);
554
- return '0';
555
- }
556
- };
557
-
558
- export type sBoldYieldParameters = {
559
- WETH: string;
560
- wsETH: string;
561
- rETH: string;
562
- };
563
-
564
- const calculateSPApy = (
565
- spYieldGainParams: sBoldYieldParameters, spAPYs: { apyEth: Dec.Value; apyWstEth: Dec.Value; apyREth: Dec.Value; },
566
- ) => {
567
- const {
568
- WETH, wsETH, rETH,
569
- } = spYieldGainParams;
570
-
571
- const apy = new Dec(WETH).mul(spAPYs.apyEth).add(new Dec(wsETH).mul(spAPYs.apyWstEth)).add(new Dec(rETH).mul(spAPYs.apyREth))
572
- .toString();
573
- return apy;
574
- };
575
-
576
- export const getLiquityV2Staking = async (provider: Client, network: NetworkNumber, market: LiquityV2Versions, user: EthAddress) => {
577
- const stabilityPoolView = createViemContractFromConfigFunc('LiquityV2StabilityPool', stabilityPoolAddrForMarket[market])(provider, network);
578
- const activePoolView = createViemContractFromConfigFunc('LiquityV2ActivePool', activePoolAddrForMarket[market])(provider, network);
579
-
580
- const debtTokenInfo = getAssetInfo(LiquityV2Markets(network)[market].debtToken, network);
581
- const debtTokenContract = createViemContractFromConfigFunc('Erc20', debtTokenInfo.address as HexString)(provider, network);
582
-
583
- const [
584
- stabilityRewardColl,
585
- stabilityRewardYield,
586
- compoundedBoldDeposit,
587
- totalBoldDeposits,
588
- P,
589
- currentScale,
590
- yieldGainsPending,
591
- debtTokenBalance,
592
-
593
- aggWeightedDebtSum,
594
- lastAggUpdateTime,
595
- ] = await Promise.all([
596
- stabilityPoolView.read.getDepositorCollGain([user]),
597
- stabilityPoolView.read.getDepositorYieldGain([user]),
598
- stabilityPoolView.read.getCompoundedBoldDeposit([user]),
599
- stabilityPoolView.read.getTotalBoldDeposits(),
600
- stabilityPoolView.read.P(),
601
- stabilityPoolView.read.currentScale(),
602
- stabilityPoolView.read.getYieldGainsPending(),
603
- debtTokenContract.read.balanceOf([user]),
604
-
605
- activePoolView.read.aggWeightedDebtSum(),
606
- activePoolView.read.lastAggUpdateTime(),
607
- ]);
608
-
609
- const stabilityPoolYieldParams: SPYieldGainParameters = {
610
- aggWeightedDebtSum: aggWeightedDebtSum.toString(),
611
- lastAggUpdateTime: lastAggUpdateTime.toString(),
612
- P: P.toString(),
613
- currentScale: currentScale.toString(),
614
- yieldGainsPending: yieldGainsPending.toString(),
615
- totalBoldDeposits: totalBoldDeposits.toString(),
616
- };
617
-
618
- const stabilityPoolApy = calculateStabilityPoolApy(stabilityPoolYieldParams);
619
-
620
- const stakedBOLDBalanceForUser = getEthAmountForDecimals(compoundedBoldDeposit.toString(), 18);
621
- const stabilityRewardCollForUser = getEthAmountForDecimals(stabilityRewardColl.toString(), 18);
622
- const stabilityRewardYieldForUser = getEthAmountForDecimals(stabilityRewardYield.toString(), 18);
623
-
624
- return {
625
- totalBOLDDeposited: getEthAmountForDecimals(totalBoldDeposits.toString(), 18),
626
- stakedBOLDBalance: stakedBOLDBalanceForUser,
627
- stabilityRewardColl: stabilityRewardCollForUser,
628
- stabilityRewardYield: stabilityRewardYieldForUser,
629
- showStakingBalances: !!(+stakedBOLDBalanceForUser || +stabilityRewardCollForUser || +stabilityRewardYieldForUser),
630
- debtTokenBalance: getEthAmountForDecimals(debtTokenBalance.toString(), debtTokenInfo.decimals),
631
- stabilityPoolApy,
632
- };
633
- };
634
-
635
- export const getLiquitySAndYBold = async (provider: Client, network: NetworkNumber, markets: any, user: EthAddress) => {
636
- const sBold = LiquityV2sBoldVaultViem(provider, network);
637
- const yBold = createViemContractFromConfigFunc('Erc4626', '0x9F4330700a36B29952869fac9b33f45EEdd8A3d8')(provider, network);
638
- const stYBold = createViemContractFromConfigFunc('Erc4626', '0x23346B04a7f55b8760E5860AA5A77383D63491cD')(provider, network);
639
- const spAPYs = {
640
- apyEth: markets[LiquityV2Versions.LiquityV2Eth].data.stabilityPoolApy,
641
- apyWstEth: markets[LiquityV2Versions.LiquityV2WstEth].data.stabilityPoolApy,
642
- apyREth: markets[LiquityV2Versions.LiquityV2REth].data.stabilityPoolApy,
643
- };
644
-
645
- const [
646
- sBoldTotalAssets,
647
- sBoldConvertToShares,
648
- sBoldMaxWithdraw,
649
-
650
- wethApy,
651
- wsETHApy,
652
- rETHApy,
653
-
654
- yBoldTotalAssets,
655
- yBoldMaxWithdraw,
656
- stYBoldConvertToShares,
657
-
658
- yBoldApy,
659
-
660
- sBoldBalance,
661
- yBoldBalance,
662
- stYBoldBalance,
663
- ] = await Promise.all([
664
- sBold.read.totalAssets(),
665
- sBold.read.convertToShares([BigInt(1e18)]),
666
- sBold.read.maxWithdraw([user]),
667
-
668
- sBold.read.sps([BigInt(0)]),
669
- sBold.read.sps([BigInt(1)]),
670
- sBold.read.sps([BigInt(2)]),
671
-
672
- yBold.read.totalAssets(),
673
- yBold.read.maxWithdraw([user]),
674
- stYBold.read.convertToShares([BigInt(1e18)]),
675
- getYBoldApyApi(),
676
-
677
- sBold.read.balanceOf([user]),
678
- yBold.read.balanceOf([user]),
679
- stYBold.read.balanceOf([user]),
680
- ]);
681
-
682
- const spMarketRes = {
683
- WETH: new Dec(wethApy[1]).div(10000).toString(),
684
- wsETH: new Dec(wsETHApy[1]).div(10000).toString(),
685
- rETH: new Dec(rETHApy[1]).div(10000).toString(),
686
- };
687
-
688
- const spApy = calculateSPApy(spMarketRes, spAPYs);
689
-
690
- return {
691
- spApy,
692
- yBoldApy,
693
- totalBoldDepositedSBold: assetAmountInEth(sBoldTotalAssets.toString(), 'sBOLD'),
694
- boldRateSBold: assetAmountInEth(sBoldConvertToShares.toString(), 'sBOLD'),
695
- maxWithdrawSBold: assetAmountInEth(sBoldMaxWithdraw.toString(), 'sBOLD'),
696
- totalBoldDepositedYBold: assetAmountInEth(yBoldTotalAssets.toString(), 'yBOLD'),
697
- boldRateYBold: assetAmountInEth(stYBoldConvertToShares.toString(), 'yBOLD'),
698
- maxWithdrawYBold: assetAmountInEth(yBoldMaxWithdraw.toString(), 'yBOLD'),
699
-
700
- sBoldBalance: assetAmountInEth(sBoldBalance.toString(), 'sBOLD'),
701
- yBoldBalance: assetAmountInEth(yBoldBalance.toString(), 'yBOLD'),
702
- stYBoldBalance: assetAmountInEth(stYBoldBalance.toString(), 'yBOLD'),
703
- };
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
+ export const calculateDebtInFrontLiquityV2 = (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, allMarketsUnbackedDebts: Record<LiquityV2Versions, string>, interestRateDebtInFront: string): string => {
268
+ // Sanity check to avoid division by 0. Very unlikely to ever happen.
269
+ const selectedMarketTotalBorrow = new Dec(markets[selectedMarket].assetsData[LiquityV2Markets(NetworkNumber.Eth)[selectedMarket].debtToken].totalBorrow);
270
+ if (selectedMarketTotalBorrow.eq(0)) return new Dec(0).toString();
271
+
272
+ const selectedMarketUnbackedDebt = new Dec(allMarketsUnbackedDebts[selectedMarket]);
273
+ const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
274
+ const totalUnbackedDebt = Object.values(allMarketsUnbackedDebts).reduce((acc, val) => acc.plus(new Dec(val)), new Dec(0));
275
+
276
+ // When totalUnbackedDebt is 0, redemptions will be proportional with the branch size and not to unbacked debt.
277
+ // When unbacked debt is 0 for branch, next redemption call won't touch that branch, so in order to estimate total debt in front we will:
278
+ // - First add up all the unbacked debt from other branches, as that will be the only debt that will be redeemed on the fist redemption call
279
+ // - Perform split the same way as we would do when totalUnbackedDebt == 0, this would represent the second call to the redemption function
280
+ if (selectedMarketUnbackedDebt.eq(0)) {
281
+ // Special case if the branch debt in front is 0, it means that all debt in front is unbacked debt from other branches.
282
+ if (new Dec(interestRateDebtInFront).eq(0)) return totalUnbackedDebt.toString();
283
+
284
+ // Then calculate how much of that estimated amount would go to each branch
285
+ // Second redemption call - calculate proportional redemption based on updated total debt
286
+ const amountBeingRedeemedOnEachMarketByTotalBorrow = Object.entries(markets).map(([version, market]) => {
287
+ const { isLegacy: isLegacyMarket } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
288
+ if (version === selectedMarket && isLegacyMarket !== isLegacy) return new Dec(interestRateDebtInFront);
289
+ const { assetsData } = market;
290
+ const { debtToken } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
291
+ // For other markets, subtract their unbacked debt as it will be cleared in first redemption call
292
+ const marketUnbackedDebt = new Dec(allMarketsUnbackedDebts[version as LiquityV2Versions]);
293
+ const totalBorrow = new Dec(assetsData[debtToken].totalBorrow).sub(marketUnbackedDebt);
294
+ const amountToRedeem = new Dec(interestRateDebtInFront).mul(totalBorrow).div(selectedMarketTotalBorrow);
295
+ return Dec.min(amountToRedeem, totalBorrow);
296
+ });
297
+
298
+ const redemptionAmount = amountBeingRedeemedOnEachMarketByTotalBorrow.reduce((acc, val) => acc.plus(val), new Dec(0));
299
+ return totalUnbackedDebt.plus(redemptionAmount).toString();
300
+ }
301
+
302
+ const amountBeingRedeemedOnEachMarketByUnbackedDebt = Object.entries(markets).map(([version, market]) => {
303
+ const { isLegacy: isLegacyMarket } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
304
+ if (version === selectedMarket && isLegacyMarket !== isLegacy) return new Dec(interestRateDebtInFront);
305
+ const { assetsData } = market;
306
+ const { debtToken } = LiquityV2Markets(NetworkNumber.Eth)[version as LiquityV2Versions];
307
+ const unbackedDebt = new Dec(allMarketsUnbackedDebts[version as LiquityV2Versions]);
308
+ const totalBorrow = new Dec(assetsData[debtToken].totalBorrow);
309
+ const amountToRedeem = new Dec(interestRateDebtInFront).mul(unbackedDebt).div(selectedMarketUnbackedDebt);
310
+ return Dec.min(amountToRedeem, totalBorrow);
311
+ });
312
+
313
+ return amountBeingRedeemedOnEachMarketByUnbackedDebt.reduce((acc, val) => acc.plus(val), new Dec(0)).toString();
314
+ };
315
+
316
+ // @dev The amount redeemed on each branch depends on the unbacked debt of every branch (the difference between total borrow and stability pool deposits).
317
+ // When new debt is generated on the selected market, the unbacked debt will increase, resulting in a higher redemption amount on that branch.
318
+ // This function accepts the new debt that's about to be generated (e.g., trove creation) and estimates the debt in front based on the new state.
319
+ export const getDebtInFrontForInterestRateIncludingNewDebtLiquityV2 = async (newDebt: string, markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, interestRate: string) => {
320
+ const marketsWithNewDebt = structuredClone(markets);
321
+ const selectedMarketDebtToken = LiquityV2Markets(network)[selectedMarket].debtToken;
322
+ const currentTotalBorrow = new Dec(marketsWithNewDebt[selectedMarket].assetsData[selectedMarketDebtToken].totalBorrow);
323
+ marketsWithNewDebt[selectedMarket].assetsData[selectedMarketDebtToken].totalBorrow = currentTotalBorrow.add(newDebt).toString();
324
+
325
+ const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
326
+ const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(marketsWithNewDebt, isLegacy, provider, network);
327
+ const interestRateDebtInFront = new Dec(await getDebtInFrontForInterestRateSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, interestRate));
328
+
329
+ return calculateDebtInFrontLiquityV2(marketsWithNewDebt, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
330
+ };
331
+
332
+ const getDebtInFrontLiquityV2 = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, viewContract: any, troveId: string) => {
333
+ const { isLegacy } = LiquityV2Markets(NetworkNumber.Eth)[selectedMarket];
334
+ const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(markets, isLegacy, provider, network);
335
+ const interestRateDebtInFront = await getDebtInFrontForSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, troveId);
336
+
337
+ return calculateDebtInFrontLiquityV2(markets, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
338
+ };
339
+
340
+ /**
341
+ * @param markets
342
+ * @param selectedMarket
343
+ * @param provider
344
+ * @param network
345
+ * @param viewContract
346
+ * @param interestRate
347
+ * @param debtInFrontBeingMoved - amound of debt being repositioned if interest rate is being increased (prevents including it as debt in front)
348
+ */
349
+ const _getDebtInFrontForInterestRateLiquityV2 = async (markets: Record<LiquityV2Versions, LiquityV2MarketData>, selectedMarket: LiquityV2Versions, provider: Client, network: NetworkNumber, isLegacy: boolean, interestRate: string, debtInFrontBeingMoved: string = '0') => {
350
+ const allMarketsUnbackedDebts = await getAllMarketsUnbackedDebts(markets, isLegacy, provider, network);
351
+ const interestRateDebtInFront = new Dec(await getDebtInFrontForInterestRateSingleMarketLiquityV2(provider, network, isLegacy, LiquityV2Markets(network)[selectedMarket].marketAddress, interestRate))
352
+ .sub(debtInFrontBeingMoved);
353
+
354
+ return calculateDebtInFrontLiquityV2(markets, selectedMarket, allMarketsUnbackedDebts, interestRateDebtInFront.toString());
355
+ };
356
+
357
+ export const getDebtInFrontForInterestRateLiquityV2 = async (
358
+ markets: Record<LiquityV2Versions, LiquityV2MarketData>,
359
+ selectedMarket: LiquityV2Versions,
360
+ provider: EthereumProvider,
361
+ network: NetworkNumber,
362
+ isLegacy: boolean,
363
+ interestRate: string,
364
+ debtInFrontBeingMoved: string = '0',
365
+ ) => _getDebtInFrontForInterestRateLiquityV2(markets, selectedMarket, getViemProvider(provider, network), network, isLegacy, interestRate, debtInFrontBeingMoved);
366
+
367
+ export const _getLiquityV2TroveData = async (
368
+ provider: Client,
369
+ network: NetworkNumber,
370
+ {
371
+ selectedMarket,
372
+ assetsData,
373
+ troveId,
374
+ allMarketsData,
375
+ }:
376
+ {
377
+ selectedMarket: LiquityV2MarketInfo,
378
+ assetsData: LiquityV2AssetsData,
379
+ troveId: string,
380
+ allMarketsData: Record<LiquityV2Versions, LiquityV2MarketData>,
381
+ },
382
+ fetchDebtInFront: boolean = true,
383
+ ): Promise<LiquityV2TroveData> => {
384
+ const viewContract = getLiquityV2ViewContract(provider, network, selectedMarket.isLegacy);
385
+ const { minCollRatio, batchCollRatio } = allMarketsData[selectedMarket.value].marketData;
386
+ const { collateralToken, marketAddress, debtToken } = selectedMarket;
387
+ const [_data, debtInFront] = await Promise.all([
388
+ viewContract.read.getTroveInfo([marketAddress, BigInt(troveId)]),
389
+ fetchDebtInFront ? getDebtInFrontLiquityV2(allMarketsData, selectedMarket.value, provider, network, selectedMarket.isLegacy, troveId) : Promise.resolve('0'),
390
+ ]);
391
+ const data = {
392
+ ..._data,
393
+ TCRatio: _data.TCRatio.toString() === MAXUINT ? '0' : _data.TCRatio.toString(), // mistake on contract side when debt is 0
394
+ };
395
+ const usedAssets: LiquityV2UsedAssets = {};
396
+
397
+ const debtAssetData = assetsData[debtToken];
398
+ const borrowed = assetAmountInEth(data.debtAmount.toString());
399
+ usedAssets[debtToken] = {
400
+ symbol: debtToken,
401
+ supplied: '0',
402
+ suppliedUsd: '0',
403
+ borrowed,
404
+ borrowedUsd: new Dec(borrowed).mul(debtAssetData.price).toString(),
405
+ isBorrowed: true,
406
+ isSupplied: false,
407
+ };
408
+
409
+ const collAssetData = assetsData[collateralToken];
410
+ const suppliedColl = assetAmountInEth(data.collAmount.toString());
411
+ usedAssets[collateralToken] = {
412
+ symbol: collateralToken,
413
+ supplied: suppliedColl,
414
+ suppliedUsd: new Dec(suppliedColl).mul(collAssetData.price).toString(),
415
+ borrowed: '0',
416
+ borrowedUsd: '0',
417
+ isBorrowed: false,
418
+ isSupplied: true,
419
+ collateral: true,
420
+ };
421
+
422
+ const collRatio = new Dec(data.TCRatio).div(1e16).toString();
423
+ const interestRate = new Dec(data.annualInterestRate).div(1e16).toString();
424
+ const interestBatchManager = data.interestBatchManager;
425
+ const lastInterestRateAdjTime = data.lastInterestRateAdjTime.toString();
426
+
427
+ const hasInterestBatchManager = !compareAddresses(interestBatchManager, ZERO_ADDRESS);
428
+ const liqRatio = hasInterestBatchManager ? new Dec(minCollRatio).add(batchCollRatio).toString() : minCollRatio;
429
+
430
+ const payload: LiquityV2TroveData = {
431
+ usedAssets,
432
+ troveId,
433
+ interestRate,
434
+ interestBatchManager,
435
+ debtInFront,
436
+ lastInterestRateAdjTime,
437
+ liqRatio,
438
+ troveStatus: LIQUITY_V2_TROVE_STATUS_ENUM[parseInt(data.status.toString(), 10)],
439
+ ...getLiquityV2AggregatedPositionData({
440
+ usedAssets, assetsData, minCollRatio: liqRatio, interestRate,
441
+ }),
442
+ collRatio,
443
+ };
444
+
445
+ return payload;
446
+ };
447
+
448
+ export const getLiquityV2TroveData = async (
449
+ provider: EthereumProvider,
450
+ network: NetworkNumber,
451
+ {
452
+ selectedMarket,
453
+ assetsData,
454
+ troveId,
455
+ allMarketsData,
456
+ }:
457
+ {
458
+ selectedMarket: LiquityV2MarketInfo,
459
+ assetsData: LiquityV2AssetsData,
460
+ troveId: string,
461
+ allMarketsData: Record<LiquityV2Versions, LiquityV2MarketData>,
462
+ },
463
+ fetchDebtInFront: boolean = true,
464
+ ): Promise<LiquityV2TroveData> => _getLiquityV2TroveData(
465
+ getViemProvider(provider, network),
466
+ network,
467
+ {
468
+ selectedMarket,
469
+ assetsData,
470
+ troveId,
471
+ allMarketsData,
472
+ },
473
+ fetchDebtInFront,
474
+ );
475
+
476
+ export const getLiquityV2ClaimableCollateral = async (collSurplusPoolAddress: EthAddress, account: EthAddress, provider: EthereumProvider, network: NetworkNumber): Promise<string> => {
477
+ const client = getViemProvider(provider, network);
478
+ const collSurplusPoolContract = createViemContractFromConfigFunc('LiquityV2CollSurplusPool', collSurplusPoolAddress)(client, network);
479
+ const claimableCollateral = await collSurplusPoolContract.read.getCollateral([account]);
480
+ return claimableCollateral.toString();
481
+ };
482
+
483
+ const stabilityPoolAddrForMarket: Record<LiquityV2Versions, EthAddress> = {
484
+ [LiquityV2Versions.LiquityV2Eth]: '0x5721cbbd64fc7Ae3Ef44A0A3F9a790A9264Cf9BF',
485
+ [LiquityV2Versions.LiquityV2WstEth]: '0x9502b7c397e9aa22fe9db7ef7daf21cd2aebe56b',
486
+ [LiquityV2Versions.LiquityV2REth]: '0xd442e41019b7f5c4dd78f50dc03726c446148695',
487
+ [LiquityV2Versions.LiquityV2EthLegacy]: ZERO_ADDRESS,
488
+ [LiquityV2Versions.LiquityV2REthLegacy]: ZERO_ADDRESS,
489
+ [LiquityV2Versions.LiquityV2WstEthLegacy]: ZERO_ADDRESS,
490
+ };
491
+ const activePoolAddrForMarket: Record<LiquityV2Versions, EthAddress> = {
492
+ [LiquityV2Versions.LiquityV2Eth]: '0xeB5A8C825582965f1d84606E078620a84ab16AfE',
493
+ [LiquityV2Versions.LiquityV2WstEth]: '0x531a8f99c70d6a56a7cee02d6b4281650d7919a0',
494
+ [LiquityV2Versions.LiquityV2REth]: '0x9074d72cc82dad1e13e454755aa8f144c479532f',
495
+ [LiquityV2Versions.LiquityV2EthLegacy]: ZERO_ADDRESS,
496
+ [LiquityV2Versions.LiquityV2WstEthLegacy]: ZERO_ADDRESS,
497
+ [LiquityV2Versions.LiquityV2REthLegacy]: ZERO_ADDRESS,
498
+ };
499
+
500
+ function ceilDiv(a: string, b: string) {
501
+ return new Dec(a).add(new Dec(b).sub(1)).div(b).toString();
502
+ }
503
+ const SP_YIELD_SPLIT = new Dec(75).mul(10 ** 16).toString(); // 75%
504
+
505
+ const calcPendingSPYield = (
506
+ aggWeightedDebtSum: string,
507
+ lastAggUpdateTime: string,
508
+ currentTime: string,
509
+ ) => {
510
+ const a = new Dec(aggWeightedDebtSum).mul(
511
+ new Dec(currentTime).sub(new Dec(lastAggUpdateTime)),
512
+ ).toString();
513
+ const b = new Dec(SECONDS_PER_YEAR).mul(1000).mul(1e18).toString();
514
+ return new Dec(ceilDiv(a, b)).mul(SP_YIELD_SPLIT).div(1e18).toString();
515
+ };
516
+
517
+
518
+ const calculateStabilityPoolApy = (
519
+ spYieldGainParams: SPYieldGainParameters,
520
+ ) => {
521
+ const {
522
+ aggWeightedDebtSum, totalBoldDeposits, lastAggUpdateTime, yieldGainsPending,
523
+ } = spYieldGainParams;
524
+
525
+ if (new Dec(totalBoldDeposits).eq(0)) {
526
+ return '0';
527
+ }
528
+
529
+ const now = Date.now().toString();
530
+ const lastAggUpdateTimeScaled = new Dec(lastAggUpdateTime).mul(1000).toString();
531
+
532
+ const pendingSPYield = new Dec(calcPendingSPYield(
533
+ aggWeightedDebtSum,
534
+ lastAggUpdateTimeScaled,
535
+ now,
536
+ )).add(yieldGainsPending).toString();
537
+
538
+ const annualizedYield = new Dec(pendingSPYield).mul(SECONDS_PER_YEAR).mul(1000).div(new Dec(now).minus(lastAggUpdateTimeScaled))
539
+ .toString();
540
+ return new Dec(annualizedYield).div(totalBoldDeposits).mul(100).toString();
541
+ };
542
+
543
+ const getYBoldApyApi = async () => {
544
+ try {
545
+ const url = 'https://ydaemon.yearn.fi/1/vaults/0x23346B04a7f55b8760E5860AA5A77383D63491cD?strategiesDetails=withDetails&strategiesCondition=inQueue';
546
+
547
+ const yBoldData = await fetch(url)
548
+ .then(res => res.json())
549
+ .catch(console.error);
550
+
551
+ return new Dec(yBoldData.apr.netAPR).mul(100).toString();
552
+ } catch (error) {
553
+ console.error('External API Failure: YBold ', error);
554
+ return '0';
555
+ }
556
+ };
557
+
558
+ export type sBoldYieldParameters = {
559
+ WETH: string;
560
+ wsETH: string;
561
+ rETH: string;
562
+ };
563
+
564
+ const calculateSPApy = (
565
+ spYieldGainParams: sBoldYieldParameters, spAPYs: { apyEth: Dec.Value; apyWstEth: Dec.Value; apyREth: Dec.Value; },
566
+ ) => {
567
+ const {
568
+ WETH, wsETH, rETH,
569
+ } = spYieldGainParams;
570
+
571
+ const apy = new Dec(WETH).mul(spAPYs.apyEth).add(new Dec(wsETH).mul(spAPYs.apyWstEth)).add(new Dec(rETH).mul(spAPYs.apyREth))
572
+ .toString();
573
+ return apy;
574
+ };
575
+
576
+ export const getLiquityV2Staking = async (provider: Client, network: NetworkNumber, market: LiquityV2Versions, user: EthAddress) => {
577
+ const stabilityPoolView = createViemContractFromConfigFunc('LiquityV2StabilityPool', stabilityPoolAddrForMarket[market])(provider, network);
578
+ const activePoolView = createViemContractFromConfigFunc('LiquityV2ActivePool', activePoolAddrForMarket[market])(provider, network);
579
+
580
+ const debtTokenInfo = getAssetInfo(LiquityV2Markets(network)[market].debtToken, network);
581
+ const debtTokenContract = createViemContractFromConfigFunc('Erc20', debtTokenInfo.address as HexString)(provider, network);
582
+
583
+ const [
584
+ stabilityRewardColl,
585
+ stabilityRewardYield,
586
+ compoundedBoldDeposit,
587
+ totalBoldDeposits,
588
+ P,
589
+ currentScale,
590
+ yieldGainsPending,
591
+ debtTokenBalance,
592
+
593
+ aggWeightedDebtSum,
594
+ lastAggUpdateTime,
595
+ ] = await Promise.all([
596
+ stabilityPoolView.read.getDepositorCollGain([user]),
597
+ stabilityPoolView.read.getDepositorYieldGain([user]),
598
+ stabilityPoolView.read.getCompoundedBoldDeposit([user]),
599
+ stabilityPoolView.read.getTotalBoldDeposits(),
600
+ stabilityPoolView.read.P(),
601
+ stabilityPoolView.read.currentScale(),
602
+ stabilityPoolView.read.getYieldGainsPending(),
603
+ debtTokenContract.read.balanceOf([user]),
604
+
605
+ activePoolView.read.aggWeightedDebtSum(),
606
+ activePoolView.read.lastAggUpdateTime(),
607
+ ]);
608
+
609
+ const stabilityPoolYieldParams: SPYieldGainParameters = {
610
+ aggWeightedDebtSum: aggWeightedDebtSum.toString(),
611
+ lastAggUpdateTime: lastAggUpdateTime.toString(),
612
+ P: P.toString(),
613
+ currentScale: currentScale.toString(),
614
+ yieldGainsPending: yieldGainsPending.toString(),
615
+ totalBoldDeposits: totalBoldDeposits.toString(),
616
+ };
617
+
618
+ const stabilityPoolApy = calculateStabilityPoolApy(stabilityPoolYieldParams);
619
+
620
+ const stakedBOLDBalanceForUser = getEthAmountForDecimals(compoundedBoldDeposit.toString(), 18);
621
+ const stabilityRewardCollForUser = getEthAmountForDecimals(stabilityRewardColl.toString(), 18);
622
+ const stabilityRewardYieldForUser = getEthAmountForDecimals(stabilityRewardYield.toString(), 18);
623
+
624
+ return {
625
+ totalBOLDDeposited: getEthAmountForDecimals(totalBoldDeposits.toString(), 18),
626
+ stakedBOLDBalance: stakedBOLDBalanceForUser,
627
+ stabilityRewardColl: stabilityRewardCollForUser,
628
+ stabilityRewardYield: stabilityRewardYieldForUser,
629
+ showStakingBalances: !!(+stakedBOLDBalanceForUser || +stabilityRewardCollForUser || +stabilityRewardYieldForUser),
630
+ debtTokenBalance: getEthAmountForDecimals(debtTokenBalance.toString(), debtTokenInfo.decimals),
631
+ stabilityPoolApy,
632
+ };
633
+ };
634
+
635
+ export const getLiquitySAndYBold = async (provider: Client, network: NetworkNumber, markets: any, user: EthAddress) => {
636
+ const sBold = LiquityV2sBoldVaultViem(provider, network);
637
+ const yBold = createViemContractFromConfigFunc('Erc4626', '0x9F4330700a36B29952869fac9b33f45EEdd8A3d8')(provider, network);
638
+ const stYBold = createViemContractFromConfigFunc('Erc4626', '0x23346B04a7f55b8760E5860AA5A77383D63491cD')(provider, network);
639
+ const spAPYs = {
640
+ apyEth: markets[LiquityV2Versions.LiquityV2Eth].data.stabilityPoolApy,
641
+ apyWstEth: markets[LiquityV2Versions.LiquityV2WstEth].data.stabilityPoolApy,
642
+ apyREth: markets[LiquityV2Versions.LiquityV2REth].data.stabilityPoolApy,
643
+ };
644
+
645
+ const [
646
+ sBoldTotalAssets,
647
+ sBoldConvertToShares,
648
+ sBoldMaxWithdraw,
649
+
650
+ wethApy,
651
+ wsETHApy,
652
+ rETHApy,
653
+
654
+ yBoldTotalAssets,
655
+ yBoldMaxWithdraw,
656
+ stYBoldConvertToShares,
657
+
658
+ yBoldApy,
659
+
660
+ sBoldBalance,
661
+ yBoldBalance,
662
+ stYBoldBalance,
663
+ ] = await Promise.all([
664
+ sBold.read.totalAssets(),
665
+ sBold.read.convertToShares([BigInt(1e18)]),
666
+ sBold.read.maxWithdraw([user]),
667
+
668
+ sBold.read.sps([BigInt(0)]),
669
+ sBold.read.sps([BigInt(1)]),
670
+ sBold.read.sps([BigInt(2)]),
671
+
672
+ yBold.read.totalAssets(),
673
+ yBold.read.maxWithdraw([user]),
674
+ stYBold.read.convertToShares([BigInt(1e18)]),
675
+ getYBoldApyApi(),
676
+
677
+ sBold.read.balanceOf([user]),
678
+ yBold.read.balanceOf([user]),
679
+ stYBold.read.balanceOf([user]),
680
+ ]);
681
+
682
+ const spMarketRes = {
683
+ WETH: new Dec(wethApy[1]).div(10000).toString(),
684
+ wsETH: new Dec(wsETHApy[1]).div(10000).toString(),
685
+ rETH: new Dec(rETHApy[1]).div(10000).toString(),
686
+ };
687
+
688
+ const spApy = calculateSPApy(spMarketRes, spAPYs);
689
+
690
+ return {
691
+ spApy,
692
+ yBoldApy,
693
+ totalBoldDepositedSBold: assetAmountInEth(sBoldTotalAssets.toString(), 'sBOLD'),
694
+ boldRateSBold: assetAmountInEth(sBoldConvertToShares.toString(), 'sBOLD'),
695
+ maxWithdrawSBold: assetAmountInEth(sBoldMaxWithdraw.toString(), 'sBOLD'),
696
+ totalBoldDepositedYBold: assetAmountInEth(yBoldTotalAssets.toString(), 'yBOLD'),
697
+ boldRateYBold: assetAmountInEth(stYBoldConvertToShares.toString(), 'yBOLD'),
698
+ maxWithdrawYBold: assetAmountInEth(yBoldMaxWithdraw.toString(), 'yBOLD'),
699
+
700
+ sBoldBalance: assetAmountInEth(sBoldBalance.toString(), 'sBOLD'),
701
+ yBoldBalance: assetAmountInEth(yBoldBalance.toString(), 'yBOLD'),
702
+ stYBoldBalance: assetAmountInEth(stYBoldBalance.toString(), 'yBOLD'),
703
+ };
704
704
  };