@morpho-org/morpho-sdk 6.0.0-next.4 → 6.0.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 (59) hide show
  1. package/MIGRATION-v5-to-v6.md +20 -14
  2. package/README.md +6 -4
  3. package/lib/cjs/actions/bundles/common.d.ts +18 -23
  4. package/lib/cjs/actions/bundles/common.js +36 -83
  5. package/lib/cjs/actions/bundles/index.d.ts +1 -1
  6. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +6 -2
  7. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +6 -2
  8. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +1 -0
  9. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -0
  10. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +11 -3
  11. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +19 -1
  12. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -1
  13. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +12 -0
  14. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +62 -17
  15. package/lib/cjs/actions/vaultV1/migrateToV2.js +48 -17
  16. package/lib/cjs/actions/vaultV1/redeem.d.ts +28 -1
  17. package/lib/cjs/actions/vaultV1/redeem.js +17 -1
  18. package/lib/cjs/actions/vaultV1/withdraw.d.ts +1 -1
  19. package/lib/cjs/actions/vaultV1/withdraw.js +1 -1
  20. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +3 -2
  21. package/lib/cjs/actions/vaultV2/forceWithdraw.js +3 -2
  22. package/lib/cjs/actions/vaultV2/redeem.d.ts +28 -1
  23. package/lib/cjs/actions/vaultV2/redeem.js +17 -1
  24. package/lib/cjs/actions/vaultV2/withdraw.d.ts +1 -1
  25. package/lib/cjs/actions/vaultV2/withdraw.js +1 -1
  26. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +29 -20
  27. package/lib/cjs/entities/vaultV1/vaultV1.js +50 -84
  28. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +33 -24
  29. package/lib/cjs/entities/vaultV2/vaultV2.js +44 -72
  30. package/lib/cjs/types/action.d.ts +1 -0
  31. package/lib/esm/actions/bundles/common.d.ts +18 -23
  32. package/lib/esm/actions/bundles/common.js +34 -80
  33. package/lib/esm/actions/bundles/index.d.ts +1 -1
  34. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +6 -2
  35. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +6 -2
  36. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +1 -0
  37. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -0
  38. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +11 -3
  39. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +21 -3
  40. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -1
  41. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +14 -2
  42. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +62 -17
  43. package/lib/esm/actions/vaultV1/migrateToV2.js +48 -17
  44. package/lib/esm/actions/vaultV1/redeem.d.ts +28 -1
  45. package/lib/esm/actions/vaultV1/redeem.js +17 -1
  46. package/lib/esm/actions/vaultV1/withdraw.d.ts +1 -1
  47. package/lib/esm/actions/vaultV1/withdraw.js +1 -1
  48. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +3 -2
  49. package/lib/esm/actions/vaultV2/forceWithdraw.js +3 -2
  50. package/lib/esm/actions/vaultV2/redeem.d.ts +28 -1
  51. package/lib/esm/actions/vaultV2/redeem.js +17 -1
  52. package/lib/esm/actions/vaultV2/withdraw.d.ts +1 -1
  53. package/lib/esm/actions/vaultV2/withdraw.js +1 -1
  54. package/lib/esm/entities/vaultV1/vaultV1.d.ts +29 -20
  55. package/lib/esm/entities/vaultV1/vaultV1.js +52 -86
  56. package/lib/esm/entities/vaultV2/vaultV2.d.ts +33 -24
  57. package/lib/esm/entities/vaultV2/vaultV2.js +46 -74
  58. package/lib/esm/types/action.d.ts +1 -0
  59. package/package.json +5 -5
@@ -3,11 +3,11 @@ 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
13
  export class MorphoVaultV1 {
@@ -21,10 +21,7 @@ export class MorphoVaultV1 {
21
21
  this.chainId = chainId;
22
22
  }
23
23
  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
- }
24
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
28
25
  return fetchAccrualVault(this.vault, this.client.viemClient, {
29
26
  ...parameters,
30
27
  deployless: this.client.options.supportDeployless,
@@ -63,7 +60,6 @@ export class MorphoVaultV1 {
63
60
  });
64
61
  const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
65
62
  let pendingRequirements;
66
- let expectedRequirement;
67
63
  return Object.freeze({
68
64
  getRequirements: async (requirementOptions) => {
69
65
  const now = Time.timestamp();
@@ -71,33 +67,22 @@ export class MorphoVaultV1 {
71
67
  throw new ExpiredDeadlineError(deadline, now);
72
68
  if (pendingRequirements != null)
73
69
  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
- })();
70
+ // Memoize the in-flight promise so concurrent callers share one round of
71
+ // allowance/nonce reads.
72
+ const pending = funding.value > 0n
73
+ ? Promise.resolve([])
74
+ : getBundlesTokenRequirements(this.client.viemClient, {
75
+ token: vaultAsset,
76
+ spender,
77
+ amount: funding.assets,
78
+ owner: userAddress,
79
+ chainId: this.chainId,
80
+ deadline,
81
+ supportSignature: this.client.options.supportSignature,
82
+ supportDeployless: this.client.options.supportDeployless,
83
+ useSimplePermit: requirementOptions?.useSimplePermit,
84
+ permit2Nonce: requirementOptions?.permit2Nonce,
85
+ });
101
86
  pendingRequirements = pending;
102
87
  try {
103
88
  return await pending;
@@ -109,7 +94,8 @@ export class MorphoVaultV1 {
109
94
  }
110
95
  },
111
96
  buildTx: (signatures) => {
112
- const requirementSignature = selectBundlesTokenRequirementSignature(signatures, expectedRequirement);
97
+ // The pure deposit action rejects a token signature supplied alongside native funding.
98
+ const requirementSignature = selectBundlesTokenRequirementSignature(signatures, { spender, amount: funding.assets, deadline });
113
99
  return vaultV1Deposit({
114
100
  vault: {
115
101
  chainId: this.chainId,
@@ -133,8 +119,11 @@ export class MorphoVaultV1 {
133
119
  });
134
120
  }
135
121
  withdraw(params) {
136
- const { amount, userAddress } = params;
122
+ const { amount, userAddress, vaultData } = params;
137
123
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
124
+ if (!isAddressEqual(vaultData.address, this.vault)) {
125
+ throw new VaultAddressMismatchError(this.vault, vaultData.address);
126
+ }
138
127
  if (amount <= 0n)
139
128
  throw new NonPositiveInputError("amount", amount);
140
129
  // Reject values outside the ABI range before resolving any requirements.
@@ -150,11 +139,14 @@ export class MorphoVaultV1 {
150
139
  });
151
140
  const slippageTolerance = params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE;
152
141
  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;
142
+ // Resolve the spender eagerly so an unregistered VaultBundlesV1 fails at handle creation.
143
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
144
+ const requiredShareAllowance = computeVaultMaxShareAllowance({
145
+ vaultData,
146
+ deadline,
147
+ assets: amount,
148
+ slippageTolerance,
149
+ });
158
150
  return Object.freeze({
159
151
  getRequirements: async () => {
160
152
  const now = Time.timestamp();
@@ -163,18 +155,9 @@ export class MorphoVaultV1 {
163
155
  // Re-read the live share allowance on every call instead of caching the resolved
164
156
  // requirements: the allowance is the sole cap on the burn, so a caller that executed the
165
157
  // 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, {
158
+ // raised afterwards must resurface as an outstanding requirement. The cap derived from
159
+ // `vaultData` is pinned at handle creation, so re-reading cannot move it.
160
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
178
161
  vaultData,
179
162
  version: "vaultV1",
180
163
  owner: userAddress,
@@ -183,17 +166,12 @@ export class MorphoVaultV1 {
183
166
  deadline,
184
167
  supportSignature: this.client.options.supportSignature,
185
168
  });
186
- const signatureRequirement = requirements.find(isRequirementSignature);
187
- expectedRequirement =
188
- signatureRequirement?.action.type === "permit"
189
- ? signatureRequirement.action
190
- : undefined;
191
- return requirements;
192
169
  },
193
170
  buildTx: (signatures) => {
194
- const permit = selectBundlesSharesRequirementSignature(signatures, {
195
- requiredShareAllowance,
196
- expectedRequirement,
171
+ const permit = selectBundlesSharesPermitSignature(signatures, {
172
+ spender,
173
+ amount: requiredShareAllowance,
174
+ deadline,
197
175
  });
198
176
  return vaultV1Withdraw({
199
177
  vault: { chainId: this.chainId, address: this.vault },
@@ -225,14 +203,13 @@ export class MorphoVaultV1 {
225
203
  referralFeePct: params.referralFeePct,
226
204
  referralFeeRecipient: params.referralFeeRecipient,
227
205
  });
228
- getChainAddress(this.chainId, "bundles.vaultBundlesV1");
229
- let expectedRequirement;
206
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
230
207
  return Object.freeze({
231
208
  getRequirements: async () => {
232
209
  const now = Time.timestamp();
233
210
  if (deadline <= now)
234
211
  throw new ExpiredDeadlineError(deadline, now);
235
- const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
212
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
236
213
  vaultData: await this.getData(),
237
214
  version: "vaultV1",
238
215
  owner: userAddress,
@@ -241,17 +218,12 @@ export class MorphoVaultV1 {
241
218
  deadline,
242
219
  supportSignature: this.client.options.supportSignature,
243
220
  });
244
- const signatureRequirement = requirements.find(isRequirementSignature);
245
- expectedRequirement =
246
- signatureRequirement?.action.type === "permit"
247
- ? signatureRequirement.action
248
- : undefined;
249
- return requirements;
250
221
  },
251
222
  buildTx: (signatures) => {
252
- const permit = selectBundlesSharesRequirementSignature(signatures, {
253
- requiredShareAllowance: shares,
254
- expectedRequirement,
223
+ const permit = selectBundlesSharesPermitSignature(signatures, {
224
+ spender,
225
+ amount: shares,
226
+ deadline,
255
227
  });
256
228
  return vaultV1Redeem({
257
229
  vault: { chainId: this.chainId, address: this.vault },
@@ -494,7 +466,7 @@ export class MorphoVaultV1 {
494
466
  assets: assets ?? 0n,
495
467
  slippageTolerance,
496
468
  });
497
- getChainAddress(this.chainId, "bundles.vaultBundlesV1");
469
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
498
470
  const { userAddress } = params;
499
471
  const sourceAsset = params.sourceVault.asset;
500
472
  const targetAddress = params.targetVault.address;
@@ -510,7 +482,6 @@ export class MorphoVaultV1 {
510
482
  extensions: [...domain.extensions],
511
483
  }),
512
484
  });
513
- let expectedRequirement;
514
485
  return Object.freeze({
515
486
  getRequirements: async () => {
516
487
  const now = Time.timestamp();
@@ -522,7 +493,7 @@ export class MorphoVaultV1 {
522
493
  // satisfied on the next call, and an allowance revoked or raised afterwards must resurface
523
494
  // as an outstanding requirement. The pinned snapshot and the cap derived from it stay
524
495
  // fixed, so re-reading cannot move the cap this handle already committed to.
525
- const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
496
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
526
497
  vaultData: sourceToken,
527
498
  version: "vaultV1",
528
499
  owner: userAddress,
@@ -531,17 +502,12 @@ export class MorphoVaultV1 {
531
502
  deadline,
532
503
  supportSignature: this.client.options.supportSignature,
533
504
  });
534
- const signatureRequirement = requirements.find(isRequirementSignature);
535
- expectedRequirement =
536
- signatureRequirement?.action.type === "permit"
537
- ? signatureRequirement.action
538
- : undefined;
539
- return requirements;
540
505
  },
541
506
  buildTx: (signatures) => {
542
- const permit = selectBundlesSharesRequirementSignature(signatures, {
543
- requiredShareAllowance,
544
- expectedRequirement,
507
+ const permit = selectBundlesSharesPermitSignature(signatures, {
508
+ spender,
509
+ amount: requiredShareAllowance,
510
+ deadline,
545
511
  });
546
512
  return vaultV1MigrateToV2({
547
513
  vault: {
@@ -11,6 +11,7 @@ export interface VaultV2Actions {
11
11
  * @param {FetchParameters} [parameters] - The parameters for the fetch operation.
12
12
  *
13
13
  * @returns {Promise<Awaited<ReturnType<typeof fetchAccrualVaultV2>>>} The latest vault data.
14
+ * @throws {ChainIdMismatchError} when the connected client targets another chain or has no chain.
14
15
  */
15
16
  getData: (parameters?: FetchParameters) => Promise<Awaited<ReturnType<typeof fetchAccrualVaultV2>>>;
16
17
  /**
@@ -21,7 +22,7 @@ export interface VaultV2Actions {
21
22
  * Permit2 nonce state. Native funding is exclusive and skips token requirements. Shares are
22
23
  * always minted to the transaction sender, which must be `userAddress`.
23
24
  * 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.
25
+ * state using their own options.
25
26
  *
26
27
  * @param params.userAddress - Account that funds, signs, submits, and receives the vault shares.
27
28
  * @param params.vaultData - Pre-fetched Vault V2 snapshot used for asset and share conversion.
@@ -57,8 +58,9 @@ export interface VaultV2Actions {
57
58
  * `getRequirements()` when the Permit2 nonce exceeds uint256.
58
59
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
59
60
  * @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.
61
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
62
+ * deadline differ from this operation's, or when the signature's carried action nonce is
63
+ * inconsistent with its signed nonce.
62
64
  * @throws {DepositOwnerMismatchError} from `buildTx()` when the signed owner differs from `userAddress`.
63
65
  * @throws {DepositAssetMismatchError} from `buildTx()` when the signed asset differs from the vault asset.
64
66
  * @throws {BundlesRequirementSignatureMismatchError} from `buildTx()` when signature metadata is malformed.
@@ -98,13 +100,14 @@ export interface VaultV2Actions {
98
100
  /**
99
101
  * Prepares an exact-assets Vault V2 withdrawal through VaultBundlesV1.
100
102
  *
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.
103
+ * Derives the share-burn cap from the supplied `vaultData` snapshot at handle creation, then
104
+ * reads the live vault-share allowance and, when a signature is needed, the permit nonce on
105
+ * each `getRequirements()` call. Captures the requested amount and owner at creation, so later
106
+ * changes to `params` do not change this handle's requirements or transaction.
105
107
  *
106
108
  * @param params.amount - Positive gross withdrawal in underlying asset base units, before fees.
107
109
  * @param params.userAddress - Share owner that must sign and submit; receives the net assets.
110
+ * @param params.vaultData - Pre-fetched Vault V2 snapshot used to derive the share cap.
108
111
  * @param params.slippageTolerance - Optional WAD-scaled share-price loss tolerance applied to
109
112
  * the share cap.
110
113
  * Defaults to 0.03% and cannot exceed 10%.
@@ -117,8 +120,11 @@ export interface VaultV2Actions {
117
120
  * which returns a deep-frozen `Transaction<VaultV2WithdrawAction>`. Requirements are empty
118
121
  * when the allowance equals the cap; an oversized allowance is always reset with an exact
119
122
  * 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`.
123
+ * support, an ERC-2612 request. The cap is fixed at handle creation while each call re-reads
124
+ * the allowance. Confirm the approval or pass its signed permit to `buildTx`.
125
+ * @remarks VaultBundlesV1 skips a share permit whose nonce was already consumed and proceeds
126
+ * under the live allowance, so execute every requirement returned by the latest
127
+ * `getRequirements()` — including the oversized-allowance reset — before submitting.
122
128
  * @throws {ChainIdMismatchError} when the connected client targets another chain.
123
129
  * @throws {NonPositiveInputError} when `amount` or the computed share cap is not positive.
124
130
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
@@ -128,14 +134,14 @@ export interface VaultV2Actions {
128
134
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
129
135
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no nonzero recipient.
130
136
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds 10%.
137
+ * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
131
138
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
132
139
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
133
140
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
134
141
  * @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.
142
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed or
143
+ * its spender, amount or deadline differ from this operation's.
144
+ * @throws {viem.BaseError} when an allowance or nonce read or transaction encoding fails.
139
145
  * @example
140
146
  * ```ts
141
147
  * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
@@ -147,7 +153,8 @@ export interface VaultV2Actions {
147
153
  * const client = createPublicClient({ chain: mainnet, transport: http() })
148
154
  * .extend(morphoViemExtension({ supportSignature: false }));
149
155
  * const vault = client.morpho.vaultV2(vaultAddress, mainnet.id);
150
- * const action = vault.withdraw({ amount: 1_000_000n, userAddress });
156
+ * const vaultData = await vault.getData();
157
+ * const action = vault.withdraw({ amount: 1_000_000n, userAddress, vaultData });
151
158
  * const requirements = await action.getRequirements();
152
159
  * // Send and confirm each approval before calling action.buildTx().
153
160
  * // action.buildTx() returns Readonly<Transaction<VaultV2WithdrawAction>>.
@@ -158,6 +165,7 @@ export interface VaultV2Actions {
158
165
  withdraw: (params: {
159
166
  readonly amount: bigint;
160
167
  readonly userAddress: Address;
168
+ readonly vaultData: AccrualVaultV2;
161
169
  readonly slippageTolerance?: bigint;
162
170
  readonly referralFeePct?: bigint;
163
171
  readonly referralFeeRecipient?: Address;
@@ -169,19 +177,19 @@ export interface VaultV2Actions {
169
177
  * Captures `shares` and `userAddress` at handle creation for both requirements and `buildTx()`.
170
178
  * The caller must satisfy the exact vault-share allowance returned by `getRequirements()` before
171
179
  * `buildTx()`; every requirement resolution re-reads the live allowance and checks the deadline.
172
- * `buildTx()` accepts permits from the latest completed requirement resolution.
173
180
  *
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.
181
+ * @param params - The redeem parameters.
182
+ * @param params.shares - Exact vault shares to burn.
183
+ * @param params.userAddress - Account that must sign and submit the transaction; VaultBundlesV1 burns `msg.sender`'s shares and pays `msg.sender`.
184
+ * @param [params.referralFeePct=0n] - WAD-scaled referral fee deducted from the redeemed assets; must be below WAD.
185
+ * @param [params.referralFeeRecipient] - Non-zero recipient required when `referralFeePct` is positive.
186
+ * @param [params.deadline] - VaultBundlesV1 execution deadline; defaults to two hours from now.
180
187
  * @returns Lazy exact share-allowance requirements and a synchronous transaction builder.
181
188
  * @throws {ChainIdMismatchError} when the client and entity target different chains.
182
189
  * @throws {NonPositiveInputError} when `shares` is not positive.
183
190
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
184
191
  * requirement resolution.
192
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
185
193
  * @throws {NegativeInputError} when `referralFeePct` is negative.
186
194
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
187
195
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
@@ -190,8 +198,8 @@ export interface VaultV2Actions {
190
198
  * @throws {viem.BaseError} from `getRequirements()` when an allowance or nonce read fails.
191
199
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
192
200
  * @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.
201
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
202
+ * deadline differ from this operation's.
195
203
  * @example
196
204
  * ```ts
197
205
  * import { isRequirementSignature } from "@morpho-org/morpho-sdk";
@@ -404,7 +412,7 @@ export interface VaultV2Actions {
404
412
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
405
413
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the permit's spender, amount, or
406
414
  * 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`.
415
+ * permit; a permit whose nonce was consumed is skipped onchain and the live allowance applies.
408
416
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the requirement has the wrong permit kind, asset, or signature encoding.
409
417
  * @example
410
418
  * ```ts
@@ -494,6 +502,7 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
494
502
  withdraw(params: {
495
503
  readonly amount: bigint;
496
504
  readonly userAddress: Address;
505
+ readonly vaultData: AccrualVaultV2;
497
506
  readonly slippageTolerance?: bigint;
498
507
  readonly referralFeePct?: bigint;
499
508
  readonly referralFeeRecipient?: Address;
@@ -3,11 +3,11 @@ 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
@@ -24,10 +24,7 @@ export class MorphoVaultV2 {
24
24
  this.chainId = chainId;
25
25
  }
26
26
  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
- }
27
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
31
28
  return fetchAccrualVaultV2(this.vault, this.client.viemClient, {
32
29
  ...parameters,
33
30
  deployless: this.client.options.supportDeployless,
@@ -66,7 +63,6 @@ export class MorphoVaultV2 {
66
63
  });
67
64
  const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
68
65
  let pendingRequirements;
69
- let expectedRequirement;
70
66
  return Object.freeze({
71
67
  getRequirements: async (requirementOptions) => {
72
68
  const now = Time.timestamp();
@@ -74,33 +70,22 @@ export class MorphoVaultV2 {
74
70
  throw new ExpiredDeadlineError(deadline, now);
75
71
  if (pendingRequirements != null)
76
72
  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
- })();
73
+ // Memoize the in-flight promise so concurrent callers share one round of
74
+ // allowance/nonce reads.
75
+ const pending = funding.value > 0n
76
+ ? Promise.resolve([])
77
+ : getBundlesTokenRequirements(this.client.viemClient, {
78
+ token: vaultAsset,
79
+ spender,
80
+ amount: funding.assets,
81
+ owner: userAddress,
82
+ chainId: this.chainId,
83
+ deadline,
84
+ supportSignature: this.client.options.supportSignature,
85
+ supportDeployless: this.client.options.supportDeployless,
86
+ useSimplePermit: requirementOptions?.useSimplePermit,
87
+ permit2Nonce: requirementOptions?.permit2Nonce,
88
+ });
104
89
  pendingRequirements = pending;
105
90
  try {
106
91
  return await pending;
@@ -112,7 +97,8 @@ export class MorphoVaultV2 {
112
97
  }
113
98
  },
114
99
  buildTx: (signatures) => {
115
- const requirementSignature = selectBundlesTokenRequirementSignature(signatures, expectedRequirement);
100
+ // The pure deposit action rejects a token signature supplied alongside native funding.
101
+ const requirementSignature = selectBundlesTokenRequirementSignature(signatures, { spender, amount: funding.assets, deadline });
116
102
  return vaultV2Deposit({
117
103
  vault: {
118
104
  chainId: this.chainId,
@@ -136,8 +122,11 @@ export class MorphoVaultV2 {
136
122
  });
137
123
  }
138
124
  withdraw(params) {
139
- const { amount, userAddress } = params;
125
+ const { amount, userAddress, vaultData } = params;
140
126
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
127
+ if (!isAddressEqual(vaultData.address, this.vault)) {
128
+ throw new VaultAddressMismatchError(this.vault, vaultData.address);
129
+ }
141
130
  if (amount <= 0n)
142
131
  throw new NonPositiveInputError("amount", amount);
143
132
  // Reject values outside the ABI range before resolving any requirements.
@@ -153,11 +142,14 @@ export class MorphoVaultV2 {
153
142
  });
154
143
  const slippageTolerance = params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE;
155
144
  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;
145
+ // Resolve the spender eagerly so an unregistered VaultBundlesV1 fails at handle creation.
146
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
147
+ const requiredShareAllowance = computeVaultMaxShareAllowance({
148
+ vaultData,
149
+ deadline,
150
+ assets: amount,
151
+ slippageTolerance,
152
+ });
161
153
  return Object.freeze({
162
154
  getRequirements: async () => {
163
155
  const now = Time.timestamp();
@@ -166,18 +158,9 @@ export class MorphoVaultV2 {
166
158
  // Re-read the live share allowance on every call instead of caching the resolved
167
159
  // requirements: the allowance is the sole cap on the burn, so a caller that executed the
168
160
  // 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, {
161
+ // raised afterwards must resurface as an outstanding requirement. The cap derived from
162
+ // `vaultData` is pinned at handle creation, so re-reading cannot move it.
163
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
181
164
  vaultData,
182
165
  version: "vaultV2",
183
166
  owner: userAddress,
@@ -186,17 +169,12 @@ export class MorphoVaultV2 {
186
169
  deadline,
187
170
  supportSignature: this.client.options.supportSignature,
188
171
  });
189
- const signatureRequirement = requirements.find(isRequirementSignature);
190
- expectedRequirement =
191
- signatureRequirement?.action.type === "permit"
192
- ? signatureRequirement.action
193
- : undefined;
194
- return requirements;
195
172
  },
196
173
  buildTx: (signatures) => {
197
- const permit = selectBundlesSharesRequirementSignature(signatures, {
198
- requiredShareAllowance,
199
- expectedRequirement,
174
+ const permit = selectBundlesSharesPermitSignature(signatures, {
175
+ spender,
176
+ amount: requiredShareAllowance,
177
+ deadline,
200
178
  });
201
179
  return vaultV2Withdraw({
202
180
  vault: { chainId: this.chainId, address: this.vault },
@@ -228,14 +206,13 @@ export class MorphoVaultV2 {
228
206
  referralFeePct: params.referralFeePct,
229
207
  referralFeeRecipient: params.referralFeeRecipient,
230
208
  });
231
- getChainAddress(this.chainId, "bundles.vaultBundlesV1");
232
- let expectedRequirement;
209
+ const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
233
210
  return Object.freeze({
234
211
  getRequirements: async () => {
235
212
  const now = Time.timestamp();
236
213
  if (deadline <= now)
237
214
  throw new ExpiredDeadlineError(deadline, now);
238
- const requirements = await getVaultBundlesSharesRequirements(this.client.viemClient, {
215
+ return getVaultBundlesSharesRequirements(this.client.viemClient, {
239
216
  vaultData: await this.getData(),
240
217
  version: "vaultV2",
241
218
  owner: userAddress,
@@ -244,17 +221,12 @@ export class MorphoVaultV2 {
244
221
  deadline,
245
222
  supportSignature: this.client.options.supportSignature,
246
223
  });
247
- const signatureRequirement = requirements.find(isRequirementSignature);
248
- expectedRequirement =
249
- signatureRequirement?.action.type === "permit"
250
- ? signatureRequirement.action
251
- : undefined;
252
- return requirements;
253
224
  },
254
225
  buildTx: (signatures) => {
255
- const permit = selectBundlesSharesRequirementSignature(signatures, {
256
- requiredShareAllowance: shares,
257
- expectedRequirement,
226
+ const permit = selectBundlesSharesPermitSignature(signatures, {
227
+ spender,
228
+ amount: shares,
229
+ deadline,
258
230
  });
259
231
  return vaultV2Redeem({
260
232
  vault: { chainId: this.chainId, address: this.vault },
@@ -482,6 +482,7 @@ export interface MidnightOfferRootSignatureArgs {
482
482
  }
483
483
  /** EIP-712 payload carried by a signable requirement action. */
484
484
  export type RequirementTypedData = TypedDataDefinition<Record<string, unknown>, string>;
485
+ /** Signable ERC-2612 permit requirement for a fixed-bundles token pull. */
485
486
  export interface PermitAction extends BaseAction<"permit", {
486
487
  readonly spender: Address;
487
488
  readonly amount: bigint;