@gearbox-protocol/sdk 3.0.0-vfour.280 → 3.0.0-vfour.282

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.
@@ -25,10 +25,12 @@ var import_viem = require("viem");
25
25
  var import_compressors = require("../../abi/compressors.js");
26
26
  var import_iBaseRewardPool = require("../../abi/iBaseRewardPool.js");
27
27
  var import_v300 = require("../../abi/v300.js");
28
+ var import_adapters = require("../../adapters/abi/adapters.js");
28
29
  var import_base = require("../base/index.js");
29
30
  var import_constants = require("../constants/index.js");
30
31
  var import_market = require("../market/index.js");
31
32
  var import_router = require("../router/index.js");
33
+ var import_sdk_gov_legacy = require("../sdk-gov-legacy/index.js");
32
34
  var import_utils = require("../utils/index.js");
33
35
  var import_viem2 = require("../utils/viem/index.js");
34
36
  class CreditAccountsService extends import_base.SDKConstruct {
@@ -142,6 +144,12 @@ class CreditAccountsService extends import_base.SDKConstruct {
142
144
  }
143
145
  return allCAs.sort((a, b) => Number(a.healthFactor - b.healthFactor));
144
146
  }
147
+ /**
148
+ * Method to get all claimable rewards for credit account (ex. stkUSDS SKY rewards)
149
+ Assosiates rewards by adapter + stakedPhantomToken
150
+ * @param {Address} creditAccount - address of credit account to get rewards for
151
+ * @returns {Array<Rewards>} list of {@link Rewards} that can be claimed
152
+ */
145
153
  async getRewards(creditAccount) {
146
154
  const rewards = await this.provider.publicClient.readContract({
147
155
  abi: import_compressors.iRewardsCompressorAbi,
@@ -160,7 +168,7 @@ class CreditAccountsService extends import_base.SDKConstruct {
160
168
  functionName: "getReward",
161
169
  args: []
162
170
  });
163
- acc[adapter] = {
171
+ acc[key] = {
164
172
  adapter,
165
173
  stakedPhantomToken,
166
174
  calls: [
@@ -172,7 +180,7 @@ class CreditAccountsService extends import_base.SDKConstruct {
172
180
  rewards: []
173
181
  };
174
182
  }
175
- acc[adapter].rewards.push({
183
+ acc[key].rewards.push({
176
184
  token: rewardToken,
177
185
  balance: r2.amount
178
186
  });
@@ -180,6 +188,11 @@ class CreditAccountsService extends import_base.SDKConstruct {
180
188
  }, {});
181
189
  return Object.values(r);
182
190
  }
191
+ /**
192
+ * Method to get all connected bots for credit account
193
+ * @param {Array<{ creditAccount: Address; creditManager: Address }>} accountsToCheck - list of credit accounts to check connected bots on
194
+ * @returns call result of getConnectedBots for each credit account
195
+ */
183
196
  async getConnectedBots(accountsToCheck) {
184
197
  const resp = await this.provider.publicClient.multicall({
185
198
  contracts: accountsToCheck.map((o) => {
@@ -225,14 +238,20 @@ class CreditAccountsService extends import_base.SDKConstruct {
225
238
  return { tx, calls, routerCloseResult, creditFacade: cm.creditFacade };
226
239
  }
227
240
  /**
228
- * Closes credit account or sets debt to zero (but keep account)
229
- * @param operation
230
- * @param creditAccount
231
- * @param assetsToWithdraw Tokens to withdraw from credit account
232
- * @param to Address to withdraw underlying to
233
- * @param slippage
234
- * @param closePath
235
- * @returns
241
+ * Closes credit account or closes credit account and keeps it open with zero debt.
242
+ Ca is closed in the following order: price update -> close path to swap all tokens into underlying ->
243
+ -> disable quotas of exiting tokens -> decrease debt -> disable exiting tokens tokens -> withdraw underlying tokenz
244
+ * @param {CloseOptions} operation - {@link CloseOptions}: close or zeroDebt
245
+ * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice}
246
+ * @param {Array<Address>} assetsToWithdraw - tokens to withdraw from credit account.
247
+ For credit account closing this is the underlying token, because during the closure,
248
+ all tokens on account are swapped into the underlying,
249
+ and only the underlying token will remain on the credit account
250
+ * @param {Address} to - Wallet address to withdraw underlying to
251
+ * @param {number} slippage - SLIPPAGE_DECIMALS = 100n
252
+ * @default 50n
253
+ * @param {RouterCloseResult | undefined} closePath - result of findBestClosePath method from router; if omited, calls marketRegister.findCreditManager {@link RouterCloseResult}
254
+ * @returns All necessary data to execute the transaction (call, credit facade)
236
255
  */
237
256
  async closeCreditAccount({
238
257
  operation,
@@ -267,20 +286,26 @@ class CreditAccountsService extends import_base.SDKConstruct {
267
286
  return { tx, calls, routerCloseResult, creditFacade: cm.creditFacade };
268
287
  }
269
288
  /**
270
- * Repays credit account or sets debt to zero (but keep account)
271
- * @param operation
272
- * @param creditAccount
273
- * @param assetsToWithdraw Tokens to withdraw from credit account
274
- * @param collateralAssets Tokens to pay for
275
- * @param to Address to withdraw underlying to
276
- * @param slippage
277
- * @param permits
278
- * @returns
289
+ * Fully repays credit account or repays credit account and keeps it open with zero debt
290
+ Repays in the following order: price update -> add collateral to cover the debt ->
291
+ -> disable quotas for all tokens -> decrease debt -> disable tokens all tokens -> withdraw all tokens
292
+ * @param {CloseOptions} operation - {@link CloseOptions}: close or zeroDebt
293
+ * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice}
294
+ * @param {Array<Address>} collateralAssets - tokens to repay dept.
295
+ In the current implementation, this is the (debt+interest+fess) * buffer,
296
+ where buffer refers to amount of tokens which will exceed current debt
297
+ in order to cover possible debt increase over tx execution
298
+ * @param {Array<Asset>} assetsToWithdraw - tokens to withdraw from credit account.
299
+ Typically all non zero ca assets (including unclaimed rewards)
300
+ plus underlying token (to withdraw any exceeding underlying token after repay)
301
+ * @param {Record<Address, PermitResult>} permits - permits of tokens to withdraw (in any permittable token is present) {@link PermitResult}
302
+ * @param {Address} to - Wallet address to withdraw underlying to
303
+ * @returns All necessary data to execute the transaction (call, credit facade)
279
304
  */
280
305
  async repayCreditAccount({
281
306
  operation,
282
307
  collateralAssets,
283
- assetsToWithdraw,
308
+ assetsToWithdraw: wrapped,
284
309
  creditAccount: ca,
285
310
  permits,
286
311
  to
@@ -292,32 +317,46 @@ class CreditAccountsService extends import_base.SDKConstruct {
292
317
  ca,
293
318
  void 0
294
319
  );
320
+ const { unwrapCalls, assetsToWithdraw } = this.#prepareUnwrapAndWithdrawCallsV3(
321
+ wrapped,
322
+ true,
323
+ true,
324
+ ca.creditManager
325
+ );
295
326
  const calls = [
296
327
  ...priceUpdates,
297
328
  ...this.#prepareAddCollateral(ca.creditFacade, addCollateral, permits),
298
329
  ...this.#prepareDisableQuotas(ca),
299
330
  ...this.#prepareDecreaseDebt(ca),
331
+ ...unwrapCalls,
300
332
  ...this.#prepareDisableTokens(ca),
301
333
  // TODO: probably needs a better way to handle reward tokens
302
334
  ...assetsToWithdraw.map(
303
- (t) => this.#prepareWithdrawToken(ca.creditFacade, t, import_constants.MAX_UINT256, to)
335
+ (t) => this.#prepareWithdrawToken(ca.creditFacade, t.token, import_constants.MAX_UINT256, to)
304
336
  )
305
337
  ];
306
338
  const tx = operation === "close" ? cm.creditFacade.closeCreditAccount(ca.creditAccount, calls) : cm.creditFacade.multicall(ca.creditAccount, calls);
307
339
  return { tx, calls, creditFacade: cm.creditFacade };
308
340
  }
309
341
  /**
310
- * Repays liquidatable credit account
311
- * @param creditAccount
312
- * @param assetsToWithdraw Tokens to withdraw from credit account
313
- * @param collateralAssets Tokens to pay for
314
- * @param to Address to withdraw underlying to
315
- * @param slippage
316
- * @returns
342
+ * Fully repays liquidatable account
343
+ Repay and liquidate is executed in the following order: price update -> add collateral to cover the debt ->
344
+ withdraw all tokens from credit account
345
+ * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice}
346
+ * @param {Array<Address>} collateralAssets - tokens to repay dept.
347
+ In the current implementation, this is the (debt+interest+fess) * buffer,
348
+ where buffer refers to amount of tokens which will exceed current debt
349
+ in order to cover possible debt increase over tx execution
350
+ * @param {Array<Address>} assetsToWithdraw - tokens to withdraw from credit account.
351
+ Typically all non zero ca assets (including unclaimed rewards)
352
+ plus underlying token (to withdraw any exceeding underlying token after repay)
353
+ * @param {Record<Address, PermitResult>} permits - permits of tokens to withdraw (in any permittable token is present) {@link PermitResult}
354
+ * @param {Address} to - Wallet address to withdraw underlying to
355
+ * @returns All necessary data to execute the transaction (call, credit facade)
317
356
  */
318
357
  async repayAndLiquidateCreditAccount({
319
358
  collateralAssets,
320
- assetsToWithdraw,
359
+ assetsToWithdraw: wrapped,
321
360
  creditAccount: ca,
322
361
  permits,
323
362
  to
@@ -329,11 +368,18 @@ class CreditAccountsService extends import_base.SDKConstruct {
329
368
  void 0
330
369
  );
331
370
  const addCollateral = collateralAssets.filter((a) => a.balance > 0);
371
+ const { unwrapCalls, assetsToWithdraw } = this.#prepareUnwrapAndWithdrawCallsV3(
372
+ wrapped,
373
+ true,
374
+ true,
375
+ ca.creditManager
376
+ );
332
377
  const calls = [
333
378
  ...priceUpdates,
334
379
  ...this.#prepareAddCollateral(ca.creditFacade, addCollateral, permits),
380
+ ...unwrapCalls,
335
381
  ...assetsToWithdraw.map(
336
- (t) => this.#prepareWithdrawToken(ca.creditFacade, t, import_constants.MAX_UINT256, to)
382
+ (t) => this.#prepareWithdrawToken(ca.creditFacade, t.token, import_constants.MAX_UINT256, to)
337
383
  )
338
384
  ];
339
385
  const tx = cm.creditFacade.liquidateCreditAccount(
@@ -343,8 +389,19 @@ class CreditAccountsService extends import_base.SDKConstruct {
343
389
  );
344
390
  return { tx, calls, creditFacade: cm.creditFacade };
345
391
  }
346
- async updateQuotas(props) {
347
- const { creditAccount } = props;
392
+ /**
393
+ * Updates quota of credit account.
394
+ CA quota updated in the following order: price update -> update quotas
395
+ * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice}
396
+ * @param {Array<Asset>} averageQuota - average quota for desired tokens {@link Asset}
397
+ * @param {Array<Asset>} minQuota - minimum quota for desired tokens {@link Asset}
398
+ * @returns All necessary data to execute the transaction (call, credit facade)
399
+ */
400
+ async updateQuotas({
401
+ minQuota,
402
+ averageQuota,
403
+ creditAccount
404
+ }) {
348
405
  const cm = this.sdk.marketRegister.findCreditManager(
349
406
  creditAccount.creditManager
350
407
  );
@@ -355,23 +412,46 @@ class CreditAccountsService extends import_base.SDKConstruct {
355
412
  );
356
413
  const calls = [
357
414
  ...priceUpdates,
358
- ...this.#prepareUpdateQuotas(props.creditAccount.creditFacade, props)
415
+ ...this.#prepareUpdateQuotas(creditAccount.creditFacade, {
416
+ minQuota,
417
+ averageQuota
418
+ })
359
419
  ];
360
420
  const tx = cm.creditFacade.multicall(creditAccount.creditAccount, [
361
421
  ...priceUpdates,
362
- ...this.#prepareUpdateQuotas(props.creditAccount.creditFacade, props)
422
+ ...this.#prepareUpdateQuotas(creditAccount.creditFacade, {
423
+ minQuota,
424
+ averageQuota
425
+ })
363
426
  ]);
364
427
  return { tx, calls, creditFacade: cm.creditFacade };
365
428
  }
366
- async addCollateral(props) {
367
- const { creditAccount, asset, permit, ethAmount } = props;
429
+ /**
430
+ * Adds a single collateral to credit account and updates quotas
431
+ Collateral is added in the following order: price update -> add collateral (with permit) -> update quotas
432
+ * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice}
433
+ * @param {Array<Asset>} averageQuota - average quota for desired token {@link Asset}
434
+ * @param {Array<Asset>} minQuota - minimum quota for desired token {@link Asset}
435
+ * @param {Asset} asset - asset to add as collateral {@link Asset}
436
+ * @param {PermitResult | undefined} permits - permits of collateral asset if it is permittable {@link PermitResult}
437
+ * @param {bigint} ethAmount - native token amount to attach to tx
438
+ * @returns All necessary data to execute the transaction (call, credit facade)
439
+ */
440
+ async addCollateral({
441
+ creditAccount,
442
+ asset,
443
+ permit,
444
+ ethAmount,
445
+ minQuota,
446
+ averageQuota
447
+ }) {
368
448
  const cm = this.sdk.marketRegister.findCreditManager(
369
449
  creditAccount.creditManager
370
450
  );
371
451
  const priceUpdatesCalls = await this.getPriceUpdatesForFacade(
372
452
  creditAccount.creditManager,
373
453
  creditAccount,
374
- props.averageQuota
454
+ averageQuota
375
455
  );
376
456
  const calls = [
377
457
  ...priceUpdatesCalls,
@@ -380,12 +460,25 @@ class CreditAccountsService extends import_base.SDKConstruct {
380
460
  [asset],
381
461
  permit ? { [asset.token]: permit } : {}
382
462
  ),
383
- ...this.#prepareUpdateQuotas(creditAccount.creditFacade, props)
463
+ ...this.#prepareUpdateQuotas(creditAccount.creditFacade, {
464
+ minQuota,
465
+ averageQuota
466
+ })
384
467
  ];
385
468
  const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
386
469
  tx.value = ethAmount.toString(10);
387
470
  return { tx, calls, creditFacade: cm.creditFacade };
388
471
  }
472
+ /**
473
+ * Increases or decreases debt of credit account; debt decrease uses token ON CREDIT ACCOUNT
474
+ Debt is changed in the following order: price update -> (enables underlying if it was disabled) -> change debt
475
+ * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice}
476
+ * @param {bigint} amount - amount to change debt by;
477
+ 0 - prohibited value;
478
+ negative value for debt decrease;
479
+ positive value for debt increase.
480
+ * @returns All necessary data to execute the transaction (call, credit facade)
481
+ */
389
482
  async changeDebt({
390
483
  creditAccount,
391
484
  amount
@@ -415,8 +508,24 @@ class CreditAccountsService extends import_base.SDKConstruct {
415
508
  const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
416
509
  return { tx, calls, creditFacade: cm.creditFacade };
417
510
  }
418
- async withdrawCollateral(props) {
419
- const { creditAccount, assetsToWithdraw, to } = props;
511
+ /**
512
+ * Withdraws a single collateral from credit account to wallet to and updates quotas;
513
+ technically can withdraw several tokens at once
514
+ Collateral is withdrawn in the following order: price update -> withdraw token -> update quotas for affected tokens
515
+ * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice}
516
+ * @param {Array<Asset>} averageQuota - average quota for desired token {@link Asset}
517
+ * @param {Array<Asset>} minQuota - minimum quota for desired token {@link Asset}
518
+ * @param {Address} to - Wallet address to withdraw token to
519
+ * @param {Array<Asset>} assetsToWithdraw - permits for asset if it is permittable {@link PermitResult}
520
+ * @returns All necessary data to execute the transaction (call, credit facade)
521
+ */
522
+ async withdrawCollateral({
523
+ creditAccount,
524
+ assetsToWithdraw: wrapped,
525
+ to,
526
+ minQuota,
527
+ averageQuota
528
+ }) {
420
529
  const cm = this.sdk.marketRegister.findCreditManager(
421
530
  creditAccount.creditManager
422
531
  );
@@ -425,8 +534,15 @@ class CreditAccountsService extends import_base.SDKConstruct {
425
534
  creditAccount,
426
535
  void 0
427
536
  );
537
+ const { unwrapCalls, assetsToWithdraw } = this.#prepareUnwrapAndWithdrawCallsV3(
538
+ wrapped,
539
+ false,
540
+ false,
541
+ creditAccount.creditManager
542
+ );
428
543
  const calls = [
429
544
  ...priceUpdatesCalls,
545
+ ...unwrapCalls,
430
546
  ...assetsToWithdraw.map(
431
547
  (a) => this.#prepareWithdrawToken(
432
548
  creditAccount.creditFacade,
@@ -435,13 +551,29 @@ class CreditAccountsService extends import_base.SDKConstruct {
435
551
  to
436
552
  )
437
553
  ),
438
- ...this.#prepareUpdateQuotas(creditAccount.creditFacade, props)
554
+ ...this.#prepareUpdateQuotas(creditAccount.creditFacade, {
555
+ minQuota,
556
+ averageQuota
557
+ })
439
558
  ];
440
559
  const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
441
560
  return { tx, calls, creditFacade: cm.creditFacade };
442
561
  }
443
- async executeSwap(props) {
444
- const { creditAccount, calls: swapCalls } = props;
562
+ /**
563
+ * Executes swap specified by given calls, update quotas of affected tokens
564
+ Swap is executed in the following order: price update -> execute swap path -> update quotas
565
+ * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice}
566
+ * @param {Array<Asset>} averageQuota - average quota for desired token {@link Asset}
567
+ * @param {Array<Asset>} minQuota - minimum quota for desired token {@link Asset}
568
+ * @param {Array<MultiCall>} calls - array of MultiCall from router methods getSingleSwap or getAllSwaps {@link MultiCall}
569
+ * @returns All necessary data to execute the transaction (call, credit facade)
570
+ */
571
+ async executeSwap({
572
+ creditAccount,
573
+ calls: swapCalls,
574
+ minQuota,
575
+ averageQuota
576
+ }) {
445
577
  if (swapCalls.length === 0) throw new Error("No path to execute");
446
578
  const cm = this.sdk.marketRegister.findCreditManager(
447
579
  creditAccount.creditManager
@@ -449,24 +581,46 @@ class CreditAccountsService extends import_base.SDKConstruct {
449
581
  const priceUpdatesCalls = await this.getPriceUpdatesForFacade(
450
582
  creditAccount.creditManager,
451
583
  creditAccount,
452
- props.averageQuota
584
+ averageQuota
453
585
  );
454
586
  const calls = [
455
587
  ...priceUpdatesCalls,
456
588
  ...swapCalls,
457
- ...this.#prepareUpdateQuotas(creditAccount.creditFacade, props)
589
+ ...this.#prepareUpdateQuotas(creditAccount.creditFacade, {
590
+ minQuota,
591
+ averageQuota
592
+ })
458
593
  ];
459
594
  const tx = cm.creditFacade.multicall(creditAccount.creditAccount, calls);
460
595
  return { tx, calls, creditFacade: cm.creditFacade };
461
596
  }
462
- async claimFarmRewards(props) {
463
- const { tokensToDisable, calls: claimCalls, creditAccount: ca } = props;
597
+ /**
598
+ * Executes swap specified by given calls, update quotas of affected tokens
599
+ Claim rewards is executed in the following order: price update -> execute claim calls ->
600
+ -> (optionally: disable reward tokens) -> (optionally: update quotas)
601
+ * @param {RouterCASlice} creditAccount - minimal credit account data {@link RouterCASlice}
602
+ * @param {Array<Asset>} averageQuota - average quota for desired token;
603
+ in this case can be omitted since rewards tokens do not require quotas {@link Asset}
604
+ * @param {Array<Asset>} minQuota - minimum quota for desired token;
605
+ in this case can be omitted since rewards tokens do not require quotas {@link Asset}
606
+ * @param {Array<MultiCall>} calls - array of MultiCall from getRewards {@link MultiCall}
607
+ * @param {Array<Asset>} tokensToDisable - tokens to disable after rewards claiming;
608
+ sometimes is needed since old credit facade used to enable tokens on claim {@link Asset}
609
+ * @returns All necessary data to execute the transaction (call, credit facade)
610
+ */
611
+ async claimFarmRewards({
612
+ tokensToDisable,
613
+ calls: claimCalls,
614
+ creditAccount: ca,
615
+ minQuota,
616
+ averageQuota
617
+ }) {
464
618
  if (claimCalls.length === 0) throw new Error("No path to execute");
465
619
  const cm = this.sdk.marketRegister.findCreditManager(ca.creditManager);
466
620
  const priceUpdatesCalls = await this.getPriceUpdatesForFacade(
467
621
  ca.creditManager,
468
622
  ca,
469
- props.averageQuota
623
+ averageQuota
470
624
  );
471
625
  const calls = [
472
626
  ...priceUpdatesCalls,
@@ -474,35 +628,63 @@ class CreditAccountsService extends import_base.SDKConstruct {
474
628
  ...tokensToDisable.map(
475
629
  (a) => this.#prepareDisableToken(ca.creditFacade, a.token)
476
630
  ),
477
- ...this.#prepareUpdateQuotas(ca.creditFacade, props)
631
+ ...this.#prepareUpdateQuotas(ca.creditFacade, { minQuota, averageQuota })
478
632
  ];
479
633
  const tx = cm.creditFacade.multicall(ca.creditAccount, calls);
480
634
  return { tx, calls, creditFacade: cm.creditFacade };
481
635
  }
482
- async openCA(props) {
483
- const {
484
- ethAmount,
485
- creditManager,
486
- collateral,
487
- permits,
488
- debt,
489
- withdrawDebt,
490
- referralCode,
491
- to,
492
- calls: openPathCalls
493
- } = props;
636
+ /**
637
+ * Executes swap specified by given calls, update quotas of affected tokens
638
+ Open credit account is executed in the following order: price update -> increase debt -> add collateral ->
639
+ -> update quotas -> (optionally: execute swap path for trading/strategy) ->
640
+ -> (optionally: withdraw debt for lending)
641
+ Basic open credit account: price update -> increase debt -> add collateral -> update quotas
642
+ Lending: price update -> increase debt -> add collateral -> update quotas -> withdraw debt
643
+ Strategy/trading: price update -> increase debt -> add collateral -> update quotas -> execute swap path
644
+ In strategy is possible situation when collateral is added, but not swapped; the only swapped value in this case will be debt
645
+ * @param {bigint} ethAmount - native token amount to attach to tx
646
+ * @param {Address} creditManager - address of credit manager to open credit account on
647
+ * @param {Array<Asset>} collateral - array of collateral which can be just directly added or swapped using the path {@link Asset}
648
+ * @param {Record<Address, PermitResult>} permits - permits of collateral tokens (in any permittable token is present) {@link PermitResult}
649
+ * @param {bigint} debt - debt to open credit account with
650
+ * @param {boolean} withdrawDebt - flag to withdraw debt to wallet after opening credit account;
651
+ used for borrowing functionality
652
+ * @param {bigint} referralCode - referral code to open credit account with
653
+ * @param {Address} to - wallet address to transfer credit account to\
654
+ * @param {Array<MultiCall>} calls - array of MultiCall from router methods findOpenStrategyPath {@link MultiCall}.
655
+ Used for trading and strategy functionality
656
+ * @param {Array<Asset>} averageQuota - average quota for tokens after open {@link Asset}
657
+ * @param {Array<Asset>} minQuota - minimum quota for tokens after open {@link Asset}
658
+ * @returns All necessary data to execute the transaction (call, credit facade)
659
+ */
660
+ async openCA({
661
+ ethAmount,
662
+ creditManager,
663
+ collateral,
664
+ permits,
665
+ debt,
666
+ withdrawDebt,
667
+ referralCode,
668
+ to,
669
+ calls: openPathCalls,
670
+ minQuota,
671
+ averageQuota
672
+ }) {
494
673
  const cmSuite = this.sdk.marketRegister.findCreditManager(creditManager);
495
674
  const cm = cmSuite.creditManager;
496
675
  const priceUpdatesCalls = await this.getPriceUpdatesForFacade(
497
676
  cm.address,
498
677
  void 0,
499
- props.averageQuota
678
+ averageQuota
500
679
  );
501
680
  const calls = [
502
681
  ...priceUpdatesCalls,
503
682
  this.#prepareIncreaseDebt(cm.creditFacade, debt),
504
683
  ...this.#prepareAddCollateral(cm.creditFacade, collateral, permits),
505
- ...this.#prepareUpdateQuotas(cm.creditFacade, props),
684
+ ...this.#prepareUpdateQuotas(cm.creditFacade, {
685
+ minQuota,
686
+ averageQuota
687
+ }),
506
688
  ...openPathCalls,
507
689
  ...withdrawDebt ? [this.#prepareWithdrawToken(cm.creditFacade, cm.underlying, debt, to)] : []
508
690
  ];
@@ -712,7 +894,8 @@ class CreditAccountsService extends import_base.SDKConstruct {
712
894
  #prepareDisableTokens(ca) {
713
895
  const calls = [];
714
896
  for (const t of ca.tokens) {
715
- if (t.token !== ca.underlying && (t.mask & ca.enabledTokensMask) !== 0n && t.quota === 0n) {
897
+ const isEnabled = (t.mask & ca.enabledTokensMask) !== 0n;
898
+ if (t.token !== ca.underlying && isEnabled && t.quota === 0n) {
716
899
  calls.push(this.#prepareDisableToken(ca.creditFacade, t.token));
717
900
  }
718
901
  }
@@ -792,6 +975,174 @@ class CreditAccountsService extends import_base.SDKConstruct {
792
975
  });
793
976
  return calls;
794
977
  }
978
+ /**
979
+ * unwraps staked tokens and optionally claims associated rewards; Should be remove after transition to 3.1
980
+ * @param acc
981
+ * @returns
982
+ */
983
+ #prepareUnwrapAndWithdrawCallsV3(assets, claim, withdrawAll, creditManager) {
984
+ const network = this.sdk.provider.networkType;
985
+ const suite = this.sdk.marketRegister.findCreditManager(creditManager);
986
+ const cmAdapters = suite.creditManager.adapters.values().reduce((acc, a) => {
987
+ const contractLc = a.targetContract.toLowerCase();
988
+ const adapterLc = a.address.toLowerCase();
989
+ acc[contractLc] = adapterLc;
990
+ return acc;
991
+ }, {});
992
+ const currentContractsData = Object.entries(
993
+ import_sdk_gov_legacy.contractsByNetwork[network]
994
+ ).reduce(
995
+ (acc, [symbol, address]) => {
996
+ if (!!address && address !== import_constants.NOT_DEPLOYED) {
997
+ acc[symbol] = address.toLowerCase();
998
+ }
999
+ return acc;
1000
+ },
1001
+ {}
1002
+ );
1003
+ const currentTokenData = Object.entries(import_sdk_gov_legacy.tokenDataByNetwork[network]).reduce(
1004
+ (acc, [symbol, address]) => {
1005
+ if (!!address && address !== import_constants.NOT_DEPLOYED) {
1006
+ acc[symbol] = address.toLowerCase();
1007
+ }
1008
+ return acc;
1009
+ },
1010
+ {}
1011
+ );
1012
+ const { aura, convex, sky } = assets.reduce(
1013
+ (acc, a) => {
1014
+ const symbol = import_sdk_gov_legacy.tokenSymbolByAddress[a.token];
1015
+ if ((0, import_sdk_gov_legacy.isConvexStakedPhantomToken)(symbol)) {
1016
+ acc.convex.push(a);
1017
+ } else if ((0, import_sdk_gov_legacy.isAuraStakedToken)(symbol)) {
1018
+ acc.aura.push(a);
1019
+ } else if ((0, import_sdk_gov_legacy.isStakingRewardsPhantomToken)(symbol)) {
1020
+ acc.sky.push(a);
1021
+ }
1022
+ return acc;
1023
+ },
1024
+ { convex: [], aura: [], sky: [] }
1025
+ );
1026
+ const getWithdrawCall = (pool, a) => {
1027
+ return withdrawAll ? this.#withdrawAllAndUnwrap_Convex(pool, claim) : this.#withdrawAndUnwrap_Convex(pool, a.balance, claim);
1028
+ };
1029
+ const getWithdrawCall_Rewards = (pool, a) => {
1030
+ const calls = [
1031
+ withdrawAll ? this.#withdrawAll_Rewards(pool) : this.#withdraw_Rewards(pool, a.balance),
1032
+ ...claim ? [this.#claim_Rewards(pool)] : []
1033
+ ];
1034
+ return calls;
1035
+ };
1036
+ const convexStkCalls = convex.map((a) => {
1037
+ const symbol = import_sdk_gov_legacy.tokenSymbolByAddress[a.token];
1038
+ const { pool } = import_sdk_gov_legacy.convexTokens[symbol];
1039
+ const poolAddress = currentContractsData[pool];
1040
+ if (!poolAddress) {
1041
+ throw new Error("Can't withdrawAllAndUnwrap_Convex (convex)");
1042
+ }
1043
+ const poolAddressLc = poolAddress.toLowerCase();
1044
+ return getWithdrawCall(cmAdapters[poolAddressLc], a);
1045
+ });
1046
+ const auraStkCalls = aura.map((a) => {
1047
+ const symbol = import_sdk_gov_legacy.tokenSymbolByAddress[a.token];
1048
+ const { pool } = import_sdk_gov_legacy.auraTokens[symbol];
1049
+ const poolAddress = currentContractsData[pool];
1050
+ if (!poolAddress) {
1051
+ throw new Error("Can't withdrawAllAndUnwrap_Convex (aura)");
1052
+ }
1053
+ const poolAddressLc = poolAddress.toLowerCase();
1054
+ return getWithdrawCall(cmAdapters[poolAddressLc], a);
1055
+ });
1056
+ const skyStkCalls = sky.map((a) => {
1057
+ const symbol = import_sdk_gov_legacy.tokenSymbolByAddress[a.token];
1058
+ const { pool } = import_sdk_gov_legacy.stakingRewardsTokens[symbol];
1059
+ const poolAddress = currentContractsData[pool];
1060
+ if (!poolAddress) {
1061
+ throw new Error("Can't withdrawAllAndUnwrap_Convex (sky)");
1062
+ }
1063
+ const poolAddressLc = poolAddress.toLowerCase();
1064
+ return getWithdrawCall_Rewards(cmAdapters[poolAddressLc], a);
1065
+ }).flat(1);
1066
+ const unwrapCalls = [...convexStkCalls, ...auraStkCalls, ...skyStkCalls];
1067
+ const withdraw = assets.map((a) => {
1068
+ const symbol = import_sdk_gov_legacy.tokenSymbolByAddress[a.token];
1069
+ if ((0, import_sdk_gov_legacy.isConvexStakedPhantomToken)(symbol)) {
1070
+ return {
1071
+ ...a,
1072
+ token: currentTokenData[import_sdk_gov_legacy.convexStakedPhantomTokens[symbol].underlying]
1073
+ };
1074
+ }
1075
+ if ((0, import_sdk_gov_legacy.isAuraStakedToken)(symbol)) {
1076
+ return {
1077
+ ...a,
1078
+ token: currentTokenData[import_sdk_gov_legacy.auraStakedTokens[symbol].underlying]
1079
+ };
1080
+ }
1081
+ if ((0, import_sdk_gov_legacy.isStakingRewardsPhantomToken)(symbol)) {
1082
+ return {
1083
+ ...a,
1084
+ token: currentTokenData[import_sdk_gov_legacy.stakingRewardsTokens[symbol].underlying]
1085
+ };
1086
+ }
1087
+ return a;
1088
+ });
1089
+ return { unwrapCalls, assetsToWithdraw: withdraw };
1090
+ }
1091
+ // TODO: remove after transition to 3.1
1092
+ #withdrawAndUnwrap_Convex(address, amount, claim) {
1093
+ return {
1094
+ target: address,
1095
+ callData: (0, import_viem.encodeFunctionData)({
1096
+ abi: import_adapters.iConvexV1BaseRewardPoolAdapterAbi,
1097
+ functionName: "withdrawAndUnwrap",
1098
+ args: [amount, claim]
1099
+ })
1100
+ };
1101
+ }
1102
+ // TODO: remove after transition to 3.1
1103
+ #withdrawAllAndUnwrap_Convex(address, claim) {
1104
+ return {
1105
+ target: address,
1106
+ callData: (0, import_viem.encodeFunctionData)({
1107
+ abi: import_adapters.iConvexV1BaseRewardPoolAdapterAbi,
1108
+ functionName: "withdrawDiffAndUnwrap",
1109
+ args: [1n, claim]
1110
+ })
1111
+ };
1112
+ }
1113
+ // TODO: remove after transition to 3.1
1114
+ #withdrawAll_Rewards(address) {
1115
+ return {
1116
+ target: address,
1117
+ callData: (0, import_viem.encodeFunctionData)({
1118
+ abi: import_adapters.iStakingRewardsAdapterAbi,
1119
+ functionName: "withdrawDiff",
1120
+ args: [1n]
1121
+ })
1122
+ };
1123
+ }
1124
+ // TODO: remove after transition to 3.1
1125
+ #withdraw_Rewards(address, amount) {
1126
+ return {
1127
+ target: address,
1128
+ callData: (0, import_viem.encodeFunctionData)({
1129
+ abi: import_adapters.iStakingRewardsAdapterAbi,
1130
+ functionName: "withdraw",
1131
+ args: [amount]
1132
+ })
1133
+ };
1134
+ }
1135
+ // TODO: remove after transition to 3.1
1136
+ #claim_Rewards(address) {
1137
+ return {
1138
+ target: address,
1139
+ callData: (0, import_viem.encodeFunctionData)({
1140
+ abi: import_adapters.iStakingRewardsAdapterAbi,
1141
+ functionName: "getReward",
1142
+ args: []
1143
+ })
1144
+ };
1145
+ }
795
1146
  /**
796
1147
  * Returns addresses of market configurators
797
1148
  */