@morpho-org/morpho-sdk 5.9.0 → 5.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +6 -0
  2. package/lib/cjs/abis.d.ts +17 -2
  3. package/lib/cjs/abis.js +14 -1
  4. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +2 -2
  5. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +2 -2
  6. package/lib/cjs/actions/midnight/takeBorrow.d.ts +2 -2
  7. package/lib/cjs/actions/midnight/takeBorrow.js +2 -2
  8. package/lib/cjs/actions/midnight/takeLend.d.ts +2 -2
  9. package/lib/cjs/actions/midnight/takeLend.js +2 -2
  10. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +4 -1
  11. package/lib/cjs/blue/abis.d.ts +5 -1
  12. package/lib/cjs/blue/abis.js +2 -0
  13. package/lib/cjs/blue/entities.d.ts +8 -2
  14. package/lib/cjs/blue/entities.js +1 -0
  15. package/lib/cjs/blue/errors.d.ts +1 -1
  16. package/lib/cjs/blue/errors.js +2 -1
  17. package/lib/cjs/blue/fetch.d.ts +3 -1
  18. package/lib/cjs/blue/fetch.js +1 -0
  19. package/lib/cjs/entities/blue/blue.d.ts +10 -0
  20. package/lib/cjs/entities/blue/blue.js +9 -2
  21. package/lib/cjs/entities/index.d.ts +8 -2
  22. package/lib/cjs/entities/index.js +1 -0
  23. package/lib/cjs/entities/midnight/midnight.d.ts +2 -2
  24. package/lib/cjs/entities/midnight/midnight.js +5 -13
  25. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +71 -12
  26. package/lib/cjs/entities/vaultV1/vaultV1.js +9 -2
  27. package/lib/cjs/entities/vaultV1ReallocationData.d.ts +6 -0
  28. package/lib/cjs/entities/vaultV1ReallocationData.js +20 -5
  29. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +2 -0
  30. package/lib/cjs/entities/vaultV2/vaultV2.js +3 -1
  31. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +8 -1
  32. package/lib/cjs/entities/vaultV2BlueReallocationData.js +46 -13
  33. package/lib/cjs/errors.d.ts +1 -1
  34. package/lib/cjs/errors.js +3 -2
  35. package/lib/cjs/fetch.d.ts +3 -1
  36. package/lib/cjs/fetch.js +1 -0
  37. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +2 -0
  38. package/lib/cjs/helpers/computeVaultV1Reallocations.js +2 -0
  39. package/lib/cjs/helpers/metadata.d.ts +3 -5
  40. package/lib/cjs/helpers/metadata.js +4 -6
  41. package/lib/cjs/helpers/previewVaultV2InKindRedeem.d.ts +1 -0
  42. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +2 -0
  43. package/lib/cjs/helpers/validate.d.ts +30 -8
  44. package/lib/cjs/helpers/validate.js +30 -8
  45. package/lib/cjs/types/action.d.ts +57 -4
  46. package/lib/cjs/types/error.d.ts +1 -1
  47. package/lib/cjs/types/error.js +2 -2
  48. package/lib/cjs/types/sharedLiquidity.d.ts +2 -2
  49. package/lib/esm/abis.d.ts +17 -2
  50. package/lib/esm/abis.js +17 -2
  51. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +2 -2
  52. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +2 -2
  53. package/lib/esm/actions/midnight/takeBorrow.d.ts +2 -2
  54. package/lib/esm/actions/midnight/takeBorrow.js +2 -2
  55. package/lib/esm/actions/midnight/takeLend.d.ts +2 -2
  56. package/lib/esm/actions/midnight/takeLend.js +2 -2
  57. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +4 -1
  58. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +3 -1
  59. package/lib/esm/blue/abis.d.ts +5 -1
  60. package/lib/esm/blue/abis.js +5 -1
  61. package/lib/esm/blue/entities.d.ts +8 -2
  62. package/lib/esm/blue/entities.js +3 -1
  63. package/lib/esm/blue/errors.d.ts +1 -1
  64. package/lib/esm/blue/errors.js +1 -1
  65. package/lib/esm/blue/fetch.d.ts +3 -1
  66. package/lib/esm/blue/fetch.js +3 -1
  67. package/lib/esm/entities/blue/blue.d.ts +10 -0
  68. package/lib/esm/entities/blue/blue.js +9 -2
  69. package/lib/esm/entities/index.d.ts +8 -2
  70. package/lib/esm/entities/index.js +3 -1
  71. package/lib/esm/entities/midnight/midnight.d.ts +2 -2
  72. package/lib/esm/entities/midnight/midnight.js +5 -13
  73. package/lib/esm/entities/vaultV1/vaultV1.d.ts +71 -12
  74. package/lib/esm/entities/vaultV1/vaultV1.js +9 -2
  75. package/lib/esm/entities/vaultV1ReallocationData.d.ts +6 -0
  76. package/lib/esm/entities/vaultV1ReallocationData.js +20 -5
  77. package/lib/esm/entities/vaultV2/vaultV2.d.ts +2 -0
  78. package/lib/esm/entities/vaultV2/vaultV2.js +3 -1
  79. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +8 -1
  80. package/lib/esm/entities/vaultV2BlueReallocationData.js +46 -13
  81. package/lib/esm/errors.d.ts +1 -1
  82. package/lib/esm/errors.js +1 -1
  83. package/lib/esm/fetch.d.ts +3 -1
  84. package/lib/esm/fetch.js +3 -1
  85. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +2 -0
  86. package/lib/esm/helpers/computeVaultV1Reallocations.js +2 -0
  87. package/lib/esm/helpers/metadata.d.ts +3 -5
  88. package/lib/esm/helpers/metadata.js +4 -6
  89. package/lib/esm/helpers/previewVaultV2InKindRedeem.d.ts +1 -0
  90. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +2 -0
  91. package/lib/esm/helpers/validate.d.ts +30 -8
  92. package/lib/esm/helpers/validate.js +30 -8
  93. package/lib/esm/types/action.d.ts +57 -4
  94. package/lib/esm/types/error.d.ts +1 -1
  95. package/lib/esm/types/error.js +2 -2
  96. package/lib/esm/types/sharedLiquidity.d.ts +2 -2
  97. package/package.json +8 -8
@@ -104,7 +104,11 @@ const cloneAdapter = (adapter, markets) => {
104
104
  if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter)
105
105
  return new AccrualVaultV2MorphoMarketV1Adapter({ ...base, marketParamsList: [...adapter.marketParamsList] }, adapter.positions.map((position) => clonePosition(position, markets)));
106
106
  if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter)
107
- return new AccrualVaultV2MorphoVaultV1Adapter({ ...base, morphoVaultV1: adapter.morphoVaultV1 }, cloneAccrualVault(adapter.accrualVaultV1, markets), adapter.shares);
107
+ return new AccrualVaultV2MorphoVaultV1Adapter({
108
+ ...base,
109
+ morphoVaultV1: adapter.morphoVaultV1,
110
+ parentAllocation: adapter.parentAllocation,
111
+ }, cloneAccrualVault(adapter.accrualVaultV1, markets), adapter.shares);
108
112
  throw new UnsupportedVaultV2AdapterError(adapter.address);
109
113
  };
110
114
  const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
@@ -568,7 +572,11 @@ export class VaultV2BlueReallocationData {
568
572
  * utilization defaults to 90% and is configurable through
569
573
  * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
570
574
  * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
571
- * considered.
575
+ * considered. Targets with no remaining supply or allocator capacity are skipped before
576
+ * projecting source interest. The adapter's minimum share minting requirement, supply-share
577
+ * limits, and target absolute or zero relative caps are checked against a one-asset deposit.
578
+ * Shared cap IDs that a source withdrawal can reduce remain eligible, as do deposits whose
579
+ * allocation does not increase after rounding.
572
580
  *
573
581
  * Shared-cap discovery is conservative. Operation planning searches at most
574
582
  * 1,024 base units above its targeted amount for the nearest executable fit.
@@ -579,6 +587,7 @@ export class VaultV2BlueReallocationData {
579
587
  * @param marketId - Target Blue market id.
580
588
  * @param options - Optional discovery controls and operation to support.
581
589
  * @returns Flat action-ready reallocations and their post-simulation state.
590
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
582
591
  * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
583
592
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
584
593
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
@@ -719,9 +728,7 @@ export class VaultV2BlueReallocationData {
719
728
  : BigInt(options.timestamp);
720
729
  let data = this;
721
730
  let simulationContext = context;
722
- data.setMarkets(Object.values(data.markets)
723
- .filter((market) => market != null)
724
- .map((market) => market.accrueInterest(timestamp)));
731
+ data.setMarkets([data.getMarket(marketId).accrueInterest(timestamp)]);
725
732
  const reallocations = [];
726
733
  const configuredVaults = Object.keys(data.vaults);
727
734
  const vaultKeyByLower = new Map(configuredVaults.map((vault) => [vault.toLowerCase(), vault]));
@@ -756,6 +763,7 @@ export class VaultV2BlueReallocationData {
756
763
  activeAdaptersCache.set(vaultAddress, activeAdapters);
757
764
  }
758
765
  const targetSupplyHeadroom = MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
766
+ const minimumSupply = targetMarket.supply(1n, 0n);
759
767
  const rawCandidates = [];
760
768
  // Missing nested allocator state means the snapshot is incomplete, so
761
769
  // typed getter errors below must propagate. Only explicit zero caps or
@@ -777,17 +785,35 @@ export class VaultV2BlueReallocationData {
777
785
  const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
778
786
  const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
779
787
  const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
780
- if ([
788
+ const targetAllocations = [
781
789
  adapterCapAllocation,
782
790
  collateralCapAllocation,
783
791
  adapterMarketCapAllocation,
784
- ].some(({ absoluteCap }) => absoluteCap === 0n))
792
+ ];
793
+ if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n))
785
794
  continue;
786
795
  const expectedSupplyAssets = targetMarket.toSupplyAssets(adapter.supplyShares[marketId] ?? 0n);
787
796
  const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
788
797
  const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation + untracked);
798
+ const minimumAllocation = minimumSupply.market.toSupplyAssets((adapter.supplyShares[marketId] ?? 0n) + minimumSupply.shares);
799
+ const minimumAllocationChange = minimumAllocation - adapterMarketCapAllocation.allocation;
800
+ const blockedTargetIds = targetAllocations
801
+ .filter(({ allocation, absoluteCap, relativeCap }) => {
802
+ const nextAllocation = allocation + minimumAllocationChange;
803
+ return (nextAllocation > absoluteCap ||
804
+ (relativeCap === 0n && nextAllocation > 0n));
805
+ })
806
+ .map(({ id }) => id);
807
+ // MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
808
+ if (targetSupplyHeadroom === 0n ||
809
+ allocatorHeadroom === 0n ||
810
+ minimumSupply.shares < minimumSupply.assets ||
811
+ minimumSupply.market.totalSupplyShares > MathLib.MAX_UINT_128 ||
812
+ blockedTargetIds.includes(adapterMarketCapId))
813
+ continue;
789
814
  if (publicAllocatorConfig.canPullFromIdle &&
790
- availableIdleAssets > 0n) {
815
+ availableIdleAssets > 0n &&
816
+ blockedTargetIds.length === 0) {
791
817
  const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
792
818
  if (assets > 0n) {
793
819
  rawCandidates.push({
@@ -823,8 +849,16 @@ export class VaultV2BlueReallocationData {
823
849
  const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
824
850
  if (sourceAllocations.some(({ allocation }) => allocation === 0n))
825
851
  continue;
826
- const expectedSourceSupplyAssets = sourceMarket.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n);
827
- const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, sourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
852
+ const sourceSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
853
+ if (sourceSupplyShares === 0n)
854
+ continue;
855
+ // A withdrawal can create target headroom only for shared cap IDs.
856
+ if (blockedTargetIds.some((id) => !sourceIds.includes(id)))
857
+ continue;
858
+ const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
859
+ data.setMarkets([accruedSourceMarket]);
860
+ const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
861
+ const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, accruedSourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
828
862
  if (assets <= 0n)
829
863
  continue;
830
864
  rawCandidates.push({
@@ -845,9 +879,6 @@ export class VaultV2BlueReallocationData {
845
879
  for (const reallocation of rawCandidates) {
846
880
  let lower = 0n;
847
881
  let upper = reallocation.assets;
848
- // MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
849
- if (targetMarket.toSupplyShares(upper, "Down") < upper)
850
- continue;
851
882
  const reallocationAdapter = data.getAdapter(reallocation.vault, reallocation.to.adapter);
852
883
  const targetIds = getAdapterIds(adapterIdsCache, reallocationAdapter, targetMarket);
853
884
  const sourceIds = new Set();
@@ -951,6 +982,7 @@ export class VaultV2BlueReallocationData {
951
982
  * @param marketId - Target Blue market id.
952
983
  * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
953
984
  * @returns Reallocatable market and idle assets, or `0n` when none are available; rounding-only shared-cap fits may be conservatively omitted.
985
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
954
986
  * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
955
987
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
956
988
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -1003,6 +1035,7 @@ export class VaultV2BlueReallocationData {
1003
1035
  * @param utilization - Desired utilization, scaled by WAD. Defaults to 90%.
1004
1036
  * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
1005
1037
  * @returns Borrowable assets while remaining at or below `utilization`; rounding-only shared-cap fits may be conservatively omitted.
1038
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
1006
1039
  * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
1007
1040
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
1008
1041
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -14,7 +14,7 @@ UnknownTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError,
14
14
  /** @deprecated Use UnknownBlueTokenPriceError or the raw protocol subpath. */
15
15
  UnknownTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError,
16
16
  /** @deprecated Use UnknownBlueVaultConfigError or the raw protocol subpath. */
17
- UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError,
17
+ UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError, UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError,
18
18
  /** @deprecated Use UnsupportedBluePreLiquidationParamsError or the raw protocol subpath. */
19
19
  UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError,
20
20
  /** @deprecated Use UnsupportedBlueVaultV2AdapterError or the raw protocol subpath. */
package/lib/esm/errors.js CHANGED
@@ -14,7 +14,7 @@ UnknownTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError,
14
14
  /** @deprecated Use UnknownBlueTokenPriceError or the raw protocol subpath. */
15
15
  UnknownTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError,
16
16
  /** @deprecated Use UnknownBlueVaultConfigError or the raw protocol subpath. */
17
- UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError,
17
+ UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError, UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError,
18
18
  /** @deprecated Use UnsupportedBluePreLiquidationParamsError or the raw protocol subpath. */
19
19
  UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError,
20
20
  /** @deprecated Use UnsupportedBlueVaultV2AdapterError or the raw protocol subpath. */
@@ -12,5 +12,7 @@ fetchPreLiquidationParams, fetchPreLiquidationPosition as fetchBluePreLiquidatio
12
12
  /** @deprecated Use `fetchBluePreLiquidationPosition` or the raw `/blue/fetch` subpath. */
13
13
  fetchPreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser,
14
14
  /** @deprecated Use `fetchBlueUser` or the raw `/blue/fetch` subpath. */
15
- fetchUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultMarketPublicAllocatorConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
15
+ fetchUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig,
16
+ /** @deprecated Vault V1 PublicAllocator support will be removed in the next major. Use `fetchVaultV2BlueMarketPublicAllocatorConfig`. */
17
+ fetchVaultMarketPublicAllocatorConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
16
18
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";
package/lib/esm/fetch.js CHANGED
@@ -12,5 +12,7 @@ fetchPreLiquidationParams, fetchPreLiquidationPosition as fetchBluePreLiquidatio
12
12
  /** @deprecated Use `fetchBluePreLiquidationPosition` or the raw `/blue/fetch` subpath. */
13
13
  fetchPreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser,
14
14
  /** @deprecated Use `fetchBlueUser` or the raw `/blue/fetch` subpath. */
15
- fetchUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultMarketPublicAllocatorConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
15
+ fetchUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig,
16
+ /** @deprecated Vault V1 PublicAllocator support will be removed in the next major. Use `fetchVaultV2BlueMarketPublicAllocatorConfig`. */
17
+ fetchVaultMarketPublicAllocatorConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
16
18
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";
@@ -22,6 +22,7 @@ import { type ReallocationComputeOptions, type VaultV1Reallocation } from "../ty
22
22
  * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
23
23
  * @param params.options - Optional reallocation computation options.
24
24
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
25
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
25
26
  * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market — preventing fee-bearing reallocations from being attached to a call that would still revert onchain.
26
27
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets` — the on-chain call would revert regardless of reallocations.
27
28
  * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
@@ -78,6 +79,7 @@ export declare const computeVaultV1Reallocations: ({ reallocationData: data, mar
78
79
  /**
79
80
  * Deprecated name for the Vault V1 amount-aware reallocation planner.
80
81
  *
82
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
81
83
  * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
82
84
  * `VaultV2BlueReallocationData.computeVaultV2BlueReallocations`.
83
85
  */
@@ -75,6 +75,7 @@ const capVaultWithdrawals = (withdrawals, assets) => {
75
75
  * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
76
76
  * @param params.options - Optional reallocation computation options.
77
77
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
78
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
78
79
  * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market — preventing fee-bearing reallocations from being attached to a call that would still revert onchain.
79
80
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets` — the on-chain call would revert regardless of reallocations.
80
81
  * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
@@ -239,6 +240,7 @@ export const computeVaultV1Reallocations = ({ reallocationData: data, marketId,
239
240
  /**
240
241
  * Deprecated name for the Vault V1 amount-aware reallocation planner.
241
242
  *
243
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
242
244
  * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
243
245
  * `VaultV2BlueReallocationData.computeVaultV2BlueReallocations`.
244
246
  */
@@ -26,11 +26,9 @@ import type { Metadata } from "../types/index.js";
26
26
  * @param {Metadata} metadata - An object containing optional metadata fields
27
27
  * such as `timestamp` and `origin`.
28
28
  *
29
- * @returns {Object} - A new transaction object with the modified `data` field
30
- * including the concatenated metadata.
31
- *
32
- * If no `data` is present in the original transaction, the function returns
33
- * the transaction unmodified.
29
+ * @returns The same `tx` object when `data` is missing, an empty string, or
30
+ * canonical empty calldata (`"0x"`); otherwise, a new transaction object
31
+ * with `data` containing any appended metadata. The input is never mutated.
34
32
  */
35
33
  export declare function addTransactionMetadata(tx: {
36
34
  data: Hex;
@@ -26,15 +26,13 @@ import { concatHex, isHex, numberToHex } from "viem";
26
26
  * @param {Metadata} metadata - An object containing optional metadata fields
27
27
  * such as `timestamp` and `origin`.
28
28
  *
29
- * @returns {Object} - A new transaction object with the modified `data` field
30
- * including the concatenated metadata.
31
- *
32
- * If no `data` is present in the original transaction, the function returns
33
- * the transaction unmodified.
29
+ * @returns The same `tx` object when `data` is missing, an empty string, or
30
+ * canonical empty calldata (`"0x"`); otherwise, a new transaction object
31
+ * with `data` containing any appended metadata. The input is never mutated.
34
32
  */
35
33
  export function addTransactionMetadata(tx, metadata) {
36
34
  const { data, ..._tx } = tx;
37
- if (!data)
35
+ if (!data || data === "0x")
38
36
  return tx;
39
37
  const concatItems = [data];
40
38
  if (metadata.timestamp) {
@@ -35,6 +35,7 @@ export interface VaultV2InKindRedeemMarketPreview {
35
35
  * @param params.requestedExitAssets - Positive penalty-inclusive amount the user wants to exit.
36
36
  * @param params.timestamp - Timestamp used to accrue Morpho Blue markets before calculating capacity.
37
37
  * @returns Frontend-ready market choices, or an empty list when no choices are available.
38
+ * @throws {UnsupportedBlueMarketIrmError} when an adapter-listed market with positive debt uses an unsupported IRM.
38
39
  * @example
39
40
  * ```ts
40
41
  * import { previewVaultV2InKindRedeem } from "@morpho-org/morpho-sdk";
@@ -11,6 +11,7 @@ import { AccrualVaultV2MorphoMarketV1AdapterV2, MathLib, } from "@morpho-org/blu
11
11
  * @param params.requestedExitAssets - Positive penalty-inclusive amount the user wants to exit.
12
12
  * @param params.timestamp - Timestamp used to accrue Morpho Blue markets before calculating capacity.
13
13
  * @returns Frontend-ready market choices, or an empty list when no choices are available.
14
+ * @throws {UnsupportedBlueMarketIrmError} when an adapter-listed market with positive debt uses an unsupported IRM.
14
15
  * @example
15
16
  * ```ts
16
17
  * import { previewVaultV2InKindRedeem } from "@morpho-org/morpho-sdk";
@@ -37,6 +38,7 @@ export function previewVaultV2InKindRedeem(vaultData, params) {
37
38
  const penalty = vaultData.forceDeallocatePenalties[adapter.address] ?? 0n;
38
39
  const availableIdleAssets = vaultData.assetBalance;
39
40
  const allocations = adapter.markets
41
+ .filter((market) => (adapter.supplyShares[market.id] ?? 0n) !== 0n)
40
42
  .map((market) => ({
41
43
  market,
42
44
  allocationAssets: market
@@ -23,22 +23,44 @@ export declare const validateMidnightMarketChainId: (market: MidnightMarketInput
23
23
  * Asserts that the client has a connected account AND that it matches
24
24
  * the provided user address.
25
25
  *
26
- * Used internally by the signature requirements (`encodeErc20Permit`,
27
- * `encodeErc20Permit2Approve`) to enforce builder = signer at `sign()` time:
28
- * the signing flow is the only path where an account/address mismatch
29
- * is a real security concern (rather than just an integrator footgun).
26
+ * Used at `sign()` time by the shared `signAndVerifyTypedData` helper (which
27
+ * backs the permit, Permit2, Blue authorization, and Midnight offer-root
28
+ * signature flows) and by `encodeVaultSharesPermit`, to enforce builder =
29
+ * signer: the signing flow is
30
+ * the only path where an account/address mismatch is a real security concern
31
+ * (rather than just an integrator footgun).
30
32
  *
31
33
  * Transaction builders no longer call this helper — callers are
32
34
  * responsible for keeping `userAddress` aligned with the signing account
33
35
  * at the builder layer.
34
36
  *
35
- * Throws {@link MissingClientPropertyError} if the client has no account.
36
- * Throws {@link AddressMismatchError} if the client account differs from
37
- * `userAddress`.
38
- *
39
37
  * @param clientAccountAddress - The client's account address; if undefined,
40
38
  * `MissingClientPropertyError` is thrown.
41
39
  * @param userAddress - The user address provided by the caller.
40
+ * @returns Nothing; narrows `clientAccountAddress` to a defined `Address` when
41
+ * it is present and equal to `userAddress`.
42
+ * @throws {MissingClientPropertyError} when the client has no connected account.
43
+ * @throws {AddressMismatchError} when the client account differs from
44
+ * `userAddress`.
45
+ * @example
46
+ * ```ts
47
+ * import { createWalletClient, http } from "viem";
48
+ * import { privateKeyToAccount } from "viem/accounts";
49
+ * import { mainnet } from "viem/chains";
50
+ * import { validateUserAddress } from "@morpho-org/morpho-sdk";
51
+ *
52
+ * const account = privateKeyToAccount("0x...");
53
+ * const walletClient = createWalletClient({
54
+ * account,
55
+ * chain: mainnet,
56
+ * transport: http(),
57
+ * });
58
+ *
59
+ * // Inside a `sign()` flow, before producing a typed-data signature:
60
+ * validateUserAddress(walletClient.account?.address, account.address);
61
+ * // Passes when the connected account equals the expected signer;
62
+ * // throws if the wallet has no account or signs for a different address.
63
+ * ```
42
64
  */
43
65
  export declare function validateUserAddress(clientAccountAddress: Address | undefined, userAddress: Address): asserts clientAccountAddress is Address;
44
66
  /**
@@ -35,22 +35,44 @@ export const validateMidnightMarketChainId = (market, chainId) => {
35
35
  * Asserts that the client has a connected account AND that it matches
36
36
  * the provided user address.
37
37
  *
38
- * Used internally by the signature requirements (`encodeErc20Permit`,
39
- * `encodeErc20Permit2Approve`) to enforce builder = signer at `sign()` time:
40
- * the signing flow is the only path where an account/address mismatch
41
- * is a real security concern (rather than just an integrator footgun).
38
+ * Used at `sign()` time by the shared `signAndVerifyTypedData` helper (which
39
+ * backs the permit, Permit2, Blue authorization, and Midnight offer-root
40
+ * signature flows) and by `encodeVaultSharesPermit`, to enforce builder =
41
+ * signer: the signing flow is
42
+ * the only path where an account/address mismatch is a real security concern
43
+ * (rather than just an integrator footgun).
42
44
  *
43
45
  * Transaction builders no longer call this helper — callers are
44
46
  * responsible for keeping `userAddress` aligned with the signing account
45
47
  * at the builder layer.
46
48
  *
47
- * Throws {@link MissingClientPropertyError} if the client has no account.
48
- * Throws {@link AddressMismatchError} if the client account differs from
49
- * `userAddress`.
50
- *
51
49
  * @param clientAccountAddress - The client's account address; if undefined,
52
50
  * `MissingClientPropertyError` is thrown.
53
51
  * @param userAddress - The user address provided by the caller.
52
+ * @returns Nothing; narrows `clientAccountAddress` to a defined `Address` when
53
+ * it is present and equal to `userAddress`.
54
+ * @throws {MissingClientPropertyError} when the client has no connected account.
55
+ * @throws {AddressMismatchError} when the client account differs from
56
+ * `userAddress`.
57
+ * @example
58
+ * ```ts
59
+ * import { createWalletClient, http } from "viem";
60
+ * import { privateKeyToAccount } from "viem/accounts";
61
+ * import { mainnet } from "viem/chains";
62
+ * import { validateUserAddress } from "@morpho-org/morpho-sdk";
63
+ *
64
+ * const account = privateKeyToAccount("0x...");
65
+ * const walletClient = createWalletClient({
66
+ * account,
67
+ * chain: mainnet,
68
+ * transport: http(),
69
+ * });
70
+ *
71
+ * // Inside a `sign()` flow, before producing a typed-data signature:
72
+ * validateUserAddress(walletClient.account?.address, account.address);
73
+ * // Passes when the connected account equals the expected signer;
74
+ * // throws if the wallet has no account or signs for a different address.
75
+ * ```
54
76
  */
55
77
  export function validateUserAddress(clientAccountAddress, userAddress) {
56
78
  if (clientAccountAddress === undefined) {
@@ -1,6 +1,17 @@
1
1
  import type { InputMarketParams } from "@morpho-org/blue-sdk";
2
2
  import type { Address, Hex, WalletClient } from "viem";
3
3
  import type { Deallocation } from "./deallocation.js";
4
+ /**
5
+ * Serves as the common discriminated action-metadata base shared by both
6
+ * {@link TransactionAction} (actions that carry encoded calldata) and
7
+ * {@link SignatureRequirementAction} (signature requirements whose metadata is
8
+ * exposed before any calldata exists). Each concrete action narrows
9
+ * {@link BaseAction} on its literal `type` tag and carries an
10
+ * operation-specific `args` record surfaced for tracing.
11
+ *
12
+ * @typeParam TType - Literal discriminator identifying the action.
13
+ * @typeParam TArgs - The action's argument record.
14
+ */
4
15
  export interface BaseAction<TType extends string = string, TArgs extends Record<string, unknown> = Record<string, unknown>> {
5
16
  readonly type: TType;
6
17
  readonly args: TArgs;
@@ -115,7 +126,11 @@ export interface BlueWithdrawAction extends BaseAction<"blueWithdraw", {
115
126
  shares: bigint;
116
127
  receiver: Address;
117
128
  minSharePrice: bigint;
118
- /** Native-token fees paid to PublicAllocator V1. */
129
+ /**
130
+ * Native-token fees paid to PublicAllocator V1.
131
+ * @deprecated Vault V1 PublicAllocator support will be removed in the next major.
132
+ * Vault V2 loan-token penalties are reported in `reallocationPenaltyAssets`.
133
+ */
119
134
  reallocationFee: bigint;
120
135
  /** Loan-token assets donated as BluePublicAllocator V2 penalties. */
121
136
  readonly reallocationPenaltyAssets: bigint;
@@ -133,7 +148,11 @@ export interface BlueBorrowAction extends BaseAction<"blueBorrow", {
133
148
  amount: bigint;
134
149
  receiver: Address;
135
150
  minSharePrice: bigint;
136
- /** Native-token fees paid to PublicAllocator V1. */
151
+ /**
152
+ * Native-token fees paid to PublicAllocator V1.
153
+ * @deprecated Vault V1 PublicAllocator support will be removed in the next major.
154
+ * Vault V2 loan-token penalties are reported in `reallocationPenaltyAssets`.
155
+ */
137
156
  reallocationFee: bigint;
138
157
  /** Loan-token assets donated as BluePublicAllocator V2 penalties. */
139
158
  readonly reallocationPenaltyAssets: bigint;
@@ -147,7 +166,11 @@ export interface BlueSupplyCollateralBorrowAction extends BaseAction<"blueSupply
147
166
  onBehalf: Address;
148
167
  receiver: Address;
149
168
  nativeAmount?: bigint;
150
- /** Native-token fees paid to PublicAllocator V1. */
169
+ /**
170
+ * Native-token fees paid to PublicAllocator V1.
171
+ * @deprecated Vault V1 PublicAllocator support will be removed in the next major.
172
+ * Vault V2 loan-token penalties are reported in `reallocationPenaltyAssets`.
173
+ */
151
174
  reallocationFee: bigint;
152
175
  /** Loan-token assets donated as BluePublicAllocator V2 penalties. */
153
176
  readonly reallocationPenaltyAssets: bigint;
@@ -194,7 +217,11 @@ export interface BlueRefinanceAction extends BaseAction<"blueRefinance", {
194
217
  readonly minBorrowSharePrice: bigint;
195
218
  readonly maxRepaySharePrice: bigint;
196
219
  readonly user: Address;
197
- /** Native-token fees paid to PublicAllocator V1. */
220
+ /**
221
+ * Native-token fees paid to PublicAllocator V1.
222
+ * @deprecated Vault V1 PublicAllocator support will be removed in the next major.
223
+ * Vault V2 loan-token penalties are reported in `reallocationPenaltyAssets`.
224
+ */
198
225
  readonly reallocationFee: bigint;
199
226
  /** Loan-token assets donated as BluePublicAllocator V2 penalties. */
200
227
  readonly reallocationPenaltyAssets: bigint;
@@ -358,7 +385,19 @@ export interface MidnightCancelOfferAction extends BaseAction<"midnightCancelOff
358
385
  readonly onBehalf: Address;
359
386
  }> {
360
387
  }
388
+ /**
389
+ * Enumerates every action a {@link Transaction} can describe across the VaultV1,
390
+ * VaultV2, Blue, and Midnight flows. The `type` tag discriminates the union so
391
+ * consumers can `switch` exhaustively on it.
392
+ */
361
393
  export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2InKindRedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1InKindRedeemAction | VaultV1MigrateToV2Action | BlueSupplyAction | BlueWithdrawAction | BlueSupplyCollateralAction | BlueBorrowAction | BlueSupplyCollateralBorrowAction | BlueRepayAction | BlueWithdrawCollateralAction | BlueRepayWithdrawCollateralAction | BlueRefinanceAction | BlueAuthorizationAction | MidnightAuthorizationAction | SetterRatifierRatifyRootAction | MidnightTakeLendAction | MidnightTakeBorrowAction | MidnightSupplyCollateralTakeBorrowAction | MidnightSupplyCollateralAction | MempoolSubmitOffersAction | MidnightRedeemAction | MidnightRepayWithdrawCollateralAction | MidnightCancelOfferAction;
394
+ /**
395
+ * Describes a single, immutable, deep-frozen transaction to submit on-chain:
396
+ * the target `to`, native `value`, encoded call `data`, and the originating
397
+ * {@link BaseAction} for tracing. Every action builder returns one.
398
+ *
399
+ * @typeParam TAction - The action that produced this transaction.
400
+ */
362
401
  export interface Transaction<TAction extends BaseAction = TransactionAction> {
363
402
  readonly to: Address;
364
403
  readonly value: bigint;
@@ -379,6 +418,14 @@ export type DepositAmountArgs = {
379
418
  nativeAmount: bigint;
380
419
  amount?: bigint;
381
420
  };
421
+ /**
422
+ * Holds the pre-resolved arguments for an ERC-2612 `permit`: the signed approval
423
+ * of `amount` of `asset` from `owner` to the permitted spender, bounded by the
424
+ * `deadline` timestamp and consuming the given `nonce`. The spender is the
425
+ * GeneralAdapter1/Bundler3 periphery for bundler permits, or the standalone
426
+ * `VaultExitBundlesV1` contract for an in-kind vault redemption permit produced
427
+ * by `encodeVaultSharesPermit`.
428
+ */
382
429
  export interface PermitArgs {
383
430
  owner: Address;
384
431
  nonce: bigint;
@@ -387,6 +434,12 @@ export interface PermitArgs {
387
434
  amount: bigint;
388
435
  deadline: bigint;
389
436
  }
437
+ /**
438
+ * Holds the pre-resolved arguments for a Permit2 `permit` bundler call. It
439
+ * mirrors {@link PermitArgs} but adds the Permit2 allowance `expiration` (when
440
+ * the on-chain allowance lapses) alongside the signature `deadline` (by when the
441
+ * signature must be submitted).
442
+ */
390
443
  export interface Permit2Args {
391
444
  owner: Address;
392
445
  nonce: bigint;
@@ -971,7 +971,7 @@ export declare class MidnightOfferRootOfferCountMismatchError extends Error {
971
971
  actualOffers: number;
972
972
  });
973
973
  }
974
- /** Thrown when a Midnight offer-root signature was not prepared by this maker flow. */
974
+ /** Thrown when a Midnight offer-root signature carries no encoded payload. */
975
975
  export declare class UnpreparedMidnightOfferRootSignatureError extends Error {
976
976
  constructor();
977
977
  }
@@ -1057,10 +1057,10 @@ export class MidnightOfferRootOfferCountMismatchError extends Error {
1057
1057
  super(`Midnight offer root offer-count mismatch: expected "${params.expectedOffers}", got "${params.actualOffers}". Rebuild the flow and sign again.`);
1058
1058
  }
1059
1059
  }
1060
- /** Thrown when a Midnight offer-root signature was not prepared by this maker flow. */
1060
+ /** Thrown when a Midnight offer-root signature carries no encoded payload. */
1061
1061
  export class UnpreparedMidnightOfferRootSignatureError extends Error {
1062
1062
  constructor() {
1063
- super("Midnight offer root signature was not prepared for this offer tree. Sign this flow's offer-root requirement before building the submit transaction.");
1063
+ super("Midnight offer root signature carries no encoded payload. Sign the offer-root requirement (its signature already includes the payload) before building the submit transaction.");
1064
1064
  }
1065
1065
  }
1066
1066
  /** Thrown when a Midnight redeem flow finds no credit units for the user. */
@@ -24,8 +24,8 @@ export interface PublicAllocatorOptions {
24
24
  * The maximum utilization each source market may reach when withdrawing
25
25
  * shared liquidity, scaled by WAD.
26
26
  *
27
- * @deprecated Per-market source ceilings will be removed in the next major.
28
- * Use `defaultMaxWithdrawalUtilization` to configure one ceiling for every source.
27
+ * @deprecated Vault V1 shared-liquidity planning will be removed in the next major.
28
+ * Use `VaultV2BluePublicAllocatorOptions.maxWithdrawalUtilization` with the Vault V2 planner.
29
29
  */
30
30
  readonly maxWithdrawalUtilization?: Readonly<Record<MarketId, bigint | undefined>>;
31
31
  /**
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": "5.9.0",
4
+ "version": "5.11.0",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "contributors": [
7
7
  "Foulks-Plb <https://x.com/FoulkPlb>"
@@ -161,10 +161,10 @@
161
161
  ],
162
162
  "dependencies": {
163
163
  "zod": "^4.4.3",
164
- "@morpho-org/blue-sdk": "^6.7.0",
165
- "@morpho-org/blue-sdk-viem": "^5.5.0",
166
- "@morpho-org/midnight-sdk": "^1.3.1",
167
- "@morpho-org/morpho-ts": "^2.11.1"
164
+ "@morpho-org/blue-sdk": "^6.9.0",
165
+ "@morpho-org/blue-sdk-viem": "^5.7.0",
166
+ "@morpho-org/midnight-sdk": "^1.4.0",
167
+ "@morpho-org/morpho-ts": "^2.13.0"
168
168
  },
169
169
  "peerDependencies": {
170
170
  "viem": "^2.0.0"
@@ -172,14 +172,14 @@
172
172
  "devDependencies": {
173
173
  "dotenv": "^17.4.2",
174
174
  "fast-check": "^4.9.0",
175
- "typescript": "^7.0.2",
175
+ "typescript": "7.0.2",
176
176
  "viem": "^2.55.10",
177
177
  "vitest": "^4.1.10",
178
178
  "@morpho-org/test": "^2.10.0"
179
179
  },
180
180
  "scripts": {
181
- "prepublish": "$npm_execpath build",
182
- "build": "tsc --noEmit && $npm_execpath build:cjs && $npm_execpath build:esm",
181
+ "prepublish": "pnpm build",
182
+ "build": "tsc --noEmit && pnpm build:cjs && pnpm build:esm",
183
183
  "build:cjs": "tsc --build tsconfig.build.cjs.json && echo '{\"type\":\"commonjs\"}' > lib/cjs/package.json",
184
184
  "build:esm": "tsc --build tsconfig.build.esm.json && echo '{\"type\":\"module\"}' > lib/esm/package.json",
185
185
  "test": "vitest --root ../.. --project morpho-sdk --project morpho-sdk-fork"