@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,172 @@
1
+ import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
2
+ import { parseMidnightApprovalRequirements } from "../../actions/requirements/midnight/getMidnightApprovalRequirements.js";
3
+ import { getTokenRequirements } from "../requirements.js";
4
+ import { prepareMidnightBundleAuthorization } from "./authorization.js";
5
+ import { prepareMidnightMakerPublication, } from "./makerPublication.js";
6
+ import { parseMakeLendParams, parseMakeRepayParams } from "./prepare.js";
7
+ /**
8
+ * Prepares a PriceRatifierV1 or RateRatifierV1 buy-offer publication for the submitting maker.
9
+ * Midnight pulls loan tokens from the maker only at fill time. Preparation checks the core
10
+ * allowance against `loanAssets + reservedLoanAssets`, not the offer caps or the wallet balance.
11
+ * The publication bundle pulls nothing and cannot fund this flow with native ETH. Approvals
12
+ * and authorizations are separate transactions and do not expire with the plan.
13
+ * Builds the offer tree and checks the offer-capped `expiresAt` first, then validates the
14
+ * publication with a plan-side copy of the entity `makeLend` constructor, in its order, except
15
+ * that malformed cancellations are rejected before any state read, and a deadline already reached
16
+ * at the pinned block is rejected before the mempool API call. So an input with several errors can fail on the tree or expiry here where the entity reports another error
17
+ * first. The chain and the bundle, Midnight and ratifier code are checked once, right before
18
+ * the first publication-state read. The allowance bound is checked like the entity's
19
+ * `getRequirements()`, after the publication is parsed and before the allowance read.
20
+ * @param client - Plain viem client for network, deployment, offer and prerequisite reads.
21
+ * @param params - Maker, offer tree or tree creation request, and loan-token allowance bounds.
22
+ * @param params.chainId - Chain containing Midnight, MidnightBundlesV2 and the selected ratifier.
23
+ * @param params.account - Non-zero maker that names itself on every offer and sends the plan.
24
+ * @param params.offers - Caller-supplied buy-offer tree, or a PriceRatifierV1 or RateRatifierV1 tree creation request.
25
+ * @param params.validation - Optional mempool API request controls; `false` skips the API call.
26
+ * @param params.cancellations - Optional groups and consumed ceilings to cancel atomically with publication; must not overlap the new tree.
27
+ * Omitting it cancels nothing (an untyped JavaScript `null` does too).
28
+ * @param params.loanToken - Loan token shared by every offer market.
29
+ * @param params.loanAssets - Positive loan assets to cover in the core allowance check; count an alternative offer group's budget once.
30
+ * @param params.reservedLoanAssets - Optional loan assets reserved by other open groups, excluding cancelled groups; defaults to `0n`.
31
+ * @param params.now - Reference Unix timestamp in seconds for plan expiry; omitting it uses the device clock (an untyped JavaScript `null` does too).
32
+ * @param params.expiresAt - Unix seconds. Defaults to the earlier of `now + 2h` and the first offer expiry minus one second.
33
+ * @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
34
+ * @returns A frozen, signature-free plan whose publication payload can be built offline.
35
+ * @throws {InvalidBigIntInputError} If `loanAssets`, a cancellation ceiling, or a supplied non-null `now`
36
+ * or `reservedLoanAssets` is not a bigint; checked before any request.
37
+ * @throws {ZeroAccountError} If the submitting account is zero.
38
+ * @throws {InvalidTransactionPlanError} If the account is not an address, calldata origin exceeds 1 MiB,
39
+ * or a supplied non-null `cancellations` is not an array or has a non-object entry; checked
40
+ * before any request.
41
+ * @throws {InvalidCalldataOriginError} If calldata origin is not nonempty, even-length hex.
42
+ * @throws {NonIntegerInputError} If `expiresAt` is not a safe integer.
43
+ * @throws {InvalidTreeError} If the offer tree is empty or invalid.
44
+ * @throws {InvalidTreeHeightError} If the tree exceeds the allowed height.
45
+ * @throws {InvalidMidnightOfferGroupError} If a tree request uses an invalid explicit group.
46
+ * @throws {InvalidMidnightRateRatifierV1RateError} If a Rate V1 tree request has a negative leaf rate.
47
+ * @throws {InvalidMidnightRateRatifierV1TickError} If a Rate V1 tree request has an offer tick below the ratifier's minimum.
48
+ * @throws {NonPositiveInputError} If `loanAssets` or `expiresAt` is not positive.
49
+ * @throws {NegativeInputError} If `reservedLoanAssets` or a cancellation ceiling is negative.
50
+ * @throws {InputExceedsMaxError} If `loanAssets + reservedLoanAssets` exceeds uint256, a cancellation ceiling exceeds uint128, or explicit expiry reaches an offer's expiry while every offer is still live at the reference time.
51
+ * @throws {MidnightCalldataEncodingError} If the loan-token address or publication input cannot be encoded.
52
+ * @throws {MidnightOfferMarketLoanTokenMismatchError} If an offer uses a different loan token.
53
+ * @throws {MidnightOfferSideMismatchError} If an offer is not a buy offer.
54
+ * @throws {MidnightOfferReduceOnlyError} If an offer is reduce-only.
55
+ * @throws {MidnightOfferMakerMismatchError} If an offer names another maker.
56
+ * @throws {MidnightOfferCallbackNotSupportedError} If an offer has a callback.
57
+ * @throws {MidnightOfferContinuousFeeCapError} If an offer sets a nonzero continuous fee cap.
58
+ * @throws {MidnightOfferExpiredError} If an offer expires at or before the pinned block timestamp.
59
+ * @throws {MidnightOfferExpiryAfterMaturityError} If an offer expiry exceeds its market maturity.
60
+ * @throws {MidnightOfferGroupConsumedError} If an offer group has no capacity remaining.
61
+ * @throws {MidnightOfferTickSpacingError} If an offer tick is not accessible in its market.
62
+ * @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} If the market fee exceeds an offer's cap.
63
+ * @throws {MidnightOfferRateBoundUnreachableError} If a Rate V1 offer cannot satisfy its rate bound.
64
+ * @throws {MidnightMarketMaturityTooFarError} If an uncreated market matures more than 100 years after offer expiry.
65
+ * @throws {MidnightMarketLltvNotEnabledError} If an uncreated market uses a disabled LLTV.
66
+ * @throws {MidnightMarketLiquidationCursorNotEnabledError} If an uncreated market uses a disabled liquidation cursor.
67
+ * @throws {MidnightMarketOracleWithoutCodeError} If an uncreated market's oracle has no code.
68
+ * @throws {MidnightOfferMarketChainMismatchError} If an offer targets another chain.
69
+ * @throws {MidnightOfferMarketAddressMismatchError} If an offer targets another Midnight deployment.
70
+ * @throws {MidnightOfferRatifierMismatchError} If an offer uses a different ratifier than the tree's route.
71
+ * @throws {MidnightPayloadDecodeError} If the offers cannot be encoded in the publication payload,
72
+ * including when the encoded payload exceeds its size limit; split the offer tree.
73
+ * @throws {InvalidMidnightHexInputError} If a cancellation group is not bytes32.
74
+ * @throws {DuplicateMidnightGroupCancellationError} If the same group is cancelled more than once.
75
+ * @throws {MidnightReplacementGroupCancelledError} If a cancellation overlaps the published tree.
76
+ * @throws {ExpiredDeadlineError} If the resolved deadline is at or before the reference time or
77
+ * pinned block timestamp, or an offer has expired by the reference time but not at the pinned
78
+ * block; this skips API validation, ratification and payload encoding.
79
+ * @throws {MidnightOfferSellerReceiverMismatchError} If an offer routes proceeds to someone other than the maker.
80
+ * @throws {ChainIdMismatchError} If the configured or transport chain differs from the requested chain.
81
+ * @throws {UnsupportedChainIdError} If the chain has no address registry.
82
+ * @throws {UnknownAddressError} If a required deployment is not registered.
83
+ * @throws {MissingContractCodeError} If a registered write target has no code.
84
+ * @throws {MidnightMempoolValidationError} If optional API validation rejects the tree.
85
+ * @throws {MidnightApiError} If API validation returns a non-2xx response.
86
+ * @throws {InvalidMidnightApiResponseError} If the API returns malformed successful validation data.
87
+ * @throws {viem.BaseError} If a chain, deployment, pinned offer-state, allowance or authorization read fails.
88
+ * @example
89
+ * ```ts
90
+ * import { buildTransactions, prepareMidnightMakeLend } from "@morpho-org/morpho-sdk";
91
+ * import { type Offer, Tree } from "@morpho-org/morpho-sdk/midnight/entities";
92
+ * import { type Address, createPublicClient, http } from "viem";
93
+ * import { base } from "viem/chains";
94
+ *
95
+ * async function buildLend(maker: Address, loanToken: Address, buyOffers: readonly Offer[]) {
96
+ * const client = createPublicClient({ chain: base, transport: http() });
97
+ * // Use the maker's proposed buy offers, each naming the Base PriceRatifierV1.
98
+ * const offers = Tree.create({ type: "priceV1", entries: buyOffers.map(offer => ({ offer })) });
99
+ * const plan = await prepareMidnightMakeLend(client, {
100
+ * chainId: base.id, account: maker, offers, loanToken, loanAssets: 1_000_000n,
101
+ * now: (await client.getBlock()).timestamp,
102
+ * });
103
+ * // Simulate and send the transactions in order from maker.
104
+ * return buildTransactions(plan);
105
+ * }
106
+ * ```
107
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
108
+ */
109
+ export async function prepareMidnightMakeLend(client, params) {
110
+ return prepareFundedMidnightMakerPublication(client, {
111
+ params,
112
+ operation: "lend",
113
+ });
114
+ }
115
+ const fundedPublications = {
116
+ lend: {
117
+ type: "midnightMakeLend",
118
+ label: "Publish Midnight lend offers",
119
+ parse: parseMakeLendParams,
120
+ },
121
+ repay: {
122
+ type: "midnightMakeRepay",
123
+ label: "Publish Midnight repay offers",
124
+ parse: parseMakeRepayParams,
125
+ },
126
+ };
127
+ /**
128
+ * @internal Prepares a buy-offer publication with the core loan-token allowance needed at fill
129
+ * time, through the operation's entity parse constructor.
130
+ */
131
+ export async function prepareFundedMidnightMakerPublication(client, { params, operation, }) {
132
+ const { chainId, account, loanToken, loanAssets, reservedLoanAssets } = params;
133
+ const { type, label, parse } = fundedPublications[operation];
134
+ const { parsed, inputs, calldataOrigin } = await prepareMidnightMakerPublication(client, {
135
+ params,
136
+ parse: (raw, context) => parse({ ...raw, loanToken, loanAssets, reservedLoanAssets }, context),
137
+ });
138
+ const midnight = getChainAddress(chainId, "midnight");
139
+ // Validation only; the entity checks the same allowance bound in getRequirements().
140
+ parseMidnightApprovalRequirements({
141
+ viemClient: client,
142
+ chainId,
143
+ token: parsed.loanToken,
144
+ owner: account,
145
+ spender: midnight,
146
+ amount: parsed.approvalAmount,
147
+ });
148
+ const [{ approvals }, authorization] = await Promise.all([
149
+ getTokenRequirements(client, {
150
+ chainId,
151
+ owner: account,
152
+ token: parsed.loanToken,
153
+ spender: midnight,
154
+ amount: parsed.approvalAmount,
155
+ approvalId: (index) => `${type}:approval:${index}`,
156
+ }),
157
+ prepareMidnightBundleAuthorization(client, { chainId, account }),
158
+ ]);
159
+ return deepFreeze({
160
+ version: 2,
161
+ chainId,
162
+ account,
163
+ expiresAt: Number(inputs.deadline),
164
+ ...(calldataOrigin && { calldataOrigin }),
165
+ steps: [
166
+ ...approvals,
167
+ ...(authorization === undefined ? [] : [authorization]),
168
+ { id: type, label, action: { type, inputs } },
169
+ ],
170
+ signatureRequests: [],
171
+ });
172
+ }
@@ -0,0 +1,118 @@
1
+ import type { Client } from "viem";
2
+ import type { TransactionPlan } from "../types.js";
3
+ import { type MidnightMakeLendPlanParams } from "./makeLend.js";
4
+ /**
5
+ * Inputs for publishing resting reduce-only Midnight buy offers against existing maker debt.
6
+ * `loanAssets` and `reservedLoanAssets` set the core allowance checked for later fills.
7
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
8
+ */
9
+ export type MidnightMakeRepayPlanParams = MidnightMakeLendPlanParams;
10
+ /**
11
+ * Prepares a PriceRatifierV1 or RateRatifierV1 publication of resting reduce-only buy offers.
12
+ * The submitting maker must have debt in every offer market. Publication activates the root
13
+ * without repaying debt or moving tokens. Midnight pulls ERC-20 loan tokens only if a taker
14
+ * later fills an offer; preparation checks core allowance for `loanAssets + reservedLoanAssets`.
15
+ * Native ETH funding is not supported. Separate approval and authorization transactions persist
16
+ * after publication or expiry. The saved plan builds offline without the tree or a root signature.
17
+ * Builds the offer tree and checks the offer-capped `expiresAt` first, then validates the
18
+ * publication with a plan-side copy of the entity `makeRepay` constructor, in its order, except
19
+ * that malformed cancellations are rejected before any state read, and a deadline already reached
20
+ * at the pinned block is rejected before the mempool API call. So an
21
+ * input with several errors can fail on the tree or expiry here where the entity reports another
22
+ * error first. The chain and the bundle, Midnight and ratifier code are checked once, right before
23
+ * the first publication-state read. The allowance bound is checked like the entity's
24
+ * `getRequirements()`, after the publication is parsed and before the allowance read.
25
+ *
26
+ * @param client - Plain viem client for network, deployment, offer and prerequisite reads.
27
+ * @param params - Maker, offer tree or tree creation request, and loan-token allowance bounds.
28
+ * @param params.chainId - Chain containing Midnight, MidnightBundlesV2 and the selected ratifier.
29
+ * @param params.account - Non-zero maker with debt in every offer market; it names itself on every offer and sends the plan.
30
+ * @param params.offers - Caller-supplied reduce-only buy-offer tree, or a PriceRatifierV1 or RateRatifierV1 tree creation request.
31
+ * @param params.validation - Optional mempool API request controls; `false` skips the API call.
32
+ * @param params.cancellations - Optional groups and consumed ceilings to cancel atomically with publication; must not overlap the new tree.
33
+ * Omitting it cancels nothing (an untyped JavaScript `null` does too).
34
+ * @param params.loanToken - Loan token shared by every offer market.
35
+ * @param params.loanAssets - Positive loan assets to cover in the core allowance check; count an alternative offer group's budget once.
36
+ * @param params.reservedLoanAssets - Optional loan assets reserved by other open groups, excluding cancelled groups; defaults to `0n`.
37
+ * @param params.now - Reference Unix timestamp in seconds for plan expiry; omitting it uses the device clock (an untyped JavaScript `null` does too).
38
+ * @param params.expiresAt - Unix seconds. Defaults to the earlier of `now + 2h` and the earliest offer expiry minus one second.
39
+ * @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
40
+ * @returns A frozen, signature-free plan.
41
+ * @throws {InvalidBigIntInputError} If `loanAssets`, a cancellation ceiling, or a supplied non-null `now`
42
+ * or `reservedLoanAssets` is not a bigint; checked before any request.
43
+ * @throws {ZeroAccountError} If the submitting account is zero.
44
+ * @throws {InvalidTransactionPlanError} If the account is not an address, calldata origin exceeds 1 MiB,
45
+ * or a supplied non-null `cancellations` is not an array or has a non-object entry; checked
46
+ * before any request.
47
+ * @throws {InvalidCalldataOriginError} If calldata origin is not nonempty, even-length hex.
48
+ * @throws {NonIntegerInputError} If `expiresAt` is not a safe integer.
49
+ * @throws {NonPositiveInputError} If `loanAssets` or `expiresAt` is not positive.
50
+ * @throws {NegativeInputError} If `reservedLoanAssets` or a cancellation ceiling is negative.
51
+ * @throws {InvalidTreeError} If the supplied tree request has no offers or is invalid.
52
+ * @throws {InvalidTreeHeightError} If the tree exceeds the maximum height.
53
+ * @throws {InvalidMidnightOfferGroupError} If a tree request uses an invalid explicit group.
54
+ * @throws {InvalidMidnightRateRatifierV1RateError} If a Rate V1 tree request has a negative leaf rate.
55
+ * @throws {InvalidMidnightRateRatifierV1TickError} If a Rate V1 tree request has an offer tick below the ratifier's minimum.
56
+ * @throws {MidnightCalldataEncodingError} If the loan-token address, offer tree or publication input cannot be encoded.
57
+ * @throws {MidnightOfferSellerReceiverMismatchError} If a tree creation request has a sell leaf that names
58
+ * `account` as maker with a zero `receiverIfMakerIsSeller`; checked before the side check. A sell
59
+ * leaf naming another maker throws `MidnightOfferMakerMismatchError` instead.
60
+ * @throws {MidnightOfferSideMismatchError} If an offer is not a buy.
61
+ * @throws {MidnightOfferNotReduceOnlyError} If an offer is not reduce-only.
62
+ * @throws {MidnightOfferNoDebtError} If the maker has no debt in an offer market.
63
+ * @throws {MidnightOfferMakerMismatchError} If an offer names a maker other than `account`.
64
+ * @throws {MidnightOfferCallbackNotSupportedError} If an offer has a callback.
65
+ * @throws {MidnightOfferContinuousFeeCapError} If an offer sets a nonzero continuous fee cap.
66
+ * @throws {MidnightOfferMarketLoanTokenMismatchError} If an offer uses a different loan token.
67
+ * @throws {MidnightOfferMarketChainMismatchError} If an offer targets another chain.
68
+ * @throws {MidnightOfferMarketAddressMismatchError} If an offer targets another Midnight deployment.
69
+ * @throws {MidnightOfferRatifierMismatchError} If an offer names a different ratifier than the tree's route.
70
+ * @throws {MidnightOfferExpiredError} If an offer expires at or before the pinned block timestamp.
71
+ * @throws {MidnightOfferExpiryAfterMaturityError} If an offer expiry exceeds its market maturity.
72
+ * @throws {MidnightOfferGroupConsumedError} If an offer group has no capacity remaining.
73
+ * @throws {MidnightOfferTickSpacingError} If an offer tick is not accessible in its market.
74
+ * @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} If the market fee exceeds an offer's cap.
75
+ * @throws {MidnightOfferRateBoundUnreachableError} If a Rate V1 offer cannot satisfy its rate bound.
76
+ * @throws {MidnightMarketMaturityTooFarError} If an uncreated market matures more than 100 years after offer expiry.
77
+ * @throws {MidnightMarketLltvNotEnabledError} If an uncreated market uses a disabled LLTV.
78
+ * @throws {MidnightMarketLiquidationCursorNotEnabledError} If an uncreated market uses a disabled liquidation cursor.
79
+ * @throws {MidnightMarketOracleWithoutCodeError} If an uncreated market's oracle has no code.
80
+ * @throws {MidnightPayloadDecodeError} If the offers cannot be encoded in the publication payload,
81
+ * including when the encoded payload exceeds its size limit; split the offer tree.
82
+ * @throws {InvalidMidnightHexInputError} If a cancellation group is not bytes32.
83
+ * @throws {DuplicateMidnightGroupCancellationError} If the same group is cancelled more than once.
84
+ * @throws {InputExceedsMaxError} If the allowance bound exceeds uint256, a cancellation ceiling exceeds uint128, or explicit expiry reaches an offer's expiry while every offer is still live at the reference time.
85
+ * @throws {MidnightReplacementGroupCancelledError} If a cancellation overlaps the published tree.
86
+ * @throws {ExpiredDeadlineError} If the resolved deadline is at or before the reference time or
87
+ * pinned block timestamp, or an offer has expired by the reference time but not at the pinned
88
+ * block; this skips API validation.
89
+ * @throws {ChainIdMismatchError} If the configured or transport chain differs from the requested chain.
90
+ * @throws {UnsupportedChainIdError} If the chain has no address registry.
91
+ * @throws {UnknownAddressError} If a required deployment is not registered.
92
+ * @throws {MissingContractCodeError} If a registered write target has no code.
93
+ * @throws {MidnightMempoolValidationError} If optional API validation rejects the tree.
94
+ * @throws {MidnightApiError} If API validation returns a non-2xx response.
95
+ * @throws {InvalidMidnightApiResponseError} If the API returns malformed successful validation data.
96
+ * @throws {viem.BaseError} If a chain, deployment, pinned offer-state, allowance or authorization read fails.
97
+ * @example
98
+ * ```ts
99
+ * import { buildTransactions, prepareMidnightMakeRepay } from "@morpho-org/morpho-sdk";
100
+ * import { type Offer, Tree } from "@morpho-org/morpho-sdk/midnight/entities";
101
+ * import { type Address, createPublicClient, http } from "viem";
102
+ * import { base } from "viem/chains";
103
+ *
104
+ * async function buildRepayOffers(maker: Address, loanToken: Address, exitOffers: readonly Offer[]) {
105
+ * const client = createPublicClient({ chain: base, transport: http() });
106
+ * // Use the maker's proposed reduce-only buy offers naming the Base PriceRatifierV1.
107
+ * const offers = Tree.create({ type: "priceV1", entries: exitOffers.map(offer => ({ offer })) });
108
+ * const plan = await prepareMidnightMakeRepay(client, {
109
+ * chainId: base.id, account: maker, offers, loanToken, loanAssets: 1_000_000n,
110
+ * now: (await client.getBlock()).timestamp,
111
+ * });
112
+ * // Simulate and send the transactions in order from maker.
113
+ * return buildTransactions(plan);
114
+ * }
115
+ * ```
116
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
117
+ */
118
+ export declare function prepareMidnightMakeRepay(client: Client, params: MidnightMakeRepayPlanParams): Promise<TransactionPlan>;
@@ -0,0 +1,115 @@
1
+ import { prepareFundedMidnightMakerPublication, } from "./makeLend.js";
2
+ /**
3
+ * Prepares a PriceRatifierV1 or RateRatifierV1 publication of resting reduce-only buy offers.
4
+ * The submitting maker must have debt in every offer market. Publication activates the root
5
+ * without repaying debt or moving tokens. Midnight pulls ERC-20 loan tokens only if a taker
6
+ * later fills an offer; preparation checks core allowance for `loanAssets + reservedLoanAssets`.
7
+ * Native ETH funding is not supported. Separate approval and authorization transactions persist
8
+ * after publication or expiry. The saved plan builds offline without the tree or a root signature.
9
+ * Builds the offer tree and checks the offer-capped `expiresAt` first, then validates the
10
+ * publication with a plan-side copy of the entity `makeRepay` constructor, in its order, except
11
+ * that malformed cancellations are rejected before any state read, and a deadline already reached
12
+ * at the pinned block is rejected before the mempool API call. So an
13
+ * input with several errors can fail on the tree or expiry here where the entity reports another
14
+ * error first. The chain and the bundle, Midnight and ratifier code are checked once, right before
15
+ * the first publication-state read. The allowance bound is checked like the entity's
16
+ * `getRequirements()`, after the publication is parsed and before the allowance read.
17
+ *
18
+ * @param client - Plain viem client for network, deployment, offer and prerequisite reads.
19
+ * @param params - Maker, offer tree or tree creation request, and loan-token allowance bounds.
20
+ * @param params.chainId - Chain containing Midnight, MidnightBundlesV2 and the selected ratifier.
21
+ * @param params.account - Non-zero maker with debt in every offer market; it names itself on every offer and sends the plan.
22
+ * @param params.offers - Caller-supplied reduce-only buy-offer tree, or a PriceRatifierV1 or RateRatifierV1 tree creation request.
23
+ * @param params.validation - Optional mempool API request controls; `false` skips the API call.
24
+ * @param params.cancellations - Optional groups and consumed ceilings to cancel atomically with publication; must not overlap the new tree.
25
+ * Omitting it cancels nothing (an untyped JavaScript `null` does too).
26
+ * @param params.loanToken - Loan token shared by every offer market.
27
+ * @param params.loanAssets - Positive loan assets to cover in the core allowance check; count an alternative offer group's budget once.
28
+ * @param params.reservedLoanAssets - Optional loan assets reserved by other open groups, excluding cancelled groups; defaults to `0n`.
29
+ * @param params.now - Reference Unix timestamp in seconds for plan expiry; omitting it uses the device clock (an untyped JavaScript `null` does too).
30
+ * @param params.expiresAt - Unix seconds. Defaults to the earlier of `now + 2h` and the earliest offer expiry minus one second.
31
+ * @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
32
+ * @returns A frozen, signature-free plan.
33
+ * @throws {InvalidBigIntInputError} If `loanAssets`, a cancellation ceiling, or a supplied non-null `now`
34
+ * or `reservedLoanAssets` is not a bigint; checked before any request.
35
+ * @throws {ZeroAccountError} If the submitting account is zero.
36
+ * @throws {InvalidTransactionPlanError} If the account is not an address, calldata origin exceeds 1 MiB,
37
+ * or a supplied non-null `cancellations` is not an array or has a non-object entry; checked
38
+ * before any request.
39
+ * @throws {InvalidCalldataOriginError} If calldata origin is not nonempty, even-length hex.
40
+ * @throws {NonIntegerInputError} If `expiresAt` is not a safe integer.
41
+ * @throws {NonPositiveInputError} If `loanAssets` or `expiresAt` is not positive.
42
+ * @throws {NegativeInputError} If `reservedLoanAssets` or a cancellation ceiling is negative.
43
+ * @throws {InvalidTreeError} If the supplied tree request has no offers or is invalid.
44
+ * @throws {InvalidTreeHeightError} If the tree exceeds the maximum height.
45
+ * @throws {InvalidMidnightOfferGroupError} If a tree request uses an invalid explicit group.
46
+ * @throws {InvalidMidnightRateRatifierV1RateError} If a Rate V1 tree request has a negative leaf rate.
47
+ * @throws {InvalidMidnightRateRatifierV1TickError} If a Rate V1 tree request has an offer tick below the ratifier's minimum.
48
+ * @throws {MidnightCalldataEncodingError} If the loan-token address, offer tree or publication input cannot be encoded.
49
+ * @throws {MidnightOfferSellerReceiverMismatchError} If a tree creation request has a sell leaf that names
50
+ * `account` as maker with a zero `receiverIfMakerIsSeller`; checked before the side check. A sell
51
+ * leaf naming another maker throws `MidnightOfferMakerMismatchError` instead.
52
+ * @throws {MidnightOfferSideMismatchError} If an offer is not a buy.
53
+ * @throws {MidnightOfferNotReduceOnlyError} If an offer is not reduce-only.
54
+ * @throws {MidnightOfferNoDebtError} If the maker has no debt in an offer market.
55
+ * @throws {MidnightOfferMakerMismatchError} If an offer names a maker other than `account`.
56
+ * @throws {MidnightOfferCallbackNotSupportedError} If an offer has a callback.
57
+ * @throws {MidnightOfferContinuousFeeCapError} If an offer sets a nonzero continuous fee cap.
58
+ * @throws {MidnightOfferMarketLoanTokenMismatchError} If an offer uses a different loan token.
59
+ * @throws {MidnightOfferMarketChainMismatchError} If an offer targets another chain.
60
+ * @throws {MidnightOfferMarketAddressMismatchError} If an offer targets another Midnight deployment.
61
+ * @throws {MidnightOfferRatifierMismatchError} If an offer names a different ratifier than the tree's route.
62
+ * @throws {MidnightOfferExpiredError} If an offer expires at or before the pinned block timestamp.
63
+ * @throws {MidnightOfferExpiryAfterMaturityError} If an offer expiry exceeds its market maturity.
64
+ * @throws {MidnightOfferGroupConsumedError} If an offer group has no capacity remaining.
65
+ * @throws {MidnightOfferTickSpacingError} If an offer tick is not accessible in its market.
66
+ * @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} If the market fee exceeds an offer's cap.
67
+ * @throws {MidnightOfferRateBoundUnreachableError} If a Rate V1 offer cannot satisfy its rate bound.
68
+ * @throws {MidnightMarketMaturityTooFarError} If an uncreated market matures more than 100 years after offer expiry.
69
+ * @throws {MidnightMarketLltvNotEnabledError} If an uncreated market uses a disabled LLTV.
70
+ * @throws {MidnightMarketLiquidationCursorNotEnabledError} If an uncreated market uses a disabled liquidation cursor.
71
+ * @throws {MidnightMarketOracleWithoutCodeError} If an uncreated market's oracle has no code.
72
+ * @throws {MidnightPayloadDecodeError} If the offers cannot be encoded in the publication payload,
73
+ * including when the encoded payload exceeds its size limit; split the offer tree.
74
+ * @throws {InvalidMidnightHexInputError} If a cancellation group is not bytes32.
75
+ * @throws {DuplicateMidnightGroupCancellationError} If the same group is cancelled more than once.
76
+ * @throws {InputExceedsMaxError} If the allowance bound exceeds uint256, a cancellation ceiling exceeds uint128, or explicit expiry reaches an offer's expiry while every offer is still live at the reference time.
77
+ * @throws {MidnightReplacementGroupCancelledError} If a cancellation overlaps the published tree.
78
+ * @throws {ExpiredDeadlineError} If the resolved deadline is at or before the reference time or
79
+ * pinned block timestamp, or an offer has expired by the reference time but not at the pinned
80
+ * block; this skips API validation.
81
+ * @throws {ChainIdMismatchError} If the configured or transport chain differs from the requested chain.
82
+ * @throws {UnsupportedChainIdError} If the chain has no address registry.
83
+ * @throws {UnknownAddressError} If a required deployment is not registered.
84
+ * @throws {MissingContractCodeError} If a registered write target has no code.
85
+ * @throws {MidnightMempoolValidationError} If optional API validation rejects the tree.
86
+ * @throws {MidnightApiError} If API validation returns a non-2xx response.
87
+ * @throws {InvalidMidnightApiResponseError} If the API returns malformed successful validation data.
88
+ * @throws {viem.BaseError} If a chain, deployment, pinned offer-state, allowance or authorization read fails.
89
+ * @example
90
+ * ```ts
91
+ * import { buildTransactions, prepareMidnightMakeRepay } from "@morpho-org/morpho-sdk";
92
+ * import { type Offer, Tree } from "@morpho-org/morpho-sdk/midnight/entities";
93
+ * import { type Address, createPublicClient, http } from "viem";
94
+ * import { base } from "viem/chains";
95
+ *
96
+ * async function buildRepayOffers(maker: Address, loanToken: Address, exitOffers: readonly Offer[]) {
97
+ * const client = createPublicClient({ chain: base, transport: http() });
98
+ * // Use the maker's proposed reduce-only buy offers naming the Base PriceRatifierV1.
99
+ * const offers = Tree.create({ type: "priceV1", entries: exitOffers.map(offer => ({ offer })) });
100
+ * const plan = await prepareMidnightMakeRepay(client, {
101
+ * chainId: base.id, account: maker, offers, loanToken, loanAssets: 1_000_000n,
102
+ * now: (await client.getBlock()).timestamp,
103
+ * });
104
+ * // Simulate and send the transactions in order from maker.
105
+ * return buildTransactions(plan);
106
+ * }
107
+ * ```
108
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
109
+ */
110
+ export async function prepareMidnightMakeRepay(client, params) {
111
+ return prepareFundedMidnightMakerPublication(client, {
112
+ params,
113
+ operation: "repay",
114
+ });
115
+ }
@@ -0,0 +1,104 @@
1
+ import type { Client } from "viem";
2
+ import type { TransactionPlan } from "../types.js";
3
+ import { type MidnightMakerPublicationPlanParams } from "./makerPublication.js";
4
+ /**
5
+ * Inputs for publishing resting Midnight reduce-only sell offers against the maker's credit.
6
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
7
+ */
8
+ export type MidnightMakeWithdrawPlanParams = MidnightMakerPublicationPlanParams;
9
+ /**
10
+ * Prepares publication of resting reduce-only sell offers through MidnightBundlesV2.
11
+ * The bundle activates the PriceRatifierV1 or RateRatifierV1 root and can cancel old groups
12
+ * atomically. The maker must have current credit in each offer's market. Publication does not
13
+ * reduce that credit or transfer tokens. An eventual fill is a separate transaction.
14
+ *
15
+ * No token approval or signature is needed. The standalone bundle authorization (if needed)
16
+ * and the ratifier grant made by the bundle persist until revoked.
17
+ * Builds the offer tree and checks the offer-capped `expiresAt` first, then validates the
18
+ * publication with a plan-side copy of the entity `makeWithdraw` constructor, in its order, except
19
+ * that malformed cancellations are rejected before any state read, and a bundle deadline already
20
+ * reached at the pinned block is rejected before the mempool API call, which the entity flow does
21
+ * not check. So an
22
+ * input with several errors can fail on the tree or expiry here where the entity reports another
23
+ * error first. The chain and the bundle, Midnight and ratifier code are checked once, right before
24
+ * the first publication-state read.
25
+ *
26
+ * @param client - Plain viem client used to check network, deployments, offers and bundle authorization.
27
+ * @param params - Maker, caller-supplied tree or tree creation request, and optional cancellations.
28
+ * @param params.expiresAt - Unix seconds. Defaults to the earlier of `now + 2h` and the first offer expiry minus one second.
29
+ * @returns A frozen plan that can be restored and built offline without the original tree.
30
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now` or a cancellation ceiling is not a bigint;
31
+ * checked before any request.
32
+ * @throws {ZeroAccountError} If the submitting account is zero.
33
+ * @throws {InvalidTransactionPlanError} If the account is not an address, calldata origin exceeds 1 MiB,
34
+ * or a supplied non-null `cancellations` is not an array or has a non-object entry; checked
35
+ * before any request.
36
+ * @throws {InvalidCalldataOriginError} If the supplied calldata origin is not nonempty, even-length hex.
37
+ * @throws {NonIntegerInputError} If `expiresAt` is not a safe integer.
38
+ * @throws {NonPositiveInputError} If `expiresAt` is not positive.
39
+ * @throws {NegativeInputError} If a cancellation ceiling is negative.
40
+ * @throws {InvalidTreeError} If the offer tree is empty or invalid.
41
+ * @throws {InvalidTreeHeightError} If the tree exceeds the maximum height.
42
+ * @throws {InvalidMidnightOfferGroupError} If a tree request uses an invalid explicit group.
43
+ * @throws {InvalidMidnightRateRatifierV1RateError} If a Rate V1 tree request has a negative leaf rate.
44
+ * @throws {InvalidMidnightRateRatifierV1TickError} If a Rate V1 tree request has an offer tick below the ratifier's minimum.
45
+ * @throws {MidnightCalldataEncodingError} If the offer tree or bundle input cannot be ABI-encoded.
46
+ * @throws {MidnightOfferSideMismatchError} If an offer is not a sell offer.
47
+ * @throws {MidnightOfferNotReduceOnlyError} If an offer is not reduce-only.
48
+ * @throws {MidnightOfferNoCreditError} If the maker has no credit in an offer's market.
49
+ * @throws {MidnightOfferMakerMismatchError} If an offer names another maker.
50
+ * @throws {MidnightOfferSellerReceiverMismatchError} If an offer routes proceeds to someone other than the maker.
51
+ * @throws {MidnightOfferCallbackNotSupportedError} If an offer has a callback.
52
+ * @throws {MidnightOfferContinuousFeeCapError} If an offer sets a nonzero continuous fee cap.
53
+ * @throws {MidnightOfferRatifierMismatchError} If an offer names a different ratifier than the tree's route.
54
+ * @throws {InvalidMidnightHexInputError} If a cancellation group is not bytes32.
55
+ * @throws {DuplicateMidnightGroupCancellationError} If a group is cancelled more than once.
56
+ * @throws {MidnightReplacementGroupCancelledError} If a cancelled group appears in the new tree.
57
+ * @throws {InputExceedsMaxError} If explicit expiry is at or after the first offer expiry while every offer is still live at the reference time, or a cancellation ceiling exceeds uint128.
58
+ * @throws {ExpiredDeadlineError} If the resolved deadline is at or before the reference time or
59
+ * pinned block timestamp, or an offer has expired by the reference time but not at the pinned
60
+ * block; this skips API validation.
61
+ * @throws {MidnightOfferExpiredError} If an offer has expired at the pinned block.
62
+ * @throws {MidnightOfferExpiryAfterMaturityError} If an offer expiry exceeds its market maturity.
63
+ * @throws {MidnightOfferGroupConsumedError} If an offer group has no capacity remaining.
64
+ * @throws {MidnightOfferTickSpacingError} If an offer tick is not accessible in its market.
65
+ * @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} If the market fee exceeds an offer's cap.
66
+ * @throws {MidnightOfferZeroPriceSellError} If a sell offer has a zero tick.
67
+ * @throws {MidnightOfferRateBoundUnreachableError} If a Rate V1 offer cannot satisfy its rate bound.
68
+ * @throws {MidnightMarketMaturityTooFarError} If an uncreated market matures more than 100 years after the offer expires.
69
+ * @throws {MidnightMarketLltvNotEnabledError} If an uncreated market uses a disabled LLTV.
70
+ * @throws {MidnightMarketLiquidationCursorNotEnabledError} If an uncreated market uses a disabled liquidation cursor.
71
+ * @throws {MidnightMarketOracleWithoutCodeError} If an uncreated market's oracle has no code.
72
+ * @throws {MidnightOfferMarketChainMismatchError} If an offer's market uses another chain.
73
+ * @throws {MidnightOfferMarketAddressMismatchError} If an offer's market names another Midnight deployment.
74
+ * @throws {MidnightPayloadDecodeError} If the offers cannot be encoded in the publication payload,
75
+ * including when the encoded payload exceeds its size limit; split the offer tree.
76
+ * @throws {ChainIdMismatchError} If the configured or transport chain differs from `chainId`.
77
+ * @throws {UnsupportedChainIdError} If the chain has no address registry.
78
+ * @throws {UnknownAddressError} If a required deployment is not registered.
79
+ * @throws {MissingContractCodeError} If a registered write target has no code.
80
+ * @throws {MidnightMempoolValidationError} If optional API validation rejects the tree.
81
+ * @throws {MidnightApiError} If API validation returns a non-2xx response.
82
+ * @throws {InvalidMidnightApiResponseError} If the API returns malformed successful validation data.
83
+ * @throws {viem.BaseError} If a chain, deployment, pinned offer-state or authorization read fails.
84
+ * @example
85
+ * ```ts
86
+ * import { buildTransactions, prepareMidnightMakeWithdraw } from "@morpho-org/morpho-sdk";
87
+ * import { type Offer, Tree } from "@morpho-org/morpho-sdk/midnight/entities";
88
+ * import { type Address, createPublicClient, http } from "viem";
89
+ * import { base } from "viem/chains";
90
+ *
91
+ * async function buildExit(maker: Address, exitOffers: readonly Offer[]) {
92
+ * const client = createPublicClient({ chain: base, transport: http() });
93
+ * // Use the maker's proposed reduce-only sell offers naming the Base PriceRatifierV1.
94
+ * const offers = Tree.create({ type: "priceV1", entries: exitOffers.map(offer => ({ offer })) });
95
+ * const plan = await prepareMidnightMakeWithdraw(client, {
96
+ * chainId: base.id, account: maker, offers, now: (await client.getBlock()).timestamp,
97
+ * });
98
+ * // Simulate, then send in order from maker on Base.
99
+ * return buildTransactions(plan);
100
+ * }
101
+ * ```
102
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
103
+ */
104
+ export declare function prepareMidnightMakeWithdraw(client: Client, params: MidnightMakeWithdrawPlanParams): Promise<TransactionPlan>;
@@ -0,0 +1,123 @@
1
+ import { deepFreeze } from "@morpho-org/morpho-ts";
2
+ import { prepareMidnightBundleAuthorization } from "./authorization.js";
3
+ import { prepareMidnightMakerPublication, } from "./makerPublication.js";
4
+ import { parseMakeWithdrawParams } from "./prepare.js";
5
+ /**
6
+ * Prepares publication of resting reduce-only sell offers through MidnightBundlesV2.
7
+ * The bundle activates the PriceRatifierV1 or RateRatifierV1 root and can cancel old groups
8
+ * atomically. The maker must have current credit in each offer's market. Publication does not
9
+ * reduce that credit or transfer tokens. An eventual fill is a separate transaction.
10
+ *
11
+ * No token approval or signature is needed. The standalone bundle authorization (if needed)
12
+ * and the ratifier grant made by the bundle persist until revoked.
13
+ * Builds the offer tree and checks the offer-capped `expiresAt` first, then validates the
14
+ * publication with a plan-side copy of the entity `makeWithdraw` constructor, in its order, except
15
+ * that malformed cancellations are rejected before any state read, and a bundle deadline already
16
+ * reached at the pinned block is rejected before the mempool API call, which the entity flow does
17
+ * not check. So an
18
+ * input with several errors can fail on the tree or expiry here where the entity reports another
19
+ * error first. The chain and the bundle, Midnight and ratifier code are checked once, right before
20
+ * the first publication-state read.
21
+ *
22
+ * @param client - Plain viem client used to check network, deployments, offers and bundle authorization.
23
+ * @param params - Maker, caller-supplied tree or tree creation request, and optional cancellations.
24
+ * @param params.expiresAt - Unix seconds. Defaults to the earlier of `now + 2h` and the first offer expiry minus one second.
25
+ * @returns A frozen plan that can be restored and built offline without the original tree.
26
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now` or a cancellation ceiling is not a bigint;
27
+ * checked before any request.
28
+ * @throws {ZeroAccountError} If the submitting account is zero.
29
+ * @throws {InvalidTransactionPlanError} If the account is not an address, calldata origin exceeds 1 MiB,
30
+ * or a supplied non-null `cancellations` is not an array or has a non-object entry; checked
31
+ * before any request.
32
+ * @throws {InvalidCalldataOriginError} If the supplied calldata origin is not nonempty, even-length hex.
33
+ * @throws {NonIntegerInputError} If `expiresAt` is not a safe integer.
34
+ * @throws {NonPositiveInputError} If `expiresAt` is not positive.
35
+ * @throws {NegativeInputError} If a cancellation ceiling is negative.
36
+ * @throws {InvalidTreeError} If the offer tree is empty or invalid.
37
+ * @throws {InvalidTreeHeightError} If the tree exceeds the maximum height.
38
+ * @throws {InvalidMidnightOfferGroupError} If a tree request uses an invalid explicit group.
39
+ * @throws {InvalidMidnightRateRatifierV1RateError} If a Rate V1 tree request has a negative leaf rate.
40
+ * @throws {InvalidMidnightRateRatifierV1TickError} If a Rate V1 tree request has an offer tick below the ratifier's minimum.
41
+ * @throws {MidnightCalldataEncodingError} If the offer tree or bundle input cannot be ABI-encoded.
42
+ * @throws {MidnightOfferSideMismatchError} If an offer is not a sell offer.
43
+ * @throws {MidnightOfferNotReduceOnlyError} If an offer is not reduce-only.
44
+ * @throws {MidnightOfferNoCreditError} If the maker has no credit in an offer's market.
45
+ * @throws {MidnightOfferMakerMismatchError} If an offer names another maker.
46
+ * @throws {MidnightOfferSellerReceiverMismatchError} If an offer routes proceeds to someone other than the maker.
47
+ * @throws {MidnightOfferCallbackNotSupportedError} If an offer has a callback.
48
+ * @throws {MidnightOfferContinuousFeeCapError} If an offer sets a nonzero continuous fee cap.
49
+ * @throws {MidnightOfferRatifierMismatchError} If an offer names a different ratifier than the tree's route.
50
+ * @throws {InvalidMidnightHexInputError} If a cancellation group is not bytes32.
51
+ * @throws {DuplicateMidnightGroupCancellationError} If a group is cancelled more than once.
52
+ * @throws {MidnightReplacementGroupCancelledError} If a cancelled group appears in the new tree.
53
+ * @throws {InputExceedsMaxError} If explicit expiry is at or after the first offer expiry while every offer is still live at the reference time, or a cancellation ceiling exceeds uint128.
54
+ * @throws {ExpiredDeadlineError} If the resolved deadline is at or before the reference time or
55
+ * pinned block timestamp, or an offer has expired by the reference time but not at the pinned
56
+ * block; this skips API validation.
57
+ * @throws {MidnightOfferExpiredError} If an offer has expired at the pinned block.
58
+ * @throws {MidnightOfferExpiryAfterMaturityError} If an offer expiry exceeds its market maturity.
59
+ * @throws {MidnightOfferGroupConsumedError} If an offer group has no capacity remaining.
60
+ * @throws {MidnightOfferTickSpacingError} If an offer tick is not accessible in its market.
61
+ * @throws {MidnightOfferContinuousFeeCapBelowMarketFeeError} If the market fee exceeds an offer's cap.
62
+ * @throws {MidnightOfferZeroPriceSellError} If a sell offer has a zero tick.
63
+ * @throws {MidnightOfferRateBoundUnreachableError} If a Rate V1 offer cannot satisfy its rate bound.
64
+ * @throws {MidnightMarketMaturityTooFarError} If an uncreated market matures more than 100 years after the offer expires.
65
+ * @throws {MidnightMarketLltvNotEnabledError} If an uncreated market uses a disabled LLTV.
66
+ * @throws {MidnightMarketLiquidationCursorNotEnabledError} If an uncreated market uses a disabled liquidation cursor.
67
+ * @throws {MidnightMarketOracleWithoutCodeError} If an uncreated market's oracle has no code.
68
+ * @throws {MidnightOfferMarketChainMismatchError} If an offer's market uses another chain.
69
+ * @throws {MidnightOfferMarketAddressMismatchError} If an offer's market names another Midnight deployment.
70
+ * @throws {MidnightPayloadDecodeError} If the offers cannot be encoded in the publication payload,
71
+ * including when the encoded payload exceeds its size limit; split the offer tree.
72
+ * @throws {ChainIdMismatchError} If the configured or transport chain differs from `chainId`.
73
+ * @throws {UnsupportedChainIdError} If the chain has no address registry.
74
+ * @throws {UnknownAddressError} If a required deployment is not registered.
75
+ * @throws {MissingContractCodeError} If a registered write target has no code.
76
+ * @throws {MidnightMempoolValidationError} If optional API validation rejects the tree.
77
+ * @throws {MidnightApiError} If API validation returns a non-2xx response.
78
+ * @throws {InvalidMidnightApiResponseError} If the API returns malformed successful validation data.
79
+ * @throws {viem.BaseError} If a chain, deployment, pinned offer-state or authorization read fails.
80
+ * @example
81
+ * ```ts
82
+ * import { buildTransactions, prepareMidnightMakeWithdraw } from "@morpho-org/morpho-sdk";
83
+ * import { type Offer, Tree } from "@morpho-org/morpho-sdk/midnight/entities";
84
+ * import { type Address, createPublicClient, http } from "viem";
85
+ * import { base } from "viem/chains";
86
+ *
87
+ * async function buildExit(maker: Address, exitOffers: readonly Offer[]) {
88
+ * const client = createPublicClient({ chain: base, transport: http() });
89
+ * // Use the maker's proposed reduce-only sell offers naming the Base PriceRatifierV1.
90
+ * const offers = Tree.create({ type: "priceV1", entries: exitOffers.map(offer => ({ offer })) });
91
+ * const plan = await prepareMidnightMakeWithdraw(client, {
92
+ * chainId: base.id, account: maker, offers, now: (await client.getBlock()).timestamp,
93
+ * });
94
+ * // Simulate, then send in order from maker on Base.
95
+ * return buildTransactions(plan);
96
+ * }
97
+ * ```
98
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
99
+ */
100
+ export async function prepareMidnightMakeWithdraw(client, params) {
101
+ const { chainId, account } = params;
102
+ const { inputs, calldataOrigin } = await prepareMidnightMakerPublication(client, { params, parse: parseMakeWithdrawParams });
103
+ const authorization = await prepareMidnightBundleAuthorization(client, {
104
+ chainId,
105
+ account,
106
+ });
107
+ return deepFreeze({
108
+ version: 2,
109
+ chainId,
110
+ account,
111
+ expiresAt: Number(inputs.deadline),
112
+ ...(calldataOrigin && { calldataOrigin }),
113
+ steps: [
114
+ ...(authorization === undefined ? [] : [authorization]),
115
+ {
116
+ id: "midnightMakeWithdraw",
117
+ label: "Publish Midnight withdrawal offers",
118
+ action: { type: "midnightMakeWithdraw", inputs },
119
+ },
120
+ ],
121
+ signatureRequests: [],
122
+ });
123
+ }