@morpho-org/morpho-sdk 9.3.0 → 9.5.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 (75) 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 +9 -5
  5. package/lib/cjs/abis.d.ts +2 -2
  6. package/lib/cjs/abis.js +4 -1
  7. package/lib/cjs/actions/blue/index.d.ts +1 -0
  8. package/lib/cjs/actions/blue/index.js +1 -0
  9. package/lib/cjs/actions/blue/withdrawBuyCallback.d.ts +60 -0
  10. package/lib/cjs/actions/blue/withdrawBuyCallback.js +79 -0
  11. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -0
  12. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -1
  13. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +4 -1
  14. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -1
  15. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  16. package/lib/cjs/blue/abis.d.ts +1 -1
  17. package/lib/cjs/blue/abis.js +3 -1
  18. package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
  19. package/lib/cjs/client/morphoViemExtension.js +1 -1
  20. package/lib/cjs/entities/blue/blue.d.ts +88 -23
  21. package/lib/cjs/entities/blue/blue.js +89 -22
  22. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +21 -25
  23. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +50 -85
  24. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.d.ts +6 -3
  25. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.js +2 -2
  26. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +5 -11
  27. package/lib/cjs/entities/vaultV1/vaultV1.js +3 -11
  28. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +5 -11
  29. package/lib/cjs/entities/vaultV2/vaultV2.js +3 -11
  30. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +3 -0
  31. package/lib/cjs/entities/vaultV2BlueReallocationData.js +40 -4
  32. package/lib/cjs/errors.d.ts +1 -1
  33. package/lib/cjs/errors.js +3 -1
  34. package/lib/cjs/midnight/abis.d.ts +1 -1
  35. package/lib/cjs/midnight/abis.js +2 -1
  36. package/lib/cjs/types/action.d.ts +26 -5
  37. package/lib/cjs/types/action.js +1 -0
  38. package/lib/cjs/types/error.d.ts +42 -2
  39. package/lib/cjs/types/error.js +49 -3
  40. package/lib/esm/abis.d.ts +2 -2
  41. package/lib/esm/abis.js +2 -2
  42. package/lib/esm/actions/blue/index.d.ts +1 -0
  43. package/lib/esm/actions/blue/index.js +1 -0
  44. package/lib/esm/actions/blue/withdrawBuyCallback.d.ts +60 -0
  45. package/lib/esm/actions/blue/withdrawBuyCallback.js +75 -0
  46. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -0
  47. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -1
  48. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +4 -1
  49. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -1
  50. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  51. package/lib/esm/blue/abis.d.ts +1 -1
  52. package/lib/esm/blue/abis.js +1 -1
  53. package/lib/esm/client/morphoViemExtension.d.ts +1 -1
  54. package/lib/esm/client/morphoViemExtension.js +1 -1
  55. package/lib/esm/entities/blue/blue.d.ts +88 -23
  56. package/lib/esm/entities/blue/blue.js +91 -24
  57. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +21 -25
  58. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +52 -87
  59. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.d.ts +6 -3
  60. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.js +2 -2
  61. package/lib/esm/entities/vaultV1/vaultV1.d.ts +5 -11
  62. package/lib/esm/entities/vaultV1/vaultV1.js +4 -12
  63. package/lib/esm/entities/vaultV2/vaultV2.d.ts +5 -11
  64. package/lib/esm/entities/vaultV2/vaultV2.js +4 -12
  65. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +3 -0
  66. package/lib/esm/entities/vaultV2BlueReallocationData.js +40 -4
  67. package/lib/esm/errors.d.ts +1 -1
  68. package/lib/esm/errors.js +1 -1
  69. package/lib/esm/midnight/abis.d.ts +1 -1
  70. package/lib/esm/midnight/abis.js +1 -1
  71. package/lib/esm/types/action.d.ts +26 -5
  72. package/lib/esm/types/action.js +1 -0
  73. package/lib/esm/types/error.d.ts +42 -2
  74. package/lib/esm/types/error.js +43 -2
  75. package/package.json +5 -5
@@ -1,22 +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
- * Reads only the allowance and nonce state required by the selected path. Permit2 keeps the
17
- * ERC-20 allowance on canonical Permit2 while the one-time signed transfer names the bundles contract
18
- * as spender. The resolver picks the lowest unused unordered nonce by default; concurrent flows for
19
- * 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.
20
17
  *
21
18
  * @param viemClient - Connected viem client used for allowance and nonce reads.
22
19
  * @param params - Token requirement parameters.
@@ -27,37 +24,35 @@ import { getUnusedPermit2Nonce } from "./getUnusedPermit2Nonce.js";
27
24
  * @param params.chainId - Target chain id; must match the client chain.
28
25
  * @param params.deadline - Final-call and signature deadline.
29
26
  * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
30
- * @param params.supportSignature - Whether ERC-2612 or Permit2 signatures may be requested.
27
+ * @param params.supportSignature - Whether ERC-2612 signatures may be requested.
31
28
  * @param params.supportDeployless - Whether ERC-2612 metadata reads may use deployless calls.
32
- * @param params.useSimplePermit - Prefer ERC-2612 when `nonces()` succeeds and the token's permit
33
- * domain is known; a recognized `nonces()` revert or undecodable result, or a missing domain
34
- * (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
35
32
  * `eip712Domain()` result rejects with `MalformedTokenMetadataError`.
36
- * @param params.permit2Nonce - Explicit unused uint256 nonce; defaults to the lowest unused nonce
37
- * found via {@link getUnusedPermit2Nonce}.
38
- * @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.
39
36
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
40
37
  * another chain than `params.chainId`.
41
- * @throws {NegativeInputError} when `amount` or `permit2Nonce` is negative.
38
+ * @throws {NegativeInputError} when `amount` is negative.
42
39
  * @throws {NonPositiveInputError} when `deadline` is not positive.
43
40
  * @throws {ExpiredDeadlineError} when `deadline` is positive but not in the future.
44
41
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
45
42
  * @throws {UnsupportedErc20ApprovalSpenderError} when `spender` is not the chain's registered
46
43
  * BlueBundlesV1 or VaultBundlesV1 deployment, including for a zero-amount request.
47
- * @throws {NoUnusedPermit2NonceError} when every Permit2 nonce for the owner is consumed and none
48
- * was passed explicitly.
49
- * @throws {Permit2SignatureTransferNonceAlreadyUsedError} when `permit2Nonce` is already consumed.
50
- * @throws {InputExceedsMaxError} when `amount`, `deadline`, or `permit2Nonce` exceeds uint256.
44
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256.
51
45
  * @throws {UnknownTokenError} when the token's `decimals()` reverts, has no code, returns
52
46
  * undecodable data, or is out of range.
53
47
  * @throws {MalformedTokenMetadataError} when the token's `eip712Domain()` or
54
48
  * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
55
49
  * deployless query reports malformed `name()`/`symbol()`/`eip712Domain()` returndata (no fallback).
56
- * @throws {viem.BaseError} when a required allowance, Permit2 nonce-bitmap, ERC-2612 metadata,
57
- * or `eth_chainId` read fails. An ERC-2612 nonce probe falls back to Permit2 or classic approval
58
- * only when the token reverts or returns undecodable data; other read failures propagate. A
59
- * missing permit domain is handled internally and also falls back; this function does not
60
- * 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.
61
56
  * @example
62
57
  * ```ts
63
58
  * import { addressesRegistry } from "@morpho-org/blue-sdk";
@@ -119,10 +114,18 @@ export const getBundlesTokenRequirements = async (viemClient, params) => {
119
114
  if (params.amount === 0n)
120
115
  return [];
121
116
  await validateClientChainId(viemClient, params.chainId);
122
- const { permit2, dai } = getChainAddresses(params.chainId);
117
+ const allowance = await readContract(viemClient, {
118
+ abi: erc20Abi,
119
+ address: params.token,
120
+ functionName: "allowance",
121
+ args: [params.owner, params.spender],
122
+ });
123
+ if (allowance >= params.amount)
124
+ return [];
125
+ const { dai } = getChainAddresses(params.chainId);
123
126
  if (params.supportSignature) {
124
127
  const isDai = isDefined(dai) && isAddressEqual(params.token, dai);
125
- if (params.useSimplePermit && !isDai) {
128
+ if ((params.useSimplePermit ?? true) && !isDai) {
126
129
  const nonce = await readContract(viemClient, {
127
130
  abi: erc2612Abi,
128
131
  address: params.token,
@@ -146,68 +149,30 @@ export const getBundlesTokenRequirements = async (viemClient, params) => {
146
149
  deadline: params.deadline,
147
150
  now: timestamp,
148
151
  supportDeployless: params.supportDeployless,
149
- }), MissingPermitDomainNameError);
150
- if (isDefined(permit))
151
- return [permit];
152
- // A token that exposes nonces() but has neither name() nor
153
- // eip712Domain() cannot be permitted over a known domain: fall
154
- // 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
+ }
155
173
  }
156
174
  }
157
- if (permit2 != null) {
158
- const permit2Nonce = params.permit2Nonce ??
159
- (await getUnusedPermit2Nonce(viemClient, {
160
- owner: params.owner,
161
- chainId: params.chainId,
162
- }));
163
- if (permit2Nonce < 0n) {
164
- throw new NegativeInputError("permit2Nonce", permit2Nonce);
165
- }
166
- if (permit2Nonce > maxUint256) {
167
- throw new InputExceedsMaxError({
168
- field: "permit2Nonce",
169
- value: permit2Nonce,
170
- max: maxUint256,
171
- });
172
- }
173
- const wordPosition = permit2Nonce >> 8n;
174
- const [allowance, nonceBitmap] = await Promise.all([
175
- readContract(viemClient, {
176
- abi: erc20Abi,
177
- address: params.token,
178
- functionName: "allowance",
179
- args: [params.owner, permit2],
180
- }),
181
- readContract(viemClient, {
182
- abi: permit2Abi,
183
- address: permit2,
184
- functionName: "nonceBitmap",
185
- args: [params.owner, wordPosition],
186
- }),
187
- ]);
188
- return resolveBundlesTokenRequirements({
189
- token: params.token,
190
- spender: params.spender,
191
- owner: params.owner,
192
- chainId: params.chainId,
193
- amount: params.amount,
194
- deadline: params.deadline,
195
- now: timestamp,
196
- state: {
197
- type: "permit2SignatureTransfer",
198
- permit2Allowance: allowance,
199
- permit2Nonce,
200
- nonceBitmap,
201
- },
202
- });
203
- }
204
175
  }
205
- const allowance = await readContract(viemClient, {
206
- abi: erc20Abi,
207
- address: params.token,
208
- functionName: "allowance",
209
- args: [params.owner, params.spender],
210
- });
211
176
  return resolveBundlesTokenRequirements({
212
177
  token: params.token,
213
178
  spender: params.spender,
@@ -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,14 @@ 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.
74
69
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
75
70
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
76
71
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -555,8 +550,7 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
555
550
  * before any other requirement read. The `inKindRedeem` and `forceWithdraw` paths validate the
556
551
  * client chain before this code check.
557
552
  *
558
- * @param roles - Registry labels to resolve and check; `permit2` is skipped when the
559
- * chain registers none.
553
+ * @param roles - Registry labels to resolve and check.
560
554
  */
561
555
  private assertWriteTargets;
562
556
  /** {@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";
@@ -39,17 +39,12 @@ export class MorphoVaultV2 {
39
39
  * before any other requirement read. The `inKindRedeem` and `forceWithdraw` paths validate the
40
40
  * client chain before this code check.
41
41
  *
42
- * @param roles - Registry labels to resolve and check; `permit2` is skipped when the
43
- * chain registers none.
42
+ * @param roles - Registry labels to resolve and check.
44
43
  */
45
44
  async assertWriteTargets(roles) {
46
45
  const targets = [];
47
46
  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;
47
+ const address = getChainAddress(this.chainId, role);
53
48
  targets.push({ role, address });
54
49
  }
55
50
  await assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, targets);
@@ -97,9 +92,7 @@ export class MorphoVaultV2 {
97
92
  // Memoize the in-flight promise so concurrent callers share one round of
98
93
  // allowance/nonce reads.
99
94
  const pending = (async () => {
100
- await this.assertWriteTargets(funding.value === 0n && this.client.options.supportSignature
101
- ? ["bundles.vaultBundlesV1", "permit2"]
102
- : ["bundles.vaultBundlesV1"]);
95
+ await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
103
96
  return funding.value > 0n
104
97
  ? []
105
98
  : getBundlesTokenRequirements(this.client.viemClient, {
@@ -112,7 +105,6 @@ export class MorphoVaultV2 {
112
105
  supportSignature: this.client.options.supportSignature,
113
106
  supportDeployless: this.client.options.supportDeployless,
114
107
  useSimplePermit: requirementOptions?.useSimplePermit,
115
- permit2Nonce: requirementOptions?.permit2Nonce,
116
108
  now,
117
109
  });
118
110
  })();
@@ -450,6 +450,9 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
450
450
  * Full-liquidity discovery omits a candidate when its non-shared maximum
451
451
  * violates a shared cap instead of scanning smaller base-unit amounts. These
452
452
  * bounds can understate executable liquidity in rounding-only edge cases.
453
+ * With an explicit Blue balance, a paid operation may retry the same search
454
+ * from a physical-funding budget and keep a strictly cheaper feasible plan.
455
+ * This bounded refinement does not guarantee globally minimal penalties.
453
456
  *
454
457
  * @param marketId - Target Blue market id.
455
458
  * @param options - Optional discovery controls and operation to support.
@@ -651,6 +651,9 @@ export class VaultV2BlueReallocationData {
651
651
  * Full-liquidity discovery omits a candidate when its non-shared maximum
652
652
  * violates a shared cap instead of scanning smaller base-unit amounts. These
653
653
  * bounds can understate executable liquidity in rounding-only edge cases.
654
+ * With an explicit Blue balance, a paid operation may retry the same search
655
+ * from a physical-funding budget and keep a strictly cheaper feasible plan.
656
+ * This bounded refinement does not guarantee globally minimal penalties.
654
657
  *
655
658
  * @param marketId - Target Blue market id.
656
659
  * @param options - Optional discovery controls and operation to support.
@@ -805,7 +808,7 @@ export class VaultV2BlueReallocationData {
805
808
  ? [config.penalty]
806
809
  : [])),
807
810
  ].sort(bigIntComparator((tier) => tier));
808
- const plan = (maxAssets, headroom) => {
811
+ const plan = (maxAssets, { headroom, usePhysicalBalance = false, }) => {
809
812
  let reserves = createCapReserveState(this.mutableMarkets);
810
813
  const reallocations = [];
811
814
  let data = this.clone();
@@ -829,6 +832,19 @@ export class VaultV2BlueReallocationData {
829
832
  : isFreeFriendlyPass
830
833
  ? maxAssets
831
834
  : remainingShortfall;
835
+ if (usePhysicalBalance && penalty > 0n) {
836
+ const penaltyMultiplier = type === "refinance" ? 2n : 1n;
837
+ const physicalPenalty = penaltyMultiplier * penalty;
838
+ if (physicalPenalty < MathLib.WAD) {
839
+ const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
840
+ // Idle must fund both the operation and its penalty flash loan.
841
+ const physicalShortfall = MathLib.zeroFloorSub(amount +
842
+ feeAssets +
843
+ penaltyMultiplier *
844
+ getBlueBundlesV1PenaltyAssets(reallocations), blueBalance + idleAssets);
845
+ passMaxAssets = MathLib.max(passMaxAssets, MathLib.mulDivUp(physicalShortfall, MathLib.WAD, MathLib.WAD - physicalPenalty));
846
+ }
847
+ }
832
848
  const retryPaidPass = penalty > 0n;
833
849
  let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
834
850
  let tryFullCapacityAttempt = false;
@@ -1019,6 +1035,8 @@ export class VaultV2BlueReallocationData {
1019
1035
  ? reallocatedAssets >= absoluteShortfall + penaltyAssets
1020
1036
  : reallocatedAssets >= absoluteShortfall;
1021
1037
  return {
1038
+ maxAssets,
1039
+ headroom,
1022
1040
  reallocations,
1023
1041
  data,
1024
1042
  liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
@@ -1035,12 +1053,12 @@ export class VaultV2BlueReallocationData {
1035
1053
  // (nearly) all of a source vault's starting idle, revert once another
1036
1054
  // allocation lands first. A bound plan therefore moves only the operation's
1037
1055
  // shortfall, or what unbound legs moved.
1038
- const target = plan(requiredAssets, allocatorCapHeadroom);
1056
+ const target = plan(requiredAssets, { headroom: allocatorCapHeadroom });
1039
1057
  let selected = target;
1040
1058
  if (allocatorCapHeadroom > 0n && target.liquidityBound) {
1041
1059
  selected = plan(absoluteShortfall > target.unboundAssets
1042
1060
  ? absoluteShortfall
1043
- : target.unboundAssets, allocatorCapHeadroom);
1061
+ : target.unboundAssets, { headroom: allocatorCapHeadroom });
1044
1062
  // Shared-cap fitting is not monotonic in the budget.
1045
1063
  if (!selected.coversShortfall && target.coversShortfall)
1046
1064
  selected = target;
@@ -1051,7 +1069,7 @@ export class VaultV2BlueReallocationData {
1051
1069
  for (const maxAssets of fullCapBudgets) {
1052
1070
  if (selected.coversShortfall)
1053
1071
  break;
1054
- selected = plan(maxAssets, 0n);
1072
+ selected = plan(maxAssets, { headroom: 0n });
1055
1073
  if (selected.reallocatedAssets > available)
1056
1074
  available = selected.reallocatedAssets;
1057
1075
  }
@@ -1083,6 +1101,24 @@ export class VaultV2BlueReallocationData {
1083
1101
  available,
1084
1102
  });
1085
1103
  }
1104
+ const selectedPenaltyAssets = getBlueBundlesV1PenaltyAssets(selected.reallocations);
1105
+ if (hasExplicitBlueBalance &&
1106
+ selectedPenaltyAssets > 1n &&
1107
+ blueBalance <
1108
+ amount +
1109
+ feeAssets +
1110
+ (type === "refinance" ? 2n : 1n) * selectedPenaltyAssets) {
1111
+ // Amount feasibility is not monotonic: retain the original plan unless
1112
+ // the physical-balance seed finds a fully funded, strictly cheaper one.
1113
+ const alternative = plan(selected.maxAssets, {
1114
+ headroom: selected.headroom,
1115
+ usePhysicalBalance: true,
1116
+ });
1117
+ if (alternative.coversShortfall &&
1118
+ getBlueBundlesV1PenaltyAssets(alternative.reallocations) <
1119
+ getBlueBundlesV1PenaltyAssets(selected.reallocations))
1120
+ selected = alternative;
1121
+ }
1086
1122
  return { reallocations: selected.reallocations, data: selected.data };
1087
1123
  }
1088
1124
  computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
@@ -4,4 +4,4 @@ UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError
4
4
  export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
5
  export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
7
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
package/lib/esm/errors.js CHANGED
@@ -3,4 +3,4 @@ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as I
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
4
  export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
5
  export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
6
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
@@ -1 +1 @@
1
- export { blueBuyCallbackFactoryAbi, ecrecoverAuthorizerAbi, ecrecoverRatifierAbi, midnightAbi, midnightBundlesV2Abi, midnightEventsAbi, priceRatifierV1Abi, rateRatifierV1Abi, setterRatifierAbi, } from "@morpho-org/midnight-sdk";
1
+ export { blueBuyCallbackAbi, blueBuyCallbackFactoryAbi, ecrecoverAuthorizerAbi, ecrecoverRatifierAbi, midnightAbi, midnightBundlesV2Abi, midnightEventsAbi, priceRatifierV1Abi, rateRatifierV1Abi, setterRatifierAbi, } from "@morpho-org/midnight-sdk";
@@ -1 +1 @@
1
- export { blueBuyCallbackFactoryAbi, ecrecoverAuthorizerAbi, ecrecoverRatifierAbi, midnightAbi, midnightBundlesV2Abi, midnightEventsAbi, priceRatifierV1Abi, rateRatifierV1Abi, setterRatifierAbi, } from "@morpho-org/midnight-sdk";
1
+ export { blueBuyCallbackAbi, blueBuyCallbackFactoryAbi, ecrecoverAuthorizerAbi, ecrecoverRatifierAbi, midnightAbi, midnightBundlesV2Abi, midnightEventsAbi, priceRatifierV1Abi, rateRatifierV1Abi, setterRatifierAbi, } from "@morpho-org/midnight-sdk";