@morpho-org/morpho-sdk 9.2.0 → 9.3.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 (44) hide show
  1. package/README.md +4 -4
  2. package/lib/cjs/actions/midnight/index.d.ts +1 -0
  3. package/lib/cjs/actions/midnight/index.js +1 -0
  4. package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +50 -0
  5. package/lib/cjs/actions/midnight/withdrawCollateral.js +105 -0
  6. package/lib/cjs/entities/blue/blue.d.ts +4 -7
  7. package/lib/cjs/entities/blue/blue.js +0 -3
  8. package/lib/cjs/entities/index.d.ts +1 -1
  9. package/lib/cjs/entities/midnight/midnight.d.ts +57 -12
  10. package/lib/cjs/entities/midnight/midnight.js +102 -12
  11. package/lib/cjs/entities/midnight/publication.d.ts +2 -1
  12. package/lib/cjs/entities/midnight/publication.js +44 -64
  13. package/lib/cjs/entities/midnight/types.d.ts +8 -0
  14. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +0 -8
  15. package/lib/cjs/entities/vaultV1/vaultV1.js +0 -4
  16. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +0 -4
  17. package/lib/cjs/entities/vaultV2/vaultV2.js +0 -3
  18. package/lib/cjs/helpers/deadShares.d.ts +5 -4
  19. package/lib/cjs/helpers/deadShares.js +5 -4
  20. package/lib/cjs/types/action.d.ts +10 -1
  21. package/lib/cjs/types/error.d.ts +1 -6
  22. package/lib/cjs/types/error.js +1 -6
  23. package/lib/esm/actions/midnight/index.d.ts +1 -0
  24. package/lib/esm/actions/midnight/index.js +1 -0
  25. package/lib/esm/actions/midnight/withdrawCollateral.d.ts +50 -0
  26. package/lib/esm/actions/midnight/withdrawCollateral.js +101 -0
  27. package/lib/esm/entities/blue/blue.d.ts +4 -7
  28. package/lib/esm/entities/blue/blue.js +0 -3
  29. package/lib/esm/entities/index.d.ts +1 -1
  30. package/lib/esm/entities/midnight/midnight.d.ts +57 -12
  31. package/lib/esm/entities/midnight/midnight.js +104 -14
  32. package/lib/esm/entities/midnight/publication.d.ts +2 -1
  33. package/lib/esm/entities/midnight/publication.js +45 -65
  34. package/lib/esm/entities/midnight/types.d.ts +8 -0
  35. package/lib/esm/entities/vaultV1/vaultV1.d.ts +0 -8
  36. package/lib/esm/entities/vaultV1/vaultV1.js +0 -4
  37. package/lib/esm/entities/vaultV2/vaultV2.d.ts +0 -4
  38. package/lib/esm/entities/vaultV2/vaultV2.js +0 -3
  39. package/lib/esm/helpers/deadShares.d.ts +5 -4
  40. package/lib/esm/helpers/deadShares.js +5 -4
  41. package/lib/esm/types/action.d.ts +10 -1
  42. package/lib/esm/types/error.d.ts +1 -6
  43. package/lib/esm/types/error.js +1 -6
  44. package/package.json +1 -1
@@ -171,6 +171,7 @@ function validateMidnightMakerOfferStates(params) {
171
171
  *
172
172
  * The reader uses a single block for contract reads and returns that block's
173
173
  * timestamp as `now`; oracle code checks use the same block number.
174
+ * Contract reads do not require a Multicall3 deployment or viem chain metadata.
174
175
  *
175
176
  * @internal
176
177
  * @param params.client - Viem client used for state reads.
@@ -180,7 +181,7 @@ function validateMidnightMakerOfferStates(params) {
180
181
  * @returns Per-offer states plus the timestamp of the pinned block.
181
182
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
182
183
  * another chain than `params.chainId`.
183
- * @throws {viem.BaseError} when block, multicall, or oracle-code reads fail.
184
+ * @throws {viem.BaseError} when block, contract, or oracle-code reads fail.
184
185
  * @example
185
186
  * ```ts
186
187
  * const { states, now } = await fetchMidnightMakerOfferStates({
@@ -229,76 +230,55 @@ async function fetchMidnightMakerOfferStates(params) {
229
230
  ])).values(),
230
231
  ];
231
232
  const [marketStates, consumedValues, creditValues, debtValues, defaultFees, lltvEnabledByCollateral, liquidationCursorEnabledByCollateral,] = await Promise.all([
232
- (0, actions_1.multicall)(params.client, {
233
- contracts: markets.map(({ id }) => ({
234
- address: midnight,
235
- abi: midnight_sdk_1.midnightAbi,
236
- functionName: "marketState",
237
- args: [id],
238
- })),
239
- allowFailure: false,
233
+ Promise.all(markets.map(({ id }) => (0, actions_1.readContract)(params.client, {
234
+ address: midnight,
235
+ abi: midnight_sdk_1.midnightAbi,
236
+ functionName: "marketState",
237
+ args: [id],
240
238
  blockNumber,
241
- }),
242
- (0, actions_1.multicall)(params.client, {
243
- contracts: groups.map(({ maker, group }) => ({
244
- address: midnight,
245
- abi: midnight_sdk_1.midnightAbi,
246
- functionName: "consumed",
247
- args: [maker, group],
248
- })),
249
- allowFailure: false,
239
+ }))),
240
+ Promise.all(groups.map(({ maker, group }) => (0, actions_1.readContract)(params.client, {
241
+ address: midnight,
242
+ abi: midnight_sdk_1.midnightAbi,
243
+ functionName: "consumed",
244
+ args: [maker, group],
250
245
  blockNumber,
251
- }),
252
- (0, actions_1.multicall)(params.client, {
253
- contracts: owners.map(({ id, maker }) => ({
254
- address: midnight,
255
- abi: midnight_sdk_1.midnightAbi,
256
- functionName: "credit",
257
- args: [id, maker],
258
- })),
259
- allowFailure: false,
246
+ }))),
247
+ Promise.all(owners.map(({ id, maker }) => (0, actions_1.readContract)(params.client, {
248
+ address: midnight,
249
+ abi: midnight_sdk_1.midnightAbi,
250
+ functionName: "credit",
251
+ args: [id, maker],
260
252
  blockNumber,
261
- }),
262
- (0, actions_1.multicall)(params.client, {
263
- contracts: owners.map(({ id, maker }) => ({
264
- address: midnight,
265
- abi: midnight_sdk_1.midnightAbi,
266
- functionName: "debt",
267
- args: [id, maker],
268
- })),
269
- allowFailure: false,
253
+ }))),
254
+ Promise.all(owners.map(({ id, maker }) => (0, actions_1.readContract)(params.client, {
255
+ address: midnight,
256
+ abi: midnight_sdk_1.midnightAbi,
257
+ functionName: "debt",
258
+ args: [id, maker],
270
259
  blockNumber,
271
- }),
272
- (0, actions_1.multicall)(params.client, {
273
- contracts: defaultFeeTokens.map((loanToken) => ({
274
- address: midnight,
275
- abi: midnight_sdk_1.midnightAbi,
276
- functionName: "defaultContinuousFee",
277
- args: [loanToken],
278
- })),
279
- allowFailure: false,
260
+ }))),
261
+ Promise.all(defaultFeeTokens.map((loanToken) => (0, actions_1.readContract)(params.client, {
262
+ address: midnight,
263
+ abi: midnight_sdk_1.midnightAbi,
264
+ functionName: "defaultContinuousFee",
265
+ args: [loanToken],
280
266
  blockNumber,
281
- }),
282
- (0, actions_1.multicall)(params.client, {
283
- contracts: collaterals.map(({ collateral }) => ({
284
- address: midnight,
285
- abi: midnight_sdk_1.midnightAbi,
286
- functionName: "isLltvEnabled",
287
- args: [collateral.lltv],
288
- })),
289
- allowFailure: false,
267
+ }))),
268
+ Promise.all(collaterals.map(({ collateral }) => (0, actions_1.readContract)(params.client, {
269
+ address: midnight,
270
+ abi: midnight_sdk_1.midnightAbi,
271
+ functionName: "isLltvEnabled",
272
+ args: [collateral.lltv],
290
273
  blockNumber,
291
- }),
292
- (0, actions_1.multicall)(params.client, {
293
- contracts: collaterals.map(({ collateral }) => ({
294
- address: midnight,
295
- abi: midnight_sdk_1.midnightAbi,
296
- functionName: "isLiquidationCursorEnabled",
297
- args: [collateral.liquidationCursor],
298
- })),
299
- allowFailure: false,
274
+ }))),
275
+ Promise.all(collaterals.map(({ collateral }) => (0, actions_1.readContract)(params.client, {
276
+ address: midnight,
277
+ abi: midnight_sdk_1.midnightAbi,
278
+ functionName: "isLiquidationCursorEnabled",
279
+ args: [collateral.liquidationCursor],
300
280
  blockNumber,
301
- }),
281
+ }))),
302
282
  ]);
303
283
  const defaultFeeByLoanToken = new Map(defaultFeeTokens.map((loanToken, index) => [
304
284
  loanToken.toLowerCase(),
@@ -235,6 +235,14 @@ export interface SupplyCollateralParams extends MarketActionParams {
235
235
  readonly reservedCollateralAssets?: bigint;
236
236
  readonly collateralIndex?: bigint;
237
237
  }
238
+ /** Parameters for a direct Midnight collateral withdrawal. */
239
+ export interface WithdrawCollateralParams extends MarketActionParams, MidnightPositionHealthParams {
240
+ readonly collateralIndex?: bigint;
241
+ /** Collateral assets to withdraw; maxUint256 resolves the snapshot's whole balance. */
242
+ readonly assets: bigint;
243
+ /** Defaults to accountAddress. */
244
+ readonly receiver?: Address;
245
+ }
238
246
  /** Parameters for the Midnight redeem flow. */
239
247
  export interface RedeemParams {
240
248
  readonly accountAddress: Address;
@@ -104,10 +104,6 @@ export interface VaultV1Actions {
104
104
  * const tx = action.buildTx(); // For a client configured with supportSignature: false.
105
105
  * // tx satisfies Readonly<Transaction<VaultV1DepositAction>>
106
106
  * ```
107
- * @throws {MissingDeadSharesDataError} when `vaultData` lacks the dead-share, cap or adapter data
108
- * the dead-deposit check needs, such as a hand-built or API-sourced snapshot.
109
- * @throws {InsufficientDeadSharesError} when the vault, or a market or vault it can allocate to,
110
- * holds less than the required dead deposit.
111
107
  */
112
108
  deposit: (params: {
113
109
  readonly userAddress: Address;
@@ -461,10 +457,6 @@ export interface VaultV1Actions {
461
457
  * const tx = migration.buildTx(signatures);
462
458
  * // tx satisfies Readonly<Transaction<VaultV1MigrateToV2Action>>
463
459
  * ```
464
- * @throws {MissingDeadSharesDataError} when `targetVault` lacks the dead-share, cap or adapter data
465
- * the dead-deposit check needs. The source Vault V1 is not checked.
466
- * @throws {InsufficientDeadSharesError} when `targetVault`, or a market or vault it can allocate
467
- * to, holds less than the required dead deposit.
468
460
  */
469
461
  migrateToV2: (params: {
470
462
  readonly userAddress: Address;
@@ -9,7 +9,6 @@ const actions_1 = require("viem/actions");
9
9
  const common_js_1 = require("../../actions/bundles/common.js");
10
10
  const index_js_1 = require("../../actions/index.js");
11
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
- const deadShares_js_1 = require("../../helpers/deadShares.js");
13
12
  const index_js_2 = require("../../helpers/index.js");
14
13
  const validate_js_1 = require("../../helpers/validate.js");
15
14
  const index_js_3 = require("../../types/index.js");
@@ -79,8 +78,6 @@ class MorphoVaultV1 {
79
78
  // The native path must target the chain's registered wrapped-native asset.
80
79
  (0, validate_js_1.validateNativeVaultAsset)(this.chainId, vaultAsset);
81
80
  }
82
- // Throws when the vault, or a market it can allocate to, lacks a sufficient dead deposit.
83
- (0, deadShares_js_1.validateVaultV1DeadShares)(vaultData);
84
81
  const referralFeeAssets = (0, common_js_1.getBundlesReferralFeeAssets)(funding.assets, common.referralFeePct);
85
82
  const maxSharePrice = (0, index_js_2.computeVaultMaxSharePrice)({
86
83
  vaultData,
@@ -476,7 +473,6 @@ class MorphoVaultV1 {
476
473
  referralFeeRecipient: params.referralFeeRecipient,
477
474
  });
478
475
  // Only the destination receives a deposit; the source vault is an exit.
479
- (0, deadShares_js_1.validateVaultV2DeadShares)(params.targetVault);
480
476
  // V1 redeem accrues market interest and performance fees before converting shares.
481
477
  const grossAssets = assets ??
482
478
  params.sourceVault
@@ -110,10 +110,6 @@ export interface VaultV2Actions {
110
110
  * const tx = action.buildTx(); // For a client configured with supportSignature: false.
111
111
  * // tx satisfies Readonly<Transaction<VaultV2DepositAction>>
112
112
  * ```
113
- * @throws {MissingDeadSharesDataError} when `vaultData` lacks the dead-share, cap or adapter data
114
- * the dead-deposit check needs, such as a hand-built or API-sourced snapshot.
115
- * @throws {InsufficientDeadSharesError} when the vault, or a market or vault it can allocate to,
116
- * holds less than the required dead deposit.
117
113
  */
118
114
  deposit: (params: {
119
115
  readonly userAddress: Address;
@@ -9,7 +9,6 @@ const actions_1 = require("viem/actions");
9
9
  const common_js_1 = require("../../actions/bundles/common.js");
10
10
  const index_js_1 = require("../../actions/index.js");
11
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
- const deadShares_js_1 = require("../../helpers/deadShares.js");
13
12
  const index_js_2 = require("../../helpers/index.js");
14
13
  const validate_js_1 = require("../../helpers/validate.js");
15
14
  const index_js_3 = require("../../types/index.js");
@@ -82,8 +81,6 @@ class MorphoVaultV2 {
82
81
  // The native path must target the chain's registered wrapped-native asset.
83
82
  (0, validate_js_1.validateNativeVaultAsset)(this.chainId, vaultAsset);
84
83
  }
85
- // Throws when the vault, or a market it can allocate to, lacks a sufficient dead deposit.
86
- (0, deadShares_js_1.validateVaultV2DeadShares)(vaultData);
87
84
  const referralFeeAssets = (0, common_js_1.getBundlesReferralFeeAssets)(funding.assets, common.referralFeePct);
88
85
  const maxSharePrice = (0, index_js_2.computeVaultMaxSharePrice)({
89
86
  vaultData,
@@ -55,15 +55,16 @@ export declare function validateVaultV1DeadShares(vault: AccrualVault, path?: De
55
55
  /**
56
56
  * Checks a Vault V2 against the dead-deposit rule: at least `MIN_DEAD_SHARES` shares at
57
57
  * `DEAD_ADDRESS` worth at least `MIN_VAULT_V2_DEAD_ASSETS` assets, a share price above
58
- * `1 / (10 * virtualShares)`, and every Blue market or Vault V1 it can allocate to (non-zero
59
- * absolute cap) passing its own rule. Zero-cap entries are skipped.
58
+ * `1 / (10 * virtualShares)`, and each currently allocated Blue market or Vault V1 with a non-zero
59
+ * absolute cap passing its own rule. A market with a positive cap but no current allocation is not
60
+ * checked; a later reallocation can reach it.
60
61
  *
61
62
  * @param vault - Fetched vault snapshot with its adapters and `absoluteCaps`.
62
63
  * @param path - Vaults leading to this vault, outermost first; empty for a direct deposit.
63
- * @returns Nothing; returns normally when the vault and everything it can allocate to pass.
64
+ * @returns Nothing; returns normally when the vault and its checked allocations pass.
64
65
  * @throws {MissingDeadSharesDataError} when a dead-share field, an adapter cap, or the data of an
65
66
  * adapter the SDK cannot hydrate is missing.
66
- * @throws {InsufficientDeadSharesError} when the vault or an allocatable market or Vault V1 fails the rule.
67
+ * @throws {InsufficientDeadSharesError} when the vault or a checked market or Vault V1 fails the rule.
67
68
  * @example
68
69
  * ```ts
69
70
  * import { validateVaultV2DeadShares } from "@morpho-org/morpho-sdk";
@@ -89,15 +89,16 @@ function validateVaultV1DeadShares(vault, path = []) {
89
89
  /**
90
90
  * Checks a Vault V2 against the dead-deposit rule: at least `MIN_DEAD_SHARES` shares at
91
91
  * `DEAD_ADDRESS` worth at least `MIN_VAULT_V2_DEAD_ASSETS` assets, a share price above
92
- * `1 / (10 * virtualShares)`, and every Blue market or Vault V1 it can allocate to (non-zero
93
- * absolute cap) passing its own rule. Zero-cap entries are skipped.
92
+ * `1 / (10 * virtualShares)`, and each currently allocated Blue market or Vault V1 with a non-zero
93
+ * absolute cap passing its own rule. A market with a positive cap but no current allocation is not
94
+ * checked; a later reallocation can reach it.
94
95
  *
95
96
  * @param vault - Fetched vault snapshot with its adapters and `absoluteCaps`.
96
97
  * @param path - Vaults leading to this vault, outermost first; empty for a direct deposit.
97
- * @returns Nothing; returns normally when the vault and everything it can allocate to pass.
98
+ * @returns Nothing; returns normally when the vault and its checked allocations pass.
98
99
  * @throws {MissingDeadSharesDataError} when a dead-share field, an adapter cap, or the data of an
99
100
  * adapter the SDK cannot hydrate is missing.
100
- * @throws {InsufficientDeadSharesError} when the vault or an allocatable market or Vault V1 fails the rule.
101
+ * @throws {InsufficientDeadSharesError} when the vault or a checked market or Vault V1 fails the rule.
101
102
  * @example
102
103
  * ```ts
103
104
  * import { validateVaultV2DeadShares } from "@morpho-org/morpho-sdk";
@@ -435,6 +435,15 @@ export interface MidnightSupplyCollateralAction extends BaseAction<"midnightSupp
435
435
  readonly onBehalf: Address;
436
436
  }> {
437
437
  }
438
+ /** Metadata for a direct Midnight collateral withdrawal transaction. */
439
+ export interface MidnightWithdrawCollateralAction extends BaseAction<"midnightWithdrawCollateral", {
440
+ readonly market: Hex;
441
+ readonly collateralIndex: bigint;
442
+ readonly assets: bigint;
443
+ readonly onBehalf: Address;
444
+ readonly receiver: Address;
445
+ }> {
446
+ }
438
447
  /** Metadata for a direct Midnight credit redemption transaction. */
439
448
  export interface MidnightRedeemAction extends BaseAction<"midnightRedeem", {
440
449
  readonly market: Hex;
@@ -501,7 +510,7 @@ export interface MidnightCancelAndMakeAction extends BaseAction<"midnightCancelA
501
510
  * VaultV2, Blue, and Midnight flows. The `type` tag discriminates the union so
502
511
  * consumers can `switch` exhaustively on it.
503
512
  */
504
- export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2InKindRedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1InKindRedeemAction | VaultV1MigrateToV2Action | BlueSupplyAction | BlueSupplyCollateralAction | BlueBorrowAction | BlueSupplyCollateralBorrowAction | BlueRepayAction | BlueWithdrawCollateralAction | BlueRepayWithdrawCollateralAction | BlueWithdrawAction | BlueRefinanceAction | BlueAuthorizationAction | MidnightAuthorizationAction | MidnightTakeLendAction | MidnightTakeBorrowAction | MidnightTakeWithdrawAction | MidnightSupplyCollateralTakeBorrowAction | MidnightSupplyCollateralAction | MidnightRedeemAction | MidnightTakeRepayWithdrawCollateralAction | MidnightRepayWithdrawCollateralAction | MidnightCancelAndMakeAction;
513
+ export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2InKindRedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1InKindRedeemAction | VaultV1MigrateToV2Action | BlueSupplyAction | BlueSupplyCollateralAction | BlueBorrowAction | BlueSupplyCollateralBorrowAction | BlueRepayAction | BlueWithdrawCollateralAction | BlueRepayWithdrawCollateralAction | BlueWithdrawAction | BlueRefinanceAction | BlueAuthorizationAction | MidnightAuthorizationAction | MidnightTakeLendAction | MidnightTakeBorrowAction | MidnightTakeWithdrawAction | MidnightSupplyCollateralTakeBorrowAction | MidnightSupplyCollateralAction | MidnightWithdrawCollateralAction | MidnightRedeemAction | MidnightTakeRepayWithdrawCollateralAction | MidnightRepayWithdrawCollateralAction | MidnightCancelAndMakeAction;
505
514
  /**
506
515
  * Describes a single, immutable, deep-frozen transaction to submit on-chain:
507
516
  * the target `to`, native `value`, encoded call `data`, and the originating
@@ -1321,12 +1321,7 @@ export declare class MidnightOfferCallbackDataMismatchError extends Error {
1321
1321
  readonly actualCallbackData: Hex;
1322
1322
  });
1323
1323
  }
1324
- /**
1325
- * Thrown when loan assets would be parked in a Morpho Blue market with no existing supply.
1326
- *
1327
- * @deprecated `supplyBlueMakeLend` now throws `InsufficientDeadSharesError` or
1328
- * `MissingDeadSharesDataError` instead; kept exported so existing `instanceof` checks compile.
1329
- */
1324
+ /** Thrown when loan assets would be parked in a Morpho Blue market with no existing supply. */
1330
1325
  export declare class EmptyBlueParkingMarketError extends Error {
1331
1326
  constructor(params: {
1332
1327
  readonly marketId: MarketId;
@@ -1694,12 +1694,7 @@ class MidnightOfferCallbackDataMismatchError extends Error {
1694
1694
  }
1695
1695
  }
1696
1696
  exports.MidnightOfferCallbackDataMismatchError = MidnightOfferCallbackDataMismatchError;
1697
- /**
1698
- * Thrown when loan assets would be parked in a Morpho Blue market with no existing supply.
1699
- *
1700
- * @deprecated `supplyBlueMakeLend` now throws `InsufficientDeadSharesError` or
1701
- * `MissingDeadSharesDataError` instead; kept exported so existing `instanceof` checks compile.
1702
- */
1697
+ /** Thrown when loan assets would be parked in a Morpho Blue market with no existing supply. */
1703
1698
  class EmptyBlueParkingMarketError extends Error {
1704
1699
  constructor(params) {
1705
1700
  super(`Morpho Blue market "${params.marketId}" has no supply shares. Parking assets in an empty market is exposed to supply-share-price inflation; choose a market with existing supply.`);
@@ -9,3 +9,4 @@ export * from "./takeLend.js";
9
9
  export * from "./takeRepayWithdrawCollateral.js";
10
10
  export * from "./takeWithdraw.js";
11
11
  export * from "./types.js";
12
+ export * from "./withdrawCollateral.js";
@@ -9,3 +9,4 @@ export * from "./takeLend.js";
9
9
  export * from "./takeRepayWithdrawCollateral.js";
10
10
  export * from "./takeWithdraw.js";
11
11
  export * from "./types.js";
12
+ export * from "./withdrawCollateral.js";
@@ -0,0 +1,50 @@
1
+ import { type MarketInput } from "@morpho-org/midnight-sdk";
2
+ import { type Address } from "viem";
3
+ import { type Metadata, type MidnightWithdrawCollateralAction, type Transaction } from "../../types/index.js";
4
+ /** Parameters for encoding a direct Midnight collateral withdrawal. */
5
+ export interface MidnightWithdrawCollateralParams {
6
+ readonly chainId: number;
7
+ readonly market: MarketInput;
8
+ readonly collateralIndex?: bigint;
9
+ readonly assets: bigint;
10
+ readonly onBehalf: Address;
11
+ readonly receiver: Address;
12
+ readonly metadata?: Metadata;
13
+ }
14
+ /**
15
+ * Encodes a direct Midnight collateral withdrawal.
16
+ *
17
+ * This builder reads no position state. Prefer the entity method for balance and health checks.
18
+ *
19
+ * @param params.chainId - Chain id used to resolve `Midnight`.
20
+ * @param params.market - Midnight market from which collateral is withdrawn.
21
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
22
+ * @param params.assets - Collateral assets to withdraw.
23
+ * @param params.onBehalf - Collateral owner; the sender must be this account or its authorized operator.
24
+ * @param params.receiver - Account receiving withdrawn collateral.
25
+ * @param params.metadata - Optional analytics metadata appended to calldata.
26
+ * @returns A deep-frozen `Transaction<MidnightWithdrawCollateralAction>` targeting `Midnight`.
27
+ * @throws {MidnightZeroReceiverError} when receiver is zero.
28
+ * @throws {MidnightContractReceiverError} when receiver cannot safely receive collateral.
29
+ * @throws {NonPositiveInputError} when `assets <= 0n`.
30
+ * @throws {InputExceedsMaxError} when `assets` exceeds `uint128`.
31
+ * @throws {MidnightZeroOnBehalfError} when `onBehalf` is the zero address.
32
+ * @throws {ChainIdMismatchError} when the market targets another chain.
33
+ * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
34
+ * @throws {UnknownCollateralIndexError} when `collateralIndex` is not configured on the market.
35
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
36
+ * @example
37
+ * ```ts
38
+ * import { midnightWithdrawCollateral } from "@morpho-org/morpho-sdk";
39
+ *
40
+ * const tx = midnightWithdrawCollateral({
41
+ * chainId: 8453,
42
+ * market: marketData.params,
43
+ * collateralIndex: 0n,
44
+ * assets: 2_000_000n,
45
+ * onBehalf: user,
46
+ * receiver: user,
47
+ * });
48
+ * ```
49
+ */
50
+ export declare const midnightWithdrawCollateral: (params: MidnightWithdrawCollateralParams) => Readonly<Transaction<MidnightWithdrawCollateralAction>>;
@@ -0,0 +1,101 @@
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 { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
9
+ import { validateMidnightReceiver } from "../../helpers/validateMidnightReceiver.js";
10
+ import { MidnightZeroOnBehalfError, NonPositiveInputError, } from "../../types/index.js";
11
+ /**
12
+ * Encodes a direct Midnight collateral withdrawal.
13
+ *
14
+ * This builder reads no position state. Prefer the entity method for balance and health checks.
15
+ *
16
+ * @param params.chainId - Chain id used to resolve `Midnight`.
17
+ * @param params.market - Midnight market from which collateral is withdrawn.
18
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
19
+ * @param params.assets - Collateral assets to withdraw.
20
+ * @param params.onBehalf - Collateral owner; the sender must be this account or its authorized operator.
21
+ * @param params.receiver - Account receiving withdrawn collateral.
22
+ * @param params.metadata - Optional analytics metadata appended to calldata.
23
+ * @returns A deep-frozen `Transaction<MidnightWithdrawCollateralAction>` targeting `Midnight`.
24
+ * @throws {MidnightZeroReceiverError} when receiver is zero.
25
+ * @throws {MidnightContractReceiverError} when receiver cannot safely receive collateral.
26
+ * @throws {NonPositiveInputError} when `assets <= 0n`.
27
+ * @throws {InputExceedsMaxError} when `assets` exceeds `uint128`.
28
+ * @throws {MidnightZeroOnBehalfError} when `onBehalf` is the zero address.
29
+ * @throws {ChainIdMismatchError} when the market targets another chain.
30
+ * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
31
+ * @throws {UnknownCollateralIndexError} when `collateralIndex` is not configured on the market.
32
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
33
+ * @example
34
+ * ```ts
35
+ * import { midnightWithdrawCollateral } from "@morpho-org/morpho-sdk";
36
+ *
37
+ * const tx = midnightWithdrawCollateral({
38
+ * chainId: 8453,
39
+ * market: marketData.params,
40
+ * collateralIndex: 0n,
41
+ * assets: 2_000_000n,
42
+ * onBehalf: user,
43
+ * receiver: user,
44
+ * });
45
+ * ```
46
+ */
47
+ export const midnightWithdrawCollateral = (params) => {
48
+ // Reject a malformed account before comparing it with the zero address.
49
+ validateMidnightAddress("onBehalf", params.onBehalf);
50
+ if (params.assets <= 0n) {
51
+ throw new NonPositiveInputError("assets", params.assets);
52
+ }
53
+ validateMidnightUint128Field("assets", params.assets);
54
+ if (isAddressEqual(params.onBehalf, zeroAddress)) {
55
+ throw new MidnightZeroOnBehalfError("onBehalf");
56
+ }
57
+ // Reject markets from another chain deployment before encoding the call.
58
+ validateMidnightMarket({ market: params.market, chainId: params.chainId });
59
+ const marketId = encodeMidnightMarketId(params.market);
60
+ const midnight = getChainAddress(params.chainId, "midnight");
61
+ const collateralIndex = params.collateralIndex ?? 0n;
62
+ // Validate that the supplied collateral index is configured before encoding.
63
+ MarketUtils.getCollateralByIndex(params.market, collateralIndex);
64
+ validateMidnightReceiver({
65
+ chainId: params.chainId,
66
+ market: params.market,
67
+ field: "receiver",
68
+ receiver: params.receiver,
69
+ });
70
+ let tx = {
71
+ to: midnight,
72
+ value: 0n,
73
+ data: encodeMidnightCalldata({
74
+ abi: midnightAbi,
75
+ functionName: "withdrawCollateral",
76
+ args: [
77
+ MarketUtils.toStruct(params.market),
78
+ collateralIndex,
79
+ params.assets,
80
+ params.onBehalf,
81
+ params.receiver,
82
+ ],
83
+ }),
84
+ };
85
+ if (params.metadata) {
86
+ tx = addTransactionMetadata(tx, params.metadata);
87
+ }
88
+ return deepFreeze({
89
+ ...tx,
90
+ action: {
91
+ type: "midnightWithdrawCollateral",
92
+ args: {
93
+ market: marketId,
94
+ collateralIndex,
95
+ assets: params.assets,
96
+ onBehalf: params.onBehalf,
97
+ receiver: params.receiver,
98
+ },
99
+ },
100
+ });
101
+ };
@@ -151,7 +151,8 @@ export interface BlueActions {
151
151
  *
152
152
  * @param params.userAddress - User funding and receiving the supply position.
153
153
  * @param params.marketData - Snapshot of this market from `getMarketData()` (or `fetchMarket` in
154
- * `@morpho-org/blue-sdk-viem`), used to check its dead deposit before building.
154
+ * `@morpho-org/blue-sdk-viem`), checked only for `MarketIdMismatchError`. To check the dead-deposit
155
+ * rule, call `validateBlueMarketDeadShares` on the snapshot yourself before building.
155
156
  * @param params.assets - Gross loan-token assets funded before the referral fee.
156
157
  * @param params.nativeAmount - Optional full native funding; must equal `assets` and requires wNative.
157
158
  * @param params.deadline - Final call deadline in Unix seconds.
@@ -180,8 +181,6 @@ export interface BlueActions {
180
181
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
181
182
  * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
182
183
  * @throws {MarketIdMismatchError} when `marketData` belongs to another market.
183
- * @throws {MissingDeadSharesDataError} when `marketData` has no `deadSupplyShares`.
184
- * @throws {InsufficientDeadSharesError} when the market holds fewer than `MIN_DEAD_SHARES` supply shares at `DEAD_ADDRESS`.
185
184
  * @throws {UnknownTokenError} from `getRequirements()` when the funded token's `decimals()` is unusable.
186
185
  * @throws {MalformedTokenMetadataError} when the token's `eip712Domain()` or
187
186
  * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
@@ -223,8 +222,7 @@ export interface BlueActions {
223
222
  readonly referralFeeRecipient?: Address;
224
223
  }): ActionOutput<BlueSupplyAction, readonly RequirementSignature[], BlueTokenRequirementsParams>;
225
224
  /**
226
- * @deprecated Pass `marketData` from `getMarketData()` to check the dead deposit.
227
- * Snapshot-free supply is unprotected and will be removed in the next major after one minor.
225
+ * @deprecated Pass `marketData` from `getMarketData()`; the snapshot-free overload is removed in the next major.
228
226
  */
229
227
  (params: {
230
228
  readonly userAddress: Address;
@@ -1002,8 +1000,7 @@ export declare class MorphoBlue implements BlueActions {
1002
1000
  readonly referralFeeRecipient?: Address;
1003
1001
  }): ActionOutput<BlueSupplyAction, readonly RequirementSignature[], BlueTokenRequirementsParams>;
1004
1002
  /**
1005
- * @deprecated Pass `marketData` from `getMarketData()` to check the dead deposit.
1006
- * Snapshot-free supply is unprotected and will be removed in the next major after one minor.
1003
+ * @deprecated Pass `marketData` from `getMarketData()`; the snapshot-free overload is removed in the next major.
1007
1004
  */
1008
1005
  supply(params: {
1009
1006
  readonly userAddress: Address;
@@ -6,7 +6,6 @@ import { readContract } from "viem/actions";
6
6
  import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBlueBundlesV1ReferralFeeAssets, normalizeBlueBundlesV1CommonParams, selectBlueBundlesV1RequirementSignatures, validateBlueBundlesV1NativeFunding, } from "../../actions/blue/common.js";
7
7
  import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawCollateral, getBlueAuthorizationRequirement, } from "../../actions/index.js";
8
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
- import { validateBlueMarketDeadShares } from "../../helpers/deadShares.js";
10
9
  import { DEFAULT_LLTV_BUFFER, validateAccrualPosition, validateChainId, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
11
10
  import { validateMarketParamsId } from "../../helpers/validate.js";
12
11
  import { ExpiredDeadlineError, InputExceedsMaxError, MarketIdMismatchError, MaxRepayAssetsBelowRepayAssetsError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, ReallocationsRequireBorrowError, RefinanceSameMarketError, RefinanceTokenMismatchError, } from "../../types/index.js";
@@ -141,8 +140,6 @@ export class MorphoBlue {
141
140
  if (params.marketData.id !== this.marketParams.id) {
142
141
  throw new MarketIdMismatchError(params.marketData.id, this.marketParams.id);
143
142
  }
144
- // Throws when the market lacks a sufficient dead deposit; nothing to return.
145
- validateBlueMarketDeadShares(params.marketData);
146
143
  }
147
144
  return {
148
145
  getRequirements: (requirementsParams) => {
@@ -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, } 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, 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";
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";