@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,440 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareMidnightTakeRepayWithdrawCollateral = prepareMidnightTakeRepayWithdrawCollateral;
4
+ exports.buildMidnightTakeRepayWithdrawCollateral = buildMidnightTakeRepayWithdrawCollateral;
5
+ exports.validateMidnightTakeRepayWithdrawCollateralPlanAction = validateMidnightTakeRepayWithdrawCollateralPlanAction;
6
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
+ const takeRepayWithdrawCollateral_js_1 = require("../../actions/midnight/takeRepayWithdrawCollateral.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 constant_js_1 = require("../../helpers/constant.js");
12
+ const parseMidnight_js_1 = require("../../helpers/parseMidnight.js");
13
+ const validate_js_1 = require("../../helpers/validate.js");
14
+ const validateMidnightTakeableOfferFields_js_1 = require("../../helpers/validateMidnightTakeableOfferFields.js");
15
+ const validateMidnightTakeFeasibility_js_1 = require("../../helpers/validateMidnightTakeFeasibility.js");
16
+ const error_js_1 = require("../../types/error.js");
17
+ const error_js_2 = require("../error.js");
18
+ const intent_js_1 = require("../intent.js");
19
+ const requirements_js_1 = require("../requirements.js");
20
+ const validation_js_1 = require("../validation.js");
21
+ const authorization_js_1 = require("./authorization.js");
22
+ const market_js_1 = require("./market.js");
23
+ const validation_js_2 = require("./validation.js");
24
+ const actionId = "midnightTakeRepayWithdrawCollateral";
25
+ /**
26
+ * Checks a Midnight repayment through borrow offers and its collateral withdrawals
27
+ * against the position snapshot: each withdrawal against the remaining collateral, then, when
28
+ * collateral is withdrawn, the debt left after the target's guaranteed reduction (`units`, or
29
+ * `minUnits` for an assets target) against the remaining collateral's buffered capacity. Runs the
30
+ * same checks as the entity's inline ones; callers parse the withdrawals first.
31
+ * @throws {WithdrawExceedsCollateralError} If a withdrawal exceeds the remaining collateral.
32
+ * @throws {MissingMarketPriceError} If remaining collateral has no price for the health check.
33
+ * @throws {WithdrawMakesPositionUnhealthyError} If the remaining debt exceeds buffered capacity.
34
+ */
35
+ const validateTakeRepayWithdrawCollateralPosition = (params) => {
36
+ const { marketData, positionData, target, collateralWithdrawals } = params;
37
+ const { postCollateral, withdrawAmount } = (0, computeMidnightPostWithdrawalCollateral_js_1.computeMidnightPostWithdrawalCollateral)({
38
+ market: marketData.params,
39
+ marketId: marketData.id,
40
+ collateral: positionData.collateral,
41
+ withdrawals: collateralWithdrawals,
42
+ });
43
+ if (collateralWithdrawals.length === 0) {
44
+ return;
45
+ }
46
+ const debtReduction = target.type === "units" ? target.units : target.minUnits;
47
+ (0, validate_js_1.validateMidnightWithdrawHealth)({
48
+ market: marketData,
49
+ collateral: postCollateral,
50
+ collateralPrices: params.collateralPrices,
51
+ debt: debtReduction >= positionData.debt
52
+ ? 0n
53
+ : positionData.debt - debtReduction,
54
+ withdrawAmount,
55
+ });
56
+ };
57
+ /**
58
+ * Prepares a reduce-only buy on MidnightBundlesV2. The bundle fills borrow offers,
59
+ * repays the unfilled remainder at par if enabled, then withdraws collateral.
60
+ * The collateral receiver defaults to the submitting account. Validates inputs with the same
61
+ * parse-once constructor, position binding, buffered post-withdrawal health check and fill
62
+ * feasibility check as the entity `takeRepayWithdrawCollateral`, including its buy-budget bound:
63
+ * a units target's `maxBuyerAssets` must cover the units at the cheapest live price, and an
64
+ * assets target has no budget check. Offers whose price conversion fails throughout the plan
65
+ * window are dropped from the stored fills; an offer that converts only at a later fee can still
66
+ * revert the bundle if sent earlier. Preparation does not see live cancellations either, so
67
+ * simulate before sending to catch these price-conversion reverts and cancelled or consumed
68
+ * offers. Native funding still requires allowance for the full
69
+ * wrapped-native pull.
70
+ * @param client - Viem client used to check the chain and deployments and read prerequisites.
71
+ * @param params - Borrower, snapshots, buy target, quote, optional withdrawals and intent.
72
+ * @param params.chainId - Chain containing the market and MidnightBundlesV2.
73
+ * @param params.account - Non-zero borrower whose debt is repaid; it funds the repayment and sends the plan.
74
+ * @param params.marketData - Hydrated market snapshot used for fill feasibility and collateral capacity.
75
+ * @param params.positionData - Borrower's position snapshot for the same market.
76
+ * @param params.collateralPrices - Oracle prices indexed by market collateral, scaled by `ORACLE_PRICE_SCALE`.
77
+ * @param params.takeableOffers - ABI-ready borrow offers from the caller's quote, in fill order.
78
+ * @param params.target.type - `"assets"` to pay exact loan assets, or `"units"` to buy exact units.
79
+ * @param params.target.assets - Loan assets paid on an assets target, referral fee included.
80
+ * @param params.target.minUnits - Unit floor on an assets target.
81
+ * @param params.target.units - Exact units bought on a units target; `maxUint256` targets the account's whole debt.
82
+ * @param params.target.maxBuyerAssets - Loan-asset cap pulled on a units target, referral fee included; the unused remainder is returned.
83
+ * @param params.repayEnabled - Whether the bundle repays the unfilled remainder directly to Midnight.
84
+ * @param params.maxContinuousFee - Largest market continuous fee accepted when taking offers; pass `maxUint256` for no cap.
85
+ * @param params.nativeAmount - Optional native ETH in wei for a wrapped-native loan, capped by the pull.
86
+ * @param params.collateralWithdrawals - Optional withdrawals after the repayment; defaults to none. Each
87
+ * `collateralIndex` indexes `marketData.params.collateralParams`, and `assets` is in that token's base units;
88
+ * `maxUint256` withdraws the account's whole balance of that collateral.
89
+ * @param params.collateralReceiver - Optional recipient of withdrawn collateral; defaults to `account`.
90
+ * @param params.referralFee.bps - Optional referral fee in integer basis points, at most 10%.
91
+ * @param params.referralFee.recipient - Recipient required for a positive referral fee.
92
+ * @param params.now - Reference Unix timestamp in seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
93
+ * @param params.expiresAt - Onchain deadline in Unix seconds; defaults to, and may not exceed, one hour after `now`.
94
+ * @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
95
+ * @returns A frozen plan with any needed approval and standalone authorization, without signatures.
96
+ * @throws {InvalidBigIntInputError} when a supplied non-null `now`, `maxContinuousFee`, a target amount, or a withdrawal's collateral index or amount is not a bigint; checked before any request.
97
+ * @throws {ZeroAccountError} when the sender is the zero address.
98
+ * @throws {InvalidTransactionPlanError} when the sender address, attribution length, target discriminator or `repayEnabled` flag is invalid.
99
+ * @throws {InvalidMidnightNativeAmountTypeError} when `nativeAmount` is supplied as a non-bigint.
100
+ * @throws {NonIntegerInputError} when expiry or referral fee basis points are not safe integers.
101
+ * @throws {NonPositiveInputError} when expiry, a target amount or bound, or a withdrawal amount is nonpositive.
102
+ * @throws {ExpiredDeadlineError} when expiry is at or before the reference timestamp.
103
+ * @throws {NegativeInputError} when the referral fee, offer cap, continuous fee cap or native amount is negative.
104
+ * @throws {InputExceedsMaxError} when referral fee basis points exceed 1,000 (10%), an amount or cap exceeds its
105
+ * bound, or native funding exceeds the pull.
106
+ * @throws {InvalidCalldataOriginError} when attribution bytes are empty or malformed.
107
+ * @throws {MidnightTakeDeadlineTooFarError} when expiry is more than one hour away.
108
+ * @throws {ChainIdMismatchError} when the market, configured client or transport is on another chain.
109
+ * @throws {UnsupportedChainIdError} when the chain is not registered.
110
+ * @throws {UnknownAddressError} when a required Midnight deployment is not registered on the chain.
111
+ * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
112
+ * @throws {InvalidMarketParameterError} when the market configuration is invalid.
113
+ * @throws {UnknownCollateralIndexError} when a withdrawal targets an unconfigured collateral index.
114
+ * @throws {MidnightCalldataEncodingError} when an address is malformed or calldata cannot be encoded.
115
+ * @throws {MidnightZeroReceiverError} when withdrawn collateral is sent to the zero address.
116
+ * @throws {MidnightContractReceiverError} when withdrawn collateral or a positive referral fee is sent to a blocked contract.
117
+ * @throws {EmptyMidnightTakeableOffersError} when the quote is empty.
118
+ * @throws {MidnightOfferSideMismatchError} when an offer is not a borrow offer.
119
+ * @throws {MidnightTakeableOfferMarketMismatchError} when an offer trades another market.
120
+ * @throws {MidnightTakeableOfferZeroSellerReceiverError} when an offer sends seller proceeds to the zero address.
121
+ * @throws {UnboundedMidnightTakeInputError} when the bundle deadline is `maxUint256`.
122
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
123
+ * @throws {ChainWNativeMissingError} when native funding is requested without a registered wrapped-native token.
124
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding is requested for a different loan token.
125
+ * @throws {MarketIdMismatchError} when the position belongs to another market.
126
+ * @throws {AccrualPositionUserMismatchError} when another account owns the position.
127
+ * @throws {WithdrawExceedsCollateralError} when withdrawals exceed the collateral balance.
128
+ * @throws {MissingMarketPriceError} when the health check needs a missing oracle price.
129
+ * @throws {WithdrawMakesPositionUnhealthyError} when remaining debt exceeds buffered collateral capacity.
130
+ * @throws {MidnightContinuousFeeAboveMaxError} when the market's continuous fee exceeds the caller's cap.
131
+ * @throws {MidnightRepayExceedsDebtError} when the target exceeds the snapshot debt.
132
+ * @throws {MidnightTakeableOffersNotFillableError} when the supplied offers cannot be used.
133
+ * @throws {MidnightTakeTargetUnreachableError} when the target cannot be met within its bounds.
134
+ * @throws {viem.BaseError} when a chain, bytecode, allowance or authorization read fails.
135
+ * @throws {MissingContractCodeError} when a registered Midnight target has no code.
136
+ * @example
137
+ * ```ts
138
+ * import {
139
+ * buildTransactions,
140
+ * prepareMidnightTakeRepayWithdrawCollateral,
141
+ * type MidnightTakeRepayWithdrawCollateralPlanParams,
142
+ * } from "@morpho-org/morpho-sdk";
143
+ * import { blueOracleAbi } from "@morpho-org/morpho-sdk/abis";
144
+ * import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
145
+ * import { MidnightApi } from "@morpho-org/morpho-sdk/midnight-api";
146
+ *
147
+ * type SnapshotParams = Parameters<typeof fetchMidnightAccrualPosition>[1];
148
+ * type PublicClient = Parameters<typeof fetchMidnightAccrualPosition>[0] & {
149
+ * getBlock(): Promise<{ number: bigint; timestamp: bigint }>;
150
+ * readContract(params: {
151
+ * address: SnapshotParams["user"];
152
+ * abi: typeof blueOracleAbi;
153
+ * functionName: "price";
154
+ * blockNumber: bigint;
155
+ * }): Promise<bigint>;
156
+ * };
157
+ *
158
+ * async function prepareRepayment(
159
+ * client: PublicClient,
160
+ * marketId: SnapshotParams["marketId"],
161
+ * params: Pick<MidnightTakeRepayWithdrawCollateralPlanParams,
162
+ * "chainId" | "account" | "maxContinuousFee" | "collateralWithdrawals">,
163
+ * assets: bigint,
164
+ * minUnits: bigint,
165
+ * ) {
166
+ * const block = await client.getBlock();
167
+ * const positionData = await fetchMidnightAccrualPosition(client, {
168
+ * marketId, user: params.account, blockNumber: block.number,
169
+ * });
170
+ * const marketData = positionData.market;
171
+ * const collateralPrices = await Promise.all(
172
+ * marketData.params.collateralParams.map(({ oracle }) =>
173
+ * client.readContract({
174
+ * address: oracle, abi: blueOracleAbi, functionName: "price", blockNumber: block.number,
175
+ * }),
176
+ * ),
177
+ * );
178
+ * const quote = await new MidnightApi().fetchBookQuote({
179
+ * marketId, side: "asks", assets, taker: params.account,
180
+ * });
181
+ * const plan = await prepareMidnightTakeRepayWithdrawCollateral(client, {
182
+ * ...params, marketData, positionData, collateralPrices, now: block.timestamp,
183
+ * target: { type: "assets", assets, minUnits },
184
+ * takeableOffers: quote.data.takeableOffers,
185
+ * repayEnabled: true,
186
+ * });
187
+ * // Simulate, then send in order from plan.account on plan.chainId.
188
+ * return buildTransactions(plan);
189
+ * }
190
+ * ```
191
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
192
+ */
193
+ async function prepareMidnightTakeRepayWithdrawCollateral(client, params) {
194
+ const { chainId, account, marketData, positionData, target, nativeAmount } = params;
195
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
196
+ // Reject a non-bigint clock before the bigint deadline sum can throw a generic TypeError.
197
+ (0, validate_js_1.validateReferenceTime)(now);
198
+ const maxDeadline = now + constant_js_1.MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
199
+ const intent = (0, intent_js_1.resolveIntent)({ ...params, expiresAt: params.expiresAt ?? Number(maxDeadline) }, now);
200
+ if (intent.deadline > maxDeadline) {
201
+ throw new error_js_1.MidnightTakeDeadlineTooFarError({
202
+ deadline: intent.deadline,
203
+ maxDeadline,
204
+ });
205
+ }
206
+ const { type } = (0, validation_js_1.getPlanObject)(target, "$.target");
207
+ if (type !== "assets" && type !== "units") {
208
+ throw invalidTargetType("$.target");
209
+ }
210
+ (0, validation_js_1.validatePlanField)(params.repayEnabled, {
211
+ path: "$.repayEnabled",
212
+ type: "boolean",
213
+ });
214
+ if (typeof params.maxContinuousFee !== "bigint") {
215
+ throw new error_js_1.InvalidBigIntInputError("maxContinuousFee", params.maxContinuousFee);
216
+ }
217
+ (0, validation_js_2.validateMidnightTargetAmountTypes)(target, target.type === "assets"
218
+ ? ["assets", "minUnits"]
219
+ : ["units", "maxBuyerAssets"]);
220
+ const collateralWithdrawals = params.collateralWithdrawals ?? [];
221
+ (0, market_js_1.validateCollateralIndexTypes)("collateralWithdrawals", collateralWithdrawals);
222
+ for (const [index, { assets }] of collateralWithdrawals.entries()) {
223
+ if (typeof assets !== "bigint") {
224
+ throw new error_js_1.InvalidBigIntInputError(`collateralWithdrawals[${index}].assets`, assets);
225
+ }
226
+ }
227
+ const parsed = (0, takeRepayWithdrawCollateral_js_1.parseMidnightTakeRepayWithdrawCollateral)({
228
+ chainId,
229
+ market: marketData.params,
230
+ target,
231
+ takeableOffers: params.takeableOffers,
232
+ repayEnabled: params.repayEnabled,
233
+ nativeAmount,
234
+ collateralWithdrawals,
235
+ collateralReceiver: params.collateralReceiver ?? account,
236
+ maxContinuousFee: params.maxContinuousFee,
237
+ deadline: intent.deadline,
238
+ referralFeePct: intent.referralFeePct,
239
+ referralFeeRecipient: intent.referralFeeRecipient,
240
+ });
241
+ (0, validateMidnightTakeableOfferFields_js_1.validateMidnightTakeableOfferFields)(parsed.takeableOffers);
242
+ const bundle = (0, morpho_ts_1.getChainAddress)(chainId, "midnightBundlesV2");
243
+ (0, parseMidnight_js_1.validateMidnightPositionBinding)({
244
+ positionData,
245
+ accountAddress: account,
246
+ marketData,
247
+ });
248
+ validateTakeRepayWithdrawCollateralPosition({
249
+ marketData,
250
+ positionData,
251
+ collateralPrices: params.collateralPrices,
252
+ target: parsed.target,
253
+ collateralWithdrawals: parsed.collateralWithdrawals,
254
+ });
255
+ const takeableOffers = (0, validateMidnightTakeFeasibility_js_1.validateMidnightTakeFeasibility)({
256
+ side: "buy",
257
+ takeableOffers: parsed.takeableOffers,
258
+ accountAddress: account,
259
+ marketData,
260
+ now,
261
+ deadline: parsed.deadline,
262
+ referralFeePct: parsed.referralFeePct,
263
+ fallbackUnits: parsed.repayEnabled ? positionData.debt : 0n,
264
+ target: parsed.target,
265
+ maxContinuousFee: parsed.maxContinuousFee,
266
+ debt: positionData.debt,
267
+ });
268
+ await assertDeployments(client, chainId);
269
+ const [{ approvals }, authorization] = await Promise.all([
270
+ (0, requirements_js_1.getTokenRequirements)(client, {
271
+ chainId,
272
+ token: parsed.market.loanToken,
273
+ owner: account,
274
+ spender: bundle,
275
+ amount: parsed.target.type === "assets"
276
+ ? parsed.target.assets
277
+ : parsed.target.maxBuyerAssets,
278
+ approvalId: (index) => `${actionId}:approval:${index}`,
279
+ }),
280
+ (0, authorization_js_1.prepareMidnightBundleAuthorization)(client, { chainId, account }),
281
+ ]);
282
+ return (0, morpho_ts_1.deepFreeze)({
283
+ version: 2,
284
+ chainId,
285
+ account,
286
+ expiresAt: intent.expiresAt,
287
+ ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
288
+ steps: [
289
+ ...approvals,
290
+ ...(authorization === undefined ? [] : [authorization]),
291
+ {
292
+ id: actionId,
293
+ label: "Repay Midnight debt through offers",
294
+ action: {
295
+ type: actionId,
296
+ inputs: {
297
+ chainId,
298
+ account,
299
+ market: parsed.market,
300
+ target: parsed.target,
301
+ takeableOffers,
302
+ repayEnabled: parsed.repayEnabled,
303
+ collateralWithdrawals: parsed.collateralWithdrawals,
304
+ collateralReceiver: parsed.collateralReceiver,
305
+ maxContinuousFee: parsed.maxContinuousFee,
306
+ ...(nativeAmount !== undefined && {
307
+ nativeAssets: parsed.nativeFunding.value,
308
+ }),
309
+ deadline: parsed.deadline,
310
+ referralFeePct: parsed.referralFeePct,
311
+ referralFeeRecipient: parsed.referralFeeRecipient,
312
+ },
313
+ },
314
+ },
315
+ ],
316
+ signatureRequests: [],
317
+ });
318
+ }
319
+ async function assertDeployments(client, chainId) {
320
+ const chainCheck = (0, chainCheck_js_1.createChainCheck)(client, chainId);
321
+ await chainCheck();
322
+ // Check deployments before allowance or authorization reads can fail decoding empty data.
323
+ await (0, assertContractCode_js_1.assertRegistryTargetsHaveCode)(client, chainId, [
324
+ {
325
+ role: "midnightBundlesV2",
326
+ address: (0, morpho_ts_1.getChainAddress)(chainId, "midnightBundlesV2"),
327
+ },
328
+ { role: "midnight", address: (0, morpho_ts_1.getChainAddress)(chainId, "midnight") },
329
+ ], chainCheck);
330
+ }
331
+ function invalidTargetType(path) {
332
+ return new error_js_2.InvalidTransactionPlanError({
333
+ path: `${path}.type`,
334
+ reason: "expected assets or units",
335
+ });
336
+ }
337
+ function storedParams(inputs) {
338
+ return {
339
+ chainId: inputs.chainId,
340
+ market: (0, market_js_1.storedMarketTuple)(inputs.market),
341
+ target: inputs.target,
342
+ takeableOffers: (0, market_js_1.storedFills)(inputs.takeableOffers),
343
+ repayEnabled: inputs.repayEnabled,
344
+ collateralWithdrawals: inputs.collateralWithdrawals.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
345
+ collateralReceiver: inputs.collateralReceiver,
346
+ maxContinuousFee: inputs.maxContinuousFee,
347
+ deadline: inputs.deadline,
348
+ referralFeePct: inputs.referralFeePct,
349
+ referralFeeRecipient: inputs.referralFeeRecipient,
350
+ nativeAmount: inputs.nativeAssets,
351
+ };
352
+ }
353
+ /**
354
+ * @internal Encodes the prepared buy and withdrawals from persisted fields alone.
355
+ * @throws {InvalidTransactionPlanError} If the market's collateral tokens are not in strictly
356
+ * ascending address order, or the target is not an object whose type is `assets` or `units`.
357
+ */
358
+ function buildMidnightTakeRepayWithdrawCollateral({ inputs, }) {
359
+ const { type } = (0, validation_js_1.getPlanObject)(inputs.target, "$.inputs.target");
360
+ if (type !== "assets" && type !== "units") {
361
+ throw invalidTargetType("$.inputs.target");
362
+ }
363
+ (0, market_js_1.validateStoredCollateralOrder)(inputs.market.collateralParams, "$.inputs.market.collateralParams");
364
+ return (0, takeRepayWithdrawCollateral_js_1.midnightTakeRepayWithdrawCollateral)(storedParams(inputs));
365
+ }
366
+ /**
367
+ * @internal Validates a stored reduce-only buy recipe without fetching any state: the field
368
+ * shapes and collateral order, then the action's clock-free parse checks on the stored inputs.
369
+ */
370
+ function validateMidnightTakeRepayWithdrawCollateralPlanAction(action, path) {
371
+ const inputsPath = `${path}.inputs`;
372
+ const inputs = (0, validation_js_1.getPlanObject)(action.inputs, inputsPath);
373
+ (0, validation_js_1.validatePlanFields)(inputs, {
374
+ path: inputsPath,
375
+ fields: {
376
+ repayEnabled: "boolean",
377
+ collateralReceiver: "address",
378
+ maxContinuousFee: "uint256 bigint",
379
+ deadline: "uint256 bigint",
380
+ referralFeePct: "uint256 bigint",
381
+ referralFeeRecipient: "address",
382
+ ...(inputs.nativeAssets !== undefined && {
383
+ nativeAssets: "uint256 bigint",
384
+ }),
385
+ },
386
+ });
387
+ const targetPath = `${inputsPath}.target`;
388
+ const target = (0, validation_js_1.getPlanObject)(inputs.target, targetPath);
389
+ switch (target.type) {
390
+ case "assets":
391
+ (0, validation_js_1.validatePlanFields)(target, {
392
+ path: targetPath,
393
+ fields: { assets: "uint256 bigint", minUnits: "uint256 bigint" },
394
+ });
395
+ break;
396
+ case "units":
397
+ (0, validation_js_1.validatePlanFields)(target, {
398
+ path: targetPath,
399
+ fields: { units: "uint256 bigint", maxBuyerAssets: "uint256 bigint" },
400
+ });
401
+ break;
402
+ default:
403
+ throw invalidTargetType(targetPath);
404
+ }
405
+ const withdrawalsPath = `${inputsPath}.collateralWithdrawals`;
406
+ if (!Array.isArray(inputs.collateralWithdrawals)) {
407
+ throw new error_js_2.InvalidTransactionPlanError({
408
+ path: withdrawalsPath,
409
+ reason: "expected an array",
410
+ });
411
+ }
412
+ for (const [index, item] of inputs.collateralWithdrawals.entries()) {
413
+ const itemPath = `${withdrawalsPath}[${index}]`;
414
+ (0, validation_js_1.validatePlanFields)((0, validation_js_1.getPlanObject)(item, itemPath), {
415
+ path: itemPath,
416
+ fields: { collateralIndex: "uint256 bigint", assets: "uint256 bigint" },
417
+ });
418
+ }
419
+ const chainId = inputs.chainId; // Checked by the parse dispatcher.
420
+ (0, validation_js_2.validateStoredMidnightMarket)(inputs.market, {
421
+ path: `${inputsPath}.market`,
422
+ chainId,
423
+ });
424
+ (0, market_js_1.validateStoredCollateralOrder)(inputs.market.collateralParams, `${inputsPath}.market.collateralParams`);
425
+ (0, validation_js_2.validateStoredMidnightFills)(inputs.takeableOffers, {
426
+ path: `${inputsPath}.takeableOffers`,
427
+ chainId,
428
+ });
429
+ (0, authorization_js_1.validateSignaturelessMidnightAction)(action, path);
430
+ try {
431
+ (0, takeRepayWithdrawCollateral_js_1.parseMidnightTakeRepayWithdrawCollateral)(storedParams(action.inputs));
432
+ }
433
+ catch (cause) {
434
+ throw new error_js_2.InvalidTransactionPlanError({
435
+ path: inputsPath,
436
+ reason: "expected a valid Midnight repayment through borrow offers",
437
+ cause,
438
+ });
439
+ }
440
+ }
@@ -0,0 +1,139 @@
1
+ import { AccrualPosition, type Market } from "@morpho-org/midnight-sdk";
2
+ import type { Address, Client } from "viem";
3
+ import { type MidnightTakeWithdrawParams } from "../../actions/midnight/takeWithdraw.js";
4
+ import { type IntentParams } from "../intent.js";
5
+ import type { Action, TransactionPlan } from "../types.js";
6
+ /**
7
+ * Inputs for withdrawing the account's Midnight credit using caller-selected lend offers.
8
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
9
+ */
10
+ export interface MidnightTakeWithdrawPlanParams extends Omit<IntentParams, "supportSignature" | "deployless">, Pick<MidnightTakeWithdrawParams, "target" | "takeableOffers"> {
11
+ /** Market snapshot used to assess liquidity and fill feasibility. */
12
+ readonly marketData: Market;
13
+ /** Owner-bound position snapshot for the same market, read at the same block. */
14
+ readonly positionData: AccrualPosition;
15
+ /** Recipient of the withdrawn loan assets; defaults to account. */
16
+ readonly receiver?: Address;
17
+ /** Reference timestamp in seconds; defaults to the device clock. */
18
+ readonly now?: bigint;
19
+ /** Unix seconds; defaults to one hour after the reference timestamp. */
20
+ readonly expiresAt?: number;
21
+ }
22
+ /**
23
+ * Prepares a reduce-only Midnight withdrawal that redeems available credit at par
24
+ * before selling the rest of the target into lend offers. It cannot open debt.
25
+ * Validates inputs with the same parse-once constructor and fill feasibility check as the
26
+ * entity `takeWithdraw`, checks every taken offer field, binds the position to the account and
27
+ * market, and caps fills at the
28
+ * position's credit accrued to the reference timestamp against `marketData`, the snapshot that
29
+ * caps withdrawable credit. It then reads the registry targets'
30
+ * bytecode and the bundle authorization. On an assets target, offers that would revert the
31
+ * whole bundle are dropped from the stored fills. Like the entity check, fill feasibility counts
32
+ * units at par and does not price discounted bids after settlement fees, so a plan can pass
33
+ * preparation and still revert onchain; the onchain bounds keep funds safe. Simulate before sending.
34
+ * @param client - Viem client used to verify chain, deployments and authorization.
35
+ * @param params - Account, market and position snapshots, fills and intent.
36
+ * @param params.chainId - Chain containing the market and MidnightBundlesV2.
37
+ * @param params.account - Non-zero position owner that sends the plan; its credit is withdrawn.
38
+ * @param params.marketData - Market snapshot used to assess liquidity and fill feasibility.
39
+ * @param params.positionData - Owner-bound position snapshot for the same market, read at the same block.
40
+ * @param params.takeableOffers - ABI-ready lend offers from the caller's quote, in fill order.
41
+ * @param params.target.type - `"assets"` to receive loan assets, or `"units"` to sell exact credit units.
42
+ * @param params.target.assets - Exact loan assets paid to the receiver on an assets target; any referral fee is sold on top.
43
+ * @param params.target.maxUnits - Unit cap on an assets target.
44
+ * @param params.target.units - Exact credit units to sell on a units target.
45
+ * @param params.target.minSellerAssets - Loan-asset floor on a units target.
46
+ * @param params.receiver - Optional recipient of the withdrawn loan assets; defaults to `account`.
47
+ * @param params.referralFee.bps - Optional referral fee in integer basis points, at most 10%.
48
+ * @param params.referralFee.recipient - Recipient required for a positive referral fee.
49
+ * @param params.now - Reference Unix timestamp in seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
50
+ * @param params.expiresAt - Onchain deadline in Unix seconds; defaults to, and may not exceed, one hour after `now`.
51
+ * @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
52
+ * @returns A frozen plan with a standalone authorization step if needed and no signature requests.
53
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now` or a target amount is not a
54
+ * bigint; checked before any request.
55
+ * @throws {ZeroAccountError} If `account` is the zero address.
56
+ * @throws {NonIntegerInputError} If `expiresAt` or `referralFee.bps` is not a safe integer.
57
+ * @throws {NonPositiveInputError} If `expiresAt`, the target amount, `maxUnits` or
58
+ * `minSellerAssets` is not positive.
59
+ * @throws {ExpiredDeadlineError} If expiry is at or before the reference timestamp.
60
+ * @throws {NegativeInputError} If `referralFee.bps` or an offer cap is negative.
61
+ * @throws {InputExceedsMaxError} If `referralFee.bps` exceeds 1,000 (10%), or a target amount or
62
+ * offer cap exceeds uint128.
63
+ * @throws {InvalidCalldataOriginError} If `calldataOrigin` is empty, malformed or has an odd number of hex digits.
64
+ * @throws {MidnightTakeDeadlineTooFarError} If expiry is more than one hour away.
65
+ * @throws {InvalidTransactionPlanError} If `account` is malformed or the target type is neither assets nor units.
66
+ * @throws {ChainIdMismatchError} If the client, transport or market is on a different chain.
67
+ * @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
68
+ * @throws {InvalidMarketParameterError} If the market tuple has invalid parameters.
69
+ * @throws {EmptyMidnightTakeableOffersError} If no offers are supplied.
70
+ * @throws {MidnightOfferSideMismatchError} If an offer is not a lend offer.
71
+ * @throws {MidnightTakeableOfferMarketMismatchError} If an offer trades another market.
72
+ * @throws {MidnightCalldataEncodingError} If an address or offer field cannot be ABI-encoded.
73
+ * @throws {MidnightZeroReceiverError} If the receiver is the zero address.
74
+ * @throws {MidnightContractReceiverError} If the receiver, or the referral fee recipient of a
75
+ * positive fee, is a Midnight protocol or market token contract.
76
+ * @throws {UnboundedMidnightTakeInputError} If `target.units` or `target.maxUnits` is `maxUint256`.
77
+ * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no recipient.
78
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
79
+ * @throws {UnknownAddressError} If the chain has no `midnightBundlesV2` deployment.
80
+ * @throws {MarketIdMismatchError} If the position belongs to another market.
81
+ * @throws {AccrualPositionUserMismatchError} If the position is not owned by the account.
82
+ * @throws {InvalidPositionLossFactorError} If the position's loss factor is ahead of its market's.
83
+ * @throws {InvalidPositionAccrualStateError} If the position's credit and fee snapshot cannot be accrued.
84
+ * @throws {MidnightTakeableOffersNotFillableError} If the supplied offers cannot be used.
85
+ * @throws {MidnightTakeCreditInsufficientError} If the target needs more units than the
86
+ * position's accrued credit.
87
+ * @throws {MidnightTakeTargetUnreachableError} With field `target.maxUnits` if `maxUnits` cannot
88
+ * cover the requested assets, or `target.minSellerAssets` if the units cannot yield it; change the
89
+ * target instead of re-quoting. With field `takeableOffers` if the credit covers the target but
90
+ * the offers plus withdrawable liquidity cannot fill it.
91
+ * @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
92
+ * @throws {viem.BaseError} If an `eth_chainId` request or the authorization read fails.
93
+ * @example
94
+ * ```ts
95
+ * import { buildTransactions, prepareMidnightTakeWithdraw, type TransactionPlan } from "@morpho-org/morpho-sdk";
96
+ * import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
97
+ * import { MidnightApi } from "@morpho-org/morpho-sdk/midnight-api";
98
+ * import { type Address, type Hash, createPublicClient, http } from "viem";
99
+ * import { base } from "viem/chains";
100
+ *
101
+ * async function prepareWithdrawal(account: Address, marketId: Hash) {
102
+ * const client = createPublicClient({ chain: base, transport: http() });
103
+ * const block = await client.getBlock();
104
+ * const positionData = await fetchMidnightAccrualPosition(client, {
105
+ * marketId,
106
+ * user: account,
107
+ * blockNumber: block.number,
108
+ * });
109
+ * const marketData = positionData.market;
110
+ * const assets = 1_000_000n;
111
+ * const maxUnits = 1_100_000n;
112
+ * // Quote the unit ceiling: fees come out of the proceeds, so fills sized to the net
113
+ * // assets could not deliver them.
114
+ * const quote = await new MidnightApi().fetchBookQuote({
115
+ * marketId,
116
+ * side: "bids",
117
+ * units: maxUnits,
118
+ * taker: account,
119
+ * });
120
+ * const plan: TransactionPlan = await prepareMidnightTakeWithdraw(client, {
121
+ * chainId: base.id,
122
+ * account,
123
+ * marketData,
124
+ * positionData,
125
+ * now: block.timestamp,
126
+ * target: { type: "assets", assets, maxUnits },
127
+ * takeableOffers: quote.data.takeableOffers,
128
+ * });
129
+ * // Simulate, then send in order from plan.account on plan.chainId.
130
+ * return buildTransactions(plan);
131
+ * }
132
+ * ```
133
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
134
+ */
135
+ export declare function prepareMidnightTakeWithdraw(client: Client, params: MidnightTakeWithdrawPlanParams): Promise<TransactionPlan>;
136
+ /** @internal Encodes the prepared credit withdrawal from persisted inputs without state reads. */
137
+ export declare function buildMidnightTakeWithdraw({ inputs: { chainId, market, target, receiver, takeableOffers, deadline, referralFeePct, referralFeeRecipient, }, }: Extract<Action, {
138
+ type: "midnightTakeWithdraw";
139
+ }>): Readonly<import("../../index.js").Transaction<import("../../index.js").MidnightTakeWithdrawAction>>;