@gearbox-protocol/sdk 16.3.2 → 16.4.0-next.10

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 (139) hide show
  1. package/dist/cjs/dev/index.js +3 -2
  2. package/dist/cjs/dev/kycUtils.js +18 -35
  3. package/dist/cjs/dev/midasUtils.js +40 -11
  4. package/dist/cjs/dev/securitizeUtils.js +14 -10
  5. package/dist/cjs/dev/withdrawalUtils.js +3 -6
  6. package/dist/cjs/model/errors/index.js +2 -0
  7. package/dist/cjs/model/errors/operation-errors.js +18 -0
  8. package/dist/cjs/model/index.js +2 -0
  9. package/dist/cjs/onchain/accounts/CreditAccountsServiceV310.js +0 -1
  10. package/dist/cjs/onchain/accounts/intents/borrow.js +139 -0
  11. package/dist/cjs/onchain/accounts/intents/collateral-valuation.js +41 -0
  12. package/dist/cjs/onchain/accounts/intents/guards.js +15 -3
  13. package/dist/cjs/onchain/accounts/intents/index.js +107 -20
  14. package/dist/cjs/onchain/accounts/intents/leverage-band.js +2 -12
  15. package/dist/cjs/onchain/accounts/intents/maxBorrow.js +89 -0
  16. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +15 -41
  17. package/dist/cjs/onchain/accounts/intents/open-strategy.js +6 -45
  18. package/dist/cjs/onchain/accounts/intents/realize.js +54 -2
  19. package/dist/cjs/onchain/accounts/intents/tail.js +1 -1
  20. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  21. package/dist/cjs/onchain/accounts/intents/utils/common.js +19 -0
  22. package/dist/cjs/onchain/accounts/intents/utils/credit-account-slice.js +21 -0
  23. package/dist/cjs/onchain/accounts/intents/utils/index.js +2 -0
  24. package/dist/cjs/onchain/accounts/intents/utils/price-impact.js +3 -3
  25. package/dist/cjs/onchain/accounts/intents/withdraw-limits.js +97 -0
  26. package/dist/cjs/onchain/core/createAddressProvider.js +2 -5
  27. package/dist/cjs/onchain/index.js +6 -0
  28. package/dist/cjs/onchain/market/adapters/abi/conctructorAbi.js +1 -1
  29. package/dist/cjs/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +11 -3
  30. package/dist/cjs/onchain/positions/calcHealthFactor.js +3 -3
  31. package/dist/cjs/onchain/preview/index.js +2 -0
  32. package/dist/cjs/onchain/preview/preview/index.js +2 -0
  33. package/dist/cjs/onchain/preview/preview/midasGreenlistsAccount.js +17 -0
  34. package/dist/cjs/onchain/preview/preview/previewOpenStrategyPosition.js +13 -16
  35. package/dist/cjs/onchain/preview/preview/previewOperation.js +19 -11
  36. package/dist/cjs/onchain/preview/preview/replayMulticall.js +4 -3
  37. package/dist/cjs/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  38. package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +4 -3
  39. package/dist/cjs/onchain/validation/bundles/checkMidasAccountGreenlist.js +44 -0
  40. package/dist/cjs/onchain/validation/bundles/checkRWAOpening.js +16 -7
  41. package/dist/cjs/onchain/validation/bundles/index.js +2 -0
  42. package/dist/cjs/onchain/validation/checkOperation.js +0 -1
  43. package/dist/cjs/onchain/validation/checks/checkReservePriceLimited.js +30 -0
  44. package/dist/cjs/onchain/validation/checks/index.js +2 -0
  45. package/dist/cjs/onchain/validation/index.js +4 -0
  46. package/dist/cjs/sdk/execute/ExecuteApi.js +65 -5
  47. package/dist/cjs/sdk/prepare/PrepareApi.js +89 -14
  48. package/dist/esm/dev/index.js +3 -3
  49. package/dist/esm/dev/kycUtils.js +17 -33
  50. package/dist/esm/dev/midasUtils.js +39 -12
  51. package/dist/esm/dev/securitizeUtils.js +15 -11
  52. package/dist/esm/dev/withdrawalUtils.js +3 -6
  53. package/dist/esm/model/errors/index.js +2 -2
  54. package/dist/esm/model/errors/operation-errors.js +17 -1
  55. package/dist/esm/model/index.js +2 -2
  56. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +0 -1
  57. package/dist/esm/onchain/accounts/intents/borrow.js +137 -0
  58. package/dist/esm/onchain/accounts/intents/collateral-valuation.js +40 -0
  59. package/dist/esm/onchain/accounts/intents/guards.js +15 -3
  60. package/dist/esm/onchain/accounts/intents/index.js +107 -20
  61. package/dist/esm/onchain/accounts/intents/leverage-band.js +2 -12
  62. package/dist/esm/onchain/accounts/intents/maxBorrow.js +87 -0
  63. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +15 -41
  64. package/dist/esm/onchain/accounts/intents/open-strategy.js +6 -45
  65. package/dist/esm/onchain/accounts/intents/realize.js +54 -2
  66. package/dist/esm/onchain/accounts/intents/tail.js +1 -1
  67. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  68. package/dist/esm/onchain/accounts/intents/utils/common.js +19 -1
  69. package/dist/esm/onchain/accounts/intents/utils/credit-account-slice.js +21 -1
  70. package/dist/esm/onchain/accounts/intents/utils/index.js +3 -3
  71. package/dist/esm/onchain/accounts/intents/utils/price-impact.js +3 -3
  72. package/dist/esm/onchain/accounts/intents/withdraw-limits.js +95 -0
  73. package/dist/esm/onchain/core/createAddressProvider.js +2 -5
  74. package/dist/esm/onchain/index.js +4 -1
  75. package/dist/esm/onchain/market/adapters/abi/conctructorAbi.js +1 -1
  76. package/dist/esm/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +11 -3
  77. package/dist/esm/onchain/positions/calcHealthFactor.js +3 -3
  78. package/dist/esm/onchain/preview/index.js +2 -1
  79. package/dist/esm/onchain/preview/preview/index.js +2 -1
  80. package/dist/esm/onchain/preview/preview/midasGreenlistsAccount.js +16 -0
  81. package/dist/esm/onchain/preview/preview/previewOpenStrategyPosition.js +14 -17
  82. package/dist/esm/onchain/preview/preview/previewOperation.js +19 -11
  83. package/dist/esm/onchain/preview/preview/replayMulticall.js +4 -3
  84. package/dist/esm/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  85. package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +4 -3
  86. package/dist/esm/onchain/validation/bundles/checkMidasAccountGreenlist.js +43 -0
  87. package/dist/esm/onchain/validation/bundles/checkRWAOpening.js +16 -7
  88. package/dist/esm/onchain/validation/bundles/index.js +2 -1
  89. package/dist/esm/onchain/validation/checkOperation.js +0 -1
  90. package/dist/esm/onchain/validation/checks/checkReservePriceLimited.js +29 -0
  91. package/dist/esm/onchain/validation/checks/index.js +2 -1
  92. package/dist/esm/onchain/validation/index.js +3 -1
  93. package/dist/esm/sdk/execute/ExecuteApi.js +65 -5
  94. package/dist/esm/sdk/prepare/PrepareApi.js +89 -14
  95. package/dist/types/dev/index.d.ts +3 -3
  96. package/dist/types/dev/kycUtils.d.ts +1 -5
  97. package/dist/types/dev/midasUtils.d.ts +11 -1
  98. package/dist/types/model/errors/index.d.ts +2 -2
  99. package/dist/types/model/errors/operation-errors.d.ts +54 -1
  100. package/dist/types/model/index.d.ts +3 -3
  101. package/dist/types/model/previews.d.ts +25 -19
  102. package/dist/types/onchain/accounts/index.d.ts +4 -3
  103. package/dist/types/onchain/accounts/intents/borrow.d.ts +141 -0
  104. package/dist/types/onchain/accounts/intents/collateral-valuation.d.ts +42 -0
  105. package/dist/types/onchain/accounts/intents/guards.d.ts +18 -2
  106. package/dist/types/onchain/accounts/intents/index.d.ts +102 -14
  107. package/dist/types/onchain/accounts/intents/maxBorrow.d.ts +54 -0
  108. package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +3 -8
  109. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +3 -17
  110. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +2 -0
  111. package/dist/types/onchain/accounts/intents/tests/open-strategy.fixtures.d.ts +2 -2
  112. package/dist/types/onchain/accounts/intents/types.d.ts +41 -5
  113. package/dist/types/onchain/accounts/intents/utils/common.d.ts +15 -1
  114. package/dist/types/onchain/accounts/intents/utils/credit-account-slice.d.ts +14 -1
  115. package/dist/types/onchain/accounts/intents/utils/index.d.ts +3 -3
  116. package/dist/types/onchain/accounts/intents/withdraw-limits.d.ts +80 -0
  117. package/dist/types/onchain/index.d.ts +8 -4
  118. package/dist/types/onchain/market/adapters/contracts/MidasGatewayAdapterContract.d.ts +8 -2
  119. package/dist/types/onchain/preview/index.d.ts +2 -1
  120. package/dist/types/onchain/preview/preview/index.d.ts +2 -1
  121. package/dist/types/onchain/preview/preview/midasGreenlistsAccount.d.ts +13 -0
  122. package/dist/types/onchain/preview/preview/previewOpenStrategyPosition.d.ts +5 -3
  123. package/dist/types/onchain/preview/preview/replayMulticall.d.ts +8 -7
  124. package/dist/types/onchain/validation/bundles/checkCreditOperation.d.ts +2 -2
  125. package/dist/types/onchain/validation/bundles/checkMidasAccountGreenlist.d.ts +22 -0
  126. package/dist/types/onchain/validation/bundles/checkRWAOpening.d.ts +6 -4
  127. package/dist/types/onchain/validation/bundles/index.d.ts +3 -2
  128. package/dist/types/onchain/validation/checks/checkDebtLimits.d.ts +2 -2
  129. package/dist/types/onchain/validation/checks/checkReservePriceLimited.d.ts +31 -0
  130. package/dist/types/onchain/validation/checks/index.d.ts +2 -1
  131. package/dist/types/onchain/validation/index.d.ts +4 -2
  132. package/dist/types/onchain/validation/raise.d.ts +2 -2
  133. package/dist/types/sdk/execute/index.d.ts +2 -2
  134. package/dist/types/sdk/execute/types.d.ts +48 -6
  135. package/dist/types/sdk/index.d.ts +5 -4
  136. package/dist/types/sdk/prepare/PrepareApi.d.ts +16 -4
  137. package/dist/types/sdk/prepare/index.d.ts +4 -3
  138. package/dist/types/sdk/prepare/types.d.ts +199 -65
  139. package/package.json +1 -1
@@ -195,26 +195,33 @@ var PrepareApi = class extends MultichainConstruct {
195
195
  }
196
196
  }
197
197
  /**
198
+ * {@inheritDoc IOpportunitiesPrepare.openEmptyCreditAccount}
199
+ **/
200
+ async openEmptyCreditAccount(strategy) {
201
+ try {
202
+ const sdk = await this.#chain(strategy.chainId);
203
+ const at = stateBlock(sdk);
204
+ const result = await service(sdk).openEmptyAccountIntent({
205
+ sdk,
206
+ creditManager: strategy.creditManager
207
+ });
208
+ return result.ok ? sdkOk(at) : methodError(result);
209
+ } catch (e) {
210
+ return sdkErr(unexpectedFailure(e));
211
+ }
212
+ }
213
+ /**
198
214
  * {@inheritDoc IOpportunitiesPrepare.openNewStrategy}
199
215
  **/
200
216
  async openNewStrategy(strategy, params) {
201
217
  try {
202
218
  const sdk = await this.#chain(strategy.chainId);
203
219
  const at = stateBlock(sdk);
204
- if (params.empty) return opened(await service(sdk).openStrategyIntent({
205
- sdk,
206
- creditManager: strategy.creditManager,
207
- empty: true
208
- }), at);
209
220
  const targetToken = params.targetToken ?? sdk.marketRegister.findCreditManager(strategy.creditManager).strategyTargetCollateral;
210
221
  if (!targetToken) return sdkErr(noStrategyTargetCollateral(strategy.creditManager));
211
- let creditAccount;
212
- if (params.creditAccount) {
213
- const reused = await slice(sdk, params.creditAccount);
214
- if (!reused || !isAddressEqual(reused.creditManager, strategy.creditManager)) return sdkErr(creditAccountNotFound(params.creditAccount));
215
- if (reused.totalDebt > 0n || reused.tokens.some((t) => t.quota > 0n)) return sdkErr(creditAccountNotEmpty(params.creditAccount));
216
- creditAccount = reused;
217
- }
222
+ const reused = await reusable(sdk, strategy, params.creditAccount);
223
+ if (reused && "error" in reused) return reused;
224
+ const creditAccount = reused?.account;
218
225
  return opened(await service(sdk).openStrategyIntent({
219
226
  sdk,
220
227
  creditManager: strategy.creditManager,
@@ -231,6 +238,30 @@ var PrepareApi = class extends MultichainConstruct {
231
238
  }
232
239
  }
233
240
  /**
241
+ * {@inheritDoc IOpportunitiesPrepare.borrow}
242
+ **/
243
+ async borrow(strategy, params) {
244
+ try {
245
+ const sdk = await this.#chain(strategy.chainId);
246
+ const at = stateBlock(sdk);
247
+ const reused = await reusable(sdk, strategy, params.creditAccount);
248
+ if (reused && "error" in reused) return reused;
249
+ return borrowed(await service(sdk).borrowIntent({
250
+ sdk,
251
+ creditManager: strategy.creditManager,
252
+ collateralToken: params.collateralToken,
253
+ collateralAmount: params.collateralAmount,
254
+ borrowToken: params.borrowToken,
255
+ borrowAmount: params.borrowAmount,
256
+ slippage: params.slippage,
257
+ quotaReserve: params.quotaReserve,
258
+ creditAccount: reused?.account
259
+ }), at);
260
+ } catch (e) {
261
+ return sdkErr(unexpectedFailure(e));
262
+ }
263
+ }
264
+ /**
234
265
  * {@inheritDoc IOpportunitiesPrepare.depositStrategy}
235
266
  **/
236
267
  async depositStrategy(position, params) {
@@ -258,12 +289,13 @@ var PrepareApi = class extends MultichainConstruct {
258
289
  /**
259
290
  * {@inheritDoc IOpportunitiesPrepare.maxWithdraw}
260
291
  **/
261
- async maxWithdraw(position) {
292
+ async maxWithdraw(position, sourceToken) {
262
293
  const sdk = await this.#chain(position.chainId);
263
294
  const creditAccount = await this.#account(sdk, position);
264
295
  return service(sdk).maxWithdraw({
265
296
  creditAccount,
266
- sdk
297
+ sdk,
298
+ sourceToken
267
299
  });
268
300
  }
269
301
  /**
@@ -352,6 +384,21 @@ var PrepareApi = class extends MultichainConstruct {
352
384
  });
353
385
  }
354
386
  /**
387
+ * {@inheritDoc IOpportunitiesPrepare.maxBorrow}
388
+ **/
389
+ maxBorrow(strategy, params) {
390
+ const sdk = this.sdk.chain(strategy.chainId);
391
+ return service(sdk).maxBorrow({
392
+ sdk,
393
+ creditManager: strategy.creditManager,
394
+ collateralToken: params.collateralToken,
395
+ collateralAmount: params.collateralAmount,
396
+ borrowToken: params.borrowToken,
397
+ targetHF: params.targetHF,
398
+ quotaReserve: params.quotaReserve
399
+ });
400
+ }
401
+ /**
355
402
  * The account a bare `max*` read weighs. These reads answer a number, not
356
403
  * an envelope, so an account the markets do not hold is thrown rather than
357
404
  * described, see {@link IOpportunitiesPrepare.maxWithdraw}.
@@ -437,6 +484,25 @@ async function slice(sdk, creditAccount) {
437
484
  return data && toCreditAccountSlice(data);
438
485
  }
439
486
  /**
487
+ * The pre-opened account a request asks to be run on, held to what "pre-opened"
488
+ * means: this manager's, owing nothing and holding no quota.
489
+ *
490
+ * Shared by the two flows that put something on a fresh account — an opening
491
+ * and a borrow — so both hold a reused one to the same terms. Whatever
492
+ * balances sit on it are left to the flow: an opening routes them, a borrow
493
+ * leaves them where they are.
494
+ *
495
+ * @returns Nothing when the request named no account, the refusal to answer
496
+ * with when it named one that does not qualify, and the slice otherwise
497
+ **/
498
+ async function reusable(sdk, strategy, creditAccount) {
499
+ if (!creditAccount) return;
500
+ const account = await slice(sdk, creditAccount);
501
+ if (!account || !isAddressEqual(account.creditManager, strategy.creditManager)) return sdkErr(creditAccountNotFound(creditAccount));
502
+ if (account.totalDebt > 0n || account.tokens.some((t) => t.quota > 0n)) return sdkErr(creditAccountNotEmpty(creditAccount));
503
+ return { account };
504
+ }
505
+ /**
440
506
  * The operation a claim resumes, or `undefined` when there is none to resume:
441
507
  * a withdrawal requested without an intent, or one read through a compressor
442
508
  * too old to report it. Every intent the engine records can be finished,
@@ -536,6 +602,15 @@ function opened(result, at) {
536
602
  }
537
603
  /**
538
604
  * {@inheritDoc planned}
605
+ **/
606
+ function borrowed(result, at) {
607
+ return result.ok ? sdkOk({
608
+ state: result.state,
609
+ ...at
610
+ }) : methodError(result);
611
+ }
612
+ /**
613
+ * {@inheritDoc planned}
539
614
  *
540
615
  * Both routes are payload, error and all: `errors` says why a missing one is
541
616
  * missing, and it stays on the error when neither route answered, since that is
@@ -11,10 +11,10 @@ import { detectChain } from "./detectChain.js";
11
11
  import { isOutOfSyncError } from "./isOutOfSyncError.js";
12
12
  import { isRateLimitError } from "./isRateLimitError.js";
13
13
  import { isTransientError } from "./isTransientError.js";
14
- import { GreenlistMidasGatewayProps, RWAKycFailure, RegisterMidasInvestorProps, RegisterRWAInvestorProps, RegisterRWAInvestorResult, RegisterSecuritizeInvestorProps, greenlistMidasGateway, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor, writeAndWait } from "./kycUtils.js";
14
+ import { GreenlistMidasGatewayProps, RWAKycFailure, RegisterMidasInvestorProps, RegisterRWAInvestorProps, RegisterRWAInvestorResult, RegisterSecuritizeInvestorProps, greenlistMidasGateway, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor } from "./kycUtils.js";
15
15
  import { LogSplitterTransportOptions, isRangeError, logSplitterTransport } from "./logSplitterTransport.js";
16
16
  import { setLTZero, setLTs } from "./ltUtils.js";
17
- import { RestoreMidasIssuanceVaultPause, UnpauseMidasIssuanceVaultProps, unpauseMidasIssuanceVault } from "./midasUtils.js";
17
+ import { RestoreMidasIssuanceVaultPause, UnpauseMidasIssuanceVaultProps, collectMidasGateways, collectMidasMTokens, unpauseMidasIssuanceVault } from "./midasUtils.js";
18
18
  import { migrateFaucet } from "./migrateFaucet.js";
19
19
  import { IMinter } from "./mint/types.js";
20
20
  import { createMinter } from "./mint/factory.js";
@@ -26,4 +26,4 @@ import { EnableDSTokenBackDatingProps, RestoreDSTokenBackDating, claimDSToken, c
26
26
  import { httpTransportOptionsSchema } from "./transports.js";
27
27
  import { ONCHAIN_EXECUTION_ID_ADDRESS, VerifyTestnetParams, verifyTestnet } from "./verifyTestnet.js";
28
28
  import { MakePendingWithdrawalsClaimableOptions, makePendingWithdrawalsClaimable } from "./withdrawalUtils.js";
29
- export { AccountOpener, AccountOpenerOptions, AnvilActions, AnvilClient, AnvilClientConfig, AnvilDealParameters, AnvilNodeInfo, AnvilRPCSchema, CheckMulticallFn, Create2Deployer, Create2Parameters, DEFAULT_CREATE2_SALT, DetectedCall, EnableDSTokenBackDatingProps, EnsureExistsUsingPublicCreate2ReturnType, EthCallMethod, EthCallRequest, EthCallSpy, GetCreate2AddressParameters, GreenlistMidasGatewayProps, IMinter, type LogSplitterTransportOptions, MakePendingWithdrawalsClaimableOptions, NoAvailableTransportsError, ONCHAIN_EXECUTION_ID_ADDRESS, OpenAccountHumanizedPreview, OpenAccountResult, OpenAccountsResult, OpenTxRevertedError, PUBLIC_CREATE2_FACTORY, PoolDepositResult, ProviderConfig, ProviderStatus, RWAKycFailure, RegisterMidasInvestorProps, RegisterRWAInvestorProps, RegisterRWAInvestorResult, RegisterSecuritizeInvestorProps, ReplaceStorageParams, ResilientTransportOptions, RestoreDSTokenBackDating, RestoreMidasIssuanceVaultPause, RevolverTransport, RevolverTransportConfig, RevolverTransportValue, RpcErrorResult, RpcProvider, RpcResponse, RpcSuccessResult, SUPPORTED_RPC_PROVIDERS, SelectionStrategy, TargetAccount, UnpauseMidasIssuanceVaultProps, VerifyTestnetParams, anvilNodeInfo, calcLiquidatableLTs, claimDSToken, claimDSTokens, claimFromFaucet, createAnvilClient, createMinter, deployUsingPublicCreate2, detectChain, enableDSTokenBackDating, evmMineDetailed, extendAnvilClient, getAlchemyUrl, getAnkrUrl, getDrpcUrl, getErpcKey, getPublicCreate2Address, getRpcProviderUrl, getThirdWebUrl, greenlistMidasGateway, httpTransportOptionsSchema, iDegenNftv2Abi, iFaucetAbi, iOnchainExecutionIdAbi, iOwnableAbi, iaclTraitAbi, isAnvil, isDeployedUsingPublicCreate2, isOutOfSyncError, isRangeError, isRateLimitError, isTransientError, logSplitterTransport, makePendingWithdrawalsClaimable, migrateFaucet, providerConfigSchema, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor, replaceStorage, resilientTransport, resilientTransportOptionsSchema, revolverTransportConfigBaseSchema, revolverTransportConfigSchema, rpcProvidersSchema, setLTZero, setLTs, unpauseMidasIssuanceVault, verifyTestnet, writeAndWait };
29
+ export { AccountOpener, AccountOpenerOptions, AnvilActions, AnvilClient, AnvilClientConfig, AnvilDealParameters, AnvilNodeInfo, AnvilRPCSchema, CheckMulticallFn, Create2Deployer, Create2Parameters, DEFAULT_CREATE2_SALT, DetectedCall, EnableDSTokenBackDatingProps, EnsureExistsUsingPublicCreate2ReturnType, EthCallMethod, EthCallRequest, EthCallSpy, GetCreate2AddressParameters, GreenlistMidasGatewayProps, IMinter, type LogSplitterTransportOptions, MakePendingWithdrawalsClaimableOptions, NoAvailableTransportsError, ONCHAIN_EXECUTION_ID_ADDRESS, OpenAccountHumanizedPreview, OpenAccountResult, OpenAccountsResult, OpenTxRevertedError, PUBLIC_CREATE2_FACTORY, PoolDepositResult, ProviderConfig, ProviderStatus, RWAKycFailure, RegisterMidasInvestorProps, RegisterRWAInvestorProps, RegisterRWAInvestorResult, RegisterSecuritizeInvestorProps, ReplaceStorageParams, ResilientTransportOptions, RestoreDSTokenBackDating, RestoreMidasIssuanceVaultPause, RevolverTransport, RevolverTransportConfig, RevolverTransportValue, RpcErrorResult, RpcProvider, RpcResponse, RpcSuccessResult, SUPPORTED_RPC_PROVIDERS, SelectionStrategy, TargetAccount, UnpauseMidasIssuanceVaultProps, VerifyTestnetParams, anvilNodeInfo, calcLiquidatableLTs, claimDSToken, claimDSTokens, claimFromFaucet, collectMidasGateways, collectMidasMTokens, createAnvilClient, createMinter, deployUsingPublicCreate2, detectChain, enableDSTokenBackDating, evmMineDetailed, extendAnvilClient, getAlchemyUrl, getAnkrUrl, getDrpcUrl, getErpcKey, getPublicCreate2Address, getRpcProviderUrl, getThirdWebUrl, greenlistMidasGateway, httpTransportOptionsSchema, iDegenNftv2Abi, iFaucetAbi, iOnchainExecutionIdAbi, iOwnableAbi, iaclTraitAbi, isAnvil, isDeployedUsingPublicCreate2, isOutOfSyncError, isRangeError, isRateLimitError, isTransientError, logSplitterTransport, makePendingWithdrawalsClaimable, migrateFaucet, providerConfigSchema, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor, replaceStorage, resilientTransport, resilientTransportOptionsSchema, revolverTransportConfigBaseSchema, revolverTransportConfigSchema, rpcProvidersSchema, setLTZero, setLTs, unpauseMidasIssuanceVault, verifyTestnet };
@@ -4,10 +4,6 @@ import "../onchain/index.js";
4
4
  import { AnvilClient } from "./createAnvilClient.js";
5
5
  import { Address, Hex } from "viem";
6
6
  //#region src/dev/kycUtils.d.ts
7
- /**
8
- * Writes to a contract, mines a block and waits for the receipt
9
- */
10
- declare function writeAndWait(anvil: AnvilClient, params: Parameters<AnvilClient["writeContract"]>[0]): Promise<Hex>;
11
7
  interface RegisterSecuritizeInvestorProps {
12
8
  anvil: AnvilClient;
13
9
  /**
@@ -138,4 +134,4 @@ interface RegisterRWAInvestorResult {
138
134
  */
139
135
  declare function registerRWAInvestor(props: RegisterRWAInvestorProps): Promise<RegisterRWAInvestorResult>;
140
136
  //#endregion
141
- export { GreenlistMidasGatewayProps, RWAKycFailure, RegisterMidasInvestorProps, RegisterRWAInvestorProps, RegisterRWAInvestorResult, RegisterSecuritizeInvestorProps, greenlistMidasGateway, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor, writeAndWait };
137
+ export { GreenlistMidasGatewayProps, RWAKycFailure, RegisterMidasInvestorProps, RegisterRWAInvestorProps, RegisterRWAInvestorResult, RegisterSecuritizeInvestorProps, greenlistMidasGateway, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor };
@@ -1,4 +1,5 @@
1
1
  import { ILogger } from "../onchain/types/logger.js";
2
+ import { OnchainSDK } from "../onchain/OnchainSDK.js";
2
3
  import "../onchain/index.js";
3
4
  import { AnvilClient } from "./createAnvilClient.js";
4
5
  import { Address } from "viem";
@@ -32,5 +33,14 @@ type RestoreMidasIssuanceVaultPause = () => Promise<void>;
32
33
  * reverted by the callback, only the pause state is.
33
34
  */
34
35
  declare function unpauseMidasIssuanceVault(props: UnpauseMidasIssuanceVaultProps): Promise<RestoreMidasIssuanceVaultPause>;
36
+ /**
37
+ * Target contracts of all Midas gateway adapters of the loaded credit managers,
38
+ * same as the foundry tests do with `ICreditConfiguratorV3.allowedAdapters`
39
+ */
40
+ declare function collectMidasGateways(sdk: OnchainSDK): Address[];
41
+ /**
42
+ * mTokens of all Midas gateway adapters of the loaded credit managers
43
+ */
44
+ declare function collectMidasMTokens(sdk: OnchainSDK): Address[];
35
45
  //#endregion
36
- export { RestoreMidasIssuanceVaultPause, UnpauseMidasIssuanceVaultProps, unpauseMidasIssuanceVault };
46
+ export { RestoreMidasIssuanceVaultPause, UnpauseMidasIssuanceVaultProps, collectMidasGateways, collectMidasMTokens, unpauseMidasIssuanceVault };
@@ -1,7 +1,7 @@
1
1
  import { IGearboxError } from "./base.js";
2
2
  import { CreditAccountFrozenError, LiquidatorNotEligibleError, NotEmergencyLiquidatorError, creditAccountFrozen, liquidatorNotEligible, notEmergencyLiquidator } from "./liquidation-errors.js";
3
- import { BorrowLimitCause, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, LeverageOutOfRangeError, MarketExpiredError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet } from "./operation-errors.js";
3
+ import { AccountNotMidasGreenlistedError, BorrowLimitCause, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, LeverageOutOfRangeError, MarketExpiredError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, ReservePriceLimitedError, accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet } from "./operation-errors.js";
4
4
  import { UnpriceableTokenError, unpriceableTokenError } from "./oracle-errors.js";
5
5
  import { CreditAccountNotEmptyError, CreditAccountNotFoundError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress } from "./prepare-errors.js";
6
6
  import { InvalidDelayedIntentError, MalformedTransactionError, PoolOperationPreviewError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, malformedTransaction } from "./preview-errors.js";
7
- export { BorrowLimitCause, CreditAccountFrozenError, CreditAccountNotEmptyError, CreditAccountNotFoundError, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, IGearboxError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, InvalidDelayedIntentError, LeverageOutOfRangeError, LiquidatorNotEligibleError, MalformedTransactionError, MarketExpiredError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, NotEmergencyLiquidatorError, PoolOperationPreviewError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, UnexpectedFailureError, UnpriceableTokenError, UnsupportedCollateralTokenError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedTokenPairError, UnsupportedZapperFunctionError, WithdrawalInProgressError, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
7
+ export { AccountNotMidasGreenlistedError, BorrowLimitCause, CreditAccountFrozenError, CreditAccountNotEmptyError, CreditAccountNotFoundError, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, IGearboxError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, InvalidDelayedIntentError, LeverageOutOfRangeError, LiquidatorNotEligibleError, MalformedTransactionError, MarketExpiredError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, NotEmergencyLiquidatorError, PoolOperationPreviewError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, ReservePriceLimitedError, UnexpectedFailureError, UnpriceableTokenError, UnsupportedCollateralTokenError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedTokenPairError, UnsupportedZapperFunctionError, WithdrawalInProgressError, accountNotMidasGreenlisted, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
@@ -126,6 +126,46 @@ interface InsufficientCollateralError extends IGearboxError {
126
126
  }
127
127
  /** {@inheritDoc InsufficientCollateralError} */
128
128
  declare function insufficientCollateral(args: Omit<InsufficientCollateralError, "code" | "message">): InsufficientCollateralError;
129
+ /**
130
+ * The same failure as {@link InsufficientCollateralError}, traced to the
131
+ * reserve price feed rather than to the size of the position.
132
+ *
133
+ * A call that hands funds over is weighed at safe prices — `min` of a token's
134
+ * two feeds, and nothing at all for collateral governance registered no
135
+ * reserve feed for — so an account that covers its debt at the main feed can
136
+ * still be refused. Worth its own code because the two call for opposite
137
+ * words: an under-collateralised position is fixed by adding collateral or
138
+ * requesting less, while this is a valuation the account does not control, and
139
+ * requesting less only helps as far as {@link withdrawable} says it does.
140
+ **/
141
+ interface ReservePriceLimitedError extends IGearboxError {
142
+ code: "reservePriceLimited";
143
+ /** The safe-price factor the operation would have ended at. */
144
+ healthFactor: Bps;
145
+ /**
146
+ * The same account at the main feed. Above {@link healthFactorThreshold} by
147
+ * definition — that is what makes the reserve feed the thing in the way, and
148
+ * the gap between the two is how far it marks the collateral down.
149
+ **/
150
+ atMainPrices: Bps;
151
+ /** The threshold both were weighed against, the facade's own `1.0`. */
152
+ healthFactorThreshold: Bps;
153
+ /**
154
+ * What the account can still take out under the same check, in the market's
155
+ * underlying — the request to offer instead of the refused one. It is the
156
+ * `safePartial` of `WithdrawCeilings`, from the same code that answers
157
+ * `maxWithdraw`, so the two never disagree.
158
+ *
159
+ * `0n` says no partial withdrawal clears the threshold at all, and a smaller
160
+ * request will not help: holding leverage flat scales collateral and debt
161
+ * together, which leaves the safe-price factor exactly where it found it.
162
+ * Such a position can still leave entirely — an exit settles the debt rather
163
+ * than shrinking it, and a check with no debt to divide by refuses nothing.
164
+ **/
165
+ withdrawable: TokenAmount;
166
+ }
167
+ /** {@inheritDoc ReservePriceLimitedError} */
168
+ declare function reservePriceLimited(args: Omit<ReservePriceLimitedError, "code" | "message">): ReservePriceLimitedError;
129
169
  /**
130
170
  * The operation would increase the balance of a token the market forbids.
131
171
  **/
@@ -218,5 +258,18 @@ interface RWAOpenRequirementsError extends IGearboxError {
218
258
  }
219
259
  /** {@inheritDoc RWAOpenRequirementsError} */
220
260
  declare function rwaOpenRequirementsNotMet(args: Omit<RWAOpenRequirementsError, "code" | "message">): RWAOpenRequirementsError;
261
+ /**
262
+ * The credit account does not hold the Midas greenlisted role this
263
+ * permissioned mToken requires of its holder.
264
+ **/
265
+ interface AccountNotMidasGreenlistedError extends IGearboxError {
266
+ code: "accountNotMidasGreenlisted";
267
+ token: Token;
268
+ creditManager: Address;
269
+ /** Absent when the opening creates the account. */
270
+ creditAccount?: Address;
271
+ }
272
+ /** {@inheritDoc AccountNotMidasGreenlistedError} */
273
+ declare function accountNotMidasGreenlisted(args: Omit<AccountNotMidasGreenlistedError, "code" | "message">): AccountNotMidasGreenlistedError;
221
274
  //#endregion
222
- export { BorrowLimitCause, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, LeverageOutOfRangeError, MarketExpiredError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet };
275
+ export { AccountNotMidasGreenlistedError, BorrowLimitCause, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, LeverageOutOfRangeError, MarketExpiredError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, ReservePriceLimitedError, accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet };
@@ -6,14 +6,14 @@ import { DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedDecreaseL
6
6
  import { IGearboxError } from "./errors/base.js";
7
7
  import { CreditAccountFrozenError, LiquidatorNotEligibleError, NotEmergencyLiquidatorError, creditAccountFrozen, liquidatorNotEligible, notEmergencyLiquidator } from "./errors/liquidation-errors.js";
8
8
  import { KYC_REGISTRATION_LINKS, KycProtocol, KycRequirement, MidasOpenAccountRequirements, RWAFactoryType, RWAMissingOpenAccountRequirements, RWAOpenAccountRequirements, RWAOperationArgs, RWAProtocol, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_PROTOCOLS, SECURITIZE_REGISTER_VAULT_TYPES, SecuritizeMissingOpenAccountRequirements, SecuritizeOpenAccountRequirements, SecuritizeOperationArgs, SecuritizeRegisterMessage, SecuritizeRegisterVaultMessage, SecuritizeSignature } from "./rwa.js";
9
- import { BorrowLimitCause, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, LeverageOutOfRangeError, MarketExpiredError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet } from "./errors/operation-errors.js";
9
+ import { AccountNotMidasGreenlistedError, BorrowLimitCause, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, LeverageOutOfRangeError, MarketExpiredError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, ReservePriceLimitedError, accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet } from "./errors/operation-errors.js";
10
10
  import { UnpriceableTokenError, unpriceableTokenError } from "./errors/oracle-errors.js";
11
11
  import { CreditAccountNotEmptyError, CreditAccountNotFoundError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress } from "./errors/prepare-errors.js";
12
12
  import { InvalidDelayedIntentError, MalformedTransactionError, PoolOperationPreviewError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, malformedTransaction } from "./errors/preview-errors.js";
13
13
  import "./errors/index.js";
14
14
  import { ApyBreakdown, Opportunity, OpportunityBase, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, PointRewards, PointsProgram, PoolOpportunity, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, Rewards, StrategyOpportunity, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, TokenRewards, matchesOpportunityFilter, opportunityId, poolOpportunityId, strategyOpportunityId } from "./opportunities.js";
15
15
  import { BorrowRateBreakdown, PnlBreakdown, PointsProgramPnL, PointsRewardsPnL, PoolPosition, PoolPositionKey, PoolPositionRef, Position, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionTransaction, PositionTransactionKind, PositionsTotals, RewardsPnL, STRATEGY_POSITION_COLLATERAL_ERROR, StrategyPosition, StrategyPositionKey, StrategyPositionRef, TokenQuotaRate, TokenRewardsPnL, liquidationPositionId, matchesPositionFilter, poolPositionId, positionId, strategyPositionId } from "./positions.js";
16
- import { AccountHoldings, AccountMetrics, AccountProjection, AccountStateChange, AdjustStrategyPositionPreview, CreditOperationMarket, DelayedStrategyPositionOperationPreview, Estimated, EstimatedProjection, ExitStrategyPositionPreview, InstantStrategyPositionOperationPreview, OpenNonRWAStrategyPositionPreview, OpenRWAStrategyPositionPreview, OpenStrategyPositionPreview, OperationPreview, PoolOperationType, PoolPositionOperationPreview, PreviewOperationInput, PreviewOperationOptions, RepayStrategyPositionPreview, RoutedField, asEstimated } from "./previews.js";
16
+ import { AccountHoldings, AccountMetrics, AccountProjection, AccountStateChange, AdjustStrategyPositionPreview, CreditOperationMarket, DelayedStrategyPositionOperationPreview, Estimated, EstimatedProjection, ExitStrategyPositionPreview, InstantStrategyPositionOperationPreview, OpenStrategyPositionPreview, OperationPreview, PoolOperationType, PoolPositionOperationPreview, PreviewOperationInput, PreviewOperationOptions, RepayStrategyPositionPreview, RoutedField, asEstimated } from "./previews.js";
17
17
  import { DelayedReceivedAsset, InstantReceivedAsset, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, ReceivedAsset, matchesLiquidatableAccountFilter } from "./liquidations.js";
18
18
  import { AnalyticsChartQuery, AnalyticsLiquidationPosition, AnalyticsPoolPosition, AnalyticsPosition, AnalyticsPositionListOptions, AnalyticsPositionOwner, AnalyticsPositionPage, AnalyticsPositionSortField, AnalyticsSortDirection, AnalyticsStrategyPosition } from "./analytics.js";
19
19
  import { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, analyticsChartQueryOptionsSchema, analyticsChartQueryParamsSchema, analyticsChartQuerySchema, analyticsPositionListOptionsSchema, analyticsPositionListQueryParamsSchema, analyticsPositionListQuerySchema, analyticsPositionPageSchema, analyticsPositionSchema, analyticsPositionSortFieldSchema, analyticsSortDirectionSchema } from "./analytics.schema.js";
@@ -33,4 +33,4 @@ import { SDKError, SDKResult, SDKReturn, SafeValue, safeValue, sdkErr, sdkOk } f
33
33
  import { kycRequirementSchema, rwaProtocolSchema } from "./rwa.schema.js";
34
34
  import { PositionClaimableWithdrawal, PositionPendingWithdrawal, PositionWithdrawals, WithdrawalOutputAmount } from "./withdrawals.js";
35
35
  import { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema, withdrawalOutputAmountSchema } from "./withdrawals.schema.js";
36
- export { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, AccountHoldings, AccountMetrics, AccountProjection, AccountStateChange, AdjustStrategyPositionPreview, Amount, AnalyticsChartQuery, AnalyticsLiquidationPosition, AnalyticsPoolPosition, AnalyticsPosition, AnalyticsPositionListOptions, AnalyticsPositionOwner, AnalyticsPositionPage, AnalyticsPositionSortField, AnalyticsSortDirection, AnalyticsStrategyPosition, ApyBreakdown, Asset, AssetType, BorrowLimitCause, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CompareTag, CompareTolerance, CreditAccountFrozenError, CreditAccountNotEmptyError, CreditAccountNotFoundError, CreditManagerPausedError, CreditOperationMarket, Curator, CuratorName, DataResponse, DataSource, DebtOutOfRangeError, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedStrategyPositionOperationPreview, DelayedWithdrawCollateralIntent, Estimated, EstimatedProjection, ExitStrategyPositionPreview, FILTER_ALL, FilterAll, Filterable, ForbiddenTokenError, GridSampling, IGearboxError, InstantReceivedAsset, InstantStrategyPositionOperationPreview, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, InvalidDelayedIntentError, KYC_REGISTRATION_LINKS, KycProtocol, KycRequirement, Leverage, LeverageOutOfRangeError, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, LiquidatorNotEligibleError, MalformedTransactionError, MarketExpiredError, MidasOpenAccountRequirements, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, NotEmergencyLiquidatorError, Notice, NoticeKind, NoticeSubject, OpenNonRWAStrategyPositionPreview, OpenRWAStrategyPositionPreview, OpenStrategyPositionPreview, OperationPreview, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PROTOCOL_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationPreviewError, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPausedError, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionOperationPreview, PoolPositionRef, PoolSunsetError, Position, PositionChartMetric, PositionClaimableWithdrawal, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionPendingWithdrawal, PositionTransaction, PositionTransactionKind, PositionWithdrawals, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, ProtocolChartMetric, QuotaAsset, QuotaCountExceededError, QuotaLimitReachedError, RWAFactoryType, RWAMissingOpenAccountRequirements, RWAOpenAccountRequirements, RWAOpenRequirementsError, RWAOperationArgs, RWAProtocol, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_PROTOCOLS, RateCurve, RateCurvePoint, ReceivedAsset, RepayStrategyPositionPreview, ResponseMetadata, Rewards, RewardsPnL, RoutedField, SDKError, SDKResult, SDKReturn, SECURITIZE_REGISTER_VAULT_TYPES, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, SafeValue, SecuritizeMissingOpenAccountRequirements, SecuritizeOpenAccountRequirements, SecuritizeOperationArgs, SecuritizeRegisterMessage, SecuritizeRegisterVaultMessage, SecuritizeSignature, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, UnexpectedFailureError, UnpriceableTokenError, UnsupportedCollateralTokenError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedTokenPairError, UnsupportedZapperFunctionError, WithdrawalInProgressError, WithdrawalOutputAmount, amountSchema, analyticsChartQueryOptionsSchema, analyticsChartQueryParamsSchema, analyticsChartQuerySchema, analyticsPositionListOptionsSchema, analyticsPositionListQueryParamsSchema, analyticsPositionListQuerySchema, analyticsPositionPageSchema, analyticsPositionSchema, analyticsPositionSortFieldSchema, analyticsSortDirectionSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, curatorNameSchema, curatorSchema, dataSourceSchema, debtOutOfRange, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, forbiddenToken, instantReceivedAssetSchema, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, isFilterSet, kycRequirementSchema, leverageOutOfRange, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, liquidatorNotEligible, malformedTransaction, marketExpired, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPaused, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, poolSunset, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, protocolChartMetricSchema, quotaAssetSchema, quotaCountExceeded, quotaLimitReached, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, rwaOpenRequirementsNotMet, rwaProtocolSchema, safeValue, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress, withdrawalOutputAmountSchema };
36
+ export { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, AccountHoldings, AccountMetrics, AccountNotMidasGreenlistedError, AccountProjection, AccountStateChange, AdjustStrategyPositionPreview, Amount, AnalyticsChartQuery, AnalyticsLiquidationPosition, AnalyticsPoolPosition, AnalyticsPosition, AnalyticsPositionListOptions, AnalyticsPositionOwner, AnalyticsPositionPage, AnalyticsPositionSortField, AnalyticsSortDirection, AnalyticsStrategyPosition, ApyBreakdown, Asset, AssetType, BorrowLimitCause, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CompareTag, CompareTolerance, CreditAccountFrozenError, CreditAccountNotEmptyError, CreditAccountNotFoundError, CreditManagerPausedError, CreditOperationMarket, Curator, CuratorName, DataResponse, DataSource, DebtOutOfRangeError, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedStrategyPositionOperationPreview, DelayedWithdrawCollateralIntent, Estimated, EstimatedProjection, ExitStrategyPositionPreview, FILTER_ALL, FilterAll, Filterable, ForbiddenTokenError, GridSampling, IGearboxError, InstantReceivedAsset, InstantStrategyPositionOperationPreview, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, InvalidDelayedIntentError, KYC_REGISTRATION_LINKS, KycProtocol, KycRequirement, Leverage, LeverageOutOfRangeError, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, LiquidatorNotEligibleError, MalformedTransactionError, MarketExpiredError, MidasOpenAccountRequirements, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, NotEmergencyLiquidatorError, Notice, NoticeKind, NoticeSubject, OpenStrategyPositionPreview, OperationPreview, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PROTOCOL_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationPreviewError, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPausedError, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionOperationPreview, PoolPositionRef, PoolSunsetError, Position, PositionChartMetric, PositionClaimableWithdrawal, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionPendingWithdrawal, PositionTransaction, PositionTransactionKind, PositionWithdrawals, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, ProtocolChartMetric, QuotaAsset, QuotaCountExceededError, QuotaLimitReachedError, RWAFactoryType, RWAMissingOpenAccountRequirements, RWAOpenAccountRequirements, RWAOpenRequirementsError, RWAOperationArgs, RWAProtocol, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_PROTOCOLS, RateCurve, RateCurvePoint, ReceivedAsset, RepayStrategyPositionPreview, ReservePriceLimitedError, ResponseMetadata, Rewards, RewardsPnL, RoutedField, SDKError, SDKResult, SDKReturn, SECURITIZE_REGISTER_VAULT_TYPES, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, SafeValue, SecuritizeMissingOpenAccountRequirements, SecuritizeOpenAccountRequirements, SecuritizeOperationArgs, SecuritizeRegisterMessage, SecuritizeRegisterVaultMessage, SecuritizeSignature, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, UnexpectedFailureError, UnpriceableTokenError, UnsupportedCollateralTokenError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedTokenPairError, UnsupportedZapperFunctionError, WithdrawalInProgressError, WithdrawalOutputAmount, accountNotMidasGreenlisted, amountSchema, analyticsChartQueryOptionsSchema, analyticsChartQueryParamsSchema, analyticsChartQuerySchema, analyticsPositionListOptionsSchema, analyticsPositionListQueryParamsSchema, analyticsPositionListQuerySchema, analyticsPositionPageSchema, analyticsPositionSchema, analyticsPositionSortFieldSchema, analyticsSortDirectionSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, curatorNameSchema, curatorSchema, dataSourceSchema, debtOutOfRange, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, forbiddenToken, instantReceivedAssetSchema, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, isFilterSet, kycRequirementSchema, leverageOutOfRange, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, liquidatorNotEligible, malformedTransaction, marketExpired, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPaused, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, poolSunset, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, protocolChartMetricSchema, quotaAssetSchema, quotaCountExceeded, quotaLimitReached, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, reservePriceLimited, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, rwaOpenRequirementsNotMet, rwaProtocolSchema, safeValue, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress, withdrawalOutputAmountSchema };
@@ -369,37 +369,43 @@ interface OpenStrategyPositionProjection extends EstimatedProjection {
369
369
  * accordingly (omitted entirely when it reaches zero).
370
370
  */
371
371
  collateralAdded: TokenAmount[];
372
+ /**
373
+ * Tokens the same transaction hands back to the wallet
374
+ * (`withdrawCollateral` calls, with the MAX_UINT256 sentinel resolved
375
+ * against replayed balances).
376
+ *
377
+ * Empty for an opening that keeps everything it bought; a borrow pays its
378
+ * loan out here, and the values above are what is left once it has.
379
+ */
380
+ collateralWithdrawn: TokenAmount[];
372
381
  /**
373
382
  * The oracle could not price a token; it contributes nothing to the values.
374
383
  */
375
384
  warning?: UnpriceableTokenError;
376
385
  }
377
386
  /**
378
- * What a facade account-opening transaction that already exists would do —
379
- * the counterpart of `prepare.openNewStrategy` on a non-RWA market, read off
387
+ * What an account-opening transaction that already exists would do — the
388
+ * counterpart of `prepare.openNewStrategy` and `prepare.borrow`, read off
380
389
  * calldata rather than planned into it.
381
390
  **/
382
- interface OpenNonRWAStrategyPositionPreview extends OpenStrategyPositionProjection {
391
+ interface OpenStrategyPositionPreview extends OpenStrategyPositionProjection {
383
392
  operation: "OpenCreditAccount";
384
- }
385
- /**
386
- * What an RWA-factory account-opening transaction that already exists would
387
- * do — the counterpart of `prepare.openNewStrategy` on an RWA market.
388
- **/
389
- interface OpenRWAStrategyPositionPreview extends OpenStrategyPositionProjection {
390
- operation: "RWAOpenCreditAccount";
393
+ /**
394
+ * Existing zero-debt, zero-quota account this operation reopens.
395
+ */
396
+ creditAccount?: Address;
391
397
  /**
392
398
  * Registration args the factory received (Securitize: `tokensToRegister`,
393
- * `signaturesToCache`).
399
+ * `signaturesToCache`). Present on RWA-factory accounts only.
400
+ */
401
+ rwaArgs?: RWAOperationArgs;
402
+ /**
403
+ * Whether the multicall grants the Midas greenlisted role to the credit
404
+ * account via `receiveGreenlist()`. Needed for the Midas empty-account
405
+ * flow.
394
406
  */
395
- rwaArgs: RWAOperationArgs;
407
+ midasGreenlistsAccount?: boolean;
396
408
  }
397
- /**
398
- * What an account-opening transaction that already exists would do — the
399
- * counterpart of `prepare.openNewStrategy`, read off calldata rather than
400
- * planned into it.
401
- **/
402
- type OpenStrategyPositionPreview = OpenNonRWAStrategyPositionPreview | OpenRWAStrategyPositionPreview;
403
409
  /**
404
410
  * What a transaction on an existing account would do — the counterpart of the
405
411
  * `prepare` flows that adjust one (`depositStrategy`, `withdrawStrategy`,
@@ -585,4 +591,4 @@ interface DelayedStrategyPositionOperationPreview extends CreditOperationMarket
585
591
  */
586
592
  type OperationPreview = PoolPositionOperationPreview | OpenStrategyPositionPreview | AdjustStrategyPositionPreview | ExitStrategyPositionPreview | RepayStrategyPositionPreview | DelayedStrategyPositionOperationPreview;
587
593
  //#endregion
588
- export { AccountHoldings, AccountMetrics, AccountProjection, AccountStateChange, AdjustStrategyPositionPreview, CreditOperationMarket, DelayedStrategyPositionOperationPreview, Estimated, EstimatedProjection, ExitStrategyPositionPreview, InstantStrategyPositionOperationPreview, OpenNonRWAStrategyPositionPreview, OpenRWAStrategyPositionPreview, OpenStrategyPositionPreview, OperationPreview, PoolOperationType, PoolPositionOperationPreview, PreviewOperationInput, PreviewOperationOptions, RepayStrategyPositionPreview, RoutedField, asEstimated };
594
+ export { AccountHoldings, AccountMetrics, AccountProjection, AccountStateChange, AdjustStrategyPositionPreview, CreditOperationMarket, DelayedStrategyPositionOperationPreview, Estimated, EstimatedProjection, ExitStrategyPositionPreview, InstantStrategyPositionOperationPreview, OpenStrategyPositionPreview, OperationPreview, PoolOperationType, PoolPositionOperationPreview, PreviewOperationInput, PreviewOperationOptions, RepayStrategyPositionPreview, RoutedField, asEstimated };
@@ -19,17 +19,18 @@ import { AccountBotsService } from "./bots/AccountBotsService.js";
19
19
  import { PeripheryCompressorV310Contract } from "./bots/PeripheryCompressorV310Contract.js";
20
20
  import "./bots/index.js";
21
21
  import { CreditAccountsServiceV310 } from "./CreditAccountsServiceV310.js";
22
- import { LeverageBand } from "./intents/leverage-band.js";
23
22
  import { CalcDefaultQuotaProps, CalcQuotaUpdateProps, CalcRecommendedQuotaProps, calcDefaultQuota, calcQuotaUpdate, calcRecommendedQuota, roundUpQuota } from "./quota-utils.js";
24
23
  import { AccountCalculatorOperation } from "./intents/operations.js";
25
24
  import { AddCollateralIntent, AdjustLeverageIntent, ClaimRemainder, CreditAccountSlice, DelayableIntent, DelayedRoute, DelayedStart, DelayedStartResult, DepositStrategyIntent, FinishIntentProps, FinishIntentResult, InstantRoute, IntentPreviewResult, IntentRoutesResult, OperationState, PathLossRate, RepayStrategyIntent, ResumableIntent, RouteErrors, StartIntent, WithdrawAssetIntent, WithdrawCeilings, WithdrawStrategyIntent } from "./intents/types.js";
25
+ import { BorrowProps, BorrowState } from "./intents/borrow.js";
26
+ import { LeverageBand } from "./intents/leverage-band.js";
26
27
  import { OpenStrategyProps, OpenStrategyState } from "./intents/open-strategy.js";
27
28
  import { fetchCreditAccountSlice, toCreditAccountSlice } from "./intents/utils/credit-account-slice.js";
28
29
  import { isPhantomToken } from "./intents/utils/pick-token.js";
29
- import { CreditAccountOperationsService, OpenStrategyPreviewResult } from "./intents/index.js";
30
+ import { BorrowPreviewResult, CreditAccountOperationsService, EmptyAccountPreviewResult, OpenStrategyPreviewResult } from "./intents/index.js";
30
31
  import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./liquidations/constants.js";
31
32
  import { BuildLiquidationTxProps, BuildLiquidationTxPropsBase, GetLiquidatableAccountsProps, GetLiquidationDetailsProps, GetLiquidationDetailsPropsBase, GetLiquidationPositionsProps, GetLiquidationPositionsPropsBase, LoadRWALiquidatorsProps, OnchainLiquidationCall, OnchainLiquidationData, OnchainLiquidationOutput, RWALiquidatorInfo } from "./liquidations/types.js";
32
33
  import { LiquidationsService } from "./liquidations/LiquidationsService.js";
33
34
  import { MultichainLiquidationsService } from "./liquidations/MultichainLiquidationsService.js";
34
35
  import "./liquidations/index.js";
35
- export { AbstractWithdrawalCompressorContract, AccountBotsService, type AccountCalculatorOperation, AccountToCheck, type AddCollateralIntent, type AdjustLeverageIntent, AssembleCaOperationsProps, AssembleClaimDelayedCallsProps, AssembleCloseCreditAccountCallsProps, AssembleRepayCreditAccountCallsProps, AssembleStartDelayedWithdrawalCallsProps, BotStatusCall, BotsDirectResponse, BuildLiquidationTxProps, BuildLiquidationTxPropsBase, CMSlice, CalcDefaultQuotaProps, CalcQuotaUpdateProps, CalcRecommendedQuotaProps, ClaimFarmRewardsProps, type ClaimRemainder, ClaimableWithdrawal, CloseCreditAccountResult, ConnectedBotsCall, ConnectedBotsPerAccount, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountDataCall, CreditAccountFilter, CreditAccountOperationResult, CreditAccountOperationsService, CreditAccountReadOptions, type CreditAccountSlice, CreditAccountsCall, CreditAccountsQuery, CreditAccountsReadOptions, CreditAccountsServiceV310, CreditAccountsTarget, CreditManagerFilter, CreditManagerOperationResult, CurrentWithdrawals, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, type DelayableIntent, DelayedIntentExtended, type DelayedRoute, type DelayedStart, type DelayedStartResult, type DepositStrategyIntent, EncodableCreditAccountOperation, type FinishIntentProps, type FinishIntentResult, FullyLiquidateProps, FullyLiquidateResult, GetApprovalAddressProps, GetConnectedBotsResponse, GetConnectedBotsResult, GetConnectedMigrationBotsResult, GetCreditAccountsArgs, GetCreditAccountsOptions, GetExternalAccountCurrentWithdrawalsProps, GetLiquidatableAccountsProps, GetLiquidationDetailsProps, GetLiquidationDetailsPropsBase, GetLiquidationPositionsProps, GetLiquidationPositionsPropsBase, GetWithdrawalRequestResultProps, ICreditAccountsService, IRedemptionLoggerContract, IWithdrawalCompressorContract, type InstantRoute, type IntentPreviewResult, type IntentRoutesResult, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, type LeverageBand, LiquidationsService, LoadRWALiquidatorsProps, MulticallWithFailure, MultichainLiquidationsService, OnchainLiquidationCall, OnchainLiquidationData, OnchainLiquidationOutput, OnchainRequestableWithdrawal, OpenCAProps, OpenStrategyPreviewResult, type OpenStrategyProps, type OpenStrategyState, type OperationState, PartiallyLiquidateProps, type PathLossRate, PendingWithdrawal, PeripheryCompressorV310Contract, PreviewDelayedWithdrawalProps, RWALiquidatorInfo, RedemptionLog, RedemptionLoggerV310Contract, type RepayStrategyIntent, RequestableWithdrawal, type ResumableIntent, Rewards, type RouteErrors, SetBotProps, SetBotResult, type StartIntent, type WithdrawAssetIntent, type WithdrawCeilings, type WithdrawStrategyIntent, WithdrawableAsset, WithdrawalCompressorLocation, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WithdrawalCompressorVersion, WithdrawalOutput, WithdrawalStatus, WithdrawalsState, calcDefaultQuota, calcQuotaUpdate, calcRecommendedQuota, createRedemptionLogger, createWithdrawalCompressor, decodeDelayedIntent, encodeDelayedIntent, fetchCreditAccountSlice, getWithdrawalCompressorAddress, iCreditAccountAbi, isPhantomToken, roundUpQuota, toClaimableWithdrawal, toCreditAccountSlice, toPendingWithdrawal, toRequestableWithdrawal, toWithdrawalStatus };
36
+ export { AbstractWithdrawalCompressorContract, AccountBotsService, type AccountCalculatorOperation, AccountToCheck, type AddCollateralIntent, type AdjustLeverageIntent, AssembleCaOperationsProps, AssembleClaimDelayedCallsProps, AssembleCloseCreditAccountCallsProps, AssembleRepayCreditAccountCallsProps, AssembleStartDelayedWithdrawalCallsProps, BorrowPreviewResult, type BorrowProps, type BorrowState, BotStatusCall, BotsDirectResponse, BuildLiquidationTxProps, BuildLiquidationTxPropsBase, CMSlice, CalcDefaultQuotaProps, CalcQuotaUpdateProps, CalcRecommendedQuotaProps, ClaimFarmRewardsProps, type ClaimRemainder, ClaimableWithdrawal, CloseCreditAccountResult, ConnectedBotsCall, ConnectedBotsPerAccount, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountDataCall, CreditAccountFilter, CreditAccountOperationResult, CreditAccountOperationsService, CreditAccountReadOptions, type CreditAccountSlice, CreditAccountsCall, CreditAccountsQuery, CreditAccountsReadOptions, CreditAccountsServiceV310, CreditAccountsTarget, CreditManagerFilter, CreditManagerOperationResult, CurrentWithdrawals, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, type DelayableIntent, DelayedIntentExtended, type DelayedRoute, type DelayedStart, type DelayedStartResult, type DepositStrategyIntent, EmptyAccountPreviewResult, EncodableCreditAccountOperation, type FinishIntentProps, type FinishIntentResult, FullyLiquidateProps, FullyLiquidateResult, GetApprovalAddressProps, GetConnectedBotsResponse, GetConnectedBotsResult, GetConnectedMigrationBotsResult, GetCreditAccountsArgs, GetCreditAccountsOptions, GetExternalAccountCurrentWithdrawalsProps, GetLiquidatableAccountsProps, GetLiquidationDetailsProps, GetLiquidationDetailsPropsBase, GetLiquidationPositionsProps, GetLiquidationPositionsPropsBase, GetWithdrawalRequestResultProps, ICreditAccountsService, IRedemptionLoggerContract, IWithdrawalCompressorContract, type InstantRoute, type IntentPreviewResult, type IntentRoutesResult, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, type LeverageBand, LiquidationsService, LoadRWALiquidatorsProps, MulticallWithFailure, MultichainLiquidationsService, OnchainLiquidationCall, OnchainLiquidationData, OnchainLiquidationOutput, OnchainRequestableWithdrawal, OpenCAProps, OpenStrategyPreviewResult, type OpenStrategyProps, type OpenStrategyState, type OperationState, PartiallyLiquidateProps, type PathLossRate, PendingWithdrawal, PeripheryCompressorV310Contract, PreviewDelayedWithdrawalProps, RWALiquidatorInfo, RedemptionLog, RedemptionLoggerV310Contract, type RepayStrategyIntent, RequestableWithdrawal, type ResumableIntent, Rewards, type RouteErrors, SetBotProps, SetBotResult, type StartIntent, type WithdrawAssetIntent, type WithdrawCeilings, type WithdrawStrategyIntent, WithdrawableAsset, WithdrawalCompressorLocation, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WithdrawalCompressorVersion, WithdrawalOutput, WithdrawalStatus, WithdrawalsState, calcDefaultQuota, calcQuotaUpdate, calcRecommendedQuota, createRedemptionLogger, createWithdrawalCompressor, decodeDelayedIntent, encodeDelayedIntent, fetchCreditAccountSlice, getWithdrawalCompressorAddress, iCreditAccountAbi, isPhantomToken, roundUpQuota, toClaimableWithdrawal, toCreditAccountSlice, toPendingWithdrawal, toRequestableWithdrawal, toWithdrawalStatus };
@@ -0,0 +1,141 @@
1
+ import { TokenAmount } from "../../../model/primitives.js";
2
+ import "../../../model/index.js";
3
+ import { Asset } from "../../base/types.js";
4
+ import { MultiCall } from "../../types/transactions.js";
5
+ import { OnchainSDK } from "../../OnchainSDK.js";
6
+ import { CreditAccountSlice, OperationState } from "./types.js";
7
+ import "../../index.js";
8
+ import { Address } from "viem";
9
+ //#region src/onchain/accounts/intents/borrow.d.ts
10
+ /**
11
+ * Taking a loan against collateral, in one transaction that opens the account.
12
+ *
13
+ * The plainest thing a credit account can do, and the one shape of it the
14
+ * leveraged flows cannot express: the borrowed funds do not stay on the
15
+ * account to be traded, they go to the wallet. What is left behind is the
16
+ * collateral and the debt it backs.
17
+ */
18
+ interface BorrowProps {
19
+ sdk: OnchainSDK;
20
+ /** Credit manager to open the account in. */
21
+ creditManager: Address;
22
+ /** Token the wallet puts up, in the manager's collateral list. */
23
+ collateralToken: Address;
24
+ /** Amount of {@link collateralToken}, in its own units. */
25
+ collateralAmount: bigint;
26
+ /**
27
+ * Token the loan is paid out in. The market underlying needs no trade;
28
+ * anything else is bought with the borrowed underlying on the way out.
29
+ *
30
+ * On an RWA market the underlying is a compliance wrapper that cannot leave
31
+ * the account, so the payout there is the asset behind it — USDC rather than
32
+ * dcUSDC — and the wrapper itself is refused.
33
+ */
34
+ borrowToken: Address;
35
+ /** Amount of {@link borrowToken} the wallet asks for, in its own units. */
36
+ borrowAmount: bigint;
37
+ /** Router slippage in PERCENTAGE_FORMAT (100% = 10_000). */
38
+ slippage: number | undefined;
39
+ /** Extra quota headroom in PERCENTAGE_FORMAT. */
40
+ quotaReserve: number | undefined;
41
+ /**
42
+ * Existing credit account to draw the loan on, instead of opening one.
43
+ *
44
+ * Must carry no debt and no quotas, as a reused opening must. Borrowing on
45
+ * an account that already owes is what the `ADJUST_LEVERAGE` intent is for.
46
+ **/
47
+ creditAccount?: CreditAccountSlice;
48
+ }
49
+ /**
50
+ * Where a borrow leaves the wallet and the account it opens.
51
+ *
52
+ * A whole {@link OperationState}, holdings included: unlike an opening, a
53
+ * borrow has no second branch of balances to choose between — the collateral
54
+ * is the only thing left on the account and its amount is known exactly.
55
+ * Slippage lands on the payout instead, which is why that one is reported
56
+ * twice.
57
+ *
58
+ * Being that state rather than merely resembling it is what lets a borrow
59
+ * result go straight to `checkSimulation`, which weighs whatever the engine
60
+ * projected: the market, the debt, the quotas and the two factors, all of
61
+ * which a borrow reports where an operation on an existing account does.
62
+ */
63
+ interface BorrowState extends OperationState {
64
+ /** What the wallet puts up, as it will sit on the account. */
65
+ collateral: TokenAmount;
66
+ /**
67
+ * What the wallet is expected to receive, in the token it asked for. Equal
68
+ * to the debt when that token is the market underlying, and to the debt
69
+ * rescaled where an RWA payout unwraps it one for one; in neither case is
70
+ * anything traded.
71
+ */
72
+ borrowed: TokenAmount;
73
+ /**
74
+ * The floor under {@link borrowed} once slippage is allowed for — what the
75
+ * transaction is signed against. Equal to `borrowed` when nothing is traded.
76
+ */
77
+ minBorrowed: TokenAmount;
78
+ /**
79
+ * Router slippage the payout leg was quoted at, in PERCENTAGE_FORMAT
80
+ * (100% = 10_000). The SDK's own default where the caller named none.
81
+ */
82
+ slippage: number;
83
+ /**
84
+ * Quota to buy for the collateral; feeds `openCA.averageQuota` and
85
+ * `openCA.minQuota` alike, both branches being the same here.
86
+ *
87
+ * Transport for the transaction rather than something to display, like
88
+ * {@link calls} below.
89
+ */
90
+ quotaIncrease: Asset[];
91
+ /**
92
+ * The leg that turns the borrowed underlying into the payout: a router path
93
+ * where it is bought, the vault redemption where an RWA market unwraps it,
94
+ * empty where the payout is the underlying itself. Feeds `openCA.calls`,
95
+ * which places it before the withdrawal.
96
+ */
97
+ calls: MultiCall[];
98
+ /**
99
+ * The account this loan was simulated against and must be executed on, when
100
+ * it reuses one; `undefined` for a borrow that opens its own.
101
+ *
102
+ * Carried here rather than asked of the caller again at `buildTx`, so the
103
+ * transaction cannot be built against an account the numbers were not
104
+ * computed for.
105
+ **/
106
+ creditAccount?: Address;
107
+ }
108
+ /**
109
+ * Builds the state a borrow would leave behind.
110
+ *
111
+ * The debt is named rather than derived: a borrow asks for an amount, where an
112
+ * opening asks for a leverage and lets the collateral decide. Everything the
113
+ * loan pays out leaves the account, so the collateral alone backs it — which
114
+ * is what makes the health factor here a straight function of the two amounts.
115
+ *
116
+ * Produces no operation list, as opening never does: the caller hands the
117
+ * numbers and the calls to `sdk.accounts.openCA`, with `withdrawToken` set to
118
+ * the payout.
119
+ */
120
+ declare function buildBorrowState(props: BorrowProps): Promise<BorrowState>;
121
+ /** Inputs of {@link borrowCollateralQuota}. */
122
+ interface BorrowCollateralQuotaProps {
123
+ sdk: OnchainSDK;
124
+ creditManager: Address;
125
+ /** Collateral the fresh account will hold. */
126
+ assets: Asset[];
127
+ /** Extra quota headroom in PERCENTAGE_FORMAT. */
128
+ quotaReserve: number | undefined;
129
+ }
130
+ /**
131
+ * Quota a borrow buys for its collateral on an account that holds none yet.
132
+ *
133
+ * Shared with `maxBorrow`, because a quota short of the collateral's weighted
134
+ * value is what caps the loan: the two have to read the same number or the
135
+ * ceiling one offers is one the other refuses.
136
+ *
137
+ * @param props - {@link BorrowCollateralQuotaProps}
138
+ **/
139
+ declare function borrowCollateralQuota({ sdk, creditManager, assets, quotaReserve }: BorrowCollateralQuotaProps): Asset[];
140
+ //#endregion
141
+ export { BorrowCollateralQuotaProps, BorrowProps, BorrowState, borrowCollateralQuota, buildBorrowState };