@gearbox-protocol/sdk 13.4.0-beta.1 → 13.4.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.
Files changed (84) hide show
  1. package/dist/cjs/permissionless/utils/price-update/get-price-update-tx.js +3 -15
  2. package/dist/cjs/sdk/GearboxSDK.js +135 -20
  3. package/dist/cjs/sdk/accounts/AbstractCreditAccountsService.js +66 -187
  4. package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +5 -5
  5. package/dist/cjs/sdk/base/BaseContract.js +26 -6
  6. package/dist/cjs/sdk/base/ChainContractsRegister.js +39 -2
  7. package/dist/cjs/sdk/base/Construct.js +15 -3
  8. package/dist/cjs/sdk/base/TokensMeta.js +23 -0
  9. package/dist/cjs/sdk/constants/address-provider.js +0 -22
  10. package/dist/cjs/sdk/core/AbstractAddressProviderContract.js +15 -0
  11. package/dist/cjs/sdk/market/MarketRegister.js +74 -3
  12. package/dist/cjs/sdk/market/oracle/PriceOracleBaseContract.js +31 -50
  13. package/dist/cjs/sdk/market/pricefeeds/PriceFeedRef.js +16 -0
  14. package/dist/cjs/sdk/market/pricefeeds/PriceFeedsRegister.js +55 -12
  15. package/dist/cjs/sdk/options.js +30 -24
  16. package/dist/cjs/sdk/plugins/BasePlugin.js +24 -0
  17. package/dist/cjs/sdk/pools/AbstractPoolService.js +6 -0
  18. package/dist/cjs/sdk/router/AbstractRouterContract.js +4 -1
  19. package/dist/cjs/sdk/router/RouterV310Contract.js +20 -15
  20. package/dist/cjs/sdk/utils/AddressMap.js +53 -17
  21. package/dist/cjs/sdk/utils/AddressSet.js +9 -0
  22. package/dist/esm/permissionless/utils/price-update/get-price-update-tx.js +6 -20
  23. package/dist/esm/sdk/GearboxSDK.js +135 -20
  24. package/dist/esm/sdk/accounts/AbstractCreditAccountsService.js +69 -188
  25. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +5 -5
  26. package/dist/esm/sdk/base/BaseContract.js +26 -6
  27. package/dist/esm/sdk/base/ChainContractsRegister.js +39 -2
  28. package/dist/esm/sdk/base/Construct.js +15 -3
  29. package/dist/esm/sdk/base/TokensMeta.js +23 -0
  30. package/dist/esm/sdk/constants/address-provider.js +0 -21
  31. package/dist/esm/sdk/core/AbstractAddressProviderContract.js +15 -0
  32. package/dist/esm/sdk/market/MarketRegister.js +74 -3
  33. package/dist/esm/sdk/market/oracle/PriceOracleBaseContract.js +31 -50
  34. package/dist/esm/sdk/market/pricefeeds/PriceFeedRef.js +16 -0
  35. package/dist/esm/sdk/market/pricefeeds/PriceFeedsRegister.js +55 -12
  36. package/dist/esm/sdk/options.js +30 -24
  37. package/dist/esm/sdk/plugins/BasePlugin.js +24 -0
  38. package/dist/esm/sdk/pools/AbstractPoolService.js +6 -0
  39. package/dist/esm/sdk/router/AbstractRouterContract.js +4 -1
  40. package/dist/esm/sdk/router/RouterV310Contract.js +20 -15
  41. package/dist/esm/sdk/utils/AddressMap.js +53 -17
  42. package/dist/esm/sdk/utils/AddressSet.js +9 -0
  43. package/dist/types/permissionless/bindings/price-feed-store.d.ts +1 -2
  44. package/dist/types/permissionless/bindings/types.d.ts +0 -4
  45. package/dist/types/permissionless/utils/price-update/get-price-update-tx.d.ts +1 -3
  46. package/dist/types/sdk/GearboxSDK.d.ts +236 -34
  47. package/dist/types/sdk/accounts/AbstractCreditAccountsService.d.ts +55 -132
  48. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +14 -5
  49. package/dist/types/sdk/accounts/multicall-utils.d.ts +3 -3
  50. package/dist/types/sdk/accounts/types.d.ts +215 -28
  51. package/dist/types/sdk/base/BaseContract.d.ts +67 -6
  52. package/dist/types/sdk/base/ChainContractsRegister.d.ts +51 -2
  53. package/dist/types/sdk/base/Construct.d.ts +31 -0
  54. package/dist/types/sdk/base/PlaceholderContract.d.ts +3 -0
  55. package/dist/types/sdk/base/SDKConstruct.d.ts +10 -0
  56. package/dist/types/sdk/base/TokensMeta.d.ts +59 -2
  57. package/dist/types/sdk/base/types.d.ts +185 -25
  58. package/dist/types/sdk/chain/chains.d.ts +78 -18
  59. package/dist/types/sdk/chain/detectNetwork.d.ts +7 -0
  60. package/dist/types/sdk/constants/address-provider.d.ts +4 -3
  61. package/dist/types/sdk/core/AbstractAddressProviderContract.d.ts +23 -0
  62. package/dist/types/sdk/core/types.d.ts +46 -0
  63. package/dist/types/sdk/market/MarketRegister.d.ts +81 -0
  64. package/dist/types/sdk/market/adapters/PlaceholderAdapterContracts.d.ts +3 -0
  65. package/dist/types/sdk/market/oracle/PriceOracleBaseContract.d.ts +40 -50
  66. package/dist/types/sdk/market/oracle/types.d.ts +78 -59
  67. package/dist/types/sdk/market/pricefeeds/AbstractLPPriceFeed.d.ts +3 -0
  68. package/dist/types/sdk/market/pricefeeds/AbstractPriceFeed.d.ts +3 -0
  69. package/dist/types/sdk/market/pricefeeds/PriceFeedRef.d.ts +22 -2
  70. package/dist/types/sdk/market/pricefeeds/PriceFeedsRegister.d.ts +80 -16
  71. package/dist/types/sdk/market/pricefeeds/getRawPriceUpdates.d.ts +2 -2
  72. package/dist/types/sdk/market/pricefeeds/types.d.ts +75 -11
  73. package/dist/types/sdk/options.d.ts +13 -4
  74. package/dist/types/sdk/plugins/BasePlugin.d.ts +39 -0
  75. package/dist/types/sdk/plugins/types.d.ts +73 -43
  76. package/dist/types/sdk/pools/AbstractPoolService.d.ts +12 -0
  77. package/dist/types/sdk/pools/types.d.ts +75 -6
  78. package/dist/types/sdk/router/AbstractRouterContract.d.ts +21 -2
  79. package/dist/types/sdk/router/RouterV310Contract.d.ts +27 -15
  80. package/dist/types/sdk/router/types.d.ts +47 -70
  81. package/dist/types/sdk/types/state.d.ts +32 -3
  82. package/dist/types/sdk/utils/AddressMap.d.ts +61 -17
  83. package/dist/types/sdk/utils/AddressSet.d.ts +15 -0
  84. package/package.json +3 -2
@@ -67,24 +67,50 @@ async function attachClient(options, network) {
67
67
  }
68
68
  class GearboxSDK extends ChainContractsRegister {
69
69
  #hooks = new Hooks();
70
+ /**
71
+ * Registered plugin instances, keyed by plugin name.
72
+ **/
70
73
  plugins;
71
- // Block which was use for data query
72
74
  #currentBlock;
73
75
  #timestamp;
74
76
  #syncing = false;
75
- // Collection of core singleton contracts
76
77
  #addressProvider;
77
78
  #attachConfig;
78
- // Collection of markets
79
79
  #marketRegister;
80
80
  #priceFeeds;
81
+ /**
82
+ * Gas limit applied to read-only `eth_call` requests.
83
+ * `undefined` means that gas limit will not be set on read-only calls,
84
+ * leaving it to rpc provider to decide.
85
+ **/
81
86
  gasLimit;
82
87
  /**
83
- * Will throw an error if contract type is not supported, otherwise will try to use generic contract first, if possible
84
- */
88
+ * When `true`, the SDK throws on unrecognised contract types instead of
89
+ * falling back to a generic contract wrapper.
90
+ **/
85
91
  strictContractTypes;
92
+ /**
93
+ * Registers a callback for an SDK lifecycle event.
94
+ *
95
+ * @see {@link SDKHooks} for available event names.
96
+ **/
86
97
  addHook = this.#hooks.addHook.bind(this.#hooks);
98
+ /**
99
+ * Removes a previously registered lifecycle callback.
100
+ *
101
+ * @see {@link SDKHooks} for available event names.
102
+ **/
87
103
  removeHook = this.#hooks.removeHook.bind(this.#hooks);
104
+ /**
105
+ * Creates and initialises a new SDK instance by reading live on-chain state.
106
+ *
107
+ * This is the primary way to bootstrap the SDK. The method connects to the
108
+ * chain, discovers the address provider and all configured markets, and
109
+ * attaches any supplied plugins.
110
+ *
111
+ * @param options - Combined SDK, client, and (optional) network options.
112
+ * @returns A fully initialised SDK instance.
113
+ **/
88
114
  static async attach(options) {
89
115
  const {
90
116
  logger,
@@ -120,6 +146,19 @@ class GearboxSDK extends ChainContractsRegister {
120
146
  pyth
121
147
  });
122
148
  }
149
+ /**
150
+ * Creates a new SDK instance from a previously serialised {@link GearboxState}
151
+ * snapshot, without making any on-chain calls.
152
+ *
153
+ * Use this for fast startup when a recent state snapshot is available
154
+ * (e.g. loaded from a file or received from a backend service).
155
+ *
156
+ * @param options - SDK and client options (block number and address provider
157
+ * are taken from the snapshot).
158
+ * @param state - Serialised state obtained from {@link GearboxSDK.state}.
159
+ * @returns A fully initialised SDK instance.
160
+ * @throws If the snapshot's {@link STATE_VERSION} does not match.
161
+ **/
123
162
  static hydrate(options, state) {
124
163
  const { logger, plugins, strictContractTypes, gasLimit, ...rest } = options;
125
164
  const client = createClient(options, {
@@ -272,9 +311,15 @@ class GearboxSDK extends ChainContractsRegister {
272
311
  return this;
273
312
  }
274
313
  /**
275
- * Reattach SDK with the same config as before, without re-creating instance. Will load all state from scratch
276
- * Be mindful of block number, for example
277
- */
314
+ * Re-attaches the SDK using the same configuration, discarding all cached
315
+ * state and re-reading everything from the chain.
316
+ *
317
+ * Useful when the SDK needs a full refresh (e.g. after a protocol upgrade).
318
+ * Note that if the original `blockNumber` was pinned, the same block is
319
+ * re-used — call {@link syncState} instead if you want to advance.
320
+ *
321
+ * @throws If the SDK has not been attached yet.
322
+ **/
278
323
  async reattach() {
279
324
  if (!this.#attachConfig) {
280
325
  throw new Error("cannot reattach, attach config is not set");
@@ -282,8 +327,15 @@ class GearboxSDK extends ChainContractsRegister {
282
327
  await this.#attach(this.#attachConfig);
283
328
  }
284
329
  /**
285
- * Rehydrate existing SDK from new state without re-creating instance
286
- */
330
+ * Replaces the SDK's in-memory state with a new serialised snapshot
331
+ * without re-creating the instance.
332
+ *
333
+ * After hydration the `rehydrate` hook is triggered so that listeners
334
+ * can react to the state change.
335
+ *
336
+ * @param state - Serialised state obtained from {@link GearboxSDK.state}.
337
+ * @throws If the SDK has not been attached or hydrated yet.
338
+ **/
287
339
  async rehydrate(state) {
288
340
  if (!this.#attachConfig) {
289
341
  throw new Error("cannot rehydrate, attach config is not set");
@@ -299,9 +351,20 @@ class GearboxSDK extends ChainContractsRegister {
299
351
  timestamp: state.timestamp
300
352
  });
301
353
  }
354
+ /**
355
+ * Gearbox network type the SDK is connected to (e.g. `"Mainnet"`, `"Arbitrum"`).
356
+ **/
302
357
  get networkType() {
303
358
  return this.client.chain.network;
304
359
  }
360
+ /**
361
+ * Returns a human-readable snapshot of the entire SDK state, suitable
362
+ * for logging or diagnostic inspection.
363
+ *
364
+ * @param raw - When `true`, include raw numeric values alongside
365
+ * formatted ones.
366
+ * @default true
367
+ **/
305
368
  stateHuman(raw = true) {
306
369
  return {
307
370
  block: Number(this.currentBlock),
@@ -319,6 +382,13 @@ class GearboxSDK extends ChainContractsRegister {
319
382
  ...this.marketRegister.stateHuman(raw)
320
383
  };
321
384
  }
385
+ /**
386
+ * Serialisable snapshot of the current SDK state.
387
+ *
388
+ * The returned object can be persisted (e.g. written to a file) and later
389
+ * passed to {@link GearboxSDK.hydrate} for instant restoration without
390
+ * on-chain reads.
391
+ **/
322
392
  get state() {
323
393
  return {
324
394
  version: STATE_VERSION,
@@ -337,10 +407,20 @@ class GearboxSDK extends ChainContractsRegister {
337
407
  };
338
408
  }
339
409
  /**
340
- * Reloads markets states based on events from last processed block to new block (defaults to latest block)
341
- * @param opts
342
- * @returns true if successful, false if was skipped or failed
343
- */
410
+ * Incrementally updates the SDK state by replaying on-chain events from the
411
+ * last processed block up to the target block (defaults to `latest`).
412
+ *
413
+ * Use the to periodically update sdk state on cron, or subscribe to new blocks
414
+ * using viem's `watchBlocks`
415
+ *
416
+ * On failure the SDK reverts to the previous block/timestamp so that
417
+ * subsequent calls can retry.
418
+ *
419
+ * @param opts - Target block and sync behaviour. When omitted the latest
420
+ * block is fetched automatically.
421
+ * @returns `true` if the sync completed successfully, `false` if it was
422
+ * skipped or failed.
423
+ **/
344
424
  async syncState(opts) {
345
425
  let {
346
426
  blockNumber,
@@ -442,12 +522,22 @@ class GearboxSDK extends ChainContractsRegister {
442
522
  }
443
523
  return success;
444
524
  }
525
+ /**
526
+ * Block number that the SDK state corresponds to.
527
+ *
528
+ * @throws If the SDK has not been attached or hydrated yet.
529
+ **/
445
530
  get currentBlock() {
446
531
  if (this.#currentBlock === void 0) {
447
532
  throw ERR_NOT_ATTACHED;
448
533
  }
449
534
  return this.#currentBlock;
450
535
  }
536
+ /**
537
+ * Block timestamp (Unix epoch seconds) corresponding to {@link currentBlock}.
538
+ *
539
+ * @throws If the SDK has not been attached or hydrated yet.
540
+ **/
451
541
  get timestamp() {
452
542
  if (this.#timestamp === void 0) {
453
543
  throw ERR_NOT_ATTACHED;
@@ -455,14 +545,23 @@ class GearboxSDK extends ChainContractsRegister {
455
545
  return this.#timestamp;
456
546
  }
457
547
  /**
458
- * All price feeds known to sdk, without oracle-related data (stalenessPeriod, main/reserve, etc.)
459
- */
548
+ * Global registry of all price feeds known to the SDK (on all markets).
549
+ *
550
+ * Unlike per-oracle price feed references, this register does not carry
551
+ * oracle-specific metadata (staleness period, main/reserve designation, etc.).
552
+ *
553
+ * @throws If the SDK has not been attached or hydrated yet.
554
+ **/
460
555
  get priceFeeds() {
461
556
  if (this.#priceFeeds === void 0) {
462
557
  throw ERR_NOT_ATTACHED;
463
558
  }
464
559
  return this.#priceFeeds;
465
560
  }
561
+ /**
562
+ * Address of the GEAR governance token on this chain, or `undefined`
563
+ * if the address provider does not list it.
564
+ **/
466
565
  get gear() {
467
566
  try {
468
567
  const g = this.addressProvider.getAddress(AP_GEAR_TOKEN, NO_VERSION);
@@ -472,12 +571,23 @@ class GearboxSDK extends ChainContractsRegister {
472
571
  return void 0;
473
572
  }
474
573
  }
574
+ /**
575
+ * The chain's address provider contract, the central directory for all
576
+ * protocol-wide Gearbox protocol addresses.
577
+ *
578
+ * @throws If the SDK has not been attached or hydrated yet.
579
+ **/
475
580
  get addressProvider() {
476
581
  if (this.#addressProvider === void 0) {
477
582
  throw ERR_NOT_ATTACHED;
478
583
  }
479
584
  return this.#addressProvider;
480
585
  }
586
+ /**
587
+ * Registry of all loaded markets (pools, credit managers, oracles, etc.).
588
+ *
589
+ * @throws If the SDK has not been attached or hydrated yet.
590
+ **/
481
591
  get marketRegister() {
482
592
  if (this.#marketRegister === void 0) {
483
593
  throw ERR_NOT_ATTACHED;
@@ -485,10 +595,15 @@ class GearboxSDK extends ChainContractsRegister {
485
595
  return this.#marketRegister;
486
596
  }
487
597
  /**
488
- * Returns router contract that will work for given credit manager or credit facade, or simply version range
489
- * @param params
490
- * @returns
491
- */
598
+ * Resolves the appropriate router contract for a given credit manager,
599
+ * credit facade, or explicit version range.
600
+ *
601
+ * @param params - Identifies the context: a credit manager address/state,
602
+ * a credit facade address/state, or a {@link VersionRange}.
603
+ * @returns The matching router contract instance.
604
+ * @throws If the credit facade version is unsupported or no router is
605
+ * registered for the resolved version range.
606
+ **/
492
607
  routerFor(params) {
493
608
  let routerRange;
494
609
  if (Array.isArray(params)) {
@@ -1,4 +1,4 @@
1
- import { encodeFunctionData, getAddress, getContract } from "viem";
1
+ import { encodeFunctionData, getContract } from "viem";
2
2
  import {
3
3
  iBotListV310Abi,
4
4
  iCreditFacadeMulticallV310Abi
@@ -21,6 +21,9 @@ import {
21
21
  RAY,
22
22
  VERSION_RANGE_310
23
23
  } from "../constants/index.js";
24
+ import {
25
+ getRawPriceUpdates
26
+ } from "../market/index.js";
24
27
  import { assetsMap } from "../router/index.js";
25
28
  import { AddressMap, AddressSet } from "../utils/index.js";
26
29
  import { simulateWithPriceUpdates } from "../utils/viem/index.js";
@@ -51,12 +54,8 @@ class AbstractCreditAccountService extends SDKConstruct {
51
54
  );
52
55
  }
53
56
  /**
54
- * Returns single credit account data, or undefined if it's not found
55
- * Performs all necessary price feed updates under the hood
56
- * @param account
57
- * @param blockNumber
58
- * @returns
59
- */
57
+ * {@inheritDoc ICreditAccountsService.getCreditAccountData}
58
+ **/
60
59
  async getCreditAccountData(account, blockNumber) {
61
60
  let raw;
62
61
  try {
@@ -75,10 +74,7 @@ class AbstractCreditAccountService extends SDKConstruct {
75
74
  if (raw.success) {
76
75
  return raw;
77
76
  }
78
- const { txs: priceUpdateTxs } = await this.getUpdateForAccount({
79
- creditManager: raw.creditManager,
80
- creditAccount: raw
81
- });
77
+ const { txs: priceUpdateTxs } = await this.getUpdateForAccount(raw);
82
78
  const [cad] = await simulateWithPriceUpdates(this.client, {
83
79
  priceUpdates: priceUpdateTxs,
84
80
  contracts: [
@@ -95,13 +91,8 @@ class AbstractCreditAccountService extends SDKConstruct {
95
91
  return cad;
96
92
  }
97
93
  /**
98
- * Methods to get all credit accounts with some optional filtering
99
- * Performs all necessary price feed updates under the hood
100
- *
101
- * @param options
102
- * @param blockNumber
103
- * @returns returned credit accounts are sorted by health factor in ascending order
104
- */
94
+ * {@inheritDoc ICreditAccountsService.getCreditAccounts}
95
+ **/
105
96
  async getCreditAccounts(options, blockNumber) {
106
97
  const {
107
98
  creditManager,
@@ -154,11 +145,8 @@ class AbstractCreditAccountService extends SDKConstruct {
154
145
  return allCAs.sort((a, b) => Number(a.healthFactor - b.healthFactor));
155
146
  }
156
147
  /**
157
- * Method to get all claimable rewards for credit account (ex. stkUSDS SKY rewards)
158
- Assosiates rewards by adapter + stakedPhantomToken
159
- * @param {Address} creditAccount - address of credit account to get rewards for
160
- * @returns {Array<Rewards>} list of {@link Rewards} that can be claimed
161
- */
148
+ * {@inheritDoc ICreditAccountsService.getRewards}
149
+ **/
162
150
  async getRewards(creditAccount) {
163
151
  const rewards = await this.client.readContract({
164
152
  abi: rewardsCompressorAbi,
@@ -198,11 +186,8 @@ class AbstractCreditAccountService extends SDKConstruct {
198
186
  return Object.values(r);
199
187
  }
200
188
  /**
201
- * Method to get all connected bots for credit account
202
- * @param {Array<AccountToCheck>} accountsToCheck - list of credit accounts
203
- and their credit managers to check connected bots on
204
- * @returns call result of getConnectedBots for each credit account
205
- */
189
+ * {@inheritDoc ICreditAccountsService.getConnectedBots}
190
+ **/
206
191
  async getConnectedBots(accountsToCheck, legacyMigrationBot, additionalBots) {
207
192
  const allResp = await this.client.multicall({
208
193
  contracts: [
@@ -306,10 +291,8 @@ class AbstractCreditAccountService extends SDKConstruct {
306
291
  return void 0;
307
292
  }
308
293
  /**
309
- * Generates transaction to liquidate credit account
310
- * @param props - {@link FullyLiquidateProps}
311
- * @returns
312
- */
294
+ * {@inheritDoc ICreditAccountsService.fullyLiquidate}
295
+ **/
313
296
  async fullyLiquidate(props) {
314
297
  const {
315
298
  account,
@@ -359,21 +342,8 @@ class AbstractCreditAccountService extends SDKConstruct {
359
342
  };
360
343
  }
361
344
  /**
362
- * Closes credit account or closes credit account and keeps it open with zero debt.
363
- - Ca is closed in the following order: price update -> close path to swap all tokens into underlying ->
364
- -> disable quotas of exiting tokens -> decrease debt -> disable exiting tokens tokens -> withdraw underlying tokenz
365
- * @param {CloseOptions} operation - {@link CloseOptions}: close or zeroDebt
366
- * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice} on which operation is performed
367
- * @param {Array<Address>} assetsToWithdraw - tokens to withdraw from credit account.
368
- For credit account closing this is the underlying token, because during the closure,
369
- all tokens on account are swapped into the underlying,
370
- and only the underlying token will remain on the credit account
371
- * @param {Address} to - Wallet address to withdraw underlying to
372
- * @param {number} slippage - Slippage in PERCENTAGE_FORMAT (100% = 10_000) per operation
373
- * @default 50n
374
- * @param {RouterCloseResult | undefined} closePath - result of findBestClosePath method from router; if omited, calls marketRegister.findCreditManager {@link RouterCloseResult}
375
- * @returns All necessary data to execute the transaction (call, credit facade)
376
- */
345
+ * {@inheritDoc ICreditAccountsService.closeCreditAccount}
346
+ **/
377
347
  async closeCreditAccount({
378
348
  operation,
379
349
  assetsToWithdraw,
@@ -401,13 +371,8 @@ class AbstractCreditAccountService extends SDKConstruct {
401
371
  return { tx, calls, routerCloseResult, creditFacade: cm.creditFacade };
402
372
  }
403
373
  /**
404
- * Updates quota of credit account.
405
- - CA quota updated in the following order: price update -> update quotas
406
- * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice} on which operation is performed
407
- * @param {Array<Asset>} averageQuota - average quota for desired tokens {@link Asset}
408
- * @param {Array<Asset>} minQuota - minimum quota for desired tokens {@link Asset}
409
- * @returns All necessary data to execute the transaction (call, credit facade)
410
- */
374
+ * {@inheritDoc ICreditAccountsService.updateQuotas}
375
+ **/
411
376
  async updateQuotas({
412
377
  minQuota,
413
378
  averageQuota,
@@ -429,16 +394,8 @@ class AbstractCreditAccountService extends SDKConstruct {
429
394
  return { tx, calls, creditFacade: cm.creditFacade };
430
395
  }
431
396
  /**
432
- * Adds a single collateral to credit account and updates quotas
433
- - Collateral is added in the following order: price update -> add collateral (with permit) -> update quotas
434
- * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice} on which operation is performed
435
- * @param {Array<Asset>} averageQuota - average quota for desired token {@link Asset}
436
- * @param {Array<Asset>} minQuota - minimum quota for desired token {@link Asset}
437
- * @param {Asset} asset - asset to add as collateral {@link Asset}
438
- * @param {PermitResult | undefined} permits - permits of collateral asset if it is permittable {@link PermitResult}
439
- * @param {bigint} ethAmount - native token amount to attach to tx
440
- * @returns All necessary data to execute the transaction (call, credit facade)
441
- */
397
+ * {@inheritDoc ICreditAccountsService.addCollateral}
398
+ **/
442
399
  async addCollateral({
443
400
  creditAccount,
444
401
  asset,
@@ -471,15 +428,8 @@ class AbstractCreditAccountService extends SDKConstruct {
471
428
  return { tx, calls, creditFacade: cm.creditFacade };
472
429
  }
473
430
  /**
474
- * Increases or decreases debt of credit account; debt decrease uses token ON CREDIT ACCOUNT
475
- - Debt is changed in the following order: price update -> (enables underlying if it was disabled) -> change debt
476
- * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice} on which operation is performed
477
- * @param {bigint} amount - amount to change debt by;
478
- 0 - prohibited value;
479
- negative value for debt decrease;
480
- positive value for debt increase.
481
- * @returns All necessary data to execute the transaction (call, credit facade)
482
- */
431
+ * {@inheritDoc ICreditAccountsService.changeDebt}
432
+ **/
483
433
  async changeDebt({
484
434
  creditAccount,
485
435
  amount,
@@ -516,14 +466,8 @@ class AbstractCreditAccountService extends SDKConstruct {
516
466
  return { tx, calls, creditFacade: cm.creditFacade };
517
467
  }
518
468
  /**
519
- * Executes swap specified by given calls, update quotas of affected tokens
520
- - Swap is executed in the following order: price update -> execute swap path -> update quotas
521
- * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice} on which operation is performed
522
- * @param {Array<Asset>} averageQuota - average quota for desired token {@link Asset}
523
- * @param {Array<Asset>} minQuota - minimum quota for desired token {@link Asset}
524
- * @param {Array<MultiCall>} calls - array of MultiCall from router methods getSingleSwap or getAllSwaps {@link MultiCall}
525
- * @returns All necessary data to execute the transaction (call, credit facade)
526
- */
469
+ * {@inheritDoc ICreditAccountsService.executeSwap}
470
+ **/
527
471
  async executeSwap({
528
472
  creditAccount,
529
473
  calls: swapCalls,
@@ -550,10 +494,8 @@ class AbstractCreditAccountService extends SDKConstruct {
550
494
  return { tx, calls, creditFacade: cm.creditFacade };
551
495
  }
552
496
  /**
553
- * Preview delayed withdrawal for given token
554
- * @param props - {@link PreviewDelayedWithdrawalProps}
555
- * @returns
556
- */
497
+ * {@inheritDoc ICreditAccountsService.previewDelayedWithdrawal}
498
+ **/
557
499
  async previewDelayedWithdrawal({
558
500
  creditAccount,
559
501
  amount,
@@ -577,10 +519,8 @@ class AbstractCreditAccountService extends SDKConstruct {
577
519
  return resp;
578
520
  }
579
521
  /**
580
- * Get claimable and pending withdrawals of an account
581
- * @param props - {@link GetPendingWithdrawalsProps}
582
- * @returns
583
- */
522
+ * {@inheritDoc ICreditAccountsService.getPendingWithdrawals}
523
+ **/
584
524
  async getPendingWithdrawals({
585
525
  creditAccount
586
526
  }) {
@@ -606,11 +546,8 @@ class AbstractCreditAccountService extends SDKConstruct {
606
546
  return respResult;
607
547
  }
608
548
  /**
609
- * Start delayed withdrawal for given token
610
- - Withdrawal is executed in the following order: price update -> execute withdraw calls -> update quotas
611
- * @param props - {@link StartDelayedWithdrawalProps}
612
- * @returns
613
- */
549
+ * {@inheritDoc ICreditAccountsService.startDelayedWithdrawal}
550
+ **/
614
551
  async startDelayedWithdrawal({
615
552
  creditAccount,
616
553
  minQuota,
@@ -665,11 +602,8 @@ class AbstractCreditAccountService extends SDKConstruct {
665
602
  return { tx, calls, creditFacade: cm.creditFacade };
666
603
  }
667
604
  /**
668
- * Claim tokens with delayed withdrawal
669
- - Claim is executed in the following order: price update -> execute claim calls -> update quotas
670
- * @param props - {@link ClaimDelayedProps}
671
- * @returns
672
- */
605
+ * {@inheritDoc ICreditAccountsService.claimDelayed}
606
+ **/
673
607
  async claimDelayed({
674
608
  creditAccount,
675
609
  minQuota,
@@ -729,29 +663,8 @@ class AbstractCreditAccountService extends SDKConstruct {
729
663
  return { tx, calls, creditFacade: cm.creditFacade };
730
664
  }
731
665
  /**
732
- * Executes swap specified by given calls, update quotas of affected tokens
733
- - Open credit account is executed in the following order: price update -> increase debt -> add collateral ->
734
- -> update quotas -> (optionally: execute swap path for trading/strategy) ->
735
- -> (optionally: withdraw debt for lending)
736
- - Basic open credit account: price update -> increase debt -> add collateral -> update quotas
737
- - Lending: price update -> increase debt -> add collateral -> update quotas -> withdraw debt
738
- - Strategy/trading: price update -> increase debt -> add collateral -> update quotas -> execute swap path
739
- - In strategy is possible situation when collateral is added, but not swapped; the only swapped value in this case will be debt
740
- * @param {bigint} ethAmount - native token amount to attach to tx
741
- * @param {Address} creditManager - address of credit manager to open credit account on
742
- * @param {Array<Asset>} collateral - array of collateral which can be just directly added or swapped using the path {@link Asset}
743
- * @param {Record<Address, PermitResult>} permits - permits of collateral tokens (in any permittable token is present) {@link PermitResult}
744
- * @param {bigint} debt - debt to open credit account with
745
- * @param {boolean} withdrawDebt - flag to withdraw debt to wallet after opening credit account;
746
- used for borrowing functionality
747
- * @param {bigint} referralCode - referral code to open credit account with
748
- * @param {Address} to - wallet address to transfer credit account to\
749
- * @param {Array<MultiCall>} calls - array of MultiCall from router methods findOpenStrategyPath {@link MultiCall}.
750
- Used for trading and strategy functionality
751
- * @param {Array<Asset>} averageQuota - average quota for tokens after open {@link Asset}
752
- * @param {Array<Asset>} minQuota - minimum quota for tokens after open {@link Asset}
753
- * @returns All necessary data to execute the transaction (call, credit facade)
754
- */
666
+ * {@inheritDoc ICreditAccountsService.openCA}
667
+ **/
755
668
  async openCA({
756
669
  ethAmount,
757
670
  creditManager,
@@ -783,10 +696,8 @@ class AbstractCreditAccountService extends SDKConstruct {
783
696
  return { calls, tx, creditFacade: cmSuite.creditFacade };
784
697
  }
785
698
  /**
786
- * Returns borrow rate with 4 digits precision (10000 = 100%)
787
- * @param ca
788
- * @returns
789
- */
699
+ * {@inheritDoc ICreditAccountsService.getBorrowRate}
700
+ **/
790
701
  getBorrowRate(ca) {
791
702
  const { creditManager } = this.sdk.marketRegister.findCreditManager(
792
703
  ca.creditManager
@@ -812,9 +723,8 @@ class AbstractCreditAccountService extends SDKConstruct {
812
723
  return r + qr;
813
724
  }
814
725
  /**
815
- * Returns optimal HF for partial liquidation with 4 digits precision (10000 = 100%)
816
- * @param ca
817
- */
726
+ * {@inheritDoc ICreditAccountsService.getOptimalHFForPartialLiquidation}
727
+ **/
818
728
  getOptimalHFForPartialLiquidation(ca) {
819
729
  const borrowRate = this.getBorrowRate(ca);
820
730
  return PERCENTAGE_FACTOR + (borrowRate < 100n ? borrowRate : 100n);
@@ -862,70 +772,18 @@ class AbstractCreditAccountService extends SDKConstruct {
862
772
  );
863
773
  return resp;
864
774
  }
865
- async getUpdateForAccount(options) {
866
- const { creditManager, creditAccount, desiredQuotas, ignoreReservePrices } = options;
867
- const quotaRecord = desiredQuotas ? assetsMap(desiredQuotas) : desiredQuotas;
868
- const caBalancesRecord = creditAccount ? assetsMap(creditAccount.tokens) : creditAccount;
869
- const market = this.sdk.marketRegister.findByCreditManager(creditManager);
870
- const cm = this.sdk.marketRegister.findCreditManager(creditManager).creditManager;
871
- const tokens = /* @__PURE__ */ new Set([getAddress(cm.underlying)]);
872
- for (const t of cm.collateralTokens) {
873
- if (creditAccount && caBalancesRecord && quotaRecord) {
874
- const balanceAsset = caBalancesRecord.get(t);
875
- const balance = balanceAsset?.balance || 0n;
876
- const mask = balanceAsset?.mask || 0n;
877
- const isEnabled = (mask & creditAccount.enabledTokensMask) !== 0n;
878
- const quotaAsset = quotaRecord.get(t);
879
- const quotaBalance = quotaAsset?.balance || 0n;
880
- if (balance > 10n && isEnabled || quotaBalance > 0) {
881
- tokens.add(getAddress(t));
882
- }
883
- } else if (creditAccount && caBalancesRecord) {
884
- const balanceAsset = caBalancesRecord.get(t);
885
- const balance = balanceAsset?.balance || 0n;
886
- const mask = balanceAsset?.mask || 0n;
887
- const isEnabled = (mask & creditAccount.enabledTokensMask) !== 0n;
888
- if (balance > 10n && isEnabled) {
889
- tokens.add(getAddress(t));
890
- }
891
- } else if (quotaRecord) {
892
- const quotaAsset = quotaRecord.get(t);
893
- const quotaBalance = quotaAsset?.balance || 0n;
894
- if (quotaBalance > 0) {
895
- tokens.add(getAddress(t));
896
- }
897
- }
898
- }
899
- const priceFeeds = market.priceOracle.priceFeedsForTokens(Array.from(tokens), {
900
- main: true,
901
- reserve: !ignoreReservePrices
902
- });
903
- const tStr = Array.from(tokens).map((t) => this.labelAddress(t)).join(", ");
904
- const remark = ignoreReservePrices ? " main" : "";
905
- this.logger?.debug(
906
- { account: creditAccount?.creditAccount, manager: cm.name },
907
- `generating price feed updates for ${tStr} from ${priceFeeds.length}${remark} price feeds`
908
- );
909
- return this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(priceFeeds);
910
- }
911
775
  /**
912
- * Returns account price updates that can be used in credit facade multicall or liquidator calls
913
- * @param options
914
- * @returns
915
- */
916
- async getOnDemandPriceUpdates(options) {
917
- const { creditManager, creditAccount } = options;
918
- const market = this.sdk.marketRegister.findByCreditManager(creditManager);
776
+ * {@inheritDoc ICreditAccountsService.getOnDemandPriceUpdates}
777
+ **/
778
+ async getOnDemandPriceUpdates(account, ignoreReservePrices) {
779
+ const { creditManager, creditAccount } = account;
919
780
  const cm = this.sdk.marketRegister.findCreditManager(creditManager);
920
- const update = await this.getUpdateForAccount(options);
781
+ const update = await this.getUpdateForAccount(account, ignoreReservePrices);
921
782
  this.logger?.debug(
922
- { account: creditAccount?.creditAccount, manager: cm.name },
783
+ { account: creditAccount, manager: cm.name },
923
784
  `getting on demand price updates from ${update.txs.length} txs`
924
785
  );
925
- return market.priceOracle.onDemandPriceUpdates(
926
- cm.creditFacade.address,
927
- update
928
- ).raw;
786
+ return getRawPriceUpdates(update);
929
787
  }
930
788
  /**
931
789
  * Analyzes a multicall array and prepends necessary on-demand price feed updates.
@@ -985,6 +843,29 @@ class AbstractCreditAccountService extends SDKConstruct {
985
843
  ...remainingCalls
986
844
  ];
987
845
  }
846
+ async getUpdateForAccount(account, ignoreReservePrices) {
847
+ const { creditManager, creditAccount, enabledTokensMask } = account;
848
+ const market = this.sdk.marketRegister.findByCreditManager(creditManager);
849
+ const cm = this.sdk.marketRegister.findCreditManager(creditManager).creditManager;
850
+ const tokens = new AddressSet([cm.underlying]);
851
+ for (const t of account.tokens) {
852
+ const isEnabled = (t.mask & enabledTokensMask) !== 0n;
853
+ if (t.balance > 10n && isEnabled) {
854
+ tokens.add(t.token);
855
+ }
856
+ }
857
+ const priceFeeds = market.priceOracle.priceFeedsForTokens(Array.from(tokens), {
858
+ main: true,
859
+ reserve: !ignoreReservePrices
860
+ });
861
+ const tStr = tokens.map((t) => this.labelAddress(t)).join(", ");
862
+ const remark = ignoreReservePrices ? " main" : "";
863
+ this.logger?.debug(
864
+ { account: creditAccount, manager: cm.name },
865
+ `generating price feed updates for ${tStr} from ${priceFeeds.length}${remark} price feeds`
866
+ );
867
+ return this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(priceFeeds);
868
+ }
988
869
  /**
989
870
  * Executes a multicall on a credit account, automatically prepending
990
871
  * necessary on-demand price feed updates.