@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,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateMidnightCollateralBatch = validateMidnightCollateralBatch;
4
+ const error_js_1 = require("../types/error.js");
5
+ /**
6
+ * Rejects empty batches and repeated collateral indexes.
7
+ * @internal
8
+ * @param transfers - Ordered collateral transfers.
9
+ * @param emptyError - Operation-specific error thrown for an empty batch.
10
+ * @returns Nothing.
11
+ * @throws {DuplicateMidnightCollateralIndexError} when an index appears twice.
12
+ * @example
13
+ * ```ts
14
+ * validateMidnightCollateralBatch(supplies, new EmptyMidnightCollateralSuppliesError());
15
+ * ```
16
+ */
17
+ function validateMidnightCollateralBatch(transfers, emptyError) {
18
+ if (transfers.length === 0)
19
+ throw emptyError;
20
+ const indexes = new Set();
21
+ for (const { collateralIndex } of transfers) {
22
+ if (indexes.has(collateralIndex)) {
23
+ throw new error_js_1.DuplicateMidnightCollateralIndexError(collateralIndex);
24
+ }
25
+ indexes.add(collateralIndex);
26
+ }
27
+ }
@@ -0,0 +1,17 @@
1
+ import { type MarketInput } from "@morpho-org/midnight-sdk";
2
+ import type { MidnightCollateralTransfer } from "../types/index.js";
3
+ /**
4
+ * Validates collateral supply entries and their per-index totals.
5
+ *
6
+ * @param params - Market, error-field prefix, and collateral supplies.
7
+ * @returns Nothing when every entry and total is valid; accepts an empty list.
8
+ * @throws {NonPositiveInputError} when an entry is not positive.
9
+ * @throws {InputExceedsMaxError} when an entry or per-index sum exceeds uint128.
10
+ * @throws {UnknownCollateralIndexError} when an index is not configured on the market.
11
+ * @internal
12
+ */
13
+ export declare const validateMidnightCollateralSupplies: (params: {
14
+ readonly market: MarketInput;
15
+ readonly field: string;
16
+ readonly supplies: readonly MidnightCollateralTransfer[];
17
+ }) => void;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateMidnightCollateralSupplies = void 0;
4
+ const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
5
+ const validateMidnightBounds_js_1 = require("./validateMidnightBounds.js");
6
+ const validatePositiveInput_js_1 = require("./validatePositiveInput.js");
7
+ /**
8
+ * Validates collateral supply entries and their per-index totals.
9
+ *
10
+ * @param params - Market, error-field prefix, and collateral supplies.
11
+ * @returns Nothing when every entry and total is valid; accepts an empty list.
12
+ * @throws {NonPositiveInputError} when an entry is not positive.
13
+ * @throws {InputExceedsMaxError} when an entry or per-index sum exceeds uint128.
14
+ * @throws {UnknownCollateralIndexError} when an index is not configured on the market.
15
+ * @internal
16
+ */
17
+ const validateMidnightCollateralSupplies = (params) => {
18
+ for (const [index, { collateralIndex, assets },] of params.supplies.entries()) {
19
+ const field = `${params.field}[${index}].assets`;
20
+ // Validation only; rejects non-positive supply amounts.
21
+ (0, validatePositiveInput_js_1.validatePositiveInput)(field, assets);
22
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)(field, assets);
23
+ // Validation only; rejects indices not configured on the market.
24
+ midnight_sdk_1.MarketUtils.getCollateralByIndex(params.market, collateralIndex);
25
+ }
26
+ (0, validateMidnightBounds_js_1.validateMidnightCollateralSupplySums)(params.field, params.supplies);
27
+ };
28
+ exports.validateMidnightCollateralSupplies = validateMidnightCollateralSupplies;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Requires a strictly positive input amount.
3
+ *
4
+ * @param field - Input field name used in the error.
5
+ * @param value - Candidate amount.
6
+ * @returns Nothing when the amount is positive.
7
+ * @throws {NonPositiveInputError} when the amount is zero or negative.
8
+ * @internal
9
+ */
10
+ export declare const validatePositiveInput: (field: string, value: bigint) => void;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validatePositiveInput = void 0;
4
+ const error_js_1 = require("../types/error.js");
5
+ /**
6
+ * Requires a strictly positive input amount.
7
+ *
8
+ * @param field - Input field name used in the error.
9
+ * @param value - Candidate amount.
10
+ * @returns Nothing when the amount is positive.
11
+ * @throws {NonPositiveInputError} when the amount is zero or negative.
12
+ * @internal
13
+ */
14
+ const validatePositiveInput = (field, value) => {
15
+ if (value <= 0n)
16
+ throw new error_js_1.NonPositiveInputError(field, value);
17
+ };
18
+ exports.validatePositiveInput = validatePositiveInput;
@@ -1 +1 @@
1
- export { ChainIdMismatchError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
1
+ export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UnknownCollateralIndexError = exports.TickOutOfRangeError = exports.SettlementFeeExceedsPriceError = exports.RatifierV1TakerNotAllowedError = exports.RateRatifierV1BoundOverflowError = exports.PriceGreaterThanOneError = exports.PayloadDecodeError = exports.MidnightMempoolValidationError = exports.MidnightApiError = exports.InvalidTypedDataSignatureError = exports.InvalidTreeHeightError = exports.InvalidTreeError = exports.InvalidTickSpacingError = exports.InvalidRatifierV1AddressError = exports.InvalidRateRatifierV1TimeError = exports.InvalidRateRatifierV1TickError = exports.InvalidRateRatifierV1RateError = exports.InvalidPositionLossFactorError = exports.InvalidPositionAccrualTimestampError = exports.InvalidPositionAccrualStateError = exports.InvalidOfferParameterError = exports.InvalidOfferGroupError = exports.InvalidMidnightApiResponseError = exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMarketParameterError = exports.InvalidEcrecoverSignatureVError = exports.ChainIdMismatchError = void 0;
3
+ exports.UnknownCollateralIndexError = exports.TickOutOfRangeError = exports.SettlementFeeExceedsPriceError = exports.RatifierV1TakerNotAllowedError = exports.RateRatifierV1BoundOverflowError = exports.PriceGreaterThanOneError = exports.PayloadDecodeError = exports.MidnightMempoolValidationError = exports.MidnightApiError = exports.InvalidTypedDataSignatureError = exports.InvalidTreeHeightError = exports.InvalidTreeError = exports.InvalidTickSpacingError = exports.InvalidRatifierV1AddressError = exports.InvalidRateRatifierV1TimeError = exports.InvalidRateRatifierV1TickError = exports.InvalidRateRatifierV1RateError = exports.InvalidPositionLossFactorError = exports.InvalidPositionAccrualTimestampError = exports.InvalidPositionAccrualStateError = exports.InvalidOfferParameterError = exports.InvalidOfferGroupError = exports.InvalidMidnightApiResponseError = exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMarketParameterError = exports.InvalidEcrecoverSignatureVError = exports.InvalidEcrecoverSignatureError = exports.ChainIdMismatchError = void 0;
4
4
  var midnight_sdk_1 = require("@morpho-org/midnight-sdk");
5
5
  Object.defineProperty(exports, "ChainIdMismatchError", { enumerable: true, get: function () { return midnight_sdk_1.ChainIdMismatchError; } });
6
+ Object.defineProperty(exports, "InvalidEcrecoverSignatureError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidEcrecoverSignatureError; } });
6
7
  Object.defineProperty(exports, "InvalidEcrecoverSignatureVError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidEcrecoverSignatureVError; } });
7
8
  Object.defineProperty(exports, "InvalidMarketParameterError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidMarketParameterError; } });
8
9
  Object.defineProperty(exports, "InvalidMidnightApiQuoteTargetError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidMidnightApiQuoteTargetError; } });
@@ -283,12 +283,12 @@ export interface BlueWithdrawAction extends BaseAction<"blueWithdraw", {
283
283
  }> {
284
284
  }
285
285
  /**
286
- * Metadata for a direct Morpho Blue withdrawal of a BlueBuyCallback's whole supply position,
286
+ * Metadata for a direct Morpho Blue withdrawal of a BlueBuyCallback's supply shares,
287
287
  * sent by the callback's owner.
288
288
  */
289
289
  export interface BlueWithdrawBuyCallbackAction extends BaseAction<"blueWithdrawBuyCallback", {
290
290
  readonly market: Hex;
291
- /** Supply shares burned: the callback's whole position. */
291
+ /** Caller-supplied number of supply shares burned. */
292
292
  readonly shares: bigint;
293
293
  /** BlueBuyCallback whose supply position is withdrawn. */
294
294
  readonly onBehalf: Address;
@@ -449,6 +449,13 @@ export interface MidnightSupplyCollateralAction extends BaseAction<"midnightSupp
449
449
  readonly onBehalf: Address;
450
450
  }> {
451
451
  }
452
+ /** Metadata for an atomic direct Midnight collateral supply batch. */
453
+ export interface MidnightSupplyCollateralBatchAction extends BaseAction<"midnightSupplyCollateralBatch", {
454
+ readonly market: Hex;
455
+ readonly collateralSupplies: readonly MidnightCollateralTransfer[];
456
+ readonly onBehalf: Address;
457
+ }> {
458
+ }
452
459
  /** Metadata for a direct Midnight collateral withdrawal transaction. */
453
460
  export interface MidnightWithdrawCollateralAction extends BaseAction<"midnightWithdrawCollateral", {
454
461
  readonly market: Hex;
@@ -458,6 +465,14 @@ export interface MidnightWithdrawCollateralAction extends BaseAction<"midnightWi
458
465
  readonly receiver: Address;
459
466
  }> {
460
467
  }
468
+ /** Metadata for an atomic direct Midnight collateral withdrawal batch. */
469
+ export interface MidnightWithdrawCollateralBatchAction extends BaseAction<"midnightWithdrawCollateralBatch", {
470
+ readonly market: Hex;
471
+ readonly collateralWithdrawals: readonly MidnightCollateralTransfer[];
472
+ readonly onBehalf: Address;
473
+ readonly receiver: Address;
474
+ }> {
475
+ }
461
476
  /** Metadata for a direct Midnight credit redemption transaction. */
462
477
  export interface MidnightRedeemAction extends BaseAction<"midnightRedeem", {
463
478
  readonly market: Hex;
@@ -524,7 +539,7 @@ export interface MidnightCancelAndMakeAction extends BaseAction<"midnightCancelA
524
539
  * VaultV2, Blue, and Midnight flows. The `type` tag discriminates the union so
525
540
  * consumers can `switch` exhaustively on it.
526
541
  */
527
- export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2InKindRedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1InKindRedeemAction | VaultV1MigrateToV2Action | BlueSupplyAction | BlueSupplyCollateralAction | BlueBorrowAction | BlueSupplyCollateralBorrowAction | BlueRepayAction | BlueWithdrawCollateralAction | BlueRepayWithdrawCollateralAction | BlueWithdrawAction | BlueWithdrawBuyCallbackAction | BlueRefinanceAction | BlueAuthorizationAction | MidnightAuthorizationAction | MidnightTakeLendAction | MidnightTakeBorrowAction | MidnightTakeWithdrawAction | MidnightSupplyCollateralTakeBorrowAction | MidnightSupplyCollateralAction | MidnightWithdrawCollateralAction | MidnightRedeemAction | MidnightTakeRepayWithdrawCollateralAction | MidnightRepayWithdrawCollateralAction | MidnightCancelAndMakeAction;
542
+ export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2InKindRedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1InKindRedeemAction | VaultV1MigrateToV2Action | BlueSupplyAction | BlueSupplyCollateralAction | BlueBorrowAction | BlueSupplyCollateralBorrowAction | BlueRepayAction | BlueWithdrawCollateralAction | BlueRepayWithdrawCollateralAction | BlueWithdrawAction | BlueWithdrawBuyCallbackAction | BlueRefinanceAction | BlueAuthorizationAction | MidnightAuthorizationAction | MidnightTakeLendAction | MidnightTakeBorrowAction | MidnightTakeWithdrawAction | MidnightSupplyCollateralTakeBorrowAction | MidnightSupplyCollateralAction | MidnightSupplyCollateralBatchAction | MidnightWithdrawCollateralAction | MidnightWithdrawCollateralBatchAction | MidnightRedeemAction | MidnightTakeRepayWithdrawCollateralAction | MidnightRepayWithdrawCollateralAction | MidnightCancelAndMakeAction;
528
543
  /**
529
544
  * Describes a single, immutable, deep-frozen transaction to submit on-chain:
530
545
  * the target `to`, native `value`, encoded call `data`, and the originating
@@ -922,9 +922,22 @@ export declare class RepayExceedsDebtError extends Error {
922
922
  market: string;
923
923
  });
924
924
  }
925
- /** Thrown when EIP-712 signature verification fails (the signed data does not match the expected signer). */
925
+ /** Thrown when EIP-712 signature verification fails to recover the expected signer. */
926
926
  export declare class InvalidSignatureError extends Error {
927
- constructor();
927
+ constructor(options?: ErrorOptions);
928
+ }
929
+ /** Thrown when signature recovery fails, with redacted diagnostics and the original error as `cause`. */
930
+ export declare class MalformedSignatureError extends InvalidSignatureError {
931
+ /** JavaScript type returned by the wallet, without the signature value. */
932
+ readonly signatureType: string;
933
+ /** Whether the returned value is an even-length hex string. */
934
+ readonly signatureIsHex: boolean;
935
+ /** Signature byte length, when it is an even-length hex string. */
936
+ readonly signatureByteLength: number | undefined;
937
+ constructor(params: {
938
+ readonly signature: unknown;
939
+ readonly cause: unknown;
940
+ });
928
941
  }
929
942
  /** Thrown when a repay in shares mode supplies more shares than the borrower owes. */
930
943
  export declare class RepaySharesExceedDebtError extends Error {
@@ -1056,6 +1069,14 @@ export declare class EmptyMidnightGroupCancellationsError extends Error {
1056
1069
  export declare class EmptyMidnightCollateralSuppliesError extends Error {
1057
1070
  constructor();
1058
1071
  }
1072
+ /** Thrown when a direct Midnight collateral withdrawal batch is empty. */
1073
+ export declare class EmptyMidnightCollateralWithdrawalsError extends Error {
1074
+ constructor();
1075
+ }
1076
+ /** Thrown when a direct Midnight collateral batch repeats an index. */
1077
+ export declare class DuplicateMidnightCollateralIndexError extends Error {
1078
+ constructor(collateralIndex: bigint);
1079
+ }
1059
1080
  /** Thrown when a Midnight batch cancellation lists the same offer group twice. */
1060
1081
  export declare class DuplicateMidnightGroupCancellationError extends Error {
1061
1082
  constructor(params: {
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DepositOwnerMismatchError = exports.DepositAssetMismatchError = exports.DepositAmountMismatchError = exports.EmptyDeallocationsError = exports.ExcessiveSlippageToleranceError = exports.MissingAccrualPositionError = exports.UnsupportedMidnightAuthorizationTargetError = exports.UnsupportedErc20ApprovalSpenderError = exports.MissingClientPropertyError = exports.CryptoUnavailableError = exports.ChainIdMismatchError = exports.AddressMismatchError = exports.UnsupportedRequirementSignatureError = exports.UnexpectedRequirementSignatureError = exports.AmbiguousRequirementSignaturesError = exports.MaxRepayAssetsBelowRepayAssetsError = exports.ReallocationsRequireBorrowError = exports.UnsupportedAuthorizationOperatorError = exports.ReallocationLoanTokenMismatchError = exports.SameVaultMigrationError = exports.AmountAndSharesExclusiveError = exports.MixedBundlesFundingError = exports.MidnightReferralFeePctExceededError = exports.ReferralFeePctExceededError = exports.ReferralFeeRecipientMissingError = exports.NativeFundingAmountMismatchError = exports.NoUnusedPermit2NonceError = exports.Permit2SignatureTransferNonceAlreadyUsedError = exports.BundlesRequirementSignatureMismatchError = exports.BundlesPermitMismatchError = exports.VaultIsBlueFeeRecipientError = exports.VaultMorphoMismatchError = exports.InsufficientBlueBalanceForInKindRedeemError = exports.InKindRedeemCoverageError = exports.InKindRedeemZeroDeallocationError = exports.VaultV2ForceWithdrawFeeSharesExceedBurnError = exports.VaultV2ForceWithdrawSharePriceBelowFloorError = exports.VaultV2ForceWithdrawZeroSharePriceError = exports.VaultV2ForceWithdrawZeroWithdrawalError = exports.VaultV2ForceWithdrawCoverageError = exports.VaultV2UndecodableLiquidityDataError = exports.VaultV2UnsupportedLiquidityAdapterError = exports.VaultV2UnsupportedExitAdapterError = exports.AdapterNotPartOfVaultError = exports.VaultV2SingleAdapterRequiredError = exports.ExpiredDeadlineError = exports.EmptyMarketParamsListError = exports.InputExceedsMaxError = exports.NonPositiveInputError = exports.NegativeInputError = void 0;
4
- exports.MidnightOfferMarketAddressMismatchError = exports.MidnightOfferMarketChainMismatchError = exports.MidnightTakeDeadlineTooFarError = exports.MidnightContractReceiverError = exports.MidnightZeroOnBehalfError = exports.MidnightZeroReceiverError = exports.MidnightRepayExceedsDebtError = exports.MidnightContinuousFeeAboveMaxError = exports.MidnightTakeTargetUnreachableError = exports.MidnightTakeableOffersNotFillableError = exports.UnboundedMidnightTakeInputError = exports.MidnightOfferSellerReceiverMismatchError = exports.MidnightOfferContinuousFeeCapError = exports.MidnightOfferMakerMismatchError = exports.MidnightOfferReduceOnlyError = exports.MidnightOfferSideMismatchError = exports.EmptyMidnightTakeableOffersError = exports.DuplicateMidnightGroupCancellationError = exports.EmptyMidnightCollateralSuppliesError = exports.EmptyMidnightGroupCancellationsError = exports.ReallocationAdapterSupplySharesUnderflowError = exports.ReallocationAllocationUnderflowError = exports.UnknownReallocationAdapterError = exports.UnknownReallocationMarketPublicAllocatorConfigError = exports.UnknownReallocationActiveAdaptersError = exports.UnknownReallocationPublicAllocatorConfigError = exports.UnknownReallocationAllocationError = exports.UnknownReallocationVaultError = exports.UnknownReallocationMarketError = exports.InsufficientSharedLiquidityError = exports.RepaySharesExceedDebtError = exports.InvalidSignatureError = exports.RepayExceedsDebtError = exports.WithdrawMakesPositionUnhealthyError = exports.WithdrawExceedsCollateralError = exports.MutuallyExclusiveRepayAmountsError = exports.InconsistentReallocationPenaltyError = exports.InvalidReallocationSourceTypeError = exports.InvalidReallocationAddressError = exports.InvalidVaultV2BlueReallocationShapeError = exports.ReallocationWithdrawalOnTargetMarketError = exports.AccrualPositionUserMismatchError = exports.MarketIdMismatchError = exports.MissingMarketPriceError = exports.BorrowExceedsSafeLtvError = exports.NativeAmountOnNonWNativeAssetError = exports.VaultAddressMismatchError = exports.ChainWNativeMissingError = exports.NativeAmountOnNonWNativeVaultError = exports.DepositSpenderMismatchError = void 0;
5
- exports.MidnightCalldataEncodingError = exports.MidnightZeroAccountError = exports.MissingContractCodeError = exports.MidnightOfferNotReduceOnlyError = exports.RefinanceTokenMismatchError = exports.RefinanceSameMarketError = exports.VaultAssetMismatchError = exports.ReallocationWithdrawExceedsMarketSupplyError = exports.BlueBuyCallbackUnauthorizedError = exports.BlueBuyCallbackOwnerMismatchError = exports.NotBlueBuyCallbackError = exports.InsufficientBlueLiquidityError = exports.EmptyBlueSupplyPositionError = exports.WithdrawSharesExceedSupplyError = exports.WithdrawExceedsSupplyError = exports.MutuallyExclusiveWithdrawAmountsError = exports.MidnightInvalidAccountAddressError = exports.InvalidMidnightHexInputError = exports.InsufficientMidnightWithdrawableLiquidityError = exports.MidnightRedeemExceedsCreditError = exports.NoMidnightCreditToRedeemError = exports.MidnightReplacementGroupCancelledError = exports.MidnightOfferRatifierMismatchError = exports.MidnightTakeableOfferZeroSellerReceiverError = exports.MidnightTakeableOfferMarketMismatchError = exports.MissingDeadSharesDataError = exports.InsufficientDeadSharesError = exports.ZeroBlueParkingSharesError = exports.EmptyBlueParkingMarketError = exports.MidnightOfferCallbackDataMismatchError = exports.MidnightOfferCallbackMismatchError = exports.MidnightOfferMarketLoanTokenMismatchError = exports.MidnightMarketAddressMismatchError = void 0;
4
+ exports.MidnightContractReceiverError = exports.MidnightZeroOnBehalfError = exports.MidnightZeroReceiverError = exports.MidnightRepayExceedsDebtError = exports.MidnightContinuousFeeAboveMaxError = exports.MidnightTakeTargetUnreachableError = exports.MidnightTakeableOffersNotFillableError = exports.UnboundedMidnightTakeInputError = exports.MidnightOfferSellerReceiverMismatchError = exports.MidnightOfferContinuousFeeCapError = exports.MidnightOfferMakerMismatchError = exports.MidnightOfferReduceOnlyError = exports.MidnightOfferSideMismatchError = exports.EmptyMidnightTakeableOffersError = exports.DuplicateMidnightGroupCancellationError = exports.DuplicateMidnightCollateralIndexError = exports.EmptyMidnightCollateralWithdrawalsError = exports.EmptyMidnightCollateralSuppliesError = exports.EmptyMidnightGroupCancellationsError = exports.ReallocationAdapterSupplySharesUnderflowError = exports.ReallocationAllocationUnderflowError = exports.UnknownReallocationAdapterError = exports.UnknownReallocationMarketPublicAllocatorConfigError = exports.UnknownReallocationActiveAdaptersError = exports.UnknownReallocationPublicAllocatorConfigError = exports.UnknownReallocationAllocationError = exports.UnknownReallocationVaultError = exports.UnknownReallocationMarketError = exports.InsufficientSharedLiquidityError = exports.RepaySharesExceedDebtError = exports.MalformedSignatureError = exports.InvalidSignatureError = exports.RepayExceedsDebtError = exports.WithdrawMakesPositionUnhealthyError = exports.WithdrawExceedsCollateralError = exports.MutuallyExclusiveRepayAmountsError = exports.InconsistentReallocationPenaltyError = exports.InvalidReallocationSourceTypeError = exports.InvalidReallocationAddressError = exports.InvalidVaultV2BlueReallocationShapeError = exports.ReallocationWithdrawalOnTargetMarketError = exports.AccrualPositionUserMismatchError = exports.MarketIdMismatchError = exports.MissingMarketPriceError = exports.BorrowExceedsSafeLtvError = exports.NativeAmountOnNonWNativeAssetError = exports.VaultAddressMismatchError = exports.ChainWNativeMissingError = exports.NativeAmountOnNonWNativeVaultError = exports.DepositSpenderMismatchError = void 0;
5
+ exports.MidnightCalldataEncodingError = exports.MidnightZeroAccountError = exports.MissingContractCodeError = exports.MidnightOfferNotReduceOnlyError = exports.RefinanceTokenMismatchError = exports.RefinanceSameMarketError = exports.VaultAssetMismatchError = exports.ReallocationWithdrawExceedsMarketSupplyError = exports.BlueBuyCallbackUnauthorizedError = exports.BlueBuyCallbackOwnerMismatchError = exports.NotBlueBuyCallbackError = exports.InsufficientBlueLiquidityError = exports.EmptyBlueSupplyPositionError = exports.WithdrawSharesExceedSupplyError = exports.WithdrawExceedsSupplyError = exports.MutuallyExclusiveWithdrawAmountsError = exports.MidnightInvalidAccountAddressError = exports.InvalidMidnightHexInputError = exports.InsufficientMidnightWithdrawableLiquidityError = exports.MidnightRedeemExceedsCreditError = exports.NoMidnightCreditToRedeemError = exports.MidnightReplacementGroupCancelledError = exports.MidnightOfferRatifierMismatchError = exports.MidnightTakeableOfferZeroSellerReceiverError = exports.MidnightTakeableOfferMarketMismatchError = exports.MissingDeadSharesDataError = exports.InsufficientDeadSharesError = exports.ZeroBlueParkingSharesError = exports.EmptyBlueParkingMarketError = exports.MidnightOfferCallbackDataMismatchError = exports.MidnightOfferCallbackMismatchError = exports.MidnightOfferMarketLoanTokenMismatchError = exports.MidnightMarketAddressMismatchError = exports.MidnightOfferMarketAddressMismatchError = exports.MidnightOfferMarketChainMismatchError = exports.MidnightTakeDeadlineTooFarError = void 0;
6
6
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
7
7
  const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
8
8
  const constant_js_1 = require("../helpers/constant.js");
@@ -1208,14 +1208,38 @@ class RepayExceedsDebtError extends Error {
1208
1208
  }
1209
1209
  }
1210
1210
  exports.RepayExceedsDebtError = RepayExceedsDebtError;
1211
- /** Thrown when EIP-712 signature verification fails (the signed data does not match the expected signer). */
1211
+ /** Thrown when EIP-712 signature verification fails to recover the expected signer. */
1212
1212
  class InvalidSignatureError extends Error {
1213
- constructor() {
1214
- super("Signature verification failed: the signed data does not match the expected signer address");
1213
+ constructor(options) {
1214
+ super("Signature verification failed: the signed data does not match the expected signer address", options);
1215
1215
  this.name = "InvalidSignatureError";
1216
1216
  }
1217
1217
  }
1218
1218
  exports.InvalidSignatureError = InvalidSignatureError;
1219
+ /** Thrown when signature recovery fails, with redacted diagnostics and the original error as `cause`. */
1220
+ class MalformedSignatureError extends InvalidSignatureError {
1221
+ /** JavaScript type returned by the wallet, without the signature value. */
1222
+ signatureType;
1223
+ /** Whether the returned value is an even-length hex string. */
1224
+ signatureIsHex;
1225
+ /** Signature byte length, when it is an even-length hex string. */
1226
+ signatureByteLength;
1227
+ constructor(params) {
1228
+ super({ cause: params.cause });
1229
+ this.name = "MalformedSignatureError";
1230
+ this.message =
1231
+ "Signature verification failed: the wallet returned a malformed signature. Check the wallet signing transport and sign the typed data again.";
1232
+ this.signatureType = typeof params.signature;
1233
+ this.signatureIsHex =
1234
+ typeof params.signature === "string" &&
1235
+ /^0x(?:[0-9a-fA-F]{2})*$/.test(params.signature);
1236
+ this.signatureByteLength =
1237
+ this.signatureIsHex && typeof params.signature === "string"
1238
+ ? (params.signature.length - 2) / 2
1239
+ : undefined;
1240
+ }
1241
+ }
1242
+ exports.MalformedSignatureError = MalformedSignatureError;
1219
1243
  /** Thrown when a repay in shares mode supplies more shares than the borrower owes. */
1220
1244
  class RepaySharesExceedDebtError extends Error {
1221
1245
  constructor(params) {
@@ -1377,6 +1401,22 @@ class EmptyMidnightCollateralSuppliesError extends Error {
1377
1401
  }
1378
1402
  }
1379
1403
  exports.EmptyMidnightCollateralSuppliesError = EmptyMidnightCollateralSuppliesError;
1404
+ /** Thrown when a direct Midnight collateral withdrawal batch is empty. */
1405
+ class EmptyMidnightCollateralWithdrawalsError extends Error {
1406
+ constructor() {
1407
+ super("Midnight collateral withdrawals cannot be empty. Pass at least one collateral withdrawal.");
1408
+ this.name = "EmptyMidnightCollateralWithdrawalsError";
1409
+ }
1410
+ }
1411
+ exports.EmptyMidnightCollateralWithdrawalsError = EmptyMidnightCollateralWithdrawalsError;
1412
+ /** Thrown when a direct Midnight collateral batch repeats an index. */
1413
+ class DuplicateMidnightCollateralIndexError extends Error {
1414
+ constructor(collateralIndex) {
1415
+ super(`Midnight collateral batch repeats index "${collateralIndex}". Pass each collateral index once.`);
1416
+ this.name = "DuplicateMidnightCollateralIndexError";
1417
+ }
1418
+ }
1419
+ exports.DuplicateMidnightCollateralIndexError = DuplicateMidnightCollateralIndexError;
1380
1420
  /** Thrown when a Midnight batch cancellation lists the same offer group twice. */
1381
1421
  class DuplicateMidnightGroupCancellationError extends Error {
1382
1422
  constructor(params) {
@@ -85,8 +85,8 @@ export const blueRepayWithdrawCollateral = (params) => {
85
85
  if (repayAssets > 0n && repayShares > 0n) {
86
86
  throw new MutuallyExclusiveRepayAmountsError(marketParams.id);
87
87
  }
88
- const hasRepay = repayAssets > 0n || repayShares > 0n;
89
- if (!hasRepay && collateralAssets === 0n) {
88
+ const hasRepay = repayAssets + repayShares > 0n;
89
+ if (repayAssets + repayShares + collateralAssets === 0n) {
90
90
  throw new NonPositiveInputError("repayAssets, repayShares, or collateralAssets", 0n);
91
91
  }
92
92
  if (hasRepay && maxRepayAssets === 0n) {
@@ -215,6 +215,15 @@ export const normalizeBundlesSignature = (serializedSignature, onInvalid = (deta
215
215
  }
216
216
  return { v: Number(normalizedV), r: parsed.r, s: parsed.s };
217
217
  };
218
+ const validateBundlesPermitValue = (params) => {
219
+ if (params.actual !== params.expected) {
220
+ throw new BundlesPermitMismatchError({
221
+ field: params.field,
222
+ expected: String(params.expected),
223
+ actual: String(params.actual),
224
+ });
225
+ }
226
+ };
218
227
  /**
219
228
  * Converts an optional vault-share ERC-2612 requirement into the ABI-ready Permit tuple.
220
229
  *
@@ -246,10 +255,6 @@ export const getBundlesSharesPermit = (params) => {
246
255
  const { requirementSignature } = params;
247
256
  // Require a positive uint256 for the fallback permit deadline.
248
257
  validateDeadline(params.deadline);
249
- if (requirementSignature != null) {
250
- // Require a positive uint256 for the signed permit deadline too.
251
- validateDeadline(requirementSignature.args.deadline);
252
- }
253
258
  if (requirementSignature == null) {
254
259
  return {
255
260
  value: 0n,
@@ -260,6 +265,9 @@ export const getBundlesSharesPermit = (params) => {
260
265
  s: zeroHash,
261
266
  };
262
267
  }
268
+ // Require a positive uint256 for the signed permit deadline too.
269
+ validateDeadline(requirementSignature.args.deadline);
270
+ const validatesOperation = params.owner != null || params.spender != null || params.amount != null;
263
271
  if (requirementSignature.action.type !== "permit") {
264
272
  throw new BundlesPermitMismatchError({
265
273
  field: "type",
@@ -299,29 +307,26 @@ export const getBundlesSharesPermit = (params) => {
299
307
  actual: String(requirementSignature.args.amount),
300
308
  });
301
309
  }
302
- if ((params.owner != null || params.spender != null || params.amount != null) &&
303
- requirementSignature.action.args.amount !== requirementSignature.args.amount) {
304
- throw new BundlesPermitMismatchError({
310
+ if (validatesOperation) {
311
+ // Validation only; checks signed values against their operation descriptors.
312
+ validateBundlesPermitValue({
305
313
  field: "amount",
306
- expected: String(requirementSignature.args.amount),
307
- actual: String(requirementSignature.action.args.amount),
314
+ expected: requirementSignature.args.amount,
315
+ actual: requirementSignature.action.args.amount,
308
316
  });
309
- }
310
- if ((params.owner != null || params.spender != null || params.amount != null) &&
311
- requirementSignature.action.args.deadline !==
312
- requirementSignature.args.deadline) {
313
- throw new BundlesPermitMismatchError({
317
+ // Validation only; checks the signed deadline against its operation descriptor.
318
+ validateBundlesPermitValue({
314
319
  field: "deadline",
315
- expected: String(requirementSignature.args.deadline),
316
- actual: String(requirementSignature.action.args.deadline),
320
+ expected: requirementSignature.args.deadline,
321
+ actual: requirementSignature.action.args.deadline,
317
322
  });
318
323
  }
319
- if (requirementSignature.action.args.nonce != null &&
320
- requirementSignature.action.args.nonce !== requirementSignature.args.nonce) {
321
- throw new BundlesPermitMismatchError({
324
+ if (requirementSignature.action.args.nonce != null) {
325
+ // Validation only; checks the optional operation nonce against the signed nonce.
326
+ validateBundlesPermitValue({
322
327
  field: "nonce",
323
- expected: String(requirementSignature.args.nonce),
324
- actual: String(requirementSignature.action.args.nonce),
328
+ expected: requirementSignature.args.nonce,
329
+ actual: requirementSignature.action.args.nonce,
325
330
  });
326
331
  }
327
332
  const signature = normalizeBundlesSignature(requirementSignature.args.signature);
@@ -349,7 +354,9 @@ export const getBundlesSharesPermit = (params) => {
349
354
  * from the operation's, or when a carried action nonce is inconsistent with the signed nonce.
350
355
  */
351
356
  export const selectBundlesTokenRequirementSignature = (signatures, expected) => {
352
- if (signatures == null || signatures.length === 0)
357
+ if (signatures == null)
358
+ return undefined;
359
+ if (signatures.length === 0)
353
360
  return undefined;
354
361
  const selected = signatures.filter((signature) => signature.action.type === "permit" ||
355
362
  signature.action.type === "permit2SignatureTransfer");
@@ -372,24 +379,24 @@ export const selectBundlesTokenRequirementSignature = (signatures, expected) =>
372
379
  actual: action.args.spender,
373
380
  });
374
381
  }
375
- if (selectedSignature.args.amount !== expected.amount ||
376
- action.args.amount !== expected.amount) {
382
+ const actualAmount = selectedSignature.args.amount !== expected.amount
383
+ ? selectedSignature.args.amount
384
+ : action.args.amount;
385
+ if (actualAmount !== expected.amount) {
377
386
  throw new BundlesPermitMismatchError({
378
387
  field: "amount",
379
388
  expected: String(expected.amount),
380
- actual: String(selectedSignature.args.amount !== expected.amount
381
- ? selectedSignature.args.amount
382
- : action.args.amount),
389
+ actual: String(actualAmount),
383
390
  });
384
391
  }
385
- if (selectedSignature.args.deadline !== expected.deadline ||
386
- action.args.deadline !== expected.deadline) {
392
+ const actualDeadline = selectedSignature.args.deadline !== expected.deadline
393
+ ? selectedSignature.args.deadline
394
+ : action.args.deadline;
395
+ if (actualDeadline !== expected.deadline) {
387
396
  throw new BundlesPermitMismatchError({
388
397
  field: "deadline",
389
398
  expected: String(expected.deadline),
390
- actual: String(selectedSignature.args.deadline !== expected.deadline
391
- ? selectedSignature.args.deadline
392
- : action.args.deadline),
399
+ actual: String(actualDeadline),
393
400
  });
394
401
  }
395
402
  if (action.args.nonce != null &&
@@ -1,22 +1,13 @@
1
- import { InvalidTreeError, MarketUtils, midnightBundlesV2Abi, } from "@morpho-org/midnight-sdk";
2
- import { deepFreeze, getChainAddress, getChainAddresses, } from "@morpho-org/morpho-ts";
3
- import { isAddressEqual, maxUint128, zeroAddress, zeroHash, } from "viem";
1
+ import { MarketUtils, midnightBundlesV2Abi } from "@morpho-org/midnight-sdk";
2
+ import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
+ import { zeroAddress, zeroHash } from "viem";
4
4
  import { encodeMidnightCalldata, encodeMidnightMarketId, } from "../../helpers/encodeMidnightCalldata.js";
5
5
  import { addTransactionMetadata } from "../../helpers/index.js";
6
6
  import { validateDeadline, validateMidnightNativeAmount, } from "../../helpers/validate.js";
7
- import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
8
- import { validateMidnightCollateralSupplySums, validateMidnightUint128Field, } from "../../helpers/validateMidnightBounds.js";
9
- import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
7
+ import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
8
+ import { normalizeMidnightCancelAndMakePublication, validateMidnightCancelAndMakePublication, } from "../../helpers/validateMidnightCancelAndMakePublication.js";
10
9
  import { snapshotMidnightCancelAndMakeParams, validateMidnightPublication, } from "../../helpers/validateMidnightPublication.js";
11
- import { DuplicateMidnightGroupCancellationError, EmptyMidnightCollateralSuppliesError, EmptyMidnightGroupCancellationsError, InputExceedsMaxError, MidnightReplacementGroupCancelledError, NegativeInputError, NonPositiveInputError, UnsupportedMidnightAuthorizationTargetError, } from "../../types/index.js";
12
- /** Blue market argument for `MidnightBundlesV2` calls that park no loan assets. */
13
- const emptyBlueMarket = {
14
- loanToken: zeroAddress,
15
- collateralToken: zeroAddress,
16
- oracle: zeroAddress,
17
- irm: zeroAddress,
18
- lltv: 0n,
19
- };
10
+ import { DuplicateMidnightGroupCancellationError, EmptyMidnightGroupCancellationsError, } from "../../types/index.js";
20
11
  /** Midnight market argument for `MidnightBundlesV2` calls that supply no collateral. */
21
12
  const emptyMidnightMarket = {
22
13
  chainId: 0n,
@@ -133,15 +124,8 @@ export const midnightCancelAndMake = (params) => {
133
124
  const cancelledGroups = new Set();
134
125
  for (const [index, { group, maxConsumed },] of snapshot.cancellations.entries()) {
135
126
  const field = `cancellations[${index}].maxConsumed`;
136
- if (maxConsumed < 0n)
137
- throw new NegativeInputError(field, maxConsumed);
138
- if (maxConsumed > maxUint128) {
139
- throw new InputExceedsMaxError({
140
- field,
141
- value: maxConsumed,
142
- max: maxUint128,
143
- });
144
- }
127
+ // Validation only; enforces the cancellation ceiling uint128 range.
128
+ validateMidnightUint128Field(field, maxConsumed);
145
129
  const key = group.toLowerCase();
146
130
  if (cancelledGroups.has(key)) {
147
131
  throw new DuplicateMidnightGroupCancellationError({ index, group });
@@ -155,54 +139,12 @@ export const midnightCancelAndMake = (params) => {
155
139
  }
156
140
  }
157
141
  else {
158
- if (publication.root === zeroHash) {
159
- throw new InvalidTreeError("Offer root cannot be zero.");
160
- }
161
- if (publication.payload === "0x") {
162
- throw new InvalidTreeError("Offer payload cannot be empty.");
163
- }
164
- if (publication.groups.length === 0) {
165
- throw new InvalidTreeError("Offer groups cannot be empty.");
166
- }
167
- const { priceRatifierV1, rateRatifierV1 } = getChainAddresses(snapshot.chainId);
168
- const supportedTargets = [priceRatifierV1, rateRatifierV1].filter((target) => target != null);
169
- validateMidnightAddress("publication.ratifier", publication.ratifier);
170
- if (!supportedTargets.some((target) => isAddressEqual(publication.ratifier, target))) {
171
- throw new UnsupportedMidnightAuthorizationTargetError({
172
- authorized: publication.ratifier,
173
- chainId: snapshot.chainId,
174
- supportedTargets,
175
- });
176
- }
177
- for (const group of publication.groups) {
178
- if (cancelledGroups.has(group.toLowerCase())) {
179
- throw new MidnightReplacementGroupCancelledError({ group });
180
- }
181
- }
182
- if (publication.blueSupply != null) {
183
- if (publication.blueSupply.assets <= 0n) {
184
- throw new NonPositiveInputError("blueSupply.assets", publication.blueSupply.assets);
185
- }
186
- validateMidnightUint128Field("blueSupply.assets", publication.blueSupply.assets);
187
- }
188
- if (publication.collateral != null) {
189
- if (publication.collateral.supplies.length === 0) {
190
- throw new EmptyMidnightCollateralSuppliesError();
191
- }
192
- validateMidnightMarket({
193
- market: publication.collateral.market,
194
- chainId: snapshot.chainId,
195
- });
196
- for (const [index, { collateralIndex, assets },] of publication.collateral.supplies.entries()) {
197
- if (assets <= 0n) {
198
- throw new NonPositiveInputError(`collateral.supplies[${index}].assets`, assets);
199
- }
200
- validateMidnightUint128Field(`collateral.supplies[${index}].assets`, assets);
201
- // Throws UnknownCollateralIndexError when the index is not configured on the market.
202
- MarketUtils.getCollateralByIndex(publication.collateral.market, collateralIndex);
203
- }
204
- validateMidnightCollateralSupplySums("collateral.supplies", publication.collateral.supplies);
205
- }
142
+ // Validation only; checks publication content and funding inputs.
143
+ validateMidnightCancelAndMakePublication({
144
+ publication,
145
+ chainId: snapshot.chainId,
146
+ cancelledGroups,
147
+ });
206
148
  }
207
149
  const collateral = publication?.collateral;
208
150
  const collateralPulls = collateral == null
@@ -230,28 +172,8 @@ export const midnightCancelAndMake = (params) => {
230
172
  group,
231
173
  maxConsumed,
232
174
  }));
233
- const supplies = (publication?.collateral?.supplies ?? []).map(({ collateralIndex, assets }) => ({ collateralIndex, assets }));
234
- const blueSupply = publication?.blueSupply == null
235
- ? undefined
236
- : {
237
- market: {
238
- loanToken: publication.blueSupply.market.loanToken,
239
- collateralToken: publication.blueSupply.market.collateralToken,
240
- oracle: publication.blueSupply.market.oracle,
241
- irm: publication.blueSupply.market.irm,
242
- lltv: publication.blueSupply.market.lltv,
243
- },
244
- assets: publication.blueSupply.assets,
245
- callbackSalt: publication.blueSupply.callbackSalt,
246
- };
247
- const signature = publication?.rootSignature ?? {
248
- height: 0n,
249
- nonce: 0n,
250
- deadline: 0n,
251
- v: 0,
252
- r: zeroHash,
253
- s: zeroHash,
254
- };
175
+ const normalized = normalizeMidnightCancelAndMakePublication(publication);
176
+ const { supplies, blueSupply, signature } = normalized;
255
177
  let tx = {
256
178
  to: getChainAddress(snapshot.chainId, "midnightBundlesV2"),
257
179
  value: nativeFunding.value,
@@ -259,15 +181,15 @@ export const midnightCancelAndMake = (params) => {
259
181
  abi: midnightBundlesV2Abi,
260
182
  functionName: "midnightBundlesV2CancelAndMake",
261
183
  args: [
262
- blueSupply?.market ?? emptyBlueMarket, // blueMarket
263
- blueSupply?.assets ?? 0n, // assetsToPark
264
- blueSupply?.callbackSalt ?? zeroHash, // callbackSalt
184
+ normalized.blueMarket, // blueMarket
185
+ normalized.assetsToPark, // assetsToPark
186
+ normalized.callbackSalt, // callbackSalt
265
187
  publication?.collateral == null
266
188
  ? emptyMidnightMarket
267
189
  : MarketUtils.toStruct(publication.collateral.market), // market
268
190
  supplies, // collateralSupplies
269
- publication?.ratifier ?? zeroAddress, // ratifier
270
- publication?.root ?? zeroHash, // newRoot
191
+ normalized.ratifier, // ratifier
192
+ normalized.root, // newRoot
271
193
  signature.height, // signatureHeight
272
194
  signature.nonce, // signatureNonce
273
195
  signature.deadline, // signatureDeadline
@@ -275,7 +197,7 @@ export const midnightCancelAndMake = (params) => {
275
197
  signature.r, // r
276
198
  signature.s, // s
277
199
  cancellations, // groupsToCancel
278
- publication?.payload ?? "0x", // payload
200
+ normalized.payload, // payload
279
201
  snapshot.deadline, // deadline
280
202
  nativeFunding.wrappedNative, // wrappedNative
281
203
  ],
@@ -292,9 +214,9 @@ export const midnightCancelAndMake = (params) => {
292
214
  market: publication?.collateral == null
293
215
  ? zeroHash
294
216
  : encodeMidnightMarketId(publication.collateral.market),
295
- ratifier: publication?.ratifier ?? zeroAddress,
296
- root: publication?.root ?? zeroHash,
297
- groups: [...(publication?.groups ?? [])],
217
+ ratifier: normalized.ratifier,
218
+ root: normalized.root,
219
+ groups: normalized.groups,
298
220
  cancellations,
299
221
  collateralSupplies: supplies,
300
222
  ...(blueSupply && { blueSupply }),