@morpho-org/morpho-sdk 9.6.0-next.0 → 9.7.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 (211) hide show
  1. package/MIGRATION-v6-to-v7.md +1 -1
  2. package/README.md +123 -3
  3. package/lib/cjs/abis.d.ts +1 -1
  4. package/lib/cjs/abis.js +1 -5
  5. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -2
  6. package/lib/cjs/actions/bundles/common.js +39 -32
  7. package/lib/cjs/actions/midnight/cancelAndMake.js +20 -98
  8. package/lib/cjs/actions/midnight/index.d.ts +2 -0
  9. package/lib/cjs/actions/midnight/index.js +2 -0
  10. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +5 -6
  11. package/lib/cjs/actions/midnight/supplyCollateralBatch.d.ts +39 -0
  12. package/lib/cjs/actions/midnight/supplyCollateralBatch.js +91 -0
  13. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +31 -32
  14. package/lib/cjs/actions/midnight/takeBorrow.js +24 -23
  15. package/lib/cjs/actions/midnight/takeLend.js +24 -23
  16. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +20 -19
  17. package/lib/cjs/actions/midnight/takeWithdraw.js +24 -23
  18. package/lib/cjs/actions/midnight/withdrawCollateralBatch.d.ts +44 -0
  19. package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +104 -0
  20. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -0
  21. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -0
  22. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +1 -0
  23. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +1 -0
  24. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +1 -0
  25. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  26. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -0
  27. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +1 -0
  28. package/lib/cjs/actions/vaultV1/migrateToV2.js +7 -7
  29. package/lib/cjs/blue/abis.d.ts +1 -1
  30. package/lib/cjs/blue/abis.js +1 -5
  31. package/lib/cjs/blue/entities.d.ts +4 -4
  32. package/lib/cjs/blue/entities.js +1 -3
  33. package/lib/cjs/blue/errors.d.ts +2 -2
  34. package/lib/cjs/blue/errors.js +1 -5
  35. package/lib/cjs/blue/fetch.d.ts +2 -2
  36. package/lib/cjs/blue/fetch.js +1 -3
  37. package/lib/cjs/blue/utils.d.ts +1 -1
  38. package/lib/cjs/blue/utils.js +1 -2
  39. package/lib/cjs/entities/index.d.ts +5 -5
  40. package/lib/cjs/entities/index.js +1 -3
  41. package/lib/cjs/entities/midnight/midnight.d.ts +77 -3
  42. package/lib/cjs/entities/midnight/midnight.js +174 -0
  43. package/lib/cjs/entities/midnight/types.d.ts +16 -0
  44. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +12 -46
  45. package/lib/cjs/entities/requirements/getErc2612Permit.d.ts +7 -0
  46. package/lib/cjs/entities/requirements/getErc2612Permit.js +60 -0
  47. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -2
  48. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +3 -3
  49. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +10 -35
  50. package/lib/cjs/entities/vaultV2/vaultV2.js +1 -33
  51. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +3 -5
  52. package/lib/cjs/entities/vaultV2BlueReallocationData.js +3 -9
  53. package/lib/cjs/errors.d.ts +4 -4
  54. package/lib/cjs/errors.js +6 -7
  55. package/lib/cjs/fetch.d.ts +2 -2
  56. package/lib/cjs/fetch.js +1 -3
  57. package/lib/cjs/helpers/deadShares.js +0 -2
  58. package/lib/cjs/helpers/signAndVerifyTypedData.d.ts +1 -0
  59. package/lib/cjs/helpers/signAndVerifyTypedData.js +12 -5
  60. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.d.ts +68 -0
  61. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.js +129 -0
  62. package/lib/cjs/helpers/validateMidnightCollateralBatch.d.ts +15 -0
  63. package/lib/cjs/helpers/validateMidnightCollateralBatch.js +28 -0
  64. package/lib/cjs/helpers/validateMidnightCollateralSupplies.d.ts +17 -0
  65. package/lib/cjs/helpers/validateMidnightCollateralSupplies.js +28 -0
  66. package/lib/cjs/helpers/validatePositiveInput.d.ts +10 -0
  67. package/lib/cjs/helpers/validatePositiveInput.js +18 -0
  68. package/lib/cjs/index.d.ts +2 -0
  69. package/lib/cjs/index.js +18 -1
  70. package/lib/cjs/midnight/errors.d.ts +1 -2
  71. package/lib/cjs/midnight/errors.js +5 -5
  72. package/lib/cjs/transactionPlan/approval.d.ts +2 -0
  73. package/lib/cjs/transactionPlan/approval.js +16 -0
  74. package/lib/cjs/transactionPlan/error.d.ts +145 -0
  75. package/lib/cjs/transactionPlan/error.js +186 -0
  76. package/lib/cjs/transactionPlan/getTokenPermit.d.ts +11 -0
  77. package/lib/cjs/transactionPlan/getTokenPermit.js +18 -0
  78. package/lib/cjs/transactionPlan/index.d.ts +9 -0
  79. package/lib/cjs/transactionPlan/index.js +24 -0
  80. package/lib/cjs/transactionPlan/intent.d.ts +51 -0
  81. package/lib/cjs/transactionPlan/intent.js +54 -0
  82. package/lib/cjs/transactionPlan/permit.d.ts +13 -0
  83. package/lib/cjs/transactionPlan/permit.js +145 -0
  84. package/lib/cjs/transactionPlan/plan.d.ts +99 -0
  85. package/lib/cjs/transactionPlan/plan.js +232 -0
  86. package/lib/cjs/transactionPlan/requirements.d.ts +44 -0
  87. package/lib/cjs/transactionPlan/requirements.js +79 -0
  88. package/lib/cjs/transactionPlan/serde.d.ts +33 -0
  89. package/lib/cjs/transactionPlan/serde.js +205 -0
  90. package/lib/cjs/transactionPlan/types.d.ts +91 -0
  91. package/lib/cjs/transactionPlan/types.js +2 -0
  92. package/lib/cjs/transactionPlan/validateActions.d.ts +8 -0
  93. package/lib/cjs/transactionPlan/validateActions.js +19 -0
  94. package/lib/cjs/transactionPlan/validation.d.ts +17 -0
  95. package/lib/cjs/transactionPlan/validation.js +70 -0
  96. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +81 -0
  97. package/lib/cjs/transactionPlan/vaultv2/deposit.js +211 -0
  98. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +77 -0
  99. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +190 -0
  100. package/lib/cjs/transactionPlan/version.d.ts +2 -0
  101. package/lib/cjs/transactionPlan/version.js +9 -0
  102. package/lib/cjs/types/action.d.ts +18 -3
  103. package/lib/cjs/types/error.d.ts +23 -2
  104. package/lib/cjs/types/error.js +45 -5
  105. package/lib/cjs/utils.d.ts +2 -2
  106. package/lib/cjs/utils.js +2 -4
  107. package/lib/esm/abis.d.ts +1 -1
  108. package/lib/esm/abis.js +1 -1
  109. package/lib/esm/actions/blue/repayWithdrawCollateral.js +2 -2
  110. package/lib/esm/actions/bundles/common.js +39 -32
  111. package/lib/esm/actions/midnight/cancelAndMake.js +25 -103
  112. package/lib/esm/actions/midnight/index.d.ts +2 -0
  113. package/lib/esm/actions/midnight/index.js +2 -0
  114. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +5 -6
  115. package/lib/esm/actions/midnight/supplyCollateralBatch.d.ts +39 -0
  116. package/lib/esm/actions/midnight/supplyCollateralBatch.js +87 -0
  117. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +33 -34
  118. package/lib/esm/actions/midnight/takeBorrow.js +25 -24
  119. package/lib/esm/actions/midnight/takeLend.js +25 -24
  120. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +20 -19
  121. package/lib/esm/actions/midnight/takeWithdraw.js +25 -24
  122. package/lib/esm/actions/midnight/withdrawCollateralBatch.d.ts +44 -0
  123. package/lib/esm/actions/midnight/withdrawCollateralBatch.js +100 -0
  124. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -0
  125. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -0
  126. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +1 -0
  127. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +1 -0
  128. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +1 -0
  129. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  130. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -0
  131. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +1 -0
  132. package/lib/esm/actions/vaultV1/migrateToV2.js +8 -8
  133. package/lib/esm/blue/abis.d.ts +1 -1
  134. package/lib/esm/blue/abis.js +1 -1
  135. package/lib/esm/blue/entities.d.ts +4 -4
  136. package/lib/esm/blue/entities.js +2 -2
  137. package/lib/esm/blue/errors.d.ts +2 -2
  138. package/lib/esm/blue/errors.js +2 -2
  139. package/lib/esm/blue/fetch.d.ts +2 -2
  140. package/lib/esm/blue/fetch.js +2 -2
  141. package/lib/esm/blue/utils.d.ts +1 -1
  142. package/lib/esm/blue/utils.js +1 -1
  143. package/lib/esm/entities/index.d.ts +5 -5
  144. package/lib/esm/entities/index.js +2 -2
  145. package/lib/esm/entities/midnight/midnight.d.ts +77 -3
  146. package/lib/esm/entities/midnight/midnight.js +176 -2
  147. package/lib/esm/entities/midnight/types.d.ts +16 -0
  148. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +14 -48
  149. package/lib/esm/entities/requirements/getErc2612Permit.d.ts +7 -0
  150. package/lib/esm/entities/requirements/getErc2612Permit.js +57 -0
  151. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -2
  152. package/lib/esm/entities/vaultV1/vaultV1.d.ts +3 -3
  153. package/lib/esm/entities/vaultV2/vaultV2.d.ts +10 -35
  154. package/lib/esm/entities/vaultV2/vaultV2.js +1 -33
  155. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +3 -5
  156. package/lib/esm/entities/vaultV2BlueReallocationData.js +3 -9
  157. package/lib/esm/errors.d.ts +4 -4
  158. package/lib/esm/errors.js +4 -4
  159. package/lib/esm/fetch.d.ts +2 -2
  160. package/lib/esm/fetch.js +2 -2
  161. package/lib/esm/helpers/deadShares.js +1 -3
  162. package/lib/esm/helpers/signAndVerifyTypedData.d.ts +1 -0
  163. package/lib/esm/helpers/signAndVerifyTypedData.js +13 -6
  164. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.d.ts +68 -0
  165. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.js +124 -0
  166. package/lib/esm/helpers/validateMidnightCollateralBatch.d.ts +15 -0
  167. package/lib/esm/helpers/validateMidnightCollateralBatch.js +25 -0
  168. package/lib/esm/helpers/validateMidnightCollateralSupplies.d.ts +17 -0
  169. package/lib/esm/helpers/validateMidnightCollateralSupplies.js +24 -0
  170. package/lib/esm/helpers/validatePositiveInput.d.ts +10 -0
  171. package/lib/esm/helpers/validatePositiveInput.js +14 -0
  172. package/lib/esm/index.d.ts +2 -0
  173. package/lib/esm/index.js +1 -0
  174. package/lib/esm/midnight/errors.d.ts +1 -2
  175. package/lib/esm/midnight/errors.js +1 -2
  176. package/lib/esm/transactionPlan/approval.d.ts +2 -0
  177. package/lib/esm/transactionPlan/approval.js +13 -0
  178. package/lib/esm/transactionPlan/error.d.ts +145 -0
  179. package/lib/esm/transactionPlan/error.js +175 -0
  180. package/lib/esm/transactionPlan/getTokenPermit.d.ts +11 -0
  181. package/lib/esm/transactionPlan/getTokenPermit.js +15 -0
  182. package/lib/esm/transactionPlan/index.d.ts +9 -0
  183. package/lib/esm/transactionPlan/index.js +5 -0
  184. package/lib/esm/transactionPlan/intent.d.ts +51 -0
  185. package/lib/esm/transactionPlan/intent.js +51 -0
  186. package/lib/esm/transactionPlan/permit.d.ts +13 -0
  187. package/lib/esm/transactionPlan/permit.js +140 -0
  188. package/lib/esm/transactionPlan/plan.d.ts +99 -0
  189. package/lib/esm/transactionPlan/plan.js +226 -0
  190. package/lib/esm/transactionPlan/requirements.d.ts +44 -0
  191. package/lib/esm/transactionPlan/requirements.js +74 -0
  192. package/lib/esm/transactionPlan/serde.d.ts +33 -0
  193. package/lib/esm/transactionPlan/serde.js +201 -0
  194. package/lib/esm/transactionPlan/types.d.ts +91 -0
  195. package/lib/esm/transactionPlan/types.js +1 -0
  196. package/lib/esm/transactionPlan/validateActions.d.ts +8 -0
  197. package/lib/esm/transactionPlan/validateActions.js +16 -0
  198. package/lib/esm/transactionPlan/validation.d.ts +17 -0
  199. package/lib/esm/transactionPlan/validation.js +64 -0
  200. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +81 -0
  201. package/lib/esm/transactionPlan/vaultv2/deposit.js +206 -0
  202. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +77 -0
  203. package/lib/esm/transactionPlan/vaultv2/withdraw.js +185 -0
  204. package/lib/esm/transactionPlan/version.d.ts +2 -0
  205. package/lib/esm/transactionPlan/version.js +6 -0
  206. package/lib/esm/types/action.d.ts +18 -3
  207. package/lib/esm/types/error.d.ts +23 -2
  208. package/lib/esm/types/error.js +40 -3
  209. package/lib/esm/utils.d.ts +2 -2
  210. package/lib/esm/utils.js +2 -2
  211. package/package.json +8 -7
@@ -294,4 +294,4 @@ Removed: `cancelOffer`, `midnightCancelOffer`, `MidnightCancelOfferParams`, `Mid
294
294
 
295
295
  ## Deployment
296
296
 
297
- MidnightBundlesV2 is pinned on Ethereum, Base, Arc, and Robinhood.
297
+ MidnightBundlesV2 is pinned on Ethereum, Base, Arbitrum, Arc, Robinhood, and Tempo.
package/README.md CHANGED
@@ -55,9 +55,10 @@ BlueBundlesV1, and the remaining rows identify their destination.
55
55
  | | `inKindRedeem` | VaultExitBundlesV1 |
56
56
  | **Blue** | `supply`, `withdraw`, `supplyCollateral`, `borrow`, `supplyCollateralBorrow`, `repay`, `withdrawCollateral`, `repayWithdrawCollateral`, `refinance` | BlueBundlesV1 |
57
57
  | **Blue** | `withdrawBuyCallback` | Morpho Blue (direct `withdraw` for a BlueBuyCallback's owner) |
58
- | **Midnight** | `takeLend`, `takeBorrow`, `supplyCollateralTakeBorrow`, `takeRepayWithdrawCollateral`, `repayWithdrawCollateral`, `takeWithdraw` | MidnightBundlesV2 (Ethereum, Base, Arc, Robinhood, Tempo) |
58
+ | **Midnight** | `takeLend`, `takeBorrow`, `supplyCollateralTakeBorrow`, `takeRepayWithdrawCollateral`, `repayWithdrawCollateral`, `takeWithdraw` | MidnightBundlesV2 (Ethereum, Base, Arbitrum, Arc, Robinhood, Tempo) |
59
59
  | | `supplyCollateral`, `withdrawCollateral`, `redeem` | Direct call |
60
- | | `makeLend`, `makeBorrow`, `makeWithdraw`, `makeRepay`, `supplyCollateralMakeBorrow`, `supplyBlueMakeLend`, `cancelOffers` | MidnightBundlesV2 (Ethereum, Base, Arc, Robinhood, Tempo) |
60
+ | | `supplyCollateralBatch`, `withdrawCollateralBatch` | Midnight multicall |
61
+ | | `makeLend`, `makeBorrow`, `makeWithdraw`, `makeRepay`, `supplyCollateralMakeBorrow`, `supplyBlueMakeLend`, `cancelOffers` | MidnightBundlesV2 (Ethereum, Base, Arbitrum, Arc, Robinhood, Tempo) |
61
62
 
62
63
  `makeBorrow` publishes without collateral; `supplyCollateralMakeBorrow` requires collateral and
63
64
  supplies it in the same transaction.
@@ -267,11 +268,72 @@ instant liquidation. Blue writes do not accept `slippageTolerance`, `minSharePri
267
268
  > High-level Blue writes and shared-liquidity planning use Vault V2 only. Vault V1 allocator and
268
269
  > low-level composition surfaces were removed in v6; direct Vault V1 flows remain.
269
270
 
271
+ ### TransactionPlan: sign and verify permits
272
+
273
+ > **Beta:** TransactionPlan is experimental; breaking changes may ship in minor releases.
274
+ > Existing entity flows remain the recommended stable path during the shadow-mode rollout.
275
+
276
+ Prepare a Vault V2 deposit or withdrawal plan, then sign its pending requests with your wallet.
277
+ `applySignatures(plan, signatures)` synchronously verifies every supplied signature before attaching
278
+ it, without a client or RPC. It validates all requests against their actions, including permit/action
279
+ deadline agreement, rejects unknown or duplicate input IDs, and recovers the permit owner from the
280
+ EIP-712 typed-data hash. The domain
281
+ binds the signature to its chain. Only low-s ECDSA permits encodable as `v/r/s` are supported
282
+ (64-byte compact or 65-byte serialized signatures, stored in serialized form). Contract wallets
283
+ should use `supportSignature: false` for direct approvals: deployed bundles do not consume
284
+ arbitrary ERC-1271 or ERC-6492 signatures.
285
+
286
+ `parseTransactionPlan` revives bigint tags and validates supported versions/actions, field shapes
287
+ and uint256 ranges, unique IDs, references, action chain/account agreement and permit consistency,
288
+ including requests with existing signatures. It allows extra keys. Malformed JSON, shapes or
289
+ references throw `InvalidTransactionPlanError` with a JSON `path` and `reason`; unsupported versions
290
+ and action types retain their dedicated errors. Serialization remains unchecked. Parsing uses no
291
+ clock or RPC and does not check expiry, live state, signature ownership or action-layer business
292
+ constraints. It does not prove authenticity or intent: tampered-but-well-formed, internally consistent
293
+ plans pass, so integrators must still protect stored plans.
294
+
295
+ When existing allowance is insufficient, withdrawal plans request an unlimited (`maxUint256`)
296
+ ERC-2612 vault-share permit or direct share approval. The quote's `requiredShareAllowance` remains
297
+ the minimum needed for that withdrawal; later withdrawals reuse sufficient allowance without a
298
+ new signature. Deposit asset permits must instead sign the exact pull amount, not an unlimited
299
+ value. Existing stored withdrawal permits covering the minimum allowance remain supported.
300
+
301
+ Only deposit plans accept `slippageTolerance`, which sets their on-chain maximum share price.
302
+ Withdrawal plans do not accept it: the share-allowance quote uses `DEFAULT_SLIPPAGE_TOLERANCE`
303
+ internally, but withdrawals have no on-chain share-price or maximum-shares bound. A price drop
304
+ before inclusion can burn more shares than quoted.
305
+
306
+ ```typescript
307
+ import {
308
+ buildTransactions,
309
+ getPendingSignatureRequests,
310
+ applySignatures,
311
+ type TransactionPlan,
312
+ } from "@morpho-org/morpho-sdk";
313
+ import type { WalletClient } from "viem";
314
+ import { signTypedData } from "viem/actions";
315
+
316
+ async function finalize(wallet: WalletClient, plan: TransactionPlan) {
317
+ const signatures = await Promise.all(
318
+ getPendingSignatureRequests(plan).map(async ({ id, typedData }) => ({
319
+ id,
320
+ signature: await signTypedData(wallet, { ...typedData, account: plan.account }),
321
+ })),
322
+ );
323
+ return buildTransactions(applySignatures(plan, signatures));
324
+ }
325
+ ```
326
+
327
+ Protect stored plans: verification checks permit consistency and signers, not whether stored action
328
+ inputs match your intended operation. Builders do not reverify signatures in restored plans. Do not
329
+ change the plan after applying signatures. Empty signature input still validates all requests and
330
+ returns the original plan; omitted IDs retain their existing signatures.
331
+
270
332
  ### Midnight: take a fixed-rate offer
271
333
 
272
334
  Protocol-specific names are qualified in shared facades, for example `fetchBluePosition` and `fetchMidnightPosition` from `@morpho-org/morpho-sdk/fetch`. Canonical raw upstream names remain available under `/blue/{abis,addresses,constants,entities,errors,fetch,types,utils}` and `/midnight/{abis,constants,entities,errors,fetch,types,utils}`.
273
335
 
274
- Morpho-ts registers MidnightBundlesV2 on Ethereum, Base, Arc, Robinhood, and Tempo.
336
+ Morpho-ts registers MidnightBundlesV2 on Ethereum, Base, Arbitrum, Arc, Robinhood, and Tempo.
275
337
 
276
338
  ```typescript
277
339
  const midnight = client.morpho.midnight(8453);
@@ -290,6 +352,62 @@ const requirements = await output.getRequirements();
290
352
  const tx = output.buildTx();
291
353
  ```
292
354
 
355
+ ### Midnight: collateral batches
356
+
357
+ `supplyCollateralBatch` and `withdrawCollateralBatch` move several collaterals of one position in
358
+ one transaction: a Midnight core `multicall` of direct `supplyCollateral` or `withdrawCollateral`
359
+ calls that reverts as a whole. Pass one entry per collateral index; duplicates throw
360
+ `DuplicateMidnightCollateralIndexError`, unlike the bundle flows, which sum them.
361
+
362
+ A supply batch returns one unlimited Midnight approval per collateral token whose allowance is
363
+ below that token's total:
364
+
365
+ ```typescript
366
+ const supply = midnight.supplyCollateralBatch({
367
+ accountAddress: user,
368
+ marketData,
369
+ collateralSupplies: [
370
+ { collateralIndex: 0n, assets: 1_000_000n },
371
+ { collateralIndex: 1n, assets: 2_000_000_000_000_000_000n },
372
+ ],
373
+ });
374
+
375
+ for (const approval of await supply.getRequirements()) {
376
+ const hash = await walletClient.sendTransaction({ ...approval, account: user });
377
+ await client.waitForTransactionReceipt({ hash });
378
+ }
379
+ await walletClient.sendTransaction({ ...supply.buildTx(), account: user });
380
+ ```
381
+
382
+ A withdraw batch checks every entry against `positionData` and, when the position has debt, checks
383
+ the remaining collateral against the LLTV buffer using `collateralPrices`. `maxUint256` withdraws
384
+ that index's whole balance. It needs no requirements:
385
+
386
+ ```typescript
387
+ import { blueOracleAbi } from "@morpho-org/morpho-sdk/abis";
388
+ import { maxUint256 } from "viem";
389
+
390
+ const positionData = await midnight.getPositionData({ marketId, accountAddress: user });
391
+ const collateralPrices = await Promise.all(
392
+ marketData.params.collateralParams.map(({ oracle }) =>
393
+ client.readContract({ address: oracle, abi: blueOracleAbi, functionName: "price" }),
394
+ ),
395
+ );
396
+
397
+ const withdrawal = midnight.withdrawCollateralBatch({
398
+ accountAddress: user,
399
+ marketData,
400
+ positionData,
401
+ collateralPrices,
402
+ collateralWithdrawals: [
403
+ { collateralIndex: 0n, assets: 500_000n },
404
+ { collateralIndex: 1n, assets: maxUint256 },
405
+ ],
406
+ receiver: user,
407
+ });
408
+ await walletClient.sendTransaction({ ...withdrawal.buildTx(), account: user });
409
+ ```
410
+
293
411
  See the [documentation](https://docs.morpho.org/developers/sdks/morpho-sdk/) for the full API:
294
412
  native wrapping, Vault V2 BluePublicAllocator reallocations, borrow-position migration, vault V1 →
295
413
  V2 migration, force withdraw/redeem, and Midnight maker flows.
@@ -368,10 +486,12 @@ graph LR
368
486
  MN1 --> MNM[maker offer submission]
369
487
  MN1 --> MNR[repayWithdrawCollateral]
370
488
  MN1 --> MNP[collateral supply / redeem]
489
+ MN1 --> MNCB[collateral batches]
371
490
  MNT --> MNB2[MidnightBundlesV2]
372
491
  MNM --> MNB2
373
492
  MNR --> MNB2
374
493
  MNP --> MNC[Midnight]
494
+ MNCB -->|multicall| MNC
375
495
  end
376
496
 
377
497
 
package/lib/cjs/abis.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { marketParamsAbi as blueMarketParamsAbi } from "@morpho-org/blue-sdk";
2
- export { adaptiveCurveIrmAbi as blueAdaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc3643Abi, erc3643IdentityRegistryAbi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, midnightAdapterAbi, midnightAdapterFactoryAbi, midnightAdapterPriceRatifierV1Abi, midnightAdapterRateRatifierV1Abi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
2
+ export { adaptiveCurveIrmAbi as blueAdaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc3643Abi, erc3643IdentityRegistryAbi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
3
3
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
4
4
  preLiquidationAbi as bluePreLiquidationAbi,
5
5
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
package/lib/cjs/abis.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.blueBundlesV1Abi = exports.vaultBundlesV1Abi = exports.vaultExitBundlesV1Abi = exports.midnightSetterRatifierAbi = exports.midnightRateRatifierV1Abi = exports.midnightPriceRatifierV1Abi = exports.midnightEventsAbi = exports.midnightBundlesV2Abi = exports.midnightAbi = exports.midnightEcrecoverRatifierAbi = exports.midnightEcrecoverAuthorizerAbi = exports.midnightBlueBuyCallbackFactoryAbi = exports.midnightBlueBuyCallbackAbi = exports.wstEthAbi = exports.wrappedBackedTokenAbi = exports.whitelistControllerAggregatorV2Abi = exports.vaultV2FactoryAbi = exports.vaultV2BluePublicAllocatorAbi = exports.vaultV2Abi = exports.bluePreLiquidationFactoryAbi = exports.bluePreLiquidationAbi = exports.permit2Abi = exports.permissionedErc20WrapperAbi = exports.morphoVaultV1AdapterFactoryAbi = exports.morphoVaultV1AdapterAbi = exports.morphoMarketV1AdapterV2FactoryAbi = exports.morphoMarketV1AdapterV2Abi = exports.morphoMarketV1AdapterFactoryAbi = exports.morphoMarketV1AdapterAbi = exports.midnightAdapterRateRatifierV1Abi = exports.midnightAdapterPriceRatifierV1Abi = exports.midnightAdapterFactoryAbi = exports.midnightAdapterAbi = exports.metaMorphoFactoryAbi = exports.metaMorphoAbi = exports.erc5267Abi = exports.erc3643IdentityRegistryAbi = exports.erc3643Abi = exports.erc2612Abi = exports.blueOracleAbi = exports.blueAbi = exports.blueAdaptiveCurveIrmAbi = exports.blueMarketParamsAbi = void 0;
3
+ exports.blueBundlesV1Abi = exports.vaultBundlesV1Abi = exports.vaultExitBundlesV1Abi = exports.midnightSetterRatifierAbi = exports.midnightRateRatifierV1Abi = exports.midnightPriceRatifierV1Abi = exports.midnightEventsAbi = exports.midnightBundlesV2Abi = exports.midnightAbi = exports.midnightEcrecoverRatifierAbi = exports.midnightEcrecoverAuthorizerAbi = exports.midnightBlueBuyCallbackFactoryAbi = exports.midnightBlueBuyCallbackAbi = exports.wstEthAbi = exports.wrappedBackedTokenAbi = exports.whitelistControllerAggregatorV2Abi = exports.vaultV2FactoryAbi = exports.vaultV2BluePublicAllocatorAbi = exports.vaultV2Abi = exports.bluePreLiquidationFactoryAbi = exports.bluePreLiquidationAbi = exports.permit2Abi = exports.permissionedErc20WrapperAbi = exports.morphoVaultV1AdapterFactoryAbi = exports.morphoVaultV1AdapterAbi = exports.morphoMarketV1AdapterV2FactoryAbi = exports.morphoMarketV1AdapterV2Abi = exports.morphoMarketV1AdapterFactoryAbi = exports.morphoMarketV1AdapterAbi = exports.metaMorphoFactoryAbi = exports.metaMorphoAbi = exports.erc5267Abi = exports.erc3643IdentityRegistryAbi = exports.erc3643Abi = exports.erc2612Abi = exports.blueOracleAbi = exports.blueAbi = exports.blueAdaptiveCurveIrmAbi = exports.blueMarketParamsAbi = void 0;
4
4
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  Object.defineProperty(exports, "blueMarketParamsAbi", { enumerable: true, get: function () { return blue_sdk_1.marketParamsAbi; } });
6
6
  var blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
@@ -13,10 +13,6 @@ Object.defineProperty(exports, "erc3643IdentityRegistryAbi", { enumerable: true,
13
13
  Object.defineProperty(exports, "erc5267Abi", { enumerable: true, get: function () { return blue_sdk_viem_1.erc5267Abi; } });
14
14
  Object.defineProperty(exports, "metaMorphoAbi", { enumerable: true, get: function () { return blue_sdk_viem_1.metaMorphoAbi; } });
15
15
  Object.defineProperty(exports, "metaMorphoFactoryAbi", { enumerable: true, get: function () { return blue_sdk_viem_1.metaMorphoFactoryAbi; } });
16
- Object.defineProperty(exports, "midnightAdapterAbi", { enumerable: true, get: function () { return blue_sdk_viem_1.midnightAdapterAbi; } });
17
- Object.defineProperty(exports, "midnightAdapterFactoryAbi", { enumerable: true, get: function () { return blue_sdk_viem_1.midnightAdapterFactoryAbi; } });
18
- Object.defineProperty(exports, "midnightAdapterPriceRatifierV1Abi", { enumerable: true, get: function () { return blue_sdk_viem_1.midnightAdapterPriceRatifierV1Abi; } });
19
- Object.defineProperty(exports, "midnightAdapterRateRatifierV1Abi", { enumerable: true, get: function () { return blue_sdk_viem_1.midnightAdapterRateRatifierV1Abi; } });
20
16
  Object.defineProperty(exports, "morphoMarketV1AdapterAbi", { enumerable: true, get: function () { return blue_sdk_viem_1.morphoMarketV1AdapterAbi; } });
21
17
  Object.defineProperty(exports, "morphoMarketV1AdapterFactoryAbi", { enumerable: true, get: function () { return blue_sdk_viem_1.morphoMarketV1AdapterFactoryAbi; } });
22
18
  Object.defineProperty(exports, "morphoMarketV1AdapterV2Abi", { enumerable: true, get: function () { return blue_sdk_viem_1.morphoMarketV1AdapterV2Abi; } });
@@ -88,8 +88,8 @@ const blueRepayWithdrawCollateral = (params) => {
88
88
  if (repayAssets > 0n && repayShares > 0n) {
89
89
  throw new index_js_1.MutuallyExclusiveRepayAmountsError(marketParams.id);
90
90
  }
91
- const hasRepay = repayAssets > 0n || repayShares > 0n;
92
- if (!hasRepay && collateralAssets === 0n) {
91
+ const hasRepay = repayAssets + repayShares > 0n;
92
+ if (repayAssets + repayShares + collateralAssets === 0n) {
93
93
  throw new index_js_1.NonPositiveInputError("repayAssets, repayShares, or collateralAssets", 0n);
94
94
  }
95
95
  if (hasRepay && maxRepayAssets === 0n) {
@@ -222,6 +222,15 @@ const normalizeBundlesSignature = (serializedSignature, onInvalid = (details) =>
222
222
  return { v: Number(normalizedV), r: parsed.r, s: parsed.s };
223
223
  };
224
224
  exports.normalizeBundlesSignature = normalizeBundlesSignature;
225
+ const validateBundlesPermitValue = (params) => {
226
+ if (params.actual !== params.expected) {
227
+ throw new index_js_2.BundlesPermitMismatchError({
228
+ field: params.field,
229
+ expected: String(params.expected),
230
+ actual: String(params.actual),
231
+ });
232
+ }
233
+ };
225
234
  /**
226
235
  * Converts an optional vault-share ERC-2612 requirement into the ABI-ready Permit tuple.
227
236
  *
@@ -253,10 +262,6 @@ const getBundlesSharesPermit = (params) => {
253
262
  const { requirementSignature } = params;
254
263
  // Require a positive uint256 for the fallback permit deadline.
255
264
  (0, validate_js_1.validateDeadline)(params.deadline);
256
- if (requirementSignature != null) {
257
- // Require a positive uint256 for the signed permit deadline too.
258
- (0, validate_js_1.validateDeadline)(requirementSignature.args.deadline);
259
- }
260
265
  if (requirementSignature == null) {
261
266
  return {
262
267
  value: 0n,
@@ -267,6 +272,9 @@ const getBundlesSharesPermit = (params) => {
267
272
  s: viem_1.zeroHash,
268
273
  };
269
274
  }
275
+ // Require a positive uint256 for the signed permit deadline too.
276
+ (0, validate_js_1.validateDeadline)(requirementSignature.args.deadline);
277
+ const validatesOperation = params.owner != null || params.spender != null || params.amount != null;
270
278
  if (requirementSignature.action.type !== "permit") {
271
279
  throw new index_js_2.BundlesPermitMismatchError({
272
280
  field: "type",
@@ -306,29 +314,26 @@ const getBundlesSharesPermit = (params) => {
306
314
  actual: String(requirementSignature.args.amount),
307
315
  });
308
316
  }
309
- if ((params.owner != null || params.spender != null || params.amount != null) &&
310
- requirementSignature.action.args.amount !== requirementSignature.args.amount) {
311
- throw new index_js_2.BundlesPermitMismatchError({
317
+ if (validatesOperation) {
318
+ // Validation only; checks signed values against their operation descriptors.
319
+ validateBundlesPermitValue({
312
320
  field: "amount",
313
- expected: String(requirementSignature.args.amount),
314
- actual: String(requirementSignature.action.args.amount),
321
+ expected: requirementSignature.args.amount,
322
+ actual: requirementSignature.action.args.amount,
315
323
  });
316
- }
317
- if ((params.owner != null || params.spender != null || params.amount != null) &&
318
- requirementSignature.action.args.deadline !==
319
- requirementSignature.args.deadline) {
320
- throw new index_js_2.BundlesPermitMismatchError({
324
+ // Validation only; checks the signed deadline against its operation descriptor.
325
+ validateBundlesPermitValue({
321
326
  field: "deadline",
322
- expected: String(requirementSignature.args.deadline),
323
- actual: String(requirementSignature.action.args.deadline),
327
+ expected: requirementSignature.args.deadline,
328
+ actual: requirementSignature.action.args.deadline,
324
329
  });
325
330
  }
326
- if (requirementSignature.action.args.nonce != null &&
327
- requirementSignature.action.args.nonce !== requirementSignature.args.nonce) {
328
- throw new index_js_2.BundlesPermitMismatchError({
331
+ if (requirementSignature.action.args.nonce != null) {
332
+ // Validation only; checks the optional operation nonce against the signed nonce.
333
+ validateBundlesPermitValue({
329
334
  field: "nonce",
330
- expected: String(requirementSignature.args.nonce),
331
- actual: String(requirementSignature.action.args.nonce),
335
+ expected: requirementSignature.args.nonce,
336
+ actual: requirementSignature.action.args.nonce,
332
337
  });
333
338
  }
334
339
  const signature = (0, exports.normalizeBundlesSignature)(requirementSignature.args.signature);
@@ -357,7 +362,9 @@ exports.getBundlesSharesPermit = getBundlesSharesPermit;
357
362
  * from the operation's, or when a carried action nonce is inconsistent with the signed nonce.
358
363
  */
359
364
  const selectBundlesTokenRequirementSignature = (signatures, expected) => {
360
- if (signatures == null || signatures.length === 0)
365
+ if (signatures == null)
366
+ return undefined;
367
+ if (signatures.length === 0)
361
368
  return undefined;
362
369
  const selected = signatures.filter((signature) => signature.action.type === "permit" ||
363
370
  signature.action.type === "permit2SignatureTransfer");
@@ -380,24 +387,24 @@ const selectBundlesTokenRequirementSignature = (signatures, expected) => {
380
387
  actual: action.args.spender,
381
388
  });
382
389
  }
383
- if (selectedSignature.args.amount !== expected.amount ||
384
- action.args.amount !== expected.amount) {
390
+ const actualAmount = selectedSignature.args.amount !== expected.amount
391
+ ? selectedSignature.args.amount
392
+ : action.args.amount;
393
+ if (actualAmount !== expected.amount) {
385
394
  throw new index_js_2.BundlesPermitMismatchError({
386
395
  field: "amount",
387
396
  expected: String(expected.amount),
388
- actual: String(selectedSignature.args.amount !== expected.amount
389
- ? selectedSignature.args.amount
390
- : action.args.amount),
397
+ actual: String(actualAmount),
391
398
  });
392
399
  }
393
- if (selectedSignature.args.deadline !== expected.deadline ||
394
- action.args.deadline !== expected.deadline) {
400
+ const actualDeadline = selectedSignature.args.deadline !== expected.deadline
401
+ ? selectedSignature.args.deadline
402
+ : action.args.deadline;
403
+ if (actualDeadline !== expected.deadline) {
395
404
  throw new index_js_2.BundlesPermitMismatchError({
396
405
  field: "deadline",
397
406
  expected: String(expected.deadline),
398
- actual: String(selectedSignature.args.deadline !== expected.deadline
399
- ? selectedSignature.args.deadline
400
- : action.args.deadline),
407
+ actual: String(actualDeadline),
401
408
  });
402
409
  }
403
410
  if (action.args.nonce != null &&
@@ -7,19 +7,10 @@ const viem_1 = require("viem");
7
7
  const encodeMidnightCalldata_js_1 = require("../../helpers/encodeMidnightCalldata.js");
8
8
  const index_js_1 = require("../../helpers/index.js");
9
9
  const validate_js_1 = require("../../helpers/validate.js");
10
- const validateMidnightAccount_js_1 = require("../../helpers/validateMidnightAccount.js");
11
10
  const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
12
- const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
11
+ const validateMidnightCancelAndMakePublication_js_1 = require("../../helpers/validateMidnightCancelAndMakePublication.js");
13
12
  const validateMidnightPublication_js_1 = require("../../helpers/validateMidnightPublication.js");
14
13
  const index_js_2 = require("../../types/index.js");
15
- /** Blue market argument for `MidnightBundlesV2` calls that park no loan assets. */
16
- const emptyBlueMarket = {
17
- loanToken: viem_1.zeroAddress,
18
- collateralToken: viem_1.zeroAddress,
19
- oracle: viem_1.zeroAddress,
20
- irm: viem_1.zeroAddress,
21
- lltv: 0n,
22
- };
23
14
  /** Midnight market argument for `MidnightBundlesV2` calls that supply no collateral. */
24
15
  const emptyMidnightMarket = {
25
16
  chainId: 0n,
@@ -136,15 +127,8 @@ const midnightCancelAndMake = (params) => {
136
127
  const cancelledGroups = new Set();
137
128
  for (const [index, { group, maxConsumed },] of snapshot.cancellations.entries()) {
138
129
  const field = `cancellations[${index}].maxConsumed`;
139
- if (maxConsumed < 0n)
140
- throw new index_js_2.NegativeInputError(field, maxConsumed);
141
- if (maxConsumed > viem_1.maxUint128) {
142
- throw new index_js_2.InputExceedsMaxError({
143
- field,
144
- value: maxConsumed,
145
- max: viem_1.maxUint128,
146
- });
147
- }
130
+ // Validation only; enforces the cancellation ceiling uint128 range.
131
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)(field, maxConsumed);
148
132
  const key = group.toLowerCase();
149
133
  if (cancelledGroups.has(key)) {
150
134
  throw new index_js_2.DuplicateMidnightGroupCancellationError({ index, group });
@@ -158,54 +142,12 @@ const midnightCancelAndMake = (params) => {
158
142
  }
159
143
  }
160
144
  else {
161
- if (publication.root === viem_1.zeroHash) {
162
- throw new midnight_sdk_1.InvalidTreeError("Offer root cannot be zero.");
163
- }
164
- if (publication.payload === "0x") {
165
- throw new midnight_sdk_1.InvalidTreeError("Offer payload cannot be empty.");
166
- }
167
- if (publication.groups.length === 0) {
168
- throw new midnight_sdk_1.InvalidTreeError("Offer groups cannot be empty.");
169
- }
170
- const { priceRatifierV1, rateRatifierV1 } = (0, morpho_ts_1.getChainAddresses)(snapshot.chainId);
171
- const supportedTargets = [priceRatifierV1, rateRatifierV1].filter((target) => target != null);
172
- (0, validateMidnightAccount_js_1.validateMidnightAddress)("publication.ratifier", publication.ratifier);
173
- if (!supportedTargets.some((target) => (0, viem_1.isAddressEqual)(publication.ratifier, target))) {
174
- throw new index_js_2.UnsupportedMidnightAuthorizationTargetError({
175
- authorized: publication.ratifier,
176
- chainId: snapshot.chainId,
177
- supportedTargets,
178
- });
179
- }
180
- for (const group of publication.groups) {
181
- if (cancelledGroups.has(group.toLowerCase())) {
182
- throw new index_js_2.MidnightReplacementGroupCancelledError({ group });
183
- }
184
- }
185
- if (publication.blueSupply != null) {
186
- if (publication.blueSupply.assets <= 0n) {
187
- throw new index_js_2.NonPositiveInputError("blueSupply.assets", publication.blueSupply.assets);
188
- }
189
- (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("blueSupply.assets", publication.blueSupply.assets);
190
- }
191
- if (publication.collateral != null) {
192
- if (publication.collateral.supplies.length === 0) {
193
- throw new index_js_2.EmptyMidnightCollateralSuppliesError();
194
- }
195
- (0, validateMidnightMarket_js_1.validateMidnightMarket)({
196
- market: publication.collateral.market,
197
- chainId: snapshot.chainId,
198
- });
199
- for (const [index, { collateralIndex, assets },] of publication.collateral.supplies.entries()) {
200
- if (assets <= 0n) {
201
- throw new index_js_2.NonPositiveInputError(`collateral.supplies[${index}].assets`, assets);
202
- }
203
- (0, validateMidnightBounds_js_1.validateMidnightUint128Field)(`collateral.supplies[${index}].assets`, assets);
204
- // Throws UnknownCollateralIndexError when the index is not configured on the market.
205
- midnight_sdk_1.MarketUtils.getCollateralByIndex(publication.collateral.market, collateralIndex);
206
- }
207
- (0, validateMidnightBounds_js_1.validateMidnightCollateralSupplySums)("collateral.supplies", publication.collateral.supplies);
208
- }
145
+ // Validation only; checks publication content and funding inputs.
146
+ (0, validateMidnightCancelAndMakePublication_js_1.validateMidnightCancelAndMakePublication)({
147
+ publication,
148
+ chainId: snapshot.chainId,
149
+ cancelledGroups,
150
+ });
209
151
  }
210
152
  const collateral = publication?.collateral;
211
153
  const collateralPulls = collateral == null
@@ -233,28 +175,8 @@ const midnightCancelAndMake = (params) => {
233
175
  group,
234
176
  maxConsumed,
235
177
  }));
236
- const supplies = (publication?.collateral?.supplies ?? []).map(({ collateralIndex, assets }) => ({ collateralIndex, assets }));
237
- const blueSupply = publication?.blueSupply == null
238
- ? undefined
239
- : {
240
- market: {
241
- loanToken: publication.blueSupply.market.loanToken,
242
- collateralToken: publication.blueSupply.market.collateralToken,
243
- oracle: publication.blueSupply.market.oracle,
244
- irm: publication.blueSupply.market.irm,
245
- lltv: publication.blueSupply.market.lltv,
246
- },
247
- assets: publication.blueSupply.assets,
248
- callbackSalt: publication.blueSupply.callbackSalt,
249
- };
250
- const signature = publication?.rootSignature ?? {
251
- height: 0n,
252
- nonce: 0n,
253
- deadline: 0n,
254
- v: 0,
255
- r: viem_1.zeroHash,
256
- s: viem_1.zeroHash,
257
- };
178
+ const normalized = (0, validateMidnightCancelAndMakePublication_js_1.normalizeMidnightCancelAndMakePublication)(publication);
179
+ const { supplies, blueSupply, signature } = normalized;
258
180
  let tx = {
259
181
  to: (0, morpho_ts_1.getChainAddress)(snapshot.chainId, "midnightBundlesV2"),
260
182
  value: nativeFunding.value,
@@ -262,15 +184,15 @@ const midnightCancelAndMake = (params) => {
262
184
  abi: midnight_sdk_1.midnightBundlesV2Abi,
263
185
  functionName: "midnightBundlesV2CancelAndMake",
264
186
  args: [
265
- blueSupply?.market ?? emptyBlueMarket, // blueMarket
266
- blueSupply?.assets ?? 0n, // assetsToPark
267
- blueSupply?.callbackSalt ?? viem_1.zeroHash, // callbackSalt
187
+ normalized.blueMarket, // blueMarket
188
+ normalized.assetsToPark, // assetsToPark
189
+ normalized.callbackSalt, // callbackSalt
268
190
  publication?.collateral == null
269
191
  ? emptyMidnightMarket
270
192
  : midnight_sdk_1.MarketUtils.toStruct(publication.collateral.market), // market
271
193
  supplies, // collateralSupplies
272
- publication?.ratifier ?? viem_1.zeroAddress, // ratifier
273
- publication?.root ?? viem_1.zeroHash, // newRoot
194
+ normalized.ratifier, // ratifier
195
+ normalized.root, // newRoot
274
196
  signature.height, // signatureHeight
275
197
  signature.nonce, // signatureNonce
276
198
  signature.deadline, // signatureDeadline
@@ -278,7 +200,7 @@ const midnightCancelAndMake = (params) => {
278
200
  signature.r, // r
279
201
  signature.s, // s
280
202
  cancellations, // groupsToCancel
281
- publication?.payload ?? "0x", // payload
203
+ normalized.payload, // payload
282
204
  snapshot.deadline, // deadline
283
205
  nativeFunding.wrappedNative, // wrappedNative
284
206
  ],
@@ -295,9 +217,9 @@ const midnightCancelAndMake = (params) => {
295
217
  market: publication?.collateral == null
296
218
  ? viem_1.zeroHash
297
219
  : (0, encodeMidnightCalldata_js_1.encodeMidnightMarketId)(publication.collateral.market),
298
- ratifier: publication?.ratifier ?? viem_1.zeroAddress,
299
- root: publication?.root ?? viem_1.zeroHash,
300
- groups: [...(publication?.groups ?? [])],
220
+ ratifier: normalized.ratifier,
221
+ root: normalized.root,
222
+ groups: normalized.groups,
301
223
  cancellations,
302
224
  collateralSupplies: supplies,
303
225
  ...(blueSupply && { blueSupply }),
@@ -3,6 +3,7 @@ export * from "./cancelAndMake.js";
3
3
  export * from "./redeem.js";
4
4
  export * from "./repayWithdrawCollateral.js";
5
5
  export * from "./supplyCollateral.js";
6
+ export * from "./supplyCollateralBatch.js";
6
7
  export * from "./supplyCollateralTakeBorrow.js";
7
8
  export * from "./takeBorrow.js";
8
9
  export * from "./takeLend.js";
@@ -10,3 +11,4 @@ export * from "./takeRepayWithdrawCollateral.js";
10
11
  export * from "./takeWithdraw.js";
11
12
  export * from "./types.js";
12
13
  export * from "./withdrawCollateral.js";
14
+ export * from "./withdrawCollateralBatch.js";
@@ -19,6 +19,7 @@ __exportStar(require("./cancelAndMake.js"), exports);
19
19
  __exportStar(require("./redeem.js"), exports);
20
20
  __exportStar(require("./repayWithdrawCollateral.js"), exports);
21
21
  __exportStar(require("./supplyCollateral.js"), exports);
22
+ __exportStar(require("./supplyCollateralBatch.js"), exports);
22
23
  __exportStar(require("./supplyCollateralTakeBorrow.js"), exports);
23
24
  __exportStar(require("./takeBorrow.js"), exports);
24
25
  __exportStar(require("./takeLend.js"), exports);
@@ -26,3 +27,4 @@ __exportStar(require("./takeRepayWithdrawCollateral.js"), exports);
26
27
  __exportStar(require("./takeWithdraw.js"), exports);
27
28
  __exportStar(require("./types.js"), exports);
28
29
  __exportStar(require("./withdrawCollateral.js"), exports);
30
+ __exportStar(require("./withdrawCollateralBatch.js"), exports);
@@ -10,6 +10,7 @@ const validate_js_1 = require("../../helpers/validate.js");
10
10
  const validateMidnightAccount_js_1 = require("../../helpers/validateMidnightAccount.js");
11
11
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
12
12
  const validateMidnightReceiver_js_1 = require("../../helpers/validateMidnightReceiver.js");
13
+ const validatePositiveInput_js_1 = require("../../helpers/validatePositiveInput.js");
13
14
  const index_js_2 = require("../../types/index.js");
14
15
  /**
15
16
  * Encodes a reduce-only `MidnightBundlesV2` buy with no offers, so the sender's debt is repaid
@@ -79,9 +80,8 @@ const midnightRepayWithdrawCollateral = (params) => {
79
80
  throw new index_js_2.NonPositiveInputError("repay or withdraw amount", 0n);
80
81
  }
81
82
  if (repay.type === "full") {
82
- if (repay.maxBuyerAssets <= 0n) {
83
- throw new index_js_2.NonPositiveInputError("repay.maxBuyerAssets", repay.maxBuyerAssets);
84
- }
83
+ // Validation only; rejects non-positive amounts.
84
+ (0, validatePositiveInput_js_1.validatePositiveInput)("repay.maxBuyerAssets", repay.maxBuyerAssets);
85
85
  if (repay.maxBuyerAssets >= viem_1.maxUint256) {
86
86
  throw new index_js_2.InputExceedsMaxError({
87
87
  field: "repay.maxBuyerAssets",
@@ -92,9 +92,8 @@ const midnightRepayWithdrawCollateral = (params) => {
92
92
  }
93
93
  (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market: params.market, chainId: params.chainId });
94
94
  for (const [index, { collateralIndex, assets },] of params.collateralWithdrawals.entries()) {
95
- if (assets <= 0n) {
96
- throw new index_js_2.NonPositiveInputError(`collateralWithdrawals[${index}].assets`, assets);
97
- }
95
+ // Validation only; rejects non-positive amounts.
96
+ (0, validatePositiveInput_js_1.validatePositiveInput)(`collateralWithdrawals[${index}].assets`, assets);
98
97
  (0, validate_js_1.validateUint256Field)(`collateralWithdrawals[${index}].assets`, assets);
99
98
  // Throws UnknownCollateralIndexError when the index is not configured on the market.
100
99
  midnight_sdk_1.MarketUtils.getCollateralByIndex(params.market, collateralIndex);
@@ -0,0 +1,39 @@
1
+ import { type MarketInput } from "@morpho-org/midnight-sdk";
2
+ import { type Address } from "viem";
3
+ import { type Metadata, type MidnightCollateralTransfer, type MidnightSupplyCollateralBatchAction, type Transaction } from "../../types/index.js";
4
+ /** Parameters for an atomic direct Midnight collateral supply batch. */
5
+ export interface MidnightSupplyCollateralBatchParams {
6
+ readonly chainId: number;
7
+ readonly market: MarketInput;
8
+ readonly collateralSupplies: readonly MidnightCollateralTransfer[];
9
+ readonly onBehalf: Address;
10
+ readonly metadata?: Metadata;
11
+ }
12
+ /**
13
+ * Encodes ordered collateral supplies in one Midnight multicall, even for one entry.
14
+ * Duplicates are rejected: pass one entry per index, unlike bundle flows which sum them.
15
+ *
16
+ * @param params.chainId - Chain containing Midnight.
17
+ * @param params.market - Market receiving collateral.
18
+ * @param params.collateralSupplies - Nonempty ordered supplies, with unique collateral indexes.
19
+ * @param params.onBehalf - Account receiving collateral; this account or an authorized operator must send the transaction.
20
+ * @param params.metadata - Optional analytics metadata appended to calldata.
21
+ * @returns A deep-frozen transaction targeting Midnight.
22
+ * @throws {EmptyMidnightCollateralSuppliesError} when the list is empty.
23
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
24
+ * @throws {NonPositiveInputError} when assets are not positive.
25
+ * @throws {InputExceedsMaxError} when assets exceed uint128.
26
+ * @throws {MidnightZeroOnBehalfError} when onBehalf is zero.
27
+ * @throws {ChainIdMismatchError} when the market targets another chain.
28
+ * @throws {MidnightMarketAddressMismatchError} when the deployment differs.
29
+ * @throws {UnknownCollateralIndexError} when an index is not configured.
30
+ * @throws {MidnightCalldataEncodingError} when an address or ABI input is malformed.
31
+ * @example
32
+ * ```ts
33
+ * const tx = midnightSupplyCollateralBatch({
34
+ * chainId: 8453, market: marketData.params, onBehalf: user,
35
+ * collateralSupplies: [{ collateralIndex: 0n, assets: 100n }],
36
+ * });
37
+ * ```
38
+ */
39
+ export declare const midnightSupplyCollateralBatch: (params: MidnightSupplyCollateralBatchParams) => Readonly<Transaction<MidnightSupplyCollateralBatchAction>>;