@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,12 +3,19 @@ import { fetchAccrualVault } 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 MorphoClientType, type RequirementSignature, type VaultV1DepositAction, type VaultV1InKindRedeemAction, type VaultV1MigrateToV2Action, type VaultV1MigrateToV2AmountArgs, type VaultV1RedeemAction, type VaultV1WithdrawAction } from "../../types/index.js";
6
+ /** Action surface for Vault V1 reads and writes; writes route through VaultBundlesV1 and VaultExitBundlesV1. */
6
7
  export interface VaultV1Actions {
7
8
  /**
8
9
  * Fetches direct onchain vault and allocation state without applying virtual interest.
9
10
  *
10
- * @param {FetchParameters} [parameters] - Optional fetch parameters (block number, state overrides, etc.).
11
- * @returns {Promise<Awaited<ReturnType<typeof fetchAccrualVault>>>} The requested vault state.
11
+ * Reads the Vault V1 state through `fetchAccrualVault` on the entity's client.
12
+ *
13
+ * @param parameters - Optional viem fetch parameters (block number, block tag, state override).
14
+ * @returns The hydrated `AccrualVault` snapshot.
15
+ * @throws {ChainIdMismatchError} when the connected client targets another chain or has no chain.
16
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
17
+ * @throws {UnknownBlueFactory} when the configured chain has no MetaMorpho factory.
18
+ * @throws {UnknownBlueOfFactory} when the vault is not a MetaMorpho vault from the configured factory.
12
19
  */
13
20
  getData: (parameters?: FetchParameters) => Promise<Awaited<ReturnType<typeof fetchAccrualVault>>>;
14
21
  /**
@@ -19,7 +26,7 @@ export interface VaultV1Actions {
19
26
  * Permit2 nonce state. Native funding is exclusive and skips token requirements. Shares are
20
27
  * always minted to the transaction sender, which must be `userAddress`.
21
28
  * Concurrent requirement reads share the first caller's options; later calls refresh on-chain
22
- * state using their own options. `buildTx()` accepts signatures from the latest completed read.
29
+ * state using their own options.
23
30
  *
24
31
  * @param params.userAddress - Account that funds, signs, submits, and receives the vault shares.
25
32
  * @param params.vaultData - Pre-fetched Vault V1 snapshot used for asset and share conversion.
@@ -55,8 +62,9 @@ export interface VaultV1Actions {
55
62
  * `getRequirements()` when the Permit2 nonce exceeds uint256.
56
63
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
57
64
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
58
- * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature was not produced for
59
- * this prepared handle.
65
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
66
+ * deadline differ from this operation's, or when the signature's carried action nonce is
67
+ * inconsistent with its signed nonce.
60
68
  * @throws {DepositOwnerMismatchError} from `buildTx()` when the signed owner differs from `userAddress`.
61
69
  * @throws {DepositAssetMismatchError} from `buildTx()` when the signed asset differs from the vault asset.
62
70
  * @throws {BundlesRequirementSignatureMismatchError} from `buildTx()` when signature metadata is malformed.
@@ -95,13 +103,14 @@ export interface VaultV1Actions {
95
103
  /**
96
104
  * Prepares an exact-assets Vault V1 withdrawal through VaultBundlesV1.
97
105
  *
98
- * Reads the vault accrual state on the first `getRequirements()` call, then reads the live
99
- * vault-share allowance and, when a signature is needed, the permit nonce on each call.
100
- * Captures the requested amount and owner at creation, so later changes to `params` do not
101
- * change this handle's requirements or transaction.
106
+ * Derives the share-burn cap from the supplied `vaultData` snapshot at handle creation, then
107
+ * reads the live vault-share allowance and, when a signature is needed, the permit nonce on
108
+ * each `getRequirements()` call. Captures the requested amount and owner at creation, so later
109
+ * changes to `params` do not change this handle's requirements or transaction.
102
110
  *
103
111
  * @param params.amount - Positive gross withdrawal in underlying asset base units, before fees.
104
112
  * @param params.userAddress - Share owner that must sign and submit; receives the net assets.
113
+ * @param params.vaultData - Pre-fetched Vault V1 snapshot used to derive the share cap.
105
114
  * @param params.slippageTolerance - Optional WAD-scaled share-price loss tolerance applied to
106
115
  * the share cap for MetaMorpho 1.0; MetaMorpho 1.1 retains its lost-assets clamp.
107
116
  * Defaults to 0.03% and cannot exceed 10%.
@@ -114,8 +123,11 @@ export interface VaultV1Actions {
114
123
  * which returns a deep-frozen `Transaction<VaultV1WithdrawAction>`. Requirements are empty
115
124
  * when the allowance equals the cap; an oversized allowance is always reset with an exact
116
125
  * onchain approval, and an insufficient one is raised by an approval or, with signature
117
- * support, an ERC-2612 request. The cap stays pinned to the first resolution while each call
118
- * re-reads the allowance. Confirm the approval or pass its signed permit to `buildTx`.
126
+ * support, an ERC-2612 request. The cap is fixed at handle creation while each call re-reads
127
+ * the allowance. Confirm the approval or pass its signed permit to `buildTx`.
128
+ * @remarks VaultBundlesV1 skips a share permit whose nonce was already consumed and proceeds
129
+ * under the live allowance, so execute every requirement returned by the latest
130
+ * `getRequirements()` — including the oversized-allowance reset — before submitting.
119
131
  * @throws {ChainIdMismatchError} when the connected client targets another chain.
120
132
  * @throws {NonPositiveInputError} when `amount` or the computed share cap is not positive.
121
133
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
@@ -125,14 +137,14 @@ export interface VaultV1Actions {
125
137
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
126
138
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no nonzero recipient.
127
139
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds 10%.
140
+ * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
128
141
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
129
142
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
130
143
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
131
144
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple permits are supplied.
132
- * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed,
133
- * was not resolved for this handle, or has incompatible vault, owner, spender, amount,
134
- * deadline, or nonce values.
135
- * @throws {viem.BaseError} when a vault, allowance, or nonce read or transaction encoding fails.
145
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed or
146
+ * its spender, amount or deadline differ from this operation's.
147
+ * @throws {viem.BaseError} when an allowance or nonce read or transaction encoding fails.
136
148
  * @example
137
149
  * ```ts
138
150
  * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
@@ -144,7 +156,8 @@ export interface VaultV1Actions {
144
156
  * const client = createPublicClient({ chain: mainnet, transport: http() })
145
157
  * .extend(morphoViemExtension({ supportSignature: false }));
146
158
  * const vault = client.morpho.vaultV1(vaultAddress, mainnet.id);
147
- * const action = vault.withdraw({ amount: 1_000_000n, userAddress });
159
+ * const vaultData = await vault.getData();
160
+ * const action = vault.withdraw({ amount: 1_000_000n, userAddress, vaultData });
148
161
  * const requirements = await action.getRequirements();
149
162
  * // Send and confirm each approval before calling action.buildTx().
150
163
  * // action.buildTx() returns Readonly<Transaction<VaultV1WithdrawAction>>.
@@ -155,6 +168,7 @@ export interface VaultV1Actions {
155
168
  withdraw: (params: {
156
169
  readonly amount: bigint;
157
170
  readonly userAddress: Address;
171
+ readonly vaultData: AccrualVault;
158
172
  readonly slippageTolerance?: bigint;
159
173
  readonly referralFeePct?: bigint;
160
174
  readonly referralFeeRecipient?: Address;
@@ -166,7 +180,6 @@ export interface VaultV1Actions {
166
180
  * Captures `shares` and `userAddress` at handle creation for both requirements and `buildTx()`.
167
181
  * The caller must satisfy the exact vault-share allowance returned by `getRequirements()` before
168
182
  * `buildTx()`; every requirement resolution re-reads the live allowance and checks the deadline.
169
- * `buildTx()` accepts permits from the latest completed requirement resolution.
170
183
  *
171
184
  * @param params.shares - Exact vault shares to burn.
172
185
  * @param params.userAddress - Account that signs and submits the transaction; VaultBundlesV1
@@ -180,6 +193,7 @@ export interface VaultV1Actions {
180
193
  * @throws {ChainIdMismatchError} when the connected client targets another chain.
181
194
  * @throws {NonPositiveInputError} when `shares` is not positive.
182
195
  * @throws {ExpiredDeadlineError} when the deadline is stale at creation or requirement resolution.
196
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
183
197
  * @throws {NegativeInputError} when `referralFeePct` is negative.
184
198
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
185
199
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
@@ -188,8 +202,8 @@ export interface VaultV1Actions {
188
202
  * @throws {viem.BaseError} from `getRequirements()` when an allowance or permit-nonce read fails.
189
203
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple permit signatures are supplied.
190
204
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
191
- * @throws {BundlesPermitMismatchError} from `buildTx()` when the supplied permit does not match
192
- * the resolved share amount, spender, owner, nonce, or deadline.
205
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
206
+ * deadline differ from this operation's.
193
207
  * @example
194
208
  * ```ts
195
209
  * import { vaults } from "@morpho-org/morpho-test";
@@ -314,7 +328,6 @@ export interface VaultV1Actions {
314
328
  * VaultBundlesV1. Only the destination deposit has an onchain share-price bound. The caller must
315
329
  * satisfy the exact source-vault share requirement before building the transaction.
316
330
  * Captures vault identities, permit-domain metadata, and the owner at handle creation.
317
- * `buildTx()` accepts permits from the latest completed requirement resolution.
318
331
  *
319
332
  * @param params.userAddress - Account that signs and submits the transaction; VaultBundlesV1
320
333
  * burns and mints shares for `msg.sender`.
@@ -347,6 +360,7 @@ export interface VaultV1Actions {
347
360
  * @throws {NegativeInputError} when slippage tolerance or `referralFeePct` is negative.
348
361
  * @throws {ExcessiveSlippageToleranceError} when slippage tolerance exceeds the SDK maximum.
349
362
  * @throws {ExpiredDeadlineError} when the deadline is stale at creation or requirement resolution.
363
+ * @throws {InputExceedsMaxError} when the selected amount, `maxSharePriceVaultV2`, or `deadline` exceeds uint256.
350
364
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
351
365
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
352
366
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
@@ -354,8 +368,8 @@ export interface VaultV1Actions {
354
368
  * @throws {viem.BaseError} from `getRequirements()` when an allowance or permit-nonce read fails.
355
369
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple permit signatures are supplied.
356
370
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
357
- * @throws {BundlesPermitMismatchError} from `buildTx()` when the supplied permit does not match
358
- * the prepared source share cap, spender, owner, nonce, or deadline.
371
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
372
+ * deadline differ from this operation's.
359
373
  * @example
360
374
  * ```ts
361
375
  * import { vaults } from "@morpho-org/morpho-test";
@@ -406,6 +420,7 @@ export interface VaultV1Actions {
406
420
  readonly deadline?: bigint;
407
421
  } & VaultV1MigrateToV2AmountArgs) => ActionOutput<VaultV1MigrateToV2Action, readonly RequirementSignature[], undefined>;
408
422
  }
423
+ /** Binds a viem client to a Vault V1 (MetaMorpho) vault's action builders. */
409
424
  export declare class MorphoVaultV1 implements VaultV1Actions {
410
425
  private readonly client;
411
426
  private readonly vault;
@@ -427,6 +442,7 @@ export declare class MorphoVaultV1 implements VaultV1Actions {
427
442
  withdraw(params: {
428
443
  readonly amount: bigint;
429
444
  readonly userAddress: Address;
445
+ readonly vaultData: AccrualVault;
430
446
  readonly slippageTolerance?: bigint;
431
447
  readonly referralFeePct?: bigint;
432
448
  readonly referralFeeRecipient?: Address;
@@ -3,13 +3,14 @@ import { blueAbi, erc2612Abi, fetchAccrualVault, metaMorphoAbi, } from "@morpho-
3
3
  import { getChainAddress, Time } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual } 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, vaultV1Deposit, vaultV1InKindRedeem, vaultV1MigrateToV2, vaultV1Redeem, vaultV1Withdraw, } from "../../actions/index.js";
8
8
  import { computeVaultMaxShareAllowance, computeVaultMaxSharePrice, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
9
9
  import { validateDeadline, validateNativeVaultAsset, validateUint256Field, } from "../../helpers/validate.js";
10
- import { AmountAndSharesExclusiveError, ChainIdMismatchError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InsufficientBlueBalanceForInKindRedeemError, isRequirementSignature, NonPositiveInputError, SameVaultMigrationError, VaultAddressMismatchError, VaultAssetMismatchError, VaultIsBlueFeeRecipientError, VaultMorphoMismatchError, } from "../../types/index.js";
10
+ import { AmountAndSharesExclusiveError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InsufficientBlueBalanceForInKindRedeemError, NonPositiveInputError, SameVaultMigrationError, VaultAddressMismatchError, VaultAssetMismatchError, VaultIsBlueFeeRecipientError, VaultMorphoMismatchError, } from "../../types/index.js";
11
11
  import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
12
12
  import { getBundlesTokenRequirements } from "../requirements/index.js";
13
+ /** Binds a viem client to a Vault V1 (MetaMorpho) vault's action builders. */
13
14
  export class MorphoVaultV1 {
14
15
  client;
15
16
  vault;
@@ -21,10 +22,7 @@ export class MorphoVaultV1 {
21
22
  this.chainId = chainId;
22
23
  }
23
24
  async getData(parameters) {
24
- if (this.client.viemClient.chain?.id &&
25
- this.client.viemClient.chain?.id !== this.chainId) {
26
- throw new ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
27
- }
25
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
28
26
  return fetchAccrualVault(this.vault, this.client.viemClient, {
29
27
  ...parameters,
30
28
  deployless: this.client.options.supportDeployless,
@@ -63,7 +61,6 @@ export class MorphoVaultV1 {
63
61
  });
64
62
  const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
65
63
  let pendingRequirements;
66
- let expectedRequirement;
67
64
  return Object.freeze({
68
65
  getRequirements: async (requirementOptions) => {
69
66
  const now = Time.timestamp();
@@ -71,33 +68,22 @@ export class MorphoVaultV1 {
71
68
  throw new ExpiredDeadlineError(deadline, now);
72
69
  if (pendingRequirements != null)
73
70
  return await pendingRequirements;
74
- // Memoize the in-flight promise, not just its result: concurrent callers
75
- // requesting different routes would otherwise both resolve requirements and
76
- // the slower one would overwrite `expectedRequirement`, making `buildTx()`
77
- // reject the signature returned by the other call.
78
- const pending = (async () => {
79
- const requirements = funding.value > 0n
80
- ? []
81
- : await getBundlesTokenRequirements(this.client.viemClient, {
82
- token: vaultAsset,
83
- spender,
84
- amount: funding.assets,
85
- owner: userAddress,
86
- chainId: this.chainId,
87
- deadline,
88
- supportSignature: this.client.options.supportSignature,
89
- supportDeployless: this.client.options.supportDeployless,
90
- useSimplePermit: requirementOptions?.useSimplePermit,
91
- permit2Nonce: requirementOptions?.permit2Nonce,
92
- });
93
- const signatureRequirement = requirements.find(isRequirementSignature);
94
- expectedRequirement =
95
- signatureRequirement?.action.type === "permit" ||
96
- signatureRequirement?.action.type === "permit2SignatureTransfer"
97
- ? signatureRequirement.action
98
- : undefined;
99
- return requirements;
100
- })();
71
+ // Memoize the in-flight promise so concurrent callers share one round of
72
+ // allowance/nonce reads.
73
+ const pending = funding.value > 0n
74
+ ? Promise.resolve([])
75
+ : getBundlesTokenRequirements(this.client.viemClient, {
76
+ token: vaultAsset,
77
+ spender,
78
+ amount: funding.assets,
79
+ owner: userAddress,
80
+ chainId: this.chainId,
81
+ deadline,
82
+ supportSignature: this.client.options.supportSignature,
83
+ supportDeployless: this.client.options.supportDeployless,
84
+ useSimplePermit: requirementOptions?.useSimplePermit,
85
+ permit2Nonce: requirementOptions?.permit2Nonce,
86
+ });
101
87
  pendingRequirements = pending;
102
88
  try {
103
89
  return await pending;
@@ -109,7 +95,8 @@ export class MorphoVaultV1 {
109
95
  }
110
96
  },
111
97
  buildTx: (signatures) => {
112
- const requirementSignature = selectBundlesTokenRequirementSignature(signatures, expectedRequirement);
98
+ // The pure deposit action rejects a token signature supplied alongside native funding.
99
+ const requirementSignature = selectBundlesTokenRequirementSignature(signatures, { spender, amount: funding.assets, deadline });
113
100
  return vaultV1Deposit({
114
101
  vault: {
115
102
  chainId: this.chainId,
@@ -133,8 +120,11 @@ export class MorphoVaultV1 {
133
120
  });
134
121
  }
135
122
  withdraw(params) {
136
- const { amount, userAddress } = params;
123
+ const { amount, userAddress, vaultData } = params;
137
124
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
125
+ if (!isAddressEqual(vaultData.address, this.vault)) {
126
+ throw new VaultAddressMismatchError(this.vault, vaultData.address);
127
+ }
138
128
  if (amount <= 0n)
139
129
  throw new NonPositiveInputError("amount", amount);
140
130
  // Reject values outside the ABI range before resolving any requirements.
@@ -150,11 +140,14 @@ export class MorphoVaultV1 {
150
140
  });
151
141
  const slippageTolerance = params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE;
152
142
  validateSlippageTolerance(slippageTolerance);
153
- // Fail eagerly if VaultBundlesV1 is unavailable; only validation is needed here.
154
- getChainAddress(this.chainId, "bundles.vaultBundlesV1");
155
- let requiredShareAllowance;
156
- let vaultSnapshot;
157
- let expectedRequirement;
143
+ // Resolve the spender eagerly so an unregistered VaultBundlesV1 fails at handle creation.
144
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
145
+ const requiredShareAllowance = computeVaultMaxShareAllowance({
146
+ vaultData,
147
+ deadline,
148
+ assets: amount,
149
+ slippageTolerance,
150
+ });
158
151
  return Object.freeze({
159
152
  getRequirements: async () => {
160
153
  const now = Time.timestamp();
@@ -163,18 +156,9 @@ export class MorphoVaultV1 {
163
156
  // Re-read the live share allowance on every call instead of caching the resolved
164
157
  // requirements: the allowance is the sole cap on the burn, so a caller that executed the
165
158
  // returned approval must see it satisfied on the next call, and an allowance revoked or
166
- // raised afterwards must resurface as an outstanding requirement. Only the vault snapshot
167
- // and the cap derived from it are pinned, so re-reading cannot move the cap this handle
168
- // already committed to; the snapshot is used for immutable identity and permit-domain
169
- // fields only.
170
- const vaultData = (vaultSnapshot ??= await this.getData());
171
- requiredShareAllowance ??= computeVaultMaxShareAllowance({
172
- vaultData,
173
- deadline,
174
- assets: amount,
175
- slippageTolerance,
176
- });
177
- const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
159
+ // raised afterwards must resurface as an outstanding requirement. The cap derived from
160
+ // `vaultData` is pinned at handle creation, so re-reading cannot move it.
161
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
178
162
  vaultData,
179
163
  version: "vaultV1",
180
164
  owner: userAddress,
@@ -183,17 +167,12 @@ export class MorphoVaultV1 {
183
167
  deadline,
184
168
  supportSignature: this.client.options.supportSignature,
185
169
  });
186
- const signatureRequirement = requirements.find(isRequirementSignature);
187
- expectedRequirement =
188
- signatureRequirement?.action.type === "permit"
189
- ? signatureRequirement.action
190
- : undefined;
191
- return requirements;
192
170
  },
193
171
  buildTx: (signatures) => {
194
- const permit = selectBundlesSharesRequirementSignature(signatures, {
195
- requiredShareAllowance,
196
- expectedRequirement,
172
+ const permit = selectBundlesSharesPermitSignature(signatures, {
173
+ spender,
174
+ amount: requiredShareAllowance,
175
+ deadline,
197
176
  });
198
177
  return vaultV1Withdraw({
199
178
  vault: { chainId: this.chainId, address: this.vault },
@@ -225,14 +204,13 @@ export class MorphoVaultV1 {
225
204
  referralFeePct: params.referralFeePct,
226
205
  referralFeeRecipient: params.referralFeeRecipient,
227
206
  });
228
- getChainAddress(this.chainId, "bundles.vaultBundlesV1");
229
- let expectedRequirement;
207
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
230
208
  return Object.freeze({
231
209
  getRequirements: async () => {
232
210
  const now = Time.timestamp();
233
211
  if (deadline <= now)
234
212
  throw new ExpiredDeadlineError(deadline, now);
235
- const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
213
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
236
214
  vaultData: await this.getData(),
237
215
  version: "vaultV1",
238
216
  owner: userAddress,
@@ -241,17 +219,12 @@ export class MorphoVaultV1 {
241
219
  deadline,
242
220
  supportSignature: this.client.options.supportSignature,
243
221
  });
244
- const signatureRequirement = requirements.find(isRequirementSignature);
245
- expectedRequirement =
246
- signatureRequirement?.action.type === "permit"
247
- ? signatureRequirement.action
248
- : undefined;
249
- return requirements;
250
222
  },
251
223
  buildTx: (signatures) => {
252
- const permit = selectBundlesSharesRequirementSignature(signatures, {
253
- requiredShareAllowance: shares,
254
- expectedRequirement,
224
+ const permit = selectBundlesSharesPermitSignature(signatures, {
225
+ spender,
226
+ amount: shares,
227
+ deadline,
255
228
  });
256
229
  return vaultV1Redeem({
257
230
  vault: { chainId: this.chainId, address: this.vault },
@@ -494,7 +467,7 @@ export class MorphoVaultV1 {
494
467
  assets: assets ?? 0n,
495
468
  slippageTolerance,
496
469
  });
497
- getChainAddress(this.chainId, "bundles.vaultBundlesV1");
470
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
498
471
  const { userAddress } = params;
499
472
  const sourceAsset = params.sourceVault.asset;
500
473
  const targetAddress = params.targetVault.address;
@@ -510,7 +483,6 @@ export class MorphoVaultV1 {
510
483
  extensions: [...domain.extensions],
511
484
  }),
512
485
  });
513
- let expectedRequirement;
514
486
  return Object.freeze({
515
487
  getRequirements: async () => {
516
488
  const now = Time.timestamp();
@@ -522,7 +494,7 @@ export class MorphoVaultV1 {
522
494
  // satisfied on the next call, and an allowance revoked or raised afterwards must resurface
523
495
  // as an outstanding requirement. The pinned snapshot and the cap derived from it stay
524
496
  // fixed, so re-reading cannot move the cap this handle already committed to.
525
- const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
497
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
526
498
  vaultData: sourceToken,
527
499
  version: "vaultV1",
528
500
  owner: userAddress,
@@ -531,17 +503,12 @@ export class MorphoVaultV1 {
531
503
  deadline,
532
504
  supportSignature: this.client.options.supportSignature,
533
505
  });
534
- const signatureRequirement = requirements.find(isRequirementSignature);
535
- expectedRequirement =
536
- signatureRequirement?.action.type === "permit"
537
- ? signatureRequirement.action
538
- : undefined;
539
- return requirements;
540
506
  },
541
507
  buildTx: (signatures) => {
542
- const permit = selectBundlesSharesRequirementSignature(signatures, {
543
- requiredShareAllowance,
544
- expectedRequirement,
508
+ const permit = selectBundlesSharesPermitSignature(signatures, {
509
+ spender,
510
+ amount: requiredShareAllowance,
511
+ deadline,
545
512
  });
546
513
  return vaultV1MigrateToV2({
547
514
  vault: {