@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,60 +1,95 @@
1
- import type { AccrualPosition, Market, MarketInput, MidnightFetchParams, Tree, TreeInput, TreeMempoolValidateParams } from "@morpho-org/midnight-sdk";
1
+ import type { InputMarketParams as BlueMarketParams } from "@morpho-org/blue-sdk";
2
+ import type { AccrualPosition, Market, MidnightFetchParams, PriceRatifierV1TreeCreateRequest, RateRatifierV1TreeCreateRequest, Tree, TreeMempoolValidateParams } from "@morpho-org/midnight-sdk";
2
3
  import type { Address, Hex } from "viem";
3
- import type { MidnightTakeableOffer } from "../../actions/midnight/types.js";
4
- import type { ActionOutput, BaseAction, MempoolSubmitOffersAction, MidnightOfferRootSignature } from "../../types/action.js";
4
+ import type { MidnightMakeBorrowCollateral } from "../../actions/midnight/cancelAndMake.js";
5
+ import type { MidnightReferralFeeParams, MidnightTakeableOffer } from "../../actions/midnight/types.js";
6
+ import type { ActionOutput, BaseAction, MidnightBuyTarget, MidnightCancelAndMakeAction, MidnightCollateralTransfer, MidnightGroupCancellation, MidnightRepay, MidnightSellTarget } from "../../types/action.js";
5
7
  /** Optional Midnight API validation controls for make-offer flows. */
6
- export type OfferValidationParams = Omit<TreeMempoolValidateParams, "chainId">;
8
+ export type OfferValidationParams = Omit<TreeMempoolValidateParams, "chainId" | "ratification">;
9
+ /**
10
+ * Offers accepted by Midnight maker flows: a PriceRatifierV1 or RateRatifierV1 tree, or
11
+ * the `Tree.create` request that builds one.
12
+ */
13
+ export type MidnightMakerTreeInput = PriceRatifierV1TreeCreateRequest | RateRatifierV1TreeCreateRequest | Tree<"priceV1"> | Tree<"rateV1">;
7
14
  /** Parameters for building and validating Midnight offer data. */
8
15
  export interface GetOffersDataParams {
9
16
  readonly accountAddress: Address;
10
- readonly offers: TreeInput;
17
+ readonly offers: MidnightMakerTreeInput;
11
18
  readonly validation?: OfferValidationParams;
12
19
  }
13
- interface OffersDataBase {
20
+ /** Prepared Midnight maker-offer data with the payload derived from its tree. */
21
+ export interface OffersData {
14
22
  readonly accountAddress: Address;
15
23
  readonly groups: readonly Hex[];
16
- readonly tree: Tree;
24
+ readonly tree: Tree<"priceV1"> | Tree<"rateV1">;
25
+ readonly ratifierType: "priceV1" | "rateV1";
17
26
  readonly ratifier: Address;
27
+ /** Encoded offer payload for `tree.root`. */
28
+ readonly payload: Hex;
18
29
  }
19
- /** Prepared Midnight maker-offer data discriminated by its ratifier execution path. */
20
- export type OffersData = (OffersDataBase & {
21
- readonly ratifierType: "ecrecover";
22
- readonly setterPayload?: never;
23
- }) | (OffersDataBase & {
24
- readonly ratifierType: "setter";
25
- readonly setterPayload: Hex;
26
- });
27
- /** Parameters shared by Midnight maker-offer flows. */
30
+ /** Parameters shared by Midnight maker flows. */
28
31
  export interface MakeOffersParams {
32
+ /** Maker expected on every offer. Must send the transaction: V2 acts on `msg.sender`. */
29
33
  readonly accountAddress: Address;
30
- readonly offers: TreeInput;
34
+ readonly offers: MidnightMakerTreeInput;
35
+ /** Previous offer groups to cancel atomically. Omit or pass `[]` for a new publication. */
36
+ readonly cancellations?: readonly MidnightGroupCancellation[];
37
+ /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
38
+ readonly deadline: bigint;
31
39
  readonly validation?: OfferValidationParams;
32
40
  }
33
- /** Parameters for the Midnight make-lend maker flow. */
41
+ /** Parameters for a Midnight lend maker flow. */
34
42
  export interface MakeLendParams extends MakeOffersParams {
35
43
  readonly loanToken: Address;
36
44
  /** New group loan reserve. For grouped OCA offers, pass the group reserve once instead of summing every leg. */
37
45
  readonly loanAssets: bigint;
38
- /** Existing loan assets reserved across the maker's other open groups, including consumed amounts when available. */
46
+ /** Existing loan assets reserved across the maker's other open groups, including consumed amounts when available. Leave out groups listed in `cancellations`; this transaction cancels them. */
39
47
  readonly reservedLoanAssets?: bigint;
40
48
  }
41
- /** Parameters for the Midnight supply-collateral-and-make-borrow maker flow. */
49
+ /** Parameters for the Midnight Blue-funded lend maker flow. */
50
+ export interface SupplyBlueMakeLendParams extends MakeOffersParams {
51
+ /**
52
+ * Morpho Blue market the parked assets are supplied to; its loan token must match every offer.
53
+ * The contract does not check supply share-price slippage: use only markets protected against
54
+ * supply-share-price inflation. Markets with no supply shares or parked amounts that mint zero
55
+ * shares are rejected.
56
+ */
57
+ readonly blueMarket: BlueMarketParams;
58
+ /** Loan assets pulled from the maker and supplied to `blueMarket` for the maker's callback. */
59
+ readonly assetsToPark: bigint;
60
+ /** Salt selecting the maker's `BlueBuyCallback`; the same salt reuses the same callback. */
61
+ readonly callbackSalt: Hex;
62
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
63
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
64
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
65
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
66
+ readonly nativeAmount?: bigint;
67
+ }
68
+ /** Parameters for the Midnight collateral-supplying borrow maker flow. */
42
69
  export interface SupplyCollateralMakeBorrowParams extends MakeOffersParams {
43
- readonly market: MarketInput;
44
- /** Collateral supplied before offer submission and the new group collateral reserve counted once for grouped offers. */
45
- readonly collateralAssets: bigint;
46
- /** Existing collateral assets reserved across the maker's other open groups, including consumed amounts when available. */
47
- readonly reservedCollateralAssets?: bigint;
48
- readonly collateralIndex?: bigint;
70
+ /** Required collateral supplied before activation; every offer must target `collateral.market`. */
71
+ readonly collateral: MidnightMakeBorrowCollateral;
72
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
73
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
74
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
75
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
76
+ readonly nativeAmount?: bigint;
77
+ }
78
+ /** Options for Midnight `getRequirements()`. */
79
+ export interface MidnightRequirementsParams {
80
+ /**
81
+ * ERC-20 allowance to set when an approval is needed. Defaults to `maxUint256` (capped per token by
82
+ * `MAX_TOKEN_APPROVALS`). Applies to every token the flow approves and must cover the amount each
83
+ * of them pulls. Flows that need no token approval ignore it.
84
+ */
85
+ readonly approvalAmount?: bigint;
49
86
  }
50
- /** Signatures accepted by Midnight action-output transaction builders. */
51
- export type MidnightActionSignatures = MidnightOfferRootSignature | readonly MidnightOfferRootSignature[];
52
87
  /**
53
88
  * Lazy Midnight entity result with async requirements and sync transaction building.
54
89
  *
55
- * Call `getRequirements()` first to collect approvals, authorizations, or
56
- * signatures. Once those are handled, pass any requirement signatures to
57
- * `buildTx`; the transaction builder itself performs no fetching or signing.
90
+ * Call `getRequirements()` first and send the approval and authorization
91
+ * transactions it returns. `buildTx()` takes no signatures and performs no
92
+ * fetching or signing.
58
93
  *
59
94
  * @example
60
95
  * ```ts
@@ -72,24 +107,19 @@ export type MidnightActionSignatures = MidnightOfferRootSignature | readonly Mid
72
107
  * const tx = output.buildTx();
73
108
  * ```
74
109
  */
75
- export type MidnightActionOutput<TAction extends BaseAction, TSignatures = undefined> = ActionOutput<TAction, TSignatures, undefined>;
110
+ export type MidnightActionOutput<TAction extends BaseAction, TSignatures = undefined> = ActionOutput<TAction, TSignatures, MidnightRequirementsParams>;
76
111
  /**
77
- * Output returned by maker-offer flows after offer-tree preparation.
112
+ * Output returned by Midnight maker flows after offer-tree preparation.
78
113
  *
79
- * Use `groups` and `root` for review UI, call `getRequirements()` to collect
80
- * ratifier approval or signature requirements, then call `buildTx(signatures)`
81
- * to publish the encoded payload to the Midnight mempool.
114
+ * Use `groups` and `root` for review UI, send the approval and authorization
115
+ * requirements from `getRequirements()`, then send `buildTx()` from the maker.
82
116
  *
83
117
  * @example
84
118
  * ```ts
85
- * const output = await midnight.makeLend(params);
119
+ * const output = await midnight.makeBorrow(params);
86
120
  * console.log(output.root, output.groups);
87
- * const requirements = await output.getRequirements();
88
- * const signatures = [];
89
- * for (const requirement of requirements) {
90
- * if ("sign" in requirement) {
91
- * signatures.push(await requirement.sign(walletClient, maker));
92
- * } else {
121
+ * for (const requirement of await output.getRequirements()) {
122
+ * if (!("sign" in requirement)) {
93
123
  * await walletClient.sendTransaction({
94
124
  * to: requirement.to,
95
125
  * data: requirement.data,
@@ -97,13 +127,13 @@ export type MidnightActionOutput<TAction extends BaseAction, TSignatures = undef
97
127
  * });
98
128
  * }
99
129
  * }
100
- * const tx = output.buildTx(signatures);
130
+ * await walletClient.sendTransaction(output.buildTx());
101
131
  * ```
102
132
  */
103
- export interface MakeOffersOutput extends MidnightActionOutput<MempoolSubmitOffersAction, MidnightActionSignatures> {
133
+ export interface MakeOffersOutput extends MidnightActionOutput<MidnightCancelAndMakeAction> {
104
134
  readonly groups: readonly Hex[];
105
135
  readonly root: Hex;
106
- readonly ratifierType: "ecrecover" | "setter";
136
+ readonly ratifierType: "priceV1" | "rateV1";
107
137
  }
108
138
  /** Parameters shared by Midnight market action flows. */
109
139
  export interface MarketActionParams {
@@ -111,25 +141,70 @@ export interface MarketActionParams {
111
141
  readonly marketData: Market;
112
142
  }
113
143
  /** Parameters for the Midnight take-lend taker flow. */
114
- export interface TakeLendParams extends MarketActionParams {
115
- readonly assets: bigint;
116
- readonly minUnits: bigint;
144
+ export interface TakeLendParams extends MarketActionParams, MidnightReferralFeeParams {
145
+ /** Loan assets paid with a unit floor, or units bought with a loan-asset cap. */
146
+ readonly target: MidnightBuyTarget;
147
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
148
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
149
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
150
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
151
+ readonly nativeAmount?: bigint;
117
152
  readonly takeableOffers: readonly MidnightTakeableOffer[];
118
- /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
153
+ /** Largest market continuous fee accepted when taking offers. Pass `maxUint256` explicitly for no cap. */
154
+ readonly maxContinuousFee: bigint;
155
+ /** Bounded bundle execution deadline timestamp. */
119
156
  readonly deadline: bigint;
120
157
  }
121
158
  /** Parameters for the Midnight take-borrow taker flow. */
122
- export interface TakeBorrowParams extends MarketActionParams {
123
- readonly loanAssets: bigint;
124
- readonly maxUnits: bigint;
159
+ export interface TakeBorrowParams extends MarketActionParams, MidnightReferralFeeParams {
160
+ /** Loan assets received with a unit cap, or units sold with a loan-asset floor. */
161
+ readonly target: MidnightSellTarget;
162
+ /** Recipient of the borrowed loan assets. Defaults to `accountAddress`. */
163
+ readonly receiver?: Address;
125
164
  readonly takeableOffers: readonly MidnightTakeableOffer[];
126
- /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
165
+ /** Bounded bundle execution deadline timestamp. */
166
+ readonly deadline: bigint;
167
+ }
168
+ /** Parameters for the Midnight credit-withdrawal taker flow. */
169
+ export interface TakeWithdrawParams extends MarketActionParams, MidnightReferralFeeParams {
170
+ /** Loan assets received with a credit-unit cap, or credit units sold with a loan-asset floor. */
171
+ readonly target: MidnightSellTarget;
172
+ /** Recipient of the withdrawn loan assets. Defaults to `accountAddress`. */
173
+ readonly receiver?: Address;
174
+ readonly takeableOffers: readonly MidnightTakeableOffer[];
175
+ /** Bounded bundle execution deadline timestamp. */
127
176
  readonly deadline: bigint;
128
177
  }
129
178
  /** Parameters for the Midnight supply-collateral-and-take-borrow taker flow. */
130
179
  export interface SupplyCollateralTakeBorrowParams extends TakeBorrowParams {
131
- readonly collateralAssets: bigint;
132
- readonly collateralIndex?: bigint;
180
+ /** Collateral supplied before borrowing; must not be empty. */
181
+ readonly collateralSupplies: readonly MidnightCollateralTransfer[];
182
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
183
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
184
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
185
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
186
+ readonly nativeAmount?: bigint;
187
+ }
188
+ /** Parameters for the Midnight offer-based repay-and-withdraw-collateral taker flow. */
189
+ export interface TakeRepayWithdrawCollateralParams extends MarketActionParams, MidnightReferralFeeParams {
190
+ /** Loan assets paid with a unit floor, or debt units repaid with a loan-asset cap. `units: maxUint256` targets the whole debt; `assets` and `maxBuyerAssets` bound the loan assets pulled and must be below `maxUint256`. */
191
+ readonly target: MidnightBuyTarget;
192
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
193
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
194
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
195
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
196
+ readonly nativeAmount?: bigint;
197
+ readonly takeableOffers: readonly MidnightTakeableOffer[];
198
+ /** Repays the rest of the target directly to Midnight when offers do not fill it. */
199
+ readonly repayEnabled: boolean;
200
+ /** Collateral withdrawn after repaying. Defaults to none. */
201
+ readonly collateralWithdrawals?: readonly MidnightCollateralTransfer[];
202
+ /** Recipient of withdrawn collateral. Defaults to `accountAddress`. */
203
+ readonly collateralReceiver?: Address;
204
+ /** Largest market continuous fee accepted when taking offers. Pass `maxUint256` explicitly for no cap. */
205
+ readonly maxContinuousFee: bigint;
206
+ /** Bounded bundle execution deadline timestamp. */
207
+ readonly deadline: bigint;
133
208
  }
134
209
  /** Parameters for the Midnight supply-collateral flow. */
135
210
  export interface SupplyCollateralParams extends MarketActionParams {
@@ -148,9 +223,17 @@ export interface RedeemParams {
148
223
  }
149
224
  /** Parameters for the Midnight repay-and-withdraw-collateral flow. */
150
225
  export interface RepayWithdrawCollateralParams extends MarketActionParams {
151
- readonly repayAssets: bigint;
152
- readonly withdrawCollateralAssets: bigint;
153
- readonly collateralIndex?: bigint;
226
+ /** `{ type: "assets", assets }` repays exactly `assets` (`0n` only withdraws); `{ type: "full", maxBuyerAssets }` repays the whole debt at execution with a finite asset cap. */
227
+ readonly repay: MidnightRepay;
228
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
229
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
230
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
231
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
232
+ readonly nativeAmount?: bigint;
233
+ /** `assets: maxUint256` withdraws the whole balance of that collateral. Defaults to none. */
234
+ readonly collateralWithdrawals?: readonly MidnightCollateralTransfer[];
235
+ /** Defaults to `accountAddress`. */
236
+ readonly collateralReceiver?: Address;
154
237
  /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
155
238
  readonly deadline: bigint;
156
239
  }
@@ -161,4 +244,3 @@ export interface GetPositionDataParams {
161
244
  /** Optional fetch controls. Pass an externally fetched block number to coordinate this snapshot with other reads. */
162
245
  readonly parameters?: MidnightFetchParams;
163
246
  }
164
- export {};
@@ -144,7 +144,8 @@ export interface VaultV1Actions {
144
144
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
145
145
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple permits are supplied.
146
146
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed or
147
- * its spender, amount or deadline differ from this operation's.
147
+ * its spender or deadline differ from this operation's, or its amount is outside
148
+ * `[cap, cap / (1 - slippageTolerance)]`.
148
149
  * @throws {viem.BaseError} when an allowance or nonce read or transaction encoding fails.
149
150
  * @example
150
151
  * ```ts
@@ -281,7 +282,7 @@ export interface VaultV1Actions {
281
282
  * assigning more than the vault owns in a repeated market.
282
283
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
283
284
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
284
- * @throws {viem.BaseError} from `getRequirements()` when an RPC or multicall contract read fails.
285
+ * @throws {viem.BaseError} from `getRequirements()` when an RPC contract read fails.
285
286
  * @throws {VaultMorphoMismatchError} from `getRequirements()` when the vault uses another Morpho deployment.
286
287
  * @throws {VaultIsBlueFeeRecipientError} from `getRequirements()` when Morpho Blue accrues protocol fees to the vault.
287
288
  * @throws {InsufficientBlueBalanceForInKindRedeemError} from `getRequirements()` when Blue cannot fund the flash loan.
@@ -2,7 +2,7 @@ import { DEFAULT_SLIPPAGE_TOLERANCE, Eip5267Domain, MarketUtils, MathLib, Token,
2
2
  import { blueAbi, erc2612Abi, fetchAccrualVault, metaMorphoAbi, } from "@morpho-org/blue-sdk-viem";
3
3
  import { getChainAddress, Time } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual } from "viem";
5
- import { multicall } from "viem/actions";
5
+ import { readContract } from "viem/actions";
6
6
  import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundlesFunding, selectBundlesSharesPermitSignature, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
7
7
  import { encodeErc20Approval, encodeVaultSharesPermit, vaultV1Deposit, vaultV1InKindRedeem, vaultV1MigrateToV2, vaultV1Redeem, vaultV1Withdraw, } from "../../actions/index.js";
8
8
  import { computeVaultMaxShareAllowance, computeVaultMaxSharePrice, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
@@ -178,6 +178,7 @@ export class MorphoVaultV1 {
178
178
  const permit = selectBundlesSharesPermitSignature(signatures, {
179
179
  spender,
180
180
  amount: requiredShareAllowance,
181
+ maxAmount: maxShareAllowance,
181
182
  deadline,
182
183
  });
183
184
  return vaultV1Withdraw({
@@ -317,40 +318,37 @@ export class MorphoVaultV1 {
317
318
  if (deadline <= requirementsTimestamp) {
318
319
  throw new ExpiredDeadlineError(deadline, requirementsTimestamp);
319
320
  }
320
- const [allowance, nonce, blueBalance, morpho, blueFeeRecipient] = await multicall(this.client.viemClient, {
321
- allowFailure: false,
322
- contracts: [
323
- {
324
- address: this.vault,
325
- abi: erc20Abi,
326
- functionName: "allowance",
327
- args: [userAddress, vaultExitBundlesV1],
328
- },
329
- {
330
- address: this.vault,
331
- abi: erc2612Abi,
332
- functionName: "nonces",
333
- args: [userAddress],
334
- },
335
- {
336
- address: vaultData.asset,
337
- abi: erc20Abi,
338
- functionName: "balanceOf",
339
- args: [blue],
340
- },
341
- {
342
- address: this.vault,
343
- abi: metaMorphoAbi,
344
- functionName: "MORPHO",
345
- },
346
- // feeRecipient() is trusted as returned by the RPC. See THREAT_MODEL.md, RPC.
347
- {
348
- address: blue,
349
- abi: blueAbi,
350
- functionName: "feeRecipient",
351
- },
352
- ],
353
- });
321
+ const [allowance, nonce, blueBalance, morpho, blueFeeRecipient] = await Promise.all([
322
+ readContract(this.client.viemClient, {
323
+ address: this.vault,
324
+ abi: erc20Abi,
325
+ functionName: "allowance",
326
+ args: [userAddress, vaultExitBundlesV1],
327
+ }),
328
+ readContract(this.client.viemClient, {
329
+ address: this.vault,
330
+ abi: erc2612Abi,
331
+ functionName: "nonces",
332
+ args: [userAddress],
333
+ }),
334
+ readContract(this.client.viemClient, {
335
+ address: vaultData.asset,
336
+ abi: erc20Abi,
337
+ functionName: "balanceOf",
338
+ args: [blue],
339
+ }),
340
+ readContract(this.client.viemClient, {
341
+ address: this.vault,
342
+ abi: metaMorphoAbi,
343
+ functionName: "MORPHO",
344
+ }),
345
+ // feeRecipient() is trusted as returned by the RPC. See THREAT_MODEL.md, RPC.
346
+ readContract(this.client.viemClient, {
347
+ address: blue,
348
+ abi: blueAbi,
349
+ functionName: "feeRecipient",
350
+ }),
351
+ ]);
354
352
  if (!isAddressEqual(morpho, blue)) {
355
353
  throw new VaultMorphoMismatchError({
356
354
  vault: this.vault,
@@ -63,8 +63,9 @@ export interface VaultV2Actions {
63
63
  * owner is consumed and none was passed explicitly.
64
64
  * @throws {Permit2SignatureTransferNonceAlreadyUsedError} from `getRequirements()` when the
65
65
  * explicit Permit2 nonce is consumed.
66
- * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, or from
67
- * `getRequirements()` when the Permit2 nonce exceeds uint256.
66
+ * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, when the vault's
67
+ * liquidity adapter is a Midnight adapter (it cannot receive vault allocations, so no deposit
68
+ * fits and `max` is `0n`), or from `getRequirements()` when the Permit2 nonce exceeds uint256.
68
69
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
69
70
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
70
71
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -139,7 +140,9 @@ export interface VaultV2Actions {
139
140
  * @throws {NonPositiveInputError} when `amount` or the computed share cap is not positive.
140
141
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
141
142
  * at any `getRequirements()` call.
142
- * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation.
143
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation,
144
+ * or when the vault's liquidity adapter is a Midnight adapter and `amount` exceeds the vault's
145
+ * idle assets.
143
146
  * @throws {NegativeInputError} when `referralFeePct` or `slippageTolerance` is negative.
144
147
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
145
148
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no nonzero recipient.
@@ -150,7 +153,8 @@ export interface VaultV2Actions {
150
153
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
151
154
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple permits are supplied.
152
155
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed or
153
- * its spender, amount or deadline differ from this operation's.
156
+ * its spender or deadline differ from this operation's, or its amount is outside
157
+ * `[cap, cap / (1 - slippageTolerance)]`.
154
158
  * @throws {viem.BaseError} when an allowance or nonce read or transaction encoding fails.
155
159
  * @example
156
160
  * ```ts
@@ -199,13 +203,30 @@ export interface VaultV2Actions {
199
203
  * @throws {NonPositiveInputError} when `shares` is not positive.
200
204
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
201
205
  * requirement resolution.
202
- * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
206
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256, or from
207
+ * `getRequirements()` when the vault's liquidity adapter is a Midnight adapter and `shares`
208
+ * are worth more than the vault's idle assets.
209
+ * @throws {UnknownBlueFactory} from `getRequirements()` when the configured chain has no VaultV2 factory.
210
+ * @throws {UnknownBlueOfFactory} from `getRequirements()` when the vault is not a VaultV2 from the
211
+ * configured factory.
212
+ * @throws {UnsupportedBlueVaultV2AdapterError} from `getRequirements()` when the vault or one of its
213
+ * adapters uses an unsupported adapter class.
214
+ * @throws {UnsupportedBlueMarketIrmError} from `getRequirements()` when the vault's liquidity adapter
215
+ * is a Midnight adapter and accrual projects an underlying market with positive debt that uses an
216
+ * unsupported IRM.
217
+ * @throws {UnknownBlueMarketAllocationError} from `getRequirements()` when the vault's liquidity
218
+ * adapter is a Midnight adapter and accrual meets a nested Vault V1 withdraw queue market without
219
+ * allocation data.
220
+ * @throws {InvalidMidnightPositionLossFactorError} from `getRequirements()` when the vault's liquidity
221
+ * adapter is a Midnight adapter and accrual meets a market loss factor below a position's.
222
+ * @throws {InvalidMidnightPositionAccrualStateError} from `getRequirements()` when the vault's
223
+ * liquidity adapter is a Midnight adapter and accrual meets invalid Midnight position inputs.
203
224
  * @throws {NegativeInputError} when `referralFeePct` is negative.
204
225
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
205
226
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
206
227
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
207
228
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
208
- * @throws {viem.BaseError} from `getRequirements()` when an allowance or nonce read fails.
229
+ * @throws {viem.BaseError} from `getRequirements()` when a vault-state, allowance or nonce read fails.
209
230
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
210
231
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
211
232
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -275,13 +296,15 @@ export interface VaultV2Actions {
275
296
  * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256`.
276
297
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
277
298
  * requirement resolution.
278
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter.
299
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter, including
300
+ * a vault that mixes Blue and Midnight adapters.
279
301
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
280
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
302
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
303
+ * including a Midnight adapter.
281
304
  * @throws {InKindRedeemCoverageError} when the deduplicated list cannot cover the exit.
282
305
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
283
306
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
284
- * @throws {viem.BaseError} from `getRequirements()` when an RPC or multicall contract read fails.
307
+ * @throws {viem.BaseError} from `getRequirements()` when an RPC contract read fails.
285
308
  * @throws {InsufficientBlueBalanceForInKindRedeemError} from `getRequirements()` when Blue cannot fund the largest callback.
286
309
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
287
310
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
@@ -398,9 +421,11 @@ export interface VaultV2Actions {
398
421
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
399
422
  * requirement resolution.
400
423
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
401
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter.
424
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter,
425
+ * including a vault that mixes Blue and Midnight adapters.
402
426
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
403
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
427
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
428
+ * including a Midnight adapter.
404
429
  * @throws {VaultV2UnsupportedLiquidityAdapterError} when the vault routes liquidity through
405
430
  * another adapter.
406
431
  * @throws {VaultV2UndecodableLiquidityDataError} when the vault's `liquidityData` does not decode
@@ -417,7 +442,7 @@ export interface VaultV2Actions {
417
442
  * @throws {ReferralFeeRecipientMissingError} when a positive `referralFeePct` has no recipient.
418
443
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
419
444
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
420
- * @throws {viem.BaseError} from `getRequirements()` when an RPC or multicall contract read fails.
445
+ * @throws {viem.BaseError} from `getRequirements()` when an RPC contract read fails.
421
446
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
422
447
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
423
448
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the permit's spender, amount, or