@morpho-org/morpho-sdk 6.0.0-next.4 → 6.1.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 (121) hide show
  1. package/MIGRATION-v5-to-v6.md +21 -15
  2. package/README.md +7 -5
  3. package/lib/cjs/abis.d.ts +1 -1
  4. package/lib/cjs/abis.js +3 -1
  5. package/lib/cjs/actions/bundles/common.d.ts +18 -23
  6. package/lib/cjs/actions/bundles/common.js +36 -83
  7. package/lib/cjs/actions/bundles/index.d.ts +1 -1
  8. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +6 -2
  9. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +6 -2
  10. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +1 -0
  11. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -0
  12. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +11 -3
  13. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +19 -1
  14. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -1
  15. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +12 -0
  16. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +62 -17
  17. package/lib/cjs/actions/vaultV1/migrateToV2.js +48 -17
  18. package/lib/cjs/actions/vaultV1/redeem.d.ts +28 -1
  19. package/lib/cjs/actions/vaultV1/redeem.js +17 -1
  20. package/lib/cjs/actions/vaultV1/withdraw.d.ts +1 -1
  21. package/lib/cjs/actions/vaultV1/withdraw.js +1 -1
  22. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +19 -7
  23. package/lib/cjs/actions/vaultV2/forceWithdraw.js +19 -7
  24. package/lib/cjs/actions/vaultV2/redeem.d.ts +28 -1
  25. package/lib/cjs/actions/vaultV2/redeem.js +17 -1
  26. package/lib/cjs/actions/vaultV2/withdraw.d.ts +1 -1
  27. package/lib/cjs/actions/vaultV2/withdraw.js +1 -1
  28. package/lib/cjs/constants.d.ts +1 -1
  29. package/lib/cjs/constants.js +4 -1
  30. package/lib/cjs/entities/blue/blue.d.ts +28 -0
  31. package/lib/cjs/entities/blue/blue.js +1 -0
  32. package/lib/cjs/entities/index.d.ts +1 -1
  33. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +38 -22
  34. package/lib/cjs/entities/vaultV1/vaultV1.js +51 -84
  35. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +68 -35
  36. package/lib/cjs/entities/vaultV2/vaultV2.js +45 -72
  37. package/lib/cjs/errors.d.ts +1 -1
  38. package/lib/cjs/errors.js +8 -1
  39. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.d.ts +10 -6
  40. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +10 -6
  41. package/lib/cjs/helpers/slippage.d.ts +3 -2
  42. package/lib/cjs/helpers/slippage.js +3 -2
  43. package/lib/cjs/helpers/validate.d.ts +40 -0
  44. package/lib/cjs/helpers/validate.js +40 -0
  45. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.d.ts +94 -59
  46. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +94 -59
  47. package/lib/cjs/midnight/abis.d.ts +1 -1
  48. package/lib/cjs/midnight/abis.js +3 -1
  49. package/lib/cjs/midnight/constants.d.ts +1 -1
  50. package/lib/cjs/midnight/constants.js +4 -1
  51. package/lib/cjs/midnight/entities.d.ts +1 -1
  52. package/lib/cjs/midnight/errors.d.ts +1 -1
  53. package/lib/cjs/midnight/errors.js +7 -1
  54. package/lib/cjs/midnight/types.d.ts +1 -1
  55. package/lib/cjs/midnight/utils.d.ts +11 -1
  56. package/lib/cjs/midnight/utils.js +13 -1
  57. package/lib/cjs/types/action.d.ts +35 -0
  58. package/lib/cjs/types/action.js +10 -0
  59. package/lib/cjs/types.d.ts +1 -1
  60. package/lib/cjs/utils.d.ts +11 -1
  61. package/lib/cjs/utils.js +14 -2
  62. package/lib/esm/abis.d.ts +1 -1
  63. package/lib/esm/abis.js +1 -1
  64. package/lib/esm/actions/bundles/common.d.ts +18 -23
  65. package/lib/esm/actions/bundles/common.js +34 -80
  66. package/lib/esm/actions/bundles/index.d.ts +1 -1
  67. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +6 -2
  68. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +6 -2
  69. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +1 -0
  70. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -0
  71. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +11 -3
  72. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +21 -3
  73. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -1
  74. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +14 -2
  75. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +62 -17
  76. package/lib/esm/actions/vaultV1/migrateToV2.js +48 -17
  77. package/lib/esm/actions/vaultV1/redeem.d.ts +28 -1
  78. package/lib/esm/actions/vaultV1/redeem.js +17 -1
  79. package/lib/esm/actions/vaultV1/withdraw.d.ts +1 -1
  80. package/lib/esm/actions/vaultV1/withdraw.js +1 -1
  81. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +19 -7
  82. package/lib/esm/actions/vaultV2/forceWithdraw.js +19 -7
  83. package/lib/esm/actions/vaultV2/redeem.d.ts +28 -1
  84. package/lib/esm/actions/vaultV2/redeem.js +17 -1
  85. package/lib/esm/actions/vaultV2/withdraw.d.ts +1 -1
  86. package/lib/esm/actions/vaultV2/withdraw.js +1 -1
  87. package/lib/esm/constants.d.ts +1 -1
  88. package/lib/esm/constants.js +1 -1
  89. package/lib/esm/entities/blue/blue.d.ts +28 -0
  90. package/lib/esm/entities/blue/blue.js +1 -0
  91. package/lib/esm/entities/index.d.ts +1 -1
  92. package/lib/esm/entities/vaultV1/vaultV1.d.ts +38 -22
  93. package/lib/esm/entities/vaultV1/vaultV1.js +53 -86
  94. package/lib/esm/entities/vaultV2/vaultV2.d.ts +68 -35
  95. package/lib/esm/entities/vaultV2/vaultV2.js +47 -74
  96. package/lib/esm/errors.d.ts +1 -1
  97. package/lib/esm/errors.js +1 -1
  98. package/lib/esm/helpers/previewVaultV2ForceWithdraw.d.ts +10 -6
  99. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +10 -6
  100. package/lib/esm/helpers/slippage.d.ts +3 -2
  101. package/lib/esm/helpers/slippage.js +3 -2
  102. package/lib/esm/helpers/validate.d.ts +40 -0
  103. package/lib/esm/helpers/validate.js +40 -0
  104. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.d.ts +94 -59
  105. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +94 -59
  106. package/lib/esm/midnight/abis.d.ts +1 -1
  107. package/lib/esm/midnight/abis.js +1 -1
  108. package/lib/esm/midnight/constants.d.ts +1 -1
  109. package/lib/esm/midnight/constants.js +1 -1
  110. package/lib/esm/midnight/entities.d.ts +1 -1
  111. package/lib/esm/midnight/errors.d.ts +1 -1
  112. package/lib/esm/midnight/errors.js +1 -1
  113. package/lib/esm/midnight/types.d.ts +1 -1
  114. package/lib/esm/midnight/utils.d.ts +11 -1
  115. package/lib/esm/midnight/utils.js +11 -1
  116. package/lib/esm/types/action.d.ts +35 -0
  117. package/lib/esm/types/action.js +10 -0
  118. package/lib/esm/types.d.ts +1 -1
  119. package/lib/esm/utils.d.ts +11 -1
  120. package/lib/esm/utils.js +11 -1
  121. package/package.json +5 -5
@@ -3,14 +3,24 @@ import { fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
3
  import { type Address } from "viem";
4
4
  import type { FetchParameters } from "../../types/data.js";
5
5
  import { type ActionOutput, type ActionRequirement, type BundlesFundingArgs, type BundlesTokenRequirementsOptions, type Deallocation, type MorphoClientType, type RequirementSignature, type Transaction, type VaultV2DepositAction, type VaultV2ForceRedeemAction, type VaultV2ForceWithdrawAction, type VaultV2InKindRedeemAction, type VaultV2RedeemAction, type VaultV2WithdrawAction } from "../../types/index.js";
6
+ /**
7
+ * Action surface for Vault V2 reads and writes; writes route through VaultBundlesV1 and
8
+ * VaultExitBundlesV1, except `forceRedeem`, which uses the vault's native multicall.
9
+ */
6
10
  export interface VaultV2Actions {
7
11
  /**
8
- * Fetches the latest vault data.
12
+ * Fetches the latest accrual snapshot of the vault.
9
13
  *
10
- * This function fetches the latest vault data from the blockchain.
11
- * @param {FetchParameters} [parameters] - The parameters for the fetch operation.
14
+ * Reads the Vault V2 state through `fetchAccrualVaultV2` on the entity's client.
12
15
  *
13
- * @returns {Promise<Awaited<ReturnType<typeof fetchAccrualVaultV2>>>} The latest vault data.
16
+ * @param parameters - Optional viem fetch parameters (block number, block tag, state override).
17
+ * @returns The hydrated `AccrualVaultV2` snapshot.
18
+ * @throws {ChainIdMismatchError} when the connected client targets another chain or has no chain.
19
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
20
+ * @throws {UnknownBlueFactory} when the configured chain has no VaultV2 factory.
21
+ * @throws {UnknownBlueOfFactory} when the vault is not a VaultV2 from the configured factory.
22
+ * @throws {UnsupportedBlueVaultV2AdapterError} when the vault or one of its adapters uses an
23
+ * unsupported adapter class.
14
24
  */
15
25
  getData: (parameters?: FetchParameters) => Promise<Awaited<ReturnType<typeof fetchAccrualVaultV2>>>;
16
26
  /**
@@ -21,7 +31,7 @@ export interface VaultV2Actions {
21
31
  * Permit2 nonce state. Native funding is exclusive and skips token requirements. Shares are
22
32
  * always minted to the transaction sender, which must be `userAddress`.
23
33
  * Concurrent requirement reads share the first caller's options; later calls refresh on-chain
24
- * state using their own options. `buildTx()` accepts signatures from the latest completed read.
34
+ * state using their own options.
25
35
  *
26
36
  * @param params.userAddress - Account that funds, signs, submits, and receives the vault shares.
27
37
  * @param params.vaultData - Pre-fetched Vault V2 snapshot used for asset and share conversion.
@@ -57,8 +67,9 @@ export interface VaultV2Actions {
57
67
  * `getRequirements()` when the Permit2 nonce exceeds uint256.
58
68
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
59
69
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
60
- * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature was not produced for
61
- * this prepared handle.
70
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
71
+ * deadline differ from this operation's, or when the signature's carried action nonce is
72
+ * inconsistent with its signed nonce.
62
73
  * @throws {DepositOwnerMismatchError} from `buildTx()` when the signed owner differs from `userAddress`.
63
74
  * @throws {DepositAssetMismatchError} from `buildTx()` when the signed asset differs from the vault asset.
64
75
  * @throws {BundlesRequirementSignatureMismatchError} from `buildTx()` when signature metadata is malformed.
@@ -98,13 +109,14 @@ export interface VaultV2Actions {
98
109
  /**
99
110
  * Prepares an exact-assets Vault V2 withdrawal through VaultBundlesV1.
100
111
  *
101
- * Reads the vault accrual state on the first `getRequirements()` call, then reads the live
102
- * vault-share allowance and, when a signature is needed, the permit nonce on each call.
103
- * Captures the requested amount and owner at creation, so later changes to `params` do not
104
- * change this handle's requirements or transaction.
112
+ * Derives the share-burn cap from the supplied `vaultData` snapshot at handle creation, then
113
+ * reads the live vault-share allowance and, when a signature is needed, the permit nonce on
114
+ * each `getRequirements()` call. Captures the requested amount and owner at creation, so later
115
+ * changes to `params` do not change this handle's requirements or transaction.
105
116
  *
106
117
  * @param params.amount - Positive gross withdrawal in underlying asset base units, before fees.
107
118
  * @param params.userAddress - Share owner that must sign and submit; receives the net assets.
119
+ * @param params.vaultData - Pre-fetched Vault V2 snapshot used to derive the share cap.
108
120
  * @param params.slippageTolerance - Optional WAD-scaled share-price loss tolerance applied to
109
121
  * the share cap.
110
122
  * Defaults to 0.03% and cannot exceed 10%.
@@ -117,8 +129,11 @@ export interface VaultV2Actions {
117
129
  * which returns a deep-frozen `Transaction<VaultV2WithdrawAction>`. Requirements are empty
118
130
  * when the allowance equals the cap; an oversized allowance is always reset with an exact
119
131
  * onchain approval, and an insufficient one is raised by an approval or, with signature
120
- * support, an ERC-2612 request. The cap stays pinned to the first resolution while each call
121
- * re-reads the allowance. Confirm the approval or pass its signed permit to `buildTx`.
132
+ * support, an ERC-2612 request. The cap is fixed at handle creation while each call re-reads
133
+ * the allowance. Confirm the approval or pass its signed permit to `buildTx`.
134
+ * @remarks VaultBundlesV1 skips a share permit whose nonce was already consumed and proceeds
135
+ * under the live allowance, so execute every requirement returned by the latest
136
+ * `getRequirements()` — including the oversized-allowance reset — before submitting.
122
137
  * @throws {ChainIdMismatchError} when the connected client targets another chain.
123
138
  * @throws {NonPositiveInputError} when `amount` or the computed share cap is not positive.
124
139
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
@@ -128,14 +143,14 @@ export interface VaultV2Actions {
128
143
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
129
144
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no nonzero recipient.
130
145
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds 10%.
146
+ * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
131
147
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
132
148
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
133
149
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
134
150
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple permits are supplied.
135
- * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed,
136
- * was not resolved for this handle, or has incompatible vault, owner, spender, amount,
137
- * deadline, or nonce values.
138
- * @throws {viem.BaseError} when a vault, allowance, or nonce read or transaction encoding fails.
151
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed or
152
+ * its spender, amount or deadline differ from this operation's.
153
+ * @throws {viem.BaseError} when an allowance or nonce read or transaction encoding fails.
139
154
  * @example
140
155
  * ```ts
141
156
  * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
@@ -147,7 +162,8 @@ export interface VaultV2Actions {
147
162
  * const client = createPublicClient({ chain: mainnet, transport: http() })
148
163
  * .extend(morphoViemExtension({ supportSignature: false }));
149
164
  * const vault = client.morpho.vaultV2(vaultAddress, mainnet.id);
150
- * const action = vault.withdraw({ amount: 1_000_000n, userAddress });
165
+ * const vaultData = await vault.getData();
166
+ * const action = vault.withdraw({ amount: 1_000_000n, userAddress, vaultData });
151
167
  * const requirements = await action.getRequirements();
152
168
  * // Send and confirm each approval before calling action.buildTx().
153
169
  * // action.buildTx() returns Readonly<Transaction<VaultV2WithdrawAction>>.
@@ -158,6 +174,7 @@ export interface VaultV2Actions {
158
174
  withdraw: (params: {
159
175
  readonly amount: bigint;
160
176
  readonly userAddress: Address;
177
+ readonly vaultData: AccrualVaultV2;
161
178
  readonly slippageTolerance?: bigint;
162
179
  readonly referralFeePct?: bigint;
163
180
  readonly referralFeeRecipient?: Address;
@@ -169,19 +186,19 @@ export interface VaultV2Actions {
169
186
  * Captures `shares` and `userAddress` at handle creation for both requirements and `buildTx()`.
170
187
  * The caller must satisfy the exact vault-share allowance returned by `getRequirements()` before
171
188
  * `buildTx()`; every requirement resolution re-reads the live allowance and checks the deadline.
172
- * `buildTx()` accepts permits from the latest completed requirement resolution.
173
189
  *
174
- * @param {Object} params - The redeem parameters.
175
- * @param {bigint} params.shares - Exact vault shares to burn.
176
- * @param {Address} params.userAddress - Account that must sign and submit the transaction; VaultBundlesV1 burns `msg.sender`'s shares and pays `msg.sender`.
177
- * @param {bigint} [params.referralFeePct=0n] - WAD-scaled referral fee deducted from the redeemed assets; must be below WAD.
178
- * @param {Address} [params.referralFeeRecipient] - Non-zero recipient required when `referralFeePct` is positive.
179
- * @param {bigint} [params.deadline] - VaultBundlesV1 execution deadline; defaults to two hours from now.
190
+ * @param params - The redeem parameters.
191
+ * @param params.shares - Exact vault shares to burn.
192
+ * @param params.userAddress - Account that must sign and submit the transaction; VaultBundlesV1 burns `msg.sender`'s shares and pays `msg.sender`.
193
+ * @param [params.referralFeePct=0n] - WAD-scaled referral fee deducted from the redeemed assets; must be below WAD.
194
+ * @param [params.referralFeeRecipient] - Non-zero recipient required when `referralFeePct` is positive.
195
+ * @param [params.deadline] - VaultBundlesV1 execution deadline; defaults to two hours from now.
180
196
  * @returns Lazy exact share-allowance requirements and a synchronous transaction builder.
181
197
  * @throws {ChainIdMismatchError} when the client and entity target different chains.
182
198
  * @throws {NonPositiveInputError} when `shares` is not positive.
183
199
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
184
200
  * requirement resolution.
201
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
185
202
  * @throws {NegativeInputError} when `referralFeePct` is negative.
186
203
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
187
204
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
@@ -190,8 +207,8 @@ export interface VaultV2Actions {
190
207
  * @throws {viem.BaseError} from `getRequirements()` when an allowance or nonce read fails.
191
208
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
192
209
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
193
- * @throws {BundlesPermitMismatchError} from `buildTx()` when the supplied permit does not match the
194
- * resolved share cap, spender, owner, nonce, or deadline.
210
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
211
+ * deadline differ from this operation's.
195
212
  * @example
196
213
  * ```ts
197
214
  * import { isRequirementSignature } from "@morpho-org/morpho-sdk";
@@ -404,7 +421,7 @@ export interface VaultV2Actions {
404
421
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
405
422
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the permit's spender, amount, or
406
423
  * deadline differs from this operation. Any handle built from the same inputs accepts the
407
- * permit; the nonce is verified onchain by the vault's `permit`.
424
+ * permit; a permit whose nonce was consumed is skipped onchain and the live allowance applies.
408
425
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the requirement has the wrong permit kind, asset, or signature encoding.
409
426
  * @example
410
427
  * ```ts
@@ -455,13 +472,27 @@ export interface VaultV2Actions {
455
472
  * asset-equivalent of the redeemed shares. The caller should apply a buffer on the deallocated
456
473
  * amounts to account for share-price drift between submission and execution.
457
474
  *
458
- * @param {Object} params - The force redeem parameters.
459
- * @param {readonly Deallocation[]} params.deallocations - The typed list of deallocations to perform.
460
- * @param {Object} params.redeem - The redeem parameters applied after deallocations.
461
- * @param {bigint} params.redeem.shares - The amount of shares to redeem.
462
- * @param {Address} params.userAddress - User address (penalty source and redeem recipient).
463
- * @returns {Object} The result object.
464
- * @returns {Readonly<Transaction<VaultV2ForceRedeemAction>>} returns.buildTx The prepared multicall transaction.
475
+ * @param params.deallocations - Typed list of `forceDeallocate` calls to perform before the redeem.
476
+ * @param params.redeem.shares - Amount of vault shares to redeem after the deallocations.
477
+ * @param params.userAddress - Account that pays the deallocation penalties and receives the redeemed assets.
478
+ * @returns An object whose `buildTx()` returns a deep-frozen `Transaction<VaultV2ForceRedeemAction>`
479
+ * encoding the vault `multicall`.
480
+ * @throws {ChainIdMismatchError} when the connected client targets another chain or has no chain.
481
+ * @throws {EmptyDeallocationsError} from `buildTx()` when `deallocations` is empty.
482
+ * @throws {NonPositiveInputError} from `buildTx()` when `redeem.shares <= 0n` or any deallocation
483
+ * amount is non-positive.
484
+ * @example
485
+ * ```ts
486
+ * const vault = client.morpho.vaultV2(vaultAddress, 1);
487
+ * const tx = vault
488
+ * .forceRedeem({
489
+ * deallocations: [{ adapter, marketParams, amount: 1_000_000n }],
490
+ * redeem: { shares: 500_000n },
491
+ * userAddress,
492
+ * })
493
+ * .buildTx();
494
+ * // tx satisfies Readonly<Transaction<VaultV2ForceRedeemAction>>
495
+ * ```
465
496
  */
466
497
  forceRedeem: (params: {
467
498
  deallocations: readonly Deallocation[];
@@ -473,6 +504,7 @@ export interface VaultV2Actions {
473
504
  buildTx: () => Readonly<Transaction<VaultV2ForceRedeemAction>>;
474
505
  };
475
506
  }
507
+ /** Binds a viem client to a Vault V2 vault's action builders. */
476
508
  export declare class MorphoVaultV2 implements VaultV2Actions {
477
509
  private readonly client;
478
510
  private readonly vault;
@@ -494,6 +526,7 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
494
526
  withdraw(params: {
495
527
  readonly amount: bigint;
496
528
  readonly userAddress: Address;
529
+ readonly vaultData: AccrualVaultV2;
497
530
  readonly slippageTolerance?: bigint;
498
531
  readonly referralFeePct?: bigint;
499
532
  readonly referralFeeRecipient?: Address;
@@ -3,16 +3,17 @@ import { erc2612Abi, fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
3
  import { _try, getChainAddress, Time } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
5
5
  import { multicall } from "viem/actions";
6
- import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundlesFunding, selectBundlesSharesPermitSignature, selectBundlesSharesRequirementSignature, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
6
+ import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundlesFunding, selectBundlesSharesPermitSignature, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
7
7
  import { encodeErc20Approval, encodeVaultSharesPermit, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2InKindRedeem, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
8
8
  import { computeMinForceWithdrawSharePrice, computeVaultMaxShareAllowance, computeVaultMaxSharePrice, computeVaultV2ForceWithdrawFeeSharesMinted, computeVaultV2ForceWithdrawMinSharesBurnt, computeVaultV2ForceWithdrawPlan, computeVaultV2ForceWithdrawSharesBurnt, MAX_SLIPPAGE_TOLERANCE, resolveVaultV2ForceWithdrawEligibility, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
9
9
  import { validateDeadline, validateNativeVaultAsset, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
10
- import { AdapterNotPartOfVaultError, ChainIdMismatchError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemZeroDeallocationError, InputExceedsMaxError, InsufficientBlueBalanceForInKindRedeemError, isRequirementSignature, NonPositiveInputError, VaultAddressMismatchError, VaultV2ForceWithdrawCoverageError, VaultV2ForceWithdrawFeeSharesExceedBurnError, VaultV2ForceWithdrawSharePriceBelowFloorError, VaultV2ForceWithdrawZeroSharePriceError, VaultV2ForceWithdrawZeroWithdrawalError, VaultV2SingleAdapterRequiredError, VaultV2UndecodableLiquidityDataError, VaultV2UnsupportedExitAdapterError, VaultV2UnsupportedLiquidityAdapterError, } from "../../types/index.js";
10
+ import { AdapterNotPartOfVaultError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemZeroDeallocationError, InputExceedsMaxError, InsufficientBlueBalanceForInKindRedeemError, NonPositiveInputError, VaultAddressMismatchError, VaultV2ForceWithdrawCoverageError, VaultV2ForceWithdrawFeeSharesExceedBurnError, VaultV2ForceWithdrawSharePriceBelowFloorError, VaultV2ForceWithdrawZeroSharePriceError, VaultV2ForceWithdrawZeroWithdrawalError, VaultV2SingleAdapterRequiredError, VaultV2UndecodableLiquidityDataError, VaultV2UnsupportedExitAdapterError, VaultV2UnsupportedLiquidityAdapterError, } from "../../types/index.js";
11
11
  import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
12
12
  import { getBundlesTokenRequirements } from "../requirements/index.js";
13
13
  // Maximum accepted deadline horizon; the on-chain management fee is capped at 5%/yr so the
14
14
  // accrual model stays well-defined inside it.
15
15
  const VAULT_V2_FEE_PROJECTION_HORIZON = Time.s.from.y(1n);
16
+ /** Binds a viem client to a Vault V2 vault's action builders. */
16
17
  export class MorphoVaultV2 {
17
18
  client;
18
19
  vault;
@@ -24,10 +25,7 @@ export class MorphoVaultV2 {
24
25
  this.chainId = chainId;
25
26
  }
26
27
  async getData(parameters) {
27
- if (this.client.viemClient.chain?.id &&
28
- this.client.viemClient.chain?.id !== this.chainId) {
29
- throw new ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
30
- }
28
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
31
29
  return fetchAccrualVaultV2(this.vault, this.client.viemClient, {
32
30
  ...parameters,
33
31
  deployless: this.client.options.supportDeployless,
@@ -66,7 +64,6 @@ export class MorphoVaultV2 {
66
64
  });
67
65
  const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
68
66
  let pendingRequirements;
69
- let expectedRequirement;
70
67
  return Object.freeze({
71
68
  getRequirements: async (requirementOptions) => {
72
69
  const now = Time.timestamp();
@@ -74,33 +71,22 @@ export class MorphoVaultV2 {
74
71
  throw new ExpiredDeadlineError(deadline, now);
75
72
  if (pendingRequirements != null)
76
73
  return await pendingRequirements;
77
- // Memoize the in-flight promise, not just its result: concurrent callers
78
- // requesting different routes would otherwise both resolve requirements and
79
- // the slower one would overwrite `expectedRequirement`, making `buildTx()`
80
- // reject the signature returned by the other call.
81
- const pending = (async () => {
82
- const requirements = funding.value > 0n
83
- ? []
84
- : await getBundlesTokenRequirements(this.client.viemClient, {
85
- token: vaultAsset,
86
- spender,
87
- amount: funding.assets,
88
- owner: userAddress,
89
- chainId: this.chainId,
90
- deadline,
91
- supportSignature: this.client.options.supportSignature,
92
- supportDeployless: this.client.options.supportDeployless,
93
- useSimplePermit: requirementOptions?.useSimplePermit,
94
- permit2Nonce: requirementOptions?.permit2Nonce,
95
- });
96
- const signatureRequirement = requirements.find(isRequirementSignature);
97
- expectedRequirement =
98
- signatureRequirement?.action.type === "permit" ||
99
- signatureRequirement?.action.type === "permit2SignatureTransfer"
100
- ? signatureRequirement.action
101
- : undefined;
102
- return requirements;
103
- })();
74
+ // Memoize the in-flight promise so concurrent callers share one round of
75
+ // allowance/nonce reads.
76
+ const pending = funding.value > 0n
77
+ ? Promise.resolve([])
78
+ : getBundlesTokenRequirements(this.client.viemClient, {
79
+ token: vaultAsset,
80
+ spender,
81
+ amount: funding.assets,
82
+ owner: userAddress,
83
+ chainId: this.chainId,
84
+ deadline,
85
+ supportSignature: this.client.options.supportSignature,
86
+ supportDeployless: this.client.options.supportDeployless,
87
+ useSimplePermit: requirementOptions?.useSimplePermit,
88
+ permit2Nonce: requirementOptions?.permit2Nonce,
89
+ });
104
90
  pendingRequirements = pending;
105
91
  try {
106
92
  return await pending;
@@ -112,7 +98,8 @@ export class MorphoVaultV2 {
112
98
  }
113
99
  },
114
100
  buildTx: (signatures) => {
115
- const requirementSignature = selectBundlesTokenRequirementSignature(signatures, expectedRequirement);
101
+ // The pure deposit action rejects a token signature supplied alongside native funding.
102
+ const requirementSignature = selectBundlesTokenRequirementSignature(signatures, { spender, amount: funding.assets, deadline });
116
103
  return vaultV2Deposit({
117
104
  vault: {
118
105
  chainId: this.chainId,
@@ -136,8 +123,11 @@ export class MorphoVaultV2 {
136
123
  });
137
124
  }
138
125
  withdraw(params) {
139
- const { amount, userAddress } = params;
126
+ const { amount, userAddress, vaultData } = params;
140
127
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
128
+ if (!isAddressEqual(vaultData.address, this.vault)) {
129
+ throw new VaultAddressMismatchError(this.vault, vaultData.address);
130
+ }
141
131
  if (amount <= 0n)
142
132
  throw new NonPositiveInputError("amount", amount);
143
133
  // Reject values outside the ABI range before resolving any requirements.
@@ -153,11 +143,14 @@ export class MorphoVaultV2 {
153
143
  });
154
144
  const slippageTolerance = params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE;
155
145
  validateSlippageTolerance(slippageTolerance);
156
- // Fail eagerly if VaultBundlesV1 is unavailable; only validation is needed here.
157
- getChainAddress(this.chainId, "bundles.vaultBundlesV1");
158
- let requiredShareAllowance;
159
- let vaultSnapshot;
160
- let expectedRequirement;
146
+ // Resolve the spender eagerly so an unregistered VaultBundlesV1 fails at handle creation.
147
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
148
+ const requiredShareAllowance = computeVaultMaxShareAllowance({
149
+ vaultData,
150
+ deadline,
151
+ assets: amount,
152
+ slippageTolerance,
153
+ });
161
154
  return Object.freeze({
162
155
  getRequirements: async () => {
163
156
  const now = Time.timestamp();
@@ -166,18 +159,9 @@ export class MorphoVaultV2 {
166
159
  // Re-read the live share allowance on every call instead of caching the resolved
167
160
  // requirements: the allowance is the sole cap on the burn, so a caller that executed the
168
161
  // returned approval must see it satisfied on the next call, and an allowance revoked or
169
- // raised afterwards must resurface as an outstanding requirement. Only the vault snapshot
170
- // and the cap derived from it are pinned, so re-reading cannot move the cap this handle
171
- // already committed to; the snapshot is used for immutable identity and permit-domain
172
- // fields only.
173
- const vaultData = (vaultSnapshot ??= await this.getData());
174
- requiredShareAllowance ??= computeVaultMaxShareAllowance({
175
- vaultData,
176
- deadline,
177
- assets: amount,
178
- slippageTolerance,
179
- });
180
- const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
162
+ // raised afterwards must resurface as an outstanding requirement. The cap derived from
163
+ // `vaultData` is pinned at handle creation, so re-reading cannot move it.
164
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
181
165
  vaultData,
182
166
  version: "vaultV2",
183
167
  owner: userAddress,
@@ -186,17 +170,12 @@ export class MorphoVaultV2 {
186
170
  deadline,
187
171
  supportSignature: this.client.options.supportSignature,
188
172
  });
189
- const signatureRequirement = requirements.find(isRequirementSignature);
190
- expectedRequirement =
191
- signatureRequirement?.action.type === "permit"
192
- ? signatureRequirement.action
193
- : undefined;
194
- return requirements;
195
173
  },
196
174
  buildTx: (signatures) => {
197
- const permit = selectBundlesSharesRequirementSignature(signatures, {
198
- requiredShareAllowance,
199
- expectedRequirement,
175
+ const permit = selectBundlesSharesPermitSignature(signatures, {
176
+ spender,
177
+ amount: requiredShareAllowance,
178
+ deadline,
200
179
  });
201
180
  return vaultV2Withdraw({
202
181
  vault: { chainId: this.chainId, address: this.vault },
@@ -228,14 +207,13 @@ export class MorphoVaultV2 {
228
207
  referralFeePct: params.referralFeePct,
229
208
  referralFeeRecipient: params.referralFeeRecipient,
230
209
  });
231
- getChainAddress(this.chainId, "bundles.vaultBundlesV1");
232
- let expectedRequirement;
210
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
233
211
  return Object.freeze({
234
212
  getRequirements: async () => {
235
213
  const now = Time.timestamp();
236
214
  if (deadline <= now)
237
215
  throw new ExpiredDeadlineError(deadline, now);
238
- const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
216
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
239
217
  vaultData: await this.getData(),
240
218
  version: "vaultV2",
241
219
  owner: userAddress,
@@ -244,17 +222,12 @@ export class MorphoVaultV2 {
244
222
  deadline,
245
223
  supportSignature: this.client.options.supportSignature,
246
224
  });
247
- const signatureRequirement = requirements.find(isRequirementSignature);
248
- expectedRequirement =
249
- signatureRequirement?.action.type === "permit"
250
- ? signatureRequirement.action
251
- : undefined;
252
- return requirements;
253
225
  },
254
226
  buildTx: (signatures) => {
255
- const permit = selectBundlesSharesRequirementSignature(signatures, {
256
- requiredShareAllowance: shares,
257
- expectedRequirement,
227
+ const permit = selectBundlesSharesPermitSignature(signatures, {
228
+ spender,
229
+ amount: shares,
230
+ deadline,
258
231
  });
259
232
  return vaultV2Redeem({
260
233
  vault: { chainId: this.chainId, address: this.vault },
@@ -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, 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, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
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";
6
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
7
  export { _try, DivisionByZeroError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } 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, 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, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
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";
6
6
  export { _try, DivisionByZeroError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
@@ -94,14 +94,18 @@ export interface VaultV2ForceWithdrawPreview {
94
94
  * floor cannot fit `uint256`.
95
95
  * @example
96
96
  * ```ts
97
+ * import type { AccrualVaultV2 } from "@morpho-org/blue-sdk";
97
98
  * import { previewVaultV2ForceWithdraw } from "@morpho-org/morpho-sdk";
98
99
  *
99
- * const preview = previewVaultV2ForceWithdraw(vaultData, {
100
- * requestedExitAssets: 1_000_000n,
101
- * timestamp: block.timestamp,
102
- * });
103
- * // preview?.exitAssets is ready to pass to vault.forceWithdraw(...)
104
- * // preview?.netAssets is what the user receives
100
+ * export function preview(vaultData: AccrualVaultV2, timestamp: bigint) {
101
+ * const preview = previewVaultV2ForceWithdraw(vaultData, {
102
+ * requestedExitAssets: 1_000_000n,
103
+ * timestamp,
104
+ * });
105
+ * // preview?.exitAssets is ready to pass to vault.forceWithdraw(...)
106
+ * // preview?.netAssets is what the user receives
107
+ * return preview;
108
+ * }
105
109
  * ```
106
110
  */
107
111
  export declare function previewVaultV2ForceWithdraw(vaultData: AccrualVaultV2, params: PreviewVaultV2ForceWithdrawParams): VaultV2ForceWithdrawPreview | undefined;
@@ -40,14 +40,18 @@ import { computeVaultV2ForceWithdrawFeeSharesMinted, computeVaultV2ForceWithdraw
40
40
  * floor cannot fit `uint256`.
41
41
  * @example
42
42
  * ```ts
43
+ * import type { AccrualVaultV2 } from "@morpho-org/blue-sdk";
43
44
  * import { previewVaultV2ForceWithdraw } from "@morpho-org/morpho-sdk";
44
45
  *
45
- * const preview = previewVaultV2ForceWithdraw(vaultData, {
46
- * requestedExitAssets: 1_000_000n,
47
- * timestamp: block.timestamp,
48
- * });
49
- * // preview?.exitAssets is ready to pass to vault.forceWithdraw(...)
50
- * // preview?.netAssets is what the user receives
46
+ * export function preview(vaultData: AccrualVaultV2, timestamp: bigint) {
47
+ * const preview = previewVaultV2ForceWithdraw(vaultData, {
48
+ * requestedExitAssets: 1_000_000n,
49
+ * timestamp,
50
+ * });
51
+ * // preview?.exitAssets is ready to pass to vault.forceWithdraw(...)
52
+ * // preview?.netAssets is what the user receives
53
+ * return preview;
54
+ * }
51
55
  * ```
52
56
  */
53
57
  export function previewVaultV2ForceWithdraw(vaultData, params) {
@@ -32,10 +32,11 @@ import { type AccrualVault, AccrualVaultV2 } from "@morpho-org/blue-sdk";
32
32
  * @example
33
33
  * ```ts
34
34
  * import { computeMinForceWithdrawSharePrice } from "@morpho-org/morpho-sdk";
35
+ * import { DEFAULT_SLIPPAGE_TOLERANCE } from "@morpho-org/morpho-sdk/constants";
35
36
  *
36
37
  * const minSharePriceE27 = computeMinForceWithdrawSharePrice({
37
- * withdrawnAssets: plan.withdrawnAssets,
38
- * sharesBurnt,
38
+ * withdrawnAssets: 1_000_000n,
39
+ * sharesBurnt: 900_000n,
39
40
  * slippageTolerance: DEFAULT_SLIPPAGE_TOLERANCE,
40
41
  * });
41
42
  * ```
@@ -35,10 +35,11 @@ import { validateSlippageTolerance } from "./validate.js";
35
35
  * @example
36
36
  * ```ts
37
37
  * import { computeMinForceWithdrawSharePrice } from "@morpho-org/morpho-sdk";
38
+ * import { DEFAULT_SLIPPAGE_TOLERANCE } from "@morpho-org/morpho-sdk/constants";
38
39
  *
39
40
  * const minSharePriceE27 = computeMinForceWithdrawSharePrice({
40
- * withdrawnAssets: plan.withdrawnAssets,
41
- * sharesBurnt,
41
+ * withdrawnAssets: 1_000_000n,
42
+ * sharesBurnt: 900_000n,
42
43
  * slippageTolerance: DEFAULT_SLIPPAGE_TOLERANCE,
43
44
  * });
44
45
  * ```
@@ -176,6 +176,31 @@ export declare const validateNativeVaultAsset: (chainId: number, vaultAsset: Add
176
176
  * @param params.withdrawAmount - Amount of collateral being withdrawn.
177
177
  * @param params.lltv - The market's liquidation LTV.
178
178
  * @param params.marketId - The market identifier (for error messages).
179
+ * @returns `void` when the post-withdraw position stays within the safe LTV threshold.
180
+ * @throws {MarketIdMismatchError} when `positionData.marketId` differs from `marketId`.
181
+ * @throws {WithdrawExceedsCollateralError} when `withdrawAmount` exceeds the position's collateral.
182
+ * @throws {MissingMarketPriceError} when the position carries debt but the market has no oracle price.
183
+ * @throws {WithdrawMakesPositionUnhealthyError} when the remaining collateral cannot cover the debt
184
+ * at LLTV minus `DEFAULT_LLTV_BUFFER`.
185
+ * @example
186
+ * ```ts
187
+ * import type { AccrualPosition, MarketId } from "@morpho-org/blue-sdk";
188
+ * import { validatePositionHealthAfterWithdraw } from "@morpho-org/morpho-sdk";
189
+ *
190
+ * export function assertSafeWithdraw(
191
+ * positionData: AccrualPosition,
192
+ * withdrawAmount: bigint,
193
+ * lltv: bigint,
194
+ * marketId: MarketId,
195
+ * ): void {
196
+ * validatePositionHealthAfterWithdraw({
197
+ * positionData,
198
+ * withdrawAmount,
199
+ * lltv,
200
+ * marketId,
201
+ * });
202
+ * }
203
+ * ```
179
204
  */
180
205
  export declare const validatePositionHealthAfterWithdraw: (params: {
181
206
  positionData: AccrualPosition;
@@ -203,6 +228,21 @@ export declare const validateRepayAmount: (params: {
203
228
  * @param params.positionData - The current accrual position.
204
229
  * @param params.repayShares - The amount of shares to repay.
205
230
  * @param params.marketId - The market identifier (for error messages).
231
+ * @returns `void` when `repayShares` does not exceed the position's borrow shares.
232
+ * @throws {RepaySharesExceedDebtError} when `repayShares` exceeds the position's borrow shares.
233
+ * @example
234
+ * ```ts
235
+ * import type { AccrualPosition, MarketId } from "@morpho-org/blue-sdk";
236
+ * import { validateRepayShares } from "@morpho-org/morpho-sdk";
237
+ *
238
+ * export function assertRepayable(
239
+ * positionData: AccrualPosition,
240
+ * repayShares: bigint,
241
+ * marketId: MarketId,
242
+ * ): void {
243
+ * validateRepayShares({ positionData, repayShares, marketId });
244
+ * }
245
+ * ```
206
246
  */
207
247
  export declare const validateRepayShares: (params: {
208
248
  positionData: AccrualPosition;