@morpho-org/morpho-sdk 10.5.0 → 10.6.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 (192) hide show
  1. package/README.md +44 -1
  2. package/lib/cjs/abis.d.ts +794 -1
  3. package/lib/cjs/abis.js +815 -1
  4. package/lib/cjs/actions/blue/close.d.ts +169 -0
  5. package/lib/cjs/actions/blue/close.js +270 -0
  6. package/lib/cjs/actions/blue/common.js +2 -2
  7. package/lib/cjs/actions/blue/delever.d.ts +156 -0
  8. package/lib/cjs/actions/blue/delever.js +223 -0
  9. package/lib/cjs/actions/blue/index.d.ts +3 -0
  10. package/lib/cjs/actions/blue/index.js +3 -0
  11. package/lib/cjs/actions/blue/lever.d.ts +184 -0
  12. package/lib/cjs/actions/blue/lever.js +272 -0
  13. package/lib/cjs/actions/blue/leverageIntent.d.ts +65 -0
  14. package/lib/cjs/actions/blue/leverageIntent.js +103 -0
  15. package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  16. package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.js +59 -0
  17. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  18. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.js +193 -0
  19. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  20. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.js +66 -0
  21. package/lib/cjs/actions/requirements/blue/index.d.ts +3 -0
  22. package/lib/cjs/actions/requirements/blue/index.js +17 -0
  23. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  24. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
  25. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +11 -6
  26. package/lib/cjs/actions/requirements/getRequirementsApproval.js +29 -5
  27. package/lib/cjs/addresses.d.ts +1 -1
  28. package/lib/cjs/addresses.js +6 -1
  29. package/lib/cjs/blue/abis.d.ts +1 -1
  30. package/lib/cjs/blue/abis.js +5 -1
  31. package/lib/cjs/blue/addresses.d.ts +1 -1
  32. package/lib/cjs/blue/addresses.js +6 -1
  33. package/lib/cjs/blue/entities.d.ts +4 -4
  34. package/lib/cjs/blue/entities.js +3 -1
  35. package/lib/cjs/blue/errors.d.ts +2 -2
  36. package/lib/cjs/blue/errors.js +5 -1
  37. package/lib/cjs/blue/fetch.d.ts +2 -2
  38. package/lib/cjs/blue/fetch.js +3 -1
  39. package/lib/cjs/blue/utils.d.ts +1 -1
  40. package/lib/cjs/blue/utils.js +2 -1
  41. package/lib/cjs/constants.d.ts +1 -1
  42. package/lib/cjs/constants.js +6 -2
  43. package/lib/cjs/entities/blue/blue.d.ts +486 -2
  44. package/lib/cjs/entities/blue/blue.js +529 -34
  45. package/lib/cjs/entities/index.d.ts +5 -5
  46. package/lib/cjs/entities/index.js +3 -1
  47. package/lib/cjs/entities/requirements/assertContractCode.d.ts +0 -23
  48. package/lib/cjs/entities/requirements/assertContractCode.js +3 -28
  49. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +34 -8
  50. package/lib/cjs/entities/vaultV2/vaultV2.js +39 -1
  51. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +120 -2
  52. package/lib/cjs/entities/vaultV2BlueReallocationData.js +232 -4
  53. package/lib/cjs/errors.d.ts +4 -4
  54. package/lib/cjs/errors.js +7 -5
  55. package/lib/cjs/fetch.d.ts +2 -2
  56. package/lib/cjs/fetch.js +3 -1
  57. package/lib/cjs/helpers/constant.d.ts +34 -0
  58. package/lib/cjs/helpers/constant.js +35 -1
  59. package/lib/cjs/helpers/deadShares.js +3 -0
  60. package/lib/cjs/helpers/getZeroExLeverageBundle.d.ts +13 -0
  61. package/lib/cjs/helpers/getZeroExLeverageBundle.js +27 -0
  62. package/lib/cjs/helpers/index.d.ts +4 -1
  63. package/lib/cjs/helpers/index.js +28 -1
  64. package/lib/cjs/helpers/leverage/index.d.ts +1 -0
  65. package/lib/cjs/helpers/leverage/index.js +11 -0
  66. package/lib/cjs/helpers/leverage/limits.d.ts +472 -0
  67. package/lib/cjs/helpers/leverage/limits.js +715 -0
  68. package/lib/cjs/helpers/leverage/positionMarket.d.ts +17 -0
  69. package/lib/cjs/helpers/leverage/positionMarket.js +28 -0
  70. package/lib/cjs/helpers/leverage/reallocations.d.ts +159 -0
  71. package/lib/cjs/helpers/leverage/reallocations.js +276 -0
  72. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  73. package/lib/cjs/helpers/validateRequirementSpender.js +4 -0
  74. package/lib/cjs/helpers/zeroExQuote.d.ts +250 -0
  75. package/lib/cjs/helpers/zeroExQuote.js +763 -0
  76. package/lib/cjs/index.d.ts +1 -0
  77. package/lib/cjs/index.js +5 -2
  78. package/lib/cjs/midnight/errors.d.ts +2 -1
  79. package/lib/cjs/midnight/errors.js +5 -4
  80. package/lib/cjs/reads/assertContractCode.d.ts +25 -0
  81. package/lib/cjs/reads/assertContractCode.js +30 -0
  82. package/lib/cjs/reads/fetchZeroExQuote.d.ts +123 -0
  83. package/lib/cjs/reads/fetchZeroExQuote.js +330 -0
  84. package/lib/cjs/types/action.d.ts +130 -1
  85. package/lib/cjs/types/error.d.ts +59 -0
  86. package/lib/cjs/types/error.js +82 -3
  87. package/lib/cjs/types/index.d.ts +2 -0
  88. package/lib/cjs/types/index.js +2 -0
  89. package/lib/cjs/types/leverageError.d.ts +1552 -0
  90. package/lib/cjs/types/leverageError.js +1711 -0
  91. package/lib/cjs/types/zeroEx.d.ts +171 -0
  92. package/lib/cjs/types/zeroEx.js +2 -0
  93. package/lib/cjs/utils.d.ts +2 -2
  94. package/lib/cjs/utils.js +4 -2
  95. package/lib/cjs/version.d.ts +1 -1
  96. package/lib/cjs/version.js +1 -1
  97. package/lib/esm/abis.d.ts +794 -1
  98. package/lib/esm/abis.js +810 -1
  99. package/lib/esm/actions/blue/close.d.ts +169 -0
  100. package/lib/esm/actions/blue/close.js +266 -0
  101. package/lib/esm/actions/blue/common.js +3 -3
  102. package/lib/esm/actions/blue/delever.d.ts +156 -0
  103. package/lib/esm/actions/blue/delever.js +219 -0
  104. package/lib/esm/actions/blue/index.d.ts +3 -0
  105. package/lib/esm/actions/blue/index.js +3 -0
  106. package/lib/esm/actions/blue/lever.d.ts +184 -0
  107. package/lib/esm/actions/blue/lever.js +268 -0
  108. package/lib/esm/actions/blue/leverageIntent.d.ts +65 -0
  109. package/lib/esm/actions/blue/leverageIntent.js +96 -0
  110. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  111. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.js +55 -0
  112. package/lib/esm/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  113. package/lib/esm/actions/requirements/blue/getLeverageRequirements.js +189 -0
  114. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  115. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.js +62 -0
  116. package/lib/esm/actions/requirements/blue/index.d.ts +3 -0
  117. package/lib/esm/actions/requirements/blue/index.js +3 -0
  118. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  119. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
  120. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +11 -6
  121. package/lib/esm/actions/requirements/getRequirementsApproval.js +29 -5
  122. package/lib/esm/addresses.d.ts +1 -1
  123. package/lib/esm/addresses.js +1 -1
  124. package/lib/esm/blue/abis.d.ts +1 -1
  125. package/lib/esm/blue/abis.js +1 -1
  126. package/lib/esm/blue/addresses.d.ts +1 -1
  127. package/lib/esm/blue/addresses.js +1 -1
  128. package/lib/esm/blue/entities.d.ts +4 -4
  129. package/lib/esm/blue/entities.js +2 -2
  130. package/lib/esm/blue/errors.d.ts +2 -2
  131. package/lib/esm/blue/errors.js +2 -2
  132. package/lib/esm/blue/fetch.d.ts +2 -2
  133. package/lib/esm/blue/fetch.js +2 -2
  134. package/lib/esm/blue/utils.d.ts +1 -1
  135. package/lib/esm/blue/utils.js +1 -1
  136. package/lib/esm/constants.d.ts +1 -1
  137. package/lib/esm/constants.js +1 -1
  138. package/lib/esm/entities/blue/blue.d.ts +486 -2
  139. package/lib/esm/entities/blue/blue.js +501 -6
  140. package/lib/esm/entities/index.d.ts +5 -5
  141. package/lib/esm/entities/index.js +2 -2
  142. package/lib/esm/entities/requirements/assertContractCode.d.ts +0 -23
  143. package/lib/esm/entities/requirements/assertContractCode.js +1 -25
  144. package/lib/esm/entities/vaultV2/vaultV2.d.ts +34 -8
  145. package/lib/esm/entities/vaultV2/vaultV2.js +40 -2
  146. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +120 -2
  147. package/lib/esm/entities/vaultV2BlueReallocationData.js +233 -5
  148. package/lib/esm/errors.d.ts +4 -4
  149. package/lib/esm/errors.js +4 -4
  150. package/lib/esm/fetch.d.ts +2 -2
  151. package/lib/esm/fetch.js +2 -2
  152. package/lib/esm/helpers/constant.d.ts +34 -0
  153. package/lib/esm/helpers/constant.js +34 -0
  154. package/lib/esm/helpers/deadShares.js +4 -1
  155. package/lib/esm/helpers/getZeroExLeverageBundle.d.ts +13 -0
  156. package/lib/esm/helpers/getZeroExLeverageBundle.js +23 -0
  157. package/lib/esm/helpers/index.d.ts +4 -1
  158. package/lib/esm/helpers/index.js +4 -1
  159. package/lib/esm/helpers/leverage/index.d.ts +1 -0
  160. package/lib/esm/helpers/leverage/index.js +1 -0
  161. package/lib/esm/helpers/leverage/limits.d.ts +472 -0
  162. package/lib/esm/helpers/leverage/limits.js +705 -0
  163. package/lib/esm/helpers/leverage/positionMarket.d.ts +17 -0
  164. package/lib/esm/helpers/leverage/positionMarket.js +24 -0
  165. package/lib/esm/helpers/leverage/reallocations.d.ts +159 -0
  166. package/lib/esm/helpers/leverage/reallocations.js +271 -0
  167. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  168. package/lib/esm/helpers/validateRequirementSpender.js +5 -1
  169. package/lib/esm/helpers/zeroExQuote.d.ts +250 -0
  170. package/lib/esm/helpers/zeroExQuote.js +754 -0
  171. package/lib/esm/index.d.ts +1 -0
  172. package/lib/esm/index.js +1 -0
  173. package/lib/esm/midnight/errors.d.ts +2 -1
  174. package/lib/esm/midnight/errors.js +2 -1
  175. package/lib/esm/reads/assertContractCode.d.ts +25 -0
  176. package/lib/esm/reads/assertContractCode.js +26 -0
  177. package/lib/esm/reads/fetchZeroExQuote.d.ts +123 -0
  178. package/lib/esm/reads/fetchZeroExQuote.js +326 -0
  179. package/lib/esm/types/action.d.ts +130 -1
  180. package/lib/esm/types/error.d.ts +59 -0
  181. package/lib/esm/types/error.js +76 -0
  182. package/lib/esm/types/index.d.ts +2 -0
  183. package/lib/esm/types/index.js +2 -0
  184. package/lib/esm/types/leverageError.d.ts +1552 -0
  185. package/lib/esm/types/leverageError.js +1660 -0
  186. package/lib/esm/types/zeroEx.d.ts +171 -0
  187. package/lib/esm/types/zeroEx.js +1 -0
  188. package/lib/esm/utils.d.ts +2 -2
  189. package/lib/esm/utils.js +2 -2
  190. package/lib/esm/version.d.ts +1 -1
  191. package/lib/esm/version.js +1 -1
  192. package/package.json +7 -7
@@ -67,7 +67,9 @@ export interface VaultV2Actions {
67
67
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
68
68
  * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
69
69
  * @throws {NativeAmountOnNonWNativeVaultError} when native funding targets a non-wNative vault.
70
- * @throws {InputExceedsMaxError} when the deadline exceeds seven days after creation or funding or the deadline exceeds uint256.
70
+ * @throws {InputExceedsMaxError} when the deadline exceeds seven days after creation or funding or
71
+ * the deadline exceeds uint256, or when the vault's liquidity adapter is a Midnight adapter (it
72
+ * cannot receive vault allocations, so no deposit fits and `max` is `0n`).
71
73
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
72
74
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
73
75
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -149,7 +151,9 @@ export interface VaultV2Actions {
149
151
  * @throws {NonPositiveInputError} when `amount` or the computed required share amount is not positive.
150
152
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
151
153
  * at any `getRequirements()` call.
152
- * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation.
154
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation,
155
+ * or when the vault's liquidity adapter is a Midnight adapter and `amount` exceeds the vault's
156
+ * idle assets plus what the adapter can withdraw from the liquidity market.
153
157
  * @throws {NegativeInputError} when `referralFeePct` or `slippageTolerance` is negative.
154
158
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
155
159
  * @throws {MidnightReferralFeePctExceededError} when the referral fee is above 10% but below WAD.
@@ -216,7 +220,25 @@ export interface VaultV2Actions {
216
220
  * @throws {NonPositiveInputError} when `shares` is not positive.
217
221
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
218
222
  * requirement resolution.
219
- * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
223
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256, or from
224
+ * `getRequirements()` when the vault's liquidity adapter is a Midnight adapter and `shares`
225
+ * are worth more than the vault's idle assets plus what the adapter can withdraw from the
226
+ * liquidity market.
227
+ * @throws {UnknownBlueFactory} from `getRequirements()` when the configured chain has no VaultV2 factory.
228
+ * @throws {UnknownBlueOfFactory} from `getRequirements()` when the vault is not a VaultV2 from the
229
+ * configured factory.
230
+ * @throws {UnsupportedBlueVaultV2AdapterError} from `getRequirements()` when the vault or one of its
231
+ * adapters uses an unsupported adapter class.
232
+ * @throws {UnsupportedBlueMarketIrmError} from `getRequirements()` when the vault's liquidity adapter
233
+ * is a Midnight adapter and accrual projects an underlying market with positive debt that uses an
234
+ * unsupported IRM.
235
+ * @throws {UnknownBlueMarketAllocationError} from `getRequirements()` when the vault's liquidity
236
+ * adapter is a Midnight adapter and accrual meets a nested Vault V1 withdraw queue market without
237
+ * allocation data.
238
+ * @throws {InvalidMidnightPositionLossFactorError} from `getRequirements()` when the vault's liquidity
239
+ * adapter is a Midnight adapter and accrual meets a market loss factor below a position's.
240
+ * @throws {InvalidMidnightPositionAccrualStateError} from `getRequirements()` when the vault's
241
+ * liquidity adapter is a Midnight adapter and accrual meets invalid Midnight position inputs.
220
242
  * @throws {NegativeInputError} when `referralFeePct` is negative.
221
243
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
222
244
  * @throws {MidnightReferralFeePctExceededError} when the referral fee is above 10% but below WAD.
@@ -225,7 +247,7 @@ export interface VaultV2Actions {
225
247
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
226
248
  * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
227
249
  * contract has no code at its registered address.
228
- * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, `eth_chainId`, or
250
+ * @throws {viem.BaseError} from `getRequirements()` when a vault-state, allowance, nonce, `eth_chainId`, or
229
251
  * `eth_getCode` read fails.
230
252
  * @throws {UnknownTokenError} from `getRequirements()` when the share token fetched by
231
253
  * `getData()` has unusable decimals.
@@ -303,9 +325,11 @@ export interface VaultV2Actions {
303
325
  * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256`.
304
326
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
305
327
  * requirement resolution.
306
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter.
328
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter, including
329
+ * a vault that mixes Blue and Midnight adapters.
307
330
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
308
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
331
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
332
+ * including a Midnight adapter.
309
333
  * @throws {InKindRedeemCoverageError} when the deduplicated list cannot cover the exit.
310
334
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
311
335
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
@@ -431,9 +455,11 @@ export interface VaultV2Actions {
431
455
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
432
456
  * requirement resolution.
433
457
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
434
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter.
458
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter,
459
+ * including a vault that mixes Blue and Midnight adapters.
435
460
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
436
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
461
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
462
+ * including a Midnight adapter.
437
463
  * @throws {VaultV2UnsupportedLiquidityAdapterError} when the vault routes liquidity through
438
464
  * another adapter.
439
465
  * @throws {VaultV2UndecodableLiquidityDataError} when the vault's `liquidityData` does not decode
@@ -14,7 +14,7 @@ import { computeVaultMaxShareAllowance, computeVaultMaxSharePrice, validateChain
14
14
  import { resolveTransactionMetadata } from "../../helpers/metadata.js";
15
15
  import { parseUint256 } from "../../helpers/parse.js";
16
16
  import { validateNativeVaultAsset, validateReferenceTime, validateVaultDepositDeadline, } from "../../helpers/validate.js";
17
- import { ExpiredDeadlineError, NonPositiveInputError, VaultAddressMismatchError, } from "../../types/index.js";
17
+ import { ExpiredDeadlineError, InputExceedsMaxError, NonPositiveInputError, VaultAddressMismatchError, } from "../../types/index.js";
18
18
  import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
19
19
  import { getParsedBundlesTokenRequirements, parseGetBundlesTokenRequirements, } from "../requirements/getBundlesTokenRequirements.js";
20
20
  import { getParsedVaultBundlesSharesRequirements, parseVaultBundlesSharesRequirements, } from "../requirements/getVaultBundlesSharesRequirements.js";
@@ -23,6 +23,16 @@ import { getVaultV2InKindRedeemRequirements } from "../requirements/getVaultV2In
23
23
  import { validateNativeRequirements } from "../requirements/validateNativeRequirements.js";
24
24
  import { computeVaultV2ForceWithdrawQuote } from "./forceWithdrawQuote.js";
25
25
  import { computeVaultV2InKindRedeemQuote } from "./inKindRedeemQuote.js";
26
+ /**
27
+ * Midnight adapters revert vault-initiated `allocate` (`SelfAllocationOnly`), so a vault routing
28
+ * liquidity through one accepts no deposit. Exits are served from idle assets plus what the adapter's
29
+ * `withdrawToVault` path can withdraw from the liquidity market.
30
+ */
31
+ const isMidnightLiquidityAdapter = (vaultData) => vaultData.accrualLiquidityAdapter?.type === "VaultV2MidnightAdapter";
32
+ /** Idle assets plus what the Midnight liquidity adapter can withdraw to the vault onchain. */
33
+ const midnightWithdrawLiquidity = (vaultData) => vaultData.assetBalance +
34
+ (vaultData.accrualLiquidityAdapter?.maxWithdraw(vaultData.liquidityData)
35
+ .value ?? 0n);
26
36
  /** Binds a viem client to a Vault V2 vault's action builders. */
27
37
  export class MorphoVaultV2 {
28
38
  client;
@@ -91,6 +101,13 @@ export class MorphoVaultV2 {
91
101
  if (funding.value > 0n) {
92
102
  validateNativeVaultAsset(this.chainId, vaultAsset);
93
103
  }
104
+ if (isMidnightLiquidityAdapter(vaultData)) {
105
+ throw new InputExceedsMaxError({
106
+ field: funding.value > 0n ? "nativeAmount" : "amount",
107
+ value: funding.assets,
108
+ max: 0n,
109
+ });
110
+ }
94
111
  const referralFeeAssets = getBundlesReferralFeeAssets(funding.assets, common.referralFeePct);
95
112
  // Bound forward accrual before deriving the deposit price protection.
96
113
  validateVaultDepositDeadline(deadline, { now: createdAt });
@@ -197,6 +214,14 @@ export class MorphoVaultV2 {
197
214
  throw new NonPositiveInputError("amount", amount);
198
215
  }
199
216
  const parsedAmount = parseUint256("amount", amount);
217
+ if (isMidnightLiquidityAdapter(vaultData) &&
218
+ amount > midnightWithdrawLiquidity(vaultData)) {
219
+ throw new InputExceedsMaxError({
220
+ field: "amount",
221
+ value: amount,
222
+ max: midnightWithdrawLiquidity(vaultData),
223
+ });
224
+ }
200
225
  const createdAt = suppliedNow ?? Time.timestamp();
201
226
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
202
227
  if (deadline <= createdAt) {
@@ -306,8 +331,21 @@ export class MorphoVaultV2 {
306
331
  }
307
332
  const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
308
333
  await this.assertWriteTargets(["bundles.vaultBundlesV1"], chainCheck);
334
+ const vaultData = await this.getDataWithChainCheck(chainCheck);
335
+ if (isMidnightLiquidityAdapter(vaultData)) {
336
+ // Onchain redeem accrues interest before converting shares to assets.
337
+ const { vault: accrued } = vaultData.accrueInterest(now);
338
+ const liquidity = midnightWithdrawLiquidity(accrued);
339
+ if (accrued.toAssets(shares) > liquidity) {
340
+ throw new InputExceedsMaxError({
341
+ field: "shares",
342
+ value: shares,
343
+ max: accrued.toShares(liquidity),
344
+ });
345
+ }
346
+ }
309
347
  return getParsedVaultBundlesSharesRequirements({ viemClient: this.client.viemClient, chainCheck }, parseVaultBundlesSharesRequirements(this.client.viemClient, {
310
- vaultData: await this.getDataWithChainCheck(chainCheck),
348
+ vaultData,
311
349
  version: "vaultV2",
312
350
  owner: userAddress,
313
351
  chainId: this.chainId,
@@ -56,7 +56,8 @@ export interface InputVaultV2BlueReallocationData {
56
56
  /**
57
57
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
58
58
  *
59
- * Constructor inputs are cloned. Every simulated reallocation returns a new
59
+ * Constructor inputs are cloned, except read-only Midnight adapter snapshots, which are
60
+ * shared by reference. Every simulated reallocation returns a new
60
61
  * instance. Planning keeps the transaction-scoped `firstTotalAssets`
61
62
  * denominator outside the durable snapshot while applying reallocations in
62
63
  * contract order. Penalty donations update simulated vault accounting but are
@@ -133,7 +134,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
133
134
  /**
134
135
  * Clones the complete simulation snapshot.
135
136
  *
136
- * @returns A deep clone of this simulation state.
137
+ * @returns A deep clone of this simulation state; read-only Midnight adapter snapshots are shared by reference.
137
138
  * @example
138
139
  * ```ts
139
140
  * import { markets } from "@morpho-org/morpho-test";
@@ -577,6 +578,123 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
577
578
  * ```
578
579
  */
579
580
  getPublicReallocationLiquidity(marketId: MarketId, options?: VaultV2BluePublicAllocatorOptions): bigint;
581
+ /**
582
+ * Replays `reallocations` toward `marketId` in order, as one transaction at `timestamp`, and
583
+ * returns the first leg that leaves a target cap id over its cap, with the interest reserve the
584
+ * planner keeps through `timestamp + capAccrualBuffer`, or a market-sourced leg whose source market's
585
+ * liquidity or source adapter's supply no longer covers its amount (for example, replayed against a newer snapshot). Idle legs are checked against
586
+ * the caps only. A plan from
587
+ * `computeVaultV2BlueReallocations` fits; a leg cut below the amount the planner chose may not,
588
+ * because a shared relative cap can require a larger move whose penalty donation lifts the cap.
589
+ *
590
+ * @param params - Replay inputs.
591
+ * @param params.marketId - Target Blue market id.
592
+ * @param params.reallocations - Legs to replay, in execution order.
593
+ * @param params.timestamp - Optional timestamp, as given to the planner.
594
+ * @param params.capAccrualBuffer - Optional cap-accrual buffer, as given to the planner.
595
+ * @returns The first leg outside its caps or not funded by its source market, or `undefined` when every
596
+ * leg fits.
597
+ * @throws {UnsupportedBlueMarketIrmError} when a Blue market the replay accrues has positive debt and an unsupported
598
+ * IRM: the target, a source, or, on a vault's first allocation, any other market the vault holds.
599
+ * @throws {NegativeInputError} when `capAccrualBuffer` is negative.
600
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
601
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
602
+ * @throws {UnknownReallocationAdapterError} when a leg's adapter is absent.
603
+ * @throws {UnknownReallocationAllocationError} when a leg's cap or allocation state is absent.
604
+ * @example
605
+ * ```ts
606
+ * // `client` is a mainnet viem client extended with `morphoViemExtension()`, and
607
+ * // `market = client.morpho.blue(marketParams, mainnet.id)` for a USDC market Keyrock's vault supplies.
608
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
609
+ * const block = await client.getBlock();
610
+ * const data = await market.getVaultV2BlueReallocationData({
611
+ * vaultAddresses: [keyrockUsdcVaultV2],
612
+ * block: { number: block.number, timestamp: block.timestamp },
613
+ * });
614
+ * const { reallocations } = data.computeVaultV2BlueReallocations(
615
+ * marketParams.id,
616
+ * { timestamp: block.timestamp, operation: { type: "borrow", amount: 1_000_000n } },
617
+ * );
618
+ * const outside = data.findVaultV2BlueReallocationOutsideCaps({
619
+ * marketId: marketParams.id,
620
+ * reallocations,
621
+ * timestamp: block.timestamp,
622
+ * });
623
+ * // outside === undefined: the planner's own plan fits every cap.
624
+ * ```
625
+ */
626
+ findVaultV2BlueReallocationOutsideCaps({ marketId, reallocations, timestamp, capAccrualBuffer, }: Pick<VaultV2BluePublicAllocatorOptions, "timestamp" | "capAccrualBuffer"> & {
627
+ readonly marketId: MarketId;
628
+ readonly reallocations: readonly VaultV2BlueReallocation[];
629
+ }): VaultV2BlueReallocation | undefined;
630
+ /**
631
+ * Replays `reallocations` toward `marketId` once, as in
632
+ * `findVaultV2BlueReallocationOutsideCaps`, then returns the first of `amounts` at which
633
+ * `reallocation`, executed next, stays within its target vault's caps. It checks the vault caps and the interest
634
+ * reserve only, not the allocator's own max-in, which the planner applies when it sizes a leg, so only try amounts at
635
+ * or below a planned leg's `assets`. Amounts outside the positive `uint128`
636
+ * range are skipped, since no reallocation can move them, and so are amounts the leg's source cannot
637
+ * fund: above the source market's liquidity or the source adapter's supply in it, or, from idle, above the vault's idle balance left by
638
+ * the earlier legs, not counting their penalty donations, as the planner counts it. Only `reallocation` is probed at
639
+ * each amount, so a search over many amounts costs one replay of the earlier legs.
640
+ *
641
+ * @param params - Search inputs.
642
+ * @param params.marketId - Target Blue market id.
643
+ * @param params.reallocations - Earlier legs, in execution order.
644
+ * @param params.reallocation - Leg to size; its `assets` is ignored.
645
+ * @param params.amounts - Candidate amounts, tried in order; non-positive or above-`uint128` ones are skipped.
646
+ * @param params.timestamp - Optional timestamp, as given to the planner.
647
+ * @param params.capAccrualBuffer - Optional cap-accrual buffer, as given to the planner.
648
+ * @returns The first amount that fits, or `undefined` when none does or an earlier leg is outside its
649
+ * caps, outside the positive `uint128` range, or above what its source can fund.
650
+ * @throws {UnsupportedBlueMarketIrmError} when a Blue market the replay accrues has positive debt and an unsupported
651
+ * IRM: the target, a source, or, on a vault's first allocation, any other market the vault holds.
652
+ * @throws {NegativeInputError} when `capAccrualBuffer` is negative.
653
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
654
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
655
+ * @throws {UnknownReallocationAdapterError} when a leg's adapter is absent.
656
+ * @throws {UnknownReallocationAllocationError} when a leg's cap or allocation state is absent.
657
+ * @example
658
+ * ```ts
659
+ * // `client` is a mainnet viem client extended with `morphoViemExtension()`, and
660
+ * // `market = client.morpho.blue(marketParams, mainnet.id)` for a USDC market Keyrock's vault supplies.
661
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
662
+ * const block = await client.getBlock();
663
+ * const data = await market.getVaultV2BlueReallocationData({
664
+ * vaultAddresses: [keyrockUsdcVaultV2],
665
+ * block: { number: block.number, timestamp: block.timestamp },
666
+ * });
667
+ * const {
668
+ * reallocations: [leg],
669
+ * } = data.computeVaultV2BlueReallocations(marketParams.id, {
670
+ * timestamp: block.timestamp,
671
+ * operation: { type: "borrow", amount: 1_000_000n },
672
+ * });
673
+ * // No leg: the market funds the borrow without a reallocation, so there is nothing to resize.
674
+ * if (leg == null) return;
675
+ * const assets = data.findVaultV2BlueReallocationFittingAssets({
676
+ * marketId: marketParams.id,
677
+ * reallocations: [],
678
+ * reallocation: leg,
679
+ * amounts: [leg.assets / 2n, leg.assets],
680
+ * timestamp: block.timestamp,
681
+ * });
682
+ * // assets === leg.assets / 2n when that smaller move fits the vault caps, else leg.assets.
683
+ * ```
684
+ */
685
+ findVaultV2BlueReallocationFittingAssets({ marketId, reallocations, reallocation, amounts, timestamp, capAccrualBuffer, }: Pick<VaultV2BluePublicAllocatorOptions, "timestamp" | "capAccrualBuffer"> & {
686
+ readonly marketId: MarketId;
687
+ readonly reallocations: readonly VaultV2BlueReallocation[];
688
+ readonly reallocation: VaultV2BlueReallocation;
689
+ readonly amounts: Iterable<bigint>;
690
+ }): bigint | undefined;
691
+ /**
692
+ * Starts a cap replay toward `marketId` at `timestamp`. Each call of the returned function prepares
693
+ * the next leg: `funds(assets)` checks that `assets` is a positive `uint128` its source holds
694
+ * (market liquidity capped at the source adapter's supply, or idle without penalty donations), `fits(assets)` probes the leg at a positive `assets`, at the replay timestamp, against its target caps and
695
+ * the planner's interest reserve, and `apply()` executes it at its own amount so later legs see it.
696
+ */
697
+ private createCapReplay;
580
698
  /**
581
699
  * Computes borrow liquidity to a target utilization, including friendly
582
700
  * Vault V2 public reallocations. Market/vault state and returned post-state
@@ -1,6 +1,6 @@
1
1
  import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, Market, MarketUtils, MathLib, UnknownDataError, UnsupportedVaultV2AdapterError, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2BluePublicAllocatorConfigUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
2
2
  import { _try, bigIntComparator } from "@morpho-org/morpho-ts";
3
- import { isAddressEqual } from "viem";
3
+ import { isAddressEqual, maxUint128 } from "viem";
4
4
  import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1ReferralFeeAssets, } from "../actions/blue/common.js";
5
5
  import { DEFAULT_SUPPLY_TARGET_UTILIZATION } from "../helpers/constant.js";
6
6
  import { resolveMaxPenalty } from "../helpers/reallocationPenalty.js";
@@ -80,6 +80,9 @@ const cloneAccrualVault = (vault, markets) => new AccrualVault({
80
80
  position: clonePosition(position, markets),
81
81
  })));
82
82
  const cloneAdapter = (adapter, markets) => {
83
+ if (adapter.type === "VaultV2MidnightAdapter") {
84
+ return adapter;
85
+ }
83
86
  const base = {
84
87
  address: adapter.address,
85
88
  parentVault: adapter.parentVault,
@@ -131,7 +134,8 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
131
134
  /**
132
135
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
133
136
  *
134
- * Constructor inputs are cloned. Every simulated reallocation returns a new
137
+ * Constructor inputs are cloned, except read-only Midnight adapter snapshots, which are
138
+ * shared by reference. Every simulated reallocation returns a new
135
139
  * instance. Planning keeps the transaction-scoped `firstTotalAssets`
136
140
  * denominator outside the durable snapshot while applying reallocations in
137
141
  * contract order. Penalty donations update simulated vault accounting but are
@@ -262,7 +266,7 @@ export class VaultV2BlueReallocationData {
262
266
  /**
263
267
  * Clones the complete simulation snapshot.
264
268
  *
265
- * @returns A deep clone of this simulation state.
269
+ * @returns A deep clone of this simulation state; read-only Midnight adapter snapshots are shared by reference.
266
270
  * @example
267
271
  * ```ts
268
272
  * import { markets } from "@morpho-org/morpho-test";
@@ -983,6 +987,230 @@ export class VaultV2BlueReallocationData {
983
987
  })
984
988
  .reallocations.reduce((total, { assets }) => total + assets, 0n);
985
989
  }
990
+ /**
991
+ * Replays `reallocations` toward `marketId` in order, as one transaction at `timestamp`, and
992
+ * returns the first leg that leaves a target cap id over its cap, with the interest reserve the
993
+ * planner keeps through `timestamp + capAccrualBuffer`, or a market-sourced leg whose source market's
994
+ * liquidity or source adapter's supply no longer covers its amount (for example, replayed against a newer snapshot). Idle legs are checked against
995
+ * the caps only. A plan from
996
+ * `computeVaultV2BlueReallocations` fits; a leg cut below the amount the planner chose may not,
997
+ * because a shared relative cap can require a larger move whose penalty donation lifts the cap.
998
+ *
999
+ * @param params - Replay inputs.
1000
+ * @param params.marketId - Target Blue market id.
1001
+ * @param params.reallocations - Legs to replay, in execution order.
1002
+ * @param params.timestamp - Optional timestamp, as given to the planner.
1003
+ * @param params.capAccrualBuffer - Optional cap-accrual buffer, as given to the planner.
1004
+ * @returns The first leg outside its caps or not funded by its source market, or `undefined` when every
1005
+ * leg fits.
1006
+ * @throws {UnsupportedBlueMarketIrmError} when a Blue market the replay accrues has positive debt and an unsupported
1007
+ * IRM: the target, a source, or, on a vault's first allocation, any other market the vault holds.
1008
+ * @throws {NegativeInputError} when `capAccrualBuffer` is negative.
1009
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
1010
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
1011
+ * @throws {UnknownReallocationAdapterError} when a leg's adapter is absent.
1012
+ * @throws {UnknownReallocationAllocationError} when a leg's cap or allocation state is absent.
1013
+ * @example
1014
+ * ```ts
1015
+ * // `client` is a mainnet viem client extended with `morphoViemExtension()`, and
1016
+ * // `market = client.morpho.blue(marketParams, mainnet.id)` for a USDC market Keyrock's vault supplies.
1017
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
1018
+ * const block = await client.getBlock();
1019
+ * const data = await market.getVaultV2BlueReallocationData({
1020
+ * vaultAddresses: [keyrockUsdcVaultV2],
1021
+ * block: { number: block.number, timestamp: block.timestamp },
1022
+ * });
1023
+ * const { reallocations } = data.computeVaultV2BlueReallocations(
1024
+ * marketParams.id,
1025
+ * { timestamp: block.timestamp, operation: { type: "borrow", amount: 1_000_000n } },
1026
+ * );
1027
+ * const outside = data.findVaultV2BlueReallocationOutsideCaps({
1028
+ * marketId: marketParams.id,
1029
+ * reallocations,
1030
+ * timestamp: block.timestamp,
1031
+ * });
1032
+ * // outside === undefined: the planner's own plan fits every cap.
1033
+ * ```
1034
+ */
1035
+ findVaultV2BlueReallocationOutsideCaps({ marketId, reallocations, timestamp, capAccrualBuffer, }) {
1036
+ const prepareLeg = this.createCapReplay({
1037
+ marketId,
1038
+ timestamp,
1039
+ capAccrualBuffer,
1040
+ });
1041
+ for (const reallocation of reallocations) {
1042
+ const leg = prepareLeg(reallocation);
1043
+ if ((reallocation.from.type === "market" &&
1044
+ !leg.funds(reallocation.assets)) ||
1045
+ !leg.fits(reallocation.assets)) {
1046
+ return reallocation;
1047
+ }
1048
+ leg.apply();
1049
+ }
1050
+ }
1051
+ /**
1052
+ * Replays `reallocations` toward `marketId` once, as in
1053
+ * `findVaultV2BlueReallocationOutsideCaps`, then returns the first of `amounts` at which
1054
+ * `reallocation`, executed next, stays within its target vault's caps. It checks the vault caps and the interest
1055
+ * reserve only, not the allocator's own max-in, which the planner applies when it sizes a leg, so only try amounts at
1056
+ * or below a planned leg's `assets`. Amounts outside the positive `uint128`
1057
+ * range are skipped, since no reallocation can move them, and so are amounts the leg's source cannot
1058
+ * fund: above the source market's liquidity or the source adapter's supply in it, or, from idle, above the vault's idle balance left by
1059
+ * the earlier legs, not counting their penalty donations, as the planner counts it. Only `reallocation` is probed at
1060
+ * each amount, so a search over many amounts costs one replay of the earlier legs.
1061
+ *
1062
+ * @param params - Search inputs.
1063
+ * @param params.marketId - Target Blue market id.
1064
+ * @param params.reallocations - Earlier legs, in execution order.
1065
+ * @param params.reallocation - Leg to size; its `assets` is ignored.
1066
+ * @param params.amounts - Candidate amounts, tried in order; non-positive or above-`uint128` ones are skipped.
1067
+ * @param params.timestamp - Optional timestamp, as given to the planner.
1068
+ * @param params.capAccrualBuffer - Optional cap-accrual buffer, as given to the planner.
1069
+ * @returns The first amount that fits, or `undefined` when none does or an earlier leg is outside its
1070
+ * caps, outside the positive `uint128` range, or above what its source can fund.
1071
+ * @throws {UnsupportedBlueMarketIrmError} when a Blue market the replay accrues has positive debt and an unsupported
1072
+ * IRM: the target, a source, or, on a vault's first allocation, any other market the vault holds.
1073
+ * @throws {NegativeInputError} when `capAccrualBuffer` is negative.
1074
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
1075
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
1076
+ * @throws {UnknownReallocationAdapterError} when a leg's adapter is absent.
1077
+ * @throws {UnknownReallocationAllocationError} when a leg's cap or allocation state is absent.
1078
+ * @example
1079
+ * ```ts
1080
+ * // `client` is a mainnet viem client extended with `morphoViemExtension()`, and
1081
+ * // `market = client.morpho.blue(marketParams, mainnet.id)` for a USDC market Keyrock's vault supplies.
1082
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
1083
+ * const block = await client.getBlock();
1084
+ * const data = await market.getVaultV2BlueReallocationData({
1085
+ * vaultAddresses: [keyrockUsdcVaultV2],
1086
+ * block: { number: block.number, timestamp: block.timestamp },
1087
+ * });
1088
+ * const {
1089
+ * reallocations: [leg],
1090
+ * } = data.computeVaultV2BlueReallocations(marketParams.id, {
1091
+ * timestamp: block.timestamp,
1092
+ * operation: { type: "borrow", amount: 1_000_000n },
1093
+ * });
1094
+ * // No leg: the market funds the borrow without a reallocation, so there is nothing to resize.
1095
+ * if (leg == null) return;
1096
+ * const assets = data.findVaultV2BlueReallocationFittingAssets({
1097
+ * marketId: marketParams.id,
1098
+ * reallocations: [],
1099
+ * reallocation: leg,
1100
+ * amounts: [leg.assets / 2n, leg.assets],
1101
+ * timestamp: block.timestamp,
1102
+ * });
1103
+ * // assets === leg.assets / 2n when that smaller move fits the vault caps, else leg.assets.
1104
+ * ```
1105
+ */
1106
+ findVaultV2BlueReallocationFittingAssets({ marketId, reallocations, reallocation, amounts, timestamp, capAccrualBuffer, }) {
1107
+ const prepareLeg = this.createCapReplay({
1108
+ marketId,
1109
+ timestamp,
1110
+ capAccrualBuffer,
1111
+ });
1112
+ for (const earlier of reallocations) {
1113
+ const leg = prepareLeg(earlier);
1114
+ if (!(leg.funds(earlier.assets) && leg.fits(earlier.assets))) {
1115
+ return undefined;
1116
+ }
1117
+ leg.apply();
1118
+ }
1119
+ const leg = prepareLeg(reallocation);
1120
+ for (const assets of amounts) {
1121
+ if (!leg.funds(assets)) {
1122
+ continue;
1123
+ }
1124
+ if (leg.fits(assets)) {
1125
+ return assets;
1126
+ }
1127
+ }
1128
+ }
1129
+ /**
1130
+ * Starts a cap replay toward `marketId` at `timestamp`. Each call of the returned function prepares
1131
+ * the next leg: `funds(assets)` checks that `assets` is a positive `uint128` its source holds
1132
+ * (market liquidity capped at the source adapter's supply, or idle without penalty donations), `fits(assets)` probes the leg at a positive `assets`, at the replay timestamp, against its target caps and
1133
+ * the planner's interest reserve, and `apply()` executes it at its own amount so later legs see it.
1134
+ */
1135
+ createCapReplay({ marketId, timestamp: inputTimestamp, capAccrualBuffer, }) {
1136
+ const timestamp = inputTimestamp == null
1137
+ ? this.getLatestSnapshotTimestamp()
1138
+ : BigInt(inputTimestamp);
1139
+ const reserves = createCapReserveState(this.mutableMarkets);
1140
+ const adapterIdsCache = new Map();
1141
+ const { getPair, capReserve } = createCapReserveResolvers({
1142
+ reserves,
1143
+ adapterIdsCache,
1144
+ timestamp,
1145
+ capAccrualBuffer: resolveCapAccrualBuffer(capAccrualBuffer),
1146
+ });
1147
+ let data = this.clone();
1148
+ data.setMarkets([data.getMarket(marketId).accrueInterest(timestamp)]);
1149
+ let context = createSimulationContext();
1150
+ return (reallocation) => {
1151
+ const { vault, from } = reallocation;
1152
+ const targetMarket = data.getMarket(marketId);
1153
+ const targetPair = getPair(vault, data.getAdapter(vault, reallocation.to.adapter), targetMarket);
1154
+ let sourcePair;
1155
+ let fundable;
1156
+ if (from.type === "market") {
1157
+ const sourceMarket = data
1158
+ .getMarket(from.marketParams.id)
1159
+ .accrueInterest(timestamp);
1160
+ data.setMarkets([sourceMarket]);
1161
+ const sourceAdapter = data.getAdapter(vault, from.adapter);
1162
+ fundable = MathLib.min(sourceMarket.liquidity, sourceMarket.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n));
1163
+ sourcePair = getPair(vault, sourceAdapter, sourceMarket);
1164
+ }
1165
+ else {
1166
+ const donatedKey = findAddressKey(context.donatedPenaltyAssets, vault);
1167
+ fundable = MathLib.zeroFloorSub(data.getVault(vault).assetBalance, donatedKey == null
1168
+ ? 0n
1169
+ : /* v8 ignore start: findAddressKey returns a key the record holds. */
1170
+ (context.donatedPenaltyAssets[donatedKey] ?? 0n));
1171
+ }
1172
+ const pairs = sourcePair == null ? [targetPair] : [targetPair, sourcePair];
1173
+ const sourceIds = new Set(sourcePair?.ids ?? []);
1174
+ const reserveById = new Map(targetPair.ids.map((id) => [id, capReserve(vault, id, pairs)]));
1175
+ const applyPublicReallocation = data.applyPublicReallocation.bind(data);
1176
+ const simulationContext = context;
1177
+ const targetSupplyHeadroom = MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
1178
+ return {
1179
+ funds: (assets) => assets > 0n && assets <= maxUint128 && assets <= fundable,
1180
+ fits: (assets) => assets > 0n &&
1181
+ assets <= targetSupplyHeadroom &&
1182
+ probeCandidateReallocation({
1183
+ assets,
1184
+ timestamp,
1185
+ targetMarket,
1186
+ applyPublicReallocation,
1187
+ simulationContext,
1188
+ reallocation,
1189
+ marketId,
1190
+ adapterIdsCache,
1191
+ targetIds: targetPair.ids,
1192
+ sourceIds,
1193
+ reserveById,
1194
+ })?.withinAllCaps === true,
1195
+ apply: () => {
1196
+ const vaultKey = vault.toLowerCase();
1197
+ const touched = reserves.touchedPairs.get(vaultKey) ??
1198
+ new Map();
1199
+ for (const pair of pairs) {
1200
+ touched.set(pair.key, pair);
1201
+ }
1202
+ reserves.touchedPairs.set(vaultKey, touched);
1203
+ ({ data, context } = data.applyPublicReallocation({
1204
+ context,
1205
+ reallocation,
1206
+ targetMarketId: marketId,
1207
+ timestamp,
1208
+ adapterIdsCache,
1209
+ }));
1210
+ },
1211
+ };
1212
+ };
1213
+ }
986
1214
  /**
987
1215
  * Computes borrow liquidity to a target utilization, including friendly
988
1216
  * Vault V2 public reallocations. Market/vault state and returned post-state
@@ -1884,7 +2112,7 @@ function fitCandidateCaps(params) {
1884
2112
  }
1885
2113
  /** Simulates one candidate amount and tests its reserved target-cap headroom. @internal */
1886
2114
  function probeCandidateReallocation(params) {
1887
- const { assets, targetMarket, applyPublicReallocation, simulationContext, reallocation, marketId, adapterIdsCache, targetIds, sourceIds, reserveById, } = params;
2115
+ const { assets, timestamp = params.targetMarket.lastUpdate, targetMarket, applyPublicReallocation, simulationContext, reallocation, marketId, adapterIdsCache, targetIds, sourceIds, reserveById, } = params;
1888
2116
  if (targetMarket.totalSupplyShares +
1889
2117
  targetMarket.toSupplyShares(assets, "Down") >
1890
2118
  MathLib.MAX_UINT_128) {
@@ -1894,7 +2122,7 @@ function probeCandidateReallocation(params) {
1894
2122
  context: simulationContext,
1895
2123
  reallocation: { ...reallocation, assets },
1896
2124
  targetMarketId: marketId,
1897
- timestamp: targetMarket.lastUpdate,
2125
+ timestamp,
1898
2126
  adapterIdsCache,
1899
2127
  probe: true,
1900
2128
  }), ReallocationAllocationUnderflowError, ReallocationAdapterSupplySharesUnderflowError);
@@ -1,7 +1,7 @@
1
- export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
1
+ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, InvalidVaultV2MidnightAdapterMarketsError as InvalidBlueVaultV2MidnightAdapterMarketsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureError as InvalidMidnightEcrecoverSignatureError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureError as InvalidMidnightEcrecoverSignatureError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, MissingLocalePartError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
7
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, MissingLocalePartError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
package/lib/esm/errors.js CHANGED
@@ -1,6 +1,6 @@
1
- export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
1
+ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, InvalidVaultV2MidnightAdapterMarketsError as InvalidBlueVaultV2MidnightAdapterMarketsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureError as InvalidMidnightEcrecoverSignatureError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, MissingLocalePartError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureError as InvalidMidnightEcrecoverSignatureError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, MissingLocalePartError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";