@morpho-org/morpho-sdk 9.1.0 → 9.3.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +5 -1
  2. package/lib/cjs/abis.d.ts +2 -2
  3. package/lib/cjs/abis.js +7 -1
  4. package/lib/cjs/actions/midnight/index.d.ts +1 -0
  5. package/lib/cjs/actions/midnight/index.js +1 -0
  6. package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +50 -0
  7. package/lib/cjs/actions/midnight/withdrawCollateral.js +105 -0
  8. package/lib/cjs/blue/abis.d.ts +1 -1
  9. package/lib/cjs/blue/abis.js +5 -1
  10. package/lib/cjs/blue/constants.d.ts +1 -1
  11. package/lib/cjs/blue/constants.js +2 -1
  12. package/lib/cjs/blue/entities.d.ts +4 -4
  13. package/lib/cjs/blue/entities.js +3 -1
  14. package/lib/cjs/blue/errors.d.ts +2 -2
  15. package/lib/cjs/blue/errors.js +5 -1
  16. package/lib/cjs/blue/fetch.d.ts +2 -2
  17. package/lib/cjs/blue/fetch.js +3 -1
  18. package/lib/cjs/blue/utils.d.ts +1 -1
  19. package/lib/cjs/blue/utils.js +2 -1
  20. package/lib/cjs/constants.d.ts +2 -2
  21. package/lib/cjs/constants.js +4 -1
  22. package/lib/cjs/entities/blue/blue.d.ts +71 -16
  23. package/lib/cjs/entities/blue/blue.js +32 -4
  24. package/lib/cjs/entities/index.d.ts +5 -5
  25. package/lib/cjs/entities/index.js +3 -1
  26. package/lib/cjs/entities/midnight/midnight.d.ts +58 -11
  27. package/lib/cjs/entities/midnight/midnight.js +103 -11
  28. package/lib/cjs/entities/midnight/publication.d.ts +2 -1
  29. package/lib/cjs/entities/midnight/publication.js +44 -64
  30. package/lib/cjs/entities/midnight/types.d.ts +8 -0
  31. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +8 -0
  32. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -0
  33. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +37 -9
  34. package/lib/cjs/entities/vaultV2/vaultV2.js +36 -1
  35. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +42 -7
  36. package/lib/cjs/entities/vaultV2BlueReallocationData.js +206 -35
  37. package/lib/cjs/errors.d.ts +4 -4
  38. package/lib/cjs/errors.js +10 -5
  39. package/lib/cjs/fetch.d.ts +2 -2
  40. package/lib/cjs/fetch.js +3 -1
  41. package/lib/cjs/helpers/constant.d.ts +7 -0
  42. package/lib/cjs/helpers/constant.js +8 -1
  43. package/lib/cjs/helpers/deadShares.d.ts +82 -0
  44. package/lib/cjs/helpers/deadShares.js +202 -0
  45. package/lib/cjs/helpers/index.d.ts +2 -1
  46. package/lib/cjs/helpers/index.js +7 -1
  47. package/lib/cjs/midnight/abis.d.ts +1 -1
  48. package/lib/cjs/midnight/abis.js +3 -1
  49. package/lib/cjs/midnight/errors.d.ts +2 -1
  50. package/lib/cjs/midnight/errors.js +5 -4
  51. package/lib/cjs/types/action.d.ts +10 -1
  52. package/lib/cjs/types/error.d.ts +54 -5
  53. package/lib/cjs/types/error.js +60 -6
  54. package/lib/cjs/types/sharedLiquidity.d.ts +10 -6
  55. package/lib/cjs/utils.d.ts +2 -2
  56. package/lib/cjs/utils.js +4 -2
  57. package/lib/esm/abis.d.ts +2 -2
  58. package/lib/esm/abis.js +2 -2
  59. package/lib/esm/actions/midnight/index.d.ts +1 -0
  60. package/lib/esm/actions/midnight/index.js +1 -0
  61. package/lib/esm/actions/midnight/withdrawCollateral.d.ts +50 -0
  62. package/lib/esm/actions/midnight/withdrawCollateral.js +101 -0
  63. package/lib/esm/blue/abis.d.ts +1 -1
  64. package/lib/esm/blue/abis.js +1 -1
  65. package/lib/esm/blue/constants.d.ts +1 -1
  66. package/lib/esm/blue/constants.js +1 -1
  67. package/lib/esm/blue/entities.d.ts +4 -4
  68. package/lib/esm/blue/entities.js +2 -2
  69. package/lib/esm/blue/errors.d.ts +2 -2
  70. package/lib/esm/blue/errors.js +2 -2
  71. package/lib/esm/blue/fetch.d.ts +2 -2
  72. package/lib/esm/blue/fetch.js +2 -2
  73. package/lib/esm/blue/utils.d.ts +1 -1
  74. package/lib/esm/blue/utils.js +1 -1
  75. package/lib/esm/constants.d.ts +2 -2
  76. package/lib/esm/constants.js +2 -2
  77. package/lib/esm/entities/blue/blue.d.ts +71 -16
  78. package/lib/esm/entities/blue/blue.js +34 -6
  79. package/lib/esm/entities/index.d.ts +5 -5
  80. package/lib/esm/entities/index.js +2 -2
  81. package/lib/esm/entities/midnight/midnight.d.ts +58 -11
  82. package/lib/esm/entities/midnight/midnight.js +105 -13
  83. package/lib/esm/entities/midnight/publication.d.ts +2 -1
  84. package/lib/esm/entities/midnight/publication.js +45 -65
  85. package/lib/esm/entities/midnight/types.d.ts +8 -0
  86. package/lib/esm/entities/vaultV1/vaultV1.d.ts +8 -0
  87. package/lib/esm/entities/vaultV1/vaultV1.js +5 -0
  88. package/lib/esm/entities/vaultV2/vaultV2.d.ts +37 -9
  89. package/lib/esm/entities/vaultV2/vaultV2.js +36 -1
  90. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +42 -7
  91. package/lib/esm/entities/vaultV2BlueReallocationData.js +206 -35
  92. package/lib/esm/errors.d.ts +4 -4
  93. package/lib/esm/errors.js +4 -4
  94. package/lib/esm/fetch.d.ts +2 -2
  95. package/lib/esm/fetch.js +2 -2
  96. package/lib/esm/helpers/constant.d.ts +7 -0
  97. package/lib/esm/helpers/constant.js +7 -0
  98. package/lib/esm/helpers/deadShares.d.ts +82 -0
  99. package/lib/esm/helpers/deadShares.js +197 -0
  100. package/lib/esm/helpers/index.d.ts +2 -1
  101. package/lib/esm/helpers/index.js +2 -1
  102. package/lib/esm/midnight/abis.d.ts +1 -1
  103. package/lib/esm/midnight/abis.js +1 -1
  104. package/lib/esm/midnight/errors.d.ts +2 -1
  105. package/lib/esm/midnight/errors.js +2 -1
  106. package/lib/esm/types/action.d.ts +10 -1
  107. package/lib/esm/types/error.d.ts +54 -5
  108. package/lib/esm/types/error.js +57 -5
  109. package/lib/esm/types/sharedLiquidity.d.ts +10 -6
  110. package/lib/esm/utils.d.ts +2 -2
  111. package/lib/esm/utils.js +2 -2
  112. package/package.json +9 -8
@@ -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("../../index.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
@@ -5,9 +5,11 @@ const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
6
6
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
7
  const viem_1 = require("viem");
8
+ const actions_1 = require("viem/actions");
8
9
  const common_js_1 = require("../../actions/blue/common.js");
9
10
  const index_js_1 = require("../../actions/index.js");
10
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
+ const deadShares_js_1 = require("../../helpers/deadShares.js");
11
13
  const index_js_2 = require("../../helpers/index.js");
12
14
  const validate_js_1 = require("../../helpers/validate.js");
13
15
  const index_js_3 = require("../../types/index.js");
@@ -127,7 +129,6 @@ class MorphoBlue {
127
129
  deployless: this.client.options.supportDeployless,
128
130
  });
129
131
  }
130
- /** {@inheritDoc BlueActions.supply} */
131
132
  supply(params) {
132
133
  const { userAddress, assets, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
133
134
  this.validateWriteCommon(params);
@@ -139,6 +140,13 @@ class MorphoBlue {
139
140
  fundedAmount: assets,
140
141
  nativeAmount,
141
142
  });
143
+ if (params.marketData != null) {
144
+ if (params.marketData.id !== this.marketParams.id) {
145
+ throw new index_js_3.MarketIdMismatchError(params.marketData.id, this.marketParams.id);
146
+ }
147
+ // Throws when the market lacks a sufficient dead deposit; nothing to return.
148
+ (0, deadShares_js_1.validateBlueMarketDeadShares)(params.marketData);
149
+ }
142
150
  return {
143
151
  getRequirements: (requirementsParams) => {
144
152
  const now = morpho_ts_1.Time.timestamp();
@@ -735,6 +743,13 @@ class MorphoBlue {
735
743
  * Reads the target Morpho Blue market, each Vault V2 accrual tree, and each
736
744
  * vault's BluePublicAllocator permissions and allocation caps at one block.
737
745
  * The snapshot keeps the fetched block's timestamp as its default planning time.
746
+ * It always records Blue's loan-token balance in `blueBalances` at that
747
+ * block, so balance-based rejection applies to plans from this fetcher.
748
+ * Sizing has zero margin over that snapshot balance; activity on other Blue
749
+ * markets with the same loan token can make a plan revert. Refetch close to
750
+ * submission; there is no balance-buffer option.
751
+ * Hand-built data without a balance uses summed snapshot-market liquidity
752
+ * only to size plans and may add about the penalty in extra paid assets.
738
753
  *
739
754
  * @param params.vaultAddresses - Vault V2 addresses to inspect for market or idle liquidity.
740
755
  * @param params.block.number - Block number used for every RPC read.
@@ -783,7 +798,7 @@ class MorphoBlue {
783
798
  chainId: this.chainId,
784
799
  deployless: this.client.options.supportDeployless,
785
800
  };
786
- const [targetMarket, vaultEntries] = await Promise.all([
801
+ const [targetMarket, vaultEntries, blueBalance] = await Promise.all([
787
802
  (0, blue_sdk_viem_1.fetchMarket)(this.marketParams.id, client, fetchParams),
788
803
  Promise.all(vaultAddresses.map(async (address) => {
789
804
  const vault = await (0, blue_sdk_viem_1.fetchAccrualVaultV2)(address, client, fetchParams);
@@ -793,10 +808,18 @@ class MorphoBlue {
793
808
  });
794
809
  return { publicAllocatorData, vault };
795
810
  })),
811
+ (0, actions_1.readContract)(client, {
812
+ address: this.marketParams.loanToken,
813
+ abi: viem_1.erc20Abi,
814
+ functionName: "balanceOf",
815
+ args: [(0, morpho_ts_1.getChainAddresses)(this.chainId).blue],
816
+ blockNumber: block.number,
817
+ }),
796
818
  ]);
797
819
  return new vaultV2BlueReallocationData_js_1.VaultV2BlueReallocationData({
798
820
  chainId: this.chainId,
799
821
  timestamp: block.timestamp,
822
+ blueBalances: { [this.marketParams.loanToken]: blueBalance },
800
823
  markets: { [targetMarket.id]: targetMarket },
801
824
  vaults: Object.fromEntries(vaultEntries.map(({ vault }) => [vault.address, vault])),
802
825
  allocations: Object.fromEntries(vaultEntries.map(({ publicAllocatorData, vault }) => [
@@ -827,6 +850,11 @@ class MorphoBlue {
827
850
  * persist across every leg of a plan. Operation plans keep
828
851
  * `allocatorCapHeadroom` (1% of the cap by default) free under each target
829
852
  * BluePublicAllocator cap unless the operation shortfall needs it.
853
+ * With an explicit `blueBalances` value, plans are rejected when Blue cannot
854
+ * fund the penalty flash loan, an earlier market-sourced withdrawal, or the
855
+ * final transfer. A missing balance uses summed snapshot-market liquidity
856
+ * only to size plans and may make them larger; it cannot cause a balance-based
857
+ * rejection.
830
858
  * For `refinance`, compute the plan on the destination-market handle (for
831
859
  * example, `client.morpho.blue(destination.marketParams, chainId)`), not the
832
860
  * source-market handle. Pass the source position's `borrowAssets` accrued to
@@ -842,7 +870,7 @@ class MorphoBlue {
842
870
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
843
871
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
844
872
  * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, penalty limit, or referral-fee percentage is negative.
845
- * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD.
873
+ * @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.
846
874
  * @throws {ReferralFeePctExceededError} when the referral-fee percentage is at least WAD.
847
875
  * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
848
876
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -853,7 +881,7 @@ class MorphoBlue {
853
881
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
854
882
  * @throws {ReallocationAdapterSupplySharesUnderflowError} when an inconsistent adapter snapshot underflows during the final transition.
855
883
  * @throws {ReallocationAllocationUnderflowError} when an inconsistent allocation snapshot underflows during the final transition.
856
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the shortfall and, for refinance, its planned allocator penalties.
884
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the operation shortfall or refinance penalties, or an explicit Blue balance cannot fund a required transfer.
857
885
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply.
858
886
  * @example
859
887
  * ```ts
@@ -1,18 +1,18 @@
1
- export type { IAccrualPosition as IBlueAccrualPosition, IAccrualVault, IAccrualVaultV2, IAccrualVaultV2Adapter, IAccrualVaultV2MorphoMarketV1Adapter, IAccrualVaultV2MorphoMarketV1AdapterV2, IAccrualVaultV2MorphoVaultV1Adapter, IAssetBalances, IEip5267Domain, IHolding, IMarket as IBlueMarket, IMarketParams as IBlueMarketParams, IPosition as IBluePosition,
1
+ export type { IAccrualPosition as IBlueAccrualPosition, IAccrualVault, IAccrualVaultV2, IAccrualVaultV2Adapter, IAccrualVaultV2MidnightAdapter, IAccrualVaultV2MorphoMarketV1Adapter, IAccrualVaultV2MorphoMarketV1AdapterV2, IAccrualVaultV2MorphoVaultV1Adapter, IAssetBalances, IEip5267Domain, IHolding, IMarket as IBlueMarket, IMarketParams as IBlueMarketParams, IPosition as IBluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  IPreLiquidationParams as IBluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- IPreLiquidationPosition as IBluePreLiquidationPosition, IToken, IVault, IVaultConfig, IVaultMarketAllocation, IVaultMarketConfig, IVaultToken, IVaultUser, IVaultV2, IVaultV2Adapter, IVaultV2Allocation, IVaultV2BlueMarketPublicAllocatorConfig, IVaultV2BluePublicAllocatorConfig, IVaultV2MorphoMarketV1Adapter, IVaultV2MorphoMarketV1AdapterV2, IVaultV2MorphoVaultV1Adapter, PeripheralBalance, PeripheralBalanceType, } from "@morpho-org/blue-sdk";
6
- export { AccrualPosition as BlueAccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market as BlueMarket, MarketParams as BlueMarketParams, Position as BluePosition,
5
+ IPreLiquidationPosition as IBluePreLiquidationPosition, IToken, IVault, IVaultConfig, IVaultMarketAllocation, IVaultMarketConfig, IVaultToken, IVaultUser, IVaultV2, IVaultV2Adapter, IVaultV2Allocation, IVaultV2BlueMarketPublicAllocatorConfig, IVaultV2BluePublicAllocatorConfig, IVaultV2MidnightAdapter, IVaultV2MidnightAdapterAccrualMarket, IVaultV2MidnightAdapterCollateralParams, IVaultV2MidnightAdapterMarket, IVaultV2MidnightAdapterMarketData, IVaultV2MidnightAdapterMarketState, IVaultV2MidnightAdapterPosition, IVaultV2MorphoMarketV1Adapter, IVaultV2MorphoMarketV1AdapterV2, IVaultV2MorphoVaultV1Adapter, PeripheralBalance, PeripheralBalanceType, VaultV2MidnightAdapterAccrualMarket, VaultV2MidnightAdapterMarketData, } from "@morpho-org/blue-sdk";
6
+ export { AccrualPosition as BlueAccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MidnightAdapter, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market as BlueMarket, MarketParams as BlueMarketParams, Position as BluePosition,
7
7
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
8
8
  PreLiquidationParams as BluePreLiquidationParams,
9
9
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
10
- PreLiquidationPosition as BluePreLiquidationPosition, Token, User as BlueUser, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
10
+ PreLiquidationPosition as BluePreLiquidationPosition, Token, User as BlueUser, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2MidnightAdapter, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
11
11
  export type { AnyTree as MidnightAnyTree, AnyTreeSnapshot as MidnightAnyTreeSnapshot, BuildOfferParams as MidnightBuildOfferParams, CollateralParams as MidnightCollateralParams, EcrecoverTreeCreateRequest as MidnightEcrecoverTreeCreateRequest, GroupInput as MidnightGroupInput, IAccrualPosition as IMidnightAccrualPosition, ICollateralParams as IMidnightCollateralParams, IGroup as IMidnightGroup, IMarket as IMidnightMarket, IMarketParams as IMidnightMarketParams, IOffer as IMidnightOffer, IPosition as IMidnightPosition, MarketInput as MidnightMarketInput, OfferStruct as MidnightOfferStruct, PriceRatifierV1TreeCreateRequest as MidnightPriceRatifierV1TreeCreateRequest, RateRatifierV1TreeCreateRequest as MidnightRateRatifierV1TreeCreateRequest, RatifierKind as MidnightRatifierKind, RatifierTreeInput as MidnightRatifierTreeInput, RatifierTypes as MidnightRatifierTypes, SetterTreeCreateRequest as MidnightSetterTreeCreateRequest, SettlementFeeCbps as MidnightSettlementFeeCbps, TreeCreateParams as MidnightTreeCreateParams, TreeCreateRequest as MidnightTreeCreateRequest, TreeData as MidnightTreeData, TreeDescriptor as MidnightTreeDescriptor, TreeEntry as MidnightTreeEntry, TreeInput as MidnightTreeInput, TreeLike as MidnightTreeLike, TreeMempoolValidateParams as MidnightTreeMempoolValidateParams, TreeMempoolValidateRatification as MidnightTreeMempoolValidateRatification, TreeProof as MidnightTreeProof, TreeSnapshot as MidnightTreeSnapshot, TypedRatifierTreeInput as MidnightTypedRatifierTreeInput, TypedTreeMempoolValidateParams as MidnightTypedTreeMempoolValidateParams, } from "@morpho-org/midnight-sdk";
12
12
  export { AccrualPosition as MidnightAccrualPosition, Group as MidnightGroup, Market as MidnightMarket, MarketParams as MidnightMarketParams, Offer as MidnightOffer, Position as MidnightPosition, Tree as MidnightTree, } from "@morpho-org/midnight-sdk";
13
13
  export type { BlueActions, BlueTokenRequirementsParams, } from "./blue/index.js";
14
14
  export { MorphoBlue } from "./blue/index.js";
15
- export type { GetOffersDataParams as MidnightGetOffersDataParams, GetPositionDataParams as MidnightGetPositionDataParams, MakeLendParams as MidnightMakeLendParams, MakeOffersOutput as MidnightMakeOffersOutput, MakeOffersParams as MidnightMakeOffersParams, MarketActionParams as MidnightMarketActionParams, MidnightMakerTreeInput, MidnightPositionHealthParams, OffersData as MidnightOffersData, OfferValidationParams as MidnightOfferValidationParams, RedeemParams as MidnightRedeemParams, RepayWithdrawCollateralParams as MidnightRepayWithdrawCollateralParams, SupplyBlueMakeLendParams as MidnightSupplyBlueMakeLendParams, SupplyCollateralMakeBorrowParams as MidnightSupplyCollateralMakeBorrowParams, SupplyCollateralParams as MidnightSupplyCollateralParams, SupplyCollateralTakeBorrowParams as MidnightSupplyCollateralTakeBorrowParams, TakeBorrowParams as MidnightTakeBorrowParams, TakeLendParams as MidnightTakeLendParams, TakeRepayWithdrawCollateralParams as MidnightTakeRepayWithdrawCollateralParams, TakeWithdrawParams as MidnightTakeWithdrawParams, } from "./midnight/index.js";
15
+ export type { GetOffersDataParams as MidnightGetOffersDataParams, GetPositionDataParams as MidnightGetPositionDataParams, MakeLendParams as MidnightMakeLendParams, MakeOffersOutput as MidnightMakeOffersOutput, MakeOffersParams as MidnightMakeOffersParams, MarketActionParams as MidnightMarketActionParams, MidnightMakerTreeInput, MidnightPositionHealthParams, OffersData as MidnightOffersData, OfferValidationParams as MidnightOfferValidationParams, RedeemParams as MidnightRedeemParams, RepayWithdrawCollateralParams as MidnightRepayWithdrawCollateralParams, SupplyBlueMakeLendParams as MidnightSupplyBlueMakeLendParams, SupplyCollateralMakeBorrowParams as MidnightSupplyCollateralMakeBorrowParams, SupplyCollateralParams as MidnightSupplyCollateralParams, SupplyCollateralTakeBorrowParams as MidnightSupplyCollateralTakeBorrowParams, TakeBorrowParams as MidnightTakeBorrowParams, TakeLendParams as MidnightTakeLendParams, TakeRepayWithdrawCollateralParams as MidnightTakeRepayWithdrawCollateralParams, TakeWithdrawParams as MidnightTakeWithdrawParams, WithdrawCollateralParams as MidnightWithdrawCollateralParams, } from "./midnight/index.js";
16
16
  export { type MidnightActionOutput, type MidnightActions, type MidnightRequirementsParams, MorphoMidnight, } from "./midnight/index.js";
17
17
  export * from "./requirements/index.js";
18
18
  export { MorphoVaultV1 } from "./vaultV1/index.js";
@@ -14,11 +14,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.VaultV2BlueReallocationData = exports.MorphoVaultV2 = exports.MorphoVaultV1 = exports.MorphoMidnight = exports.MorphoBlue = exports.MidnightTree = exports.MidnightPosition = exports.MidnightOffer = exports.MidnightMarketParams = exports.MidnightMarket = exports.MidnightGroup = exports.MidnightAccrualPosition = exports.WrappedToken = exports.VaultV2MorphoVaultV1Adapter = exports.VaultV2MorphoMarketV1AdapterV2 = exports.VaultV2MorphoMarketV1Adapter = exports.VaultV2BluePublicAllocatorConfig = exports.VaultV2BlueMarketPublicAllocatorConfig = exports.VaultV2Adapter = exports.VaultV2 = exports.VaultUser = exports.VaultToken = exports.VaultMarketConfig = exports.VaultMarketAllocation = exports.VaultConfig = exports.Vault = exports.BlueUser = exports.Token = exports.BluePreLiquidationPosition = exports.BluePreLiquidationParams = exports.BluePosition = exports.BlueMarketParams = exports.BlueMarket = exports.Holding = exports.ExchangeRateWrappedToken = exports.Eip5267Domain = exports.ConstantWrappedToken = exports.AssetBalances = exports.AccrualVaultV2MorphoVaultV1Adapter = exports.AccrualVaultV2MorphoMarketV1AdapterV2 = exports.AccrualVaultV2MorphoMarketV1Adapter = exports.AccrualVaultV2 = exports.AccrualVault = exports.BlueAccrualPosition = void 0;
17
+ exports.VaultV2BlueReallocationData = exports.MorphoVaultV2 = exports.MorphoVaultV1 = exports.MorphoMidnight = exports.MorphoBlue = exports.MidnightTree = exports.MidnightPosition = exports.MidnightOffer = exports.MidnightMarketParams = exports.MidnightMarket = exports.MidnightGroup = exports.MidnightAccrualPosition = exports.WrappedToken = exports.VaultV2MorphoVaultV1Adapter = exports.VaultV2MorphoMarketV1AdapterV2 = exports.VaultV2MorphoMarketV1Adapter = exports.VaultV2MidnightAdapter = exports.VaultV2BluePublicAllocatorConfig = exports.VaultV2BlueMarketPublicAllocatorConfig = exports.VaultV2Adapter = exports.VaultV2 = exports.VaultUser = exports.VaultToken = exports.VaultMarketConfig = exports.VaultMarketAllocation = exports.VaultConfig = exports.Vault = exports.BlueUser = exports.Token = exports.BluePreLiquidationPosition = exports.BluePreLiquidationParams = exports.BluePosition = exports.BlueMarketParams = exports.BlueMarket = exports.Holding = exports.ExchangeRateWrappedToken = exports.Eip5267Domain = exports.ConstantWrappedToken = exports.AssetBalances = exports.AccrualVaultV2MorphoVaultV1Adapter = exports.AccrualVaultV2MorphoMarketV1AdapterV2 = exports.AccrualVaultV2MorphoMarketV1Adapter = exports.AccrualVaultV2MidnightAdapter = exports.AccrualVaultV2 = exports.AccrualVault = exports.BlueAccrualPosition = void 0;
18
18
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
19
19
  Object.defineProperty(exports, "BlueAccrualPosition", { enumerable: true, get: function () { return blue_sdk_1.AccrualPosition; } });
20
20
  Object.defineProperty(exports, "AccrualVault", { enumerable: true, get: function () { return blue_sdk_1.AccrualVault; } });
21
21
  Object.defineProperty(exports, "AccrualVaultV2", { enumerable: true, get: function () { return blue_sdk_1.AccrualVaultV2; } });
22
+ Object.defineProperty(exports, "AccrualVaultV2MidnightAdapter", { enumerable: true, get: function () { return blue_sdk_1.AccrualVaultV2MidnightAdapter; } });
22
23
  Object.defineProperty(exports, "AccrualVaultV2MorphoMarketV1Adapter", { enumerable: true, get: function () { return blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter; } });
23
24
  Object.defineProperty(exports, "AccrualVaultV2MorphoMarketV1AdapterV2", { enumerable: true, get: function () { return blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2; } });
24
25
  Object.defineProperty(exports, "AccrualVaultV2MorphoVaultV1Adapter", { enumerable: true, get: function () { return blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter; } });
@@ -46,6 +47,7 @@ Object.defineProperty(exports, "VaultV2", { enumerable: true, get: function () {
46
47
  Object.defineProperty(exports, "VaultV2Adapter", { enumerable: true, get: function () { return blue_sdk_1.VaultV2Adapter; } });
47
48
  Object.defineProperty(exports, "VaultV2BlueMarketPublicAllocatorConfig", { enumerable: true, get: function () { return blue_sdk_1.VaultV2BlueMarketPublicAllocatorConfig; } });
48
49
  Object.defineProperty(exports, "VaultV2BluePublicAllocatorConfig", { enumerable: true, get: function () { return blue_sdk_1.VaultV2BluePublicAllocatorConfig; } });
50
+ Object.defineProperty(exports, "VaultV2MidnightAdapter", { enumerable: true, get: function () { return blue_sdk_1.VaultV2MidnightAdapter; } });
49
51
  Object.defineProperty(exports, "VaultV2MorphoMarketV1Adapter", { enumerable: true, get: function () { return blue_sdk_1.VaultV2MorphoMarketV1Adapter; } });
50
52
  Object.defineProperty(exports, "VaultV2MorphoMarketV1AdapterV2", { enumerable: true, get: function () { return blue_sdk_1.VaultV2MorphoMarketV1AdapterV2; } });
51
53
  Object.defineProperty(exports, "VaultV2MorphoVaultV1Adapter", { enumerable: true, get: function () { return blue_sdk_1.VaultV2MorphoVaultV1Adapter; } });
@@ -1,8 +1,8 @@
1
1
  import { type AccrualPosition, type Market, type MidnightFetchParams } from "@morpho-org/midnight-sdk";
2
2
  import { type Address, type Hex } from "viem";
3
3
  import type { MorphoClientType } from "../../types/client.js";
4
- import { type MidnightCancelAndMakeAction, type MidnightGroupCancellation, type MidnightRedeemAction, type MidnightRepayWithdrawCollateralAction, type MidnightSupplyCollateralAction, type MidnightSupplyCollateralTakeBorrowAction, type MidnightTakeBorrowAction, type MidnightTakeLendAction, type MidnightTakeRepayWithdrawCollateralAction, type MidnightTakeWithdrawAction } from "../../types/index.js";
5
- import type { GetOffersDataParams, GetPositionDataParams, MakeLendParams, MakeOffersOutput, MakeOffersParams, MidnightActionOutput, OffersData, RedeemParams, RepayWithdrawCollateralParams, SupplyBlueMakeLendParams, SupplyCollateralMakeBorrowParams, SupplyCollateralParams, SupplyCollateralTakeBorrowParams, TakeBorrowParams, TakeLendParams, TakeRepayWithdrawCollateralParams, TakeWithdrawParams } from "./types.js";
4
+ import { type MidnightCancelAndMakeAction, type MidnightGroupCancellation, type MidnightRedeemAction, type MidnightRepayWithdrawCollateralAction, type MidnightSupplyCollateralAction, type MidnightSupplyCollateralTakeBorrowAction, type MidnightTakeBorrowAction, type MidnightTakeLendAction, type MidnightTakeRepayWithdrawCollateralAction, type MidnightTakeWithdrawAction, type MidnightWithdrawCollateralAction } from "../../types/index.js";
5
+ import type { GetOffersDataParams, GetPositionDataParams, MakeLendParams, MakeOffersOutput, MakeOffersParams, MidnightActionOutput, OffersData, RedeemParams, RepayWithdrawCollateralParams, SupplyBlueMakeLendParams, SupplyCollateralMakeBorrowParams, SupplyCollateralParams, SupplyCollateralTakeBorrowParams, TakeBorrowParams, TakeLendParams, TakeRepayWithdrawCollateralParams, TakeWithdrawParams, WithdrawCollateralParams } from "./types.js";
6
6
  /**
7
7
  * Entity methods exposed by `client.morpho.midnight(chainId)`.
8
8
  *
@@ -30,7 +30,7 @@ import type { GetOffersDataParams, GetPositionDataParams, MakeLendParams, MakeOf
30
30
  * const tx = output.buildTx();
31
31
  * ```
32
32
  */
33
- export type MidnightActions = Pick<MorphoMidnight, "getMarketData" | "getPositionData" | "getOffersData" | "takeLend" | "takeBorrow" | "takeWithdraw" | "supplyCollateralTakeBorrow" | "takeRepayWithdrawCollateral" | "supplyCollateral" | "makeLend" | "makeBorrow" | "supplyBlueMakeLend" | "makeWithdraw" | "makeRepay" | "supplyCollateralMakeBorrow" | "redeem" | "repayWithdrawCollateral" | "cancelOffers">;
33
+ export type MidnightActions = Pick<MorphoMidnight, "getMarketData" | "getPositionData" | "getOffersData" | "takeLend" | "takeBorrow" | "takeWithdraw" | "supplyCollateralTakeBorrow" | "takeRepayWithdrawCollateral" | "supplyCollateral" | "withdrawCollateral" | "makeLend" | "makeBorrow" | "supplyBlueMakeLend" | "makeWithdraw" | "makeRepay" | "supplyCollateralMakeBorrow" | "redeem" | "repayWithdrawCollateral" | "cancelOffers">;
34
34
  /**
35
35
  * Entity facade for Midnight fixed-rate action flows.
36
36
  *
@@ -126,7 +126,7 @@ export declare class MorphoMidnight {
126
126
  * @throws {MidnightOfferRatifierMismatchError} when an offer does not use its tree's ratifier.
127
127
  * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
128
128
  * @throws {MidnightCalldataEncodingError} when an offer cannot be ABI-encoded, such as an out-of-range integer, or `accountAddress` is not a well-formed address.
129
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
129
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
130
130
  * @throws {MidnightOfferExpiredError} when an offer expiry is not later than the pinned block timestamp.
131
131
  * @throws {MidnightOfferExpiryAfterMaturityError} when an offer expiry exceeds its market maturity.
132
132
  * @throws {MidnightOfferGroupConsumedError} when an offer group has no remaining capacity.
@@ -591,6 +591,52 @@ export declare class MorphoMidnight {
591
591
  * ```
592
592
  */
593
593
  takeRepayWithdrawCollateral(params: TakeRepayWithdrawCollateralParams): MidnightActionOutput<MidnightTakeRepayWithdrawCollateralAction>;
594
+ /**
595
+ * Withdraws collateral directly from Midnight without bundle authorization or token pulls.
596
+ *
597
+ * Uses the supplied position snapshot to resolve maxUint256 and check collateral health.
598
+ * No requirements or RPC reads are needed. The signing account must be accountAddress.
599
+ *
600
+ * @param params - Market, owner-bound position, collateral prices and withdrawal amount.
601
+ * @param params.accountAddress - Collateral owner. This account must send the transaction.
602
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
603
+ * @param params.positionData - Owner-bound position snapshot returned by getPositionData.
604
+ * @param params.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
605
+ * ORACLE_PRICE_SCALE; required when the position has debt, otherwise an empty array is safe.
606
+ * @param params.collateralIndex - Optional collateral index; defaults to 0n. Indexes follow the
607
+ * market's collateral parameters, which Midnight sorts by token address, not the order they were
608
+ * listed in when the market was built; check marketData.getCollateralByIndex(index).token.
609
+ * @param params.assets - Collateral assets to withdraw. maxUint256 resolves the whole balance of
610
+ * the selected collateral from positionData before building the transaction.
611
+ * @param params.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
612
+ * @returns Lazy handles for a direct Midnight withdrawal.
613
+ * @throws {ChainIdMismatchError} when the client or market targets another chain.
614
+ * @throws {MidnightCalldataEncodingError} when accountAddress is malformed or an input cannot be ABI-encoded.
615
+ * @throws {MidnightZeroAccountError} when accountAddress is zero.
616
+ * @throws {MidnightMarketAddressMismatchError} when marketData targets another Midnight deployment.
617
+ * @throws {MissingMarketPriceError} when debt is positive and held collateral has no supplied price.
618
+ * @throws {MarketIdMismatchError} when positionData belongs to another market.
619
+ * @throws {AccrualPositionUserMismatchError} when positionData belongs to another account.
620
+ * @throws {UnknownCollateralIndexError} when collateralIndex is not configured.
621
+ * @throws {NonPositiveInputError} when the resolved amount is not positive.
622
+ * @throws {InputExceedsMaxError} when assets exceeds uint128.
623
+ * @throws {WithdrawExceedsCollateralError} when assets exceeds the collateral balance.
624
+ * @throws {WithdrawMakesPositionUnhealthyError} when remaining collateral cannot safely cover debt.
625
+ * @throws {MidnightZeroReceiverError} when receiver is zero.
626
+ * @throws {MidnightContractReceiverError} when receiver cannot safely receive collateral.
627
+ * @example
628
+ * ```ts
629
+ * const output = midnight.withdrawCollateral({
630
+ * accountAddress: user,
631
+ * marketData,
632
+ * positionData,
633
+ * collateralPrices,
634
+ * assets: 1_000n,
635
+ * });
636
+ * const tx = output.buildTx();
637
+ * ```
638
+ */
639
+ withdrawCollateral(params: WithdrawCollateralParams): MidnightActionOutput<MidnightWithdrawCollateralAction>;
594
640
  /**
595
641
  * Prepares a direct collateral supply using a caller-provided market snapshot.
596
642
  *
@@ -684,7 +730,7 @@ export declare class MorphoMidnight {
684
730
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
685
731
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
686
732
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
687
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
733
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
688
734
  * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
689
735
  * @example
690
736
  * ```ts
@@ -746,7 +792,7 @@ export declare class MorphoMidnight {
746
792
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
747
793
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
748
794
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
749
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
795
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
750
796
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
751
797
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
752
798
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
@@ -847,8 +893,9 @@ export declare class MorphoMidnight {
847
893
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
848
894
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
849
895
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
850
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
851
- * @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
896
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
897
+ * @throws {MissingDeadSharesDataError} when the fetched `blueMarket` snapshot has no `deadSupplyShares`.
898
+ * @throws {InsufficientDeadSharesError} when `blueMarket` holds fewer than `MIN_DEAD_SHARES` supply shares at `DEAD_ADDRESS`.
852
899
  * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price (checked at preparation time only).
853
900
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
854
901
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
@@ -922,7 +969,7 @@ export declare class MorphoMidnight {
922
969
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
923
970
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
924
971
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
925
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
972
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
926
973
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
927
974
  * (not thrown when `validation` is `false`).
928
975
  * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
@@ -996,7 +1043,7 @@ export declare class MorphoMidnight {
996
1043
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
997
1044
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
998
1045
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
999
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1046
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1000
1047
  * @throws {MidnightMempoolValidationError} when the Midnight mempool API rejects the offer tree
1001
1048
  * (not thrown when `validation` is `false`).
1002
1049
  * @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer uses another loan token.
@@ -1081,7 +1128,7 @@ export declare class MorphoMidnight {
1081
1128
  * @throws {MidnightMarketLltvNotEnabledError} when an uncreated market uses a disabled LLTV.
1082
1129
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1083
1130
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1084
- * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1131
+ * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1085
1132
  * @throws {MarketIdMismatchError} when an offer targets another market than `collateral.market`, including a `collateral.market` on another chain or Midnight deployment.
1086
1133
  * @throws {EmptyMidnightCollateralSuppliesError} when a collateral market has no collateral supplies.
1087
1134
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.