@morpho-org/morpho-sdk 8.3.0 → 9.0.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 (155) hide show
  1. package/MIGRATION-v8-to-v9.md +54 -0
  2. package/README.md +13 -7
  3. package/lib/cjs/actions/bundles/common.d.ts +4 -7
  4. package/lib/cjs/actions/bundles/common.js +8 -14
  5. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  6. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +1 -8
  7. package/lib/cjs/actions/midnight/authorization.d.ts +3 -1
  8. package/lib/cjs/actions/midnight/authorization.js +11 -1
  9. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -0
  10. package/lib/cjs/actions/midnight/cancelAndMake.js +10 -2
  11. package/lib/cjs/actions/midnight/redeem.d.ts +3 -1
  12. package/lib/cjs/actions/midnight/redeem.js +9 -3
  13. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  14. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +7 -3
  15. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +4 -1
  16. package/lib/cjs/actions/midnight/supplyCollateral.js +10 -3
  17. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  18. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +9 -3
  19. package/lib/cjs/actions/midnight/takeBorrow.d.ts +3 -1
  20. package/lib/cjs/actions/midnight/takeBorrow.js +9 -3
  21. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
  22. package/lib/cjs/actions/midnight/takeLend.js +7 -2
  23. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  24. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +8 -2
  25. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +3 -1
  26. package/lib/cjs/actions/midnight/takeWithdraw.js +10 -3
  27. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  28. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +5 -7
  29. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +7 -11
  30. package/lib/cjs/actions/requirements/getRequirementsApproval.js +8 -15
  31. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  32. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +11 -8
  33. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  34. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  35. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +1 -1
  36. package/lib/cjs/actions/vaultV1/inKindRedeem.js +1 -1
  37. package/lib/cjs/actions/vaultV1/withdraw.d.ts +4 -4
  38. package/lib/cjs/actions/vaultV1/withdraw.js +4 -4
  39. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +1 -1
  40. package/lib/cjs/actions/vaultV2/forceWithdraw.js +1 -1
  41. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +1 -1
  42. package/lib/cjs/actions/vaultV2/inKindRedeem.js +1 -1
  43. package/lib/cjs/actions/vaultV2/withdraw.d.ts +4 -4
  44. package/lib/cjs/actions/vaultV2/withdraw.js +4 -4
  45. package/lib/cjs/entities/blue/blue.d.ts +2 -12
  46. package/lib/cjs/entities/blue/blue.js +0 -4
  47. package/lib/cjs/entities/midnight/midnight.d.ts +56 -17
  48. package/lib/cjs/entities/midnight/midnight.js +131 -52
  49. package/lib/cjs/entities/midnight/types.d.ts +2 -9
  50. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  51. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +0 -7
  52. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  53. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -20
  54. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +40 -37
  55. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -34
  56. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +36 -34
  57. package/lib/cjs/entities/vaultV2/vaultV2.js +8 -34
  58. package/lib/cjs/helpers/encodeMidnightCalldata.d.ts +48 -0
  59. package/lib/cjs/helpers/encodeMidnightCalldata.js +74 -0
  60. package/lib/cjs/helpers/slippage.d.ts +9 -25
  61. package/lib/cjs/helpers/slippage.js +10 -27
  62. package/lib/cjs/helpers/validate.d.ts +1 -0
  63. package/lib/cjs/helpers/validate.js +5 -0
  64. package/lib/cjs/helpers/validateMidnightAccount.d.ts +34 -0
  65. package/lib/cjs/helpers/validateMidnightAccount.js +47 -0
  66. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  67. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +4 -0
  68. package/lib/cjs/helpers/validateMidnightMarket.d.ts +2 -0
  69. package/lib/cjs/helpers/validateMidnightMarket.js +5 -0
  70. package/lib/cjs/helpers/validateMidnightPublication.d.ts +11 -0
  71. package/lib/cjs/helpers/validateMidnightPublication.js +12 -1
  72. package/lib/cjs/helpers/validateMidnightReceiver.d.ts +1 -0
  73. package/lib/cjs/helpers/validateMidnightReceiver.js +8 -0
  74. package/lib/cjs/helpers/validateTakeableOffers.d.ts +2 -1
  75. package/lib/cjs/helpers/validateTakeableOffers.js +4 -3
  76. package/lib/cjs/types/action.d.ts +3 -1
  77. package/lib/cjs/types/error.d.ts +56 -5
  78. package/lib/cjs/types/error.js +139 -10
  79. package/lib/esm/actions/bundles/common.d.ts +4 -7
  80. package/lib/esm/actions/bundles/common.js +8 -14
  81. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  82. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -9
  83. package/lib/esm/actions/midnight/authorization.d.ts +3 -1
  84. package/lib/esm/actions/midnight/authorization.js +12 -2
  85. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -0
  86. package/lib/esm/actions/midnight/cancelAndMake.js +11 -3
  87. package/lib/esm/actions/midnight/redeem.d.ts +3 -1
  88. package/lib/esm/actions/midnight/redeem.js +10 -4
  89. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  90. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +8 -4
  91. package/lib/esm/actions/midnight/supplyCollateral.d.ts +4 -1
  92. package/lib/esm/actions/midnight/supplyCollateral.js +11 -4
  93. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  94. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +10 -4
  95. package/lib/esm/actions/midnight/takeBorrow.d.ts +3 -1
  96. package/lib/esm/actions/midnight/takeBorrow.js +10 -4
  97. package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
  98. package/lib/esm/actions/midnight/takeLend.js +8 -3
  99. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  100. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +9 -3
  101. package/lib/esm/actions/midnight/takeWithdraw.d.ts +3 -1
  102. package/lib/esm/actions/midnight/takeWithdraw.js +11 -4
  103. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  104. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +6 -8
  105. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +7 -11
  106. package/lib/esm/actions/requirements/getRequirementsApproval.js +9 -16
  107. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  108. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +12 -9
  109. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  110. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  111. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +1 -1
  112. package/lib/esm/actions/vaultV1/inKindRedeem.js +1 -1
  113. package/lib/esm/actions/vaultV1/withdraw.d.ts +4 -4
  114. package/lib/esm/actions/vaultV1/withdraw.js +4 -4
  115. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +1 -1
  116. package/lib/esm/actions/vaultV2/forceWithdraw.js +1 -1
  117. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +1 -1
  118. package/lib/esm/actions/vaultV2/inKindRedeem.js +1 -1
  119. package/lib/esm/actions/vaultV2/withdraw.d.ts +4 -4
  120. package/lib/esm/actions/vaultV2/withdraw.js +4 -4
  121. package/lib/esm/entities/blue/blue.d.ts +2 -12
  122. package/lib/esm/entities/blue/blue.js +0 -4
  123. package/lib/esm/entities/midnight/midnight.d.ts +56 -17
  124. package/lib/esm/entities/midnight/midnight.js +132 -53
  125. package/lib/esm/entities/midnight/types.d.ts +2 -9
  126. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  127. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +1 -8
  128. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  129. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +9 -21
  130. package/lib/esm/entities/vaultV1/vaultV1.d.ts +40 -37
  131. package/lib/esm/entities/vaultV1/vaultV1.js +6 -35
  132. package/lib/esm/entities/vaultV2/vaultV2.d.ts +36 -34
  133. package/lib/esm/entities/vaultV2/vaultV2.js +8 -34
  134. package/lib/esm/helpers/encodeMidnightCalldata.d.ts +48 -0
  135. package/lib/esm/helpers/encodeMidnightCalldata.js +69 -0
  136. package/lib/esm/helpers/slippage.d.ts +9 -25
  137. package/lib/esm/helpers/slippage.js +9 -25
  138. package/lib/esm/helpers/validate.d.ts +1 -0
  139. package/lib/esm/helpers/validate.js +5 -0
  140. package/lib/esm/helpers/validateMidnightAccount.d.ts +34 -0
  141. package/lib/esm/helpers/validateMidnightAccount.js +43 -0
  142. package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  143. package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +4 -0
  144. package/lib/esm/helpers/validateMidnightMarket.d.ts +2 -0
  145. package/lib/esm/helpers/validateMidnightMarket.js +5 -0
  146. package/lib/esm/helpers/validateMidnightPublication.d.ts +11 -0
  147. package/lib/esm/helpers/validateMidnightPublication.js +10 -0
  148. package/lib/esm/helpers/validateMidnightReceiver.d.ts +1 -0
  149. package/lib/esm/helpers/validateMidnightReceiver.js +8 -0
  150. package/lib/esm/helpers/validateTakeableOffers.d.ts +2 -1
  151. package/lib/esm/helpers/validateTakeableOffers.js +4 -3
  152. package/lib/esm/types/action.d.ts +3 -1
  153. package/lib/esm/types/error.d.ts +56 -5
  154. package/lib/esm/types/error.js +134 -6
  155. package/package.json +4 -3
@@ -8,18 +8,23 @@ import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, }
8
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
9
  import { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "../../helpers/callback.js";
10
10
  import { MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS } from "../../helpers/constant.js";
11
+ import { encodeMidnightMarketId, wrapMidnightEncoding, } from "../../helpers/encodeMidnightCalldata.js";
11
12
  import { getMidnightMaxSafeDebt, validateChainId, } from "../../helpers/index.js";
13
+ import { validateMidnightAccount, validateMidnightAddress, } from "../../helpers/validateMidnightAccount.js";
12
14
  import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
13
15
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
16
+ import { validateMidnightBytes32 } from "../../helpers/validateMidnightPublication.js";
14
17
  import { validateMidnightTakeFeasibility } from "../../helpers/validateMidnightTakeFeasibility.js";
15
18
  import { validateOfferSides } from "../../helpers/validateOfferSides.js";
16
- import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, EmptyBlueParkingMarketError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
19
+ import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, EmptyBlueParkingMarketError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MidnightZeroOnBehalfError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
17
20
  import { validateMidnightDeadline } from "./deadline.js";
18
21
  import { fetchMidnightMakerOfferStates, offerMarketParams, validateMidnightMakerOfferCallbacks, validateMidnightMakerOfferStates, } from "./publication.js";
19
22
  const validatePositionBinding = (params) => {
20
23
  if (params.positionData.marketId !== params.marketData.id) {
21
24
  throw new MarketIdMismatchError(params.positionData.marketId, params.marketData.id);
22
25
  }
26
+ // Reject a malformed address before viem compares it.
27
+ validateMidnightAddress("positionData.user", params.positionData.user);
23
28
  if (!isAddressEqual(params.positionData.user, params.accountAddress)) {
24
29
  throw new AccrualPositionUserMismatchError(params.positionData.user, params.accountAddress);
25
30
  }
@@ -49,7 +54,9 @@ const rejectReduceOnlyOffers = (offers) => {
49
54
  };
50
55
  const getOffersDataInternal = async ({ client, chainId, params, marketCreationTime = "expiry", }) => {
51
56
  validateChainId(client.viemClient.chain?.id, chainId);
52
- const tree = Tree.from(params.offers);
57
+ // Reject a malformed or zero maker before comparing offers against it.
58
+ validateMidnightAccount("accountAddress", params.accountAddress);
59
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
53
60
  const midnight = getChainAddress(chainId, "midnight");
54
61
  tree.offers.forEach((offer, index) => {
55
62
  if (!isAddressEqual(offer.maker, params.accountAddress)) {
@@ -243,6 +250,7 @@ export class MorphoMidnight {
243
250
  * @returns Prepared tree, groups, ratifier, and encoded payload used by maker flows.
244
251
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, another chain than this entity's.
245
252
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
253
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
246
254
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
247
255
  * (not thrown when `validation` is `false`).
248
256
  * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
@@ -252,6 +260,8 @@ export class MorphoMidnight {
252
260
  * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
253
261
  * @throws {UnknownAddressError} when the chain has no deployment for the tree's V1 ratifier.
254
262
  * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
263
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
264
+ * @throws {MidnightCalldataEncodingError} when an offer cannot be ABI-encoded, such as an out-of-range integer, or `accountAddress` is not a well-formed address.
255
265
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
256
266
  * @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
257
267
  * @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
@@ -306,6 +316,8 @@ export class MorphoMidnight {
306
316
  * @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
307
317
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
308
318
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
319
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
320
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
309
321
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
310
322
  * RPC read fails.
311
323
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -339,7 +351,6 @@ export class MorphoMidnight {
339
351
  * offers plus the fallback.
340
352
  * @throws {MidnightContractReceiverError} when `referralFeeRecipient` is a Midnight protocol
341
353
  * contract or a market token contract with a positive referral fee.
342
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
343
354
  * @example
344
355
  * ```ts
345
356
  * const output = midnight.takeLend({
@@ -354,6 +365,8 @@ export class MorphoMidnight {
354
365
  */
355
366
  takeLend(params) {
356
367
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
368
+ // Reject the zero account before preparing anything for it.
369
+ validateMidnightAccount("accountAddress", params.accountAddress);
357
370
  validateTakeDeadlineWindow(params.deadline);
358
371
  const market = params.marketData.params;
359
372
  const rawParams = {
@@ -388,7 +401,7 @@ export class MorphoMidnight {
388
401
  ? params.target.assets
389
402
  : params.target.maxBuyerAssets;
390
403
  return {
391
- getRequirements: async (requirementsParams) => {
404
+ getRequirements: async (_requirementsParams) => {
392
405
  const approvals = await getMidnightApprovalRequirements({
393
406
  viemClient: this.client.viemClient,
394
407
  chainId: this.chainId,
@@ -396,7 +409,6 @@ export class MorphoMidnight {
396
409
  owner: params.accountAddress,
397
410
  spender: tx.to,
398
411
  amount: pulledAssets,
399
- approvalAmount: requirementsParams?.approvalAmount,
400
412
  });
401
413
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
402
414
  return [...approvals, ...authorization];
@@ -431,11 +443,14 @@ export class MorphoMidnight {
431
443
  * Midnight protocol and market token contracts are rejected.
432
444
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
433
445
  * @param params.deadline - Bounded bundle execution deadline timestamp.
434
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
446
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
447
+ * proceeds; on an assets target it is added on top of `target.assets`.
435
448
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
436
449
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
437
450
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
438
451
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
452
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
453
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
439
454
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
440
455
  * RPC read fails.
441
456
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -497,6 +512,8 @@ export class MorphoMidnight {
497
512
  */
498
513
  takeBorrow(params) {
499
514
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
515
+ // Reject the zero account before preparing anything for it.
516
+ validateMidnightAccount("accountAddress", params.accountAddress);
500
517
  validateTakeDeadlineWindow(params.deadline);
501
518
  const rawParams = {
502
519
  chainId: this.chainId,
@@ -571,11 +588,14 @@ export class MorphoMidnight {
571
588
  * Midnight protocol and market token contracts are rejected.
572
589
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
573
590
  * @param params.deadline - Bundle execution deadline timestamp.
574
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
591
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
592
+ * proceeds; on an assets target it is added on top of `target.assets`.
575
593
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
576
594
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
577
595
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
578
596
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
597
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
598
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
579
599
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
580
600
  * RPC read fails.
581
601
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
@@ -619,6 +639,8 @@ export class MorphoMidnight {
619
639
  */
620
640
  takeWithdraw(params) {
621
641
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
642
+ // Reject the zero account before preparing anything for it.
643
+ validateMidnightAccount("accountAddress", params.accountAddress);
622
644
  validateTakeDeadlineWindow(params.deadline);
623
645
  const rawParams = {
624
646
  chainId: this.chainId,
@@ -686,11 +708,14 @@ export class MorphoMidnight {
686
708
  * Midnight protocol and market token contracts are rejected.
687
709
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
688
710
  * @param params.deadline - Bounded bundle execution deadline timestamp.
689
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
711
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
712
+ * proceeds; on an assets target it is added on top of `target.assets`.
690
713
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
691
714
  * @returns Lazy collateral approvals and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
692
715
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
693
716
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
717
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
718
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
694
719
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
695
720
  * RPC read fails.
696
721
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -731,7 +756,6 @@ export class MorphoMidnight {
731
756
  * withdrawal.
732
757
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
733
758
  * its bounds cannot hold at any fill.
734
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
735
759
  * @example
736
760
  * ```ts
737
761
  * const output = midnight.supplyCollateralTakeBorrow({
@@ -748,6 +772,8 @@ export class MorphoMidnight {
748
772
  */
749
773
  supplyCollateralTakeBorrow(params) {
750
774
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
775
+ // Reject the zero account before preparing anything for it.
776
+ validateMidnightAccount("accountAddress", params.accountAddress);
751
777
  validateTakeDeadlineWindow(params.deadline);
752
778
  const market = params.marketData.params;
753
779
  const rawParams = {
@@ -816,7 +842,7 @@ export class MorphoMidnight {
816
842
  collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
817
843
  }
818
844
  return {
819
- getRequirements: async (requirementsParams) => {
845
+ getRequirements: async (_requirementsParams) => {
820
846
  const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => getMidnightApprovalRequirements({
821
847
  viemClient: this.client.viemClient,
822
848
  chainId: this.chainId,
@@ -824,7 +850,6 @@ export class MorphoMidnight {
824
850
  owner: params.accountAddress,
825
851
  spender: tx.to,
826
852
  amount,
827
- approvalAmount: requirementsParams?.approvalAmount,
828
853
  })));
829
854
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
830
855
  return [...approvals.flat(), ...authorization];
@@ -876,6 +901,8 @@ export class MorphoMidnight {
876
901
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
877
902
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
878
903
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
904
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
905
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
879
906
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
880
907
  * RPC read fails.
881
908
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -920,7 +947,6 @@ export class MorphoMidnight {
920
947
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
921
948
  * contract or a market token contract, or when `referralFeeRecipient` is either with a
922
949
  * positive referral fee.
923
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
924
950
  * @example
925
951
  * ```ts
926
952
  * const output = midnight.takeRepayWithdrawCollateral({
@@ -939,6 +965,8 @@ export class MorphoMidnight {
939
965
  */
940
966
  takeRepayWithdrawCollateral(params) {
941
967
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
968
+ // Reject the zero account before preparing anything for it.
969
+ validateMidnightAccount("accountAddress", params.accountAddress);
942
970
  validateTakeDeadlineWindow(params.deadline);
943
971
  const market = params.marketData.params;
944
972
  const rawParams = {
@@ -1025,7 +1053,7 @@ export class MorphoMidnight {
1025
1053
  ? params.target.assets
1026
1054
  : params.target.maxBuyerAssets;
1027
1055
  return {
1028
- getRequirements: async (requirementsParams) => {
1056
+ getRequirements: async (_requirementsParams) => {
1029
1057
  const approvals = await getMidnightApprovalRequirements({
1030
1058
  viemClient: this.client.viemClient,
1031
1059
  chainId: this.chainId,
@@ -1033,7 +1061,6 @@ export class MorphoMidnight {
1033
1061
  owner: params.accountAddress,
1034
1062
  spender: tx.to,
1035
1063
  amount: pulledAssets,
1036
- approvalAmount: requirementsParams?.approvalAmount,
1037
1064
  });
1038
1065
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
1039
1066
  return [...approvals, ...authorization];
@@ -1045,23 +1072,30 @@ export class MorphoMidnight {
1045
1072
  * Prepares a direct collateral supply using a caller-provided market snapshot.
1046
1073
  *
1047
1074
  * @param params - Supplier, market snapshot, collateral amount, reserve, and optional collateral index.
1048
- * @param params.accountAddress - Account receiving the supplied collateral position.
1075
+ * @param params.accountAddress - Account receiving the supplied collateral position. It must send
1076
+ * the transaction: Midnight pulls the collateral from `msg.sender` and only lets the position owner
1077
+ * or its operators supply for it, and the approval requirements are resolved for this account.
1049
1078
  * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
1050
1079
  * @param params.collateralAssets - Collateral assets supplied in this transaction.
1051
1080
  * @param params.reservedCollateralAssets - Existing collateral reserved by other open maker groups.
1052
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
1081
+ * Only raises the approval requirement so those groups keep their allowance; the transaction
1082
+ * transfers only `collateralAssets`.
1083
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`. Indexes follow the
1084
+ * market's collateral parameters, which Midnight sorts by token address, not the order they were
1085
+ * listed in when the market was built; check `marketData.getCollateralByIndex(index).token`.
1053
1086
  * @returns Lazy token-approval requirements and a synchronous transaction builder.
1054
1087
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1055
1088
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
1089
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1056
1090
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1057
1091
  * RPC read fails.
1058
1092
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
1059
1093
  * @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
1060
1094
  * @throws {InputExceedsMaxError} when `collateralAssets` exceeds `uint128`.
1061
1095
  * @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
1062
- * @throws {MidnightZeroOnBehalfError} from `buildTx()` when `accountAddress` is the zero address.
1096
+ * @throws {MidnightZeroOnBehalfError} from `getRequirements()` and `buildTx()` when `accountAddress`
1097
+ * is the zero address.
1063
1098
  * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
1064
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled collateral assets.
1065
1099
  * @example
1066
1100
  * ```ts
1067
1101
  * const output = midnight.supplyCollateral({
@@ -1073,6 +1107,8 @@ export class MorphoMidnight {
1073
1107
  */
1074
1108
  supplyCollateral(params) {
1075
1109
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1110
+ // Reject a malformed account here; the builder rejects the zero account.
1111
+ validateMidnightAddress("accountAddress", params.accountAddress);
1076
1112
  validateMarketData(params.marketData, this.chainId);
1077
1113
  assertPositiveAmount("collateralAssets", params.collateralAssets);
1078
1114
  validateMidnightUint128Field("collateralAssets", params.collateralAssets);
@@ -1082,15 +1118,20 @@ export class MorphoMidnight {
1082
1118
  const collateral = market.getCollateralByIndex(collateralIndex);
1083
1119
  const midnight = getChainAddress(this.chainId, "midnight");
1084
1120
  return {
1085
- getRequirements: async (requirementsParams) => await getMidnightApprovalRequirements({
1086
- viemClient: this.client.viemClient,
1087
- chainId: this.chainId,
1088
- token: collateral.token,
1089
- owner: params.accountAddress,
1090
- spender: midnight,
1091
- amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1092
- approvalAmount: requirementsParams?.approvalAmount,
1093
- }),
1121
+ getRequirements: async (_requirementsParams) => {
1122
+ // Match buildTx(): the requirement helper would report a zero owner with another class.
1123
+ if (isAddressEqual(params.accountAddress, zeroAddress)) {
1124
+ throw new MidnightZeroOnBehalfError("onBehalf");
1125
+ }
1126
+ return await getMidnightApprovalRequirements({
1127
+ viemClient: this.client.viemClient,
1128
+ chainId: this.chainId,
1129
+ token: collateral.token,
1130
+ owner: params.accountAddress,
1131
+ spender: midnight,
1132
+ amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1133
+ });
1134
+ },
1094
1135
  buildTx: () => midnightSupplyCollateral({
1095
1136
  chainId: this.chainId,
1096
1137
  market: market.params,
@@ -1121,9 +1162,12 @@ export class MorphoMidnight {
1121
1162
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
1122
1163
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1123
1164
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1165
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1166
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1124
1167
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1125
1168
  * RPC read fails.
1126
1169
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1170
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1127
1171
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1128
1172
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1129
1173
  * @throws {NonPositiveInputError} when `loanAssets` is non-positive.
@@ -1154,7 +1198,6 @@ export class MorphoMidnight {
1154
1198
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1155
1199
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1156
1200
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1157
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1158
1201
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1159
1202
  * @example
1160
1203
  * ```ts
@@ -1170,9 +1213,11 @@ export class MorphoMidnight {
1170
1213
  */
1171
1214
  async makeLend(params) {
1172
1215
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1216
+ // Reject the zero account before preparing anything for it.
1217
+ validateMidnightAccount("accountAddress", params.accountAddress);
1173
1218
  // Fails before any API read or build when the deadline has already passed.
1174
1219
  validateMidnightDeadline(params.deadline);
1175
- const tree = Tree.from(params.offers);
1220
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1176
1221
  rejectReduceOnlyOffers(tree.offers);
1177
1222
  return this.prepareLendOffers({ ...params, offers: tree });
1178
1223
  }
@@ -1192,9 +1237,12 @@ export class MorphoMidnight {
1192
1237
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1193
1238
  * @returns Prepared group metadata, lazy authorization requirements, and a synchronous transaction builder.
1194
1239
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1240
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1241
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1195
1242
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1196
1243
  * RPC read fails.
1197
1244
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1245
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1198
1246
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1199
1247
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1200
1248
  * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
@@ -1236,9 +1284,11 @@ export class MorphoMidnight {
1236
1284
  */
1237
1285
  async makeBorrow(params) {
1238
1286
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1287
+ // Reject the zero account before preparing anything for it.
1288
+ validateMidnightAccount("accountAddress", params.accountAddress);
1239
1289
  // Fails before any API read or build when the deadline has already passed.
1240
1290
  validateMidnightDeadline(params.deadline);
1241
- const tree = Tree.from(params.offers);
1291
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1242
1292
  rejectReduceOnlyOffers(tree.offers);
1243
1293
  return this.prepareBorrowOffers({ ...params, offers: tree });
1244
1294
  }
@@ -1246,9 +1296,11 @@ export class MorphoMidnight {
1246
1296
  * Prepares lend-side offers for publication.
1247
1297
  */
1248
1298
  async prepareLendOffers(params) {
1299
+ // Reject a malformed address before viem compares offer markets with it.
1300
+ validateMidnightAddress("loanToken", params.loanToken);
1249
1301
  assertPositiveAmount("loanAssets", params.loanAssets);
1250
1302
  assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
1251
- const tree = Tree.from(params.offers);
1303
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1252
1304
  validateOfferSides(tree.offers, true);
1253
1305
  validateMidnightMakerOfferCallbacks(tree.offers);
1254
1306
  const data = await getOffersDataInternal({
@@ -1283,7 +1335,7 @@ export class MorphoMidnight {
1283
1335
  groups: data.groups,
1284
1336
  root: data.tree.root,
1285
1337
  ratifierType: data.ratifierType,
1286
- getRequirements: async (requirementsParams) => {
1338
+ getRequirements: async (_requirementsParams) => {
1287
1339
  const approvals = await getMidnightApprovalRequirements({
1288
1340
  viemClient: this.client.viemClient,
1289
1341
  chainId: this.chainId,
@@ -1291,7 +1343,6 @@ export class MorphoMidnight {
1291
1343
  owner: data.accountAddress,
1292
1344
  spender: midnight,
1293
1345
  amount: params.loanAssets + (params.reservedLoanAssets ?? 0n),
1294
- approvalAmount: requirementsParams?.approvalAmount,
1295
1346
  });
1296
1347
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1297
1348
  return [...approvals, ...authorization];
@@ -1338,6 +1389,8 @@ export class MorphoMidnight {
1338
1389
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1339
1390
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
1340
1391
  * another chain than `this.chainId`.
1392
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1393
+ * @throws {MidnightCalldataEncodingError} when the offer tree or `blueMarket` cannot be ABI-encoded.
1341
1394
  * @throws {viem.BaseError} when the `eth_chainId` request, a Blue market RPC read, or a
1342
1395
  * requirement RPC read fails.
1343
1396
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2`, `midnightBlueBuyCallbackFactory`, `midnight`, `blue` or V1 ratifier deployment.
@@ -1349,6 +1402,7 @@ export class MorphoMidnight {
1349
1402
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1350
1403
  * @throws {NativeAmountOnNonWNativeAssetError} when `blueMarket.loanToken` is not wNative.
1351
1404
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1405
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1352
1406
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1353
1407
  * (not thrown when `validation` is `false`).
1354
1408
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1378,7 +1432,6 @@ export class MorphoMidnight {
1378
1432
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1379
1433
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
1380
1434
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1381
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `assetsToPark`.
1382
1435
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1383
1436
  * @example
1384
1437
  * ```ts
@@ -1398,15 +1451,21 @@ export class MorphoMidnight {
1398
1451
  * ```
1399
1452
  */
1400
1453
  async supplyBlueMakeLend(params) {
1454
+ // Reject the zero account before preparing anything for it.
1455
+ validateMidnightAccount("accountAddress", params.accountAddress);
1456
+ // Reject wrong-sized salts before callback derivation pads them or any read occurs.
1457
+ validateMidnightBytes32("callbackSalt", params.callbackSalt);
1401
1458
  assertPositiveAmount("assetsToPark", params.assetsToPark);
1402
1459
  validateMidnightUint128Field("assetsToPark", params.assetsToPark);
1403
- const tree = Tree.from(params.offers);
1460
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1404
1461
  validateOfferSides(tree.offers, true);
1405
1462
  rejectReduceOnlyOffers(tree.offers);
1406
1463
  await validateClientChainId(this.client.viemClient, this.chainId);
1407
1464
  // Fails before any API read or build when the deadline has already passed.
1408
1465
  validateMidnightDeadline(params.deadline);
1409
1466
  const { callbackSalt } = params;
1467
+ // Encode the whole Blue market first so a malformed field fails typed, before the RPC read.
1468
+ const callbackData = wrapMidnightEncoding("blueMarket", () => getMidnightBlueBuyCallbackData(params.blueMarket));
1410
1469
  const blueMarketId = BlueMarketUtils.getMarketId(params.blueMarket);
1411
1470
  const callback = getMidnightBlueBuyCallbackAddress({
1412
1471
  chainId: this.chainId,
@@ -1433,7 +1492,6 @@ export class MorphoMidnight {
1433
1492
  assets: params.assetsToPark,
1434
1493
  });
1435
1494
  }
1436
- const callbackData = getMidnightBlueBuyCallbackData(params.blueMarket);
1437
1495
  data.tree.offers.forEach((offer, index) => {
1438
1496
  const offerMarket = offerMarketParams(offer);
1439
1497
  if (!isAddressEqual(offerMarket.loanToken, params.blueMarket.loanToken)) {
@@ -1480,7 +1538,7 @@ export class MorphoMidnight {
1480
1538
  groups: data.groups,
1481
1539
  root: data.tree.root,
1482
1540
  ratifierType: data.ratifierType,
1483
- getRequirements: async (requirementsParams) => {
1541
+ getRequirements: async (_requirementsParams) => {
1484
1542
  const approvals = await getMidnightApprovalRequirements({
1485
1543
  viemClient: this.client.viemClient,
1486
1544
  chainId: this.chainId,
@@ -1488,7 +1546,6 @@ export class MorphoMidnight {
1488
1546
  owner: data.accountAddress,
1489
1547
  spender: getChainAddress(this.chainId, "midnightBundlesV2"),
1490
1548
  amount: params.assetsToPark,
1491
- approvalAmount: requirementsParams?.approvalAmount,
1492
1549
  });
1493
1550
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1494
1551
  return [...approvals, ...authorization];
@@ -1500,7 +1557,7 @@ export class MorphoMidnight {
1500
1557
  * Prepares borrow-side offers for publication.
1501
1558
  */
1502
1559
  async prepareBorrowOffers(params) {
1503
- const tree = Tree.from(params.offers);
1560
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1504
1561
  validateOfferSides(tree.offers, false);
1505
1562
  validateMidnightMakerOfferCallbacks(tree.offers);
1506
1563
  const data = await getOffersDataInternal({
@@ -1546,9 +1603,12 @@ export class MorphoMidnight {
1546
1603
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1547
1604
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1548
1605
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1606
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1607
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1549
1608
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1550
1609
  * RPC read fails.
1551
1610
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1611
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1552
1612
  * @throws {MidnightOfferSideMismatchError} when an offer is not a sell offer (`buy = false`).
1553
1613
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1554
1614
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1593,9 +1653,11 @@ export class MorphoMidnight {
1593
1653
  */
1594
1654
  async makeWithdraw(params) {
1595
1655
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1656
+ // Reject the zero account before preparing anything for it.
1657
+ validateMidnightAccount("accountAddress", params.accountAddress);
1596
1658
  // Fails before any API read or build when the deadline has already passed.
1597
1659
  validateMidnightDeadline(params.deadline);
1598
- const tree = Tree.from(params.offers);
1660
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1599
1661
  // Reject the wrong exit intent before calling the mempool validation API.
1600
1662
  validateOfferSides(tree.offers, false);
1601
1663
  for (const [index, offer] of tree.offers.entries()) {
@@ -1628,9 +1690,12 @@ export class MorphoMidnight {
1628
1690
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
1629
1691
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1630
1692
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1693
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1694
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1631
1695
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1632
1696
  * RPC read fails.
1633
1697
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1698
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1634
1699
  * @throws {MidnightOfferSideMismatchError} when an offer is not a buy offer (`buy = true`).
1635
1700
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1636
1701
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1662,7 +1727,6 @@ export class MorphoMidnight {
1662
1727
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1663
1728
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1664
1729
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1665
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1666
1730
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1667
1731
  * @example
1668
1732
  * ```ts
@@ -1679,9 +1743,11 @@ export class MorphoMidnight {
1679
1743
  */
1680
1744
  async makeRepay(params) {
1681
1745
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1746
+ // Reject the zero account before preparing anything for it.
1747
+ validateMidnightAccount("accountAddress", params.accountAddress);
1682
1748
  // Fails before any API read or build when the deadline has already passed.
1683
1749
  validateMidnightDeadline(params.deadline);
1684
- const tree = Tree.from(params.offers);
1750
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1685
1751
  // Reject the wrong exit intent before calling the mempool validation API.
1686
1752
  validateOfferSides(tree.offers, true);
1687
1753
  for (const [index, offer] of tree.offers.entries()) {
@@ -1715,6 +1781,8 @@ export class MorphoMidnight {
1715
1781
  * required for the full pulled amount.
1716
1782
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1717
1783
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1784
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1785
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1718
1786
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1719
1787
  * RPC read fails.
1720
1788
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
@@ -1727,6 +1795,7 @@ export class MorphoMidnight {
1727
1795
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1728
1796
  * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
1729
1797
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1798
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1730
1799
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1731
1800
  * (not thrown when `validation` is `false`).
1732
1801
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1755,7 +1824,6 @@ export class MorphoMidnight {
1755
1824
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1756
1825
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1757
1826
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1758
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
1759
1827
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1760
1828
  * @example
1761
1829
  * ```ts
@@ -1772,12 +1840,14 @@ export class MorphoMidnight {
1772
1840
  */
1773
1841
  async supplyCollateralMakeBorrow(params) {
1774
1842
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1843
+ // Reject the zero account before preparing anything for it.
1844
+ validateMidnightAccount("accountAddress", params.accountAddress);
1775
1845
  // Fails before any API read or build when the deadline has already passed.
1776
1846
  validateMidnightDeadline(params.deadline);
1777
1847
  const market = params.collateral.market instanceof MarketParams
1778
1848
  ? params.collateral.market
1779
1849
  : MarketParams.from(params.collateral.market);
1780
- const tree = Tree.from(params.offers);
1850
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1781
1851
  validateOfferSides(tree.offers, false);
1782
1852
  validateMidnightMakerOfferCallbacks(tree.offers);
1783
1853
  rejectReduceOnlyOffers(tree.offers);
@@ -1787,9 +1857,9 @@ export class MorphoMidnight {
1787
1857
  params: { ...params, offers: tree },
1788
1858
  marketCreationTime: "now",
1789
1859
  });
1790
- const marketId = MarketUtils.toId(market);
1860
+ const marketId = encodeMidnightMarketId(market);
1791
1861
  for (const offer of data.tree.offers) {
1792
- const offerMarketId = MarketUtils.toId(offer.market);
1862
+ const offerMarketId = encodeMidnightMarketId(offer.market);
1793
1863
  if (offerMarketId.toLowerCase() !== marketId.toLowerCase()) {
1794
1864
  throw new MarketIdMismatchError(offerMarketId, marketId);
1795
1865
  }
@@ -1822,7 +1892,7 @@ export class MorphoMidnight {
1822
1892
  groups: data.groups,
1823
1893
  root: data.tree.root,
1824
1894
  ratifierType: data.ratifierType,
1825
- getRequirements: async (requirementsParams) => {
1895
+ getRequirements: async (_requirementsParams) => {
1826
1896
  const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => getMidnightApprovalRequirements({
1827
1897
  viemClient: this.client.viemClient,
1828
1898
  chainId: this.chainId,
@@ -1830,7 +1900,6 @@ export class MorphoMidnight {
1830
1900
  owner: data.accountAddress,
1831
1901
  spender: midnightBundlesV2,
1832
1902
  amount,
1833
- approvalAmount: requirementsParams?.approvalAmount,
1834
1903
  })));
1835
1904
  return [
1836
1905
  ...approvals.flat(),
@@ -1844,7 +1913,9 @@ export class MorphoMidnight {
1844
1913
  * Prepares redemption of accrued Midnight credit from a position snapshot.
1845
1914
  *
1846
1915
  * @param params - Position owner, accrued position, optional unit amount, and receiver.
1847
- * @param params.accountAddress - Position owner whose credit is redeemed.
1916
+ * @param params.accountAddress - Position owner whose credit is redeemed. It must send the
1917
+ * transaction (or authorize the sender): Midnight reverts `Unauthorized()` otherwise, which
1918
+ * `getRequirements()` cannot detect because it does not know the sender.
1848
1919
  * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`.
1849
1920
  * @param params.receiver - Optional credit receiver; defaults to the position owner.
1850
1921
  * Midnight protocol and market token contracts are rejected.
@@ -1857,6 +1928,7 @@ export class MorphoMidnight {
1857
1928
  * is left. Redeem again after maturity to empty the position.
1858
1929
  * @returns No requirements and a synchronous redemption transaction builder.
1859
1930
  * @throws {ChainIdMismatchError} when the position market targets another chain.
1931
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1860
1932
  * @throws {MidnightMarketAddressMismatchError} when the position market targets another Midnight deployment.
1861
1933
  * @throws {MissingAccrualPositionError} when no position snapshot is supplied.
1862
1934
  * @throws {AccrualPositionUserMismatchError} when the position snapshot belongs to another account.
@@ -1884,9 +1956,13 @@ export class MorphoMidnight {
1884
1956
  */
1885
1957
  redeem(params) {
1886
1958
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1959
+ // Reject a malformed account here; the builder rejects the zero account.
1960
+ validateMidnightAddress("accountAddress", params.accountAddress);
1887
1961
  if (!params.positionData) {
1888
1962
  throw new MissingAccrualPositionError();
1889
1963
  }
1964
+ if (params.positionData.user != null)
1965
+ validateMidnightAddress("positionData.user", params.positionData.user);
1890
1966
  if (params.positionData.user == null ||
1891
1967
  !isAddressEqual(params.positionData.user, params.accountAddress)) {
1892
1968
  throw new AccrualPositionUserMismatchError(params.positionData.user ?? "unbound", params.accountAddress);
@@ -1947,7 +2023,7 @@ export class MorphoMidnight {
1947
2023
  * scaled by `ORACLE_PRICE_SCALE`. An empty array is safe only when
1948
2024
  * `collateralWithdrawals` is empty or the conservative post-operation debt is zero: a `full`
1949
2025
  * repay, or `repay.assets` covering `positionData.debt`.
1950
- * @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.
2026
+ * @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.
1951
2027
  * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
1952
2028
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
1953
2029
  * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
@@ -1963,6 +2039,8 @@ export class MorphoMidnight {
1963
2039
  * @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
1964
2040
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1965
2041
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
2042
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
2043
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1966
2044
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1967
2045
  * RPC read fails.
1968
2046
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
@@ -1987,7 +2065,6 @@ export class MorphoMidnight {
1987
2065
  * during this method call, before the lazy output is returned.
1988
2066
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
1989
2067
  * contract or a market token contract.
1990
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
1991
2068
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1992
2069
  * @example
1993
2070
  * ```ts
@@ -2005,6 +2082,8 @@ export class MorphoMidnight {
2005
2082
  */
2006
2083
  repayWithdrawCollateral(params) {
2007
2084
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
2085
+ // Reject the zero account before preparing anything for it.
2086
+ validateMidnightAccount("accountAddress", params.accountAddress);
2008
2087
  // Fails before any API read or build when the deadline has already passed.
2009
2088
  validateMidnightDeadline(params.deadline);
2010
2089
  const market = params.marketData.params;
@@ -2082,7 +2161,7 @@ export class MorphoMidnight {
2082
2161
  ? params.repay.assets
2083
2162
  : params.repay.maxBuyerAssets;
2084
2163
  return {
2085
- getRequirements: async (requirementsParams) => {
2164
+ getRequirements: async (_requirementsParams) => {
2086
2165
  const approvals = pulledAssets > 0n
2087
2166
  ? await getMidnightApprovalRequirements({
2088
2167
  viemClient: this.client.viemClient,
@@ -2091,7 +2170,6 @@ export class MorphoMidnight {
2091
2170
  owner: params.accountAddress,
2092
2171
  spender: tx.to,
2093
2172
  amount: pulledAssets,
2094
- approvalAmount: requirementsParams?.approvalAmount,
2095
2173
  })
2096
2174
  : [];
2097
2175
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
@@ -2121,6 +2199,7 @@ export class MorphoMidnight {
2121
2199
  * @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
2122
2200
  * @throws {ChainIdMismatchError} when the client targets another chain, or from
2123
2201
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
2202
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as an out-of-range integer.
2124
2203
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
2125
2204
  * RPC read fails.
2126
2205
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.