@morpho-org/morpho-sdk 5.5.0 → 5.6.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 (90) hide show
  1. package/README.md +8 -6
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +3 -1
  4. package/lib/cjs/actions/blue/borrow.d.ts +21 -15
  5. package/lib/cjs/actions/blue/borrow.js +25 -18
  6. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +1 -1
  7. package/lib/cjs/actions/blue/buildAssetFundingActions.js +1 -1
  8. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +62 -19
  9. package/lib/cjs/actions/blue/buildReallocationActions.js +123 -27
  10. package/lib/cjs/actions/blue/refinance.d.ts +14 -7
  11. package/lib/cjs/actions/blue/refinance.js +18 -10
  12. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +28 -19
  13. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +39 -23
  14. package/lib/cjs/actions/blue/withdraw.d.ts +20 -13
  15. package/lib/cjs/actions/blue/withdraw.js +23 -18
  16. package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -1
  17. package/lib/cjs/bundler/actions.d.ts +117 -0
  18. package/lib/cjs/bundler/actions.js +211 -4
  19. package/lib/cjs/bundler/types.d.ts +20 -0
  20. package/lib/cjs/constants.d.ts +1 -1
  21. package/lib/cjs/constants.js +3 -1
  22. package/lib/cjs/entities/blue/blue.d.ts +360 -71
  23. package/lib/cjs/entities/blue/blue.js +285 -52
  24. package/lib/cjs/entities/index.d.ts +2 -1
  25. package/lib/cjs/entities/index.js +6 -3
  26. package/lib/cjs/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +40 -15
  27. package/lib/cjs/entities/{reallocationData.js → vaultV1ReallocationData.js} +29 -16
  28. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +1 -1
  29. package/lib/cjs/entities/vaultV2/vaultV2.js +1 -1
  30. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +511 -0
  31. package/lib/cjs/entities/vaultV2BlueReallocationData.js +1311 -0
  32. package/lib/{esm/helpers/computeReallocations.d.ts → cjs/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  33. package/lib/cjs/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +27 -13
  34. package/lib/cjs/helpers/constant.d.ts +5 -3
  35. package/lib/cjs/helpers/constant.js +6 -4
  36. package/lib/cjs/helpers/index.d.ts +2 -2
  37. package/lib/cjs/helpers/index.js +6 -3
  38. package/lib/cjs/helpers/validate.d.ts +30 -14
  39. package/lib/cjs/helpers/validate.js +140 -27
  40. package/lib/cjs/types/action.d.ts +12 -0
  41. package/lib/cjs/types/error.d.ts +224 -5
  42. package/lib/cjs/types/error.js +269 -7
  43. package/lib/cjs/types/sharedLiquidity.d.ts +72 -8
  44. package/lib/cjs/utils.d.ts +2 -2
  45. package/lib/cjs/utils.js +6 -4
  46. package/lib/esm/abis.d.ts +1 -1
  47. package/lib/esm/abis.js +1 -1
  48. package/lib/esm/actions/blue/borrow.d.ts +21 -15
  49. package/lib/esm/actions/blue/borrow.js +26 -19
  50. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +1 -1
  51. package/lib/esm/actions/blue/buildAssetFundingActions.js +1 -1
  52. package/lib/esm/actions/blue/buildReallocationActions.d.ts +62 -19
  53. package/lib/esm/actions/blue/buildReallocationActions.js +119 -25
  54. package/lib/esm/actions/blue/refinance.d.ts +14 -7
  55. package/lib/esm/actions/blue/refinance.js +19 -11
  56. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +28 -19
  57. package/lib/esm/actions/blue/supplyCollateralBorrow.js +40 -24
  58. package/lib/esm/actions/blue/withdraw.d.ts +20 -13
  59. package/lib/esm/actions/blue/withdraw.js +24 -19
  60. package/lib/esm/actions/requirements/getRequirementsApproval.js +2 -1
  61. package/lib/esm/bundler/actions.d.ts +117 -0
  62. package/lib/esm/bundler/actions.js +214 -7
  63. package/lib/esm/bundler/types.d.ts +20 -0
  64. package/lib/esm/constants.d.ts +1 -1
  65. package/lib/esm/constants.js +1 -1
  66. package/lib/esm/entities/blue/blue.d.ts +360 -71
  67. package/lib/esm/entities/blue/blue.js +288 -55
  68. package/lib/esm/entities/index.d.ts +2 -1
  69. package/lib/esm/entities/index.js +2 -1
  70. package/lib/esm/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +40 -15
  71. package/lib/esm/entities/{reallocationData.js → vaultV1ReallocationData.js} +32 -14
  72. package/lib/esm/entities/vaultV2/vaultV2.d.ts +1 -1
  73. package/lib/esm/entities/vaultV2/vaultV2.js +1 -1
  74. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +511 -0
  75. package/lib/esm/entities/vaultV2BlueReallocationData.js +1307 -0
  76. package/lib/{cjs/helpers/computeReallocations.d.ts → esm/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  77. package/lib/esm/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +25 -11
  78. package/lib/esm/helpers/constant.d.ts +5 -3
  79. package/lib/esm/helpers/constant.js +5 -3
  80. package/lib/esm/helpers/index.d.ts +2 -2
  81. package/lib/esm/helpers/index.js +2 -2
  82. package/lib/esm/helpers/validate.d.ts +30 -14
  83. package/lib/esm/helpers/validate.js +141 -30
  84. package/lib/esm/types/action.d.ts +12 -0
  85. package/lib/esm/types/error.d.ts +224 -5
  86. package/lib/esm/types/error.js +253 -4
  87. package/lib/esm/types/sharedLiquidity.d.ts +72 -8
  88. package/lib/esm/utils.d.ts +2 -2
  89. package/lib/esm/utils.js +2 -2
  90. package/package.json +5 -5
@@ -1,11 +1,13 @@
1
- import { AccrualPosition, DEFAULT_SLIPPAGE_TOLERANCE, MathLib, } from "@morpho-org/blue-sdk";
2
- import { fetchAccrualPosition, fetchMarket, fetchPosition, fetchVault, fetchVaultMarketConfig, } from "@morpho-org/blue-sdk-viem";
1
+ import { AccrualPosition, DEFAULT_SLIPPAGE_TOLERANCE, MathLib, VaultV2BluePublicAllocatorConfigUtils, } from "@morpho-org/blue-sdk";
2
+ import { fetchAccrualPosition, fetchAccrualVaultV2, fetchMarket, fetchPosition, fetchVault, fetchVaultMarketConfig, fetchVaultV2BluePublicAllocatorData, } from "@morpho-org/blue-sdk-viem";
3
3
  import { Time } from "@morpho-org/morpho-ts";
4
4
  import { isAddressEqual } from "viem";
5
5
  import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawCollateral, getBlueAuthorizationRequirement, getGeneralAdapterRequirements, } from "../../actions/index.js";
6
- import { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, computeReallocations, validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
6
+ import { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, computeVaultV1Reallocations, validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
7
+ import { validateAndNormalizeReallocations } from "../../helpers/validate.js";
7
8
  import { BorrowAmountAndSharesExclusiveError, MarketIdMismatchError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, RefinanceExceedsBorrowAssetsError, RefinanceExceedsBorrowSharesError, RefinanceExceedsCollateralError, RefinanceSameMarketError, RefinanceTokenMismatchError, selectRequirementSignatures, WithdrawExceedsCollateralError, } from "../../types/index.js";
8
- import { ReallocationData } from "../reallocationData.js";
9
+ import { VaultV1ReallocationData } from "../vaultV1ReallocationData.js";
10
+ import { VaultV2BlueReallocationData } from "../vaultV2BlueReallocationData.js";
9
11
  export class MorphoBlue {
10
12
  client;
11
13
  marketParams;
@@ -16,6 +18,22 @@ export class MorphoBlue {
16
18
  this.marketParams = marketParams;
17
19
  this.chainId = chainId;
18
20
  }
21
+ getReallocationPenaltyRequirements(userAddress, reallocationPlan) {
22
+ if (reallocationPlan.type === "vaultV1")
23
+ return [];
24
+ const { reallocations } = reallocationPlan;
25
+ const amount = reallocations.reduce((total, reallocation) => total +
26
+ VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets), 0n);
27
+ // Separate-token penalty funding uses a classic GeneralAdapter1 allowance so a collateral
28
+ // permit and a loan-token penalty can coexist in one bundle. The shared-token path aggregates
29
+ // both amounts into the collateral requirement instead.
30
+ return getGeneralAdapterRequirements(this.client.viemClient, {
31
+ address: this.marketParams.loanToken,
32
+ chainId: this.chainId,
33
+ supportSignature: false,
34
+ args: { amount, from: userAddress },
35
+ });
36
+ }
19
37
  async getMarketData(parameters) {
20
38
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
21
39
  return fetchMarket(this.marketParams.id, this.client.viemClient, {
@@ -89,6 +107,12 @@ export class MorphoBlue {
89
107
  withdraw(params) {
90
108
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
91
109
  const { userAddress, receiver = userAddress, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, reallocations, } = params;
110
+ const reallocationPlan = validateAndNormalizeReallocations({
111
+ reallocations,
112
+ targetMarketId: this.marketParams.id,
113
+ chainId: this.chainId,
114
+ });
115
+ const reallocationList = reallocationPlan.reallocations;
92
116
  // Mode normalization: a missing or undefined `assets`/`shares` key collapses to `0n`
93
117
  // so the mutual-exclusion and positivity checks below are pure value comparisons.
94
118
  const assets = ("assets" in params ? params.assets : undefined) ?? 0n;
@@ -110,9 +134,6 @@ export class MorphoBlue {
110
134
  throw new NonPositiveInputError("assets or shares", 0n);
111
135
  }
112
136
  validateSlippageTolerance(slippageTolerance);
113
- if (reallocations) {
114
- validateReallocations(reallocations, this.marketParams.id);
115
- }
116
137
  if (!positionData) {
117
138
  throw new MissingAccrualPositionError(this.marketParams.id);
118
139
  }
@@ -143,13 +164,16 @@ export class MorphoBlue {
143
164
  });
144
165
  return {
145
166
  getRequirements: async () => {
146
- const authTx = await getBlueAuthorizationRequirement({
147
- viemClient: this.client.viemClient,
148
- chainId: this.chainId,
149
- userAddress,
150
- supportSignature: this.client.options.supportSignature,
151
- });
152
- return authTx ? [authTx] : [];
167
+ const [penaltyRequirements, authTx] = await Promise.all([
168
+ this.getReallocationPenaltyRequirements(userAddress, reallocationPlan),
169
+ getBlueAuthorizationRequirement({
170
+ viemClient: this.client.viemClient,
171
+ chainId: this.chainId,
172
+ userAddress,
173
+ supportSignature: this.client.options.supportSignature,
174
+ }),
175
+ ]);
176
+ return [...penaltyRequirements, ...(authTx ? [authTx] : [])];
153
177
  },
154
178
  buildTx: (signatures) => {
155
179
  const { authorization } = selectRequirementSignatures(signatures, {
@@ -162,7 +186,7 @@ export class MorphoBlue {
162
186
  shares,
163
187
  receiver,
164
188
  minSharePrice,
165
- reallocations,
189
+ reallocations: reallocationList,
166
190
  authorizationSignature: authorization,
167
191
  },
168
192
  metadata: this.client.options.metadata,
@@ -216,13 +240,16 @@ export class MorphoBlue {
216
240
  }
217
241
  borrow({ amount, userAddress, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, reallocations, }) {
218
242
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
243
+ const reallocationPlan = validateAndNormalizeReallocations({
244
+ reallocations,
245
+ targetMarketId: this.marketParams.id,
246
+ chainId: this.chainId,
247
+ });
248
+ const reallocationList = reallocationPlan.reallocations;
219
249
  if (amount <= 0n) {
220
250
  throw new NonPositiveInputError("amount", amount);
221
251
  }
222
252
  validateSlippageTolerance(slippageTolerance);
223
- if (reallocations) {
224
- validateReallocations(reallocations, this.marketParams.id);
225
- }
226
253
  if (!positionData) {
227
254
  throw new MissingAccrualPositionError(this.marketParams.id);
228
255
  }
@@ -245,13 +272,16 @@ export class MorphoBlue {
245
272
  });
246
273
  return {
247
274
  getRequirements: async () => {
248
- const authTx = await getBlueAuthorizationRequirement({
249
- viemClient: this.client.viemClient,
250
- chainId: this.chainId,
251
- userAddress,
252
- supportSignature: this.client.options.supportSignature,
253
- });
254
- return authTx ? [authTx] : [];
275
+ const [penaltyRequirements, authTx] = await Promise.all([
276
+ this.getReallocationPenaltyRequirements(userAddress, reallocationPlan),
277
+ getBlueAuthorizationRequirement({
278
+ viemClient: this.client.viemClient,
279
+ chainId: this.chainId,
280
+ userAddress,
281
+ supportSignature: this.client.options.supportSignature,
282
+ }),
283
+ ]);
284
+ return [...penaltyRequirements, ...(authTx ? [authTx] : [])];
255
285
  },
256
286
  buildTx: (signatures) => {
257
287
  const { authorization } = selectRequirementSignatures(signatures, {
@@ -266,7 +296,7 @@ export class MorphoBlue {
266
296
  amount,
267
297
  receiver: userAddress,
268
298
  minSharePrice,
269
- reallocations,
299
+ reallocations: reallocationList,
270
300
  authorizationSignature: authorization,
271
301
  },
272
302
  metadata: this.client.options.metadata,
@@ -603,6 +633,12 @@ export class MorphoBlue {
603
633
  }
604
634
  supplyCollateralBorrow({ amount = 0n, userAddress, positionData, borrowAmount, nativeAmount, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, reallocations, }) {
605
635
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
636
+ const reallocationPlan = validateAndNormalizeReallocations({
637
+ reallocations,
638
+ targetMarketId: this.marketParams.id,
639
+ chainId: this.chainId,
640
+ });
641
+ const reallocationList = reallocationPlan.reallocations;
606
642
  if (amount < 0n) {
607
643
  throw new NegativeInputError("amount", amount);
608
644
  }
@@ -617,9 +653,6 @@ export class MorphoBlue {
617
653
  throw new NonPositiveInputError("totalCollateral", totalCollateral);
618
654
  }
619
655
  validateSlippageTolerance(slippageTolerance);
620
- if (reallocations) {
621
- validateReallocations(reallocations, this.marketParams.id);
622
- }
623
656
  if (!positionData) {
624
657
  throw new MissingAccrualPositionError(this.marketParams.id);
625
658
  }
@@ -645,15 +678,26 @@ export class MorphoBlue {
645
678
  });
646
679
  return {
647
680
  getRequirements: async (params) => {
648
- const [erc20Requirements, authTx] = await Promise.all([
681
+ const penaltyAssets = reallocationPlan.type === "vaultV2Blue"
682
+ ? reallocationPlan.reallocations.reduce((total, reallocation) => total +
683
+ VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets), 0n)
684
+ : 0n;
685
+ const usesSharedFundingToken = isAddressEqual(this.marketParams.collateralToken, this.marketParams.loanToken);
686
+ const [erc20Requirements, penaltyRequirements, authTx] = await Promise.all([
649
687
  getGeneralAdapterRequirements(this.client.viemClient, {
650
688
  address: this.marketParams.collateralToken,
651
689
  chainId: this.chainId,
652
690
  supportSignature: this.client.options.supportSignature,
653
691
  supportDeployless: this.client.options.supportDeployless,
654
692
  useSimplePermit: params?.useSimplePermit,
655
- args: { amount, from: userAddress },
693
+ args: {
694
+ amount: amount + (usesSharedFundingToken ? penaltyAssets : 0n),
695
+ from: userAddress,
696
+ },
656
697
  }),
698
+ usesSharedFundingToken
699
+ ? []
700
+ : this.getReallocationPenaltyRequirements(userAddress, reallocationPlan),
657
701
  getBlueAuthorizationRequirement({
658
702
  viemClient: this.client.viemClient,
659
703
  chainId: this.chainId,
@@ -661,7 +705,11 @@ export class MorphoBlue {
661
705
  supportSignature: this.client.options.supportSignature,
662
706
  }),
663
707
  ]);
664
- return [...erc20Requirements, ...(authTx ? [authTx] : [])];
708
+ return [
709
+ ...erc20Requirements,
710
+ ...penaltyRequirements,
711
+ ...(authTx ? [authTx] : []),
712
+ ];
665
713
  },
666
714
  buildTx: (signatures) => {
667
715
  const { permit, authorization } = selectRequirementSignatures(signatures, { permit: true, authorization: true });
@@ -679,7 +727,7 @@ export class MorphoBlue {
679
727
  minSharePrice,
680
728
  requirementSignature: permit,
681
729
  authorizationSignature: authorization,
682
- reallocations,
730
+ reallocations: reallocationList,
683
731
  },
684
732
  metadata: this.client.options.metadata,
685
733
  });
@@ -689,6 +737,12 @@ export class MorphoBlue {
689
737
  refinance({ userAddress, positionData, target, collateralAmount, borrowAssets, borrowShares, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, targetReallocations, }) {
690
738
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
691
739
  validateSlippageTolerance(slippageTolerance);
740
+ const targetReallocationPlan = validateAndNormalizeReallocations({
741
+ reallocations: targetReallocations,
742
+ targetMarketId: target.marketParams.id,
743
+ chainId: this.chainId,
744
+ });
745
+ const targetReallocationList = targetReallocationPlan.reallocations;
692
746
  if (collateralAmount <= 0n) {
693
747
  throw new NonPositiveInputError("collateralAmount", collateralAmount);
694
748
  }
@@ -703,9 +757,6 @@ export class MorphoBlue {
703
757
  if (requestedAssets > 0n && requestedShares > 0n) {
704
758
  throw new BorrowAmountAndSharesExclusiveError(this.marketParams.id);
705
759
  }
706
- if (targetReallocations) {
707
- validateReallocations(targetReallocations, target.marketParams.id);
708
- }
709
760
  if (!positionData) {
710
761
  throw new MissingAccrualPositionError(this.marketParams.id);
711
762
  }
@@ -819,13 +870,16 @@ export class MorphoBlue {
819
870
  : 0n;
820
871
  return {
821
872
  getRequirements: async () => {
822
- const authTx = await getBlueAuthorizationRequirement({
823
- viemClient: this.client.viemClient,
824
- chainId: this.chainId,
825
- userAddress,
826
- supportSignature: this.client.options.supportSignature,
827
- });
828
- return authTx ? [authTx] : [];
873
+ const [penaltyRequirements, authTx] = await Promise.all([
874
+ this.getReallocationPenaltyRequirements(userAddress, targetReallocationPlan),
875
+ getBlueAuthorizationRequirement({
876
+ viemClient: this.client.viemClient,
877
+ chainId: this.chainId,
878
+ userAddress,
879
+ supportSignature: this.client.options.supportSignature,
880
+ }),
881
+ ]);
882
+ return [...penaltyRequirements, ...(authTx ? [authTx] : [])];
829
883
  },
830
884
  buildTx: (signatures) => {
831
885
  const { authorization } = selectRequirementSignatures(signatures, {
@@ -844,7 +898,7 @@ export class MorphoBlue {
844
898
  borrowShares: requestedShares,
845
899
  minBorrowSharePrice,
846
900
  maxRepaySharePrice,
847
- targetReallocations,
901
+ targetReallocations: targetReallocationList,
848
902
  authorizationSignature: authorization,
849
903
  },
850
904
  metadata: this.client.options.metadata,
@@ -855,13 +909,30 @@ export class MorphoBlue {
855
909
  /**
856
910
  * Fetches all on-chain inputs needed to compute public allocator reallocations.
857
911
  *
858
- * @param params - Reallocation data fetch parameters.
859
912
  * @param params.vaultAddresses - Vaults to inspect for source-market liquidity.
860
- * @param params.block - Block number and timestamp used for consistent RPC reads.
861
- * @returns Reallocation data ready for {@link getReallocations}.
913
+ * @param params.block.number - Block number used for every RPC read.
914
+ * @param params.block.timestamp - Timestamp corresponding to the fetched block.
915
+ * @returns Reallocation data ready for {@link getVaultV1Reallocations}.
862
916
  * @throws {ChainIdMismatchError} when the client chain does not match this market.
917
+ * @example
918
+ * ```ts
919
+ * import { markets, vaults } from "@morpho-org/morpho-test";
920
+ * import { createPublicClient, http } from "viem";
921
+ * import { mainnet } from "viem/chains";
922
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
923
+ * import type { VaultV1ReallocationData } from "@morpho-org/morpho-sdk/entities";
924
+ *
925
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
926
+ * .extend(morphoViemExtension());
927
+ * const market = client.morpho.blue(markets[mainnet.id].usdc_wbtc, mainnet.id);
928
+ * const block = await client.getBlock();
929
+ * const data: VaultV1ReallocationData = await market.getVaultV1ReallocationData({
930
+ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
931
+ * block,
932
+ * });
933
+ * ```
863
934
  */
864
- async getReallocationData({ vaultAddresses, block, }) {
935
+ async getVaultV1ReallocationData({ vaultAddresses, block, }) {
865
936
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
866
937
  const client = this.client.viemClient;
867
938
  const fetchParams = {
@@ -901,7 +972,7 @@ export class MorphoBlue {
901
972
  position,
902
973
  })))),
903
974
  ]);
904
- // Assemble records for ReallocationData.
975
+ // Assemble records for VaultV1ReallocationData.
905
976
  const marketsRecord = {
906
977
  [targetMarketId]: targetMarket,
907
978
  };
@@ -920,7 +991,7 @@ export class MorphoBlue {
920
991
  for (const { vault, mid, position } of positions) {
921
992
  (positionsRecord[vault] ??= {})[mid] = position;
922
993
  }
923
- return new ReallocationData({
994
+ return new VaultV1ReallocationData({
924
995
  chainId: this.chainId,
925
996
  markets: marketsRecord,
926
997
  vaults: vaultsRecord,
@@ -929,13 +1000,109 @@ export class MorphoBlue {
929
1000
  });
930
1001
  }
931
1002
  /**
932
- * Computes public allocator reallocations for a borrow or withdraw on this market.
1003
+ * Fetches Vault V1 PublicAllocator state using the deprecated unversioned name.
1004
+ *
1005
+ * @param params.vaultAddresses - Addresses of MetaMorpho vaults that allocate to this market.
1006
+ * @param params.block.number - Block number used for every RPC read.
1007
+ * @param params.block.timestamp - Timestamp corresponding to the fetched block.
1008
+ * @returns A `VaultV1ReallocationData` snapshot populated from one block.
1009
+ * @throws {ChainIdMismatchError} when the client chain does not match this market.
1010
+ * @deprecated Use {@link getVaultV1ReallocationData} instead.
1011
+ * @example
1012
+ * ```ts
1013
+ * const data = await market.getReallocationData({ vaultAddresses, block });
1014
+ * // Equivalent to market.getVaultV1ReallocationData({ vaultAddresses, block }).
1015
+ * ```
1016
+ */
1017
+ getReallocationData(params) {
1018
+ return this.getVaultV1ReallocationData(params);
1019
+ }
1020
+ /**
1021
+ * Fetches Vault V2 BluePublicAllocator state for this target market.
1022
+ *
1023
+ * Reads the target Morpho Blue market, each Vault V2 accrual tree, and each
1024
+ * vault's BluePublicAllocator permissions and allocation caps at one block.
1025
+ *
1026
+ * @param params.vaultAddresses - Vault V2 addresses to inspect for market or idle liquidity.
1027
+ * @param params.block.number - Block number used for every RPC read.
1028
+ * @param params.block.timestamp - Timestamp corresponding to the fetched block.
1029
+ * @returns A `VaultV2BlueReallocationData` snapshot ready for {@link getVaultV2BlueReallocations}.
1030
+ * @throws {ChainIdMismatchError} when the client chain does not match this market.
1031
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
1032
+ * @throws {UnknownAddressError} when the chain has no BluePublicAllocator deployment.
1033
+ * @throws {UnknownFactory} when the chain has no Vault V2 factory.
1034
+ * @throws {UnknownOfFactory} when a requested address is not a Vault V2 from that factory.
1035
+ * @throws {UnsupportedVaultV2AdapterError} when a vault contains an unsupported adapter.
1036
+ * @throws {viem.BaseError} when an RPC or contract read fails with no fallback left.
1037
+ * @example
1038
+ * ```ts
1039
+ * import { markets } from "@morpho-org/morpho-test";
1040
+ * import { createPublicClient, http } from "viem";
1041
+ * import { mainnet } from "viem/chains";
1042
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
1043
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
1044
+ *
1045
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
1046
+ * .extend(morphoViemExtension());
1047
+ * const market = client.morpho.blue(markets[mainnet.id].usdc_wbtc, mainnet.id);
1048
+ * const block = await client.getBlock();
1049
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
1050
+ * const data: VaultV2BlueReallocationData =
1051
+ * await market.getVaultV2BlueReallocationData({
1052
+ * vaultAddresses: [keyrockUsdcVaultV2],
1053
+ * block,
1054
+ * });
1055
+ * ```
1056
+ */
1057
+ async getVaultV2BlueReallocationData({ vaultAddresses, block, }) {
1058
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
1059
+ const client = this.client.viemClient;
1060
+ const fetchParams = {
1061
+ blockNumber: block.number,
1062
+ chainId: this.chainId,
1063
+ deployless: this.client.options.supportDeployless,
1064
+ };
1065
+ const [targetMarket, vaultEntries] = await Promise.all([
1066
+ fetchMarket(this.marketParams.id, client, fetchParams),
1067
+ Promise.all(vaultAddresses.map(async (address) => {
1068
+ const vault = await fetchAccrualVaultV2(address, client, fetchParams);
1069
+ const publicAllocatorData = await fetchVaultV2BluePublicAllocatorData(vault, client, {
1070
+ ...fetchParams,
1071
+ targetMarketParams: this.marketParams,
1072
+ });
1073
+ return { publicAllocatorData, vault };
1074
+ })),
1075
+ ]);
1076
+ return new VaultV2BlueReallocationData({
1077
+ chainId: this.chainId,
1078
+ markets: { [targetMarket.id]: targetMarket },
1079
+ vaults: Object.fromEntries(vaultEntries.map(({ vault }) => [vault.address, vault])),
1080
+ allocations: Object.fromEntries(vaultEntries.map(({ publicAllocatorData, vault }) => [
1081
+ vault.address,
1082
+ publicAllocatorData.allocations,
1083
+ ])),
1084
+ publicAllocatorConfigs: Object.fromEntries(vaultEntries.map(({ publicAllocatorData, vault }) => [
1085
+ vault.address,
1086
+ publicAllocatorData.publicAllocatorConfig,
1087
+ ])),
1088
+ activeAdapters: Object.fromEntries(vaultEntries.map(({ publicAllocatorData, vault }) => [
1089
+ vault.address,
1090
+ publicAllocatorData.activeAdapters,
1091
+ ])),
1092
+ marketPublicAllocatorConfigs: Object.fromEntries(vaultEntries.map(({ publicAllocatorData, vault }) => [
1093
+ vault.address,
1094
+ publicAllocatorData.marketPublicAllocatorConfigs,
1095
+ ])),
1096
+ });
1097
+ }
1098
+ /**
1099
+ * Computes Vault V1 PublicAllocator reallocations for this market.
933
1100
  *
934
1101
  * Pass `{ borrowAmount }` for a borrow (legacy alias, equivalent to `{ operation: "borrow", amount }`)
935
1102
  * or `{ operation, amount }` for a borrow or loan-asset withdraw.
936
1103
  *
937
1104
  * @param params - Reallocation computation parameters.
938
- * @param params.reallocationData - State returned by {@link getReallocationData}.
1105
+ * @param params.reallocationData - State returned by {@link getVaultV1ReallocationData}.
939
1106
  * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`).
940
1107
  * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
941
1108
  * @param params.borrowAmount - {@deprecated Pass `{ operation: "borrow", amount }` instead.}
@@ -946,13 +1113,21 @@ export class MorphoBlue {
946
1113
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets`.
947
1114
  * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
948
1115
  * @throws {UnknownReallocationMarketError} when the target market is absent from the reallocation data.
1116
+ * @example
1117
+ * ```ts
1118
+ * const reallocations = market.getVaultV1Reallocations({
1119
+ * reallocationData,
1120
+ * operation: "borrow",
1121
+ * amount: 1_000_000n,
1122
+ * });
1123
+ * ```
949
1124
  */
950
- getReallocations(params) {
1125
+ getVaultV1Reallocations(params) {
951
1126
  validateChainId(params.reallocationData.chainId, this.chainId);
952
1127
  const marketId = this.marketParams.id;
953
1128
  const options = { enabled: true, ...params.options };
954
1129
  if (params.borrowAmount !== undefined) {
955
- return computeReallocations({
1130
+ return computeVaultV1Reallocations({
956
1131
  reallocationData: params.reallocationData,
957
1132
  marketId,
958
1133
  operation: "borrow",
@@ -960,7 +1135,7 @@ export class MorphoBlue {
960
1135
  options,
961
1136
  });
962
1137
  }
963
- return computeReallocations({
1138
+ return computeVaultV1Reallocations({
964
1139
  reallocationData: params.reallocationData,
965
1140
  marketId,
966
1141
  operation: params.operation,
@@ -968,4 +1143,62 @@ export class MorphoBlue {
968
1143
  options,
969
1144
  });
970
1145
  }
1146
+ /**
1147
+ * Computes Vault V1 PublicAllocator reallocations using the deprecated unversioned name.
1148
+ *
1149
+ * @param params.reallocationData - State returned by {@link getVaultV1ReallocationData}.
1150
+ * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`).
1151
+ * @param params.amount - The borrow or withdraw amount used to compute post-state utilization.
1152
+ * @param params.borrowAmount - Deprecated borrow amount alias.
1153
+ * @param params.options - Optional allocator and utilization options.
1154
+ * @returns Vault V1 reallocations ready for a Blue action.
1155
+ * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
1156
+ * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation.
1157
+ * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply.
1158
+ * @throws {MissingPublicAllocatorConfigError} when a selected vault lacks allocator state.
1159
+ * @throws {UnknownReallocationMarketError} when the target market is absent.
1160
+ * @deprecated Use {@link getVaultV1Reallocations} instead.
1161
+ * @example
1162
+ * ```ts
1163
+ * const reallocations = market.getReallocations({
1164
+ * reallocationData,
1165
+ * operation: "borrow",
1166
+ * amount: 1_000_000n,
1167
+ * });
1168
+ * ```
1169
+ */
1170
+ getReallocations(params) {
1171
+ return this.getVaultV1Reallocations(params);
1172
+ }
1173
+ /**
1174
+ * Computes Vault V2 BluePublicAllocator reallocations for this market.
1175
+ *
1176
+ * @param params.reallocationData - State returned by {@link getVaultV2BlueReallocationData}.
1177
+ * @param params.options - Optional allocator discovery controls and operation to support.
1178
+ * @returns Action-ready reallocations and their post-simulation state.
1179
+ * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
1180
+ * @throws {NegativeInputError} when a utilization or penalty limit is negative.
1181
+ * @throws {InputExceedsMaxError} when a utilization or penalty limit exceeds WAD.
1182
+ * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
1183
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
1184
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
1185
+ * @throws {UnknownReallocationPublicAllocatorConfigError} when allocator authorization state is absent.
1186
+ * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent.
1187
+ * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
1188
+ * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
1189
+ * @throws {ReallocationAllocationUnderflowError} when an inconsistent allocation snapshot underflows during the final transition.
1190
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the shortfall.
1191
+ * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply.
1192
+ * @example
1193
+ * ```ts
1194
+ * const result = market.getVaultV2BlueReallocations({
1195
+ * reallocationData,
1196
+ * options: { operation: { type: "borrow", amount: 1_000_000n } },
1197
+ * });
1198
+ * ```
1199
+ */
1200
+ getVaultV2BlueReallocations({ reallocationData, options, }) {
1201
+ validateChainId(reallocationData.chainId, this.chainId);
1202
+ return reallocationData.computeVaultV2BlueReallocations(this.marketParams.id, options);
1203
+ }
971
1204
  }
@@ -2,6 +2,7 @@ export type { IAccrualPosition, IAccrualVault, IAccrualVaultV2, IAccrualVaultV2A
2
2
  export { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market, MarketParams, Position, PreLiquidationParams, PreLiquidationPosition, Token, User, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultMarketPublicAllocatorConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
3
3
  export { MorphoBlue } from "./blue/index.js";
4
4
  export * from "./midnight/index.js";
5
- export { type InputReallocationData, ReallocationData, } from "./reallocationData.js";
6
5
  export { MorphoVaultV1 } from "./vaultV1/index.js";
6
+ export { type InputReallocationData, type InputVaultV1ReallocationData, ReallocationData, VaultV1ReallocationData, } from "./vaultV1ReallocationData.js";
7
7
  export { MorphoVaultV2 } from "./vaultV2/index.js";
8
+ export { type InputVaultV2BlueReallocationData, VaultV2BlueReallocationData, } from "./vaultV2BlueReallocationData.js";
@@ -1,6 +1,7 @@
1
1
  export { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market, MarketParams, Position, PreLiquidationParams, PreLiquidationPosition, Token, User, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultMarketPublicAllocatorConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
2
2
  export { MorphoBlue } from "./blue/index.js";
3
3
  export * from "./midnight/index.js";
4
- export { ReallocationData, } from "./reallocationData.js";
5
4
  export { MorphoVaultV1 } from "./vaultV1/index.js";
5
+ export { ReallocationData, VaultV1ReallocationData, } from "./vaultV1ReallocationData.js";
6
6
  export { MorphoVaultV2 } from "./vaultV2/index.js";
7
+ export { VaultV2BlueReallocationData, } from "./vaultV2BlueReallocationData.js";