@gearbox-protocol/sdk 13.0.0-beta.1 → 13.0.0-beta.3
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.
- package/dist/cjs/sdk/utils/assetsMath.js +149 -0
- package/dist/cjs/sdk/utils/bigintMath.js +33 -0
- package/dist/cjs/sdk/utils/creditAccount.js +409 -0
- package/dist/cjs/sdk/utils/endpoints.js +71 -0
- package/dist/cjs/sdk/utils/formatter.js +55 -2
- package/dist/cjs/sdk/utils/index.js +10 -0
- package/dist/cjs/sdk/utils/priceMath.js +35 -0
- package/dist/esm/sdk/utils/assetsMath.js +125 -0
- package/dist/esm/sdk/utils/bigintMath.js +9 -0
- package/dist/esm/sdk/utils/creditAccount.js +396 -0
- package/dist/esm/sdk/utils/endpoints.js +46 -0
- package/dist/esm/sdk/utils/formatter.js +37 -1
- package/dist/esm/sdk/utils/index.js +5 -0
- package/dist/esm/sdk/utils/priceMath.js +11 -0
- package/dist/types/sdk/utils/assetsMath.d.ts +42 -0
- package/dist/types/sdk/utils/bigintMath.d.ts +6 -0
- package/dist/types/sdk/utils/creditAccount.d.ts +128 -0
- package/dist/types/sdk/utils/endpoints.d.ts +19 -0
- package/dist/types/sdk/utils/formatter.d.ts +9 -0
- package/dist/types/sdk/utils/index.d.ts +5 -0
- package/dist/types/sdk/utils/priceMath.d.ts +9 -0
- package/package.json +1 -1
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BigIntMath,
|
|
3
|
+
MIN_INT96,
|
|
4
|
+
PERCENTAGE_DECIMALS,
|
|
5
|
+
PERCENTAGE_FACTOR,
|
|
6
|
+
PRICE_DECIMALS,
|
|
7
|
+
PRICE_DECIMALS_POW,
|
|
8
|
+
PriceUtils,
|
|
9
|
+
SECONDS_PER_YEAR,
|
|
10
|
+
WAD,
|
|
11
|
+
WAD_DECIMALS_POW
|
|
12
|
+
} from "../index.js";
|
|
13
|
+
const MAX_UINT16 = 65535;
|
|
14
|
+
class CreditAccountDataUtils {
|
|
15
|
+
constructor() {
|
|
16
|
+
}
|
|
17
|
+
static sortBalances(balances, prices, tokens) {
|
|
18
|
+
return Object.entries(balances).sort(
|
|
19
|
+
([addr1, amount1], [addr2, amount2]) => {
|
|
20
|
+
return CreditAccountDataUtils.assetComparator(
|
|
21
|
+
{
|
|
22
|
+
token: addr1,
|
|
23
|
+
balance: amount1
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
token: addr2,
|
|
27
|
+
balance: amount2
|
|
28
|
+
},
|
|
29
|
+
prices,
|
|
30
|
+
prices,
|
|
31
|
+
tokens,
|
|
32
|
+
tokens
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
static sortAssets(balances, prices, tokens) {
|
|
38
|
+
return [...balances].sort(
|
|
39
|
+
(t1, t2) => CreditAccountDataUtils.assetComparator(
|
|
40
|
+
t1,
|
|
41
|
+
t2,
|
|
42
|
+
prices,
|
|
43
|
+
prices,
|
|
44
|
+
tokens,
|
|
45
|
+
tokens
|
|
46
|
+
)
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
static assetComparator(t1, t2, prices1, prices2, tokens1, tokens2) {
|
|
50
|
+
const addr1Lc = t1.token.toLowerCase();
|
|
51
|
+
const addr2Lc = t2.token.toLowerCase();
|
|
52
|
+
const token1 = tokens1?.[addr1Lc];
|
|
53
|
+
const token2 = tokens2?.[addr2Lc];
|
|
54
|
+
const price1 = prices1?.[addr1Lc] || PRICE_DECIMALS;
|
|
55
|
+
const price2 = prices2?.[addr2Lc] || PRICE_DECIMALS;
|
|
56
|
+
const totalPrice1 = PriceUtils.calcTotalPrice(
|
|
57
|
+
price1,
|
|
58
|
+
t1.balance,
|
|
59
|
+
token1?.decimals
|
|
60
|
+
);
|
|
61
|
+
const totalPrice2 = PriceUtils.calcTotalPrice(
|
|
62
|
+
price2,
|
|
63
|
+
t2.balance,
|
|
64
|
+
token2?.decimals
|
|
65
|
+
);
|
|
66
|
+
if (totalPrice1 === totalPrice2) {
|
|
67
|
+
return t1.balance === t2.balance ? CreditAccountDataUtils.tokensAbcComparator(token1, token2) : CreditAccountDataUtils.amountAbcComparator(t1.balance, t2.balance);
|
|
68
|
+
}
|
|
69
|
+
return CreditAccountDataUtils.amountAbcComparator(totalPrice1, totalPrice2);
|
|
70
|
+
}
|
|
71
|
+
static tokensAbcComparator(t1, t2) {
|
|
72
|
+
const { symbol: symbol1 = "" } = t1 || {};
|
|
73
|
+
const { symbol: symbol2 = "" } = t2 || {};
|
|
74
|
+
const symbol1LC = symbol1.toLowerCase();
|
|
75
|
+
const symbol2LC = symbol2.toLowerCase();
|
|
76
|
+
if (symbol1LC === symbol2LC) return 0;
|
|
77
|
+
return symbol1LC > symbol2LC ? 1 : -1;
|
|
78
|
+
}
|
|
79
|
+
static amountAbcComparator(t1, t2) {
|
|
80
|
+
return t1 > t2 ? -1 : 1;
|
|
81
|
+
}
|
|
82
|
+
static calcMaxDebtIncrease(healthFactor, debt, underlyingLT, minHf = Number(PERCENTAGE_FACTOR)) {
|
|
83
|
+
const result = debt * BigInt(healthFactor - minHf) / BigInt(minHf - underlyingLT);
|
|
84
|
+
return BigIntMath.max(0n, result);
|
|
85
|
+
}
|
|
86
|
+
static calcMaxLendingDebt({
|
|
87
|
+
assets,
|
|
88
|
+
liquidationThresholds,
|
|
89
|
+
underlyingToken,
|
|
90
|
+
prices,
|
|
91
|
+
tokensList,
|
|
92
|
+
targetHF = PERCENTAGE_FACTOR
|
|
93
|
+
}) {
|
|
94
|
+
const assetsLTMoney = assets.reduce(
|
|
95
|
+
(acc, { token: tokenAddress, balance: amount }) => {
|
|
96
|
+
const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
|
|
97
|
+
const lt = liquidationThresholds[tokenAddress] || 0n;
|
|
98
|
+
const price = prices[tokenAddress] || 0n;
|
|
99
|
+
const tokenMoney = PriceUtils.calcTotalPrice(
|
|
100
|
+
price,
|
|
101
|
+
amount,
|
|
102
|
+
tokenDecimals
|
|
103
|
+
);
|
|
104
|
+
const tokenLtMoney = tokenMoney * lt;
|
|
105
|
+
return acc + tokenLtMoney;
|
|
106
|
+
},
|
|
107
|
+
0n
|
|
108
|
+
);
|
|
109
|
+
const underlyingPrice = prices[underlyingToken] || 0n;
|
|
110
|
+
const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
|
|
111
|
+
const max = underlyingPrice > 0 ? assetsLTMoney * 10n ** BigInt(underlyingDecimals) / underlyingPrice / targetHF / 10n ** BigInt(WAD_DECIMALS_POW - PRICE_DECIMALS_POW) : 0n;
|
|
112
|
+
return max;
|
|
113
|
+
}
|
|
114
|
+
// [
|
|
115
|
+
// Sum(amount_i * price_i * apy_i - quota_i * quotaPrice * quotaRate_i * (1 + feeInterest)) -
|
|
116
|
+
// debt * debtPrice * baseRateWithFee
|
|
117
|
+
// ] / (totalValue - debt) * debtPrice
|
|
118
|
+
static calcOverallAPY({
|
|
119
|
+
caAssets,
|
|
120
|
+
lpAPY,
|
|
121
|
+
prices,
|
|
122
|
+
quotas,
|
|
123
|
+
quotaRates,
|
|
124
|
+
feeInterest,
|
|
125
|
+
totalValue,
|
|
126
|
+
debt,
|
|
127
|
+
baseRateWithFee,
|
|
128
|
+
underlyingToken,
|
|
129
|
+
tokensList
|
|
130
|
+
}) {
|
|
131
|
+
if (!lpAPY || !totalValue || totalValue <= 0n || !debt || totalValue <= debt)
|
|
132
|
+
return void 0;
|
|
133
|
+
const underlyingTokenDecimals = tokensList[underlyingToken]?.decimals || 18;
|
|
134
|
+
const underlyingPrice = prices[underlyingToken];
|
|
135
|
+
const assetAPYMoney = caAssets.reduce(
|
|
136
|
+
(acc, { token: tokenAddress, balance: amount }) => {
|
|
137
|
+
const apy = lpAPY[tokenAddress] || 0;
|
|
138
|
+
const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
|
|
139
|
+
const price = prices[tokenAddress] || 0n;
|
|
140
|
+
const money = PriceUtils.calcTotalPrice(price, amount, tokenDecimals);
|
|
141
|
+
const apyMoney = money * BigInt(apy);
|
|
142
|
+
const { rate: quotaAPY = 0n, isActive = false } = quotaRates?.[tokenAddress] || {};
|
|
143
|
+
const { balance: quotaBalance = 0n } = quotas[tokenAddress] || {};
|
|
144
|
+
const quotaAmount = isActive ? quotaBalance : 0n;
|
|
145
|
+
const quotaMoney = PriceUtils.calcTotalPrice(
|
|
146
|
+
underlyingPrice || 0n,
|
|
147
|
+
quotaAmount,
|
|
148
|
+
underlyingTokenDecimals
|
|
149
|
+
);
|
|
150
|
+
const quotaRate = quotaAPY * (BigInt(feeInterest) + PERCENTAGE_FACTOR) / PERCENTAGE_FACTOR;
|
|
151
|
+
const quotaAPYMoney = quotaMoney * quotaRate;
|
|
152
|
+
return acc + apyMoney - quotaAPYMoney;
|
|
153
|
+
},
|
|
154
|
+
0n
|
|
155
|
+
);
|
|
156
|
+
const debtMoney = PriceUtils.calcTotalPrice(
|
|
157
|
+
underlyingPrice || 0n,
|
|
158
|
+
debt,
|
|
159
|
+
underlyingTokenDecimals
|
|
160
|
+
);
|
|
161
|
+
const debtAPYMoney = debtMoney * BigInt(baseRateWithFee);
|
|
162
|
+
const yourAssetsMoney = PriceUtils.calcTotalPrice(
|
|
163
|
+
underlyingPrice || PRICE_DECIMALS,
|
|
164
|
+
totalValue - debt,
|
|
165
|
+
underlyingTokenDecimals
|
|
166
|
+
);
|
|
167
|
+
const apyInPercent = (assetAPYMoney - debtAPYMoney) / yourAssetsMoney;
|
|
168
|
+
return apyInPercent;
|
|
169
|
+
}
|
|
170
|
+
static calcHealthFactor({
|
|
171
|
+
assets,
|
|
172
|
+
quotas,
|
|
173
|
+
quotasInfo,
|
|
174
|
+
liquidationThresholds,
|
|
175
|
+
underlyingToken,
|
|
176
|
+
debt,
|
|
177
|
+
prices,
|
|
178
|
+
tokensList
|
|
179
|
+
}) {
|
|
180
|
+
if (debt === 0n) return MAX_UINT16;
|
|
181
|
+
const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
|
|
182
|
+
const underlyingPrice = prices[underlyingToken] || 0n;
|
|
183
|
+
const assetMoney = assets.reduce(
|
|
184
|
+
(acc, { token: tokenAddress, balance: amount }) => {
|
|
185
|
+
const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
|
|
186
|
+
const lt = liquidationThresholds[tokenAddress] || 0n;
|
|
187
|
+
const price = prices[tokenAddress] || 0n;
|
|
188
|
+
const tokenMoney = PriceUtils.calcTotalPrice(
|
|
189
|
+
price,
|
|
190
|
+
amount,
|
|
191
|
+
tokenDecimals
|
|
192
|
+
);
|
|
193
|
+
const tokenLtMoney = tokenMoney * lt / PERCENTAGE_FACTOR;
|
|
194
|
+
const { isActive = false } = quotasInfo?.[tokenAddress] || {};
|
|
195
|
+
const quota = quotas[tokenAddress];
|
|
196
|
+
const quotaBalance = isActive ? quota?.balance || 0n : 0n;
|
|
197
|
+
const quotaMoney = PriceUtils.calcTotalPrice(
|
|
198
|
+
underlyingPrice,
|
|
199
|
+
quotaBalance,
|
|
200
|
+
underlyingDecimals
|
|
201
|
+
);
|
|
202
|
+
const money = quota ? BigIntMath.min(quotaMoney, tokenLtMoney) : tokenLtMoney;
|
|
203
|
+
return acc + money;
|
|
204
|
+
},
|
|
205
|
+
0n
|
|
206
|
+
);
|
|
207
|
+
const borrowedMoney = PriceUtils.calcTotalPrice(
|
|
208
|
+
underlyingPrice || PRICE_DECIMALS,
|
|
209
|
+
debt,
|
|
210
|
+
underlyingDecimals
|
|
211
|
+
);
|
|
212
|
+
const hfInPercent = borrowedMoney > 0n ? assetMoney * PERCENTAGE_FACTOR / borrowedMoney : 0n;
|
|
213
|
+
return Number(hfInPercent);
|
|
214
|
+
}
|
|
215
|
+
static roundUpQuota(quotaChange) {
|
|
216
|
+
return quotaChange !== MIN_INT96 ? quotaChange / PERCENTAGE_FACTOR * PERCENTAGE_FACTOR : quotaChange;
|
|
217
|
+
}
|
|
218
|
+
static calcRecommendedQuota({
|
|
219
|
+
amount,
|
|
220
|
+
debt,
|
|
221
|
+
lt,
|
|
222
|
+
quotaReserve
|
|
223
|
+
}) {
|
|
224
|
+
const recommendedBaseQuota = BigIntMath.min(
|
|
225
|
+
debt,
|
|
226
|
+
amount * lt / PERCENTAGE_FACTOR
|
|
227
|
+
);
|
|
228
|
+
const recommendedQuota = recommendedBaseQuota * (PERCENTAGE_FACTOR + quotaReserve) / PERCENTAGE_FACTOR;
|
|
229
|
+
return CreditAccountDataUtils.roundUpQuota(recommendedQuota);
|
|
230
|
+
}
|
|
231
|
+
static calcDefaultQuota({ amount, lt, quotaReserve }) {
|
|
232
|
+
const recommendedBaseQuota = amount * lt / PERCENTAGE_FACTOR;
|
|
233
|
+
const recommendedQuota = recommendedBaseQuota * (PERCENTAGE_FACTOR + quotaReserve) / PERCENTAGE_FACTOR;
|
|
234
|
+
return CreditAccountDataUtils.roundUpQuota(recommendedQuota);
|
|
235
|
+
}
|
|
236
|
+
static calcQuotaUpdate(props) {
|
|
237
|
+
const { quotas, initialQuotas, maxDebt, allowedToSpend, allowedToObtain } = props;
|
|
238
|
+
const quotaDecrease = Object.keys(allowedToSpend).reduce((acc, token) => {
|
|
239
|
+
const ch = CreditAccountDataUtils.getSingleQuotaChange(
|
|
240
|
+
token,
|
|
241
|
+
0n,
|
|
242
|
+
props
|
|
243
|
+
);
|
|
244
|
+
if (ch && ch.balance < 0) acc[ch.token] = ch;
|
|
245
|
+
return acc;
|
|
246
|
+
}, {});
|
|
247
|
+
const quotaCap = CreditAccountDataUtils.roundUpQuota(maxDebt * 2n);
|
|
248
|
+
const quotaBought = Object.values(initialQuotas).reduce(
|
|
249
|
+
(sum, q) => sum + CreditAccountDataUtils.roundUpQuota(q?.quota || 0n),
|
|
250
|
+
0n
|
|
251
|
+
);
|
|
252
|
+
const quotaReduced = Object.values(quotaDecrease).reduce((sum, q) => {
|
|
253
|
+
const quotaBalance = q.balance || 0n;
|
|
254
|
+
const safeBalance = quotaBalance === MIN_INT96 ? BigIntMath.neg(
|
|
255
|
+
CreditAccountDataUtils.roundUpQuota(
|
|
256
|
+
initialQuotas[q.token]?.quota || 0n
|
|
257
|
+
)
|
|
258
|
+
) : quotaBalance;
|
|
259
|
+
return sum + safeBalance;
|
|
260
|
+
}, 0n);
|
|
261
|
+
const maxQuotaIncrease = CreditAccountDataUtils.roundUpQuota(
|
|
262
|
+
BigIntMath.max(quotaCap - (quotaBought + quotaReduced), 0n)
|
|
263
|
+
);
|
|
264
|
+
const quotaIncrease = Object.keys(allowedToObtain).reduce((acc, token) => {
|
|
265
|
+
const ch = CreditAccountDataUtils.getSingleQuotaChange(
|
|
266
|
+
token,
|
|
267
|
+
maxQuotaIncrease,
|
|
268
|
+
props
|
|
269
|
+
);
|
|
270
|
+
if (ch && ch.balance > 0) acc[ch.token] = ch;
|
|
271
|
+
return acc;
|
|
272
|
+
}, {});
|
|
273
|
+
const quotaChange = {
|
|
274
|
+
...quotaDecrease,
|
|
275
|
+
...quotaIncrease
|
|
276
|
+
};
|
|
277
|
+
const desiredQuota = Object.values(quotas).reduce(
|
|
278
|
+
(acc, cmQuota) => {
|
|
279
|
+
const { token, isActive } = cmQuota;
|
|
280
|
+
const { quota: initialQuota = 0n } = initialQuotas[token] || {};
|
|
281
|
+
if (!isActive) {
|
|
282
|
+
acc[token] = {
|
|
283
|
+
balance: initialQuota,
|
|
284
|
+
token
|
|
285
|
+
};
|
|
286
|
+
} else {
|
|
287
|
+
const change = quotaChange[token]?.balance || 0n;
|
|
288
|
+
const quotaAfter = change === MIN_INT96 ? 0n : initialQuota + change;
|
|
289
|
+
acc[token] = {
|
|
290
|
+
balance: quotaAfter,
|
|
291
|
+
token
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
return acc;
|
|
295
|
+
},
|
|
296
|
+
{}
|
|
297
|
+
);
|
|
298
|
+
return {
|
|
299
|
+
desiredQuota,
|
|
300
|
+
quotaDecrease: Object.values(quotaDecrease),
|
|
301
|
+
quotaIncrease: Object.values(quotaIncrease)
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
static getSingleQuotaChange(token, unsafeMaxQuotaIncrease, props) {
|
|
305
|
+
const { isActive = false } = props.quotas[token] || {};
|
|
306
|
+
const { quota: unsafeInitialQuota = 0n } = props.initialQuotas[token] || {};
|
|
307
|
+
if (!isActive) {
|
|
308
|
+
return void 0;
|
|
309
|
+
}
|
|
310
|
+
const assetAfter = props.assetsAfterUpdate[token];
|
|
311
|
+
const { amountInTarget = 0n } = assetAfter || {};
|
|
312
|
+
const lt = props.liquidationThresholds[token] || 0n;
|
|
313
|
+
const maxQuotaIncrease = CreditAccountDataUtils.roundUpQuota(
|
|
314
|
+
unsafeMaxQuotaIncrease
|
|
315
|
+
);
|
|
316
|
+
const initialQuota = CreditAccountDataUtils.roundUpQuota(unsafeInitialQuota);
|
|
317
|
+
const defaultQuota = props.calcModification?.type === "recommendedQuota" && props.calcModification.debt > 0 ? CreditAccountDataUtils.calcRecommendedQuota({
|
|
318
|
+
lt,
|
|
319
|
+
quotaReserve: props.quotaReserve,
|
|
320
|
+
amount: amountInTarget,
|
|
321
|
+
debt: props.calcModification.debt
|
|
322
|
+
}) : CreditAccountDataUtils.calcDefaultQuota({
|
|
323
|
+
lt,
|
|
324
|
+
quotaReserve: props.quotaReserve,
|
|
325
|
+
amount: amountInTarget
|
|
326
|
+
});
|
|
327
|
+
const unsafeQuotaChange = CreditAccountDataUtils.roundUpQuota(
|
|
328
|
+
defaultQuota - initialQuota
|
|
329
|
+
);
|
|
330
|
+
const quotaChange = unsafeQuotaChange > 0 ? BigIntMath.min(maxQuotaIncrease, unsafeQuotaChange) : unsafeQuotaChange < 0 && BigIntMath.abs(unsafeQuotaChange) >= initialQuota ? MIN_INT96 : unsafeQuotaChange;
|
|
331
|
+
const correctIncrease = assetAfter && props.allowedToObtain[token] && quotaChange > 0;
|
|
332
|
+
const correctDecrease = assetAfter && props.allowedToSpend[token] && quotaChange < 0;
|
|
333
|
+
if (correctIncrease || correctDecrease) {
|
|
334
|
+
return {
|
|
335
|
+
balance: quotaChange,
|
|
336
|
+
token
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
return void 0;
|
|
340
|
+
}
|
|
341
|
+
static calcQuotaBorrowRate({ quotas, quotaRates }) {
|
|
342
|
+
const totalRateBalance = Object.values(quotas).reduce(
|
|
343
|
+
(acc, { token, balance }) => {
|
|
344
|
+
const { rate = 0, isActive = false } = quotaRates?.[token] || {};
|
|
345
|
+
const quotaBalance = isActive ? balance : 0n;
|
|
346
|
+
const rateBalance = quotaBalance * BigInt(rate);
|
|
347
|
+
return acc + rateBalance;
|
|
348
|
+
},
|
|
349
|
+
0n
|
|
350
|
+
);
|
|
351
|
+
return totalRateBalance;
|
|
352
|
+
}
|
|
353
|
+
static calcRelativeBaseBorrowRate({
|
|
354
|
+
debt,
|
|
355
|
+
baseRateWithFee,
|
|
356
|
+
assetAmountInUnderlying
|
|
357
|
+
}) {
|
|
358
|
+
return debt * BigInt(baseRateWithFee) * assetAmountInUnderlying;
|
|
359
|
+
}
|
|
360
|
+
static liquidationPrice({
|
|
361
|
+
liquidationThresholds,
|
|
362
|
+
debt,
|
|
363
|
+
underlyingToken,
|
|
364
|
+
targetToken,
|
|
365
|
+
assets,
|
|
366
|
+
tokensList
|
|
367
|
+
}) {
|
|
368
|
+
const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
|
|
369
|
+
const { balance: underlyingBalance = 0n } = assets[underlyingToken] || {};
|
|
370
|
+
const ltUnderlying = liquidationThresholds[underlyingToken] || 0n;
|
|
371
|
+
const effectiveDebt = (debt - underlyingBalance * ltUnderlying / PERCENTAGE_FACTOR) * WAD / 10n ** BigInt(underlyingDecimals);
|
|
372
|
+
const targetDecimals = tokensList[targetToken]?.decimals || 18;
|
|
373
|
+
const { balance: targetBalance = 0n } = assets[targetToken] || {};
|
|
374
|
+
const effectiveTargetBalance = targetBalance * WAD / 10n ** BigInt(targetDecimals);
|
|
375
|
+
const lpLT = liquidationThresholds[targetToken] || 0n;
|
|
376
|
+
if (targetBalance <= 0n || lpLT <= 0n) return 0n;
|
|
377
|
+
return effectiveDebt * PRICE_DECIMALS * PERCENTAGE_FACTOR / (effectiveTargetBalance * lpLT);
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Calculates the time remaining until liquidation for a credit account.
|
|
381
|
+
* @returns The time remaining until liquidation in milliseconds.
|
|
382
|
+
*/
|
|
383
|
+
static getTimeToLiquidation({
|
|
384
|
+
healthFactor,
|
|
385
|
+
totalBorrowRate_debt
|
|
386
|
+
}) {
|
|
387
|
+
if (healthFactor <= PERCENTAGE_FACTOR || totalBorrowRate_debt === 0n)
|
|
388
|
+
return null;
|
|
389
|
+
const HF_1 = BigInt(healthFactor) - PERCENTAGE_FACTOR;
|
|
390
|
+
const brPerYear = BigInt(SECONDS_PER_YEAR) * PERCENTAGE_FACTOR * PERCENTAGE_DECIMALS / totalBorrowRate_debt;
|
|
391
|
+
return HF_1 * brPerYear * 1000n / PERCENTAGE_FACTOR;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
export {
|
|
395
|
+
CreditAccountDataUtils
|
|
396
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { isSupportedNetwork } from "../index.js";
|
|
2
|
+
const CHARTS_BACKEND_ADDRESS = "https://charts-server.fly.dev";
|
|
3
|
+
const STATIC_TOKEN = "https://static.gearbox.finance/tokens/";
|
|
4
|
+
class GearboxBackendApi {
|
|
5
|
+
constructor() {
|
|
6
|
+
}
|
|
7
|
+
static getChartsUrl = (url, chainId, options = { params: {} }, priceSource) => {
|
|
8
|
+
const domain = CHARTS_BACKEND_ADDRESS;
|
|
9
|
+
const priceSourceArr = priceSource ? [priceSource] : [];
|
|
10
|
+
const isMain = isSupportedNetwork(chainId);
|
|
11
|
+
const relativePath = URLApi.getRelativeUrl(
|
|
12
|
+
url,
|
|
13
|
+
isMain ? {
|
|
14
|
+
...options,
|
|
15
|
+
params: { ...options.params, chainId }
|
|
16
|
+
} : options
|
|
17
|
+
);
|
|
18
|
+
return [domain, "api", ...priceSourceArr, relativePath].join("/");
|
|
19
|
+
};
|
|
20
|
+
static getStaticTokenUrl = () => STATIC_TOKEN;
|
|
21
|
+
static getRewardsMerkleUrl = (network, root, account) => {
|
|
22
|
+
const path = `${network}_${root.slice(2)}/${account.slice(2, 4)}`;
|
|
23
|
+
const url = `https://am.gearbox.finance/${path.toLowerCase()}.json`;
|
|
24
|
+
return url;
|
|
25
|
+
};
|
|
26
|
+
static getNFTMerkleUrl = (network, root) => {
|
|
27
|
+
const url = `https://dm.gearbox.finance/${network.toLowerCase()}_${root}.json`;
|
|
28
|
+
return url;
|
|
29
|
+
};
|
|
30
|
+
static apyAllRewards = () => URLApi.getRelativeUrl(
|
|
31
|
+
"https://state-cache.gearbox.foundation/apy-server/latest.json"
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
class URLApi {
|
|
35
|
+
constructor() {
|
|
36
|
+
}
|
|
37
|
+
static getRelativeUrl = (url, options) => {
|
|
38
|
+
const { params = {} } = options || {};
|
|
39
|
+
const paramsString = Object.entries(params).map(([key, value]) => `${key}=${value}`).join("&");
|
|
40
|
+
return [url, ...paramsString ? [paramsString] : []].join("?");
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export {
|
|
44
|
+
GearboxBackendApi,
|
|
45
|
+
URLApi
|
|
46
|
+
};
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { formatDuration as fmtDuration, intervalToDuration } from "date-fns";
|
|
2
|
+
import Decimal from "decimal.js-light";
|
|
3
|
+
import { LEVERAGE_DECIMALS, PERCENTAGE_FACTOR } from "../index.js";
|
|
2
4
|
const toBigInt = (v) => {
|
|
3
5
|
const value = typeof v === "object" && v.type === "BigNumber" ? v.hex : v.toString();
|
|
4
6
|
return BigInt(value);
|
|
@@ -98,14 +100,48 @@ function formatTimestamp(timestamp, raw = true) {
|
|
|
98
100
|
});
|
|
99
101
|
return raw ? `${result} [${timestamp}]` : result;
|
|
100
102
|
}
|
|
103
|
+
function rayToNumber(num) {
|
|
104
|
+
return Number(toBigInt(num) / 10n ** 21n) / 1e6;
|
|
105
|
+
}
|
|
106
|
+
function toSignificant(num, decimals, precision = 6) {
|
|
107
|
+
if (num === 1n) return "0";
|
|
108
|
+
const divider = new Decimal(10).toPower(decimals);
|
|
109
|
+
const number = new Decimal(num.toString()).div(divider);
|
|
110
|
+
return number.toSignificantDigits(precision, 4).toString();
|
|
111
|
+
}
|
|
112
|
+
function toBN(num, decimals) {
|
|
113
|
+
if (num === "") return 0n;
|
|
114
|
+
const multiplier = new Decimal(10).toPower(decimals);
|
|
115
|
+
const number = new Decimal(num).mul(multiplier);
|
|
116
|
+
return BigInt(number.toFixed(0));
|
|
117
|
+
}
|
|
118
|
+
function shortAddress(address) {
|
|
119
|
+
return address === void 0 ? "" : `${address.slice(0, 6)}...${address.slice(address.length - 4)}`;
|
|
120
|
+
}
|
|
121
|
+
function shortHash(address) {
|
|
122
|
+
return address === void 0 ? "" : `${address.slice(0, 5)}...`;
|
|
123
|
+
}
|
|
124
|
+
function formatPercentage(healthFactor, decimals = 2) {
|
|
125
|
+
return (healthFactor / Number(PERCENTAGE_FACTOR)).toFixed(decimals);
|
|
126
|
+
}
|
|
127
|
+
function formatLeverage(leverage, decimals = 2) {
|
|
128
|
+
return (leverage / Number(LEVERAGE_DECIMALS)).toFixed(decimals);
|
|
129
|
+
}
|
|
101
130
|
export {
|
|
102
131
|
fmtBinaryMask,
|
|
103
132
|
formatBN,
|
|
104
133
|
formatBNvalue,
|
|
105
134
|
formatDuration,
|
|
135
|
+
formatLeverage,
|
|
106
136
|
formatNumberToString_,
|
|
137
|
+
formatPercentage,
|
|
107
138
|
formatTimestamp,
|
|
108
139
|
numberWithCommas,
|
|
109
140
|
percentFmt,
|
|
110
|
-
|
|
141
|
+
rayToNumber,
|
|
142
|
+
shortAddress,
|
|
143
|
+
shortHash,
|
|
144
|
+
toBN,
|
|
145
|
+
toBigInt,
|
|
146
|
+
toSignificant
|
|
111
147
|
};
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
export * from "./AddressMap.js";
|
|
2
2
|
export * from "./AddressSet.js";
|
|
3
3
|
export * from "./abi-decode.js";
|
|
4
|
+
export * from "./assetsMath.js";
|
|
5
|
+
export * from "./bigintMath.js";
|
|
4
6
|
export * from "./bytes32ToString.js";
|
|
5
7
|
export * from "./childLogger.js";
|
|
6
8
|
export * from "./createRawTx.js";
|
|
9
|
+
export * from "./creditAccount.js";
|
|
10
|
+
export * from "./endpoints.js";
|
|
7
11
|
export * from "./etherscan.js";
|
|
8
12
|
export * from "./filterDust.js";
|
|
9
13
|
export * from "./formatter.js";
|
|
@@ -11,6 +15,7 @@ export * from "./hex.js";
|
|
|
11
15
|
export * from "./isDust.js";
|
|
12
16
|
export * from "./json.js";
|
|
13
17
|
export * from "./mappers.js";
|
|
18
|
+
export * from "./priceMath.js";
|
|
14
19
|
export * from "./retry.js";
|
|
15
20
|
export * from "./toAddress.js";
|
|
16
21
|
export * from "./type-utils.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { PRICE_DECIMALS, WAD } from "../index.js";
|
|
2
|
+
class PriceUtils {
|
|
3
|
+
static calcTotalPrice = (price, amount, decimals = 18) => amount * WAD * price / 10n ** BigInt(decimals) / PRICE_DECIMALS;
|
|
4
|
+
static convertByPrice(totalMoney, { price: targetPrice, decimals: targetDecimals = 18 }) {
|
|
5
|
+
if (targetPrice <= 0n) return 0n;
|
|
6
|
+
return totalMoney * 10n ** BigInt(targetDecimals) * PRICE_DECIMALS / targetPrice / WAD;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export {
|
|
10
|
+
PriceUtils
|
|
11
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Address } from "viem";
|
|
2
|
+
import { type Asset } from "../index.js";
|
|
3
|
+
interface TokenDataSlice {
|
|
4
|
+
symbol: string;
|
|
5
|
+
decimals: number;
|
|
6
|
+
}
|
|
7
|
+
export interface AssetWithView extends Asset {
|
|
8
|
+
balanceView: string;
|
|
9
|
+
}
|
|
10
|
+
export interface AssetWithAmountInTarget extends Asset {
|
|
11
|
+
amountInTarget: bigint;
|
|
12
|
+
}
|
|
13
|
+
interface NextAssetProps<T extends Asset> {
|
|
14
|
+
allowedTokens: Array<Address>;
|
|
15
|
+
selectedAssets: Array<T>;
|
|
16
|
+
balances: Record<Address, bigint>;
|
|
17
|
+
tokensList: Record<Address, TokenDataSlice>;
|
|
18
|
+
prices?: Record<Address, bigint>;
|
|
19
|
+
}
|
|
20
|
+
export type WrapResult = [Array<Asset>, bigint, bigint];
|
|
21
|
+
export declare class AssetUtils {
|
|
22
|
+
static nextAsset<T extends Asset>({ allowedTokens, selectedAssets, balances, tokensList, prices, }: NextAssetProps<T>): Address | undefined;
|
|
23
|
+
private static getBalances;
|
|
24
|
+
static constructAssetRecord<A extends Asset>(a: Array<A>): Record<`0x${string}`, A>;
|
|
25
|
+
static memoWrap: (unwrappedAddress: Address, wrappedAddress: Address, prices: Record<Address, bigint>, tokensList: Record<Address, TokenDataSlice>) => (assets: Array<Asset>) => WrapResult;
|
|
26
|
+
/**
|
|
27
|
+
* Sums the the second assets list into the first assets list
|
|
28
|
+
* Balances cant be negative; creates new assets.
|
|
29
|
+
*/
|
|
30
|
+
static sumAssets<A extends Asset, B extends Asset>(a: Array<A>, b: Array<B>): Array<A | B>;
|
|
31
|
+
/**
|
|
32
|
+
* Sums the the second assets list into the first assets list
|
|
33
|
+
* Balances cant be negative; doesn't create new assets.
|
|
34
|
+
*/
|
|
35
|
+
static addBalances<A extends Asset, B extends Asset>(a: Array<A>, b: Array<B>): Array<A | B>;
|
|
36
|
+
/**
|
|
37
|
+
* Subtracts the the second assets list from the first assets list
|
|
38
|
+
* Balances cant be negative; doesn't create new assets.
|
|
39
|
+
*/
|
|
40
|
+
static subAssets<A extends Asset, B extends Asset>(a: Array<A>, b: Array<B>): Array<A>;
|
|
41
|
+
}
|
|
42
|
+
export {};
|