@morpho-org/morpho-sdk 9.1.0 → 9.2.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 (56) hide show
  1. package/README.md +4 -0
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +3 -1
  4. package/lib/cjs/blue/constants.d.ts +1 -1
  5. package/lib/cjs/blue/constants.js +2 -1
  6. package/lib/cjs/constants.d.ts +2 -2
  7. package/lib/cjs/constants.js +4 -1
  8. package/lib/cjs/entities/blue/blue.d.ts +71 -16
  9. package/lib/cjs/entities/blue/blue.js +32 -4
  10. package/lib/cjs/entities/midnight/midnight.d.ts +2 -1
  11. package/lib/cjs/entities/midnight/midnight.js +5 -4
  12. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +8 -0
  13. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -0
  14. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +4 -0
  15. package/lib/cjs/entities/vaultV2/vaultV2.js +3 -0
  16. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +37 -4
  17. package/lib/cjs/entities/vaultV2BlueReallocationData.js +197 -32
  18. package/lib/cjs/helpers/constant.d.ts +7 -0
  19. package/lib/cjs/helpers/constant.js +8 -1
  20. package/lib/cjs/helpers/deadShares.d.ts +82 -0
  21. package/lib/cjs/helpers/deadShares.js +200 -0
  22. package/lib/cjs/helpers/index.d.ts +2 -1
  23. package/lib/cjs/helpers/index.js +7 -1
  24. package/lib/cjs/midnight/abis.d.ts +1 -1
  25. package/lib/cjs/midnight/abis.js +3 -1
  26. package/lib/cjs/types/error.d.ts +54 -5
  27. package/lib/cjs/types/error.js +60 -6
  28. package/lib/cjs/types/sharedLiquidity.d.ts +10 -6
  29. package/lib/esm/abis.d.ts +1 -1
  30. package/lib/esm/abis.js +1 -1
  31. package/lib/esm/blue/constants.d.ts +1 -1
  32. package/lib/esm/blue/constants.js +1 -1
  33. package/lib/esm/constants.d.ts +2 -2
  34. package/lib/esm/constants.js +2 -2
  35. package/lib/esm/entities/blue/blue.d.ts +71 -16
  36. package/lib/esm/entities/blue/blue.js +34 -6
  37. package/lib/esm/entities/midnight/midnight.d.ts +2 -1
  38. package/lib/esm/entities/midnight/midnight.js +6 -5
  39. package/lib/esm/entities/vaultV1/vaultV1.d.ts +8 -0
  40. package/lib/esm/entities/vaultV1/vaultV1.js +5 -0
  41. package/lib/esm/entities/vaultV2/vaultV2.d.ts +4 -0
  42. package/lib/esm/entities/vaultV2/vaultV2.js +3 -0
  43. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +37 -4
  44. package/lib/esm/entities/vaultV2BlueReallocationData.js +197 -32
  45. package/lib/esm/helpers/constant.d.ts +7 -0
  46. package/lib/esm/helpers/constant.js +7 -0
  47. package/lib/esm/helpers/deadShares.d.ts +82 -0
  48. package/lib/esm/helpers/deadShares.js +195 -0
  49. package/lib/esm/helpers/index.d.ts +2 -1
  50. package/lib/esm/helpers/index.js +2 -1
  51. package/lib/esm/midnight/abis.d.ts +1 -1
  52. package/lib/esm/midnight/abis.js +1 -1
  53. package/lib/esm/types/error.d.ts +54 -5
  54. package/lib/esm/types/error.js +57 -5
  55. package/lib/esm/types/sharedLiquidity.d.ts +10 -6
  56. package/package.json +8 -7
@@ -150,6 +150,8 @@ export interface BlueActions {
150
150
  * share-price bound or `slippageTolerance`.
151
151
  *
152
152
  * @param params.userAddress - User funding and receiving the supply position.
153
+ * @param params.marketData - Snapshot of this market from `getMarketData()` (or `fetchMarket` in
154
+ * `@morpho-org/blue-sdk-viem`), used to check its dead deposit before building.
153
155
  * @param params.assets - Gross loan-token assets funded before the referral fee.
154
156
  * @param params.nativeAmount - Optional full native funding; must equal `assets` and requires wNative.
155
157
  * @param params.deadline - Final call deadline in Unix seconds.
@@ -177,6 +179,9 @@ export interface BlueActions {
177
179
  * @throws {BundlesRequirementSignatureMismatchError} from `buildTx()` when a signature cannot be encoded safely.
178
180
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
179
181
  * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
182
+ * @throws {MarketIdMismatchError} when `marketData` belongs to another market.
183
+ * @throws {MissingDeadSharesDataError} when `marketData` has no `deadSupplyShares`.
184
+ * @throws {InsufficientDeadSharesError} when the market holds fewer than `MIN_DEAD_SHARES` supply shares at `DEAD_ADDRESS`.
180
185
  * @throws {UnknownTokenError} from `getRequirements()` when the funded token's `decimals()` is unusable.
181
186
  * @throws {MalformedTokenMetadataError} when the token's `eip712Domain()` or
182
187
  * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
@@ -198,6 +203,7 @@ export interface BlueActions {
198
203
  * const market = client.morpho.blue(markets[mainnet.id].usdc_wbtc, mainnet.id);
199
204
  * const action = market.supply({
200
205
  * userAddress,
206
+ * marketData: await market.getMarketData(),
201
207
  * assets: 1_000_000n,
202
208
  * deadline: BigInt(Math.floor(Date.now() / 1_000) + 3_600),
203
209
  * });
@@ -206,14 +212,29 @@ export interface BlueActions {
206
212
  * // tx satisfies Readonly<Transaction<BlueSupplyAction>>
207
213
  * ```
208
214
  */
209
- supply: (params: {
210
- readonly userAddress: Address;
211
- readonly assets: bigint;
212
- readonly nativeAmount?: bigint;
213
- readonly deadline: bigint;
214
- readonly referralFeePct?: bigint;
215
- readonly referralFeeRecipient?: Address;
216
- }) => ActionOutput<BlueSupplyAction, readonly RequirementSignature[], BlueTokenRequirementsParams>;
215
+ supply: {
216
+ (params: {
217
+ readonly userAddress: Address;
218
+ readonly marketData: Market;
219
+ readonly assets: bigint;
220
+ readonly nativeAmount?: bigint;
221
+ readonly deadline: bigint;
222
+ readonly referralFeePct?: bigint;
223
+ readonly referralFeeRecipient?: Address;
224
+ }): ActionOutput<BlueSupplyAction, readonly RequirementSignature[], BlueTokenRequirementsParams>;
225
+ /**
226
+ * @deprecated Pass `marketData` from `getMarketData()` to check the dead deposit.
227
+ * Snapshot-free supply is unprotected and will be removed in the next major after one minor.
228
+ */
229
+ (params: {
230
+ readonly userAddress: Address;
231
+ readonly assets: bigint;
232
+ readonly nativeAmount?: bigint;
233
+ readonly deadline: bigint;
234
+ readonly referralFeePct?: bigint;
235
+ readonly referralFeeRecipient?: Address;
236
+ }): ActionOutput<BlueSupplyAction, readonly RequirementSignature[], BlueTokenRequirementsParams>;
237
+ };
217
238
  /**
218
239
  * Prepares a direct BlueBundlesV1 loan-asset withdrawal by assets or shares.
219
240
  *
@@ -847,6 +868,13 @@ export interface BlueActions {
847
868
  * Reads the target Morpho Blue market, each Vault V2 accrual tree, and each
848
869
  * vault's BluePublicAllocator permissions and allocation caps at one block.
849
870
  * The snapshot keeps the fetched block's timestamp as its default planning time.
871
+ * It always records Blue's loan-token balance in `blueBalances` at that
872
+ * block, so balance-based rejection applies to plans from this fetcher.
873
+ * Sizing has zero margin over that snapshot balance; activity on other Blue
874
+ * markets with the same loan token can make a plan revert. Refetch close to
875
+ * submission; there is no balance-buffer option.
876
+ * Hand-built data without a balance uses summed snapshot-market liquidity
877
+ * only to size plans and may add about the penalty in extra paid assets.
850
878
  *
851
879
  * @param params.vaultAddresses - Vault V2 addresses to inspect for market or idle liquidity.
852
880
  * @param params.block.number - Block number used for every RPC read.
@@ -885,6 +913,11 @@ export interface BlueActions {
885
913
  * persist across every leg of a plan. Operation plans keep
886
914
  * `allocatorCapHeadroom` (1% of the cap by default) free under each target
887
915
  * BluePublicAllocator cap unless the operation shortfall needs it.
916
+ * With an explicit `blueBalances` value, plans are rejected when Blue cannot
917
+ * fund the penalty flash loan, an earlier market-sourced withdrawal, or the
918
+ * final transfer. A missing balance uses summed snapshot-market liquidity
919
+ * only to size plans and may make them larger; it cannot cause a balance-based
920
+ * rejection.
888
921
  * For `refinance`, compute the plan on the destination-market handle (for
889
922
  * example, `client.morpho.blue(destination.marketParams, chainId)`), not the
890
923
  * source-market handle. Pass the source position's `borrowAssets` accrued to
@@ -900,7 +933,7 @@ export interface BlueActions {
900
933
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
901
934
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
902
935
  * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, penalty limit, or referral-fee percentage is negative.
903
- * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD.
936
+ * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD, or a selected borrow/withdraw plan otherwise covers its shortfall but its planned penalty exceeds the operation amount.
904
937
  * @throws {ReferralFeePctExceededError} when the referral-fee percentage is at least WAD.
905
938
  * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
906
939
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -911,7 +944,7 @@ export interface BlueActions {
911
944
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
912
945
  * @throws {ReallocationAdapterSupplySharesUnderflowError} when an inconsistent adapter snapshot underflows during the final transition.
913
946
  * @throws {ReallocationAllocationUnderflowError} when an inconsistent allocation snapshot underflows during the final transition.
914
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the shortfall and, for refinance, its planned allocator penalties.
947
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the operation shortfall or refinance penalties, or an explicit Blue balance cannot fund a required transfer.
915
948
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply.
916
949
  * @example
917
950
  * ```ts
@@ -961,15 +994,25 @@ export declare class MorphoBlue implements BlueActions {
961
994
  /** {@inheritDoc BlueActions.supply} */
962
995
  supply(params: {
963
996
  readonly userAddress: Address;
997
+ readonly marketData: Market;
964
998
  readonly assets: bigint;
965
999
  readonly nativeAmount?: bigint;
966
1000
  readonly deadline: bigint;
967
1001
  readonly referralFeePct?: bigint;
968
1002
  readonly referralFeeRecipient?: Address;
969
- }): {
970
- getRequirements: (requirementsParams?: BlueTokenRequirementsParams) => Promise<readonly ActionRequirement[]>;
971
- buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<import("../../types/action.js").Transaction<BlueSupplyAction>>;
972
- };
1003
+ }): ActionOutput<BlueSupplyAction, readonly RequirementSignature[], BlueTokenRequirementsParams>;
1004
+ /**
1005
+ * @deprecated Pass `marketData` from `getMarketData()` to check the dead deposit.
1006
+ * Snapshot-free supply is unprotected and will be removed in the next major after one minor.
1007
+ */
1008
+ supply(params: {
1009
+ readonly userAddress: Address;
1010
+ readonly assets: bigint;
1011
+ readonly nativeAmount?: bigint;
1012
+ readonly deadline: bigint;
1013
+ readonly referralFeePct?: bigint;
1014
+ readonly referralFeeRecipient?: Address;
1015
+ }): ActionOutput<BlueSupplyAction, readonly RequirementSignature[], BlueTokenRequirementsParams>;
973
1016
  /** {@inheritDoc BlueActions.withdraw} */
974
1017
  withdraw(params: {
975
1018
  readonly userAddress: Address;
@@ -1084,6 +1127,13 @@ export declare class MorphoBlue implements BlueActions {
1084
1127
  * Reads the target Morpho Blue market, each Vault V2 accrual tree, and each
1085
1128
  * vault's BluePublicAllocator permissions and allocation caps at one block.
1086
1129
  * The snapshot keeps the fetched block's timestamp as its default planning time.
1130
+ * It always records Blue's loan-token balance in `blueBalances` at that
1131
+ * block, so balance-based rejection applies to plans from this fetcher.
1132
+ * Sizing has zero margin over that snapshot balance; activity on other Blue
1133
+ * markets with the same loan token can make a plan revert. Refetch close to
1134
+ * submission; there is no balance-buffer option.
1135
+ * Hand-built data without a balance uses summed snapshot-market liquidity
1136
+ * only to size plans and may add about the penalty in extra paid assets.
1087
1137
  *
1088
1138
  * @param params.vaultAddresses - Vault V2 addresses to inspect for market or idle liquidity.
1089
1139
  * @param params.block.number - Block number used for every RPC read.
@@ -1141,6 +1191,11 @@ export declare class MorphoBlue implements BlueActions {
1141
1191
  * persist across every leg of a plan. Operation plans keep
1142
1192
  * `allocatorCapHeadroom` (1% of the cap by default) free under each target
1143
1193
  * BluePublicAllocator cap unless the operation shortfall needs it.
1194
+ * With an explicit `blueBalances` value, plans are rejected when Blue cannot
1195
+ * fund the penalty flash loan, an earlier market-sourced withdrawal, or the
1196
+ * final transfer. A missing balance uses summed snapshot-market liquidity
1197
+ * only to size plans and may make them larger; it cannot cause a balance-based
1198
+ * rejection.
1144
1199
  * For `refinance`, compute the plan on the destination-market handle (for
1145
1200
  * example, `client.morpho.blue(destination.marketParams, chainId)`), not the
1146
1201
  * source-market handle. Pass the source position's `borrowAssets` accrued to
@@ -1156,7 +1211,7 @@ export declare class MorphoBlue implements BlueActions {
1156
1211
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
1157
1212
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
1158
1213
  * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, penalty limit, or referral-fee percentage is negative.
1159
- * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD.
1214
+ * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD, or a selected borrow/withdraw plan otherwise covers its shortfall but its planned penalty exceeds the operation amount.
1160
1215
  * @throws {ReferralFeePctExceededError} when the referral-fee percentage is at least WAD.
1161
1216
  * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
1162
1217
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -1167,7 +1222,7 @@ export declare class MorphoBlue implements BlueActions {
1167
1222
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
1168
1223
  * @throws {ReallocationAdapterSupplySharesUnderflowError} when an inconsistent adapter snapshot underflows during the final transition.
1169
1224
  * @throws {ReallocationAllocationUnderflowError} when an inconsistent allocation snapshot underflows during the final transition.
1170
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the shortfall and, for refinance, its planned allocator penalties.
1225
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the operation shortfall or refinance penalties, or an explicit Blue balance cannot fund a required transfer.
1171
1226
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply.
1172
1227
  * @example
1173
1228
  * ```ts
@@ -1,13 +1,15 @@
1
1
  import { MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualPosition, fetchAccrualVaultV2, fetchMarket, fetchVaultV2BluePublicAllocatorData, } from "@morpho-org/blue-sdk-viem";
3
3
  import { getChainAddress, getChainAddresses, Time, } from "@morpho-org/morpho-ts";
4
- import { isAddressEqual, maxUint256 } from "viem";
4
+ import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
5
+ import { readContract } from "viem/actions";
5
6
  import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBlueBundlesV1ReferralFeeAssets, normalizeBlueBundlesV1CommonParams, selectBlueBundlesV1RequirementSignatures, validateBlueBundlesV1NativeFunding, } from "../../actions/blue/common.js";
6
7
  import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawCollateral, getBlueAuthorizationRequirement, } from "../../actions/index.js";
7
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
+ import { validateBlueMarketDeadShares } from "../../helpers/deadShares.js";
8
10
  import { DEFAULT_LLTV_BUFFER, validateAccrualPosition, validateChainId, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
9
11
  import { validateMarketParamsId } from "../../helpers/validate.js";
10
- import { ExpiredDeadlineError, InputExceedsMaxError, MaxRepayAssetsBelowRepayAssetsError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, ReallocationsRequireBorrowError, RefinanceSameMarketError, RefinanceTokenMismatchError, } from "../../types/index.js";
12
+ import { ExpiredDeadlineError, InputExceedsMaxError, MarketIdMismatchError, MaxRepayAssetsBelowRepayAssetsError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, ReallocationsRequireBorrowError, RefinanceSameMarketError, RefinanceTokenMismatchError, } from "../../types/index.js";
11
13
  import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
12
14
  import { getBundlesTokenRequirements } from "../requirements/index.js";
13
15
  import { VaultV2BlueReallocationData } from "../vaultV2BlueReallocationData.js";
@@ -124,7 +126,6 @@ export class MorphoBlue {
124
126
  deployless: this.client.options.supportDeployless,
125
127
  });
126
128
  }
127
- /** {@inheritDoc BlueActions.supply} */
128
129
  supply(params) {
129
130
  const { userAddress, assets, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
130
131
  this.validateWriteCommon(params);
@@ -136,6 +137,13 @@ export class MorphoBlue {
136
137
  fundedAmount: assets,
137
138
  nativeAmount,
138
139
  });
140
+ if (params.marketData != null) {
141
+ if (params.marketData.id !== this.marketParams.id) {
142
+ throw new MarketIdMismatchError(params.marketData.id, this.marketParams.id);
143
+ }
144
+ // Throws when the market lacks a sufficient dead deposit; nothing to return.
145
+ validateBlueMarketDeadShares(params.marketData);
146
+ }
139
147
  return {
140
148
  getRequirements: (requirementsParams) => {
141
149
  const now = Time.timestamp();
@@ -732,6 +740,13 @@ export class MorphoBlue {
732
740
  * Reads the target Morpho Blue market, each Vault V2 accrual tree, and each
733
741
  * vault's BluePublicAllocator permissions and allocation caps at one block.
734
742
  * The snapshot keeps the fetched block's timestamp as its default planning time.
743
+ * It always records Blue's loan-token balance in `blueBalances` at that
744
+ * block, so balance-based rejection applies to plans from this fetcher.
745
+ * Sizing has zero margin over that snapshot balance; activity on other Blue
746
+ * markets with the same loan token can make a plan revert. Refetch close to
747
+ * submission; there is no balance-buffer option.
748
+ * Hand-built data without a balance uses summed snapshot-market liquidity
749
+ * only to size plans and may add about the penalty in extra paid assets.
735
750
  *
736
751
  * @param params.vaultAddresses - Vault V2 addresses to inspect for market or idle liquidity.
737
752
  * @param params.block.number - Block number used for every RPC read.
@@ -780,7 +795,7 @@ export class MorphoBlue {
780
795
  chainId: this.chainId,
781
796
  deployless: this.client.options.supportDeployless,
782
797
  };
783
- const [targetMarket, vaultEntries] = await Promise.all([
798
+ const [targetMarket, vaultEntries, blueBalance] = await Promise.all([
784
799
  fetchMarket(this.marketParams.id, client, fetchParams),
785
800
  Promise.all(vaultAddresses.map(async (address) => {
786
801
  const vault = await fetchAccrualVaultV2(address, client, fetchParams);
@@ -790,10 +805,18 @@ export class MorphoBlue {
790
805
  });
791
806
  return { publicAllocatorData, vault };
792
807
  })),
808
+ readContract(client, {
809
+ address: this.marketParams.loanToken,
810
+ abi: erc20Abi,
811
+ functionName: "balanceOf",
812
+ args: [getChainAddresses(this.chainId).blue],
813
+ blockNumber: block.number,
814
+ }),
793
815
  ]);
794
816
  return new VaultV2BlueReallocationData({
795
817
  chainId: this.chainId,
796
818
  timestamp: block.timestamp,
819
+ blueBalances: { [this.marketParams.loanToken]: blueBalance },
797
820
  markets: { [targetMarket.id]: targetMarket },
798
821
  vaults: Object.fromEntries(vaultEntries.map(({ vault }) => [vault.address, vault])),
799
822
  allocations: Object.fromEntries(vaultEntries.map(({ publicAllocatorData, vault }) => [
@@ -824,6 +847,11 @@ export class MorphoBlue {
824
847
  * persist across every leg of a plan. Operation plans keep
825
848
  * `allocatorCapHeadroom` (1% of the cap by default) free under each target
826
849
  * BluePublicAllocator cap unless the operation shortfall needs it.
850
+ * With an explicit `blueBalances` value, plans are rejected when Blue cannot
851
+ * fund the penalty flash loan, an earlier market-sourced withdrawal, or the
852
+ * final transfer. A missing balance uses summed snapshot-market liquidity
853
+ * only to size plans and may make them larger; it cannot cause a balance-based
854
+ * rejection.
827
855
  * For `refinance`, compute the plan on the destination-market handle (for
828
856
  * example, `client.morpho.blue(destination.marketParams, chainId)`), not the
829
857
  * source-market handle. Pass the source position's `borrowAssets` accrued to
@@ -839,7 +867,7 @@ export class MorphoBlue {
839
867
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
840
868
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
841
869
  * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, penalty limit, or referral-fee percentage is negative.
842
- * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD.
870
+ * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD, or a selected borrow/withdraw plan otherwise covers its shortfall but its planned penalty exceeds the operation amount.
843
871
  * @throws {ReferralFeePctExceededError} when the referral-fee percentage is at least WAD.
844
872
  * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
845
873
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -850,7 +878,7 @@ export class MorphoBlue {
850
878
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
851
879
  * @throws {ReallocationAdapterSupplySharesUnderflowError} when an inconsistent adapter snapshot underflows during the final transition.
852
880
  * @throws {ReallocationAllocationUnderflowError} when an inconsistent allocation snapshot underflows during the final transition.
853
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the shortfall and, for refinance, its planned allocator penalties.
881
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the operation shortfall or refinance penalties, or an explicit Blue balance cannot fund a required transfer.
854
882
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply.
855
883
  * @example
856
884
  * ```ts
@@ -848,7 +848,8 @@ export declare class MorphoMidnight {
848
848
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
849
849
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
850
850
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
851
- * @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
851
+ * @throws {MissingDeadSharesDataError} when the fetched `blueMarket` snapshot has no `deadSupplyShares`.
852
+ * @throws {InsufficientDeadSharesError} when `blueMarket` holds fewer than `MIN_DEAD_SHARES` supply shares at `DEAD_ADDRESS`.
852
853
  * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price (checked at preparation time only).
853
854
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
854
855
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
@@ -8,6 +8,7 @@ import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, }
8
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
9
  import { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "../../helpers/callback.js";
10
10
  import { MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS } from "../../helpers/constant.js";
11
+ import { validateBlueMarketDeadShares } from "../../helpers/deadShares.js";
11
12
  import { encodeMidnightMarketId, wrapMidnightEncoding, } from "../../helpers/encodeMidnightCalldata.js";
12
13
  import { getMidnightMaxSafeDebt, validateChainId, } from "../../helpers/index.js";
13
14
  import { validateMidnightAccount, validateMidnightAddress, } from "../../helpers/validateMidnightAccount.js";
@@ -16,7 +17,7 @@ import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js"
16
17
  import { validateMidnightBytes32 } from "../../helpers/validateMidnightPublication.js";
17
18
  import { validateMidnightTakeFeasibility } from "../../helpers/validateMidnightTakeFeasibility.js";
18
19
  import { validateOfferSides } from "../../helpers/validateOfferSides.js";
19
- import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, EmptyBlueParkingMarketError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MidnightZeroOnBehalfError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
20
+ import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MidnightZeroOnBehalfError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
20
21
  import { validateMidnightDeadline } from "./deadline.js";
21
22
  import { fetchMidnightMakerOfferStates, offerMarketParams, validateMidnightMakerOfferCallbacks, validateMidnightMakerOfferStates, } from "./publication.js";
22
23
  const validatePositionBinding = (params) => {
@@ -1435,7 +1436,8 @@ export class MorphoMidnight {
1435
1436
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1436
1437
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1437
1438
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1438
- * @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
1439
+ * @throws {MissingDeadSharesDataError} when the fetched `blueMarket` snapshot has no `deadSupplyShares`.
1440
+ * @throws {InsufficientDeadSharesError} when `blueMarket` holds fewer than `MIN_DEAD_SHARES` supply shares at `DEAD_ADDRESS`.
1439
1441
  * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price (checked at preparation time only).
1440
1442
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1441
1443
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
@@ -1491,9 +1493,8 @@ export class MorphoMidnight {
1491
1493
  }),
1492
1494
  ]);
1493
1495
  const market = _try(() => fetched.accrueInterest(MathLib.max(Time.timestamp(), fetched.lastUpdate)), UnsupportedMarketIrmError) ?? fetched;
1494
- if (market.totalSupplyShares === 0n) {
1495
- throw new EmptyBlueParkingMarketError({ marketId: blueMarketId });
1496
- }
1496
+ // Throws when the parking market lacks a sufficient dead deposit; nothing to return.
1497
+ validateBlueMarketDeadShares(fetched);
1497
1498
  if (market.toSupplyShares(params.assetsToPark, "Down") === 0n) {
1498
1499
  throw new ZeroBlueParkingSharesError({
1499
1500
  marketId: blueMarketId,
@@ -104,6 +104,10 @@ export interface VaultV1Actions {
104
104
  * const tx = action.buildTx(); // For a client configured with supportSignature: false.
105
105
  * // tx satisfies Readonly<Transaction<VaultV1DepositAction>>
106
106
  * ```
107
+ * @throws {MissingDeadSharesDataError} when `vaultData` lacks the dead-share, cap or adapter data
108
+ * the dead-deposit check needs, such as a hand-built or API-sourced snapshot.
109
+ * @throws {InsufficientDeadSharesError} when the vault, or a market or vault it can allocate to,
110
+ * holds less than the required dead deposit.
107
111
  */
108
112
  deposit: (params: {
109
113
  readonly userAddress: Address;
@@ -457,6 +461,10 @@ export interface VaultV1Actions {
457
461
  * const tx = migration.buildTx(signatures);
458
462
  * // tx satisfies Readonly<Transaction<VaultV1MigrateToV2Action>>
459
463
  * ```
464
+ * @throws {MissingDeadSharesDataError} when `targetVault` lacks the dead-share, cap or adapter data
465
+ * the dead-deposit check needs. The source Vault V1 is not checked.
466
+ * @throws {InsufficientDeadSharesError} when `targetVault`, or a market or vault it can allocate
467
+ * to, holds less than the required dead deposit.
460
468
  */
461
469
  migrateToV2: (params: {
462
470
  readonly userAddress: Address;
@@ -6,6 +6,7 @@ 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
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
+ import { validateVaultV1DeadShares, validateVaultV2DeadShares, } from "../../helpers/deadShares.js";
9
10
  import { computeVaultMaxShareAllowance, computeVaultMaxSharePrice, validateChainId, validateSlippageTolerance, } from "../../helpers/index.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";
@@ -75,6 +76,8 @@ export class MorphoVaultV1 {
75
76
  // The native path must target the chain's registered wrapped-native asset.
76
77
  validateNativeVaultAsset(this.chainId, vaultAsset);
77
78
  }
79
+ // Throws when the vault, or a market it can allocate to, lacks a sufficient dead deposit.
80
+ validateVaultV1DeadShares(vaultData);
78
81
  const referralFeeAssets = getBundlesReferralFeeAssets(funding.assets, common.referralFeePct);
79
82
  const maxSharePrice = computeVaultMaxSharePrice({
80
83
  vaultData,
@@ -469,6 +472,8 @@ export class MorphoVaultV1 {
469
472
  referralFeePct: params.referralFeePct,
470
473
  referralFeeRecipient: params.referralFeeRecipient,
471
474
  });
475
+ // Only the destination receives a deposit; the source vault is an exit.
476
+ validateVaultV2DeadShares(params.targetVault);
472
477
  // V1 redeem accrues market interest and performance fees before converting shares.
473
478
  const grossAssets = assets ??
474
479
  params.sourceVault
@@ -110,6 +110,10 @@ export interface VaultV2Actions {
110
110
  * const tx = action.buildTx(); // For a client configured with supportSignature: false.
111
111
  * // tx satisfies Readonly<Transaction<VaultV2DepositAction>>
112
112
  * ```
113
+ * @throws {MissingDeadSharesDataError} when `vaultData` lacks the dead-share, cap or adapter data
114
+ * the dead-deposit check needs, such as a hand-built or API-sourced snapshot.
115
+ * @throws {InsufficientDeadSharesError} when the vault, or a market or vault it can allocate to,
116
+ * holds less than the required dead deposit.
113
117
  */
114
118
  deposit: (params: {
115
119
  readonly userAddress: Address;
@@ -6,6 +6,7 @@ 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
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
+ import { validateVaultV2DeadShares } from "../../helpers/deadShares.js";
9
10
  import { computeMinForceWithdrawSharePrice, computeVaultMaxShareAllowance, computeVaultMaxSharePrice, computeVaultV2ForceWithdrawFeeSharesMinted, computeVaultV2ForceWithdrawMinSharesBurnt, computeVaultV2ForceWithdrawPlan, computeVaultV2ForceWithdrawSharesBurnt, MAX_SLIPPAGE_TOLERANCE, resolveVaultV2ForceWithdrawEligibility, validateChainId, validateSlippageTolerance, } from "../../helpers/index.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";
@@ -78,6 +79,8 @@ export class MorphoVaultV2 {
78
79
  // The native path must target the chain's registered wrapped-native asset.
79
80
  validateNativeVaultAsset(this.chainId, vaultAsset);
80
81
  }
82
+ // Throws when the vault, or a market it can allocate to, lacks a sufficient dead deposit.
83
+ validateVaultV2DeadShares(vaultData);
81
84
  const referralFeeAssets = getBundlesReferralFeeAssets(funding.assets, common.referralFeePct);
82
85
  const maxSharePrice = computeVaultMaxSharePrice({
83
86
  vaultData,
@@ -26,6 +26,16 @@ export interface InputVaultV2BlueReallocationData {
26
26
  * defaults to the latest market/vault `lastUpdate`.
27
27
  */
28
28
  readonly timestamp?: BigIntish;
29
+ /**
30
+ * Morpho Blue's ERC-20 balances at the snapshot block, indexed by token address.
31
+ * Explicit balances increase with idle-sourced reallocations in returned
32
+ * post-states. Sizing has zero margin over the snapshot balance, so activity
33
+ * on other Blue markets with the same loan token can make a plan revert;
34
+ * refetch close to submission. A missing token uses summed non-negative
35
+ * snapshot-market supply-minus-borrow only to size plans; balance-based
36
+ * rejection requires an explicit balance.
37
+ */
38
+ readonly blueBalances?: Readonly<Record<Address, BigIntish | undefined>>;
29
39
  /** Markets indexed by market id. */
30
40
  readonly markets?: Readonly<Record<MarketId, ReadonlyMarketSnapshot | undefined>>;
31
41
  /** Accrued Vault V2 entities indexed by vault address. */
@@ -83,10 +93,22 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
83
93
  private readonly mutableVaults;
84
94
  /** Mutable allocation state used only by cloned simulation transitions. */
85
95
  private readonly mutableAllocations;
96
+ /** Mutable Blue token balances used only by cloned simulation transitions. */
97
+ private readonly mutableBlueBalances;
86
98
  /** Chain id associated with this snapshot. */
87
99
  readonly chainId: number;
88
100
  /** Timestamp of the block the state was fetched at. */
89
101
  readonly timestamp?: bigint;
102
+ /**
103
+ * Morpho Blue's ERC-20 balances at the snapshot block, indexed by token address.
104
+ * Explicit balances increase with idle-sourced reallocations in returned
105
+ * post-states. Sizing has zero margin over the snapshot balance, so activity
106
+ * on other Blue markets with the same loan token can make a plan revert;
107
+ * refetch close to submission. A missing token uses summed non-negative
108
+ * snapshot-market supply-minus-borrow only to size plans; balance-based
109
+ * rejection requires an explicit balance.
110
+ */
111
+ readonly blueBalances: Readonly<Record<Address, bigint | undefined>>;
90
112
  /** Markets indexed by market id. */
91
113
  readonly markets: Readonly<Record<MarketId, ReadonlyMarketSnapshot | undefined>>;
92
114
  /** Vault V2 entities indexed by address. */
@@ -367,8 +389,9 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
367
389
  * Without `options.operation`, discovers every friendly call. With an
368
390
  * operation, penalty tiers are considered ascending, starting with free
369
391
  * vaults. The free tier aims to bring the target market back to 90%
370
- * utilization; positive tiers cover only the remaining absolute shortfall
371
- * (borrows minus supply). Within each tier, source markets go to the
392
+ * utilization; positive tiers cover the remaining absolute shortfall or,
393
+ * when larger, Blue's loan-token balance deficit while the penalty is
394
+ * flash-loaned. Within each tier, source markets go to the
372
395
  * friendly source utilization (90% by default) before 100%. Free capacity
373
396
  * inside `allocatorCapHeadroom` is kept unused, so a penalized leg can cover
374
397
  * it instead. Discovery and liquidity getters still count every vault up to
@@ -382,6 +405,16 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
382
405
  * The planner includes the referral fee and its allocator-leg penalties in
383
406
  * destination debt, so penalized legs also cover their own penalty.
384
407
  * Refinance never uses vaults with a 100% penalty.
408
+ * BlueBundlesV1 flash-loans the plan's penalty from Blue before executing
409
+ * reallocation legs. When an explicit `blueBalances` value is supplied, plans
410
+ * throw `InsufficientSharedLiquidityError` if Blue cannot fund that flash
411
+ * loan or a market-sourced leg's withdrawal before later idle legs arrive.
412
+ * Legs are not reordered. A missing balance falls back to summed snapshot-
413
+ * market liquidity only to size plans and may make them larger; it cannot
414
+ * cause rejection for Blue-balance constraints.
415
+ * Sizing has zero margin over the snapshot balance; activity on other Blue
416
+ * markets with the same loan token can make a plan revert. Refetch close to
417
+ * submission; there is no balance-buffer option.
385
418
  * Friendly source utilization defaults to 90% and is configurable through
386
419
  * `options.maxWithdrawalUtilization`. Market/vault state and the returned
387
420
  * post-state stay at `timestamp`. An enabled operation that needs no
@@ -429,7 +462,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
429
462
  * @returns Flat action-ready reallocations and their post-simulation state.
430
463
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
431
464
  * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, `maxPenalty`, or `referralFeePct` is negative.
432
- * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
465
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD, or an enabled borrow/withdraw plan otherwise covers its shortfall but its planned penalty exceeds the operation amount.
433
466
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
434
467
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
435
468
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -438,7 +471,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
438
471
  * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
439
472
  * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
440
473
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
441
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall and, for refinance, its planned allocator penalties.
474
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the operation shortfall or refinance penalties, or an explicit Blue balance cannot fund the penalty flash loan, an earlier market-sourced withdrawal, or the final operation transfer.
442
475
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
443
476
  * @example
444
477
  * ```ts