@morpho-org/morpho-sdk 7.0.0 → 8.1.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 (192) hide show
  1. package/MIGRATION-v6-to-v7.md +6 -0
  2. package/MIGRATION-v7-to-v8.md +290 -0
  3. package/README.md +11 -6
  4. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
  5. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
  6. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +17 -71
  7. package/lib/cjs/actions/midnight/cancelAndMake.js +41 -29
  8. package/lib/cjs/actions/midnight/redeem.d.ts +8 -1
  9. package/lib/cjs/actions/midnight/redeem.js +18 -1
  10. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
  11. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +24 -2
  12. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +1 -0
  13. package/lib/cjs/actions/midnight/supplyCollateral.js +3 -0
  14. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
  15. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +49 -14
  16. package/lib/cjs/actions/midnight/takeBorrow.d.ts +18 -5
  17. package/lib/cjs/actions/midnight/takeBorrow.js +44 -12
  18. package/lib/cjs/actions/midnight/takeLend.d.ts +10 -5
  19. package/lib/cjs/actions/midnight/takeLend.js +27 -9
  20. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
  21. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +51 -27
  22. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +14 -5
  23. package/lib/cjs/actions/midnight/takeWithdraw.js +40 -9
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
  25. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +11 -6
  26. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
  27. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +17 -6
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
  31. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
  32. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
  33. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
  34. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
  35. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
  36. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
  37. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
  38. package/lib/cjs/actions/requirements/validateClientChainId.d.ts +26 -0
  39. package/lib/cjs/actions/requirements/validateClientChainId.js +34 -0
  40. package/lib/cjs/blue/errors.d.ts +1 -1
  41. package/lib/cjs/blue/errors.js +3 -1
  42. package/lib/cjs/blue/types.d.ts +1 -1
  43. package/lib/cjs/blue/utils.d.ts +1 -1
  44. package/lib/cjs/blue/utils.js +5 -1
  45. package/lib/cjs/entities/blue/blue.d.ts +109 -27
  46. package/lib/cjs/entities/blue/blue.js +103 -28
  47. package/lib/cjs/entities/index.d.ts +1 -1
  48. package/lib/cjs/entities/midnight/deadline.d.ts +15 -0
  49. package/lib/cjs/entities/midnight/deadline.js +24 -0
  50. package/lib/cjs/entities/midnight/midnight.d.ts +432 -74
  51. package/lib/cjs/entities/midnight/midnight.js +869 -188
  52. package/lib/cjs/entities/midnight/publication.d.ts +134 -0
  53. package/lib/cjs/entities/midnight/publication.js +404 -0
  54. package/lib/cjs/entities/midnight/types.d.ts +26 -5
  55. package/lib/cjs/entities/requirements/assertContractCode.d.ts +49 -0
  56. package/lib/cjs/entities/requirements/assertContractCode.js +79 -0
  57. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
  58. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +45 -18
  59. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
  60. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.js +5 -2
  61. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
  62. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  63. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +63 -11
  64. package/lib/cjs/entities/vaultV1/vaultV1.js +83 -49
  65. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +54 -12
  66. package/lib/cjs/entities/vaultV2/vaultV2.js +86 -55
  67. package/lib/cjs/errors.d.ts +1 -1
  68. package/lib/cjs/errors.js +4 -2
  69. package/lib/cjs/helpers/constant.d.ts +5 -0
  70. package/lib/cjs/helpers/constant.js +6 -1
  71. package/lib/cjs/helpers/index.d.ts +1 -1
  72. package/lib/cjs/helpers/index.js +2 -1
  73. package/lib/cjs/helpers/validate.d.ts +163 -8
  74. package/lib/cjs/helpers/validate.js +179 -8
  75. package/lib/cjs/helpers/validateMidnightBounds.d.ts +47 -0
  76. package/lib/cjs/helpers/validateMidnightBounds.js +79 -0
  77. package/lib/cjs/helpers/validateMidnightPublication.d.ts +12 -0
  78. package/lib/cjs/helpers/validateMidnightPublication.js +144 -0
  79. package/lib/cjs/helpers/validateMidnightReceiver.d.ts +29 -0
  80. package/lib/cjs/helpers/validateMidnightReceiver.js +84 -0
  81. package/lib/cjs/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
  82. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +231 -0
  83. package/lib/cjs/index.d.ts +1 -0
  84. package/lib/cjs/index.js +3 -0
  85. package/lib/cjs/types/action.d.ts +102 -1
  86. package/lib/cjs/types/action.js +102 -1
  87. package/lib/cjs/types/error.d.ts +197 -4
  88. package/lib/cjs/types/error.js +265 -5
  89. package/lib/cjs/types/index.d.ts +1 -0
  90. package/lib/cjs/types/index.js +1 -0
  91. package/lib/cjs/types/midnightCancelAndMake.d.ts +70 -0
  92. package/lib/cjs/types/midnightCancelAndMake.js +2 -0
  93. package/lib/cjs/types/midnightPublicationError.d.ts +332 -0
  94. package/lib/cjs/types/midnightPublicationError.js +376 -0
  95. package/lib/cjs/types.d.ts +1 -1
  96. package/lib/cjs/utils.d.ts +2 -1
  97. package/lib/cjs/utils.js +8 -2
  98. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
  99. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
  100. package/lib/esm/actions/midnight/cancelAndMake.d.ts +17 -71
  101. package/lib/esm/actions/midnight/cancelAndMake.js +42 -30
  102. package/lib/esm/actions/midnight/redeem.d.ts +8 -1
  103. package/lib/esm/actions/midnight/redeem.js +18 -1
  104. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
  105. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +24 -2
  106. package/lib/esm/actions/midnight/supplyCollateral.d.ts +1 -0
  107. package/lib/esm/actions/midnight/supplyCollateral.js +3 -0
  108. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
  109. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +52 -17
  110. package/lib/esm/actions/midnight/takeBorrow.d.ts +18 -5
  111. package/lib/esm/actions/midnight/takeBorrow.js +47 -15
  112. package/lib/esm/actions/midnight/takeLend.d.ts +10 -5
  113. package/lib/esm/actions/midnight/takeLend.js +27 -9
  114. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
  115. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +52 -28
  116. package/lib/esm/actions/midnight/takeWithdraw.d.ts +14 -5
  117. package/lib/esm/actions/midnight/takeWithdraw.js +41 -10
  118. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
  119. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +13 -8
  120. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
  121. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
  122. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
  123. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +17 -6
  124. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
  125. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
  126. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
  127. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
  128. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
  129. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
  130. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
  131. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
  132. package/lib/esm/actions/requirements/validateClientChainId.d.ts +26 -0
  133. package/lib/esm/actions/requirements/validateClientChainId.js +30 -0
  134. package/lib/esm/blue/errors.d.ts +1 -1
  135. package/lib/esm/blue/errors.js +1 -1
  136. package/lib/esm/blue/types.d.ts +1 -1
  137. package/lib/esm/blue/utils.d.ts +1 -1
  138. package/lib/esm/blue/utils.js +1 -1
  139. package/lib/esm/entities/blue/blue.d.ts +109 -27
  140. package/lib/esm/entities/blue/blue.js +104 -29
  141. package/lib/esm/entities/index.d.ts +1 -1
  142. package/lib/esm/entities/midnight/deadline.d.ts +15 -0
  143. package/lib/esm/entities/midnight/deadline.js +20 -0
  144. package/lib/esm/entities/midnight/midnight.d.ts +432 -74
  145. package/lib/esm/entities/midnight/midnight.js +870 -189
  146. package/lib/esm/entities/midnight/publication.d.ts +134 -0
  147. package/lib/esm/entities/midnight/publication.js +397 -0
  148. package/lib/esm/entities/midnight/types.d.ts +26 -5
  149. package/lib/esm/entities/requirements/assertContractCode.d.ts +49 -0
  150. package/lib/esm/entities/requirements/assertContractCode.js +74 -0
  151. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
  152. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +47 -20
  153. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
  154. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.js +5 -2
  155. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
  156. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  157. package/lib/esm/entities/vaultV1/vaultV1.d.ts +63 -11
  158. package/lib/esm/entities/vaultV1/vaultV1.js +85 -51
  159. package/lib/esm/entities/vaultV2/vaultV2.d.ts +54 -12
  160. package/lib/esm/entities/vaultV2/vaultV2.js +88 -57
  161. package/lib/esm/errors.d.ts +1 -1
  162. package/lib/esm/errors.js +1 -1
  163. package/lib/esm/helpers/constant.d.ts +5 -0
  164. package/lib/esm/helpers/constant.js +5 -0
  165. package/lib/esm/helpers/index.d.ts +1 -1
  166. package/lib/esm/helpers/index.js +1 -1
  167. package/lib/esm/helpers/validate.d.ts +163 -8
  168. package/lib/esm/helpers/validate.js +177 -7
  169. package/lib/esm/helpers/validateMidnightBounds.d.ts +47 -0
  170. package/lib/esm/helpers/validateMidnightBounds.js +72 -0
  171. package/lib/esm/helpers/validateMidnightPublication.d.ts +12 -0
  172. package/lib/esm/helpers/validateMidnightPublication.js +139 -0
  173. package/lib/esm/helpers/validateMidnightReceiver.d.ts +29 -0
  174. package/lib/esm/helpers/validateMidnightReceiver.js +80 -0
  175. package/lib/esm/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
  176. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +226 -0
  177. package/lib/esm/index.d.ts +1 -0
  178. package/lib/esm/index.js +1 -0
  179. package/lib/esm/types/action.d.ts +102 -1
  180. package/lib/esm/types/action.js +102 -1
  181. package/lib/esm/types/error.d.ts +197 -4
  182. package/lib/esm/types/error.js +253 -2
  183. package/lib/esm/types/index.d.ts +1 -0
  184. package/lib/esm/types/index.js +1 -0
  185. package/lib/esm/types/midnightCancelAndMake.d.ts +70 -0
  186. package/lib/esm/types/midnightCancelAndMake.js +1 -0
  187. package/lib/esm/types/midnightPublicationError.d.ts +332 -0
  188. package/lib/esm/types/midnightPublicationError.js +359 -0
  189. package/lib/esm/types.d.ts +1 -1
  190. package/lib/esm/utils.d.ts +2 -1
  191. package/lib/esm/utils.js +2 -1
  192. package/package.json +10 -10
@@ -6,7 +6,9 @@ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
7
  const index_js_1 = require("../../helpers/index.js");
8
8
  const validate_js_1 = require("../../helpers/validate.js");
9
+ const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
9
10
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
11
+ const validateMidnightPublication_js_1 = require("../../helpers/validateMidnightPublication.js");
10
12
  const index_js_2 = require("../../types/index.js");
11
13
  /** Blue market argument for `MidnightBundlesV2` calls that park no loan assets. */
12
14
  const emptyBlueMarket = {
@@ -33,9 +35,13 @@ const emptyMidnightMarket = {
33
35
  * `BlueBuyCallback` or supply collateral, activate `root`, and publish `payload`.
34
36
  * Without `publication`, it only cancels groups (`cancelOffers` uses this).
35
37
  * Execution reverts as a whole if any group's consumption exceeds its `maxConsumed` ceiling.
38
+ * The builder snapshots every input field once before validation and encoding. It checks root,
39
+ * groups, cancellation groups, Blue callback salt, and root-signature `r`/`s` as 32-byte hex and
40
+ * checks payload hex shape and size, but cannot decode it; callers must supply a mutually
41
+ * consistent root, group list, and payload.
36
42
  *
37
- * The contract does not check that `payload` matches `root`; callers must derive both from the
38
- * same tree. Prefer `client.morpho.midnight(chainId).makeLend(...)`,
43
+ * The contract does not check that `payload` matches `root`. Prefer
44
+ * `client.morpho.midnight(chainId).makeLend(...)`,
39
45
  * `makeBorrow(...)`, `supplyCollateralMakeBorrow(...)`, or `supplyBlueMakeLend(...)`, which derive
40
46
  * the tree data and resolve the requirements for each flow; `supplyBlueMakeLend` also runs the
41
47
  * Blue parking checks (callback, callbackData, empty-market and zero-share guards) that this builder
@@ -43,7 +49,7 @@ const emptyMidnightMarket = {
43
49
  *
44
50
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
45
51
  * @param params.cancellations - Offer groups to cancel and their consumption ceilings.
46
- * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry.
52
+ * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry. Not checked against the clock; validate freshness before building.
47
53
  * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
48
54
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of the
49
55
  * maximum wNative amount this call can pull, but not more. Any wrapped native not pulled stays in
@@ -56,7 +62,9 @@ const emptyMidnightMarket = {
56
62
  * @param params.publication.root - Offer tree root to activate.
57
63
  * @param params.publication.groups - Distinct offer groups contained in the root.
58
64
  * @param params.publication.payload - Encoded offer payload published to the Midnight log.
59
- * @param params.publication.rootSignature - Optional delegated root-activation signature; omitted, all fields are zero.
65
+ * @param params.publication.rootSignature - Optional builder-only delegated root-activation
66
+ * signature. Maker entity methods never set it; they encode zero signature fields and rely on
67
+ * MidnightBundlesV2 authorization.
60
68
  * @param params.publication.rootSignature.height - Tree height committed by the signature.
61
69
  * @param params.publication.rootSignature.nonce - Ratifier signature nonce.
62
70
  * @param params.publication.rootSignature.deadline - Signature deadline timestamp, independent of the bundle `deadline`.
@@ -77,11 +85,14 @@ const emptyMidnightMarket = {
77
85
  * @throws {EmptyMidnightGroupCancellationsError} when nothing is published and no groups are cancelled.
78
86
  * @throws {EmptyMidnightCollateralSuppliesError} when a collateral market has no collateral supplies.
79
87
  * @throws {InvalidTreeError} when `root` is zero, or `payload` or `groups` is empty.
88
+ * @throws {InvalidMidnightHexInputError} when a publication root or group, cancellation group,
89
+ * Blue callback salt, or root-signature `r`/`s` is not 32-byte hex, or when payload is malformed,
90
+ * odd-length, or larger than 1,000,000 bytes.
80
91
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
81
92
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
82
93
  * @throws {NonPositiveInputError} when `deadline` is not positive.
83
94
  * @throws {NegativeInputError} when a `maxConsumed` ceiling or `nativeAmount` is negative.
84
- * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128`, or `deadline` or a collateral supply amount exceeds `uint256`, or `nativeAmount` exceeds the maximum wNative pull, including zero when no wNative is pulled.
95
+ * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling, collateral supply amount, collateral supply sum, or Blue supply amount exceeds `uint128`, `deadline` exceeds `uint256`, or `nativeAmount` exceeds the maximum wNative pull, including zero when no wNative is pulled.
85
96
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
86
97
  * @throws {NativeAmountOnNonWNativeAssetError} when configured token pulls contain no wNative token.
87
98
  * @throws {ChainIdMismatchError} when the collateral market targets another chain.
@@ -114,9 +125,12 @@ const emptyMidnightMarket = {
114
125
  * ```
115
126
  */
116
127
  const midnightCancelAndMake = (params) => {
117
- (0, validate_js_1.validateDeadline)(params.deadline);
128
+ const snapshot = (0, validateMidnightPublication_js_1.snapshotMidnightCancelAndMakeParams)(params);
129
+ // Throws on malformed or oversized hex; validation only.
130
+ (0, validateMidnightPublication_js_1.validateMidnightPublication)(snapshot);
131
+ (0, validate_js_1.validateDeadline)(snapshot.deadline);
118
132
  const cancelledGroups = new Set();
119
- for (const [index, { group, maxConsumed },] of params.cancellations.entries()) {
133
+ for (const [index, { group, maxConsumed },] of snapshot.cancellations.entries()) {
120
134
  const field = `cancellations[${index}].maxConsumed`;
121
135
  if (maxConsumed < 0n)
122
136
  throw new index_js_2.NegativeInputError(field, maxConsumed);
@@ -133,9 +147,9 @@ const midnightCancelAndMake = (params) => {
133
147
  }
134
148
  cancelledGroups.add(key);
135
149
  }
136
- const publication = params.publication;
150
+ const publication = snapshot.publication;
137
151
  if (publication == null) {
138
- if (params.cancellations.length === 0) {
152
+ if (snapshot.cancellations.length === 0) {
139
153
  throw new index_js_2.EmptyMidnightGroupCancellationsError();
140
154
  }
141
155
  }
@@ -149,12 +163,12 @@ const midnightCancelAndMake = (params) => {
149
163
  if (publication.groups.length === 0) {
150
164
  throw new midnight_sdk_1.InvalidTreeError("Offer groups cannot be empty.");
151
165
  }
152
- const { priceRatifierV1, rateRatifierV1 } = (0, morpho_ts_1.getChainAddresses)(params.chainId);
166
+ const { priceRatifierV1, rateRatifierV1 } = (0, morpho_ts_1.getChainAddresses)(snapshot.chainId);
153
167
  const supportedTargets = [priceRatifierV1, rateRatifierV1].filter((target) => target != null);
154
168
  if (!supportedTargets.some((target) => (0, viem_1.isAddressEqual)(publication.ratifier, target))) {
155
169
  throw new index_js_2.UnsupportedMidnightAuthorizationTargetError({
156
170
  authorized: publication.ratifier,
157
- chainId: params.chainId,
171
+ chainId: snapshot.chainId,
158
172
  supportedTargets,
159
173
  });
160
174
  }
@@ -163,8 +177,11 @@ const midnightCancelAndMake = (params) => {
163
177
  throw new index_js_2.MidnightReplacementGroupCancelledError({ group });
164
178
  }
165
179
  }
166
- if (publication.blueSupply != null && publication.blueSupply.assets <= 0n) {
167
- throw new index_js_2.NonPositiveInputError("blueSupply.assets", publication.blueSupply.assets);
180
+ if (publication.blueSupply != null) {
181
+ if (publication.blueSupply.assets <= 0n) {
182
+ throw new index_js_2.NonPositiveInputError("blueSupply.assets", publication.blueSupply.assets);
183
+ }
184
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("blueSupply.assets", publication.blueSupply.assets);
168
185
  }
169
186
  if (publication.collateral != null) {
170
187
  if (publication.collateral.supplies.length === 0) {
@@ -172,22 +189,17 @@ const midnightCancelAndMake = (params) => {
172
189
  }
173
190
  (0, validateMidnightMarket_js_1.validateMidnightMarket)({
174
191
  market: publication.collateral.market,
175
- chainId: params.chainId,
192
+ chainId: snapshot.chainId,
176
193
  });
177
194
  for (const [index, { collateralIndex, assets },] of publication.collateral.supplies.entries()) {
178
195
  if (assets <= 0n) {
179
196
  throw new index_js_2.NonPositiveInputError(`collateral.supplies[${index}].assets`, assets);
180
197
  }
181
- if (assets > viem_1.maxUint256) {
182
- throw new index_js_2.InputExceedsMaxError({
183
- field: `collateral.supplies[${index}].assets`,
184
- value: assets,
185
- max: viem_1.maxUint256,
186
- });
187
- }
198
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)(`collateral.supplies[${index}].assets`, assets);
188
199
  // Throws UnknownCollateralIndexError when the index is not configured on the market.
189
200
  midnight_sdk_1.MarketUtils.getCollateralByIndex(publication.collateral.market, collateralIndex);
190
201
  }
202
+ (0, validateMidnightBounds_js_1.validateMidnightCollateralSupplySums)("collateral.supplies", publication.collateral.supplies);
191
203
  }
192
204
  }
193
205
  const collateral = publication?.collateral;
@@ -198,8 +210,8 @@ const midnightCancelAndMake = (params) => {
198
210
  assets,
199
211
  }));
200
212
  const nativeFunding = (0, validate_js_1.validateMidnightNativeAmount)({
201
- chainId: params.chainId,
202
- nativeAmount: params.nativeAmount,
213
+ chainId: snapshot.chainId,
214
+ nativeAmount: snapshot.nativeAmount,
203
215
  pulls: [
204
216
  ...(publication?.blueSupply != null && publication.blueSupply.assets > 0n
205
217
  ? [
@@ -212,7 +224,7 @@ const midnightCancelAndMake = (params) => {
212
224
  ...collateralPulls,
213
225
  ],
214
226
  });
215
- const cancellations = params.cancellations.map(({ group, maxConsumed }) => ({
227
+ const cancellations = snapshot.cancellations.map(({ group, maxConsumed }) => ({
216
228
  group,
217
229
  maxConsumed,
218
230
  }));
@@ -239,7 +251,7 @@ const midnightCancelAndMake = (params) => {
239
251
  s: viem_1.zeroHash,
240
252
  };
241
253
  let tx = {
242
- to: (0, morpho_ts_1.getChainAddress)(params.chainId, "midnightBundlesV2"),
254
+ to: (0, morpho_ts_1.getChainAddress)(snapshot.chainId, "midnightBundlesV2"),
243
255
  value: nativeFunding.value,
244
256
  data: (0, viem_1.encodeFunctionData)({
245
257
  abi: midnight_sdk_1.midnightBundlesV2Abi,
@@ -262,13 +274,13 @@ const midnightCancelAndMake = (params) => {
262
274
  signature.s, // s
263
275
  cancellations, // groupsToCancel
264
276
  publication?.payload ?? "0x", // payload
265
- params.deadline, // deadline
277
+ snapshot.deadline, // deadline
266
278
  nativeFunding.wrappedNative, // wrappedNative
267
279
  ],
268
280
  }),
269
281
  };
270
- if (params.metadata) {
271
- tx = (0, index_js_1.addTransactionMetadata)(tx, params.metadata);
282
+ if (snapshot.metadata) {
283
+ tx = (0, index_js_1.addTransactionMetadata)(tx, snapshot.metadata);
272
284
  }
273
285
  return (0, morpho_ts_1.deepFreeze)({
274
286
  ...tx,
@@ -284,7 +296,7 @@ const midnightCancelAndMake = (params) => {
284
296
  cancellations,
285
297
  collateralSupplies: supplies,
286
298
  ...(blueSupply && { blueSupply }),
287
- deadline: params.deadline,
299
+ deadline: snapshot.deadline,
288
300
  },
289
301
  },
290
302
  });
@@ -16,18 +16,25 @@ export interface MidnightRedeemParams {
16
16
  * Use this low-level builder after the caller has fetched and checked position
17
17
  * credit and market withdrawable liquidity. App flows should usually call
18
18
  * `client.morpho.midnight(chainId).redeem(...)`, which performs those checks
19
- * from the supplied `positionData` snapshot before exposing `buildTx`.
19
+ * from the supplied `positionData` snapshot, after applying realized losses and accrued continuous
20
+ * fees, before exposing `buildTx`. This builder bounds `units` by neither credit nor liquidity; a
21
+ * redemption above the credit Midnight computes onchain reverts.
20
22
  *
21
23
  * @param params.chainId - Chain id used to resolve `Midnight`.
22
24
  * @param params.market - Midnight market whose credit is redeemed.
23
25
  * @param params.units - Credit units to withdraw.
24
26
  * @param params.onBehalf - Account whose credit balance is reduced.
25
27
  * @param params.receiver - Optional receiver for withdrawn loan assets; defaults to `onBehalf`.
28
+ * Midnight protocol and market token contracts are rejected.
26
29
  * @param params.metadata - Optional analytics metadata appended to calldata.
27
30
  * @returns A deep-frozen `Transaction<MidnightRedeemAction>` targeting `Midnight`.
28
31
  * @throws {NonPositiveInputError} when `units <= 0n`.
32
+ * @throws {InputExceedsMaxError} when `units` exceeds `uint128`.
29
33
  * @throws {ChainIdMismatchError} when the market targets another chain.
30
34
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
35
+ * @throws {MidnightZeroReceiverError} when `receiver` resolves to the zero address.
36
+ * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
37
+ * market token contract.
31
38
  * @example
32
39
  * ```ts
33
40
  * import { midnightRedeem } from "@morpho-org/morpho-sdk";
@@ -5,7 +5,9 @@ const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
5
5
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
7
  const index_js_1 = require("../../helpers/index.js");
8
+ const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
8
9
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
10
+ const validateMidnightReceiver_js_1 = require("../../helpers/validateMidnightReceiver.js");
9
11
  const index_js_2 = require("../../types/index.js");
10
12
  /**
11
13
  * Encodes a direct Midnight credit redemption.
@@ -13,18 +15,25 @@ const index_js_2 = require("../../types/index.js");
13
15
  * Use this low-level builder after the caller has fetched and checked position
14
16
  * credit and market withdrawable liquidity. App flows should usually call
15
17
  * `client.morpho.midnight(chainId).redeem(...)`, which performs those checks
16
- * from the supplied `positionData` snapshot before exposing `buildTx`.
18
+ * from the supplied `positionData` snapshot, after applying realized losses and accrued continuous
19
+ * fees, before exposing `buildTx`. This builder bounds `units` by neither credit nor liquidity; a
20
+ * redemption above the credit Midnight computes onchain reverts.
17
21
  *
18
22
  * @param params.chainId - Chain id used to resolve `Midnight`.
19
23
  * @param params.market - Midnight market whose credit is redeemed.
20
24
  * @param params.units - Credit units to withdraw.
21
25
  * @param params.onBehalf - Account whose credit balance is reduced.
22
26
  * @param params.receiver - Optional receiver for withdrawn loan assets; defaults to `onBehalf`.
27
+ * Midnight protocol and market token contracts are rejected.
23
28
  * @param params.metadata - Optional analytics metadata appended to calldata.
24
29
  * @returns A deep-frozen `Transaction<MidnightRedeemAction>` targeting `Midnight`.
25
30
  * @throws {NonPositiveInputError} when `units <= 0n`.
31
+ * @throws {InputExceedsMaxError} when `units` exceeds `uint128`.
26
32
  * @throws {ChainIdMismatchError} when the market targets another chain.
27
33
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
34
+ * @throws {MidnightZeroReceiverError} when `receiver` resolves to the zero address.
35
+ * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
36
+ * market token contract.
28
37
  * @example
29
38
  * ```ts
30
39
  * import { midnightRedeem } from "@morpho-org/morpho-sdk";
@@ -41,11 +50,19 @@ const midnightRedeem = (params) => {
41
50
  if (params.units <= 0n) {
42
51
  throw new index_js_2.NonPositiveInputError("units", params.units);
43
52
  }
53
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("units", params.units);
44
54
  // Reject markets from another chain deployment before encoding the call.
45
55
  (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market: params.market, chainId: params.chainId });
46
56
  const marketId = midnight_sdk_1.MarketUtils.toId(params.market);
47
57
  const midnight = (0, morpho_ts_1.getChainAddress)(params.chainId, "midnight");
48
58
  const receiver = params.receiver ?? params.onBehalf;
59
+ // Rejects receivers that would strand the redeemed assets in a contract.
60
+ (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
61
+ chainId: params.chainId,
62
+ market: params.market,
63
+ field: "receiver",
64
+ receiver,
65
+ });
49
66
  let tx = {
50
67
  to: midnight,
51
68
  value: 0n,
@@ -15,8 +15,12 @@ export interface MidnightRepayWithdrawCollateralParams {
15
15
  readonly nativeAmount?: bigint;
16
16
  /** `assets: maxUint256` withdraws the sender's whole balance of that collateral at execution. */
17
17
  readonly collateralWithdrawals: readonly MidnightCollateralTransfer[];
18
+ /** Must be non-zero when withdrawals are provided; unused otherwise. */
18
19
  readonly collateralReceiver: Address;
19
- /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
20
+ /**
21
+ * Bundle execution deadline timestamp. Unlike taker builders, `maxUint256` is accepted because
22
+ * no offers are filled; the pull remains bounded by `repay.assets` or `repay.maxBuyerAssets`.
23
+ */
20
24
  readonly deadline: bigint;
21
25
  readonly metadata?: Metadata;
22
26
  }
@@ -26,6 +30,11 @@ export interface MidnightRepayWithdrawCollateralParams {
26
30
  * assets-target entrypoint with `minUnits = assets` (a direct repay counts one unit per asset); a
27
31
  * `full` repay uses the units-target entrypoint with `targetUnits = maxUint256`.
28
32
  *
33
+ * This builder reads no position or prices, so it checks neither the debt nor the collateral
34
+ * withdrawn against the position, and applies no `DEFAULT_LLTV_BUFFER` health check. The entity
35
+ * method checks both from `positionData` and `collateralPrices`; onchain, Midnight still rejects a
36
+ * withdrawal that leaves the position above LLTV.
37
+ *
29
38
  * Prefer `client.morpho.midnight(chainId).repayWithdrawCollateral(...)` in app flows so the
30
39
  * loan-token approval and Midnight authorization requirements are resolved first.
31
40
  *
@@ -38,8 +47,12 @@ export interface MidnightRepayWithdrawCollateralParams {
38
47
  * the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still required
39
48
  * for the full pulled amount.
40
49
  * @param params.collateralWithdrawals - Collateral withdrawals; `assets: maxUint256` withdraws the full balance.
41
- * @param params.collateralReceiver - Recipient of the withdrawn collateral.
42
- * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry.
50
+ * @param params.collateralReceiver - Recipient of withdrawn collateral; must be non-zero and not
51
+ * a Midnight protocol or market token contract when `collateralWithdrawals` is non-empty, and is
52
+ * unused otherwise.
53
+ * @param params.deadline - Bundle execution deadline timestamp. Unlike taker builders, `maxUint256`
54
+ * is accepted because no offers are filled; the pull remains bounded by `repay.assets` or
55
+ * `repay.maxBuyerAssets`. Not checked against the clock; validate freshness before building.
43
56
  * @param params.metadata - Optional analytics metadata appended to calldata.
44
57
  * @returns A deep-frozen `Transaction<MidnightRepayWithdrawCollateralAction>` targeting `MidnightBundlesV2`.
45
58
  * @throws {NegativeInputError} when `repay.assets` or `nativeAmount` is negative.
@@ -51,6 +64,9 @@ export interface MidnightRepayWithdrawCollateralParams {
51
64
  * @throws {ChainIdMismatchError} when the market targets another chain.
52
65
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
53
66
  * @throws {UnknownCollateralIndexError} when a withdrawal targets an unconfigured collateral index.
67
+ * @throws {MidnightZeroReceiverError} when collateral is withdrawn to the zero address.
68
+ * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
69
+ * contract or a market token contract.
54
70
  * @example
55
71
  * ```ts
56
72
  * import { maxUint256 } from "viem";
@@ -7,6 +7,7 @@ const viem_1 = require("viem");
7
7
  const index_js_1 = require("../../helpers/index.js");
8
8
  const validate_js_1 = require("../../helpers/validate.js");
9
9
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
10
+ const validateMidnightReceiver_js_1 = require("../../helpers/validateMidnightReceiver.js");
10
11
  const index_js_2 = require("../../types/index.js");
11
12
  /**
12
13
  * Encodes a reduce-only `MidnightBundlesV2` buy with no offers, so the sender's debt is repaid
@@ -14,6 +15,11 @@ const index_js_2 = require("../../types/index.js");
14
15
  * assets-target entrypoint with `minUnits = assets` (a direct repay counts one unit per asset); a
15
16
  * `full` repay uses the units-target entrypoint with `targetUnits = maxUint256`.
16
17
  *
18
+ * This builder reads no position or prices, so it checks neither the debt nor the collateral
19
+ * withdrawn against the position, and applies no `DEFAULT_LLTV_BUFFER` health check. The entity
20
+ * method checks both from `positionData` and `collateralPrices`; onchain, Midnight still rejects a
21
+ * withdrawal that leaves the position above LLTV.
22
+ *
17
23
  * Prefer `client.morpho.midnight(chainId).repayWithdrawCollateral(...)` in app flows so the
18
24
  * loan-token approval and Midnight authorization requirements are resolved first.
19
25
  *
@@ -26,8 +32,12 @@ const index_js_2 = require("../../types/index.js");
26
32
  * the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still required
27
33
  * for the full pulled amount.
28
34
  * @param params.collateralWithdrawals - Collateral withdrawals; `assets: maxUint256` withdraws the full balance.
29
- * @param params.collateralReceiver - Recipient of the withdrawn collateral.
30
- * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry.
35
+ * @param params.collateralReceiver - Recipient of withdrawn collateral; must be non-zero and not
36
+ * a Midnight protocol or market token contract when `collateralWithdrawals` is non-empty, and is
37
+ * unused otherwise.
38
+ * @param params.deadline - Bundle execution deadline timestamp. Unlike taker builders, `maxUint256`
39
+ * is accepted because no offers are filled; the pull remains bounded by `repay.assets` or
40
+ * `repay.maxBuyerAssets`. Not checked against the clock; validate freshness before building.
31
41
  * @param params.metadata - Optional analytics metadata appended to calldata.
32
42
  * @returns A deep-frozen `Transaction<MidnightRepayWithdrawCollateralAction>` targeting `MidnightBundlesV2`.
33
43
  * @throws {NegativeInputError} when `repay.assets` or `nativeAmount` is negative.
@@ -39,6 +49,9 @@ const index_js_2 = require("../../types/index.js");
39
49
  * @throws {ChainIdMismatchError} when the market targets another chain.
40
50
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
41
51
  * @throws {UnknownCollateralIndexError} when a withdrawal targets an unconfigured collateral index.
52
+ * @throws {MidnightZeroReceiverError} when collateral is withdrawn to the zero address.
53
+ * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
54
+ * contract or a market token contract.
42
55
  * @example
43
56
  * ```ts
44
57
  * import { maxUint256 } from "viem";
@@ -83,6 +96,15 @@ const midnightRepayWithdrawCollateral = (params) => {
83
96
  // Throws UnknownCollateralIndexError when the index is not configured on the market.
84
97
  midnight_sdk_1.MarketUtils.getCollateralByIndex(params.market, collateralIndex);
85
98
  }
99
+ if (params.collateralWithdrawals.length > 0) {
100
+ // Rejects receivers that would strand the withdrawn collateral in a contract.
101
+ (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
102
+ chainId: params.chainId,
103
+ market: params.market,
104
+ field: "collateralReceiver",
105
+ receiver: params.collateralReceiver,
106
+ });
107
+ }
86
108
  if (repay.type === "assets") {
87
109
  (0, validate_js_1.validateUint256Field)("repay.assets", repay.assets);
88
110
  // An assets repay has no "whole debt" sentinel; use `{ type: "full" }` for that.
@@ -26,6 +26,7 @@ export interface MidnightSupplyCollateralParams {
26
26
  * @param params.metadata - Optional analytics metadata appended to calldata.
27
27
  * @returns A deep-frozen `Transaction<MidnightSupplyCollateralAction>` targeting `Midnight`.
28
28
  * @throws {NonPositiveInputError} when `assets <= 0n`.
29
+ * @throws {InputExceedsMaxError} when `assets` exceeds `uint128`.
29
30
  * @throws {ChainIdMismatchError} when the market targets another chain.
30
31
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
31
32
  * @throws {UnknownCollateralIndexError} when `collateralIndex` is not configured on the market.
@@ -5,6 +5,7 @@ const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
5
5
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
7
  const index_js_1 = require("../../helpers/index.js");
8
+ const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
8
9
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
9
10
  const index_js_2 = require("../../types/index.js");
10
11
  /**
@@ -23,6 +24,7 @@ const index_js_2 = require("../../types/index.js");
23
24
  * @param params.metadata - Optional analytics metadata appended to calldata.
24
25
  * @returns A deep-frozen `Transaction<MidnightSupplyCollateralAction>` targeting `Midnight`.
25
26
  * @throws {NonPositiveInputError} when `assets <= 0n`.
27
+ * @throws {InputExceedsMaxError} when `assets` exceeds `uint128`.
26
28
  * @throws {ChainIdMismatchError} when the market targets another chain.
27
29
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
28
30
  * @throws {UnknownCollateralIndexError} when `collateralIndex` is not configured on the market.
@@ -43,6 +45,7 @@ const midnightSupplyCollateral = (params) => {
43
45
  if (params.assets <= 0n) {
44
46
  throw new index_js_2.NonPositiveInputError("assets", params.assets);
45
47
  }
48
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("assets", params.assets);
46
49
  // Reject markets from another chain deployment before encoding the call.
47
50
  (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market: params.market, chainId: params.chainId });
48
51
  const marketId = midnight_sdk_1.MarketUtils.toId(params.market);
@@ -20,10 +20,16 @@ export interface MidnightSupplyCollateralTakeBorrowParams extends MidnightTakeBo
20
20
  * Prefer `client.morpho.midnight(chainId).supplyCollateralTakeBorrow(...)` in app flows so
21
21
  * collateral approvals and the `MidnightBundlesV2` authorization are resolved first.
22
22
  *
23
+ * This builder reads no position or prices, so it applies no `DEFAULT_LLTV_BUFFER` health check:
24
+ * keeping the position inside the buffer is the caller's responsibility. The entity method checks
25
+ * it from `positionData` and `collateralPrices`; onchain, Midnight still rejects a position above
26
+ * LLTV.
27
+ *
23
28
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
24
29
  * @param params.market - Midnight market traded by every takeable offer.
25
30
  * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
26
- * @param params.receiver - Recipient of the borrowed loan assets.
31
+ * @param params.receiver - Recipient of the borrowed loan assets; Midnight protocol and market
32
+ * token contracts are rejected.
27
33
  * @param params.collateralSupplies - Collateral index and assets per supply; must not be empty.
28
34
  * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
29
35
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of the
@@ -31,7 +37,7 @@ export interface MidnightSupplyCollateralTakeBorrowParams extends MidnightTakeBo
31
37
  * the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still required
32
38
  * for the full pulled amount.
33
39
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
34
- * @param params.deadline - Bounded bundle execution deadline timestamp.
40
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
35
41
  * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
36
42
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
37
43
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -46,17 +52,26 @@ export interface MidnightSupplyCollateralTakeBorrowParams extends MidnightTakeBo
46
52
  * @throws {MidnightOfferSideMismatchError} when any offer is not lend-side.
47
53
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
48
54
  * @throws {NonPositiveInputError} when a supply amount, the target amount, `maxUnits`, `minSellerAssets` or `deadline` is not positive.
49
- * @throws {NegativeInputError} when `referralFeePct` or `nativeAmount` is negative.
50
- * @throws {InputExceedsMaxError} when a `collateralSupplies[].assets` amount, `target.assets`,
51
- * `target.maxUnits`, `target.units`, `target.minSellerAssets` or `deadline` exceeds `uint256`, or
52
- * `nativeAmount` exceeds the maximum wNative collateral amount this call can pull.
55
+ * @throws {NegativeInputError} when a takeable offer cap,
56
+ * `referralFeePct` or `nativeAmount` is negative.
57
+ * @throws {InputExceedsMaxError} when a collateral supply amount or per-index sum, target amount,
58
+ * or offer cap exceeds `uint128`, when `target.maxUnits` exceeds `uint128` (an SDK cap: the
59
+ * bundle accepts `uint256`, but a higher ceiling gives no slippage protection), when `deadline`
60
+ * exceeds `uint256`, or when `nativeAmount` exceeds the maximum wNative collateral amount this
61
+ * call can pull.
53
62
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
54
63
  * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
55
64
  * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or
56
65
  * `deadline` is `maxUint256`.
57
66
  * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
67
+ * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
68
+ * market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
58
69
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
70
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
59
71
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
72
+ * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds `target.units`
73
+ * minus the referral fee, or `target.maxUnits` is below `target.assets` plus the referral fee, since
74
+ * a unit sells for at most one asset.
60
75
  * @example
61
76
  * ```ts
62
77
  * import { Time } from "@morpho-org/morpho-ts";
@@ -6,7 +6,10 @@ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
7
  const index_js_1 = require("../../helpers/index.js");
8
8
  const validate_js_1 = require("../../helpers/validate.js");
9
+ const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
9
10
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
11
+ const validateMidnightReceiver_js_1 = require("../../helpers/validateMidnightReceiver.js");
12
+ const validateMidnightTakeFeasibility_js_1 = require("../../helpers/validateMidnightTakeFeasibility.js");
10
13
  const validateTakeableOffers_js_1 = require("../../helpers/validateTakeableOffers.js");
11
14
  const index_js_2 = require("../../types/index.js");
12
15
  /**
@@ -17,10 +20,16 @@ const index_js_2 = require("../../types/index.js");
17
20
  * Prefer `client.morpho.midnight(chainId).supplyCollateralTakeBorrow(...)` in app flows so
18
21
  * collateral approvals and the `MidnightBundlesV2` authorization are resolved first.
19
22
  *
23
+ * This builder reads no position or prices, so it applies no `DEFAULT_LLTV_BUFFER` health check:
24
+ * keeping the position inside the buffer is the caller's responsibility. The entity method checks
25
+ * it from `positionData` and `collateralPrices`; onchain, Midnight still rejects a position above
26
+ * LLTV.
27
+ *
20
28
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
21
29
  * @param params.market - Midnight market traded by every takeable offer.
22
30
  * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
23
- * @param params.receiver - Recipient of the borrowed loan assets.
31
+ * @param params.receiver - Recipient of the borrowed loan assets; Midnight protocol and market
32
+ * token contracts are rejected.
24
33
  * @param params.collateralSupplies - Collateral index and assets per supply; must not be empty.
25
34
  * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
26
35
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of the
@@ -28,7 +37,7 @@ const index_js_2 = require("../../types/index.js");
28
37
  * the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still required
29
38
  * for the full pulled amount.
30
39
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
31
- * @param params.deadline - Bounded bundle execution deadline timestamp.
40
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
32
41
  * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
33
42
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
34
43
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -43,17 +52,26 @@ const index_js_2 = require("../../types/index.js");
43
52
  * @throws {MidnightOfferSideMismatchError} when any offer is not lend-side.
44
53
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
45
54
  * @throws {NonPositiveInputError} when a supply amount, the target amount, `maxUnits`, `minSellerAssets` or `deadline` is not positive.
46
- * @throws {NegativeInputError} when `referralFeePct` or `nativeAmount` is negative.
47
- * @throws {InputExceedsMaxError} when a `collateralSupplies[].assets` amount, `target.assets`,
48
- * `target.maxUnits`, `target.units`, `target.minSellerAssets` or `deadline` exceeds `uint256`, or
49
- * `nativeAmount` exceeds the maximum wNative collateral amount this call can pull.
55
+ * @throws {NegativeInputError} when a takeable offer cap,
56
+ * `referralFeePct` or `nativeAmount` is negative.
57
+ * @throws {InputExceedsMaxError} when a collateral supply amount or per-index sum, target amount,
58
+ * or offer cap exceeds `uint128`, when `target.maxUnits` exceeds `uint128` (an SDK cap: the
59
+ * bundle accepts `uint256`, but a higher ceiling gives no slippage protection), when `deadline`
60
+ * exceeds `uint256`, or when `nativeAmount` exceeds the maximum wNative collateral amount this
61
+ * call can pull.
50
62
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
51
63
  * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
52
64
  * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or
53
65
  * `deadline` is `maxUint256`.
54
66
  * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
67
+ * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
68
+ * market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
55
69
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
70
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
56
71
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
72
+ * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds `target.units`
73
+ * minus the referral fee, or `target.maxUnits` is below `target.assets` plus the referral fee, since
74
+ * a unit sells for at most one asset.
57
75
  * @example
58
76
  * ```ts
59
77
  * import { Time } from "@morpho-org/morpho-ts";
@@ -80,18 +98,24 @@ const midnightSupplyCollateralTakeBorrow = (params) => {
80
98
  if (assets <= 0n) {
81
99
  throw new index_js_2.NonPositiveInputError(`collateralSupplies[${index}].assets`, assets);
82
100
  }
83
- (0, validate_js_1.validateUint256Field)(`collateralSupplies[${index}].assets`, assets);
101
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)(`collateralSupplies[${index}].assets`, assets);
84
102
  // Throws UnknownCollateralIndexError when the index is not configured on the market.
85
103
  midnight_sdk_1.MarketUtils.getCollateralByIndex(params.market, collateralIndex);
86
104
  }
105
+ (0, validateMidnightBounds_js_1.validateMidnightCollateralSupplySums)("collateralSupplies", params.collateralSupplies);
87
106
  const marketId = (0, validateTakeableOffers_js_1.validateTakeableOffers)({
88
107
  market: params.market,
89
108
  takeableOffers: params.takeableOffers,
90
109
  expectedBuy: true,
91
110
  });
92
- if ((0, viem_1.isAddressEqual)(params.receiver, viem_1.zeroAddress)) {
93
- throw new index_js_2.MidnightZeroReceiverError("receiver");
94
- }
111
+ (0, validateMidnightBounds_js_1.validateMidnightTakeableOfferBounds)(params.takeableOffers);
112
+ // Rejects receivers that would strand the borrowed assets in a contract.
113
+ (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
114
+ chainId: params.chainId,
115
+ market: params.market,
116
+ field: "receiver",
117
+ receiver: params.receiver,
118
+ });
95
119
  const { target } = params;
96
120
  if (target.type === "assets") {
97
121
  if (target.assets <= 0n) {
@@ -103,8 +127,8 @@ const midnightSupplyCollateralTakeBorrow = (params) => {
103
127
  if (target.maxUnits <= 0n) {
104
128
  throw new index_js_2.NonPositiveInputError("target.maxUnits", target.maxUnits);
105
129
  }
106
- (0, validate_js_1.validateUint256Field)("target.assets", target.assets);
107
- (0, validate_js_1.validateUint256Field)("target.maxUnits", target.maxUnits);
130
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("target.assets", target.assets);
131
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("target.maxUnits", target.maxUnits);
108
132
  }
109
133
  else {
110
134
  if (target.units === viem_1.maxUint256) {
@@ -116,14 +140,25 @@ const midnightSupplyCollateralTakeBorrow = (params) => {
116
140
  if (target.minSellerAssets <= 0n) {
117
141
  throw new index_js_2.NonPositiveInputError("target.minSellerAssets", target.minSellerAssets);
118
142
  }
119
- (0, validate_js_1.validateUint256Field)("target.units", target.units);
120
- (0, validate_js_1.validateUint256Field)("target.minSellerAssets", target.minSellerAssets);
143
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("target.units", target.units);
144
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("target.minSellerAssets", target.minSellerAssets);
121
145
  }
122
146
  if (params.deadline === viem_1.maxUint256) {
123
147
  throw new index_js_2.UnboundedMidnightTakeInputError("deadline");
124
148
  }
125
149
  (0, validate_js_1.validateDeadline)(params.deadline);
126
150
  const { referralFeePct, referralFeeRecipient } = (0, validate_js_1.validateReferralFee)(params);
151
+ (0, validateMidnightBounds_js_1.validateMidnightReferralFeeCap)(referralFeePct);
152
+ (0, validateMidnightTakeFeasibility_js_1.validateMidnightSellTargetBounds)({ target, referralFeePct });
153
+ if (referralFeePct > 0n) {
154
+ // Rejects fee recipients that would strand the fee in a contract.
155
+ (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
156
+ chainId: params.chainId,
157
+ market: params.market,
158
+ field: "referralFeeRecipient",
159
+ receiver: referralFeeRecipient,
160
+ });
161
+ }
127
162
  const nativeFunding = (0, validate_js_1.validateMidnightNativeAmount)({
128
163
  chainId: params.chainId,
129
164
  nativeAmount: params.nativeAmount,