@morpho-org/morpho-sdk 7.1.0-next.1 → 8.2.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/MIGRATION-v7-to-v8.md +290 -0
  2. package/README.md +11 -6
  3. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
  4. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
  5. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +17 -71
  6. package/lib/cjs/actions/midnight/cancelAndMake.js +41 -29
  7. package/lib/cjs/actions/midnight/redeem.d.ts +8 -1
  8. package/lib/cjs/actions/midnight/redeem.js +18 -1
  9. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
  10. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +24 -2
  11. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +1 -0
  12. package/lib/cjs/actions/midnight/supplyCollateral.js +3 -0
  13. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
  14. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +49 -14
  15. package/lib/cjs/actions/midnight/takeBorrow.d.ts +18 -5
  16. package/lib/cjs/actions/midnight/takeBorrow.js +44 -12
  17. package/lib/cjs/actions/midnight/takeLend.d.ts +10 -5
  18. package/lib/cjs/actions/midnight/takeLend.js +27 -9
  19. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
  20. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +51 -27
  21. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +14 -5
  22. package/lib/cjs/actions/midnight/takeWithdraw.js +40 -9
  23. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +11 -6
  25. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
  26. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
  27. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +17 -6
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
  31. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
  32. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
  33. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
  34. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
  35. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
  36. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
  37. package/lib/cjs/actions/requirements/validateClientChainId.d.ts +26 -0
  38. package/lib/cjs/actions/requirements/validateClientChainId.js +34 -0
  39. package/lib/cjs/blue/errors.d.ts +1 -1
  40. package/lib/cjs/blue/errors.js +3 -1
  41. package/lib/cjs/blue/types.d.ts +1 -1
  42. package/lib/cjs/blue/utils.d.ts +1 -1
  43. package/lib/cjs/blue/utils.js +5 -1
  44. package/lib/cjs/entities/blue/blue.d.ts +109 -27
  45. package/lib/cjs/entities/blue/blue.js +103 -28
  46. package/lib/cjs/entities/index.d.ts +1 -1
  47. package/lib/cjs/entities/midnight/deadline.d.ts +15 -0
  48. package/lib/cjs/entities/midnight/deadline.js +24 -0
  49. package/lib/cjs/entities/midnight/midnight.d.ts +427 -72
  50. package/lib/cjs/entities/midnight/midnight.js +864 -186
  51. package/lib/cjs/entities/midnight/publication.d.ts +134 -0
  52. package/lib/cjs/entities/midnight/publication.js +404 -0
  53. package/lib/cjs/entities/midnight/types.d.ts +26 -5
  54. package/lib/cjs/entities/requirements/assertContractCode.d.ts +49 -0
  55. package/lib/cjs/entities/requirements/assertContractCode.js +79 -0
  56. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
  57. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +45 -18
  58. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
  59. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.js +5 -2
  60. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
  61. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  62. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +63 -11
  63. package/lib/cjs/entities/vaultV1/vaultV1.js +52 -15
  64. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +54 -12
  65. package/lib/cjs/entities/vaultV2/vaultV2.js +52 -15
  66. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +12 -6
  67. package/lib/cjs/entities/vaultV2BlueReallocationData.js +42 -14
  68. package/lib/cjs/errors.d.ts +1 -1
  69. package/lib/cjs/errors.js +4 -2
  70. package/lib/cjs/helpers/constant.d.ts +5 -0
  71. package/lib/cjs/helpers/constant.js +6 -1
  72. package/lib/cjs/helpers/index.d.ts +1 -1
  73. package/lib/cjs/helpers/index.js +2 -1
  74. package/lib/cjs/helpers/validate.d.ts +163 -8
  75. package/lib/cjs/helpers/validate.js +179 -8
  76. package/lib/cjs/helpers/validateMidnightBounds.d.ts +47 -0
  77. package/lib/cjs/helpers/validateMidnightBounds.js +79 -0
  78. package/lib/cjs/helpers/validateMidnightPublication.d.ts +12 -0
  79. package/lib/cjs/helpers/validateMidnightPublication.js +144 -0
  80. package/lib/cjs/helpers/validateMidnightReceiver.d.ts +29 -0
  81. package/lib/cjs/helpers/validateMidnightReceiver.js +84 -0
  82. package/lib/cjs/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
  83. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +231 -0
  84. package/lib/cjs/index.d.ts +1 -0
  85. package/lib/cjs/index.js +3 -0
  86. package/lib/cjs/types/error.d.ts +197 -4
  87. package/lib/cjs/types/error.js +265 -5
  88. package/lib/cjs/types/index.d.ts +1 -0
  89. package/lib/cjs/types/index.js +1 -0
  90. package/lib/cjs/types/midnightCancelAndMake.d.ts +70 -0
  91. package/lib/cjs/types/midnightCancelAndMake.js +2 -0
  92. package/lib/cjs/types/midnightPublicationError.d.ts +332 -0
  93. package/lib/cjs/types/midnightPublicationError.js +376 -0
  94. package/lib/cjs/types/sharedLiquidity.d.ts +12 -7
  95. package/lib/cjs/types.d.ts +1 -1
  96. package/lib/cjs/utils.d.ts +2 -1
  97. package/lib/cjs/utils.js +8 -2
  98. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
  99. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
  100. package/lib/esm/actions/midnight/cancelAndMake.d.ts +17 -71
  101. package/lib/esm/actions/midnight/cancelAndMake.js +42 -30
  102. package/lib/esm/actions/midnight/redeem.d.ts +8 -1
  103. package/lib/esm/actions/midnight/redeem.js +18 -1
  104. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
  105. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +24 -2
  106. package/lib/esm/actions/midnight/supplyCollateral.d.ts +1 -0
  107. package/lib/esm/actions/midnight/supplyCollateral.js +3 -0
  108. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
  109. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +52 -17
  110. package/lib/esm/actions/midnight/takeBorrow.d.ts +18 -5
  111. package/lib/esm/actions/midnight/takeBorrow.js +47 -15
  112. package/lib/esm/actions/midnight/takeLend.d.ts +10 -5
  113. package/lib/esm/actions/midnight/takeLend.js +27 -9
  114. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
  115. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +52 -28
  116. package/lib/esm/actions/midnight/takeWithdraw.d.ts +14 -5
  117. package/lib/esm/actions/midnight/takeWithdraw.js +41 -10
  118. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
  119. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +13 -8
  120. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
  121. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
  122. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
  123. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +17 -6
  124. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
  125. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
  126. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
  127. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
  128. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
  129. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
  130. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
  131. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
  132. package/lib/esm/actions/requirements/validateClientChainId.d.ts +26 -0
  133. package/lib/esm/actions/requirements/validateClientChainId.js +30 -0
  134. package/lib/esm/blue/errors.d.ts +1 -1
  135. package/lib/esm/blue/errors.js +1 -1
  136. package/lib/esm/blue/types.d.ts +1 -1
  137. package/lib/esm/blue/utils.d.ts +1 -1
  138. package/lib/esm/blue/utils.js +1 -1
  139. package/lib/esm/entities/blue/blue.d.ts +109 -27
  140. package/lib/esm/entities/blue/blue.js +104 -29
  141. package/lib/esm/entities/index.d.ts +1 -1
  142. package/lib/esm/entities/midnight/deadline.d.ts +15 -0
  143. package/lib/esm/entities/midnight/deadline.js +20 -0
  144. package/lib/esm/entities/midnight/midnight.d.ts +427 -72
  145. package/lib/esm/entities/midnight/midnight.js +865 -187
  146. package/lib/esm/entities/midnight/publication.d.ts +134 -0
  147. package/lib/esm/entities/midnight/publication.js +397 -0
  148. package/lib/esm/entities/midnight/types.d.ts +26 -5
  149. package/lib/esm/entities/requirements/assertContractCode.d.ts +49 -0
  150. package/lib/esm/entities/requirements/assertContractCode.js +74 -0
  151. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
  152. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +47 -20
  153. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
  154. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.js +5 -2
  155. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
  156. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  157. package/lib/esm/entities/vaultV1/vaultV1.d.ts +63 -11
  158. package/lib/esm/entities/vaultV1/vaultV1.js +53 -16
  159. package/lib/esm/entities/vaultV2/vaultV2.d.ts +54 -12
  160. package/lib/esm/entities/vaultV2/vaultV2.js +53 -16
  161. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +12 -6
  162. package/lib/esm/entities/vaultV2BlueReallocationData.js +42 -14
  163. package/lib/esm/errors.d.ts +1 -1
  164. package/lib/esm/errors.js +1 -1
  165. package/lib/esm/helpers/constant.d.ts +5 -0
  166. package/lib/esm/helpers/constant.js +5 -0
  167. package/lib/esm/helpers/index.d.ts +1 -1
  168. package/lib/esm/helpers/index.js +1 -1
  169. package/lib/esm/helpers/validate.d.ts +163 -8
  170. package/lib/esm/helpers/validate.js +177 -7
  171. package/lib/esm/helpers/validateMidnightBounds.d.ts +47 -0
  172. package/lib/esm/helpers/validateMidnightBounds.js +72 -0
  173. package/lib/esm/helpers/validateMidnightPublication.d.ts +12 -0
  174. package/lib/esm/helpers/validateMidnightPublication.js +139 -0
  175. package/lib/esm/helpers/validateMidnightReceiver.d.ts +29 -0
  176. package/lib/esm/helpers/validateMidnightReceiver.js +80 -0
  177. package/lib/esm/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
  178. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +226 -0
  179. package/lib/esm/index.d.ts +1 -0
  180. package/lib/esm/index.js +1 -0
  181. package/lib/esm/types/error.d.ts +197 -4
  182. package/lib/esm/types/error.js +253 -2
  183. package/lib/esm/types/index.d.ts +1 -0
  184. package/lib/esm/types/index.js +1 -0
  185. package/lib/esm/types/midnightCancelAndMake.d.ts +70 -0
  186. package/lib/esm/types/midnightCancelAndMake.js +1 -0
  187. package/lib/esm/types/midnightPublicationError.d.ts +332 -0
  188. package/lib/esm/types/midnightPublicationError.js +359 -0
  189. package/lib/esm/types/sharedLiquidity.d.ts +12 -7
  190. package/lib/esm/types.d.ts +1 -1
  191. package/lib/esm/utils.d.ts +2 -1
  192. package/lib/esm/utils.js +2 -1
  193. package/package.json +7 -6
@@ -1,14 +1,16 @@
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, Time } from "@morpho-org/morpho-ts";
3
+ import { getChainAddress, getChainAddresses, Time, } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual } from "viem";
5
5
  import { readContract } 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
+ import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
8
9
  import { computeVaultMaxShareAllowance, computeVaultMaxSharePrice, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
9
10
  import { computeVaultShareAllowanceCeiling } from "../../helpers/slippage.js";
10
11
  import { validateDeadline, validateNativeVaultAsset, validateUint256Field, } from "../../helpers/validate.js";
11
12
  import { AmountAndSharesExclusiveError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InsufficientBlueBalanceForInKindRedeemError, NonPositiveInputError, SameVaultMigrationError, VaultAddressMismatchError, VaultAssetMismatchError, VaultIsBlueFeeRecipientError, VaultMorphoMismatchError, } from "../../types/index.js";
13
+ import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
12
14
  import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
13
15
  import { getBundlesTokenRequirements } from "../requirements/index.js";
14
16
  /** Binds a viem client to a Vault V1 (MetaMorpho) vault's action builders. */
@@ -23,12 +25,33 @@ export class MorphoVaultV1 {
23
25
  this.chainId = chainId;
24
26
  }
25
27
  async getData(parameters) {
26
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
28
+ await validateClientChainId(this.client.viemClient, this.chainId);
27
29
  return fetchAccrualVault(this.vault, this.client.viemClient, {
28
30
  ...parameters,
29
31
  deployless: this.client.options.supportDeployless,
30
32
  });
31
33
  }
34
+ /**
35
+ * Asserts that every registry contract this flow's transaction targets or names as
36
+ * spender/authorized operator holds code, with one `eth_getCode` per distinct address
37
+ * before any other requirement read. This VaultV1 `inKindRedeem` path validates the client chain
38
+ * before this code check.
39
+ *
40
+ * @param roles - Registry labels to resolve and check; `permit2` is skipped when the
41
+ * chain registers none.
42
+ */
43
+ async assertWriteTargets(roles) {
44
+ const targets = [];
45
+ for (const role of roles) {
46
+ const address = role === "permit2"
47
+ ? getChainAddresses(this.chainId).permit2
48
+ : getChainAddress(this.chainId, role);
49
+ if (address == null)
50
+ continue;
51
+ targets.push({ role, address });
52
+ }
53
+ await assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, targets);
54
+ }
32
55
  /** {@inheritDoc VaultV1Actions.deposit} */
33
56
  deposit(params) {
34
57
  const { userAddress, vaultData } = params;
@@ -71,20 +94,26 @@ export class MorphoVaultV1 {
71
94
  return await pendingRequirements;
72
95
  // Memoize the in-flight promise so concurrent callers share one round of
73
96
  // allowance/nonce reads.
74
- const pending = funding.value > 0n
75
- ? Promise.resolve([])
76
- : getBundlesTokenRequirements(this.client.viemClient, {
77
- token: vaultAsset,
78
- spender,
79
- amount: funding.assets,
80
- owner: userAddress,
81
- chainId: this.chainId,
82
- deadline,
83
- supportSignature: this.client.options.supportSignature,
84
- supportDeployless: this.client.options.supportDeployless,
85
- useSimplePermit: requirementOptions?.useSimplePermit,
86
- permit2Nonce: requirementOptions?.permit2Nonce,
87
- });
97
+ const pending = (async () => {
98
+ await this.assertWriteTargets(funding.value === 0n && this.client.options.supportSignature
99
+ ? ["bundles.vaultBundlesV1", "permit2"]
100
+ : ["bundles.vaultBundlesV1"]);
101
+ return funding.value > 0n
102
+ ? []
103
+ : getBundlesTokenRequirements(this.client.viemClient, {
104
+ token: vaultAsset,
105
+ spender,
106
+ amount: funding.assets,
107
+ owner: userAddress,
108
+ chainId: this.chainId,
109
+ deadline,
110
+ supportSignature: this.client.options.supportSignature,
111
+ supportDeployless: this.client.options.supportDeployless,
112
+ useSimplePermit: requirementOptions?.useSimplePermit,
113
+ permit2Nonce: requirementOptions?.permit2Nonce,
114
+ now,
115
+ });
116
+ })();
88
117
  pendingRequirements = pending;
89
118
  try {
90
119
  return await pending;
@@ -158,6 +187,7 @@ export class MorphoVaultV1 {
158
187
  const now = Time.timestamp();
159
188
  if (deadline <= now)
160
189
  throw new ExpiredDeadlineError(deadline, now);
190
+ await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
161
191
  // Re-read the live share allowance on every call instead of caching the resolved
162
192
  // requirements: the allowance is the sole cap on the burn, so a caller that executed the
163
193
  // returned approval must see it satisfied on the next call, and an allowance revoked or
@@ -172,6 +202,7 @@ export class MorphoVaultV1 {
172
202
  maxShareAllowance,
173
203
  deadline,
174
204
  supportSignature: this.client.options.supportSignature,
205
+ now,
175
206
  });
176
207
  },
177
208
  buildTx: (signatures) => {
@@ -217,6 +248,7 @@ export class MorphoVaultV1 {
217
248
  const now = Time.timestamp();
218
249
  if (deadline <= now)
219
250
  throw new ExpiredDeadlineError(deadline, now);
251
+ await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
220
252
  return getVaultBundlesSharesRequirements(this.client.viemClient, {
221
253
  vaultData: await this.getData(),
222
254
  version: "vaultV1",
@@ -225,6 +257,7 @@ export class MorphoVaultV1 {
225
257
  requiredShareAllowance: shares,
226
258
  deadline,
227
259
  supportSignature: this.client.options.supportSignature,
260
+ now,
228
261
  });
229
262
  },
230
263
  buildTx: (signatures) => {
@@ -318,6 +351,8 @@ export class MorphoVaultV1 {
318
351
  if (deadline <= requirementsTimestamp) {
319
352
  throw new ExpiredDeadlineError(deadline, requirementsTimestamp);
320
353
  }
354
+ await validateClientChainId(this.client.viemClient, this.chainId);
355
+ await this.assertWriteTargets(["bundles.vaultExitBundlesV1", "blue"]);
321
356
  const [allowance, nonce, blueBalance, morpho, blueFeeRecipient] = await Promise.all([
322
357
  readContract(this.client.viemClient, {
323
358
  address: this.vault,
@@ -499,6 +534,7 @@ export class MorphoVaultV1 {
499
534
  const now = Time.timestamp();
500
535
  if (deadline <= now)
501
536
  throw new ExpiredDeadlineError(deadline, now);
537
+ await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
502
538
  // Re-read the live share allowance on every call instead of caching the resolved
503
539
  // requirements: in assets mode the calldata carries no share limit, so the allowance is
504
540
  // the sole cap on the burn. A caller that executed the returned approval must see it
@@ -514,6 +550,7 @@ export class MorphoVaultV1 {
514
550
  maxShareAllowance,
515
551
  deadline,
516
552
  supportSignature: this.client.options.supportSignature,
553
+ now,
517
554
  });
518
555
  },
519
556
  buildTx: (signatures) => {
@@ -15,12 +15,17 @@ export interface VaultV2Actions {
15
15
  *
16
16
  * @param parameters - Optional viem fetch parameters (block number, block tag, state override).
17
17
  * @returns The hydrated `AccrualVaultV2` snapshot.
18
- * @throws {ChainIdMismatchError} when the connected client targets another chain or has no chain.
18
+ * @throws {ChainIdMismatchError} when the connected client declares another chain or none, or its RPC reports another chain via `eth_chainId`.
19
+ * @throws {viem.BaseError} when the `eth_chainId` request or a state read fails.
19
20
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
20
21
  * @throws {UnknownBlueFactory} when the configured chain has no VaultV2 factory.
21
22
  * @throws {UnknownBlueOfFactory} when the vault is not a VaultV2 from the configured factory.
22
23
  * @throws {UnsupportedBlueVaultV2AdapterError} when the vault or one of its adapters uses an
23
24
  * unsupported adapter class.
25
+ * @throws {UnknownTokenError} when the vault's share token has unusable decimals.
26
+ * @throws {MalformedTokenMetadataError} when the share token's `eip712Domain()` or
27
+ * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
28
+ * deployless query reports malformed `name()`/`symbol()`/`eip712Domain()` returndata (no fallback).
24
29
  */
25
30
  getData: (parameters?: FetchParameters) => Promise<Awaited<ReturnType<typeof fetchAccrualVaultV2>>>;
26
31
  /**
@@ -47,7 +52,8 @@ export interface VaultV2Actions {
47
52
  * two hours from handle creation.
48
53
  * @returns Lazy token prerequisite resolution and a synchronous deep-frozen VaultBundlesV1
49
54
  * transaction builder.
50
- * @throws {ChainIdMismatchError} when the connected client targets another chain.
55
+ * @throws {ChainIdMismatchError} when the connected client targets another chain, or from
56
+ * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
51
57
  * @throws {UnsupportedBlueMarketIrmError} when an underlying market with positive debt uses an unsupported IRM.
52
58
  * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
53
59
  * @throws {ExpiredDeadlineError} when the deadline is stale at creation or requirement resolution.
@@ -76,7 +82,14 @@ export interface VaultV2Actions {
76
82
  * @throws {BundlesRequirementSignatureMismatchError} from `buildTx()` when signature metadata is malformed.
77
83
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
78
84
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered.
79
- * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, or token metadata read fails.
85
+ * @throws {UnknownTokenError} from `getRequirements()` when the token's `decimals()` is unusable.
86
+ * @throws {MalformedTokenMetadataError} when the token's `eip712Domain()` or
87
+ * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
88
+ * deployless query reports malformed `name()`/`symbol()`/`eip712Domain()` returndata (no fallback).
89
+ * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
90
+ * contract has no code at its registered address.
91
+ * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, token metadata
92
+ * read, or `eth_chainId` request fails.
80
93
  * @example
81
94
  * ```ts
82
95
  * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
@@ -136,7 +149,8 @@ export interface VaultV2Actions {
136
149
  * @remarks VaultBundlesV1 skips a share permit whose nonce was already consumed and proceeds
137
150
  * under the live allowance, so execute every requirement returned by the latest
138
151
  * `getRequirements()` — including the oversized-allowance reset — before submitting.
139
- * @throws {ChainIdMismatchError} when the connected client targets another chain.
152
+ * @throws {ChainIdMismatchError} when the connected client targets another chain, or from
153
+ * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
140
154
  * @throws {NonPositiveInputError} when `amount` or the computed share cap is not positive.
141
155
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
142
156
  * at any `getRequirements()` call.
@@ -155,7 +169,10 @@ export interface VaultV2Actions {
155
169
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed or
156
170
  * its spender or deadline differ from this operation's, or its amount is outside
157
171
  * `[cap, cap / (1 - slippageTolerance)]`.
158
- * @throws {viem.BaseError} when an allowance or nonce read or transaction encoding fails.
172
+ * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
173
+ * contract has no code at its registered address.
174
+ * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, or `eth_chainId`
175
+ * read fails, or transaction encoding fails.
159
176
  * @example
160
177
  * ```ts
161
178
  * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
@@ -199,7 +216,8 @@ export interface VaultV2Actions {
199
216
  * @param [params.referralFeeRecipient] - Non-zero recipient required when `referralFeePct` is positive.
200
217
  * @param [params.deadline] - VaultBundlesV1 execution deadline; defaults to two hours from now.
201
218
  * @returns Lazy exact share-allowance requirements and a synchronous transaction builder.
202
- * @throws {ChainIdMismatchError} when the client and entity target different chains.
219
+ * @throws {ChainIdMismatchError} when the client and entity target different chains, or from
220
+ * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
203
221
  * @throws {NonPositiveInputError} when `shares` is not positive.
204
222
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
205
223
  * requirement resolution.
@@ -226,7 +244,15 @@ export interface VaultV2Actions {
226
244
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
227
245
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
228
246
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
229
- * @throws {viem.BaseError} from `getRequirements()` when a vault-state, allowance or nonce read fails.
247
+ * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
248
+ * contract has no code at its registered address.
249
+ * @throws {viem.BaseError} from `getRequirements()` when a vault-state, allowance, nonce, `eth_chainId`, or
250
+ * `eth_getCode` read fails.
251
+ * @throws {UnknownTokenError} from `getRequirements()` when the share token fetched by
252
+ * `getData()` has unusable decimals.
253
+ * @throws {MalformedTokenMetadataError} when the share token's `eip712Domain()` or
254
+ * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
255
+ * deployless query reports malformed `name()`/`symbol()`/`eip712Domain()` returndata (no fallback).
230
256
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
231
257
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
232
258
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -286,7 +312,8 @@ export interface VaultV2Actions {
286
312
  * @param params.adapter - Optional adapter override; defaults to the vault's sole adapter.
287
313
  * @param params.deadline - Optional shared permit/bundle deadline; defaults to two hours from now.
288
314
  * @returns Lazy prerequisite resolution and a synchronous transaction builder.
289
- * @throws {ChainIdMismatchError} when the client and entity target different chains.
315
+ * @throws {ChainIdMismatchError} when the client and entity target different chains, or from
316
+ * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
290
317
  * @throws {UnsupportedBlueMarketIrmError} when an adapter-listed market with positive debt uses an unsupported IRM.
291
318
  * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
292
319
  * @throws {NonPositiveInputError} when `amount` or `deadline` is not positive.
@@ -304,7 +331,9 @@ export interface VaultV2Actions {
304
331
  * @throws {InKindRedeemCoverageError} when the deduplicated list cannot cover the exit.
305
332
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
306
333
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
307
- * @throws {viem.BaseError} from `getRequirements()` when an RPC contract read fails.
334
+ * @throws {viem.BaseError} from `getRequirements()` when the `eth_chainId` request or an
335
+ * RPC contract read fails.
336
+ * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol contract has no code at its registered address.
308
337
  * @throws {InsufficientBlueBalanceForInKindRedeemError} from `getRequirements()` when Blue cannot fund the largest callback.
309
338
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
310
339
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
@@ -410,7 +439,8 @@ export interface VaultV2Actions {
410
439
  * @param params.referralFeeRecipient - Optional referral fee recipient, required when
411
440
  * `referralFeePct` is positive.
412
441
  * @returns Lazy prerequisite resolution and a synchronous transaction builder.
413
- * @throws {ChainIdMismatchError} when the client and entity target different chains.
442
+ * @throws {ChainIdMismatchError} when the client and entity target different chains, or from
443
+ * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
414
444
  * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
415
445
  * @throws {NonPositiveInputError} when `exitAssets`, `deadline`, or a supplied
416
446
  * `minSharePriceE27` is not positive.
@@ -442,7 +472,9 @@ export interface VaultV2Actions {
442
472
  * @throws {ReferralFeeRecipientMissingError} when a positive `referralFeePct` has no recipient.
443
473
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
444
474
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
445
- * @throws {viem.BaseError} from `getRequirements()` when an RPC contract read fails.
475
+ * @throws {viem.BaseError} from `getRequirements()` when the `eth_chainId` request or an
476
+ * RPC contract read fails.
477
+ * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol contract has no code at its registered address.
446
478
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
447
479
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
448
480
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the permit's spender, amount, or
@@ -503,7 +535,7 @@ export interface VaultV2Actions {
503
535
  * @param params.userAddress - Account that pays the deallocation penalties and receives the redeemed assets.
504
536
  * @returns An object whose `buildTx()` returns a deep-frozen `Transaction<VaultV2ForceRedeemAction>`
505
537
  * encoding the vault `multicall`.
506
- * @throws {ChainIdMismatchError} when the connected client targets another chain or has no chain.
538
+ * @throws {ChainIdMismatchError} when the connected client declares another chain or none.
507
539
  * @throws {EmptyDeallocationsError} from `buildTx()` when `deallocations` is empty.
508
540
  * @throws {NonPositiveInputError} from `buildTx()` when `redeem.shares <= 0n` or any deallocation
509
541
  * amount is non-positive.
@@ -537,6 +569,16 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
537
569
  private readonly chainId;
538
570
  constructor(client: MorphoClientType, vault: Address, chainId: number);
539
571
  getData(parameters?: FetchParameters): Promise<AccrualVaultV2>;
572
+ /**
573
+ * Asserts that every registry contract this flow's transaction targets or names as
574
+ * spender/authorized operator holds code, with one `eth_getCode` per distinct address
575
+ * before any other requirement read. The `inKindRedeem` and `forceWithdraw` paths validate the
576
+ * client chain before this code check.
577
+ *
578
+ * @param roles - Registry labels to resolve and check; `permit2` is skipped when the
579
+ * chain registers none.
580
+ */
581
+ private assertWriteTargets;
540
582
  /** {@inheritDoc VaultV2Actions.deposit} */
541
583
  deposit(params: {
542
584
  readonly userAddress: Address;
@@ -1,14 +1,16 @@
1
1
  import { AccrualVaultV2MorphoMarketV1AdapterV2, DEFAULT_SLIPPAGE_TOLERANCE, MarketUtils, MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { erc2612Abi, fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
- import { _try, getChainAddress, Time } from "@morpho-org/morpho-ts";
3
+ import { _try, getChainAddress, getChainAddresses, 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";
7
7
  import { encodeErc20Approval, encodeVaultSharesPermit, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2InKindRedeem, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
8
+ import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
8
9
  import { computeMinForceWithdrawSharePrice, computeVaultMaxShareAllowance, computeVaultMaxSharePrice, computeVaultV2ForceWithdrawFeeSharesMinted, computeVaultV2ForceWithdrawMinSharesBurnt, computeVaultV2ForceWithdrawPlan, computeVaultV2ForceWithdrawSharesBurnt, MAX_SLIPPAGE_TOLERANCE, resolveVaultV2ForceWithdrawEligibility, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
9
10
  import { computeVaultShareAllowanceCeiling } from "../../helpers/slippage.js";
10
11
  import { validateDeadline, validateNativeVaultAsset, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
11
12
  import { AdapterNotPartOfVaultError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemZeroDeallocationError, InputExceedsMaxError, InsufficientBlueBalanceForInKindRedeemError, NonPositiveInputError, VaultAddressMismatchError, VaultV2ForceWithdrawCoverageError, VaultV2ForceWithdrawFeeSharesExceedBurnError, VaultV2ForceWithdrawSharePriceBelowFloorError, VaultV2ForceWithdrawZeroSharePriceError, VaultV2ForceWithdrawZeroWithdrawalError, VaultV2SingleAdapterRequiredError, VaultV2UndecodableLiquidityDataError, VaultV2UnsupportedExitAdapterError, VaultV2UnsupportedLiquidityAdapterError, } from "../../types/index.js";
13
+ import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
12
14
  import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
13
15
  import { getBundlesTokenRequirements } from "../requirements/index.js";
14
16
  // Maximum accepted deadline horizon; the on-chain management fee is capped at 5%/yr so the
@@ -31,12 +33,33 @@ export class MorphoVaultV2 {
31
33
  this.chainId = chainId;
32
34
  }
33
35
  async getData(parameters) {
34
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
36
+ await validateClientChainId(this.client.viemClient, this.chainId);
35
37
  return fetchAccrualVaultV2(this.vault, this.client.viemClient, {
36
38
  ...parameters,
37
39
  deployless: this.client.options.supportDeployless,
38
40
  });
39
41
  }
42
+ /**
43
+ * Asserts that every registry contract this flow's transaction targets or names as
44
+ * spender/authorized operator holds code, with one `eth_getCode` per distinct address
45
+ * before any other requirement read. The `inKindRedeem` and `forceWithdraw` paths validate the
46
+ * client chain before this code check.
47
+ *
48
+ * @param roles - Registry labels to resolve and check; `permit2` is skipped when the
49
+ * chain registers none.
50
+ */
51
+ async assertWriteTargets(roles) {
52
+ const targets = [];
53
+ for (const role of roles) {
54
+ const address = role === "permit2"
55
+ ? getChainAddresses(this.chainId).permit2
56
+ : getChainAddress(this.chainId, role);
57
+ if (address == null)
58
+ continue;
59
+ targets.push({ role, address });
60
+ }
61
+ await assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, targets);
62
+ }
40
63
  /** {@inheritDoc VaultV2Actions.deposit} */
41
64
  deposit(params) {
42
65
  const { userAddress, vaultData } = params;
@@ -86,20 +109,26 @@ export class MorphoVaultV2 {
86
109
  return await pendingRequirements;
87
110
  // Memoize the in-flight promise so concurrent callers share one round of
88
111
  // allowance/nonce reads.
89
- const pending = funding.value > 0n
90
- ? Promise.resolve([])
91
- : getBundlesTokenRequirements(this.client.viemClient, {
92
- token: vaultAsset,
93
- spender,
94
- amount: funding.assets,
95
- owner: userAddress,
96
- chainId: this.chainId,
97
- deadline,
98
- supportSignature: this.client.options.supportSignature,
99
- supportDeployless: this.client.options.supportDeployless,
100
- useSimplePermit: requirementOptions?.useSimplePermit,
101
- permit2Nonce: requirementOptions?.permit2Nonce,
102
- });
112
+ const pending = (async () => {
113
+ await this.assertWriteTargets(funding.value === 0n && this.client.options.supportSignature
114
+ ? ["bundles.vaultBundlesV1", "permit2"]
115
+ : ["bundles.vaultBundlesV1"]);
116
+ return funding.value > 0n
117
+ ? []
118
+ : getBundlesTokenRequirements(this.client.viemClient, {
119
+ token: vaultAsset,
120
+ spender,
121
+ amount: funding.assets,
122
+ owner: userAddress,
123
+ chainId: this.chainId,
124
+ deadline,
125
+ supportSignature: this.client.options.supportSignature,
126
+ supportDeployless: this.client.options.supportDeployless,
127
+ useSimplePermit: requirementOptions?.useSimplePermit,
128
+ permit2Nonce: requirementOptions?.permit2Nonce,
129
+ now,
130
+ });
131
+ })();
103
132
  pendingRequirements = pending;
104
133
  try {
105
134
  return await pending;
@@ -181,6 +210,7 @@ export class MorphoVaultV2 {
181
210
  const now = Time.timestamp();
182
211
  if (deadline <= now)
183
212
  throw new ExpiredDeadlineError(deadline, now);
213
+ await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
184
214
  // Re-read the live share allowance on every call instead of caching the resolved
185
215
  // requirements: the allowance is the sole cap on the burn, so a caller that executed the
186
216
  // returned approval must see it satisfied on the next call, and an allowance revoked or
@@ -195,6 +225,7 @@ export class MorphoVaultV2 {
195
225
  maxShareAllowance,
196
226
  deadline,
197
227
  supportSignature: this.client.options.supportSignature,
228
+ now,
198
229
  });
199
230
  },
200
231
  buildTx: (signatures) => {
@@ -240,6 +271,7 @@ export class MorphoVaultV2 {
240
271
  const now = Time.timestamp();
241
272
  if (deadline <= now)
242
273
  throw new ExpiredDeadlineError(deadline, now);
274
+ await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
243
275
  const vaultData = await this.getData();
244
276
  if (isMidnightLiquidityAdapter(vaultData)) {
245
277
  // Onchain redeem accrues interest before converting shares to assets.
@@ -260,6 +292,7 @@ export class MorphoVaultV2 {
260
292
  requiredShareAllowance: shares,
261
293
  deadline,
262
294
  supportSignature: this.client.options.supportSignature,
295
+ now,
263
296
  });
264
297
  },
265
298
  buildTx: (signatures) => {
@@ -385,6 +418,8 @@ export class MorphoVaultV2 {
385
418
  if (deadline <= requirementsTimestamp) {
386
419
  throw new ExpiredDeadlineError(deadline, requirementsTimestamp);
387
420
  }
421
+ await validateClientChainId(this.client.viemClient, this.chainId);
422
+ await this.assertWriteTargets(["bundles.vaultExitBundlesV1", "blue"]);
388
423
  // Vault gates are intentionally left to the final transaction. A receive gate may inspect
389
424
  // VaultExitBundlesV1's transient `initiator`, which is populated only during the actual
390
425
  // periphery call. A send-share gate is arbitrary external code and is evaluated repeatedly
@@ -647,6 +682,8 @@ export class MorphoVaultV2 {
647
682
  if (deadline <= requirementsTimestamp) {
648
683
  throw new ExpiredDeadlineError(deadline, requirementsTimestamp);
649
684
  }
685
+ await validateClientChainId(this.client.viemClient, this.chainId);
686
+ await this.assertWriteTargets(["bundles.vaultExitBundlesV1"]);
650
687
  // Vault gates are intentionally left to the final transaction: the receive-assets gate may
651
688
  // inspect VaultExitBundlesV1's transient `initiator`, and a send-shares gate is arbitrary
652
689
  // external code re-evaluated after each intermediate penalty burn, so neither is
@@ -371,12 +371,18 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
371
371
  * (two hours by default; `0n` disables it). When an operation's plan would
372
372
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
373
373
  * BluePublicAllocator cap, the plan is reduced to the larger of the
374
- * operation's absolute shortfall and what vaults below their cap moved. The
375
- * kept headroom absorbs other allocations up to that share of the cap landing
376
- * before inclusion. The plan uses the full cap only when the shortfall needs
377
- * it, and can then still revert if another allocation lands first. A plan of
378
- * only the shortfall leaves the market fully utilized, so a competing borrow
379
- * or withdraw landing first can also make it revert. For market-source reallocations
374
+ * operation's absolute shortfall and what unbound legs moved (legs that
375
+ * neither come within the headroom of an allocator cap nor take nearly all
376
+ * of their source vault's idle). The kept headroom absorbs other allocations
377
+ * up to that share of the cap landing before inclusion. The plan uses the
378
+ * full cap only when the shortfall needs it, and can then still revert if
379
+ * another allocation lands first.
380
+ * Idle legs that together leave at most `allocatorCapHeadroom` of a source
381
+ * vault's starting idle are bound the same way, so an operation without
382
+ * shortfall whose plan draws only on such idle plans no reallocation.
383
+ * A plan of only the shortfall leaves the market fully utilized, so a
384
+ * competing borrow or withdraw landing first can also make it revert. For
385
+ * market-source reallocations
380
386
  * the source position's interest is also reserved on cap ids shared with the
381
387
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
382
388
  * or allocator capacity are skipped before projecting source interest. The
@@ -573,12 +573,18 @@ export class VaultV2BlueReallocationData {
573
573
  * (two hours by default; `0n` disables it). When an operation's plan would
574
574
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
575
575
  * BluePublicAllocator cap, the plan is reduced to the larger of the
576
- * operation's absolute shortfall and what vaults below their cap moved. The
577
- * kept headroom absorbs other allocations up to that share of the cap landing
578
- * before inclusion. The plan uses the full cap only when the shortfall needs
579
- * it, and can then still revert if another allocation lands first. A plan of
580
- * only the shortfall leaves the market fully utilized, so a competing borrow
581
- * or withdraw landing first can also make it revert. For market-source reallocations
576
+ * operation's absolute shortfall and what unbound legs moved (legs that
577
+ * neither come within the headroom of an allocator cap nor take nearly all
578
+ * of their source vault's idle). The kept headroom absorbs other allocations
579
+ * up to that share of the cap landing before inclusion. The plan uses the
580
+ * full cap only when the shortfall needs it, and can then still revert if
581
+ * another allocation lands first.
582
+ * Idle legs that together leave at most `allocatorCapHeadroom` of a source
583
+ * vault's starting idle are bound the same way, so an operation without
584
+ * shortfall whose plan draws only on such idle plans no reallocation.
585
+ * A plan of only the shortfall leaves the market fully utilized, so a
586
+ * competing borrow or withdraw landing first can also make it revert. For
587
+ * market-source reallocations
582
588
  * the source position's interest is also reserved on cap ids shared with the
583
589
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
584
590
  * or allocator capacity are skipped before projecting source interest. The
@@ -739,29 +745,32 @@ export class VaultV2BlueReallocationData {
739
745
  }
740
746
  // The fallback pass only runs when the plan moves exactly the absolute
741
747
  // shortfall, which a reduced plan would move anyway.
742
- const capBoundTargets = friendly.allocatorCapBoundTargets;
748
+ const allocatorCapBoundTargets = friendly.allocatorCapBoundTargets;
749
+ const idleBoundVaults = friendly.idleBoundVaults;
743
750
  let reallocatedAssets = 0n;
744
751
  let unboundAssets = 0n;
745
- for (const { vault, to, assets } of reallocations) {
752
+ for (const { vault, from, to, assets } of reallocations) {
746
753
  reallocatedAssets += assets;
747
754
  const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
748
- if (!capBoundTargets.has(key))
755
+ if (!allocatorCapBoundTargets.has(key) &&
756
+ !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
749
757
  unboundAssets += assets;
750
758
  }
751
759
  return {
752
760
  reallocations,
753
761
  data,
754
- capBound: capBoundTargets.size > 0,
762
+ liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
755
763
  reallocatedAssets,
756
764
  unboundAssets,
757
765
  };
758
766
  };
759
- // A leg that fills an allocator cap reverts once any other allocation to
760
- // that market lands first. A cap-bound plan therefore moves only the
761
- // operation's shortfall, or what vaults below their cap already moved.
767
+ // A leg that fills an allocator cap, or idle legs that together take
768
+ // (nearly) all of a source vault's starting idle, revert once another
769
+ // allocation lands first. A bound plan therefore moves only the operation's
770
+ // shortfall, or what unbound legs moved.
762
771
  const target = plan(requiredAssets, allocatorCapHeadroom);
763
772
  let selected = target;
764
- if (allocatorCapHeadroom > 0n && target.capBound) {
773
+ if (allocatorCapHeadroom > 0n && target.liquidityBound) {
765
774
  selected = plan(absoluteShortfall > target.unboundAssets
766
775
  ? absoluteShortfall
767
776
  : target.unboundAssets, allocatorCapHeadroom);
@@ -796,6 +805,7 @@ export class VaultV2BlueReallocationData {
796
805
  data: this,
797
806
  context,
798
807
  allocatorCapBoundTargets: new Set(),
808
+ idleBoundVaults: new Set(),
799
809
  };
800
810
  this.getMarket(marketId);
801
811
  const timestamp = options.timestamp == null
@@ -815,6 +825,9 @@ export class VaultV2BlueReallocationData {
815
825
  const activeAdaptersCache = new Map();
816
826
  let remainingAssets = maxAssets;
817
827
  const allocatorCapBoundTargets = new Set();
828
+ const idleBoundVaults = new Set();
829
+ const initialIdleAssets = new Map();
830
+ const idleTakenAssets = new Map();
818
831
  // Onchain, market interest is booked once at transaction start, on pre-plan
819
832
  // positions at pre-plan rates, and stays on touched positions' cap ids.
820
833
  // This reserve state is shared across every planner pass and leg of the plan.
@@ -883,6 +896,9 @@ export class VaultV2BlueReallocationData {
883
896
  const availableIdleAssets = MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssetsKey == null
884
897
  ? 0n
885
898
  : simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey]);
899
+ const vaultAddressKey = vaultAddress.toLowerCase();
900
+ if (!initialIdleAssets.has(vaultAddressKey))
901
+ initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
886
902
  let activeAdapters = activeAdaptersCache.get(vaultAddress);
887
903
  if (activeAdapters == null) {
888
904
  activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
@@ -1107,11 +1123,22 @@ export class VaultV2BlueReallocationData {
1107
1123
  data,
1108
1124
  context: simulationContext,
1109
1125
  allocatorCapBoundTargets,
1126
+ idleBoundVaults,
1110
1127
  };
1111
1128
  const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1112
1129
  if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1113
1130
  // BluePublicAllocator caps are per vault and target adapter.
1114
1131
  allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1132
+ if (acceptedReallocation.from.type === "idle") {
1133
+ const vaultKey = acceptedReallocation.vault.toLowerCase();
1134
+ const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
1135
+ idleTakenAssets.set(vaultKey, taken);
1136
+ // Candidates always record this; a missing entry counts the vault as bound.
1137
+ const initial = initialIdleAssets.get(vaultKey) ?? 0n;
1138
+ if (taken >=
1139
+ MathLib.zeroFloorSub(initial, MathLib.wMulUp(initial, allocatorCapHeadroom)))
1140
+ idleBoundVaults.add(vaultKey);
1141
+ }
1115
1142
  const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1116
1143
  let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1117
1144
  if (touchedVaultPairs == null) {
@@ -1141,6 +1168,7 @@ export class VaultV2BlueReallocationData {
1141
1168
  data,
1142
1169
  context: simulationContext,
1143
1170
  allocatorCapBoundTargets,
1171
+ idleBoundVaults,
1144
1172
  };
1145
1173
  }
1146
1174
  /**
@@ -1,7 +1,7 @@
1
1
  export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, InvalidVaultV2MidnightAdapterMarketsError as InvalidBlueVaultV2MidnightAdapterMarketsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError as BlueUnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError as BlueUnresolvedBlockNumberError, 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, 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
7
  export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";