@gearbox-protocol/sdk 13.0.1 → 13.1.0-next.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 (96) hide show
  1. package/dist/cjs/abi/310/iSecuritizeDegenNFT.js +263 -0
  2. package/dist/cjs/abi/310/iSecuritizeKYCFactory.js +278 -0
  3. package/dist/cjs/{sdk/pools/PoolServiceV310.js → abi/iStateSerializer.js} +14 -8
  4. package/dist/cjs/dev/AccountOpener.js +45 -5
  5. package/dist/cjs/sdk/accounts/AbstractCreditAccountsService.js +462 -104
  6. package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +16 -5
  7. package/dist/cjs/sdk/base/ChainContractsRegister.js +1 -1
  8. package/dist/cjs/sdk/base/TokensMeta.js +255 -32
  9. package/dist/cjs/sdk/base/index.js +2 -0
  10. package/dist/cjs/sdk/{constants/phantom-tokens.js → base/token-types.js} +9 -3
  11. package/dist/cjs/sdk/chain/chains.js +2 -1
  12. package/dist/cjs/sdk/constants/index.js +0 -2
  13. package/dist/cjs/sdk/market/MarketRegister.js +2 -2
  14. package/dist/cjs/sdk/market/MarketSuite.js +6 -0
  15. package/dist/cjs/{plugins/zappers/extraZappers.js → sdk/market/ZapperRegister.js} +110 -6
  16. package/dist/cjs/sdk/market/index.js +3 -1
  17. package/dist/cjs/sdk/market/pool/PoolSuite.js +3 -0
  18. package/dist/cjs/sdk/market/pool/PoolV310Contract.js +17 -2
  19. package/dist/cjs/sdk/market/pool/SecuritizeKYCFactory.js +97 -0
  20. package/dist/cjs/sdk/market/pool/index.js +4 -0
  21. package/dist/cjs/sdk/pools/PoolService.js +391 -0
  22. package/dist/cjs/sdk/pools/index.js +2 -4
  23. package/dist/cjs/sdk/utils/AddressMap.js +1 -1
  24. package/dist/cjs/sdk/utils/viem/sendRawTx.js +16 -0
  25. package/dist/esm/abi/310/iSecuritizeDegenNFT.js +239 -0
  26. package/dist/esm/abi/310/iSecuritizeKYCFactory.js +254 -0
  27. package/dist/esm/abi/iStateSerializer.js +12 -0
  28. package/dist/esm/dev/AccountOpener.js +47 -6
  29. package/dist/esm/sdk/accounts/AbstractCreditAccountsService.js +462 -104
  30. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +16 -5
  31. package/dist/esm/sdk/base/ChainContractsRegister.js +1 -1
  32. package/dist/esm/sdk/base/TokensMeta.js +261 -32
  33. package/dist/esm/sdk/base/index.js +1 -0
  34. package/dist/esm/sdk/{constants/phantom-tokens.js → base/token-types.js} +4 -0
  35. package/dist/esm/sdk/chain/chains.js +2 -1
  36. package/dist/esm/sdk/constants/index.js +0 -1
  37. package/dist/esm/sdk/market/MarketRegister.js +2 -2
  38. package/dist/esm/sdk/market/MarketSuite.js +6 -0
  39. package/dist/esm/{plugins/zappers/extraZappers.js → sdk/market/ZapperRegister.js} +109 -2
  40. package/dist/esm/sdk/market/index.js +1 -0
  41. package/dist/esm/sdk/market/pool/PoolSuite.js +3 -0
  42. package/dist/esm/sdk/market/pool/PoolV310Contract.js +17 -2
  43. package/dist/esm/sdk/market/pool/SecuritizeKYCFactory.js +73 -0
  44. package/dist/esm/sdk/market/pool/index.js +2 -0
  45. package/dist/esm/sdk/pools/PoolService.js +371 -0
  46. package/dist/esm/sdk/pools/index.js +1 -2
  47. package/dist/esm/sdk/utils/AddressMap.js +1 -1
  48. package/dist/esm/sdk/utils/viem/sendRawTx.js +19 -1
  49. package/dist/types/abi/310/iSecuritizeDegenNFT.d.ts +324 -0
  50. package/dist/types/abi/310/iSecuritizeKYCFactory.d.ts +322 -0
  51. package/dist/types/abi/iStateSerializer.d.ts +11 -0
  52. package/dist/types/sdk/accounts/AbstractCreditAccountsService.d.ts +123 -27
  53. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +1 -1
  54. package/dist/types/sdk/accounts/types.d.ts +108 -8
  55. package/dist/types/sdk/base/TokensMeta.d.ts +34 -18
  56. package/dist/types/sdk/base/index.d.ts +1 -0
  57. package/dist/types/sdk/base/token-types.d.ts +33 -0
  58. package/dist/types/sdk/base/types.d.ts +0 -1
  59. package/dist/types/sdk/chain/chains.d.ts +1 -1
  60. package/dist/types/sdk/constants/index.d.ts +0 -1
  61. package/dist/types/sdk/market/MarketRegister.d.ts +2 -2
  62. package/dist/types/sdk/market/MarketSuite.d.ts +3 -0
  63. package/dist/types/sdk/market/ZapperRegister.d.ts +17 -0
  64. package/dist/types/sdk/market/index.d.ts +1 -0
  65. package/dist/types/sdk/market/pool/PoolSuite.d.ts +2 -0
  66. package/dist/types/sdk/market/pool/PoolV310Contract.d.ts +6 -2
  67. package/dist/types/sdk/market/pool/SecuritizeKYCFactory.d.ts +345 -0
  68. package/dist/types/sdk/market/pool/index.d.ts +2 -0
  69. package/dist/types/sdk/market/types.d.ts +10 -0
  70. package/dist/types/sdk/pools/PoolService.d.ts +14 -0
  71. package/dist/types/sdk/pools/index.d.ts +1 -2
  72. package/dist/types/sdk/pools/types.d.ts +84 -63
  73. package/dist/types/sdk/utils/AddressMap.d.ts +1 -1
  74. package/dist/types/sdk/utils/viem/sendRawTx.d.ts +5 -1
  75. package/package.json +1 -1
  76. package/dist/cjs/plugins/zappers/ZappersPlugin.js +0 -144
  77. package/dist/cjs/plugins/zappers/index.js +0 -26
  78. package/dist/cjs/plugins/zappers/package.json +0 -1
  79. package/dist/cjs/sdk/pools/AbstractPoolService.js +0 -137
  80. package/dist/cjs/sdk/pools/createPoolService.js +0 -35
  81. package/dist/esm/plugins/zappers/ZappersPlugin.js +0 -126
  82. package/dist/esm/plugins/zappers/index.js +0 -3
  83. package/dist/esm/plugins/zappers/package.json +0 -1
  84. package/dist/esm/sdk/pools/AbstractPoolService.js +0 -113
  85. package/dist/esm/sdk/pools/PoolServiceV310.js +0 -6
  86. package/dist/esm/sdk/pools/createPoolService.js +0 -11
  87. package/dist/types/plugins/zappers/ZappersPlugin.d.ts +0 -18
  88. package/dist/types/plugins/zappers/extraZappers.d.ts +0 -6
  89. package/dist/types/plugins/zappers/index.d.ts +0 -3
  90. package/dist/types/plugins/zappers/types.d.ts +0 -12
  91. package/dist/types/sdk/constants/phantom-tokens.d.ts +0 -2
  92. package/dist/types/sdk/pools/AbstractPoolService.d.ts +0 -9
  93. package/dist/types/sdk/pools/PoolServiceV310.d.ts +0 -4
  94. package/dist/types/sdk/pools/createPoolService.d.ts +0 -3
  95. /package/dist/cjs/{plugins/zappers → sdk/market}/types.js +0 -0
  96. /package/dist/esm/{plugins/zappers → sdk/market}/types.js +0 -0
@@ -39,6 +39,7 @@ const COMPRESSORS = {
39
39
  [import_chains.chains.Mainnet.id]: "0x36F3d0Bb73CBC2E94fE24dF0f26a689409cF9023",
40
40
  [import_chains.chains.Monad.id]: "0x36F3d0Bb73CBC2E94fE24dF0f26a689409cF9023"
41
41
  };
42
+ const INVESTORS = new import_utils.AddressMap([], "investors");
42
43
  function getWithdrawalCompressorAddress(chainId) {
43
44
  return COMPRESSORS[chainId];
44
45
  }
@@ -100,6 +101,23 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
100
101
  });
101
102
  return cad;
102
103
  }
104
+ /**
105
+ * Returns credit account data for a single account with the investor address resolved.
106
+ * Loads CA via getCreditAccountData; for KYC underlyings fetches the investor from the KYC factory's getInvestor(creditAccount), otherwise uses the account owner.
107
+ * @param account - Credit account address
108
+ * @param blockNumber - Optional block number for the read
109
+ * @returns CreditAccountDataWithInvestor (CA data + investor address), or undefined if the account is not found
110
+ */
111
+ async getCreditAccountDataWithInvestor(account, blockNumber) {
112
+ const ca = await this.getCreditAccountData(account, blockNumber);
113
+ if (!ca) return ca;
114
+ const marketSuite = this.sdk.marketRegister.findByCreditManager(
115
+ ca.creditManager
116
+ );
117
+ const factory = await marketSuite.getKYCFactory();
118
+ const investor = factory ? await factory.getInvestor(ca.creditAccount, true) : void 0;
119
+ return { ...ca, investor: investor ?? ca.owner };
120
+ }
103
121
  /**
104
122
  * Methods to get all credit accounts with some optional filtering
105
123
  * Performs all necessary price feed updates under the hood
@@ -108,7 +126,7 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
108
126
  * @param blockNumber
109
127
  * @returns returned credit accounts are sorted by health factor in ascending order
110
128
  */
111
- async getCreditAccounts(options, blockNumber) {
129
+ async getCreditAccounts(options, blockNumber, priceUpdate) {
112
130
  const {
113
131
  creditManager,
114
132
  includeZeroDebt = false,
@@ -130,7 +148,7 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
130
148
  maxHealthFactor,
131
149
  reverting: false
132
150
  };
133
- const { txs: priceUpdateTxs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(
151
+ const { txs: priceUpdateTxs } = priceUpdate ?? await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(
134
152
  ignoreReservePrices ? { main: true } : void 0
135
153
  );
136
154
  const allCAs = [];
@@ -159,6 +177,75 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
159
177
  );
160
178
  return allCAs.sort((a, b) => Number(a.healthFactor - b.healthFactor));
161
179
  }
180
+ /**
181
+ * Returns all credit accounts matching the filter, with investor set on each item.
182
+ * Delegates to getCreditAccounts; when options.owner is set, also loads KYC credit accounts for that owner and merges them into the list. Result is sorted by health factor ascending.
183
+ * @param options - Filter options (owner, creditManager, health factor, etc.)
184
+ * @param blockNumber - Optional block number for the read
185
+ * @returns Array of credit accounts (with investor field), sorted by health factor ascending
186
+ */
187
+ async getCreditAccountsWithInvestor(options, blockNumber) {
188
+ const { owner, ignoreReservePrices = false } = options ?? {};
189
+ const priceUpdate = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(
190
+ ignoreReservePrices ? { main: true } : void 0
191
+ );
192
+ const { txs: priceUpdateTxs } = priceUpdate;
193
+ const [common, kyc] = await Promise.all([
194
+ this.getCreditAccounts(options, blockNumber),
195
+ owner ? this.getKYCCreditAccountsOfOwner(owner, priceUpdateTxs, blockNumber) : void 0
196
+ ]);
197
+ const allCAs = common.map(
198
+ (ca) => ({
199
+ ...ca,
200
+ investor: owner || ca.owner
201
+ })
202
+ );
203
+ allCAs.push(...kyc || []);
204
+ return allCAs.sort((a, b) => Number(a.healthFactor - b.healthFactor));
205
+ }
206
+ async getKYCCreditAccountsOfOwner(owner, priceUpdateTxs, blockNumber) {
207
+ const suites = this.marketConfigurators.map((mc) => {
208
+ const suite = this.sdk.marketRegister.markets.find(
209
+ (m) => m.configurator.address === mc
210
+ );
211
+ return suite;
212
+ });
213
+ const kycCAAddresses = await this.getKYCCaOfInvestor(owner, suites);
214
+ const kycCAs = await this.loadSpecifiedAccounts(
215
+ kycCAAddresses,
216
+ priceUpdateTxs,
217
+ blockNumber
218
+ );
219
+ return kycCAs.map((ca) => ({
220
+ ...ca,
221
+ investor: owner
222
+ }));
223
+ }
224
+ /**
225
+ * Loads credit account data for the given addresses using simulateWithPriceUpdates.
226
+ * Applies the provided price update txs before reading, so returned data is consistent with up-to-date prices.
227
+ * @param accounts - Credit account addresses to load
228
+ * @param priceUpdateTxs - Price feed update txs to simulate before the read (e.g. from generatePriceFeedsUpdateTxs)
229
+ * @param blockNumber - Optional block number for the read
230
+ * @returns Array of CreditAccountData in the same order as accounts (throws if any getCreditAccountData call reverts)
231
+ */
232
+ async loadSpecifiedAccounts(accounts, priceUpdateTxs, blockNumber) {
233
+ if (accounts.length === 0) return [];
234
+ const list = await (0, import_viem2.simulateWithPriceUpdates)(this.client, {
235
+ priceUpdates: priceUpdateTxs,
236
+ contracts: accounts.map(
237
+ (account) => ({
238
+ abi: import_creditAccountCompressor.creditAccountCompressorAbi,
239
+ address: this.#compressor,
240
+ functionName: "getCreditAccountData",
241
+ args: [account]
242
+ })
243
+ ),
244
+ blockNumber,
245
+ gas: this.sdk.gasLimit
246
+ });
247
+ return list;
248
+ }
162
249
  /**
163
250
  * Method to get all claimable rewards for credit account (ex. stkUSDS SKY rewards)
164
251
  Assosiates rewards by adapter + stakedPhantomToken
@@ -389,6 +476,13 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
389
476
  closePath
390
477
  }) {
391
478
  const cm = this.sdk.marketRegister.findCreditManager(ca.creditManager);
479
+ await this.sdk.tokensMeta.loadTokenData(cm.underlying);
480
+ const underlying = this.sdk.tokensMeta.mustGet(cm.underlying);
481
+ if (this.sdk.tokensMeta.isKYCUnderlying(underlying)) {
482
+ throw new Error(
483
+ "closeCreditAccount is not supported for KYC underlying credit accounts"
484
+ );
485
+ }
392
486
  const routerCloseResult = closePath || await this.sdk.routerFor(ca).findBestClosePath({
393
487
  creditAccount: ca,
394
488
  creditManager: cm.creditManager,
@@ -407,7 +501,12 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
407
501
  (t) => this.prepareWithdrawToken(ca.creditFacade, t, import_constants.MAX_UINT256, to)
408
502
  )
409
503
  ];
410
- const tx = operation === "close" ? cm.creditFacade.closeCreditAccount(ca.creditAccount, calls) : cm.creditFacade.multicall(ca.creditAccount, calls);
504
+ const tx = await this.closeCreditAccountTx(
505
+ cm,
506
+ ca.creditAccount,
507
+ calls,
508
+ operation
509
+ );
411
510
  return { tx, calls, routerCloseResult, creditFacade: cm.creditFacade };
412
511
  }
413
512
  /**
@@ -437,7 +536,7 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
437
536
  averageQuota
438
537
  })
439
538
  ];
440
- const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
539
+ const tx = await this.multicallTx(cm, creditAccount.creditAccount, calls);
441
540
  return { tx, calls, creditFacade: cm.creditFacade };
442
541
  }
443
542
  /**
@@ -479,7 +578,7 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
479
578
  averageQuota
480
579
  })
481
580
  ];
482
- const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
581
+ const tx = await this.multicallTx(cm, creditAccount.creditAccount, calls);
483
582
  tx.value = ethAmount.toString(10);
484
583
  return { tx, calls, creditFacade: cm.creditFacade };
485
584
  }
@@ -496,7 +595,7 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
496
595
  async changeDebt({
497
596
  creditAccount,
498
597
  amount,
499
- addCollateral
598
+ collateral
500
599
  }) {
501
600
  if (amount === 0n) {
502
601
  throw new Error("debt increase or decrease must be non-zero");
@@ -510,22 +609,32 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
510
609
  creditManager: creditAccount.creditManager,
511
610
  creditAccount
512
611
  });
513
- const addCollateralCalls = addCollateral && isDecrease ? this.prepareAddCollateral(
612
+ const addCollateralCalls = collateral && isDecrease ? this.prepareAddCollateral(
514
613
  creditAccount.creditFacade,
515
614
  [
516
615
  {
517
- token: creditAccount.underlying,
518
- balance: change
616
+ token: collateral[0].token,
617
+ balance: collateral[0].balance
519
618
  }
520
619
  ],
521
620
  {}
522
621
  ) : [];
622
+ const unwrapCalls = collateral && isDecrease ? await this.getKYCUnwrapCalls(
623
+ collateral[0].balance,
624
+ creditAccount.creditManager
625
+ ) || [] : [];
626
+ if (addCollateralCalls.length > 0 && unwrapCalls.length === 0 && collateral && collateral?.[0].token !== creditAccount.underlying) {
627
+ throw new Error(
628
+ "Can't use collateral other than underlying for non KYC market"
629
+ );
630
+ }
523
631
  const calls = [
524
632
  ...priceUpdatesCalls,
525
633
  ...addCollateralCalls,
634
+ ...unwrapCalls,
526
635
  this.#prepareChangeDebt(creditAccount.creditFacade, change, isDecrease)
527
636
  ];
528
- const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
637
+ const tx = await this.multicallTx(cm, creditAccount.creditAccount, calls);
529
638
  return { tx, calls, creditFacade: cm.creditFacade };
530
639
  }
531
640
  /**
@@ -560,7 +669,7 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
560
669
  averageQuota
561
670
  })
562
671
  ];
563
- const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
672
+ const tx = await this.multicallTx(cm, creditAccount.creditAccount, calls);
564
673
  return { tx, calls, creditFacade: cm.creditFacade };
565
674
  }
566
675
  /**
@@ -676,7 +785,7 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
676
785
  averageQuota
677
786
  })
678
787
  ];
679
- const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
788
+ const tx = await this.multicallTx(cm, creditAccount.creditAccount, calls);
680
789
  return { tx, calls, creditFacade: cm.creditFacade };
681
790
  }
682
791
  /**
@@ -741,48 +850,63 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
741
850
  compareBalances,
742
851
  ...quotaCalls
743
852
  ];
744
- const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
853
+ const tx = await this.multicallTx(cm, creditAccount.creditAccount, calls);
745
854
  return { tx, calls, creditFacade: cm.creditFacade };
746
855
  }
856
+ /**
857
+ * Returns address to which approval should be given on collateral token
858
+ * It's credit manager for classical markets and special wallet for KYC markets
859
+ * @param options - {@link GetApprovalAddressProps}
860
+ * @returns
861
+ **/
862
+ async getApprovalAddress(options) {
863
+ const { creditManager } = options;
864
+ const suite = this.sdk.marketRegister.findCreditManager(creditManager);
865
+ const marketSuite = this.sdk.marketRegister.findByPool(suite.pool);
866
+ const factory = await marketSuite.getKYCFactory();
867
+ if (factory) {
868
+ if ("creditAccount" in options) {
869
+ return factory.getWallet(options.creditAccount);
870
+ }
871
+ return factory.precomputeWalletAddress(creditManager, options.borrower);
872
+ }
873
+ return suite.creditManager.address;
874
+ }
747
875
  /**
748
876
  * Executes swap specified by given calls, update quotas of affected tokens
749
- - Open credit account is executed in the following order: price update -> increase debt -> add collateral ->
750
- -> update quotas -> (optionally: execute swap path for trading/strategy) ->
751
- -> (optionally: withdraw debt for lending)
752
- - Basic open credit account: price update -> increase debt -> add collateral -> update quotas
753
- - Lending: price update -> increase debt -> add collateral -> update quotas -> withdraw debt
754
- - Strategy/trading: price update -> increase debt -> add collateral -> update quotas -> execute swap path
755
- - In strategy is possible situation when collateral is added, but not swapped; the only swapped value in this case will be debt
756
- * @param {bigint} ethAmount - native token amount to attach to tx
757
- * @param {Address} creditManager - address of credit manager to open credit account on
758
- * @param {Array<Asset>} collateral - array of collateral which can be just directly added or swapped using the path {@link Asset}
759
- * @param {Record<Address, PermitResult>} permits - permits of collateral tokens (in any permittable token is present) {@link PermitResult}
760
- * @param {bigint} debt - debt to open credit account with
761
- * @param {boolean} withdrawDebt - flag to withdraw debt to wallet after opening credit account;
762
- used for borrowing functionality
763
- * @param {bigint} referralCode - referral code to open credit account with
764
- * @param {Address} to - wallet address to transfer credit account to\
765
- * @param {Array<MultiCall>} calls - array of MultiCall from router methods findOpenStrategyPath {@link MultiCall}.
766
- Used for trading and strategy functionality
767
- * @param {Array<Asset>} averageQuota - average quota for tokens after open {@link Asset}
768
- * @param {Array<Asset>} minQuota - minimum quota for tokens after open {@link Asset}
877
+ * - Open credit account is executed in the following order: price update -> increase debt -> add collateral ->
878
+ * -> update quotas -> (optionally: execute swap path for trading/strategy) ->
879
+ * -> (optionally: withdraw debt for lending)
880
+ *- Basic open credit account: price update -> increase debt -> add collateral -> update quotas
881
+ *- Lending: price update -> increase debt -> add collateral -> update quotas -> withdraw debt
882
+ *- Strategy/trading: price update -> increase debt -> add collateral -> update quotas -> execute swap path
883
+ *- In strategy is possible situation when collateral is added, but not swapped; the only swapped value in this case will be debt
769
884
  * @returns All necessary data to execute the transaction (call, credit facade)
770
- */
771
- async openCA({
772
- ethAmount,
773
- creditManager,
774
- collateral,
775
- permits,
776
- debt,
777
- withdrawDebt,
778
- referralCode,
779
- to,
780
- calls: openPathCalls,
781
- minQuota,
782
- averageQuota
783
- }) {
885
+ **/
886
+ async openCA(props) {
887
+ const {
888
+ ethAmount,
889
+ creditManager,
890
+ reopenCreditAccount,
891
+ collateral,
892
+ permits,
893
+ debt,
894
+ withdrawToken,
895
+ referralCode,
896
+ to,
897
+ calls: openPathCalls,
898
+ callsAfter,
899
+ minQuota,
900
+ averageQuota
901
+ } = props;
784
902
  const cmSuite = this.sdk.marketRegister.findCreditManager(creditManager);
785
903
  const cm = cmSuite.creditManager;
904
+ let tokenToWithdraw;
905
+ if (withdrawToken === true) {
906
+ tokenToWithdraw = cm.underlying;
907
+ } else if (typeof withdrawToken === "string") {
908
+ tokenToWithdraw = withdrawToken;
909
+ }
786
910
  const priceUpdatesCalls = await this.getPriceUpdatesForFacade({
787
911
  creditManager: cm.address,
788
912
  desiredQuotas: averageQuota
@@ -792,13 +916,27 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
792
916
  this.#prepareIncreaseDebt(cm.creditFacade, debt),
793
917
  ...this.prepareAddCollateral(cm.creditFacade, collateral, permits),
794
918
  ...openPathCalls,
795
- ...withdrawDebt ? [this.prepareWithdrawToken(cm.creditFacade, cm.underlying, debt, to)] : [],
919
+ // путь из underlying в withdrawal token
920
+ ...tokenToWithdraw ? [
921
+ this.prepareWithdrawToken(
922
+ cm.creditFacade,
923
+ tokenToWithdraw,
924
+ import_constants.MAX_UINT256,
925
+ to
926
+ )
927
+ ] : [],
796
928
  ...this.prepareUpdateQuotas(cm.creditFacade, {
797
929
  minQuota,
798
930
  averageQuota
799
- })
931
+ }),
932
+ ...callsAfter ?? []
800
933
  ];
801
- const tx = cmSuite.creditFacade.openCreditAccount(to, calls, referralCode);
934
+ let tx;
935
+ if (reopenCreditAccount) {
936
+ tx = await this.multicallTx(cmSuite, reopenCreditAccount, calls);
937
+ } else {
938
+ tx = await this.openCreditAccountTx(cmSuite, to, calls, referralCode);
939
+ }
802
940
  tx.value = ethAmount.toString(10);
803
941
  return { calls, tx, creditFacade: cmSuite.creditFacade };
804
942
  }
@@ -882,6 +1020,130 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
882
1020
  );
883
1021
  return resp;
884
1022
  }
1023
+ /**
1024
+ * Returns multicall entries to redeem (unwrap) KYC ERC-4626 vault shares into underlying for the given credit manager.
1025
+ * Used when withdrawing debt from a KYC market: redeems adapter vault shares so the underlying can be withdrawn.
1026
+ * Only applies when the credit manager's underlying is KYC-gated and has an ERC-4626 adapter configured.
1027
+ * @param amount - Number of vault shares (adapter tokens) to redeem
1028
+ * @param creditManager - Credit manager address
1029
+ * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not KYC or no adapter is configured
1030
+ */
1031
+ async getKYCUnwrapCalls(amount, creditManager) {
1032
+ const suite = this.sdk.marketRegister.findCreditManager(creditManager);
1033
+ const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
1034
+ if (!this.sdk.tokensMeta.isKYCUnderlying(meta)) {
1035
+ return void 0;
1036
+ }
1037
+ const adapter = suite.creditManager.adapters.get(meta.addr);
1038
+ const adapterAddress = adapter?.address;
1039
+ if (!adapterAddress) {
1040
+ return void 0;
1041
+ }
1042
+ const mc = [
1043
+ {
1044
+ target: adapterAddress,
1045
+ callData: (0, import_viem.encodeFunctionData)({
1046
+ abi: ierc4626AdapterAbi,
1047
+ functionName: "redeem",
1048
+ args: [amount, import_constants.ADDRESS_0X0, import_constants.ADDRESS_0X0]
1049
+ })
1050
+ }
1051
+ ];
1052
+ return mc;
1053
+ }
1054
+ /**
1055
+ * Returns multicall entries to deposit (wrap) underlying into KYC ERC-4626 vault shares for the given credit manager.
1056
+ * Used when adding debt on a KYC market: deposits underlying into the adapter vault so shares are minted on the account.
1057
+ * Only applies when the credit manager's underlying is KYC-gated and has an ERC-4626 adapter configured.
1058
+ * @param amount - Amount of underlying assets to deposit into the vault (in underlying decimals)
1059
+ * @param creditManager - Credit manager address
1060
+ * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not KYC or no adapter is configured
1061
+ */
1062
+ async getKYCWrapCalls(amount, creditManager) {
1063
+ const suite = this.sdk.marketRegister.findCreditManager(creditManager);
1064
+ const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
1065
+ if (!this.sdk.tokensMeta.isKYCUnderlying(meta)) {
1066
+ return void 0;
1067
+ }
1068
+ const adapter = suite.creditManager.adapters.get(meta.addr);
1069
+ const adapterAddress = adapter?.address;
1070
+ if (!adapterAddress) {
1071
+ return void 0;
1072
+ }
1073
+ const mc = [
1074
+ {
1075
+ target: adapterAddress,
1076
+ callData: (0, import_viem.encodeFunctionData)({
1077
+ abi: ierc4626AdapterAbi,
1078
+ functionName: "deposit",
1079
+ args: [amount, import_constants.ADDRESS_0X0]
1080
+ })
1081
+ }
1082
+ ];
1083
+ return mc;
1084
+ }
1085
+ /**
1086
+ * Returns multicall entries to call redeemDiff on the KYC ERC-4626 adapter for the given credit manager.
1087
+ * Redeems the leftover vault shares (e.g. after repaying debt) so the account does not hold excess KYC vault tokens.
1088
+ * Only applies when the credit manager's underlying is KYC-gated and has an ERC-4626 adapter configured.
1089
+ * @param amount - Leftover vault share amount to redeem (in adapter/vault decimals)
1090
+ * @param creditManager - Credit manager address
1091
+ * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not KYC or no adapter is configured
1092
+ */
1093
+ async getRedeemDiffCalls(amount, creditManager) {
1094
+ const suite = this.sdk.marketRegister.findCreditManager(creditManager);
1095
+ const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
1096
+ if (!this.sdk.tokensMeta.isKYCUnderlying(meta)) {
1097
+ return void 0;
1098
+ }
1099
+ const adapter = suite.creditManager.adapters.get(meta.addr);
1100
+ const adapterAddress = adapter?.address;
1101
+ if (!adapterAddress) {
1102
+ return void 0;
1103
+ }
1104
+ const mc = [
1105
+ {
1106
+ target: adapterAddress,
1107
+ callData: (0, import_viem.encodeFunctionData)({
1108
+ abi: ierc4626AdapterAbi,
1109
+ functionName: "redeemDiff",
1110
+ args: [amount]
1111
+ })
1112
+ }
1113
+ ];
1114
+ return mc;
1115
+ }
1116
+ /**
1117
+ * Returns multicall entries to call depositDiff on the KYC ERC-4626 adapter for the given credit manager.
1118
+ * Deposits the leftover underlying (e.g. after decreasing debt) into the vault so the account does not hold excess underlying.
1119
+ * Only applies when the credit manager's underlying is KYC-gated and has an ERC-4626 adapter configured.
1120
+ * @param amount - Leftover underlying amount to deposit into the vault (in underlying decimals)
1121
+ * @param creditManager - Credit manager address
1122
+ * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not KYC or no adapter is configured
1123
+ */
1124
+ async getDepositDiffCalls(amount, creditManager) {
1125
+ const suite = this.sdk.marketRegister.findCreditManager(creditManager);
1126
+ const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
1127
+ if (!this.sdk.tokensMeta.isKYCUnderlying(meta)) {
1128
+ return void 0;
1129
+ }
1130
+ const adapter = suite.creditManager.adapters.get(meta.addr);
1131
+ const adapterAddress = adapter?.address;
1132
+ if (!adapterAddress) {
1133
+ return void 0;
1134
+ }
1135
+ const mc = [
1136
+ {
1137
+ target: adapterAddress,
1138
+ callData: (0, import_viem.encodeFunctionData)({
1139
+ abi: ierc4626AdapterAbi,
1140
+ functionName: "depositDiff",
1141
+ args: [amount]
1142
+ })
1143
+ }
1144
+ ];
1145
+ return mc;
1146
+ }
885
1147
  /**
886
1148
  * Returns raw txs that are needed to update all price feeds so that all credit accounts (possibly from different markets) compute
887
1149
  *
@@ -1109,78 +1371,174 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
1109
1371
  import_constants.VERSION_RANGE_310
1110
1372
  )[0];
1111
1373
  }
1374
+ /**
1375
+ * Wrapper that selects between credit facade and KYC factory
1376
+ * @param suite
1377
+ * @param to
1378
+ * @param calls
1379
+ * @param referralCode
1380
+ * @returns
1381
+ */
1382
+ async openCreditAccountTx(suite, to, calls, referralCode) {
1383
+ const marketSuite = this.sdk.marketRegister.findByPool(suite.pool);
1384
+ const factory = await marketSuite.getKYCFactory();
1385
+ if (factory) {
1386
+ const tokensToRegister = await factory.getDSTokens();
1387
+ return factory.openCreditAccount(
1388
+ suite.creditManager.address,
1389
+ calls,
1390
+ tokensToRegister
1391
+ );
1392
+ }
1393
+ return suite.creditFacade.openCreditAccount(to, calls, referralCode ?? 0n);
1394
+ }
1395
+ /**
1396
+ * Wrapper that selects between credit facade and KYC factory
1397
+ * @param suite
1398
+ * @param creditAccount
1399
+ * @param calls
1400
+ * @returns
1401
+ */
1402
+ async multicallTx(suite, creditAccount, calls) {
1403
+ const marketSuite = this.sdk.marketRegister.findByCreditManager(
1404
+ suite.creditManager.address
1405
+ );
1406
+ const factory = await marketSuite.getKYCFactory();
1407
+ if (factory) {
1408
+ const tokensToRegister = [];
1409
+ return factory.multicall(creditAccount, calls, tokensToRegister);
1410
+ }
1411
+ return suite.creditFacade.multicall(creditAccount, calls);
1412
+ }
1413
+ /**
1414
+ * Wrapper that selects between credit facade and KYC factory
1415
+ * @param suite
1416
+ * @param creditAccount
1417
+ * @param calls
1418
+ * @param operation
1419
+ * @returns
1420
+ */
1421
+ async closeCreditAccountTx(suite, creditAccount, calls, operation) {
1422
+ const marketSuite = this.sdk.marketRegister.findByCreditManager(
1423
+ suite.creditManager.address
1424
+ );
1425
+ const factory = await marketSuite.getKYCFactory();
1426
+ if (operation === "close") {
1427
+ if (factory) {
1428
+ throw new Error(
1429
+ "CloseOptions=close is not supported for KYC underlying credit accounts"
1430
+ );
1431
+ }
1432
+ return suite.creditFacade.closeCreditAccount(creditAccount, calls);
1433
+ }
1434
+ if (factory) {
1435
+ const tokensToRegister = [];
1436
+ return factory.multicall(creditAccount, calls, tokensToRegister);
1437
+ }
1438
+ return suite.creditFacade.multicall(creditAccount, calls);
1439
+ }
1440
+ /**
1441
+ * Returns all KYC credit account addresses for an investor across the given market suites.
1442
+ * Resolves KYC factory per suite, then multicalls each factory's getCreditAccounts(investor).
1443
+ * @param investor - Owner address to query
1444
+ * @param suites - Market suites (KYC factories are resolved for each; undefined entries are skipped)
1445
+ * @returns Flat array of credit account addresses from all KYC markets
1446
+ */
1447
+ async getKYCCaOfInvestor(investor, suites) {
1448
+ if (suites.length === 0 || investor === import_constants.ADDRESS_0X0) return [];
1449
+ const factories = await Promise.all(
1450
+ suites.map((suite) => suite ? suite.getKYCFactory() : void 0)
1451
+ );
1452
+ const safeFactories = factories.reduce(
1453
+ (acc, v) => {
1454
+ if (v) {
1455
+ acc.push(v);
1456
+ }
1457
+ return acc;
1458
+ },
1459
+ []
1460
+ );
1461
+ const allResp = await this.client.multicall({
1462
+ contracts: [
1463
+ ...safeFactories.map((factory) => {
1464
+ return {
1465
+ abi: factory.abi,
1466
+ address: factory.address,
1467
+ functionName: "getCreditAccounts",
1468
+ args: [investor]
1469
+ };
1470
+ })
1471
+ ],
1472
+ allowFailure: true,
1473
+ batchSize: 0
1474
+ });
1475
+ const caLists = safeFactories.reduce((acc, _, index) => {
1476
+ const response = allResp[index];
1477
+ acc.push(...response.result || []);
1478
+ return acc;
1479
+ }, []);
1480
+ return caLists;
1481
+ }
1112
1482
  }
1113
- const iMellowClaimerAdapterAbi = [
1483
+ const ierc4626AdapterAbi = [
1114
1484
  {
1115
- type: "function",
1116
- name: "getMultiVaultSubvaultIndices",
1117
- inputs: [{ name: "multiVault", type: "address", internalType: "address" }],
1118
- outputs: [
1119
- {
1120
- name: "subvaultIndices",
1121
- type: "uint256[]",
1122
- internalType: "uint256[]"
1123
- },
1124
- {
1125
- name: "withdrawalIndices",
1126
- type: "uint256[][]",
1127
- internalType: "uint256[][]"
1128
- }
1485
+ inputs: [
1486
+ { name: "assets", type: "uint256", internalType: "uint256" },
1487
+ { name: "receiver", type: "address", internalType: "address" }
1129
1488
  ],
1130
- stateMutability: "view"
1489
+ name: "deposit",
1490
+ outputs: [{ name: "useSafePrices", type: "bool", internalType: "bool" }],
1491
+ stateMutability: "nonpayable",
1492
+ type: "function"
1131
1493
  },
1132
1494
  {
1133
- type: "function",
1134
- name: "getUserSubvaultIndices",
1135
1495
  inputs: [
1136
- { name: "multiVault", type: "address", internalType: "address" },
1137
- { name: "user", type: "address", internalType: "address" }
1496
+ { name: "shares", type: "uint256", internalType: "uint256" },
1497
+ { name: "receiver", type: "address", internalType: "address" },
1498
+ { name: "owner", type: "address", internalType: "address" }
1138
1499
  ],
1139
- outputs: [
1500
+ name: "redeem",
1501
+ outputs: [{ name: "useSafePrices", type: "bool", internalType: "bool" }],
1502
+ stateMutability: "nonpayable",
1503
+ type: "function"
1504
+ },
1505
+ {
1506
+ inputs: [
1140
1507
  {
1141
- name: "subvaultIndices",
1142
- type: "uint256[]",
1143
- internalType: "uint256[]"
1144
- },
1508
+ name: "leftoverAmount",
1509
+ type: "uint256",
1510
+ internalType: "uint256"
1511
+ }
1512
+ ],
1513
+ name: "redeemDiff",
1514
+ outputs: [
1145
1515
  {
1146
- name: "withdrawalIndices",
1147
- type: "uint256[][]",
1148
- internalType: "uint256[][]"
1516
+ name: "useSafePrices",
1517
+ type: "bool",
1518
+ internalType: "bool"
1149
1519
  }
1150
1520
  ],
1151
- stateMutability: "view"
1521
+ stateMutability: "nonpayable",
1522
+ type: "function"
1152
1523
  },
1153
1524
  {
1154
- type: "function",
1155
- name: "multiAccept",
1156
1525
  inputs: [
1157
- { name: "multiVault", type: "address", internalType: "address" },
1158
1526
  {
1159
- name: "subvaultIndices",
1160
- type: "uint256[]",
1161
- internalType: "uint256[]"
1162
- },
1163
- { name: "indices", type: "uint256[][]", internalType: "uint256[][]" }
1527
+ name: "leftoverAmount",
1528
+ type: "uint256",
1529
+ internalType: "uint256"
1530
+ }
1164
1531
  ],
1165
- outputs: [{ name: "", type: "bool", internalType: "bool" }],
1166
- stateMutability: "nonpayable"
1167
- },
1168
- {
1169
- type: "function",
1170
- name: "multiAcceptAndClaim",
1171
- inputs: [
1172
- { name: "multiVault", type: "address", internalType: "address" },
1532
+ name: "depositDiff",
1533
+ outputs: [
1173
1534
  {
1174
- name: "subvaultIndices",
1175
- type: "uint256[]",
1176
- internalType: "uint256[]"
1177
- },
1178
- { name: "indices", type: "uint256[][]", internalType: "uint256[][]" },
1179
- { name: "", type: "address", internalType: "address" },
1180
- { name: "maxAssets", type: "uint256", internalType: "uint256" }
1535
+ name: "useSafePrices",
1536
+ type: "bool",
1537
+ internalType: "bool"
1538
+ }
1181
1539
  ],
1182
- outputs: [{ name: "", type: "bool", internalType: "bool" }],
1183
- stateMutability: "nonpayable"
1540
+ stateMutability: "nonpayable",
1541
+ type: "function"
1184
1542
  }
1185
1543
  ];
1186
1544
  // Annotate the CommonJS export names for ESM import in node: