@morpho-org/morpho-sdk 9.6.0-next.0 → 9.6.0

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 (136) hide show
  1. package/README.md +59 -0
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +1 -5
  4. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -2
  5. package/lib/cjs/actions/bundles/common.js +39 -32
  6. package/lib/cjs/actions/midnight/cancelAndMake.js +20 -98
  7. package/lib/cjs/actions/midnight/index.d.ts +2 -0
  8. package/lib/cjs/actions/midnight/index.js +2 -0
  9. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +5 -6
  10. package/lib/cjs/actions/midnight/supplyCollateralBatch.d.ts +39 -0
  11. package/lib/cjs/actions/midnight/supplyCollateralBatch.js +91 -0
  12. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +31 -32
  13. package/lib/cjs/actions/midnight/takeBorrow.js +24 -23
  14. package/lib/cjs/actions/midnight/takeLend.js +24 -23
  15. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +20 -19
  16. package/lib/cjs/actions/midnight/takeWithdraw.js +24 -23
  17. package/lib/cjs/actions/midnight/withdrawCollateralBatch.d.ts +44 -0
  18. package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +104 -0
  19. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -0
  20. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -0
  21. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +1 -0
  22. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +1 -0
  23. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +1 -0
  24. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  25. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -0
  26. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +1 -0
  27. package/lib/cjs/actions/vaultV1/migrateToV2.js +7 -7
  28. package/lib/cjs/blue/abis.d.ts +1 -1
  29. package/lib/cjs/blue/abis.js +1 -5
  30. package/lib/cjs/blue/entities.d.ts +4 -4
  31. package/lib/cjs/blue/entities.js +1 -3
  32. package/lib/cjs/blue/errors.d.ts +2 -2
  33. package/lib/cjs/blue/errors.js +1 -5
  34. package/lib/cjs/blue/fetch.d.ts +2 -2
  35. package/lib/cjs/blue/fetch.js +1 -3
  36. package/lib/cjs/blue/utils.d.ts +1 -1
  37. package/lib/cjs/blue/utils.js +1 -2
  38. package/lib/cjs/entities/index.d.ts +5 -5
  39. package/lib/cjs/entities/index.js +1 -3
  40. package/lib/cjs/entities/midnight/midnight.d.ts +77 -3
  41. package/lib/cjs/entities/midnight/midnight.js +174 -0
  42. package/lib/cjs/entities/midnight/types.d.ts +16 -0
  43. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +8 -33
  44. package/lib/cjs/entities/vaultV2/vaultV2.js +1 -33
  45. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +3 -5
  46. package/lib/cjs/entities/vaultV2BlueReallocationData.js +3 -9
  47. package/lib/cjs/errors.d.ts +4 -4
  48. package/lib/cjs/errors.js +6 -7
  49. package/lib/cjs/fetch.d.ts +2 -2
  50. package/lib/cjs/fetch.js +1 -3
  51. package/lib/cjs/helpers/deadShares.js +0 -2
  52. package/lib/cjs/helpers/signAndVerifyTypedData.d.ts +1 -0
  53. package/lib/cjs/helpers/signAndVerifyTypedData.js +12 -5
  54. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.d.ts +68 -0
  55. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.js +129 -0
  56. package/lib/cjs/helpers/validateMidnightCollateralBatch.d.ts +14 -0
  57. package/lib/cjs/helpers/validateMidnightCollateralBatch.js +27 -0
  58. package/lib/cjs/helpers/validateMidnightCollateralSupplies.d.ts +17 -0
  59. package/lib/cjs/helpers/validateMidnightCollateralSupplies.js +28 -0
  60. package/lib/cjs/helpers/validatePositiveInput.d.ts +10 -0
  61. package/lib/cjs/helpers/validatePositiveInput.js +18 -0
  62. package/lib/cjs/midnight/errors.d.ts +1 -2
  63. package/lib/cjs/midnight/errors.js +5 -5
  64. package/lib/cjs/types/action.d.ts +18 -3
  65. package/lib/cjs/types/error.d.ts +23 -2
  66. package/lib/cjs/types/error.js +45 -5
  67. package/lib/cjs/utils.d.ts +2 -2
  68. package/lib/cjs/utils.js +2 -4
  69. package/lib/esm/abis.d.ts +1 -1
  70. package/lib/esm/abis.js +1 -1
  71. package/lib/esm/actions/blue/repayWithdrawCollateral.js +2 -2
  72. package/lib/esm/actions/bundles/common.js +39 -32
  73. package/lib/esm/actions/midnight/cancelAndMake.js +25 -103
  74. package/lib/esm/actions/midnight/index.d.ts +2 -0
  75. package/lib/esm/actions/midnight/index.js +2 -0
  76. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +5 -6
  77. package/lib/esm/actions/midnight/supplyCollateralBatch.d.ts +39 -0
  78. package/lib/esm/actions/midnight/supplyCollateralBatch.js +87 -0
  79. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +33 -34
  80. package/lib/esm/actions/midnight/takeBorrow.js +25 -24
  81. package/lib/esm/actions/midnight/takeLend.js +25 -24
  82. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +20 -19
  83. package/lib/esm/actions/midnight/takeWithdraw.js +25 -24
  84. package/lib/esm/actions/midnight/withdrawCollateralBatch.d.ts +44 -0
  85. package/lib/esm/actions/midnight/withdrawCollateralBatch.js +100 -0
  86. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -0
  87. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -0
  88. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +1 -0
  89. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +1 -0
  90. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +1 -0
  91. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  92. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -0
  93. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +1 -0
  94. package/lib/esm/actions/vaultV1/migrateToV2.js +8 -8
  95. package/lib/esm/blue/abis.d.ts +1 -1
  96. package/lib/esm/blue/abis.js +1 -1
  97. package/lib/esm/blue/entities.d.ts +4 -4
  98. package/lib/esm/blue/entities.js +2 -2
  99. package/lib/esm/blue/errors.d.ts +2 -2
  100. package/lib/esm/blue/errors.js +2 -2
  101. package/lib/esm/blue/fetch.d.ts +2 -2
  102. package/lib/esm/blue/fetch.js +2 -2
  103. package/lib/esm/blue/utils.d.ts +1 -1
  104. package/lib/esm/blue/utils.js +1 -1
  105. package/lib/esm/entities/index.d.ts +5 -5
  106. package/lib/esm/entities/index.js +2 -2
  107. package/lib/esm/entities/midnight/midnight.d.ts +77 -3
  108. package/lib/esm/entities/midnight/midnight.js +176 -2
  109. package/lib/esm/entities/midnight/types.d.ts +16 -0
  110. package/lib/esm/entities/vaultV2/vaultV2.d.ts +8 -33
  111. package/lib/esm/entities/vaultV2/vaultV2.js +1 -33
  112. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +3 -5
  113. package/lib/esm/entities/vaultV2BlueReallocationData.js +3 -9
  114. package/lib/esm/errors.d.ts +4 -4
  115. package/lib/esm/errors.js +4 -4
  116. package/lib/esm/fetch.d.ts +2 -2
  117. package/lib/esm/fetch.js +2 -2
  118. package/lib/esm/helpers/deadShares.js +1 -3
  119. package/lib/esm/helpers/signAndVerifyTypedData.d.ts +1 -0
  120. package/lib/esm/helpers/signAndVerifyTypedData.js +13 -6
  121. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.d.ts +68 -0
  122. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.js +124 -0
  123. package/lib/esm/helpers/validateMidnightCollateralBatch.d.ts +14 -0
  124. package/lib/esm/helpers/validateMidnightCollateralBatch.js +24 -0
  125. package/lib/esm/helpers/validateMidnightCollateralSupplies.d.ts +17 -0
  126. package/lib/esm/helpers/validateMidnightCollateralSupplies.js +24 -0
  127. package/lib/esm/helpers/validatePositiveInput.d.ts +10 -0
  128. package/lib/esm/helpers/validatePositiveInput.js +14 -0
  129. package/lib/esm/midnight/errors.d.ts +1 -2
  130. package/lib/esm/midnight/errors.js +1 -2
  131. package/lib/esm/types/action.d.ts +18 -3
  132. package/lib/esm/types/error.d.ts +23 -2
  133. package/lib/esm/types/error.js +40 -3
  134. package/lib/esm/utils.d.ts +2 -2
  135. package/lib/esm/utils.js +2 -2
  136. package/package.json +6 -6
@@ -1,8 +1,8 @@
1
1
  import { type AccrualPosition, type Market, type MidnightFetchParams } from "@morpho-org/midnight-sdk";
2
2
  import { type Address, type Hex } from "viem";
3
3
  import type { MorphoClientType } from "../../types/client.js";
4
- import { type MidnightCancelAndMakeAction, type MidnightGroupCancellation, type MidnightRedeemAction, type MidnightRepayWithdrawCollateralAction, type MidnightSupplyCollateralAction, type MidnightSupplyCollateralTakeBorrowAction, type MidnightTakeBorrowAction, type MidnightTakeLendAction, type MidnightTakeRepayWithdrawCollateralAction, type MidnightTakeWithdrawAction, type MidnightWithdrawCollateralAction } from "../../types/index.js";
5
- import type { GetOffersDataParams, GetPositionDataParams, MakeLendParams, MakeOffersOutput, MakeOffersParams, MidnightActionOutput, OffersData, RedeemParams, RepayWithdrawCollateralParams, SupplyBlueMakeLendParams, SupplyCollateralMakeBorrowParams, SupplyCollateralParams, SupplyCollateralTakeBorrowParams, TakeBorrowParams, TakeLendParams, TakeRepayWithdrawCollateralParams, TakeWithdrawParams, WithdrawCollateralParams } from "./types.js";
4
+ import { type MidnightCancelAndMakeAction, type MidnightGroupCancellation, type MidnightRedeemAction, type MidnightRepayWithdrawCollateralAction, type MidnightSupplyCollateralAction, type MidnightSupplyCollateralBatchAction, type MidnightSupplyCollateralTakeBorrowAction, type MidnightTakeBorrowAction, type MidnightTakeLendAction, type MidnightTakeRepayWithdrawCollateralAction, type MidnightTakeWithdrawAction, type MidnightWithdrawCollateralAction, type MidnightWithdrawCollateralBatchAction } from "../../types/index.js";
5
+ import type { GetOffersDataParams, GetPositionDataParams, MakeLendParams, MakeOffersOutput, MakeOffersParams, MidnightActionOutput, OffersData, RedeemParams, RepayWithdrawCollateralParams, SupplyBlueMakeLendParams, SupplyCollateralBatchParams, SupplyCollateralMakeBorrowParams, SupplyCollateralParams, SupplyCollateralTakeBorrowParams, TakeBorrowParams, TakeLendParams, TakeRepayWithdrawCollateralParams, TakeWithdrawParams, WithdrawCollateralBatchParams, WithdrawCollateralParams } from "./types.js";
6
6
  /**
7
7
  * Entity methods exposed by `client.morpho.midnight(chainId)`.
8
8
  *
@@ -30,7 +30,7 @@ import type { GetOffersDataParams, GetPositionDataParams, MakeLendParams, MakeOf
30
30
  * const tx = output.buildTx();
31
31
  * ```
32
32
  */
33
- export type MidnightActions = Pick<MorphoMidnight, "getMarketData" | "getPositionData" | "getOffersData" | "takeLend" | "takeBorrow" | "takeWithdraw" | "supplyCollateralTakeBorrow" | "takeRepayWithdrawCollateral" | "supplyCollateral" | "withdrawCollateral" | "makeLend" | "makeBorrow" | "supplyBlueMakeLend" | "makeWithdraw" | "makeRepay" | "supplyCollateralMakeBorrow" | "redeem" | "repayWithdrawCollateral" | "cancelOffers">;
33
+ export type MidnightActions = Pick<MorphoMidnight, "getMarketData" | "getPositionData" | "getOffersData" | "takeLend" | "takeBorrow" | "takeWithdraw" | "supplyCollateralTakeBorrow" | "takeRepayWithdrawCollateral" | "supplyCollateral" | "supplyCollateralBatch" | "withdrawCollateral" | "withdrawCollateralBatch" | "makeLend" | "makeBorrow" | "supplyBlueMakeLend" | "makeWithdraw" | "makeRepay" | "supplyCollateralMakeBorrow" | "redeem" | "repayWithdrawCollateral" | "cancelOffers">;
34
34
  /**
35
35
  * Entity facade for Midnight fixed-rate action flows.
36
36
  *
@@ -637,6 +637,52 @@ export declare class MorphoMidnight {
637
637
  * ```
638
638
  */
639
639
  withdrawCollateral(params: WithdrawCollateralParams): MidnightActionOutput<MidnightWithdrawCollateralAction>;
640
+ /**
641
+ * Withdraws an ordered collateral batch atomically from Midnight without bundle authorization or token pulls.
642
+ *
643
+ * Uses the supplied position snapshot to resolve maxUint256 and check collateral health.
644
+ * Duplicates are rejected, unlike bundle flows which sum them.
645
+ * No requirements or RPC reads are needed. The signing account must be accountAddress.
646
+ *
647
+ * @param params - Market, owner-bound position, collateral prices and withdrawal amount.
648
+ * @param params.accountAddress - Collateral owner. This account must send the transaction.
649
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
650
+ * @param params.positionData - Owner-bound position snapshot returned by getPositionData.
651
+ * @param params.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
652
+ * ORACLE_PRICE_SCALE; required when the position has debt, otherwise an empty array is safe.
653
+ * @param params.collateralWithdrawals - Nonempty ordered withdrawals, one per index.
654
+ * maxUint256 resolves that index's full snapshot balance.
655
+ * @param params.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
656
+ * @returns Lazy handles for a direct Midnight withdrawal.
657
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
658
+ * @throws {MidnightCalldataEncodingError} when accountAddress is malformed or an input cannot be ABI-encoded.
659
+ * @throws {MidnightZeroAccountError} when accountAddress is zero.
660
+ * @throws {MidnightMarketAddressMismatchError} when marketData targets another Midnight deployment.
661
+ * @throws {MissingMarketPriceError} when debt is positive and held collateral has no supplied price.
662
+ * @throws {MarketIdMismatchError} when positionData belongs to another market.
663
+ * @throws {AccrualPositionUserMismatchError} when positionData belongs to another account.
664
+ * @throws {UnknownCollateralIndexError} when collateralIndex is not configured.
665
+ * @throws {EmptyMidnightCollateralWithdrawalsError} when the list is empty.
666
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
667
+ * @throws {NonPositiveInputError} when the resolved amount is not positive.
668
+ * @throws {InputExceedsMaxError} when assets exceeds uint128.
669
+ * @throws {WithdrawExceedsCollateralError} when assets exceeds the collateral balance.
670
+ * @throws {WithdrawMakesPositionUnhealthyError} when remaining collateral cannot safely cover debt.
671
+ * @throws {MidnightZeroReceiverError} when receiver is zero.
672
+ * @throws {MidnightContractReceiverError} when receiver cannot safely receive collateral.
673
+ * @example
674
+ * ```ts
675
+ * const output = midnight.withdrawCollateralBatch({
676
+ * accountAddress: user,
677
+ * marketData,
678
+ * positionData,
679
+ * collateralPrices,
680
+ * collateralWithdrawals: [{ collateralIndex: 0n, assets: 1_000n }],
681
+ * });
682
+ * const tx = output.buildTx();
683
+ * ```
684
+ */
685
+ withdrawCollateralBatch(params: WithdrawCollateralBatchParams): MidnightActionOutput<MidnightWithdrawCollateralBatchAction>;
640
686
  /**
641
687
  * Prepares a direct collateral supply using a caller-provided market snapshot.
642
688
  *
@@ -675,6 +721,34 @@ export declare class MorphoMidnight {
675
721
  * ```
676
722
  */
677
723
  supplyCollateral(params: SupplyCollateralParams): MidnightActionOutput<MidnightSupplyCollateralAction>;
724
+ /**
725
+ * Prepares ordered direct collateral supplies in one Midnight multicall.
726
+ * Pass one entry per index: duplicates are rejected, unlike bundle flows which sum them.
727
+ *
728
+ * @param params.accountAddress - Sender and collateral beneficiary.
729
+ * @param params.marketData - Snapshot of the target market.
730
+ * @param params.collateralSupplies - Ordered supplies with optional reserved allowance amounts.
731
+ * @returns A lazy approval resolver and synchronous stateless transaction builder.
732
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
733
+ * @throws {MidnightMarketAddressMismatchError} when the deployment differs.
734
+ * @throws {MidnightCalldataEncodingError} when the account is malformed.
735
+ * @throws {NegativeInputError} when reserved assets are negative.
736
+ * @throws {NonPositiveInputError} when assets are not positive.
737
+ * @throws {InputExceedsMaxError} when assets exceed uint128.
738
+ * @throws {UnknownCollateralIndexError} when an index is not configured.
739
+ * @throws {EmptyMidnightCollateralSuppliesError} when the list is empty.
740
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
741
+ * @throws {MidnightZeroOnBehalfError} when requirements or construction uses the zero account.
742
+ * @example
743
+ * ```ts
744
+ * const output = midnight.supplyCollateralBatch({
745
+ * accountAddress: user, marketData,
746
+ * collateralSupplies: [{ collateralIndex: 0n, assets: 100n }],
747
+ * });
748
+ * const tx = output.buildTx();
749
+ * ```
750
+ */
751
+ supplyCollateralBatch(params: SupplyCollateralBatchParams): MidnightActionOutput<MidnightSupplyCollateralBatchAction>;
678
752
  /**
679
753
  * Prepares an atomic lend-offer publication or repost through `MidnightBundlesV2`.
680
754
  *
@@ -3,7 +3,7 @@ import { fetchMarket as fetchBlueMarket } from "@morpho-org/blue-sdk-viem";
3
3
  import { fetchAccrualPosition, fetchMarket, MarketParams, MarketUtils, Payload, PriceRatifierV1, RateRatifierV1, Tree, } from "@morpho-org/midnight-sdk";
4
4
  import { _try, getChainAddress, Time } from "@morpho-org/morpho-ts";
5
5
  import { isAddress, isAddressEqual, maxUint256, zeroAddress, } from "viem";
6
- import { midnightCancelAndMake, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, midnightTakeRepayWithdrawCollateral, midnightTakeWithdraw, midnightWithdrawCollateral, } from "../../actions/midnight/index.js";
6
+ import { midnightCancelAndMake, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralBatch, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, midnightTakeRepayWithdrawCollateral, midnightTakeWithdraw, midnightWithdrawCollateral, midnightWithdrawCollateralBatch, } from "../../actions/midnight/index.js";
7
7
  import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, } from "../../actions/requirements/index.js";
8
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
9
  import { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "../../helpers/callback.js";
@@ -12,11 +12,12 @@ import { encodeMidnightMarketId, wrapMidnightEncoding, } from "../../helpers/enc
12
12
  import { getMidnightMaxSafeDebt, validateChainId, } from "../../helpers/index.js";
13
13
  import { validateMidnightAccount, validateMidnightAddress, } from "../../helpers/validateMidnightAccount.js";
14
14
  import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
15
+ import { validateMidnightCollateralBatch } from "../../helpers/validateMidnightCollateralBatch.js";
15
16
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
16
17
  import { validateMidnightBytes32 } from "../../helpers/validateMidnightPublication.js";
17
18
  import { validateMidnightTakeFeasibility } from "../../helpers/validateMidnightTakeFeasibility.js";
18
19
  import { validateOfferSides } from "../../helpers/validateOfferSides.js";
19
- import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, EmptyBlueParkingMarketError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MidnightZeroOnBehalfError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
20
+ import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, EmptyBlueParkingMarketError, EmptyMidnightCollateralSuppliesError, EmptyMidnightCollateralWithdrawalsError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MidnightZeroOnBehalfError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
20
21
  import { validateMidnightDeadline } from "./deadline.js";
21
22
  import { fetchMidnightMakerOfferStates, offerMarketParams, validateMidnightMakerOfferCallbacks, validateMidnightMakerOfferStates, } from "./publication.js";
22
23
  const validatePositionBinding = (params) => {
@@ -1161,6 +1162,106 @@ export class MorphoMidnight {
1161
1162
  }
1162
1163
  return { getRequirements: async () => [], buildTx: () => tx };
1163
1164
  }
1165
+ /**
1166
+ * Withdraws an ordered collateral batch atomically from Midnight without bundle authorization or token pulls.
1167
+ *
1168
+ * Uses the supplied position snapshot to resolve maxUint256 and check collateral health.
1169
+ * Duplicates are rejected, unlike bundle flows which sum them.
1170
+ * No requirements or RPC reads are needed. The signing account must be accountAddress.
1171
+ *
1172
+ * @param params - Market, owner-bound position, collateral prices and withdrawal amount.
1173
+ * @param params.accountAddress - Collateral owner. This account must send the transaction.
1174
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
1175
+ * @param params.positionData - Owner-bound position snapshot returned by getPositionData.
1176
+ * @param params.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
1177
+ * ORACLE_PRICE_SCALE; required when the position has debt, otherwise an empty array is safe.
1178
+ * @param params.collateralWithdrawals - Nonempty ordered withdrawals, one per index.
1179
+ * maxUint256 resolves that index's full snapshot balance.
1180
+ * @param params.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
1181
+ * @returns Lazy handles for a direct Midnight withdrawal.
1182
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
1183
+ * @throws {MidnightCalldataEncodingError} when accountAddress is malformed or an input cannot be ABI-encoded.
1184
+ * @throws {MidnightZeroAccountError} when accountAddress is zero.
1185
+ * @throws {MidnightMarketAddressMismatchError} when marketData targets another Midnight deployment.
1186
+ * @throws {MissingMarketPriceError} when debt is positive and held collateral has no supplied price.
1187
+ * @throws {MarketIdMismatchError} when positionData belongs to another market.
1188
+ * @throws {AccrualPositionUserMismatchError} when positionData belongs to another account.
1189
+ * @throws {UnknownCollateralIndexError} when collateralIndex is not configured.
1190
+ * @throws {EmptyMidnightCollateralWithdrawalsError} when the list is empty.
1191
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
1192
+ * @throws {NonPositiveInputError} when the resolved amount is not positive.
1193
+ * @throws {InputExceedsMaxError} when assets exceeds uint128.
1194
+ * @throws {WithdrawExceedsCollateralError} when assets exceeds the collateral balance.
1195
+ * @throws {WithdrawMakesPositionUnhealthyError} when remaining collateral cannot safely cover debt.
1196
+ * @throws {MidnightZeroReceiverError} when receiver is zero.
1197
+ * @throws {MidnightContractReceiverError} when receiver cannot safely receive collateral.
1198
+ * @example
1199
+ * ```ts
1200
+ * const output = midnight.withdrawCollateralBatch({
1201
+ * accountAddress: user,
1202
+ * marketData,
1203
+ * positionData,
1204
+ * collateralPrices,
1205
+ * collateralWithdrawals: [{ collateralIndex: 0n, assets: 1_000n }],
1206
+ * });
1207
+ * const tx = output.buildTx();
1208
+ * ```
1209
+ */
1210
+ withdrawCollateralBatch(params) {
1211
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
1212
+ // Reject invalid owners before preparing the direct call.
1213
+ validateMidnightAccount("accountAddress", params.accountAddress);
1214
+ validateMarketData(params.marketData, this.chainId);
1215
+ validatePositionBinding(params);
1216
+ // Direct batches reject duplicates instead of summing them.
1217
+ validateMidnightCollateralBatch(params.collateralWithdrawals, new EmptyMidnightCollateralWithdrawalsError());
1218
+ const collateralWithdrawals = params.collateralWithdrawals.map(({ collateralIndex, assets }) => {
1219
+ // Reject unconfigured indexes before reading the position balance.
1220
+ MarketUtils.getCollateralByIndex(params.marketData.params, collateralIndex);
1221
+ return {
1222
+ collateralIndex,
1223
+ assets: assets === maxUint256
1224
+ ? (params.positionData.collateral[Number(collateralIndex)] ?? 0n)
1225
+ : assets,
1226
+ };
1227
+ });
1228
+ const tx = midnightWithdrawCollateralBatch({
1229
+ chainId: this.chainId,
1230
+ market: params.marketData.params,
1231
+ collateralWithdrawals,
1232
+ onBehalf: params.accountAddress,
1233
+ receiver: params.receiver ?? params.accountAddress,
1234
+ metadata: this.client.options.metadata,
1235
+ });
1236
+ const collateral = Array.from({ length: params.marketData.params.collateralParams.length }, (_, i) => params.positionData.collateral[i] ?? 0n);
1237
+ for (const { collateralIndex, assets } of collateralWithdrawals) {
1238
+ const index = Number(collateralIndex);
1239
+ const available = collateral[index];
1240
+ if (assets > available) {
1241
+ throw new WithdrawExceedsCollateralError({
1242
+ withdrawAmount: assets,
1243
+ available,
1244
+ market: params.marketData.id,
1245
+ });
1246
+ }
1247
+ collateral[index] = available - assets;
1248
+ }
1249
+ if (params.positionData.debt > 0n) {
1250
+ const maxSafeDebt = getMidnightMaxSafeDebt({
1251
+ market: params.marketData,
1252
+ collateral,
1253
+ collateralPrices: params.collateralPrices,
1254
+ });
1255
+ if (params.positionData.debt > maxSafeDebt) {
1256
+ throw new WithdrawMakesPositionUnhealthyError({
1257
+ withdrawAmount: collateralWithdrawals.reduce((sum, entry) => sum + entry.assets, 0n),
1258
+ borrowAssets: params.positionData.debt,
1259
+ maxSafeBorrow: maxSafeDebt,
1260
+ });
1261
+ }
1262
+ }
1263
+ return { getRequirements: async () => [], buildTx: () => tx };
1264
+ }
1164
1265
  /**
1165
1266
  * Prepares a direct collateral supply using a caller-provided market snapshot.
1166
1267
  *
@@ -1235,6 +1336,79 @@ export class MorphoMidnight {
1235
1336
  }),
1236
1337
  };
1237
1338
  }
1339
+ /**
1340
+ * Prepares ordered direct collateral supplies in one Midnight multicall.
1341
+ * Pass one entry per index: duplicates are rejected, unlike bundle flows which sum them.
1342
+ *
1343
+ * @param params.accountAddress - Sender and collateral beneficiary.
1344
+ * @param params.marketData - Snapshot of the target market.
1345
+ * @param params.collateralSupplies - Ordered supplies with optional reserved allowance amounts.
1346
+ * @returns A lazy approval resolver and synchronous stateless transaction builder.
1347
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
1348
+ * @throws {MidnightMarketAddressMismatchError} when the deployment differs.
1349
+ * @throws {MidnightCalldataEncodingError} when the account is malformed.
1350
+ * @throws {NegativeInputError} when reserved assets are negative.
1351
+ * @throws {NonPositiveInputError} when assets are not positive.
1352
+ * @throws {InputExceedsMaxError} when assets exceed uint128.
1353
+ * @throws {UnknownCollateralIndexError} when an index is not configured.
1354
+ * @throws {EmptyMidnightCollateralSuppliesError} when the list is empty.
1355
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
1356
+ * @throws {MidnightZeroOnBehalfError} when requirements or construction uses the zero account.
1357
+ * @example
1358
+ * ```ts
1359
+ * const output = midnight.supplyCollateralBatch({
1360
+ * accountAddress: user, marketData,
1361
+ * collateralSupplies: [{ collateralIndex: 0n, assets: 100n }],
1362
+ * });
1363
+ * const tx = output.buildTx();
1364
+ * ```
1365
+ */
1366
+ supplyCollateralBatch(params) {
1367
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
1368
+ // Reject malformed accounts before resolving token requirements.
1369
+ validateMidnightAddress("accountAddress", params.accountAddress);
1370
+ validateMarketData(params.marketData, this.chainId);
1371
+ // Reject empty and duplicate-index batches before resolving allowance thresholds.
1372
+ validateMidnightCollateralBatch(params.collateralSupplies, new EmptyMidnightCollateralSuppliesError());
1373
+ for (const supply of params.collateralSupplies) {
1374
+ assertPositiveAmount("assets", supply.assets);
1375
+ validateMidnightUint128Field("assets", supply.assets);
1376
+ assertNonNegativeAmount("reservedCollateralAssets", supply.reservedCollateralAssets ?? 0n);
1377
+ // Fail eagerly for collateral absent from the supplied snapshot.
1378
+ params.marketData.getCollateralByIndex(supply.collateralIndex);
1379
+ }
1380
+ const midnight = getChainAddress(this.chainId, "midnight");
1381
+ return {
1382
+ getRequirements: async (_requirementsParams) => {
1383
+ if (isAddressEqual(params.accountAddress, zeroAddress)) {
1384
+ throw new MidnightZeroOnBehalfError("onBehalf");
1385
+ }
1386
+ const amounts = new Map();
1387
+ for (const supply of params.collateralSupplies) {
1388
+ const token = params.marketData.getCollateralByIndex(supply.collateralIndex).token;
1389
+ amounts.set(token, (amounts.get(token) ?? 0n) +
1390
+ supply.assets +
1391
+ (supply.reservedCollateralAssets ?? 0n));
1392
+ }
1393
+ const requirements = await Promise.all([...amounts].map(([token, amount]) => getMidnightApprovalRequirements({
1394
+ viemClient: this.client.viemClient,
1395
+ chainId: this.chainId,
1396
+ token,
1397
+ owner: params.accountAddress,
1398
+ spender: midnight,
1399
+ amount,
1400
+ })));
1401
+ return requirements.flat();
1402
+ },
1403
+ buildTx: () => midnightSupplyCollateralBatch({
1404
+ chainId: this.chainId,
1405
+ market: params.marketData.params,
1406
+ collateralSupplies: params.collateralSupplies.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
1407
+ onBehalf: params.accountAddress,
1408
+ metadata: this.client.options.metadata,
1409
+ }),
1410
+ };
1411
+ }
1238
1412
  /**
1239
1413
  * Prepares an atomic lend-offer publication or repost through `MidnightBundlesV2`.
1240
1414
  *
@@ -235,6 +235,15 @@ export interface SupplyCollateralParams extends MarketActionParams {
235
235
  readonly reservedCollateralAssets?: bigint;
236
236
  readonly collateralIndex?: bigint;
237
237
  }
238
+ /** Parameters for an atomic direct Midnight collateral supply batch. */
239
+ export interface SupplyCollateralBatchParams extends MarketActionParams {
240
+ readonly collateralSupplies: readonly {
241
+ readonly collateralIndex: bigint;
242
+ readonly assets: bigint;
243
+ /** Additional assets included only in the allowance threshold. */
244
+ readonly reservedCollateralAssets?: bigint;
245
+ }[];
246
+ }
238
247
  /** Parameters for a direct Midnight collateral withdrawal. */
239
248
  export interface WithdrawCollateralParams extends MarketActionParams, MidnightPositionHealthParams {
240
249
  readonly collateralIndex?: bigint;
@@ -243,6 +252,13 @@ export interface WithdrawCollateralParams extends MarketActionParams, MidnightPo
243
252
  /** Defaults to accountAddress. */
244
253
  readonly receiver?: Address;
245
254
  }
255
+ /** Parameters for an atomic direct Midnight collateral withdrawal batch. */
256
+ export interface WithdrawCollateralBatchParams extends MarketActionParams, MidnightPositionHealthParams {
257
+ /** Ordered unique indexes; maxUint256 resolves that index's whole snapshot balance. */
258
+ readonly collateralWithdrawals: readonly MidnightCollateralTransfer[];
259
+ /** Defaults to accountAddress for every withdrawal. */
260
+ readonly receiver?: Address;
261
+ }
246
262
  /** Parameters for the Midnight redeem flow. */
247
263
  export interface RedeemParams {
248
264
  readonly accountAddress: Address;
@@ -65,9 +65,7 @@ export interface VaultV2Actions {
65
65
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
66
66
  * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
67
67
  * @throws {NativeAmountOnNonWNativeVaultError} when native funding targets a non-wNative vault.
68
- * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, or when the vault's
69
- * liquidity adapter is a Midnight adapter (it cannot receive vault allocations, so no deposit
70
- * fits and `max` is `0n`).
68
+ * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256.
71
69
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
72
70
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
73
71
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -149,9 +147,7 @@ export interface VaultV2Actions {
149
147
  * @throws {NonPositiveInputError} when `amount` or the computed required share amount is not positive.
150
148
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
151
149
  * at any `getRequirements()` call.
152
- * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation,
153
- * or when the vault's liquidity adapter is a Midnight adapter and `amount` exceeds the vault's
154
- * idle assets.
150
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation.
155
151
  * @throws {NegativeInputError} when `referralFeePct` or `slippageTolerance` is negative.
156
152
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
157
153
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no nonzero recipient.
@@ -217,24 +213,7 @@ export interface VaultV2Actions {
217
213
  * @throws {NonPositiveInputError} when `shares` is not positive.
218
214
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
219
215
  * requirement resolution.
220
- * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256, or from
221
- * `getRequirements()` when the vault's liquidity adapter is a Midnight adapter and `shares`
222
- * are worth more than the vault's idle assets.
223
- * @throws {UnknownBlueFactory} from `getRequirements()` when the configured chain has no VaultV2 factory.
224
- * @throws {UnknownBlueOfFactory} from `getRequirements()` when the vault is not a VaultV2 from the
225
- * configured factory.
226
- * @throws {UnsupportedBlueVaultV2AdapterError} from `getRequirements()` when the vault or one of its
227
- * adapters uses an unsupported adapter class.
228
- * @throws {UnsupportedBlueMarketIrmError} from `getRequirements()` when the vault's liquidity adapter
229
- * is a Midnight adapter and accrual projects an underlying market with positive debt that uses an
230
- * unsupported IRM.
231
- * @throws {UnknownBlueMarketAllocationError} from `getRequirements()` when the vault's liquidity
232
- * adapter is a Midnight adapter and accrual meets a nested Vault V1 withdraw queue market without
233
- * allocation data.
234
- * @throws {InvalidMidnightPositionLossFactorError} from `getRequirements()` when the vault's liquidity
235
- * adapter is a Midnight adapter and accrual meets a market loss factor below a position's.
236
- * @throws {InvalidMidnightPositionAccrualStateError} from `getRequirements()` when the vault's
237
- * liquidity adapter is a Midnight adapter and accrual meets invalid Midnight position inputs.
216
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
238
217
  * @throws {NegativeInputError} when `referralFeePct` is negative.
239
218
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
240
219
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
@@ -242,7 +221,7 @@ export interface VaultV2Actions {
242
221
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
243
222
  * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
244
223
  * contract has no code at its registered address.
245
- * @throws {viem.BaseError} from `getRequirements()` when a vault-state, allowance, nonce, `eth_chainId`, or
224
+ * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, `eth_chainId`, or
246
225
  * `eth_getCode` read fails.
247
226
  * @throws {UnknownTokenError} from `getRequirements()` when the share token fetched by
248
227
  * `getData()` has unusable decimals.
@@ -320,11 +299,9 @@ export interface VaultV2Actions {
320
299
  * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256`.
321
300
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
322
301
  * requirement resolution.
323
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter, including
324
- * a vault that mixes Blue and Midnight adapters.
302
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter.
325
303
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
326
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
327
- * including a Midnight adapter.
304
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
328
305
  * @throws {InKindRedeemCoverageError} when the deduplicated list cannot cover the exit.
329
306
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
330
307
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
@@ -449,11 +426,9 @@ export interface VaultV2Actions {
449
426
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
450
427
  * requirement resolution.
451
428
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
452
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter,
453
- * including a vault that mixes Blue and Midnight adapters.
429
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter.
454
430
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
455
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
456
- * including a Midnight adapter.
431
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
457
432
  * @throws {VaultV2UnsupportedLiquidityAdapterError} when the vault routes liquidity through
458
433
  * another adapter.
459
434
  * @throws {VaultV2UndecodableLiquidityDataError} when the vault's `liquidityData` does not decode
@@ -15,11 +15,6 @@ import { getBundlesTokenRequirements } from "../requirements/index.js";
15
15
  // Maximum accepted deadline horizon; the on-chain management fee is capped at 5%/yr so the
16
16
  // accrual model stays well-defined inside it.
17
17
  const VAULT_V2_FEE_PROJECTION_HORIZON = Time.s.from.y(1n);
18
- /**
19
- * Midnight adapters revert vault-initiated `allocate` and `deallocate` (`SelfAllocationOnly`), so a
20
- * vault routing liquidity through one accepts no deposit and serves exits from idle assets only.
21
- */
22
- const isMidnightLiquidityAdapter = (vaultData) => vaultData.accrualLiquidityAdapter?.type === "VaultV2MidnightAdapter";
23
18
  /** Binds a viem client to a Vault V2 vault's action builders. */
24
19
  export class MorphoVaultV2 {
25
20
  client;
@@ -78,13 +73,6 @@ export class MorphoVaultV2 {
78
73
  // The native path must target the chain's registered wrapped-native asset.
79
74
  validateNativeVaultAsset(this.chainId, vaultAsset);
80
75
  }
81
- if (isMidnightLiquidityAdapter(vaultData)) {
82
- throw new InputExceedsMaxError({
83
- field: funding.value > 0n ? "nativeAmount" : "amount",
84
- value: funding.assets,
85
- max: 0n,
86
- });
87
- }
88
76
  const referralFeeAssets = getBundlesReferralFeeAssets(funding.assets, common.referralFeePct);
89
77
  const maxSharePrice = computeVaultMaxSharePrice({
90
78
  vaultData,
@@ -165,14 +153,6 @@ export class MorphoVaultV2 {
165
153
  throw new NonPositiveInputError("amount", amount);
166
154
  // Reject values outside the ABI range before resolving any requirements.
167
155
  validateUint256Field("amount", amount);
168
- if (isMidnightLiquidityAdapter(vaultData) &&
169
- amount > vaultData.assetBalance) {
170
- throw new InputExceedsMaxError({
171
- field: "amount",
172
- value: amount,
173
- max: vaultData.assetBalance,
174
- });
175
- }
176
156
  const createdAt = Time.timestamp();
177
157
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
178
158
  if (deadline <= createdAt)
@@ -253,20 +233,8 @@ export class MorphoVaultV2 {
253
233
  if (deadline <= now)
254
234
  throw new ExpiredDeadlineError(deadline, now);
255
235
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
256
- const vaultData = await this.getData();
257
- if (isMidnightLiquidityAdapter(vaultData)) {
258
- // Onchain redeem accrues interest before converting shares to assets.
259
- const { vault: accrued } = vaultData.accrueInterest(now);
260
- if (accrued.toAssets(shares) > accrued.assetBalance) {
261
- throw new InputExceedsMaxError({
262
- field: "shares",
263
- value: shares,
264
- max: accrued.toShares(accrued.assetBalance),
265
- });
266
- }
267
- }
268
236
  return getVaultBundlesSharesRequirements(this.client.viemClient, {
269
- vaultData,
237
+ vaultData: await this.getData(),
270
238
  version: "vaultV2",
271
239
  owner: userAddress,
272
240
  chainId: this.chainId,
@@ -56,9 +56,8 @@ export interface InputVaultV2BlueReallocationData {
56
56
  /**
57
57
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
58
58
  *
59
- * Constructor inputs are cloned, except Midnight adapter snapshots: those are
60
- * shared by reference and must be treated as read-only. Every simulated
61
- * reallocation returns a new instance. Planning keeps the transaction-scoped `firstTotalAssets`
59
+ * Constructor inputs are cloned. Every simulated reallocation returns a new
60
+ * instance. Planning keeps the transaction-scoped `firstTotalAssets`
62
61
  * denominator outside the durable snapshot while applying reallocations in
63
62
  * contract order. Penalty donations update simulated vault accounting but are
64
63
  * excluded from same-plan idle liquidity so round-up dust cannot create
@@ -132,8 +131,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
132
131
  /**
133
132
  * Clones the complete simulation snapshot.
134
133
  *
135
- * @returns A deep clone of this simulation state. Midnight adapter snapshots are
136
- * shared by reference and must be treated as read-only.
134
+ * @returns A deep clone of this simulation state.
137
135
  * @example
138
136
  * ```ts
139
137
  * import { markets } from "@morpho-org/morpho-test";
@@ -87,10 +87,6 @@ const cloneAccrualVault = (vault, markets) => new AccrualVault({
87
87
  position: clonePosition(position, markets),
88
88
  })));
89
89
  const cloneAdapter = (adapter, markets) => {
90
- // BluePublicAllocator never moves Midnight liquidity, and reallocation never mutates a Midnight
91
- // adapter, so its read-only snapshot is shared as-is.
92
- if (adapter.type === "VaultV2MidnightAdapter")
93
- return adapter;
94
90
  const base = {
95
91
  address: adapter.address,
96
92
  parentVault: adapter.parentVault,
@@ -138,9 +134,8 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
138
134
  /**
139
135
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
140
136
  *
141
- * Constructor inputs are cloned, except Midnight adapter snapshots: those are
142
- * shared by reference and must be treated as read-only. Every simulated
143
- * reallocation returns a new instance. Planning keeps the transaction-scoped `firstTotalAssets`
137
+ * Constructor inputs are cloned. Every simulated reallocation returns a new
138
+ * instance. Planning keeps the transaction-scoped `firstTotalAssets`
144
139
  * denominator outside the durable snapshot while applying reallocations in
145
140
  * contract order. Penalty donations update simulated vault accounting but are
146
141
  * excluded from same-plan idle liquidity so round-up dust cannot create
@@ -284,8 +279,7 @@ export class VaultV2BlueReallocationData {
284
279
  /**
285
280
  * Clones the complete simulation snapshot.
286
281
  *
287
- * @returns A deep clone of this simulation state. Midnight adapter snapshots are
288
- * shared by reference and must be treated as read-only.
282
+ * @returns A deep clone of this simulation state.
289
283
  * @example
290
284
  * ```ts
291
285
  * import { markets } from "@morpho-org/morpho-test";
@@ -1,7 +1,7 @@
1
- export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, InvalidVaultV2MidnightAdapterMarketsError as InvalidBlueVaultV2MidnightAdapterMarketsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
1
+ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureError as InvalidMidnightEcrecoverSignatureError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
7
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
package/lib/esm/errors.js CHANGED
@@ -1,6 +1,6 @@
1
- export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, InvalidVaultV2MidnightAdapterMarketsError as InvalidBlueVaultV2MidnightAdapterMarketsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
1
+ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureError as InvalidMidnightEcrecoverSignatureError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
@@ -1,6 +1,6 @@
1
- export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MidnightAdapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
1
+ export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  fetchPreLiquidationParams as fetchBluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MidnightAdapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
5
+ fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
6
6
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";
package/lib/esm/fetch.js CHANGED
@@ -1,6 +1,6 @@
1
- export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MidnightAdapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
1
+ export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  fetchPreLiquidationParams as fetchBluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MidnightAdapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
5
+ fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
6
6
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";