@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,51 +1,68 @@
1
1
  import { type MarketInput } from "@morpho-org/midnight-sdk";
2
2
  import { type Address } from "viem";
3
- import { type Metadata, type MidnightRepayWithdrawCollateralAction, type Transaction } from "../../types/index.js";
4
- /** Parameters for encoding a Midnight repay and/or collateral withdrawal bundle. */
3
+ import { type Metadata, type MidnightCollateralTransfer, type MidnightRepay, type MidnightRepayWithdrawCollateralAction, type Transaction } from "../../types/index.js";
4
+ /** Parameters for encoding a direct Midnight repayment and/or collateral withdrawal. */
5
5
  export interface MidnightRepayWithdrawCollateralParams {
6
6
  readonly chainId: number;
7
7
  readonly market: MarketInput;
8
- readonly repayAssets: bigint;
9
- readonly withdrawCollateralAssets: bigint;
10
- readonly onBehalf: Address;
11
- readonly collateralIndex?: bigint;
8
+ readonly repay: MidnightRepay;
9
+ /**
10
+ * Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
11
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
12
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
13
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount.
14
+ */
15
+ readonly nativeAmount?: bigint;
16
+ /** `assets: maxUint256` withdraws the sender's whole balance of that collateral at execution. */
17
+ readonly collateralWithdrawals: readonly MidnightCollateralTransfer[];
18
+ readonly collateralReceiver: Address;
12
19
  /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
13
20
  readonly deadline: bigint;
14
21
  readonly metadata?: Metadata;
15
22
  }
16
23
  /**
17
- * Encodes a Midnight bundle that repays debt, withdraws collateral, or both.
24
+ * Encodes a reduce-only `MidnightBundlesV2` buy with no offers, so the sender's debt is repaid
25
+ * directly, then collateral is withdrawn to `collateralReceiver`. An `assets` repay uses the
26
+ * assets-target entrypoint with `minUnits = assets` (a direct repay counts one unit per asset); a
27
+ * `full` repay uses the units-target entrypoint with `targetUnits = maxUint256`.
18
28
  *
19
- * Prefer `client.morpho.midnight(chainId).repayWithdrawCollateral(...)` in app
20
- * flows so loan-token approval and Midnight authorization requirements are
21
- * resolved first. Use this low-level builder only when those requirements and
22
- * collateral-index checks are already handled by the caller.
29
+ * Prefer `client.morpho.midnight(chainId).repayWithdrawCollateral(...)` in app flows so the
30
+ * loan-token approval and Midnight authorization requirements are resolved first.
23
31
  *
24
- * @param params.chainId - Chain id used to resolve `MidnightBundles`.
32
+ * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
25
33
  * @param params.market - Midnight market whose position is updated.
26
- * @param params.repayAssets - Loan assets repaid; may be zero when only withdrawing collateral.
27
- * @param params.withdrawCollateralAssets - Collateral assets withdrawn; may be zero when only repaying.
28
- * @param params.onBehalf - Position owner.
29
- * @param params.collateralIndex - Optional collateral index for withdrawal; defaults to `0n`.
34
+ * @param params.repay - `{ type: "assets", assets }` (`0n` to only withdraw) or `{ type: "full", maxBuyerAssets }`.
35
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
36
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of the
37
+ * maximum wNative amount this call can pull, but not more. Any wrapped native not pulled stays in
38
+ * the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still required
39
+ * for the full pulled amount.
40
+ * @param params.collateralWithdrawals - Collateral withdrawals; `assets: maxUint256` withdraws the full balance.
41
+ * @param params.collateralReceiver - Recipient of the withdrawn collateral.
30
42
  * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry.
31
43
  * @param params.metadata - Optional analytics metadata appended to calldata.
32
- * @returns A deep-frozen `Transaction<MidnightRepayWithdrawCollateralAction>` targeting `MidnightBundles`.
33
- * @throws {NegativeInputError} when any amount, collateral index, or deadline is negative.
34
- * @throws {NonPositiveInputError} when both repay and withdrawal amounts are zero.
44
+ * @returns A deep-frozen `Transaction<MidnightRepayWithdrawCollateralAction>` targeting `MidnightBundlesV2`.
45
+ * @throws {NegativeInputError} when `repay.assets` or `nativeAmount` is negative.
46
+ * @throws {NonPositiveInputError} when nothing is repaid or withdrawn, a withdrawal amount is zero, `repay.maxBuyerAssets` is zero, or `deadline` is not positive.
47
+ * @throws {InputExceedsMaxError} when `repay.assets` or `repay.maxBuyerAssets` is at least `maxUint256`, a withdrawal amount or `deadline` exceeds uint256, or `nativeAmount` exceeds the maximum wNative pull, including zero for a withdraw-only call.
48
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
49
+ * @throws {NativeAmountOnNonWNativeAssetError} when `market.loanToken` is not wNative.
50
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
35
51
  * @throws {ChainIdMismatchError} when the market targets another chain.
36
52
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
37
- * @throws {UnknownCollateralIndexError} when a positive withdrawal targets an unconfigured collateral index.
53
+ * @throws {UnknownCollateralIndexError} when a withdrawal targets an unconfigured collateral index.
38
54
  * @example
39
55
  * ```ts
40
56
  * import { maxUint256 } from "viem";
41
57
  * import { midnightRepayWithdrawCollateral } from "@morpho-org/morpho-sdk";
42
58
  *
59
+ * // Close the position: repay all debt, then withdraw all collateral at index 0.
43
60
  * const tx = midnightRepayWithdrawCollateral({
44
61
  * chainId: 8453,
45
62
  * market: marketData.params,
46
- * repayAssets: 1_000_000n,
47
- * withdrawCollateralAssets: 0n,
48
- * onBehalf: user,
63
+ * repay: { type: "full", maxBuyerAssets: 1_010_000n },
64
+ * collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
65
+ * collateralReceiver: user,
49
66
  * deadline: maxUint256,
50
67
  * });
51
68
  * ```
@@ -1,101 +1,138 @@
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, zeroAddress } from "viem";
3
+ import { encodeFunctionData, maxUint256, zeroAddress, } from "viem";
4
4
  import { addTransactionMetadata } from "../../helpers/index.js";
5
+ import { validateDeadline, validateMidnightNativeAmount, validateUint256Field, } from "../../helpers/validate.js";
5
6
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
6
- import { NegativeInputError, NonPositiveInputError, } from "../../types/index.js";
7
- import { PermitKind } from "./types.js";
7
+ import { InputExceedsMaxError, NonPositiveInputError, } from "../../types/index.js";
8
8
  /**
9
- * Encodes a Midnight bundle that repays debt, withdraws collateral, or both.
9
+ * Encodes a reduce-only `MidnightBundlesV2` buy with no offers, so the sender's debt is repaid
10
+ * directly, then collateral is withdrawn to `collateralReceiver`. An `assets` repay uses the
11
+ * assets-target entrypoint with `minUnits = assets` (a direct repay counts one unit per asset); a
12
+ * `full` repay uses the units-target entrypoint with `targetUnits = maxUint256`.
10
13
  *
11
- * Prefer `client.morpho.midnight(chainId).repayWithdrawCollateral(...)` in app
12
- * flows so loan-token approval and Midnight authorization requirements are
13
- * resolved first. Use this low-level builder only when those requirements and
14
- * collateral-index checks are already handled by the caller.
14
+ * Prefer `client.morpho.midnight(chainId).repayWithdrawCollateral(...)` in app flows so the
15
+ * loan-token approval and Midnight authorization requirements are resolved first.
15
16
  *
16
- * @param params.chainId - Chain id used to resolve `MidnightBundles`.
17
+ * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
17
18
  * @param params.market - Midnight market whose position is updated.
18
- * @param params.repayAssets - Loan assets repaid; may be zero when only withdrawing collateral.
19
- * @param params.withdrawCollateralAssets - Collateral assets withdrawn; may be zero when only repaying.
20
- * @param params.onBehalf - Position owner.
21
- * @param params.collateralIndex - Optional collateral index for withdrawal; defaults to `0n`.
19
+ * @param params.repay - `{ type: "assets", assets }` (`0n` to only withdraw) or `{ type: "full", maxBuyerAssets }`.
20
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
21
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of the
22
+ * maximum wNative amount this call can pull, but not more. Any wrapped native not pulled stays in
23
+ * the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still required
24
+ * for the full pulled amount.
25
+ * @param params.collateralWithdrawals - Collateral withdrawals; `assets: maxUint256` withdraws the full balance.
26
+ * @param params.collateralReceiver - Recipient of the withdrawn collateral.
22
27
  * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry.
23
28
  * @param params.metadata - Optional analytics metadata appended to calldata.
24
- * @returns A deep-frozen `Transaction<MidnightRepayWithdrawCollateralAction>` targeting `MidnightBundles`.
25
- * @throws {NegativeInputError} when any amount, collateral index, or deadline is negative.
26
- * @throws {NonPositiveInputError} when both repay and withdrawal amounts are zero.
29
+ * @returns A deep-frozen `Transaction<MidnightRepayWithdrawCollateralAction>` targeting `MidnightBundlesV2`.
30
+ * @throws {NegativeInputError} when `repay.assets` or `nativeAmount` is negative.
31
+ * @throws {NonPositiveInputError} when nothing is repaid or withdrawn, a withdrawal amount is zero, `repay.maxBuyerAssets` is zero, or `deadline` is not positive.
32
+ * @throws {InputExceedsMaxError} when `repay.assets` or `repay.maxBuyerAssets` is at least `maxUint256`, a withdrawal amount or `deadline` exceeds uint256, or `nativeAmount` exceeds the maximum wNative pull, including zero for a withdraw-only call.
33
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
34
+ * @throws {NativeAmountOnNonWNativeAssetError} when `market.loanToken` is not wNative.
35
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
27
36
  * @throws {ChainIdMismatchError} when the market targets another chain.
28
37
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
29
- * @throws {UnknownCollateralIndexError} when a positive withdrawal targets an unconfigured collateral index.
38
+ * @throws {UnknownCollateralIndexError} when a withdrawal targets an unconfigured collateral index.
30
39
  * @example
31
40
  * ```ts
32
41
  * import { maxUint256 } from "viem";
33
42
  * import { midnightRepayWithdrawCollateral } from "@morpho-org/morpho-sdk";
34
43
  *
44
+ * // Close the position: repay all debt, then withdraw all collateral at index 0.
35
45
  * const tx = midnightRepayWithdrawCollateral({
36
46
  * chainId: 8453,
37
47
  * market: marketData.params,
38
- * repayAssets: 1_000_000n,
39
- * withdrawCollateralAssets: 0n,
40
- * onBehalf: user,
48
+ * repay: { type: "full", maxBuyerAssets: 1_010_000n },
49
+ * collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
50
+ * collateralReceiver: user,
41
51
  * deadline: maxUint256,
42
52
  * });
43
53
  * ```
44
54
  */
45
55
  export const midnightRepayWithdrawCollateral = (params) => {
46
- if (params.repayAssets < 0n) {
47
- throw new NegativeInputError("repayAssets", params.repayAssets);
48
- }
49
- if (params.withdrawCollateralAssets < 0n) {
50
- throw new NegativeInputError("withdrawCollateralAssets", params.withdrawCollateralAssets);
56
+ const { repay } = params;
57
+ if (repay.type === "assets" &&
58
+ repay.assets === 0n &&
59
+ params.collateralWithdrawals.length === 0) {
60
+ throw new NonPositiveInputError("repay or withdraw amount", 0n);
51
61
  }
52
- if (params.deadline < 0n) {
53
- throw new NegativeInputError("deadline", params.deadline);
62
+ if (repay.type === "full") {
63
+ if (repay.maxBuyerAssets <= 0n) {
64
+ throw new NonPositiveInputError("repay.maxBuyerAssets", repay.maxBuyerAssets);
65
+ }
66
+ if (repay.maxBuyerAssets >= maxUint256) {
67
+ throw new InputExceedsMaxError({
68
+ field: "repay.maxBuyerAssets",
69
+ value: repay.maxBuyerAssets,
70
+ max: maxUint256 - 1n,
71
+ });
72
+ }
54
73
  }
55
- const collateralWithdrawals = params.withdrawCollateralAssets > 0n
56
- ? [
57
- {
58
- collateralIndex: params.collateralIndex ?? 0n,
59
- assets: params.withdrawCollateralAssets,
60
- },
61
- ]
62
- : [];
63
- for (const [index, withdrawal] of collateralWithdrawals.entries()) {
64
- if (withdrawal.collateralIndex < 0n) {
65
- throw new NegativeInputError(`collateralWithdrawals[${index}].collateralIndex`, withdrawal.collateralIndex);
74
+ validateMidnightMarket({ market: params.market, chainId: params.chainId });
75
+ for (const [index, { collateralIndex, assets },] of params.collateralWithdrawals.entries()) {
76
+ if (assets <= 0n) {
77
+ throw new NonPositiveInputError(`collateralWithdrawals[${index}].assets`, assets);
66
78
  }
79
+ validateUint256Field(`collateralWithdrawals[${index}].assets`, assets);
80
+ // Throws UnknownCollateralIndexError when the index is not configured on the market.
81
+ MarketUtils.getCollateralByIndex(params.market, collateralIndex);
67
82
  }
68
- if (params.repayAssets === 0n &&
69
- collateralWithdrawals.every((withdrawal) => withdrawal.assets === 0n)) {
70
- throw new NonPositiveInputError("repay or withdraw amount", 0n);
83
+ if (repay.type === "assets") {
84
+ validateUint256Field("repay.assets", repay.assets);
85
+ // An assets repay has no "whole debt" sentinel; use `{ type: "full" }` for that.
86
+ if (repay.assets === maxUint256) {
87
+ throw new InputExceedsMaxError({
88
+ field: "repay.assets",
89
+ value: repay.assets,
90
+ max: maxUint256 - 1n,
91
+ });
92
+ }
71
93
  }
72
- // Reject markets from another chain deployment before encoding the bundle.
73
- validateMidnightMarket({ market: params.market, chainId: params.chainId });
74
- const marketId = MarketUtils.toId(params.market);
94
+ validateDeadline(params.deadline);
75
95
  const market = MarketUtils.toStruct(params.market);
76
- for (const withdrawal of collateralWithdrawals) {
77
- // Validate that every withdrawal targets a configured collateral.
78
- MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
79
- }
80
- const midnightBundles = getChainAddress(params.chainId, "midnightBundles");
96
+ const nativeFunding = validateMidnightNativeAmount({
97
+ chainId: params.chainId,
98
+ nativeAmount: params.nativeAmount,
99
+ pulls: [
100
+ {
101
+ token: market.loanToken,
102
+ assets: repay.type === "assets" ? repay.assets : repay.maxBuyerAssets,
103
+ },
104
+ ],
105
+ });
106
+ const args = [
107
+ true, // reduceOnly
108
+ true, // repayEnabled
109
+ [], // offerFills
110
+ params.collateralWithdrawals.map(({ collateralIndex, assets }) => ({
111
+ collateralIndex,
112
+ assets,
113
+ })), // collateralWithdrawals
114
+ params.collateralReceiver, // collateralReceiver
115
+ 0n, // referralFeePct
116
+ zeroAddress, // referralFeeRecipient
117
+ // MidnightBundlesV2 checks maxContinuousFee only per offer fill; there are none here.
118
+ 0n, // maxContinuousFee
119
+ params.deadline, // deadline
120
+ nativeFunding.wrappedNative, // wrappedNative
121
+ ];
81
122
  let tx = {
82
- to: midnightBundles,
83
- value: 0n,
84
- data: encodeFunctionData({
85
- abi: midnightBundlesAbi,
86
- functionName: "midnightBundlesV1RepayAndWithdrawCollateral",
87
- args: [
88
- market,
89
- params.repayAssets,
90
- params.onBehalf,
91
- { kind: PermitKind.None, data: "0x" },
92
- collateralWithdrawals,
93
- params.onBehalf,
94
- 0n,
95
- zeroAddress,
96
- params.deadline,
97
- ],
98
- }),
123
+ to: getChainAddress(params.chainId, "midnightBundlesV2"),
124
+ value: nativeFunding.value,
125
+ data: repay.type === "assets"
126
+ ? encodeFunctionData({
127
+ abi: midnightBundlesV2Abi,
128
+ functionName: "midnightBundlesV2BuyWithAssetsTargetAndWithdrawCollateral",
129
+ args: [market, repay.assets, repay.assets, ...args],
130
+ })
131
+ : encodeFunctionData({
132
+ abi: midnightBundlesV2Abi,
133
+ functionName: "midnightBundlesV2BuyWithUnitsTargetAndWithdrawCollateral",
134
+ args: [market, maxUint256, repay.maxBuyerAssets, ...args],
135
+ }),
99
136
  };
100
137
  if (params.metadata) {
101
138
  tx = addTransactionMetadata(tx, params.metadata);
@@ -105,11 +142,10 @@ export const midnightRepayWithdrawCollateral = (params) => {
105
142
  action: {
106
143
  type: "midnightRepayWithdrawCollateral",
107
144
  args: {
108
- market: marketId,
109
- repayAssets: params.repayAssets,
110
- collateralWithdrawals: collateralWithdrawals.length,
111
- onBehalf: params.onBehalf,
112
- collateralReceiver: params.onBehalf,
145
+ market: MarketUtils.toId(params.market),
146
+ repay: { ...repay },
147
+ collateralWithdrawals: params.collateralWithdrawals.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
148
+ collateralReceiver: params.collateralReceiver,
113
149
  deadline: params.deadline,
114
150
  },
115
151
  },
@@ -1,50 +1,75 @@
1
- import { type MidnightSupplyCollateralTakeBorrowAction, type Transaction } from "../../types/index.js";
1
+ import { type MidnightCollateralTransfer, type MidnightSupplyCollateralTakeBorrowAction, type Transaction } from "../../types/index.js";
2
2
  import type { MidnightTakeBorrowParams } from "./takeBorrow.js";
3
3
  /** Parameters for encoding a collateral supply followed by a Midnight borrow take. */
4
4
  export interface MidnightSupplyCollateralTakeBorrowParams extends MidnightTakeBorrowParams {
5
- readonly collateralAssets: bigint;
6
- readonly collateralIndex?: bigint;
5
+ /** Collateral pulled from `msg.sender` and supplied before taking offers; must not be empty. */
6
+ readonly collateralSupplies: readonly MidnightCollateralTransfer[];
7
+ /**
8
+ * Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
9
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
10
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
11
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount.
12
+ */
13
+ readonly nativeAmount?: bigint;
7
14
  }
8
15
  /**
9
- * Encodes a Midnight bundle that supplies collateral and borrows in one call.
16
+ * Encodes a `MidnightBundlesV2` sell that supplies collateral and borrows from lend-side offers
17
+ * for `msg.sender` in one call.
10
18
  *
11
- * Prefer `client.morpho.midnight(chainId).supplyCollateralTakeBorrow(...)` in
12
- * app flows so collateral approval and Midnight authorization requirements are
13
- * resolved before building the bundle. Use this low-level builder only after
14
- * market data and API takeable offers are already available.
19
+ * Like `midnightTakeBorrow`, the sender's existing credit is withdrawn before offers are taken.
20
+ * Prefer `client.morpho.midnight(chainId).supplyCollateralTakeBorrow(...)` in app flows so
21
+ * collateral approvals and the `MidnightBundlesV2` authorization are resolved first.
15
22
  *
16
- * @param params.chainId - Chain id used to resolve `MidnightBundles`.
23
+ * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
17
24
  * @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.
25
+ * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
26
+ * @param params.receiver - Recipient of the borrowed loan assets.
27
+ * @param params.collateralSupplies - Collateral index and assets per supply; must not be empty.
28
+ * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
29
+ * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of the
30
+ * maximum wNative amount this call can pull, but not more. Any wrapped native not pulled stays in
31
+ * the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still required
32
+ * for the full pulled amount.
22
33
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
23
- * @param params.collateralAssets - Collateral assets supplied before taking offers.
24
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
25
- * @returns A deep-frozen `Transaction<MidnightSupplyCollateralTakeBorrowAction>` targeting `MidnightBundles`.
26
- * @throws {NonPositiveInputError} when collateral assets, loan assets, or `maxUnits` are non-positive.
27
- * @throws {NegativeInputError} when `deadline` is negative.
34
+ * @param params.deadline - Bounded bundle execution deadline timestamp.
35
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
36
+ * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
37
+ * @param params.metadata - Optional analytics metadata appended to calldata.
38
+ * @returns A deep-frozen `Transaction<MidnightSupplyCollateralTakeBorrowAction>` targeting `MidnightBundlesV2`.
39
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
40
+ * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
41
+ * @throws {ChainIdMismatchError} when the market targets another chain.
42
+ * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
43
+ * @throws {EmptyMidnightCollateralSuppliesError} when no collateral supply is provided.
44
+ * @throws {UnknownCollateralIndexError} when a collateral index is not configured on the market.
28
45
  * @throws {EmptyMidnightTakeableOffersError} when no offers are provided.
29
46
  * @throws {MidnightOfferSideMismatchError} when any offer is not lend-side.
30
47
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
31
- * @throws {ChainIdMismatchError} when the market targets another chain.
32
- * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
33
- * @throws {UnknownCollateralIndexError} when `collateralIndex` is not configured on the market.
48
+ * @throws {NonPositiveInputError} when a supply amount, the target amount, `maxUnits`, `minSellerAssets` or `deadline` is not positive.
49
+ * @throws {NegativeInputError} when `referralFeePct` or `nativeAmount` is negative.
50
+ * @throws {InputExceedsMaxError} when a `collateralSupplies[].assets` amount, `target.assets`,
51
+ * `target.maxUnits`, `target.units`, `target.minSellerAssets` or `deadline` exceeds `uint256`, or
52
+ * `nativeAmount` exceeds the maximum wNative collateral amount this call can pull.
53
+ * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
54
+ * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
55
+ * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or
56
+ * `deadline` is `maxUint256`.
57
+ * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
58
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
59
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
34
60
  * @example
35
61
  * ```ts
36
- * import { maxUint256 } from "viem";
62
+ * import { Time } from "@morpho-org/morpho-ts";
37
63
  * import { midnightSupplyCollateralTakeBorrow } from "@morpho-org/morpho-sdk";
38
64
  *
39
65
  * const tx = midnightSupplyCollateralTakeBorrow({
40
66
  * chainId: 8453,
41
67
  * market: marketData.params,
42
- * collateralAssets: 2_000_000n,
43
- * loanAssets: 1_000_000n,
44
- * maxUnits: 1_100_000n,
45
- * taker: borrower,
68
+ * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
69
+ * receiver: borrower,
70
+ * collateralSupplies: [{ collateralIndex: 0n, assets: 2_000_000n }],
46
71
  * takeableOffers: quote.data.takeableOffers,
47
- * deadline: maxUint256,
72
+ * deadline: Time.timestamp() + 600n,
48
73
  * });
49
74
  * ```
50
75
  */