@morpho-org/morpho-sdk 9.5.1 → 9.6.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 (92) hide show
  1. package/README.md +59 -0
  2. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -2
  3. package/lib/cjs/actions/bundles/common.js +39 -32
  4. package/lib/cjs/actions/midnight/cancelAndMake.js +20 -98
  5. package/lib/cjs/actions/midnight/index.d.ts +2 -0
  6. package/lib/cjs/actions/midnight/index.js +2 -0
  7. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +5 -6
  8. package/lib/cjs/actions/midnight/supplyCollateralBatch.d.ts +39 -0
  9. package/lib/cjs/actions/midnight/supplyCollateralBatch.js +91 -0
  10. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +31 -32
  11. package/lib/cjs/actions/midnight/takeBorrow.js +24 -23
  12. package/lib/cjs/actions/midnight/takeLend.js +24 -23
  13. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +20 -19
  14. package/lib/cjs/actions/midnight/takeWithdraw.js +24 -23
  15. package/lib/cjs/actions/midnight/withdrawCollateralBatch.d.ts +44 -0
  16. package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +104 -0
  17. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -0
  18. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -0
  19. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +1 -0
  20. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +1 -0
  21. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +1 -0
  22. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  23. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -0
  24. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +1 -0
  25. package/lib/cjs/actions/vaultV1/migrateToV2.js +7 -7
  26. package/lib/cjs/entities/index.d.ts +1 -1
  27. package/lib/cjs/entities/midnight/midnight.d.ts +77 -3
  28. package/lib/cjs/entities/midnight/midnight.js +174 -0
  29. package/lib/cjs/entities/midnight/types.d.ts +16 -0
  30. package/lib/cjs/errors.d.ts +1 -1
  31. package/lib/cjs/errors.js +3 -2
  32. package/lib/cjs/helpers/signAndVerifyTypedData.d.ts +1 -0
  33. package/lib/cjs/helpers/signAndVerifyTypedData.js +12 -5
  34. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.d.ts +68 -0
  35. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.js +129 -0
  36. package/lib/cjs/helpers/validateMidnightCollateralBatch.d.ts +14 -0
  37. package/lib/cjs/helpers/validateMidnightCollateralBatch.js +27 -0
  38. package/lib/cjs/helpers/validateMidnightCollateralSupplies.d.ts +17 -0
  39. package/lib/cjs/helpers/validateMidnightCollateralSupplies.js +28 -0
  40. package/lib/cjs/helpers/validatePositiveInput.d.ts +10 -0
  41. package/lib/cjs/helpers/validatePositiveInput.js +18 -0
  42. package/lib/cjs/midnight/errors.d.ts +1 -1
  43. package/lib/cjs/midnight/errors.js +2 -1
  44. package/lib/cjs/types/action.d.ts +18 -3
  45. package/lib/cjs/types/error.d.ts +23 -2
  46. package/lib/cjs/types/error.js +45 -5
  47. package/lib/esm/actions/blue/repayWithdrawCollateral.js +2 -2
  48. package/lib/esm/actions/bundles/common.js +39 -32
  49. package/lib/esm/actions/midnight/cancelAndMake.js +25 -103
  50. package/lib/esm/actions/midnight/index.d.ts +2 -0
  51. package/lib/esm/actions/midnight/index.js +2 -0
  52. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +5 -6
  53. package/lib/esm/actions/midnight/supplyCollateralBatch.d.ts +39 -0
  54. package/lib/esm/actions/midnight/supplyCollateralBatch.js +87 -0
  55. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +33 -34
  56. package/lib/esm/actions/midnight/takeBorrow.js +25 -24
  57. package/lib/esm/actions/midnight/takeLend.js +25 -24
  58. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +20 -19
  59. package/lib/esm/actions/midnight/takeWithdraw.js +25 -24
  60. package/lib/esm/actions/midnight/withdrawCollateralBatch.d.ts +44 -0
  61. package/lib/esm/actions/midnight/withdrawCollateralBatch.js +100 -0
  62. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -0
  63. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -0
  64. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +1 -0
  65. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +1 -0
  66. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +1 -0
  67. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  68. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -0
  69. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +1 -0
  70. package/lib/esm/actions/vaultV1/migrateToV2.js +8 -8
  71. package/lib/esm/entities/index.d.ts +1 -1
  72. package/lib/esm/entities/midnight/midnight.d.ts +77 -3
  73. package/lib/esm/entities/midnight/midnight.js +176 -2
  74. package/lib/esm/entities/midnight/types.d.ts +16 -0
  75. package/lib/esm/errors.d.ts +1 -1
  76. package/lib/esm/errors.js +1 -1
  77. package/lib/esm/helpers/signAndVerifyTypedData.d.ts +1 -0
  78. package/lib/esm/helpers/signAndVerifyTypedData.js +13 -6
  79. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.d.ts +68 -0
  80. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.js +124 -0
  81. package/lib/esm/helpers/validateMidnightCollateralBatch.d.ts +14 -0
  82. package/lib/esm/helpers/validateMidnightCollateralBatch.js +24 -0
  83. package/lib/esm/helpers/validateMidnightCollateralSupplies.d.ts +17 -0
  84. package/lib/esm/helpers/validateMidnightCollateralSupplies.js +24 -0
  85. package/lib/esm/helpers/validatePositiveInput.d.ts +10 -0
  86. package/lib/esm/helpers/validatePositiveInput.js +14 -0
  87. package/lib/esm/midnight/errors.d.ts +1 -1
  88. package/lib/esm/midnight/errors.js +1 -1
  89. package/lib/esm/types/action.d.ts +18 -3
  90. package/lib/esm/types/error.d.ts +23 -2
  91. package/lib/esm/types/error.js +40 -3
  92. package/package.json +5 -5
@@ -0,0 +1,100 @@
1
+ import { MarketUtils, midnightAbi, } from "@morpho-org/midnight-sdk";
2
+ import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
+ import { isAddressEqual, zeroAddress } from "viem";
4
+ import { encodeMidnightCalldata, encodeMidnightMarketId, } from "../../helpers/encodeMidnightCalldata.js";
5
+ import { addTransactionMetadata } from "../../helpers/index.js";
6
+ import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
7
+ import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
8
+ import { validateMidnightCollateralBatch } from "../../helpers/validateMidnightCollateralBatch.js";
9
+ import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
10
+ import { validateMidnightReceiver } from "../../helpers/validateMidnightReceiver.js";
11
+ import { EmptyMidnightCollateralWithdrawalsError, MidnightZeroOnBehalfError, NonPositiveInputError, } from "../../types/index.js";
12
+ /**
13
+ * Encodes ordered collateral withdrawals 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 - Market, ordered withdrawals, owner, shared receiver and optional metadata.
17
+ * @param params.chainId - Chain containing Midnight.
18
+ * @param params.market - Market holding collateral.
19
+ * @param params.collateralWithdrawals - Nonempty ordered withdrawals, with unique collateral indexes.
20
+ * @param params.onBehalf - Collateral owner; this account or an authorized operator must send the transaction.
21
+ * @param params.receiver - Shared recipient of all withdrawn collateral.
22
+ * @param params.metadata - Optional analytics metadata appended to calldata.
23
+ * @returns A deep-frozen transaction targeting Midnight.
24
+ * @throws {EmptyMidnightCollateralWithdrawalsError} when the list is empty.
25
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
26
+ * @throws {MidnightZeroReceiverError} when receiver is zero.
27
+ * @throws {MidnightContractReceiverError} when receiver cannot safely receive collateral.
28
+ * @throws {NonPositiveInputError} when assets are not positive.
29
+ * @throws {InputExceedsMaxError} when assets exceed uint128.
30
+ * @throws {MidnightZeroOnBehalfError} when onBehalf is zero.
31
+ * @throws {ChainIdMismatchError} when the market targets another chain.
32
+ * @throws {MidnightMarketAddressMismatchError} when the deployment differs.
33
+ * @throws {UnknownCollateralIndexError} when an index is not configured.
34
+ * @throws {MidnightCalldataEncodingError} when an address or ABI input is malformed.
35
+ * @example
36
+ * ```ts
37
+ * const tx = midnightWithdrawCollateralBatch({
38
+ * chainId: 8453, market: marketData.params, onBehalf: user, receiver: user,
39
+ * collateralWithdrawals: [{ collateralIndex: 0n, assets: 100n }],
40
+ * });
41
+ * ```
42
+ */
43
+ export const midnightWithdrawCollateralBatch = (params) => {
44
+ // Reject malformed addresses before comparing with zero.
45
+ validateMidnightAddress("onBehalf", params.onBehalf);
46
+ if (isAddressEqual(params.onBehalf, zeroAddress)) {
47
+ throw new MidnightZeroOnBehalfError("onBehalf");
48
+ }
49
+ // Reject markets from another deployment before encoding.
50
+ validateMidnightMarket({ market: params.market, chainId: params.chainId });
51
+ validateMidnightReceiver({
52
+ chainId: params.chainId,
53
+ market: params.market,
54
+ field: "receiver",
55
+ receiver: params.receiver,
56
+ });
57
+ // Direct batches require one entry per index rather than summing duplicates.
58
+ validateMidnightCollateralBatch(params.collateralWithdrawals, new EmptyMidnightCollateralWithdrawalsError());
59
+ const calls = params.collateralWithdrawals.map(({ collateralIndex, assets }) => {
60
+ if (assets <= 0n)
61
+ throw new NonPositiveInputError("assets", assets);
62
+ validateMidnightUint128Field("assets", assets);
63
+ // Reject indexes not configured on the market.
64
+ MarketUtils.getCollateralByIndex(params.market, collateralIndex);
65
+ return encodeMidnightCalldata({
66
+ abi: midnightAbi,
67
+ functionName: "withdrawCollateral",
68
+ args: [
69
+ MarketUtils.toStruct(params.market),
70
+ collateralIndex,
71
+ assets,
72
+ params.onBehalf,
73
+ params.receiver,
74
+ ],
75
+ });
76
+ });
77
+ let tx = {
78
+ to: getChainAddress(params.chainId, "midnight"),
79
+ value: 0n,
80
+ data: encodeMidnightCalldata({
81
+ abi: midnightAbi,
82
+ functionName: "multicall",
83
+ args: [calls],
84
+ }),
85
+ };
86
+ if (params.metadata)
87
+ tx = addTransactionMetadata(tx, params.metadata);
88
+ return deepFreeze({
89
+ ...tx,
90
+ action: {
91
+ type: "midnightWithdrawCollateralBatch",
92
+ args: {
93
+ market: encodeMidnightMarketId(params.market),
94
+ collateralWithdrawals: params.collateralWithdrawals.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
95
+ onBehalf: params.onBehalf,
96
+ receiver: params.receiver,
97
+ },
98
+ },
99
+ });
100
+ };
@@ -55,6 +55,7 @@ interface EncodeBlueSignatureAuthorizationParams {
55
55
  * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
56
56
  * client account differs from `userAddress`.
57
57
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
58
+ * @throws {MalformedSignatureError} from `sign()` when the wallet returns a malformed signature.
58
59
  * @example
59
60
  * ```ts
60
61
  * import { createWalletClient, http } from "viem";
@@ -41,6 +41,7 @@ import { ChainIdMismatchError, ExpiredDeadlineError, UnsupportedAuthorizationOpe
41
41
  * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
42
42
  * client account differs from `userAddress`.
43
43
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
44
+ * @throws {MalformedSignatureError} from `sign()` when the wallet returns a malformed signature.
44
45
  * @example
45
46
  * ```ts
46
47
  * import { createWalletClient, http } from "viem";
@@ -62,6 +62,7 @@ interface EncodeErc20PermitParams {
62
62
  * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
63
63
  * client account differs from `userAddress`.
64
64
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
65
+ * @throws {MalformedSignatureError} from `sign()` when the wallet returns a malformed signature.
65
66
  * @example
66
67
  * ```ts
67
68
  * import { createWalletClient, http } from "viem";
@@ -52,6 +52,7 @@ import { validateClientChainId } from "../validateClientChainId.js";
52
52
  * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
53
53
  * client account differs from `userAddress`.
54
54
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
55
+ * @throws {MalformedSignatureError} from `sign()` when the wallet returns a malformed signature.
55
56
  * @example
56
57
  * ```ts
57
58
  * import { createWalletClient, http } from "viem";
@@ -48,6 +48,7 @@ export interface EncodeErc20Permit2SignatureTransferParams {
48
48
  * @throws {AddressMismatchError} from `sign()` when the wallet account differs from `userAddress`.
49
49
  * @throws {ChainIdMismatchError} from `sign()` when the wallet chain differs from `chainId`.
50
50
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
51
+ * @throws {MalformedSignatureError} from `sign()` when the wallet returns a malformed signature.
51
52
  * @example
52
53
  * ```ts
53
54
  * import { addressesRegistry } from "@morpho-org/blue-sdk";
@@ -33,6 +33,7 @@ import { ExpiredDeadlineError, InputExceedsMaxError, NonPositiveInputError, } fr
33
33
  * @throws {AddressMismatchError} from `sign()` when the wallet account differs from `userAddress`.
34
34
  * @throws {ChainIdMismatchError} from `sign()` when the wallet chain differs from `chainId`.
35
35
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
36
+ * @throws {MalformedSignatureError} from `sign()` when the wallet returns a malformed signature.
36
37
  * @example
37
38
  * ```ts
38
39
  * import { addressesRegistry } from "@morpho-org/blue-sdk";
@@ -46,6 +46,7 @@ export interface EncodeVaultSharesPermitParams {
46
46
  * wallet account differs from `userAddress`.
47
47
  * @throws {ChainIdMismatchError} from `sign()` when the wallet targets another chain.
48
48
  * @throws {InvalidSignatureError} from `sign()` when signature recovery fails.
49
+ * @throws {MalformedSignatureError} from `sign()` when the wallet returns a malformed signature.
49
50
  * @throws {InvalidPermitDomainChainIdError} when a Vault V1 permit domain targets another chain or omits `chainId`.
50
51
  * @throws {InvalidPermitDomainVerifyingContractError} when a Vault V1 permit domain targets another token or omits `verifyingContract`.
51
52
  * @throws {UnsupportedPermitDomainExtensionsError} when a Vault V1 permit domain advertises unsupported extensions.
@@ -33,6 +33,7 @@ import { ExpiredDeadlineError, } from "../../../types/index.js";
33
33
  * wallet account differs from `userAddress`.
34
34
  * @throws {ChainIdMismatchError} from `sign()` when the wallet targets another chain.
35
35
  * @throws {InvalidSignatureError} from `sign()` when signature recovery fails.
36
+ * @throws {MalformedSignatureError} from `sign()` when the wallet returns a malformed signature.
36
37
  * @throws {InvalidPermitDomainChainIdError} when a Vault V1 permit domain targets another chain or omits `chainId`.
37
38
  * @throws {InvalidPermitDomainVerifyingContractError} when a Vault V1 permit domain targets another token or omits `verifyingContract`.
38
39
  * @throws {UnsupportedPermitDomainExtensionsError} when a Vault V1 permit domain advertises unsupported extensions.
@@ -2,7 +2,8 @@ import { getChainAddress } from "@morpho-org/morpho-ts";
2
2
  import { encodeFunctionData, isAddressEqual } from "viem";
3
3
  import { vaultBundlesV1Abi } from "../../abis.js";
4
4
  import { validateUint256Field } from "../../helpers/validate.js";
5
- import { AmountAndSharesExclusiveError, NonPositiveInputError, SameVaultMigrationError, VaultAssetMismatchError, } from "../../types/index.js";
5
+ import { validatePositiveInput } from "../../helpers/validatePositiveInput.js";
6
+ import { AmountAndSharesExclusiveError, SameVaultMigrationError, VaultAssetMismatchError, } from "../../types/index.js";
6
7
  import { finalizeVaultBundlesV1Transaction, getBundlesReferralFeeAssets, getBundlesSharesPermit, normalizeBundlesCommonParams, } from "../bundles/common.js";
7
8
  /**
8
9
  * Encodes an assets-or-shares Vault V1 to Vault V2 migration through VaultBundlesV1.
@@ -86,14 +87,13 @@ export const vaultV1MigrateToV2 = (params) => {
86
87
  throw new AmountAndSharesExclusiveError();
87
88
  }
88
89
  const selectedAmount = assets ?? shares ?? 0n;
89
- if (selectedAmount <= 0n) {
90
- throw new NonPositiveInputError(assets != null ? "assets" : "shares", selectedAmount);
91
- }
92
- if (params.args.maxSharePriceVaultV2 <= 0n) {
93
- throw new NonPositiveInputError("maxSharePriceVaultV2", params.args.maxSharePriceVaultV2);
94
- }
90
+ const amountField = assets != null ? "assets" : "shares";
91
+ // Validation only; rejects non-positive migration amounts.
92
+ validatePositiveInput(amountField, selectedAmount);
93
+ // Validation only; rejects non-positive share-price bounds.
94
+ validatePositiveInput("maxSharePriceVaultV2", params.args.maxSharePriceVaultV2);
95
95
  // Reject ABI overflow with SDK errors before calldata encoding.
96
- validateUint256Field(assets != null ? "assets" : "shares", selectedAmount);
96
+ validateUint256Field(amountField, selectedAmount);
97
97
  validateUint256Field("maxSharePriceVaultV2", params.args.maxSharePriceVaultV2);
98
98
  const common = normalizeBundlesCommonParams(params.args);
99
99
  const spender = getChainAddress(params.vault.chainId, "bundles.vaultBundlesV1");
@@ -12,7 +12,7 @@ export type { AnyTree as MidnightAnyTree, AnyTreeSnapshot as MidnightAnyTreeSnap
12
12
  export { AccrualPosition as MidnightAccrualPosition, Group as MidnightGroup, Market as MidnightMarket, MarketParams as MidnightMarketParams, Offer as MidnightOffer, Position as MidnightPosition, Tree as MidnightTree, } from "@morpho-org/midnight-sdk";
13
13
  export type { BlueActions, BlueTokenRequirementsParams, } from "./blue/index.js";
14
14
  export { MorphoBlue } from "./blue/index.js";
15
- export type { GetOffersDataParams as MidnightGetOffersDataParams, GetPositionDataParams as MidnightGetPositionDataParams, MakeLendParams as MidnightMakeLendParams, MakeOffersOutput as MidnightMakeOffersOutput, MakeOffersParams as MidnightMakeOffersParams, MarketActionParams as MidnightMarketActionParams, MidnightMakerTreeInput, MidnightPositionHealthParams, OffersData as MidnightOffersData, OfferValidationParams as MidnightOfferValidationParams, RedeemParams as MidnightRedeemParams, RepayWithdrawCollateralParams as MidnightRepayWithdrawCollateralParams, SupplyBlueMakeLendParams as MidnightSupplyBlueMakeLendParams, SupplyCollateralMakeBorrowParams as MidnightSupplyCollateralMakeBorrowParams, SupplyCollateralParams as MidnightSupplyCollateralParams, SupplyCollateralTakeBorrowParams as MidnightSupplyCollateralTakeBorrowParams, TakeBorrowParams as MidnightTakeBorrowParams, TakeLendParams as MidnightTakeLendParams, TakeRepayWithdrawCollateralParams as MidnightTakeRepayWithdrawCollateralParams, TakeWithdrawParams as MidnightTakeWithdrawParams, WithdrawCollateralParams as MidnightWithdrawCollateralParams, } from "./midnight/index.js";
15
+ export type { GetOffersDataParams as MidnightGetOffersDataParams, GetPositionDataParams as MidnightGetPositionDataParams, MakeLendParams as MidnightMakeLendParams, MakeOffersOutput as MidnightMakeOffersOutput, MakeOffersParams as MidnightMakeOffersParams, MarketActionParams as MidnightMarketActionParams, MidnightMakerTreeInput, MidnightPositionHealthParams, OffersData as MidnightOffersData, OfferValidationParams as MidnightOfferValidationParams, RedeemParams as MidnightRedeemParams, RepayWithdrawCollateralParams as MidnightRepayWithdrawCollateralParams, SupplyBlueMakeLendParams as MidnightSupplyBlueMakeLendParams, SupplyCollateralBatchParams as MidnightSupplyCollateralBatchParams, SupplyCollateralMakeBorrowParams as MidnightSupplyCollateralMakeBorrowParams, SupplyCollateralParams as MidnightSupplyCollateralParams, SupplyCollateralTakeBorrowParams as MidnightSupplyCollateralTakeBorrowParams, TakeBorrowParams as MidnightTakeBorrowParams, TakeLendParams as MidnightTakeLendParams, TakeRepayWithdrawCollateralParams as MidnightTakeRepayWithdrawCollateralParams, TakeWithdrawParams as MidnightTakeWithdrawParams, WithdrawCollateralBatchParams as MidnightWithdrawCollateralBatchParams, WithdrawCollateralParams as MidnightWithdrawCollateralParams, } from "./midnight/index.js";
16
16
  export { type MidnightActionOutput, type MidnightActions, type MidnightRequirementsParams, MorphoMidnight, } from "./midnight/index.js";
17
17
  export * from "./requirements/index.js";
18
18
  export { MorphoVaultV1 } from "./vaultV1/index.js";
@@ -1,8 +1,8 @@
1
1
  import { type AccrualPosition, type Market, type MidnightFetchParams } from "@morpho-org/midnight-sdk";
2
2
  import { type Address, type Hex } from "viem";
3
3
  import type { MorphoClientType } from "../../types/client.js";
4
- import { type MidnightCancelAndMakeAction, type MidnightGroupCancellation, type MidnightRedeemAction, type MidnightRepayWithdrawCollateralAction, type MidnightSupplyCollateralAction, type MidnightSupplyCollateralTakeBorrowAction, type MidnightTakeBorrowAction, type MidnightTakeLendAction, type MidnightTakeRepayWithdrawCollateralAction, type MidnightTakeWithdrawAction, type MidnightWithdrawCollateralAction } from "../../types/index.js";
5
- import type { GetOffersDataParams, GetPositionDataParams, MakeLendParams, MakeOffersOutput, MakeOffersParams, MidnightActionOutput, OffersData, RedeemParams, RepayWithdrawCollateralParams, SupplyBlueMakeLendParams, SupplyCollateralMakeBorrowParams, SupplyCollateralParams, SupplyCollateralTakeBorrowParams, TakeBorrowParams, TakeLendParams, TakeRepayWithdrawCollateralParams, TakeWithdrawParams, WithdrawCollateralParams } from "./types.js";
4
+ import { type MidnightCancelAndMakeAction, type MidnightGroupCancellation, type MidnightRedeemAction, type MidnightRepayWithdrawCollateralAction, type MidnightSupplyCollateralAction, type MidnightSupplyCollateralBatchAction, type MidnightSupplyCollateralTakeBorrowAction, type MidnightTakeBorrowAction, type MidnightTakeLendAction, type MidnightTakeRepayWithdrawCollateralAction, type MidnightTakeWithdrawAction, type MidnightWithdrawCollateralAction, type MidnightWithdrawCollateralBatchAction } from "../../types/index.js";
5
+ import type { GetOffersDataParams, GetPositionDataParams, MakeLendParams, MakeOffersOutput, MakeOffersParams, MidnightActionOutput, OffersData, RedeemParams, RepayWithdrawCollateralParams, SupplyBlueMakeLendParams, SupplyCollateralBatchParams, SupplyCollateralMakeBorrowParams, SupplyCollateralParams, SupplyCollateralTakeBorrowParams, TakeBorrowParams, TakeLendParams, TakeRepayWithdrawCollateralParams, TakeWithdrawParams, WithdrawCollateralBatchParams, WithdrawCollateralParams } from "./types.js";
6
6
  /**
7
7
  * Entity methods exposed by `client.morpho.midnight(chainId)`.
8
8
  *
@@ -30,7 +30,7 @@ import type { GetOffersDataParams, GetPositionDataParams, MakeLendParams, MakeOf
30
30
  * const tx = output.buildTx();
31
31
  * ```
32
32
  */
33
- export type MidnightActions = Pick<MorphoMidnight, "getMarketData" | "getPositionData" | "getOffersData" | "takeLend" | "takeBorrow" | "takeWithdraw" | "supplyCollateralTakeBorrow" | "takeRepayWithdrawCollateral" | "supplyCollateral" | "withdrawCollateral" | "makeLend" | "makeBorrow" | "supplyBlueMakeLend" | "makeWithdraw" | "makeRepay" | "supplyCollateralMakeBorrow" | "redeem" | "repayWithdrawCollateral" | "cancelOffers">;
33
+ export type MidnightActions = Pick<MorphoMidnight, "getMarketData" | "getPositionData" | "getOffersData" | "takeLend" | "takeBorrow" | "takeWithdraw" | "supplyCollateralTakeBorrow" | "takeRepayWithdrawCollateral" | "supplyCollateral" | "supplyCollateralBatch" | "withdrawCollateral" | "withdrawCollateralBatch" | "makeLend" | "makeBorrow" | "supplyBlueMakeLend" | "makeWithdraw" | "makeRepay" | "supplyCollateralMakeBorrow" | "redeem" | "repayWithdrawCollateral" | "cancelOffers">;
34
34
  /**
35
35
  * Entity facade for Midnight fixed-rate action flows.
36
36
  *
@@ -637,6 +637,52 @@ export declare class MorphoMidnight {
637
637
  * ```
638
638
  */
639
639
  withdrawCollateral(params: WithdrawCollateralParams): MidnightActionOutput<MidnightWithdrawCollateralAction>;
640
+ /**
641
+ * Withdraws an ordered collateral batch atomically from Midnight without bundle authorization or token pulls.
642
+ *
643
+ * Uses the supplied position snapshot to resolve maxUint256 and check collateral health.
644
+ * Duplicates are rejected, unlike bundle flows which sum them.
645
+ * No requirements or RPC reads are needed. The signing account must be accountAddress.
646
+ *
647
+ * @param params - Market, owner-bound position, collateral prices and withdrawal amount.
648
+ * @param params.accountAddress - Collateral owner. This account must send the transaction.
649
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
650
+ * @param params.positionData - Owner-bound position snapshot returned by getPositionData.
651
+ * @param params.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
652
+ * ORACLE_PRICE_SCALE; required when the position has debt, otherwise an empty array is safe.
653
+ * @param params.collateralWithdrawals - Nonempty ordered withdrawals, one per index.
654
+ * maxUint256 resolves that index's full snapshot balance.
655
+ * @param params.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
656
+ * @returns Lazy handles for a direct Midnight withdrawal.
657
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
658
+ * @throws {MidnightCalldataEncodingError} when accountAddress is malformed or an input cannot be ABI-encoded.
659
+ * @throws {MidnightZeroAccountError} when accountAddress is zero.
660
+ * @throws {MidnightMarketAddressMismatchError} when marketData targets another Midnight deployment.
661
+ * @throws {MissingMarketPriceError} when debt is positive and held collateral has no supplied price.
662
+ * @throws {MarketIdMismatchError} when positionData belongs to another market.
663
+ * @throws {AccrualPositionUserMismatchError} when positionData belongs to another account.
664
+ * @throws {UnknownCollateralIndexError} when collateralIndex is not configured.
665
+ * @throws {EmptyMidnightCollateralWithdrawalsError} when the list is empty.
666
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
667
+ * @throws {NonPositiveInputError} when the resolved amount is not positive.
668
+ * @throws {InputExceedsMaxError} when assets exceeds uint128.
669
+ * @throws {WithdrawExceedsCollateralError} when assets exceeds the collateral balance.
670
+ * @throws {WithdrawMakesPositionUnhealthyError} when remaining collateral cannot safely cover debt.
671
+ * @throws {MidnightZeroReceiverError} when receiver is zero.
672
+ * @throws {MidnightContractReceiverError} when receiver cannot safely receive collateral.
673
+ * @example
674
+ * ```ts
675
+ * const output = midnight.withdrawCollateralBatch({
676
+ * accountAddress: user,
677
+ * marketData,
678
+ * positionData,
679
+ * collateralPrices,
680
+ * collateralWithdrawals: [{ collateralIndex: 0n, assets: 1_000n }],
681
+ * });
682
+ * const tx = output.buildTx();
683
+ * ```
684
+ */
685
+ withdrawCollateralBatch(params: WithdrawCollateralBatchParams): MidnightActionOutput<MidnightWithdrawCollateralBatchAction>;
640
686
  /**
641
687
  * Prepares a direct collateral supply using a caller-provided market snapshot.
642
688
  *
@@ -675,6 +721,34 @@ export declare class MorphoMidnight {
675
721
  * ```
676
722
  */
677
723
  supplyCollateral(params: SupplyCollateralParams): MidnightActionOutput<MidnightSupplyCollateralAction>;
724
+ /**
725
+ * Prepares ordered direct collateral supplies in one Midnight multicall.
726
+ * Pass one entry per index: duplicates are rejected, unlike bundle flows which sum them.
727
+ *
728
+ * @param params.accountAddress - Sender and collateral beneficiary.
729
+ * @param params.marketData - Snapshot of the target market.
730
+ * @param params.collateralSupplies - Ordered supplies with optional reserved allowance amounts.
731
+ * @returns A lazy approval resolver and synchronous stateless transaction builder.
732
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
733
+ * @throws {MidnightMarketAddressMismatchError} when the deployment differs.
734
+ * @throws {MidnightCalldataEncodingError} when the account is malformed.
735
+ * @throws {NegativeInputError} when reserved assets are negative.
736
+ * @throws {NonPositiveInputError} when assets are not positive.
737
+ * @throws {InputExceedsMaxError} when assets exceed uint128.
738
+ * @throws {UnknownCollateralIndexError} when an index is not configured.
739
+ * @throws {EmptyMidnightCollateralSuppliesError} when the list is empty.
740
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
741
+ * @throws {MidnightZeroOnBehalfError} when requirements or construction uses the zero account.
742
+ * @example
743
+ * ```ts
744
+ * const output = midnight.supplyCollateralBatch({
745
+ * accountAddress: user, marketData,
746
+ * collateralSupplies: [{ collateralIndex: 0n, assets: 100n }],
747
+ * });
748
+ * const tx = output.buildTx();
749
+ * ```
750
+ */
751
+ supplyCollateralBatch(params: SupplyCollateralBatchParams): MidnightActionOutput<MidnightSupplyCollateralBatchAction>;
678
752
  /**
679
753
  * Prepares an atomic lend-offer publication or repost through `MidnightBundlesV2`.
680
754
  *
@@ -3,7 +3,7 @@ import { fetchMarket as fetchBlueMarket } from "@morpho-org/blue-sdk-viem";
3
3
  import { fetchAccrualPosition, fetchMarket, MarketParams, MarketUtils, Payload, PriceRatifierV1, RateRatifierV1, Tree, } from "@morpho-org/midnight-sdk";
4
4
  import { _try, getChainAddress, Time } from "@morpho-org/morpho-ts";
5
5
  import { isAddress, isAddressEqual, maxUint256, zeroAddress, } from "viem";
6
- import { midnightCancelAndMake, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, midnightTakeRepayWithdrawCollateral, midnightTakeWithdraw, midnightWithdrawCollateral, } from "../../actions/midnight/index.js";
6
+ import { midnightCancelAndMake, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralBatch, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, midnightTakeRepayWithdrawCollateral, midnightTakeWithdraw, midnightWithdrawCollateral, midnightWithdrawCollateralBatch, } from "../../actions/midnight/index.js";
7
7
  import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, } from "../../actions/requirements/index.js";
8
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
9
  import { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "../../helpers/callback.js";
@@ -12,11 +12,12 @@ import { encodeMidnightMarketId, wrapMidnightEncoding, } from "../../helpers/enc
12
12
  import { getMidnightMaxSafeDebt, validateChainId, } from "../../helpers/index.js";
13
13
  import { validateMidnightAccount, validateMidnightAddress, } from "../../helpers/validateMidnightAccount.js";
14
14
  import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
15
+ import { validateMidnightCollateralBatch } from "../../helpers/validateMidnightCollateralBatch.js";
15
16
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
16
17
  import { validateMidnightBytes32 } from "../../helpers/validateMidnightPublication.js";
17
18
  import { validateMidnightTakeFeasibility } from "../../helpers/validateMidnightTakeFeasibility.js";
18
19
  import { validateOfferSides } from "../../helpers/validateOfferSides.js";
19
- import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, EmptyBlueParkingMarketError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MidnightZeroOnBehalfError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
20
+ import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, EmptyBlueParkingMarketError, EmptyMidnightCollateralSuppliesError, EmptyMidnightCollateralWithdrawalsError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MidnightZeroOnBehalfError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
20
21
  import { validateMidnightDeadline } from "./deadline.js";
21
22
  import { fetchMidnightMakerOfferStates, offerMarketParams, validateMidnightMakerOfferCallbacks, validateMidnightMakerOfferStates, } from "./publication.js";
22
23
  const validatePositionBinding = (params) => {
@@ -1161,6 +1162,106 @@ export class MorphoMidnight {
1161
1162
  }
1162
1163
  return { getRequirements: async () => [], buildTx: () => tx };
1163
1164
  }
1165
+ /**
1166
+ * Withdraws an ordered collateral batch atomically from Midnight without bundle authorization or token pulls.
1167
+ *
1168
+ * Uses the supplied position snapshot to resolve maxUint256 and check collateral health.
1169
+ * Duplicates are rejected, unlike bundle flows which sum them.
1170
+ * No requirements or RPC reads are needed. The signing account must be accountAddress.
1171
+ *
1172
+ * @param params - Market, owner-bound position, collateral prices and withdrawal amount.
1173
+ * @param params.accountAddress - Collateral owner. This account must send the transaction.
1174
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
1175
+ * @param params.positionData - Owner-bound position snapshot returned by getPositionData.
1176
+ * @param params.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
1177
+ * ORACLE_PRICE_SCALE; required when the position has debt, otherwise an empty array is safe.
1178
+ * @param params.collateralWithdrawals - Nonempty ordered withdrawals, one per index.
1179
+ * maxUint256 resolves that index's full snapshot balance.
1180
+ * @param params.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
1181
+ * @returns Lazy handles for a direct Midnight withdrawal.
1182
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
1183
+ * @throws {MidnightCalldataEncodingError} when accountAddress is malformed or an input cannot be ABI-encoded.
1184
+ * @throws {MidnightZeroAccountError} when accountAddress is zero.
1185
+ * @throws {MidnightMarketAddressMismatchError} when marketData targets another Midnight deployment.
1186
+ * @throws {MissingMarketPriceError} when debt is positive and held collateral has no supplied price.
1187
+ * @throws {MarketIdMismatchError} when positionData belongs to another market.
1188
+ * @throws {AccrualPositionUserMismatchError} when positionData belongs to another account.
1189
+ * @throws {UnknownCollateralIndexError} when collateralIndex is not configured.
1190
+ * @throws {EmptyMidnightCollateralWithdrawalsError} when the list is empty.
1191
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
1192
+ * @throws {NonPositiveInputError} when the resolved amount is not positive.
1193
+ * @throws {InputExceedsMaxError} when assets exceeds uint128.
1194
+ * @throws {WithdrawExceedsCollateralError} when assets exceeds the collateral balance.
1195
+ * @throws {WithdrawMakesPositionUnhealthyError} when remaining collateral cannot safely cover debt.
1196
+ * @throws {MidnightZeroReceiverError} when receiver is zero.
1197
+ * @throws {MidnightContractReceiverError} when receiver cannot safely receive collateral.
1198
+ * @example
1199
+ * ```ts
1200
+ * const output = midnight.withdrawCollateralBatch({
1201
+ * accountAddress: user,
1202
+ * marketData,
1203
+ * positionData,
1204
+ * collateralPrices,
1205
+ * collateralWithdrawals: [{ collateralIndex: 0n, assets: 1_000n }],
1206
+ * });
1207
+ * const tx = output.buildTx();
1208
+ * ```
1209
+ */
1210
+ withdrawCollateralBatch(params) {
1211
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
1212
+ // Reject invalid owners before preparing the direct call.
1213
+ validateMidnightAccount("accountAddress", params.accountAddress);
1214
+ validateMarketData(params.marketData, this.chainId);
1215
+ validatePositionBinding(params);
1216
+ // Direct batches reject duplicates instead of summing them.
1217
+ validateMidnightCollateralBatch(params.collateralWithdrawals, new EmptyMidnightCollateralWithdrawalsError());
1218
+ const collateralWithdrawals = params.collateralWithdrawals.map(({ collateralIndex, assets }) => {
1219
+ // Reject unconfigured indexes before reading the position balance.
1220
+ MarketUtils.getCollateralByIndex(params.marketData.params, collateralIndex);
1221
+ return {
1222
+ collateralIndex,
1223
+ assets: assets === maxUint256
1224
+ ? (params.positionData.collateral[Number(collateralIndex)] ?? 0n)
1225
+ : assets,
1226
+ };
1227
+ });
1228
+ const tx = midnightWithdrawCollateralBatch({
1229
+ chainId: this.chainId,
1230
+ market: params.marketData.params,
1231
+ collateralWithdrawals,
1232
+ onBehalf: params.accountAddress,
1233
+ receiver: params.receiver ?? params.accountAddress,
1234
+ metadata: this.client.options.metadata,
1235
+ });
1236
+ const collateral = Array.from({ length: params.marketData.params.collateralParams.length }, (_, i) => params.positionData.collateral[i] ?? 0n);
1237
+ for (const { collateralIndex, assets } of collateralWithdrawals) {
1238
+ const index = Number(collateralIndex);
1239
+ const available = collateral[index];
1240
+ if (assets > available) {
1241
+ throw new WithdrawExceedsCollateralError({
1242
+ withdrawAmount: assets,
1243
+ available,
1244
+ market: params.marketData.id,
1245
+ });
1246
+ }
1247
+ collateral[index] = available - assets;
1248
+ }
1249
+ if (params.positionData.debt > 0n) {
1250
+ const maxSafeDebt = getMidnightMaxSafeDebt({
1251
+ market: params.marketData,
1252
+ collateral,
1253
+ collateralPrices: params.collateralPrices,
1254
+ });
1255
+ if (params.positionData.debt > maxSafeDebt) {
1256
+ throw new WithdrawMakesPositionUnhealthyError({
1257
+ withdrawAmount: collateralWithdrawals.reduce((sum, entry) => sum + entry.assets, 0n),
1258
+ borrowAssets: params.positionData.debt,
1259
+ maxSafeBorrow: maxSafeDebt,
1260
+ });
1261
+ }
1262
+ }
1263
+ return { getRequirements: async () => [], buildTx: () => tx };
1264
+ }
1164
1265
  /**
1165
1266
  * Prepares a direct collateral supply using a caller-provided market snapshot.
1166
1267
  *
@@ -1235,6 +1336,79 @@ export class MorphoMidnight {
1235
1336
  }),
1236
1337
  };
1237
1338
  }
1339
+ /**
1340
+ * Prepares ordered direct collateral supplies in one Midnight multicall.
1341
+ * Pass one entry per index: duplicates are rejected, unlike bundle flows which sum them.
1342
+ *
1343
+ * @param params.accountAddress - Sender and collateral beneficiary.
1344
+ * @param params.marketData - Snapshot of the target market.
1345
+ * @param params.collateralSupplies - Ordered supplies with optional reserved allowance amounts.
1346
+ * @returns A lazy approval resolver and synchronous stateless transaction builder.
1347
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
1348
+ * @throws {MidnightMarketAddressMismatchError} when the deployment differs.
1349
+ * @throws {MidnightCalldataEncodingError} when the account is malformed.
1350
+ * @throws {NegativeInputError} when reserved assets are negative.
1351
+ * @throws {NonPositiveInputError} when assets are not positive.
1352
+ * @throws {InputExceedsMaxError} when assets exceed uint128.
1353
+ * @throws {UnknownCollateralIndexError} when an index is not configured.
1354
+ * @throws {EmptyMidnightCollateralSuppliesError} when the list is empty.
1355
+ * @throws {DuplicateMidnightCollateralIndexError} when an index repeats.
1356
+ * @throws {MidnightZeroOnBehalfError} when requirements or construction uses the zero account.
1357
+ * @example
1358
+ * ```ts
1359
+ * const output = midnight.supplyCollateralBatch({
1360
+ * accountAddress: user, marketData,
1361
+ * collateralSupplies: [{ collateralIndex: 0n, assets: 100n }],
1362
+ * });
1363
+ * const tx = output.buildTx();
1364
+ * ```
1365
+ */
1366
+ supplyCollateralBatch(params) {
1367
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
1368
+ // Reject malformed accounts before resolving token requirements.
1369
+ validateMidnightAddress("accountAddress", params.accountAddress);
1370
+ validateMarketData(params.marketData, this.chainId);
1371
+ // Reject empty and duplicate-index batches before resolving allowance thresholds.
1372
+ validateMidnightCollateralBatch(params.collateralSupplies, new EmptyMidnightCollateralSuppliesError());
1373
+ for (const supply of params.collateralSupplies) {
1374
+ assertPositiveAmount("assets", supply.assets);
1375
+ validateMidnightUint128Field("assets", supply.assets);
1376
+ assertNonNegativeAmount("reservedCollateralAssets", supply.reservedCollateralAssets ?? 0n);
1377
+ // Fail eagerly for collateral absent from the supplied snapshot.
1378
+ params.marketData.getCollateralByIndex(supply.collateralIndex);
1379
+ }
1380
+ const midnight = getChainAddress(this.chainId, "midnight");
1381
+ return {
1382
+ getRequirements: async (_requirementsParams) => {
1383
+ if (isAddressEqual(params.accountAddress, zeroAddress)) {
1384
+ throw new MidnightZeroOnBehalfError("onBehalf");
1385
+ }
1386
+ const amounts = new Map();
1387
+ for (const supply of params.collateralSupplies) {
1388
+ const token = params.marketData.getCollateralByIndex(supply.collateralIndex).token;
1389
+ amounts.set(token, (amounts.get(token) ?? 0n) +
1390
+ supply.assets +
1391
+ (supply.reservedCollateralAssets ?? 0n));
1392
+ }
1393
+ const requirements = await Promise.all([...amounts].map(([token, amount]) => getMidnightApprovalRequirements({
1394
+ viemClient: this.client.viemClient,
1395
+ chainId: this.chainId,
1396
+ token,
1397
+ owner: params.accountAddress,
1398
+ spender: midnight,
1399
+ amount,
1400
+ })));
1401
+ return requirements.flat();
1402
+ },
1403
+ buildTx: () => midnightSupplyCollateralBatch({
1404
+ chainId: this.chainId,
1405
+ market: params.marketData.params,
1406
+ collateralSupplies: params.collateralSupplies.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
1407
+ onBehalf: params.accountAddress,
1408
+ metadata: this.client.options.metadata,
1409
+ }),
1410
+ };
1411
+ }
1238
1412
  /**
1239
1413
  * Prepares an atomic lend-offer publication or repost through `MidnightBundlesV2`.
1240
1414
  *
@@ -235,6 +235,15 @@ export interface SupplyCollateralParams extends MarketActionParams {
235
235
  readonly reservedCollateralAssets?: bigint;
236
236
  readonly collateralIndex?: bigint;
237
237
  }
238
+ /** Parameters for an atomic direct Midnight collateral supply batch. */
239
+ export interface SupplyCollateralBatchParams extends MarketActionParams {
240
+ readonly collateralSupplies: readonly {
241
+ readonly collateralIndex: bigint;
242
+ readonly assets: bigint;
243
+ /** Additional assets included only in the allowance threshold. */
244
+ readonly reservedCollateralAssets?: bigint;
245
+ }[];
246
+ }
238
247
  /** Parameters for a direct Midnight collateral withdrawal. */
239
248
  export interface WithdrawCollateralParams extends MarketActionParams, MidnightPositionHealthParams {
240
249
  readonly collateralIndex?: bigint;
@@ -243,6 +252,13 @@ export interface WithdrawCollateralParams extends MarketActionParams, MidnightPo
243
252
  /** Defaults to accountAddress. */
244
253
  readonly receiver?: Address;
245
254
  }
255
+ /** Parameters for an atomic direct Midnight collateral withdrawal batch. */
256
+ export interface WithdrawCollateralBatchParams extends MarketActionParams, MidnightPositionHealthParams {
257
+ /** Ordered unique indexes; maxUint256 resolves that index's whole snapshot balance. */
258
+ readonly collateralWithdrawals: readonly MidnightCollateralTransfer[];
259
+ /** Defaults to accountAddress for every withdrawal. */
260
+ readonly receiver?: Address;
261
+ }
246
262
  /** Parameters for the Midnight redeem flow. */
247
263
  export interface RedeemParams {
248
264
  readonly accountAddress: Address;
@@ -2,6 +2,6 @@ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as I
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
4
  export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureError as InvalidMidnightEcrecoverSignatureError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
7
  export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
package/lib/esm/errors.js CHANGED
@@ -2,5 +2,5 @@ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as I
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
4
  export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureError as InvalidMidnightEcrecoverSignatureError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
6
  export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
@@ -16,6 +16,7 @@ import type { Address, Hex, TypedDataDefinition, WalletClient } from "viem";
16
16
  * @throws {AddressMismatchError} when the wallet client account differs from `userAddress`.
17
17
  * @throws {ChainIdMismatchError} when the wallet client targets a different chain than the typed-data domain.
18
18
  * @throws {InvalidSignatureError} when the signature does not recover to `userAddress`.
19
+ * @throws {MalformedSignatureError} when verification throws; preserves the original error as `cause` with redacted signature diagnostics. Extends `InvalidSignatureError`.
19
20
  * @example
20
21
  * ```ts
21
22
  * import { signAndVerifyTypedData } from "@morpho-org/morpho-sdk";