@morpho-org/morpho-sdk 9.1.0 → 9.3.0-next.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 (112) hide show
  1. package/README.md +5 -1
  2. package/lib/cjs/abis.d.ts +2 -2
  3. package/lib/cjs/abis.js +7 -1
  4. package/lib/cjs/actions/midnight/index.d.ts +1 -0
  5. package/lib/cjs/actions/midnight/index.js +1 -0
  6. package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +50 -0
  7. package/lib/cjs/actions/midnight/withdrawCollateral.js +105 -0
  8. package/lib/cjs/blue/abis.d.ts +1 -1
  9. package/lib/cjs/blue/abis.js +5 -1
  10. package/lib/cjs/blue/constants.d.ts +1 -1
  11. package/lib/cjs/blue/constants.js +2 -1
  12. package/lib/cjs/blue/entities.d.ts +4 -4
  13. package/lib/cjs/blue/entities.js +3 -1
  14. package/lib/cjs/blue/errors.d.ts +2 -2
  15. package/lib/cjs/blue/errors.js +5 -1
  16. package/lib/cjs/blue/fetch.d.ts +2 -2
  17. package/lib/cjs/blue/fetch.js +3 -1
  18. package/lib/cjs/blue/utils.d.ts +1 -1
  19. package/lib/cjs/blue/utils.js +2 -1
  20. package/lib/cjs/constants.d.ts +2 -2
  21. package/lib/cjs/constants.js +4 -1
  22. package/lib/cjs/entities/blue/blue.d.ts +71 -16
  23. package/lib/cjs/entities/blue/blue.js +32 -4
  24. package/lib/cjs/entities/index.d.ts +5 -5
  25. package/lib/cjs/entities/index.js +3 -1
  26. package/lib/cjs/entities/midnight/midnight.d.ts +58 -11
  27. package/lib/cjs/entities/midnight/midnight.js +103 -11
  28. package/lib/cjs/entities/midnight/publication.d.ts +2 -1
  29. package/lib/cjs/entities/midnight/publication.js +44 -64
  30. package/lib/cjs/entities/midnight/types.d.ts +8 -0
  31. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +8 -0
  32. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -0
  33. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +37 -9
  34. package/lib/cjs/entities/vaultV2/vaultV2.js +36 -1
  35. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +42 -7
  36. package/lib/cjs/entities/vaultV2BlueReallocationData.js +206 -35
  37. package/lib/cjs/errors.d.ts +4 -4
  38. package/lib/cjs/errors.js +10 -5
  39. package/lib/cjs/fetch.d.ts +2 -2
  40. package/lib/cjs/fetch.js +3 -1
  41. package/lib/cjs/helpers/constant.d.ts +7 -0
  42. package/lib/cjs/helpers/constant.js +8 -1
  43. package/lib/cjs/helpers/deadShares.d.ts +82 -0
  44. package/lib/cjs/helpers/deadShares.js +202 -0
  45. package/lib/cjs/helpers/index.d.ts +2 -1
  46. package/lib/cjs/helpers/index.js +7 -1
  47. package/lib/cjs/midnight/abis.d.ts +1 -1
  48. package/lib/cjs/midnight/abis.js +3 -1
  49. package/lib/cjs/midnight/errors.d.ts +2 -1
  50. package/lib/cjs/midnight/errors.js +5 -4
  51. package/lib/cjs/types/action.d.ts +10 -1
  52. package/lib/cjs/types/error.d.ts +54 -5
  53. package/lib/cjs/types/error.js +60 -6
  54. package/lib/cjs/types/sharedLiquidity.d.ts +10 -6
  55. package/lib/cjs/utils.d.ts +2 -2
  56. package/lib/cjs/utils.js +4 -2
  57. package/lib/esm/abis.d.ts +2 -2
  58. package/lib/esm/abis.js +2 -2
  59. package/lib/esm/actions/midnight/index.d.ts +1 -0
  60. package/lib/esm/actions/midnight/index.js +1 -0
  61. package/lib/esm/actions/midnight/withdrawCollateral.d.ts +50 -0
  62. package/lib/esm/actions/midnight/withdrawCollateral.js +101 -0
  63. package/lib/esm/blue/abis.d.ts +1 -1
  64. package/lib/esm/blue/abis.js +1 -1
  65. package/lib/esm/blue/constants.d.ts +1 -1
  66. package/lib/esm/blue/constants.js +1 -1
  67. package/lib/esm/blue/entities.d.ts +4 -4
  68. package/lib/esm/blue/entities.js +2 -2
  69. package/lib/esm/blue/errors.d.ts +2 -2
  70. package/lib/esm/blue/errors.js +2 -2
  71. package/lib/esm/blue/fetch.d.ts +2 -2
  72. package/lib/esm/blue/fetch.js +2 -2
  73. package/lib/esm/blue/utils.d.ts +1 -1
  74. package/lib/esm/blue/utils.js +1 -1
  75. package/lib/esm/constants.d.ts +2 -2
  76. package/lib/esm/constants.js +2 -2
  77. package/lib/esm/entities/blue/blue.d.ts +71 -16
  78. package/lib/esm/entities/blue/blue.js +34 -6
  79. package/lib/esm/entities/index.d.ts +5 -5
  80. package/lib/esm/entities/index.js +2 -2
  81. package/lib/esm/entities/midnight/midnight.d.ts +58 -11
  82. package/lib/esm/entities/midnight/midnight.js +105 -13
  83. package/lib/esm/entities/midnight/publication.d.ts +2 -1
  84. package/lib/esm/entities/midnight/publication.js +45 -65
  85. package/lib/esm/entities/midnight/types.d.ts +8 -0
  86. package/lib/esm/entities/vaultV1/vaultV1.d.ts +8 -0
  87. package/lib/esm/entities/vaultV1/vaultV1.js +5 -0
  88. package/lib/esm/entities/vaultV2/vaultV2.d.ts +37 -9
  89. package/lib/esm/entities/vaultV2/vaultV2.js +36 -1
  90. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +42 -7
  91. package/lib/esm/entities/vaultV2BlueReallocationData.js +206 -35
  92. package/lib/esm/errors.d.ts +4 -4
  93. package/lib/esm/errors.js +4 -4
  94. package/lib/esm/fetch.d.ts +2 -2
  95. package/lib/esm/fetch.js +2 -2
  96. package/lib/esm/helpers/constant.d.ts +7 -0
  97. package/lib/esm/helpers/constant.js +7 -0
  98. package/lib/esm/helpers/deadShares.d.ts +82 -0
  99. package/lib/esm/helpers/deadShares.js +197 -0
  100. package/lib/esm/helpers/index.d.ts +2 -1
  101. package/lib/esm/helpers/index.js +2 -1
  102. package/lib/esm/midnight/abis.d.ts +1 -1
  103. package/lib/esm/midnight/abis.js +1 -1
  104. package/lib/esm/midnight/errors.d.ts +2 -1
  105. package/lib/esm/midnight/errors.js +2 -1
  106. package/lib/esm/types/action.d.ts +10 -1
  107. package/lib/esm/types/error.d.ts +54 -5
  108. package/lib/esm/types/error.js +57 -5
  109. package/lib/esm/types/sharedLiquidity.d.ts +10 -6
  110. package/lib/esm/utils.d.ts +2 -2
  111. package/lib/esm/utils.js +2 -2
  112. package/package.json +9 -8
@@ -11,6 +11,7 @@ const index_js_2 = require("../../actions/requirements/index.js");
11
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
12
  const callback_js_1 = require("../../helpers/callback.js");
13
13
  const constant_js_1 = require("../../helpers/constant.js");
14
+ const deadShares_js_1 = require("../../helpers/deadShares.js");
14
15
  const encodeMidnightCalldata_js_1 = require("../../helpers/encodeMidnightCalldata.js");
15
16
  const index_js_3 = require("../../helpers/index.js");
16
17
  const validateMidnightAccount_js_1 = require("../../helpers/validateMidnightAccount.js");
@@ -265,7 +266,7 @@ class MorphoMidnight {
265
266
  * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
266
267
  * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
267
268
  * @throws {MidnightCalldataEncodingError} when an offer cannot be ABI-encoded, such as an out-of-range integer, or `accountAddress` is not a well-formed address.
268
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
269
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
269
270
  * @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
270
271
  * @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
271
272
  * @throws {MidnightOfferGroupConsumedError} when an offer group has no remaining capacity.
@@ -1073,6 +1074,97 @@ class MorphoMidnight {
1073
1074
  buildTx: () => tx,
1074
1075
  };
1075
1076
  }
1077
+ /**
1078
+ * Withdraws collateral directly from Midnight without bundle authorization or token pulls.
1079
+ *
1080
+ * Uses the supplied position snapshot to resolve maxUint256 and check collateral health.
1081
+ * No requirements or RPC reads are needed. The signing account must be accountAddress.
1082
+ *
1083
+ * @param params - Market, owner-bound position, collateral prices and withdrawal amount.
1084
+ * @param params.accountAddress - Collateral owner. This account must send the transaction.
1085
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
1086
+ * @param params.positionData - Owner-bound position snapshot returned by getPositionData.
1087
+ * @param params.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
1088
+ * ORACLE_PRICE_SCALE; required when the position has debt, otherwise an empty array is safe.
1089
+ * @param params.collateralIndex - Optional collateral index; defaults to 0n. Indexes follow the
1090
+ * market's collateral parameters, which Midnight sorts by token address, not the order they were
1091
+ * listed in when the market was built; check marketData.getCollateralByIndex(index).token.
1092
+ * @param params.assets - Collateral assets to withdraw. maxUint256 resolves the whole balance of
1093
+ * the selected collateral from positionData before building the transaction.
1094
+ * @param params.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
1095
+ * @returns Lazy handles for a direct Midnight withdrawal.
1096
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
1097
+ * @throws {MidnightCalldataEncodingError} when accountAddress is malformed or an input cannot be ABI-encoded.
1098
+ * @throws {MidnightZeroAccountError} when accountAddress is zero.
1099
+ * @throws {MidnightMarketAddressMismatchError} when marketData targets another Midnight deployment.
1100
+ * @throws {MissingMarketPriceError} when debt is positive and held collateral has no supplied price.
1101
+ * @throws {MarketIdMismatchError} when positionData belongs to another market.
1102
+ * @throws {AccrualPositionUserMismatchError} when positionData belongs to another account.
1103
+ * @throws {UnknownCollateralIndexError} when collateralIndex is not configured.
1104
+ * @throws {NonPositiveInputError} when the resolved amount is not positive.
1105
+ * @throws {InputExceedsMaxError} when assets exceeds uint128.
1106
+ * @throws {WithdrawExceedsCollateralError} when assets exceeds the collateral balance.
1107
+ * @throws {WithdrawMakesPositionUnhealthyError} when remaining collateral cannot safely cover debt.
1108
+ * @throws {MidnightZeroReceiverError} when receiver is zero.
1109
+ * @throws {MidnightContractReceiverError} when receiver cannot safely receive collateral.
1110
+ * @example
1111
+ * ```ts
1112
+ * const output = midnight.withdrawCollateral({
1113
+ * accountAddress: user,
1114
+ * marketData,
1115
+ * positionData,
1116
+ * collateralPrices,
1117
+ * assets: 1_000n,
1118
+ * });
1119
+ * const tx = output.buildTx();
1120
+ * ```
1121
+ */
1122
+ withdrawCollateral(params) {
1123
+ (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1124
+ // Reject invalid owners before preparing the direct call.
1125
+ (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1126
+ validateMarketData(params.marketData, this.chainId);
1127
+ validatePositionBinding(params);
1128
+ const collateralIndex = params.collateralIndex ?? 0n;
1129
+ // Reject unconfigured indexes before reading the position balance.
1130
+ midnight_sdk_1.MarketUtils.getCollateralByIndex(params.marketData.params, collateralIndex);
1131
+ const index = Number(collateralIndex);
1132
+ const available = params.positionData.collateral[index] ?? 0n;
1133
+ const assets = params.assets === viem_1.maxUint256 ? available : params.assets;
1134
+ const tx = (0, index_js_1.midnightWithdrawCollateral)({
1135
+ chainId: this.chainId,
1136
+ market: params.marketData.params,
1137
+ collateralIndex,
1138
+ assets,
1139
+ onBehalf: params.accountAddress,
1140
+ receiver: params.receiver ?? params.accountAddress,
1141
+ metadata: this.client.options.metadata,
1142
+ });
1143
+ if (assets > available) {
1144
+ throw new index_js_4.WithdrawExceedsCollateralError({
1145
+ withdrawAmount: assets,
1146
+ available,
1147
+ market: params.marketData.id,
1148
+ });
1149
+ }
1150
+ if (params.positionData.debt > 0n) {
1151
+ const collateral = Array.from({ length: params.marketData.params.collateralParams.length }, (_, i) => params.positionData.collateral[i] ?? 0n);
1152
+ collateral[index] = available - assets;
1153
+ const maxSafeDebt = (0, index_js_3.getMidnightMaxSafeDebt)({
1154
+ market: params.marketData,
1155
+ collateral,
1156
+ collateralPrices: params.collateralPrices,
1157
+ });
1158
+ if (params.positionData.debt > maxSafeDebt) {
1159
+ throw new index_js_4.WithdrawMakesPositionUnhealthyError({
1160
+ withdrawAmount: assets,
1161
+ borrowAssets: params.positionData.debt,
1162
+ maxSafeBorrow: maxSafeDebt,
1163
+ });
1164
+ }
1165
+ }
1166
+ return { getRequirements: async () => [], buildTx: () => tx };
1167
+ }
1076
1168
  /**
1077
1169
  * Prepares a direct collateral supply using a caller-provided market snapshot.
1078
1170
  *
@@ -1202,7 +1294,7 @@ class MorphoMidnight {
1202
1294
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
1203
1295
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1204
1296
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1205
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1297
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1206
1298
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1207
1299
  * @example
1208
1300
  * ```ts
@@ -1273,7 +1365,7 @@ class MorphoMidnight {
1273
1365
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
1274
1366
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1275
1367
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1276
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1368
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1277
1369
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1278
1370
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1279
1371
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
@@ -1437,8 +1529,9 @@ class MorphoMidnight {
1437
1529
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
1438
1530
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1439
1531
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1440
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1441
- * @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
1532
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1533
+ * @throws {MissingDeadSharesDataError} when the fetched `blueMarket` snapshot has no `deadSupplyShares`.
1534
+ * @throws {InsufficientDeadSharesError} when `blueMarket` holds fewer than `MIN_DEAD_SHARES` supply shares at `DEAD_ADDRESS`.
1442
1535
  * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price (checked at preparation time only).
1443
1536
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1444
1537
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
@@ -1494,9 +1587,8 @@ class MorphoMidnight {
1494
1587
  }),
1495
1588
  ]);
1496
1589
  const market = (0, morpho_ts_1._try)(() => fetched.accrueInterest(blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), fetched.lastUpdate)), blue_sdk_1.UnsupportedMarketIrmError) ?? fetched;
1497
- if (market.totalSupplyShares === 0n) {
1498
- throw new index_js_4.EmptyBlueParkingMarketError({ marketId: blueMarketId });
1499
- }
1590
+ // Throws when the parking market lacks a sufficient dead deposit; nothing to return.
1591
+ (0, deadShares_js_1.validateBlueMarketDeadShares)(fetched);
1500
1592
  if (market.toSupplyShares(params.assetsToPark, "Down") === 0n) {
1501
1593
  throw new index_js_4.ZeroBlueParkingSharesError({
1502
1594
  marketId: blueMarketId,
@@ -1642,7 +1734,7 @@ class MorphoMidnight {
1642
1734
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
1643
1735
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1644
1736
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1645
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1737
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1646
1738
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1647
1739
  * (not thrown when `validation` is `false`).
1648
1740
  * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
@@ -1730,7 +1822,7 @@ class MorphoMidnight {
1730
1822
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
1731
1823
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1732
1824
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1733
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1825
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1734
1826
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1735
1827
  * (not thrown when `validation` is `false`).
1736
1828
  * @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer uses another loan token.
@@ -1829,7 +1921,7 @@ class MorphoMidnight {
1829
1921
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
1830
1922
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1831
1923
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1832
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1924
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1833
1925
  * @throws {MarketIdMismatchError} when an offer targets another market than `collateral.market`, including a `collateral.market` on another chain or Midnight deployment.
1834
1926
  * @throws {EmptyMidnightCollateralSuppliesError} when a collateral market has no collateral supplies.
1835
1927
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
@@ -87,6 +87,7 @@ export declare function validateMidnightMakerOfferStates(params: {
87
87
  *
88
88
  * The reader uses a single block for contract reads and returns that block's
89
89
  * timestamp as `now`; oracle code checks use the same block number.
90
+ * Contract reads do not require a Multicall3 deployment or viem chain metadata.
90
91
  *
91
92
  * @internal
92
93
  * @param params.client - Viem client used for state reads.
@@ -96,7 +97,7 @@ export declare function validateMidnightMakerOfferStates(params: {
96
97
  * @returns Per-offer states plus the timestamp of the pinned block.
97
98
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
98
99
  * another chain than `params.chainId`.
99
- * @throws {viem.BaseError} when block, multicall, or oracle-code reads fail.
100
+ * @throws {viem.BaseError} when block, contract, or oracle-code reads fail.
100
101
  * @example
101
102
  * ```ts
102
103
  * const { states, now } = await fetchMidnightMakerOfferStates({
@@ -171,6 +171,7 @@ function validateMidnightMakerOfferStates(params) {
171
171
  *
172
172
  * The reader uses a single block for contract reads and returns that block's
173
173
  * timestamp as `now`; oracle code checks use the same block number.
174
+ * Contract reads do not require a Multicall3 deployment or viem chain metadata.
174
175
  *
175
176
  * @internal
176
177
  * @param params.client - Viem client used for state reads.
@@ -180,7 +181,7 @@ function validateMidnightMakerOfferStates(params) {
180
181
  * @returns Per-offer states plus the timestamp of the pinned block.
181
182
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
182
183
  * another chain than `params.chainId`.
183
- * @throws {viem.BaseError} when block, multicall, or oracle-code reads fail.
184
+ * @throws {viem.BaseError} when block, contract, or oracle-code reads fail.
184
185
  * @example
185
186
  * ```ts
186
187
  * const { states, now } = await fetchMidnightMakerOfferStates({
@@ -229,76 +230,55 @@ async function fetchMidnightMakerOfferStates(params) {
229
230
  ])).values(),
230
231
  ];
231
232
  const [marketStates, consumedValues, creditValues, debtValues, defaultFees, lltvEnabledByCollateral, liquidationCursorEnabledByCollateral,] = await Promise.all([
232
- (0, actions_1.multicall)(params.client, {
233
- contracts: markets.map(({ id }) => ({
234
- address: midnight,
235
- abi: midnight_sdk_1.midnightAbi,
236
- functionName: "marketState",
237
- args: [id],
238
- })),
239
- allowFailure: false,
233
+ Promise.all(markets.map(({ id }) => (0, actions_1.readContract)(params.client, {
234
+ address: midnight,
235
+ abi: midnight_sdk_1.midnightAbi,
236
+ functionName: "marketState",
237
+ args: [id],
240
238
  blockNumber,
241
- }),
242
- (0, actions_1.multicall)(params.client, {
243
- contracts: groups.map(({ maker, group }) => ({
244
- address: midnight,
245
- abi: midnight_sdk_1.midnightAbi,
246
- functionName: "consumed",
247
- args: [maker, group],
248
- })),
249
- allowFailure: false,
239
+ }))),
240
+ Promise.all(groups.map(({ maker, group }) => (0, actions_1.readContract)(params.client, {
241
+ address: midnight,
242
+ abi: midnight_sdk_1.midnightAbi,
243
+ functionName: "consumed",
244
+ args: [maker, group],
250
245
  blockNumber,
251
- }),
252
- (0, actions_1.multicall)(params.client, {
253
- contracts: owners.map(({ id, maker }) => ({
254
- address: midnight,
255
- abi: midnight_sdk_1.midnightAbi,
256
- functionName: "credit",
257
- args: [id, maker],
258
- })),
259
- allowFailure: false,
246
+ }))),
247
+ Promise.all(owners.map(({ id, maker }) => (0, actions_1.readContract)(params.client, {
248
+ address: midnight,
249
+ abi: midnight_sdk_1.midnightAbi,
250
+ functionName: "credit",
251
+ args: [id, maker],
260
252
  blockNumber,
261
- }),
262
- (0, actions_1.multicall)(params.client, {
263
- contracts: owners.map(({ id, maker }) => ({
264
- address: midnight,
265
- abi: midnight_sdk_1.midnightAbi,
266
- functionName: "debt",
267
- args: [id, maker],
268
- })),
269
- allowFailure: false,
253
+ }))),
254
+ Promise.all(owners.map(({ id, maker }) => (0, actions_1.readContract)(params.client, {
255
+ address: midnight,
256
+ abi: midnight_sdk_1.midnightAbi,
257
+ functionName: "debt",
258
+ args: [id, maker],
270
259
  blockNumber,
271
- }),
272
- (0, actions_1.multicall)(params.client, {
273
- contracts: defaultFeeTokens.map((loanToken) => ({
274
- address: midnight,
275
- abi: midnight_sdk_1.midnightAbi,
276
- functionName: "defaultContinuousFee",
277
- args: [loanToken],
278
- })),
279
- allowFailure: false,
260
+ }))),
261
+ Promise.all(defaultFeeTokens.map((loanToken) => (0, actions_1.readContract)(params.client, {
262
+ address: midnight,
263
+ abi: midnight_sdk_1.midnightAbi,
264
+ functionName: "defaultContinuousFee",
265
+ args: [loanToken],
280
266
  blockNumber,
281
- }),
282
- (0, actions_1.multicall)(params.client, {
283
- contracts: collaterals.map(({ collateral }) => ({
284
- address: midnight,
285
- abi: midnight_sdk_1.midnightAbi,
286
- functionName: "isLltvEnabled",
287
- args: [collateral.lltv],
288
- })),
289
- allowFailure: false,
267
+ }))),
268
+ Promise.all(collaterals.map(({ collateral }) => (0, actions_1.readContract)(params.client, {
269
+ address: midnight,
270
+ abi: midnight_sdk_1.midnightAbi,
271
+ functionName: "isLltvEnabled",
272
+ args: [collateral.lltv],
290
273
  blockNumber,
291
- }),
292
- (0, actions_1.multicall)(params.client, {
293
- contracts: collaterals.map(({ collateral }) => ({
294
- address: midnight,
295
- abi: midnight_sdk_1.midnightAbi,
296
- functionName: "isLiquidationCursorEnabled",
297
- args: [collateral.liquidationCursor],
298
- })),
299
- allowFailure: false,
274
+ }))),
275
+ Promise.all(collaterals.map(({ collateral }) => (0, actions_1.readContract)(params.client, {
276
+ address: midnight,
277
+ abi: midnight_sdk_1.midnightAbi,
278
+ functionName: "isLiquidationCursorEnabled",
279
+ args: [collateral.liquidationCursor],
300
280
  blockNumber,
301
- }),
281
+ }))),
302
282
  ]);
303
283
  const defaultFeeByLoanToken = new Map(defaultFeeTokens.map((loanToken, index) => [
304
284
  loanToken.toLowerCase(),
@@ -235,6 +235,14 @@ export interface SupplyCollateralParams extends MarketActionParams {
235
235
  readonly reservedCollateralAssets?: bigint;
236
236
  readonly collateralIndex?: bigint;
237
237
  }
238
+ /** Parameters for a direct Midnight collateral withdrawal. */
239
+ export interface WithdrawCollateralParams extends MarketActionParams, MidnightPositionHealthParams {
240
+ readonly collateralIndex?: bigint;
241
+ /** Collateral assets to withdraw; maxUint256 resolves the snapshot's whole balance. */
242
+ readonly assets: bigint;
243
+ /** Defaults to accountAddress. */
244
+ readonly receiver?: Address;
245
+ }
238
246
  /** Parameters for the Midnight redeem flow. */
239
247
  export interface RedeemParams {
240
248
  readonly accountAddress: Address;
@@ -104,6 +104,10 @@ export interface VaultV1Actions {
104
104
  * const tx = action.buildTx(); // For a client configured with supportSignature: false.
105
105
  * // tx satisfies Readonly<Transaction<VaultV1DepositAction>>
106
106
  * ```
107
+ * @throws {MissingDeadSharesDataError} when `vaultData` lacks the dead-share, cap or adapter data
108
+ * the dead-deposit check needs, such as a hand-built or API-sourced snapshot.
109
+ * @throws {InsufficientDeadSharesError} when the vault, or a market or vault it can allocate to,
110
+ * holds less than the required dead deposit.
107
111
  */
108
112
  deposit: (params: {
109
113
  readonly userAddress: Address;
@@ -457,6 +461,10 @@ export interface VaultV1Actions {
457
461
  * const tx = migration.buildTx(signatures);
458
462
  * // tx satisfies Readonly<Transaction<VaultV1MigrateToV2Action>>
459
463
  * ```
464
+ * @throws {MissingDeadSharesDataError} when `targetVault` lacks the dead-share, cap or adapter data
465
+ * the dead-deposit check needs. The source Vault V1 is not checked.
466
+ * @throws {InsufficientDeadSharesError} when `targetVault`, or a market or vault it can allocate
467
+ * to, holds less than the required dead deposit.
460
468
  */
461
469
  migrateToV2: (params: {
462
470
  readonly userAddress: Address;
@@ -9,6 +9,7 @@ const actions_1 = require("viem/actions");
9
9
  const common_js_1 = require("../../actions/bundles/common.js");
10
10
  const index_js_1 = require("../../actions/index.js");
11
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
+ const deadShares_js_1 = require("../../helpers/deadShares.js");
12
13
  const index_js_2 = require("../../helpers/index.js");
13
14
  const validate_js_1 = require("../../helpers/validate.js");
14
15
  const index_js_3 = require("../../types/index.js");
@@ -78,6 +79,8 @@ class MorphoVaultV1 {
78
79
  // The native path must target the chain's registered wrapped-native asset.
79
80
  (0, validate_js_1.validateNativeVaultAsset)(this.chainId, vaultAsset);
80
81
  }
82
+ // Throws when the vault, or a market it can allocate to, lacks a sufficient dead deposit.
83
+ (0, deadShares_js_1.validateVaultV1DeadShares)(vaultData);
81
84
  const referralFeeAssets = (0, common_js_1.getBundlesReferralFeeAssets)(funding.assets, common.referralFeePct);
82
85
  const maxSharePrice = (0, index_js_2.computeVaultMaxSharePrice)({
83
86
  vaultData,
@@ -472,6 +475,8 @@ class MorphoVaultV1 {
472
475
  referralFeePct: params.referralFeePct,
473
476
  referralFeeRecipient: params.referralFeeRecipient,
474
477
  });
478
+ // Only the destination receives a deposit; the source vault is an exit.
479
+ (0, deadShares_js_1.validateVaultV2DeadShares)(params.targetVault);
475
480
  // V1 redeem accrues market interest and performance fees before converting shares.
476
481
  const grossAssets = assets ??
477
482
  params.sourceVault
@@ -69,8 +69,9 @@ export interface VaultV2Actions {
69
69
  * owner is consumed and none was passed explicitly.
70
70
  * @throws {Permit2SignatureTransferNonceAlreadyUsedError} from `getRequirements()` when the
71
71
  * explicit Permit2 nonce is consumed.
72
- * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, or from
73
- * `getRequirements()` when the Permit2 nonce exceeds uint256.
72
+ * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, when the vault's
73
+ * liquidity adapter is a Midnight adapter (it cannot receive vault allocations, so no deposit
74
+ * fits and `max` is `0n`), or from `getRequirements()` when the Permit2 nonce exceeds uint256.
74
75
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
75
76
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
76
77
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -110,6 +111,10 @@ export interface VaultV2Actions {
110
111
  * const tx = action.buildTx(); // For a client configured with supportSignature: false.
111
112
  * // tx satisfies Readonly<Transaction<VaultV2DepositAction>>
112
113
  * ```
114
+ * @throws {MissingDeadSharesDataError} when `vaultData` lacks the dead-share, cap or adapter data
115
+ * the dead-deposit check needs, such as a hand-built or API-sourced snapshot.
116
+ * @throws {InsufficientDeadSharesError} when the vault, or a market or vault it can allocate to,
117
+ * holds less than the required dead deposit.
113
118
  */
114
119
  deposit: (params: {
115
120
  readonly userAddress: Address;
@@ -152,7 +157,9 @@ export interface VaultV2Actions {
152
157
  * @throws {NonPositiveInputError} when `amount` or the computed required share amount is not positive.
153
158
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
154
159
  * at any `getRequirements()` call.
155
- * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation.
160
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation,
161
+ * or when the vault's liquidity adapter is a Midnight adapter and `amount` exceeds the vault's
162
+ * idle assets.
156
163
  * @throws {NegativeInputError} when `referralFeePct` or `slippageTolerance` is negative.
157
164
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
158
165
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no nonzero recipient.
@@ -218,7 +225,24 @@ export interface VaultV2Actions {
218
225
  * @throws {NonPositiveInputError} when `shares` is not positive.
219
226
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
220
227
  * requirement resolution.
221
- * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
228
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256, or from
229
+ * `getRequirements()` when the vault's liquidity adapter is a Midnight adapter and `shares`
230
+ * are worth more than the vault's idle assets.
231
+ * @throws {UnknownBlueFactory} from `getRequirements()` when the configured chain has no VaultV2 factory.
232
+ * @throws {UnknownBlueOfFactory} from `getRequirements()` when the vault is not a VaultV2 from the
233
+ * configured factory.
234
+ * @throws {UnsupportedBlueVaultV2AdapterError} from `getRequirements()` when the vault or one of its
235
+ * adapters uses an unsupported adapter class.
236
+ * @throws {UnsupportedBlueMarketIrmError} from `getRequirements()` when the vault's liquidity adapter
237
+ * is a Midnight adapter and accrual projects an underlying market with positive debt that uses an
238
+ * unsupported IRM.
239
+ * @throws {UnknownBlueMarketAllocationError} from `getRequirements()` when the vault's liquidity
240
+ * adapter is a Midnight adapter and accrual meets a nested Vault V1 withdraw queue market without
241
+ * allocation data.
242
+ * @throws {InvalidMidnightPositionLossFactorError} from `getRequirements()` when the vault's liquidity
243
+ * adapter is a Midnight adapter and accrual meets a market loss factor below a position's.
244
+ * @throws {InvalidMidnightPositionAccrualStateError} from `getRequirements()` when the vault's
245
+ * liquidity adapter is a Midnight adapter and accrual meets invalid Midnight position inputs.
222
246
  * @throws {NegativeInputError} when `referralFeePct` is negative.
223
247
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
224
248
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
@@ -226,7 +250,7 @@ export interface VaultV2Actions {
226
250
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
227
251
  * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
228
252
  * contract has no code at its registered address.
229
- * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, `eth_chainId`, or
253
+ * @throws {viem.BaseError} from `getRequirements()` when a vault-state, allowance, nonce, `eth_chainId`, or
230
254
  * `eth_getCode` read fails.
231
255
  * @throws {UnknownTokenError} from `getRequirements()` when the share token fetched by
232
256
  * `getData()` has unusable decimals.
@@ -304,9 +328,11 @@ export interface VaultV2Actions {
304
328
  * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256`.
305
329
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
306
330
  * requirement resolution.
307
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter.
331
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter, including
332
+ * a vault that mixes Blue and Midnight adapters.
308
333
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
309
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
334
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
335
+ * including a Midnight adapter.
310
336
  * @throws {InKindRedeemCoverageError} when the deduplicated list cannot cover the exit.
311
337
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
312
338
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
@@ -431,9 +457,11 @@ export interface VaultV2Actions {
431
457
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
432
458
  * requirement resolution.
433
459
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
434
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter.
460
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter,
461
+ * including a vault that mixes Blue and Midnight adapters.
435
462
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
436
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
463
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
464
+ * including a Midnight adapter.
437
465
  * @throws {VaultV2UnsupportedLiquidityAdapterError} when the vault routes liquidity through
438
466
  * another adapter.
439
467
  * @throws {VaultV2UndecodableLiquidityDataError} when the vault's `liquidityData` does not decode
@@ -9,6 +9,7 @@ const actions_1 = require("viem/actions");
9
9
  const common_js_1 = require("../../actions/bundles/common.js");
10
10
  const index_js_1 = require("../../actions/index.js");
11
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
+ const deadShares_js_1 = require("../../helpers/deadShares.js");
12
13
  const index_js_2 = require("../../helpers/index.js");
13
14
  const validate_js_1 = require("../../helpers/validate.js");
14
15
  const index_js_3 = require("../../types/index.js");
@@ -18,6 +19,11 @@ const index_js_4 = require("../requirements/index.js");
18
19
  // Maximum accepted deadline horizon; the on-chain management fee is capped at 5%/yr so the
19
20
  // accrual model stays well-defined inside it.
20
21
  const VAULT_V2_FEE_PROJECTION_HORIZON = morpho_ts_1.Time.s.from.y(1n);
22
+ /**
23
+ * Midnight adapters revert vault-initiated `allocate` and `deallocate` (`SelfAllocationOnly`), so a
24
+ * vault routing liquidity through one accepts no deposit and serves exits from idle assets only.
25
+ */
26
+ const isMidnightLiquidityAdapter = (vaultData) => vaultData.accrualLiquidityAdapter?.type === "VaultV2MidnightAdapter";
21
27
  /** Binds a viem client to a Vault V2 vault's action builders. */
22
28
  class MorphoVaultV2 {
23
29
  client;
@@ -81,6 +87,15 @@ class MorphoVaultV2 {
81
87
  // The native path must target the chain's registered wrapped-native asset.
82
88
  (0, validate_js_1.validateNativeVaultAsset)(this.chainId, vaultAsset);
83
89
  }
90
+ if (isMidnightLiquidityAdapter(vaultData)) {
91
+ throw new index_js_3.InputExceedsMaxError({
92
+ field: funding.value > 0n ? "nativeAmount" : "amount",
93
+ value: funding.assets,
94
+ max: 0n,
95
+ });
96
+ }
97
+ // Throws when the vault, or a market it can allocate to, lacks a sufficient dead deposit.
98
+ (0, deadShares_js_1.validateVaultV2DeadShares)(vaultData);
84
99
  const referralFeeAssets = (0, common_js_1.getBundlesReferralFeeAssets)(funding.assets, common.referralFeePct);
85
100
  const maxSharePrice = (0, index_js_2.computeVaultMaxSharePrice)({
86
101
  vaultData,
@@ -164,6 +179,14 @@ class MorphoVaultV2 {
164
179
  throw new index_js_3.NonPositiveInputError("amount", amount);
165
180
  // Reject values outside the ABI range before resolving any requirements.
166
181
  (0, validate_js_1.validateUint256Field)("amount", amount);
182
+ if (isMidnightLiquidityAdapter(vaultData) &&
183
+ amount > vaultData.assetBalance) {
184
+ throw new index_js_3.InputExceedsMaxError({
185
+ field: "amount",
186
+ value: amount,
187
+ max: vaultData.assetBalance,
188
+ });
189
+ }
167
190
  const createdAt = morpho_ts_1.Time.timestamp();
168
191
  const deadline = params.deadline ?? createdAt + morpho_ts_1.Time.s.from.h(2n);
169
192
  if (deadline <= createdAt)
@@ -244,8 +267,20 @@ class MorphoVaultV2 {
244
267
  if (deadline <= now)
245
268
  throw new index_js_3.ExpiredDeadlineError(deadline, now);
246
269
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
270
+ const vaultData = await this.getData();
271
+ if (isMidnightLiquidityAdapter(vaultData)) {
272
+ // Onchain redeem accrues interest before converting shares to assets.
273
+ const { vault: accrued } = vaultData.accrueInterest(now);
274
+ if (accrued.toAssets(shares) > accrued.assetBalance) {
275
+ throw new index_js_3.InputExceedsMaxError({
276
+ field: "shares",
277
+ value: shares,
278
+ max: accrued.toShares(accrued.assetBalance),
279
+ });
280
+ }
281
+ }
247
282
  return (0, getVaultBundlesSharesRequirements_js_1.getVaultBundlesSharesRequirements)(this.client.viemClient, {
248
- vaultData: await this.getData(),
283
+ vaultData,
249
284
  version: "vaultV2",
250
285
  owner: userAddress,
251
286
  chainId: this.chainId,