@morpho-org/morpho-sdk 10.3.0 → 10.4.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 (188) hide show
  1. package/README.md +172 -8
  2. package/lib/cjs/actions/midnight/redeem.d.ts +20 -3
  3. package/lib/cjs/actions/midnight/redeem.js +58 -1
  4. package/lib/cjs/actions/midnight/supplyCollateralWithNative.d.ts +24 -1
  5. package/lib/cjs/actions/midnight/supplyCollateralWithNative.js +41 -0
  6. package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +16 -2
  7. package/lib/cjs/actions/midnight/withdrawCollateral.js +26 -1
  8. package/lib/cjs/helpers/callback.d.ts +3 -2
  9. package/lib/cjs/helpers/callback.js +4 -20
  10. package/lib/cjs/helpers/computeMidnightPostWithdrawalCollateral.d.ts +17 -0
  11. package/lib/cjs/helpers/computeMidnightPostWithdrawalCollateral.js +30 -0
  12. package/lib/cjs/helpers/parseMidnightMaker.d.ts +21 -0
  13. package/lib/cjs/helpers/parseMidnightMaker.js +41 -1
  14. package/lib/cjs/helpers/validate.d.ts +49 -1
  15. package/lib/cjs/helpers/validate.js +87 -1
  16. package/lib/cjs/helpers/validateMidnightPublication.d.ts +10 -0
  17. package/lib/cjs/helpers/validateMidnightPublication.js +18 -1
  18. package/lib/cjs/helpers/validateMidnightTakeableOfferFields.d.ts +28 -0
  19. package/lib/cjs/helpers/validateMidnightTakeableOfferFields.js +85 -0
  20. package/lib/cjs/index.d.ts +2 -2
  21. package/lib/cjs/index.js +23 -1
  22. package/lib/cjs/midnight/utils.d.ts +1 -1
  23. package/lib/cjs/midnight/utils.js +2 -1
  24. package/lib/cjs/transactionPlan/blue/withdrawBuyCallback.d.ts +101 -0
  25. package/lib/cjs/transactionPlan/blue/withdrawBuyCallback.js +264 -0
  26. package/lib/cjs/transactionPlan/error.d.ts +27 -0
  27. package/lib/cjs/transactionPlan/error.js +30 -1
  28. package/lib/cjs/transactionPlan/index.d.ts +40 -1
  29. package/lib/cjs/transactionPlan/index.js +46 -5
  30. package/lib/cjs/transactionPlan/midnight/authorization.d.ts +15 -0
  31. package/lib/cjs/transactionPlan/midnight/authorization.js +45 -0
  32. package/lib/cjs/transactionPlan/midnight/cancelOffers.d.ts +80 -0
  33. package/lib/cjs/transactionPlan/midnight/cancelOffers.js +125 -0
  34. package/lib/cjs/transactionPlan/midnight/makeBorrow.d.ts +104 -0
  35. package/lib/cjs/transactionPlan/midnight/makeBorrow.js +126 -0
  36. package/lib/cjs/transactionPlan/midnight/makeLend.d.ts +140 -0
  37. package/lib/cjs/transactionPlan/midnight/makeLend.js +176 -0
  38. package/lib/cjs/transactionPlan/midnight/makeRepay.d.ts +118 -0
  39. package/lib/cjs/transactionPlan/midnight/makeRepay.js +118 -0
  40. package/lib/cjs/transactionPlan/midnight/makeWithdraw.d.ts +104 -0
  41. package/lib/cjs/transactionPlan/midnight/makeWithdraw.js +126 -0
  42. package/lib/cjs/transactionPlan/midnight/makerPublication.d.ts +55 -0
  43. package/lib/cjs/transactionPlan/midnight/makerPublication.js +315 -0
  44. package/lib/cjs/transactionPlan/midnight/market.d.ts +49 -0
  45. package/lib/cjs/transactionPlan/midnight/market.js +120 -0
  46. package/lib/cjs/transactionPlan/midnight/prepare.d.ts +244 -0
  47. package/lib/cjs/transactionPlan/midnight/prepare.js +547 -0
  48. package/lib/cjs/transactionPlan/midnight/publicationState.d.ts +24 -0
  49. package/lib/cjs/transactionPlan/midnight/publicationState.js +50 -0
  50. package/lib/cjs/transactionPlan/midnight/redeem.d.ts +102 -0
  51. package/lib/cjs/transactionPlan/midnight/redeem.js +170 -0
  52. package/lib/cjs/transactionPlan/midnight/reduceOnlySellFeasibility.d.ts +25 -0
  53. package/lib/cjs/transactionPlan/midnight/reduceOnlySellFeasibility.js +51 -0
  54. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.d.ts +162 -0
  55. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.js +328 -0
  56. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.d.ts +155 -0
  57. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.js +199 -0
  58. package/lib/cjs/transactionPlan/midnight/supplyCollateral.d.ts +96 -0
  59. package/lib/cjs/transactionPlan/midnight/supplyCollateral.js +190 -0
  60. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.d.ts +112 -0
  61. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.js +221 -0
  62. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +129 -0
  63. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.js +179 -0
  64. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.d.ts +115 -0
  65. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.js +259 -0
  66. package/lib/cjs/transactionPlan/midnight/takeBorrow.d.ts +304 -0
  67. package/lib/cjs/transactionPlan/midnight/takeBorrow.js +545 -0
  68. package/lib/cjs/transactionPlan/midnight/takeLend.d.ts +99 -0
  69. package/lib/cjs/transactionPlan/midnight/takeLend.js +263 -0
  70. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +175 -0
  71. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.js +440 -0
  72. package/lib/cjs/transactionPlan/midnight/takeWithdraw.d.ts +139 -0
  73. package/lib/cjs/transactionPlan/midnight/takeWithdraw.js +240 -0
  74. package/lib/cjs/transactionPlan/midnight/validation.d.ts +22 -0
  75. package/lib/cjs/transactionPlan/midnight/validation.js +158 -0
  76. package/lib/cjs/transactionPlan/midnight/withdrawCollateral.d.ts +130 -0
  77. package/lib/cjs/transactionPlan/midnight/withdrawCollateral.js +228 -0
  78. package/lib/cjs/transactionPlan/midnight/withdrawCollateralBatch.d.ts +142 -0
  79. package/lib/cjs/transactionPlan/midnight/withdrawCollateralBatch.js +232 -0
  80. package/lib/cjs/transactionPlan/plan.d.ts +48 -14
  81. package/lib/cjs/transactionPlan/plan.js +103 -18
  82. package/lib/cjs/transactionPlan/requirements.d.ts +7 -4
  83. package/lib/cjs/transactionPlan/requirements.js +2 -2
  84. package/lib/cjs/transactionPlan/serde.d.ts +13 -2
  85. package/lib/cjs/transactionPlan/serde.js +68 -21
  86. package/lib/cjs/transactionPlan/types.d.ts +147 -0
  87. package/lib/cjs/transactionPlan/validateActions.d.ts +3 -1
  88. package/lib/cjs/transactionPlan/validateActions.js +31 -3
  89. package/lib/cjs/transactionPlan/validation.d.ts +1 -1
  90. package/lib/cjs/transactionPlan/validation.js +37 -1
  91. package/lib/cjs/types/error.d.ts +2 -0
  92. package/lib/cjs/types/error.js +2 -0
  93. package/lib/cjs/version.d.ts +1 -1
  94. package/lib/cjs/version.js +1 -1
  95. package/lib/esm/actions/midnight/redeem.d.ts +20 -3
  96. package/lib/esm/actions/midnight/redeem.js +56 -0
  97. package/lib/esm/actions/midnight/supplyCollateralWithNative.d.ts +24 -1
  98. package/lib/esm/actions/midnight/supplyCollateralWithNative.js +40 -0
  99. package/lib/esm/actions/midnight/withdrawCollateral.d.ts +16 -2
  100. package/lib/esm/actions/midnight/withdrawCollateral.js +25 -1
  101. package/lib/esm/helpers/callback.d.ts +3 -2
  102. package/lib/esm/helpers/callback.js +5 -21
  103. package/lib/esm/helpers/computeMidnightPostWithdrawalCollateral.d.ts +17 -0
  104. package/lib/esm/helpers/computeMidnightPostWithdrawalCollateral.js +27 -0
  105. package/lib/esm/helpers/parseMidnightMaker.d.ts +21 -0
  106. package/lib/esm/helpers/parseMidnightMaker.js +40 -1
  107. package/lib/esm/helpers/validate.d.ts +49 -1
  108. package/lib/esm/helpers/validate.js +84 -1
  109. package/lib/esm/helpers/validateMidnightPublication.d.ts +10 -0
  110. package/lib/esm/helpers/validateMidnightPublication.js +16 -0
  111. package/lib/esm/helpers/validateMidnightTakeableOfferFields.d.ts +28 -0
  112. package/lib/esm/helpers/validateMidnightTakeableOfferFields.js +81 -0
  113. package/lib/esm/index.d.ts +2 -2
  114. package/lib/esm/index.js +1 -1
  115. package/lib/esm/midnight/utils.d.ts +1 -1
  116. package/lib/esm/midnight/utils.js +1 -1
  117. package/lib/esm/transactionPlan/blue/withdrawBuyCallback.d.ts +101 -0
  118. package/lib/esm/transactionPlan/blue/withdrawBuyCallback.js +259 -0
  119. package/lib/esm/transactionPlan/error.d.ts +27 -0
  120. package/lib/esm/transactionPlan/error.js +28 -0
  121. package/lib/esm/transactionPlan/index.d.ts +40 -1
  122. package/lib/esm/transactionPlan/index.js +20 -1
  123. package/lib/esm/transactionPlan/midnight/authorization.d.ts +15 -0
  124. package/lib/esm/transactionPlan/midnight/authorization.js +40 -0
  125. package/lib/esm/transactionPlan/midnight/cancelOffers.d.ts +80 -0
  126. package/lib/esm/transactionPlan/midnight/cancelOffers.js +120 -0
  127. package/lib/esm/transactionPlan/midnight/makeBorrow.d.ts +104 -0
  128. package/lib/esm/transactionPlan/midnight/makeBorrow.js +123 -0
  129. package/lib/esm/transactionPlan/midnight/makeLend.d.ts +140 -0
  130. package/lib/esm/transactionPlan/midnight/makeLend.js +172 -0
  131. package/lib/esm/transactionPlan/midnight/makeRepay.d.ts +118 -0
  132. package/lib/esm/transactionPlan/midnight/makeRepay.js +115 -0
  133. package/lib/esm/transactionPlan/midnight/makeWithdraw.d.ts +104 -0
  134. package/lib/esm/transactionPlan/midnight/makeWithdraw.js +123 -0
  135. package/lib/esm/transactionPlan/midnight/makerPublication.d.ts +55 -0
  136. package/lib/esm/transactionPlan/midnight/makerPublication.js +310 -0
  137. package/lib/esm/transactionPlan/midnight/market.d.ts +49 -0
  138. package/lib/esm/transactionPlan/midnight/market.js +112 -0
  139. package/lib/esm/transactionPlan/midnight/prepare.d.ts +244 -0
  140. package/lib/esm/transactionPlan/midnight/prepare.js +536 -0
  141. package/lib/esm/transactionPlan/midnight/publicationState.d.ts +24 -0
  142. package/lib/esm/transactionPlan/midnight/publicationState.js +47 -0
  143. package/lib/esm/transactionPlan/midnight/redeem.d.ts +102 -0
  144. package/lib/esm/transactionPlan/midnight/redeem.js +165 -0
  145. package/lib/esm/transactionPlan/midnight/reduceOnlySellFeasibility.d.ts +25 -0
  146. package/lib/esm/transactionPlan/midnight/reduceOnlySellFeasibility.js +47 -0
  147. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.d.ts +162 -0
  148. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.js +323 -0
  149. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.d.ts +155 -0
  150. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.js +196 -0
  151. package/lib/esm/transactionPlan/midnight/supplyCollateral.d.ts +96 -0
  152. package/lib/esm/transactionPlan/midnight/supplyCollateral.js +185 -0
  153. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.d.ts +112 -0
  154. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.js +216 -0
  155. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +129 -0
  156. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.js +176 -0
  157. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.d.ts +115 -0
  158. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.js +254 -0
  159. package/lib/esm/transactionPlan/midnight/takeBorrow.d.ts +304 -0
  160. package/lib/esm/transactionPlan/midnight/takeBorrow.js +539 -0
  161. package/lib/esm/transactionPlan/midnight/takeLend.d.ts +99 -0
  162. package/lib/esm/transactionPlan/midnight/takeLend.js +258 -0
  163. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +175 -0
  164. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.js +435 -0
  165. package/lib/esm/transactionPlan/midnight/takeWithdraw.d.ts +139 -0
  166. package/lib/esm/transactionPlan/midnight/takeWithdraw.js +236 -0
  167. package/lib/esm/transactionPlan/midnight/validation.d.ts +22 -0
  168. package/lib/esm/transactionPlan/midnight/validation.js +151 -0
  169. package/lib/esm/transactionPlan/midnight/withdrawCollateral.d.ts +130 -0
  170. package/lib/esm/transactionPlan/midnight/withdrawCollateral.js +223 -0
  171. package/lib/esm/transactionPlan/midnight/withdrawCollateralBatch.d.ts +142 -0
  172. package/lib/esm/transactionPlan/midnight/withdrawCollateralBatch.js +227 -0
  173. package/lib/esm/transactionPlan/plan.d.ts +48 -14
  174. package/lib/esm/transactionPlan/plan.js +99 -14
  175. package/lib/esm/transactionPlan/requirements.d.ts +7 -4
  176. package/lib/esm/transactionPlan/requirements.js +2 -2
  177. package/lib/esm/transactionPlan/serde.d.ts +13 -2
  178. package/lib/esm/transactionPlan/serde.js +49 -2
  179. package/lib/esm/transactionPlan/types.d.ts +147 -0
  180. package/lib/esm/transactionPlan/validateActions.d.ts +3 -1
  181. package/lib/esm/transactionPlan/validateActions.js +31 -3
  182. package/lib/esm/transactionPlan/validation.d.ts +1 -1
  183. package/lib/esm/transactionPlan/validation.js +38 -2
  184. package/lib/esm/types/error.d.ts +2 -0
  185. package/lib/esm/types/error.js +2 -0
  186. package/lib/esm/version.d.ts +1 -1
  187. package/lib/esm/version.js +1 -1
  188. package/package.json +4 -4
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareMidnightWithdrawCollateral = prepareMidnightWithdrawCollateral;
4
+ exports.buildMidnightWithdrawCollateral = buildMidnightWithdrawCollateral;
5
+ exports.validateMidnightWithdrawCollateralPlanAction = validateMidnightWithdrawCollateralPlanAction;
6
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
+ const withdrawCollateral_js_1 = require("../../actions/midnight/withdrawCollateral.js");
8
+ const chainCheck_js_1 = require("../../actions/requirements/chainCheck.js");
9
+ const assertContractCode_js_1 = require("../../entities/requirements/assertContractCode.js");
10
+ const computeMidnightPostWithdrawalCollateral_js_1 = require("../../helpers/computeMidnightPostWithdrawalCollateral.js");
11
+ const validate_js_1 = require("../../helpers/validate.js");
12
+ const index_js_1 = require("../../types/index.js");
13
+ const error_js_1 = require("../error.js");
14
+ const intent_js_1 = require("../intent.js");
15
+ const validation_js_1 = require("../validation.js");
16
+ const authorization_js_1 = require("./authorization.js");
17
+ const market_js_1 = require("./market.js");
18
+ const validation_js_2 = require("./validation.js");
19
+ const actionId = "midnightWithdrawCollateral";
20
+ /**
21
+ * Prepares one direct Midnight core collateral withdrawal. Inputs go through
22
+ * `parseMidnightWithdrawCollateralPreparation`, which applies the entity `withdrawCollateral`
23
+ * checks in the same order: the position is bound to the sender and market, the index is
24
+ * resolved, and `maxUint256` becomes the snapshot balance before the amount, receiver and
25
+ * encoding checks. The withdrawal is then checked against the snapshot balance and, when the
26
+ * snapshot has debt, against the remaining collateral's capacity at LLTV minus
27
+ * `DEFAULT_LLTV_BUFFER`. Restoring and building offline does not refresh those checks;
28
+ * simulate against current state before sending.
29
+ *
30
+ * The account sends the withdrawal itself, so the plan has no approvals, authorizations or
31
+ * signature requests. Expiry is checked during preparation only; it is not an onchain deadline.
32
+ * @param client - Viem client used to check the network and the Midnight core deployment.
33
+ * @param params - Market and position snapshots, collateral selection, amount and optional receiver.
34
+ * @param params.chainId - EIP-155 chain ID of the market and submitting client.
35
+ * @param params.account - Nonzero position owner who sends the withdrawal.
36
+ * @param params.marketData - Hydrated market snapshot from the same block as `positionData`.
37
+ * @param params.positionData - Position snapshot for the same market, owned by `account`.
38
+ * @param params.collateralPrices - Raw `price()` values from each collateral oracle at the snapshot
39
+ * block, indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE` (1e36). Not
40
+ * needed when the snapshot has no debt.
41
+ * @param params.collateralIndex - Collateral index in token-address order. Defaults to `0n`.
42
+ * @param params.assets - Positive collateral amount in token base units; `maxUint256` withdraws
43
+ * the snapshot balance at that index.
44
+ * @param params.receiver - Optional recipient of the collateral; defaults to `account`. Midnight
45
+ * and market token contracts are rejected.
46
+ * @param params.now - Reference Unix timestamp in seconds, normally the snapshot block's timestamp;
47
+ * omitting it uses the device clock (an untyped JavaScript `null` does too).
48
+ * @param params.expiresAt - Plan expiry in Unix seconds; defaults to two hours after `now`. Midnight does not enforce it onchain.
49
+ * @param params.calldataOrigin - Optional attribution bytes appended to the built transaction.
50
+ * @returns A frozen plan with one withdrawal step and no approvals, authorizations or signature requests.
51
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now`, the amount, the index or a supplied collateral price is not a bigint; checked before any request.
52
+ * @throws {ZeroAccountError} If the account is the zero address.
53
+ * @throws {NonIntegerInputError} If expiry is not a safe integer.
54
+ * @throws {ExpiredDeadlineError} If expiry is at or before the reference time.
55
+ * @throws {InvalidCalldataOriginError} If attribution bytes are empty or malformed.
56
+ * @throws {InvalidTransactionPlanError} If the account is malformed, `collateralPrices` is not an array, or attribution exceeds 1 MiB.
57
+ * @throws {ChainIdMismatchError} If the market, client or RPC targets another chain.
58
+ * @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
59
+ * @throws {InvalidMarketParameterError} If the market configuration is invalid.
60
+ * @throws {MarketIdMismatchError} If the position belongs to another market.
61
+ * @throws {AccrualPositionUserMismatchError} If the position is owned by another account.
62
+ * @throws {UnknownCollateralIndexError} If the index is not configured on the market.
63
+ * @throws {NonPositiveInputError} If expiry or the resolved amount is not positive.
64
+ * @throws {InputExceedsMaxError} If the resolved amount exceeds uint128.
65
+ * @throws {MidnightZeroReceiverError} If the receiver is the zero address.
66
+ * @throws {MidnightContractReceiverError} If the receiver is a blocked protocol or market token contract.
67
+ * @throws {MidnightCalldataEncodingError} If a market, position owner or receiver address is malformed, or calldata cannot be encoded.
68
+ * @throws {WithdrawExceedsCollateralError} If the amount exceeds the snapshot balance.
69
+ * @throws {MissingMarketPriceError} If remaining collateral has no price for the health check.
70
+ * @throws {WithdrawMakesPositionUnhealthyError} If the snapshot debt exceeds the remaining buffered capacity.
71
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
72
+ * @throws {UnknownAddressError} If Midnight core is not registered on the chain.
73
+ * @throws {MissingContractCodeError} If the registered Midnight core has no deployed code.
74
+ * @throws {viem.BaseError} If the `eth_chainId` or bytecode request fails.
75
+ * @example
76
+ * ```ts
77
+ * import {
78
+ * buildTransactions,
79
+ * prepareMidnightWithdrawCollateral,
80
+ * type TransactionPlan,
81
+ * } from "@morpho-org/morpho-sdk";
82
+ * import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
83
+ * import { type Address, type Hash, createPublicClient, http, maxUint256 } from "viem";
84
+ * import { base } from "viem/chains";
85
+ *
86
+ * // For a debt-free position only. With debt, pass each collateral oracle's `price()`
87
+ * // from the same block as `collateralPrices`; an empty list then throws MissingMarketPriceError.
88
+ * async function prepareCollateralExit(account: Address, marketId: Hash) {
89
+ * const client = createPublicClient({ chain: base, transport: http() });
90
+ * const block = await client.getBlock();
91
+ * const positionData = await fetchMidnightAccrualPosition(client, {
92
+ * marketId, user: account, blockNumber: block.number,
93
+ * });
94
+ * const plan: TransactionPlan = await prepareMidnightWithdrawCollateral(client, {
95
+ * chainId: base.id, account, marketData: positionData.market, positionData,
96
+ * collateralPrices: [], // No price check is needed without debt.
97
+ * now: block.timestamp,
98
+ * assets: maxUint256,
99
+ * });
100
+ * // plan.steps: a single "midnightWithdrawCollateral" step; plan.signatureRequests is empty.
101
+ * // Simulate, then send from plan.account on plan.chainId.
102
+ * return buildTransactions(plan);
103
+ * }
104
+ * ```
105
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
106
+ */
107
+ async function prepareMidnightWithdrawCollateral(client, params) {
108
+ const { account, chainId, marketData, positionData } = params;
109
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
110
+ (0, validate_js_1.validateReferenceTime)(now);
111
+ const { expiresAt, calldataOrigin } = (0, intent_js_1.resolveIntent)({
112
+ account,
113
+ chainId,
114
+ expiresAt: params.expiresAt,
115
+ calldataOrigin: params.calldataOrigin,
116
+ }, now);
117
+ if (typeof params.assets !== "bigint") {
118
+ throw new index_js_1.InvalidBigIntInputError("assets", params.assets);
119
+ }
120
+ if (params.collateralIndex !== undefined &&
121
+ typeof params.collateralIndex !== "bigint") {
122
+ throw new index_js_1.InvalidBigIntInputError("collateralIndex", params.collateralIndex);
123
+ }
124
+ (0, market_js_1.validateCollateralPriceTypes)(params.collateralPrices);
125
+ const parsed = (0, withdrawCollateral_js_1.parseMidnightWithdrawCollateralPreparation)({
126
+ chainId,
127
+ accountAddress: account,
128
+ marketData,
129
+ positionData,
130
+ collateralIndex: params.collateralIndex,
131
+ assets: params.assets,
132
+ receiver: params.receiver,
133
+ });
134
+ const { postCollateral, withdrawAmount } = (0, computeMidnightPostWithdrawalCollateral_js_1.computeMidnightPostWithdrawalCollateral)({
135
+ market: marketData.params,
136
+ marketId: marketData.id,
137
+ collateral: positionData.collateral,
138
+ withdrawals: [
139
+ { collateralIndex: parsed.collateralIndex, assets: parsed.assets },
140
+ ],
141
+ });
142
+ (0, validate_js_1.validateMidnightWithdrawHealth)({
143
+ market: marketData,
144
+ collateral: postCollateral,
145
+ collateralPrices: params.collateralPrices,
146
+ debt: positionData.debt,
147
+ withdrawAmount,
148
+ });
149
+ const chainCheck = (0, chainCheck_js_1.createChainCheck)(client, chainId);
150
+ await chainCheck();
151
+ // A code-less core would accept the withdrawal as a silent no-op.
152
+ await (0, assertContractCode_js_1.assertRegistryTargetsHaveCode)(client, chainId, [{ role: "midnight", address: (0, morpho_ts_1.getChainAddress)(chainId, "midnight") }], chainCheck);
153
+ return (0, morpho_ts_1.deepFreeze)({
154
+ version: 2,
155
+ chainId,
156
+ account,
157
+ expiresAt,
158
+ ...(calldataOrigin && { calldataOrigin }),
159
+ steps: [
160
+ {
161
+ id: actionId,
162
+ label: "Withdraw Midnight collateral",
163
+ action: {
164
+ type: actionId,
165
+ inputs: {
166
+ account,
167
+ chainId,
168
+ market: parsed.market.struct,
169
+ collateralIndex: parsed.collateralIndex,
170
+ assets: parsed.assets,
171
+ receiver: parsed.receiver,
172
+ },
173
+ },
174
+ },
175
+ ],
176
+ signatureRequests: [],
177
+ });
178
+ }
179
+ /** @internal Encodes the stored direct withdrawal without retaining the snapshot. */
180
+ function buildMidnightWithdrawCollateral({ inputs, }) {
181
+ const { account, chainId, market, collateralIndex, assets, receiver } = inputs;
182
+ // The action builder defaults a missing index to 0n, which would switch the withdrawn token.
183
+ if (typeof collateralIndex !== "bigint") {
184
+ throw new error_js_1.InvalidTransactionPlanError({
185
+ path: "$.inputs.collateralIndex",
186
+ reason: "expected a bigint",
187
+ });
188
+ }
189
+ (0, market_js_1.validateStoredCollateralOrder)(market.collateralParams, "$.inputs.market.collateralParams");
190
+ return (0, withdrawCollateral_js_1.midnightWithdrawCollateral)({
191
+ chainId,
192
+ market: (0, market_js_1.storedMarketTuple)(market),
193
+ collateralIndex,
194
+ assets,
195
+ onBehalf: account,
196
+ receiver,
197
+ });
198
+ }
199
+ /** @internal Validates the stored Midnight collateral withdrawal without RPC. */
200
+ function validateMidnightWithdrawCollateralPlanAction(action, path) {
201
+ const inputsPath = `${path}.inputs`;
202
+ const inputs = (0, validation_js_1.getPlanObject)(action.inputs, inputsPath);
203
+ (0, validation_js_1.validatePlanFields)(inputs, {
204
+ path: inputsPath,
205
+ fields: {
206
+ assets: "uint128 bigint",
207
+ collateralIndex: "uint256 bigint",
208
+ receiver: "address",
209
+ },
210
+ });
211
+ const marketPath = `${inputsPath}.market`;
212
+ const market = (0, validation_js_1.getPlanObject)(inputs.market, marketPath);
213
+ // Validate the tuple before reading its collateral tokens.
214
+ (0, validation_js_2.validateStoredMidnightMarket)(market, {
215
+ path: marketPath,
216
+ chainId: inputs.chainId,
217
+ });
218
+ const collaterals = market.collateralParams;
219
+ (0, market_js_1.validateStoredCollateralOrder)(collaterals, `${marketPath}.collateralParams`);
220
+ if (inputs.collateralIndex >= BigInt(collaterals.length)) {
221
+ throw new error_js_1.InvalidTransactionPlanError({
222
+ path: `${inputsPath}.collateralIndex`,
223
+ reason: "expected an index configured in the market",
224
+ });
225
+ }
226
+ // Midnight never consumes a signature reference.
227
+ (0, authorization_js_1.validateSignaturelessMidnightAction)(action, path);
228
+ }
@@ -0,0 +1,142 @@
1
+ import { type AccrualPosition, type Market } from "@morpho-org/midnight-sdk";
2
+ import type { Address, Client } from "viem";
3
+ import type { MidnightCollateralTransfer, ReferenceTimestampParams } from "../../types/index.js";
4
+ import { type IntentParams } from "../intent.js";
5
+ import type { Action, TransactionPlan } from "../types.js";
6
+ type WithdrawCollateralBatchAction = Extract<Action, {
7
+ type: "midnightWithdrawCollateralBatch";
8
+ }>;
9
+ /**
10
+ * Represents an intent to withdraw several collaterals atomically from the submitting account's
11
+ * Midnight position.
12
+ * @example
13
+ * ```ts
14
+ * import type { MidnightWithdrawCollateralBatchPlanParams } from "@morpho-org/morpho-sdk";
15
+ * import { maxUint256 } from "viem";
16
+ * const withdrawBoth = (params: MidnightWithdrawCollateralBatchPlanParams) => ({
17
+ * ...params,
18
+ * collateralWithdrawals: [
19
+ * { collateralIndex: 0n, assets: maxUint256 },
20
+ * { collateralIndex: 1n, assets: maxUint256 },
21
+ * ],
22
+ * });
23
+ * ```
24
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
25
+ */
26
+ export interface MidnightWithdrawCollateralBatchPlanParams extends Pick<IntentParams, "chainId" | "account" | "expiresAt" | "calldataOrigin">, ReferenceTimestampParams {
27
+ /** Hydrated market snapshot from the same block as `positionData`. */
28
+ readonly marketData: Market;
29
+ /** Position snapshot for the same market, owned by the submitting account. */
30
+ readonly positionData: AccrualPosition;
31
+ /**
32
+ * Raw values from `price()` on each `marketData.params.collateralParams[i].oracle`,
33
+ * indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE` (1e36).
34
+ * Use prices from the snapshot block. No prices are needed when the snapshot has no debt.
35
+ */
36
+ readonly collateralPrices: readonly bigint[];
37
+ /**
38
+ * Nonempty ordered withdrawals with unique `collateralIndex` values in Midnight's
39
+ * token-address order. Amounts are in that token's base units; `maxUint256` withdraws the
40
+ * snapshot balance at that index.
41
+ */
42
+ readonly collateralWithdrawals: readonly MidnightCollateralTransfer[];
43
+ /** Shared recipient of every withdrawal; defaults to `account`. */
44
+ readonly receiver?: Address;
45
+ }
46
+ /**
47
+ * Prepares ordered collateral withdrawals in one direct Midnight core multicall, even for one
48
+ * entry. Inputs go through `parseMidnightWithdrawCollateralBatchPreparation`, the parse-once
49
+ * constructor the entity `withdrawCollateralBatch` uses, in the same order: the position is bound
50
+ * to the sender and market, every index is resolved, and each `maxUint256` becomes that index's
51
+ * snapshot balance before the receiver, amount and encoding checks. Duplicate indexes are
52
+ * rejected, unlike bundle flows which sum them. The withdrawals are then applied to the snapshot
53
+ * balances in order and, when the snapshot has debt, the remaining collateral must cover it at
54
+ * LLTV minus `DEFAULT_LLTV_BUFFER`. Restoring and building offline does not refresh those checks;
55
+ * simulate against current state before sending.
56
+ *
57
+ * The account sends the multicall itself, so the plan has no approvals, authorizations or
58
+ * signature requests. Expiry is checked during preparation only; it is not an onchain deadline.
59
+ * @param client - Viem client used to check the network and the Midnight core deployment.
60
+ * @param params - Market and position snapshots, ordered withdrawals and optional receiver.
61
+ * @param params.chainId - EIP-155 chain ID of the market and submitting client.
62
+ * @param params.account - Nonzero position owner who sends the multicall.
63
+ * @param params.marketData - Hydrated market snapshot from the same block as `positionData`.
64
+ * @param params.positionData - Position snapshot for the same market, owned by `account`.
65
+ * @param params.collateralPrices - Raw `price()` values from each collateral oracle at the snapshot
66
+ * block, indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE` (1e36). Not
67
+ * needed when the snapshot has no debt.
68
+ * @param params.collateralWithdrawals - Nonempty ordered withdrawals, one per collateral index;
69
+ * `maxUint256` withdraws the snapshot balance at that index.
70
+ * @param params.receiver - Optional recipient of every withdrawal; defaults to `account`. Midnight
71
+ * and market token contracts are rejected.
72
+ * @param params.now - Reference Unix timestamp in seconds, normally the snapshot block's timestamp;
73
+ * omitting it uses the device clock (an untyped JavaScript `null` does too).
74
+ * @param params.expiresAt - Plan expiry in Unix seconds; defaults to two hours after `now`. Midnight does not enforce it onchain.
75
+ * @param params.calldataOrigin - Optional attribution bytes appended to the built transaction.
76
+ * @returns A frozen plan with one multicall step and no approvals, authorizations or signature requests.
77
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now`, a withdrawal's `collateralIndex` or `assets`, or a supplied collateral price is not a bigint; checked before any request.
78
+ * @throws {ZeroAccountError} If the account is the zero address.
79
+ * @throws {NonIntegerInputError} If expiry is not a safe integer.
80
+ * @throws {ExpiredDeadlineError} If expiry is at or before the reference time.
81
+ * @throws {InvalidCalldataOriginError} If attribution bytes are empty or malformed.
82
+ * @throws {InvalidTransactionPlanError} If the account is malformed, attribution exceeds 1 MiB, the withdrawals or `collateralPrices` are not an array, or an entry is not an object.
83
+ * @throws {ChainIdMismatchError} If the market, client or RPC targets another chain.
84
+ * @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
85
+ * @throws {InvalidMarketParameterError} If the market configuration is invalid.
86
+ * @throws {MarketIdMismatchError} If the position belongs to another market.
87
+ * @throws {AccrualPositionUserMismatchError} If the position is owned by another account.
88
+ * @throws {EmptyMidnightCollateralWithdrawalsError} If the list is empty.
89
+ * @throws {DuplicateMidnightCollateralIndexError} If an index repeats.
90
+ * @throws {UnknownCollateralIndexError} If an index is not configured on the market.
91
+ * @throws {NonPositiveInputError} If expiry or a resolved amount is not positive.
92
+ * @throws {InputExceedsMaxError} If a resolved amount exceeds uint128.
93
+ * @throws {MidnightZeroReceiverError} If the receiver is the zero address.
94
+ * @throws {MidnightContractReceiverError} If the receiver is a blocked protocol or market token contract.
95
+ * @throws {MidnightCalldataEncodingError} If a market, position owner or receiver address is malformed, or calldata cannot be encoded.
96
+ * @throws {WithdrawExceedsCollateralError} If a withdrawal exceeds the snapshot balance at its index.
97
+ * @throws {MissingMarketPriceError} If remaining collateral has no price for the health check.
98
+ * @throws {WithdrawMakesPositionUnhealthyError} If the snapshot debt exceeds the remaining buffered capacity.
99
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
100
+ * @throws {UnknownAddressError} If Midnight core is not registered on the chain.
101
+ * @throws {MissingContractCodeError} If the registered Midnight core has no deployed code.
102
+ * @throws {viem.BaseError} If the `eth_chainId` or bytecode request fails.
103
+ * @example
104
+ * ```ts
105
+ * import {
106
+ * buildTransactions,
107
+ * prepareMidnightWithdrawCollateralBatch,
108
+ * type TransactionPlan,
109
+ * } from "@morpho-org/morpho-sdk";
110
+ * import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
111
+ * import { type Address, type Hash, createPublicClient, http, maxUint256 } from "viem";
112
+ * import { base } from "viem/chains";
113
+ *
114
+ * // A full exit of a debt-free position that holds both collaterals; an empty index throws.
115
+ * async function prepareCollateralExit(account: Address, marketId: Hash) {
116
+ * const client = createPublicClient({ chain: base, transport: http() });
117
+ * const block = await client.getBlock();
118
+ * const positionData = await fetchMidnightAccrualPosition(client, {
119
+ * marketId, user: account, blockNumber: block.number,
120
+ * });
121
+ * const plan: TransactionPlan = await prepareMidnightWithdrawCollateralBatch(client, {
122
+ * chainId: base.id, account, marketData: positionData.market, positionData,
123
+ * collateralPrices: [], // No price check is needed without debt.
124
+ * now: block.timestamp,
125
+ * collateralWithdrawals: [
126
+ * { collateralIndex: 0n, assets: maxUint256 },
127
+ * { collateralIndex: 1n, assets: maxUint256 },
128
+ * ],
129
+ * });
130
+ * // plan.steps: a single "midnightWithdrawCollateralBatch" step; plan.signatureRequests is empty.
131
+ * // Simulate, then send from plan.account on plan.chainId.
132
+ * return buildTransactions(plan);
133
+ * }
134
+ * ```
135
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
136
+ */
137
+ export declare function prepareMidnightWithdrawCollateralBatch(client: Client, params: MidnightWithdrawCollateralBatchPlanParams): Promise<TransactionPlan>;
138
+ /** @internal Encodes the stored direct withdrawal batch without retaining the snapshot. */
139
+ export declare function buildMidnightWithdrawCollateralBatch({ inputs, }: WithdrawCollateralBatchAction): Readonly<import("../../index.js").Transaction<import("../../index.js").MidnightWithdrawCollateralBatchAction>>;
140
+ /** @internal Validates the stored Midnight collateral withdrawal batch without RPC. */
141
+ export declare function validateMidnightWithdrawCollateralBatchPlanAction(action: Record<string, unknown>, path: string): void;
142
+ export {};
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareMidnightWithdrawCollateralBatch = prepareMidnightWithdrawCollateralBatch;
4
+ exports.buildMidnightWithdrawCollateralBatch = buildMidnightWithdrawCollateralBatch;
5
+ exports.validateMidnightWithdrawCollateralBatchPlanAction = validateMidnightWithdrawCollateralBatchPlanAction;
6
+ const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
7
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
8
+ const parseCollateralBatch_js_1 = require("../../actions/midnight/parseCollateralBatch.js");
9
+ const withdrawCollateralBatch_js_1 = require("../../actions/midnight/withdrawCollateralBatch.js");
10
+ const chainCheck_js_1 = require("../../actions/requirements/chainCheck.js");
11
+ const assertContractCode_js_1 = require("../../entities/requirements/assertContractCode.js");
12
+ const computeMidnightPostWithdrawalCollateral_js_1 = require("../../helpers/computeMidnightPostWithdrawalCollateral.js");
13
+ const validate_js_1 = require("../../helpers/validate.js");
14
+ const error_js_1 = require("../error.js");
15
+ const intent_js_1 = require("../intent.js");
16
+ const validation_js_1 = require("../validation.js");
17
+ const authorization_js_1 = require("./authorization.js");
18
+ const market_js_1 = require("./market.js");
19
+ const validation_js_2 = require("./validation.js");
20
+ const actionId = "midnightWithdrawCollateralBatch";
21
+ /**
22
+ * Prepares ordered collateral withdrawals in one direct Midnight core multicall, even for one
23
+ * entry. Inputs go through `parseMidnightWithdrawCollateralBatchPreparation`, the parse-once
24
+ * constructor the entity `withdrawCollateralBatch` uses, in the same order: the position is bound
25
+ * to the sender and market, every index is resolved, and each `maxUint256` becomes that index's
26
+ * snapshot balance before the receiver, amount and encoding checks. Duplicate indexes are
27
+ * rejected, unlike bundle flows which sum them. The withdrawals are then applied to the snapshot
28
+ * balances in order and, when the snapshot has debt, the remaining collateral must cover it at
29
+ * LLTV minus `DEFAULT_LLTV_BUFFER`. Restoring and building offline does not refresh those checks;
30
+ * simulate against current state before sending.
31
+ *
32
+ * The account sends the multicall itself, so the plan has no approvals, authorizations or
33
+ * signature requests. Expiry is checked during preparation only; it is not an onchain deadline.
34
+ * @param client - Viem client used to check the network and the Midnight core deployment.
35
+ * @param params - Market and position snapshots, ordered withdrawals and optional receiver.
36
+ * @param params.chainId - EIP-155 chain ID of the market and submitting client.
37
+ * @param params.account - Nonzero position owner who sends the multicall.
38
+ * @param params.marketData - Hydrated market snapshot from the same block as `positionData`.
39
+ * @param params.positionData - Position snapshot for the same market, owned by `account`.
40
+ * @param params.collateralPrices - Raw `price()` values from each collateral oracle at the snapshot
41
+ * block, indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE` (1e36). Not
42
+ * needed when the snapshot has no debt.
43
+ * @param params.collateralWithdrawals - Nonempty ordered withdrawals, one per collateral index;
44
+ * `maxUint256` withdraws the snapshot balance at that index.
45
+ * @param params.receiver - Optional recipient of every withdrawal; defaults to `account`. Midnight
46
+ * and market token contracts are rejected.
47
+ * @param params.now - Reference Unix timestamp in seconds, normally the snapshot block's timestamp;
48
+ * omitting it uses the device clock (an untyped JavaScript `null` does too).
49
+ * @param params.expiresAt - Plan expiry in Unix seconds; defaults to two hours after `now`. Midnight does not enforce it onchain.
50
+ * @param params.calldataOrigin - Optional attribution bytes appended to the built transaction.
51
+ * @returns A frozen plan with one multicall step and no approvals, authorizations or signature requests.
52
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now`, a withdrawal's `collateralIndex` or `assets`, or a supplied collateral price is not a bigint; checked before any request.
53
+ * @throws {ZeroAccountError} If the account is the zero address.
54
+ * @throws {NonIntegerInputError} If expiry is not a safe integer.
55
+ * @throws {ExpiredDeadlineError} If expiry is at or before the reference time.
56
+ * @throws {InvalidCalldataOriginError} If attribution bytes are empty or malformed.
57
+ * @throws {InvalidTransactionPlanError} If the account is malformed, attribution exceeds 1 MiB, the withdrawals or `collateralPrices` are not an array, or an entry is not an object.
58
+ * @throws {ChainIdMismatchError} If the market, client or RPC targets another chain.
59
+ * @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
60
+ * @throws {InvalidMarketParameterError} If the market configuration is invalid.
61
+ * @throws {MarketIdMismatchError} If the position belongs to another market.
62
+ * @throws {AccrualPositionUserMismatchError} If the position is owned by another account.
63
+ * @throws {EmptyMidnightCollateralWithdrawalsError} If the list is empty.
64
+ * @throws {DuplicateMidnightCollateralIndexError} If an index repeats.
65
+ * @throws {UnknownCollateralIndexError} If an index is not configured on the market.
66
+ * @throws {NonPositiveInputError} If expiry or a resolved amount is not positive.
67
+ * @throws {InputExceedsMaxError} If a resolved amount exceeds uint128.
68
+ * @throws {MidnightZeroReceiverError} If the receiver is the zero address.
69
+ * @throws {MidnightContractReceiverError} If the receiver is a blocked protocol or market token contract.
70
+ * @throws {MidnightCalldataEncodingError} If a market, position owner or receiver address is malformed, or calldata cannot be encoded.
71
+ * @throws {WithdrawExceedsCollateralError} If a withdrawal exceeds the snapshot balance at its index.
72
+ * @throws {MissingMarketPriceError} If remaining collateral has no price for the health check.
73
+ * @throws {WithdrawMakesPositionUnhealthyError} If the snapshot debt exceeds the remaining buffered capacity.
74
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
75
+ * @throws {UnknownAddressError} If Midnight core is not registered on the chain.
76
+ * @throws {MissingContractCodeError} If the registered Midnight core has no deployed code.
77
+ * @throws {viem.BaseError} If the `eth_chainId` or bytecode request fails.
78
+ * @example
79
+ * ```ts
80
+ * import {
81
+ * buildTransactions,
82
+ * prepareMidnightWithdrawCollateralBatch,
83
+ * type TransactionPlan,
84
+ * } from "@morpho-org/morpho-sdk";
85
+ * import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
86
+ * import { type Address, type Hash, createPublicClient, http, maxUint256 } from "viem";
87
+ * import { base } from "viem/chains";
88
+ *
89
+ * // A full exit of a debt-free position that holds both collaterals; an empty index throws.
90
+ * async function prepareCollateralExit(account: Address, marketId: Hash) {
91
+ * const client = createPublicClient({ chain: base, transport: http() });
92
+ * const block = await client.getBlock();
93
+ * const positionData = await fetchMidnightAccrualPosition(client, {
94
+ * marketId, user: account, blockNumber: block.number,
95
+ * });
96
+ * const plan: TransactionPlan = await prepareMidnightWithdrawCollateralBatch(client, {
97
+ * chainId: base.id, account, marketData: positionData.market, positionData,
98
+ * collateralPrices: [], // No price check is needed without debt.
99
+ * now: block.timestamp,
100
+ * collateralWithdrawals: [
101
+ * { collateralIndex: 0n, assets: maxUint256 },
102
+ * { collateralIndex: 1n, assets: maxUint256 },
103
+ * ],
104
+ * });
105
+ * // plan.steps: a single "midnightWithdrawCollateralBatch" step; plan.signatureRequests is empty.
106
+ * // Simulate, then send from plan.account on plan.chainId.
107
+ * return buildTransactions(plan);
108
+ * }
109
+ * ```
110
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
111
+ */
112
+ async function prepareMidnightWithdrawCollateralBatch(client, params) {
113
+ const { account, chainId, marketData, positionData } = params;
114
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
115
+ (0, validate_js_1.validateReferenceTime)(now);
116
+ const { expiresAt, calldataOrigin } = (0, intent_js_1.resolveIntent)({
117
+ account,
118
+ chainId,
119
+ expiresAt: params.expiresAt,
120
+ calldataOrigin: params.calldataOrigin,
121
+ }, now);
122
+ const { collateralWithdrawals } = params;
123
+ (0, market_js_1.validateCollateralTransferInputs)("collateralWithdrawals", collateralWithdrawals);
124
+ (0, market_js_1.validateCollateralPriceTypes)(params.collateralPrices);
125
+ const parsed = (0, parseCollateralBatch_js_1.parseMidnightWithdrawCollateralBatchPreparation)({
126
+ chainId,
127
+ accountAddress: account,
128
+ marketData,
129
+ positionData,
130
+ collateralPrices: params.collateralPrices,
131
+ collateralWithdrawals,
132
+ receiver: params.receiver,
133
+ });
134
+ const { postCollateral, withdrawAmount } = (0, computeMidnightPostWithdrawalCollateral_js_1.computeMidnightPostWithdrawalCollateral)({
135
+ market: marketData.params,
136
+ marketId: marketData.id,
137
+ collateral: positionData.collateral,
138
+ withdrawals: parsed.collateralWithdrawals,
139
+ });
140
+ (0, validate_js_1.validateMidnightWithdrawHealth)({
141
+ market: marketData,
142
+ collateral: postCollateral,
143
+ collateralPrices: params.collateralPrices,
144
+ debt: positionData.debt,
145
+ withdrawAmount,
146
+ });
147
+ // Store the tuple the checks above used, not one read again after the awaits below.
148
+ const market = midnight_sdk_1.MarketUtils.toStruct(marketData.params);
149
+ const chainCheck = (0, chainCheck_js_1.createChainCheck)(client, chainId);
150
+ await chainCheck();
151
+ // A code-less core would accept the multicall as a silent no-op.
152
+ await (0, assertContractCode_js_1.assertRegistryTargetsHaveCode)(client, chainId, [{ role: "midnight", address: (0, morpho_ts_1.getChainAddress)(chainId, "midnight") }], chainCheck);
153
+ return (0, morpho_ts_1.deepFreeze)({
154
+ version: 2,
155
+ chainId,
156
+ account,
157
+ expiresAt,
158
+ ...(calldataOrigin && { calldataOrigin }),
159
+ steps: [
160
+ {
161
+ id: actionId,
162
+ label: "Withdraw Midnight collateral batch",
163
+ action: {
164
+ type: actionId,
165
+ inputs: {
166
+ account,
167
+ chainId,
168
+ market,
169
+ collateralWithdrawals: parsed.collateralWithdrawals.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
170
+ receiver: parsed.receiver,
171
+ },
172
+ },
173
+ },
174
+ ],
175
+ signatureRequests: [],
176
+ });
177
+ }
178
+ /** @internal Encodes the stored direct withdrawal batch without retaining the snapshot. */
179
+ function buildMidnightWithdrawCollateralBatch({ inputs, }) {
180
+ const { account, chainId, market, collateralWithdrawals, receiver } = inputs;
181
+ // A directly built step skips restore, so check each entry's shape and index type here.
182
+ (0, market_js_1.validateCollateralTransferInputs)("inputs.collateralWithdrawals", collateralWithdrawals);
183
+ (0, market_js_1.validateStoredCollateralOrder)(market.collateralParams, "$.inputs.market.collateralParams");
184
+ return (0, withdrawCollateralBatch_js_1.midnightWithdrawCollateralBatch)({
185
+ chainId,
186
+ market: (0, market_js_1.storedMarketTuple)(market),
187
+ collateralWithdrawals,
188
+ onBehalf: account,
189
+ receiver,
190
+ });
191
+ }
192
+ /** @internal Validates the stored Midnight collateral withdrawal batch without RPC. */
193
+ function validateMidnightWithdrawCollateralBatchPlanAction(action, path) {
194
+ const inputsPath = `${path}.inputs`;
195
+ const inputs = (0, validation_js_1.getPlanObject)(action.inputs, inputsPath);
196
+ (0, validation_js_1.validatePlanFields)(inputs, {
197
+ path: inputsPath,
198
+ fields: { receiver: "address" },
199
+ });
200
+ const marketPath = `${inputsPath}.market`;
201
+ const market = (0, validation_js_1.getPlanObject)(inputs.market, marketPath);
202
+ // Validate the tuple before reading its collateral tokens.
203
+ (0, validation_js_2.validateStoredMidnightMarket)(market, {
204
+ path: marketPath,
205
+ chainId: inputs.chainId,
206
+ });
207
+ const collaterals = market.collateralParams;
208
+ (0, market_js_1.validateStoredCollateralOrder)(collaterals, `${marketPath}.collateralParams`);
209
+ const withdrawalsPath = `${inputsPath}.collateralWithdrawals`;
210
+ if (!Array.isArray(inputs.collateralWithdrawals)) {
211
+ throw new error_js_1.InvalidTransactionPlanError({
212
+ path: withdrawalsPath,
213
+ reason: "expected an array",
214
+ });
215
+ }
216
+ for (const [index, withdrawal] of inputs.collateralWithdrawals.entries()) {
217
+ const itemPath = `${withdrawalsPath}[${index}]`;
218
+ const item = (0, validation_js_1.getPlanObject)(withdrawal, itemPath);
219
+ (0, validation_js_1.validatePlanFields)(item, {
220
+ path: itemPath,
221
+ fields: { collateralIndex: "uint256 bigint", assets: "uint128 bigint" },
222
+ });
223
+ if (item.collateralIndex >= BigInt(collaterals.length)) {
224
+ throw new error_js_1.InvalidTransactionPlanError({
225
+ path: `${itemPath}.collateralIndex`,
226
+ reason: "expected an index configured in the market",
227
+ });
228
+ }
229
+ }
230
+ // Midnight never consumes a signature reference.
231
+ (0, authorization_js_1.validateSignaturelessMidnightAction)(action, path);
232
+ }