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

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 (69) hide show
  1. package/dist/cjs/dev/midasUtils.js +11 -46
  2. package/dist/cjs/model/errors/index.js +1 -0
  3. package/dist/cjs/model/errors/operation-errors.js +9 -0
  4. package/dist/cjs/model/index.js +1 -0
  5. package/dist/cjs/onchain/accounts/intents/collateral-money.js +41 -0
  6. package/dist/cjs/onchain/accounts/intents/guards.js +15 -3
  7. package/dist/cjs/onchain/accounts/intents/index.js +21 -18
  8. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +12 -38
  9. package/dist/cjs/onchain/accounts/intents/realize.js +10 -2
  10. package/dist/cjs/onchain/accounts/intents/tail.js +1 -1
  11. package/dist/cjs/onchain/accounts/intents/withdraw-limits.js +97 -0
  12. package/dist/cjs/onchain/index.js +2 -0
  13. package/dist/cjs/onchain/market/adapters/abi/conctructorAbi.js +1 -1
  14. package/dist/cjs/onchain/preview/preview/previewOpenStrategyPosition.js +10 -16
  15. package/dist/cjs/onchain/preview/preview/previewOperation.js +19 -11
  16. package/dist/cjs/onchain/preview/preview/replayMulticall.js +4 -3
  17. package/dist/cjs/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  18. package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +2 -2
  19. package/dist/cjs/onchain/validation/bundles/checkRWAOpening.js +1 -2
  20. package/dist/cjs/onchain/validation/checkOperation.js +0 -1
  21. package/dist/cjs/onchain/validation/checks/checkReservePriceLimited.js +30 -0
  22. package/dist/cjs/onchain/validation/checks/index.js +2 -0
  23. package/dist/cjs/onchain/validation/index.js +2 -0
  24. package/dist/cjs/sdk/prepare/PrepareApi.js +3 -2
  25. package/dist/esm/dev/midasUtils.js +12 -47
  26. package/dist/esm/model/errors/index.js +2 -2
  27. package/dist/esm/model/errors/operation-errors.js +9 -1
  28. package/dist/esm/model/index.js +2 -2
  29. package/dist/esm/onchain/accounts/intents/collateral-money.js +40 -0
  30. package/dist/esm/onchain/accounts/intents/guards.js +15 -3
  31. package/dist/esm/onchain/accounts/intents/index.js +21 -18
  32. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +12 -38
  33. package/dist/esm/onchain/accounts/intents/realize.js +10 -2
  34. package/dist/esm/onchain/accounts/intents/tail.js +1 -1
  35. package/dist/esm/onchain/accounts/intents/withdraw-limits.js +95 -0
  36. package/dist/esm/onchain/index.js +2 -1
  37. package/dist/esm/onchain/market/adapters/abi/conctructorAbi.js +1 -1
  38. package/dist/esm/onchain/preview/preview/previewOpenStrategyPosition.js +11 -17
  39. package/dist/esm/onchain/preview/preview/previewOperation.js +19 -11
  40. package/dist/esm/onchain/preview/preview/replayMulticall.js +4 -3
  41. package/dist/esm/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  42. package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +2 -2
  43. package/dist/esm/onchain/validation/bundles/checkRWAOpening.js +1 -2
  44. package/dist/esm/onchain/validation/checkOperation.js +0 -1
  45. package/dist/esm/onchain/validation/checks/checkReservePriceLimited.js +29 -0
  46. package/dist/esm/onchain/validation/checks/index.js +2 -1
  47. package/dist/esm/onchain/validation/index.js +2 -1
  48. package/dist/esm/sdk/prepare/PrepareApi.js +3 -2
  49. package/dist/types/dev/midasUtils.d.ts +3 -4
  50. package/dist/types/model/errors/index.d.ts +2 -2
  51. package/dist/types/model/errors/operation-errors.d.ts +41 -1
  52. package/dist/types/model/index.d.ts +3 -3
  53. package/dist/types/model/previews.d.ts +11 -20
  54. package/dist/types/onchain/accounts/intents/collateral-money.d.ts +42 -0
  55. package/dist/types/onchain/accounts/intents/guards.d.ts +18 -2
  56. package/dist/types/onchain/accounts/intents/index.d.ts +23 -14
  57. package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +3 -8
  58. package/dist/types/onchain/accounts/intents/types.d.ts +26 -4
  59. package/dist/types/onchain/accounts/intents/withdraw-limits.d.ts +80 -0
  60. package/dist/types/onchain/index.d.ts +2 -1
  61. package/dist/types/onchain/preview/preview/previewOpenStrategyPosition.d.ts +5 -3
  62. package/dist/types/onchain/preview/preview/replayMulticall.d.ts +8 -7
  63. package/dist/types/onchain/validation/checks/checkReservePriceLimited.d.ts +31 -0
  64. package/dist/types/onchain/validation/checks/index.d.ts +2 -1
  65. package/dist/types/onchain/validation/index.d.ts +2 -1
  66. package/dist/types/onchain/validation/raise.d.ts +2 -2
  67. package/dist/types/sdk/prepare/PrepareApi.d.ts +1 -1
  68. package/dist/types/sdk/prepare/types.d.ts +23 -16
  69. package/package.json +1 -1
@@ -11,6 +11,7 @@ import { collectPriceImpact } from "./utils/price-impact.js";
11
11
  import { clearedQuotas, getQuotasForUpdate, quotasAfterUpdate } from "./utils/quotas-for-update.js";
12
12
  import { createRouterPaths } from "./utils/router-path.js";
13
13
  import { buildAddCollateralOperation, buildClaimDelayedWithdrawalOperation, buildCloseSwapOperation, buildDecreaseDebtOperation, buildIncreaseDebtOperation, buildQuotaUpdateOperation, buildStartDelayedWithdrawalOperation, buildSwapOperation, buildUnwrapRwaCollateralOperation, buildWithdrawCollateralOperation, buildWrapRwaCollateralOperation, instantOutput } from "./operations.js";
14
+ import { withdrawLimits } from "./withdraw-limits.js";
14
15
  //#region src/onchain/accounts/intents/realize.ts
15
16
  /**
16
17
  * Turns a plan into operations: the one place that talks to the router, knows
@@ -319,11 +320,18 @@ async function realize(steps, props) {
319
320
  totalValue: projected.totalValue
320
321
  };
321
322
  const projection = sdk.positions.projection(snapshot, { availableLiquidityChange: creditAccount.totalDebt - debt });
322
- assertCollateralised(sdk.positions.healthFactor({
323
+ const settled = {
323
324
  ...snapshot,
324
325
  assets,
325
326
  totalValue: floor.totalValue
326
- }, { safePrices: withdrawsCollateral }), withdrawsCollateral);
327
+ };
328
+ assertCollateralised(sdk.positions.healthFactor(settled, { safePrices: withdrawsCollateral }), withdrawsCollateral, () => ({
329
+ atMainPrices: sdk.positions.healthFactor(settled, { safePrices: false }),
330
+ withdrawable: toTokenAmount(sdk, underlying, withdrawLimits({
331
+ creditAccount,
332
+ sdk
333
+ }).safePartial)
334
+ }));
327
335
  const priceImpact = await collectPriceImpact(probes, {
328
336
  totalValue: projected.totalValue,
329
337
  netValue: projected.totalValue - debt,
@@ -7,8 +7,8 @@ import { toTargetDecimals } from "./utils/common.js";
7
7
  import { createOraclePaths } from "./utils/router-path.js";
8
8
  import { planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw } from "./plan.js";
9
9
  import { instantOutput } from "./operations.js";
10
- import { realize } from "./realize.js";
11
10
  import { accountView } from "./view.js";
11
+ import { realize } from "./realize.js";
12
12
  //#region src/onchain/accounts/intents/tail.ts
13
13
  /**
14
14
  * The second half of a delayed intent: the claim, then whatever the intent
@@ -0,0 +1,95 @@
1
+ import { BigIntMath } from "../../utils/bigint-math.js";
2
+ import "../../utils/index.js";
3
+ import { MIN_HEALTH_FACTOR_FACADE } from "../../validation/helpers/health-factor-limits.js";
4
+ import "../../validation/index.js";
5
+ import { eq } from "./utils/common.js";
6
+ import { collateralMoney } from "./collateral-money.js";
7
+ import { maxProportionalWithdrawal } from "./math.js";
8
+ import { accountView } from "./view.js";
9
+ //#region src/onchain/accounts/intents/withdraw-limits.ts
10
+ /**
11
+ * Every limit a `WITHDRAW` answers to, in underlying units.
12
+ *
13
+ * The one place they are assembled, so the figure a form is offered and the
14
+ * figure the collateral guard names when it turns a withdrawal down cannot
15
+ * drift apart: `CreditAccountOperationsService` reports this, and the guard
16
+ * quotes it back.
17
+ *
18
+ * @param props - Account slice, the SDK holding its market, and optionally the
19
+ * collateral the withdrawal would be funded from
20
+ * @returns The three limits, see {@link WithdrawCeilings}
21
+ **/
22
+ function withdrawLimits(props) {
23
+ const { creditAccount, sdk } = props;
24
+ const view = accountView(creditAccount, sdk);
25
+ const partial = maxProportionalWithdrawal(view, view.debtLimits);
26
+ const safe = maxSafeWithdrawal({
27
+ ...props,
28
+ targetHF: BigInt(MIN_HEALTH_FACTOR_FACADE)
29
+ });
30
+ return {
31
+ partial,
32
+ safePartial: BigIntMath.min(partial, safe),
33
+ exit: view.collateral > 0n ? view.collateral : 0n
34
+ };
35
+ }
36
+ /**
37
+ * Largest proportional withdrawal the safe-price collateral check still clears,
38
+ * in underlying units.
39
+ *
40
+ * A withdrawal hands funds over, so the facade weighs the account it leaves
41
+ * behind at safe prices rather than main ones — see {@link collateralMoney}.
42
+ * That is a second limit on top of the facade's `debtLimits`, and the two are
43
+ * independent: a caller wanting the amount a form may actually offer takes the
44
+ * lesser of this and `maxProportionalWithdrawal`.
45
+ *
46
+ * The arithmetic is the check solved for the amount. Taking `W` out at fixed
47
+ * leverage repays `dD = D·W/C`, so `W·TVL/C` of value is sold out of the source
48
+ * token; each dollar of that sale costs the check the source's threshold times
49
+ * its safe-to-main price ratio, while the repayment relieves `targetHF` per
50
+ * dollar of debt. Both terms are linear in `W`, which is why one division
51
+ * answers instead of a search — and why the answer is exact rather than a
52
+ * bound, as long as the plan really does fund itself from `sourceToken`.
53
+ *
54
+ * Two consequences worth stating, because they surprise:
55
+ *
56
+ * - An account whose collateral is entirely a token the reserve feed marks
57
+ * down cannot withdraw at all once it is under the threshold. A proportional
58
+ * withdrawal scales collateral and debt together, so it leaves the safe-price
59
+ * factor exactly where it found it — no amount climbs back over.
60
+ * - Leaving entirely is never refused for this reason: the exit settles the
61
+ * debt instead of shrinking it, and a check with no debt to divide by has
62
+ * nothing to refuse.
63
+ *
64
+ * @returns Amount in underlying units. The account's net value when safe prices
65
+ * do not limit the withdrawal at all, so the caller's `min` is a no-op; `0n`
66
+ * when the account already sits below `targetHF` at safe prices, and only the
67
+ * exit is left
68
+ **/
69
+ function maxSafeWithdrawal(props) {
70
+ const { creditAccount, sdk, targetHF } = props;
71
+ const view = accountView(creditAccount, sdk);
72
+ if (view.collateral <= 0n) return 0n;
73
+ if (view.debt === 0n) return view.collateral;
74
+ const money = collateralMoney(creditAccount, sdk);
75
+ const source = props.sourceToken ?? view.fattest();
76
+ const holding = source === void 0 ? void 0 : creditAccount.tokens.find((t) => eq(t.token, source));
77
+ if (!holding) return view.collateral;
78
+ let total = 0n;
79
+ for (const t of creditAccount.tokens) if (money.counts(t)) total += money.weigh(t);
80
+ const debtUsd = money.mainUsd(money.underlying, view.debt);
81
+ if (debtUsd === void 0 || debtUsd <= 0n) return view.collateral;
82
+ const slack = total - debtUsd * targetHF;
83
+ if (slack < 0n) return 0n;
84
+ const sourceMainUsd = money.mainUsd(holding.token, holding.balance);
85
+ if (sourceMainUsd === void 0 || sourceMainUsd <= 0n) return view.collateral;
86
+ const sourceRate = money.lt(holding.token) * money.checkedUsd(holding);
87
+ const tvlUsd = money.mainUsd(money.underlying, view.collateral + view.debt);
88
+ if (tvlUsd === void 0) return view.collateral;
89
+ const drain = sourceRate * tvlUsd - targetHF * debtUsd * sourceMainUsd;
90
+ if (drain <= 0n) return view.collateral;
91
+ const limit = view.collateral * slack * sourceMainUsd / drain;
92
+ return limit < view.collateral ? limit : view.collateral;
93
+ }
94
+ //#endregion
95
+ export { maxSafeWithdrawal, withdrawLimits };
@@ -212,6 +212,7 @@ import { checkPoolPaused } from "./validation/checks/checkPoolPaused.js";
212
212
  import { checkPoolSunset } from "./validation/checks/checkPoolSunset.js";
213
213
  import { checkQuotaCount } from "./validation/checks/checkQuotaCount.js";
214
214
  import { checkQuotaLimit } from "./validation/checks/checkQuotaLimit.js";
215
+ import { checkReservePriceLimited } from "./validation/checks/checkReservePriceLimited.js";
215
216
  import { checkAccountQuotas } from "./validation/bundles/checkAccountQuotas.js";
216
217
  import { checkWalletAllowance } from "./validation/bundles/checkWalletAllowance.js";
217
218
  import { checkWalletBalance } from "./validation/bundles/checkWalletBalance.js";
@@ -298,4 +299,4 @@ import { replayMulticall } from "./preview/preview/replayMulticall.js";
298
299
  import { previewOperation } from "./preview/preview/previewOperation.js";
299
300
  import "./preview/index.js";
300
301
  import "./types/index.js";
301
- export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AccountMigratorAdapterContract, AdapterType, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, CamelotV3AdapterContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountState, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DEGEN_NFT_MIDAS, DEGEN_NFT_SECURITIZE, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, EXECUTE_BYTES_SELECTOR, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LidoV1AdapterContract, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_INT96, MIN_SAFE_HEALTH_FACTOR_FORM, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasDegenNFT, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NON_STRATEGY_PHANTOM_TOKEN_TYPES, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PeripheryCompressorV310Contract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeDegenNFT, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UpshiftVaultAdapterContract, VERSION_RANGE_310, VelodromeV2RouterAdapterContract, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, amountOf, assetsMap, attachOptionsSchema, botPermissionsToString, bpsToRay, buildDelayedStrategyPositionOperationPreview, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkAccountQuotas, checkBorrowLimit, checkCollateralFunding, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkCreditOperation, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkHealthFactors, checkIncreaseDebt, checkIncreaseQuota, checkLeverage, checkLiquidation, checkLiquidationEligibility, checkLiquidationFunding, checkLiquidatorEligible, checkMarket, checkMarketExpired, checkObtained, checkOperation, checkPoolFunding, checkPoolLiquidity, checkPoolOperation, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkRWAOpenRequirements, checkRWAOpening, checkSimulation, checkWallet, checkWalletAllowance, checkWalletBalance, childLogger, classifyCloseOrRepay, classifyCurveOperation, classifyInnerOperations, collateralPriceInUnderlying, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectDelayedClaim, detectDelayedOperation, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateClaimableAt, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, fetchRedstonePayloads, filterDust, filterDustUSD, findCallTo, findCallWithInput, findCuratorMarketConfigurator, findExecuteBytes, fmtBinaryMask, fnSigToName, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAccountTargetCollateral, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getLegacyStrategyTarget, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, hasAdapterDeployParamsAbi, healthFactorBps, hexEq, hydrateAddressProvider, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, iCreditAccountAbi, iCurvePoolAbi, iCurvePoolStableNGAbi, iCurvePool_2Abi, iCurvePool_3Abi, iCurvePool_4Abi, iCurveV1StableNgAdapterAbi, iCurveV1_2AssetsAdapterAbi, iCurveV1_3AssetsAdapterAbi, iCurveV1_4AssetsAdapterAbi, iDaiUsdsAbi, iDaiUsdsAdapterAbi, iERC4626Abi, iERC4626ReferralAbi, iFluidDexAbi, iFluidDexAdapterAbi, iInfinifiGatewayAbi, iInfinifiGatewayAdapterAbi, iInfinifiUnwindingGatewayAbi, iInfinifiUnwindingGatewayAdapterAbi, iKelpLRTDepositPoolGatewayAbi, iKelpLRTWithdrawalManagerGatewayAbi, iKelpLrtDepositPoolAdapterAbi, iKelpLrtDepositPoolGatewayAbi, iKelpLrtWithdrawalManagerAdapterAbi, iKelpLrtWithdrawalManagerGatewayAbi, iLidoV1AdapterAbi, iMellow4626VaultAdapterAbi, iMellowClaimerAbi, iMellowClaimerAdapterAbi, iMellowWrapperAbi, iMellowWrapperAdapterAbi, iMidasGatewayAdapterV311Abi, iMidasGatewayV311Abi, iMidasIssuanceVaultAdapterV310Abi, iMidasIssuanceVaultV310Abi, iMidasRedemptionVaultAdapterV310Abi, iMidasRedemptionVaultGatewayV310Abi, iPendleRouterAbi, iPendleRouterAdapterAbi, iSecuritizeOnRampAbi, iSecuritizeOnRampAdapterV310Abi, iSecuritizeRedemptionGatewayAdapterV311Abi, iSecuritizeRedemptionGatewayV311Abi, iStakingRewardsAbi, iStakingRewardsAdapterAbi, iTraderJoeRouterAbi, iTraderJoeRouterAdapterAbi, iUniswapV2AdapterAbi, iUniswapV2Router02Abi, iUniswapV3Abi, iUniswapV3AdapterAbi, iUniswapV4AdapterAbi, iUniswapV4GatewayAbi, iUpshiftVaultAdapterAbi, iUpshiftVaultGatewayAbi, iVelodromeV2RouterAbi, iVelodromeV2RouterAdapterAbi, isCloseOrRepay, isDust, isLPPriceFeed, isPhantomToken, isPoolOperation, isPublicNetwork, isRWAFactory, isRWAOperation, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, makeReplayState, mellowDvvAdapterAbi, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parsePosNegAmount, parseRWAFactoryOperationCalldata, percentFmt, pickStrategyTargetCollateral, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, raise, rayToBps, rayToNumber, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent, resolveProtocolCall, retry, rewardsFromTransfers, roundUpQuota, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, soleNonUnderlyingCollateral, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, usdToNumber, watchBlocksAsync };
302
+ export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AccountMigratorAdapterContract, AdapterType, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, CamelotV3AdapterContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountState, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DEGEN_NFT_MIDAS, DEGEN_NFT_SECURITIZE, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, EXECUTE_BYTES_SELECTOR, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LidoV1AdapterContract, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_INT96, MIN_SAFE_HEALTH_FACTOR_FORM, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasDegenNFT, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NON_STRATEGY_PHANTOM_TOKEN_TYPES, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PeripheryCompressorV310Contract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeDegenNFT, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UpshiftVaultAdapterContract, VERSION_RANGE_310, VelodromeV2RouterAdapterContract, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, amountOf, assetsMap, attachOptionsSchema, botPermissionsToString, bpsToRay, buildDelayedStrategyPositionOperationPreview, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkAccountQuotas, checkBorrowLimit, checkCollateralFunding, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkCreditOperation, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkHealthFactors, checkIncreaseDebt, checkIncreaseQuota, checkLeverage, checkLiquidation, checkLiquidationEligibility, checkLiquidationFunding, checkLiquidatorEligible, checkMarket, checkMarketExpired, checkObtained, checkOperation, checkPoolFunding, checkPoolLiquidity, checkPoolOperation, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkRWAOpenRequirements, checkRWAOpening, checkReservePriceLimited, checkSimulation, checkWallet, checkWalletAllowance, checkWalletBalance, childLogger, classifyCloseOrRepay, classifyCurveOperation, classifyInnerOperations, collateralPriceInUnderlying, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectDelayedClaim, detectDelayedOperation, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateClaimableAt, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, fetchRedstonePayloads, filterDust, filterDustUSD, findCallTo, findCallWithInput, findCuratorMarketConfigurator, findExecuteBytes, fmtBinaryMask, fnSigToName, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAccountTargetCollateral, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getLegacyStrategyTarget, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, hasAdapterDeployParamsAbi, healthFactorBps, hexEq, hydrateAddressProvider, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, iCreditAccountAbi, iCurvePoolAbi, iCurvePoolStableNGAbi, iCurvePool_2Abi, iCurvePool_3Abi, iCurvePool_4Abi, iCurveV1StableNgAdapterAbi, iCurveV1_2AssetsAdapterAbi, iCurveV1_3AssetsAdapterAbi, iCurveV1_4AssetsAdapterAbi, iDaiUsdsAbi, iDaiUsdsAdapterAbi, iERC4626Abi, iERC4626ReferralAbi, iFluidDexAbi, iFluidDexAdapterAbi, iInfinifiGatewayAbi, iInfinifiGatewayAdapterAbi, iInfinifiUnwindingGatewayAbi, iInfinifiUnwindingGatewayAdapterAbi, iKelpLRTDepositPoolGatewayAbi, iKelpLRTWithdrawalManagerGatewayAbi, iKelpLrtDepositPoolAdapterAbi, iKelpLrtDepositPoolGatewayAbi, iKelpLrtWithdrawalManagerAdapterAbi, iKelpLrtWithdrawalManagerGatewayAbi, iLidoV1AdapterAbi, iMellow4626VaultAdapterAbi, iMellowClaimerAbi, iMellowClaimerAdapterAbi, iMellowWrapperAbi, iMellowWrapperAdapterAbi, iMidasGatewayAdapterV311Abi, iMidasGatewayV311Abi, iMidasIssuanceVaultAdapterV310Abi, iMidasIssuanceVaultV310Abi, iMidasRedemptionVaultAdapterV310Abi, iMidasRedemptionVaultGatewayV310Abi, iPendleRouterAbi, iPendleRouterAdapterAbi, iSecuritizeOnRampAbi, iSecuritizeOnRampAdapterV310Abi, iSecuritizeRedemptionGatewayAdapterV311Abi, iSecuritizeRedemptionGatewayV311Abi, iStakingRewardsAbi, iStakingRewardsAdapterAbi, iTraderJoeRouterAbi, iTraderJoeRouterAdapterAbi, iUniswapV2AdapterAbi, iUniswapV2Router02Abi, iUniswapV3Abi, iUniswapV3AdapterAbi, iUniswapV4AdapterAbi, iUniswapV4GatewayAbi, iUpshiftVaultAdapterAbi, iUpshiftVaultGatewayAbi, iVelodromeV2RouterAbi, iVelodromeV2RouterAdapterAbi, isCloseOrRepay, isDust, isLPPriceFeed, isPhantomToken, isPoolOperation, isPublicNetwork, isRWAFactory, isRWAOperation, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, makeReplayState, mellowDvvAdapterAbi, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parsePosNegAmount, parseRWAFactoryOperationCalldata, percentFmt, pickStrategyTargetCollateral, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, raise, rayToBps, rayToNumber, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent, resolveProtocolCall, retry, rewardsFromTransfers, roundUpQuota, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, soleNonUnderlyingCollateral, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, usdToNumber, watchBlocksAsync };
@@ -19,7 +19,7 @@ const adapterConstructorAbi = {
19
19
  ["INFINIFI_GATEWAY"]: { 310: BASIC_ADAPTER_ABI },
20
20
  ["LIDO_V1"]: { 310: BASIC_ADAPTER_ABI },
21
21
  ["LIDO_WSTETH_V1"]: { 310: BASIC_ADAPTER_ABI },
22
- ["MIDAS_GATEWAY"]: { 311: REFERER_ID_ADAPTER_ABI },
22
+ ["MIDAS_GATEWAY"]: { 311: BASIC_ADAPTER_ABI },
23
23
  ["MIDAS_REDEMPTION_VAULT"]: {
24
24
  310: BASIC_ADAPTER_ABI,
25
25
  311: BASIC_ADAPTER_ABI
@@ -1,26 +1,23 @@
1
1
  import { AP_WETH_TOKEN } from "../../constants/address-provider.js";
2
2
  import { asEstimated } from "../../../model/previews.js";
3
- import { sdkErr, sdkOk } from "../../../model/result.js";
3
+ import { sdkOk } from "../../../model/result.js";
4
4
  import "../../../model/index.js";
5
- import { CreditAccountState } from "./CreditAccountState.js";
6
5
  import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
7
- import { makeReplayState, replayInnerOperations } from "./replayInnerOperations.js";
8
6
  //#region src/onchain/preview/preview/previewOpenStrategyPosition.ts
9
- function previewOpenStrategyPosition(sdk, input, operation) {
7
+ function previewOpenStrategyPosition(sdk, input, operation, replay) {
10
8
  const { value = 0n } = input;
11
9
  const market = sdk.marketRegister.findByCreditManager(operation.creditManager);
12
10
  const oracle = market.priceOracle;
13
- const state = makeReplayState(CreditAccountState.beforeOpen(operation.creditManager, market.underlying));
14
- const replayError = replayInnerOperations(sdk, operation.multicall, state);
15
- if (replayError) return sdkErr(replayError);
16
- const account = state.account;
11
+ const { before, after } = replay;
12
+ const account = after.account;
17
13
  let warning;
18
- const netValue = state.collateralAdded.sum((token, balance) => {
14
+ const price = (token, balance) => {
19
15
  const priced = oracle.safeConvert(token, market.underlying, balance);
20
16
  warning ??= priced.error;
21
17
  return priced.value;
22
- });
23
- const unwrapped = unwrapNativeCollateral(state.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
18
+ };
19
+ const netValue = before.balances.sum(price) + after.collateralAdded.sum(price);
20
+ const unwrapped = unwrapNativeCollateral(after.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
24
21
  if (!unwrapped.ok) return unwrapped;
25
22
  const collateral = unwrapped.data;
26
23
  const snap = account.toSnapshot(netValue + account.totalDebt);
@@ -31,14 +28,11 @@ function previewOpenStrategyPosition(sdk, input, operation) {
31
28
  collateralAdded: collateral.map((a) => oracle.toTokenAmount(a.token, a.balance)),
32
29
  warning
33
30
  };
34
- if (operation.operation === "RWAOpenCreditAccount") return sdkOk({
35
- ...projection,
36
- operation: "RWAOpenCreditAccount",
37
- rwaArgs: operation.args
38
- });
39
31
  return sdkOk({
40
32
  ...projection,
41
- operation: "OpenCreditAccount"
33
+ operation: "OpenCreditAccount",
34
+ ...operation.operation === "MultiCall" || operation.operation === "BotMulticall" || operation.operation === "RWAMulticall" ? { creditAccount: operation.creditAccount } : {},
35
+ ..."args" in operation ? { rwaArgs: operation.args } : {}
42
36
  });
43
37
  }
44
38
  /**
@@ -33,9 +33,13 @@ async function previewOperation(sdk, input, options, creditAccount) {
33
33
  if (!parsed.ok) return parsed;
34
34
  const operation = parsed.data;
35
35
  if (isPoolOperation(operation)) return previewPoolPositionOperation(sdk, operation, options);
36
- if (operation.operation === "OpenCreditAccount" || operation.operation === "RWAOpenCreditAccount") return previewOpenStrategyPosition(sdk, input, operation);
36
+ if (operation.operation === "OpenCreditAccount" || operation.operation === "RWAOpenCreditAccount") {
37
+ const replayed = replayMulticall(sdk, operation);
38
+ if (!replayed.ok) return replayed;
39
+ return previewOpenStrategyPosition(sdk, input, operation, replayed.data);
40
+ }
37
41
  if (operation.operation === "CloseCreditAccount") {
38
- const resolved = await resolveCreditAccount(sdk, operation, options, creditAccount);
42
+ const resolved = await resolveCreditAccount(sdk, operation.creditAccount, options, creditAccount);
39
43
  if (!resolved.ok) return resolved;
40
44
  const replayed = replayMulticall(sdk, operation, resolved.data);
41
45
  if (!replayed.ok) return replayed;
@@ -47,7 +51,7 @@ async function previewOperation(sdk, input, options, creditAccount) {
47
51
  return preview;
48
52
  }
49
53
  if (operation.operation === "MultiCall" || operation.operation === "BotMulticall" || operation.operation === "RWAMulticall") {
50
- const resolved = await resolveCreditAccount(sdk, operation, options, creditAccount);
54
+ const resolved = await resolveCreditAccount(sdk, operation.creditAccount, options, creditAccount);
51
55
  if (!resolved.ok) return resolved;
52
56
  const replayed = replayMulticall(sdk, operation, resolved.data);
53
57
  if (!replayed.ok) return replayed;
@@ -64,20 +68,24 @@ async function previewOperation(sdk, input, options, creditAccount) {
64
68
  * injected state when present, otherwise fetches it from the credit account
65
69
  * compressor.
66
70
  */
67
- async function resolveCreditAccount(sdk, operation, options, creditAccount) {
68
- let resolved = creditAccount;
69
- if (!resolved) resolved = await sdk.accounts.getCreditAccountData(operation.creditAccount, options?.blockNumber);
70
- if (!resolved) return sdkErr(creditAccountNotFound(operation.creditAccount));
71
+ async function resolveCreditAccount(sdk, address, options, data) {
72
+ let resolved = data;
73
+ if (!resolved) resolved = await sdk.accounts.getCreditAccountData(address, options?.blockNumber);
74
+ if (!resolved) return sdkErr(creditAccountNotFound(address));
71
75
  return sdkOk(resolved);
72
76
  }
73
77
  /**
74
78
  * Previews a plain/bot/RWA multicall: classifies the instant preview
75
- * (zero-debt closure/repay vs adjustment) and, when the multicall requests a
76
- * delayed withdrawal, wraps the instant preview into a
77
- * `DelayedCreditAccountOperation` together with the best-effort preview of
78
- * the state after the withdrawal is claimed.
79
+ * (reopening a zero-debt account, zero-debt closure/repay, or adjustment)
80
+ * and, when the multicall requests a delayed withdrawal, wraps the instant
81
+ * preview into a `DelayedCreditAccountOperation` together with the
82
+ * best-effort preview of the state after the withdrawal is claimed.
83
+ *
84
+ * A reopening is reported as `OpenCreditAccount` and never as a delayed
85
+ * withdrawal: an opening requests no redemption.
79
86
  */
80
87
  async function previewMulticallOperation(sdk, input, operation, replay, blockNumber) {
88
+ if (replay.before.totalDebt === 0n && replay.before.quotas.toAssets(0n).length === 0 && replay.after.account.totalDebt > 0n) return previewOpenStrategyPosition(sdk, input, operation, replay);
81
89
  let instantPreview;
82
90
  if (isCloseOrRepay(operation.multicall)) {
83
91
  const instant = previewExitOrRepayStrategyPosition(sdk, input, operation, false, replay);
@@ -4,11 +4,12 @@ import { CreditAccountState } from "./CreditAccountState.js";
4
4
  import { makeReplayState, replayInnerOperations } from "./replayInnerOperations.js";
5
5
  //#region src/onchain/preview/preview/replayMulticall.ts
6
6
  /**
7
- * Replays the operation's multicall over the account's pre-resolved
8
- * pre-state via {@link replayInnerOperations}.
7
+ * Replays the operation's multicall via {@link replayInnerOperations}.
8
+ * When `creditAccount` is omitted, the seed is
9
+ * {@link CreditAccountState.beforeOpen} (a fresh opening).
9
10
  */
10
11
  function replayMulticall(sdk, operation, creditAccount) {
11
- const before = CreditAccountState.fromCreditAccountData(creditAccount);
12
+ const before = creditAccount ? CreditAccountState.fromCreditAccountData(creditAccount) : CreditAccountState.beforeOpen(operation.creditManager, sdk.marketRegister.findByCreditManager(operation.creditManager).underlying);
12
13
  const after = makeReplayState(before.clone());
13
14
  const error = replayInnerOperations(sdk, operation.multicall, after);
14
15
  if (error) return sdkErr(error);
@@ -22,13 +22,13 @@ async function checkCollateralFunding(input) {
22
22
  if (held.size === 0) return [];
23
23
  let spender;
24
24
  try {
25
- if (preview.operation === "OpenCreditAccount" || preview.operation === "RWAOpenCreditAccount") spender = await sdk.accounts.getApprovalAddress({
25
+ if (preview.creditAccount) spender = await sdk.accounts.getApprovalAddress({
26
26
  creditManager: preview.creditManager,
27
- borrower: sender
27
+ creditAccount: preview.creditAccount
28
28
  });
29
29
  else spender = await sdk.accounts.getApprovalAddress({
30
30
  creditManager: preview.creditManager,
31
- creditAccount: preview.creditAccount
31
+ borrower: sender
32
32
  });
33
33
  } catch (cause) {
34
34
  return [unexpectedFailure(cause, "resolve the approval address")];
@@ -25,7 +25,7 @@ async function checkCreditOperation(args) {
25
25
  const suite = sdk.marketRegister.findCreditManager(preview.creditManager);
26
26
  const market = suite.market;
27
27
  const underlying = toToken(sdk, market.pool.underlying);
28
- const isOpening = preview.operation === "OpenCreditAccount" || preview.operation === "RWAOpenCreditAccount";
28
+ const isOpening = preview.operation === "OpenCreditAccount";
29
29
  const protocol = [
30
30
  ...checkMarket(suite),
31
31
  ...checkDebtLimits({
@@ -51,7 +51,7 @@ async function checkCreditOperation(args) {
51
51
  preview,
52
52
  sender,
53
53
  blockNumber
54
- }), preview.operation === "OpenCreditAccount" || preview.operation === "RWAOpenCreditAccount" ? checkRWAOpening({
54
+ }), isOpening ? checkRWAOpening({
55
55
  sdk,
56
56
  preview,
57
57
  sender
@@ -11,13 +11,12 @@ async function checkRWAOpening(input) {
11
11
  if (!nft) return [];
12
12
  const gated = new AddressSet(await nft.getTokens());
13
13
  const candidates = new AddressSet([...preview.collateralAdded.map((a) => a.token.address), ...preview.quotas.map((q) => q.token.address)]);
14
- const providedArgs = preview.operation === "RWAOpenCreditAccount" ? preview.rwaArgs : void 0;
15
14
  return (await Promise.all([...candidates].filter((token) => gated.has(token)).map((token) => checkRWAOpenRequirements({
16
15
  sdk,
17
16
  wallet: sender,
18
17
  creditManager: preview.creditManager,
19
18
  token,
20
- providedArgs
19
+ providedArgs: preview.rwaArgs
21
20
  })))).flat();
22
21
  }
23
22
  //#endregion
@@ -42,7 +42,6 @@ async function checkOperation(input, options = {}) {
42
42
  sender
43
43
  }, options);
44
44
  case "OpenCreditAccount":
45
- case "RWAOpenCreditAccount":
46
45
  case "AdjustCreditAccount": return checkCreditOperation({
47
46
  sdk,
48
47
  preview,
@@ -0,0 +1,29 @@
1
+ import { reservePriceLimited } from "../../../model/errors/operation-errors.js";
2
+ import "../../../model/index.js";
3
+ //#region src/onchain/validation/checks/checkReservePriceLimited.ts
4
+ /**
5
+ * Whether a failed collateral check is the reserve price feed's doing.
6
+ *
7
+ * A call that hands funds over is weighed at safe prices — `min` of a token's
8
+ * two feeds, and nothing at all where governance registered no reserve feed —
9
+ * so an account that covers its debt at the main feed can still be refused.
10
+ * The two are worth telling apart: a position that is genuinely too small is
11
+ * fixed by adding collateral or requesting less, while this one is a valuation
12
+ * the account does not control, and requesting less only helps as far as
13
+ * `withdrawable` says it does.
14
+ *
15
+ * Runs after `checkCollateralised` and answers only when that one refused, so
16
+ * the caller keeps its own threshold rather than restating it here.
17
+ */
18
+ function checkReservePriceLimited(args) {
19
+ const { healthFactor, atMainPrices, healthFactorThreshold, withdrawable } = args;
20
+ if (healthFactor >= healthFactorThreshold || atMainPrices < healthFactorThreshold) return [];
21
+ return [reservePriceLimited({
22
+ healthFactor,
23
+ atMainPrices,
24
+ healthFactorThreshold,
25
+ withdrawable
26
+ })];
27
+ }
28
+ //#endregion
29
+ export { checkReservePriceLimited };
@@ -13,4 +13,5 @@ import { checkPoolPaused } from "./checkPoolPaused.js";
13
13
  import { checkPoolSunset } from "./checkPoolSunset.js";
14
14
  import { checkQuotaCount } from "./checkQuotaCount.js";
15
15
  import { checkQuotaLimit } from "./checkQuotaLimit.js";
16
- export { checkBorrowLimit, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkLeverage, checkLiquidatorEligible, checkMarketExpired, checkPoolLiquidity, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit };
16
+ import { checkReservePriceLimited } from "./checkReservePriceLimited.js";
17
+ export { checkBorrowLimit, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkLeverage, checkLiquidatorEligible, checkMarketExpired, checkPoolLiquidity, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkReservePriceLimited };
@@ -17,6 +17,7 @@ import { checkPoolPaused } from "./checks/checkPoolPaused.js";
17
17
  import { checkPoolSunset } from "./checks/checkPoolSunset.js";
18
18
  import { checkQuotaCount } from "./checks/checkQuotaCount.js";
19
19
  import { checkQuotaLimit } from "./checks/checkQuotaLimit.js";
20
+ import { checkReservePriceLimited } from "./checks/checkReservePriceLimited.js";
20
21
  import "./checks/index.js";
21
22
  import { checkAccountQuotas } from "./bundles/checkAccountQuotas.js";
22
23
  import { checkWalletAllowance } from "./bundles/checkWalletAllowance.js";
@@ -40,4 +41,4 @@ import { checkLiquidation } from "./checkLiquidation.js";
40
41
  import { checkOperation } from "./checkOperation.js";
41
42
  import { checkSimulation } from "./checkSimulation.js";
42
43
  import { raise } from "./raise.js";
43
- export { MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_SAFE_HEALTH_FACTOR_FORM, amountOf, checkAccountQuotas, checkBorrowLimit, checkCollateralFunding, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkCreditOperation, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkHealthFactors, checkIncreaseDebt, checkIncreaseQuota, checkLeverage, checkLiquidation, checkLiquidationEligibility, checkLiquidationFunding, checkLiquidatorEligible, checkMarket, checkMarketExpired, checkObtained, checkOperation, checkPoolFunding, checkPoolLiquidity, checkPoolOperation, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkRWAOpenRequirements, checkRWAOpening, checkSimulation, checkWallet, checkWalletAllowance, checkWalletBalance, raise, toToken, toTokenAmount };
44
+ export { MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_SAFE_HEALTH_FACTOR_FORM, amountOf, checkAccountQuotas, checkBorrowLimit, checkCollateralFunding, checkCollateralised, checkCreditAccountFrozen, checkCreditManagerPaused, checkCreditOperation, checkDebtLimits, checkEmergencyLiquidator, checkForbiddenToken, checkHealthFactors, checkIncreaseDebt, checkIncreaseQuota, checkLeverage, checkLiquidation, checkLiquidationEligibility, checkLiquidationFunding, checkLiquidatorEligible, checkMarket, checkMarketExpired, checkObtained, checkOperation, checkPoolFunding, checkPoolLiquidity, checkPoolOperation, checkPoolPaused, checkPoolSunset, checkQuotaCount, checkQuotaLimit, checkRWAOpenRequirements, checkRWAOpening, checkReservePriceLimited, checkSimulation, checkWallet, checkWalletAllowance, checkWalletBalance, raise, toToken, toTokenAmount };
@@ -258,12 +258,13 @@ var PrepareApi = class extends MultichainConstruct {
258
258
  /**
259
259
  * {@inheritDoc IOpportunitiesPrepare.maxWithdraw}
260
260
  **/
261
- async maxWithdraw(position) {
261
+ async maxWithdraw(position, sourceToken) {
262
262
  const sdk = await this.#chain(position.chainId);
263
263
  const creditAccount = await this.#account(sdk, position);
264
264
  return service(sdk).maxWithdraw({
265
265
  creditAccount,
266
- sdk
266
+ sdk,
267
+ sourceToken
267
268
  });
268
269
  }
269
270
  /**
@@ -22,10 +22,9 @@ interface UnpauseMidasIssuanceVaultProps {
22
22
  */
23
23
  type RestoreMidasIssuanceVaultPause = () => Promise<void>;
24
24
  /**
25
- * Unpauses a Midas issuance vault on an anvil fork so that `depositInstant`
26
- * stops reverting with `Pausable: paused` (global) or `Pausable: fn paused`
27
- * (per-selector), and returns a callback that restores the original pause
28
- * state of each layer that was cleared.
25
+ * Unpauses a globally paused Midas issuance vault on an anvil fork, so that
26
+ * `depositInstant` stops reverting with `Pausable: paused`, and returns a
27
+ * callback that restores the original pause state.
29
28
  *
30
29
  * Impersonates `admin` and grants it `pauseAdminRole()` when missing, same as
31
30
  * `greenlistMidasGateway` does with the greenlist roles. The grant is not
@@ -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 { BorrowLimitCause, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, LeverageOutOfRangeError, MarketExpiredError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, ReservePriceLimitedError, 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 { 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, 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
  **/
@@ -219,4 +259,4 @@ interface RWAOpenRequirementsError extends IGearboxError {
219
259
  /** {@inheritDoc RWAOpenRequirementsError} */
220
260
  declare function rwaOpenRequirementsNotMet(args: Omit<RWAOpenRequirementsError, "code" | "message">): RWAOpenRequirementsError;
221
261
  //#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 };
262
+ export { BorrowLimitCause, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, LeverageOutOfRangeError, MarketExpiredError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, ReservePriceLimitedError, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet };