@morpho-org/morpho-sdk 8.2.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 +14 -8
  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 +4 -1
  12. package/lib/cjs/actions/midnight/redeem.js +13 -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 +5 -1
  16. package/lib/cjs/actions/midnight/supplyCollateral.js +14 -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 +58 -17
  48. package/lib/cjs/entities/midnight/midnight.js +133 -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 +64 -5
  78. package/lib/cjs/types/error.js +152 -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 +4 -1
  88. package/lib/esm/actions/midnight/redeem.js +15 -5
  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 +5 -1
  92. package/lib/esm/actions/midnight/supplyCollateral.js +16 -5
  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 +58 -17
  124. package/lib/esm/entities/midnight/midnight.js +134 -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 +64 -5
  154. package/lib/esm/types/error.js +146 -6
  155. package/package.json +6 -5
@@ -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,22 +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.
1096
+ * @throws {MidnightZeroOnBehalfError} from `getRequirements()` and `buildTx()` when `accountAddress`
1097
+ * is the zero address.
1062
1098
  * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
1063
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled collateral assets.
1064
1099
  * @example
1065
1100
  * ```ts
1066
1101
  * const output = midnight.supplyCollateral({
@@ -1072,6 +1107,8 @@ export class MorphoMidnight {
1072
1107
  */
1073
1108
  supplyCollateral(params) {
1074
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);
1075
1112
  validateMarketData(params.marketData, this.chainId);
1076
1113
  assertPositiveAmount("collateralAssets", params.collateralAssets);
1077
1114
  validateMidnightUint128Field("collateralAssets", params.collateralAssets);
@@ -1081,15 +1118,20 @@ export class MorphoMidnight {
1081
1118
  const collateral = market.getCollateralByIndex(collateralIndex);
1082
1119
  const midnight = getChainAddress(this.chainId, "midnight");
1083
1120
  return {
1084
- getRequirements: async (requirementsParams) => await getMidnightApprovalRequirements({
1085
- viemClient: this.client.viemClient,
1086
- chainId: this.chainId,
1087
- token: collateral.token,
1088
- owner: params.accountAddress,
1089
- spender: midnight,
1090
- amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1091
- approvalAmount: requirementsParams?.approvalAmount,
1092
- }),
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
+ },
1093
1135
  buildTx: () => midnightSupplyCollateral({
1094
1136
  chainId: this.chainId,
1095
1137
  market: market.params,
@@ -1120,9 +1162,12 @@ export class MorphoMidnight {
1120
1162
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
1121
1163
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1122
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.
1123
1167
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1124
1168
  * RPC read fails.
1125
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.
1126
1171
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1127
1172
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1128
1173
  * @throws {NonPositiveInputError} when `loanAssets` is non-positive.
@@ -1153,7 +1198,6 @@ export class MorphoMidnight {
1153
1198
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1154
1199
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1155
1200
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1156
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1157
1201
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1158
1202
  * @example
1159
1203
  * ```ts
@@ -1169,9 +1213,11 @@ export class MorphoMidnight {
1169
1213
  */
1170
1214
  async makeLend(params) {
1171
1215
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1216
+ // Reject the zero account before preparing anything for it.
1217
+ validateMidnightAccount("accountAddress", params.accountAddress);
1172
1218
  // Fails before any API read or build when the deadline has already passed.
1173
1219
  validateMidnightDeadline(params.deadline);
1174
- const tree = Tree.from(params.offers);
1220
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1175
1221
  rejectReduceOnlyOffers(tree.offers);
1176
1222
  return this.prepareLendOffers({ ...params, offers: tree });
1177
1223
  }
@@ -1191,9 +1237,12 @@ export class MorphoMidnight {
1191
1237
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1192
1238
  * @returns Prepared group metadata, lazy authorization requirements, and a synchronous transaction builder.
1193
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.
1194
1242
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1195
1243
  * RPC read fails.
1196
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.
1197
1246
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1198
1247
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1199
1248
  * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
@@ -1235,9 +1284,11 @@ export class MorphoMidnight {
1235
1284
  */
1236
1285
  async makeBorrow(params) {
1237
1286
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1287
+ // Reject the zero account before preparing anything for it.
1288
+ validateMidnightAccount("accountAddress", params.accountAddress);
1238
1289
  // Fails before any API read or build when the deadline has already passed.
1239
1290
  validateMidnightDeadline(params.deadline);
1240
- const tree = Tree.from(params.offers);
1291
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1241
1292
  rejectReduceOnlyOffers(tree.offers);
1242
1293
  return this.prepareBorrowOffers({ ...params, offers: tree });
1243
1294
  }
@@ -1245,9 +1296,11 @@ export class MorphoMidnight {
1245
1296
  * Prepares lend-side offers for publication.
1246
1297
  */
1247
1298
  async prepareLendOffers(params) {
1299
+ // Reject a malformed address before viem compares offer markets with it.
1300
+ validateMidnightAddress("loanToken", params.loanToken);
1248
1301
  assertPositiveAmount("loanAssets", params.loanAssets);
1249
1302
  assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
1250
- const tree = Tree.from(params.offers);
1303
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1251
1304
  validateOfferSides(tree.offers, true);
1252
1305
  validateMidnightMakerOfferCallbacks(tree.offers);
1253
1306
  const data = await getOffersDataInternal({
@@ -1282,7 +1335,7 @@ export class MorphoMidnight {
1282
1335
  groups: data.groups,
1283
1336
  root: data.tree.root,
1284
1337
  ratifierType: data.ratifierType,
1285
- getRequirements: async (requirementsParams) => {
1338
+ getRequirements: async (_requirementsParams) => {
1286
1339
  const approvals = await getMidnightApprovalRequirements({
1287
1340
  viemClient: this.client.viemClient,
1288
1341
  chainId: this.chainId,
@@ -1290,7 +1343,6 @@ export class MorphoMidnight {
1290
1343
  owner: data.accountAddress,
1291
1344
  spender: midnight,
1292
1345
  amount: params.loanAssets + (params.reservedLoanAssets ?? 0n),
1293
- approvalAmount: requirementsParams?.approvalAmount,
1294
1346
  });
1295
1347
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1296
1348
  return [...approvals, ...authorization];
@@ -1337,6 +1389,8 @@ export class MorphoMidnight {
1337
1389
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1338
1390
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
1339
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.
1340
1394
  * @throws {viem.BaseError} when the `eth_chainId` request, a Blue market RPC read, or a
1341
1395
  * requirement RPC read fails.
1342
1396
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2`, `midnightBlueBuyCallbackFactory`, `midnight`, `blue` or V1 ratifier deployment.
@@ -1348,6 +1402,7 @@ export class MorphoMidnight {
1348
1402
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1349
1403
  * @throws {NativeAmountOnNonWNativeAssetError} when `blueMarket.loanToken` is not wNative.
1350
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.
1351
1406
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1352
1407
  * (not thrown when `validation` is `false`).
1353
1408
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1377,7 +1432,6 @@ export class MorphoMidnight {
1377
1432
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1378
1433
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
1379
1434
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1380
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `assetsToPark`.
1381
1435
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1382
1436
  * @example
1383
1437
  * ```ts
@@ -1397,15 +1451,21 @@ export class MorphoMidnight {
1397
1451
  * ```
1398
1452
  */
1399
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);
1400
1458
  assertPositiveAmount("assetsToPark", params.assetsToPark);
1401
1459
  validateMidnightUint128Field("assetsToPark", params.assetsToPark);
1402
- const tree = Tree.from(params.offers);
1460
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1403
1461
  validateOfferSides(tree.offers, true);
1404
1462
  rejectReduceOnlyOffers(tree.offers);
1405
1463
  await validateClientChainId(this.client.viemClient, this.chainId);
1406
1464
  // Fails before any API read or build when the deadline has already passed.
1407
1465
  validateMidnightDeadline(params.deadline);
1408
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));
1409
1469
  const blueMarketId = BlueMarketUtils.getMarketId(params.blueMarket);
1410
1470
  const callback = getMidnightBlueBuyCallbackAddress({
1411
1471
  chainId: this.chainId,
@@ -1432,7 +1492,6 @@ export class MorphoMidnight {
1432
1492
  assets: params.assetsToPark,
1433
1493
  });
1434
1494
  }
1435
- const callbackData = getMidnightBlueBuyCallbackData(params.blueMarket);
1436
1495
  data.tree.offers.forEach((offer, index) => {
1437
1496
  const offerMarket = offerMarketParams(offer);
1438
1497
  if (!isAddressEqual(offerMarket.loanToken, params.blueMarket.loanToken)) {
@@ -1479,7 +1538,7 @@ export class MorphoMidnight {
1479
1538
  groups: data.groups,
1480
1539
  root: data.tree.root,
1481
1540
  ratifierType: data.ratifierType,
1482
- getRequirements: async (requirementsParams) => {
1541
+ getRequirements: async (_requirementsParams) => {
1483
1542
  const approvals = await getMidnightApprovalRequirements({
1484
1543
  viemClient: this.client.viemClient,
1485
1544
  chainId: this.chainId,
@@ -1487,7 +1546,6 @@ export class MorphoMidnight {
1487
1546
  owner: data.accountAddress,
1488
1547
  spender: getChainAddress(this.chainId, "midnightBundlesV2"),
1489
1548
  amount: params.assetsToPark,
1490
- approvalAmount: requirementsParams?.approvalAmount,
1491
1549
  });
1492
1550
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1493
1551
  return [...approvals, ...authorization];
@@ -1499,7 +1557,7 @@ export class MorphoMidnight {
1499
1557
  * Prepares borrow-side offers for publication.
1500
1558
  */
1501
1559
  async prepareBorrowOffers(params) {
1502
- const tree = Tree.from(params.offers);
1560
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1503
1561
  validateOfferSides(tree.offers, false);
1504
1562
  validateMidnightMakerOfferCallbacks(tree.offers);
1505
1563
  const data = await getOffersDataInternal({
@@ -1545,9 +1603,12 @@ export class MorphoMidnight {
1545
1603
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1546
1604
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1547
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.
1548
1608
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1549
1609
  * RPC read fails.
1550
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.
1551
1612
  * @throws {MidnightOfferSideMismatchError} when an offer is not a sell offer (`buy = false`).
1552
1613
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1553
1614
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1592,9 +1653,11 @@ export class MorphoMidnight {
1592
1653
  */
1593
1654
  async makeWithdraw(params) {
1594
1655
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1656
+ // Reject the zero account before preparing anything for it.
1657
+ validateMidnightAccount("accountAddress", params.accountAddress);
1595
1658
  // Fails before any API read or build when the deadline has already passed.
1596
1659
  validateMidnightDeadline(params.deadline);
1597
- const tree = Tree.from(params.offers);
1660
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1598
1661
  // Reject the wrong exit intent before calling the mempool validation API.
1599
1662
  validateOfferSides(tree.offers, false);
1600
1663
  for (const [index, offer] of tree.offers.entries()) {
@@ -1627,9 +1690,12 @@ export class MorphoMidnight {
1627
1690
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
1628
1691
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1629
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.
1630
1695
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1631
1696
  * RPC read fails.
1632
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.
1633
1699
  * @throws {MidnightOfferSideMismatchError} when an offer is not a buy offer (`buy = true`).
1634
1700
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1635
1701
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1661,7 +1727,6 @@ export class MorphoMidnight {
1661
1727
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1662
1728
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1663
1729
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1664
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1665
1730
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1666
1731
  * @example
1667
1732
  * ```ts
@@ -1678,9 +1743,11 @@ export class MorphoMidnight {
1678
1743
  */
1679
1744
  async makeRepay(params) {
1680
1745
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1746
+ // Reject the zero account before preparing anything for it.
1747
+ validateMidnightAccount("accountAddress", params.accountAddress);
1681
1748
  // Fails before any API read or build when the deadline has already passed.
1682
1749
  validateMidnightDeadline(params.deadline);
1683
- const tree = Tree.from(params.offers);
1750
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1684
1751
  // Reject the wrong exit intent before calling the mempool validation API.
1685
1752
  validateOfferSides(tree.offers, true);
1686
1753
  for (const [index, offer] of tree.offers.entries()) {
@@ -1714,6 +1781,8 @@ export class MorphoMidnight {
1714
1781
  * required for the full pulled amount.
1715
1782
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1716
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.
1717
1786
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1718
1787
  * RPC read fails.
1719
1788
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
@@ -1726,6 +1795,7 @@ export class MorphoMidnight {
1726
1795
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1727
1796
  * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
1728
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.
1729
1799
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1730
1800
  * (not thrown when `validation` is `false`).
1731
1801
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1754,7 +1824,6 @@ export class MorphoMidnight {
1754
1824
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1755
1825
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1756
1826
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1757
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
1758
1827
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1759
1828
  * @example
1760
1829
  * ```ts
@@ -1771,12 +1840,14 @@ export class MorphoMidnight {
1771
1840
  */
1772
1841
  async supplyCollateralMakeBorrow(params) {
1773
1842
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1843
+ // Reject the zero account before preparing anything for it.
1844
+ validateMidnightAccount("accountAddress", params.accountAddress);
1774
1845
  // Fails before any API read or build when the deadline has already passed.
1775
1846
  validateMidnightDeadline(params.deadline);
1776
1847
  const market = params.collateral.market instanceof MarketParams
1777
1848
  ? params.collateral.market
1778
1849
  : MarketParams.from(params.collateral.market);
1779
- const tree = Tree.from(params.offers);
1850
+ const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1780
1851
  validateOfferSides(tree.offers, false);
1781
1852
  validateMidnightMakerOfferCallbacks(tree.offers);
1782
1853
  rejectReduceOnlyOffers(tree.offers);
@@ -1786,9 +1857,9 @@ export class MorphoMidnight {
1786
1857
  params: { ...params, offers: tree },
1787
1858
  marketCreationTime: "now",
1788
1859
  });
1789
- const marketId = MarketUtils.toId(market);
1860
+ const marketId = encodeMidnightMarketId(market);
1790
1861
  for (const offer of data.tree.offers) {
1791
- const offerMarketId = MarketUtils.toId(offer.market);
1862
+ const offerMarketId = encodeMidnightMarketId(offer.market);
1792
1863
  if (offerMarketId.toLowerCase() !== marketId.toLowerCase()) {
1793
1864
  throw new MarketIdMismatchError(offerMarketId, marketId);
1794
1865
  }
@@ -1821,7 +1892,7 @@ export class MorphoMidnight {
1821
1892
  groups: data.groups,
1822
1893
  root: data.tree.root,
1823
1894
  ratifierType: data.ratifierType,
1824
- getRequirements: async (requirementsParams) => {
1895
+ getRequirements: async (_requirementsParams) => {
1825
1896
  const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => getMidnightApprovalRequirements({
1826
1897
  viemClient: this.client.viemClient,
1827
1898
  chainId: this.chainId,
@@ -1829,7 +1900,6 @@ export class MorphoMidnight {
1829
1900
  owner: data.accountAddress,
1830
1901
  spender: midnightBundlesV2,
1831
1902
  amount,
1832
- approvalAmount: requirementsParams?.approvalAmount,
1833
1903
  })));
1834
1904
  return [
1835
1905
  ...approvals.flat(),
@@ -1843,7 +1913,9 @@ export class MorphoMidnight {
1843
1913
  * Prepares redemption of accrued Midnight credit from a position snapshot.
1844
1914
  *
1845
1915
  * @param params - Position owner, accrued position, optional unit amount, and receiver.
1846
- * @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.
1847
1919
  * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`.
1848
1920
  * @param params.receiver - Optional credit receiver; defaults to the position owner.
1849
1921
  * Midnight protocol and market token contracts are rejected.
@@ -1856,18 +1928,20 @@ export class MorphoMidnight {
1856
1928
  * is left. Redeem again after maturity to empty the position.
1857
1929
  * @returns No requirements and a synchronous redemption transaction builder.
1858
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.
1859
1932
  * @throws {MidnightMarketAddressMismatchError} when the position market targets another Midnight deployment.
1860
1933
  * @throws {MissingAccrualPositionError} when no position snapshot is supplied.
1861
1934
  * @throws {AccrualPositionUserMismatchError} when the position snapshot belongs to another account.
1862
1935
  * @throws {NoMidnightCreditToRedeemError} when the selected unit amount is non-positive.
1936
+ * @throws {InputExceedsMaxError} when the selected units exceed `uint128`.
1863
1937
  * @throws {MidnightRedeemExceedsCreditError} when the selected amount exceeds the accrued
1864
1938
  * position credit.
1865
1939
  * @throws {InvalidMidnightPositionLossFactorError} when the market loss factor is below the
1866
1940
  * position's `lastLossFactor`, which `getPositionData` snapshots never are.
1867
1941
  * @throws {InvalidMidnightPositionAccrualStateError} when the snapshot's credit, pending fee or
1868
1942
  * loss factor are inconsistent, which `getPositionData` snapshots never are.
1869
- * @throws {InputExceedsMaxError} when the selected units exceed `uint128`.
1870
1943
  * @throws {InsufficientMidnightWithdrawableLiquidityError} when market liquidity cannot cover the redemption.
1944
+ * @throws {MidnightZeroOnBehalfError} when `accountAddress` is the zero address.
1871
1945
  * @throws {MidnightZeroReceiverError} when `receiver` resolves to the zero address.
1872
1946
  * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
1873
1947
  * market token contract.
@@ -1882,9 +1956,13 @@ export class MorphoMidnight {
1882
1956
  */
1883
1957
  redeem(params) {
1884
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);
1885
1961
  if (!params.positionData) {
1886
1962
  throw new MissingAccrualPositionError();
1887
1963
  }
1964
+ if (params.positionData.user != null)
1965
+ validateMidnightAddress("positionData.user", params.positionData.user);
1888
1966
  if (params.positionData.user == null ||
1889
1967
  !isAddressEqual(params.positionData.user, params.accountAddress)) {
1890
1968
  throw new AccrualPositionUserMismatchError(params.positionData.user ?? "unbound", params.accountAddress);
@@ -1945,7 +2023,7 @@ export class MorphoMidnight {
1945
2023
  * scaled by `ORACLE_PRICE_SCALE`. An empty array is safe only when
1946
2024
  * `collateralWithdrawals` is empty or the conservative post-operation debt is zero: a `full`
1947
2025
  * repay, or `repay.assets` covering `positionData.debt`.
1948
- * @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.
1949
2027
  * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
1950
2028
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
1951
2029
  * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
@@ -1961,6 +2039,8 @@ export class MorphoMidnight {
1961
2039
  * @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
1962
2040
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1963
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.
1964
2044
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1965
2045
  * RPC read fails.
1966
2046
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
@@ -1985,7 +2065,6 @@ export class MorphoMidnight {
1985
2065
  * during this method call, before the lazy output is returned.
1986
2066
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
1987
2067
  * contract or a market token contract.
1988
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
1989
2068
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1990
2069
  * @example
1991
2070
  * ```ts
@@ -2003,6 +2082,8 @@ export class MorphoMidnight {
2003
2082
  */
2004
2083
  repayWithdrawCollateral(params) {
2005
2084
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
2085
+ // Reject the zero account before preparing anything for it.
2086
+ validateMidnightAccount("accountAddress", params.accountAddress);
2006
2087
  // Fails before any API read or build when the deadline has already passed.
2007
2088
  validateMidnightDeadline(params.deadline);
2008
2089
  const market = params.marketData.params;
@@ -2080,7 +2161,7 @@ export class MorphoMidnight {
2080
2161
  ? params.repay.assets
2081
2162
  : params.repay.maxBuyerAssets;
2082
2163
  return {
2083
- getRequirements: async (requirementsParams) => {
2164
+ getRequirements: async (_requirementsParams) => {
2084
2165
  const approvals = pulledAssets > 0n
2085
2166
  ? await getMidnightApprovalRequirements({
2086
2167
  viemClient: this.client.viemClient,
@@ -2089,7 +2170,6 @@ export class MorphoMidnight {
2089
2170
  owner: params.accountAddress,
2090
2171
  spender: tx.to,
2091
2172
  amount: pulledAssets,
2092
- approvalAmount: requirementsParams?.approvalAmount,
2093
2173
  })
2094
2174
  : [];
2095
2175
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
@@ -2119,6 +2199,7 @@ export class MorphoMidnight {
2119
2199
  * @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
2120
2200
  * @throws {ChainIdMismatchError} when the client targets another chain, or from
2121
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.
2122
2203
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
2123
2204
  * RPC read fails.
2124
2205
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.