@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
@@ -22,15 +22,21 @@ export interface MidnightTakeBorrowParams extends MidnightReferralFeeParams {
22
22
  * market liquidity allow, and fills only the rest from offers: a sender with credit nets it before
23
23
  * taking debt.
24
24
  *
25
+ * This builder reads no position or prices, so it applies no `DEFAULT_LLTV_BUFFER` health check:
26
+ * keeping the position inside the buffer is the caller's responsibility. The entity method checks
27
+ * it from `positionData` and `collateralPrices`; onchain, Midnight still rejects a position above
28
+ * LLTV.
29
+ *
25
30
  * Prefer `client.morpho.midnight(chainId).takeBorrow(...)` in app flows so the
26
31
  * `MidnightBundlesV2` authorization is resolved before building the bundle.
27
32
  *
28
33
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
29
34
  * @param params.market - Midnight market traded by every takeable offer.
30
35
  * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
31
- * @param params.receiver - Recipient of the borrowed loan assets.
36
+ * @param params.receiver - Recipient of the borrowed loan assets; Midnight protocol and market
37
+ * token contracts are rejected.
32
38
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
33
- * @param params.deadline - Bounded bundle execution deadline timestamp.
39
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
34
40
  * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
35
41
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
36
42
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -43,14 +49,21 @@ export interface MidnightTakeBorrowParams extends MidnightReferralFeeParams {
43
49
  * @throws {MidnightOfferSideMismatchError} when any offer is not lend-side.
44
50
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
45
51
  * @throws {NonPositiveInputError} when the target amount, `maxUnits`, `minSellerAssets` or `deadline` is not positive.
46
- * @throws {NegativeInputError} when `referralFeePct` is negative.
47
- * @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`,
48
- * `target.minSellerAssets` or `deadline` exceeds `uint256`.
52
+ * @throws {NegativeInputError} when a takeable offer cap or `referralFeePct` is negative.
53
+ * @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`, when
54
+ * `target.maxUnits` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a higher
55
+ * ceiling gives no slippage protection), or when `deadline` exceeds `uint256`.
49
56
  * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or
50
57
  * `deadline` is `maxUint256`.
51
58
  * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
59
+ * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
60
+ * market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
52
61
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
62
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
53
63
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
64
+ * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds `target.units`
65
+ * minus the referral fee, or `target.maxUnits` is below `target.assets` plus the referral fee, since
66
+ * a unit sells for at most one asset.
54
67
  * @example
55
68
  * ```ts
56
69
  * 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, zeroAddress, } from "viem";
4
4
  import { addTransactionMetadata } from "../../helpers/index.js";
5
- import { validateDeadline, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
5
+ import { validateDeadline, validateReferralFee, } from "../../helpers/validate.js";
6
+ import { 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 { MidnightZeroReceiverError, NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../types/index.js";
11
+ import { NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../types/index.js";
9
12
  /**
10
13
  * Encodes a `MidnightBundlesV2` sell that borrows from lend-side offers for `msg.sender`.
11
14
  *
@@ -13,15 +16,21 @@ import { MidnightZeroReceiverError, NonPositiveInputError, UnboundedMidnightTake
13
16
  * market liquidity allow, and fills only the rest from offers: a sender with credit nets it before
14
17
  * taking debt.
15
18
  *
19
+ * This builder reads no position or prices, so it applies no `DEFAULT_LLTV_BUFFER` health check:
20
+ * keeping the position inside the buffer is the caller's responsibility. The entity method checks
21
+ * it from `positionData` and `collateralPrices`; onchain, Midnight still rejects a position above
22
+ * LLTV.
23
+ *
16
24
  * Prefer `client.morpho.midnight(chainId).takeBorrow(...)` in app flows so the
17
25
  * `MidnightBundlesV2` authorization is resolved before building the bundle.
18
26
  *
19
27
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
20
28
  * @param params.market - Midnight market traded by every takeable offer.
21
29
  * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
22
- * @param params.receiver - Recipient of the borrowed loan assets.
30
+ * @param params.receiver - Recipient of the borrowed loan assets; Midnight protocol and market
31
+ * token contracts are rejected.
23
32
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
24
- * @param params.deadline - Bounded bundle execution deadline timestamp.
33
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
25
34
  * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
26
35
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
27
36
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -34,14 +43,21 @@ import { MidnightZeroReceiverError, NonPositiveInputError, UnboundedMidnightTake
34
43
  * @throws {MidnightOfferSideMismatchError} when any offer is not lend-side.
35
44
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
36
45
  * @throws {NonPositiveInputError} when the target amount, `maxUnits`, `minSellerAssets` or `deadline` is not positive.
37
- * @throws {NegativeInputError} when `referralFeePct` is negative.
38
- * @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`,
39
- * `target.minSellerAssets` or `deadline` exceeds `uint256`.
46
+ * @throws {NegativeInputError} when a takeable offer cap or `referralFeePct` is negative.
47
+ * @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`, when
48
+ * `target.maxUnits` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a higher
49
+ * ceiling gives no slippage protection), or when `deadline` exceeds `uint256`.
40
50
  * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or
41
51
  * `deadline` is `maxUint256`.
42
52
  * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
53
+ * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
54
+ * market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
43
55
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
56
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
44
57
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
58
+ * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds `target.units`
59
+ * minus the referral fee, or `target.maxUnits` is below `target.assets` plus the referral fee, since
60
+ * a unit sells for at most one asset.
45
61
  * @example
46
62
  * ```ts
47
63
  * import { Time } from "@morpho-org/morpho-ts";
@@ -65,9 +81,14 @@ export const midnightTakeBorrow = (params) => {
65
81
  takeableOffers: params.takeableOffers,
66
82
  expectedBuy: true,
67
83
  });
68
- if (isAddressEqual(params.receiver, zeroAddress)) {
69
- throw new MidnightZeroReceiverError("receiver");
70
- }
84
+ validateMidnightTakeableOfferBounds(params.takeableOffers);
85
+ // Rejects receivers that would strand the borrowed assets in a contract.
86
+ validateMidnightReceiver({
87
+ chainId: params.chainId,
88
+ market: params.market,
89
+ field: "receiver",
90
+ receiver: params.receiver,
91
+ });
71
92
  const { target } = params;
72
93
  if (target.type === "assets") {
73
94
  if (target.assets <= 0n) {
@@ -79,8 +100,8 @@ export const midnightTakeBorrow = (params) => {
79
100
  if (target.maxUnits <= 0n) {
80
101
  throw new NonPositiveInputError("target.maxUnits", target.maxUnits);
81
102
  }
82
- validateUint256Field("target.assets", target.assets);
83
- validateUint256Field("target.maxUnits", target.maxUnits);
103
+ validateMidnightUint128Field("target.assets", target.assets);
104
+ validateMidnightUint128Field("target.maxUnits", target.maxUnits);
84
105
  }
85
106
  else {
86
107
  if (target.units === maxUint256) {
@@ -92,14 +113,25 @@ export const midnightTakeBorrow = (params) => {
92
113
  if (target.minSellerAssets <= 0n) {
93
114
  throw new NonPositiveInputError("target.minSellerAssets", target.minSellerAssets);
94
115
  }
95
- validateUint256Field("target.units", target.units);
96
- validateUint256Field("target.minSellerAssets", target.minSellerAssets);
116
+ validateMidnightUint128Field("target.units", target.units);
117
+ validateMidnightUint128Field("target.minSellerAssets", target.minSellerAssets);
97
118
  }
98
119
  if (params.deadline === maxUint256) {
99
120
  throw new UnboundedMidnightTakeInputError("deadline");
100
121
  }
101
122
  validateDeadline(params.deadline);
102
123
  const { referralFeePct, referralFeeRecipient } = validateReferralFee(params);
124
+ validateMidnightReferralFeeCap(referralFeePct);
125
+ validateMidnightSellTargetBounds({ target, referralFeePct });
126
+ if (referralFeePct > 0n) {
127
+ // Rejects fee recipients that would strand the fee in a contract.
128
+ validateMidnightReceiver({
129
+ chainId: params.chainId,
130
+ market: params.market,
131
+ field: "referralFeeRecipient",
132
+ receiver: referralFeeRecipient,
133
+ });
134
+ }
103
135
  const market = MarketUtils.toStruct(params.market);
104
136
  const args = [
105
137
  false, // reduceOnly
@@ -39,7 +39,7 @@ export interface MidnightTakeLendParams extends MidnightReferralFeeParams {
39
39
  * @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
40
40
  * onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
41
41
  * is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
42
- * @param params.deadline - Bounded bundle execution deadline timestamp.
42
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
43
43
  * @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
44
44
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
45
45
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -52,15 +52,20 @@ export interface MidnightTakeLendParams extends MidnightReferralFeeParams {
52
52
  * @throws {MidnightOfferSideMismatchError} when any offer is not borrow-side.
53
53
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
54
54
  * @throws {NonPositiveInputError} when the target amount, `minUnits`, `maxBuyerAssets` or `deadline` is not positive.
55
- * @throws {NegativeInputError} when `maxContinuousFee`, `referralFeePct` or `nativeAmount` is negative.
55
+ * @throws {NegativeInputError} when a takeable offer cap, `maxContinuousFee`,
56
+ * `referralFeePct` or `nativeAmount` is negative.
56
57
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
57
58
  * @throws {NativeAmountOnNonWNativeAssetError} when `market.loanToken` is not wNative.
58
- * @throws {InputExceedsMaxError} when `target.assets`, `target.units`, `minUnits`, `maxBuyerAssets`,
59
- * `maxContinuousFee` or `deadline` exceeds `uint256`, or `nativeAmount` exceeds the maximum
60
- * wNative amount this call can pull.
59
+ * @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`; when
60
+ * `target.maxBuyerAssets` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a
61
+ * higher ceiling gives no slippage protection); when `maxContinuousFee` or `deadline` exceeds
62
+ * `uint256`; or when `nativeAmount` exceeds the maximum wNative amount this call can pull.
61
63
  * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxBuyerAssets` or
62
64
  * `deadline` is `maxUint256`.
65
+ * @throws {MidnightContractReceiverError} when `referralFeeRecipient` is a Midnight protocol
66
+ * contract or a market token contract with a positive referral fee.
63
67
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
68
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
64
69
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
65
70
  * @example
66
71
  * ```ts
@@ -3,7 +3,9 @@ import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
3
  import { encodeFunctionData, maxUint256, zeroAddress } from "viem";
4
4
  import { addTransactionMetadata } from "../../helpers/index.js";
5
5
  import { validateDeadline, validateMidnightNativeAmount, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
6
+ import { validateMidnightReferralFeeCap, validateMidnightTakeableOfferBounds, validateMidnightUint128Field, } from "../../helpers/validateMidnightBounds.js";
6
7
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
8
+ import { validateMidnightReceiver } from "../../helpers/validateMidnightReceiver.js";
7
9
  import { validateTakeableOffers } from "../../helpers/validateTakeableOffers.js";
8
10
  import { NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../types/index.js";
9
11
  /**
@@ -24,7 +26,7 @@ import { NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../t
24
26
  * @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
25
27
  * onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
26
28
  * is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
27
- * @param params.deadline - Bounded bundle execution deadline timestamp.
29
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
28
30
  * @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
29
31
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
30
32
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -37,15 +39,20 @@ import { NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../t
37
39
  * @throws {MidnightOfferSideMismatchError} when any offer is not borrow-side.
38
40
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
39
41
  * @throws {NonPositiveInputError} when the target amount, `minUnits`, `maxBuyerAssets` or `deadline` is not positive.
40
- * @throws {NegativeInputError} when `maxContinuousFee`, `referralFeePct` or `nativeAmount` is negative.
42
+ * @throws {NegativeInputError} when a takeable offer cap, `maxContinuousFee`,
43
+ * `referralFeePct` or `nativeAmount` is negative.
41
44
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
42
45
  * @throws {NativeAmountOnNonWNativeAssetError} when `market.loanToken` is not wNative.
43
- * @throws {InputExceedsMaxError} when `target.assets`, `target.units`, `minUnits`, `maxBuyerAssets`,
44
- * `maxContinuousFee` or `deadline` exceeds `uint256`, or `nativeAmount` exceeds the maximum
45
- * wNative amount this call can pull.
46
+ * @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`; when
47
+ * `target.maxBuyerAssets` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a
48
+ * higher ceiling gives no slippage protection); when `maxContinuousFee` or `deadline` exceeds
49
+ * `uint256`; or when `nativeAmount` exceeds the maximum wNative amount this call can pull.
46
50
  * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxBuyerAssets` or
47
51
  * `deadline` is `maxUint256`.
52
+ * @throws {MidnightContractReceiverError} when `referralFeeRecipient` is a Midnight protocol
53
+ * contract or a market token contract with a positive referral fee.
48
54
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
55
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
49
56
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
50
57
  * @example
51
58
  * ```ts
@@ -71,6 +78,7 @@ export const midnightTakeLend = (params) => {
71
78
  takeableOffers: params.takeableOffers,
72
79
  expectedBuy: false,
73
80
  });
81
+ validateMidnightTakeableOfferBounds(params.takeableOffers);
74
82
  const { target } = params;
75
83
  if (target.type === "assets") {
76
84
  if (target.assets <= 0n) {
@@ -79,8 +87,8 @@ export const midnightTakeLend = (params) => {
79
87
  if (target.minUnits <= 0n) {
80
88
  throw new NonPositiveInputError("target.minUnits", target.minUnits);
81
89
  }
82
- validateUint256Field("target.assets", target.assets);
83
- validateUint256Field("target.minUnits", target.minUnits);
90
+ validateMidnightUint128Field("target.assets", target.assets);
91
+ validateMidnightUint128Field("target.minUnits", target.minUnits);
84
92
  }
85
93
  else {
86
94
  if (target.units === maxUint256) {
@@ -95,8 +103,8 @@ export const midnightTakeLend = (params) => {
95
103
  if (target.maxBuyerAssets <= 0n) {
96
104
  throw new NonPositiveInputError("target.maxBuyerAssets", target.maxBuyerAssets);
97
105
  }
98
- validateUint256Field("target.units", target.units);
99
- validateUint256Field("target.maxBuyerAssets", target.maxBuyerAssets);
106
+ validateMidnightUint128Field("target.units", target.units);
107
+ validateMidnightUint128Field("target.maxBuyerAssets", target.maxBuyerAssets);
100
108
  }
101
109
  validateUint256Field("maxContinuousFee", params.maxContinuousFee);
102
110
  if (params.deadline === maxUint256) {
@@ -104,6 +112,16 @@ export const midnightTakeLend = (params) => {
104
112
  }
105
113
  validateDeadline(params.deadline);
106
114
  const { referralFeePct, referralFeeRecipient } = validateReferralFee(params);
115
+ validateMidnightReferralFeeCap(referralFeePct);
116
+ if (referralFeePct > 0n) {
117
+ // Rejects fee recipients that would strand the fee in a contract.
118
+ validateMidnightReceiver({
119
+ chainId: params.chainId,
120
+ market: params.market,
121
+ field: "referralFeeRecipient",
122
+ receiver: referralFeeRecipient,
123
+ });
124
+ }
107
125
  const market = MarketUtils.toStruct(params.market);
108
126
  const nativeFunding = validateMidnightNativeAmount({
109
127
  chainId: params.chainId,
@@ -20,6 +20,7 @@ export interface MidnightTakeRepayWithdrawCollateralParams extends MidnightRefer
20
20
  readonly repayEnabled: boolean;
21
21
  /** Collateral withdrawn after repaying; `maxUint256` assets withdraws the whole balance. */
22
22
  readonly collateralWithdrawals: readonly MidnightCollateralTransfer[];
23
+ /** Must be non-zero when withdrawals are provided; unused otherwise. */
23
24
  readonly collateralReceiver: Address;
24
25
  /** Largest market continuous fee accepted when taking offers. Pass `maxUint256` explicitly for no cap. */
25
26
  readonly maxContinuousFee: bigint;
@@ -35,6 +36,11 @@ export interface MidnightTakeRepayWithdrawCollateralParams extends MidnightRefer
35
36
  * `client.morpho.midnight(chainId).takeRepayWithdrawCollateral(...)` in app flows so the
36
37
  * loan-token approval and the `MidnightBundlesV2` authorization are resolved first.
37
38
  *
39
+ * This builder reads no position or prices, so it applies no `DEFAULT_LLTV_BUFFER` health check:
40
+ * keeping the position inside the buffer is the caller's responsibility. The entity method checks
41
+ * it from `positionData` and `collateralPrices`; onchain, Midnight still rejects a position above
42
+ * LLTV.
43
+ *
38
44
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
39
45
  * @param params.market - Midnight market traded by every takeable offer.
40
46
  * @param params.target - `{ type: "assets", assets, minUnits }` or `{ type: "units", units, maxBuyerAssets }`; `units: maxUint256` targets the sender's whole debt, capped by `maxBuyerAssets` (must be finite; `units: maxUint256` already selects the whole debt).
@@ -46,11 +52,13 @@ export interface MidnightTakeRepayWithdrawCollateralParams extends MidnightRefer
46
52
  * @param params.takeableOffers - ABI-ready borrow-side offers returned by the Midnight API; must not be empty.
47
53
  * @param params.repayEnabled - Whether the unfilled remainder is repaid directly to Midnight.
48
54
  * @param params.collateralWithdrawals - Collateral index and assets per withdrawal; may be empty.
49
- * @param params.collateralReceiver - Recipient of withdrawn collateral.
55
+ * @param params.collateralReceiver - Recipient of withdrawn collateral; must be non-zero and not
56
+ * a Midnight protocol or market token contract when `collateralWithdrawals` is non-empty, and
57
+ * is unused otherwise.
50
58
  * @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
51
59
  * onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
52
60
  * is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
53
- * @param params.deadline - Bounded bundle execution deadline timestamp.
61
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
54
62
  * @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
55
63
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
56
64
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -65,16 +73,23 @@ export interface MidnightTakeRepayWithdrawCollateralParams extends MidnightRefer
65
73
  * @throws {UnknownCollateralIndexError} when a withdrawal targets a collateral index not configured on the market.
66
74
  * @throws {NonPositiveInputError} when the target amount, `minUnits`, `maxBuyerAssets`, a
67
75
  * withdrawal amount or `deadline` is not positive.
68
- * @throws {NegativeInputError} when `maxContinuousFee`, `referralFeePct` or `nativeAmount` is negative.
76
+ * @throws {NegativeInputError} when a takeable offer cap, `maxContinuousFee`, `referralFeePct`
77
+ * or `nativeAmount` is negative.
69
78
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
70
79
  * @throws {NativeAmountOnNonWNativeAssetError} when `market.loanToken` is not wNative.
71
- * @throws {InputExceedsMaxError} when `target.assets` or `target.maxBuyerAssets` is at
72
- * least `maxUint256`, or a `collateralWithdrawals[].assets` amount, `target.units`,
73
- * `minUnits`, `maxBuyerAssets`, `maxContinuousFee` or `deadline` exceeds `uint256`, or
74
- * `nativeAmount` exceeds the maximum wNative amount this call can pull.
80
+ * @throws {InputExceedsMaxError} when a finite target or collateral withdrawal amount, or an
81
+ * offer cap, exceeds `uint128`; when `target.maxBuyerAssets` exceeds `uint128` (an SDK cap: the
82
+ * bundle accepts `uint256`, but a higher ceiling gives no slippage protection); when
83
+ * `maxContinuousFee` or `deadline` exceeds `uint256`; or when `nativeAmount` exceeds the maximum
84
+ * wNative amount this call can pull.
75
85
  * @throws {UnboundedMidnightTakeInputError} when `deadline` is `maxUint256`.
76
86
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
87
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
77
88
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
89
+ * @throws {MidnightZeroReceiverError} when collateral is withdrawn to the zero address.
90
+ * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
91
+ * contract or a market token contract, or when `referralFeeRecipient` is either with a positive
92
+ * referral fee.
78
93
  * @example
79
94
  * ```ts
80
95
  * import { Time } from "@morpho-org/morpho-ts";
@@ -3,9 +3,11 @@ import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
3
  import { encodeFunctionData, maxUint256 } from "viem";
4
4
  import { addTransactionMetadata } from "../../helpers/index.js";
5
5
  import { validateDeadline, validateMidnightNativeAmount, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
6
+ import { validateMidnightReferralFeeCap, validateMidnightTakeableOfferBounds, validateMidnightUint128Field, } from "../../helpers/validateMidnightBounds.js";
6
7
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
8
+ import { validateMidnightReceiver } from "../../helpers/validateMidnightReceiver.js";
7
9
  import { validateTakeableOffers } from "../../helpers/validateTakeableOffers.js";
8
- import { InputExceedsMaxError, NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../types/index.js";
10
+ import { NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../types/index.js";
9
11
  /**
10
12
  * Encodes a `MidnightBundlesV2` reduce-only buy that repays `msg.sender`'s debt by taking
11
13
  * borrow-side offers, optionally repays the remainder directly, then withdraws collateral.
@@ -14,6 +16,11 @@ import { InputExceedsMaxError, NonPositiveInputError, UnboundedMidnightTakeInput
14
16
  * `client.morpho.midnight(chainId).takeRepayWithdrawCollateral(...)` in app flows so the
15
17
  * loan-token approval and the `MidnightBundlesV2` authorization are resolved first.
16
18
  *
19
+ * This builder reads no position or prices, so it applies no `DEFAULT_LLTV_BUFFER` health check:
20
+ * keeping the position inside the buffer is the caller's responsibility. The entity method checks
21
+ * it from `positionData` and `collateralPrices`; onchain, Midnight still rejects a position above
22
+ * LLTV.
23
+ *
17
24
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
18
25
  * @param params.market - Midnight market traded by every takeable offer.
19
26
  * @param params.target - `{ type: "assets", assets, minUnits }` or `{ type: "units", units, maxBuyerAssets }`; `units: maxUint256` targets the sender's whole debt, capped by `maxBuyerAssets` (must be finite; `units: maxUint256` already selects the whole debt).
@@ -25,11 +32,13 @@ import { InputExceedsMaxError, NonPositiveInputError, UnboundedMidnightTakeInput
25
32
  * @param params.takeableOffers - ABI-ready borrow-side offers returned by the Midnight API; must not be empty.
26
33
  * @param params.repayEnabled - Whether the unfilled remainder is repaid directly to Midnight.
27
34
  * @param params.collateralWithdrawals - Collateral index and assets per withdrawal; may be empty.
28
- * @param params.collateralReceiver - Recipient of withdrawn collateral.
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
37
+ * is unused otherwise.
29
38
  * @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
30
39
  * onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
31
40
  * is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
32
- * @param params.deadline - Bounded bundle execution deadline timestamp.
41
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
33
42
  * @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
34
43
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
35
44
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -44,16 +53,23 @@ import { InputExceedsMaxError, NonPositiveInputError, UnboundedMidnightTakeInput
44
53
  * @throws {UnknownCollateralIndexError} when a withdrawal targets a collateral index not configured on the market.
45
54
  * @throws {NonPositiveInputError} when the target amount, `minUnits`, `maxBuyerAssets`, a
46
55
  * withdrawal amount or `deadline` is not positive.
47
- * @throws {NegativeInputError} when `maxContinuousFee`, `referralFeePct` or `nativeAmount` is negative.
56
+ * @throws {NegativeInputError} when a takeable offer cap, `maxContinuousFee`, `referralFeePct`
57
+ * or `nativeAmount` is negative.
48
58
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
49
59
  * @throws {NativeAmountOnNonWNativeAssetError} when `market.loanToken` is not wNative.
50
- * @throws {InputExceedsMaxError} when `target.assets` or `target.maxBuyerAssets` is at
51
- * least `maxUint256`, or a `collateralWithdrawals[].assets` amount, `target.units`,
52
- * `minUnits`, `maxBuyerAssets`, `maxContinuousFee` or `deadline` exceeds `uint256`, or
53
- * `nativeAmount` exceeds the maximum wNative amount this call can pull.
60
+ * @throws {InputExceedsMaxError} when a finite target or collateral withdrawal amount, or an
61
+ * offer cap, exceeds `uint128`; when `target.maxBuyerAssets` exceeds `uint128` (an SDK cap: the
62
+ * bundle accepts `uint256`, but a higher ceiling gives no slippage protection); when
63
+ * `maxContinuousFee` or `deadline` exceeds `uint256`; or when `nativeAmount` exceeds the maximum
64
+ * wNative amount this call can pull.
54
65
  * @throws {UnboundedMidnightTakeInputError} when `deadline` is `maxUint256`.
55
66
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
67
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
56
68
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
69
+ * @throws {MidnightZeroReceiverError} when collateral is withdrawn to the zero address.
70
+ * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
71
+ * contract or a market token contract, or when `referralFeeRecipient` is either with a positive
72
+ * referral fee.
57
73
  * @example
58
74
  * ```ts
59
75
  * import { Time } from "@morpho-org/morpho-ts";
@@ -83,30 +99,34 @@ export const midnightTakeRepayWithdrawCollateral = (params) => {
83
99
  if (assets <= 0n) {
84
100
  throw new NonPositiveInputError(`collateralWithdrawals[${index}].assets`, assets);
85
101
  }
86
- validateUint256Field(`collateralWithdrawals[${index}].assets`, assets);
102
+ if (assets !== maxUint256) {
103
+ validateMidnightUint128Field(`collateralWithdrawals[${index}].assets`, assets);
104
+ }
87
105
  // Throws UnknownCollateralIndexError when the index is not configured on the market.
88
106
  MarketUtils.getCollateralByIndex(params.market, collateralIndex);
89
107
  }
108
+ if (params.collateralWithdrawals.length > 0) {
109
+ // Rejects receivers that would strand the withdrawn collateral in a contract.
110
+ validateMidnightReceiver({
111
+ chainId: params.chainId,
112
+ market: params.market,
113
+ field: "collateralReceiver",
114
+ receiver: params.collateralReceiver,
115
+ });
116
+ }
90
117
  const marketId = validateTakeableOffers({
91
118
  market: params.market,
92
119
  takeableOffers: params.takeableOffers,
93
120
  expectedBuy: false,
94
121
  });
122
+ validateMidnightTakeableOfferBounds(params.takeableOffers);
95
123
  const { target } = params;
96
124
  if (target.type === "assets") {
97
- // `assets` bounds the loan assets pulled; it stays finite since there is no
98
- // "whole debt" sentinel for an assets target.
99
- if (target.assets >= maxUint256) {
100
- throw new InputExceedsMaxError({
101
- field: "target.assets",
102
- value: target.assets,
103
- max: maxUint256 - 1n,
104
- });
105
- }
106
125
  if (target.minUnits <= 0n) {
107
126
  throw new NonPositiveInputError("target.minUnits", target.minUnits);
108
127
  }
109
- validateUint256Field("target.minUnits", target.minUnits);
128
+ validateMidnightUint128Field("target.assets", target.assets);
129
+ validateMidnightUint128Field("target.minUnits", target.minUnits);
110
130
  }
111
131
  else {
112
132
  if (target.units <= 0n) {
@@ -115,16 +135,10 @@ export const midnightTakeRepayWithdrawCollateral = (params) => {
115
135
  if (target.maxBuyerAssets <= 0n) {
116
136
  throw new NonPositiveInputError("target.maxBuyerAssets", target.maxBuyerAssets);
117
137
  }
118
- // `maxBuyerAssets` bounds the loan assets pulled; it stays finite since
119
- // `units: maxUint256` already selects the whole debt.
120
- if (target.maxBuyerAssets >= maxUint256) {
121
- throw new InputExceedsMaxError({
122
- field: "target.maxBuyerAssets",
123
- value: target.maxBuyerAssets,
124
- max: maxUint256 - 1n,
125
- });
138
+ if (target.units !== maxUint256) {
139
+ validateMidnightUint128Field("target.units", target.units);
126
140
  }
127
- validateUint256Field("target.units", target.units);
141
+ validateMidnightUint128Field("target.maxBuyerAssets", target.maxBuyerAssets);
128
142
  }
129
143
  validateUint256Field("maxContinuousFee", params.maxContinuousFee);
130
144
  if (params.deadline === maxUint256) {
@@ -132,6 +146,16 @@ export const midnightTakeRepayWithdrawCollateral = (params) => {
132
146
  }
133
147
  validateDeadline(params.deadline);
134
148
  const { referralFeePct, referralFeeRecipient } = validateReferralFee(params);
149
+ validateMidnightReferralFeeCap(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
+ }
135
159
  const market = MarketUtils.toStruct(params.market);
136
160
  const nativeFunding = validateMidnightNativeAmount({
137
161
  chainId: params.chainId,
@@ -28,9 +28,10 @@ export interface MidnightTakeWithdrawParams extends MidnightReferralFeeParams {
28
28
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
29
29
  * @param params.market - Midnight market traded by every takeable offer.
30
30
  * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
31
- * @param params.receiver - Recipient of the withdrawn loan assets.
31
+ * @param params.receiver - Recipient of the withdrawn loan assets; Midnight protocol and market
32
+ * token contracts are rejected.
32
33
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
33
- * @param params.deadline - Bounded bundle execution deadline timestamp.
34
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
34
35
  * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
35
36
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
36
37
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -44,13 +45,21 @@ export interface MidnightTakeWithdrawParams extends MidnightReferralFeeParams {
44
45
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
45
46
  * @throws {NonPositiveInputError} when the target amount, `maxUnits`, `minSellerAssets` or
46
47
  * `deadline` is not positive.
47
- * @throws {NegativeInputError} when `referralFeePct` is negative.
48
- * @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`,
49
- * `target.minSellerAssets` or `deadline` exceeds `uint256`.
48
+ * @throws {NegativeInputError} when a takeable offer cap or `referralFeePct` is negative.
49
+ * @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`, when
50
+ * `target.maxUnits` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a higher
51
+ * ceiling gives no slippage protection), or when `deadline` exceeds `uint256`.
50
52
  * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or `deadline`
51
53
  * is `maxUint256`.
54
+ * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
55
+ * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
56
+ * market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
52
57
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
58
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
53
59
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
60
+ * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds `target.units`
61
+ * minus the referral fee, or `target.maxUnits` is below `target.assets` plus the referral fee, since
62
+ * a unit sells for at most one asset.
54
63
  * @example
55
64
  * ```ts
56
65
  * import { Time } from "@morpho-org/morpho-ts";