@morpho-org/morpho-sdk 8.3.0 → 9.1.0-next.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 (203) hide show
  1. package/MIGRATION-v8-to-v9.md +54 -0
  2. package/README.md +13 -7
  3. package/lib/cjs/abis.d.ts +1 -1
  4. package/lib/cjs/abis.js +5 -1
  5. package/lib/cjs/actions/bundles/common.d.ts +4 -7
  6. package/lib/cjs/actions/bundles/common.js +8 -14
  7. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  8. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +1 -8
  9. package/lib/cjs/actions/midnight/authorization.d.ts +3 -1
  10. package/lib/cjs/actions/midnight/authorization.js +11 -1
  11. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -0
  12. package/lib/cjs/actions/midnight/cancelAndMake.js +10 -2
  13. package/lib/cjs/actions/midnight/redeem.d.ts +3 -1
  14. package/lib/cjs/actions/midnight/redeem.js +9 -3
  15. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  16. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +7 -3
  17. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +4 -1
  18. package/lib/cjs/actions/midnight/supplyCollateral.js +10 -3
  19. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  20. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +9 -3
  21. package/lib/cjs/actions/midnight/takeBorrow.d.ts +3 -1
  22. package/lib/cjs/actions/midnight/takeBorrow.js +9 -3
  23. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
  24. package/lib/cjs/actions/midnight/takeLend.js +7 -2
  25. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  26. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +8 -2
  27. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +3 -1
  28. package/lib/cjs/actions/midnight/takeWithdraw.js +10 -3
  29. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  30. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +5 -7
  31. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +7 -11
  32. package/lib/cjs/actions/requirements/getRequirementsApproval.js +8 -15
  33. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  34. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +11 -8
  35. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  36. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  37. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +1 -1
  38. package/lib/cjs/actions/vaultV1/inKindRedeem.js +1 -1
  39. package/lib/cjs/actions/vaultV1/withdraw.d.ts +4 -4
  40. package/lib/cjs/actions/vaultV1/withdraw.js +4 -4
  41. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +1 -1
  42. package/lib/cjs/actions/vaultV2/forceWithdraw.js +1 -1
  43. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +1 -1
  44. package/lib/cjs/actions/vaultV2/inKindRedeem.js +1 -1
  45. package/lib/cjs/actions/vaultV2/withdraw.d.ts +4 -4
  46. package/lib/cjs/actions/vaultV2/withdraw.js +4 -4
  47. package/lib/cjs/blue/abis.d.ts +1 -1
  48. package/lib/cjs/blue/abis.js +5 -1
  49. package/lib/cjs/blue/entities.d.ts +4 -4
  50. package/lib/cjs/blue/entities.js +3 -1
  51. package/lib/cjs/blue/errors.d.ts +2 -2
  52. package/lib/cjs/blue/errors.js +5 -1
  53. package/lib/cjs/blue/fetch.d.ts +2 -2
  54. package/lib/cjs/blue/fetch.js +3 -1
  55. package/lib/cjs/blue/utils.d.ts +1 -1
  56. package/lib/cjs/blue/utils.js +2 -1
  57. package/lib/cjs/entities/blue/blue.d.ts +2 -12
  58. package/lib/cjs/entities/blue/blue.js +0 -4
  59. package/lib/cjs/entities/index.d.ts +4 -4
  60. package/lib/cjs/entities/index.js +3 -1
  61. package/lib/cjs/entities/midnight/midnight.d.ts +63 -18
  62. package/lib/cjs/entities/midnight/midnight.js +138 -53
  63. package/lib/cjs/entities/midnight/types.d.ts +3 -10
  64. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  65. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +0 -7
  66. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  67. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -20
  68. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +40 -37
  69. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -34
  70. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +69 -43
  71. package/lib/cjs/entities/vaultV2/vaultV2.js +41 -35
  72. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +5 -3
  73. package/lib/cjs/entities/vaultV2BlueReallocationData.js +9 -3
  74. package/lib/cjs/errors.d.ts +4 -4
  75. package/lib/cjs/errors.js +10 -5
  76. package/lib/cjs/fetch.d.ts +2 -2
  77. package/lib/cjs/fetch.js +3 -1
  78. package/lib/cjs/helpers/encodeMidnightCalldata.d.ts +48 -0
  79. package/lib/cjs/helpers/encodeMidnightCalldata.js +74 -0
  80. package/lib/cjs/helpers/slippage.d.ts +9 -25
  81. package/lib/cjs/helpers/slippage.js +10 -27
  82. package/lib/cjs/helpers/validate.d.ts +1 -0
  83. package/lib/cjs/helpers/validate.js +5 -0
  84. package/lib/cjs/helpers/validateMidnightAccount.d.ts +34 -0
  85. package/lib/cjs/helpers/validateMidnightAccount.js +47 -0
  86. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  87. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +4 -0
  88. package/lib/cjs/helpers/validateMidnightMarket.d.ts +2 -0
  89. package/lib/cjs/helpers/validateMidnightMarket.js +5 -0
  90. package/lib/cjs/helpers/validateMidnightPublication.d.ts +11 -0
  91. package/lib/cjs/helpers/validateMidnightPublication.js +12 -1
  92. package/lib/cjs/helpers/validateMidnightReceiver.d.ts +1 -0
  93. package/lib/cjs/helpers/validateMidnightReceiver.js +8 -0
  94. package/lib/cjs/helpers/validateTakeableOffers.d.ts +2 -1
  95. package/lib/cjs/helpers/validateTakeableOffers.js +4 -3
  96. package/lib/cjs/midnight/errors.d.ts +2 -1
  97. package/lib/cjs/midnight/errors.js +5 -4
  98. package/lib/cjs/types/action.d.ts +3 -1
  99. package/lib/cjs/types/error.d.ts +60 -6
  100. package/lib/cjs/types/error.js +143 -11
  101. package/lib/cjs/utils.d.ts +2 -2
  102. package/lib/cjs/utils.js +4 -2
  103. package/lib/esm/abis.d.ts +1 -1
  104. package/lib/esm/abis.js +1 -1
  105. package/lib/esm/actions/bundles/common.d.ts +4 -7
  106. package/lib/esm/actions/bundles/common.js +8 -14
  107. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  108. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -9
  109. package/lib/esm/actions/midnight/authorization.d.ts +3 -1
  110. package/lib/esm/actions/midnight/authorization.js +12 -2
  111. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -0
  112. package/lib/esm/actions/midnight/cancelAndMake.js +11 -3
  113. package/lib/esm/actions/midnight/redeem.d.ts +3 -1
  114. package/lib/esm/actions/midnight/redeem.js +10 -4
  115. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  116. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +8 -4
  117. package/lib/esm/actions/midnight/supplyCollateral.d.ts +4 -1
  118. package/lib/esm/actions/midnight/supplyCollateral.js +11 -4
  119. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  120. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +10 -4
  121. package/lib/esm/actions/midnight/takeBorrow.d.ts +3 -1
  122. package/lib/esm/actions/midnight/takeBorrow.js +10 -4
  123. package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
  124. package/lib/esm/actions/midnight/takeLend.js +8 -3
  125. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  126. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +9 -3
  127. package/lib/esm/actions/midnight/takeWithdraw.d.ts +3 -1
  128. package/lib/esm/actions/midnight/takeWithdraw.js +11 -4
  129. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  130. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +6 -8
  131. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +7 -11
  132. package/lib/esm/actions/requirements/getRequirementsApproval.js +9 -16
  133. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  134. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +12 -9
  135. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  136. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  137. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +1 -1
  138. package/lib/esm/actions/vaultV1/inKindRedeem.js +1 -1
  139. package/lib/esm/actions/vaultV1/withdraw.d.ts +4 -4
  140. package/lib/esm/actions/vaultV1/withdraw.js +4 -4
  141. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +1 -1
  142. package/lib/esm/actions/vaultV2/forceWithdraw.js +1 -1
  143. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +1 -1
  144. package/lib/esm/actions/vaultV2/inKindRedeem.js +1 -1
  145. package/lib/esm/actions/vaultV2/withdraw.d.ts +4 -4
  146. package/lib/esm/actions/vaultV2/withdraw.js +4 -4
  147. package/lib/esm/blue/abis.d.ts +1 -1
  148. package/lib/esm/blue/abis.js +1 -1
  149. package/lib/esm/blue/entities.d.ts +4 -4
  150. package/lib/esm/blue/entities.js +2 -2
  151. package/lib/esm/blue/errors.d.ts +2 -2
  152. package/lib/esm/blue/errors.js +2 -2
  153. package/lib/esm/blue/fetch.d.ts +2 -2
  154. package/lib/esm/blue/fetch.js +2 -2
  155. package/lib/esm/blue/utils.d.ts +1 -1
  156. package/lib/esm/blue/utils.js +1 -1
  157. package/lib/esm/entities/blue/blue.d.ts +2 -12
  158. package/lib/esm/entities/blue/blue.js +0 -4
  159. package/lib/esm/entities/index.d.ts +4 -4
  160. package/lib/esm/entities/index.js +2 -2
  161. package/lib/esm/entities/midnight/midnight.d.ts +63 -18
  162. package/lib/esm/entities/midnight/midnight.js +139 -54
  163. package/lib/esm/entities/midnight/types.d.ts +3 -10
  164. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  165. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +1 -8
  166. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  167. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +9 -21
  168. package/lib/esm/entities/vaultV1/vaultV1.d.ts +40 -37
  169. package/lib/esm/entities/vaultV1/vaultV1.js +6 -35
  170. package/lib/esm/entities/vaultV2/vaultV2.d.ts +69 -43
  171. package/lib/esm/entities/vaultV2/vaultV2.js +41 -35
  172. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +5 -3
  173. package/lib/esm/entities/vaultV2BlueReallocationData.js +9 -3
  174. package/lib/esm/errors.d.ts +4 -4
  175. package/lib/esm/errors.js +4 -4
  176. package/lib/esm/fetch.d.ts +2 -2
  177. package/lib/esm/fetch.js +2 -2
  178. package/lib/esm/helpers/encodeMidnightCalldata.d.ts +48 -0
  179. package/lib/esm/helpers/encodeMidnightCalldata.js +69 -0
  180. package/lib/esm/helpers/slippage.d.ts +9 -25
  181. package/lib/esm/helpers/slippage.js +9 -25
  182. package/lib/esm/helpers/validate.d.ts +1 -0
  183. package/lib/esm/helpers/validate.js +5 -0
  184. package/lib/esm/helpers/validateMidnightAccount.d.ts +34 -0
  185. package/lib/esm/helpers/validateMidnightAccount.js +43 -0
  186. package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  187. package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +4 -0
  188. package/lib/esm/helpers/validateMidnightMarket.d.ts +2 -0
  189. package/lib/esm/helpers/validateMidnightMarket.js +5 -0
  190. package/lib/esm/helpers/validateMidnightPublication.d.ts +11 -0
  191. package/lib/esm/helpers/validateMidnightPublication.js +10 -0
  192. package/lib/esm/helpers/validateMidnightReceiver.d.ts +1 -0
  193. package/lib/esm/helpers/validateMidnightReceiver.js +8 -0
  194. package/lib/esm/helpers/validateTakeableOffers.d.ts +2 -1
  195. package/lib/esm/helpers/validateTakeableOffers.js +4 -3
  196. package/lib/esm/midnight/errors.d.ts +2 -1
  197. package/lib/esm/midnight/errors.js +2 -1
  198. package/lib/esm/types/action.d.ts +3 -1
  199. package/lib/esm/types/error.d.ts +60 -6
  200. package/lib/esm/types/error.js +138 -7
  201. package/lib/esm/utils.d.ts +2 -2
  202. package/lib/esm/utils.js +2 -2
  203. package/package.json +8 -7
@@ -11,9 +11,12 @@ const index_js_2 = require("../../actions/requirements/index.js");
11
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
12
  const callback_js_1 = require("../../helpers/callback.js");
13
13
  const constant_js_1 = require("../../helpers/constant.js");
14
+ const encodeMidnightCalldata_js_1 = require("../../helpers/encodeMidnightCalldata.js");
14
15
  const index_js_3 = require("../../helpers/index.js");
16
+ const validateMidnightAccount_js_1 = require("../../helpers/validateMidnightAccount.js");
15
17
  const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
16
18
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
19
+ const validateMidnightPublication_js_1 = require("../../helpers/validateMidnightPublication.js");
17
20
  const validateMidnightTakeFeasibility_js_1 = require("../../helpers/validateMidnightTakeFeasibility.js");
18
21
  const validateOfferSides_js_1 = require("../../helpers/validateOfferSides.js");
19
22
  const index_js_4 = require("../../types/index.js");
@@ -23,6 +26,8 @@ const validatePositionBinding = (params) => {
23
26
  if (params.positionData.marketId !== params.marketData.id) {
24
27
  throw new index_js_4.MarketIdMismatchError(params.positionData.marketId, params.marketData.id);
25
28
  }
29
+ // Reject a malformed address before viem compares it.
30
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("positionData.user", params.positionData.user);
26
31
  if (!(0, viem_1.isAddressEqual)(params.positionData.user, params.accountAddress)) {
27
32
  throw new index_js_4.AccrualPositionUserMismatchError(params.positionData.user, params.accountAddress);
28
33
  }
@@ -52,7 +57,9 @@ const rejectReduceOnlyOffers = (offers) => {
52
57
  };
53
58
  const getOffersDataInternal = async ({ client, chainId, params, marketCreationTime = "expiry", }) => {
54
59
  (0, index_js_3.validateChainId)(client.viemClient.chain?.id, chainId);
55
- const tree = midnight_sdk_1.Tree.from(params.offers);
60
+ // Reject a malformed or zero maker before comparing offers against it.
61
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
62
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
56
63
  const midnight = (0, morpho_ts_1.getChainAddress)(chainId, "midnight");
57
64
  tree.offers.forEach((offer, index) => {
58
65
  if (!(0, viem_1.isAddressEqual)(offer.maker, params.accountAddress)) {
@@ -246,6 +253,7 @@ class MorphoMidnight {
246
253
  * @returns Prepared tree, groups, ratifier, and encoded payload used by maker flows.
247
254
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, another chain than this entity's.
248
255
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
256
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
249
257
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
250
258
  * (not thrown when `validation` is `false`).
251
259
  * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
@@ -255,6 +263,8 @@ class MorphoMidnight {
255
263
  * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
256
264
  * @throws {UnknownAddressError} when the chain has no deployment for the tree's V1 ratifier.
257
265
  * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
266
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
267
+ * @throws {MidnightCalldataEncodingError} when an offer cannot be ABI-encoded, such as an out-of-range integer, or `accountAddress` is not a well-formed address.
258
268
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
259
269
  * @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
260
270
  * @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
@@ -309,6 +319,8 @@ class MorphoMidnight {
309
319
  * @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
310
320
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
311
321
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
322
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
323
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
312
324
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
313
325
  * RPC read fails.
314
326
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -342,7 +354,6 @@ class MorphoMidnight {
342
354
  * offers plus the fallback.
343
355
  * @throws {MidnightContractReceiverError} when `referralFeeRecipient` is a Midnight protocol
344
356
  * contract or a market token contract with a positive referral fee.
345
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
346
357
  * @example
347
358
  * ```ts
348
359
  * const output = midnight.takeLend({
@@ -357,6 +368,8 @@ class MorphoMidnight {
357
368
  */
358
369
  takeLend(params) {
359
370
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
371
+ // Reject the zero account before preparing anything for it.
372
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
360
373
  validateTakeDeadlineWindow(params.deadline);
361
374
  const market = params.marketData.params;
362
375
  const rawParams = {
@@ -391,7 +404,7 @@ class MorphoMidnight {
391
404
  ? params.target.assets
392
405
  : params.target.maxBuyerAssets;
393
406
  return {
394
- getRequirements: async (requirementsParams) => {
407
+ getRequirements: async (_requirementsParams) => {
395
408
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
396
409
  viemClient: this.client.viemClient,
397
410
  chainId: this.chainId,
@@ -399,7 +412,6 @@ class MorphoMidnight {
399
412
  owner: params.accountAddress,
400
413
  spender: tx.to,
401
414
  amount: pulledAssets,
402
- approvalAmount: requirementsParams?.approvalAmount,
403
415
  });
404
416
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
405
417
  return [...approvals, ...authorization];
@@ -434,11 +446,14 @@ class MorphoMidnight {
434
446
  * Midnight protocol and market token contracts are rejected.
435
447
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
436
448
  * @param params.deadline - Bounded bundle execution deadline timestamp.
437
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
449
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
450
+ * proceeds; on an assets target it is added on top of `target.assets`.
438
451
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
439
452
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
440
453
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
441
454
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
455
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
456
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
442
457
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
443
458
  * RPC read fails.
444
459
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -500,6 +515,8 @@ class MorphoMidnight {
500
515
  */
501
516
  takeBorrow(params) {
502
517
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
518
+ // Reject the zero account before preparing anything for it.
519
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
503
520
  validateTakeDeadlineWindow(params.deadline);
504
521
  const rawParams = {
505
522
  chainId: this.chainId,
@@ -574,11 +591,14 @@ class MorphoMidnight {
574
591
  * Midnight protocol and market token contracts are rejected.
575
592
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
576
593
  * @param params.deadline - Bundle execution deadline timestamp.
577
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
594
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
595
+ * proceeds; on an assets target it is added on top of `target.assets`.
578
596
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
579
597
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
580
598
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
581
599
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
600
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
601
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
582
602
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
583
603
  * RPC read fails.
584
604
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
@@ -622,6 +642,8 @@ class MorphoMidnight {
622
642
  */
623
643
  takeWithdraw(params) {
624
644
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
645
+ // Reject the zero account before preparing anything for it.
646
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
625
647
  validateTakeDeadlineWindow(params.deadline);
626
648
  const rawParams = {
627
649
  chainId: this.chainId,
@@ -689,11 +711,14 @@ class MorphoMidnight {
689
711
  * Midnight protocol and market token contracts are rejected.
690
712
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
691
713
  * @param params.deadline - Bounded bundle execution deadline timestamp.
692
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
714
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
715
+ * proceeds; on an assets target it is added on top of `target.assets`.
693
716
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
694
717
  * @returns Lazy collateral approvals and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
695
718
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
696
719
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
720
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
721
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
697
722
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
698
723
  * RPC read fails.
699
724
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -734,7 +759,6 @@ class MorphoMidnight {
734
759
  * withdrawal.
735
760
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
736
761
  * its bounds cannot hold at any fill.
737
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
738
762
  * @example
739
763
  * ```ts
740
764
  * const output = midnight.supplyCollateralTakeBorrow({
@@ -751,6 +775,8 @@ class MorphoMidnight {
751
775
  */
752
776
  supplyCollateralTakeBorrow(params) {
753
777
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
778
+ // Reject the zero account before preparing anything for it.
779
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
754
780
  validateTakeDeadlineWindow(params.deadline);
755
781
  const market = params.marketData.params;
756
782
  const rawParams = {
@@ -819,7 +845,7 @@ class MorphoMidnight {
819
845
  collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
820
846
  }
821
847
  return {
822
- getRequirements: async (requirementsParams) => {
848
+ getRequirements: async (_requirementsParams) => {
823
849
  const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => (0, index_js_2.getMidnightApprovalRequirements)({
824
850
  viemClient: this.client.viemClient,
825
851
  chainId: this.chainId,
@@ -827,7 +853,6 @@ class MorphoMidnight {
827
853
  owner: params.accountAddress,
828
854
  spender: tx.to,
829
855
  amount,
830
- approvalAmount: requirementsParams?.approvalAmount,
831
856
  })));
832
857
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
833
858
  return [...approvals.flat(), ...authorization];
@@ -879,6 +904,8 @@ class MorphoMidnight {
879
904
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
880
905
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
881
906
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
907
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
908
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
882
909
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
883
910
  * RPC read fails.
884
911
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -923,7 +950,6 @@ class MorphoMidnight {
923
950
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
924
951
  * contract or a market token contract, or when `referralFeeRecipient` is either with a
925
952
  * positive referral fee.
926
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
927
953
  * @example
928
954
  * ```ts
929
955
  * const output = midnight.takeRepayWithdrawCollateral({
@@ -942,6 +968,8 @@ class MorphoMidnight {
942
968
  */
943
969
  takeRepayWithdrawCollateral(params) {
944
970
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
971
+ // Reject the zero account before preparing anything for it.
972
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
945
973
  validateTakeDeadlineWindow(params.deadline);
946
974
  const market = params.marketData.params;
947
975
  const rawParams = {
@@ -1028,7 +1056,7 @@ class MorphoMidnight {
1028
1056
  ? params.target.assets
1029
1057
  : params.target.maxBuyerAssets;
1030
1058
  return {
1031
- getRequirements: async (requirementsParams) => {
1059
+ getRequirements: async (_requirementsParams) => {
1032
1060
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
1033
1061
  viemClient: this.client.viemClient,
1034
1062
  chainId: this.chainId,
@@ -1036,7 +1064,6 @@ class MorphoMidnight {
1036
1064
  owner: params.accountAddress,
1037
1065
  spender: tx.to,
1038
1066
  amount: pulledAssets,
1039
- approvalAmount: requirementsParams?.approvalAmount,
1040
1067
  });
1041
1068
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
1042
1069
  return [...approvals, ...authorization];
@@ -1048,23 +1075,30 @@ class MorphoMidnight {
1048
1075
  * Prepares a direct collateral supply using a caller-provided market snapshot.
1049
1076
  *
1050
1077
  * @param params - Supplier, market snapshot, collateral amount, reserve, and optional collateral index.
1051
- * @param params.accountAddress - Account receiving the supplied collateral position.
1078
+ * @param params.accountAddress - Account receiving the supplied collateral position. It must send
1079
+ * the transaction: Midnight pulls the collateral from `msg.sender` and only lets the position owner
1080
+ * or its operators supply for it, and the approval requirements are resolved for this account.
1052
1081
  * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
1053
1082
  * @param params.collateralAssets - Collateral assets supplied in this transaction.
1054
1083
  * @param params.reservedCollateralAssets - Existing collateral reserved by other open maker groups.
1055
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
1084
+ * Only raises the approval requirement so those groups keep their allowance; the transaction
1085
+ * transfers only `collateralAssets`.
1086
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`. Indexes follow the
1087
+ * market's collateral parameters, which Midnight sorts by token address, not the order they were
1088
+ * listed in when the market was built; check `marketData.getCollateralByIndex(index).token`.
1056
1089
  * @returns Lazy token-approval requirements and a synchronous transaction builder.
1057
1090
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1058
1091
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
1092
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1059
1093
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1060
1094
  * RPC read fails.
1061
1095
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
1062
1096
  * @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
1063
1097
  * @throws {InputExceedsMaxError} when `collateralAssets` exceeds `uint128`.
1064
1098
  * @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
1065
- * @throws {MidnightZeroOnBehalfError} from `buildTx()` when `accountAddress` is the zero address.
1099
+ * @throws {MidnightZeroOnBehalfError} from `getRequirements()` and `buildTx()` when `accountAddress`
1100
+ * is the zero address.
1066
1101
  * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
1067
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled collateral assets.
1068
1102
  * @example
1069
1103
  * ```ts
1070
1104
  * const output = midnight.supplyCollateral({
@@ -1076,6 +1110,8 @@ class MorphoMidnight {
1076
1110
  */
1077
1111
  supplyCollateral(params) {
1078
1112
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1113
+ // Reject a malformed account here; the builder rejects the zero account.
1114
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("accountAddress", params.accountAddress);
1079
1115
  validateMarketData(params.marketData, this.chainId);
1080
1116
  assertPositiveAmount("collateralAssets", params.collateralAssets);
1081
1117
  (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("collateralAssets", params.collateralAssets);
@@ -1085,15 +1121,20 @@ class MorphoMidnight {
1085
1121
  const collateral = market.getCollateralByIndex(collateralIndex);
1086
1122
  const midnight = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnight");
1087
1123
  return {
1088
- getRequirements: async (requirementsParams) => await (0, index_js_2.getMidnightApprovalRequirements)({
1089
- viemClient: this.client.viemClient,
1090
- chainId: this.chainId,
1091
- token: collateral.token,
1092
- owner: params.accountAddress,
1093
- spender: midnight,
1094
- amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1095
- approvalAmount: requirementsParams?.approvalAmount,
1096
- }),
1124
+ getRequirements: async (_requirementsParams) => {
1125
+ // Match buildTx(): the requirement helper would report a zero owner with another class.
1126
+ if ((0, viem_1.isAddressEqual)(params.accountAddress, viem_1.zeroAddress)) {
1127
+ throw new index_js_4.MidnightZeroOnBehalfError("onBehalf");
1128
+ }
1129
+ return await (0, index_js_2.getMidnightApprovalRequirements)({
1130
+ viemClient: this.client.viemClient,
1131
+ chainId: this.chainId,
1132
+ token: collateral.token,
1133
+ owner: params.accountAddress,
1134
+ spender: midnight,
1135
+ amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1136
+ });
1137
+ },
1097
1138
  buildTx: () => (0, index_js_1.midnightSupplyCollateral)({
1098
1139
  chainId: this.chainId,
1099
1140
  market: market.params,
@@ -1124,9 +1165,12 @@ class MorphoMidnight {
1124
1165
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
1125
1166
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1126
1167
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1168
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1169
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1127
1170
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1128
1171
  * RPC read fails.
1129
1172
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1173
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1130
1174
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1131
1175
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1132
1176
  * @throws {NonPositiveInputError} when `loanAssets` is non-positive.
@@ -1157,7 +1201,6 @@ class MorphoMidnight {
1157
1201
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1158
1202
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1159
1203
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1160
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1161
1204
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1162
1205
  * @example
1163
1206
  * ```ts
@@ -1173,9 +1216,11 @@ class MorphoMidnight {
1173
1216
  */
1174
1217
  async makeLend(params) {
1175
1218
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1219
+ // Reject the zero account before preparing anything for it.
1220
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1176
1221
  // Fails before any API read or build when the deadline has already passed.
1177
1222
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1178
- const tree = midnight_sdk_1.Tree.from(params.offers);
1223
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1179
1224
  rejectReduceOnlyOffers(tree.offers);
1180
1225
  return this.prepareLendOffers({ ...params, offers: tree });
1181
1226
  }
@@ -1195,9 +1240,12 @@ class MorphoMidnight {
1195
1240
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1196
1241
  * @returns Prepared group metadata, lazy authorization requirements, and a synchronous transaction builder.
1197
1242
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1243
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1244
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1198
1245
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1199
1246
  * RPC read fails.
1200
1247
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1248
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1201
1249
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1202
1250
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1203
1251
  * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
@@ -1239,9 +1287,11 @@ class MorphoMidnight {
1239
1287
  */
1240
1288
  async makeBorrow(params) {
1241
1289
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1290
+ // Reject the zero account before preparing anything for it.
1291
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1242
1292
  // Fails before any API read or build when the deadline has already passed.
1243
1293
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1244
- const tree = midnight_sdk_1.Tree.from(params.offers);
1294
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1245
1295
  rejectReduceOnlyOffers(tree.offers);
1246
1296
  return this.prepareBorrowOffers({ ...params, offers: tree });
1247
1297
  }
@@ -1249,9 +1299,11 @@ class MorphoMidnight {
1249
1299
  * Prepares lend-side offers for publication.
1250
1300
  */
1251
1301
  async prepareLendOffers(params) {
1302
+ // Reject a malformed address before viem compares offer markets with it.
1303
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("loanToken", params.loanToken);
1252
1304
  assertPositiveAmount("loanAssets", params.loanAssets);
1253
1305
  assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
1254
- const tree = midnight_sdk_1.Tree.from(params.offers);
1306
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1255
1307
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
1256
1308
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
1257
1309
  const data = await getOffersDataInternal({
@@ -1286,7 +1338,7 @@ class MorphoMidnight {
1286
1338
  groups: data.groups,
1287
1339
  root: data.tree.root,
1288
1340
  ratifierType: data.ratifierType,
1289
- getRequirements: async (requirementsParams) => {
1341
+ getRequirements: async (_requirementsParams) => {
1290
1342
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
1291
1343
  viemClient: this.client.viemClient,
1292
1344
  chainId: this.chainId,
@@ -1294,7 +1346,6 @@ class MorphoMidnight {
1294
1346
  owner: data.accountAddress,
1295
1347
  spender: midnight,
1296
1348
  amount: params.loanAssets + (params.reservedLoanAssets ?? 0n),
1297
- approvalAmount: requirementsParams?.approvalAmount,
1298
1349
  });
1299
1350
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1300
1351
  return [...approvals, ...authorization];
@@ -1320,6 +1371,12 @@ class MorphoMidnight {
1320
1371
  * `midnightBlueBuyCallbackFactory`, `accountAddress` and `callbackSalt`, and fetches the Morpho Blue market,
1321
1372
  * accruing interest to the current time before previewing parked shares (markets whose
1322
1373
  * IRM the SDK cannot accrue are previewed on their last-updated state).
1374
+ * The share check runs once, before signing: the bundle supplies `assetsToPark` with no
1375
+ * minimum-shares bound, so interest accrued before inclusion can still round the supply down
1376
+ * to zero shares if `assetsToPark` is worth less than one share at inclusion. A preview above
1377
+ * one share does not rule this out: interest accrued while the transaction waits, or not
1378
+ * accrued by the SDK for an IRM it cannot accrue, raises the share price. Choosing a market
1379
+ * whose share price makes that impossible is the caller's responsibility.
1323
1380
  * The caller is responsible for trusting the Blue market's oracle and IRM. If Blue liquidity is
1324
1381
  * drained, callback offers cannot fill until liquidity returns. `assetsToPark` may underfund the
1325
1382
  * offers; top-ups are allowed.
@@ -1341,6 +1398,8 @@ class MorphoMidnight {
1341
1398
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1342
1399
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
1343
1400
  * another chain than `this.chainId`.
1401
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1402
+ * @throws {MidnightCalldataEncodingError} when the offer tree or `blueMarket` cannot be ABI-encoded.
1344
1403
  * @throws {viem.BaseError} when the `eth_chainId` request, a Blue market RPC read, or a
1345
1404
  * requirement RPC read fails.
1346
1405
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2`, `midnightBlueBuyCallbackFactory`, `midnight`, `blue` or V1 ratifier deployment.
@@ -1352,6 +1411,7 @@ class MorphoMidnight {
1352
1411
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1353
1412
  * @throws {NativeAmountOnNonWNativeAssetError} when `blueMarket.loanToken` is not wNative.
1354
1413
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1414
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1355
1415
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1356
1416
  * (not thrown when `validation` is `false`).
1357
1417
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1377,11 +1437,10 @@ class MorphoMidnight {
1377
1437
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1378
1438
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1379
1439
  * @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
1380
- * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price.
1440
+ * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price (checked at preparation time only).
1381
1441
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1382
1442
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
1383
1443
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1384
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `assetsToPark`.
1385
1444
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1386
1445
  * @example
1387
1446
  * ```ts
@@ -1401,15 +1460,21 @@ class MorphoMidnight {
1401
1460
  * ```
1402
1461
  */
1403
1462
  async supplyBlueMakeLend(params) {
1463
+ // Reject the zero account before preparing anything for it.
1464
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1465
+ // Reject wrong-sized salts before callback derivation pads them or any read occurs.
1466
+ (0, validateMidnightPublication_js_1.validateMidnightBytes32)("callbackSalt", params.callbackSalt);
1404
1467
  assertPositiveAmount("assetsToPark", params.assetsToPark);
1405
1468
  (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("assetsToPark", params.assetsToPark);
1406
- const tree = midnight_sdk_1.Tree.from(params.offers);
1469
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1407
1470
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
1408
1471
  rejectReduceOnlyOffers(tree.offers);
1409
1472
  await (0, validateClientChainId_js_1.validateClientChainId)(this.client.viemClient, this.chainId);
1410
1473
  // Fails before any API read or build when the deadline has already passed.
1411
1474
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1412
1475
  const { callbackSalt } = params;
1476
+ // Encode the whole Blue market first so a malformed field fails typed, before the RPC read.
1477
+ const callbackData = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("blueMarket", () => (0, callback_js_1.getMidnightBlueBuyCallbackData)(params.blueMarket));
1413
1478
  const blueMarketId = blue_sdk_1.MarketUtils.getMarketId(params.blueMarket);
1414
1479
  const callback = (0, callback_js_1.getMidnightBlueBuyCallbackAddress)({
1415
1480
  chainId: this.chainId,
@@ -1436,7 +1501,6 @@ class MorphoMidnight {
1436
1501
  assets: params.assetsToPark,
1437
1502
  });
1438
1503
  }
1439
- const callbackData = (0, callback_js_1.getMidnightBlueBuyCallbackData)(params.blueMarket);
1440
1504
  data.tree.offers.forEach((offer, index) => {
1441
1505
  const offerMarket = (0, publication_js_1.offerMarketParams)(offer);
1442
1506
  if (!(0, viem_1.isAddressEqual)(offerMarket.loanToken, params.blueMarket.loanToken)) {
@@ -1483,7 +1547,7 @@ class MorphoMidnight {
1483
1547
  groups: data.groups,
1484
1548
  root: data.tree.root,
1485
1549
  ratifierType: data.ratifierType,
1486
- getRequirements: async (requirementsParams) => {
1550
+ getRequirements: async (_requirementsParams) => {
1487
1551
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
1488
1552
  viemClient: this.client.viemClient,
1489
1553
  chainId: this.chainId,
@@ -1491,7 +1555,6 @@ class MorphoMidnight {
1491
1555
  owner: data.accountAddress,
1492
1556
  spender: (0, morpho_ts_1.getChainAddress)(this.chainId, "midnightBundlesV2"),
1493
1557
  amount: params.assetsToPark,
1494
- approvalAmount: requirementsParams?.approvalAmount,
1495
1558
  });
1496
1559
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1497
1560
  return [...approvals, ...authorization];
@@ -1503,7 +1566,7 @@ class MorphoMidnight {
1503
1566
  * Prepares borrow-side offers for publication.
1504
1567
  */
1505
1568
  async prepareBorrowOffers(params) {
1506
- const tree = midnight_sdk_1.Tree.from(params.offers);
1569
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1507
1570
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1508
1571
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
1509
1572
  const data = await getOffersDataInternal({
@@ -1549,9 +1612,12 @@ class MorphoMidnight {
1549
1612
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1550
1613
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1551
1614
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1615
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1616
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1552
1617
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1553
1618
  * RPC read fails.
1554
1619
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1620
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1555
1621
  * @throws {MidnightOfferSideMismatchError} when an offer is not a sell offer (`buy = false`).
1556
1622
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1557
1623
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1596,9 +1662,11 @@ class MorphoMidnight {
1596
1662
  */
1597
1663
  async makeWithdraw(params) {
1598
1664
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1665
+ // Reject the zero account before preparing anything for it.
1666
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1599
1667
  // Fails before any API read or build when the deadline has already passed.
1600
1668
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1601
- const tree = midnight_sdk_1.Tree.from(params.offers);
1669
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1602
1670
  // Reject the wrong exit intent before calling the mempool validation API.
1603
1671
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1604
1672
  for (const [index, offer] of tree.offers.entries()) {
@@ -1631,9 +1699,12 @@ class MorphoMidnight {
1631
1699
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
1632
1700
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1633
1701
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1702
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1703
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1634
1704
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1635
1705
  * RPC read fails.
1636
1706
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1707
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1637
1708
  * @throws {MidnightOfferSideMismatchError} when an offer is not a buy offer (`buy = true`).
1638
1709
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1639
1710
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1665,7 +1736,6 @@ class MorphoMidnight {
1665
1736
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1666
1737
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1667
1738
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1668
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1669
1739
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1670
1740
  * @example
1671
1741
  * ```ts
@@ -1682,9 +1752,11 @@ class MorphoMidnight {
1682
1752
  */
1683
1753
  async makeRepay(params) {
1684
1754
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1755
+ // Reject the zero account before preparing anything for it.
1756
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1685
1757
  // Fails before any API read or build when the deadline has already passed.
1686
1758
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1687
- const tree = midnight_sdk_1.Tree.from(params.offers);
1759
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1688
1760
  // Reject the wrong exit intent before calling the mempool validation API.
1689
1761
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
1690
1762
  for (const [index, offer] of tree.offers.entries()) {
@@ -1718,6 +1790,8 @@ class MorphoMidnight {
1718
1790
  * required for the full pulled amount.
1719
1791
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1720
1792
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1793
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1794
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1721
1795
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1722
1796
  * RPC read fails.
1723
1797
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
@@ -1730,6 +1804,7 @@ class MorphoMidnight {
1730
1804
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1731
1805
  * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
1732
1806
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1807
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1733
1808
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1734
1809
  * (not thrown when `validation` is `false`).
1735
1810
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1758,7 +1833,6 @@ class MorphoMidnight {
1758
1833
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1759
1834
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1760
1835
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1761
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
1762
1836
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1763
1837
  * @example
1764
1838
  * ```ts
@@ -1775,12 +1849,14 @@ class MorphoMidnight {
1775
1849
  */
1776
1850
  async supplyCollateralMakeBorrow(params) {
1777
1851
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1852
+ // Reject the zero account before preparing anything for it.
1853
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1778
1854
  // Fails before any API read or build when the deadline has already passed.
1779
1855
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1780
1856
  const market = params.collateral.market instanceof midnight_sdk_1.MarketParams
1781
1857
  ? params.collateral.market
1782
1858
  : midnight_sdk_1.MarketParams.from(params.collateral.market);
1783
- const tree = midnight_sdk_1.Tree.from(params.offers);
1859
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1784
1860
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1785
1861
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
1786
1862
  rejectReduceOnlyOffers(tree.offers);
@@ -1790,9 +1866,9 @@ class MorphoMidnight {
1790
1866
  params: { ...params, offers: tree },
1791
1867
  marketCreationTime: "now",
1792
1868
  });
1793
- const marketId = midnight_sdk_1.MarketUtils.toId(market);
1869
+ const marketId = (0, encodeMidnightCalldata_js_1.encodeMidnightMarketId)(market);
1794
1870
  for (const offer of data.tree.offers) {
1795
- const offerMarketId = midnight_sdk_1.MarketUtils.toId(offer.market);
1871
+ const offerMarketId = (0, encodeMidnightCalldata_js_1.encodeMidnightMarketId)(offer.market);
1796
1872
  if (offerMarketId.toLowerCase() !== marketId.toLowerCase()) {
1797
1873
  throw new index_js_4.MarketIdMismatchError(offerMarketId, marketId);
1798
1874
  }
@@ -1825,7 +1901,7 @@ class MorphoMidnight {
1825
1901
  groups: data.groups,
1826
1902
  root: data.tree.root,
1827
1903
  ratifierType: data.ratifierType,
1828
- getRequirements: async (requirementsParams) => {
1904
+ getRequirements: async (_requirementsParams) => {
1829
1905
  const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => (0, index_js_2.getMidnightApprovalRequirements)({
1830
1906
  viemClient: this.client.viemClient,
1831
1907
  chainId: this.chainId,
@@ -1833,7 +1909,6 @@ class MorphoMidnight {
1833
1909
  owner: data.accountAddress,
1834
1910
  spender: midnightBundlesV2,
1835
1911
  amount,
1836
- approvalAmount: requirementsParams?.approvalAmount,
1837
1912
  })));
1838
1913
  return [
1839
1914
  ...approvals.flat(),
@@ -1847,7 +1922,9 @@ class MorphoMidnight {
1847
1922
  * Prepares redemption of accrued Midnight credit from a position snapshot.
1848
1923
  *
1849
1924
  * @param params - Position owner, accrued position, optional unit amount, and receiver.
1850
- * @param params.accountAddress - Position owner whose credit is redeemed.
1925
+ * @param params.accountAddress - Position owner whose credit is redeemed. It must send the
1926
+ * transaction (or authorize the sender): Midnight reverts `Unauthorized()` otherwise, which
1927
+ * `getRequirements()` cannot detect because it does not know the sender.
1851
1928
  * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`.
1852
1929
  * @param params.receiver - Optional credit receiver; defaults to the position owner.
1853
1930
  * Midnight protocol and market token contracts are rejected.
@@ -1860,6 +1937,7 @@ class MorphoMidnight {
1860
1937
  * is left. Redeem again after maturity to empty the position.
1861
1938
  * @returns No requirements and a synchronous redemption transaction builder.
1862
1939
  * @throws {ChainIdMismatchError} when the position market targets another chain.
1940
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1863
1941
  * @throws {MidnightMarketAddressMismatchError} when the position market targets another Midnight deployment.
1864
1942
  * @throws {MissingAccrualPositionError} when no position snapshot is supplied.
1865
1943
  * @throws {AccrualPositionUserMismatchError} when the position snapshot belongs to another account.
@@ -1887,9 +1965,13 @@ class MorphoMidnight {
1887
1965
  */
1888
1966
  redeem(params) {
1889
1967
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1968
+ // Reject a malformed account here; the builder rejects the zero account.
1969
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("accountAddress", params.accountAddress);
1890
1970
  if (!params.positionData) {
1891
1971
  throw new index_js_4.MissingAccrualPositionError();
1892
1972
  }
1973
+ if (params.positionData.user != null)
1974
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("positionData.user", params.positionData.user);
1893
1975
  if (params.positionData.user == null ||
1894
1976
  !(0, viem_1.isAddressEqual)(params.positionData.user, params.accountAddress)) {
1895
1977
  throw new index_js_4.AccrualPositionUserMismatchError(params.positionData.user ?? "unbound", params.accountAddress);
@@ -1950,7 +2032,7 @@ class MorphoMidnight {
1950
2032
  * scaled by `ORACLE_PRICE_SCALE`. An empty array is safe only when
1951
2033
  * `collateralWithdrawals` is empty or the conservative post-operation debt is zero: a `full`
1952
2034
  * repay, or `repay.assets` covering `positionData.debt`.
1953
- * @param params.repay - `{ type: "assets", assets }` (`0n` to only withdraw) or `{ type: "full", maxBuyerAssets }`; a loan-token approval to `MidnightBundlesV2` is required when the allowance is below the pulled amount — unlimited (`maxUint256`) by default, or `approvalAmount` when passed to `getRequirements()` — and any unused part is refunded.
2035
+ * @param params.repay - `{ type: "assets", assets }` (`0n` to only withdraw) or `{ type: "full", maxBuyerAssets }`; a loan-token approval to `MidnightBundlesV2` is required when the allowance is below the pulled amount (unlimited: `maxUint256`, capped per token by `MAX_TOKEN_APPROVALS`), and any unused part is refunded.
1954
2036
  * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
1955
2037
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
1956
2038
  * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
@@ -1966,6 +2048,8 @@ class MorphoMidnight {
1966
2048
  * @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
1967
2049
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1968
2050
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
2051
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
2052
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1969
2053
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1970
2054
  * RPC read fails.
1971
2055
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
@@ -1990,7 +2074,6 @@ class MorphoMidnight {
1990
2074
  * during this method call, before the lazy output is returned.
1991
2075
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
1992
2076
  * contract or a market token contract.
1993
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
1994
2077
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1995
2078
  * @example
1996
2079
  * ```ts
@@ -2008,6 +2091,8 @@ class MorphoMidnight {
2008
2091
  */
2009
2092
  repayWithdrawCollateral(params) {
2010
2093
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
2094
+ // Reject the zero account before preparing anything for it.
2095
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
2011
2096
  // Fails before any API read or build when the deadline has already passed.
2012
2097
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
2013
2098
  const market = params.marketData.params;
@@ -2085,7 +2170,7 @@ class MorphoMidnight {
2085
2170
  ? params.repay.assets
2086
2171
  : params.repay.maxBuyerAssets;
2087
2172
  return {
2088
- getRequirements: async (requirementsParams) => {
2173
+ getRequirements: async (_requirementsParams) => {
2089
2174
  const approvals = pulledAssets > 0n
2090
2175
  ? await (0, index_js_2.getMidnightApprovalRequirements)({
2091
2176
  viemClient: this.client.viemClient,
@@ -2094,7 +2179,6 @@ class MorphoMidnight {
2094
2179
  owner: params.accountAddress,
2095
2180
  spender: tx.to,
2096
2181
  amount: pulledAssets,
2097
- approvalAmount: requirementsParams?.approvalAmount,
2098
2182
  })
2099
2183
  : [];
2100
2184
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
@@ -2124,6 +2208,7 @@ class MorphoMidnight {
2124
2208
  * @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
2125
2209
  * @throws {ChainIdMismatchError} when the client targets another chain, or from
2126
2210
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
2211
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as an out-of-range integer.
2127
2212
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
2128
2213
  * RPC read fails.
2129
2214
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.