@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
@@ -11,9 +11,12 @@ const index_js_2 = require("../../actions/requirements/index.js");
11
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
12
  const callback_js_1 = require("../../helpers/callback.js");
13
13
  const constant_js_1 = require("../../helpers/constant.js");
14
+ const encodeMidnightCalldata_js_1 = require("../../helpers/encodeMidnightCalldata.js");
14
15
  const index_js_3 = require("../../helpers/index.js");
16
+ const validateMidnightAccount_js_1 = require("../../helpers/validateMidnightAccount.js");
15
17
  const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
16
18
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
19
+ const validateMidnightPublication_js_1 = require("../../helpers/validateMidnightPublication.js");
17
20
  const validateMidnightTakeFeasibility_js_1 = require("../../helpers/validateMidnightTakeFeasibility.js");
18
21
  const validateOfferSides_js_1 = require("../../helpers/validateOfferSides.js");
19
22
  const index_js_4 = require("../../types/index.js");
@@ -23,6 +26,8 @@ const validatePositionBinding = (params) => {
23
26
  if (params.positionData.marketId !== params.marketData.id) {
24
27
  throw new index_js_4.MarketIdMismatchError(params.positionData.marketId, params.marketData.id);
25
28
  }
29
+ // Reject a malformed address before viem compares it.
30
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("positionData.user", params.positionData.user);
26
31
  if (!(0, viem_1.isAddressEqual)(params.positionData.user, params.accountAddress)) {
27
32
  throw new index_js_4.AccrualPositionUserMismatchError(params.positionData.user, params.accountAddress);
28
33
  }
@@ -52,7 +57,9 @@ const rejectReduceOnlyOffers = (offers) => {
52
57
  };
53
58
  const getOffersDataInternal = async ({ client, chainId, params, marketCreationTime = "expiry", }) => {
54
59
  (0, index_js_3.validateChainId)(client.viemClient.chain?.id, chainId);
55
- const tree = midnight_sdk_1.Tree.from(params.offers);
60
+ // Reject a malformed or zero maker before comparing offers against it.
61
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
62
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
56
63
  const midnight = (0, morpho_ts_1.getChainAddress)(chainId, "midnight");
57
64
  tree.offers.forEach((offer, index) => {
58
65
  if (!(0, viem_1.isAddressEqual)(offer.maker, params.accountAddress)) {
@@ -246,6 +253,7 @@ class MorphoMidnight {
246
253
  * @returns Prepared tree, groups, ratifier, and encoded payload used by maker flows.
247
254
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, another chain than this entity's.
248
255
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
256
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
249
257
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
250
258
  * (not thrown when `validation` is `false`).
251
259
  * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
@@ -255,6 +263,8 @@ class MorphoMidnight {
255
263
  * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
256
264
  * @throws {UnknownAddressError} when the chain has no deployment for the tree's V1 ratifier.
257
265
  * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
266
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
267
+ * @throws {MidnightCalldataEncodingError} when an offer cannot be ABI-encoded, such as an out-of-range integer, or `accountAddress` is not a well-formed address.
258
268
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
259
269
  * @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
260
270
  * @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
@@ -309,6 +319,8 @@ class MorphoMidnight {
309
319
  * @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
310
320
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
311
321
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
322
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
323
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
312
324
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
313
325
  * RPC read fails.
314
326
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -342,7 +354,6 @@ class MorphoMidnight {
342
354
  * offers plus the fallback.
343
355
  * @throws {MidnightContractReceiverError} when `referralFeeRecipient` is a Midnight protocol
344
356
  * contract or a market token contract with a positive referral fee.
345
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
346
357
  * @example
347
358
  * ```ts
348
359
  * const output = midnight.takeLend({
@@ -357,6 +368,8 @@ class MorphoMidnight {
357
368
  */
358
369
  takeLend(params) {
359
370
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
371
+ // Reject the zero account before preparing anything for it.
372
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
360
373
  validateTakeDeadlineWindow(params.deadline);
361
374
  const market = params.marketData.params;
362
375
  const rawParams = {
@@ -391,7 +404,7 @@ class MorphoMidnight {
391
404
  ? params.target.assets
392
405
  : params.target.maxBuyerAssets;
393
406
  return {
394
- getRequirements: async (requirementsParams) => {
407
+ getRequirements: async (_requirementsParams) => {
395
408
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
396
409
  viemClient: this.client.viemClient,
397
410
  chainId: this.chainId,
@@ -399,7 +412,6 @@ class MorphoMidnight {
399
412
  owner: params.accountAddress,
400
413
  spender: tx.to,
401
414
  amount: pulledAssets,
402
- approvalAmount: requirementsParams?.approvalAmount,
403
415
  });
404
416
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
405
417
  return [...approvals, ...authorization];
@@ -434,11 +446,14 @@ class MorphoMidnight {
434
446
  * Midnight protocol and market token contracts are rejected.
435
447
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
436
448
  * @param params.deadline - Bounded bundle execution deadline timestamp.
437
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
449
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
450
+ * proceeds; on an assets target it is added on top of `target.assets`.
438
451
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
439
452
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
440
453
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
441
454
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
455
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
456
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
442
457
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
443
458
  * RPC read fails.
444
459
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -500,6 +515,8 @@ class MorphoMidnight {
500
515
  */
501
516
  takeBorrow(params) {
502
517
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
518
+ // Reject the zero account before preparing anything for it.
519
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
503
520
  validateTakeDeadlineWindow(params.deadline);
504
521
  const rawParams = {
505
522
  chainId: this.chainId,
@@ -574,11 +591,14 @@ class MorphoMidnight {
574
591
  * Midnight protocol and market token contracts are rejected.
575
592
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
576
593
  * @param params.deadline - Bundle execution deadline timestamp.
577
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
594
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
595
+ * proceeds; on an assets target it is added on top of `target.assets`.
578
596
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
579
597
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
580
598
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
581
599
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
600
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
601
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
582
602
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
583
603
  * RPC read fails.
584
604
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
@@ -622,6 +642,8 @@ class MorphoMidnight {
622
642
  */
623
643
  takeWithdraw(params) {
624
644
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
645
+ // Reject the zero account before preparing anything for it.
646
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
625
647
  validateTakeDeadlineWindow(params.deadline);
626
648
  const rawParams = {
627
649
  chainId: this.chainId,
@@ -689,11 +711,14 @@ class MorphoMidnight {
689
711
  * Midnight protocol and market token contracts are rejected.
690
712
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
691
713
  * @param params.deadline - Bounded bundle execution deadline timestamp.
692
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
714
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
715
+ * proceeds; on an assets target it is added on top of `target.assets`.
693
716
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
694
717
  * @returns Lazy collateral approvals and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
695
718
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
696
719
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
720
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
721
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
697
722
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
698
723
  * RPC read fails.
699
724
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -734,7 +759,6 @@ class MorphoMidnight {
734
759
  * withdrawal.
735
760
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
736
761
  * its bounds cannot hold at any fill.
737
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
738
762
  * @example
739
763
  * ```ts
740
764
  * const output = midnight.supplyCollateralTakeBorrow({
@@ -751,6 +775,8 @@ class MorphoMidnight {
751
775
  */
752
776
  supplyCollateralTakeBorrow(params) {
753
777
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
778
+ // Reject the zero account before preparing anything for it.
779
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
754
780
  validateTakeDeadlineWindow(params.deadline);
755
781
  const market = params.marketData.params;
756
782
  const rawParams = {
@@ -819,7 +845,7 @@ class MorphoMidnight {
819
845
  collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
820
846
  }
821
847
  return {
822
- getRequirements: async (requirementsParams) => {
848
+ getRequirements: async (_requirementsParams) => {
823
849
  const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => (0, index_js_2.getMidnightApprovalRequirements)({
824
850
  viemClient: this.client.viemClient,
825
851
  chainId: this.chainId,
@@ -827,7 +853,6 @@ class MorphoMidnight {
827
853
  owner: params.accountAddress,
828
854
  spender: tx.to,
829
855
  amount,
830
- approvalAmount: requirementsParams?.approvalAmount,
831
856
  })));
832
857
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
833
858
  return [...approvals.flat(), ...authorization];
@@ -879,6 +904,8 @@ class MorphoMidnight {
879
904
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
880
905
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
881
906
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
907
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
908
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
882
909
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
883
910
  * RPC read fails.
884
911
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -923,7 +950,6 @@ class MorphoMidnight {
923
950
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
924
951
  * contract or a market token contract, or when `referralFeeRecipient` is either with a
925
952
  * positive referral fee.
926
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
927
953
  * @example
928
954
  * ```ts
929
955
  * const output = midnight.takeRepayWithdrawCollateral({
@@ -942,6 +968,8 @@ class MorphoMidnight {
942
968
  */
943
969
  takeRepayWithdrawCollateral(params) {
944
970
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
971
+ // Reject the zero account before preparing anything for it.
972
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
945
973
  validateTakeDeadlineWindow(params.deadline);
946
974
  const market = params.marketData.params;
947
975
  const rawParams = {
@@ -1028,7 +1056,7 @@ class MorphoMidnight {
1028
1056
  ? params.target.assets
1029
1057
  : params.target.maxBuyerAssets;
1030
1058
  return {
1031
- getRequirements: async (requirementsParams) => {
1059
+ getRequirements: async (_requirementsParams) => {
1032
1060
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
1033
1061
  viemClient: this.client.viemClient,
1034
1062
  chainId: this.chainId,
@@ -1036,7 +1064,6 @@ class MorphoMidnight {
1036
1064
  owner: params.accountAddress,
1037
1065
  spender: tx.to,
1038
1066
  amount: pulledAssets,
1039
- approvalAmount: requirementsParams?.approvalAmount,
1040
1067
  });
1041
1068
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
1042
1069
  return [...approvals, ...authorization];
@@ -1048,22 +1075,30 @@ class MorphoMidnight {
1048
1075
  * Prepares a direct collateral supply using a caller-provided market snapshot.
1049
1076
  *
1050
1077
  * @param params - Supplier, market snapshot, collateral amount, reserve, and optional collateral index.
1051
- * @param params.accountAddress - Account receiving the supplied collateral position.
1078
+ * @param params.accountAddress - Account receiving the supplied collateral position. It must send
1079
+ * the transaction: Midnight pulls the collateral from `msg.sender` and only lets the position owner
1080
+ * or its operators supply for it, and the approval requirements are resolved for this account.
1052
1081
  * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
1053
1082
  * @param params.collateralAssets - Collateral assets supplied in this transaction.
1054
1083
  * @param params.reservedCollateralAssets - Existing collateral reserved by other open maker groups.
1055
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
1084
+ * Only raises the approval requirement so those groups keep their allowance; the transaction
1085
+ * transfers only `collateralAssets`.
1086
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`. Indexes follow the
1087
+ * market's collateral parameters, which Midnight sorts by token address, not the order they were
1088
+ * listed in when the market was built; check `marketData.getCollateralByIndex(index).token`.
1056
1089
  * @returns Lazy token-approval requirements and a synchronous transaction builder.
1057
1090
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1058
1091
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
1092
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1059
1093
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1060
1094
  * RPC read fails.
1061
1095
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
1062
1096
  * @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
1063
1097
  * @throws {InputExceedsMaxError} when `collateralAssets` exceeds `uint128`.
1064
1098
  * @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
1099
+ * @throws {MidnightZeroOnBehalfError} from `getRequirements()` and `buildTx()` when `accountAddress`
1100
+ * is the zero address.
1065
1101
  * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
1066
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled collateral assets.
1067
1102
  * @example
1068
1103
  * ```ts
1069
1104
  * const output = midnight.supplyCollateral({
@@ -1075,6 +1110,8 @@ class MorphoMidnight {
1075
1110
  */
1076
1111
  supplyCollateral(params) {
1077
1112
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1113
+ // Reject a malformed account here; the builder rejects the zero account.
1114
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("accountAddress", params.accountAddress);
1078
1115
  validateMarketData(params.marketData, this.chainId);
1079
1116
  assertPositiveAmount("collateralAssets", params.collateralAssets);
1080
1117
  (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("collateralAssets", params.collateralAssets);
@@ -1084,15 +1121,20 @@ class MorphoMidnight {
1084
1121
  const collateral = market.getCollateralByIndex(collateralIndex);
1085
1122
  const midnight = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnight");
1086
1123
  return {
1087
- getRequirements: async (requirementsParams) => await (0, index_js_2.getMidnightApprovalRequirements)({
1088
- viemClient: this.client.viemClient,
1089
- chainId: this.chainId,
1090
- token: collateral.token,
1091
- owner: params.accountAddress,
1092
- spender: midnight,
1093
- amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1094
- approvalAmount: requirementsParams?.approvalAmount,
1095
- }),
1124
+ getRequirements: async (_requirementsParams) => {
1125
+ // Match buildTx(): the requirement helper would report a zero owner with another class.
1126
+ if ((0, viem_1.isAddressEqual)(params.accountAddress, viem_1.zeroAddress)) {
1127
+ throw new index_js_4.MidnightZeroOnBehalfError("onBehalf");
1128
+ }
1129
+ return await (0, index_js_2.getMidnightApprovalRequirements)({
1130
+ viemClient: this.client.viemClient,
1131
+ chainId: this.chainId,
1132
+ token: collateral.token,
1133
+ owner: params.accountAddress,
1134
+ spender: midnight,
1135
+ amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1136
+ });
1137
+ },
1096
1138
  buildTx: () => (0, index_js_1.midnightSupplyCollateral)({
1097
1139
  chainId: this.chainId,
1098
1140
  market: market.params,
@@ -1123,9 +1165,12 @@ class MorphoMidnight {
1123
1165
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
1124
1166
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1125
1167
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1168
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1169
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1126
1170
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1127
1171
  * RPC read fails.
1128
1172
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1173
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1129
1174
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1130
1175
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1131
1176
  * @throws {NonPositiveInputError} when `loanAssets` is non-positive.
@@ -1156,7 +1201,6 @@ class MorphoMidnight {
1156
1201
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1157
1202
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1158
1203
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1159
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1160
1204
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1161
1205
  * @example
1162
1206
  * ```ts
@@ -1172,9 +1216,11 @@ class MorphoMidnight {
1172
1216
  */
1173
1217
  async makeLend(params) {
1174
1218
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1219
+ // Reject the zero account before preparing anything for it.
1220
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1175
1221
  // Fails before any API read or build when the deadline has already passed.
1176
1222
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1177
- const tree = midnight_sdk_1.Tree.from(params.offers);
1223
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1178
1224
  rejectReduceOnlyOffers(tree.offers);
1179
1225
  return this.prepareLendOffers({ ...params, offers: tree });
1180
1226
  }
@@ -1194,9 +1240,12 @@ class MorphoMidnight {
1194
1240
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1195
1241
  * @returns Prepared group metadata, lazy authorization requirements, and a synchronous transaction builder.
1196
1242
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1243
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1244
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1197
1245
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1198
1246
  * RPC read fails.
1199
1247
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1248
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1200
1249
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1201
1250
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1202
1251
  * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
@@ -1238,9 +1287,11 @@ class MorphoMidnight {
1238
1287
  */
1239
1288
  async makeBorrow(params) {
1240
1289
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1290
+ // Reject the zero account before preparing anything for it.
1291
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1241
1292
  // Fails before any API read or build when the deadline has already passed.
1242
1293
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1243
- const tree = midnight_sdk_1.Tree.from(params.offers);
1294
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1244
1295
  rejectReduceOnlyOffers(tree.offers);
1245
1296
  return this.prepareBorrowOffers({ ...params, offers: tree });
1246
1297
  }
@@ -1248,9 +1299,11 @@ class MorphoMidnight {
1248
1299
  * Prepares lend-side offers for publication.
1249
1300
  */
1250
1301
  async prepareLendOffers(params) {
1302
+ // Reject a malformed address before viem compares offer markets with it.
1303
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("loanToken", params.loanToken);
1251
1304
  assertPositiveAmount("loanAssets", params.loanAssets);
1252
1305
  assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
1253
- const tree = midnight_sdk_1.Tree.from(params.offers);
1306
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1254
1307
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
1255
1308
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
1256
1309
  const data = await getOffersDataInternal({
@@ -1285,7 +1338,7 @@ class MorphoMidnight {
1285
1338
  groups: data.groups,
1286
1339
  root: data.tree.root,
1287
1340
  ratifierType: data.ratifierType,
1288
- getRequirements: async (requirementsParams) => {
1341
+ getRequirements: async (_requirementsParams) => {
1289
1342
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
1290
1343
  viemClient: this.client.viemClient,
1291
1344
  chainId: this.chainId,
@@ -1293,7 +1346,6 @@ class MorphoMidnight {
1293
1346
  owner: data.accountAddress,
1294
1347
  spender: midnight,
1295
1348
  amount: params.loanAssets + (params.reservedLoanAssets ?? 0n),
1296
- approvalAmount: requirementsParams?.approvalAmount,
1297
1349
  });
1298
1350
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1299
1351
  return [...approvals, ...authorization];
@@ -1340,6 +1392,8 @@ class MorphoMidnight {
1340
1392
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1341
1393
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
1342
1394
  * another chain than `this.chainId`.
1395
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1396
+ * @throws {MidnightCalldataEncodingError} when the offer tree or `blueMarket` cannot be ABI-encoded.
1343
1397
  * @throws {viem.BaseError} when the `eth_chainId` request, a Blue market RPC read, or a
1344
1398
  * requirement RPC read fails.
1345
1399
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2`, `midnightBlueBuyCallbackFactory`, `midnight`, `blue` or V1 ratifier deployment.
@@ -1351,6 +1405,7 @@ class MorphoMidnight {
1351
1405
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1352
1406
  * @throws {NativeAmountOnNonWNativeAssetError} when `blueMarket.loanToken` is not wNative.
1353
1407
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1408
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1354
1409
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1355
1410
  * (not thrown when `validation` is `false`).
1356
1411
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1380,7 +1435,6 @@ class MorphoMidnight {
1380
1435
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1381
1436
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
1382
1437
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1383
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `assetsToPark`.
1384
1438
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1385
1439
  * @example
1386
1440
  * ```ts
@@ -1400,15 +1454,21 @@ class MorphoMidnight {
1400
1454
  * ```
1401
1455
  */
1402
1456
  async supplyBlueMakeLend(params) {
1457
+ // Reject the zero account before preparing anything for it.
1458
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1459
+ // Reject wrong-sized salts before callback derivation pads them or any read occurs.
1460
+ (0, validateMidnightPublication_js_1.validateMidnightBytes32)("callbackSalt", params.callbackSalt);
1403
1461
  assertPositiveAmount("assetsToPark", params.assetsToPark);
1404
1462
  (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("assetsToPark", params.assetsToPark);
1405
- const tree = midnight_sdk_1.Tree.from(params.offers);
1463
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1406
1464
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
1407
1465
  rejectReduceOnlyOffers(tree.offers);
1408
1466
  await (0, validateClientChainId_js_1.validateClientChainId)(this.client.viemClient, this.chainId);
1409
1467
  // Fails before any API read or build when the deadline has already passed.
1410
1468
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1411
1469
  const { callbackSalt } = params;
1470
+ // Encode the whole Blue market first so a malformed field fails typed, before the RPC read.
1471
+ const callbackData = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("blueMarket", () => (0, callback_js_1.getMidnightBlueBuyCallbackData)(params.blueMarket));
1412
1472
  const blueMarketId = blue_sdk_1.MarketUtils.getMarketId(params.blueMarket);
1413
1473
  const callback = (0, callback_js_1.getMidnightBlueBuyCallbackAddress)({
1414
1474
  chainId: this.chainId,
@@ -1435,7 +1495,6 @@ class MorphoMidnight {
1435
1495
  assets: params.assetsToPark,
1436
1496
  });
1437
1497
  }
1438
- const callbackData = (0, callback_js_1.getMidnightBlueBuyCallbackData)(params.blueMarket);
1439
1498
  data.tree.offers.forEach((offer, index) => {
1440
1499
  const offerMarket = (0, publication_js_1.offerMarketParams)(offer);
1441
1500
  if (!(0, viem_1.isAddressEqual)(offerMarket.loanToken, params.blueMarket.loanToken)) {
@@ -1482,7 +1541,7 @@ class MorphoMidnight {
1482
1541
  groups: data.groups,
1483
1542
  root: data.tree.root,
1484
1543
  ratifierType: data.ratifierType,
1485
- getRequirements: async (requirementsParams) => {
1544
+ getRequirements: async (_requirementsParams) => {
1486
1545
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
1487
1546
  viemClient: this.client.viemClient,
1488
1547
  chainId: this.chainId,
@@ -1490,7 +1549,6 @@ class MorphoMidnight {
1490
1549
  owner: data.accountAddress,
1491
1550
  spender: (0, morpho_ts_1.getChainAddress)(this.chainId, "midnightBundlesV2"),
1492
1551
  amount: params.assetsToPark,
1493
- approvalAmount: requirementsParams?.approvalAmount,
1494
1552
  });
1495
1553
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1496
1554
  return [...approvals, ...authorization];
@@ -1502,7 +1560,7 @@ class MorphoMidnight {
1502
1560
  * Prepares borrow-side offers for publication.
1503
1561
  */
1504
1562
  async prepareBorrowOffers(params) {
1505
- const tree = midnight_sdk_1.Tree.from(params.offers);
1563
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1506
1564
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1507
1565
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
1508
1566
  const data = await getOffersDataInternal({
@@ -1548,9 +1606,12 @@ class MorphoMidnight {
1548
1606
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1549
1607
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1550
1608
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1609
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1610
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1551
1611
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1552
1612
  * RPC read fails.
1553
1613
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1614
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1554
1615
  * @throws {MidnightOfferSideMismatchError} when an offer is not a sell offer (`buy = false`).
1555
1616
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1556
1617
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1595,9 +1656,11 @@ class MorphoMidnight {
1595
1656
  */
1596
1657
  async makeWithdraw(params) {
1597
1658
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1659
+ // Reject the zero account before preparing anything for it.
1660
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1598
1661
  // Fails before any API read or build when the deadline has already passed.
1599
1662
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1600
- const tree = midnight_sdk_1.Tree.from(params.offers);
1663
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1601
1664
  // Reject the wrong exit intent before calling the mempool validation API.
1602
1665
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1603
1666
  for (const [index, offer] of tree.offers.entries()) {
@@ -1630,9 +1693,12 @@ class MorphoMidnight {
1630
1693
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
1631
1694
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1632
1695
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1696
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1697
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1633
1698
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1634
1699
  * RPC read fails.
1635
1700
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1701
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1636
1702
  * @throws {MidnightOfferSideMismatchError} when an offer is not a buy offer (`buy = true`).
1637
1703
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1638
1704
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1664,7 +1730,6 @@ class MorphoMidnight {
1664
1730
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1665
1731
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1666
1732
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1667
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1668
1733
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1669
1734
  * @example
1670
1735
  * ```ts
@@ -1681,9 +1746,11 @@ class MorphoMidnight {
1681
1746
  */
1682
1747
  async makeRepay(params) {
1683
1748
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1749
+ // Reject the zero account before preparing anything for it.
1750
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1684
1751
  // Fails before any API read or build when the deadline has already passed.
1685
1752
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1686
- const tree = midnight_sdk_1.Tree.from(params.offers);
1753
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1687
1754
  // Reject the wrong exit intent before calling the mempool validation API.
1688
1755
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
1689
1756
  for (const [index, offer] of tree.offers.entries()) {
@@ -1717,6 +1784,8 @@ class MorphoMidnight {
1717
1784
  * required for the full pulled amount.
1718
1785
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1719
1786
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1787
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1788
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1720
1789
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1721
1790
  * RPC read fails.
1722
1791
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
@@ -1729,6 +1798,7 @@ class MorphoMidnight {
1729
1798
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1730
1799
  * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
1731
1800
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1801
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1732
1802
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1733
1803
  * (not thrown when `validation` is `false`).
1734
1804
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1757,7 +1827,6 @@ class MorphoMidnight {
1757
1827
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1758
1828
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1759
1829
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1760
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
1761
1830
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1762
1831
  * @example
1763
1832
  * ```ts
@@ -1774,12 +1843,14 @@ class MorphoMidnight {
1774
1843
  */
1775
1844
  async supplyCollateralMakeBorrow(params) {
1776
1845
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1846
+ // Reject the zero account before preparing anything for it.
1847
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1777
1848
  // Fails before any API read or build when the deadline has already passed.
1778
1849
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1779
1850
  const market = params.collateral.market instanceof midnight_sdk_1.MarketParams
1780
1851
  ? params.collateral.market
1781
1852
  : midnight_sdk_1.MarketParams.from(params.collateral.market);
1782
- const tree = midnight_sdk_1.Tree.from(params.offers);
1853
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1783
1854
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1784
1855
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
1785
1856
  rejectReduceOnlyOffers(tree.offers);
@@ -1789,9 +1860,9 @@ class MorphoMidnight {
1789
1860
  params: { ...params, offers: tree },
1790
1861
  marketCreationTime: "now",
1791
1862
  });
1792
- const marketId = midnight_sdk_1.MarketUtils.toId(market);
1863
+ const marketId = (0, encodeMidnightCalldata_js_1.encodeMidnightMarketId)(market);
1793
1864
  for (const offer of data.tree.offers) {
1794
- const offerMarketId = midnight_sdk_1.MarketUtils.toId(offer.market);
1865
+ const offerMarketId = (0, encodeMidnightCalldata_js_1.encodeMidnightMarketId)(offer.market);
1795
1866
  if (offerMarketId.toLowerCase() !== marketId.toLowerCase()) {
1796
1867
  throw new index_js_4.MarketIdMismatchError(offerMarketId, marketId);
1797
1868
  }
@@ -1824,7 +1895,7 @@ class MorphoMidnight {
1824
1895
  groups: data.groups,
1825
1896
  root: data.tree.root,
1826
1897
  ratifierType: data.ratifierType,
1827
- getRequirements: async (requirementsParams) => {
1898
+ getRequirements: async (_requirementsParams) => {
1828
1899
  const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => (0, index_js_2.getMidnightApprovalRequirements)({
1829
1900
  viemClient: this.client.viemClient,
1830
1901
  chainId: this.chainId,
@@ -1832,7 +1903,6 @@ class MorphoMidnight {
1832
1903
  owner: data.accountAddress,
1833
1904
  spender: midnightBundlesV2,
1834
1905
  amount,
1835
- approvalAmount: requirementsParams?.approvalAmount,
1836
1906
  })));
1837
1907
  return [
1838
1908
  ...approvals.flat(),
@@ -1846,7 +1916,9 @@ class MorphoMidnight {
1846
1916
  * Prepares redemption of accrued Midnight credit from a position snapshot.
1847
1917
  *
1848
1918
  * @param params - Position owner, accrued position, optional unit amount, and receiver.
1849
- * @param params.accountAddress - Position owner whose credit is redeemed.
1919
+ * @param params.accountAddress - Position owner whose credit is redeemed. It must send the
1920
+ * transaction (or authorize the sender): Midnight reverts `Unauthorized()` otherwise, which
1921
+ * `getRequirements()` cannot detect because it does not know the sender.
1850
1922
  * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`.
1851
1923
  * @param params.receiver - Optional credit receiver; defaults to the position owner.
1852
1924
  * Midnight protocol and market token contracts are rejected.
@@ -1859,18 +1931,20 @@ class MorphoMidnight {
1859
1931
  * is left. Redeem again after maturity to empty the position.
1860
1932
  * @returns No requirements and a synchronous redemption transaction builder.
1861
1933
  * @throws {ChainIdMismatchError} when the position market targets another chain.
1934
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1862
1935
  * @throws {MidnightMarketAddressMismatchError} when the position market targets another Midnight deployment.
1863
1936
  * @throws {MissingAccrualPositionError} when no position snapshot is supplied.
1864
1937
  * @throws {AccrualPositionUserMismatchError} when the position snapshot belongs to another account.
1865
1938
  * @throws {NoMidnightCreditToRedeemError} when the selected unit amount is non-positive.
1939
+ * @throws {InputExceedsMaxError} when the selected units exceed `uint128`.
1866
1940
  * @throws {MidnightRedeemExceedsCreditError} when the selected amount exceeds the accrued
1867
1941
  * position credit.
1868
1942
  * @throws {InvalidMidnightPositionLossFactorError} when the market loss factor is below the
1869
1943
  * position's `lastLossFactor`, which `getPositionData` snapshots never are.
1870
1944
  * @throws {InvalidMidnightPositionAccrualStateError} when the snapshot's credit, pending fee or
1871
1945
  * loss factor are inconsistent, which `getPositionData` snapshots never are.
1872
- * @throws {InputExceedsMaxError} when the selected units exceed `uint128`.
1873
1946
  * @throws {InsufficientMidnightWithdrawableLiquidityError} when market liquidity cannot cover the redemption.
1947
+ * @throws {MidnightZeroOnBehalfError} when `accountAddress` is the zero address.
1874
1948
  * @throws {MidnightZeroReceiverError} when `receiver` resolves to the zero address.
1875
1949
  * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
1876
1950
  * market token contract.
@@ -1885,9 +1959,13 @@ class MorphoMidnight {
1885
1959
  */
1886
1960
  redeem(params) {
1887
1961
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1962
+ // Reject a malformed account here; the builder rejects the zero account.
1963
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("accountAddress", params.accountAddress);
1888
1964
  if (!params.positionData) {
1889
1965
  throw new index_js_4.MissingAccrualPositionError();
1890
1966
  }
1967
+ if (params.positionData.user != null)
1968
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("positionData.user", params.positionData.user);
1891
1969
  if (params.positionData.user == null ||
1892
1970
  !(0, viem_1.isAddressEqual)(params.positionData.user, params.accountAddress)) {
1893
1971
  throw new index_js_4.AccrualPositionUserMismatchError(params.positionData.user ?? "unbound", params.accountAddress);
@@ -1948,7 +2026,7 @@ class MorphoMidnight {
1948
2026
  * scaled by `ORACLE_PRICE_SCALE`. An empty array is safe only when
1949
2027
  * `collateralWithdrawals` is empty or the conservative post-operation debt is zero: a `full`
1950
2028
  * repay, or `repay.assets` covering `positionData.debt`.
1951
- * @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.
2029
+ * @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.
1952
2030
  * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
1953
2031
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
1954
2032
  * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
@@ -1964,6 +2042,8 @@ class MorphoMidnight {
1964
2042
  * @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
1965
2043
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1966
2044
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
2045
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
2046
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1967
2047
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1968
2048
  * RPC read fails.
1969
2049
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
@@ -1988,7 +2068,6 @@ class MorphoMidnight {
1988
2068
  * during this method call, before the lazy output is returned.
1989
2069
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
1990
2070
  * contract or a market token contract.
1991
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
1992
2071
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1993
2072
  * @example
1994
2073
  * ```ts
@@ -2006,6 +2085,8 @@ class MorphoMidnight {
2006
2085
  */
2007
2086
  repayWithdrawCollateral(params) {
2008
2087
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
2088
+ // Reject the zero account before preparing anything for it.
2089
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
2009
2090
  // Fails before any API read or build when the deadline has already passed.
2010
2091
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
2011
2092
  const market = params.marketData.params;
@@ -2083,7 +2164,7 @@ class MorphoMidnight {
2083
2164
  ? params.repay.assets
2084
2165
  : params.repay.maxBuyerAssets;
2085
2166
  return {
2086
- getRequirements: async (requirementsParams) => {
2167
+ getRequirements: async (_requirementsParams) => {
2087
2168
  const approvals = pulledAssets > 0n
2088
2169
  ? await (0, index_js_2.getMidnightApprovalRequirements)({
2089
2170
  viemClient: this.client.viemClient,
@@ -2092,7 +2173,6 @@ class MorphoMidnight {
2092
2173
  owner: params.accountAddress,
2093
2174
  spender: tx.to,
2094
2175
  amount: pulledAssets,
2095
- approvalAmount: requirementsParams?.approvalAmount,
2096
2176
  })
2097
2177
  : [];
2098
2178
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
@@ -2122,6 +2202,7 @@ class MorphoMidnight {
2122
2202
  * @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
2123
2203
  * @throws {ChainIdMismatchError} when the client targets another chain, or from
2124
2204
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
2205
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as an out-of-range integer.
2125
2206
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
2126
2207
  * RPC read fails.
2127
2208
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.