@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,236 @@
1
+ import { MathLib } from "@morpho-org/blue-sdk";
2
+ import { AccrualPosition } from "@morpho-org/midnight-sdk";
3
+ import { deepFreeze, getChainAddress, Time } from "@morpho-org/morpho-ts";
4
+ import { midnightTakeWithdraw, parseMidnightTakeWithdraw, } from "../../actions/midnight/takeWithdraw.js";
5
+ import { createChainCheck } from "../../actions/requirements/chainCheck.js";
6
+ import { assertRegistryTargetsHaveCode } from "../../entities/requirements/assertContractCode.js";
7
+ import { MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS } from "../../helpers/constant.js";
8
+ import { validateMidnightPositionBinding } from "../../helpers/parseMidnight.js";
9
+ import { validateReferenceTime } from "../../helpers/validate.js";
10
+ import { validateMidnightTakeableOfferFields } from "../../helpers/validateMidnightTakeableOfferFields.js";
11
+ import { MidnightTakeDeadlineTooFarError } from "../../types/error.js";
12
+ import { resolveIntent } from "../intent.js";
13
+ import { prepareMidnightBundleAuthorization } from "./authorization.js";
14
+ import { storedFills, storedMarketTuple } from "./market.js";
15
+ import { validateMidnightReduceOnlySellFeasibility } from "./reduceOnlySellFeasibility.js";
16
+ import { invalidSellTargetType, validateMidnightTargetAmountTypes, } from "./validation.js";
17
+ /**
18
+ * Prepares a reduce-only Midnight withdrawal that redeems available credit at par
19
+ * before selling the rest of the target into lend offers. It cannot open debt.
20
+ * Validates inputs with the same parse-once constructor and fill feasibility check as the
21
+ * entity `takeWithdraw`, checks every taken offer field, binds the position to the account and
22
+ * market, and caps fills at the
23
+ * position's credit accrued to the reference timestamp against `marketData`, the snapshot that
24
+ * caps withdrawable credit. It then reads the registry targets'
25
+ * bytecode and the bundle authorization. On an assets target, offers that would revert the
26
+ * whole bundle are dropped from the stored fills. Like the entity check, fill feasibility counts
27
+ * units at par and does not price discounted bids after settlement fees, so a plan can pass
28
+ * preparation and still revert onchain; the onchain bounds keep funds safe. Simulate before sending.
29
+ * @param client - Viem client used to verify chain, deployments and authorization.
30
+ * @param params - Account, market and position snapshots, fills and intent.
31
+ * @param params.chainId - Chain containing the market and MidnightBundlesV2.
32
+ * @param params.account - Non-zero position owner that sends the plan; its credit is withdrawn.
33
+ * @param params.marketData - Market snapshot used to assess liquidity and fill feasibility.
34
+ * @param params.positionData - Owner-bound position snapshot for the same market, read at the same block.
35
+ * @param params.takeableOffers - ABI-ready lend offers from the caller's quote, in fill order.
36
+ * @param params.target.type - `"assets"` to receive loan assets, or `"units"` to sell exact credit units.
37
+ * @param params.target.assets - Exact loan assets paid to the receiver on an assets target; any referral fee is sold on top.
38
+ * @param params.target.maxUnits - Unit cap on an assets target.
39
+ * @param params.target.units - Exact credit units to sell on a units target.
40
+ * @param params.target.minSellerAssets - Loan-asset floor on a units target.
41
+ * @param params.receiver - Optional recipient of the withdrawn loan assets; defaults to `account`.
42
+ * @param params.referralFee.bps - Optional referral fee in integer basis points, at most 10%.
43
+ * @param params.referralFee.recipient - Recipient required for a positive referral fee.
44
+ * @param params.now - Reference Unix timestamp in seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
45
+ * @param params.expiresAt - Onchain deadline in Unix seconds; defaults to, and may not exceed, one hour after `now`.
46
+ * @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
47
+ * @returns A frozen plan with a standalone authorization step if needed and no signature requests.
48
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now` or a target amount is not a
49
+ * bigint; checked before any request.
50
+ * @throws {ZeroAccountError} If `account` is the zero address.
51
+ * @throws {NonIntegerInputError} If `expiresAt` or `referralFee.bps` is not a safe integer.
52
+ * @throws {NonPositiveInputError} If `expiresAt`, the target amount, `maxUnits` or
53
+ * `minSellerAssets` is not positive.
54
+ * @throws {ExpiredDeadlineError} If expiry is at or before the reference timestamp.
55
+ * @throws {NegativeInputError} If `referralFee.bps` or an offer cap is negative.
56
+ * @throws {InputExceedsMaxError} If `referralFee.bps` exceeds 1,000 (10%), or a target amount or
57
+ * offer cap exceeds uint128.
58
+ * @throws {InvalidCalldataOriginError} If `calldataOrigin` is empty, malformed or has an odd number of hex digits.
59
+ * @throws {MidnightTakeDeadlineTooFarError} If expiry is more than one hour away.
60
+ * @throws {InvalidTransactionPlanError} If `account` is malformed or the target type is neither assets nor units.
61
+ * @throws {ChainIdMismatchError} If the client, transport or market is on a different chain.
62
+ * @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
63
+ * @throws {InvalidMarketParameterError} If the market tuple has invalid parameters.
64
+ * @throws {EmptyMidnightTakeableOffersError} If no offers are supplied.
65
+ * @throws {MidnightOfferSideMismatchError} If an offer is not a lend offer.
66
+ * @throws {MidnightTakeableOfferMarketMismatchError} If an offer trades another market.
67
+ * @throws {MidnightCalldataEncodingError} If an address or offer field cannot be ABI-encoded.
68
+ * @throws {MidnightZeroReceiverError} If the receiver is the zero address.
69
+ * @throws {MidnightContractReceiverError} If the receiver, or the referral fee recipient of a
70
+ * positive fee, is a Midnight protocol or market token contract.
71
+ * @throws {UnboundedMidnightTakeInputError} If `target.units` or `target.maxUnits` is `maxUint256`.
72
+ * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no recipient.
73
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
74
+ * @throws {UnknownAddressError} If the chain has no `midnightBundlesV2` deployment.
75
+ * @throws {MarketIdMismatchError} If the position belongs to another market.
76
+ * @throws {AccrualPositionUserMismatchError} If the position is not owned by the account.
77
+ * @throws {InvalidPositionLossFactorError} If the position's loss factor is ahead of its market's.
78
+ * @throws {InvalidPositionAccrualStateError} If the position's credit and fee snapshot cannot be accrued.
79
+ * @throws {MidnightTakeableOffersNotFillableError} If the supplied offers cannot be used.
80
+ * @throws {MidnightTakeCreditInsufficientError} If the target needs more units than the
81
+ * position's accrued credit.
82
+ * @throws {MidnightTakeTargetUnreachableError} With field `target.maxUnits` if `maxUnits` cannot
83
+ * cover the requested assets, or `target.minSellerAssets` if the units cannot yield it; change the
84
+ * target instead of re-quoting. With field `takeableOffers` if the credit covers the target but
85
+ * the offers plus withdrawable liquidity cannot fill it.
86
+ * @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
87
+ * @throws {viem.BaseError} If an `eth_chainId` request or the authorization read fails.
88
+ * @example
89
+ * ```ts
90
+ * import { buildTransactions, prepareMidnightTakeWithdraw, type TransactionPlan } from "@morpho-org/morpho-sdk";
91
+ * import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
92
+ * import { MidnightApi } from "@morpho-org/morpho-sdk/midnight-api";
93
+ * import { type Address, type Hash, createPublicClient, http } from "viem";
94
+ * import { base } from "viem/chains";
95
+ *
96
+ * async function prepareWithdrawal(account: Address, marketId: Hash) {
97
+ * const client = createPublicClient({ chain: base, transport: http() });
98
+ * const block = await client.getBlock();
99
+ * const positionData = await fetchMidnightAccrualPosition(client, {
100
+ * marketId,
101
+ * user: account,
102
+ * blockNumber: block.number,
103
+ * });
104
+ * const marketData = positionData.market;
105
+ * const assets = 1_000_000n;
106
+ * const maxUnits = 1_100_000n;
107
+ * // Quote the unit ceiling: fees come out of the proceeds, so fills sized to the net
108
+ * // assets could not deliver them.
109
+ * const quote = await new MidnightApi().fetchBookQuote({
110
+ * marketId,
111
+ * side: "bids",
112
+ * units: maxUnits,
113
+ * taker: account,
114
+ * });
115
+ * const plan: TransactionPlan = await prepareMidnightTakeWithdraw(client, {
116
+ * chainId: base.id,
117
+ * account,
118
+ * marketData,
119
+ * positionData,
120
+ * now: block.timestamp,
121
+ * target: { type: "assets", assets, maxUnits },
122
+ * takeableOffers: quote.data.takeableOffers,
123
+ * });
124
+ * // Simulate, then send in order from plan.account on plan.chainId.
125
+ * return buildTransactions(plan);
126
+ * }
127
+ * ```
128
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
129
+ */
130
+ export async function prepareMidnightTakeWithdraw(client, params) {
131
+ const { chainId, account, marketData, positionData, target } = params;
132
+ const now = params.now ?? Time.timestamp();
133
+ // Reject a non-bigint clock before the deadline window sum can mix types.
134
+ validateReferenceTime(now);
135
+ const maxDeadline = now + MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
136
+ const intent = resolveIntent({ ...params, expiresAt: params.expiresAt ?? Number(maxDeadline) }, now);
137
+ if (intent.deadline > maxDeadline) {
138
+ throw new MidnightTakeDeadlineTooFarError({
139
+ deadline: intent.deadline,
140
+ maxDeadline,
141
+ });
142
+ }
143
+ if (target.type !== "assets" && target.type !== "units") {
144
+ throw invalidSellTargetType("$.target");
145
+ }
146
+ validateMidnightTargetAmountTypes(target, target.type === "assets"
147
+ ? ["assets", "maxUnits"]
148
+ : ["units", "minSellerAssets"]);
149
+ const parsed = parseMidnightTakeWithdraw({
150
+ chainId,
151
+ market: marketData.params,
152
+ target,
153
+ receiver: params.receiver ?? account,
154
+ takeableOffers: params.takeableOffers,
155
+ deadline: intent.deadline,
156
+ referralFeePct: intent.referralFeePct,
157
+ referralFeeRecipient: intent.referralFeeRecipient,
158
+ });
159
+ validateMidnightTakeableOfferFields(parsed.takeableOffers);
160
+ const bundle = getChainAddress(chainId, "midnightBundlesV2");
161
+ validateMidnightPositionBinding({
162
+ positionData,
163
+ accountAddress: account,
164
+ marketData,
165
+ });
166
+ const { credit } = new AccrualPosition(positionData, marketData).accrueInterest(MathLib.max(now, positionData.lastAccrual));
167
+ const takeableOffers = validateMidnightReduceOnlySellFeasibility({
168
+ side: "sell",
169
+ takeableOffers: parsed.takeableOffers,
170
+ accountAddress: account,
171
+ marketData,
172
+ now,
173
+ deadline: parsed.deadline,
174
+ referralFeePct: parsed.referralFeePct,
175
+ fallbackUnits: MathLib.min(credit, marketData.withdrawable),
176
+ credit,
177
+ target: parsed.target,
178
+ increasesDebt: false,
179
+ });
180
+ const chainCheck = createChainCheck(client, chainId);
181
+ await chainCheck();
182
+ // Check deployments before an authorization read can fail decoding empty data.
183
+ await assertRegistryTargetsHaveCode(client, chainId, [
184
+ { role: "midnightBundlesV2", address: bundle },
185
+ { role: "midnight", address: getChainAddress(chainId, "midnight") },
186
+ ], chainCheck);
187
+ const authorization = await prepareMidnightBundleAuthorization(client, {
188
+ chainId,
189
+ account,
190
+ });
191
+ return deepFreeze({
192
+ version: 2,
193
+ chainId,
194
+ account,
195
+ expiresAt: intent.expiresAt,
196
+ ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
197
+ steps: [
198
+ ...(authorization === undefined ? [] : [authorization]),
199
+ {
200
+ id: "midnightTakeWithdraw",
201
+ label: "Withdraw Midnight credit",
202
+ action: {
203
+ type: "midnightTakeWithdraw",
204
+ inputs: {
205
+ chainId,
206
+ account,
207
+ market: parsed.market,
208
+ target: parsed.target,
209
+ receiver: parsed.receiver,
210
+ takeableOffers,
211
+ deadline: parsed.deadline,
212
+ referralFeePct: parsed.referralFeePct,
213
+ referralFeeRecipient: parsed.referralFeeRecipient,
214
+ },
215
+ },
216
+ },
217
+ ],
218
+ signatureRequests: [],
219
+ });
220
+ }
221
+ /** @internal Encodes the prepared credit withdrawal from persisted inputs without state reads. */
222
+ export function buildMidnightTakeWithdraw({ inputs: { chainId, market, target, receiver, takeableOffers, deadline, referralFeePct, referralFeeRecipient, }, }) {
223
+ if (target.type !== "assets" && target.type !== "units") {
224
+ throw invalidSellTargetType("$.inputs.target");
225
+ }
226
+ return midnightTakeWithdraw({
227
+ chainId,
228
+ market: storedMarketTuple(market),
229
+ target,
230
+ receiver,
231
+ takeableOffers: storedFills(takeableOffers),
232
+ deadline,
233
+ referralFeePct,
234
+ referralFeeRecipient,
235
+ });
236
+ }
@@ -0,0 +1,22 @@
1
+ import { InvalidTransactionPlanError } from "../error.js";
2
+ /** @internal Reports an invalid sell target discriminator in an input or stored recipe. */
3
+ export declare function invalidSellTargetType(targetPath: string): InvalidTransactionPlanError;
4
+ /** @internal Validates a stored sell recipe shape without encoding or reading market state. */
5
+ export declare function validateMidnightSellPlanAction(action: Record<string, unknown>, path: string): void;
6
+ type StoredMarketContext = {
7
+ readonly path: string;
8
+ readonly chainId: number;
9
+ };
10
+ /** @internal Validates the plain market tuple used by a restored Midnight plan. */
11
+ export declare function validateStoredMidnightMarket(value: unknown, { path, chainId }: StoredMarketContext): void;
12
+ /** @internal Validates ABI-ready quote fields without testing onchain fill availability. */
13
+ export declare function validateStoredMidnightFills(value: unknown, { path, chainId }: StoredMarketContext): void;
14
+ /**
15
+ * @internal Rejects a non-bigint take target amount before any read, so a JavaScript caller's
16
+ * number fails at preparation instead of when the saved plan is restored.
17
+ * @param target - Caller's take target.
18
+ * @param fields - Amount fields of the target's variant.
19
+ * @throws {InvalidBigIntInputError} If one of `fields` is not a bigint.
20
+ */
21
+ export declare function validateMidnightTargetAmountTypes(target: object, fields: readonly string[]): void;
22
+ export {};
@@ -0,0 +1,151 @@
1
+ import { InvalidBigIntInputError } from "../../types/error.js";
2
+ import { InvalidTransactionPlanError } from "../error.js";
3
+ import { getPlanObject, validatePlanFields } from "../validation.js";
4
+ import { validateSignaturelessMidnightAction } from "./authorization.js";
5
+ /** @internal Reports an invalid sell target discriminator in an input or stored recipe. */
6
+ export function invalidSellTargetType(targetPath) {
7
+ return new InvalidTransactionPlanError({
8
+ path: `${targetPath}.type`,
9
+ reason: "expected assets or units",
10
+ });
11
+ }
12
+ /** @internal Validates a stored sell recipe shape without encoding or reading market state. */
13
+ export function validateMidnightSellPlanAction(action, path) {
14
+ const inputsPath = `${path}.inputs`;
15
+ const inputs = getPlanObject(action.inputs, inputsPath);
16
+ validatePlanFields(inputs, {
17
+ path: inputsPath,
18
+ fields: {
19
+ receiver: "address",
20
+ deadline: "uint256 bigint",
21
+ referralFeePct: "uint256 bigint",
22
+ referralFeeRecipient: "address",
23
+ },
24
+ });
25
+ const targetPath = `${inputsPath}.target`;
26
+ const target = getPlanObject(inputs.target, targetPath);
27
+ switch (target.type) {
28
+ case "assets":
29
+ validatePlanFields(target, {
30
+ path: targetPath,
31
+ fields: { assets: "uint128 bigint", maxUnits: "uint128 bigint" },
32
+ });
33
+ break;
34
+ case "units":
35
+ validatePlanFields(target, {
36
+ path: targetPath,
37
+ fields: { units: "uint128 bigint", minSellerAssets: "uint128 bigint" },
38
+ });
39
+ break;
40
+ default:
41
+ throw invalidSellTargetType(targetPath);
42
+ }
43
+ const chainId = inputs.chainId; // Checked by the parse dispatcher.
44
+ validateStoredMidnightMarket(inputs.market, {
45
+ path: `${inputsPath}.market`,
46
+ chainId,
47
+ });
48
+ validateStoredMidnightFills(inputs.takeableOffers, {
49
+ path: `${inputsPath}.takeableOffers`,
50
+ chainId,
51
+ });
52
+ validateSignaturelessMidnightAction(action, path);
53
+ }
54
+ /** @internal Validates the plain market tuple used by a restored Midnight plan. */
55
+ export function validateStoredMidnightMarket(value, { path, chainId }) {
56
+ const market = getPlanObject(value, path);
57
+ validatePlanFields(market, {
58
+ path,
59
+ fields: {
60
+ chainId: "uint256 bigint",
61
+ midnight: "address",
62
+ loanToken: "address",
63
+ maturity: "uint256 bigint",
64
+ rcfThreshold: "uint256 bigint",
65
+ enterGate: "address",
66
+ liquidatorGate: "address",
67
+ },
68
+ });
69
+ if (market.chainId !== BigInt(chainId)) {
70
+ throw new InvalidTransactionPlanError({
71
+ path: `${path}.chainId`,
72
+ reason: "expected the plan chainId",
73
+ });
74
+ }
75
+ if (!Array.isArray(market.collateralParams)) {
76
+ throw new InvalidTransactionPlanError({
77
+ path: `${path}.collateralParams`,
78
+ reason: "expected an array",
79
+ });
80
+ }
81
+ for (const [index, item] of market.collateralParams.entries()) {
82
+ const collateralPath = `${path}.collateralParams[${index}]`;
83
+ validatePlanFields(getPlanObject(item, collateralPath), {
84
+ path: collateralPath,
85
+ fields: {
86
+ token: "address",
87
+ oracle: "address",
88
+ lltv: "uint256 bigint",
89
+ liquidationCursor: "uint256 bigint",
90
+ },
91
+ });
92
+ }
93
+ }
94
+ /** @internal Validates ABI-ready quote fields without testing onchain fill availability. */
95
+ export function validateStoredMidnightFills(value, { path, chainId }) {
96
+ if (!Array.isArray(value)) {
97
+ throw new InvalidTransactionPlanError({
98
+ path,
99
+ reason: "expected an array",
100
+ });
101
+ }
102
+ for (const [index, item] of value.entries()) {
103
+ const fillPath = `${path}[${index}]`;
104
+ const fill = getPlanObject(item, fillPath);
105
+ validatePlanFields(fill, {
106
+ path: fillPath,
107
+ fields: { units: "uint256 bigint", ratifierData: "hex" },
108
+ });
109
+ const offerPath = `${fillPath}.offer`;
110
+ const offer = getPlanObject(fill.offer, offerPath);
111
+ validatePlanFields(offer, {
112
+ path: offerPath,
113
+ fields: {
114
+ buy: "boolean",
115
+ maker: "address",
116
+ start: "uint256 bigint",
117
+ expiry: "uint256 bigint",
118
+ tick: "uint256 bigint",
119
+ group: "bytes32",
120
+ callback: "address",
121
+ callbackData: "hex",
122
+ receiverIfMakerIsSeller: "address",
123
+ ratifier: "address",
124
+ reduceOnly: "boolean",
125
+ maxUnits: "uint128 bigint",
126
+ maxAssets: "uint128 bigint",
127
+ continuousFeeCap: "uint256 bigint",
128
+ },
129
+ });
130
+ // The offer's market tuple is independently present in the quote.
131
+ validateStoredMidnightMarket(offer.market, {
132
+ path: `${offerPath}.market`,
133
+ chainId,
134
+ });
135
+ }
136
+ }
137
+ /**
138
+ * @internal Rejects a non-bigint take target amount before any read, so a JavaScript caller's
139
+ * number fails at preparation instead of when the saved plan is restored.
140
+ * @param target - Caller's take target.
141
+ * @param fields - Amount fields of the target's variant.
142
+ * @throws {InvalidBigIntInputError} If one of `fields` is not a bigint.
143
+ */
144
+ export function validateMidnightTargetAmountTypes(target, fields) {
145
+ for (const field of fields) {
146
+ const value = target[field];
147
+ if (typeof value !== "bigint") {
148
+ throw new InvalidBigIntInputError(`target.${field}`, value);
149
+ }
150
+ }
151
+ }
@@ -0,0 +1,130 @@
1
+ import type { AccrualPosition, Market } from "@morpho-org/midnight-sdk";
2
+ import type { Address, Client } from "viem";
3
+ import { type ReferenceTimestampParams } from "../../types/index.js";
4
+ import { type IntentParams } from "../intent.js";
5
+ import type { Action, TransactionPlan } from "../types.js";
6
+ type WithdrawCollateralAction = Extract<Action, {
7
+ type: "midnightWithdrawCollateral";
8
+ }>;
9
+ /**
10
+ * Represents an intent to withdraw one collateral directly from the submitting account's Midnight position.
11
+ * @example
12
+ * ```ts
13
+ * import type { MidnightWithdrawCollateralPlanParams } from "@morpho-org/morpho-sdk";
14
+ * import { maxUint256 } from "viem";
15
+ * const withdrawAll = (params: MidnightWithdrawCollateralPlanParams) =>
16
+ * ({ ...params, assets: maxUint256 });
17
+ * ```
18
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
19
+ */
20
+ export interface MidnightWithdrawCollateralPlanParams extends Pick<IntentParams, "chainId" | "account" | "expiresAt" | "calldataOrigin">, ReferenceTimestampParams {
21
+ /** Hydrated market snapshot from the same block as `positionData`. */
22
+ readonly marketData: Market;
23
+ /** Position snapshot for the same market, owned by the submitting account. */
24
+ readonly positionData: AccrualPosition;
25
+ /**
26
+ * Raw values from `price()` on each `marketData.params.collateralParams[i].oracle`,
27
+ * indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE` (1e36).
28
+ * Use prices from the snapshot block. No prices are needed when the snapshot has no debt.
29
+ */
30
+ readonly collateralPrices: readonly bigint[];
31
+ /** Collateral index in Midnight's token-address order; defaults to `0n`. */
32
+ readonly collateralIndex?: bigint;
33
+ /** Collateral amount in token base units; `maxUint256` withdraws the snapshot balance at that index. */
34
+ readonly assets: bigint;
35
+ /** Recipient of the withdrawn collateral; defaults to `account`. */
36
+ readonly receiver?: Address;
37
+ }
38
+ /**
39
+ * Prepares one direct Midnight core collateral withdrawal. Inputs go through
40
+ * `parseMidnightWithdrawCollateralPreparation`, which applies the entity `withdrawCollateral`
41
+ * checks in the same order: the position is bound to the sender and market, the index is
42
+ * resolved, and `maxUint256` becomes the snapshot balance before the amount, receiver and
43
+ * encoding checks. The withdrawal is then checked against the snapshot balance and, when the
44
+ * snapshot has debt, against the remaining collateral's capacity at LLTV minus
45
+ * `DEFAULT_LLTV_BUFFER`. Restoring and building offline does not refresh those checks;
46
+ * simulate against current state before sending.
47
+ *
48
+ * The account sends the withdrawal itself, so the plan has no approvals, authorizations or
49
+ * signature requests. Expiry is checked during preparation only; it is not an onchain deadline.
50
+ * @param client - Viem client used to check the network and the Midnight core deployment.
51
+ * @param params - Market and position snapshots, collateral selection, amount and optional receiver.
52
+ * @param params.chainId - EIP-155 chain ID of the market and submitting client.
53
+ * @param params.account - Nonzero position owner who sends the withdrawal.
54
+ * @param params.marketData - Hydrated market snapshot from the same block as `positionData`.
55
+ * @param params.positionData - Position snapshot for the same market, owned by `account`.
56
+ * @param params.collateralPrices - Raw `price()` values from each collateral oracle at the snapshot
57
+ * block, indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE` (1e36). Not
58
+ * needed when the snapshot has no debt.
59
+ * @param params.collateralIndex - Collateral index in token-address order. Defaults to `0n`.
60
+ * @param params.assets - Positive collateral amount in token base units; `maxUint256` withdraws
61
+ * the snapshot balance at that index.
62
+ * @param params.receiver - Optional recipient of the collateral; defaults to `account`. Midnight
63
+ * and market token contracts are rejected.
64
+ * @param params.now - Reference Unix timestamp in seconds, normally the snapshot block's timestamp;
65
+ * omitting it uses the device clock (an untyped JavaScript `null` does too).
66
+ * @param params.expiresAt - Plan expiry in Unix seconds; defaults to two hours after `now`. Midnight does not enforce it onchain.
67
+ * @param params.calldataOrigin - Optional attribution bytes appended to the built transaction.
68
+ * @returns A frozen plan with one withdrawal step and no approvals, authorizations or signature requests.
69
+ * @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.
70
+ * @throws {ZeroAccountError} If the account is the zero address.
71
+ * @throws {NonIntegerInputError} If expiry is not a safe integer.
72
+ * @throws {ExpiredDeadlineError} If expiry is at or before the reference time.
73
+ * @throws {InvalidCalldataOriginError} If attribution bytes are empty or malformed.
74
+ * @throws {InvalidTransactionPlanError} If the account is malformed, `collateralPrices` is not an array, or attribution exceeds 1 MiB.
75
+ * @throws {ChainIdMismatchError} If the market, client or RPC targets another chain.
76
+ * @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
77
+ * @throws {InvalidMarketParameterError} If the market configuration is invalid.
78
+ * @throws {MarketIdMismatchError} If the position belongs to another market.
79
+ * @throws {AccrualPositionUserMismatchError} If the position is owned by another account.
80
+ * @throws {UnknownCollateralIndexError} If the index is not configured on the market.
81
+ * @throws {NonPositiveInputError} If expiry or the resolved amount is not positive.
82
+ * @throws {InputExceedsMaxError} If the resolved amount exceeds uint128.
83
+ * @throws {MidnightZeroReceiverError} If the receiver is the zero address.
84
+ * @throws {MidnightContractReceiverError} If the receiver is a blocked protocol or market token contract.
85
+ * @throws {MidnightCalldataEncodingError} If a market, position owner or receiver address is malformed, or calldata cannot be encoded.
86
+ * @throws {WithdrawExceedsCollateralError} If the amount exceeds the snapshot balance.
87
+ * @throws {MissingMarketPriceError} If remaining collateral has no price for the health check.
88
+ * @throws {WithdrawMakesPositionUnhealthyError} If the snapshot debt exceeds the remaining buffered capacity.
89
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
90
+ * @throws {UnknownAddressError} If Midnight core is not registered on the chain.
91
+ * @throws {MissingContractCodeError} If the registered Midnight core has no deployed code.
92
+ * @throws {viem.BaseError} If the `eth_chainId` or bytecode request fails.
93
+ * @example
94
+ * ```ts
95
+ * import {
96
+ * buildTransactions,
97
+ * prepareMidnightWithdrawCollateral,
98
+ * type TransactionPlan,
99
+ * } from "@morpho-org/morpho-sdk";
100
+ * import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
101
+ * import { type Address, type Hash, createPublicClient, http, maxUint256 } from "viem";
102
+ * import { base } from "viem/chains";
103
+ *
104
+ * // For a debt-free position only. With debt, pass each collateral oracle's `price()`
105
+ * // from the same block as `collateralPrices`; an empty list then throws MissingMarketPriceError.
106
+ * async function prepareCollateralExit(account: Address, marketId: Hash) {
107
+ * const client = createPublicClient({ chain: base, transport: http() });
108
+ * const block = await client.getBlock();
109
+ * const positionData = await fetchMidnightAccrualPosition(client, {
110
+ * marketId, user: account, blockNumber: block.number,
111
+ * });
112
+ * const plan: TransactionPlan = await prepareMidnightWithdrawCollateral(client, {
113
+ * chainId: base.id, account, marketData: positionData.market, positionData,
114
+ * collateralPrices: [], // No price check is needed without debt.
115
+ * now: block.timestamp,
116
+ * assets: maxUint256,
117
+ * });
118
+ * // plan.steps: a single "midnightWithdrawCollateral" step; plan.signatureRequests is empty.
119
+ * // Simulate, then send from plan.account on plan.chainId.
120
+ * return buildTransactions(plan);
121
+ * }
122
+ * ```
123
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
124
+ */
125
+ export declare function prepareMidnightWithdrawCollateral(client: Client, params: MidnightWithdrawCollateralPlanParams): Promise<TransactionPlan>;
126
+ /** @internal Encodes the stored direct withdrawal without retaining the snapshot. */
127
+ export declare function buildMidnightWithdrawCollateral({ inputs, }: WithdrawCollateralAction): Readonly<import("../../types/action.js").Transaction<import("../../types/action.js").MidnightWithdrawCollateralAction>>;
128
+ /** @internal Validates the stored Midnight collateral withdrawal without RPC. */
129
+ export declare function validateMidnightWithdrawCollateralPlanAction(action: Record<string, unknown>, path: string): void;
130
+ export {};