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