@gearbox-protocol/sdk 13.6.0 → 13.7.0-kyc.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 (109) hide show
  1. package/dist/cjs/abi/kyc/iDSRegistryService.js +70 -0
  2. package/dist/cjs/abi/kyc/iDSToken.js +71 -0
  3. package/dist/cjs/abi/kyc/iKYCCompressor.js +196 -0
  4. package/dist/cjs/abi/kyc/iKYCFactory.js +122 -0
  5. package/dist/cjs/abi/kyc/iKYCUnderlying.js +401 -0
  6. package/dist/cjs/abi/kyc/iSecuritizeDegenNFT.js +326 -0
  7. package/dist/cjs/abi/kyc/iSecuritizeKYCFactory.js +319 -0
  8. package/dist/cjs/dev/AccountOpener.js +45 -5
  9. package/dist/cjs/history/errors.js +2 -0
  10. package/dist/cjs/sdk/GearboxSDK.js +51 -4
  11. package/dist/cjs/sdk/accounts/AbstractCreditAccountsService.js +324 -16
  12. package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +7 -1
  13. package/dist/cjs/sdk/base/TokensMeta.js +32 -43
  14. package/dist/cjs/sdk/base/token-types.js +9 -0
  15. package/dist/cjs/sdk/chain/chains.js +2 -1
  16. package/dist/cjs/sdk/constants/address-provider.js +3 -0
  17. package/dist/cjs/sdk/market/MarketRegister.js +70 -116
  18. package/dist/cjs/sdk/market/MarketSuite.js +3 -0
  19. package/dist/cjs/sdk/market/index.js +2 -0
  20. package/dist/cjs/sdk/market/kyc/KYCRegistry.js +269 -0
  21. package/dist/cjs/sdk/market/kyc/index.js +26 -0
  22. package/dist/cjs/sdk/market/kyc/securitize/SecuritizeKYCFactory.js +244 -0
  23. package/dist/cjs/sdk/market/kyc/securitize/constants.js +28 -0
  24. package/dist/cjs/sdk/market/kyc/securitize/index.js +26 -0
  25. package/dist/cjs/sdk/market/kyc/securitize/types.js +16 -0
  26. package/dist/cjs/sdk/market/kyc/types.js +34 -0
  27. package/dist/cjs/sdk/market/pool/PoolSuite.js +3 -0
  28. package/dist/cjs/sdk/market/pool/PoolV310Contract.js +11 -2
  29. package/dist/cjs/sdk/market/pool/index.js +2 -0
  30. package/dist/cjs/sdk/market/pricefeeds/PriceFeedsRegister.js +3 -3
  31. package/dist/cjs/sdk/options.js +6 -0
  32. package/dist/cjs/sdk/pools/PoolService.js +104 -12
  33. package/dist/cjs/sdk/utils/viem/executeDelegatedMulticalls.js +38 -0
  34. package/dist/cjs/sdk/utils/viem/index.js +2 -0
  35. package/dist/esm/abi/kyc/iDSRegistryService.js +46 -0
  36. package/dist/esm/abi/kyc/iDSToken.js +47 -0
  37. package/dist/esm/abi/kyc/iKYCCompressor.js +172 -0
  38. package/dist/esm/abi/kyc/iKYCFactory.js +98 -0
  39. package/dist/esm/abi/kyc/iKYCUnderlying.js +377 -0
  40. package/dist/esm/abi/kyc/iSecuritizeDegenNFT.js +302 -0
  41. package/dist/esm/abi/kyc/iSecuritizeKYCFactory.js +295 -0
  42. package/dist/esm/dev/AccountOpener.js +47 -6
  43. package/dist/esm/history/errors.js +2 -0
  44. package/dist/esm/sdk/GearboxSDK.js +55 -5
  45. package/dist/esm/sdk/accounts/AbstractCreditAccountsService.js +328 -17
  46. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +7 -1
  47. package/dist/esm/sdk/base/TokensMeta.js +32 -45
  48. package/dist/esm/sdk/base/token-types.js +6 -0
  49. package/dist/esm/sdk/chain/chains.js +2 -1
  50. package/dist/esm/sdk/constants/address-provider.js +2 -0
  51. package/dist/esm/sdk/market/MarketRegister.js +74 -118
  52. package/dist/esm/sdk/market/MarketSuite.js +3 -0
  53. package/dist/esm/sdk/market/index.js +1 -0
  54. package/dist/esm/sdk/market/kyc/KYCRegistry.js +253 -0
  55. package/dist/esm/sdk/market/kyc/index.js +3 -0
  56. package/dist/esm/sdk/market/kyc/securitize/SecuritizeKYCFactory.js +220 -0
  57. package/dist/esm/sdk/market/kyc/securitize/constants.js +4 -0
  58. package/dist/esm/sdk/market/kyc/securitize/index.js +3 -0
  59. package/dist/esm/sdk/market/kyc/securitize/types.js +0 -0
  60. package/dist/esm/sdk/market/kyc/types.js +9 -0
  61. package/dist/esm/sdk/market/pool/PoolSuite.js +3 -0
  62. package/dist/esm/sdk/market/pool/PoolV310Contract.js +11 -2
  63. package/dist/esm/sdk/market/pool/index.js +1 -0
  64. package/dist/esm/sdk/market/pricefeeds/PriceFeedsRegister.js +3 -3
  65. package/dist/esm/sdk/options.js +6 -0
  66. package/dist/esm/sdk/pools/PoolService.js +109 -13
  67. package/dist/esm/sdk/utils/viem/executeDelegatedMulticalls.js +14 -0
  68. package/dist/esm/sdk/utils/viem/index.js +1 -0
  69. package/dist/types/abi/kyc/iDSRegistryService.d.ts +71 -0
  70. package/dist/types/abi/kyc/iDSToken.d.ts +67 -0
  71. package/dist/types/abi/kyc/iKYCCompressor.d.ts +228 -0
  72. package/dist/types/abi/kyc/iKYCFactory.d.ts +139 -0
  73. package/dist/types/abi/kyc/iKYCUnderlying.d.ts +548 -0
  74. package/dist/types/abi/kyc/iSecuritizeDegenNFT.d.ts +404 -0
  75. package/dist/types/abi/kyc/iSecuritizeKYCFactory.d.ts +376 -0
  76. package/dist/types/sdk/GearboxSDK.d.ts +7 -0
  77. package/dist/types/sdk/accounts/AbstractCreditAccountsService.d.ts +52 -2
  78. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +1 -1
  79. package/dist/types/sdk/accounts/types.d.ts +93 -13
  80. package/dist/types/sdk/base/TokensMeta.d.ts +14 -3
  81. package/dist/types/sdk/base/token-types.d.ts +44 -4
  82. package/dist/types/sdk/base/types.d.ts +116 -2
  83. package/dist/types/sdk/chain/chains.d.ts +5 -1
  84. package/dist/types/sdk/constants/address-provider.d.ts +1 -0
  85. package/dist/types/sdk/market/MarketRegister.d.ts +6 -9
  86. package/dist/types/sdk/market/MarketSuite.d.ts +2 -0
  87. package/dist/types/sdk/market/index.d.ts +1 -0
  88. package/dist/types/sdk/market/kyc/KYCRegistry.d.ts +52 -0
  89. package/dist/types/sdk/market/kyc/index.d.ts +3 -0
  90. package/dist/types/sdk/market/kyc/securitize/SecuritizeKYCFactory.d.ts +428 -0
  91. package/dist/types/sdk/market/kyc/securitize/constants.d.ts +1 -0
  92. package/dist/types/sdk/market/kyc/securitize/index.d.ts +3 -0
  93. package/dist/types/sdk/market/kyc/securitize/types.d.ts +127 -0
  94. package/dist/types/sdk/market/kyc/types.d.ts +170 -0
  95. package/dist/types/sdk/market/oracle/PriceOracleBaseContract.d.ts +3 -2
  96. package/dist/types/sdk/market/oracle/types.d.ts +3 -10
  97. package/dist/types/sdk/market/pool/PoolSuite.d.ts +2 -0
  98. package/dist/types/sdk/market/pool/PoolV310Contract.d.ts +6 -2
  99. package/dist/types/sdk/market/pool/index.d.ts +1 -0
  100. package/dist/types/sdk/market/pricefeeds/PriceFeedsRegister.d.ts +1 -1
  101. package/dist/types/sdk/market/types.d.ts +1 -1
  102. package/dist/types/sdk/options.d.ts +1 -0
  103. package/dist/types/sdk/pools/PoolService.d.ts +8 -8
  104. package/dist/types/sdk/pools/types.d.ts +1 -1
  105. package/dist/types/sdk/types/state-human.d.ts +2 -0
  106. package/dist/types/sdk/types/state.d.ts +5 -0
  107. package/dist/types/sdk/utils/viem/executeDelegatedMulticalls.d.ts +28 -0
  108. package/dist/types/sdk/utils/viem/index.d.ts +1 -0
  109. package/package.json +8 -7
@@ -52,6 +52,7 @@ class AccountOpener extends import_sdk.SDKConstruct {
52
52
  #minDebtMultiplier;
53
53
  #allowMint;
54
54
  #leverageDelta;
55
+ #poolService;
55
56
  constructor(service, options_ = {}) {
56
57
  super(service.sdk);
57
58
  const {
@@ -77,6 +78,7 @@ class AccountOpener extends import_sdk.SDKConstruct {
77
78
  this.#poolDepositMultiplier = BigInt(poolDepositMultiplier);
78
79
  this.#minDebtMultiplier = BigInt(minDebtMultiplier);
79
80
  this.#leverageDelta = BigInt(leverageDelta);
81
+ this.#poolService = new import_sdk.PoolService(service.sdk);
80
82
  this.#logger?.info(
81
83
  {
82
84
  borrower: (0, import_accounts.privateKeyToAccount)(this.borrowerKey).address,
@@ -114,6 +116,10 @@ class AccountOpener extends import_sdk.SDKConstruct {
114
116
  },
115
117
  "opening credit accounts"
116
118
  );
119
+ await Promise.all([
120
+ this.sdk.tokensMeta.loadTokenData(),
121
+ this.sdk.marketRegister.loadZappers()
122
+ ]);
117
123
  let deposits = [];
118
124
  if (depositIntoPools) {
119
125
  try {
@@ -465,9 +471,34 @@ class AccountOpener extends import_sdk.SDKConstruct {
465
471
  this.#logger?.debug(
466
472
  `depositor balance in underlying: ${this.sdk.tokensMeta.formatBN(pool.underlying, allowance, { symbol: true })}`
467
473
  );
474
+ const tokensOut = this.#poolService.getDepositTokensOut(
475
+ address,
476
+ underlying
477
+ );
478
+ this.#logger?.debug(
479
+ { tokensOut: tokensOut.map((t) => this.labelAddress(t)) },
480
+ "deposit tokens out"
481
+ );
482
+ if (tokensOut.length === 0) {
483
+ throw new Error(`no tokens out found for pool ${poolName}`);
484
+ }
485
+ const tokenOut = tokensOut[0];
486
+ const metadata = this.#poolService.getDepositMetadata(
487
+ address,
488
+ underlying,
489
+ tokenOut
490
+ );
491
+ this.logger?.debug(
492
+ {
493
+ underlying: this.labelAddress(underlying),
494
+ tokenOut: this.labelAddress(tokenOut),
495
+ ...metadata
496
+ },
497
+ "pool deposit metadata"
498
+ );
468
499
  txHash = await this.#anvil.writeContract({
469
500
  account: depositor,
470
- address: underlying,
501
+ address: metadata.approveTarget,
471
502
  abi: import_iERC20.ierc20Abi,
472
503
  functionName: "approve",
473
504
  args: [address, allowance],
@@ -484,12 +515,21 @@ class AccountOpener extends import_sdk.SDKConstruct {
484
515
  this.#logger?.debug(
485
516
  `depositor approved underlying for pool ${poolName}: ${txHash}`
486
517
  );
518
+ const depositCall = this.#poolService.addLiquidity({
519
+ collateral: { token: underlying, balance: amount },
520
+ pool: address,
521
+ wallet: depositor.address,
522
+ meta: metadata
523
+ });
524
+ if (!depositCall) {
525
+ throw new Error(`no deposit call could be created for ${poolName}`);
526
+ }
487
527
  txHash = await this.#anvil.writeContract({
488
528
  account: depositor,
489
- address,
490
- abi: import_generated.iPoolV310Abi,
491
- functionName: "deposit",
492
- args: [amount, depositor.address],
529
+ address: depositCall.target,
530
+ abi: depositCall.abi,
531
+ functionName: depositCall.functionName,
532
+ args: depositCall.args,
493
533
  chain: this.#anvil.chain
494
534
  });
495
535
  receipt = await this.#anvil.waitForTransactionReceipt({ hash: txHash });
@@ -61,6 +61,8 @@ class AdapterTraceAlignmentError extends Error {
61
61
  this.actual = actual;
62
62
  this.name = "AdapterTracesAlignmentError";
63
63
  }
64
+ expected;
65
+ actual;
64
66
  }
65
67
  class UnexpectedFacadeEventOrderError extends Error {
66
68
  constructor(e) {
@@ -27,6 +27,7 @@ var import_base = require("./base/index.js");
27
27
  var import_chain = require("./chain/index.js");
28
28
  var import_constants = require("./constants/index.js");
29
29
  var import_core = require("./core/index.js");
30
+ var import_kyc = require("./market/kyc/index.js");
30
31
  var import_MarketRegister = require("./market/MarketRegister.js");
31
32
  var import_pricefeeds = require("./market/pricefeeds/index.js");
32
33
  var import_plugins = require("./plugins/index.js");
@@ -86,6 +87,7 @@ class GearboxSDK extends import_base.ChainContractsRegister {
86
87
  #addressProvider;
87
88
  #attachConfig;
88
89
  #marketRegister;
90
+ #kyc;
89
91
  #priceFeeds;
90
92
  /**
91
93
  * Gas limit applied to read-only `eth_call` requests.
@@ -130,6 +132,7 @@ class GearboxSDK extends import_base.ChainContractsRegister {
130
132
  ignoreUpdateablePrices,
131
133
  ignoreMarkets,
132
134
  marketConfigurators: mcs,
135
+ kycFactories: kfs,
133
136
  strictContractTypes,
134
137
  gasLimit
135
138
  } = options;
@@ -139,6 +142,7 @@ class GearboxSDK extends import_base.ChainContractsRegister {
139
142
  addressProvider = import_constants.ADDRESS_PROVIDER_V310;
140
143
  }
141
144
  const marketConfigurators = mcs ?? import_utils.TypedObjectUtils.keys(client.chain.defaultMarketConfigurators);
145
+ const kycFactories = kfs ?? client.chain.kycFactories;
142
146
  return new GearboxSDK({
143
147
  client,
144
148
  logger,
@@ -151,6 +155,7 @@ class GearboxSDK extends import_base.ChainContractsRegister {
151
155
  ignoreUpdateablePrices,
152
156
  ignoreMarkets,
153
157
  marketConfigurators,
158
+ kycFactories,
154
159
  redstone,
155
160
  pyth
156
161
  });
@@ -200,6 +205,7 @@ class GearboxSDK extends import_base.ChainContractsRegister {
200
205
  ignoreUpdateablePrices,
201
206
  ignoreMarkets,
202
207
  marketConfigurators,
208
+ kycFactories,
203
209
  redstone,
204
210
  pyth
205
211
  } = opts;
@@ -210,6 +216,7 @@ class GearboxSDK extends import_base.ChainContractsRegister {
210
216
  chainId: this.chainId,
211
217
  addressProvider,
212
218
  marketConfigurators,
219
+ kycFactories,
213
220
  blockNumber,
214
221
  ignoreMarkets
215
222
  },
@@ -244,10 +251,34 @@ class GearboxSDK extends import_base.ChainContractsRegister {
244
251
  );
245
252
  await this.#addressProvider.syncState(this.currentBlock);
246
253
  this.#marketRegister = new import_MarketRegister.MarketRegister(this, ignoreMarkets);
247
- await this.#marketRegister.loadMarkets(
248
- marketConfigurators,
249
- ignoreUpdateablePrices
250
- );
254
+ this.#kyc = new import_kyc.KYCRegistry(this);
255
+ if (!marketConfigurators.length) {
256
+ this.logger?.warn(
257
+ "no market configurators provided, skipping market loading"
258
+ );
259
+ } else {
260
+ const delegated = [
261
+ ...this.#marketRegister.getLoadMulticalls(marketConfigurators),
262
+ ...this.#kyc.getLoadMulticalls(marketConfigurators, kycFactories)
263
+ ];
264
+ let txs = [];
265
+ if (!ignoreUpdateablePrices) {
266
+ const updatables = await this.#priceFeeds.getPartialUpdatablePriceFeeds(
267
+ marketConfigurators
268
+ );
269
+ const updates = await this.#priceFeeds.generatePriceFeedsUpdateTxs(updatables);
270
+ txs = updates.txs;
271
+ }
272
+ this.logger?.debug(
273
+ { configurators: marketConfigurators },
274
+ `calling getMarkets with ${txs.length} price updates in block ${this.currentBlock}`
275
+ );
276
+ await (0, import_viem2.executeDelegatedMulticalls)(this.client, delegated, {
277
+ priceUpdates: txs,
278
+ blockNumber: this.currentBlock,
279
+ gas: this.gasLimit
280
+ });
281
+ }
251
282
  const pluginsList = import_utils.TypedObjectUtils.entries(this.plugins);
252
283
  const pluginResponse = await Promise.allSettled(
253
284
  pluginsList.map(([name, plugin]) => {
@@ -293,12 +324,15 @@ class GearboxSDK extends import_base.ChainContractsRegister {
293
324
  );
294
325
  this.#marketRegister = new import_MarketRegister.MarketRegister(this, ignoreMarkets);
295
326
  this.#marketRegister.hydrate(state.markets);
327
+ this.#kyc = new import_kyc.KYCRegistry(this);
328
+ this.#kyc.setState(state.kyc);
296
329
  this.#attachConfig = {
297
330
  ...opts,
298
331
  addressProvider: this.addressProvider.address,
299
332
  marketConfigurators: this.marketRegister.marketConfigurators.map(
300
333
  (m) => m.address
301
334
  ),
335
+ kycFactories: this.kyc.factories.map((f) => f.address),
302
336
  blockNumber: this.currentBlock
303
337
  };
304
338
  for (const [name, plugin] of import_utils.TypedObjectUtils.entries(this.plugins)) {
@@ -382,6 +416,7 @@ class GearboxSDK extends import_base.ChainContractsRegister {
382
416
  addressProviderV3: this.addressProvider.stateHuman(raw)
383
417
  },
384
418
  tokens: this.tokensMeta.values(),
419
+ kyc: this.kyc.stateHuman(raw),
385
420
  plugins: Object.fromEntries(
386
421
  import_utils.TypedObjectUtils.entries(this.plugins).map(([name, plugin]) => [
387
422
  name,
@@ -407,6 +442,7 @@ class GearboxSDK extends import_base.ChainContractsRegister {
407
442
  timestamp: this.timestamp,
408
443
  addressProvider: this.addressProvider.state,
409
444
  markets: this.marketRegister.state,
445
+ kyc: this.kyc.state,
410
446
  plugins: Object.fromEntries(
411
447
  import_utils.TypedObjectUtils.entries(this.plugins).map(([name, plugin]) => [
412
448
  name,
@@ -603,6 +639,17 @@ class GearboxSDK extends import_base.ChainContractsRegister {
603
639
  }
604
640
  return this.#marketRegister;
605
641
  }
642
+ /**
643
+ * KYC register for KYC-wrapped underlying tokens and factories.
644
+ *
645
+ * @throws If the SDK has not been attached or hydrated yet.
646
+ **/
647
+ get kyc() {
648
+ if (this.#kyc === void 0) {
649
+ throw ERR_NOT_ATTACHED;
650
+ }
651
+ return this.#kyc;
652
+ }
606
653
  /**
607
654
  * Resolves the appropriate router contract for a given credit manager,
608
655
  * credit facade, or explicit version range.
@@ -22,6 +22,7 @@ __export(AbstractCreditAccountsService_exports, {
22
22
  getWithdrawalCompressorAddress: () => getWithdrawalCompressorAddress
23
23
  });
24
24
  module.exports = __toCommonJS(AbstractCreditAccountsService_exports);
25
+ var import_integrations_v3 = require("@gearbox-protocol/integrations-v3");
25
26
  var import_viem = require("viem");
26
27
  var import_generated = require("../../abi/310/generated.js");
27
28
  var import_creditAccountCompressor = require("../../abi/compressors/creditAccountCompressor.js");
@@ -29,10 +30,12 @@ var import_peripheryCompressor = require("../../abi/compressors/peripheryCompres
29
30
  var import_rewardsCompressor = require("../../abi/compressors/rewardsCompressor.js");
30
31
  var import_IWithdrawalCompressorV310 = require("../../abi/IWithdrawalCompressorV310.js");
31
32
  var import_iBaseRewardPool = require("../../abi/iBaseRewardPool.js");
33
+ var import_iKYCFactory = require("../../abi/kyc/iKYCFactory.js");
32
34
  var import_base = require("../base/index.js");
33
35
  var import_chains = require("../chain/chains.js");
34
36
  var import_constants = require("../constants/index.js");
35
37
  var import_market = require("../market/index.js");
38
+ var import_kyc = require("../market/kyc/index.js");
36
39
  var import_router = require("../router/index.js");
37
40
  var import_utils = require("../utils/index.js");
38
41
  var import_viem2 = require("../utils/viem/index.js");
@@ -76,24 +79,40 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
76
79
  } catch (_e) {
77
80
  return void 0;
78
81
  }
82
+ const marketSuite = this.sdk.marketRegister.findByCreditManager(
83
+ raw.creditManager
84
+ );
85
+ const factory = marketSuite.kycFactory;
86
+ let ca;
87
+ let investor;
79
88
  if (raw.success) {
80
- return raw;
89
+ ca = raw;
90
+ investor = await factory?.getInvestor(raw.creditAccount, false);
91
+ } else {
92
+ const { txs: priceUpdateTxs } = await this.getUpdateForAccount(raw);
93
+ [ca, investor] = await (0, import_viem2.simulateWithPriceUpdates)(this.client, {
94
+ priceUpdates: priceUpdateTxs,
95
+ contracts: [
96
+ {
97
+ abi: import_creditAccountCompressor.creditAccountCompressorAbi,
98
+ address: this.#compressor,
99
+ functionName: "getCreditAccountData",
100
+ args: [account]
101
+ },
102
+ ...factory ? [
103
+ {
104
+ abi: import_iKYCFactory.iKYCFactoryAbi,
105
+ address: factory.address,
106
+ functionName: "getInvestor",
107
+ args: [raw.creditAccount]
108
+ }
109
+ ] : []
110
+ ],
111
+ blockNumber,
112
+ gas: this.sdk.gasLimit
113
+ });
81
114
  }
82
- const { txs: priceUpdateTxs } = await this.getUpdateForAccount(raw);
83
- const [cad] = await (0, import_viem2.simulateWithPriceUpdates)(this.client, {
84
- priceUpdates: priceUpdateTxs,
85
- contracts: [
86
- {
87
- abi: import_creditAccountCompressor.creditAccountCompressorAbi,
88
- address: this.#compressor,
89
- functionName: "getCreditAccountData",
90
- args: [account]
91
- }
92
- ],
93
- blockNumber,
94
- gas: this.sdk.gasLimit
95
- });
96
- return cad;
115
+ return { ...ca, investor };
97
116
  }
98
117
  /**
99
118
  * {@inheritDoc ICreditAccountsService.getCreditAccounts}
@@ -149,6 +168,99 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
149
168
  );
150
169
  return allCAs.sort((a, b) => Number(a.healthFactor - b.healthFactor));
151
170
  }
171
+ /**
172
+ * {@inheritDoc ICreditAccountsService.getBorrowerCreditAccounts}
173
+ **/
174
+ async getBorrowerCreditAccounts(borrower, options, blockNumber) {
175
+ const {
176
+ creditManager,
177
+ includeZeroDebt = false,
178
+ maxHealthFactor = import_constants.MAX_UINT256,
179
+ minHealthFactor = 0n,
180
+ ignoreReservePrices = false
181
+ } = options ?? {};
182
+ const { txs: priceUpdateTxs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(
183
+ ignoreReservePrices ? { main: true } : void 0
184
+ );
185
+ const investorDataList = await this.sdk.kyc.getInvestorData(borrower);
186
+ const kycAccountAddresses = investorDataList.flatMap(
187
+ (d) => d.creditAccounts.map((ca) => ca.creditAccount)
188
+ );
189
+ const cmFilter = creditManager ? {
190
+ configurators: [],
191
+ creditManagers: [creditManager],
192
+ pools: [],
193
+ underlying: import_constants.ADDRESS_0X0
194
+ } : {
195
+ configurators: this.marketConfigurators,
196
+ creditManagers: [],
197
+ pools: [],
198
+ underlying: import_constants.ADDRESS_0X0
199
+ };
200
+ const permissiveFilter = {
201
+ owner: borrower,
202
+ includeZeroDebt: true,
203
+ minHealthFactor: 0n,
204
+ maxHealthFactor: import_constants.MAX_UINT256,
205
+ reverting: false
206
+ };
207
+ const kycContracts = kycAccountAddresses.map(
208
+ (account) => ({
209
+ abi: import_creditAccountCompressor.creditAccountCompressorAbi,
210
+ address: this.#compressor,
211
+ functionName: "getCreditAccountData",
212
+ args: [account]
213
+ })
214
+ );
215
+ const getCreditAccountsContracts = [false, true].map(
216
+ (reverting) => ({
217
+ abi: import_creditAccountCompressor.creditAccountCompressorAbi,
218
+ address: this.#compressor,
219
+ functionName: "getCreditAccounts",
220
+ args: [cmFilter, { ...permissiveFilter, reverting }, 0n]
221
+ })
222
+ );
223
+ const allContracts = [...kycContracts, ...getCreditAccountsContracts];
224
+ const results = await (0, import_viem2.simulateWithPriceUpdates)(this.client, {
225
+ priceUpdates: priceUpdateTxs,
226
+ contracts: allContracts,
227
+ blockNumber,
228
+ gas: this.sdk.gasLimit
229
+ });
230
+ const kycResults = results.slice(
231
+ 0,
232
+ kycAccountAddresses.length
233
+ );
234
+ const normalResults = results.slice(kycAccountAddresses.length);
235
+ const seen = new import_utils.AddressSet();
236
+ const allCAs = [];
237
+ for (const ca of kycResults) {
238
+ if (!seen.has(ca.creditAccount)) {
239
+ seen.add(ca.creditAccount);
240
+ allCAs.push({ ...ca, investor: borrower });
241
+ }
242
+ }
243
+ for (const [accounts] of normalResults) {
244
+ for (const ca of accounts) {
245
+ if (!seen.has(ca.creditAccount)) {
246
+ seen.add(ca.creditAccount);
247
+ allCAs.push({ ...ca, investor: void 0 });
248
+ }
249
+ }
250
+ }
251
+ const filtered = allCAs.filter((ca) => {
252
+ if (!includeZeroDebt && ca.debt === 0n) return false;
253
+ if (ca.healthFactor < minHealthFactor) return false;
254
+ if (ca.healthFactor > maxHealthFactor) return false;
255
+ if (creditManager && !(0, import_utils.hexEq)(ca.creditManager, creditManager))
256
+ return false;
257
+ return true;
258
+ });
259
+ this.logger?.debug(
260
+ `loaded ${allCAs.length} borrower credit accounts (${kycResults.length} KYC, ${filtered.length} after filter)`
261
+ );
262
+ return filtered.sort((a, b) => Number(a.healthFactor - b.healthFactor));
263
+ }
152
264
  /**
153
265
  * {@inheritDoc ICreditAccountsService.getRewards}
154
266
  **/
@@ -358,6 +470,13 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
358
470
  closePath
359
471
  }) {
360
472
  const cm = this.sdk.marketRegister.findCreditManager(ca.creditManager);
473
+ await this.sdk.tokensMeta.loadTokenData(cm.underlying);
474
+ const underlying = this.sdk.tokensMeta.mustGet(cm.underlying);
475
+ if (this.sdk.tokensMeta.isKYCUnderlying(underlying)) {
476
+ throw new Error(
477
+ "closeCreditAccount is not supported for KYC underlying credit accounts"
478
+ );
479
+ }
361
480
  const routerCloseResult = closePath || await this.sdk.routerFor(ca).findBestClosePath({
362
481
  creditAccount: ca,
363
482
  creditManager: cm.creditManager,
@@ -463,8 +582,18 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
463
582
  ],
464
583
  {}
465
584
  ) : [];
585
+ const unwrapCalls = collateral && isDecrease ? await this.getKYCUnwrapCalls(
586
+ collateral[0].balance,
587
+ creditAccount.creditManager
588
+ ) || [] : [];
589
+ if (addCollateralCalls.length > 0 && unwrapCalls.length === 0 && collateral && collateral?.[0].token !== creditAccount.underlying) {
590
+ throw new Error(
591
+ "Can't use collateral other than underlying for non KYC market"
592
+ );
593
+ }
466
594
  const operationCalls = [
467
595
  ...addCollateralCalls,
596
+ ...unwrapCalls,
468
597
  this.#prepareChangeDebt(creditAccount.creditFacade, change, isDecrease)
469
598
  ];
470
599
  const calls = await this.prependPriceUpdates(
@@ -672,6 +801,30 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
672
801
  const tx = await this.multicallTx(cm, creditAccount.creditAccount, calls);
673
802
  return { tx, calls, creditFacade: cm.creditFacade };
674
803
  }
804
+ /**
805
+ * {@inheritDoc ICreditAccountsService.getApprovalAddress}
806
+ **/
807
+ async getApprovalAddress(options) {
808
+ const { creditManager } = options;
809
+ const suite = this.sdk.marketRegister.findCreditManager(creditManager);
810
+ const marketSuite = this.sdk.marketRegister.findByPool(suite.pool);
811
+ const factory = marketSuite.kycFactory;
812
+ if (factory) {
813
+ return factory.getApprovalAddress(options);
814
+ }
815
+ return suite.creditManager.address;
816
+ }
817
+ /**
818
+ * {@inheritDoc ICreditAccountsService.getOpenAccountRequirements}
819
+ */
820
+ async getOpenAccountRequirements(borrower, props) {
821
+ const { creditManager } = props;
822
+ const { kycFactory } = this.sdk.marketRegister.findByCreditManager(creditManager);
823
+ if (!kycFactory) {
824
+ return void 0;
825
+ }
826
+ return kycFactory.getOpenAccountRequirements(borrower);
827
+ }
675
828
  /**
676
829
  * {@inheritDoc ICreditAccountsService.openCA}
677
830
  **/
@@ -806,6 +959,131 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
806
959
  return resp;
807
960
  }
808
961
  /**
962
+ * Returns multicall entries to redeem (unwrap) KYC ERC-4626 vault shares into underlying for the given credit manager.
963
+ * Used when withdrawing debt from a KYC market: redeems adapter vault shares so the underlying can be withdrawn.
964
+ * Only applies when the credit manager's underlying is KYC-gated and has an ERC-4626 adapter configured.
965
+ * @param amount - Number of vault shares (adapter tokens) to redeem
966
+ * @param creditManager - Credit manager address
967
+ * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not KYC or no adapter is configured
968
+ */
969
+ async getKYCUnwrapCalls(amount, creditManager) {
970
+ const suite = this.sdk.marketRegister.findCreditManager(creditManager);
971
+ const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
972
+ if (!this.sdk.tokensMeta.isKYCUnderlying(meta)) {
973
+ return void 0;
974
+ }
975
+ const adapter = suite.creditManager.adapters.get(meta.addr);
976
+ const adapterAddress = adapter?.address;
977
+ if (!adapterAddress) {
978
+ return void 0;
979
+ }
980
+ const mc = [
981
+ {
982
+ target: adapterAddress,
983
+ callData: (0, import_viem.encodeFunctionData)({
984
+ abi: import_integrations_v3.ierc4626AdapterAbi,
985
+ functionName: "redeem",
986
+ args: [amount, import_constants.ADDRESS_0X0, import_constants.ADDRESS_0X0]
987
+ })
988
+ }
989
+ ];
990
+ return mc;
991
+ }
992
+ /**
993
+ * Returns multicall entries to deposit (wrap) underlying into KYC ERC-4626 vault shares for the given credit manager.
994
+ * Used when adding debt on a KYC market: deposits underlying into the adapter vault so shares are minted on the account.
995
+ * Only applies when the credit manager's underlying is KYC-gated and has an ERC-4626 adapter configured.
996
+ * @param amount - Amount of underlying assets to deposit into the vault (in underlying decimals)
997
+ * @param creditManager - Credit manager address
998
+ * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not KYC or no adapter is configured
999
+ */
1000
+ async getKYCWrapCalls(amount, creditManager) {
1001
+ const suite = this.sdk.marketRegister.findCreditManager(creditManager);
1002
+ const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
1003
+ if (!this.sdk.tokensMeta.isKYCUnderlying(meta)) {
1004
+ return void 0;
1005
+ }
1006
+ const adapter = suite.creditManager.adapters.get(meta.addr);
1007
+ const adapterAddress = adapter?.address;
1008
+ if (!adapterAddress) {
1009
+ return void 0;
1010
+ }
1011
+ const mc = [
1012
+ {
1013
+ target: adapterAddress,
1014
+ callData: (0, import_viem.encodeFunctionData)({
1015
+ abi: import_integrations_v3.ierc4626AdapterAbi,
1016
+ functionName: "deposit",
1017
+ args: [amount, import_constants.ADDRESS_0X0]
1018
+ })
1019
+ }
1020
+ ];
1021
+ return mc;
1022
+ }
1023
+ /**
1024
+ * Returns multicall entries to call redeemDiff on the KYC ERC-4626 adapter for the given credit manager.
1025
+ * Redeems the leftover vault shares (e.g. after repaying debt) so the account does not hold excess KYC vault tokens.
1026
+ * Only applies when the credit manager's underlying is KYC-gated and has an ERC-4626 adapter configured.
1027
+ * @param amount - Leftover vault share amount to redeem (in adapter/vault decimals)
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 getRedeemDiffCalls(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: import_integrations_v3.ierc4626AdapterAbi,
1047
+ functionName: "redeemDiff",
1048
+ args: [amount]
1049
+ })
1050
+ }
1051
+ ];
1052
+ return mc;
1053
+ }
1054
+ /**
1055
+ * Returns multicall entries to call depositDiff on the KYC ERC-4626 adapter for the given credit manager.
1056
+ * Deposits the leftover underlying (e.g. after decreasing debt) into the vault so the account does not hold excess underlying.
1057
+ * Only applies when the credit manager's underlying is KYC-gated and has an ERC-4626 adapter configured.
1058
+ * @param amount - Leftover underlying amount 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 getDepositDiffCalls(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: import_integrations_v3.ierc4626AdapterAbi,
1078
+ functionName: "depositDiff",
1079
+ args: [amount]
1080
+ })
1081
+ }
1082
+ ];
1083
+ return mc;
1084
+ }
1085
+ /**
1086
+ * Returns raw txs that are needed to update all price feeds so that all credit accounts (possibly from different markets) compute
809
1087
  * {@inheritDoc ICreditAccountsService.getOnDemandPriceUpdates}
810
1088
  **/
811
1089
  async getOnDemandPriceUpdates(account, ignoreReservePrices) {
@@ -1063,6 +1341,17 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
1063
1341
  * @returns
1064
1342
  */
1065
1343
  async openCreditAccountTx(suite, to, calls, referralCode) {
1344
+ const marketSuite = this.sdk.marketRegister.findByPool(suite.pool);
1345
+ const factory = marketSuite.kycFactory;
1346
+ if (factory && (0, import_kyc.isKYCFactory)(factory, import_kyc.KYC_FACTORY_SECURITIZE)) {
1347
+ const tokensToRegister = factory.dsTokens.map(
1348
+ (t) => t.address
1349
+ );
1350
+ return factory.openCreditAccount(suite.creditManager.address, calls, {
1351
+ tokensToRegister,
1352
+ signaturesToCache: []
1353
+ });
1354
+ }
1066
1355
  return suite.creditFacade.openCreditAccount(to, calls, referralCode ?? 0n);
1067
1356
  }
1068
1357
  /**
@@ -1073,6 +1362,13 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
1073
1362
  * @returns
1074
1363
  */
1075
1364
  async multicallTx(suite, creditAccount, calls) {
1365
+ const marketSuite = this.sdk.marketRegister.findByCreditManager(
1366
+ suite.creditManager.address
1367
+ );
1368
+ const factory = marketSuite.kycFactory;
1369
+ if (factory) {
1370
+ return factory.multicall(creditAccount, calls);
1371
+ }
1076
1372
  return suite.creditFacade.multicall(creditAccount, calls);
1077
1373
  }
1078
1374
  /**
@@ -1084,9 +1380,21 @@ class AbstractCreditAccountService extends import_base.SDKConstruct {
1084
1380
  * @returns
1085
1381
  */
1086
1382
  async closeCreditAccountTx(suite, creditAccount, calls, operation) {
1383
+ const marketSuite = this.sdk.marketRegister.findByCreditManager(
1384
+ suite.creditManager.address
1385
+ );
1386
+ const factory = marketSuite.kycFactory;
1087
1387
  if (operation === "close") {
1388
+ if (factory) {
1389
+ throw new Error(
1390
+ "CloseOptions=close is not supported for KYC underlying credit accounts"
1391
+ );
1392
+ }
1088
1393
  return suite.creditFacade.closeCreditAccount(creditAccount, calls);
1089
1394
  }
1395
+ if (factory) {
1396
+ return factory.multicall(creditAccount, calls);
1397
+ }
1090
1398
  return suite.creditFacade.multicall(creditAccount, calls);
1091
1399
  }
1092
1400
  }