@gearbox-protocol/sdk 13.0.0-beta.1 → 13.0.0-beta.2

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.
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var assetsMath_exports = {};
20
+ __export(assetsMath_exports, {
21
+ AssetUtils: () => AssetUtils
22
+ });
23
+ module.exports = __toCommonJS(assetsMath_exports);
24
+ var import__ = require("../index.js");
25
+ var import_creditAccount = require("./creditAccount.js");
26
+ class AssetUtils {
27
+ static nextAsset({
28
+ allowedTokens,
29
+ selectedAssets,
30
+ balances,
31
+ tokensList,
32
+ prices = {}
33
+ }) {
34
+ const selectedRecord = selectedAssets.reduce(
35
+ (acc, { token }) => {
36
+ acc[token.toLowerCase()] = true;
37
+ return acc;
38
+ },
39
+ {}
40
+ );
41
+ const notSelected = allowedTokens.filter((allowedToken) => {
42
+ const alreadySelected = selectedRecord[allowedToken.toLowerCase()];
43
+ return !alreadySelected;
44
+ });
45
+ const sorted = import_creditAccount.CreditAccountDataUtils.sortBalances(
46
+ AssetUtils.getBalances(notSelected, balances),
47
+ prices,
48
+ tokensList
49
+ );
50
+ const [address] = sorted[0] || [];
51
+ return address;
52
+ }
53
+ static getBalances(allowedTokens, externalBalances) {
54
+ return allowedTokens.reduce((acc, address) => {
55
+ const addressLc = address.toLowerCase();
56
+ return {
57
+ ...acc,
58
+ [addressLc]: externalBalances[addressLc] || 0n
59
+ };
60
+ }, {});
61
+ }
62
+ static constructAssetRecord(a) {
63
+ const record = a.reduce((acc, asset) => {
64
+ acc[asset.token] = asset;
65
+ return acc;
66
+ }, {});
67
+ return record;
68
+ }
69
+ static memoWrap = (unwrappedAddress, wrappedAddress, prices, tokensList) => function wrap(assets) {
70
+ const assetsRecord = AssetUtils.constructAssetRecord(assets);
71
+ const unwrapped = assetsRecord[unwrappedAddress];
72
+ const wrapped = assetsRecord[wrappedAddress];
73
+ const { balance: wrappedAmount = 0n } = wrapped || {};
74
+ if (unwrapped) {
75
+ const { balance: unwrappedAmount = 0n } = unwrapped || {};
76
+ const unwrappedToken = tokensList[unwrappedAddress];
77
+ const unwrappedPrice = prices[unwrappedAddress] || 0n;
78
+ const wrappedToken = tokensList[wrappedAddress];
79
+ const wrappedPrice = prices[wrappedAddress] || 0n;
80
+ const unwrappedInWrapped = import__.PriceUtils.convertByPrice(
81
+ import__.PriceUtils.calcTotalPrice(
82
+ unwrappedPrice,
83
+ import__.BigIntMath.max(0n, unwrappedAmount),
84
+ unwrappedToken.decimals
85
+ ),
86
+ {
87
+ price: wrappedPrice,
88
+ decimals: wrappedToken.decimals
89
+ }
90
+ );
91
+ assetsRecord[wrappedAddress] = {
92
+ token: wrappedAddress,
93
+ balance: import__.BigIntMath.max(0n, wrappedAmount) + unwrappedInWrapped
94
+ };
95
+ delete assetsRecord[unwrappedAddress];
96
+ return [Object.values(assetsRecord), unwrappedInWrapped, wrappedAmount];
97
+ }
98
+ return [Object.values(assetsRecord), 0n, wrappedAmount];
99
+ };
100
+ /**
101
+ * Sums the the second assets list into the first assets list
102
+ * Balances cant be negative; creates new assets.
103
+ */
104
+ static sumAssets(a, b) {
105
+ const aRecord = AssetUtils.constructAssetRecord(a);
106
+ const resRecord = b.reduce((acc, bAsset) => {
107
+ const aAsset = acc[bAsset.token];
108
+ const { balance: amount = 0n } = aAsset || {};
109
+ const amountSum = import__.BigIntMath.max(0n, bAsset.balance) + import__.BigIntMath.max(0n, amount);
110
+ const aOrB = aAsset || bAsset;
111
+ acc[bAsset.token] = {
112
+ ...aOrB,
113
+ balance: amountSum
114
+ };
115
+ return acc;
116
+ }, aRecord);
117
+ return Object.values(resRecord);
118
+ }
119
+ /**
120
+ * Sums the the second assets list into the first assets list
121
+ * Balances cant be negative; doesn't create new assets.
122
+ */
123
+ static addBalances(a, b) {
124
+ const bRecord = AssetUtils.constructAssetRecord(b);
125
+ return a.map((asset) => {
126
+ const bAsset = bRecord[asset.token];
127
+ const { balance: bAmount = 0n } = bAsset || {};
128
+ const amountSum = import__.BigIntMath.max(0n, asset.balance) + import__.BigIntMath.max(0n, bAmount);
129
+ return { ...asset, balance: amountSum };
130
+ });
131
+ }
132
+ /**
133
+ * Subtracts the the second assets list from the first assets list
134
+ * Balances cant be negative; doesn't create new assets.
135
+ */
136
+ static subAssets(a, b) {
137
+ const bRecord = AssetUtils.constructAssetRecord(b);
138
+ return a.map((asset) => {
139
+ const bAsset = bRecord[asset.token];
140
+ const { balance: bAmount = 0n } = bAsset || {};
141
+ const amountSub = import__.BigIntMath.max(0n, asset.balance) - import__.BigIntMath.max(0n, bAmount);
142
+ return { ...asset, balance: import__.BigIntMath.max(0n, amountSub) };
143
+ });
144
+ }
145
+ }
146
+ // Annotate the CommonJS export names for ESM import in node:
147
+ 0 && (module.exports = {
148
+ AssetUtils
149
+ });
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var bigintMath_exports = {};
20
+ __export(bigintMath_exports, {
21
+ BigIntMath: () => BigIntMath
22
+ });
23
+ module.exports = __toCommonJS(bigintMath_exports);
24
+ class BigIntMath {
25
+ static abs = (x) => x < 0n ? -x : x;
26
+ static max = (a, b) => a > b ? a : b;
27
+ static min = (a, b) => a < b ? a : b;
28
+ static neg = (a) => a > 0 ? a * -1n : a;
29
+ }
30
+ // Annotate the CommonJS export names for ESM import in node:
31
+ 0 && (module.exports = {
32
+ BigIntMath
33
+ });
@@ -0,0 +1,407 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var creditAccount_exports = {};
20
+ __export(creditAccount_exports, {
21
+ CreditAccountDataUtils: () => CreditAccountDataUtils
22
+ });
23
+ module.exports = __toCommonJS(creditAccount_exports);
24
+ var import__ = require("../index.js");
25
+ const MAX_UINT16 = 65535;
26
+ class CreditAccountDataUtils {
27
+ static sortBalances(balances, prices, tokens) {
28
+ return Object.entries(balances).sort(
29
+ ([addr1, amount1], [addr2, amount2]) => {
30
+ return CreditAccountDataUtils.assetComparator(
31
+ {
32
+ token: addr1,
33
+ balance: amount1
34
+ },
35
+ {
36
+ token: addr2,
37
+ balance: amount2
38
+ },
39
+ prices,
40
+ prices,
41
+ tokens,
42
+ tokens
43
+ );
44
+ }
45
+ );
46
+ }
47
+ static sortAssets(balances, prices, tokens) {
48
+ return [...balances].sort(
49
+ (t1, t2) => CreditAccountDataUtils.assetComparator(
50
+ t1,
51
+ t2,
52
+ prices,
53
+ prices,
54
+ tokens,
55
+ tokens
56
+ )
57
+ );
58
+ }
59
+ static assetComparator(t1, t2, prices1, prices2, tokens1, tokens2) {
60
+ const addr1Lc = t1.token.toLowerCase();
61
+ const addr2Lc = t2.token.toLowerCase();
62
+ const token1 = tokens1?.[addr1Lc];
63
+ const token2 = tokens2?.[addr2Lc];
64
+ const price1 = prices1?.[addr1Lc] || import__.PRICE_DECIMALS;
65
+ const price2 = prices2?.[addr2Lc] || import__.PRICE_DECIMALS;
66
+ const totalPrice1 = import__.PriceUtils.calcTotalPrice(
67
+ price1,
68
+ t1.balance,
69
+ token1?.decimals
70
+ );
71
+ const totalPrice2 = import__.PriceUtils.calcTotalPrice(
72
+ price2,
73
+ t2.balance,
74
+ token2?.decimals
75
+ );
76
+ if (totalPrice1 === totalPrice2) {
77
+ return t1.balance === t2.balance ? CreditAccountDataUtils.tokensAbcComparator(token1, token2) : CreditAccountDataUtils.amountAbcComparator(t1.balance, t2.balance);
78
+ }
79
+ return CreditAccountDataUtils.amountAbcComparator(totalPrice1, totalPrice2);
80
+ }
81
+ static tokensAbcComparator(t1, t2) {
82
+ const { symbol: symbol1 = "" } = t1 || {};
83
+ const { symbol: symbol2 = "" } = t2 || {};
84
+ const symbol1LC = symbol1.toLowerCase();
85
+ const symbol2LC = symbol2.toLowerCase();
86
+ if (symbol1LC === symbol2LC) return 0;
87
+ return symbol1LC > symbol2LC ? 1 : -1;
88
+ }
89
+ static amountAbcComparator(t1, t2) {
90
+ return t1 > t2 ? -1 : 1;
91
+ }
92
+ static calcMaxDebtIncrease(healthFactor, debt, underlyingLT, minHf = Number(import__.PERCENTAGE_FACTOR)) {
93
+ const result = debt * BigInt(healthFactor - minHf) / BigInt(minHf - underlyingLT);
94
+ return import__.BigIntMath.max(0n, result);
95
+ }
96
+ static calcMaxLendingDebt({
97
+ assets,
98
+ liquidationThresholds,
99
+ underlyingToken,
100
+ prices,
101
+ tokensList,
102
+ targetHF = import__.PERCENTAGE_FACTOR
103
+ }) {
104
+ const assetsLTMoney = assets.reduce(
105
+ (acc, { token: tokenAddress, balance: amount }) => {
106
+ const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
107
+ const lt = liquidationThresholds[tokenAddress] || 0n;
108
+ const price = prices[tokenAddress] || 0n;
109
+ const tokenMoney = import__.PriceUtils.calcTotalPrice(
110
+ price,
111
+ amount,
112
+ tokenDecimals
113
+ );
114
+ const tokenLtMoney = tokenMoney * lt;
115
+ return acc + tokenLtMoney;
116
+ },
117
+ 0n
118
+ );
119
+ const underlyingPrice = prices[underlyingToken] || 0n;
120
+ const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
121
+ const max = underlyingPrice > 0 ? assetsLTMoney * 10n ** BigInt(underlyingDecimals) / underlyingPrice / targetHF / 10n ** BigInt(import__.WAD_DECIMALS_POW - import__.PRICE_DECIMALS_POW) : 0n;
122
+ return max;
123
+ }
124
+ // [
125
+ // Sum(amount_i * price_i * apy_i - quota_i * quotaPrice * quotaRate_i * (1 + feeInterest)) -
126
+ // debt * debtPrice * baseRateWithFee
127
+ // ] / (totalValue - debt) * debtPrice
128
+ static calcOverallAPY({
129
+ caAssets,
130
+ lpAPY,
131
+ prices,
132
+ quotas,
133
+ quotaRates,
134
+ feeInterest,
135
+ totalValue,
136
+ debt,
137
+ baseRateWithFee,
138
+ underlyingToken,
139
+ tokensList
140
+ }) {
141
+ if (!lpAPY || !totalValue || totalValue <= 0n || !debt || totalValue <= debt)
142
+ return void 0;
143
+ const underlyingTokenDecimals = tokensList[underlyingToken]?.decimals || 18;
144
+ const underlyingPrice = prices[underlyingToken];
145
+ const assetAPYMoney = caAssets.reduce(
146
+ (acc, { token: tokenAddress, balance: amount }) => {
147
+ const apy = lpAPY[tokenAddress] || 0;
148
+ const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
149
+ const price = prices[tokenAddress] || 0n;
150
+ const money = import__.PriceUtils.calcTotalPrice(price, amount, tokenDecimals);
151
+ const apyMoney = money * BigInt(apy);
152
+ const { rate: quotaAPY = 0n, isActive = false } = quotaRates?.[tokenAddress] || {};
153
+ const { balance: quotaBalance = 0n } = quotas[tokenAddress] || {};
154
+ const quotaAmount = isActive ? quotaBalance : 0n;
155
+ const quotaMoney = import__.PriceUtils.calcTotalPrice(
156
+ underlyingPrice || 0n,
157
+ quotaAmount,
158
+ underlyingTokenDecimals
159
+ );
160
+ const quotaRate = quotaAPY * (BigInt(feeInterest) + import__.PERCENTAGE_FACTOR) / import__.PERCENTAGE_FACTOR;
161
+ const quotaAPYMoney = quotaMoney * quotaRate;
162
+ return acc + apyMoney - quotaAPYMoney;
163
+ },
164
+ 0n
165
+ );
166
+ const debtMoney = import__.PriceUtils.calcTotalPrice(
167
+ underlyingPrice || 0n,
168
+ debt,
169
+ underlyingTokenDecimals
170
+ );
171
+ const debtAPYMoney = debtMoney * BigInt(baseRateWithFee);
172
+ const yourAssetsMoney = import__.PriceUtils.calcTotalPrice(
173
+ underlyingPrice || import__.PRICE_DECIMALS,
174
+ totalValue - debt,
175
+ underlyingTokenDecimals
176
+ );
177
+ const apyInPercent = (assetAPYMoney - debtAPYMoney) / yourAssetsMoney;
178
+ return apyInPercent;
179
+ }
180
+ static calcHealthFactor({
181
+ assets,
182
+ quotas,
183
+ quotasInfo,
184
+ liquidationThresholds,
185
+ underlyingToken,
186
+ debt,
187
+ prices,
188
+ tokensList
189
+ }) {
190
+ if (debt === 0n) return MAX_UINT16;
191
+ const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
192
+ const underlyingPrice = prices[underlyingToken] || 0n;
193
+ const assetMoney = assets.reduce(
194
+ (acc, { token: tokenAddress, balance: amount }) => {
195
+ const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
196
+ const lt = liquidationThresholds[tokenAddress] || 0n;
197
+ const price = prices[tokenAddress] || 0n;
198
+ const tokenMoney = import__.PriceUtils.calcTotalPrice(
199
+ price,
200
+ amount,
201
+ tokenDecimals
202
+ );
203
+ const tokenLtMoney = tokenMoney * lt / import__.PERCENTAGE_FACTOR;
204
+ const { isActive = false } = quotasInfo?.[tokenAddress] || {};
205
+ const quota = quotas[tokenAddress];
206
+ const quotaBalance = isActive ? quota?.balance || 0n : 0n;
207
+ const quotaMoney = import__.PriceUtils.calcTotalPrice(
208
+ underlyingPrice,
209
+ quotaBalance,
210
+ underlyingDecimals
211
+ );
212
+ const money = quota ? import__.BigIntMath.min(quotaMoney, tokenLtMoney) : tokenLtMoney;
213
+ return acc + money;
214
+ },
215
+ 0n
216
+ );
217
+ const borrowedMoney = import__.PriceUtils.calcTotalPrice(
218
+ underlyingPrice || import__.PRICE_DECIMALS,
219
+ debt,
220
+ underlyingDecimals
221
+ );
222
+ const hfInPercent = borrowedMoney > 0n ? assetMoney * import__.PERCENTAGE_FACTOR / borrowedMoney : 0n;
223
+ return Number(hfInPercent);
224
+ }
225
+ static roundUpQuota(quotaChange) {
226
+ return quotaChange !== import__.MIN_INT96 ? quotaChange / import__.PERCENTAGE_FACTOR * import__.PERCENTAGE_FACTOR : quotaChange;
227
+ }
228
+ static calcRecommendedQuota({
229
+ amount,
230
+ debt,
231
+ lt,
232
+ quotaReserve
233
+ }) {
234
+ const recommendedBaseQuota = import__.BigIntMath.min(
235
+ debt,
236
+ amount * lt / import__.PERCENTAGE_FACTOR
237
+ );
238
+ const recommendedQuota = recommendedBaseQuota * (import__.PERCENTAGE_FACTOR + quotaReserve) / import__.PERCENTAGE_FACTOR;
239
+ return CreditAccountDataUtils.roundUpQuota(recommendedQuota);
240
+ }
241
+ static calcDefaultQuota({ amount, lt, quotaReserve }) {
242
+ const recommendedBaseQuota = amount * lt / import__.PERCENTAGE_FACTOR;
243
+ const recommendedQuota = recommendedBaseQuota * (import__.PERCENTAGE_FACTOR + quotaReserve) / import__.PERCENTAGE_FACTOR;
244
+ return CreditAccountDataUtils.roundUpQuota(recommendedQuota);
245
+ }
246
+ static calcQuotaUpdate(props) {
247
+ const { quotas, initialQuotas, maxDebt, allowedToSpend, allowedToObtain } = props;
248
+ const quotaDecrease = Object.keys(allowedToSpend).reduce((acc, token) => {
249
+ const ch = CreditAccountDataUtils.getSingleQuotaChange(
250
+ token,
251
+ 0n,
252
+ props
253
+ );
254
+ if (ch && ch.balance < 0) acc[ch.token] = ch;
255
+ return acc;
256
+ }, {});
257
+ const quotaCap = CreditAccountDataUtils.roundUpQuota(maxDebt * 2n);
258
+ const quotaBought = Object.values(initialQuotas).reduce(
259
+ (sum, q) => sum + CreditAccountDataUtils.roundUpQuota(q?.quota || 0n),
260
+ 0n
261
+ );
262
+ const quotaReduced = Object.values(quotaDecrease).reduce((sum, q) => {
263
+ const quotaBalance = q.balance || 0n;
264
+ const safeBalance = quotaBalance === import__.MIN_INT96 ? import__.BigIntMath.neg(
265
+ CreditAccountDataUtils.roundUpQuota(
266
+ initialQuotas[q.token]?.quota || 0n
267
+ )
268
+ ) : quotaBalance;
269
+ return sum + safeBalance;
270
+ }, 0n);
271
+ const maxQuotaIncrease = CreditAccountDataUtils.roundUpQuota(
272
+ import__.BigIntMath.max(quotaCap - (quotaBought + quotaReduced), 0n)
273
+ );
274
+ const quotaIncrease = Object.keys(allowedToObtain).reduce((acc, token) => {
275
+ const ch = CreditAccountDataUtils.getSingleQuotaChange(
276
+ token,
277
+ maxQuotaIncrease,
278
+ props
279
+ );
280
+ if (ch && ch.balance > 0) acc[ch.token] = ch;
281
+ return acc;
282
+ }, {});
283
+ const quotaChange = {
284
+ ...quotaDecrease,
285
+ ...quotaIncrease
286
+ };
287
+ const desiredQuota = Object.values(quotas).reduce(
288
+ (acc, cmQuota) => {
289
+ const { token, isActive } = cmQuota;
290
+ const { quota: initialQuota = 0n } = initialQuotas[token] || {};
291
+ if (!isActive) {
292
+ acc[token] = {
293
+ balance: initialQuota,
294
+ token
295
+ };
296
+ } else {
297
+ const change = quotaChange[token]?.balance || 0n;
298
+ const quotaAfter = change === import__.MIN_INT96 ? 0n : initialQuota + change;
299
+ acc[token] = {
300
+ balance: quotaAfter,
301
+ token
302
+ };
303
+ }
304
+ return acc;
305
+ },
306
+ {}
307
+ );
308
+ return {
309
+ desiredQuota,
310
+ quotaDecrease: Object.values(quotaDecrease),
311
+ quotaIncrease: Object.values(quotaIncrease)
312
+ };
313
+ }
314
+ static getSingleQuotaChange(token, unsafeMaxQuotaIncrease, props) {
315
+ const { isActive = false } = props.quotas[token] || {};
316
+ const { quota: unsafeInitialQuota = 0n } = props.initialQuotas[token] || {};
317
+ if (!isActive) {
318
+ return void 0;
319
+ }
320
+ const assetAfter = props.assetsAfterUpdate[token];
321
+ const { amountInTarget = 0n } = assetAfter || {};
322
+ const lt = props.liquidationThresholds[token] || 0n;
323
+ const maxQuotaIncrease = CreditAccountDataUtils.roundUpQuota(
324
+ unsafeMaxQuotaIncrease
325
+ );
326
+ const initialQuota = CreditAccountDataUtils.roundUpQuota(unsafeInitialQuota);
327
+ const defaultQuota = props.calcModification?.type === "recommendedQuota" && props.calcModification.debt > 0 ? CreditAccountDataUtils.calcRecommendedQuota({
328
+ lt,
329
+ quotaReserve: props.quotaReserve,
330
+ amount: amountInTarget,
331
+ debt: props.calcModification.debt
332
+ }) : CreditAccountDataUtils.calcDefaultQuota({
333
+ lt,
334
+ quotaReserve: props.quotaReserve,
335
+ amount: amountInTarget
336
+ });
337
+ const unsafeQuotaChange = CreditAccountDataUtils.roundUpQuota(
338
+ defaultQuota - initialQuota
339
+ );
340
+ const quotaChange = unsafeQuotaChange > 0 ? import__.BigIntMath.min(maxQuotaIncrease, unsafeQuotaChange) : unsafeQuotaChange < 0 && import__.BigIntMath.abs(unsafeQuotaChange) >= initialQuota ? import__.MIN_INT96 : unsafeQuotaChange;
341
+ const correctIncrease = assetAfter && props.allowedToObtain[token] && quotaChange > 0;
342
+ const correctDecrease = assetAfter && props.allowedToSpend[token] && quotaChange < 0;
343
+ if (correctIncrease || correctDecrease) {
344
+ return {
345
+ balance: quotaChange,
346
+ token
347
+ };
348
+ }
349
+ return void 0;
350
+ }
351
+ static calcQuotaBorrowRate({ quotas, quotaRates }) {
352
+ const totalRateBalance = Object.values(quotas).reduce(
353
+ (acc, { token, balance }) => {
354
+ const { rate = 0, isActive = false } = quotaRates?.[token] || {};
355
+ const quotaBalance = isActive ? balance : 0n;
356
+ const rateBalance = quotaBalance * BigInt(rate);
357
+ return acc + rateBalance;
358
+ },
359
+ 0n
360
+ );
361
+ return totalRateBalance;
362
+ }
363
+ static calcRelativeBaseBorrowRate({
364
+ debt,
365
+ baseRateWithFee,
366
+ assetAmountInUnderlying
367
+ }) {
368
+ return debt * BigInt(baseRateWithFee) * assetAmountInUnderlying;
369
+ }
370
+ static liquidationPrice({
371
+ liquidationThresholds,
372
+ debt,
373
+ underlyingToken,
374
+ targetToken,
375
+ assets,
376
+ tokensList
377
+ }) {
378
+ const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
379
+ const { balance: underlyingBalance = 0n } = assets[underlyingToken] || {};
380
+ const ltUnderlying = liquidationThresholds[underlyingToken] || 0n;
381
+ const effectiveDebt = (debt - underlyingBalance * ltUnderlying / import__.PERCENTAGE_FACTOR) * import__.WAD / 10n ** BigInt(underlyingDecimals);
382
+ const targetDecimals = tokensList[targetToken]?.decimals || 18;
383
+ const { balance: targetBalance = 0n } = assets[targetToken] || {};
384
+ const effectiveTargetBalance = targetBalance * import__.WAD / 10n ** BigInt(targetDecimals);
385
+ const lpLT = liquidationThresholds[targetToken] || 0n;
386
+ if (targetBalance <= 0n || lpLT <= 0n) return 0n;
387
+ return effectiveDebt * import__.PRICE_DECIMALS * import__.PERCENTAGE_FACTOR / (effectiveTargetBalance * lpLT);
388
+ }
389
+ /**
390
+ * Calculates the time remaining until liquidation for a credit account.
391
+ * @returns The time remaining until liquidation in milliseconds.
392
+ */
393
+ static getTimeToLiquidation({
394
+ healthFactor,
395
+ totalBorrowRate_debt
396
+ }) {
397
+ if (healthFactor <= import__.PERCENTAGE_FACTOR || totalBorrowRate_debt === 0n)
398
+ return null;
399
+ const HF_1 = BigInt(healthFactor) - import__.PERCENTAGE_FACTOR;
400
+ const brPerYear = BigInt(import__.SECONDS_PER_YEAR) * import__.PERCENTAGE_FACTOR * import__.PERCENTAGE_DECIMALS / totalBorrowRate_debt;
401
+ return HF_1 * brPerYear * 1000n / import__.PERCENTAGE_FACTOR;
402
+ }
403
+ }
404
+ // Annotate the CommonJS export names for ESM import in node:
405
+ 0 && (module.exports = {
406
+ CreditAccountDataUtils
407
+ });
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var formatter_exports = {};
20
30
  __export(formatter_exports, {
@@ -22,14 +32,23 @@ __export(formatter_exports, {
22
32
  formatBN: () => formatBN,
23
33
  formatBNvalue: () => formatBNvalue,
24
34
  formatDuration: () => formatDuration,
35
+ formatLeverage: () => formatLeverage,
25
36
  formatNumberToString_: () => formatNumberToString_,
37
+ formatPercentage: () => formatPercentage,
26
38
  formatTimestamp: () => formatTimestamp,
27
39
  numberWithCommas: () => numberWithCommas,
28
40
  percentFmt: () => percentFmt,
29
- toBigInt: () => toBigInt
41
+ rayToNumber: () => rayToNumber,
42
+ shortAddress: () => shortAddress,
43
+ shortHash: () => shortHash,
44
+ toBN: () => toBN,
45
+ toBigInt: () => toBigInt,
46
+ toSignificant: () => toSignificant
30
47
  });
31
48
  module.exports = __toCommonJS(formatter_exports);
32
49
  var import_date_fns = require("date-fns");
50
+ var import_decimal = __toESM(require("decimal.js-light"));
51
+ var import__ = require("../index.js");
33
52
  const toBigInt = (v) => {
34
53
  const value = typeof v === "object" && v.type === "BigNumber" ? v.hex : v.toString();
35
54
  return BigInt(value);
@@ -129,15 +148,49 @@ function formatTimestamp(timestamp, raw = true) {
129
148
  });
130
149
  return raw ? `${result} [${timestamp}]` : result;
131
150
  }
151
+ function rayToNumber(num) {
152
+ return Number(toBigInt(num) / 10n ** 21n) / 1e6;
153
+ }
154
+ function toSignificant(num, decimals, precision = 6) {
155
+ if (num === 1n) return "0";
156
+ const divider = new import_decimal.default(10).toPower(decimals);
157
+ const number = new import_decimal.default(num.toString()).div(divider);
158
+ return number.toSignificantDigits(precision, 4).toString();
159
+ }
160
+ function toBN(num, decimals) {
161
+ if (num === "") return 0n;
162
+ const multiplier = new import_decimal.default(10).toPower(decimals);
163
+ const number = new import_decimal.default(num).mul(multiplier);
164
+ return BigInt(number.toFixed(0));
165
+ }
166
+ function shortAddress(address) {
167
+ return address === void 0 ? "" : `${address.slice(0, 6)}...${address.slice(address.length - 4)}`;
168
+ }
169
+ function shortHash(address) {
170
+ return address === void 0 ? "" : `${address.slice(0, 5)}...`;
171
+ }
172
+ function formatPercentage(healthFactor, decimals = 2) {
173
+ return (healthFactor / Number(import__.PERCENTAGE_FACTOR)).toFixed(decimals);
174
+ }
175
+ function formatLeverage(leverage, decimals = 2) {
176
+ return (leverage / Number(import__.LEVERAGE_DECIMALS)).toFixed(decimals);
177
+ }
132
178
  // Annotate the CommonJS export names for ESM import in node:
133
179
  0 && (module.exports = {
134
180
  fmtBinaryMask,
135
181
  formatBN,
136
182
  formatBNvalue,
137
183
  formatDuration,
184
+ formatLeverage,
138
185
  formatNumberToString_,
186
+ formatPercentage,
139
187
  formatTimestamp,
140
188
  numberWithCommas,
141
189
  percentFmt,
142
- toBigInt
190
+ rayToNumber,
191
+ shortAddress,
192
+ shortHash,
193
+ toBN,
194
+ toBigInt,
195
+ toSignificant
143
196
  });