@morpho-org/morpho-sdk 6.6.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/MIGRATION-v6-to-v7.md +291 -0
  2. package/README.md +26 -12
  3. package/lib/cjs/abis.d.ts +1 -1
  4. package/lib/cjs/abis.js +3 -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/constants.d.ts +1 -1
  40. package/lib/cjs/constants.js +2 -1
  41. package/lib/cjs/entities/index.d.ts +2 -2
  42. package/lib/cjs/entities/midnight/midnight.d.ts +582 -108
  43. package/lib/cjs/entities/midnight/midnight.js +981 -509
  44. package/lib/cjs/entities/midnight/types.d.ts +142 -60
  45. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +2 -1
  46. package/lib/cjs/entities/vaultV1/vaultV1.js +1 -0
  47. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +2 -1
  48. package/lib/cjs/entities/vaultV2/vaultV2.js +1 -0
  49. package/lib/cjs/helpers/callback.d.ts +54 -0
  50. package/lib/cjs/helpers/callback.js +73 -0
  51. package/lib/cjs/helpers/constant.d.ts +2 -0
  52. package/lib/cjs/helpers/constant.js +3 -1
  53. package/lib/cjs/helpers/index.d.ts +3 -2
  54. package/lib/cjs/helpers/index.js +6 -1
  55. package/lib/cjs/helpers/signAndVerifyTypedData.d.ts +3 -3
  56. package/lib/cjs/helpers/signAndVerifyTypedData.js +3 -3
  57. package/lib/cjs/helpers/validate.d.ts +43 -2
  58. package/lib/cjs/helpers/validate.js +60 -3
  59. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +1 -1
  60. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +3 -7
  61. package/lib/cjs/helpers/validateRequirementSpender.d.ts +3 -3
  62. package/lib/cjs/helpers/validateRequirementSpender.js +4 -5
  63. package/lib/cjs/midnight/abis.d.ts +1 -1
  64. package/lib/cjs/midnight/abis.js +3 -2
  65. package/lib/cjs/midnight/types.d.ts +1 -1
  66. package/lib/cjs/types/action.d.ts +117 -89
  67. package/lib/cjs/types/action.js +1 -19
  68. package/lib/cjs/types/error.d.ts +126 -40
  69. package/lib/cjs/types/error.js +154 -49
  70. package/lib/esm/abis.d.ts +1 -1
  71. package/lib/esm/abis.js +1 -1
  72. package/lib/esm/actions/bundles/common.d.ts +9 -5
  73. package/lib/esm/actions/bundles/common.js +22 -13
  74. package/lib/esm/actions/midnight/authorization.d.ts +3 -2
  75. package/lib/esm/actions/midnight/authorization.js +3 -2
  76. package/lib/esm/actions/midnight/cancelAndMake.d.ts +153 -0
  77. package/lib/esm/actions/midnight/cancelAndMake.js +288 -0
  78. package/lib/esm/actions/midnight/index.d.ts +3 -3
  79. package/lib/esm/actions/midnight/index.js +3 -3
  80. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +40 -23
  81. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +108 -72
  82. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +52 -27
  83. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +131 -74
  84. package/lib/esm/actions/midnight/takeBorrow.d.ts +40 -28
  85. package/lib/esm/actions/midnight/takeBorrow.js +98 -57
  86. package/lib/esm/actions/midnight/takeLend.d.ts +51 -27
  87. package/lib/esm/actions/midnight/takeLend.js +114 -57
  88. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +97 -0
  89. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +197 -0
  90. package/lib/esm/actions/midnight/takeWithdraw.d.ts +69 -0
  91. package/lib/esm/actions/midnight/takeWithdraw.js +149 -0
  92. package/lib/esm/actions/midnight/types.d.ts +7 -26
  93. package/lib/esm/actions/midnight/types.js +1 -12
  94. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  95. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
  96. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -4
  97. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +5 -5
  98. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +2 -2
  99. package/lib/esm/actions/requirements/getRequirementsApproval.js +2 -2
  100. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +24 -8
  101. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +25 -14
  102. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -7
  103. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +11 -7
  104. package/lib/esm/actions/requirements/midnight/index.d.ts +0 -1
  105. package/lib/esm/actions/requirements/midnight/index.js +0 -1
  106. package/lib/esm/constants.d.ts +1 -1
  107. package/lib/esm/constants.js +1 -1
  108. package/lib/esm/entities/index.d.ts +2 -2
  109. package/lib/esm/entities/midnight/midnight.d.ts +582 -108
  110. package/lib/esm/entities/midnight/midnight.js +987 -515
  111. package/lib/esm/entities/midnight/types.d.ts +142 -60
  112. package/lib/esm/entities/vaultV1/vaultV1.d.ts +2 -1
  113. package/lib/esm/entities/vaultV1/vaultV1.js +1 -0
  114. package/lib/esm/entities/vaultV2/vaultV2.d.ts +2 -1
  115. package/lib/esm/entities/vaultV2/vaultV2.js +1 -0
  116. package/lib/esm/helpers/callback.d.ts +54 -0
  117. package/lib/esm/helpers/callback.js +68 -0
  118. package/lib/esm/helpers/constant.d.ts +2 -0
  119. package/lib/esm/helpers/constant.js +2 -0
  120. package/lib/esm/helpers/index.d.ts +3 -2
  121. package/lib/esm/helpers/index.js +3 -2
  122. package/lib/esm/helpers/signAndVerifyTypedData.d.ts +3 -3
  123. package/lib/esm/helpers/signAndVerifyTypedData.js +3 -3
  124. package/lib/esm/helpers/validate.d.ts +43 -2
  125. package/lib/esm/helpers/validate.js +58 -2
  126. package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +1 -1
  127. package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +3 -7
  128. package/lib/esm/helpers/validateRequirementSpender.d.ts +3 -3
  129. package/lib/esm/helpers/validateRequirementSpender.js +4 -5
  130. package/lib/esm/midnight/abis.d.ts +1 -1
  131. package/lib/esm/midnight/abis.js +1 -1
  132. package/lib/esm/midnight/types.d.ts +1 -1
  133. package/lib/esm/types/action.d.ts +117 -89
  134. package/lib/esm/types/action.js +1 -18
  135. package/lib/esm/types/error.d.ts +126 -40
  136. package/lib/esm/types/error.js +135 -38
  137. package/package.json +8 -7
  138. package/lib/cjs/actions/midnight/cancelOffer.d.ts +0 -38
  139. package/lib/cjs/actions/midnight/cancelOffer.js +0 -73
  140. package/lib/cjs/actions/midnight/mempoolSubmitOffers.d.ts +0 -52
  141. package/lib/cjs/actions/midnight/mempoolSubmitOffers.js +0 -72
  142. package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.d.ts +0 -40
  143. package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.js +0 -59
  144. package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +0 -42
  145. package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +0 -70
  146. package/lib/esm/actions/midnight/cancelOffer.d.ts +0 -38
  147. package/lib/esm/actions/midnight/cancelOffer.js +0 -69
  148. package/lib/esm/actions/midnight/mempoolSubmitOffers.d.ts +0 -52
  149. package/lib/esm/actions/midnight/mempoolSubmitOffers.js +0 -68
  150. package/lib/esm/actions/midnight/setterRatifierRatifyRoot.d.ts +0 -40
  151. package/lib/esm/actions/midnight/setterRatifierRatifyRoot.js +0 -55
  152. package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +0 -42
  153. package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +0 -66
@@ -1,105 +1,163 @@
1
- import { MarketUtils, midnightBundlesAbi } from "@morpho-org/midnight-sdk";
1
+ import { MarketUtils, midnightBundlesV2Abi } from "@morpho-org/midnight-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { encodeFunctionData, maxUint256, zeroAddress } from "viem";
3
+ import { encodeFunctionData, isAddressEqual, maxUint256, zeroAddress, } from "viem";
4
4
  import { addTransactionMetadata } from "../../helpers/index.js";
5
+ import { validateDeadline, validateMidnightNativeAmount, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
5
6
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
6
7
  import { validateTakeableOffers } from "../../helpers/validateTakeableOffers.js";
7
- import { NegativeInputError, NonPositiveInputError, } from "../../types/index.js";
8
- import { PermitKind } from "./types.js";
8
+ import { EmptyMidnightCollateralSuppliesError, MidnightZeroReceiverError, NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../types/index.js";
9
9
  /**
10
- * Encodes a Midnight bundle that supplies collateral and borrows in one call.
10
+ * Encodes a `MidnightBundlesV2` sell that supplies collateral and borrows from lend-side offers
11
+ * for `msg.sender` in one call.
11
12
  *
12
- * Prefer `client.morpho.midnight(chainId).supplyCollateralTakeBorrow(...)` in
13
- * app flows so collateral approval and Midnight authorization requirements are
14
- * resolved before building the bundle. Use this low-level builder only after
15
- * market data and API takeable offers are already available.
13
+ * Like `midnightTakeBorrow`, the sender's existing credit is withdrawn before offers are taken.
14
+ * Prefer `client.morpho.midnight(chainId).supplyCollateralTakeBorrow(...)` in app flows so
15
+ * collateral approvals and the `MidnightBundlesV2` authorization are resolved first.
16
16
  *
17
- * @param params.chainId - Chain id used to resolve `MidnightBundles`.
17
+ * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
18
18
  * @param params.market - Midnight market traded by every takeable offer.
19
- * @param params.loanAssets - Loan assets the borrower receives.
20
- * @param params.maxUnits - Maximum debt units accepted from the bundle quote.
21
- * @param params.taker - Borrower address executing the bundle.
22
- * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry.
19
+ * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
20
+ * @param params.receiver - Recipient of the borrowed loan assets.
21
+ * @param params.collateralSupplies - Collateral index and assets per supply; must not be empty.
22
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
23
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of the
24
+ * maximum wNative amount this call can pull, but not more. Any wrapped native not pulled stays in
25
+ * the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still required
26
+ * for the full pulled amount.
23
27
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
24
- * @param params.collateralAssets - Collateral assets supplied before taking offers.
25
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
26
- * @returns A deep-frozen `Transaction<MidnightSupplyCollateralTakeBorrowAction>` targeting `MidnightBundles`.
27
- * @throws {NonPositiveInputError} when collateral assets, loan assets, or `maxUnits` are non-positive.
28
- * @throws {NegativeInputError} when `deadline` is negative.
28
+ * @param params.deadline - Bounded bundle execution deadline timestamp.
29
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
30
+ * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
31
+ * @param params.metadata - Optional analytics metadata appended to calldata.
32
+ * @returns A deep-frozen `Transaction<MidnightSupplyCollateralTakeBorrowAction>` targeting `MidnightBundlesV2`.
33
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
34
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
35
+ * @throws {ChainIdMismatchError} when the market targets another chain.
36
+ * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
37
+ * @throws {EmptyMidnightCollateralSuppliesError} when no collateral supply is provided.
38
+ * @throws {UnknownCollateralIndexError} when a collateral index is not configured on the market.
29
39
  * @throws {EmptyMidnightTakeableOffersError} when no offers are provided.
30
40
  * @throws {MidnightOfferSideMismatchError} when any offer is not lend-side.
31
41
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
32
- * @throws {ChainIdMismatchError} when the market targets another chain.
33
- * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
34
- * @throws {UnknownCollateralIndexError} when `collateralIndex` is not configured on the market.
42
+ * @throws {NonPositiveInputError} when a supply amount, the target amount, `maxUnits`, `minSellerAssets` or `deadline` is not positive.
43
+ * @throws {NegativeInputError} when `referralFeePct` or `nativeAmount` is negative.
44
+ * @throws {InputExceedsMaxError} when a `collateralSupplies[].assets` amount, `target.assets`,
45
+ * `target.maxUnits`, `target.units`, `target.minSellerAssets` or `deadline` exceeds `uint256`, or
46
+ * `nativeAmount` exceeds the maximum wNative collateral amount this call can pull.
47
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
48
+ * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
49
+ * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or
50
+ * `deadline` is `maxUint256`.
51
+ * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
52
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
53
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
35
54
  * @example
36
55
  * ```ts
37
- * import { maxUint256 } from "viem";
56
+ * import { Time } from "@morpho-org/morpho-ts";
38
57
  * import { midnightSupplyCollateralTakeBorrow } from "@morpho-org/morpho-sdk";
39
58
  *
40
59
  * const tx = midnightSupplyCollateralTakeBorrow({
41
60
  * chainId: 8453,
42
61
  * market: marketData.params,
43
- * collateralAssets: 2_000_000n,
44
- * loanAssets: 1_000_000n,
45
- * maxUnits: 1_100_000n,
46
- * taker: borrower,
62
+ * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
63
+ * receiver: borrower,
64
+ * collateralSupplies: [{ collateralIndex: 0n, assets: 2_000_000n }],
47
65
  * takeableOffers: quote.data.takeableOffers,
48
- * deadline: maxUint256,
66
+ * deadline: Time.timestamp() + 600n,
49
67
  * });
50
68
  * ```
51
69
  */
52
70
  export const midnightSupplyCollateralTakeBorrow = (params) => {
53
- if (params.collateralAssets <= 0n) {
54
- throw new NonPositiveInputError("collateralAssets", params.collateralAssets);
55
- }
56
- if (params.loanAssets <= 0n) {
57
- throw new NonPositiveInputError("loanAssets", params.loanAssets);
58
- }
59
- if (params.maxUnits <= 0n) {
60
- throw new NonPositiveInputError("maxUnits", params.maxUnits);
71
+ // Reject markets from another chain deployment before checking offers against them.
72
+ validateMidnightMarket({ market: params.market, chainId: params.chainId });
73
+ if (params.collateralSupplies.length === 0) {
74
+ throw new EmptyMidnightCollateralSuppliesError();
61
75
  }
62
- if (params.deadline < 0n) {
63
- throw new NegativeInputError("deadline", params.deadline);
76
+ for (const [index, { collateralIndex, assets },] of params.collateralSupplies.entries()) {
77
+ if (assets <= 0n) {
78
+ throw new NonPositiveInputError(`collateralSupplies[${index}].assets`, assets);
79
+ }
80
+ validateUint256Field(`collateralSupplies[${index}].assets`, assets);
81
+ // Throws UnknownCollateralIndexError when the index is not configured on the market.
82
+ MarketUtils.getCollateralByIndex(params.market, collateralIndex);
64
83
  }
65
- // Reject markets from another chain deployment before encoding the bundle.
66
- validateMidnightMarket({ market: params.market, chainId: params.chainId });
67
84
  const marketId = validateTakeableOffers({
68
85
  market: params.market,
69
86
  takeableOffers: params.takeableOffers,
70
87
  expectedBuy: true,
71
88
  });
72
- const midnightBundles = getChainAddress(params.chainId, "midnightBundles");
73
- const collateralIndex = params.collateralIndex ?? 0n;
74
- // Validate that the collateral index is configured before encoding the bundle.
75
- MarketUtils.getCollateralByIndex(params.market, collateralIndex);
76
- const collateralSupplies = [
77
- {
89
+ if (isAddressEqual(params.receiver, zeroAddress)) {
90
+ throw new MidnightZeroReceiverError("receiver");
91
+ }
92
+ const { target } = params;
93
+ if (target.type === "assets") {
94
+ if (target.assets <= 0n) {
95
+ throw new NonPositiveInputError("target.assets", target.assets);
96
+ }
97
+ if (target.maxUnits === maxUint256) {
98
+ throw new UnboundedMidnightTakeInputError("target.maxUnits");
99
+ }
100
+ if (target.maxUnits <= 0n) {
101
+ throw new NonPositiveInputError("target.maxUnits", target.maxUnits);
102
+ }
103
+ validateUint256Field("target.assets", target.assets);
104
+ validateUint256Field("target.maxUnits", target.maxUnits);
105
+ }
106
+ else {
107
+ if (target.units === maxUint256) {
108
+ throw new UnboundedMidnightTakeInputError("target.units");
109
+ }
110
+ if (target.units <= 0n) {
111
+ throw new NonPositiveInputError("target.units", target.units);
112
+ }
113
+ if (target.minSellerAssets <= 0n) {
114
+ throw new NonPositiveInputError("target.minSellerAssets", target.minSellerAssets);
115
+ }
116
+ validateUint256Field("target.units", target.units);
117
+ validateUint256Field("target.minSellerAssets", target.minSellerAssets);
118
+ }
119
+ if (params.deadline === maxUint256) {
120
+ throw new UnboundedMidnightTakeInputError("deadline");
121
+ }
122
+ validateDeadline(params.deadline);
123
+ const { referralFeePct, referralFeeRecipient } = validateReferralFee(params);
124
+ const nativeFunding = validateMidnightNativeAmount({
125
+ chainId: params.chainId,
126
+ nativeAmount: params.nativeAmount,
127
+ pulls: params.collateralSupplies.map(({ collateralIndex, assets }) => ({
128
+ token: MarketUtils.getCollateralByIndex(params.market, collateralIndex)
129
+ .token,
130
+ assets,
131
+ })),
132
+ });
133
+ const market = MarketUtils.toStruct(params.market);
134
+ const args = [
135
+ false, // reduceOnly
136
+ params.receiver, // receiver
137
+ params.collateralSupplies.map(({ collateralIndex, assets }) => ({
78
138
  collateralIndex,
79
- assets: params.collateralAssets,
80
- permit: { kind: PermitKind.None, data: "0x" },
81
- },
139
+ assets,
140
+ })), // collateralSupplies
141
+ params.takeableOffers, // offerFills
142
+ referralFeePct, // referralFeePct
143
+ referralFeeRecipient, // referralFeeRecipient
144
+ params.deadline, // deadline
145
+ nativeFunding.wrappedNative, // wrappedNative
82
146
  ];
83
147
  let tx = {
84
- to: midnightBundles,
85
- value: 0n,
86
- data: encodeFunctionData({
87
- abi: midnightBundlesAbi,
88
- functionName: "midnightBundlesV1SupplyCollateralAndSellWithAssetsTarget",
89
- args: [
90
- params.loanAssets,
91
- params.maxUnits,
92
- params.taker,
93
- false,
94
- params.taker,
95
- collateralSupplies,
96
- params.takeableOffers,
97
- 0n,
98
- zeroAddress,
99
- maxUint256,
100
- params.deadline,
101
- ],
102
- }),
148
+ to: getChainAddress(params.chainId, "midnightBundlesV2"),
149
+ value: nativeFunding.value,
150
+ data: target.type === "assets"
151
+ ? encodeFunctionData({
152
+ abi: midnightBundlesV2Abi,
153
+ functionName: "midnightBundlesV2SupplyCollateralAndSellWithAssetsTarget",
154
+ args: [market, target.assets, target.maxUnits, ...args],
155
+ })
156
+ : encodeFunctionData({
157
+ abi: midnightBundlesV2Abi,
158
+ functionName: "midnightBundlesV2SupplyCollateralAndSellWithUnitsTarget",
159
+ args: [market, target.units, target.minSellerAssets, ...args],
160
+ }),
103
161
  };
104
162
  if (params.metadata) {
105
163
  tx = addTransactionMetadata(tx, params.metadata);
@@ -110,14 +168,13 @@ export const midnightSupplyCollateralTakeBorrow = (params) => {
110
168
  type: "midnightSupplyCollateralTakeBorrow",
111
169
  args: {
112
170
  market: marketId,
113
- collateralAssets: params.collateralAssets,
114
- loanAssets: params.loanAssets,
115
- maxUnits: params.maxUnits,
116
- taker: params.taker,
117
- receiver: params.taker,
118
- collateralSupplies: collateralSupplies.length,
171
+ target: { ...params.target },
172
+ receiver: params.receiver,
173
+ collateralSupplies: params.collateralSupplies.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
119
174
  takeableOffers: params.takeableOffers.length,
120
175
  deadline: params.deadline,
176
+ referralFeePct,
177
+ referralFeeRecipient,
121
178
  },
122
179
  },
123
180
  });
@@ -1,56 +1,68 @@
1
1
  import { type MarketInput } from "@morpho-org/midnight-sdk";
2
2
  import { type Address } from "viem";
3
- import { type Metadata, type MidnightTakeBorrowAction, type Transaction } from "../../types/index.js";
4
- import type { MidnightTakeableOffer } from "./types.js";
3
+ import { type Metadata, type MidnightSellTarget, type MidnightTakeBorrowAction, type Transaction } from "../../types/index.js";
4
+ import type { MidnightReferralFeeParams, MidnightTakeableOffer } from "./types.js";
5
5
  /** Parameters for encoding a Midnight borrow take from already selected offers. */
6
- export interface MidnightTakeBorrowParams {
6
+ export interface MidnightTakeBorrowParams extends MidnightReferralFeeParams {
7
7
  readonly chainId: number;
8
8
  readonly market: MarketInput;
9
- readonly loanAssets: bigint;
10
- readonly maxUnits: bigint;
11
- readonly taker: Address;
12
- /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
13
- readonly deadline: bigint;
9
+ /** Loan assets received with a unit cap, or units sold with a loan-asset floor. */
10
+ readonly target: MidnightSellTarget;
11
+ /** Recipient of the borrowed loan assets. */
12
+ readonly receiver: Address;
14
13
  readonly takeableOffers: readonly MidnightTakeableOffer[];
14
+ /** Bounded bundle execution deadline timestamp. */
15
+ readonly deadline: bigint;
15
16
  readonly metadata?: Metadata;
16
17
  }
17
18
  /**
18
- * Encodes a Midnight bundle that borrows loan assets by taking lend-side offers.
19
+ * Encodes a `MidnightBundlesV2` sell that borrows from lend-side offers for `msg.sender`.
19
20
  *
20
- * Prefer `client.morpho.midnight(chainId).takeBorrow(...)` in app flows so
21
- * authorization requirements are resolved first. Use this low-level builder
22
- * only after the Midnight API has returned takeable offers and the caller has
23
- * already handled prerequisites.
21
+ * `MidnightBundlesV2` first withdraws as much of the sender's existing credit as the target and
22
+ * market liquidity allow, and fills only the rest from offers: a sender with credit nets it before
23
+ * taking debt.
24
24
  *
25
- * @param params.chainId - Chain id used to resolve `MidnightBundles`.
25
+ * Prefer `client.morpho.midnight(chainId).takeBorrow(...)` in app flows so the
26
+ * `MidnightBundlesV2` authorization is resolved before building the bundle.
27
+ *
28
+ * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
26
29
  * @param params.market - Midnight market traded by every takeable offer.
27
- * @param params.loanAssets - Loan assets the borrower receives.
28
- * @param params.maxUnits - Maximum debt units accepted from the bundle quote.
29
- * @param params.taker - Borrower address executing the bundle.
30
- * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry.
30
+ * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
31
+ * @param params.receiver - Recipient of the borrowed loan assets.
31
32
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
33
+ * @param params.deadline - Bounded bundle execution deadline timestamp.
34
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
35
+ * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
32
36
  * @param params.metadata - Optional analytics metadata appended to calldata.
33
- * @returns A deep-frozen `Transaction<MidnightTakeBorrowAction>` targeting `MidnightBundles`.
34
- * @throws {NonPositiveInputError} when `loanAssets` or `maxUnits` is non-positive.
35
- * @throws {NegativeInputError} when `deadline` is negative.
37
+ * @returns A deep-frozen `Transaction<MidnightTakeBorrowAction>` targeting `MidnightBundlesV2`.
38
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
39
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
40
+ * @throws {ChainIdMismatchError} when the market targets another chain.
41
+ * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
36
42
  * @throws {EmptyMidnightTakeableOffersError} when no offers are provided.
37
43
  * @throws {MidnightOfferSideMismatchError} when any offer is not lend-side.
38
44
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
39
- * @throws {ChainIdMismatchError} when the market targets another chain.
40
- * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
45
+ * @throws {NonPositiveInputError} when the target amount, `maxUnits`, `minSellerAssets` or `deadline` is not positive.
46
+ * @throws {NegativeInputError} when `referralFeePct` is negative.
47
+ * @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`,
48
+ * `target.minSellerAssets` or `deadline` exceeds `uint256`.
49
+ * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or
50
+ * `deadline` is `maxUint256`.
51
+ * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
52
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
53
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
41
54
  * @example
42
55
  * ```ts
43
- * import { maxUint256 } from "viem";
56
+ * import { Time } from "@morpho-org/morpho-ts";
44
57
  * import { midnightTakeBorrow } from "@morpho-org/morpho-sdk";
45
58
  *
46
59
  * const tx = midnightTakeBorrow({
47
60
  * chainId: 8453,
48
61
  * market: marketData.params,
49
- * loanAssets: 1_000_000n,
50
- * maxUnits: 1_100_000n,
51
- * taker: borrower,
62
+ * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
63
+ * receiver: borrower,
52
64
  * takeableOffers: quote.data.takeableOffers,
53
- * deadline: maxUint256,
65
+ * deadline: Time.timestamp() + 600n,
54
66
  * });
55
67
  * ```
56
68
  */
@@ -1,88 +1,130 @@
1
- import { midnightBundlesAbi } from "@morpho-org/midnight-sdk";
1
+ import { MarketUtils, midnightBundlesV2Abi, } from "@morpho-org/midnight-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { encodeFunctionData, maxUint256, zeroAddress, } from "viem";
3
+ import { encodeFunctionData, isAddressEqual, maxUint256, zeroAddress, } from "viem";
4
4
  import { addTransactionMetadata } from "../../helpers/index.js";
5
+ import { validateDeadline, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
5
6
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
6
7
  import { validateTakeableOffers } from "../../helpers/validateTakeableOffers.js";
7
- import { NegativeInputError, NonPositiveInputError, } from "../../types/index.js";
8
+ import { MidnightZeroReceiverError, NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../types/index.js";
8
9
  /**
9
- * Encodes a Midnight bundle that borrows loan assets by taking lend-side offers.
10
+ * Encodes a `MidnightBundlesV2` sell that borrows from lend-side offers for `msg.sender`.
10
11
  *
11
- * Prefer `client.morpho.midnight(chainId).takeBorrow(...)` in app flows so
12
- * authorization requirements are resolved first. Use this low-level builder
13
- * only after the Midnight API has returned takeable offers and the caller has
14
- * already handled prerequisites.
12
+ * `MidnightBundlesV2` first withdraws as much of the sender's existing credit as the target and
13
+ * market liquidity allow, and fills only the rest from offers: a sender with credit nets it before
14
+ * taking debt.
15
15
  *
16
- * @param params.chainId - Chain id used to resolve `MidnightBundles`.
16
+ * Prefer `client.morpho.midnight(chainId).takeBorrow(...)` in app flows so the
17
+ * `MidnightBundlesV2` authorization is resolved before building the bundle.
18
+ *
19
+ * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
17
20
  * @param params.market - Midnight market traded by every takeable offer.
18
- * @param params.loanAssets - Loan assets the borrower receives.
19
- * @param params.maxUnits - Maximum debt units accepted from the bundle quote.
20
- * @param params.taker - Borrower address executing the bundle.
21
- * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry.
21
+ * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
22
+ * @param params.receiver - Recipient of the borrowed loan assets.
22
23
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
24
+ * @param params.deadline - Bounded bundle execution deadline timestamp.
25
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
26
+ * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
23
27
  * @param params.metadata - Optional analytics metadata appended to calldata.
24
- * @returns A deep-frozen `Transaction<MidnightTakeBorrowAction>` targeting `MidnightBundles`.
25
- * @throws {NonPositiveInputError} when `loanAssets` or `maxUnits` is non-positive.
26
- * @throws {NegativeInputError} when `deadline` is negative.
28
+ * @returns A deep-frozen `Transaction<MidnightTakeBorrowAction>` targeting `MidnightBundlesV2`.
29
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
30
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
31
+ * @throws {ChainIdMismatchError} when the market targets another chain.
32
+ * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
27
33
  * @throws {EmptyMidnightTakeableOffersError} when no offers are provided.
28
34
  * @throws {MidnightOfferSideMismatchError} when any offer is not lend-side.
29
35
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
30
- * @throws {ChainIdMismatchError} when the market targets another chain.
31
- * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
36
+ * @throws {NonPositiveInputError} when the target amount, `maxUnits`, `minSellerAssets` or `deadline` is not positive.
37
+ * @throws {NegativeInputError} when `referralFeePct` is negative.
38
+ * @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`,
39
+ * `target.minSellerAssets` or `deadline` exceeds `uint256`.
40
+ * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or
41
+ * `deadline` is `maxUint256`.
42
+ * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
43
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
44
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
32
45
  * @example
33
46
  * ```ts
34
- * import { maxUint256 } from "viem";
47
+ * import { Time } from "@morpho-org/morpho-ts";
35
48
  * import { midnightTakeBorrow } from "@morpho-org/morpho-sdk";
36
49
  *
37
50
  * const tx = midnightTakeBorrow({
38
51
  * chainId: 8453,
39
52
  * market: marketData.params,
40
- * loanAssets: 1_000_000n,
41
- * maxUnits: 1_100_000n,
42
- * taker: borrower,
53
+ * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
54
+ * receiver: borrower,
43
55
  * takeableOffers: quote.data.takeableOffers,
44
- * deadline: maxUint256,
56
+ * deadline: Time.timestamp() + 600n,
45
57
  * });
46
58
  * ```
47
59
  */
48
60
  export const midnightTakeBorrow = (params) => {
49
- if (params.loanAssets <= 0n) {
50
- throw new NonPositiveInputError("loanAssets", params.loanAssets);
51
- }
52
- if (params.maxUnits <= 0n) {
53
- throw new NonPositiveInputError("maxUnits", params.maxUnits);
54
- }
55
- if (params.deadline < 0n) {
56
- throw new NegativeInputError("deadline", params.deadline);
57
- }
58
- // Reject markets from another chain deployment before encoding the bundle.
61
+ // Reject markets from another chain deployment before checking offers against them.
59
62
  validateMidnightMarket({ market: params.market, chainId: params.chainId });
60
63
  const marketId = validateTakeableOffers({
61
64
  market: params.market,
62
65
  takeableOffers: params.takeableOffers,
63
66
  expectedBuy: true,
64
67
  });
65
- const midnightBundles = getChainAddress(params.chainId, "midnightBundles");
68
+ if (isAddressEqual(params.receiver, zeroAddress)) {
69
+ throw new MidnightZeroReceiverError("receiver");
70
+ }
71
+ const { target } = params;
72
+ if (target.type === "assets") {
73
+ if (target.assets <= 0n) {
74
+ throw new NonPositiveInputError("target.assets", target.assets);
75
+ }
76
+ if (target.maxUnits === maxUint256) {
77
+ throw new UnboundedMidnightTakeInputError("target.maxUnits");
78
+ }
79
+ if (target.maxUnits <= 0n) {
80
+ throw new NonPositiveInputError("target.maxUnits", target.maxUnits);
81
+ }
82
+ validateUint256Field("target.assets", target.assets);
83
+ validateUint256Field("target.maxUnits", target.maxUnits);
84
+ }
85
+ else {
86
+ if (target.units === maxUint256) {
87
+ throw new UnboundedMidnightTakeInputError("target.units");
88
+ }
89
+ if (target.units <= 0n) {
90
+ throw new NonPositiveInputError("target.units", target.units);
91
+ }
92
+ if (target.minSellerAssets <= 0n) {
93
+ throw new NonPositiveInputError("target.minSellerAssets", target.minSellerAssets);
94
+ }
95
+ validateUint256Field("target.units", target.units);
96
+ validateUint256Field("target.minSellerAssets", target.minSellerAssets);
97
+ }
98
+ if (params.deadline === maxUint256) {
99
+ throw new UnboundedMidnightTakeInputError("deadline");
100
+ }
101
+ validateDeadline(params.deadline);
102
+ const { referralFeePct, referralFeeRecipient } = validateReferralFee(params);
103
+ const market = MarketUtils.toStruct(params.market);
104
+ const args = [
105
+ false, // reduceOnly
106
+ params.receiver, // receiver
107
+ [], // collateralSupplies
108
+ params.takeableOffers, // offerFills
109
+ referralFeePct, // referralFeePct
110
+ referralFeeRecipient, // referralFeeRecipient
111
+ params.deadline, // deadline
112
+ zeroAddress, // wrappedNative
113
+ ];
66
114
  let tx = {
67
- to: midnightBundles,
115
+ to: getChainAddress(params.chainId, "midnightBundlesV2"),
68
116
  value: 0n,
69
- data: encodeFunctionData({
70
- abi: midnightBundlesAbi,
71
- functionName: "midnightBundlesV1SupplyCollateralAndSellWithAssetsTarget",
72
- args: [
73
- params.loanAssets,
74
- params.maxUnits,
75
- params.taker,
76
- false,
77
- params.taker,
78
- [],
79
- params.takeableOffers,
80
- 0n,
81
- zeroAddress,
82
- maxUint256,
83
- params.deadline,
84
- ],
85
- }),
117
+ data: target.type === "assets"
118
+ ? encodeFunctionData({
119
+ abi: midnightBundlesV2Abi,
120
+ functionName: "midnightBundlesV2SupplyCollateralAndSellWithAssetsTarget",
121
+ args: [market, target.assets, target.maxUnits, ...args],
122
+ })
123
+ : encodeFunctionData({
124
+ abi: midnightBundlesV2Abi,
125
+ functionName: "midnightBundlesV2SupplyCollateralAndSellWithUnitsTarget",
126
+ args: [market, target.units, target.minSellerAssets, ...args],
127
+ }),
86
128
  };
87
129
  if (params.metadata) {
88
130
  tx = addTransactionMetadata(tx, params.metadata);
@@ -93,13 +135,12 @@ export const midnightTakeBorrow = (params) => {
93
135
  type: "midnightTakeBorrow",
94
136
  args: {
95
137
  market: marketId,
96
- loanAssets: params.loanAssets,
97
- maxUnits: params.maxUnits,
98
- taker: params.taker,
99
- receiver: params.taker,
100
- collateralSupplies: 0,
138
+ target: { ...params.target },
139
+ receiver: params.receiver,
101
140
  takeableOffers: params.takeableOffers.length,
102
141
  deadline: params.deadline,
142
+ referralFeePct,
143
+ referralFeeRecipient,
103
144
  },
104
145
  },
105
146
  });