@morpho-org/morpho-sdk 6.3.0 → 6.4.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 (31) hide show
  1. package/MIGRATION-v5-to-v6.md +4 -3
  2. package/README.md +3 -2
  3. package/lib/cjs/blue/errors.d.ts +1 -1
  4. package/lib/cjs/blue/errors.js +2 -1
  5. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +10 -6
  6. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +13 -12
  7. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +6 -4
  8. package/lib/cjs/entities/vaultV1/vaultV1.js +13 -0
  9. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +3 -2
  10. package/lib/cjs/entities/vaultV2/vaultV2.js +6 -0
  11. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +3 -2
  12. package/lib/cjs/entities/vaultV2BlueReallocationData.js +9 -14
  13. package/lib/cjs/errors.d.ts +1 -1
  14. package/lib/cjs/errors.js +2 -1
  15. package/lib/cjs/helpers/slippage.d.ts +19 -0
  16. package/lib/cjs/helpers/slippage.js +21 -1
  17. package/lib/esm/blue/errors.d.ts +1 -1
  18. package/lib/esm/blue/errors.js +1 -1
  19. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +10 -6
  20. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +13 -12
  21. package/lib/esm/entities/vaultV1/vaultV1.d.ts +6 -4
  22. package/lib/esm/entities/vaultV1/vaultV1.js +13 -0
  23. package/lib/esm/entities/vaultV2/vaultV2.d.ts +3 -2
  24. package/lib/esm/entities/vaultV2/vaultV2.js +6 -0
  25. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +3 -2
  26. package/lib/esm/entities/vaultV2BlueReallocationData.js +9 -14
  27. package/lib/esm/errors.d.ts +1 -1
  28. package/lib/esm/errors.js +1 -1
  29. package/lib/esm/helpers/slippage.d.ts +19 -0
  30. package/lib/esm/helpers/slippage.js +19 -0
  31. package/package.json +3 -3
@@ -166,13 +166,14 @@ prerequisite v5 withdrawals did not have. Await `getRequirements()` and satisfy
166
166
  - Without signature support, it returns one ERC-20 approval transaction to send first.
167
167
  - With `supportSignature: true`, it returns one signable ERC-2612 shares permit when the current
168
168
  allowance is below the cap; pass the signature to `buildTx([sharesPermit])` and it is folded into
169
- the VaultBundlesV1 call. A larger leftover allowance is always reset with an ERC-20 approval
170
- transaction instead, because VaultBundlesV1 skips a permit whose nonce was already consumed.
169
+ the VaultBundlesV1 call. An allowance above the cap divided by `1 - slippageTolerance` is always
170
+ reset with an ERC-20 approval transaction instead, because VaultBundlesV1 skips a permit whose nonce was already consumed.
171
171
 
172
172
  The allowance is the only cap on the burn, since asset-mode calldata carries no maximum-shares
173
173
  argument. The exact cap is derived at handle creation from the supplied `vaultData`, the deadline,
174
174
  and `slippageTolerance` (default 0.03%); `getRequirements()` re-reads the live allowance against
175
- that fixed cap and returns an approval or permit for exactly that amount whenever it differs.
175
+ that fixed cap and returns an approval or permit for exactly that amount whenever the allowance
176
+ falls outside `[cap, cap / (1 - slippageTolerance)]`.
176
177
 
177
178
  `getRequirements()` re-validates the deadline on every call, so a prepared withdrawal reused after
178
179
  its deadline throws `ExpiredDeadlineError` rather than returning cached prerequisites.
package/README.md CHANGED
@@ -128,8 +128,9 @@ const requirements = await getRequirements();
128
128
  const tx = buildTx([permitSignature]);
129
129
  ```
130
130
 
131
- Withdraw is a VaultBundlesV1 call that burns the caller's shares, so it needs the exact share
132
- allowance returned by `getRequirements()`:
131
+ Withdraw is a VaultBundlesV1 call that burns the caller's shares, so it needs the share
132
+ allowance returned by `getRequirements()` (an existing allowance up to one slippage tolerance
133
+ above that cap is kept):
133
134
 
134
135
  ```typescript
135
136
  import { morphoViemExtension } from "@morpho-org/morpho-sdk";
@@ -1,4 +1,4 @@
1
- export { BlueErrors, DivisionByZeroError, IncompleteChainRegistryError, InvalidBitLengthError, InvalidMarketParamsError, RegistryValueAlreadyRegisteredError, UnknownAddressError, UnknownDataError, UnknownFactory, UnknownMarketAllocationError, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError,
1
+ export { BlueErrors, DivisionByZeroError, IncompleteChainRegistryError, InvalidAddressError, InvalidBitLengthError, InvalidMarketParamsError, RegistryValueAlreadyRegisteredError, UnknownAddressError, UnknownDataError, UnknownFactory, UnknownMarketAllocationError, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
4
  export { getUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError, MarketParamsIdMismatchError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UnsupportedPermitDomainExtensionsError = exports.MarketParamsIdMismatchError = exports.isUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedVaultV2AdapterError = exports.UnsupportedPreLiquidationParamsError = exports.UnsupportedMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownVaultConfigError = exports.UnknownTokenPriceError = exports.UnknownTokenError = exports.UnknownOfFactory = exports.UnknownMarketParamsError = exports.UnknownMarketAllocationError = exports.UnknownFactory = exports.UnknownDataError = exports.UnknownAddressError = exports.RegistryValueAlreadyRegisteredError = exports.InvalidMarketParamsError = exports.InvalidBitLengthError = exports.IncompleteChainRegistryError = exports.DivisionByZeroError = exports.BlueErrors = void 0;
3
+ exports.UnsupportedPermitDomainExtensionsError = exports.MarketParamsIdMismatchError = exports.isUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedVaultV2AdapterError = exports.UnsupportedPreLiquidationParamsError = exports.UnsupportedMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownVaultConfigError = exports.UnknownTokenPriceError = exports.UnknownTokenError = exports.UnknownOfFactory = exports.UnknownMarketParamsError = exports.UnknownMarketAllocationError = exports.UnknownFactory = exports.UnknownDataError = exports.UnknownAddressError = exports.RegistryValueAlreadyRegisteredError = exports.InvalidMarketParamsError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.IncompleteChainRegistryError = exports.DivisionByZeroError = exports.BlueErrors = void 0;
4
4
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  Object.defineProperty(exports, "BlueErrors", { enumerable: true, get: function () { return blue_sdk_1.BlueErrors; } });
6
6
  Object.defineProperty(exports, "DivisionByZeroError", { enumerable: true, get: function () { return blue_sdk_1.DivisionByZeroError; } });
7
7
  Object.defineProperty(exports, "IncompleteChainRegistryError", { enumerable: true, get: function () { return blue_sdk_1.IncompleteChainRegistryError; } });
8
+ Object.defineProperty(exports, "InvalidAddressError", { enumerable: true, get: function () { return blue_sdk_1.InvalidAddressError; } });
8
9
  Object.defineProperty(exports, "InvalidBitLengthError", { enumerable: true, get: function () { return blue_sdk_1.InvalidBitLengthError; } });
9
10
  Object.defineProperty(exports, "InvalidMarketParamsError", { enumerable: true, get: function () { return blue_sdk_1.InvalidMarketParamsError; } });
10
11
  Object.defineProperty(exports, "RegistryValueAlreadyRegisteredError", { enumerable: true, get: function () { return blue_sdk_1.RegistryValueAlreadyRegisteredError; } });
@@ -5,16 +5,19 @@ import { type ActionRequirement } from "../../types/index.js";
5
5
  * Resolves the exact vault-share approval or ERC-2612 requirement for a VaultBundlesV1 exit.
6
6
  *
7
7
  * The exit burns however many shares the vault prices at execution time, so the share allowance is
8
- * the only cap on that burn. A leftover allowance above `requiredShareAllowance` therefore does not
9
- * satisfy the requirement: it is replaced by an onchain approval for exactly the computed cap. Only
10
- * an insufficient allowance may be raised through an ERC-2612 permit, because VaultBundlesV1 skips a
11
- * permit whose nonce was already consumed and the leftover allowance would then stay in force.
8
+ * the only cap on that burn. An allowance within `[requiredShareAllowance, maxShareAllowance]`
9
+ * satisfies the requirement; one above `maxShareAllowance` is replaced by an onchain approval for
10
+ * exactly the computed cap. Only an insufficient allowance may be raised through an ERC-2612 permit,
11
+ * because VaultBundlesV1 skips a permit whose nonce was already consumed and the leftover allowance
12
+ * would then stay in force.
12
13
  *
13
14
  * @internal
14
15
  *
15
16
  * @param viemClient - Client used to read the current share allowance and permit nonce.
16
- * @param params - Vault snapshot, owner, exact allowance, and deadline values.
17
- * @returns No requirement when the allowance already equals `requiredShareAllowance`, otherwise one
17
+ * @param params - Vault snapshot, owner, allowance bounds, and deadline values. `maxShareAllowance`
18
+ * defaults to `requiredShareAllowance`, which accepts only an exact match.
19
+ * @returns No requirement when the allowance is within `[requiredShareAllowance,
20
+ * maxShareAllowance]`, otherwise one
18
21
  * approval that sets it to exactly that cap, or one permit when the allowance is below the cap
19
22
  * and signatures are supported.
20
23
  * @throws {ExpiredDeadlineError} when the bundles deadline has elapsed.
@@ -26,6 +29,7 @@ export declare const getVaultBundlesSharesRequirements: (viemClient: Client, par
26
29
  readonly owner: Address;
27
30
  readonly chainId: number;
28
31
  readonly requiredShareAllowance: bigint;
32
+ readonly maxShareAllowance?: bigint;
29
33
  readonly deadline: bigint;
30
34
  readonly supportSignature: boolean;
31
35
  }) => Promise<readonly ActionRequirement[]>;
@@ -12,16 +12,19 @@ const index_js_3 = require("../../types/index.js");
12
12
  * Resolves the exact vault-share approval or ERC-2612 requirement for a VaultBundlesV1 exit.
13
13
  *
14
14
  * The exit burns however many shares the vault prices at execution time, so the share allowance is
15
- * the only cap on that burn. A leftover allowance above `requiredShareAllowance` therefore does not
16
- * satisfy the requirement: it is replaced by an onchain approval for exactly the computed cap. Only
17
- * an insufficient allowance may be raised through an ERC-2612 permit, because VaultBundlesV1 skips a
18
- * permit whose nonce was already consumed and the leftover allowance would then stay in force.
15
+ * the only cap on that burn. An allowance within `[requiredShareAllowance, maxShareAllowance]`
16
+ * satisfies the requirement; one above `maxShareAllowance` is replaced by an onchain approval for
17
+ * exactly the computed cap. Only an insufficient allowance may be raised through an ERC-2612 permit,
18
+ * because VaultBundlesV1 skips a permit whose nonce was already consumed and the leftover allowance
19
+ * would then stay in force.
19
20
  *
20
21
  * @internal
21
22
  *
22
23
  * @param viemClient - Client used to read the current share allowance and permit nonce.
23
- * @param params - Vault snapshot, owner, exact allowance, and deadline values.
24
- * @returns No requirement when the allowance already equals `requiredShareAllowance`, otherwise one
24
+ * @param params - Vault snapshot, owner, allowance bounds, and deadline values. `maxShareAllowance`
25
+ * defaults to `requiredShareAllowance`, which accepts only an exact match.
26
+ * @returns No requirement when the allowance is within `[requiredShareAllowance,
27
+ * maxShareAllowance]`, otherwise one
25
28
  * approval that sets it to exactly that cap, or one permit when the allowance is below the cap
26
29
  * and signatures are supported.
27
30
  * @throws {ExpiredDeadlineError} when the bundles deadline has elapsed.
@@ -41,13 +44,11 @@ const getVaultBundlesSharesRequirements = async (viemClient, params) => {
41
44
  functionName: "allowance",
42
45
  args: [params.owner, spender],
43
46
  });
44
- // Asset-mode withdrawals carry no onchain share cap, so the allowance itself is the cap. A
45
- // larger leftover allowance would let a share-price loss burn past `requiredShareAllowance`,
46
- // so only an exact match skips the approval or permit that resets it to the computed cap.
47
- if (allowance === params.requiredShareAllowance)
47
+ // Asset-mode withdrawals carry no onchain share cap, so the allowance itself is the cap. Only an
48
+ // allowance up to `maxShareAllowance` skips the approval or permit that resets it to the cap.
49
+ if (allowance >= params.requiredShareAllowance &&
50
+ allowance <= (params.maxShareAllowance ?? params.requiredShareAllowance))
48
51
  return [];
49
- // An oversized allowance is only ever lowered onchain: `TokenLib.submitPermit` skips a permit
50
- // whose nonce was already consumed, which would silently leave the stale cap in force.
51
52
  if (allowance < params.requiredShareAllowance && params.supportSignature) {
52
53
  const nonce = await (0, actions_1.readContract)(viemClient, {
53
54
  address: params.vaultData.address,
@@ -121,8 +121,9 @@ export interface VaultV1Actions {
121
121
  * defaults to two hours from handle creation.
122
122
  * @returns A frozen handle with lazy `getRequirements()` and synchronous `buildTx(signatures?)`,
123
123
  * which returns a deep-frozen `Transaction<VaultV1WithdrawAction>`. Requirements are empty
124
- * when the allowance equals the cap; an oversized allowance is always reset with an exact
125
- * onchain approval, and an insufficient one is raised by an approval or, with signature
124
+ * when the allowance is between the cap and the cap divided by `1 - slippageTolerance`; a
125
+ * larger allowance is always reset with an exact onchain approval, and an insufficient one is
126
+ * raised by an approval or, with signature
126
127
  * support, an ERC-2612 request. The cap is fixed at handle creation while each call re-reads
127
128
  * the allowance. Confirm the approval or pass its signed permit to `buildTx`.
128
129
  * @remarks VaultBundlesV1 skips a share permit whose nonce was already consumed and proceeds
@@ -345,8 +346,9 @@ export interface VaultV1Actions {
345
346
  * @param params.referralFeeRecipient - Optional non-zero recipient required for a positive fee.
346
347
  * @param params.deadline - Optional execution and share-permit deadline in Unix seconds; defaults
347
348
  * to two hours from handle creation.
348
- * @returns Lazy exact source-share requirements and a synchronous transaction builder.
349
- * `getRequirements()` re-reads the live share allowance on every call, so a requirement
349
+ * @returns Lazy source-share requirements and a synchronous transaction builder. Shares mode
350
+ * needs an exact allowance; assets mode accepts one between the cap and the cap divided by
351
+ * `1 - slippageTolerance`, and resets a larger one. `getRequirements()` re-reads the live share allowance on every call, so a requirement
350
352
  * satisfied between calls stops being reported, while the derived source share cap stays
351
353
  * pinned to the supplied snapshot.
352
354
  * @throws {UnknownBlueMarketAllocationError} when a source withdraw-queue market has no allocation snapshot.
@@ -9,6 +9,7 @@ const actions_1 = require("viem/actions");
9
9
  const common_js_1 = require("../../actions/bundles/common.js");
10
10
  const index_js_1 = require("../../actions/index.js");
11
11
  const index_js_2 = require("../../helpers/index.js");
12
+ const slippage_js_1 = require("../../helpers/slippage.js");
12
13
  const validate_js_1 = require("../../helpers/validate.js");
13
14
  const index_js_3 = require("../../types/index.js");
14
15
  const getVaultBundlesSharesRequirements_js_1 = require("../requirements/getVaultBundlesSharesRequirements.js");
@@ -151,6 +152,10 @@ class MorphoVaultV1 {
151
152
  assets: amount,
152
153
  slippageTolerance,
153
154
  });
155
+ const maxShareAllowance = (0, slippage_js_1.computeVaultShareAllowanceCeiling)({
156
+ requiredShareAllowance,
157
+ slippageTolerance,
158
+ });
154
159
  return Object.freeze({
155
160
  getRequirements: async () => {
156
161
  const now = morpho_ts_1.Time.timestamp();
@@ -167,6 +172,7 @@ class MorphoVaultV1 {
167
172
  owner: userAddress,
168
173
  chainId: this.chainId,
169
174
  requiredShareAllowance,
175
+ maxShareAllowance,
170
176
  deadline,
171
177
  supportSignature: this.client.options.supportSignature,
172
178
  });
@@ -471,6 +477,12 @@ class MorphoVaultV1 {
471
477
  assets: assets ?? 0n,
472
478
  slippageTolerance,
473
479
  });
480
+ // In shares mode the calldata pins the burn, so only an exact allowance is accepted there.
481
+ const maxShareAllowance = shares ??
482
+ (0, slippage_js_1.computeVaultShareAllowanceCeiling)({
483
+ requiredShareAllowance,
484
+ slippageTolerance,
485
+ });
474
486
  const spender = (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.vaultBundlesV1");
475
487
  const { userAddress } = params;
476
488
  const sourceAsset = params.sourceVault.asset;
@@ -504,6 +516,7 @@ class MorphoVaultV1 {
504
516
  owner: userAddress,
505
517
  chainId: this.chainId,
506
518
  requiredShareAllowance,
519
+ maxShareAllowance,
507
520
  deadline,
508
521
  supportSignature: this.client.options.supportSignature,
509
522
  });
@@ -127,8 +127,9 @@ export interface VaultV2Actions {
127
127
  * defaults to two hours from handle creation.
128
128
  * @returns A frozen handle with lazy `getRequirements()` and synchronous `buildTx(signatures?)`,
129
129
  * which returns a deep-frozen `Transaction<VaultV2WithdrawAction>`. Requirements are empty
130
- * when the allowance equals the cap; an oversized allowance is always reset with an exact
131
- * onchain approval, and an insufficient one is raised by an approval or, with signature
130
+ * when the allowance is between the cap and the cap divided by `1 - slippageTolerance`; a
131
+ * larger allowance is always reset with an exact onchain approval, and an insufficient one is
132
+ * raised by an approval or, with signature
132
133
  * support, an ERC-2612 request. The cap is fixed at handle creation while each call re-reads
133
134
  * the allowance. Confirm the approval or pass its signed permit to `buildTx`.
134
135
  * @remarks VaultBundlesV1 skips a share permit whose nonce was already consumed and proceeds
@@ -9,6 +9,7 @@ const actions_1 = require("viem/actions");
9
9
  const common_js_1 = require("../../actions/bundles/common.js");
10
10
  const index_js_1 = require("../../actions/index.js");
11
11
  const index_js_2 = require("../../helpers/index.js");
12
+ const slippage_js_1 = require("../../helpers/slippage.js");
12
13
  const validate_js_1 = require("../../helpers/validate.js");
13
14
  const index_js_3 = require("../../types/index.js");
14
15
  const getVaultBundlesSharesRequirements_js_1 = require("../requirements/getVaultBundlesSharesRequirements.js");
@@ -154,6 +155,10 @@ class MorphoVaultV2 {
154
155
  assets: amount,
155
156
  slippageTolerance,
156
157
  });
158
+ const maxShareAllowance = (0, slippage_js_1.computeVaultShareAllowanceCeiling)({
159
+ requiredShareAllowance,
160
+ slippageTolerance,
161
+ });
157
162
  return Object.freeze({
158
163
  getRequirements: async () => {
159
164
  const now = morpho_ts_1.Time.timestamp();
@@ -170,6 +175,7 @@ class MorphoVaultV2 {
170
175
  owner: userAddress,
171
176
  chainId: this.chainId,
172
177
  requiredShareAllowance,
178
+ maxShareAllowance,
173
179
  deadline,
174
180
  supportSignature: this.client.options.supportSignature,
175
181
  });
@@ -372,8 +372,9 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
372
372
  * or allocator capacity are skipped before projecting source interest. The
373
373
  * adapter's minimum share minting requirement, supply-share limits, and target
374
374
  * absolute or zero relative caps are checked against a one-asset deposit.
375
- * Shared cap IDs that a source withdrawal can reduce remain eligible, as do deposits whose
376
- * allocation does not increase after rounding.
375
+ * Shared cap IDs that a source withdrawal can reduce remain eligible. Each
376
+ * accepted leg counts at least its requested `assets` against the target cap
377
+ * IDs, so a leg sized to a cap leaves no rounding headroom.
377
378
  *
378
379
  * Shared-cap discovery is conservative. Operation planning searches at most
379
380
  * 1,024 base units above its targeted amount for the nearest executable fit.
@@ -573,8 +573,9 @@ class VaultV2BlueReallocationData {
573
573
  * or allocator capacity are skipped before projecting source interest. The
574
574
  * adapter's minimum share minting requirement, supply-share limits, and target
575
575
  * absolute or zero relative caps are checked against a one-asset deposit.
576
- * Shared cap IDs that a source withdrawal can reduce remain eligible, as do deposits whose
577
- * allocation does not increase after rounding.
576
+ * Shared cap IDs that a source withdrawal can reduce remain eligible. Each
577
+ * accepted leg counts at least its requested `assets` against the target cap
578
+ * IDs, so a leg sized to a cap leaves no rounding headroom.
578
579
  *
579
580
  * Shared-cap discovery is conservative. Operation planning searches at most
580
581
  * 1,024 base units above its targeted amount for the nearest executable fit.
@@ -862,7 +863,7 @@ class VaultV2BlueReallocationData {
862
863
  untracked +
863
864
  targetPair.reserve());
864
865
  const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
865
- const minimumAllocationChange = minimumAllocation - adapterMarketCapAllocation.allocation;
866
+ const minimumAllocationChange = blue_sdk_1.MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
866
867
  const blockedTargetIds = targetAllocations
867
868
  .filter(({ allocation, absoluteCap, relativeCap, id }) => {
868
869
  const nextAllocation = allocation +
@@ -1367,21 +1368,15 @@ class VaultV2BlueReallocationData {
1367
1368
  if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id))
1368
1369
  targetAdapter.markets.push(supply.market);
1369
1370
  data.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
1370
- const targetChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1371
+ const simulatedChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1372
+ // The adapter's rounded expected-assets delta can differ by one wei at inclusion,
1373
+ // so cap tracking assumes each accepted leg adds at least its requested assets.
1374
+ const targetChange = blue_sdk_1.MathLib.max(simulatedChange, reallocation.assets);
1371
1375
  for (const id of targetIds) {
1372
1376
  const allocation = data.getAllocation(reallocation.vault, id);
1373
- const nextAllocation = allocation.allocation + targetChange;
1374
- if (nextAllocation < 0n) {
1375
- throw new index_js_1.ReallocationAllocationUnderflowError({
1376
- vault: reallocation.vault,
1377
- id,
1378
- allocation: allocation.allocation,
1379
- change: targetChange,
1380
- });
1381
- }
1382
1377
  data.mutableAllocations[allocationsKey][id] = {
1383
1378
  ...allocation,
1384
- allocation: nextAllocation,
1379
+ allocation: allocation.allocation + targetChange,
1385
1380
  };
1386
1381
  }
1387
1382
  vault.assetBalance -= reallocation.assets;
@@ -4,4 +4,4 @@ UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError
4
4
  export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, 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, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
7
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
package/lib/cjs/errors.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MidnightTickOutOfRangeError = exports.MidnightSettlementFeeExceedsPriceError = exports.MidnightRatifierV1TakerNotAllowedError = exports.MidnightRateRatifierV1BoundOverflowError = exports.MidnightPriceGreaterThanOneError = exports.MidnightPayloadDecodeError = exports.MidnightMempoolValidationError = exports.MidnightApiError = exports.InvalidMidnightTypedDataSignatureError = exports.InvalidMidnightTreeHeightError = exports.InvalidMidnightTreeError = exports.InvalidMidnightTickSpacingError = exports.InvalidMidnightRatifierV1AddressError = exports.InvalidMidnightRateRatifierV1TimeError = exports.InvalidMidnightRateRatifierV1TickError = exports.InvalidMidnightRateRatifierV1RateError = exports.InvalidMidnightPositionLossFactorError = exports.InvalidMidnightPositionAccrualTimestampError = exports.InvalidMidnightPositionAccrualStateError = exports.InvalidMidnightOfferParameterError = exports.InvalidMidnightOfferGroupError = exports.InvalidMidnightApiResponseError = exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMidnightMarketParameterError = exports.InvalidMidnightEcrecoverSignatureVError = exports.MidnightChainIdMismatchError = exports.UnsupportedPermitDomainExtensionsError = exports.BlueMarketParamsIdMismatchError = exports.isBlueUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getBlueUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedBlueVaultV2AdapterError = exports.UnsupportedBluePreLiquidationParamsError = exports.UnsupportedBlueMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownBlueVaultConfigError = exports.UnknownBlueTokenPriceError = exports.UnknownBlueTokenError = exports.UnknownBlueOfFactory = exports.UnknownBlueMarketParamsError = exports.UnknownBlueMarketAllocationError = exports.UnknownBlueFactory = exports.UnknownBlueDataError = exports.UnknownAddressError = exports.InvalidBlueMarketParamsError = exports.IncompleteChainRegistryError = exports.BlueErrors = void 0;
4
- exports.RegistryValueAlreadyRegisteredError = exports.NegativeValueError = exports.InvalidBitLengthError = exports.DivisionByZeroError = exports._try = exports.UnknownMidnightCollateralIndexError = void 0;
4
+ exports.RegistryValueAlreadyRegisteredError = exports.NegativeValueError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.DivisionByZeroError = exports._try = exports.UnknownMidnightCollateralIndexError = void 0;
5
5
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  Object.defineProperty(exports, "BlueErrors", { enumerable: true, get: function () { return blue_sdk_1.BlueErrors; } });
7
7
  Object.defineProperty(exports, "IncompleteChainRegistryError", { enumerable: true, get: function () { return blue_sdk_1.IncompleteChainRegistryError; } });
@@ -60,6 +60,7 @@ Object.defineProperty(exports, "UnknownMidnightCollateralIndexError", { enumerab
60
60
  var morpho_ts_1 = require("@morpho-org/morpho-ts");
61
61
  Object.defineProperty(exports, "_try", { enumerable: true, get: function () { return morpho_ts_1._try; } });
62
62
  Object.defineProperty(exports, "DivisionByZeroError", { enumerable: true, get: function () { return morpho_ts_1.DivisionByZeroError; } });
63
+ Object.defineProperty(exports, "InvalidAddressError", { enumerable: true, get: function () { return morpho_ts_1.InvalidAddressError; } });
63
64
  Object.defineProperty(exports, "InvalidBitLengthError", { enumerable: true, get: function () { return morpho_ts_1.InvalidBitLengthError; } });
64
65
  Object.defineProperty(exports, "NegativeValueError", { enumerable: true, get: function () { return morpho_ts_1.NegativeValueError; } });
65
66
  Object.defineProperty(exports, "RegistryValueAlreadyRegisteredError", { enumerable: true, get: function () { return morpho_ts_1.RegistryValueAlreadyRegisteredError; } });
@@ -135,3 +135,22 @@ export declare const computeVaultMaxShareAllowance: (params: {
135
135
  readonly assets: bigint;
136
136
  readonly slippageTolerance: bigint;
137
137
  }) => bigint;
138
+ /**
139
+ * Computes the largest live share allowance a re-prepared asset-mode exit accepts without a reset.
140
+ *
141
+ * A Safe approval can execute after the caller re-prepared the exit from a fresher snapshot, whose
142
+ * cap is slightly lower. Allowances in `[requiredShareAllowance, ceiling]` are kept, so the burn may
143
+ * exceed the current cap by at most one more slippage tolerance.
144
+ *
145
+ * @internal
146
+ *
147
+ * @param params.requiredShareAllowance - Cap from {@link computeVaultMaxShareAllowance}.
148
+ * @param params.slippageTolerance - WAD-scaled slippage used to derive that cap.
149
+ * @returns `requiredShareAllowance / (1 - slippageTolerance)`, rounded down.
150
+ * @throws {NegativeInputError} when `slippageTolerance` is negative.
151
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
152
+ */
153
+ export declare const computeVaultShareAllowanceCeiling: (params: {
154
+ readonly requiredShareAllowance: bigint;
155
+ readonly slippageTolerance: bigint;
156
+ }) => bigint;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.computeVaultMaxShareAllowance = exports.computeVaultMaxSharePrice = void 0;
3
+ exports.computeVaultShareAllowanceCeiling = exports.computeVaultMaxShareAllowance = exports.computeVaultMaxSharePrice = void 0;
4
4
  exports.computeMinForceWithdrawSharePrice = computeMinForceWithdrawSharePrice;
5
5
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  const index_js_1 = require("../types/index.js");
@@ -192,3 +192,23 @@ const computeVaultMaxShareAllowance = (params) => {
192
192
  : previewedShares;
193
193
  };
194
194
  exports.computeVaultMaxShareAllowance = computeVaultMaxShareAllowance;
195
+ /**
196
+ * Computes the largest live share allowance a re-prepared asset-mode exit accepts without a reset.
197
+ *
198
+ * A Safe approval can execute after the caller re-prepared the exit from a fresher snapshot, whose
199
+ * cap is slightly lower. Allowances in `[requiredShareAllowance, ceiling]` are kept, so the burn may
200
+ * exceed the current cap by at most one more slippage tolerance.
201
+ *
202
+ * @internal
203
+ *
204
+ * @param params.requiredShareAllowance - Cap from {@link computeVaultMaxShareAllowance}.
205
+ * @param params.slippageTolerance - WAD-scaled slippage used to derive that cap.
206
+ * @returns `requiredShareAllowance / (1 - slippageTolerance)`, rounded down.
207
+ * @throws {NegativeInputError} when `slippageTolerance` is negative.
208
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
209
+ */
210
+ const computeVaultShareAllowanceCeiling = (params) => {
211
+ (0, validate_js_1.validateSlippageTolerance)(params.slippageTolerance);
212
+ return blue_sdk_1.MathLib.wDivDown(params.requiredShareAllowance, blue_sdk_1.MathLib.WAD - params.slippageTolerance);
213
+ };
214
+ exports.computeVaultShareAllowanceCeiling = computeVaultShareAllowanceCeiling;
@@ -1,4 +1,4 @@
1
- export { BlueErrors, DivisionByZeroError, IncompleteChainRegistryError, InvalidBitLengthError, InvalidMarketParamsError, RegistryValueAlreadyRegisteredError, UnknownAddressError, UnknownDataError, UnknownFactory, UnknownMarketAllocationError, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError,
1
+ export { BlueErrors, DivisionByZeroError, IncompleteChainRegistryError, InvalidAddressError, InvalidBitLengthError, InvalidMarketParamsError, RegistryValueAlreadyRegisteredError, UnknownAddressError, UnknownDataError, UnknownFactory, UnknownMarketAllocationError, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
4
  export { getUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError, MarketParamsIdMismatchError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
@@ -1,4 +1,4 @@
1
- export { BlueErrors, DivisionByZeroError, IncompleteChainRegistryError, InvalidBitLengthError, InvalidMarketParamsError, RegistryValueAlreadyRegisteredError, UnknownAddressError, UnknownDataError, UnknownFactory, UnknownMarketAllocationError, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError,
1
+ export { BlueErrors, DivisionByZeroError, IncompleteChainRegistryError, InvalidAddressError, InvalidBitLengthError, InvalidMarketParamsError, RegistryValueAlreadyRegisteredError, UnknownAddressError, UnknownDataError, UnknownFactory, UnknownMarketAllocationError, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
4
  export { getUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError, MarketParamsIdMismatchError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
@@ -5,16 +5,19 @@ import { type ActionRequirement } from "../../types/index.js";
5
5
  * Resolves the exact vault-share approval or ERC-2612 requirement for a VaultBundlesV1 exit.
6
6
  *
7
7
  * The exit burns however many shares the vault prices at execution time, so the share allowance is
8
- * the only cap on that burn. A leftover allowance above `requiredShareAllowance` therefore does not
9
- * satisfy the requirement: it is replaced by an onchain approval for exactly the computed cap. Only
10
- * an insufficient allowance may be raised through an ERC-2612 permit, because VaultBundlesV1 skips a
11
- * permit whose nonce was already consumed and the leftover allowance would then stay in force.
8
+ * the only cap on that burn. An allowance within `[requiredShareAllowance, maxShareAllowance]`
9
+ * satisfies the requirement; one above `maxShareAllowance` is replaced by an onchain approval for
10
+ * exactly the computed cap. Only an insufficient allowance may be raised through an ERC-2612 permit,
11
+ * because VaultBundlesV1 skips a permit whose nonce was already consumed and the leftover allowance
12
+ * would then stay in force.
12
13
  *
13
14
  * @internal
14
15
  *
15
16
  * @param viemClient - Client used to read the current share allowance and permit nonce.
16
- * @param params - Vault snapshot, owner, exact allowance, and deadline values.
17
- * @returns No requirement when the allowance already equals `requiredShareAllowance`, otherwise one
17
+ * @param params - Vault snapshot, owner, allowance bounds, and deadline values. `maxShareAllowance`
18
+ * defaults to `requiredShareAllowance`, which accepts only an exact match.
19
+ * @returns No requirement when the allowance is within `[requiredShareAllowance,
20
+ * maxShareAllowance]`, otherwise one
18
21
  * approval that sets it to exactly that cap, or one permit when the allowance is below the cap
19
22
  * and signatures are supported.
20
23
  * @throws {ExpiredDeadlineError} when the bundles deadline has elapsed.
@@ -26,6 +29,7 @@ export declare const getVaultBundlesSharesRequirements: (viemClient: Client, par
26
29
  readonly owner: Address;
27
30
  readonly chainId: number;
28
31
  readonly requiredShareAllowance: bigint;
32
+ readonly maxShareAllowance?: bigint;
29
33
  readonly deadline: bigint;
30
34
  readonly supportSignature: boolean;
31
35
  }) => Promise<readonly ActionRequirement[]>;
@@ -9,16 +9,19 @@ import { ExpiredDeadlineError, } from "../../types/index.js";
9
9
  * Resolves the exact vault-share approval or ERC-2612 requirement for a VaultBundlesV1 exit.
10
10
  *
11
11
  * The exit burns however many shares the vault prices at execution time, so the share allowance is
12
- * the only cap on that burn. A leftover allowance above `requiredShareAllowance` therefore does not
13
- * satisfy the requirement: it is replaced by an onchain approval for exactly the computed cap. Only
14
- * an insufficient allowance may be raised through an ERC-2612 permit, because VaultBundlesV1 skips a
15
- * permit whose nonce was already consumed and the leftover allowance would then stay in force.
12
+ * the only cap on that burn. An allowance within `[requiredShareAllowance, maxShareAllowance]`
13
+ * satisfies the requirement; one above `maxShareAllowance` is replaced by an onchain approval for
14
+ * exactly the computed cap. Only an insufficient allowance may be raised through an ERC-2612 permit,
15
+ * because VaultBundlesV1 skips a permit whose nonce was already consumed and the leftover allowance
16
+ * would then stay in force.
16
17
  *
17
18
  * @internal
18
19
  *
19
20
  * @param viemClient - Client used to read the current share allowance and permit nonce.
20
- * @param params - Vault snapshot, owner, exact allowance, and deadline values.
21
- * @returns No requirement when the allowance already equals `requiredShareAllowance`, otherwise one
21
+ * @param params - Vault snapshot, owner, allowance bounds, and deadline values. `maxShareAllowance`
22
+ * defaults to `requiredShareAllowance`, which accepts only an exact match.
23
+ * @returns No requirement when the allowance is within `[requiredShareAllowance,
24
+ * maxShareAllowance]`, otherwise one
22
25
  * approval that sets it to exactly that cap, or one permit when the allowance is below the cap
23
26
  * and signatures are supported.
24
27
  * @throws {ExpiredDeadlineError} when the bundles deadline has elapsed.
@@ -38,13 +41,11 @@ export const getVaultBundlesSharesRequirements = async (viemClient, params) => {
38
41
  functionName: "allowance",
39
42
  args: [params.owner, spender],
40
43
  });
41
- // Asset-mode withdrawals carry no onchain share cap, so the allowance itself is the cap. A
42
- // larger leftover allowance would let a share-price loss burn past `requiredShareAllowance`,
43
- // so only an exact match skips the approval or permit that resets it to the computed cap.
44
- if (allowance === params.requiredShareAllowance)
44
+ // Asset-mode withdrawals carry no onchain share cap, so the allowance itself is the cap. Only an
45
+ // allowance up to `maxShareAllowance` skips the approval or permit that resets it to the cap.
46
+ if (allowance >= params.requiredShareAllowance &&
47
+ allowance <= (params.maxShareAllowance ?? params.requiredShareAllowance))
45
48
  return [];
46
- // An oversized allowance is only ever lowered onchain: `TokenLib.submitPermit` skips a permit
47
- // whose nonce was already consumed, which would silently leave the stale cap in force.
48
49
  if (allowance < params.requiredShareAllowance && params.supportSignature) {
49
50
  const nonce = await readContract(viemClient, {
50
51
  address: params.vaultData.address,
@@ -121,8 +121,9 @@ export interface VaultV1Actions {
121
121
  * defaults to two hours from handle creation.
122
122
  * @returns A frozen handle with lazy `getRequirements()` and synchronous `buildTx(signatures?)`,
123
123
  * which returns a deep-frozen `Transaction<VaultV1WithdrawAction>`. Requirements are empty
124
- * when the allowance equals the cap; an oversized allowance is always reset with an exact
125
- * onchain approval, and an insufficient one is raised by an approval or, with signature
124
+ * when the allowance is between the cap and the cap divided by `1 - slippageTolerance`; a
125
+ * larger allowance is always reset with an exact onchain approval, and an insufficient one is
126
+ * raised by an approval or, with signature
126
127
  * support, an ERC-2612 request. The cap is fixed at handle creation while each call re-reads
127
128
  * the allowance. Confirm the approval or pass its signed permit to `buildTx`.
128
129
  * @remarks VaultBundlesV1 skips a share permit whose nonce was already consumed and proceeds
@@ -345,8 +346,9 @@ export interface VaultV1Actions {
345
346
  * @param params.referralFeeRecipient - Optional non-zero recipient required for a positive fee.
346
347
  * @param params.deadline - Optional execution and share-permit deadline in Unix seconds; defaults
347
348
  * to two hours from handle creation.
348
- * @returns Lazy exact source-share requirements and a synchronous transaction builder.
349
- * `getRequirements()` re-reads the live share allowance on every call, so a requirement
349
+ * @returns Lazy source-share requirements and a synchronous transaction builder. Shares mode
350
+ * needs an exact allowance; assets mode accepts one between the cap and the cap divided by
351
+ * `1 - slippageTolerance`, and resets a larger one. `getRequirements()` re-reads the live share allowance on every call, so a requirement
350
352
  * satisfied between calls stops being reported, while the derived source share cap stays
351
353
  * pinned to the supplied snapshot.
352
354
  * @throws {UnknownBlueMarketAllocationError} when a source withdraw-queue market has no allocation snapshot.
@@ -6,6 +6,7 @@ import { multicall } from "viem/actions";
6
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
+ import { computeVaultShareAllowanceCeiling } from "../../helpers/slippage.js";
9
10
  import { validateDeadline, validateNativeVaultAsset, validateUint256Field, } from "../../helpers/validate.js";
10
11
  import { AmountAndSharesExclusiveError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InsufficientBlueBalanceForInKindRedeemError, NonPositiveInputError, SameVaultMigrationError, VaultAddressMismatchError, VaultAssetMismatchError, VaultIsBlueFeeRecipientError, VaultMorphoMismatchError, } from "../../types/index.js";
11
12
  import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
@@ -148,6 +149,10 @@ export class MorphoVaultV1 {
148
149
  assets: amount,
149
150
  slippageTolerance,
150
151
  });
152
+ const maxShareAllowance = computeVaultShareAllowanceCeiling({
153
+ requiredShareAllowance,
154
+ slippageTolerance,
155
+ });
151
156
  return Object.freeze({
152
157
  getRequirements: async () => {
153
158
  const now = Time.timestamp();
@@ -164,6 +169,7 @@ export class MorphoVaultV1 {
164
169
  owner: userAddress,
165
170
  chainId: this.chainId,
166
171
  requiredShareAllowance,
172
+ maxShareAllowance,
167
173
  deadline,
168
174
  supportSignature: this.client.options.supportSignature,
169
175
  });
@@ -468,6 +474,12 @@ export class MorphoVaultV1 {
468
474
  assets: assets ?? 0n,
469
475
  slippageTolerance,
470
476
  });
477
+ // In shares mode the calldata pins the burn, so only an exact allowance is accepted there.
478
+ const maxShareAllowance = shares ??
479
+ computeVaultShareAllowanceCeiling({
480
+ requiredShareAllowance,
481
+ slippageTolerance,
482
+ });
471
483
  const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
472
484
  const { userAddress } = params;
473
485
  const sourceAsset = params.sourceVault.asset;
@@ -501,6 +513,7 @@ export class MorphoVaultV1 {
501
513
  owner: userAddress,
502
514
  chainId: this.chainId,
503
515
  requiredShareAllowance,
516
+ maxShareAllowance,
504
517
  deadline,
505
518
  supportSignature: this.client.options.supportSignature,
506
519
  });
@@ -127,8 +127,9 @@ export interface VaultV2Actions {
127
127
  * defaults to two hours from handle creation.
128
128
  * @returns A frozen handle with lazy `getRequirements()` and synchronous `buildTx(signatures?)`,
129
129
  * which returns a deep-frozen `Transaction<VaultV2WithdrawAction>`. Requirements are empty
130
- * when the allowance equals the cap; an oversized allowance is always reset with an exact
131
- * onchain approval, and an insufficient one is raised by an approval or, with signature
130
+ * when the allowance is between the cap and the cap divided by `1 - slippageTolerance`; a
131
+ * larger allowance is always reset with an exact onchain approval, and an insufficient one is
132
+ * raised by an approval or, with signature
132
133
  * support, an ERC-2612 request. The cap is fixed at handle creation while each call re-reads
133
134
  * the allowance. Confirm the approval or pass its signed permit to `buildTx`.
134
135
  * @remarks VaultBundlesV1 skips a share permit whose nonce was already consumed and proceeds
@@ -6,6 +6,7 @@ import { multicall } from "viem/actions";
6
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
+ import { computeVaultShareAllowanceCeiling } from "../../helpers/slippage.js";
9
10
  import { validateDeadline, validateNativeVaultAsset, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
10
11
  import { AdapterNotPartOfVaultError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemZeroDeallocationError, InputExceedsMaxError, InsufficientBlueBalanceForInKindRedeemError, NonPositiveInputError, VaultAddressMismatchError, VaultV2ForceWithdrawCoverageError, VaultV2ForceWithdrawFeeSharesExceedBurnError, VaultV2ForceWithdrawSharePriceBelowFloorError, VaultV2ForceWithdrawZeroSharePriceError, VaultV2ForceWithdrawZeroWithdrawalError, VaultV2SingleAdapterRequiredError, VaultV2UndecodableLiquidityDataError, VaultV2UnsupportedExitAdapterError, VaultV2UnsupportedLiquidityAdapterError, } from "../../types/index.js";
11
12
  import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
@@ -151,6 +152,10 @@ export class MorphoVaultV2 {
151
152
  assets: amount,
152
153
  slippageTolerance,
153
154
  });
155
+ const maxShareAllowance = computeVaultShareAllowanceCeiling({
156
+ requiredShareAllowance,
157
+ slippageTolerance,
158
+ });
154
159
  return Object.freeze({
155
160
  getRequirements: async () => {
156
161
  const now = Time.timestamp();
@@ -167,6 +172,7 @@ export class MorphoVaultV2 {
167
172
  owner: userAddress,
168
173
  chainId: this.chainId,
169
174
  requiredShareAllowance,
175
+ maxShareAllowance,
170
176
  deadline,
171
177
  supportSignature: this.client.options.supportSignature,
172
178
  });
@@ -372,8 +372,9 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
372
372
  * or allocator capacity are skipped before projecting source interest. The
373
373
  * adapter's minimum share minting requirement, supply-share limits, and target
374
374
  * absolute or zero relative caps are checked against a one-asset deposit.
375
- * Shared cap IDs that a source withdrawal can reduce remain eligible, as do deposits whose
376
- * allocation does not increase after rounding.
375
+ * Shared cap IDs that a source withdrawal can reduce remain eligible. Each
376
+ * accepted leg counts at least its requested `assets` against the target cap
377
+ * IDs, so a leg sized to a cap leaves no rounding headroom.
377
378
  *
378
379
  * Shared-cap discovery is conservative. Operation planning searches at most
379
380
  * 1,024 base units above its targeted amount for the nearest executable fit.
@@ -570,8 +570,9 @@ export class VaultV2BlueReallocationData {
570
570
  * or allocator capacity are skipped before projecting source interest. The
571
571
  * adapter's minimum share minting requirement, supply-share limits, and target
572
572
  * absolute or zero relative caps are checked against a one-asset deposit.
573
- * Shared cap IDs that a source withdrawal can reduce remain eligible, as do deposits whose
574
- * allocation does not increase after rounding.
573
+ * Shared cap IDs that a source withdrawal can reduce remain eligible. Each
574
+ * accepted leg counts at least its requested `assets` against the target cap
575
+ * IDs, so a leg sized to a cap leaves no rounding headroom.
575
576
  *
576
577
  * Shared-cap discovery is conservative. Operation planning searches at most
577
578
  * 1,024 base units above its targeted amount for the nearest executable fit.
@@ -859,7 +860,7 @@ export class VaultV2BlueReallocationData {
859
860
  untracked +
860
861
  targetPair.reserve());
861
862
  const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
862
- const minimumAllocationChange = minimumAllocation - adapterMarketCapAllocation.allocation;
863
+ const minimumAllocationChange = MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
863
864
  const blockedTargetIds = targetAllocations
864
865
  .filter(({ allocation, absoluteCap, relativeCap, id }) => {
865
866
  const nextAllocation = allocation +
@@ -1364,21 +1365,15 @@ export class VaultV2BlueReallocationData {
1364
1365
  if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id))
1365
1366
  targetAdapter.markets.push(supply.market);
1366
1367
  data.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
1367
- const targetChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1368
+ const simulatedChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1369
+ // The adapter's rounded expected-assets delta can differ by one wei at inclusion,
1370
+ // so cap tracking assumes each accepted leg adds at least its requested assets.
1371
+ const targetChange = MathLib.max(simulatedChange, reallocation.assets);
1368
1372
  for (const id of targetIds) {
1369
1373
  const allocation = data.getAllocation(reallocation.vault, id);
1370
- const nextAllocation = allocation.allocation + targetChange;
1371
- if (nextAllocation < 0n) {
1372
- throw new ReallocationAllocationUnderflowError({
1373
- vault: reallocation.vault,
1374
- id,
1375
- allocation: allocation.allocation,
1376
- change: targetChange,
1377
- });
1378
- }
1379
1374
  data.mutableAllocations[allocationsKey][id] = {
1380
1375
  ...allocation,
1381
- allocation: nextAllocation,
1376
+ allocation: allocation.allocation + targetChange,
1382
1377
  };
1383
1378
  }
1384
1379
  vault.assetBalance -= reallocation.assets;
@@ -4,4 +4,4 @@ UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError
4
4
  export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, 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, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
7
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } 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, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, 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, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
6
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
@@ -135,3 +135,22 @@ export declare const computeVaultMaxShareAllowance: (params: {
135
135
  readonly assets: bigint;
136
136
  readonly slippageTolerance: bigint;
137
137
  }) => bigint;
138
+ /**
139
+ * Computes the largest live share allowance a re-prepared asset-mode exit accepts without a reset.
140
+ *
141
+ * A Safe approval can execute after the caller re-prepared the exit from a fresher snapshot, whose
142
+ * cap is slightly lower. Allowances in `[requiredShareAllowance, ceiling]` are kept, so the burn may
143
+ * exceed the current cap by at most one more slippage tolerance.
144
+ *
145
+ * @internal
146
+ *
147
+ * @param params.requiredShareAllowance - Cap from {@link computeVaultMaxShareAllowance}.
148
+ * @param params.slippageTolerance - WAD-scaled slippage used to derive that cap.
149
+ * @returns `requiredShareAllowance / (1 - slippageTolerance)`, rounded down.
150
+ * @throws {NegativeInputError} when `slippageTolerance` is negative.
151
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
152
+ */
153
+ export declare const computeVaultShareAllowanceCeiling: (params: {
154
+ readonly requiredShareAllowance: bigint;
155
+ readonly slippageTolerance: bigint;
156
+ }) => bigint;
@@ -186,3 +186,22 @@ export const computeVaultMaxShareAllowance = (params) => {
186
186
  ? MathLib.wDivUp(previewedShares, MathLib.WAD - params.slippageTolerance)
187
187
  : previewedShares;
188
188
  };
189
+ /**
190
+ * Computes the largest live share allowance a re-prepared asset-mode exit accepts without a reset.
191
+ *
192
+ * A Safe approval can execute after the caller re-prepared the exit from a fresher snapshot, whose
193
+ * cap is slightly lower. Allowances in `[requiredShareAllowance, ceiling]` are kept, so the burn may
194
+ * exceed the current cap by at most one more slippage tolerance.
195
+ *
196
+ * @internal
197
+ *
198
+ * @param params.requiredShareAllowance - Cap from {@link computeVaultMaxShareAllowance}.
199
+ * @param params.slippageTolerance - WAD-scaled slippage used to derive that cap.
200
+ * @returns `requiredShareAllowance / (1 - slippageTolerance)`, rounded down.
201
+ * @throws {NegativeInputError} when `slippageTolerance` is negative.
202
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
203
+ */
204
+ export const computeVaultShareAllowanceCeiling = (params) => {
205
+ validateSlippageTolerance(params.slippageTolerance);
206
+ return MathLib.wDivDown(params.requiredShareAllowance, MathLib.WAD - params.slippageTolerance);
207
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@morpho-org/morpho-sdk",
3
3
  "description": "Abstraction layer for Morpho's complexity.",
4
- "version": "6.3.0",
4
+ "version": "6.4.0",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "repository": {
7
7
  "type": "git",
@@ -150,10 +150,10 @@
150
150
  "MIGRATION-v5-to-v6.md"
151
151
  ],
152
152
  "dependencies": {
153
- "@morpho-org/blue-sdk": "^7.1.0",
153
+ "@morpho-org/blue-sdk": "^7.2.0",
154
154
  "@morpho-org/blue-sdk-viem": "^6.1.0",
155
155
  "@morpho-org/midnight-sdk": "^1.8.0",
156
- "@morpho-org/morpho-ts": "^3.1.0"
156
+ "@morpho-org/morpho-ts": "^3.2.0"
157
157
  },
158
158
  "peerDependencies": {
159
159
  "viem": "^2.0.0"