@gearbox-protocol/sdk 13.0.0-beta.3 → 13.0.0-beta.4

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 (53) hide show
  1. package/dist/cjs/abi/iPriceFeed.js +84 -0
  2. package/dist/cjs/permissionless/bindings/cross-chain-multisig.js +3 -3
  3. package/dist/cjs/permissionless/bindings/instance-manager.js +2 -2
  4. package/dist/cjs/plugins/adapters/contracts/MellowDepositQueueAdapterContract.js +0 -6
  5. package/dist/cjs/plugins/adapters/contracts/MellowRedeemQueueAdapterContract.js +0 -6
  6. package/dist/cjs/sdk/GearboxSDK.js +0 -2
  7. package/dist/cjs/sdk/base/BaseContract.js +5 -2
  8. package/dist/cjs/sdk/base/ChainContractsRegister.js +2 -10
  9. package/dist/cjs/sdk/base/Construct.js +25 -19
  10. package/dist/cjs/sdk/base/SDKConstruct.js +1 -1
  11. package/dist/cjs/sdk/market/adapters/PlaceholderAdapterContracts.js +16 -0
  12. package/dist/cjs/sdk/market/pricefeeds/updates/PriceUpdatesCache.js +0 -17
  13. package/dist/cjs/sdk/market/pricefeeds/updates/PythUpdater.js +1 -1
  14. package/dist/cjs/sdk/market/pricefeeds/updates/RedstoneUpdater.js +1 -1
  15. package/dist/cjs/sdk/market/pricefeeds/updates/fetchPythPayloads.js +2 -2
  16. package/dist/cjs/sdk/utils/assetsMath.js +10 -9
  17. package/dist/cjs/sdk/utils/creditAccount.js +42 -40
  18. package/dist/cjs/sdk/utils/endpoints.js +2 -2
  19. package/dist/cjs/sdk/utils/formatter.js +3 -3
  20. package/dist/cjs/sdk/utils/priceMath.js +3 -3
  21. package/dist/esm/abi/iPriceFeed.js +60 -0
  22. package/dist/esm/permissionless/bindings/cross-chain-multisig.js +3 -3
  23. package/dist/esm/permissionless/bindings/instance-manager.js +2 -2
  24. package/dist/esm/plugins/adapters/contracts/MellowDepositQueueAdapterContract.js +0 -6
  25. package/dist/esm/plugins/adapters/contracts/MellowRedeemQueueAdapterContract.js +0 -6
  26. package/dist/esm/sdk/GearboxSDK.js +0 -2
  27. package/dist/esm/sdk/base/BaseContract.js +5 -2
  28. package/dist/esm/sdk/base/ChainContractsRegister.js +2 -10
  29. package/dist/esm/sdk/base/Construct.js +25 -19
  30. package/dist/esm/sdk/base/SDKConstruct.js +1 -1
  31. package/dist/esm/sdk/market/adapters/PlaceholderAdapterContracts.js +16 -0
  32. package/dist/esm/sdk/market/pricefeeds/updates/PriceUpdatesCache.js +0 -17
  33. package/dist/esm/sdk/market/pricefeeds/updates/PythUpdater.js +1 -1
  34. package/dist/esm/sdk/market/pricefeeds/updates/RedstoneUpdater.js +1 -1
  35. package/dist/esm/sdk/market/pricefeeds/updates/fetchPythPayloads.js +2 -2
  36. package/dist/esm/sdk/utils/assetsMath.js +2 -1
  37. package/dist/esm/sdk/utils/creditAccount.js +3 -3
  38. package/dist/esm/sdk/utils/endpoints.js +1 -1
  39. package/dist/esm/sdk/utils/formatter.js +1 -1
  40. package/dist/esm/sdk/utils/priceMath.js +1 -1
  41. package/dist/types/abi/iPriceFeed.d.ts +87 -0
  42. package/dist/types/permissionless/bindings/cross-chain-multisig.d.ts +3 -3
  43. package/dist/types/permissionless/bindings/instance-manager.d.ts +3 -3
  44. package/dist/types/plugins/adapters/contracts/MellowDepositQueueAdapterContract.d.ts +1 -4
  45. package/dist/types/plugins/adapters/contracts/MellowRedeemQueueAdapterContract.d.ts +1 -4
  46. package/dist/types/sdk/base/ChainContractsRegister.d.ts +0 -2
  47. package/dist/types/sdk/base/Construct.d.ts +7 -10
  48. package/dist/types/sdk/market/adapters/PlaceholderAdapterContracts.d.ts +2 -1
  49. package/dist/types/sdk/market/pricefeeds/updates/PriceUpdatesCache.d.ts +1 -8
  50. package/dist/types/sdk/utils/assetsMath.d.ts +1 -1
  51. package/dist/types/sdk/utils/creditAccount.d.ts +1 -1
  52. package/dist/types/sdk/utils/endpoints.d.ts +1 -1
  53. package/package.json +6 -2
@@ -21,7 +21,9 @@ __export(creditAccount_exports, {
21
21
  CreditAccountDataUtils: () => CreditAccountDataUtils
22
22
  });
23
23
  module.exports = __toCommonJS(creditAccount_exports);
24
- var import__ = require("../index.js");
24
+ var import_constants = require("../constants/index.js");
25
+ var import_bigintMath = require("./bigintMath.js");
26
+ var import_priceMath = require("./priceMath.js");
25
27
  const MAX_UINT16 = 65535;
26
28
  class CreditAccountDataUtils {
27
29
  constructor() {
@@ -63,14 +65,14 @@ class CreditAccountDataUtils {
63
65
  const addr2Lc = t2.token.toLowerCase();
64
66
  const token1 = tokens1?.[addr1Lc];
65
67
  const token2 = tokens2?.[addr2Lc];
66
- const price1 = prices1?.[addr1Lc] || import__.PRICE_DECIMALS;
67
- const price2 = prices2?.[addr2Lc] || import__.PRICE_DECIMALS;
68
- const totalPrice1 = import__.PriceUtils.calcTotalPrice(
68
+ const price1 = prices1?.[addr1Lc] || import_constants.PRICE_DECIMALS;
69
+ const price2 = prices2?.[addr2Lc] || import_constants.PRICE_DECIMALS;
70
+ const totalPrice1 = import_priceMath.PriceUtils.calcTotalPrice(
69
71
  price1,
70
72
  t1.balance,
71
73
  token1?.decimals
72
74
  );
73
- const totalPrice2 = import__.PriceUtils.calcTotalPrice(
75
+ const totalPrice2 = import_priceMath.PriceUtils.calcTotalPrice(
74
76
  price2,
75
77
  t2.balance,
76
78
  token2?.decimals
@@ -91,9 +93,9 @@ class CreditAccountDataUtils {
91
93
  static amountAbcComparator(t1, t2) {
92
94
  return t1 > t2 ? -1 : 1;
93
95
  }
94
- static calcMaxDebtIncrease(healthFactor, debt, underlyingLT, minHf = Number(import__.PERCENTAGE_FACTOR)) {
96
+ static calcMaxDebtIncrease(healthFactor, debt, underlyingLT, minHf = Number(import_constants.PERCENTAGE_FACTOR)) {
95
97
  const result = debt * BigInt(healthFactor - minHf) / BigInt(minHf - underlyingLT);
96
- return import__.BigIntMath.max(0n, result);
98
+ return import_bigintMath.BigIntMath.max(0n, result);
97
99
  }
98
100
  static calcMaxLendingDebt({
99
101
  assets,
@@ -101,14 +103,14 @@ class CreditAccountDataUtils {
101
103
  underlyingToken,
102
104
  prices,
103
105
  tokensList,
104
- targetHF = import__.PERCENTAGE_FACTOR
106
+ targetHF = import_constants.PERCENTAGE_FACTOR
105
107
  }) {
106
108
  const assetsLTMoney = assets.reduce(
107
109
  (acc, { token: tokenAddress, balance: amount }) => {
108
110
  const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
109
111
  const lt = liquidationThresholds[tokenAddress] || 0n;
110
112
  const price = prices[tokenAddress] || 0n;
111
- const tokenMoney = import__.PriceUtils.calcTotalPrice(
113
+ const tokenMoney = import_priceMath.PriceUtils.calcTotalPrice(
112
114
  price,
113
115
  amount,
114
116
  tokenDecimals
@@ -120,7 +122,7 @@ class CreditAccountDataUtils {
120
122
  );
121
123
  const underlyingPrice = prices[underlyingToken] || 0n;
122
124
  const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
123
- const max = underlyingPrice > 0 ? assetsLTMoney * 10n ** BigInt(underlyingDecimals) / underlyingPrice / targetHF / 10n ** BigInt(import__.WAD_DECIMALS_POW - import__.PRICE_DECIMALS_POW) : 0n;
125
+ const max = underlyingPrice > 0 ? assetsLTMoney * 10n ** BigInt(underlyingDecimals) / underlyingPrice / targetHF / 10n ** BigInt(import_constants.WAD_DECIMALS_POW - import_constants.PRICE_DECIMALS_POW) : 0n;
124
126
  return max;
125
127
  }
126
128
  // [
@@ -149,30 +151,30 @@ class CreditAccountDataUtils {
149
151
  const apy = lpAPY[tokenAddress] || 0;
150
152
  const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
151
153
  const price = prices[tokenAddress] || 0n;
152
- const money = import__.PriceUtils.calcTotalPrice(price, amount, tokenDecimals);
154
+ const money = import_priceMath.PriceUtils.calcTotalPrice(price, amount, tokenDecimals);
153
155
  const apyMoney = money * BigInt(apy);
154
156
  const { rate: quotaAPY = 0n, isActive = false } = quotaRates?.[tokenAddress] || {};
155
157
  const { balance: quotaBalance = 0n } = quotas[tokenAddress] || {};
156
158
  const quotaAmount = isActive ? quotaBalance : 0n;
157
- const quotaMoney = import__.PriceUtils.calcTotalPrice(
159
+ const quotaMoney = import_priceMath.PriceUtils.calcTotalPrice(
158
160
  underlyingPrice || 0n,
159
161
  quotaAmount,
160
162
  underlyingTokenDecimals
161
163
  );
162
- const quotaRate = quotaAPY * (BigInt(feeInterest) + import__.PERCENTAGE_FACTOR) / import__.PERCENTAGE_FACTOR;
164
+ const quotaRate = quotaAPY * (BigInt(feeInterest) + import_constants.PERCENTAGE_FACTOR) / import_constants.PERCENTAGE_FACTOR;
163
165
  const quotaAPYMoney = quotaMoney * quotaRate;
164
166
  return acc + apyMoney - quotaAPYMoney;
165
167
  },
166
168
  0n
167
169
  );
168
- const debtMoney = import__.PriceUtils.calcTotalPrice(
170
+ const debtMoney = import_priceMath.PriceUtils.calcTotalPrice(
169
171
  underlyingPrice || 0n,
170
172
  debt,
171
173
  underlyingTokenDecimals
172
174
  );
173
175
  const debtAPYMoney = debtMoney * BigInt(baseRateWithFee);
174
- const yourAssetsMoney = import__.PriceUtils.calcTotalPrice(
175
- underlyingPrice || import__.PRICE_DECIMALS,
176
+ const yourAssetsMoney = import_priceMath.PriceUtils.calcTotalPrice(
177
+ underlyingPrice || import_constants.PRICE_DECIMALS,
176
178
  totalValue - debt,
177
179
  underlyingTokenDecimals
178
180
  );
@@ -197,35 +199,35 @@ class CreditAccountDataUtils {
197
199
  const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
198
200
  const lt = liquidationThresholds[tokenAddress] || 0n;
199
201
  const price = prices[tokenAddress] || 0n;
200
- const tokenMoney = import__.PriceUtils.calcTotalPrice(
202
+ const tokenMoney = import_priceMath.PriceUtils.calcTotalPrice(
201
203
  price,
202
204
  amount,
203
205
  tokenDecimals
204
206
  );
205
- const tokenLtMoney = tokenMoney * lt / import__.PERCENTAGE_FACTOR;
207
+ const tokenLtMoney = tokenMoney * lt / import_constants.PERCENTAGE_FACTOR;
206
208
  const { isActive = false } = quotasInfo?.[tokenAddress] || {};
207
209
  const quota = quotas[tokenAddress];
208
210
  const quotaBalance = isActive ? quota?.balance || 0n : 0n;
209
- const quotaMoney = import__.PriceUtils.calcTotalPrice(
211
+ const quotaMoney = import_priceMath.PriceUtils.calcTotalPrice(
210
212
  underlyingPrice,
211
213
  quotaBalance,
212
214
  underlyingDecimals
213
215
  );
214
- const money = quota ? import__.BigIntMath.min(quotaMoney, tokenLtMoney) : tokenLtMoney;
216
+ const money = quota ? import_bigintMath.BigIntMath.min(quotaMoney, tokenLtMoney) : tokenLtMoney;
215
217
  return acc + money;
216
218
  },
217
219
  0n
218
220
  );
219
- const borrowedMoney = import__.PriceUtils.calcTotalPrice(
220
- underlyingPrice || import__.PRICE_DECIMALS,
221
+ const borrowedMoney = import_priceMath.PriceUtils.calcTotalPrice(
222
+ underlyingPrice || import_constants.PRICE_DECIMALS,
221
223
  debt,
222
224
  underlyingDecimals
223
225
  );
224
- const hfInPercent = borrowedMoney > 0n ? assetMoney * import__.PERCENTAGE_FACTOR / borrowedMoney : 0n;
226
+ const hfInPercent = borrowedMoney > 0n ? assetMoney * import_constants.PERCENTAGE_FACTOR / borrowedMoney : 0n;
225
227
  return Number(hfInPercent);
226
228
  }
227
229
  static roundUpQuota(quotaChange) {
228
- return quotaChange !== import__.MIN_INT96 ? quotaChange / import__.PERCENTAGE_FACTOR * import__.PERCENTAGE_FACTOR : quotaChange;
230
+ return quotaChange !== import_constants.MIN_INT96 ? quotaChange / import_constants.PERCENTAGE_FACTOR * import_constants.PERCENTAGE_FACTOR : quotaChange;
229
231
  }
230
232
  static calcRecommendedQuota({
231
233
  amount,
@@ -233,16 +235,16 @@ class CreditAccountDataUtils {
233
235
  lt,
234
236
  quotaReserve
235
237
  }) {
236
- const recommendedBaseQuota = import__.BigIntMath.min(
238
+ const recommendedBaseQuota = import_bigintMath.BigIntMath.min(
237
239
  debt,
238
- amount * lt / import__.PERCENTAGE_FACTOR
240
+ amount * lt / import_constants.PERCENTAGE_FACTOR
239
241
  );
240
- const recommendedQuota = recommendedBaseQuota * (import__.PERCENTAGE_FACTOR + quotaReserve) / import__.PERCENTAGE_FACTOR;
242
+ const recommendedQuota = recommendedBaseQuota * (import_constants.PERCENTAGE_FACTOR + quotaReserve) / import_constants.PERCENTAGE_FACTOR;
241
243
  return CreditAccountDataUtils.roundUpQuota(recommendedQuota);
242
244
  }
243
245
  static calcDefaultQuota({ amount, lt, quotaReserve }) {
244
- const recommendedBaseQuota = amount * lt / import__.PERCENTAGE_FACTOR;
245
- const recommendedQuota = recommendedBaseQuota * (import__.PERCENTAGE_FACTOR + quotaReserve) / import__.PERCENTAGE_FACTOR;
246
+ const recommendedBaseQuota = amount * lt / import_constants.PERCENTAGE_FACTOR;
247
+ const recommendedQuota = recommendedBaseQuota * (import_constants.PERCENTAGE_FACTOR + quotaReserve) / import_constants.PERCENTAGE_FACTOR;
246
248
  return CreditAccountDataUtils.roundUpQuota(recommendedQuota);
247
249
  }
248
250
  static calcQuotaUpdate(props) {
@@ -263,7 +265,7 @@ class CreditAccountDataUtils {
263
265
  );
264
266
  const quotaReduced = Object.values(quotaDecrease).reduce((sum, q) => {
265
267
  const quotaBalance = q.balance || 0n;
266
- const safeBalance = quotaBalance === import__.MIN_INT96 ? import__.BigIntMath.neg(
268
+ const safeBalance = quotaBalance === import_constants.MIN_INT96 ? import_bigintMath.BigIntMath.neg(
267
269
  CreditAccountDataUtils.roundUpQuota(
268
270
  initialQuotas[q.token]?.quota || 0n
269
271
  )
@@ -271,7 +273,7 @@ class CreditAccountDataUtils {
271
273
  return sum + safeBalance;
272
274
  }, 0n);
273
275
  const maxQuotaIncrease = CreditAccountDataUtils.roundUpQuota(
274
- import__.BigIntMath.max(quotaCap - (quotaBought + quotaReduced), 0n)
276
+ import_bigintMath.BigIntMath.max(quotaCap - (quotaBought + quotaReduced), 0n)
275
277
  );
276
278
  const quotaIncrease = Object.keys(allowedToObtain).reduce((acc, token) => {
277
279
  const ch = CreditAccountDataUtils.getSingleQuotaChange(
@@ -297,7 +299,7 @@ class CreditAccountDataUtils {
297
299
  };
298
300
  } else {
299
301
  const change = quotaChange[token]?.balance || 0n;
300
- const quotaAfter = change === import__.MIN_INT96 ? 0n : initialQuota + change;
302
+ const quotaAfter = change === import_constants.MIN_INT96 ? 0n : initialQuota + change;
301
303
  acc[token] = {
302
304
  balance: quotaAfter,
303
305
  token
@@ -339,7 +341,7 @@ class CreditAccountDataUtils {
339
341
  const unsafeQuotaChange = CreditAccountDataUtils.roundUpQuota(
340
342
  defaultQuota - initialQuota
341
343
  );
342
- const quotaChange = unsafeQuotaChange > 0 ? import__.BigIntMath.min(maxQuotaIncrease, unsafeQuotaChange) : unsafeQuotaChange < 0 && import__.BigIntMath.abs(unsafeQuotaChange) >= initialQuota ? import__.MIN_INT96 : unsafeQuotaChange;
344
+ const quotaChange = unsafeQuotaChange > 0 ? import_bigintMath.BigIntMath.min(maxQuotaIncrease, unsafeQuotaChange) : unsafeQuotaChange < 0 && import_bigintMath.BigIntMath.abs(unsafeQuotaChange) >= initialQuota ? import_constants.MIN_INT96 : unsafeQuotaChange;
343
345
  const correctIncrease = assetAfter && props.allowedToObtain[token] && quotaChange > 0;
344
346
  const correctDecrease = assetAfter && props.allowedToSpend[token] && quotaChange < 0;
345
347
  if (correctIncrease || correctDecrease) {
@@ -380,13 +382,13 @@ class CreditAccountDataUtils {
380
382
  const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
381
383
  const { balance: underlyingBalance = 0n } = assets[underlyingToken] || {};
382
384
  const ltUnderlying = liquidationThresholds[underlyingToken] || 0n;
383
- const effectiveDebt = (debt - underlyingBalance * ltUnderlying / import__.PERCENTAGE_FACTOR) * import__.WAD / 10n ** BigInt(underlyingDecimals);
385
+ const effectiveDebt = (debt - underlyingBalance * ltUnderlying / import_constants.PERCENTAGE_FACTOR) * import_constants.WAD / 10n ** BigInt(underlyingDecimals);
384
386
  const targetDecimals = tokensList[targetToken]?.decimals || 18;
385
387
  const { balance: targetBalance = 0n } = assets[targetToken] || {};
386
- const effectiveTargetBalance = targetBalance * import__.WAD / 10n ** BigInt(targetDecimals);
388
+ const effectiveTargetBalance = targetBalance * import_constants.WAD / 10n ** BigInt(targetDecimals);
387
389
  const lpLT = liquidationThresholds[targetToken] || 0n;
388
390
  if (targetBalance <= 0n || lpLT <= 0n) return 0n;
389
- return effectiveDebt * import__.PRICE_DECIMALS * import__.PERCENTAGE_FACTOR / (effectiveTargetBalance * lpLT);
391
+ return effectiveDebt * import_constants.PRICE_DECIMALS * import_constants.PERCENTAGE_FACTOR / (effectiveTargetBalance * lpLT);
390
392
  }
391
393
  /**
392
394
  * Calculates the time remaining until liquidation for a credit account.
@@ -396,11 +398,11 @@ class CreditAccountDataUtils {
396
398
  healthFactor,
397
399
  totalBorrowRate_debt
398
400
  }) {
399
- if (healthFactor <= import__.PERCENTAGE_FACTOR || totalBorrowRate_debt === 0n)
401
+ if (healthFactor <= import_constants.PERCENTAGE_FACTOR || totalBorrowRate_debt === 0n)
400
402
  return null;
401
- const HF_1 = BigInt(healthFactor) - import__.PERCENTAGE_FACTOR;
402
- const brPerYear = BigInt(import__.SECONDS_PER_YEAR) * import__.PERCENTAGE_FACTOR * import__.PERCENTAGE_DECIMALS / totalBorrowRate_debt;
403
- return HF_1 * brPerYear * 1000n / import__.PERCENTAGE_FACTOR;
403
+ const HF_1 = BigInt(healthFactor) - import_constants.PERCENTAGE_FACTOR;
404
+ const brPerYear = BigInt(import_constants.SECONDS_PER_YEAR) * import_constants.PERCENTAGE_FACTOR * import_constants.PERCENTAGE_DECIMALS / totalBorrowRate_debt;
405
+ return HF_1 * brPerYear * 1000n / import_constants.PERCENTAGE_FACTOR;
404
406
  }
405
407
  }
406
408
  // Annotate the CommonJS export names for ESM import in node:
@@ -22,7 +22,7 @@ __export(endpoints_exports, {
22
22
  URLApi: () => URLApi
23
23
  });
24
24
  module.exports = __toCommonJS(endpoints_exports);
25
- var import__ = require("../index.js");
25
+ var import_chains = require("../chain/chains.js");
26
26
  const CHARTS_BACKEND_ADDRESS = "https://charts-server.fly.dev";
27
27
  const STATIC_TOKEN = "https://static.gearbox.finance/tokens/";
28
28
  class GearboxBackendApi {
@@ -31,7 +31,7 @@ class GearboxBackendApi {
31
31
  static getChartsUrl = (url, chainId, options = { params: {} }, priceSource) => {
32
32
  const domain = CHARTS_BACKEND_ADDRESS;
33
33
  const priceSourceArr = priceSource ? [priceSource] : [];
34
- const isMain = (0, import__.isSupportedNetwork)(chainId);
34
+ const isMain = (0, import_chains.isSupportedNetwork)(chainId);
35
35
  const relativePath = URLApi.getRelativeUrl(
36
36
  url,
37
37
  isMain ? {
@@ -48,7 +48,7 @@ __export(formatter_exports, {
48
48
  module.exports = __toCommonJS(formatter_exports);
49
49
  var import_date_fns = require("date-fns");
50
50
  var import_decimal = __toESM(require("decimal.js-light"));
51
- var import__ = require("../index.js");
51
+ var import_constants = require("../constants/index.js");
52
52
  const toBigInt = (v) => {
53
53
  const value = typeof v === "object" && v.type === "BigNumber" ? v.hex : v.toString();
54
54
  return BigInt(value);
@@ -170,10 +170,10 @@ function shortHash(address) {
170
170
  return address === void 0 ? "" : `${address.slice(0, 5)}...`;
171
171
  }
172
172
  function formatPercentage(healthFactor, decimals = 2) {
173
- return (healthFactor / Number(import__.PERCENTAGE_FACTOR)).toFixed(decimals);
173
+ return (healthFactor / Number(import_constants.PERCENTAGE_FACTOR)).toFixed(decimals);
174
174
  }
175
175
  function formatLeverage(leverage, decimals = 2) {
176
- return (leverage / Number(import__.LEVERAGE_DECIMALS)).toFixed(decimals);
176
+ return (leverage / Number(import_constants.LEVERAGE_DECIMALS)).toFixed(decimals);
177
177
  }
178
178
  // Annotate the CommonJS export names for ESM import in node:
179
179
  0 && (module.exports = {
@@ -21,12 +21,12 @@ __export(priceMath_exports, {
21
21
  PriceUtils: () => PriceUtils
22
22
  });
23
23
  module.exports = __toCommonJS(priceMath_exports);
24
- var import__ = require("../index.js");
24
+ var import_constants = require("../constants/index.js");
25
25
  class PriceUtils {
26
- static calcTotalPrice = (price, amount, decimals = 18) => amount * import__.WAD * price / 10n ** BigInt(decimals) / import__.PRICE_DECIMALS;
26
+ static calcTotalPrice = (price, amount, decimals = 18) => amount * import_constants.WAD * price / 10n ** BigInt(decimals) / import_constants.PRICE_DECIMALS;
27
27
  static convertByPrice(totalMoney, { price: targetPrice, decimals: targetDecimals = 18 }) {
28
28
  if (targetPrice <= 0n) return 0n;
29
- return totalMoney * 10n ** BigInt(targetDecimals) * import__.PRICE_DECIMALS / targetPrice / import__.WAD;
29
+ return totalMoney * 10n ** BigInt(targetDecimals) * import_constants.PRICE_DECIMALS / targetPrice / import_constants.WAD;
30
30
  }
31
31
  }
32
32
  // Annotate the CommonJS export names for ESM import in node:
@@ -0,0 +1,60 @@
1
+ const iPriceFeedAbi = [
2
+ {
3
+ type: "function",
4
+ name: "contractType",
5
+ inputs: [],
6
+ outputs: [{ name: "", type: "bytes32", internalType: "bytes32" }],
7
+ stateMutability: "view"
8
+ },
9
+ {
10
+ type: "function",
11
+ name: "decimals",
12
+ inputs: [],
13
+ outputs: [{ name: "", type: "uint8", internalType: "uint8" }],
14
+ stateMutability: "view"
15
+ },
16
+ {
17
+ type: "function",
18
+ name: "description",
19
+ inputs: [],
20
+ outputs: [{ name: "", type: "string", internalType: "string" }],
21
+ stateMutability: "view"
22
+ },
23
+ {
24
+ type: "function",
25
+ name: "latestRoundData",
26
+ inputs: [],
27
+ outputs: [
28
+ { name: "", type: "uint80", internalType: "uint80" },
29
+ { name: "answer", type: "int256", internalType: "int256" },
30
+ { name: "", type: "uint256", internalType: "uint256" },
31
+ { name: "updatedAt", type: "uint256", internalType: "uint256" },
32
+ { name: "", type: "uint80", internalType: "uint80" }
33
+ ],
34
+ stateMutability: "view"
35
+ },
36
+ {
37
+ type: "function",
38
+ name: "serialize",
39
+ inputs: [],
40
+ outputs: [{ name: "serializedData", type: "bytes", internalType: "bytes" }],
41
+ stateMutability: "view"
42
+ },
43
+ {
44
+ type: "function",
45
+ name: "skipPriceCheck",
46
+ inputs: [],
47
+ outputs: [{ name: "", type: "bool", internalType: "bool" }],
48
+ stateMutability: "view"
49
+ },
50
+ {
51
+ type: "function",
52
+ name: "version",
53
+ inputs: [],
54
+ outputs: [{ name: "", type: "uint256", internalType: "uint256" }],
55
+ stateMutability: "view"
56
+ }
57
+ ];
58
+ export {
59
+ iPriceFeedAbi
60
+ };
@@ -16,8 +16,8 @@ import { InstanceManagerContract } from "./instance-manager.js";
16
16
  import { MarketConfiguratorFactoryContract } from "./market-configurator-factory.js";
17
17
  const abi = crossChainMultisigAbi;
18
18
  class CrossChainMultisigContract extends BaseContract {
19
- constructor(addr, client) {
20
- super({ client }, { abi, addr, name: "CrossChainMultisig" });
19
+ constructor(addr, register) {
20
+ super({ register }, { abi, addr, name: "CrossChainMultisig" });
21
21
  }
22
22
  async getExecutedBatches(fromBlock, toBlock) {
23
23
  const events = await this.getEvents("ExecuteBatch", fromBlock, toBlock);
@@ -170,7 +170,7 @@ class CrossChainMultisigContract extends BaseContract {
170
170
  case Addresses.INSTANCE_MANAGER.toLowerCase(): {
171
171
  const instanceManager = new InstanceManagerContract(
172
172
  target,
173
- this.client
173
+ this.register
174
174
  );
175
175
  return instanceManager.parseFunctionData(calldata);
176
176
  }
@@ -22,8 +22,8 @@ import { RoutingManagerContract } from "./router/index.js";
22
22
  import { TreasurySplitterContract } from "./treasury-splitter.js";
23
23
  const abi = instanceManagerAbi;
24
24
  class InstanceManagerContract extends BaseContract {
25
- constructor(addr, client) {
26
- super({ client }, { abi, addr, name: "InstanceManager" });
25
+ constructor(addr, register) {
26
+ super({ register }, { abi, addr, name: "InstanceManager" });
27
27
  }
28
28
  // TODO:
29
29
  #decodeFunctionData(target, calldata) {
@@ -48,12 +48,6 @@ class MellowDepositQueueAdapterContract extends AbstractAdapterContract {
48
48
  referral: this.#referral ? this.labelAddress(this.#referral) : void 0
49
49
  };
50
50
  }
51
- /** Legacy adapter not present in integrations-v3. */
52
- classifyLegacyOperation(_parsed, _transfers) {
53
- throw new Error(
54
- `classifyLegacyOperation is not supported for legacy adapter: ${this.contractType}`
55
- );
56
- }
57
51
  }
58
52
  export {
59
53
  MellowDepositQueueAdapterContract
@@ -40,12 +40,6 @@ class MellowRedeemQueueAdapterContract extends AbstractAdapterContract {
40
40
  phantomToken: this.#phantomToken ? this.labelAddress(this.#phantomToken) : void 0
41
41
  };
42
42
  }
43
- /** Legacy adapter not present in integrations-v3. */
44
- classifyLegacyOperation(_parsed, _transfers) {
45
- throw new Error(
46
- `classifyLegacyOperation is not supported for legacy adapter: ${this.contractType}`
47
- );
48
- }
49
43
  }
50
44
  export {
51
45
  MellowRedeemQueueAdapterContract
@@ -144,8 +144,6 @@ class GearboxSDK extends ChainContractsRegister {
144
144
  if (options.gasLimit !== null) {
145
145
  this.gasLimit = options.gasLimit || 550000000n;
146
146
  }
147
- Object.assign(this, ChainContractsRegister.for(this.client, this.logger));
148
- this.resetContracts();
149
147
  }
150
148
  async #attach(opts) {
151
149
  const {
@@ -57,8 +57,11 @@ class BaseContract extends Construct {
57
57
  this.contractType = bytes32ToString(this.contractType);
58
58
  }
59
59
  this.name = args.name || this.contractType || this.address || this.constructor.name;
60
- this.register.setContract(this.address, this);
61
- this.register.setAddressLabel(this.address, this.name);
60
+ const register = this.safeGetRegister();
61
+ if (register) {
62
+ register.setContract(this.address, this);
63
+ register.setAddressLabel(this.address, this.name);
64
+ }
62
65
  }
63
66
  stateHuman(_ = true) {
64
67
  return {
@@ -2,16 +2,6 @@ import { NOT_DEPLOYED } from "../constants/addresses.js";
2
2
  import { AddressMap } from "../utils/AddressMap.js";
3
3
  import { TokensMeta } from "./TokensMeta.js";
4
4
  class ChainContractsRegister {
5
- static #chains = /* @__PURE__ */ new Map();
6
- static for(client, logger) {
7
- const chainId = client.chain.id;
8
- let result = ChainContractsRegister.#chains.get(chainId);
9
- if (!result) {
10
- result = new ChainContractsRegister(client, logger);
11
- ChainContractsRegister.#chains.set(chainId, result);
12
- }
13
- return result;
14
- }
15
5
  contracts = new AddressMap(
16
6
  [],
17
7
  "contracts"
@@ -32,7 +22,9 @@ class ChainContractsRegister {
32
22
  this.logger?.debug(
33
23
  `resetting contacts register with ${this.contracts.size} contracts`
34
24
  );
25
+ this.labels.clear();
35
26
  this.contracts.clear();
27
+ this.tokensMeta.reset();
36
28
  }
37
29
  getContract(address) {
38
30
  return this.contracts.get(address);
@@ -3,27 +3,41 @@ import { ChainContractsRegister } from "./ChainContractsRegister.js";
3
3
  class Construct {
4
4
  logger;
5
5
  client;
6
- register;
6
+ #register;
7
7
  /**
8
8
  * Indicates that contract state needs to be updated
9
9
  */
10
10
  #dirty = false;
11
11
  constructor(options) {
12
- const { logger } = options;
13
- if ("client" in options) {
14
- const { client } = options;
15
- this.client = client;
16
- this.register = ChainContractsRegister.for(client, logger);
12
+ if (options instanceof ChainContractsRegister) {
13
+ this.#register = options;
14
+ this.client = options.client;
15
+ } else if ("register" in options) {
16
+ this.#register = options.register;
17
+ this.client = options.register.client;
17
18
  } else {
18
- const { register } = options;
19
- this.register = register;
20
- this.client = register.client;
19
+ this.client = options.client;
21
20
  }
22
21
  this.logger = childLogger(
23
22
  this.constructor.name,
24
- this.register.logger ?? logger
23
+ this.#register?.logger ?? options.logger
25
24
  );
26
25
  }
26
+ /**
27
+ * Throws if register was not provided in constructor options
28
+ * Ephemeral contracts that do not need to access other contracts may not need it
29
+ */
30
+ get register() {
31
+ if (!this.#register) {
32
+ throw new Error(
33
+ "contracts register not available, it must be provided if contract needs to access other contracts"
34
+ );
35
+ }
36
+ return this.#register;
37
+ }
38
+ safeGetRegister() {
39
+ return this.#register;
40
+ }
27
41
  get chain() {
28
42
  return this.client.chain;
29
43
  }
@@ -45,19 +59,11 @@ class Construct {
45
59
  set dirty(value) {
46
60
  this.#dirty = value;
47
61
  }
48
- /**
49
- * Syntax sugar for rgister.tokensMeta
50
- */
51
62
  get tokensMeta() {
52
63
  return this.register.tokensMeta;
53
64
  }
54
- /**
55
- * Syntax suggar for getting contract labels
56
- * @param address
57
- * @returns
58
- */
59
65
  labelAddress(address, omitAddress) {
60
- return this.register.labelAddress(address, omitAddress);
66
+ return this.#register?.labelAddress(address, omitAddress) ?? address;
61
67
  }
62
68
  /**
63
69
  * Returns list of addresses that should be watched for events to sync state
@@ -2,7 +2,7 @@ import { Construct } from "./Construct.js";
2
2
  class SDKConstruct extends Construct {
3
3
  sdk;
4
4
  constructor(sdk) {
5
- super(sdk);
5
+ super({ register: sdk });
6
6
  this.sdk = sdk;
7
7
  }
8
8
  }
@@ -1,11 +1,21 @@
1
+ import { decodeAbiParameters } from "viem";
1
2
  import {
2
3
  MissingSerializedParamsError,
3
4
  PlaceholderContract
4
5
  } from "../../base/index.js";
5
6
  class PlaceholderAdapterContract extends PlaceholderContract {
6
7
  #targetContract;
8
+ #creditManager;
7
9
  constructor(options, args) {
8
10
  super(options, args.baseParams);
11
+ if (args.baseParams.serializedParams) {
12
+ const [cm, tc] = decodeAbiParameters(
13
+ [{ type: "address" }, { type: "address" }],
14
+ args.baseParams.serializedParams
15
+ );
16
+ this.#creditManager = cm;
17
+ this.#targetContract = tc;
18
+ }
9
19
  }
10
20
  get targetContract() {
11
21
  if (!this.#targetContract) {
@@ -13,6 +23,12 @@ class PlaceholderAdapterContract extends PlaceholderContract {
13
23
  }
14
24
  return this.#targetContract;
15
25
  }
26
+ get creditManager() {
27
+ if (!this.#creditManager) {
28
+ throw new MissingSerializedParamsError("creditManager");
29
+ }
30
+ return this.#creditManager;
31
+ }
16
32
  }
17
33
  export {
18
34
  PlaceholderAdapterContract
@@ -1,21 +1,4 @@
1
1
  class PriceUpdatesCache {
2
- static #caches = /* @__PURE__ */ new Map();
3
- /**
4
- * Price update caches can be shared across networks
5
- * @param id - unique key to identify the cache
6
- * @param opts
7
- * @returns
8
- */
9
- static get(id, opts) {
10
- const key = `${id}:${opts.historical ? "historical" : "latest"}:${opts.ttl}`;
11
- const cache = PriceUpdatesCache.#caches.get(key);
12
- if (cache) {
13
- return cache;
14
- }
15
- const newCache = new PriceUpdatesCache(opts);
16
- PriceUpdatesCache.#caches.set(key, newCache);
17
- return newCache;
18
- }
19
2
  #cache = /* @__PURE__ */ new Map();
20
3
  #ttlMs;
21
4
  #historical;
@@ -44,7 +44,7 @@ class PythUpdater extends SDKConstruct {
44
44
  `using historical timestamp ${this.#historicalTimestamp}`
45
45
  );
46
46
  }
47
- this.#cache = PriceUpdatesCache.get("pyth", {
47
+ this.#cache = new PriceUpdatesCache({
48
48
  // currently staleness period is 240 seconds on all networks, add some buffer
49
49
  // this period of 4 minutes is selected based on time that is required for user to sign transaction with wallet
50
50
  // so it's unlikely to decrease
@@ -52,7 +52,7 @@ class RedstoneUpdater extends SDKConstruct {
52
52
  `using historical timestamp ${this.#historicalTimestampMs}`
53
53
  );
54
54
  }
55
- this.#cache = PriceUpdatesCache.get("redstone", {
55
+ this.#cache = new PriceUpdatesCache({
56
56
  // currently staleness period is 240 seconds on all networks, add some buffer
57
57
  // this period of 4 minutes is selected based on time that is required for user to sign transaction with wallet
58
58
  // so it's unlikely to decrease
@@ -16,7 +16,7 @@ async function fetchPythPayloads(options) {
16
16
  customFetch = fetch,
17
17
  returnPrices
18
18
  } = options;
19
- const ids = Array.from(new Set(dataFeedsIds));
19
+ const ids = Array.from(new Set(dataFeedsIds)).sort();
20
20
  if (ids.length === 0) {
21
21
  return [];
22
22
  }
@@ -27,7 +27,7 @@ async function fetchPythPayloads(options) {
27
27
  if (ignoreMissingFeeds) {
28
28
  url.searchParams.append("ignore_invalid_price_ids", "true");
29
29
  }
30
- for (const id of dataFeedsIds) {
30
+ for (const id of ids) {
31
31
  url.searchParams.append("ids[]", id);
32
32
  }
33
33
  const resp = await retry(
@@ -1,5 +1,6 @@
1
- import { BigIntMath, PriceUtils } from "../index.js";
1
+ import { BigIntMath } from "./bigintMath.js";
2
2
  import { CreditAccountDataUtils } from "./creditAccount.js";
3
+ import { PriceUtils } from "./priceMath.js";
3
4
  class AssetUtils {
4
5
  static nextAsset({
5
6
  allowedTokens,