@morpho-org/morpho-sdk 6.6.0 → 7.1.0-next.1

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 (195) hide show
  1. package/MIGRATION-v6-to-v7.md +297 -0
  2. package/README.md +26 -12
  3. package/lib/cjs/abis.d.ts +2 -2
  4. package/lib/cjs/abis.js +7 -2
  5. package/lib/cjs/actions/bundles/common.d.ts +9 -5
  6. package/lib/cjs/actions/bundles/common.js +22 -13
  7. package/lib/cjs/actions/midnight/authorization.d.ts +3 -2
  8. package/lib/cjs/actions/midnight/authorization.js +3 -2
  9. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +153 -0
  10. package/lib/cjs/actions/midnight/cancelAndMake.js +292 -0
  11. package/lib/cjs/actions/midnight/index.d.ts +3 -3
  12. package/lib/cjs/actions/midnight/index.js +3 -3
  13. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +40 -23
  14. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +105 -69
  15. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +52 -27
  16. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +128 -71
  17. package/lib/cjs/actions/midnight/takeBorrow.d.ts +40 -28
  18. package/lib/cjs/actions/midnight/takeBorrow.js +95 -54
  19. package/lib/cjs/actions/midnight/takeLend.d.ts +51 -27
  20. package/lib/cjs/actions/midnight/takeLend.js +111 -54
  21. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +97 -0
  22. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +201 -0
  23. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +69 -0
  24. package/lib/cjs/actions/midnight/takeWithdraw.js +153 -0
  25. package/lib/cjs/actions/midnight/types.d.ts +7 -26
  26. package/lib/cjs/actions/midnight/types.js +0 -13
  27. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -4
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +5 -5
  31. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +2 -2
  32. package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -2
  33. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +24 -8
  34. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +24 -13
  35. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -7
  36. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +11 -7
  37. package/lib/cjs/actions/requirements/midnight/index.d.ts +0 -1
  38. package/lib/cjs/actions/requirements/midnight/index.js +0 -1
  39. package/lib/cjs/blue/abis.d.ts +1 -1
  40. package/lib/cjs/blue/abis.js +5 -1
  41. package/lib/cjs/blue/entities.d.ts +4 -4
  42. package/lib/cjs/blue/entities.js +3 -1
  43. package/lib/cjs/blue/errors.d.ts +2 -2
  44. package/lib/cjs/blue/errors.js +5 -1
  45. package/lib/cjs/blue/fetch.d.ts +2 -2
  46. package/lib/cjs/blue/fetch.js +3 -1
  47. package/lib/cjs/blue/utils.d.ts +1 -1
  48. package/lib/cjs/blue/utils.js +2 -1
  49. package/lib/cjs/constants.d.ts +1 -1
  50. package/lib/cjs/constants.js +2 -1
  51. package/lib/cjs/entities/index.d.ts +6 -6
  52. package/lib/cjs/entities/index.js +3 -1
  53. package/lib/cjs/entities/midnight/midnight.d.ts +585 -108
  54. package/lib/cjs/entities/midnight/midnight.js +984 -509
  55. package/lib/cjs/entities/midnight/types.d.ts +142 -60
  56. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +3 -2
  57. package/lib/cjs/entities/vaultV1/vaultV1.js +32 -34
  58. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +37 -12
  59. package/lib/cjs/entities/vaultV2/vaultV2.js +68 -41
  60. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +5 -3
  61. package/lib/cjs/entities/vaultV2BlueReallocationData.js +9 -3
  62. package/lib/cjs/errors.d.ts +4 -4
  63. package/lib/cjs/errors.js +10 -5
  64. package/lib/cjs/fetch.d.ts +2 -2
  65. package/lib/cjs/fetch.js +3 -1
  66. package/lib/cjs/helpers/callback.d.ts +54 -0
  67. package/lib/cjs/helpers/callback.js +73 -0
  68. package/lib/cjs/helpers/constant.d.ts +2 -0
  69. package/lib/cjs/helpers/constant.js +3 -1
  70. package/lib/cjs/helpers/index.d.ts +3 -2
  71. package/lib/cjs/helpers/index.js +6 -1
  72. package/lib/cjs/helpers/signAndVerifyTypedData.d.ts +3 -3
  73. package/lib/cjs/helpers/signAndVerifyTypedData.js +3 -3
  74. package/lib/cjs/helpers/validate.d.ts +43 -2
  75. package/lib/cjs/helpers/validate.js +60 -3
  76. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +1 -1
  77. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +3 -7
  78. package/lib/cjs/helpers/validateRequirementSpender.d.ts +3 -3
  79. package/lib/cjs/helpers/validateRequirementSpender.js +4 -5
  80. package/lib/cjs/midnight/abis.d.ts +1 -1
  81. package/lib/cjs/midnight/abis.js +3 -2
  82. package/lib/cjs/midnight/errors.d.ts +2 -1
  83. package/lib/cjs/midnight/errors.js +5 -4
  84. package/lib/cjs/midnight/types.d.ts +1 -1
  85. package/lib/cjs/types/action.d.ts +219 -90
  86. package/lib/cjs/types/action.js +103 -20
  87. package/lib/cjs/types/error.d.ts +126 -40
  88. package/lib/cjs/types/error.js +154 -49
  89. package/lib/cjs/utils.d.ts +2 -2
  90. package/lib/cjs/utils.js +4 -2
  91. package/lib/esm/abis.d.ts +2 -2
  92. package/lib/esm/abis.js +2 -2
  93. package/lib/esm/actions/bundles/common.d.ts +9 -5
  94. package/lib/esm/actions/bundles/common.js +22 -13
  95. package/lib/esm/actions/midnight/authorization.d.ts +3 -2
  96. package/lib/esm/actions/midnight/authorization.js +3 -2
  97. package/lib/esm/actions/midnight/cancelAndMake.d.ts +153 -0
  98. package/lib/esm/actions/midnight/cancelAndMake.js +288 -0
  99. package/lib/esm/actions/midnight/index.d.ts +3 -3
  100. package/lib/esm/actions/midnight/index.js +3 -3
  101. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +40 -23
  102. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +108 -72
  103. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +52 -27
  104. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +131 -74
  105. package/lib/esm/actions/midnight/takeBorrow.d.ts +40 -28
  106. package/lib/esm/actions/midnight/takeBorrow.js +98 -57
  107. package/lib/esm/actions/midnight/takeLend.d.ts +51 -27
  108. package/lib/esm/actions/midnight/takeLend.js +114 -57
  109. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +97 -0
  110. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +197 -0
  111. package/lib/esm/actions/midnight/takeWithdraw.d.ts +69 -0
  112. package/lib/esm/actions/midnight/takeWithdraw.js +149 -0
  113. package/lib/esm/actions/midnight/types.d.ts +7 -26
  114. package/lib/esm/actions/midnight/types.js +1 -12
  115. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  116. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
  117. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -4
  118. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +5 -5
  119. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +2 -2
  120. package/lib/esm/actions/requirements/getRequirementsApproval.js +2 -2
  121. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +24 -8
  122. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +25 -14
  123. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -7
  124. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +11 -7
  125. package/lib/esm/actions/requirements/midnight/index.d.ts +0 -1
  126. package/lib/esm/actions/requirements/midnight/index.js +0 -1
  127. package/lib/esm/blue/abis.d.ts +1 -1
  128. package/lib/esm/blue/abis.js +1 -1
  129. package/lib/esm/blue/entities.d.ts +4 -4
  130. package/lib/esm/blue/entities.js +2 -2
  131. package/lib/esm/blue/errors.d.ts +2 -2
  132. package/lib/esm/blue/errors.js +2 -2
  133. package/lib/esm/blue/fetch.d.ts +2 -2
  134. package/lib/esm/blue/fetch.js +2 -2
  135. package/lib/esm/blue/utils.d.ts +1 -1
  136. package/lib/esm/blue/utils.js +1 -1
  137. package/lib/esm/constants.d.ts +1 -1
  138. package/lib/esm/constants.js +1 -1
  139. package/lib/esm/entities/index.d.ts +6 -6
  140. package/lib/esm/entities/index.js +2 -2
  141. package/lib/esm/entities/midnight/midnight.d.ts +585 -108
  142. package/lib/esm/entities/midnight/midnight.js +990 -515
  143. package/lib/esm/entities/midnight/types.d.ts +142 -60
  144. package/lib/esm/entities/vaultV1/vaultV1.d.ts +3 -2
  145. package/lib/esm/entities/vaultV1/vaultV1.js +33 -35
  146. package/lib/esm/entities/vaultV2/vaultV2.d.ts +37 -12
  147. package/lib/esm/entities/vaultV2/vaultV2.js +69 -42
  148. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +5 -3
  149. package/lib/esm/entities/vaultV2BlueReallocationData.js +9 -3
  150. package/lib/esm/errors.d.ts +4 -4
  151. package/lib/esm/errors.js +4 -4
  152. package/lib/esm/fetch.d.ts +2 -2
  153. package/lib/esm/fetch.js +2 -2
  154. package/lib/esm/helpers/callback.d.ts +54 -0
  155. package/lib/esm/helpers/callback.js +68 -0
  156. package/lib/esm/helpers/constant.d.ts +2 -0
  157. package/lib/esm/helpers/constant.js +2 -0
  158. package/lib/esm/helpers/index.d.ts +3 -2
  159. package/lib/esm/helpers/index.js +3 -2
  160. package/lib/esm/helpers/signAndVerifyTypedData.d.ts +3 -3
  161. package/lib/esm/helpers/signAndVerifyTypedData.js +3 -3
  162. package/lib/esm/helpers/validate.d.ts +43 -2
  163. package/lib/esm/helpers/validate.js +58 -2
  164. package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +1 -1
  165. package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +3 -7
  166. package/lib/esm/helpers/validateRequirementSpender.d.ts +3 -3
  167. package/lib/esm/helpers/validateRequirementSpender.js +4 -5
  168. package/lib/esm/midnight/abis.d.ts +1 -1
  169. package/lib/esm/midnight/abis.js +1 -1
  170. package/lib/esm/midnight/errors.d.ts +2 -1
  171. package/lib/esm/midnight/errors.js +2 -1
  172. package/lib/esm/midnight/types.d.ts +1 -1
  173. package/lib/esm/types/action.d.ts +219 -90
  174. package/lib/esm/types/action.js +103 -19
  175. package/lib/esm/types/error.d.ts +126 -40
  176. package/lib/esm/types/error.js +135 -38
  177. package/lib/esm/utils.d.ts +2 -2
  178. package/lib/esm/utils.js +2 -2
  179. package/package.json +10 -10
  180. package/lib/cjs/actions/midnight/cancelOffer.d.ts +0 -38
  181. package/lib/cjs/actions/midnight/cancelOffer.js +0 -73
  182. package/lib/cjs/actions/midnight/mempoolSubmitOffers.d.ts +0 -52
  183. package/lib/cjs/actions/midnight/mempoolSubmitOffers.js +0 -72
  184. package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.d.ts +0 -40
  185. package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.js +0 -59
  186. package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +0 -42
  187. package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +0 -70
  188. package/lib/esm/actions/midnight/cancelOffer.d.ts +0 -38
  189. package/lib/esm/actions/midnight/cancelOffer.js +0 -69
  190. package/lib/esm/actions/midnight/mempoolSubmitOffers.d.ts +0 -52
  191. package/lib/esm/actions/midnight/mempoolSubmitOffers.js +0 -68
  192. package/lib/esm/actions/midnight/setterRatifierRatifyRoot.d.ts +0 -40
  193. package/lib/esm/actions/midnight/setterRatifierRatifyRoot.js +0 -55
  194. package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +0 -42
  195. package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +0 -66
@@ -1,14 +1,27 @@
1
- import { EcrecoverRatifierUtils, fetchAccrualPosition, fetchMarket, InvalidTreeError, MarketParams, MarketUtils, Payload, SetterRatifierUtils, Tree, } from "@morpho-org/midnight-sdk";
2
- import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { isAddressEqual, } from "viem";
4
- import { mempoolSubmitOffers, midnightCancelOffer, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, } from "../../actions/midnight/index.js";
5
- import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, getSetterRatifierRatifyRootRequirement, } from "../../actions/requirements/index.js";
1
+ import { MarketUtils as BlueMarketUtils, MathLib, UnsupportedMarketIrmError, } from "@morpho-org/blue-sdk";
2
+ import { fetchMarket as fetchBlueMarket } from "@morpho-org/blue-sdk-viem";
3
+ import { fetchAccrualPosition, fetchMarket, MarketParams, MarketUtils, Payload, PriceRatifierV1, RateRatifierV1, Tree, } from "@morpho-org/midnight-sdk";
4
+ import { _try, getChainAddress, Time } from "@morpho-org/morpho-ts";
5
+ import { isAddressEqual } from "viem";
6
+ import { midnightCancelAndMake, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, midnightTakeRepayWithdrawCollateral, midnightTakeWithdraw, } from "../../actions/midnight/index.js";
7
+ import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, } from "../../actions/requirements/index.js";
8
+ import { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "../../helpers/callback.js";
9
+ import { MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS } from "../../helpers/constant.js";
6
10
  import { validateChainId } from "../../helpers/index.js";
7
- import { signAndVerifyTypedData } from "../../helpers/signAndVerifyTypedData.js";
8
11
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
9
12
  import { validateOfferSides } from "../../helpers/validateOfferSides.js";
10
- import { validateTakeableOffers } from "../../helpers/validateTakeableOffers.js";
11
- import { AccrualPositionUserMismatchError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferRootMismatchError, MidnightOfferRootOfferCountMismatchError, MidnightOfferRootOwnerMismatchError, MidnightOfferRootRatifierMismatchError, MidnightRedeemExceedsCreditError, MissingAccrualPositionError, MissingMidnightOfferRootSignatureError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, selectRequirementSignatures, UnknownMidnightRatifierError, UnpreparedMidnightOfferRootSignatureError, } from "../../types/index.js";
13
+ import { AccrualPositionUserMismatchError, EmptyBlueParkingMarketError, ExpiredDeadlineError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightTakeDeadlineTooFarError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, ZeroBlueParkingSharesError, } from "../../types/index.js";
14
+ const offerMarketParams = (offer) => "params" in offer.market ? offer.market.params : offer.market;
15
+ const validateTakeDeadlineWindow = (deadline) => {
16
+ const now = Time.timestamp();
17
+ if (deadline <= now) {
18
+ throw new ExpiredDeadlineError(deadline, now);
19
+ }
20
+ const maxDeadline = now + MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
21
+ if (deadline > maxDeadline) {
22
+ throw new MidnightTakeDeadlineTooFarError({ deadline, maxDeadline });
23
+ }
24
+ };
12
25
  const assertNonNegativeAmount = (label, amount) => {
13
26
  if (amount < 0n)
14
27
  throw new NegativeInputError(label, amount);
@@ -17,6 +30,12 @@ const assertPositiveAmount = (label, amount) => {
17
30
  if (amount <= 0n)
18
31
  throw new NonPositiveInputError(label, amount);
19
32
  };
33
+ const rejectReduceOnlyOffers = (offers) => {
34
+ offers.forEach((offer, index) => {
35
+ if (offer.reduceOnly)
36
+ throw new MidnightOfferReduceOnlyError({ index });
37
+ });
38
+ };
20
39
  const validateMarketData = (market, chainId) => {
21
40
  // Reject snapshots from another chain deployment before exposing requirements.
22
41
  validateMidnightMarket({ market, chainId });
@@ -108,22 +127,26 @@ export class MorphoMidnight {
108
127
  /**
109
128
  * Builds and validates a maker offer tree against the Midnight mempool API.
110
129
  *
111
- * @param params - Maker account, raw offer or group inputs, and optional API validation controls.
130
+ * @param params - Maker account, PriceRatifierV1 or RateRatifierV1 tree input, and optional API validation controls.
112
131
  * @param params.accountAddress - Maker expected on every offer.
113
- * @param params.offers - Offer, group, tree, or list accepted by `Tree.create`.
132
+ * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
114
133
  * @param params.validation - Optional Midnight mempool API request controls.
115
- * @returns Prepared tree data used by maker flows.
134
+ * @returns Prepared tree, groups, ratifier, and encoded payload used by maker flows.
116
135
  * @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
117
136
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
137
+ * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
118
138
  * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
139
+ * @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
140
+ * @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
119
141
  * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
120
142
  * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
121
- * @throws {UnknownMidnightRatifierError} when the tree uses an unsupported ratifier.
143
+ * @throws {UnknownAddressError} when the chain has no deployment for the tree's V1 ratifier.
144
+ * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
122
145
  * @example
123
146
  * ```ts
124
147
  * const offersData = await midnight.getOffersData({
125
148
  * accountAddress: maker,
126
- * offers: [offer],
149
+ * offers: { type: "rateV1", entries: [{ offer, rate }] },
127
150
  * });
128
151
  * ```
129
152
  */
@@ -139,7 +162,21 @@ export class MorphoMidnight {
139
162
  actualMaker: offer.maker,
140
163
  });
141
164
  }
142
- const market = "params" in offer.market ? offer.market.params : offer.market;
165
+ if (offer.continuousFeeCap !== 0n) {
166
+ throw new MidnightOfferContinuousFeeCapError({
167
+ index,
168
+ continuousFeeCap: offer.continuousFeeCap,
169
+ });
170
+ }
171
+ if (!offer.buy &&
172
+ !isAddressEqual(offer.receiverIfMakerIsSeller, offer.maker)) {
173
+ throw new MidnightOfferSellerReceiverMismatchError({
174
+ index,
175
+ expectedReceiver: offer.maker,
176
+ actualReceiver: offer.receiverIfMakerIsSeller,
177
+ });
178
+ }
179
+ const market = offerMarketParams(offer);
143
180
  if (market.chainId !== BigInt(this.chainId)) {
144
181
  throw new MidnightOfferMarketChainMismatchError({
145
182
  index,
@@ -155,25 +192,17 @@ export class MorphoMidnight {
155
192
  });
156
193
  }
157
194
  });
158
- const firstOffer = tree.offers[0];
159
- if (firstOffer == null) {
160
- throw new InvalidTreeError("Tree must contain at least one offer.");
161
- }
162
- const ratifier = firstOffer.ratifier;
163
- const ecrecoverRatifier = getChainAddress(this.chainId, "ecrecoverRatifier");
164
- const setterRatifier = getChainAddress(this.chainId, "setterRatifier");
165
- const ratifierType = isAddressEqual(ratifier, ecrecoverRatifier)
166
- ? "ecrecover"
167
- : isAddressEqual(ratifier, setterRatifier)
168
- ? "setter"
169
- : undefined;
170
- if (ratifierType == null) {
171
- throw new UnknownMidnightRatifierError({
172
- ratifier,
173
- ecrecoverRatifier,
174
- setterRatifier,
175
- });
176
- }
195
+ const ratifierType = tree.type;
196
+ const ratifier = getChainAddress(this.chainId, ratifierType === "priceV1" ? "priceRatifierV1" : "rateRatifierV1");
197
+ tree.offers.forEach((offer, index) => {
198
+ if (!isAddressEqual(offer.ratifier, ratifier)) {
199
+ throw new MidnightOfferRatifierMismatchError({
200
+ index,
201
+ expectedRatifier: ratifier,
202
+ actualRatifier: offer.ratifier,
203
+ });
204
+ }
205
+ });
177
206
  const groups = [];
178
207
  const seenGroups = new Set();
179
208
  for (const offer of tree.offers) {
@@ -188,260 +217,434 @@ export class MorphoMidnight {
188
217
  ...params.validation,
189
218
  chainId: this.chainId,
190
219
  });
191
- if (ratifierType === "setter") {
192
- // Setter ratifier payload generation validates that the created tree has one ratifier.
193
- const items = SetterRatifierUtils.ratify({ tree });
194
- return {
195
- accountAddress: params.accountAddress,
196
- groups,
197
- tree,
198
- ratifierType,
199
- ratifier,
200
- setterPayload: await Payload.encode(items),
201
- };
202
- }
203
- // Ecrecover typed-data generation validates that the created tree has one ratifier.
204
- EcrecoverRatifierUtils.typedData({ tree, chainId: this.chainId });
220
+ const items = tree.type === "priceV1"
221
+ ? PriceRatifierV1.ratify({ tree })
222
+ : RateRatifierV1.ratify({ tree });
205
223
  return {
206
224
  accountAddress: params.accountAddress,
207
225
  groups,
208
226
  tree,
209
227
  ratifierType,
210
228
  ratifier,
229
+ payload: await Payload.encode(items),
211
230
  };
212
231
  }
213
232
  /**
214
- * Prepares a lend-side take using caller-provided market data and API offers.
233
+ * Prepares a `MidnightBundlesV2` buy that lends into borrow-side offers for `accountAddress`.
215
234
  *
216
- * @param params - Lender, market snapshot, target assets, units, offers, and deadline.
217
- * @param params.accountAddress - Lender executing the take.
235
+ * @param params - Lender, market snapshot, buy target, offers, fee cap, deadline, and optional referral fee.
236
+ * @param params.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
218
237
  * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
219
- * @param params.assets - Loan assets spent by the lender.
220
- * @param params.minUnits - Minimum credit units accepted.
238
+ * @param params.target - `{ type: "assets", assets, minUnits }` or `{ type: "units", units, maxBuyerAssets }`.
239
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
240
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
241
+ * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
242
+ * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
243
+ * required for the full pulled amount.
221
244
  * @param params.takeableOffers - Borrow-side offers returned by the Midnight API.
245
+ * @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
246
+ * onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
247
+ * is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
222
248
  * @param params.deadline - Bundle execution deadline timestamp.
223
- * @returns Lazy approval/authorization requirements and a synchronous transaction builder.
249
+ * @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
250
+ * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
251
+ * @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
224
252
  * @throws {ChainIdMismatchError} when client or market data targets another chain.
253
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
254
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
255
+ * @throws {InputExceedsMaxError} when `target.assets`, `target.units`, `minUnits`, `maxBuyerAssets`
256
+ * or `maxContinuousFee` exceeds `uint256`, or `nativeAmount` exceeds the maximum
257
+ * wNative amount this call can pull.
225
258
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
226
- * @throws {NonPositiveInputError} when `assets` is non-positive.
227
- * @throws {NegativeInputError} when `minUnits` or `deadline` is negative.
259
+ * @throws {NonPositiveInputError} when the target amount, `minUnits` or `maxBuyerAssets` is not positive.
260
+ * @throws {NegativeInputError} when `maxContinuousFee`, `referralFeePct` or `nativeAmount` is negative.
261
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
262
+ * @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
263
+ * @throws {UnboundedMidnightTakeInputError} when `target.units` or
264
+ * `target.maxBuyerAssets` is `maxUint256`.
265
+ * @throws {ExpiredDeadlineError} when `deadline` has expired.
266
+ * @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
228
267
  * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
229
268
  * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
230
269
  * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
270
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
271
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
272
+ * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
231
273
  * @example
232
274
  * ```ts
233
275
  * const output = midnight.takeLend({
234
276
  * accountAddress: lender,
235
277
  * marketData,
236
- * assets: 1_000_000n,
237
- * minUnits: 900_000n,
278
+ * target: { type: "assets", assets: 1_000_000n, minUnits: 900_000n },
238
279
  * takeableOffers: quote.data.takeableOffers,
239
- * deadline: maxUint256,
280
+ * maxContinuousFee: maxUint256,
281
+ * deadline: Time.timestamp() + 600n,
240
282
  * });
241
283
  * ```
242
284
  */
243
285
  takeLend(params) {
244
286
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
245
- validateMarketData(params.marketData, this.chainId);
246
- assertPositiveAmount("assets", params.assets);
247
- assertNonNegativeAmount("minUnits", params.minUnits);
248
- assertNonNegativeAmount("deadline", params.deadline);
249
- // Reject inconsistent quotes before exposing requirement reads.
250
- validateTakeableOffers({
251
- market: params.marketData.params,
287
+ validateTakeDeadlineWindow(params.deadline);
288
+ const market = params.marketData.params;
289
+ const tx = midnightTakeLend({
290
+ chainId: this.chainId,
291
+ market,
292
+ target: params.target,
293
+ nativeAmount: params.nativeAmount,
252
294
  takeableOffers: params.takeableOffers,
253
- expectedBuy: false,
295
+ maxContinuousFee: params.maxContinuousFee,
296
+ deadline: params.deadline,
297
+ referralFeePct: params.referralFeePct,
298
+ referralFeeRecipient: params.referralFeeRecipient,
299
+ metadata: this.client.options.metadata,
254
300
  });
255
- const market = params.marketData;
256
- const midnightBundles = getChainAddress(this.chainId, "midnightBundles");
301
+ const pulledAssets = params.target.type === "assets"
302
+ ? params.target.assets
303
+ : params.target.maxBuyerAssets;
257
304
  return {
258
- getRequirements: async () => {
259
- const requirements = [
260
- ...(await getMidnightApprovalRequirements({
261
- viemClient: this.client.viemClient,
262
- chainId: this.chainId,
263
- token: market.params.loanToken,
264
- owner: params.accountAddress,
265
- spender: midnightBundles,
266
- amount: params.assets,
267
- })),
268
- ];
269
- const authorization = await getMidnightAuthorizationRequirement({
305
+ getRequirements: async (requirementsParams) => {
306
+ const approvals = await getMidnightApprovalRequirements({
270
307
  viemClient: this.client.viemClient,
271
308
  chainId: this.chainId,
309
+ token: market.loanToken,
272
310
  owner: params.accountAddress,
273
- authorized: midnightBundles,
311
+ spender: tx.to,
312
+ amount: pulledAssets,
313
+ approvalAmount: requirementsParams?.approvalAmount,
274
314
  });
275
- if (authorization)
276
- requirements.push(authorization);
277
- return requirements;
315
+ const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
316
+ return [...approvals, ...authorization];
278
317
  },
279
- buildTx: () => midnightTakeLend({
280
- chainId: this.chainId,
281
- market: market.params,
282
- assets: params.assets,
283
- minUnits: params.minUnits,
284
- taker: params.accountAddress,
285
- takeableOffers: params.takeableOffers,
286
- deadline: params.deadline,
287
- metadata: this.client.options.metadata,
288
- }),
318
+ buildTx: () => tx,
289
319
  };
290
320
  }
291
321
  /**
292
- * Prepares a borrow-side take using caller-provided market data and API offers.
322
+ * Prepares a `MidnightBundlesV2` sell that borrows from lend-side offers for `accountAddress`.
323
+ *
324
+ * The bundle first withdraws as much of the sender's existing credit as the target and market
325
+ * liquidity allow, then fills the rest from offers.
293
326
  *
294
- * @param params - Borrower, market snapshot, target assets, unit cap, offers, and deadline.
295
- * @param params.accountAddress - Borrower executing the take.
327
+ * @param params - Borrower, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
328
+ * @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
296
329
  * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
297
- * @param params.loanAssets - Loan assets received by the borrower.
298
- * @param params.maxUnits - Maximum debt units accepted.
330
+ * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
331
+ * @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
299
332
  * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
300
- * @param params.deadline - Bundle execution deadline timestamp.
301
- * @returns Lazy authorization requirements and a synchronous transaction builder.
333
+ * @param params.deadline - Bounded bundle execution deadline timestamp.
334
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
335
+ * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
336
+ * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
302
337
  * @throws {ChainIdMismatchError} when client or market data targets another chain.
338
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
339
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
340
+ * @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`
341
+ * or `target.minSellerAssets` exceeds `uint256`.
303
342
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
304
- * @throws {NonPositiveInputError} when `loanAssets` or `maxUnits` is non-positive.
305
- * @throws {NegativeInputError} when `deadline` is negative.
343
+ * @throws {NonPositiveInputError} when the target amount, `maxUnits` or `minSellerAssets` is not positive.
344
+ * @throws {NegativeInputError} when `referralFeePct` is negative.
345
+ * @throws {UnboundedMidnightTakeInputError} when `target.units` or
346
+ * `target.maxUnits` is `maxUint256`.
347
+ * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
348
+ * @throws {ExpiredDeadlineError} when `deadline` has expired.
349
+ * @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
306
350
  * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
307
351
  * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
308
352
  * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
353
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
354
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
309
355
  * @example
310
356
  * ```ts
311
357
  * const output = midnight.takeBorrow({
312
358
  * accountAddress: borrower,
313
359
  * marketData,
314
- * loanAssets: 1_000_000n,
315
- * maxUnits: 1_100_000n,
360
+ * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
316
361
  * takeableOffers: quote.data.takeableOffers,
317
- * deadline: maxUint256,
362
+ * deadline: Time.timestamp() + 600n,
318
363
  * });
319
364
  * ```
320
365
  */
321
366
  takeBorrow(params) {
322
367
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
323
- validateMarketData(params.marketData, this.chainId);
324
- assertPositiveAmount("loanAssets", params.loanAssets);
325
- assertPositiveAmount("maxUnits", params.maxUnits);
326
- assertNonNegativeAmount("deadline", params.deadline);
327
- // Reject inconsistent quotes before exposing requirement reads.
328
- validateTakeableOffers({
368
+ validateTakeDeadlineWindow(params.deadline);
369
+ const tx = midnightTakeBorrow({
370
+ chainId: this.chainId,
329
371
  market: params.marketData.params,
372
+ target: params.target,
373
+ receiver: params.receiver ?? params.accountAddress,
330
374
  takeableOffers: params.takeableOffers,
331
- expectedBuy: true,
375
+ deadline: params.deadline,
376
+ referralFeePct: params.referralFeePct,
377
+ referralFeeRecipient: params.referralFeeRecipient,
378
+ metadata: this.client.options.metadata,
332
379
  });
333
- const market = params.marketData;
334
- const midnightBundles = getChainAddress(this.chainId, "midnightBundles");
335
380
  return {
336
- getRequirements: async () => {
337
- const requirements = [];
338
- const authorization = await getMidnightAuthorizationRequirement({
381
+ getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
382
+ buildTx: () => tx,
383
+ };
384
+ }
385
+ /**
386
+ * Prepares a reduce-only `MidnightBundlesV2` sell that withdraws `accountAddress`'s credit.
387
+ *
388
+ * The bundle first redeems as much credit as the target and market liquidity allow, then sells
389
+ * the rest to lend-side offers. `reduceOnly` is always set, so it never opens debt. Use `redeem`
390
+ * for a direct redemption without offers.
391
+ *
392
+ * @param params - Lender, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
393
+ * @param params.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
394
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
395
+ * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
396
+ * @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
397
+ * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
398
+ * @param params.deadline - Bundle execution deadline timestamp.
399
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
400
+ * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
401
+ * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
402
+ * @throws {ChainIdMismatchError} when client or market data targets another chain.
403
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
404
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
405
+ * @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`
406
+ * or `target.minSellerAssets` exceeds `uint256`.
407
+ * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
408
+ * @throws {NonPositiveInputError} when the target amount, `maxUnits` or `minSellerAssets` is
409
+ * not positive.
410
+ * @throws {NegativeInputError} when `referralFeePct` is negative.
411
+ * @throws {UnboundedMidnightTakeInputError} when `target.units` or `target.maxUnits` is `maxUint256`.
412
+ * @throws {ExpiredDeadlineError} when `deadline` has expired.
413
+ * @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
414
+ * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
415
+ * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
416
+ * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
417
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
418
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
419
+ * @example
420
+ * ```ts
421
+ * const output = midnight.takeWithdraw({
422
+ * accountAddress: lender,
423
+ * marketData,
424
+ * target: { type: "units", units: credit, minSellerAssets: 990_000n },
425
+ * takeableOffers: quote.data.takeableOffers,
426
+ * deadline: Time.timestamp() + 600n,
427
+ * });
428
+ * ```
429
+ */
430
+ takeWithdraw(params) {
431
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
432
+ validateTakeDeadlineWindow(params.deadline);
433
+ const tx = midnightTakeWithdraw({
434
+ chainId: this.chainId,
435
+ market: params.marketData.params,
436
+ target: params.target,
437
+ receiver: params.receiver ?? params.accountAddress,
438
+ takeableOffers: params.takeableOffers,
439
+ deadline: params.deadline,
440
+ referralFeePct: params.referralFeePct,
441
+ referralFeeRecipient: params.referralFeeRecipient,
442
+ metadata: this.client.options.metadata,
443
+ });
444
+ return {
445
+ getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
446
+ buildTx: () => tx,
447
+ };
448
+ }
449
+ /**
450
+ * Prepares one `MidnightBundlesV2` sell that supplies collateral and borrows from lend-side
451
+ * offers for `accountAddress`.
452
+ *
453
+ * Like `takeBorrow`, the sender's existing credit is withdrawn before offers are taken.
454
+ *
455
+ * @param params - Borrower, market snapshot, collateral supplies, sell target, offers, deadline, receiver, and optional referral fee.
456
+ * @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
457
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
458
+ * @param params.collateralSupplies - Collateral index and assets per supply; must not be empty.
459
+ * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
460
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
461
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
462
+ * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
463
+ * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
464
+ * required for the full pulled amount.
465
+ * @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
466
+ * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
467
+ * @param params.deadline - Bounded bundle execution deadline timestamp.
468
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
469
+ * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
470
+ * @returns Lazy collateral approvals and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
471
+ * @throws {ChainIdMismatchError} when client or market data targets another chain.
472
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
473
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
474
+ * @throws {InputExceedsMaxError} when a `collateralSupplies[].assets` amount, `target.assets`,
475
+ * `target.maxUnits`, `target.units` or `target.minSellerAssets` exceeds `uint256`, or
476
+ * `nativeAmount` exceeds the maximum wNative collateral amount this call can pull.
477
+ * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
478
+ * @throws {EmptyMidnightCollateralSuppliesError} when no collateral supply is provided.
479
+ * @throws {UnknownCollateralIndexError} when a collateral index is not configured.
480
+ * @throws {NonPositiveInputError} when a supply amount, the target amount, `maxUnits` or `minSellerAssets` is not positive.
481
+ * @throws {NegativeInputError} when `referralFeePct` or `nativeAmount` is negative.
482
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
483
+ * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
484
+ * @throws {UnboundedMidnightTakeInputError} when `target.units` or
485
+ * `target.maxUnits` is `maxUint256`.
486
+ * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
487
+ * @throws {ExpiredDeadlineError} when `deadline` has expired.
488
+ * @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
489
+ * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
490
+ * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
491
+ * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
492
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
493
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
494
+ * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
495
+ * @example
496
+ * ```ts
497
+ * const output = midnight.supplyCollateralTakeBorrow({
498
+ * accountAddress: borrower,
499
+ * marketData,
500
+ * collateralSupplies: [{ collateralIndex: 0n, assets: 2_000_000n }],
501
+ * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
502
+ * takeableOffers: quote.data.takeableOffers,
503
+ * deadline: Time.timestamp() + 600n,
504
+ * });
505
+ * ```
506
+ */
507
+ supplyCollateralTakeBorrow(params) {
508
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
509
+ validateTakeDeadlineWindow(params.deadline);
510
+ const market = params.marketData.params;
511
+ const tx = midnightSupplyCollateralTakeBorrow({
512
+ chainId: this.chainId,
513
+ market,
514
+ collateralSupplies: params.collateralSupplies,
515
+ nativeAmount: params.nativeAmount,
516
+ target: params.target,
517
+ receiver: params.receiver ?? params.accountAddress,
518
+ takeableOffers: params.takeableOffers,
519
+ deadline: params.deadline,
520
+ referralFeePct: params.referralFeePct,
521
+ referralFeeRecipient: params.referralFeeRecipient,
522
+ metadata: this.client.options.metadata,
523
+ });
524
+ // Sum per token so a token supplied at several indices gets one approval.
525
+ const collateralAmounts = new Map();
526
+ for (const { collateralIndex, assets } of tx.action.args
527
+ .collateralSupplies) {
528
+ const { token } = MarketUtils.getCollateralByIndex(market, collateralIndex);
529
+ collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
530
+ }
531
+ return {
532
+ getRequirements: async (requirementsParams) => {
533
+ const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => getMidnightApprovalRequirements({
339
534
  viemClient: this.client.viemClient,
340
535
  chainId: this.chainId,
536
+ token,
341
537
  owner: params.accountAddress,
342
- authorized: midnightBundles,
343
- });
344
- if (authorization)
345
- requirements.push(authorization);
346
- return requirements;
538
+ spender: tx.to,
539
+ amount,
540
+ approvalAmount: requirementsParams?.approvalAmount,
541
+ })));
542
+ const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
543
+ return [...approvals.flat(), ...authorization];
347
544
  },
348
- buildTx: () => midnightTakeBorrow({
349
- chainId: this.chainId,
350
- market: market.params,
351
- loanAssets: params.loanAssets,
352
- maxUnits: params.maxUnits,
353
- taker: params.accountAddress,
354
- takeableOffers: params.takeableOffers,
355
- deadline: params.deadline,
356
- metadata: this.client.options.metadata,
357
- }),
545
+ buildTx: () => tx,
358
546
  };
359
547
  }
360
548
  /**
361
- * Prepares one bundle that supplies collateral and takes borrow-side offers.
549
+ * Prepares a `MidnightBundlesV2` reduce-only buy that repays `accountAddress`'s debt by taking
550
+ * borrow-side offers, optionally repays the remainder directly, then withdraws collateral.
551
+ *
552
+ * `reduceOnly` is always set, so the buy never opens a lender position.
362
553
  *
363
- * @param params - Borrower, market snapshot, collateral and loan amounts, unit cap, offers, and deadline.
364
- * @param params.accountAddress - Borrower executing the bundle.
554
+ * @param params - Borrower, market snapshot, buy target, offers, repay fallback, withdrawals, fee cap, deadline and optional referral fee.
555
+ * @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
365
556
  * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
366
- * @param params.collateralAssets - Collateral assets supplied before borrowing.
367
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
368
- * @param params.loanAssets - Loan assets received by the borrower.
369
- * @param params.maxUnits - Maximum debt units accepted.
370
- * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
557
+ * @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).
558
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
559
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
560
+ * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
561
+ * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
562
+ * required for the full pulled amount.
563
+ * @param params.takeableOffers - Borrow-side offers returned by the Midnight API.
564
+ * @param params.repayEnabled - Whether the unfilled remainder is repaid directly to Midnight.
565
+ * @param params.collateralWithdrawals - Optional collateral withdrawals; `maxUint256` assets withdraws the whole balance.
566
+ * @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`.
567
+ * @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
568
+ * onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
569
+ * is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
371
570
  * @param params.deadline - Bundle execution deadline timestamp.
372
- * @returns Lazy collateral approval/authorization requirements and a synchronous transaction builder.
571
+ * @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
572
+ * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
573
+ * @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
574
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
373
575
  * @throws {ChainIdMismatchError} when client or market data targets another chain.
576
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
374
577
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
375
- * @throws {NonPositiveInputError} when collateral, loan assets, or `maxUnits` is non-positive.
376
- * @throws {NegativeInputError} when `deadline` is negative.
377
- * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
578
+ * @throws {NonPositiveInputError} when the target amount, `minUnits`, `maxBuyerAssets` or a
579
+ * withdrawal amount is not positive.
580
+ * @throws {NegativeInputError} when `maxContinuousFee`, `referralFeePct` or `nativeAmount` is negative.
581
+ * @throws {InputExceedsMaxError} when `target.assets` or `target.maxBuyerAssets` is at
582
+ * least `maxUint256`, or a `collateralWithdrawals[].assets` amount, `target.units`,
583
+ * `minUnits`, `maxBuyerAssets` or `maxContinuousFee` exceeds `uint256`, or
584
+ * `nativeAmount` exceeds the maximum wNative amount this call can pull, including zero for a
585
+ * withdraw-only call.
586
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
587
+ * @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
588
+ * @throws {UnknownCollateralIndexError} when a withdrawal targets a collateral index not configured on the market.
378
589
  * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
379
590
  * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
380
591
  * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
592
+ * @throws {ExpiredDeadlineError} when `deadline` has expired.
593
+ * @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
594
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
595
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
596
+ * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
381
597
  * @example
382
598
  * ```ts
383
- * const output = midnight.supplyCollateralTakeBorrow({
599
+ * const output = midnight.takeRepayWithdrawCollateral({
384
600
  * accountAddress: borrower,
385
601
  * marketData,
386
- * collateralAssets: 2_000_000n,
387
- * loanAssets: 1_000_000n,
388
- * maxUnits: 1_100_000n,
602
+ * target: { type: "units", units: 1_000_000n, maxBuyerAssets: 990_000n },
389
603
  * takeableOffers: quote.data.takeableOffers,
390
- * deadline: maxUint256,
604
+ * repayEnabled: true,
605
+ * collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
606
+ * maxContinuousFee: maxUint256,
607
+ * deadline: Time.timestamp() + 600n,
391
608
  * });
392
609
  * ```
393
610
  */
394
- supplyCollateralTakeBorrow(params) {
611
+ takeRepayWithdrawCollateral(params) {
395
612
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
396
- validateMarketData(params.marketData, this.chainId);
397
- assertPositiveAmount("collateralAssets", params.collateralAssets);
398
- assertPositiveAmount("loanAssets", params.loanAssets);
399
- assertPositiveAmount("maxUnits", params.maxUnits);
400
- assertNonNegativeAmount("deadline", params.deadline);
401
- // Reject inconsistent quotes before exposing requirement reads.
402
- validateTakeableOffers({
403
- market: params.marketData.params,
613
+ validateTakeDeadlineWindow(params.deadline);
614
+ const market = params.marketData.params;
615
+ const tx = midnightTakeRepayWithdrawCollateral({
616
+ chainId: this.chainId,
617
+ market,
618
+ target: params.target,
619
+ nativeAmount: params.nativeAmount,
404
620
  takeableOffers: params.takeableOffers,
405
- expectedBuy: true,
621
+ repayEnabled: params.repayEnabled,
622
+ collateralWithdrawals: params.collateralWithdrawals ?? [],
623
+ collateralReceiver: params.collateralReceiver ?? params.accountAddress,
624
+ maxContinuousFee: params.maxContinuousFee,
625
+ deadline: params.deadline,
626
+ referralFeePct: params.referralFeePct,
627
+ referralFeeRecipient: params.referralFeeRecipient,
628
+ metadata: this.client.options.metadata,
406
629
  });
407
- const market = params.marketData;
408
- const collateralIndex = params.collateralIndex ?? 0n;
409
- const midnightBundles = getChainAddress(this.chainId, "midnightBundles");
410
- const collateral = market.getCollateralByIndex(collateralIndex);
630
+ const pulledAssets = params.target.type === "assets"
631
+ ? params.target.assets
632
+ : params.target.maxBuyerAssets;
411
633
  return {
412
- getRequirements: async () => {
413
- const requirements = [
414
- ...(await getMidnightApprovalRequirements({
415
- viemClient: this.client.viemClient,
416
- chainId: this.chainId,
417
- token: collateral.token,
418
- owner: params.accountAddress,
419
- spender: midnightBundles,
420
- amount: params.collateralAssets,
421
- })),
422
- ];
423
- const authorization = await getMidnightAuthorizationRequirement({
634
+ getRequirements: async (requirementsParams) => {
635
+ const approvals = await getMidnightApprovalRequirements({
424
636
  viemClient: this.client.viemClient,
425
637
  chainId: this.chainId,
638
+ token: market.loanToken,
426
639
  owner: params.accountAddress,
427
- authorized: midnightBundles,
640
+ spender: tx.to,
641
+ amount: pulledAssets,
642
+ approvalAmount: requirementsParams?.approvalAmount,
428
643
  });
429
- if (authorization)
430
- requirements.push(authorization);
431
- return requirements;
644
+ const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
645
+ return [...approvals, ...authorization];
432
646
  },
433
- buildTx: () => midnightSupplyCollateralTakeBorrow({
434
- chainId: this.chainId,
435
- market: market.params,
436
- collateralAssets: params.collateralAssets,
437
- loanAssets: params.loanAssets,
438
- maxUnits: params.maxUnits,
439
- taker: params.accountAddress,
440
- collateralIndex,
441
- takeableOffers: params.takeableOffers,
442
- deadline: params.deadline,
443
- metadata: this.client.options.metadata,
444
- }),
647
+ buildTx: () => tx,
445
648
  };
446
649
  }
447
650
  /**
@@ -459,6 +662,7 @@ export class MorphoMidnight {
459
662
  * @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
460
663
  * @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
461
664
  * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
665
+ * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled collateral assets.
462
666
  * @example
463
667
  * ```ts
464
668
  * const output = midnight.supplyCollateral({
@@ -478,13 +682,14 @@ export class MorphoMidnight {
478
682
  const collateral = market.getCollateralByIndex(collateralIndex);
479
683
  const midnight = getChainAddress(this.chainId, "midnight");
480
684
  return {
481
- getRequirements: async () => await getMidnightApprovalRequirements({
685
+ getRequirements: async (requirementsParams) => await getMidnightApprovalRequirements({
482
686
  viemClient: this.client.viemClient,
483
687
  chainId: this.chainId,
484
688
  token: collateral.token,
485
689
  owner: params.accountAddress,
486
690
  spender: midnight,
487
691
  amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
692
+ approvalAmount: requirementsParams?.approvalAmount,
488
693
  }),
489
694
  buildTx: () => midnightSupplyCollateral({
490
695
  chainId: this.chainId,
@@ -497,30 +702,49 @@ export class MorphoMidnight {
497
702
  };
498
703
  }
499
704
  /**
500
- * Validates lend-side maker offers and prepares their reserve and ratifier requirements.
705
+ * Prepares an atomic lend-offer publication or repost through `MidnightBundlesV2`.
501
706
  *
502
- * Calls the Midnight mempool validation API while preparing the offer tree;
503
- * allowance and ratifier state are read lazily by `getRequirements()`.
707
+ * One transaction cancels `cancellations` under their consumption ceilings, activates the
708
+ * PriceRatifierV1 or RateRatifierV1 root, and publishes its payload. Pass no cancellations
709
+ * for a new publication. Calls the Midnight mempool validation API while preparing the tree.
504
710
  *
505
- * @param params - Maker, raw offers, loan token, reserve amounts, and validation controls.
506
- * @param params.accountAddress - Maker expected on every offer.
507
- * @param params.offers - Raw lend-side offers or groups.
711
+ * @param params - Maker, lend-side offers, loan reserve, cancellations, and deadline.
712
+ * @param params.accountAddress - Maker expected on every offer; must send the transaction.
713
+ * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
714
+ * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
715
+ * @param params.deadline - Bundle execution deadline timestamp.
508
716
  * @param params.validation - Optional Midnight mempool API request controls.
509
717
  * @param params.loanToken - Loan token shared by every offer market.
510
- * @param params.loanAssets - New loan reserve assigned to the submitted groups.
511
- * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
512
- * @returns Prepared group metadata, lazy requirements, and a synchronous mempool transaction builder.
718
+ * @param params.loanAssets - New loan reserve assigned to the published groups.
719
+ * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
720
+ * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
513
721
  * @throws {ChainIdMismatchError} when the client targets another chain.
514
- * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
722
+ * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
723
+ * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
724
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
515
725
  * @throws {NonPositiveInputError} when `loanAssets` is non-positive.
516
- * @throws {NegativeInputError} when `reservedLoanAssets` is negative.
726
+ * @throws {NegativeInputError} when `reservedLoanAssets` or a `maxConsumed` ceiling is negative.
727
+ * @throws {NonPositiveInputError} when `deadline` is not positive.
728
+ * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128` or `deadline` exceeds `uint256`.
729
+ * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
730
+ * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
731
+ * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
732
+ * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
733
+ * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
734
+ * @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
735
+ * @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
517
736
  * @throws {MidnightOfferSideMismatchError} when an offer is not lend-side.
518
737
  * @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer uses another loan token.
738
+ * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
739
+ * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
740
+ * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
519
741
  * @example
520
742
  * ```ts
521
743
  * const output = await midnight.makeLend({
522
744
  * accountAddress: maker,
523
- * offers: [offer],
745
+ * offers: { type: "rateV1", entries: [{ offer, rate }] },
746
+ * cancellations: [{ group: previousGroup, maxConsumed: 0n }],
747
+ * deadline: maxUint256,
524
748
  * loanToken,
525
749
  * loanAssets: 1_000_000n,
526
750
  * });
@@ -528,16 +752,66 @@ export class MorphoMidnight {
528
752
  */
529
753
  async makeLend(params) {
530
754
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
755
+ const tree = Tree.from(params.offers);
756
+ rejectReduceOnlyOffers(tree.offers);
757
+ return this.prepareLendOffers({ ...params, offers: tree });
758
+ }
759
+ /**
760
+ * Prepares an atomic borrow-offer publication or repost through `MidnightBundlesV2`.
761
+ *
762
+ * One transaction cancels `cancellations` under their consumption ceilings, activates the
763
+ * PriceRatifierV1 or RateRatifierV1 root, and publishes its payload. Pass no cancellations for
764
+ * a new publication. Calls the Midnight mempool validation API while preparing the tree.
765
+ *
766
+ * @param params - Maker, borrow-side offers, cancellations, and deadline.
767
+ * @param params.accountAddress - Maker expected on every offer; must send the transaction.
768
+ * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
769
+ * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
770
+ * @param params.deadline - Bundle execution deadline timestamp.
771
+ * @param params.validation - Optional Midnight mempool API request controls.
772
+ * @returns Prepared group metadata, lazy authorization requirements, and a synchronous transaction builder.
773
+ * @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
774
+ * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
775
+ * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
776
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
777
+ * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
778
+ * @throws {NonPositiveInputError} when `deadline` is not positive.
779
+ * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128` or `deadline` exceeds `uint256`.
780
+ * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
781
+ * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
782
+ * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
783
+ * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
784
+ * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
785
+ * @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
786
+ * @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
787
+ * @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
788
+ * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
789
+ * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
790
+ * @example
791
+ * ```ts
792
+ * const output = await midnight.makeBorrow({
793
+ * accountAddress: maker,
794
+ * offers: { type: "rateV1", entries: [{ offer, rate }] },
795
+ * deadline: maxUint256,
796
+ * });
797
+ * ```
798
+ */
799
+ async makeBorrow(params) {
800
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
801
+ const tree = Tree.from(params.offers);
802
+ rejectReduceOnlyOffers(tree.offers);
803
+ return this.prepareBorrowOffers({ ...params, offers: tree });
804
+ }
805
+ /**
806
+ * Prepares lend-side offers for publication.
807
+ */
808
+ async prepareLendOffers(params) {
531
809
  assertPositiveAmount("loanAssets", params.loanAssets);
532
810
  assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
533
- const data = await this.getOffersData({
534
- accountAddress: params.accountAddress,
535
- offers: params.offers,
536
- validation: params.validation,
537
- });
811
+ const data = await this.getOffersData(params);
538
812
  validateOfferSides(data.tree.offers, true);
539
813
  data.tree.offers.forEach((offer, index) => {
540
- const market = "params" in offer.market ? offer.market.params : offer.market;
814
+ const market = offerMarketParams(offer);
541
815
  if (!isAddressEqual(market.loanToken, params.loanToken)) {
542
816
  throw new MidnightOfferMarketLoanTokenMismatchError({
543
817
  index,
@@ -546,120 +820,422 @@ export class MorphoMidnight {
546
820
  });
547
821
  }
548
822
  });
823
+ const tx = midnightCancelAndMake({
824
+ chainId: this.chainId,
825
+ cancellations: params.cancellations ?? [],
826
+ deadline: params.deadline,
827
+ metadata: this.client.options.metadata,
828
+ publication: {
829
+ ratifier: data.ratifier,
830
+ root: data.tree.root,
831
+ groups: data.groups,
832
+ payload: data.payload,
833
+ },
834
+ });
549
835
  const midnight = getChainAddress(this.chainId, "midnight");
550
836
  return {
551
837
  groups: data.groups,
552
838
  root: data.tree.root,
553
839
  ratifierType: data.ratifierType,
554
- getRequirements: async () => {
555
- const requirements = [];
556
- requirements.push(...(await getMidnightApprovalRequirements({
840
+ getRequirements: async (requirementsParams) => {
841
+ const approvals = await getMidnightApprovalRequirements({
557
842
  viemClient: this.client.viemClient,
558
843
  chainId: this.chainId,
559
844
  token: params.loanToken,
560
845
  owner: data.accountAddress,
561
846
  spender: midnight,
562
847
  amount: params.loanAssets + (params.reservedLoanAssets ?? 0n),
563
- })));
564
- requirements.push(...(await this.getRatifierRequirements({
565
- offersData: data,
566
- })));
567
- return requirements;
848
+ approvalAmount: requirementsParams?.approvalAmount,
849
+ });
850
+ const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
851
+ return [...approvals, ...authorization];
568
852
  },
569
- buildTx: (signatures) => this.buildSubmitOffersTx({
570
- offersData: data,
571
- signatures,
572
- }),
853
+ buildTx: () => tx,
573
854
  };
574
855
  }
575
856
  /**
576
- * Validates borrow-side maker offers and prepares their ratifier requirements.
857
+ * Prepares an atomic Blue-funded lend-offer publication or repost through `MidnightBundlesV2`.
577
858
  *
578
- * @param params - Maker, raw borrow-side offers, and optional mempool validation controls.
579
- * @param params.accountAddress - Maker expected on every offer.
580
- * @param params.offers - Raw borrow-side offers or groups.
859
+ * One transaction cancels `cancellations` under their consumption ceilings, pulls `assetsToPark`
860
+ * from the maker and supplies them to `blueMarket` on Morpho Blue for the maker's
861
+ * `BlueBuyCallback` (created if missing), activates the PriceRatifierV1 or RateRatifierV1 root,
862
+ * and publishes its payload. When an offer is taken, the callback withdraws the bought assets
863
+ * from Blue and pays Midnight, so the maker needs no loan-token approval to Midnight.
864
+ *
865
+ * Every offer must set `callback` to the maker's derived `BlueBuyCallback` and `callbackData`
866
+ * to `abi.encode(blueMarket)`. The contract does not check supply share-price slippage, so
867
+ * `blueMarket` must be protected against supply-share-price inflation; this method rejects
868
+ * Blue markets with no supply shares and parked amounts that would mint zero shares. Calls the
869
+ * Midnight mempool validation API while preparing the tree. Computes the callback's CREATE2 address from the chain's
870
+ * `midnightBlueBuyCallbackFactory`, `accountAddress` and `callbackSalt`, and fetches the Morpho Blue market,
871
+ * accruing interest to the current time before previewing parked shares (markets whose
872
+ * IRM the SDK cannot accrue are previewed on their last-updated state).
873
+ *
874
+ * @param params - Maker, lend-side offers, Blue market, parked assets, cancellations, and deadline.
875
+ * @param params.accountAddress - Maker expected on every offer; must send the transaction.
876
+ * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
877
+ * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
878
+ * @param params.deadline - Bundle execution deadline timestamp.
581
879
  * @param params.validation - Optional Midnight mempool API request controls.
582
- * @returns Prepared group metadata, lazy ratifier requirements, and a synchronous mempool transaction builder.
880
+ * @param params.blueMarket - Morpho Blue market the parked assets are supplied to.
881
+ * @param params.assetsToPark - Loan assets supplied to `blueMarket` for the maker's callback.
882
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
883
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
884
+ * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
885
+ * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
886
+ * required for the full pulled amount.
887
+ * @param params.callbackSalt - Salt selecting the maker's callback; the same salt reuses the same callback.
888
+ * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
583
889
  * @throws {ChainIdMismatchError} when the client targets another chain.
890
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2`, `midnightBlueBuyCallbackFactory`, `midnight`, `blue` or V1 ratifier deployment.
891
+ * @throws {NonPositiveInputError} when `assetsToPark` is non-positive.
892
+ * @throws {NegativeInputError} when a `maxConsumed` ceiling or `nativeAmount` is negative.
893
+ * @throws {NonPositiveInputError} when `deadline` is not positive.
894
+ * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128`, `deadline` exceeds
895
+ * `uint256`, or `nativeAmount` exceeds `assetsToPark` when `blueMarket.loanToken` is wNative.
896
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
897
+ * @throws {NativeAmountOnNonWNativeAssetError} when `blueMarket.loanToken` is not wNative.
898
+ * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
899
+ * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
900
+ * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
584
901
  * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
585
- * @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
902
+ * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
903
+ * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
904
+ * @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
905
+ * @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
906
+ * @throws {MidnightOfferSideMismatchError} when an offer is not lend-side.
907
+ * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
908
+ * @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer's loan token differs from `blueMarket`'s.
909
+ * @throws {MidnightOfferCallbackMismatchError} when an offer does not use the maker's derived callback.
910
+ * @throws {MidnightOfferCallbackDataMismatchError} when an offer's callback data is not `abi.encode(blueMarket)`.
911
+ * @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
912
+ * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price.
913
+ * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
914
+ * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
915
+ * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `assetsToPark`.
586
916
  * @example
587
917
  * ```ts
588
- * const output = await midnight.makeBorrow({
918
+ * const callback = getMidnightBlueBuyCallbackAddress({ chainId, owner: maker, salt: callbackSalt });
919
+ * const callbackData = getMidnightBlueBuyCallbackData(blueMarket);
920
+ * const output = await midnight.supplyBlueMakeLend({
589
921
  * accountAddress: maker,
590
- * offers: [offer],
922
+ * offers: {
923
+ * type: "rateV1",
924
+ * entries: [{ offer: { ...offer, callback, callbackData }, rate }],
925
+ * },
926
+ * deadline: maxUint256,
927
+ * blueMarket,
928
+ * assetsToPark: 1_000_000n,
929
+ * callbackSalt,
591
930
  * });
592
931
  * ```
593
932
  */
594
- async makeBorrow(params) {
933
+ async supplyBlueMakeLend(params) {
595
934
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
596
- const data = await this.getOffersData({
597
- accountAddress: params.accountAddress,
598
- offers: params.offers,
599
- validation: params.validation,
935
+ assertPositiveAmount("assetsToPark", params.assetsToPark);
936
+ const { callbackSalt } = params;
937
+ const blueMarketId = BlueMarketUtils.getMarketId(params.blueMarket);
938
+ const callback = getMidnightBlueBuyCallbackAddress({
939
+ chainId: this.chainId,
940
+ owner: params.accountAddress,
941
+ salt: callbackSalt,
942
+ });
943
+ const [data, fetched] = await Promise.all([
944
+ this.getOffersData(params),
945
+ fetchBlueMarket(blueMarketId, this.client.viemClient, {
946
+ deployless: this.client.options.supportDeployless,
947
+ }),
948
+ ]);
949
+ const market = _try(() => fetched.accrueInterest(MathLib.max(Time.timestamp(), fetched.lastUpdate)), UnsupportedMarketIrmError) ?? fetched;
950
+ if (market.totalSupplyShares === 0n) {
951
+ throw new EmptyBlueParkingMarketError({ marketId: blueMarketId });
952
+ }
953
+ if (market.toSupplyShares(params.assetsToPark, "Down") === 0n) {
954
+ throw new ZeroBlueParkingSharesError({
955
+ marketId: blueMarketId,
956
+ assets: params.assetsToPark,
957
+ });
958
+ }
959
+ validateOfferSides(data.tree.offers, true);
960
+ rejectReduceOnlyOffers(data.tree.offers);
961
+ const callbackData = getMidnightBlueBuyCallbackData(params.blueMarket);
962
+ data.tree.offers.forEach((offer, index) => {
963
+ const offerMarket = offerMarketParams(offer);
964
+ if (!isAddressEqual(offerMarket.loanToken, params.blueMarket.loanToken)) {
965
+ throw new MidnightOfferMarketLoanTokenMismatchError({
966
+ index,
967
+ expectedLoanToken: params.blueMarket.loanToken,
968
+ actualLoanToken: offerMarket.loanToken,
969
+ });
970
+ }
971
+ if (!isAddressEqual(offer.callback, callback)) {
972
+ throw new MidnightOfferCallbackMismatchError({
973
+ index,
974
+ expectedCallback: callback,
975
+ actualCallback: offer.callback,
976
+ });
977
+ }
978
+ if (offer.callbackData.toLowerCase() !== callbackData.toLowerCase()) {
979
+ throw new MidnightOfferCallbackDataMismatchError({
980
+ index,
981
+ expectedCallbackData: callbackData,
982
+ actualCallbackData: offer.callbackData,
983
+ });
984
+ }
985
+ });
986
+ const tx = midnightCancelAndMake({
987
+ chainId: this.chainId,
988
+ publication: {
989
+ ratifier: data.ratifier,
990
+ root: data.tree.root,
991
+ groups: data.groups,
992
+ payload: data.payload,
993
+ blueSupply: {
994
+ market: params.blueMarket,
995
+ assets: params.assetsToPark,
996
+ callbackSalt,
997
+ },
998
+ },
999
+ nativeAmount: params.nativeAmount,
1000
+ cancellations: params.cancellations ?? [],
1001
+ deadline: params.deadline,
1002
+ metadata: this.client.options.metadata,
600
1003
  });
601
- validateOfferSides(data.tree.offers, false);
602
1004
  return {
603
1005
  groups: data.groups,
604
1006
  root: data.tree.root,
605
1007
  ratifierType: data.ratifierType,
606
- getRequirements: async () => {
607
- return await this.getRatifierRequirements({
608
- offersData: data,
1008
+ getRequirements: async (requirementsParams) => {
1009
+ const approvals = await getMidnightApprovalRequirements({
1010
+ viemClient: this.client.viemClient,
1011
+ chainId: this.chainId,
1012
+ token: params.blueMarket.loanToken,
1013
+ owner: data.accountAddress,
1014
+ spender: getChainAddress(this.chainId, "midnightBundlesV2"),
1015
+ amount: params.assetsToPark,
1016
+ approvalAmount: requirementsParams?.approvalAmount,
609
1017
  });
1018
+ const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1019
+ return [...approvals, ...authorization];
610
1020
  },
611
- buildTx: (signatures) => this.buildSubmitOffersTx({
612
- offersData: data,
613
- signatures,
614
- }),
1021
+ buildTx: () => tx,
1022
+ };
1023
+ }
1024
+ /**
1025
+ * Prepares borrow-side offers for publication.
1026
+ */
1027
+ async prepareBorrowOffers(params) {
1028
+ const data = await this.getOffersData(params);
1029
+ validateOfferSides(data.tree.offers, false);
1030
+ const tx = midnightCancelAndMake({
1031
+ chainId: this.chainId,
1032
+ cancellations: params.cancellations ?? [],
1033
+ deadline: params.deadline,
1034
+ metadata: this.client.options.metadata,
1035
+ publication: {
1036
+ ratifier: data.ratifier,
1037
+ root: data.tree.root,
1038
+ groups: data.groups,
1039
+ payload: data.payload,
1040
+ },
1041
+ });
1042
+ return {
1043
+ groups: data.groups,
1044
+ root: data.tree.root,
1045
+ ratifierType: data.ratifierType,
1046
+ getRequirements: async () => this.getBundlesV2AuthorizationRequirements(data.accountAddress),
1047
+ buildTx: () => tx,
615
1048
  };
616
1049
  }
617
1050
  /**
618
- * Prepares collateral supply followed by borrow-side maker-offer submission.
1051
+ * Publishes reduce-only sell offers for a lend limit exit through MidnightBundlesV2.
619
1052
  *
620
- * @param params - Maker, market, collateral reserve, raw offers, and validation controls.
621
- * @param params.accountAddress - Maker expected on every offer.
622
- * @param params.offers - Raw borrow-side offers or groups.
1053
+ * Shares the borrow-side publication and requirement handling of {@link MorphoMidnight.makeBorrow}.
1054
+ * No tokens are pulled during publication and no token approval is required.
1055
+ * Execution waits for a taker; publication does not close the position or withdraw collateral.
1056
+ * Every offer must already have `buy = false` and `reduceOnly = true`.
1057
+ * The supplied tree, group caps and prices are preserved; no separate root signature is needed.
1058
+ *
1059
+ * @param params - Maker, reduce-only offers, optional cancellations, and deadline.
1060
+ * @param params.accountAddress - Maker expected on every offer; must send the transaction.
1061
+ * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
1062
+ * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
1063
+ * @param params.deadline - Bundle execution deadline timestamp.
623
1064
  * @param params.validation - Optional Midnight mempool API request controls.
624
- * @param params.market - Market shared by every submitted offer.
625
- * @param params.collateralAssets - Collateral supplied before offer submission.
626
- * @param params.reservedCollateralAssets - Existing collateral reserved by other open groups.
627
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
628
- * @returns Prepared group metadata, lazy supply/ratifier requirements, and a synchronous mempool transaction builder.
1065
+ * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1066
+ * @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
1067
+ * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1068
+ * @throws {MidnightOfferSideMismatchError} when an offer is not a sell offer (`buy = false`).
1069
+ * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1070
+ * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
1071
+ * @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
1072
+ * @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
1073
+ * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
1074
+ * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
1075
+ * @throws {UnknownAddressError} when the chain has no V1 ratifier or `midnightBundlesV2` deployment.
1076
+ * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
1077
+ * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
1078
+ * @throws {NonPositiveInputError} when `deadline` is not positive.
1079
+ * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
1080
+ * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
1081
+ * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1082
+ * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1083
+ * @example
1084
+ * ```ts
1085
+ * const output = await midnight.makeWithdraw({
1086
+ * accountAddress: maker,
1087
+ * offers: { type: "priceV1", entries: [{ offer: reduceOnlySellOffer }] },
1088
+ * deadline: maxUint256,
1089
+ * });
1090
+ * const requirements = await output.getRequirements();
1091
+ * const tx = output.buildTx();
1092
+ * ```
1093
+ */
1094
+ async makeWithdraw(params) {
1095
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
1096
+ const tree = Tree.from(params.offers);
1097
+ // Reject the wrong exit intent before calling the mempool validation API.
1098
+ validateOfferSides(tree.offers, false);
1099
+ for (const [index, offer] of tree.offers.entries()) {
1100
+ if (!offer.reduceOnly)
1101
+ throw new MidnightOfferNotReduceOnlyError({ index });
1102
+ }
1103
+ return this.prepareBorrowOffers({ ...params, offers: tree });
1104
+ }
1105
+ /**
1106
+ * Publishes reduce-only buy offers for a borrow limit exit through MidnightBundlesV2.
1107
+ *
1108
+ * Shares the lend-side publication and requirement handling of {@link MorphoMidnight.makeLend}.
1109
+ * Loan assets are pulled by Midnight when the offers fill, not during publication.
1110
+ * The loan reserve uses the same approval sizing as `makeLend`.
1111
+ * Execution waits for a taker; publication does not close the position or withdraw collateral.
1112
+ * Every offer must already have `buy = true` and `reduceOnly = true`.
1113
+ * The supplied tree, group caps and prices are preserved; no separate root signature is needed.
1114
+ *
1115
+ * @param params - Maker, reduce-only offers, optional cancellations, loan reserve, and deadline.
1116
+ * @param params.accountAddress - Maker expected on every offer; must send the transaction.
1117
+ * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
1118
+ * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
1119
+ * @param params.deadline - Bundle execution deadline timestamp.
1120
+ * @param params.validation - Optional Midnight mempool API request controls.
1121
+ * @param params.loanToken - Loan token shared by every offer market.
1122
+ * @param params.loanAssets - New loan reserve assigned to the published groups.
1123
+ * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
1124
+ * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
629
1125
  * @throws {ChainIdMismatchError} when the client targets another chain.
630
- * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
631
- * @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
632
- * @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
633
- * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
1126
+ * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1127
+ * @throws {MidnightOfferSideMismatchError} when an offer is not a buy offer (`buy = true`).
1128
+ * @throws {MidnightOfferNotReduceOnlyError} when any offer can increase a position.
1129
+ * @throws {NonPositiveInputError} when `loanAssets` or `deadline` is not positive.
1130
+ * @throws {NegativeInputError} when `reservedLoanAssets` or a `maxConsumed` ceiling is negative.
1131
+ * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
1132
+ * @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
1133
+ * @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
1134
+ * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
1135
+ * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
1136
+ * @throws {UnknownAddressError} when the chain has no V1 ratifier or `midnightBundlesV2` deployment.
1137
+ * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
1138
+ * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
1139
+ * @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer uses another loan token.
1140
+ * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
1141
+ * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1142
+ * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1143
+ * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below `loanAssets + reservedLoanAssets`.
1144
+ * @example
1145
+ * ```ts
1146
+ * const output = await midnight.makeRepay({
1147
+ * accountAddress: maker,
1148
+ * offers: { type: "priceV1", entries: [{ offer: reduceOnlyBuyOffer }] },
1149
+ * loanToken,
1150
+ * loanAssets: 1_000_000n,
1151
+ * deadline: maxUint256,
1152
+ * });
1153
+ * const requirements = await output.getRequirements();
1154
+ * const tx = output.buildTx();
1155
+ * ```
1156
+ */
1157
+ async makeRepay(params) {
1158
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
1159
+ const tree = Tree.from(params.offers);
1160
+ // Reject the wrong exit intent before calling the mempool validation API.
1161
+ validateOfferSides(tree.offers, true);
1162
+ for (const [index, offer] of tree.offers.entries()) {
1163
+ if (!offer.reduceOnly)
1164
+ throw new MidnightOfferNotReduceOnlyError({ index });
1165
+ }
1166
+ return this.prepareLendOffers({ ...params, offers: tree });
1167
+ }
1168
+ /**
1169
+ * Prepares an atomic borrow-offer publication or repost through `MidnightBundlesV2`,
1170
+ * requiring collateral before activation.
1171
+ *
1172
+ * One transaction cancels `cancellations` under their consumption ceilings, pulls and supplies
1173
+ * required `collateral`, activates the PriceRatifierV1 or RateRatifierV1 root, and publishes its
1174
+ * payload. Pass no cancellations for a new publication. Calls the Midnight mempool validation
1175
+ * API while preparing the tree.
1176
+ *
1177
+ * @param params - Maker, borrow-side offers, required collateral, cancellations, and deadline.
1178
+ * @param params.accountAddress - Maker expected on every offer; must send the transaction.
1179
+ * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
1180
+ * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
1181
+ * @param params.deadline - Bundle execution deadline timestamp.
1182
+ * @param params.validation - Optional Midnight mempool API request controls.
1183
+ * @param params.collateral - Required market and collateral supplies; every offer must target that market.
1184
+ * @param params.collateral.market - Midnight market receiving the collateral; every offer must target it.
1185
+ * @param params.collateral.supplies - Collateral index and assets per supply; must not be empty.
1186
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
1187
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
1188
+ * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
1189
+ * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
1190
+ * required for the full pulled amount.
1191
+ * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1192
+ * @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
1193
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` or V1 ratifier deployment.
1194
+ * @throws {UnknownCollateralIndexError} when a collateral index is not configured.
1195
+ * @throws {NonPositiveInputError} when a collateral supply amount is non-positive.
1196
+ * @throws {NegativeInputError} when a `maxConsumed` ceiling or `nativeAmount` is negative.
1197
+ * @throws {NonPositiveInputError} when `deadline` is not positive.
1198
+ * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128`, `deadline` or a
1199
+ * collateral supply amount exceeds `uint256`, or `nativeAmount` exceeds the maximum wNative
1200
+ * collateral amount this call can pull.
1201
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1202
+ * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
1203
+ * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
1204
+ * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree.
1205
+ * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
1206
+ * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
1207
+ * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
1208
+ * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
1209
+ * @throws {MidnightOfferContinuousFeeCapError} when an offer has a nonzero continuous fee cap.
1210
+ * @throws {MidnightOfferSellerReceiverMismatchError} when a sell offer routes proceeds to another address.
634
1211
  * @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
635
- * @throws {MarketIdMismatchError} when an offer targets another market.
1212
+ * @throws {MidnightOfferReduceOnlyError} when an offer is reduce-only.
1213
+ * @throws {MarketIdMismatchError} when an offer targets another market than `collateral.market`, including a `collateral.market` on another chain or Midnight deployment.
1214
+ * @throws {EmptyMidnightCollateralSuppliesError} when a collateral market has no collateral supplies.
1215
+ * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1216
+ * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1217
+ * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below a collateral token's pulled assets.
636
1218
  * @example
637
1219
  * ```ts
638
1220
  * const output = await midnight.supplyCollateralMakeBorrow({
639
1221
  * accountAddress: maker,
640
- * market: marketData.params,
641
- * collateralAssets: 2_000_000n,
642
- * offers: [offer],
1222
+ * offers: { type: "rateV1", entries: [{ offer, rate }] },
1223
+ * collateral: {
1224
+ * market: marketData.params,
1225
+ * supplies: [{ collateralIndex: 0n, assets: 2_000_000n }],
1226
+ * },
1227
+ * deadline: maxUint256,
643
1228
  * });
644
1229
  * ```
645
1230
  */
646
1231
  async supplyCollateralMakeBorrow(params) {
647
1232
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
648
- assertPositiveAmount("collateralAssets", params.collateralAssets);
649
- assertNonNegativeAmount("reservedCollateralAssets", params.reservedCollateralAssets ?? 0n);
650
- const market = params.market instanceof MarketParams
651
- ? params.market
652
- : MarketParams.from(params.market);
653
- // Reject markets from another chain deployment before preparing requirements.
654
- validateMidnightMarket({ market, chainId: this.chainId });
655
- const collateralIndex = params.collateralIndex ?? 0n;
656
- const collateral = MarketUtils.getCollateralByIndex(market, collateralIndex);
657
- const data = await this.getOffersData({
658
- accountAddress: params.accountAddress,
659
- offers: params.offers,
660
- validation: params.validation,
661
- });
1233
+ const market = params.collateral.market instanceof MarketParams
1234
+ ? params.collateral.market
1235
+ : MarketParams.from(params.collateral.market);
1236
+ const data = await this.getOffersData(params);
662
1237
  validateOfferSides(data.tree.offers, false);
1238
+ rejectReduceOnlyOffers(data.tree.offers);
663
1239
  const marketId = MarketUtils.toId(market);
664
1240
  for (const offer of data.tree.offers) {
665
1241
  const offerMarketId = MarketUtils.toId(offer.market);
@@ -667,39 +1243,50 @@ export class MorphoMidnight {
667
1243
  throw new MarketIdMismatchError(offerMarketId, marketId);
668
1244
  }
669
1245
  }
670
- const midnight = getChainAddress(this.chainId, "midnight");
1246
+ const tx = midnightCancelAndMake({
1247
+ chainId: this.chainId,
1248
+ nativeAmount: params.nativeAmount,
1249
+ cancellations: params.cancellations ?? [],
1250
+ deadline: params.deadline,
1251
+ metadata: this.client.options.metadata,
1252
+ publication: {
1253
+ ratifier: data.ratifier,
1254
+ root: data.tree.root,
1255
+ groups: data.groups,
1256
+ payload: data.payload,
1257
+ collateral: {
1258
+ market,
1259
+ supplies: params.collateral.supplies,
1260
+ },
1261
+ },
1262
+ });
1263
+ const midnightBundlesV2 = getChainAddress(this.chainId, "midnightBundlesV2");
1264
+ const collateralAmounts = new Map();
1265
+ for (const { collateralIndex, assets } of tx.action.args
1266
+ .collateralSupplies) {
1267
+ const { token } = MarketUtils.getCollateralByIndex(market, collateralIndex);
1268
+ collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
1269
+ }
671
1270
  return {
672
1271
  groups: data.groups,
673
1272
  root: data.tree.root,
674
1273
  ratifierType: data.ratifierType,
675
- getRequirements: async () => {
676
- const requirements = [
677
- ...(await getMidnightApprovalRequirements({
678
- viemClient: this.client.viemClient,
679
- chainId: this.chainId,
680
- token: collateral.token,
681
- owner: data.accountAddress,
682
- spender: midnight,
683
- amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
684
- })),
685
- midnightSupplyCollateral({
686
- chainId: this.chainId,
687
- market,
688
- collateralIndex,
689
- assets: params.collateralAssets,
690
- onBehalf: data.accountAddress,
691
- metadata: this.client.options.metadata,
692
- }),
693
- ...(await this.getRatifierRequirements({
694
- offersData: data,
695
- })),
1274
+ getRequirements: async (requirementsParams) => {
1275
+ const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => getMidnightApprovalRequirements({
1276
+ viemClient: this.client.viemClient,
1277
+ chainId: this.chainId,
1278
+ token,
1279
+ owner: data.accountAddress,
1280
+ spender: midnightBundlesV2,
1281
+ amount,
1282
+ approvalAmount: requirementsParams?.approvalAmount,
1283
+ })));
1284
+ return [
1285
+ ...approvals.flat(),
1286
+ ...(await this.getBundlesV2AuthorizationRequirements(data.accountAddress)),
696
1287
  ];
697
- return requirements;
698
1288
  },
699
- buildTx: (signatures) => this.buildSubmitOffersTx({
700
- offersData: data,
701
- signatures,
702
- }),
1289
+ buildTx: () => tx,
703
1290
  };
704
1291
  }
705
1292
  /**
@@ -759,7 +1346,9 @@ export class MorphoMidnight {
759
1346
  });
760
1347
  }
761
1348
  return {
762
- getRequirements: async () => [],
1349
+ getRequirements: async () => {
1350
+ return [];
1351
+ },
763
1352
  buildTx: () => midnightRedeem({
764
1353
  chainId: this.chainId,
765
1354
  market: market.params,
@@ -771,258 +1360,144 @@ export class MorphoMidnight {
771
1360
  };
772
1361
  }
773
1362
  /**
774
- * Prepares a bundle that repays debt, withdraws collateral, or performs both.
1363
+ * Prepares a direct `MidnightBundlesV2` repayment, collateral withdrawal, or both, for `accountAddress`.
775
1364
  *
776
- * @param params - Account, market snapshot, repay and withdrawal amounts, collateral index, and deadline.
777
- * @param params.accountAddress - Position owner whose debt or collateral is updated.
1365
+ * @param params - Account, market snapshot, `repay` mode, collateral withdrawals, optional collateral receiver, and deadline.
1366
+ * @param params.accountAddress - Position owner and transaction sender.
778
1367
  * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
779
- * @param params.repayAssets - Loan assets repaid; may be zero for withdrawal-only flows.
780
- * @param params.withdrawCollateralAssets - Collateral assets withdrawn; may be zero for repay-only flows.
781
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
1368
+ * @param params.repay - `{ type: "assets", assets }` (`0n` to only withdraw) or `{ type: "full", maxBuyerAssets }`; a loan-token approval to `MidnightBundlesV2` is required when the allowance is below the pulled amount — unlimited (`maxUint256`) by default, or `approvalAmount` when passed to `getRequirements()` — and any unused part is refunded.
1369
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
1370
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
1371
+ * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
1372
+ * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
1373
+ * required for the full pulled amount.
1374
+ * @param params.collateralWithdrawals - Optional withdrawals; `assets: maxUint256` withdraws the full balance.
1375
+ * @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`.
782
1376
  * @param params.deadline - Bundle execution deadline timestamp.
783
1377
  * @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
784
1378
  * @throws {ChainIdMismatchError} when client or market data targets another chain.
785
1379
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
786
- * @throws {NegativeInputError} when an amount, index, or deadline is negative.
787
- * @throws {NonPositiveInputError} when both repay and withdrawal amounts are zero.
788
- * @throws {UnknownCollateralIndexError} when a positive withdrawal selects an unconfigured collateral.
1380
+ * @throws {NegativeInputError} when `repay.assets` or `nativeAmount` is negative.
1381
+ * @throws {NonPositiveInputError} when nothing is repaid or withdrawn, a withdrawal amount is zero, `repay.maxBuyerAssets` is zero, or `deadline` is not positive.
1382
+ * @throws {InputExceedsMaxError} when `repay.assets` or `repay.maxBuyerAssets` is at least
1383
+ * `maxUint256`, a withdrawal amount or `deadline` exceeds uint256, or `nativeAmount` exceeds
1384
+ * the maximum wNative amount this call can pull, including zero for a withdraw-only call.
1385
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1386
+ * @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
1387
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
1388
+ * @throws {UnknownCollateralIndexError} when a withdrawal selects an unconfigured collateral.
1389
+ * @throws {ApprovalAmountLessThanSpendAmountError} from `getRequirements()` when `approvalAmount` is below the pulled loan assets.
789
1390
  * @example
790
1391
  * ```ts
1392
+ * // Close the position: repay all debt, withdraw all collateral.
791
1393
  * const output = midnight.repayWithdrawCollateral({
792
1394
  * accountAddress: borrower,
793
1395
  * marketData,
794
- * repayAssets: 1_000_000n,
795
- * withdrawCollateralAssets: 2_000_000n,
1396
+ * repay: { type: "full", maxBuyerAssets: 1_010_000n },
1397
+ * collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
796
1398
  * deadline: maxUint256,
797
1399
  * });
798
1400
  * ```
799
1401
  */
800
1402
  repayWithdrawCollateral(params) {
801
1403
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
802
- validateMarketData(params.marketData, this.chainId);
803
- assertNonNegativeAmount("repayAssets", params.repayAssets);
804
- assertNonNegativeAmount("withdrawCollateralAssets", params.withdrawCollateralAssets);
805
- assertNonNegativeAmount("deadline", params.deadline);
806
- const market = params.marketData;
807
- const collateralWithdrawals = params.withdrawCollateralAssets > 0n
808
- ? [
809
- {
810
- collateralIndex: params.collateralIndex ?? 0n,
811
- assets: params.withdrawCollateralAssets,
812
- },
813
- ]
814
- : [];
815
- for (const [index, withdrawal] of collateralWithdrawals.entries()) {
816
- assertNonNegativeAmount(`collateralWithdrawals[${index}].collateralIndex`, withdrawal.collateralIndex);
817
- // Validate the configured collateral before exposing requirement reads.
818
- market.getCollateralByIndex(withdrawal.collateralIndex);
819
- }
820
- if (params.repayAssets === 0n &&
821
- collateralWithdrawals.every((withdrawal) => withdrawal.assets === 0n)) {
822
- throw new NonPositiveInputError("repay or withdraw amount", 0n);
823
- }
824
- const midnightBundles = getChainAddress(this.chainId, "midnightBundles");
1404
+ const market = params.marketData.params;
1405
+ const tx = midnightRepayWithdrawCollateral({
1406
+ chainId: this.chainId,
1407
+ market,
1408
+ repay: params.repay,
1409
+ nativeAmount: params.nativeAmount,
1410
+ collateralWithdrawals: params.collateralWithdrawals ?? [],
1411
+ collateralReceiver: params.collateralReceiver ?? params.accountAddress,
1412
+ deadline: params.deadline,
1413
+ metadata: this.client.options.metadata,
1414
+ });
1415
+ const pulledAssets = params.repay.type === "assets"
1416
+ ? params.repay.assets
1417
+ : params.repay.maxBuyerAssets;
825
1418
  return {
826
- getRequirements: async () => {
827
- const requirements = [];
828
- if (params.repayAssets > 0n) {
829
- requirements.push(...(await getMidnightApprovalRequirements({
1419
+ getRequirements: async (requirementsParams) => {
1420
+ const approvals = pulledAssets > 0n
1421
+ ? await getMidnightApprovalRequirements({
830
1422
  viemClient: this.client.viemClient,
831
1423
  chainId: this.chainId,
832
- token: market.params.loanToken,
1424
+ token: market.loanToken,
833
1425
  owner: params.accountAddress,
834
- spender: midnightBundles,
835
- amount: params.repayAssets,
836
- })));
837
- }
838
- const authorization = await getMidnightAuthorizationRequirement({
839
- viemClient: this.client.viemClient,
840
- chainId: this.chainId,
841
- owner: params.accountAddress,
842
- authorized: midnightBundles,
843
- });
844
- if (authorization)
845
- requirements.push(authorization);
846
- return requirements;
1426
+ spender: tx.to,
1427
+ amount: pulledAssets,
1428
+ approvalAmount: requirementsParams?.approvalAmount,
1429
+ })
1430
+ : [];
1431
+ const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
1432
+ return [...approvals, ...authorization];
847
1433
  },
848
- buildTx: () => midnightRepayWithdrawCollateral({
849
- chainId: this.chainId,
850
- market: market.params,
851
- repayAssets: params.repayAssets,
852
- withdrawCollateralAssets: params.withdrawCollateralAssets,
853
- onBehalf: params.accountAddress,
854
- collateralIndex: params.collateralIndex,
855
- deadline: params.deadline,
856
- metadata: this.client.options.metadata,
857
- }),
1434
+ buildTx: () => tx,
858
1435
  };
859
1436
  }
860
1437
  /**
861
- * Prepares full cancellation of a maker offer group.
1438
+ * Prepares guarded cancellation of several maker offer groups through `MidnightBundlesV2`.
1439
+ *
1440
+ * The transaction reverts as a whole when any group's consumption exceeds its
1441
+ * `maxConsumed` ceiling, so fills landing before execution never leave a partial cancel.
862
1442
  *
863
- * @param params - Group id and maker account whose consumption is updated.
864
- * @param params.group - Offer group id to fully consume.
865
- * @param params.accountAddress - Maker whose group consumption is updated.
866
- * @returns No requirements and a synchronous cancellation transaction builder.
1443
+ * @param params - Maker account, groups with consumption ceilings, and deadline.
1444
+ * @param params.accountAddress - Maker that must send the transaction. It is used only to check
1445
+ * the maker's Midnight authorization of `MidnightBundlesV2`; the bundle cancels the groups of
1446
+ * `msg.sender`. A transaction sent from another account that has also authorized
1447
+ * `MidnightBundlesV2` does not revert: it cancels that account's groups and leaves the maker's
1448
+ * offers fillable.
1449
+ * @param params.cancellations - Offer groups and the largest consumption accepted for each.
1450
+ * To cancel unconditionally, set `maxConsumed` to `maxUint128`; the contract treats
1451
+ * `type(uint128).max` as no limit.
1452
+ * @param params.deadline - Bundle execution deadline timestamp.
1453
+ * @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
867
1454
  * @throws {ChainIdMismatchError} when the client targets another chain.
1455
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
1456
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
1457
+ * @throws {EmptyMidnightGroupCancellationsError} when no groups are provided.
1458
+ * @throws {DuplicateMidnightGroupCancellationError} when a group appears more than once.
1459
+ * @throws {NonPositiveInputError} when `deadline` is not positive.
1460
+ * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
1461
+ * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
868
1462
  * @example
869
1463
  * ```ts
870
- * const output = midnight.cancelOffer({
871
- * group,
1464
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
1465
+ * import { createPublicClient, http, maxUint256, type Address, type Hex } from "viem";
1466
+ * import { base } from "viem/chains";
1467
+ *
1468
+ * declare const maker: Address;
1469
+ * declare const group: Hex;
1470
+ * const client = createPublicClient({ chain: base, transport: http() }).extend(
1471
+ * morphoViemExtension(),
1472
+ * );
1473
+ * const midnight = client.morpho.midnight(base.id);
1474
+ * const output = midnight.cancelOffers({
872
1475
  * accountAddress: maker,
1476
+ * cancellations: [{ group, maxConsumed: 0n }],
1477
+ * deadline: maxUint256,
873
1478
  * });
874
1479
  * ```
875
1480
  */
876
- cancelOffer(params) {
1481
+ cancelOffers(params) {
877
1482
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1483
+ const tx = midnightCancelAndMake({
1484
+ chainId: this.chainId,
1485
+ cancellations: params.cancellations,
1486
+ deadline: params.deadline,
1487
+ metadata: this.client.options.metadata,
1488
+ });
878
1489
  return {
879
- getRequirements: async () => [],
880
- buildTx: () => midnightCancelOffer({
881
- chainId: this.chainId,
882
- group: params.group,
883
- onBehalf: params.accountAddress,
884
- metadata: this.client.options.metadata,
885
- }),
1490
+ getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
1491
+ buildTx: () => tx,
886
1492
  };
887
1493
  }
888
- async getRatifierRequirements(params) {
889
- const data = params.offersData;
890
- const requirements = [];
1494
+ async getBundlesV2AuthorizationRequirements(owner) {
891
1495
  const authorization = await getMidnightAuthorizationRequirement({
892
1496
  viemClient: this.client.viemClient,
893
1497
  chainId: this.chainId,
894
- owner: data.accountAddress,
895
- authorized: data.ratifier,
896
- });
897
- if (authorization)
898
- requirements.push(authorization);
899
- if (data.ratifierType === "ecrecover") {
900
- const chainId = this.chainId;
901
- // The offer-tree EIP-712 payload is signed over the tree, not the signer, so it is fully
902
- // determined at build time and stored on the action for external signing.
903
- const treeTypedData = EcrecoverRatifierUtils.typedData({
904
- tree: data.tree,
905
- chainId,
906
- });
907
- const typedData = deepFreeze({
908
- domain: treeTypedData.domain,
909
- types: treeTypedData.types,
910
- primaryType: treeTypedData.primaryType,
911
- message: treeTypedData.message,
912
- });
913
- const action = {
914
- type: "midnightOfferRootSignature",
915
- args: {
916
- root: data.tree.root,
917
- ratifier: data.ratifier,
918
- offers: data.tree.offers.length,
919
- },
920
- typedData,
921
- };
922
- requirements.push({
923
- action,
924
- async sign(client, userAddress) {
925
- const signature = await signAndVerifyTypedData({
926
- client,
927
- userAddress,
928
- typedData,
929
- });
930
- // Derive the ratification payload `buildTx()` submits.
931
- const items = await EcrecoverRatifierUtils.ratify({
932
- tree: data.tree,
933
- account: userAddress,
934
- signature,
935
- });
936
- const payload = await Payload.encode(items);
937
- return deepFreeze({
938
- args: {
939
- owner: userAddress,
940
- root: data.tree.root,
941
- signature,
942
- payload,
943
- },
944
- action,
945
- });
946
- },
947
- });
948
- return requirements;
949
- }
950
- const ratifyRoot = await getSetterRatifierRatifyRootRequirement({
951
- viemClient: this.client.viemClient,
952
- chainId: this.chainId,
953
- maker: data.accountAddress,
954
- root: data.tree.root,
955
- });
956
- if (ratifyRoot)
957
- requirements.push(ratifyRoot);
958
- return requirements;
959
- }
960
- buildSubmitOffersTx(params) {
961
- const data = params.offersData;
962
- const collectedSignatures = params.signatures == null
963
- ? undefined
964
- : "action" in params.signatures
965
- ? [params.signatures]
966
- : params.signatures;
967
- let payload;
968
- if (data.ratifierType === "ecrecover") {
969
- const { midnightOfferRoot: signature } = selectRequirementSignatures(collectedSignatures, { midnightOfferRoot: true });
970
- if (signature == null) {
971
- throw new MissingMidnightOfferRootSignatureError();
972
- }
973
- if (!isAddressEqual(signature.args.owner, data.accountAddress)) {
974
- throw new MidnightOfferRootOwnerMismatchError({
975
- expectedOwner: data.accountAddress,
976
- actualOwner: signature.args.owner,
977
- });
978
- }
979
- if (signature.args.root.toLowerCase() !== data.tree.root.toLowerCase()) {
980
- throw new MidnightOfferRootMismatchError({
981
- expectedRoot: data.tree.root,
982
- actualRoot: signature.args.root,
983
- });
984
- }
985
- if (signature.action.args.root.toLowerCase() !==
986
- data.tree.root.toLowerCase()) {
987
- throw new MidnightOfferRootMismatchError({
988
- expectedRoot: data.tree.root,
989
- actualRoot: signature.action.args.root,
990
- });
991
- }
992
- if (!isAddressEqual(signature.action.args.ratifier, data.ratifier)) {
993
- throw new MidnightOfferRootRatifierMismatchError({
994
- expectedRatifier: data.ratifier,
995
- actualRatifier: signature.action.args.ratifier,
996
- });
997
- }
998
- if (signature.action.args.offers !== data.tree.offers.length) {
999
- throw new MidnightOfferRootOfferCountMismatchError({
1000
- expectedOffers: data.tree.offers.length,
1001
- actualOffers: signature.action.args.offers,
1002
- });
1003
- }
1004
- // The payload is carried on the signature the caller hands to buildTx, so
1005
- // a prepared offer-root requirement can be signed on one instance and
1006
- // submitted from another without sharing in-memory state.
1007
- if (signature.args.payload == null) {
1008
- throw new UnpreparedMidnightOfferRootSignatureError();
1009
- }
1010
- payload = signature.args.payload;
1011
- }
1012
- else {
1013
- selectRequirementSignatures(collectedSignatures, {});
1014
- payload = data.setterPayload;
1015
- }
1016
- return mempoolSubmitOffers({
1017
- chainId: this.chainId,
1018
- groups: data.groups,
1019
- root: data.tree.root,
1020
- maker: data.accountAddress,
1021
- ratifier: data.ratifier,
1022
- ratifierType: data.ratifierType,
1023
- offers: data.tree.offers.length,
1024
- payload,
1025
- metadata: this.client.options.metadata,
1498
+ owner,
1499
+ authorized: getChainAddress(this.chainId, "midnightBundlesV2"),
1026
1500
  });
1501
+ return authorization ? [authorization] : [];
1027
1502
  }
1028
1503
  }