@morpho-org/morpho-sdk 8.3.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/MIGRATION-v8-to-v9.md +54 -0
  2. package/README.md +13 -7
  3. package/lib/cjs/actions/bundles/common.d.ts +4 -7
  4. package/lib/cjs/actions/bundles/common.js +8 -14
  5. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  6. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +1 -8
  7. package/lib/cjs/actions/midnight/authorization.d.ts +3 -1
  8. package/lib/cjs/actions/midnight/authorization.js +11 -1
  9. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -0
  10. package/lib/cjs/actions/midnight/cancelAndMake.js +10 -2
  11. package/lib/cjs/actions/midnight/redeem.d.ts +3 -1
  12. package/lib/cjs/actions/midnight/redeem.js +9 -3
  13. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  14. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +7 -3
  15. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +4 -1
  16. package/lib/cjs/actions/midnight/supplyCollateral.js +10 -3
  17. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  18. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +9 -3
  19. package/lib/cjs/actions/midnight/takeBorrow.d.ts +3 -1
  20. package/lib/cjs/actions/midnight/takeBorrow.js +9 -3
  21. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
  22. package/lib/cjs/actions/midnight/takeLend.js +7 -2
  23. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  24. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +8 -2
  25. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +3 -1
  26. package/lib/cjs/actions/midnight/takeWithdraw.js +10 -3
  27. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  28. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +5 -7
  29. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +7 -11
  30. package/lib/cjs/actions/requirements/getRequirementsApproval.js +8 -15
  31. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  32. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +11 -8
  33. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  34. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  35. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +1 -1
  36. package/lib/cjs/actions/vaultV1/inKindRedeem.js +1 -1
  37. package/lib/cjs/actions/vaultV1/withdraw.d.ts +4 -4
  38. package/lib/cjs/actions/vaultV1/withdraw.js +4 -4
  39. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +1 -1
  40. package/lib/cjs/actions/vaultV2/forceWithdraw.js +1 -1
  41. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +1 -1
  42. package/lib/cjs/actions/vaultV2/inKindRedeem.js +1 -1
  43. package/lib/cjs/actions/vaultV2/withdraw.d.ts +4 -4
  44. package/lib/cjs/actions/vaultV2/withdraw.js +4 -4
  45. package/lib/cjs/entities/blue/blue.d.ts +2 -12
  46. package/lib/cjs/entities/blue/blue.js +0 -4
  47. package/lib/cjs/entities/midnight/midnight.d.ts +56 -17
  48. package/lib/cjs/entities/midnight/midnight.js +131 -52
  49. package/lib/cjs/entities/midnight/types.d.ts +2 -9
  50. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  51. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +0 -7
  52. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  53. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -20
  54. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +40 -37
  55. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -34
  56. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +36 -34
  57. package/lib/cjs/entities/vaultV2/vaultV2.js +8 -34
  58. package/lib/cjs/helpers/encodeMidnightCalldata.d.ts +48 -0
  59. package/lib/cjs/helpers/encodeMidnightCalldata.js +74 -0
  60. package/lib/cjs/helpers/slippage.d.ts +9 -25
  61. package/lib/cjs/helpers/slippage.js +10 -27
  62. package/lib/cjs/helpers/validate.d.ts +1 -0
  63. package/lib/cjs/helpers/validate.js +5 -0
  64. package/lib/cjs/helpers/validateMidnightAccount.d.ts +34 -0
  65. package/lib/cjs/helpers/validateMidnightAccount.js +47 -0
  66. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  67. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +4 -0
  68. package/lib/cjs/helpers/validateMidnightMarket.d.ts +2 -0
  69. package/lib/cjs/helpers/validateMidnightMarket.js +5 -0
  70. package/lib/cjs/helpers/validateMidnightPublication.d.ts +11 -0
  71. package/lib/cjs/helpers/validateMidnightPublication.js +12 -1
  72. package/lib/cjs/helpers/validateMidnightReceiver.d.ts +1 -0
  73. package/lib/cjs/helpers/validateMidnightReceiver.js +8 -0
  74. package/lib/cjs/helpers/validateTakeableOffers.d.ts +2 -1
  75. package/lib/cjs/helpers/validateTakeableOffers.js +4 -3
  76. package/lib/cjs/types/action.d.ts +3 -1
  77. package/lib/cjs/types/error.d.ts +56 -5
  78. package/lib/cjs/types/error.js +139 -10
  79. package/lib/esm/actions/bundles/common.d.ts +4 -7
  80. package/lib/esm/actions/bundles/common.js +8 -14
  81. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  82. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -9
  83. package/lib/esm/actions/midnight/authorization.d.ts +3 -1
  84. package/lib/esm/actions/midnight/authorization.js +12 -2
  85. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -0
  86. package/lib/esm/actions/midnight/cancelAndMake.js +11 -3
  87. package/lib/esm/actions/midnight/redeem.d.ts +3 -1
  88. package/lib/esm/actions/midnight/redeem.js +10 -4
  89. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  90. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +8 -4
  91. package/lib/esm/actions/midnight/supplyCollateral.d.ts +4 -1
  92. package/lib/esm/actions/midnight/supplyCollateral.js +11 -4
  93. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  94. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +10 -4
  95. package/lib/esm/actions/midnight/takeBorrow.d.ts +3 -1
  96. package/lib/esm/actions/midnight/takeBorrow.js +10 -4
  97. package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
  98. package/lib/esm/actions/midnight/takeLend.js +8 -3
  99. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  100. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +9 -3
  101. package/lib/esm/actions/midnight/takeWithdraw.d.ts +3 -1
  102. package/lib/esm/actions/midnight/takeWithdraw.js +11 -4
  103. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  104. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +6 -8
  105. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +7 -11
  106. package/lib/esm/actions/requirements/getRequirementsApproval.js +9 -16
  107. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  108. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +12 -9
  109. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  110. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  111. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +1 -1
  112. package/lib/esm/actions/vaultV1/inKindRedeem.js +1 -1
  113. package/lib/esm/actions/vaultV1/withdraw.d.ts +4 -4
  114. package/lib/esm/actions/vaultV1/withdraw.js +4 -4
  115. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +1 -1
  116. package/lib/esm/actions/vaultV2/forceWithdraw.js +1 -1
  117. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +1 -1
  118. package/lib/esm/actions/vaultV2/inKindRedeem.js +1 -1
  119. package/lib/esm/actions/vaultV2/withdraw.d.ts +4 -4
  120. package/lib/esm/actions/vaultV2/withdraw.js +4 -4
  121. package/lib/esm/entities/blue/blue.d.ts +2 -12
  122. package/lib/esm/entities/blue/blue.js +0 -4
  123. package/lib/esm/entities/midnight/midnight.d.ts +56 -17
  124. package/lib/esm/entities/midnight/midnight.js +132 -53
  125. package/lib/esm/entities/midnight/types.d.ts +2 -9
  126. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  127. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +1 -8
  128. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  129. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +9 -21
  130. package/lib/esm/entities/vaultV1/vaultV1.d.ts +40 -37
  131. package/lib/esm/entities/vaultV1/vaultV1.js +6 -35
  132. package/lib/esm/entities/vaultV2/vaultV2.d.ts +36 -34
  133. package/lib/esm/entities/vaultV2/vaultV2.js +8 -34
  134. package/lib/esm/helpers/encodeMidnightCalldata.d.ts +48 -0
  135. package/lib/esm/helpers/encodeMidnightCalldata.js +69 -0
  136. package/lib/esm/helpers/slippage.d.ts +9 -25
  137. package/lib/esm/helpers/slippage.js +9 -25
  138. package/lib/esm/helpers/validate.d.ts +1 -0
  139. package/lib/esm/helpers/validate.js +5 -0
  140. package/lib/esm/helpers/validateMidnightAccount.d.ts +34 -0
  141. package/lib/esm/helpers/validateMidnightAccount.js +43 -0
  142. package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  143. package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +4 -0
  144. package/lib/esm/helpers/validateMidnightMarket.d.ts +2 -0
  145. package/lib/esm/helpers/validateMidnightMarket.js +5 -0
  146. package/lib/esm/helpers/validateMidnightPublication.d.ts +11 -0
  147. package/lib/esm/helpers/validateMidnightPublication.js +10 -0
  148. package/lib/esm/helpers/validateMidnightReceiver.d.ts +1 -0
  149. package/lib/esm/helpers/validateMidnightReceiver.js +8 -0
  150. package/lib/esm/helpers/validateTakeableOffers.d.ts +2 -1
  151. package/lib/esm/helpers/validateTakeableOffers.js +4 -3
  152. package/lib/esm/types/action.d.ts +3 -1
  153. package/lib/esm/types/error.d.ts +56 -5
  154. package/lib/esm/types/error.js +134 -6
  155. package/package.json +4 -3
@@ -11,9 +11,12 @@ const index_js_2 = require("../../actions/requirements/index.js");
11
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
12
  const callback_js_1 = require("../../helpers/callback.js");
13
13
  const constant_js_1 = require("../../helpers/constant.js");
14
+ const encodeMidnightCalldata_js_1 = require("../../helpers/encodeMidnightCalldata.js");
14
15
  const index_js_3 = require("../../helpers/index.js");
16
+ const validateMidnightAccount_js_1 = require("../../helpers/validateMidnightAccount.js");
15
17
  const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
16
18
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
19
+ const validateMidnightPublication_js_1 = require("../../helpers/validateMidnightPublication.js");
17
20
  const validateMidnightTakeFeasibility_js_1 = require("../../helpers/validateMidnightTakeFeasibility.js");
18
21
  const validateOfferSides_js_1 = require("../../helpers/validateOfferSides.js");
19
22
  const index_js_4 = require("../../types/index.js");
@@ -23,6 +26,8 @@ const validatePositionBinding = (params) => {
23
26
  if (params.positionData.marketId !== params.marketData.id) {
24
27
  throw new index_js_4.MarketIdMismatchError(params.positionData.marketId, params.marketData.id);
25
28
  }
29
+ // Reject a malformed address before viem compares it.
30
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("positionData.user", params.positionData.user);
26
31
  if (!(0, viem_1.isAddressEqual)(params.positionData.user, params.accountAddress)) {
27
32
  throw new index_js_4.AccrualPositionUserMismatchError(params.positionData.user, params.accountAddress);
28
33
  }
@@ -52,7 +57,9 @@ const rejectReduceOnlyOffers = (offers) => {
52
57
  };
53
58
  const getOffersDataInternal = async ({ client, chainId, params, marketCreationTime = "expiry", }) => {
54
59
  (0, index_js_3.validateChainId)(client.viemClient.chain?.id, chainId);
55
- const tree = midnight_sdk_1.Tree.from(params.offers);
60
+ // Reject a malformed or zero maker before comparing offers against it.
61
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
62
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
56
63
  const midnight = (0, morpho_ts_1.getChainAddress)(chainId, "midnight");
57
64
  tree.offers.forEach((offer, index) => {
58
65
  if (!(0, viem_1.isAddressEqual)(offer.maker, params.accountAddress)) {
@@ -246,6 +253,7 @@ class MorphoMidnight {
246
253
  * @returns Prepared tree, groups, ratifier, and encoded payload used by maker flows.
247
254
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, another chain than this entity's.
248
255
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
256
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
249
257
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
250
258
  * (not thrown when `validation` is `false`).
251
259
  * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
@@ -255,6 +263,8 @@ class MorphoMidnight {
255
263
  * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
256
264
  * @throws {UnknownAddressError} when the chain has no deployment for the tree's V1 ratifier.
257
265
  * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
266
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
267
+ * @throws {MidnightCalldataEncodingError} when an offer cannot be ABI-encoded, such as an out-of-range integer, or `accountAddress` is not a well-formed address.
258
268
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
259
269
  * @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
260
270
  * @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
@@ -309,6 +319,8 @@ class MorphoMidnight {
309
319
  * @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
310
320
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
311
321
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
322
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
323
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
312
324
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
313
325
  * RPC read fails.
314
326
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -342,7 +354,6 @@ class MorphoMidnight {
342
354
  * offers plus the fallback.
343
355
  * @throws {MidnightContractReceiverError} when `referralFeeRecipient` is a Midnight protocol
344
356
  * contract or a market token contract with a positive referral fee.
345
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
346
357
  * @example
347
358
  * ```ts
348
359
  * const output = midnight.takeLend({
@@ -357,6 +368,8 @@ class MorphoMidnight {
357
368
  */
358
369
  takeLend(params) {
359
370
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
371
+ // Reject the zero account before preparing anything for it.
372
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
360
373
  validateTakeDeadlineWindow(params.deadline);
361
374
  const market = params.marketData.params;
362
375
  const rawParams = {
@@ -391,7 +404,7 @@ class MorphoMidnight {
391
404
  ? params.target.assets
392
405
  : params.target.maxBuyerAssets;
393
406
  return {
394
- getRequirements: async (requirementsParams) => {
407
+ getRequirements: async (_requirementsParams) => {
395
408
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
396
409
  viemClient: this.client.viemClient,
397
410
  chainId: this.chainId,
@@ -399,7 +412,6 @@ class MorphoMidnight {
399
412
  owner: params.accountAddress,
400
413
  spender: tx.to,
401
414
  amount: pulledAssets,
402
- approvalAmount: requirementsParams?.approvalAmount,
403
415
  });
404
416
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
405
417
  return [...approvals, ...authorization];
@@ -434,11 +446,14 @@ class MorphoMidnight {
434
446
  * Midnight protocol and market token contracts are rejected.
435
447
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
436
448
  * @param params.deadline - Bounded bundle execution deadline timestamp.
437
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
449
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
450
+ * proceeds; on an assets target it is added on top of `target.assets`.
438
451
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
439
452
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
440
453
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
441
454
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
455
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
456
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
442
457
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
443
458
  * RPC read fails.
444
459
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -500,6 +515,8 @@ class MorphoMidnight {
500
515
  */
501
516
  takeBorrow(params) {
502
517
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
518
+ // Reject the zero account before preparing anything for it.
519
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
503
520
  validateTakeDeadlineWindow(params.deadline);
504
521
  const rawParams = {
505
522
  chainId: this.chainId,
@@ -574,11 +591,14 @@ class MorphoMidnight {
574
591
  * Midnight protocol and market token contracts are rejected.
575
592
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
576
593
  * @param params.deadline - Bundle execution deadline timestamp.
577
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
594
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
595
+ * proceeds; on an assets target it is added on top of `target.assets`.
578
596
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
579
597
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
580
598
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
581
599
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
600
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
601
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
582
602
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
583
603
  * RPC read fails.
584
604
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
@@ -622,6 +642,8 @@ class MorphoMidnight {
622
642
  */
623
643
  takeWithdraw(params) {
624
644
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
645
+ // Reject the zero account before preparing anything for it.
646
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
625
647
  validateTakeDeadlineWindow(params.deadline);
626
648
  const rawParams = {
627
649
  chainId: this.chainId,
@@ -689,11 +711,14 @@ class MorphoMidnight {
689
711
  * Midnight protocol and market token contracts are rejected.
690
712
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
691
713
  * @param params.deadline - Bounded bundle execution deadline timestamp.
692
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
714
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
715
+ * proceeds; on an assets target it is added on top of `target.assets`.
693
716
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
694
717
  * @returns Lazy collateral approvals and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
695
718
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
696
719
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
720
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
721
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
697
722
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
698
723
  * RPC read fails.
699
724
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -734,7 +759,6 @@ class MorphoMidnight {
734
759
  * withdrawal.
735
760
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
736
761
  * its bounds cannot hold at any fill.
737
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
738
762
  * @example
739
763
  * ```ts
740
764
  * const output = midnight.supplyCollateralTakeBorrow({
@@ -751,6 +775,8 @@ class MorphoMidnight {
751
775
  */
752
776
  supplyCollateralTakeBorrow(params) {
753
777
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
778
+ // Reject the zero account before preparing anything for it.
779
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
754
780
  validateTakeDeadlineWindow(params.deadline);
755
781
  const market = params.marketData.params;
756
782
  const rawParams = {
@@ -819,7 +845,7 @@ class MorphoMidnight {
819
845
  collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
820
846
  }
821
847
  return {
822
- getRequirements: async (requirementsParams) => {
848
+ getRequirements: async (_requirementsParams) => {
823
849
  const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => (0, index_js_2.getMidnightApprovalRequirements)({
824
850
  viemClient: this.client.viemClient,
825
851
  chainId: this.chainId,
@@ -827,7 +853,6 @@ class MorphoMidnight {
827
853
  owner: params.accountAddress,
828
854
  spender: tx.to,
829
855
  amount,
830
- approvalAmount: requirementsParams?.approvalAmount,
831
856
  })));
832
857
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
833
858
  return [...approvals.flat(), ...authorization];
@@ -879,6 +904,8 @@ class MorphoMidnight {
879
904
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
880
905
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
881
906
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
907
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
908
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
882
909
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
883
910
  * RPC read fails.
884
911
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -923,7 +950,6 @@ class MorphoMidnight {
923
950
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
924
951
  * contract or a market token contract, or when `referralFeeRecipient` is either with a
925
952
  * positive referral fee.
926
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
927
953
  * @example
928
954
  * ```ts
929
955
  * const output = midnight.takeRepayWithdrawCollateral({
@@ -942,6 +968,8 @@ class MorphoMidnight {
942
968
  */
943
969
  takeRepayWithdrawCollateral(params) {
944
970
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
971
+ // Reject the zero account before preparing anything for it.
972
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
945
973
  validateTakeDeadlineWindow(params.deadline);
946
974
  const market = params.marketData.params;
947
975
  const rawParams = {
@@ -1028,7 +1056,7 @@ class MorphoMidnight {
1028
1056
  ? params.target.assets
1029
1057
  : params.target.maxBuyerAssets;
1030
1058
  return {
1031
- getRequirements: async (requirementsParams) => {
1059
+ getRequirements: async (_requirementsParams) => {
1032
1060
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
1033
1061
  viemClient: this.client.viemClient,
1034
1062
  chainId: this.chainId,
@@ -1036,7 +1064,6 @@ class MorphoMidnight {
1036
1064
  owner: params.accountAddress,
1037
1065
  spender: tx.to,
1038
1066
  amount: pulledAssets,
1039
- approvalAmount: requirementsParams?.approvalAmount,
1040
1067
  });
1041
1068
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
1042
1069
  return [...approvals, ...authorization];
@@ -1048,23 +1075,30 @@ class MorphoMidnight {
1048
1075
  * Prepares a direct collateral supply using a caller-provided market snapshot.
1049
1076
  *
1050
1077
  * @param params - Supplier, market snapshot, collateral amount, reserve, and optional collateral index.
1051
- * @param params.accountAddress - Account receiving the supplied collateral position.
1078
+ * @param params.accountAddress - Account receiving the supplied collateral position. It must send
1079
+ * the transaction: Midnight pulls the collateral from `msg.sender` and only lets the position owner
1080
+ * or its operators supply for it, and the approval requirements are resolved for this account.
1052
1081
  * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
1053
1082
  * @param params.collateralAssets - Collateral assets supplied in this transaction.
1054
1083
  * @param params.reservedCollateralAssets - Existing collateral reserved by other open maker groups.
1055
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
1084
+ * Only raises the approval requirement so those groups keep their allowance; the transaction
1085
+ * transfers only `collateralAssets`.
1086
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`. Indexes follow the
1087
+ * market's collateral parameters, which Midnight sorts by token address, not the order they were
1088
+ * listed in when the market was built; check `marketData.getCollateralByIndex(index).token`.
1056
1089
  * @returns Lazy token-approval requirements and a synchronous transaction builder.
1057
1090
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1058
1091
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
1092
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1059
1093
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1060
1094
  * RPC read fails.
1061
1095
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
1062
1096
  * @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
1063
1097
  * @throws {InputExceedsMaxError} when `collateralAssets` exceeds `uint128`.
1064
1098
  * @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
1065
- * @throws {MidnightZeroOnBehalfError} from `buildTx()` when `accountAddress` is the zero address.
1099
+ * @throws {MidnightZeroOnBehalfError} from `getRequirements()` and `buildTx()` when `accountAddress`
1100
+ * is the zero address.
1066
1101
  * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
1067
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled collateral assets.
1068
1102
  * @example
1069
1103
  * ```ts
1070
1104
  * const output = midnight.supplyCollateral({
@@ -1076,6 +1110,8 @@ class MorphoMidnight {
1076
1110
  */
1077
1111
  supplyCollateral(params) {
1078
1112
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1113
+ // Reject a malformed account here; the builder rejects the zero account.
1114
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("accountAddress", params.accountAddress);
1079
1115
  validateMarketData(params.marketData, this.chainId);
1080
1116
  assertPositiveAmount("collateralAssets", params.collateralAssets);
1081
1117
  (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("collateralAssets", params.collateralAssets);
@@ -1085,15 +1121,20 @@ class MorphoMidnight {
1085
1121
  const collateral = market.getCollateralByIndex(collateralIndex);
1086
1122
  const midnight = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnight");
1087
1123
  return {
1088
- getRequirements: async (requirementsParams) => await (0, index_js_2.getMidnightApprovalRequirements)({
1089
- viemClient: this.client.viemClient,
1090
- chainId: this.chainId,
1091
- token: collateral.token,
1092
- owner: params.accountAddress,
1093
- spender: midnight,
1094
- amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1095
- approvalAmount: requirementsParams?.approvalAmount,
1096
- }),
1124
+ getRequirements: async (_requirementsParams) => {
1125
+ // Match buildTx(): the requirement helper would report a zero owner with another class.
1126
+ if ((0, viem_1.isAddressEqual)(params.accountAddress, viem_1.zeroAddress)) {
1127
+ throw new index_js_4.MidnightZeroOnBehalfError("onBehalf");
1128
+ }
1129
+ return await (0, index_js_2.getMidnightApprovalRequirements)({
1130
+ viemClient: this.client.viemClient,
1131
+ chainId: this.chainId,
1132
+ token: collateral.token,
1133
+ owner: params.accountAddress,
1134
+ spender: midnight,
1135
+ amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1136
+ });
1137
+ },
1097
1138
  buildTx: () => (0, index_js_1.midnightSupplyCollateral)({
1098
1139
  chainId: this.chainId,
1099
1140
  market: market.params,
@@ -1124,9 +1165,12 @@ class MorphoMidnight {
1124
1165
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
1125
1166
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1126
1167
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1168
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1169
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1127
1170
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1128
1171
  * RPC read fails.
1129
1172
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1173
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1130
1174
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1131
1175
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1132
1176
  * @throws {NonPositiveInputError} when `loanAssets` is non-positive.
@@ -1157,7 +1201,6 @@ class MorphoMidnight {
1157
1201
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1158
1202
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1159
1203
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1160
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1161
1204
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1162
1205
  * @example
1163
1206
  * ```ts
@@ -1173,9 +1216,11 @@ class MorphoMidnight {
1173
1216
  */
1174
1217
  async makeLend(params) {
1175
1218
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1219
+ // Reject the zero account before preparing anything for it.
1220
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1176
1221
  // Fails before any API read or build when the deadline has already passed.
1177
1222
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1178
- const tree = midnight_sdk_1.Tree.from(params.offers);
1223
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1179
1224
  rejectReduceOnlyOffers(tree.offers);
1180
1225
  return this.prepareLendOffers({ ...params, offers: tree });
1181
1226
  }
@@ -1195,9 +1240,12 @@ class MorphoMidnight {
1195
1240
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1196
1241
  * @returns Prepared group metadata, lazy authorization requirements, and a synchronous transaction builder.
1197
1242
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
1243
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
1244
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1198
1245
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1199
1246
  * RPC read fails.
1200
1247
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1248
+ * @throws {InvalidMidnightOfferGroupError} when a priceV1/rateV1 `Tree.create` request has explicit groups that break `OfferUtils.validateOfferGroup` rules.
1201
1249
  * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1202
1250
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1203
1251
  * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
@@ -1239,9 +1287,11 @@ class MorphoMidnight {
1239
1287
  */
1240
1288
  async makeBorrow(params) {
1241
1289
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1290
+ // Reject the zero account before preparing anything for it.
1291
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1242
1292
  // Fails before any API read or build when the deadline has already passed.
1243
1293
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1244
- const tree = midnight_sdk_1.Tree.from(params.offers);
1294
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1245
1295
  rejectReduceOnlyOffers(tree.offers);
1246
1296
  return this.prepareBorrowOffers({ ...params, offers: tree });
1247
1297
  }
@@ -1249,9 +1299,11 @@ class MorphoMidnight {
1249
1299
  * Prepares lend-side offers for publication.
1250
1300
  */
1251
1301
  async prepareLendOffers(params) {
1302
+ // Reject a malformed address before viem compares offer markets with it.
1303
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("loanToken", params.loanToken);
1252
1304
  assertPositiveAmount("loanAssets", params.loanAssets);
1253
1305
  assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
1254
- const tree = midnight_sdk_1.Tree.from(params.offers);
1306
+ const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1255
1307
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
1256
1308
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
1257
1309
  const data = await getOffersDataInternal({
@@ -1286,7 +1338,7 @@ class MorphoMidnight {
1286
1338
  groups: data.groups,
1287
1339
  root: data.tree.root,
1288
1340
  ratifierType: data.ratifierType,
1289
- getRequirements: async (requirementsParams) => {
1341
+ getRequirements: async (_requirementsParams) => {
1290
1342
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
1291
1343
  viemClient: this.client.viemClient,
1292
1344
  chainId: this.chainId,
@@ -1294,7 +1346,6 @@ class MorphoMidnight {
1294
1346
  owner: data.accountAddress,
1295
1347
  spender: midnight,
1296
1348
  amount: params.loanAssets + (params.reservedLoanAssets ?? 0n),
1297
- approvalAmount: requirementsParams?.approvalAmount,
1298
1349
  });
1299
1350
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1300
1351
  return [...approvals, ...authorization];
@@ -1341,6 +1392,8 @@ class MorphoMidnight {
1341
1392
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1342
1393
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
1343
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.
1344
1397
  * @throws {viem.BaseError} when the `eth_chainId` request, a Blue market RPC read, or a
1345
1398
  * requirement RPC read fails.
1346
1399
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2`, `midnightBlueBuyCallbackFactory`, `midnight`, `blue` or V1 ratifier deployment.
@@ -1352,6 +1405,7 @@ class MorphoMidnight {
1352
1405
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1353
1406
  * @throws {NativeAmountOnNonWNativeAssetError} when `blueMarket.loanToken` is not wNative.
1354
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.
1355
1409
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1356
1410
  * (not thrown when `validation` is `false`).
1357
1411
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1381,7 +1435,6 @@ class MorphoMidnight {
1381
1435
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1382
1436
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
1383
1437
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1384
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `assetsToPark`.
1385
1438
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1386
1439
  * @example
1387
1440
  * ```ts
@@ -1401,15 +1454,21 @@ class MorphoMidnight {
1401
1454
  * ```
1402
1455
  */
1403
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);
1404
1461
  assertPositiveAmount("assetsToPark", params.assetsToPark);
1405
1462
  (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("assetsToPark", params.assetsToPark);
1406
- 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));
1407
1464
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
1408
1465
  rejectReduceOnlyOffers(tree.offers);
1409
1466
  await (0, validateClientChainId_js_1.validateClientChainId)(this.client.viemClient, this.chainId);
1410
1467
  // Fails before any API read or build when the deadline has already passed.
1411
1468
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1412
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));
1413
1472
  const blueMarketId = blue_sdk_1.MarketUtils.getMarketId(params.blueMarket);
1414
1473
  const callback = (0, callback_js_1.getMidnightBlueBuyCallbackAddress)({
1415
1474
  chainId: this.chainId,
@@ -1436,7 +1495,6 @@ class MorphoMidnight {
1436
1495
  assets: params.assetsToPark,
1437
1496
  });
1438
1497
  }
1439
- const callbackData = (0, callback_js_1.getMidnightBlueBuyCallbackData)(params.blueMarket);
1440
1498
  data.tree.offers.forEach((offer, index) => {
1441
1499
  const offerMarket = (0, publication_js_1.offerMarketParams)(offer);
1442
1500
  if (!(0, viem_1.isAddressEqual)(offerMarket.loanToken, params.blueMarket.loanToken)) {
@@ -1483,7 +1541,7 @@ class MorphoMidnight {
1483
1541
  groups: data.groups,
1484
1542
  root: data.tree.root,
1485
1543
  ratifierType: data.ratifierType,
1486
- getRequirements: async (requirementsParams) => {
1544
+ getRequirements: async (_requirementsParams) => {
1487
1545
  const approvals = await (0, index_js_2.getMidnightApprovalRequirements)({
1488
1546
  viemClient: this.client.viemClient,
1489
1547
  chainId: this.chainId,
@@ -1491,7 +1549,6 @@ class MorphoMidnight {
1491
1549
  owner: data.accountAddress,
1492
1550
  spender: (0, morpho_ts_1.getChainAddress)(this.chainId, "midnightBundlesV2"),
1493
1551
  amount: params.assetsToPark,
1494
- approvalAmount: requirementsParams?.approvalAmount,
1495
1552
  });
1496
1553
  const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1497
1554
  return [...approvals, ...authorization];
@@ -1503,7 +1560,7 @@ class MorphoMidnight {
1503
1560
  * Prepares borrow-side offers for publication.
1504
1561
  */
1505
1562
  async prepareBorrowOffers(params) {
1506
- 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));
1507
1564
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1508
1565
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
1509
1566
  const data = await getOffersDataInternal({
@@ -1549,9 +1606,12 @@ class MorphoMidnight {
1549
1606
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1550
1607
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1551
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.
1552
1611
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1553
1612
  * RPC read fails.
1554
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.
1555
1615
  * @throws {MidnightOfferSideMismatchError} when an offer is not a sell offer (`buy = false`).
1556
1616
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1557
1617
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1596,9 +1656,11 @@ class MorphoMidnight {
1596
1656
  */
1597
1657
  async makeWithdraw(params) {
1598
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);
1599
1661
  // Fails before any API read or build when the deadline has already passed.
1600
1662
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1601
- 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));
1602
1664
  // Reject the wrong exit intent before calling the mempool validation API.
1603
1665
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1604
1666
  for (const [index, offer] of tree.offers.entries()) {
@@ -1631,9 +1693,12 @@ class MorphoMidnight {
1631
1693
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
1632
1694
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1633
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.
1634
1698
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1635
1699
  * RPC read fails.
1636
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.
1637
1702
  * @throws {MidnightOfferSideMismatchError} when an offer is not a buy offer (`buy = true`).
1638
1703
  * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1639
1704
  * @throws {MidnightOfferCallbackNotSupportedError} when an offer has a nonzero callback.
@@ -1665,7 +1730,6 @@ class MorphoMidnight {
1665
1730
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1666
1731
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1667
1732
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1668
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1669
1733
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1670
1734
  * @example
1671
1735
  * ```ts
@@ -1682,9 +1746,11 @@ class MorphoMidnight {
1682
1746
  */
1683
1747
  async makeRepay(params) {
1684
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);
1685
1751
  // Fails before any API read or build when the deadline has already passed.
1686
1752
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1687
- 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));
1688
1754
  // Reject the wrong exit intent before calling the mempool validation API.
1689
1755
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
1690
1756
  for (const [index, offer] of tree.offers.entries()) {
@@ -1718,6 +1784,8 @@ class MorphoMidnight {
1718
1784
  * required for the full pulled amount.
1719
1785
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1720
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.
1721
1789
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1722
1790
  * RPC read fails.
1723
1791
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
@@ -1730,6 +1798,7 @@ class MorphoMidnight {
1730
1798
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1731
1799
  * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
1732
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.
1733
1802
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1734
1803
  * (not thrown when `validation` is `false`).
1735
1804
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
@@ -1758,7 +1827,6 @@ class MorphoMidnight {
1758
1827
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1759
1828
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1760
1829
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1761
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
1762
1830
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1763
1831
  * @example
1764
1832
  * ```ts
@@ -1775,12 +1843,14 @@ class MorphoMidnight {
1775
1843
  */
1776
1844
  async supplyCollateralMakeBorrow(params) {
1777
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);
1778
1848
  // Fails before any API read or build when the deadline has already passed.
1779
1849
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1780
1850
  const market = params.collateral.market instanceof midnight_sdk_1.MarketParams
1781
1851
  ? params.collateral.market
1782
1852
  : midnight_sdk_1.MarketParams.from(params.collateral.market);
1783
- 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));
1784
1854
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1785
1855
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
1786
1856
  rejectReduceOnlyOffers(tree.offers);
@@ -1790,9 +1860,9 @@ class MorphoMidnight {
1790
1860
  params: { ...params, offers: tree },
1791
1861
  marketCreationTime: "now",
1792
1862
  });
1793
- const marketId = midnight_sdk_1.MarketUtils.toId(market);
1863
+ const marketId = (0, encodeMidnightCalldata_js_1.encodeMidnightMarketId)(market);
1794
1864
  for (const offer of data.tree.offers) {
1795
- const offerMarketId = midnight_sdk_1.MarketUtils.toId(offer.market);
1865
+ const offerMarketId = (0, encodeMidnightCalldata_js_1.encodeMidnightMarketId)(offer.market);
1796
1866
  if (offerMarketId.toLowerCase() !== marketId.toLowerCase()) {
1797
1867
  throw new index_js_4.MarketIdMismatchError(offerMarketId, marketId);
1798
1868
  }
@@ -1825,7 +1895,7 @@ class MorphoMidnight {
1825
1895
  groups: data.groups,
1826
1896
  root: data.tree.root,
1827
1897
  ratifierType: data.ratifierType,
1828
- getRequirements: async (requirementsParams) => {
1898
+ getRequirements: async (_requirementsParams) => {
1829
1899
  const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => (0, index_js_2.getMidnightApprovalRequirements)({
1830
1900
  viemClient: this.client.viemClient,
1831
1901
  chainId: this.chainId,
@@ -1833,7 +1903,6 @@ class MorphoMidnight {
1833
1903
  owner: data.accountAddress,
1834
1904
  spender: midnightBundlesV2,
1835
1905
  amount,
1836
- approvalAmount: requirementsParams?.approvalAmount,
1837
1906
  })));
1838
1907
  return [
1839
1908
  ...approvals.flat(),
@@ -1847,7 +1916,9 @@ class MorphoMidnight {
1847
1916
  * Prepares redemption of accrued Midnight credit from a position snapshot.
1848
1917
  *
1849
1918
  * @param params - Position owner, accrued position, optional unit amount, and receiver.
1850
- * @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.
1851
1922
  * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`.
1852
1923
  * @param params.receiver - Optional credit receiver; defaults to the position owner.
1853
1924
  * Midnight protocol and market token contracts are rejected.
@@ -1860,6 +1931,7 @@ class MorphoMidnight {
1860
1931
  * is left. Redeem again after maturity to empty the position.
1861
1932
  * @returns No requirements and a synchronous redemption transaction builder.
1862
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.
1863
1935
  * @throws {MidnightMarketAddressMismatchError} when the position market targets another Midnight deployment.
1864
1936
  * @throws {MissingAccrualPositionError} when no position snapshot is supplied.
1865
1937
  * @throws {AccrualPositionUserMismatchError} when the position snapshot belongs to another account.
@@ -1887,9 +1959,13 @@ class MorphoMidnight {
1887
1959
  */
1888
1960
  redeem(params) {
1889
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);
1890
1964
  if (!params.positionData) {
1891
1965
  throw new index_js_4.MissingAccrualPositionError();
1892
1966
  }
1967
+ if (params.positionData.user != null)
1968
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)("positionData.user", params.positionData.user);
1893
1969
  if (params.positionData.user == null ||
1894
1970
  !(0, viem_1.isAddressEqual)(params.positionData.user, params.accountAddress)) {
1895
1971
  throw new index_js_4.AccrualPositionUserMismatchError(params.positionData.user ?? "unbound", params.accountAddress);
@@ -1950,7 +2026,7 @@ class MorphoMidnight {
1950
2026
  * scaled by `ORACLE_PRICE_SCALE`. An empty array is safe only when
1951
2027
  * `collateralWithdrawals` is empty or the conservative post-operation debt is zero: a `full`
1952
2028
  * repay, or `repay.assets` covering `positionData.debt`.
1953
- * @param params.repay - `{ type: "assets", assets }` (`0n` to only withdraw) or `{ type: "full", maxBuyerAssets }`; a loan-token approval to `MidnightBundlesV2` is required when the allowance is below the pulled amount — unlimited (`maxUint256`) by default, or `approvalAmount` when passed to `getRequirements()` — and any unused part is refunded.
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.
1954
2030
  * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
1955
2031
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
1956
2032
  * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
@@ -1966,6 +2042,8 @@ class MorphoMidnight {
1966
2042
  * @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
1967
2043
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1968
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.
1969
2047
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1970
2048
  * RPC read fails.
1971
2049
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
@@ -1990,7 +2068,6 @@ class MorphoMidnight {
1990
2068
  * during this method call, before the lazy output is returned.
1991
2069
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
1992
2070
  * contract or a market token contract.
1993
- * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
1994
2071
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1995
2072
  * @example
1996
2073
  * ```ts
@@ -2008,6 +2085,8 @@ class MorphoMidnight {
2008
2085
  */
2009
2086
  repayWithdrawCollateral(params) {
2010
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);
2011
2090
  // Fails before any API read or build when the deadline has already passed.
2012
2091
  (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
2013
2092
  const market = params.marketData.params;
@@ -2085,7 +2164,7 @@ class MorphoMidnight {
2085
2164
  ? params.repay.assets
2086
2165
  : params.repay.maxBuyerAssets;
2087
2166
  return {
2088
- getRequirements: async (requirementsParams) => {
2167
+ getRequirements: async (_requirementsParams) => {
2089
2168
  const approvals = pulledAssets > 0n
2090
2169
  ? await (0, index_js_2.getMidnightApprovalRequirements)({
2091
2170
  viemClient: this.client.viemClient,
@@ -2094,7 +2173,6 @@ class MorphoMidnight {
2094
2173
  owner: params.accountAddress,
2095
2174
  spender: tx.to,
2096
2175
  amount: pulledAssets,
2097
- approvalAmount: requirementsParams?.approvalAmount,
2098
2176
  })
2099
2177
  : [];
2100
2178
  const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
@@ -2124,6 +2202,7 @@ class MorphoMidnight {
2124
2202
  * @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
2125
2203
  * @throws {ChainIdMismatchError} when the client targets another chain, or from
2126
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.
2127
2206
  * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
2128
2207
  * RPC read fails.
2129
2208
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.