@morpho-org/morpho-sdk 9.4.0 → 9.6.0-next.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 (97) hide show
  1. package/MIGRATION-v5-to-v6.md +7 -0
  2. package/MIGRATION-v7-to-v8.md +7 -0
  3. package/MIGRATION-v8-to-v9.md +7 -0
  4. package/README.md +6 -4
  5. package/lib/cjs/abis.d.ts +1 -1
  6. package/lib/cjs/abis.js +5 -1
  7. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -0
  8. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -1
  9. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +4 -1
  10. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -1
  11. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  12. package/lib/cjs/blue/abis.d.ts +1 -1
  13. package/lib/cjs/blue/abis.js +5 -1
  14. package/lib/cjs/blue/entities.d.ts +4 -4
  15. package/lib/cjs/blue/entities.js +3 -1
  16. package/lib/cjs/blue/errors.d.ts +2 -2
  17. package/lib/cjs/blue/errors.js +5 -1
  18. package/lib/cjs/blue/fetch.d.ts +2 -2
  19. package/lib/cjs/blue/fetch.js +3 -1
  20. package/lib/cjs/blue/utils.d.ts +1 -1
  21. package/lib/cjs/blue/utils.js +2 -1
  22. package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
  23. package/lib/cjs/client/morphoViemExtension.js +1 -1
  24. package/lib/cjs/entities/blue/blue.d.ts +7 -21
  25. package/lib/cjs/entities/blue/blue.js +4 -22
  26. package/lib/cjs/entities/index.d.ts +4 -4
  27. package/lib/cjs/entities/index.js +3 -1
  28. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +21 -26
  29. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +42 -80
  30. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.d.ts +6 -3
  31. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.js +2 -2
  32. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +5 -11
  33. package/lib/cjs/entities/vaultV1/vaultV1.js +3 -11
  34. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +37 -18
  35. package/lib/cjs/entities/vaultV2/vaultV2.js +36 -12
  36. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +8 -3
  37. package/lib/cjs/entities/vaultV2BlueReallocationData.js +49 -7
  38. package/lib/cjs/errors.d.ts +4 -4
  39. package/lib/cjs/errors.js +7 -5
  40. package/lib/cjs/fetch.d.ts +2 -2
  41. package/lib/cjs/fetch.js +3 -1
  42. package/lib/cjs/helpers/deadShares.js +2 -0
  43. package/lib/cjs/midnight/errors.d.ts +2 -1
  44. package/lib/cjs/midnight/errors.js +5 -4
  45. package/lib/cjs/types/action.d.ts +11 -4
  46. package/lib/cjs/types/action.js +1 -0
  47. package/lib/cjs/types/error.d.ts +8 -2
  48. package/lib/cjs/types/error.js +8 -2
  49. package/lib/cjs/utils.d.ts +2 -2
  50. package/lib/cjs/utils.js +4 -2
  51. package/lib/esm/abis.d.ts +1 -1
  52. package/lib/esm/abis.js +1 -1
  53. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -0
  54. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -1
  55. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +4 -1
  56. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -1
  57. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  58. package/lib/esm/blue/abis.d.ts +1 -1
  59. package/lib/esm/blue/abis.js +1 -1
  60. package/lib/esm/blue/entities.d.ts +4 -4
  61. package/lib/esm/blue/entities.js +2 -2
  62. package/lib/esm/blue/errors.d.ts +2 -2
  63. package/lib/esm/blue/errors.js +2 -2
  64. package/lib/esm/blue/fetch.d.ts +2 -2
  65. package/lib/esm/blue/fetch.js +2 -2
  66. package/lib/esm/blue/utils.d.ts +1 -1
  67. package/lib/esm/blue/utils.js +1 -1
  68. package/lib/esm/client/morphoViemExtension.d.ts +1 -1
  69. package/lib/esm/client/morphoViemExtension.js +1 -1
  70. package/lib/esm/entities/blue/blue.d.ts +7 -21
  71. package/lib/esm/entities/blue/blue.js +4 -22
  72. package/lib/esm/entities/index.d.ts +4 -4
  73. package/lib/esm/entities/index.js +2 -2
  74. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +21 -26
  75. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +44 -82
  76. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.d.ts +6 -3
  77. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.js +2 -2
  78. package/lib/esm/entities/vaultV1/vaultV1.d.ts +5 -11
  79. package/lib/esm/entities/vaultV1/vaultV1.js +4 -12
  80. package/lib/esm/entities/vaultV2/vaultV2.d.ts +37 -18
  81. package/lib/esm/entities/vaultV2/vaultV2.js +37 -13
  82. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +8 -3
  83. package/lib/esm/entities/vaultV2BlueReallocationData.js +49 -7
  84. package/lib/esm/errors.d.ts +4 -4
  85. package/lib/esm/errors.js +4 -4
  86. package/lib/esm/fetch.d.ts +2 -2
  87. package/lib/esm/fetch.js +2 -2
  88. package/lib/esm/helpers/deadShares.js +3 -1
  89. package/lib/esm/midnight/errors.d.ts +2 -1
  90. package/lib/esm/midnight/errors.js +2 -1
  91. package/lib/esm/types/action.d.ts +11 -4
  92. package/lib/esm/types/action.js +1 -0
  93. package/lib/esm/types/error.d.ts +8 -2
  94. package/lib/esm/types/error.js +8 -2
  95. package/lib/esm/utils.d.ts +2 -2
  96. package/lib/esm/utils.js +2 -2
  97. package/package.json +6 -6
@@ -1,23 +1,19 @@
1
1
  import { getChainAddresses } from "@morpho-org/blue-sdk";
2
- import { erc2612Abi, isContractRevertError, isTransportError, isUndecodableResultError, MissingPermitDomainNameError, permit2Abi, } from "@morpho-org/blue-sdk-viem";
2
+ import { erc2612Abi, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isContractRevertError, isTransportError, isUndecodableResultError, MissingPermitDomainNameError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
3
3
  import { _try, isDefined, Time } from "@morpho-org/morpho-ts";
4
- import { erc20Abi, isAddressEqual, maxUint256, } from "viem";
4
+ import { erc20Abi, getTypesForEIP712Domain, hashDomain, isAddressEqual, maxUint256, } from "viem";
5
5
  import { readContract } from "viem/actions";
6
6
  import { resolveBundlesTokenRequirements } from "../../actions/bundles/index.js";
7
7
  import { encodeErc20Permit } from "../../actions/requirements/encode/encodeErc20Permit.js";
8
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
9
  import { validateChainId, validateRequirementSpender, } from "../../helpers/index.js";
10
10
  import { ExpiredDeadlineError, InputExceedsMaxError, NegativeInputError, NonPositiveInputError, } from "../../types/index.js";
11
- import { getUnusedPermit2Nonce } from "./getUnusedPermit2Nonce.js";
12
11
  /**
13
- * Resolves direct approval, ERC-2612, or Permit2 SignatureTransfer prerequisites for
14
- * a registered fixed bundles contract.
12
+ * Resolves direct approval or ERC-2612 prerequisites for a registered fixed bundles contract.
15
13
  *
16
- * Returns no requirements when the direct bundles allowance covers the amount, even when
17
- * signatures are supported. Otherwise reads only the state required by the selected path.
18
- * Permit2 keeps the ERC-20 allowance on canonical Permit2 while the one-time signed transfer
19
- * names the bundles contract as spender. The resolver picks the lowest unused unordered nonce
20
- * by default; concurrent flows for the same owner should pass explicit nonces.
14
+ * Reads the direct allowance first for nonzero amounts. Only when it is insufficient does
15
+ * the selected signature path try ERC-2612 nonce and metadata reads. A permit is returned only
16
+ * when the token's DOMAIN_SEPARATOR matches the domain to be signed; otherwise use approval.
21
17
  *
22
18
  * @param viemClient - Connected viem client used for allowance and nonce reads.
23
19
  * @param params - Token requirement parameters.
@@ -28,37 +24,35 @@ import { getUnusedPermit2Nonce } from "./getUnusedPermit2Nonce.js";
28
24
  * @param params.chainId - Target chain id; must match the client chain.
29
25
  * @param params.deadline - Final-call and signature deadline.
30
26
  * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
31
- * @param params.supportSignature - Whether ERC-2612 or Permit2 signatures may be requested.
27
+ * @param params.supportSignature - Whether ERC-2612 signatures may be requested.
32
28
  * @param params.supportDeployless - Whether ERC-2612 metadata reads may use deployless calls.
33
- * @param params.useSimplePermit - Prefer ERC-2612 when `nonces()` succeeds and the token's permit
34
- * domain is known; a recognized `nonces()` revert or undecodable result, or a missing domain
35
- * (no `name()` and no EIP-5267 domain), falls back to Permit2 or classic approval. A malformed
29
+ * @param params.useSimplePermit - Defaults to true when signatures are supported. Prefer ERC-2612 when `nonces()` succeeds and the token's
30
+ * DOMAIN_SEPARATOR matches the signing domain. Missing, mismatched, or unsupported domains,
31
+ * or recognized nonce/separator reverts or undecodable results, fall back to classic approval. A malformed
36
32
  * `eip712Domain()` result rejects with `MalformedTokenMetadataError`.
37
- * @param params.permit2Nonce - Explicit unused uint256 nonce; defaults to the lowest unused nonce
38
- * found via {@link getUnusedPermit2Nonce}.
39
- * @returns Ordered deep-frozen approval transactions and/or signable token requirements.
33
+ * @param params.permit2Nonce - Deprecated and ignored.
34
+ * @returns Ordered deep-frozen approval transactions and/or signable token requirements;
35
+ * empty when the direct allowance already covers the amount, without probing permit support.
40
36
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
41
37
  * another chain than `params.chainId`.
42
- * @throws {NegativeInputError} when `amount` or `permit2Nonce` is negative.
38
+ * @throws {NegativeInputError} when `amount` is negative.
43
39
  * @throws {NonPositiveInputError} when `deadline` is not positive.
44
40
  * @throws {ExpiredDeadlineError} when `deadline` is positive but not in the future.
45
41
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
46
42
  * @throws {UnsupportedErc20ApprovalSpenderError} when `spender` is not the chain's registered
47
43
  * BlueBundlesV1 or VaultBundlesV1 deployment, including for a zero-amount request.
48
- * @throws {NoUnusedPermit2NonceError} when every Permit2 nonce for the owner is consumed and none
49
- * was passed explicitly.
50
- * @throws {Permit2SignatureTransferNonceAlreadyUsedError} when `permit2Nonce` is already consumed.
51
- * @throws {InputExceedsMaxError} when `amount`, `deadline`, or `permit2Nonce` exceeds uint256.
44
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256.
52
45
  * @throws {UnknownTokenError} when the token's `decimals()` reverts, has no code, returns
53
46
  * undecodable data, or is out of range.
54
47
  * @throws {MalformedTokenMetadataError} when the token's `eip712Domain()` or
55
48
  * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
56
49
  * deployless query reports malformed `name()`/`symbol()`/`eip712Domain()` returndata (no fallback).
57
- * @throws {viem.BaseError} when a required allowance, Permit2 nonce-bitmap, ERC-2612 metadata,
58
- * or `eth_chainId` read fails. An ERC-2612 nonce probe falls back to Permit2 or classic approval
59
- * only when the token reverts or returns undecodable data; other read failures propagate. A
60
- * missing permit domain is handled internally and also falls back; this function does not
61
- * surface `MissingPermitDomainNameError`.
50
+ * @throws {viem.BaseError} when a required allowance, ERC-2612 metadata, DOMAIN_SEPARATOR,
51
+ * or `eth_chainId` read fails. Nonce and separator probes fall back to classic approval
52
+ * only when the token reverts or returns undecodable data; other read failures propagate.
53
+ * `MissingPermitDomainNameError`, `InvalidPermitDomainChainIdError`,
54
+ * `InvalidPermitDomainVerifyingContractError`, and `UnsupportedPermitDomainExtensionsError`
55
+ * are handled internally and fall back to approval.
62
56
  * @example
63
57
  * ```ts
64
58
  * import { addressesRegistry } from "@morpho-org/blue-sdk";
@@ -128,10 +122,10 @@ export const getBundlesTokenRequirements = async (viemClient, params) => {
128
122
  });
129
123
  if (allowance >= params.amount)
130
124
  return [];
131
- const { permit2, dai } = getChainAddresses(params.chainId);
125
+ const { dai } = getChainAddresses(params.chainId);
132
126
  if (params.supportSignature) {
133
127
  const isDai = isDefined(dai) && isAddressEqual(params.token, dai);
134
- if (params.useSimplePermit && !isDai) {
128
+ if ((params.useSimplePermit ?? true) && !isDai) {
135
129
  const nonce = await readContract(viemClient, {
136
130
  abi: erc2612Abi,
137
131
  address: params.token,
@@ -155,61 +149,29 @@ export const getBundlesTokenRequirements = async (viemClient, params) => {
155
149
  deadline: params.deadline,
156
150
  now: timestamp,
157
151
  supportDeployless: params.supportDeployless,
158
- }), MissingPermitDomainNameError);
159
- if (isDefined(permit))
160
- return [permit];
161
- // A token that exposes nonces() but has neither name() nor
162
- // eip712Domain() cannot be permitted over a known domain: fall
163
- // through to the Permit2/classic-approval path.
152
+ }), MissingPermitDomainNameError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, UnsupportedPermitDomainExtensionsError);
153
+ if (isDefined(permit)) {
154
+ const separator = await readContract(viemClient, {
155
+ abi: erc2612Abi,
156
+ address: params.token,
157
+ functionName: "DOMAIN_SEPARATOR",
158
+ }).catch((error) => {
159
+ if (isTransportError(error))
160
+ throw error;
161
+ if (isContractRevertError(error) || isUndecodableResultError(error))
162
+ return undefined;
163
+ throw error;
164
+ });
165
+ const domain = permit.action.typedData.domain ?? {};
166
+ if (separator?.toLowerCase() ===
167
+ hashDomain({
168
+ domain,
169
+ types: { EIP712Domain: getTypesForEIP712Domain({ domain }) },
170
+ }).toLowerCase())
171
+ return [permit];
172
+ }
164
173
  }
165
174
  }
166
- if (permit2 != null) {
167
- const permit2Nonce = params.permit2Nonce ??
168
- (await getUnusedPermit2Nonce(viemClient, {
169
- owner: params.owner,
170
- chainId: params.chainId,
171
- }));
172
- if (permit2Nonce < 0n) {
173
- throw new NegativeInputError("permit2Nonce", permit2Nonce);
174
- }
175
- if (permit2Nonce > maxUint256) {
176
- throw new InputExceedsMaxError({
177
- field: "permit2Nonce",
178
- value: permit2Nonce,
179
- max: maxUint256,
180
- });
181
- }
182
- const wordPosition = permit2Nonce >> 8n;
183
- const [permit2Allowance, nonceBitmap] = await Promise.all([
184
- readContract(viemClient, {
185
- abi: erc20Abi,
186
- address: params.token,
187
- functionName: "allowance",
188
- args: [params.owner, permit2],
189
- }),
190
- readContract(viemClient, {
191
- abi: permit2Abi,
192
- address: permit2,
193
- functionName: "nonceBitmap",
194
- args: [params.owner, wordPosition],
195
- }),
196
- ]);
197
- return resolveBundlesTokenRequirements({
198
- token: params.token,
199
- spender: params.spender,
200
- owner: params.owner,
201
- chainId: params.chainId,
202
- amount: params.amount,
203
- deadline: params.deadline,
204
- now: timestamp,
205
- state: {
206
- type: "permit2SignatureTransfer",
207
- permit2Allowance,
208
- permit2Nonce,
209
- nonceBitmap,
210
- },
211
- });
212
- }
213
175
  }
214
176
  return resolveBundlesTokenRequirements({
215
177
  token: params.token,
@@ -1,5 +1,8 @@
1
1
  import { type Address, type Client } from "viem";
2
- /** Parameters for {@link getUnusedPermit2Nonce}. */
2
+ /**
3
+ * Parameters for {@link getUnusedPermit2Nonce}.
4
+ * @deprecated The SDK no longer requests Permit2 funding; use ERC-2612 permits or ERC-20 approvals.
5
+ */
3
6
  export interface GetUnusedPermit2NonceParams {
4
7
  /** Account that will sign the Permit2 SignatureTransfer. */
5
8
  readonly owner: Address;
@@ -9,8 +12,7 @@ export interface GetUnusedPermit2NonceParams {
9
12
  readonly startNonce?: bigint;
10
13
  }
11
14
  /**
12
- * Finds the lowest unused Permit2 unordered nonce for `owner`, ready to pass as `permit2Nonce` to
13
- * {@link getBundlesTokenRequirements} or as `nonce` to {@link encodeErc20Permit2SignatureTransfer}.
15
+ * Finds the lowest unused Permit2 unordered nonce for legacy SignatureTransfer integrations.
14
16
  *
15
17
  * Permit2 SignatureTransfer consumes an unordered 256-bit nonce; a nonce is free when its bit in
16
18
  * `nonceBitmap(owner, word)` is unset. This scans consecutive bitmap words starting at `startNonce`
@@ -45,5 +47,6 @@ export interface GetUnusedPermit2NonceParams {
45
47
  * });
46
48
  * // permit2Nonce satisfies bigint
47
49
  * ```
50
+ * @deprecated The SDK no longer requests Permit2 funding; use ERC-2612 permits or ERC-20 approvals.
48
51
  */
49
52
  export declare const getUnusedPermit2Nonce: (viemClient: Client, params: GetUnusedPermit2NonceParams) => Promise<bigint>;
@@ -9,8 +9,7 @@ import { NoUnusedPermit2NonceError } from "../../types/index.js";
9
9
  /** Highest Permit2 nonce-bitmap word index; each word covers 256 unordered nonces. */
10
10
  const MAX_PERMIT2_NONCE_WORD = maxUint256 >> 8n;
11
11
  /**
12
- * Finds the lowest unused Permit2 unordered nonce for `owner`, ready to pass as `permit2Nonce` to
13
- * {@link getBundlesTokenRequirements} or as `nonce` to {@link encodeErc20Permit2SignatureTransfer}.
12
+ * Finds the lowest unused Permit2 unordered nonce for legacy SignatureTransfer integrations.
14
13
  *
15
14
  * Permit2 SignatureTransfer consumes an unordered 256-bit nonce; a nonce is free when its bit in
16
15
  * `nonceBitmap(owner, word)` is unset. This scans consecutive bitmap words starting at `startNonce`
@@ -45,6 +44,7 @@ const MAX_PERMIT2_NONCE_WORD = maxUint256 >> 8n;
45
44
  * });
46
45
  * // permit2Nonce satisfies bigint
47
46
  * ```
47
+ * @deprecated The SDK no longer requests Permit2 funding; use ERC-2612 permits or ERC-20 approvals.
48
48
  */
49
49
  export const getUnusedPermit2Nonce = async (viemClient, params) => {
50
50
  validateChainId(viemClient.chain?.id, params.chainId);
@@ -27,8 +27,8 @@ export interface VaultV1Actions {
27
27
  * Prepares a Vault V1 deposit through the registered VaultBundlesV1 contract.
28
28
  *
29
29
  * Uses the supplied vault snapshot to compute the deadline-accrued `maxSharePrice`.
30
- * `getRequirements()` reads the asset allowance and, when enabled, the selected ERC-2612 or
31
- * Permit2 nonce state. Native funding is exclusive and skips token requirements. Shares are
30
+ * `getRequirements()` reads the asset allowance and, when enabled, the selected ERC-2612
31
+ * nonce state. Native funding is exclusive and skips token requirements. Shares are
32
32
  * always minted to the transaction sender, which must be `userAddress`.
33
33
  * Concurrent requirement reads share the first caller's options; later calls refresh on-chain
34
34
  * state using their own options.
@@ -53,19 +53,14 @@ export interface VaultV1Actions {
53
53
  * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
54
54
  * @throws {ExpiredDeadlineError} when the deadline is stale at creation or requirement resolution.
55
55
  * @throws {MixedBundlesFundingError} when ERC-20 and native funding are both supplied.
56
- * @throws {NegativeInputError} when funding, slippage, the referral fee, or a Permit2 nonce is negative.
56
+ * @throws {NegativeInputError} when funding, slippage, or the referral fee is negative.
57
57
  * @throws {NonPositiveInputError} when funding or the previewed vault shares are not positive.
58
58
  * @throws {ExcessiveSlippageToleranceError} when slippage tolerance exceeds the SDK maximum.
59
59
  * @throws {ReferralFeePctExceededError} when the referral fee is at least WAD.
60
60
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
61
61
  * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
62
62
  * @throws {NativeAmountOnNonWNativeVaultError} when native funding targets a non-wNative vault.
63
- * @throws {NoUnusedPermit2NonceError} from `getRequirements()` when every Permit2 nonce for the
64
- * owner is consumed and none was passed explicitly.
65
- * @throws {Permit2SignatureTransferNonceAlreadyUsedError} from `getRequirements()` when the
66
- * explicit Permit2 nonce is consumed.
67
- * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, or from
68
- * `getRequirements()` when the Permit2 nonce exceeds uint256.
63
+ * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256.
69
64
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
70
65
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
71
66
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -481,8 +476,7 @@ export declare class MorphoVaultV1 implements VaultV1Actions {
481
476
  * before any other requirement read. This VaultV1 `inKindRedeem` path validates the client chain
482
477
  * before this code check.
483
478
  *
484
- * @param roles - Registry labels to resolve and check; `permit2` is skipped when the
485
- * chain registers none.
479
+ * @param roles - Registry labels to resolve and check.
486
480
  */
487
481
  private assertWriteTargets;
488
482
  /** {@inheritDoc VaultV1Actions.deposit} */
@@ -1,6 +1,6 @@
1
1
  import { DEFAULT_SLIPPAGE_TOLERANCE, Eip5267Domain, MarketUtils, MathLib, Token, } from "@morpho-org/blue-sdk";
2
2
  import { blueAbi, erc2612Abi, fetchAccrualVault, metaMorphoAbi, } from "@morpho-org/blue-sdk-viem";
3
- import { getChainAddress, getChainAddresses, Time, } from "@morpho-org/morpho-ts";
3
+ import { getChainAddress, Time, } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
5
5
  import { readContract } from "viem/actions";
6
6
  import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundlesFunding, selectBundlesSharesPermitSignature, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
@@ -36,17 +36,12 @@ export class MorphoVaultV1 {
36
36
  * before any other requirement read. This VaultV1 `inKindRedeem` path validates the client chain
37
37
  * before this code check.
38
38
  *
39
- * @param roles - Registry labels to resolve and check; `permit2` is skipped when the
40
- * chain registers none.
39
+ * @param roles - Registry labels to resolve and check.
41
40
  */
42
41
  async assertWriteTargets(roles) {
43
42
  const targets = [];
44
43
  for (const role of roles) {
45
- const address = role === "permit2"
46
- ? getChainAddresses(this.chainId).permit2
47
- : getChainAddress(this.chainId, role);
48
- if (address == null)
49
- continue;
44
+ const address = getChainAddress(this.chainId, role);
50
45
  targets.push({ role, address });
51
46
  }
52
47
  await assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, targets);
@@ -94,9 +89,7 @@ export class MorphoVaultV1 {
94
89
  // Memoize the in-flight promise so concurrent callers share one round of
95
90
  // allowance/nonce reads.
96
91
  const pending = (async () => {
97
- await this.assertWriteTargets(funding.value === 0n && this.client.options.supportSignature
98
- ? ["bundles.vaultBundlesV1", "permit2"]
99
- : ["bundles.vaultBundlesV1"]);
92
+ await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
100
93
  return funding.value > 0n
101
94
  ? []
102
95
  : getBundlesTokenRequirements(this.client.viemClient, {
@@ -109,7 +102,6 @@ export class MorphoVaultV1 {
109
102
  supportSignature: this.client.options.supportSignature,
110
103
  supportDeployless: this.client.options.supportDeployless,
111
104
  useSimplePermit: requirementOptions?.useSimplePermit,
112
- permit2Nonce: requirementOptions?.permit2Nonce,
113
105
  now,
114
106
  });
115
107
  })();
@@ -32,8 +32,8 @@ export interface VaultV2Actions {
32
32
  * Prepares a Vault V2 deposit through the registered VaultBundlesV1 contract.
33
33
  *
34
34
  * Uses the supplied vault snapshot to compute the deadline-accrued `maxSharePrice`.
35
- * `getRequirements()` reads the asset allowance and, when enabled, the selected ERC-2612 or
36
- * Permit2 nonce state. Native funding is exclusive and skips token requirements. Shares are
35
+ * `getRequirements()` reads the asset allowance and, when enabled, the selected ERC-2612
36
+ * nonce state. Native funding is exclusive and skips token requirements. Shares are
37
37
  * always minted to the transaction sender, which must be `userAddress`.
38
38
  * Concurrent requirement reads share the first caller's options; later calls refresh on-chain
39
39
  * state using their own options.
@@ -58,19 +58,16 @@ export interface VaultV2Actions {
58
58
  * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
59
59
  * @throws {ExpiredDeadlineError} when the deadline is stale at creation or requirement resolution.
60
60
  * @throws {MixedBundlesFundingError} when ERC-20 and native funding are both supplied.
61
- * @throws {NegativeInputError} when funding, slippage, the referral fee, or a Permit2 nonce is negative.
61
+ * @throws {NegativeInputError} when funding, slippage, or the referral fee is negative.
62
62
  * @throws {NonPositiveInputError} when funding or the previewed vault shares are not positive.
63
63
  * @throws {ExcessiveSlippageToleranceError} when slippage tolerance exceeds the SDK maximum.
64
64
  * @throws {ReferralFeePctExceededError} when the referral fee is at least WAD.
65
65
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
66
66
  * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
67
67
  * @throws {NativeAmountOnNonWNativeVaultError} when native funding targets a non-wNative vault.
68
- * @throws {NoUnusedPermit2NonceError} from `getRequirements()` when every Permit2 nonce for the
69
- * owner is consumed and none was passed explicitly.
70
- * @throws {Permit2SignatureTransferNonceAlreadyUsedError} from `getRequirements()` when the
71
- * explicit Permit2 nonce is consumed.
72
- * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, or from
73
- * `getRequirements()` when the Permit2 nonce exceeds uint256.
68
+ * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, or when the vault's
69
+ * liquidity adapter is a Midnight adapter (it cannot receive vault allocations, so no deposit
70
+ * fits and `max` is `0n`).
74
71
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
75
72
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
76
73
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -152,7 +149,9 @@ export interface VaultV2Actions {
152
149
  * @throws {NonPositiveInputError} when `amount` or the computed required share amount is not positive.
153
150
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
154
151
  * at any `getRequirements()` call.
155
- * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation.
152
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation,
153
+ * or when the vault's liquidity adapter is a Midnight adapter and `amount` exceeds the vault's
154
+ * idle assets.
156
155
  * @throws {NegativeInputError} when `referralFeePct` or `slippageTolerance` is negative.
157
156
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
158
157
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no nonzero recipient.
@@ -218,7 +217,24 @@ export interface VaultV2Actions {
218
217
  * @throws {NonPositiveInputError} when `shares` is not positive.
219
218
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
220
219
  * requirement resolution.
221
- * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
220
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256, or from
221
+ * `getRequirements()` when the vault's liquidity adapter is a Midnight adapter and `shares`
222
+ * are worth more than the vault's idle assets.
223
+ * @throws {UnknownBlueFactory} from `getRequirements()` when the configured chain has no VaultV2 factory.
224
+ * @throws {UnknownBlueOfFactory} from `getRequirements()` when the vault is not a VaultV2 from the
225
+ * configured factory.
226
+ * @throws {UnsupportedBlueVaultV2AdapterError} from `getRequirements()` when the vault or one of its
227
+ * adapters uses an unsupported adapter class.
228
+ * @throws {UnsupportedBlueMarketIrmError} from `getRequirements()` when the vault's liquidity adapter
229
+ * is a Midnight adapter and accrual projects an underlying market with positive debt that uses an
230
+ * unsupported IRM.
231
+ * @throws {UnknownBlueMarketAllocationError} from `getRequirements()` when the vault's liquidity
232
+ * adapter is a Midnight adapter and accrual meets a nested Vault V1 withdraw queue market without
233
+ * allocation data.
234
+ * @throws {InvalidMidnightPositionLossFactorError} from `getRequirements()` when the vault's liquidity
235
+ * adapter is a Midnight adapter and accrual meets a market loss factor below a position's.
236
+ * @throws {InvalidMidnightPositionAccrualStateError} from `getRequirements()` when the vault's
237
+ * liquidity adapter is a Midnight adapter and accrual meets invalid Midnight position inputs.
222
238
  * @throws {NegativeInputError} when `referralFeePct` is negative.
223
239
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
224
240
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
@@ -226,7 +242,7 @@ export interface VaultV2Actions {
226
242
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
227
243
  * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
228
244
  * contract has no code at its registered address.
229
- * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, `eth_chainId`, or
245
+ * @throws {viem.BaseError} from `getRequirements()` when a vault-state, allowance, nonce, `eth_chainId`, or
230
246
  * `eth_getCode` read fails.
231
247
  * @throws {UnknownTokenError} from `getRequirements()` when the share token fetched by
232
248
  * `getData()` has unusable decimals.
@@ -304,9 +320,11 @@ export interface VaultV2Actions {
304
320
  * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256`.
305
321
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
306
322
  * requirement resolution.
307
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter.
323
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter, including
324
+ * a vault that mixes Blue and Midnight adapters.
308
325
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
309
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
326
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
327
+ * including a Midnight adapter.
310
328
  * @throws {InKindRedeemCoverageError} when the deduplicated list cannot cover the exit.
311
329
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
312
330
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
@@ -431,9 +449,11 @@ export interface VaultV2Actions {
431
449
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
432
450
  * requirement resolution.
433
451
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
434
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter.
452
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter,
453
+ * including a vault that mixes Blue and Midnight adapters.
435
454
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
436
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
455
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
456
+ * including a Midnight adapter.
437
457
  * @throws {VaultV2UnsupportedLiquidityAdapterError} when the vault routes liquidity through
438
458
  * another adapter.
439
459
  * @throws {VaultV2UndecodableLiquidityDataError} when the vault's `liquidityData` does not decode
@@ -555,8 +575,7 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
555
575
  * before any other requirement read. The `inKindRedeem` and `forceWithdraw` paths validate the
556
576
  * client chain before this code check.
557
577
  *
558
- * @param roles - Registry labels to resolve and check; `permit2` is skipped when the
559
- * chain registers none.
578
+ * @param roles - Registry labels to resolve and check.
560
579
  */
561
580
  private assertWriteTargets;
562
581
  /** {@inheritDoc VaultV2Actions.deposit} */
@@ -1,6 +1,6 @@
1
1
  import { AccrualVaultV2MorphoMarketV1AdapterV2, DEFAULT_SLIPPAGE_TOLERANCE, MarketParams, MarketUtils, MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { erc2612Abi, fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
- import { _try, getChainAddress, getChainAddresses, Time, } from "@morpho-org/morpho-ts";
3
+ import { _try, getChainAddress, Time, } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
5
5
  import { readContract } from "viem/actions";
6
6
  import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundlesFunding, selectBundlesSharesPermitSignature, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
@@ -15,6 +15,11 @@ import { getBundlesTokenRequirements } from "../requirements/index.js";
15
15
  // Maximum accepted deadline horizon; the on-chain management fee is capped at 5%/yr so the
16
16
  // accrual model stays well-defined inside it.
17
17
  const VAULT_V2_FEE_PROJECTION_HORIZON = Time.s.from.y(1n);
18
+ /**
19
+ * Midnight adapters revert vault-initiated `allocate` and `deallocate` (`SelfAllocationOnly`), so a
20
+ * vault routing liquidity through one accepts no deposit and serves exits from idle assets only.
21
+ */
22
+ const isMidnightLiquidityAdapter = (vaultData) => vaultData.accrualLiquidityAdapter?.type === "VaultV2MidnightAdapter";
18
23
  /** Binds a viem client to a Vault V2 vault's action builders. */
19
24
  export class MorphoVaultV2 {
20
25
  client;
@@ -39,17 +44,12 @@ export class MorphoVaultV2 {
39
44
  * before any other requirement read. The `inKindRedeem` and `forceWithdraw` paths validate the
40
45
  * client chain before this code check.
41
46
  *
42
- * @param roles - Registry labels to resolve and check; `permit2` is skipped when the
43
- * chain registers none.
47
+ * @param roles - Registry labels to resolve and check.
44
48
  */
45
49
  async assertWriteTargets(roles) {
46
50
  const targets = [];
47
51
  for (const role of roles) {
48
- const address = role === "permit2"
49
- ? getChainAddresses(this.chainId).permit2
50
- : getChainAddress(this.chainId, role);
51
- if (address == null)
52
- continue;
52
+ const address = getChainAddress(this.chainId, role);
53
53
  targets.push({ role, address });
54
54
  }
55
55
  await assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, targets);
@@ -78,6 +78,13 @@ export class MorphoVaultV2 {
78
78
  // The native path must target the chain's registered wrapped-native asset.
79
79
  validateNativeVaultAsset(this.chainId, vaultAsset);
80
80
  }
81
+ if (isMidnightLiquidityAdapter(vaultData)) {
82
+ throw new InputExceedsMaxError({
83
+ field: funding.value > 0n ? "nativeAmount" : "amount",
84
+ value: funding.assets,
85
+ max: 0n,
86
+ });
87
+ }
81
88
  const referralFeeAssets = getBundlesReferralFeeAssets(funding.assets, common.referralFeePct);
82
89
  const maxSharePrice = computeVaultMaxSharePrice({
83
90
  vaultData,
@@ -97,9 +104,7 @@ export class MorphoVaultV2 {
97
104
  // Memoize the in-flight promise so concurrent callers share one round of
98
105
  // allowance/nonce reads.
99
106
  const pending = (async () => {
100
- await this.assertWriteTargets(funding.value === 0n && this.client.options.supportSignature
101
- ? ["bundles.vaultBundlesV1", "permit2"]
102
- : ["bundles.vaultBundlesV1"]);
107
+ await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
103
108
  return funding.value > 0n
104
109
  ? []
105
110
  : getBundlesTokenRequirements(this.client.viemClient, {
@@ -112,7 +117,6 @@ export class MorphoVaultV2 {
112
117
  supportSignature: this.client.options.supportSignature,
113
118
  supportDeployless: this.client.options.supportDeployless,
114
119
  useSimplePermit: requirementOptions?.useSimplePermit,
115
- permit2Nonce: requirementOptions?.permit2Nonce,
116
120
  now,
117
121
  });
118
122
  })();
@@ -161,6 +165,14 @@ export class MorphoVaultV2 {
161
165
  throw new NonPositiveInputError("amount", amount);
162
166
  // Reject values outside the ABI range before resolving any requirements.
163
167
  validateUint256Field("amount", amount);
168
+ if (isMidnightLiquidityAdapter(vaultData) &&
169
+ amount > vaultData.assetBalance) {
170
+ throw new InputExceedsMaxError({
171
+ field: "amount",
172
+ value: amount,
173
+ max: vaultData.assetBalance,
174
+ });
175
+ }
164
176
  const createdAt = Time.timestamp();
165
177
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
166
178
  if (deadline <= createdAt)
@@ -241,8 +253,20 @@ export class MorphoVaultV2 {
241
253
  if (deadline <= now)
242
254
  throw new ExpiredDeadlineError(deadline, now);
243
255
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
256
+ const vaultData = await this.getData();
257
+ if (isMidnightLiquidityAdapter(vaultData)) {
258
+ // Onchain redeem accrues interest before converting shares to assets.
259
+ const { vault: accrued } = vaultData.accrueInterest(now);
260
+ if (accrued.toAssets(shares) > accrued.assetBalance) {
261
+ throw new InputExceedsMaxError({
262
+ field: "shares",
263
+ value: shares,
264
+ max: accrued.toShares(accrued.assetBalance),
265
+ });
266
+ }
267
+ }
244
268
  return getVaultBundlesSharesRequirements(this.client.viemClient, {
245
- vaultData: await this.getData(),
269
+ vaultData,
246
270
  version: "vaultV2",
247
271
  owner: userAddress,
248
272
  chainId: this.chainId,
@@ -56,8 +56,9 @@ export interface InputVaultV2BlueReallocationData {
56
56
  /**
57
57
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
58
58
  *
59
- * Constructor inputs are cloned. Every simulated reallocation returns a new
60
- * instance. Planning keeps the transaction-scoped `firstTotalAssets`
59
+ * Constructor inputs are cloned, except Midnight adapter snapshots: those are
60
+ * shared by reference and must be treated as read-only. Every simulated
61
+ * reallocation returns a new instance. Planning keeps the transaction-scoped `firstTotalAssets`
61
62
  * denominator outside the durable snapshot while applying reallocations in
62
63
  * contract order. Penalty donations update simulated vault accounting but are
63
64
  * excluded from same-plan idle liquidity so round-up dust cannot create
@@ -131,7 +132,8 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
131
132
  /**
132
133
  * Clones the complete simulation snapshot.
133
134
  *
134
- * @returns A deep clone of this simulation state.
135
+ * @returns A deep clone of this simulation state. Midnight adapter snapshots are
136
+ * shared by reference and must be treated as read-only.
135
137
  * @example
136
138
  * ```ts
137
139
  * import { markets } from "@morpho-org/morpho-test";
@@ -450,6 +452,9 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
450
452
  * Full-liquidity discovery omits a candidate when its non-shared maximum
451
453
  * violates a shared cap instead of scanning smaller base-unit amounts. These
452
454
  * bounds can understate executable liquidity in rounding-only edge cases.
455
+ * With an explicit Blue balance, a paid operation may retry the same search
456
+ * from a physical-funding budget and keep a strictly cheaper feasible plan.
457
+ * This bounded refinement does not guarantee globally minimal penalties.
453
458
  *
454
459
  * @param marketId - Target Blue market id.
455
460
  * @param options - Optional discovery controls and operation to support.