@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
@@ -1,5 +1,6 @@
1
1
  import { Tree, type TreeCreateRequest } from "@morpho-org/midnight-sdk";
2
2
  import { type Address, type Hex } from "viem";
3
+ import type { MidnightCancelAndMakeParams } from "../types/midnightCancelAndMake.js";
3
4
  /** Preserves maker and sell-receiver errors before the upstream tree constructor. @internal */
4
5
  export declare const parseMidnightMakerTree: (params: {
5
6
  readonly offers: Extract<TreeCreateRequest, {
@@ -42,3 +43,23 @@ export declare const parseMidnightMakerFundingBinding: (params: {
42
43
  }) => {
43
44
  loanToken: `0x${string}`;
44
45
  };
46
+ /**
47
+ * Rejects malformed cancellations before any maker-state read, with the bundle parser's checks
48
+ * and order: group hex, then each ceiling's type, bounds and duplicate, then overlap with the new
49
+ * tree. Used by TransactionPlan maker constructors; entity flows run these checks in the bundle
50
+ * parser.
51
+ *
52
+ * @param params.cancellations - Groups to cancel with their consumption ceilings.
53
+ * @param params.tree - Parsed offer tree whose groups the bundle publishes.
54
+ * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
55
+ * @throws {InvalidBigIntInputError} when a `maxConsumed` ceiling is not a bigint.
56
+ * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
57
+ * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds uint128.
58
+ * @throws {DuplicateMidnightGroupCancellationError} when a group is cancelled more than once.
59
+ * @throws {MidnightReplacementGroupCancelledError} when a cancelled group is in the new tree.
60
+ * @internal
61
+ */
62
+ export declare const validateMidnightMakerCancellations: (params: {
63
+ readonly cancellations: MidnightCancelAndMakeParams["cancellations"];
64
+ readonly tree: ReturnType<typeof parseMidnightMakerTree>;
65
+ }) => void;
@@ -1,11 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseMidnightMakerFundingBinding = exports.parseMidnightMakerBinding = exports.parseMidnightMakerIntent = exports.parseMidnightMakerTree = void 0;
3
+ exports.validateMidnightMakerCancellations = exports.parseMidnightMakerFundingBinding = exports.parseMidnightMakerBinding = exports.parseMidnightMakerIntent = exports.parseMidnightMakerTree = void 0;
4
4
  const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
5
5
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
7
  const index_js_1 = require("../types/index.js");
8
8
  const encodeMidnightCalldata_js_1 = require("./encodeMidnightCalldata.js");
9
+ const validateMidnightBounds_js_1 = require("./validateMidnightBounds.js");
10
+ const validateMidnightPublication_js_1 = require("./validateMidnightPublication.js");
9
11
  const validateOfferSides_js_1 = require("./validateOfferSides.js");
10
12
  /** Preserves maker and sell-receiver errors before the upstream tree constructor. @internal */
11
13
  const parseMidnightMakerTree = (params) => {
@@ -152,3 +154,41 @@ const parseMidnightMakerFundingBinding = (params) => {
152
154
  return { loanToken: params.loanToken };
153
155
  };
154
156
  exports.parseMidnightMakerFundingBinding = parseMidnightMakerFundingBinding;
157
+ /**
158
+ * Rejects malformed cancellations before any maker-state read, with the bundle parser's checks
159
+ * and order: group hex, then each ceiling's type, bounds and duplicate, then overlap with the new
160
+ * tree. Used by TransactionPlan maker constructors; entity flows run these checks in the bundle
161
+ * parser.
162
+ *
163
+ * @param params.cancellations - Groups to cancel with their consumption ceilings.
164
+ * @param params.tree - Parsed offer tree whose groups the bundle publishes.
165
+ * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
166
+ * @throws {InvalidBigIntInputError} when a `maxConsumed` ceiling is not a bigint.
167
+ * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
168
+ * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds uint128.
169
+ * @throws {DuplicateMidnightGroupCancellationError} when a group is cancelled more than once.
170
+ * @throws {MidnightReplacementGroupCancelledError} when a cancelled group is in the new tree.
171
+ * @internal
172
+ */
173
+ const validateMidnightMakerCancellations = (params) => {
174
+ const { cancellations, tree } = params;
175
+ (0, validateMidnightPublication_js_1.validateMidnightCancellationGroups)(cancellations);
176
+ const cancelledGroups = new Set();
177
+ for (const [index, { group, maxConsumed }] of cancellations.entries()) {
178
+ if (typeof maxConsumed !== "bigint") {
179
+ throw new index_js_1.InvalidBigIntInputError(`cancellations[${index}].maxConsumed`, maxConsumed);
180
+ }
181
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)(`cancellations[${index}].maxConsumed`, maxConsumed);
182
+ const key = group.toLowerCase();
183
+ if (cancelledGroups.has(key)) {
184
+ throw new index_js_1.DuplicateMidnightGroupCancellationError({ index, group });
185
+ }
186
+ cancelledGroups.add(key);
187
+ }
188
+ for (const { group } of tree.offers) {
189
+ if (cancelledGroups.has(group.toLowerCase())) {
190
+ throw new index_js_1.MidnightReplacementGroupCancelledError({ group });
191
+ }
192
+ }
193
+ };
194
+ exports.validateMidnightMakerCancellations = validateMidnightMakerCancellations;
@@ -1,7 +1,7 @@
1
1
  import { type AccrualPosition, type InputMarketParams, type MarketId, type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Market as MidnightMarket, type MarketInput as MidnightMarketInput } from "@morpho-org/midnight-sdk";
3
3
  import { type Address } from "viem";
4
- import { type VaultV2BlueReallocation } from "../types/index.js";
4
+ import { type MidnightCollateralTransfer, type MidnightRepay, type VaultV2BlueReallocation } from "../types/index.js";
5
5
  /**
6
6
  * Rejects a reference time that is not a bigint, so a serialized timestamp fails with a typed
7
7
  * error before any deadline arithmetic.
@@ -223,6 +223,54 @@ export declare const getMidnightMaxSafeDebt: (params: {
223
223
  readonly collateral: readonly bigint[];
224
224
  readonly collateralPrices: readonly bigint[];
225
225
  }) => bigint;
226
+ /**
227
+ * @internal Rejects a Midnight borrow whose post-borrow debt exceeds the collateral's capacity at
228
+ * LLTV minus `DEFAULT_LLTV_BUFFER`, with the same check and error as the entity borrow flows.
229
+ * Used by TransactionPlan preparers; the entity keeps its inline check.
230
+ */
231
+ export declare const validateMidnightBorrowHealth: (params: {
232
+ readonly market: MidnightMarket;
233
+ readonly collateral: readonly bigint[];
234
+ readonly collateralPrices: readonly bigint[];
235
+ readonly debt: bigint;
236
+ readonly borrowUnits: bigint;
237
+ }) => void;
238
+ /**
239
+ * @internal Rejects a Midnight collateral withdrawal whose post-operation debt exceeds the remaining
240
+ * collateral's capacity at LLTV minus `DEFAULT_LLTV_BUFFER`, with the same check and error as the
241
+ * entity withdraw and repay-withdraw flows. Used by TransactionPlan preparers; the entity keeps its
242
+ * inline checks.
243
+ */
244
+ export declare const validateMidnightWithdrawHealth: (params: {
245
+ readonly market: MidnightMarket;
246
+ readonly collateral: readonly bigint[];
247
+ readonly collateralPrices: readonly bigint[];
248
+ readonly debt: bigint;
249
+ readonly withdrawAmount: bigint;
250
+ }) => void;
251
+ /**
252
+ * @internal Checks a direct Midnight repayment and collateral withdrawal against the position
253
+ * snapshot, in order: each withdrawal against the remaining collateral, an exact repayment against
254
+ * the debt, a full repayment cap against the debt, then the remaining debt against the remaining
255
+ * collateral's buffered capacity when collateral is withdrawn. Matches the entity
256
+ * `repayWithdrawCollateral` checks; used by TransactionPlan preparers, while the entity keeps its
257
+ * inline checks. Callers parse the withdrawals first.
258
+ * @throws {WithdrawExceedsCollateralError} If a withdrawal exceeds the remaining collateral.
259
+ * @throws {MidnightRepayExceedsDebtError} If an exact repayment exceeds the debt.
260
+ * @throws {MidnightTakeTargetUnreachableError} If a full repayment cap is below the debt.
261
+ * @throws {MissingMarketPriceError} If remaining collateral has no price for the health check.
262
+ * @throws {WithdrawMakesPositionUnhealthyError} If the remaining debt exceeds buffered capacity.
263
+ */
264
+ export declare const validateMidnightRepayWithdrawCollateralPosition: (params: {
265
+ readonly marketData: MidnightMarket;
266
+ readonly positionData: {
267
+ readonly collateral: readonly bigint[];
268
+ readonly debt: bigint;
269
+ };
270
+ readonly collateralPrices: readonly bigint[];
271
+ readonly repay: MidnightRepay;
272
+ readonly collateralWithdrawals: readonly MidnightCollateralTransfer[];
273
+ }) => void;
226
274
  /**
227
275
  * Validates that the resulting position stays within the safe LTV threshold
228
276
  * (LLTV minus buffer) after supplying additional collateral and borrowing.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateSlippageTolerance = exports.validateVaultV2BlueReallocations = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeVaultAsset = exports.validateMidnightNativeAmount = exports.validateNativeAsset = exports.validateChainId = exports.validatePositionHealth = exports.getMidnightMaxSafeDebt = exports.validateAccrualPosition = exports.validateMidnightMarketChainId = exports.validateReferralFee = exports.validateDeadline = exports.validateMarketParamsId = exports.validateUint256Field = void 0;
3
+ exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateSlippageTolerance = exports.validateVaultV2BlueReallocations = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeVaultAsset = exports.validateMidnightNativeAmount = exports.validateNativeAsset = exports.validateChainId = exports.validatePositionHealth = exports.validateMidnightRepayWithdrawCollateralPosition = exports.validateMidnightWithdrawHealth = exports.validateMidnightBorrowHealth = exports.getMidnightMaxSafeDebt = exports.validateAccrualPosition = exports.validateMidnightMarketChainId = exports.validateReferralFee = exports.validateDeadline = exports.validateMarketParamsId = exports.validateUint256Field = void 0;
4
4
  exports.validateReferenceTime = validateReferenceTime;
5
5
  exports.validateVaultDepositDeadline = validateVaultDepositDeadline;
6
6
  exports.validateUserAddress = validateUserAddress;
@@ -9,6 +9,7 @@ const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
9
9
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
10
10
  const viem_1 = require("viem");
11
11
  const index_js_1 = require("../types/index.js");
12
+ const computeMidnightPostWithdrawalCollateral_js_1 = require("./computeMidnightPostWithdrawalCollateral.js");
12
13
  const constant_js_1 = require("./constant.js");
13
14
  const reallocationPenalty_js_1 = require("./reallocationPenalty.js");
14
15
  const validateMidnightAccount_js_1 = require("./validateMidnightAccount.js");
@@ -320,6 +321,91 @@ const getMidnightMaxSafeDebt = (params) => {
320
321
  return maxSafeDebt;
321
322
  };
322
323
  exports.getMidnightMaxSafeDebt = getMidnightMaxSafeDebt;
324
+ /**
325
+ * @internal Rejects a Midnight borrow whose post-borrow debt exceeds the collateral's capacity at
326
+ * LLTV minus `DEFAULT_LLTV_BUFFER`, with the same check and error as the entity borrow flows.
327
+ * Used by TransactionPlan preparers; the entity keeps its inline check.
328
+ */
329
+ const validateMidnightBorrowHealth = (params) => {
330
+ const postDebt = params.debt + params.borrowUnits;
331
+ if (postDebt <= 0n) {
332
+ return;
333
+ }
334
+ const maxSafeDebt = (0, exports.getMidnightMaxSafeDebt)(params);
335
+ if (postDebt > maxSafeDebt) {
336
+ throw new index_js_1.BorrowExceedsSafeLtvError(params.borrowUnits, blue_sdk_1.MathLib.zeroFloorSub(maxSafeDebt, params.debt));
337
+ }
338
+ };
339
+ exports.validateMidnightBorrowHealth = validateMidnightBorrowHealth;
340
+ /**
341
+ * @internal Rejects a Midnight collateral withdrawal whose post-operation debt exceeds the remaining
342
+ * collateral's capacity at LLTV minus `DEFAULT_LLTV_BUFFER`, with the same check and error as the
343
+ * entity withdraw and repay-withdraw flows. Used by TransactionPlan preparers; the entity keeps its
344
+ * inline checks.
345
+ */
346
+ const validateMidnightWithdrawHealth = (params) => {
347
+ if (params.debt <= 0n) {
348
+ return;
349
+ }
350
+ const maxSafeDebt = (0, exports.getMidnightMaxSafeDebt)(params);
351
+ if (params.debt > maxSafeDebt) {
352
+ throw new index_js_1.WithdrawMakesPositionUnhealthyError({
353
+ withdrawAmount: params.withdrawAmount,
354
+ borrowAssets: params.debt,
355
+ maxSafeBorrow: maxSafeDebt,
356
+ });
357
+ }
358
+ };
359
+ exports.validateMidnightWithdrawHealth = validateMidnightWithdrawHealth;
360
+ /**
361
+ * @internal Checks a direct Midnight repayment and collateral withdrawal against the position
362
+ * snapshot, in order: each withdrawal against the remaining collateral, an exact repayment against
363
+ * the debt, a full repayment cap against the debt, then the remaining debt against the remaining
364
+ * collateral's buffered capacity when collateral is withdrawn. Matches the entity
365
+ * `repayWithdrawCollateral` checks; used by TransactionPlan preparers, while the entity keeps its
366
+ * inline checks. Callers parse the withdrawals first.
367
+ * @throws {WithdrawExceedsCollateralError} If a withdrawal exceeds the remaining collateral.
368
+ * @throws {MidnightRepayExceedsDebtError} If an exact repayment exceeds the debt.
369
+ * @throws {MidnightTakeTargetUnreachableError} If a full repayment cap is below the debt.
370
+ * @throws {MissingMarketPriceError} If remaining collateral has no price for the health check.
371
+ * @throws {WithdrawMakesPositionUnhealthyError} If the remaining debt exceeds buffered capacity.
372
+ */
373
+ const validateMidnightRepayWithdrawCollateralPosition = (params) => {
374
+ const { marketData, positionData, repay, collateralWithdrawals } = params;
375
+ const { debt } = positionData;
376
+ const { postCollateral, withdrawAmount } = (0, computeMidnightPostWithdrawalCollateral_js_1.computeMidnightPostWithdrawalCollateral)({
377
+ market: marketData.params,
378
+ marketId: marketData.id,
379
+ collateral: positionData.collateral,
380
+ withdrawals: collateralWithdrawals,
381
+ });
382
+ // The bundle must fill the whole assets target and the direct repay is capped at the debt, so a repay above it reverts `OutOfOffers()`.
383
+ if (repay.type === "assets" && repay.assets > debt) {
384
+ throw new index_js_1.MidnightRepayExceedsDebtError({
385
+ field: "repay.assets",
386
+ value: repay.assets,
387
+ debt,
388
+ });
389
+ }
390
+ if (repay.type === "full" && repay.maxBuyerAssets < debt) {
391
+ throw new index_js_1.MidnightTakeTargetUnreachableError({
392
+ field: "repay.maxBuyerAssets",
393
+ value: repay.maxBuyerAssets,
394
+ limit: debt,
395
+ });
396
+ }
397
+ if (collateralWithdrawals.length === 0) {
398
+ return;
399
+ }
400
+ (0, exports.validateMidnightWithdrawHealth)({
401
+ market: marketData,
402
+ collateral: postCollateral,
403
+ collateralPrices: params.collateralPrices,
404
+ debt: repay.type === "assets" && debt > repay.assets ? debt - repay.assets : 0n,
405
+ withdrawAmount,
406
+ });
407
+ };
408
+ exports.validateMidnightRepayWithdrawCollateralPosition = validateMidnightRepayWithdrawCollateralPosition;
323
409
  /**
324
410
  * Validates that the resulting position stays within the safe LTV threshold
325
411
  * (LLTV minus buffer) after supplying additional collateral and borrowing.
@@ -37,3 +37,13 @@ export declare const validateMidnightPublication: (params: MidnightCancelAndMake
37
37
  * @throws {InvalidMidnightHexInputError} when `value` is not exactly 32 bytes of hex.
38
38
  */
39
39
  export declare const validateMidnightBytes32: (field: string, value: Hex) => void;
40
+ /**
41
+ * @internal
42
+ * Validates every cancelled group as 32-byte hex, in input order, with the same checks and error
43
+ * labels as {@link validateMidnightPublication}. Used by TransactionPlan maker constructors before
44
+ * any state read; entity flows keep the check inside the bundle parser.
45
+ *
46
+ * @param cancellations - Groups to cancel with their consumption ceilings.
47
+ * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
48
+ */
49
+ export declare const validateMidnightCancellationGroups: (cancellations: MidnightCancelAndMakeParams["cancellations"]) => void;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateMidnightBytes32 = exports.validateMidnightPublication = exports.snapshotMidnightCancelAndMakeParams = void 0;
3
+ exports.validateMidnightCancellationGroups = exports.validateMidnightBytes32 = exports.validateMidnightPublication = exports.snapshotMidnightCancelAndMakeParams = void 0;
4
4
  const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
5
5
  const viem_1 = require("viem");
6
6
  const index_js_1 = require("../types/index.js");
@@ -155,3 +155,20 @@ const validateHexInput = (value, field, size) => {
155
155
  });
156
156
  }
157
157
  };
158
+ /**
159
+ * @internal
160
+ * Validates every cancelled group as 32-byte hex, in input order, with the same checks and error
161
+ * labels as {@link validateMidnightPublication}. Used by TransactionPlan maker constructors before
162
+ * any state read; entity flows keep the check inside the bundle parser.
163
+ *
164
+ * @param cancellations - Groups to cancel with their consumption ceilings.
165
+ * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
166
+ */
167
+ const validateMidnightCancellationGroups = (cancellations) => {
168
+ for (const [index, { group }] of cancellations.entries()) {
169
+ validateHexInput(group, `cancellations[${index}].group`, {
170
+ exactBytes: 32,
171
+ });
172
+ }
173
+ };
174
+ exports.validateMidnightCancellationGroups = validateMidnightCancellationGroups;
@@ -0,0 +1,28 @@
1
+ import type { OfferStruct } from "@morpho-org/midnight-sdk";
2
+ import { type Hex } from "viem";
3
+ declare const OFFER_ADDRESS_FIELDS: readonly ["maker", "callback", "receiverIfMakerIsSeller", "ratifier"];
4
+ declare const OFFER_UINT256_FIELDS: readonly ["start", "expiry", "tick", "continuousFeeCap"];
5
+ declare const OFFER_CAP_FIELDS: readonly ["maxUnits", "maxAssets"];
6
+ /**
7
+ * Parses the fields of each taken offer fill that `MidnightBundlesV2` ABI-encodes and that the
8
+ * side, market and cap guards do not already check, so a malformed offer is rejected before any
9
+ * read or encoding.
10
+ *
11
+ * Integer and address bounds are the ABI's: `start`, `expiry`, `tick`, `continuousFeeCap` and
12
+ * the fill's `units` are `uint256` bigints; the `maxUnits` and `maxAssets` caps are bigints whose
13
+ * `uint128` bounds the action parser checks; `maker`, `callback`, `receiverIfMakerIsSeller` and
14
+ * `ratifier` are addresses (checksummed when mixed-case); `group` is exactly 32 bytes of `0x` hex;
15
+ * `reduceOnly` is a boolean. `callbackData` and `ratifierData` must be even-length `0x` hex.
16
+ *
17
+ * @param takeableOffers - Offers selected for a Midnight take.
18
+ * @returns Nothing when every offer field can be encoded.
19
+ * @throws {MidnightCalldataEncodingError} when a field is malformed; `input` is its path, such as
20
+ * `"takeableOffers[0].offer.maker"`.
21
+ * @internal
22
+ */
23
+ export declare const validateMidnightTakeableOfferFields: (takeableOffers: readonly {
24
+ readonly units: bigint;
25
+ readonly offer: Pick<OfferStruct, (typeof OFFER_ADDRESS_FIELDS)[number] | (typeof OFFER_UINT256_FIELDS)[number] | (typeof OFFER_CAP_FIELDS)[number] | "group" | "callbackData" | "reduceOnly">;
26
+ readonly ratifierData: Hex;
27
+ }[]) => void;
28
+ export {};
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateMidnightTakeableOfferFields = void 0;
4
+ const viem_1 = require("viem");
5
+ const index_js_1 = require("../types/index.js");
6
+ const validateMidnightAccount_js_1 = require("./validateMidnightAccount.js");
7
+ const OFFER_ADDRESS_FIELDS = [
8
+ "maker",
9
+ "callback",
10
+ "receiverIfMakerIsSeller",
11
+ "ratifier",
12
+ ];
13
+ const OFFER_UINT256_FIELDS = [
14
+ "start",
15
+ "expiry",
16
+ "tick",
17
+ "continuousFeeCap",
18
+ ];
19
+ const OFFER_CAP_FIELDS = ["maxUnits", "maxAssets"];
20
+ const BYTES32_PATTERN = /^0x[0-9a-fA-F]{64}$/;
21
+ const validateUint256 = (field, value) => {
22
+ if (typeof value !== "bigint") {
23
+ throw new index_js_1.MidnightCalldataEncodingError(field, new viem_1.BaseError(`Invalid bigint value: "${String(value)}".`));
24
+ }
25
+ if (value < 0n || value > viem_1.maxUint256) {
26
+ throw new index_js_1.MidnightCalldataEncodingError(field, new viem_1.IntegerOutOfRangeError({
27
+ max: `${viem_1.maxUint256}n`,
28
+ min: "0n",
29
+ signed: false,
30
+ size: 32,
31
+ value: `${value}n`,
32
+ }));
33
+ }
34
+ };
35
+ const validateBytes = (field, value) => {
36
+ if (!(0, viem_1.isHex)(value) || value.length % 2 !== 0) {
37
+ throw new index_js_1.MidnightCalldataEncodingError(field, new viem_1.InvalidHexValueError(value));
38
+ }
39
+ };
40
+ /**
41
+ * Parses the fields of each taken offer fill that `MidnightBundlesV2` ABI-encodes and that the
42
+ * side, market and cap guards do not already check, so a malformed offer is rejected before any
43
+ * read or encoding.
44
+ *
45
+ * Integer and address bounds are the ABI's: `start`, `expiry`, `tick`, `continuousFeeCap` and
46
+ * the fill's `units` are `uint256` bigints; the `maxUnits` and `maxAssets` caps are bigints whose
47
+ * `uint128` bounds the action parser checks; `maker`, `callback`, `receiverIfMakerIsSeller` and
48
+ * `ratifier` are addresses (checksummed when mixed-case); `group` is exactly 32 bytes of `0x` hex;
49
+ * `reduceOnly` is a boolean. `callbackData` and `ratifierData` must be even-length `0x` hex.
50
+ *
51
+ * @param takeableOffers - Offers selected for a Midnight take.
52
+ * @returns Nothing when every offer field can be encoded.
53
+ * @throws {MidnightCalldataEncodingError} when a field is malformed; `input` is its path, such as
54
+ * `"takeableOffers[0].offer.maker"`.
55
+ * @internal
56
+ */
57
+ const validateMidnightTakeableOfferFields = (takeableOffers) => {
58
+ for (const [index, { units, offer, ratifierData },] of takeableOffers.entries()) {
59
+ const path = `takeableOffers[${index}]`;
60
+ for (const field of OFFER_ADDRESS_FIELDS) {
61
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)(`${path}.offer.${field}`, offer[field]);
62
+ }
63
+ for (const field of OFFER_UINT256_FIELDS) {
64
+ validateUint256(`${path}.offer.${field}`, offer[field]);
65
+ }
66
+ for (const field of OFFER_CAP_FIELDS) {
67
+ validateUint256(`${path}.offer.${field}`, offer[field]);
68
+ }
69
+ if (typeof offer.group !== "string" || !BYTES32_PATTERN.test(offer.group)) {
70
+ throw new index_js_1.MidnightCalldataEncodingError(`${path}.offer.group`, (0, viem_1.isHex)(offer.group, { strict: true })
71
+ ? new viem_1.AbiEncodingBytesSizeMismatchError({
72
+ expectedSize: 32,
73
+ value: offer.group,
74
+ })
75
+ : new viem_1.InvalidHexValueError(offer.group));
76
+ }
77
+ validateBytes(`${path}.offer.callbackData`, offer.callbackData);
78
+ if (typeof offer.reduceOnly !== "boolean") {
79
+ throw new index_js_1.MidnightCalldataEncodingError(`${path}.offer.reduceOnly`, new viem_1.BaseError(`Invalid boolean value: "${offer.reduceOnly}".`));
80
+ }
81
+ validateBytes(`${path}.ratifierData`, ratifierData);
82
+ validateUint256(`${path}.units`, units);
83
+ }
84
+ };
85
+ exports.validateMidnightTakeableOfferFields = validateMidnightTakeableOfferFields;
@@ -4,7 +4,7 @@ export * from "./client/index.js";
4
4
  export type { SupplyCollateralWithNativeParams } from "./entities/midnight/types.js";
5
5
  export * from "./entities/requirements/index.js";
6
6
  export * from "./helpers/index.js";
7
- export type { Action, BlueBorrowPlanParams, BlueMarketSnapshot, BluePositionSnapshot, BlueRefinancePlanParams, BlueRepayPlanParams, BlueRepayWithdrawCollateralPlanParams, BlueSupplyCollateralBorrowPlanParams, BlueSupplyCollateralPlanParams, BlueSupplyPlanParams, BlueWithdrawCollateralPlanParams, BlueWithdrawPlanParams, Funding, IntentParams, ReferralFee, SignatureRequest, Step, TransactionPlan, VaultV1DepositPlanParams, VaultV1InKindRedeemPlanParams, VaultV1MigrateToV2PlanParams, VaultV1RedeemPlanParams, VaultV1WithdrawPlanParams, VaultV2DepositPlanParams, VaultV2ForceRedeemPlanParams, VaultV2ForceWithdrawPlanParams, VaultV2InKindRedeemPlanParams, VaultV2RedeemPlanParams, VaultV2WithdrawPlanParams, } from "./transactionPlan/index.js";
8
- export { applySignatures, BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, parseTransactionPlan, prepareBlueBorrow, prepareBlueRefinance, prepareBlueRepay, prepareBlueRepayWithdrawCollateral, prepareBlueSupply, prepareBlueSupplyCollateral, prepareBlueSupplyCollateralBorrow, prepareBlueWithdraw, prepareBlueWithdrawCollateral, prepareVaultV1Deposit, prepareVaultV1InKindRedeem, prepareVaultV1MigrateToV2, prepareVaultV1Redeem, prepareVaultV1Withdraw, prepareVaultV2Deposit, prepareVaultV2ForceRedeem, prepareVaultV2ForceWithdraw, prepareVaultV2InKindRedeem, prepareVaultV2Redeem, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, validateBlueMarketSnapshot, ZeroAccountError, } from "./transactionPlan/index.js";
7
+ export type { Action, BlueBorrowPlanParams, BlueMarketSnapshot, BluePositionSnapshot, BlueRefinancePlanParams, BlueRepayPlanParams, BlueRepayWithdrawCollateralPlanParams, BlueSupplyCollateralBorrowPlanParams, BlueSupplyCollateralPlanParams, BlueSupplyPlanParams, BlueWithdrawBuyCallbackPlanParams, BlueWithdrawCollateralPlanParams, BlueWithdrawPlanParams, Funding, IntentParams, MidnightCancelOffersPlanParams, MidnightMakeBorrowPlanParams, MidnightMakeLendPlanParams, MidnightMakeRepayPlanParams, MidnightMakerPublicationPlanParams, MidnightMakeWithdrawPlanParams, MidnightRedeemPlanParams, MidnightRepayWithdrawCollateralPlanParams, MidnightSupplyBlueMakeLendPlanParams, MidnightSupplyCollateralBatchPlanParams, MidnightSupplyCollateralMakeBorrowPlanParams, MidnightSupplyCollateralPlanParams, MidnightSupplyCollateralTakeBorrowPlanParams, MidnightSupplyCollateralWithNativePlanParams, MidnightTakeBorrowPlanParams, MidnightTakeLendPlanParams, MidnightTakeRepayWithdrawCollateralPlanParams, MidnightTakeWithdrawPlanParams, MidnightWithdrawCollateralBatchPlanParams, MidnightWithdrawCollateralPlanParams, ReferralFee, SignatureRequest, Step, TransactionPlan, VaultV1DepositPlanParams, VaultV1InKindRedeemPlanParams, VaultV1MigrateToV2PlanParams, VaultV1RedeemPlanParams, VaultV1WithdrawPlanParams, VaultV2DepositPlanParams, VaultV2ForceRedeemPlanParams, VaultV2ForceWithdrawPlanParams, VaultV2InKindRedeemPlanParams, VaultV2RedeemPlanParams, VaultV2WithdrawPlanParams, } from "./transactionPlan/index.js";
8
+ export { applySignatures, BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, MidnightTakeCreditInsufficientError, NonIntegerInputError, parseTransactionPlan, prepareBlueBorrow, prepareBlueRefinance, prepareBlueRepay, prepareBlueRepayWithdrawCollateral, prepareBlueSupply, prepareBlueSupplyCollateral, prepareBlueSupplyCollateralBorrow, prepareBlueWithdraw, prepareBlueWithdrawBuyCallback, prepareBlueWithdrawCollateral, prepareMidnightCancelOffers, prepareMidnightMakeBorrow, prepareMidnightMakeLend, prepareMidnightMakeRepay, prepareMidnightMakeWithdraw, prepareMidnightRedeem, prepareMidnightRepayWithdrawCollateral, prepareMidnightSupplyBlueMakeLend, prepareMidnightSupplyCollateral, prepareMidnightSupplyCollateralBatch, prepareMidnightSupplyCollateralMakeBorrow, prepareMidnightSupplyCollateralTakeBorrow, prepareMidnightSupplyCollateralWithNative, prepareMidnightTakeBorrow, prepareMidnightTakeLend, prepareMidnightTakeRepayWithdrawCollateral, prepareMidnightTakeWithdraw, prepareMidnightWithdrawCollateral, prepareMidnightWithdrawCollateralBatch, prepareVaultV1Deposit, prepareVaultV1InKindRedeem, prepareVaultV1MigrateToV2, prepareVaultV1Redeem, prepareVaultV1Withdraw, prepareVaultV2Deposit, prepareVaultV2ForceRedeem, prepareVaultV2ForceWithdraw, prepareVaultV2InKindRedeem, prepareVaultV2Redeem, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, validateBlueMarketSnapshot, ZeroAccountError, } from "./transactionPlan/index.js";
9
9
  export * from "./types/index.js";
10
10
  export { version } from "./version.js";
package/lib/cjs/index.js CHANGED
@@ -14,7 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.version = exports.ZeroAccountError = exports.validateBlueMarketSnapshot = exports.UnsupportedTransactionPlanVersionError = exports.UnsupportedTransactionPlanActionError = exports.TransactionPlanSignatureMismatchError = exports.serializeTransactionPlan = exports.prepareVaultV2Withdraw = exports.prepareVaultV2Redeem = exports.prepareVaultV2InKindRedeem = exports.prepareVaultV2ForceWithdraw = exports.prepareVaultV2ForceRedeem = exports.prepareVaultV2Deposit = exports.prepareVaultV1Withdraw = exports.prepareVaultV1Redeem = exports.prepareVaultV1MigrateToV2 = exports.prepareVaultV1InKindRedeem = exports.prepareVaultV1Deposit = exports.prepareBlueWithdrawCollateral = exports.prepareBlueWithdraw = exports.prepareBlueSupplyCollateralBorrow = exports.prepareBlueSupplyCollateral = exports.prepareBlueSupply = exports.prepareBlueRepayWithdrawCollateral = exports.prepareBlueRepay = exports.prepareBlueRefinance = exports.prepareBlueBorrow = exports.parseTransactionPlan = exports.NonIntegerInputError = exports.InvalidTransactionPlanError = exports.InvalidCalldataOriginError = exports.IncompleteTransactionPlanError = exports.getPendingSignatureRequests = exports.buildTransactions = exports.buildTransaction = exports.BlueSnapshotStateMismatchError = exports.BlueSnapshotChainMismatchError = exports.applySignatures = exports.validateClientChainId = void 0;
17
+ exports.prepareVaultV2ForceWithdraw = exports.prepareVaultV2ForceRedeem = exports.prepareVaultV2Deposit = exports.prepareVaultV1Withdraw = exports.prepareVaultV1Redeem = exports.prepareVaultV1MigrateToV2 = exports.prepareVaultV1InKindRedeem = exports.prepareVaultV1Deposit = exports.prepareMidnightWithdrawCollateralBatch = exports.prepareMidnightWithdrawCollateral = exports.prepareMidnightTakeWithdraw = exports.prepareMidnightTakeRepayWithdrawCollateral = exports.prepareMidnightTakeLend = exports.prepareMidnightTakeBorrow = exports.prepareMidnightSupplyCollateralWithNative = exports.prepareMidnightSupplyCollateralTakeBorrow = exports.prepareMidnightSupplyCollateralMakeBorrow = exports.prepareMidnightSupplyCollateralBatch = exports.prepareMidnightSupplyCollateral = exports.prepareMidnightSupplyBlueMakeLend = exports.prepareMidnightRepayWithdrawCollateral = exports.prepareMidnightRedeem = exports.prepareMidnightMakeWithdraw = exports.prepareMidnightMakeRepay = exports.prepareMidnightMakeLend = exports.prepareMidnightMakeBorrow = exports.prepareMidnightCancelOffers = exports.prepareBlueWithdrawCollateral = exports.prepareBlueWithdrawBuyCallback = exports.prepareBlueWithdraw = exports.prepareBlueSupplyCollateralBorrow = exports.prepareBlueSupplyCollateral = exports.prepareBlueSupply = exports.prepareBlueRepayWithdrawCollateral = exports.prepareBlueRepay = exports.prepareBlueRefinance = exports.prepareBlueBorrow = exports.parseTransactionPlan = exports.NonIntegerInputError = exports.MidnightTakeCreditInsufficientError = exports.InvalidTransactionPlanError = exports.InvalidCalldataOriginError = exports.IncompleteTransactionPlanError = exports.getPendingSignatureRequests = exports.buildTransactions = exports.buildTransaction = exports.BlueSnapshotStateMismatchError = exports.BlueSnapshotChainMismatchError = exports.applySignatures = exports.validateClientChainId = void 0;
18
+ exports.version = exports.ZeroAccountError = exports.validateBlueMarketSnapshot = exports.UnsupportedTransactionPlanVersionError = exports.UnsupportedTransactionPlanActionError = exports.TransactionPlanSignatureMismatchError = exports.serializeTransactionPlan = exports.prepareVaultV2Withdraw = exports.prepareVaultV2Redeem = exports.prepareVaultV2InKindRedeem = void 0;
18
19
  __exportStar(require("./actions/index.js"), exports);
19
20
  var validateClientChainId_js_1 = require("./actions/requirements/validateClientChainId.js");
20
21
  Object.defineProperty(exports, "validateClientChainId", { enumerable: true, get: function () { return validateClientChainId_js_1.validateClientChainId; } });
@@ -31,6 +32,7 @@ Object.defineProperty(exports, "getPendingSignatureRequests", { enumerable: true
31
32
  Object.defineProperty(exports, "IncompleteTransactionPlanError", { enumerable: true, get: function () { return index_js_1.IncompleteTransactionPlanError; } });
32
33
  Object.defineProperty(exports, "InvalidCalldataOriginError", { enumerable: true, get: function () { return index_js_1.InvalidCalldataOriginError; } });
33
34
  Object.defineProperty(exports, "InvalidTransactionPlanError", { enumerable: true, get: function () { return index_js_1.InvalidTransactionPlanError; } });
35
+ Object.defineProperty(exports, "MidnightTakeCreditInsufficientError", { enumerable: true, get: function () { return index_js_1.MidnightTakeCreditInsufficientError; } });
34
36
  Object.defineProperty(exports, "NonIntegerInputError", { enumerable: true, get: function () { return index_js_1.NonIntegerInputError; } });
35
37
  Object.defineProperty(exports, "parseTransactionPlan", { enumerable: true, get: function () { return index_js_1.parseTransactionPlan; } });
36
38
  Object.defineProperty(exports, "prepareBlueBorrow", { enumerable: true, get: function () { return index_js_1.prepareBlueBorrow; } });
@@ -41,7 +43,27 @@ Object.defineProperty(exports, "prepareBlueSupply", { enumerable: true, get: fun
41
43
  Object.defineProperty(exports, "prepareBlueSupplyCollateral", { enumerable: true, get: function () { return index_js_1.prepareBlueSupplyCollateral; } });
42
44
  Object.defineProperty(exports, "prepareBlueSupplyCollateralBorrow", { enumerable: true, get: function () { return index_js_1.prepareBlueSupplyCollateralBorrow; } });
43
45
  Object.defineProperty(exports, "prepareBlueWithdraw", { enumerable: true, get: function () { return index_js_1.prepareBlueWithdraw; } });
46
+ Object.defineProperty(exports, "prepareBlueWithdrawBuyCallback", { enumerable: true, get: function () { return index_js_1.prepareBlueWithdrawBuyCallback; } });
44
47
  Object.defineProperty(exports, "prepareBlueWithdrawCollateral", { enumerable: true, get: function () { return index_js_1.prepareBlueWithdrawCollateral; } });
48
+ Object.defineProperty(exports, "prepareMidnightCancelOffers", { enumerable: true, get: function () { return index_js_1.prepareMidnightCancelOffers; } });
49
+ Object.defineProperty(exports, "prepareMidnightMakeBorrow", { enumerable: true, get: function () { return index_js_1.prepareMidnightMakeBorrow; } });
50
+ Object.defineProperty(exports, "prepareMidnightMakeLend", { enumerable: true, get: function () { return index_js_1.prepareMidnightMakeLend; } });
51
+ Object.defineProperty(exports, "prepareMidnightMakeRepay", { enumerable: true, get: function () { return index_js_1.prepareMidnightMakeRepay; } });
52
+ Object.defineProperty(exports, "prepareMidnightMakeWithdraw", { enumerable: true, get: function () { return index_js_1.prepareMidnightMakeWithdraw; } });
53
+ Object.defineProperty(exports, "prepareMidnightRedeem", { enumerable: true, get: function () { return index_js_1.prepareMidnightRedeem; } });
54
+ Object.defineProperty(exports, "prepareMidnightRepayWithdrawCollateral", { enumerable: true, get: function () { return index_js_1.prepareMidnightRepayWithdrawCollateral; } });
55
+ Object.defineProperty(exports, "prepareMidnightSupplyBlueMakeLend", { enumerable: true, get: function () { return index_js_1.prepareMidnightSupplyBlueMakeLend; } });
56
+ Object.defineProperty(exports, "prepareMidnightSupplyCollateral", { enumerable: true, get: function () { return index_js_1.prepareMidnightSupplyCollateral; } });
57
+ Object.defineProperty(exports, "prepareMidnightSupplyCollateralBatch", { enumerable: true, get: function () { return index_js_1.prepareMidnightSupplyCollateralBatch; } });
58
+ Object.defineProperty(exports, "prepareMidnightSupplyCollateralMakeBorrow", { enumerable: true, get: function () { return index_js_1.prepareMidnightSupplyCollateralMakeBorrow; } });
59
+ Object.defineProperty(exports, "prepareMidnightSupplyCollateralTakeBorrow", { enumerable: true, get: function () { return index_js_1.prepareMidnightSupplyCollateralTakeBorrow; } });
60
+ Object.defineProperty(exports, "prepareMidnightSupplyCollateralWithNative", { enumerable: true, get: function () { return index_js_1.prepareMidnightSupplyCollateralWithNative; } });
61
+ Object.defineProperty(exports, "prepareMidnightTakeBorrow", { enumerable: true, get: function () { return index_js_1.prepareMidnightTakeBorrow; } });
62
+ Object.defineProperty(exports, "prepareMidnightTakeLend", { enumerable: true, get: function () { return index_js_1.prepareMidnightTakeLend; } });
63
+ Object.defineProperty(exports, "prepareMidnightTakeRepayWithdrawCollateral", { enumerable: true, get: function () { return index_js_1.prepareMidnightTakeRepayWithdrawCollateral; } });
64
+ Object.defineProperty(exports, "prepareMidnightTakeWithdraw", { enumerable: true, get: function () { return index_js_1.prepareMidnightTakeWithdraw; } });
65
+ Object.defineProperty(exports, "prepareMidnightWithdrawCollateral", { enumerable: true, get: function () { return index_js_1.prepareMidnightWithdrawCollateral; } });
66
+ Object.defineProperty(exports, "prepareMidnightWithdrawCollateralBatch", { enumerable: true, get: function () { return index_js_1.prepareMidnightWithdrawCollateralBatch; } });
45
67
  Object.defineProperty(exports, "prepareVaultV1Deposit", { enumerable: true, get: function () { return index_js_1.prepareVaultV1Deposit; } });
46
68
  Object.defineProperty(exports, "prepareVaultV1InKindRedeem", { enumerable: true, get: function () { return index_js_1.prepareVaultV1InKindRedeem; } });
47
69
  Object.defineProperty(exports, "prepareVaultV1MigrateToV2", { enumerable: true, get: function () { return index_js_1.prepareVaultV1MigrateToV2; } });
@@ -1,6 +1,6 @@
1
1
  export { EcrecoverRatifier,
2
2
  /** @deprecated Use EcrecoverRatifier with a tagged tree. */
3
- EcrecoverRatifierUtils, eip712Digest, GroupUtils, MarketUtils, OfferChainUtils, OfferUtils, Payload, PositionUtils, PriceRatifierV1,
3
+ EcrecoverRatifierUtils, eip712Digest, GroupUtils, getBlueBuyCallbackAddress, MarketUtils, OfferChainUtils, OfferUtils, Payload, PositionUtils, PriceRatifierV1,
4
4
  /** @deprecated Use PriceRatifierV1. */
5
5
  PriceRatifierV1Utils, RateRatifierV1,
6
6
  /** @deprecated Use RateRatifierV1. */
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TreeUtils = exports.TickLib = exports.TakeAmountsLib = exports.SetterRatifierUtils = exports.SetterRatifier = exports.RatifierUtils = exports.Ratifier = exports.RateRatifierV1Utils = exports.RateRatifierV1 = exports.PriceRatifierV1Utils = exports.PriceRatifierV1 = exports.PositionUtils = exports.Payload = exports.OfferUtils = exports.OfferChainUtils = exports.MarketUtils = exports.GroupUtils = exports.eip712Digest = exports.EcrecoverRatifierUtils = exports.EcrecoverRatifier = void 0;
3
+ exports.TreeUtils = exports.TickLib = exports.TakeAmountsLib = exports.SetterRatifierUtils = exports.SetterRatifier = exports.RatifierUtils = exports.Ratifier = exports.RateRatifierV1Utils = exports.RateRatifierV1 = exports.PriceRatifierV1Utils = exports.PriceRatifierV1 = exports.PositionUtils = exports.Payload = exports.OfferUtils = exports.OfferChainUtils = exports.MarketUtils = exports.getBlueBuyCallbackAddress = exports.GroupUtils = exports.eip712Digest = exports.EcrecoverRatifierUtils = exports.EcrecoverRatifier = void 0;
4
4
  var midnight_sdk_1 = require("@morpho-org/midnight-sdk");
5
5
  Object.defineProperty(exports, "EcrecoverRatifier", { enumerable: true, get: function () { return midnight_sdk_1.EcrecoverRatifier; } });
6
6
  /** @deprecated Use EcrecoverRatifier with a tagged tree. */
7
7
  Object.defineProperty(exports, "EcrecoverRatifierUtils", { enumerable: true, get: function () { return midnight_sdk_1.EcrecoverRatifierUtils; } });
8
8
  Object.defineProperty(exports, "eip712Digest", { enumerable: true, get: function () { return midnight_sdk_1.eip712Digest; } });
9
9
  Object.defineProperty(exports, "GroupUtils", { enumerable: true, get: function () { return midnight_sdk_1.GroupUtils; } });
10
+ Object.defineProperty(exports, "getBlueBuyCallbackAddress", { enumerable: true, get: function () { return midnight_sdk_1.getBlueBuyCallbackAddress; } });
10
11
  Object.defineProperty(exports, "MarketUtils", { enumerable: true, get: function () { return midnight_sdk_1.MarketUtils; } });
11
12
  Object.defineProperty(exports, "OfferChainUtils", { enumerable: true, get: function () { return midnight_sdk_1.OfferChainUtils; } });
12
13
  Object.defineProperty(exports, "OfferUtils", { enumerable: true, get: function () { return midnight_sdk_1.OfferUtils; } });
@@ -0,0 +1,101 @@
1
+ import { type MarketId } from "@morpho-org/blue-sdk";
2
+ import { type Address, type Client } from "viem";
3
+ import { type BlueWithdrawBuyCallbackAction, type ReferenceTimestampParams, type Transaction } from "../../types/index.js";
4
+ import { type IntentParams } from "../intent.js";
5
+ import type { Action, TransactionPlan } from "../types.js";
6
+ import { type BlueMarketSnapshot, type BluePositionSnapshot } from "./prepare.js";
7
+ /**
8
+ * Caller intent and caller-fetched snapshots for withdrawing a BlueBuyCallback's whole supply
9
+ * position to its owner. The position belongs to `callbackAddress`, not to `account`.
10
+ * @example
11
+ * ```ts
12
+ * import type { BlueWithdrawBuyCallbackPlanParams } from "@morpho-org/morpho-sdk";
13
+ * import type { Address } from "viem";
14
+ * declare const callbackAddress: Address;
15
+ * const withdrawal = { callbackAddress, expiresAt: 1_900_000_000 } satisfies Pick<
16
+ * BlueWithdrawBuyCallbackPlanParams,
17
+ * "callbackAddress" | "expiresAt"
18
+ * >;
19
+ * ```
20
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
21
+ */
22
+ export interface BlueWithdrawBuyCallbackPlanParams extends Pick<IntentParams, "chainId" | "account" | "expiresAt" | "calldataOrigin">, ReferenceTimestampParams {
23
+ readonly marketId: MarketId;
24
+ readonly marketData: BlueMarketSnapshot;
25
+ /** BlueBuyCallback whose supply position is withdrawn; `account` must be its owner. */
26
+ readonly callbackAddress: Address;
27
+ /** Caller-fetched position of `callbackAddress`; every supply share in it is withdrawn. */
28
+ readonly positionData: BluePositionSnapshot;
29
+ }
30
+ /**
31
+ * Prepares a direct Morpho Blue withdrawal of a BlueBuyCallback's whole supply position to its owner.
32
+ * The call is `withdraw(marketParams, 0, shares, callbackAddress, account)` on Morpho Blue, not
33
+ * BlueBundlesV1: the callback authorizes its owner on Blue at construction, so the plan has no
34
+ * approval, authorization step or signature request. Preparation reads the chain and rejects a
35
+ * callback the registered factory did not create, another owner, or a revoked Blue authorization.
36
+ * The plan carries no referral fee, and `expiresAt` is plan metadata, not an onchain deadline.
37
+ * @param client - Viem client on the requested chain.
38
+ * @param params.chainId - Chain containing Morpho Blue and the registered `midnightBlueBuyCallbackFactory`.
39
+ * @param params.account - Non-zero callback owner that sends the transaction and receives the loan assets.
40
+ * @param params.marketId - Market ID matching both snapshots and the market tuple.
41
+ * @param params.marketData.chainId - Chain on which the market snapshot was fetched; must equal `chainId`.
42
+ * @param params.marketData.market - Caller-fetched `Market` snapshot used to fix the market tuple; its state must equal the position snapshot's market. Never stored in the plan.
43
+ * @param params.callbackAddress - BlueBuyCallback whose supply position is withdrawn.
44
+ * @param params.positionData.chainId - Position snapshot's chain; must equal `chainId`.
45
+ * @param params.positionData.position - Caller-fetched `AccrualPosition` of `callbackAddress` on `marketId`; all its supply shares are withdrawn and their assets must not exceed that market's liquidity.
46
+ * @param params.now - Optional reference timestamp in seconds, normally the latest block timestamp; defaults to the device clock.
47
+ * @param params.expiresAt - Optional Unix expiry in safe-integer seconds, later than `now`; defaults to `now + 2h`. Plan metadata only.
48
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to the withdrawal calldata; omitted by default.
49
+ * @returns A deep-frozen, data-only `{ version, chainId, account, expiresAt, steps, signatureRequests, calldataOrigin? }` plan with one `blueWithdrawBuyCallback` step and no signature requests.
50
+ * @throws {BlueSnapshotChainMismatchError} when a market or position snapshot's chain differs from `chainId`.
51
+ * @throws {MarketIdMismatchError} when a snapshot's ID differs from `marketId` or does not hash from its market tuple.
52
+ * @throws {BlueSnapshotStateMismatchError} when the market snapshot's state differs from the position snapshot's market.
53
+ * @throws {MissingAccrualPositionError} when no position snapshot is provided.
54
+ * @throws {AccrualPositionUserMismatchError} when the position belongs to another address than `callbackAddress`.
55
+ * @throws {ZeroAccountError} when `account` is the zero address.
56
+ * @throws {InvalidTransactionPlanError} when `account` or `callbackAddress` is not a checksum-valid address, or `calldataOrigin` exceeds 1 MiB.
57
+ * @throws {NonIntegerInputError} when `expiresAt` is not a safe integer.
58
+ * @throws {NonPositiveInputError} when `expiresAt` is not positive.
59
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now`.
60
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
61
+ * @throws {EmptyBlueSupplyPositionError} when the callback holds no supply shares.
62
+ * @throws {InsufficientBlueLiquidityError} when the position's supply assets exceed the snapshot market's liquidity.
63
+ * @throws {InputExceedsMaxError} when the supply shares exceed `uint256`.
64
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the registry.
65
+ * @throws {UnknownAddressError} when Morpho Blue or `midnightBlueBuyCallbackFactory` is not registered on `chainId`.
66
+ * @throws {ChainIdMismatchError} when the client declares another chain (checked before any snapshot) or its transport serves one.
67
+ * @throws {MissingContractCodeError} when Morpho Blue or the factory has no deployed code.
68
+ * @throws {NotBlueBuyCallbackError} when the factory did not create `callbackAddress`.
69
+ * @throws {BlueBuyCallbackOwnerMismatchError} when the callback's `OWNER()` is not `account`.
70
+ * @throws {BlueBuyCallbackUnauthorizedError} when Morpho Blue does not authorize `account` for the callback.
71
+ * @throws {viem.BaseError} when a chain, bytecode, factory, owner or authorization read fails.
72
+ * @example
73
+ * ```ts
74
+ * import { markets } from "@morpho-org/morpho-test";
75
+ * import { buildTransactions, prepareBlueWithdrawBuyCallback } from "@morpho-org/morpho-sdk";
76
+ * import { fetchBlueAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
77
+ * import { createPublicClient, type Address, http } from "viem";
78
+ * import { mainnet } from "viem/chains";
79
+ *
80
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
81
+ * declare const account: Address; // Owner of the BlueBuyCallback.
82
+ * declare const callbackAddress: Address; // BlueBuyCallback created by the registered factory.
83
+ * const position = await fetchBlueAccrualPosition(callbackAddress, markets[mainnet.id].usdc_wbtc.id, client);
84
+ * const plan = await prepareBlueWithdrawBuyCallback(client, {
85
+ * chainId: mainnet.id, account, callbackAddress, marketId: position.market.id,
86
+ * marketData: { chainId: mainnet.id, market: position.market },
87
+ * positionData: { chainId: mainnet.id, position },
88
+ * now: (await client.getBlock()).timestamp,
89
+ * });
90
+ * const [transaction] = buildTransactions(plan);
91
+ * // Submit transaction from account; it calls Morpho Blue directly.
92
+ * ```
93
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
94
+ */
95
+ export declare function prepareBlueWithdrawBuyCallback(client: Client, params: BlueWithdrawBuyCallbackPlanParams): Promise<TransactionPlan>;
96
+ /** @internal Encodes the stored callback withdrawal through the same action as the entity handle. */
97
+ export declare function buildBlueWithdrawBuyCallback(action: Extract<Action, {
98
+ type: "blueWithdrawBuyCallback";
99
+ }>): Readonly<Transaction<BlueWithdrawBuyCallbackAction>>;
100
+ /** @internal Validates the stored callback withdrawal's structural inputs. */
101
+ export declare function validateBlueWithdrawBuyCallbackPlanAction(action: Record<string, unknown>, path: string): void;