@morpho-org/morpho-sdk 10.5.0-next.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 (170) hide show
  1. package/README.md +44 -1
  2. package/lib/cjs/abis.d.ts +793 -0
  3. package/lib/cjs/abis.js +811 -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/midnight/supplyCollateralTakeBorrow.js +16 -11
  16. package/lib/cjs/actions/midnight/takeBorrow.js +14 -8
  17. package/lib/cjs/actions/midnight/takeLend.js +15 -9
  18. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
  19. package/lib/cjs/actions/midnight/takeWithdraw.js +14 -8
  20. package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  21. package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.js +59 -0
  22. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  23. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.js +193 -0
  24. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  25. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.js +66 -0
  26. package/lib/cjs/actions/requirements/blue/index.d.ts +3 -0
  27. package/lib/cjs/actions/requirements/blue/index.js +17 -0
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
  30. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +11 -6
  31. package/lib/cjs/actions/requirements/getRequirementsApproval.js +29 -5
  32. package/lib/cjs/addresses.d.ts +1 -1
  33. package/lib/cjs/addresses.js +6 -1
  34. package/lib/cjs/blue/addresses.d.ts +1 -1
  35. package/lib/cjs/blue/addresses.js +6 -1
  36. package/lib/cjs/constants.d.ts +1 -1
  37. package/lib/cjs/constants.js +7 -2
  38. package/lib/cjs/entities/blue/blue.d.ts +486 -2
  39. package/lib/cjs/entities/blue/blue.js +529 -34
  40. package/lib/cjs/entities/index.d.ts +1 -1
  41. package/lib/cjs/entities/midnight/midnight.d.ts +6 -0
  42. package/lib/cjs/entities/midnight/midnight.js +21 -2
  43. package/lib/cjs/entities/requirements/assertContractCode.d.ts +0 -23
  44. package/lib/cjs/entities/requirements/assertContractCode.js +3 -28
  45. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +117 -0
  46. package/lib/cjs/entities/vaultV2BlueReallocationData.js +226 -2
  47. package/lib/cjs/helpers/constant.d.ts +41 -0
  48. package/lib/cjs/helpers/constant.js +42 -1
  49. package/lib/cjs/helpers/getZeroExLeverageBundle.d.ts +13 -0
  50. package/lib/cjs/helpers/getZeroExLeverageBundle.js +27 -0
  51. package/lib/cjs/helpers/index.d.ts +4 -1
  52. package/lib/cjs/helpers/index.js +29 -1
  53. package/lib/cjs/helpers/leverage/index.d.ts +1 -0
  54. package/lib/cjs/helpers/leverage/index.js +11 -0
  55. package/lib/cjs/helpers/leverage/limits.d.ts +472 -0
  56. package/lib/cjs/helpers/leverage/limits.js +715 -0
  57. package/lib/cjs/helpers/leverage/positionMarket.d.ts +17 -0
  58. package/lib/cjs/helpers/leverage/positionMarket.js +28 -0
  59. package/lib/cjs/helpers/leverage/reallocations.d.ts +159 -0
  60. package/lib/cjs/helpers/leverage/reallocations.js +276 -0
  61. package/lib/cjs/helpers/validate.d.ts +14 -0
  62. package/lib/cjs/helpers/validate.js +25 -1
  63. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  64. package/lib/cjs/helpers/validateRequirementSpender.js +4 -0
  65. package/lib/cjs/helpers/zeroExQuote.d.ts +250 -0
  66. package/lib/cjs/helpers/zeroExQuote.js +763 -0
  67. package/lib/cjs/index.d.ts +1 -0
  68. package/lib/cjs/index.js +5 -2
  69. package/lib/cjs/reads/assertContractCode.d.ts +25 -0
  70. package/lib/cjs/reads/assertContractCode.js +30 -0
  71. package/lib/cjs/reads/fetchZeroExQuote.d.ts +123 -0
  72. package/lib/cjs/reads/fetchZeroExQuote.js +330 -0
  73. package/lib/cjs/transactionPlan/midnight/takeBorrow.d.ts +4 -0
  74. package/lib/cjs/transactionPlan/midnight/takeBorrow.js +8 -2
  75. package/lib/cjs/types/action.d.ts +130 -1
  76. package/lib/cjs/types/error.d.ts +84 -0
  77. package/lib/cjs/types/error.js +110 -3
  78. package/lib/cjs/types/index.d.ts +2 -0
  79. package/lib/cjs/types/index.js +2 -0
  80. package/lib/cjs/types/leverageError.d.ts +1552 -0
  81. package/lib/cjs/types/leverageError.js +1711 -0
  82. package/lib/cjs/types/zeroEx.d.ts +171 -0
  83. package/lib/cjs/types/zeroEx.js +2 -0
  84. package/lib/cjs/version.d.ts +1 -1
  85. package/lib/cjs/version.js +1 -1
  86. package/lib/esm/abis.d.ts +793 -0
  87. package/lib/esm/abis.js +809 -0
  88. package/lib/esm/actions/blue/close.d.ts +169 -0
  89. package/lib/esm/actions/blue/close.js +266 -0
  90. package/lib/esm/actions/blue/common.js +3 -3
  91. package/lib/esm/actions/blue/delever.d.ts +156 -0
  92. package/lib/esm/actions/blue/delever.js +219 -0
  93. package/lib/esm/actions/blue/index.d.ts +3 -0
  94. package/lib/esm/actions/blue/index.js +3 -0
  95. package/lib/esm/actions/blue/lever.d.ts +184 -0
  96. package/lib/esm/actions/blue/lever.js +268 -0
  97. package/lib/esm/actions/blue/leverageIntent.d.ts +65 -0
  98. package/lib/esm/actions/blue/leverageIntent.js +96 -0
  99. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +16 -11
  100. package/lib/esm/actions/midnight/takeBorrow.js +14 -8
  101. package/lib/esm/actions/midnight/takeLend.js +15 -9
  102. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
  103. package/lib/esm/actions/midnight/takeWithdraw.js +14 -8
  104. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  105. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.js +55 -0
  106. package/lib/esm/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  107. package/lib/esm/actions/requirements/blue/getLeverageRequirements.js +189 -0
  108. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  109. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.js +62 -0
  110. package/lib/esm/actions/requirements/blue/index.d.ts +3 -0
  111. package/lib/esm/actions/requirements/blue/index.js +3 -0
  112. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  113. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
  114. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +11 -6
  115. package/lib/esm/actions/requirements/getRequirementsApproval.js +29 -5
  116. package/lib/esm/addresses.d.ts +1 -1
  117. package/lib/esm/addresses.js +1 -1
  118. package/lib/esm/blue/addresses.d.ts +1 -1
  119. package/lib/esm/blue/addresses.js +1 -1
  120. package/lib/esm/constants.d.ts +1 -1
  121. package/lib/esm/constants.js +1 -1
  122. package/lib/esm/entities/blue/blue.d.ts +486 -2
  123. package/lib/esm/entities/blue/blue.js +501 -6
  124. package/lib/esm/entities/index.d.ts +1 -1
  125. package/lib/esm/entities/midnight/midnight.d.ts +6 -0
  126. package/lib/esm/entities/midnight/midnight.js +21 -2
  127. package/lib/esm/entities/requirements/assertContractCode.d.ts +0 -23
  128. package/lib/esm/entities/requirements/assertContractCode.js +1 -25
  129. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +117 -0
  130. package/lib/esm/entities/vaultV2BlueReallocationData.js +227 -3
  131. package/lib/esm/helpers/constant.d.ts +41 -0
  132. package/lib/esm/helpers/constant.js +41 -0
  133. package/lib/esm/helpers/getZeroExLeverageBundle.d.ts +13 -0
  134. package/lib/esm/helpers/getZeroExLeverageBundle.js +23 -0
  135. package/lib/esm/helpers/index.d.ts +4 -1
  136. package/lib/esm/helpers/index.js +4 -1
  137. package/lib/esm/helpers/leverage/index.d.ts +1 -0
  138. package/lib/esm/helpers/leverage/index.js +1 -0
  139. package/lib/esm/helpers/leverage/limits.d.ts +472 -0
  140. package/lib/esm/helpers/leverage/limits.js +705 -0
  141. package/lib/esm/helpers/leverage/positionMarket.d.ts +17 -0
  142. package/lib/esm/helpers/leverage/positionMarket.js +24 -0
  143. package/lib/esm/helpers/leverage/reallocations.d.ts +159 -0
  144. package/lib/esm/helpers/leverage/reallocations.js +271 -0
  145. package/lib/esm/helpers/validate.d.ts +14 -0
  146. package/lib/esm/helpers/validate.js +25 -2
  147. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  148. package/lib/esm/helpers/validateRequirementSpender.js +5 -1
  149. package/lib/esm/helpers/zeroExQuote.d.ts +250 -0
  150. package/lib/esm/helpers/zeroExQuote.js +754 -0
  151. package/lib/esm/index.d.ts +1 -0
  152. package/lib/esm/index.js +1 -0
  153. package/lib/esm/reads/assertContractCode.d.ts +25 -0
  154. package/lib/esm/reads/assertContractCode.js +26 -0
  155. package/lib/esm/reads/fetchZeroExQuote.d.ts +123 -0
  156. package/lib/esm/reads/fetchZeroExQuote.js +326 -0
  157. package/lib/esm/transactionPlan/midnight/takeBorrow.d.ts +4 -0
  158. package/lib/esm/transactionPlan/midnight/takeBorrow.js +9 -3
  159. package/lib/esm/types/action.d.ts +130 -1
  160. package/lib/esm/types/error.d.ts +84 -0
  161. package/lib/esm/types/error.js +103 -0
  162. package/lib/esm/types/index.d.ts +2 -0
  163. package/lib/esm/types/index.js +2 -0
  164. package/lib/esm/types/leverageError.d.ts +1552 -0
  165. package/lib/esm/types/leverageError.js +1660 -0
  166. package/lib/esm/types/zeroEx.d.ts +171 -0
  167. package/lib/esm/types/zeroEx.js +1 -0
  168. package/lib/esm/version.d.ts +1 -1
  169. package/lib/esm/version.js +1 -1
  170. package/package.json +7 -7
@@ -1,29 +1,6 @@
1
1
  import type { AddressLabel } from "@morpho-org/morpho-ts";
2
2
  import type { Address, Client } from "viem";
3
3
  import { type ChainCheck } from "../../actions/requirements/chainCheck.js";
4
- /**
5
- * Asserts that a configured contract address holds deployed code on the client's chain.
6
- *
7
- * A call to a code-less address succeeds on-chain as a no-op, so entity flows check each
8
- * registered target before returning requirements. The `eth_getCode` read runs at the
9
- * client's default block; transport failures propagate unwrapped because they are
10
- * infrastructure failures, not configuration failures.
11
- *
12
- * @param client - Connected viem client used for the `eth_getCode` read.
13
- * @param params - Assertion parameters.
14
- * @param params.address - Contract address expected to hold code.
15
- * @param params.chainId - Chain id the flow targets, reported on the error.
16
- * @param params.role - Registry label naming the address's role in the flow.
17
- * @returns Nothing when the address holds code.
18
- * @throws {MissingContractCodeError} when the address has no deployed bytecode.
19
- * @throws {viem.BaseError} when the `eth_getCode` read itself fails.
20
- * @internal
21
- */
22
- export declare const assertContractCode: (client: Client, params: {
23
- readonly address: Address;
24
- readonly chainId: number;
25
- readonly role: AddressLabel;
26
- }) => Promise<void>;
27
4
  /**
28
5
  * Asserts that each distinct target in a flow's write-surface list holds code.
29
6
  *
@@ -1,30 +1,6 @@
1
- import { getBytecode } from "viem/actions";
2
1
  import { createChainCheck, } from "../../actions/requirements/chainCheck.js";
2
+ import { assertContractCode } from "../../reads/assertContractCode.js";
3
3
  import { ChainIdMismatchError, MissingContractCodeError, } from "../../types/index.js";
4
- /**
5
- * Asserts that a configured contract address holds deployed code on the client's chain.
6
- *
7
- * A call to a code-less address succeeds on-chain as a no-op, so entity flows check each
8
- * registered target before returning requirements. The `eth_getCode` read runs at the
9
- * client's default block; transport failures propagate unwrapped because they are
10
- * infrastructure failures, not configuration failures.
11
- *
12
- * @param client - Connected viem client used for the `eth_getCode` read.
13
- * @param params - Assertion parameters.
14
- * @param params.address - Contract address expected to hold code.
15
- * @param params.chainId - Chain id the flow targets, reported on the error.
16
- * @param params.role - Registry label naming the address's role in the flow.
17
- * @returns Nothing when the address holds code.
18
- * @throws {MissingContractCodeError} when the address has no deployed bytecode.
19
- * @throws {viem.BaseError} when the `eth_getCode` read itself fails.
20
- * @internal
21
- */
22
- export const assertContractCode = async (client, params) => {
23
- const bytecode = await getBytecode(client, { address: params.address });
24
- if (bytecode === undefined || bytecode === "0x") {
25
- throw new MissingContractCodeError(params.address, params.chainId, params.role);
26
- }
27
- };
28
4
  /**
29
5
  * Asserts that each distinct target in a flow's write-surface list holds code.
30
6
  *
@@ -578,6 +578,123 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
578
578
  * ```
579
579
  */
580
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;
581
698
  /**
582
699
  * Computes borrow liquidity to a target utilization, including friendly
583
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";
@@ -987,6 +987,230 @@ export class VaultV2BlueReallocationData {
987
987
  })
988
988
  .reallocations.reduce((total, { assets }) => total + assets, 0n);
989
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
+ }
990
1214
  /**
991
1215
  * Computes borrow liquidity to a target utilization, including friendly
992
1216
  * Vault V2 public reallocations. Market/vault state and returned post-state
@@ -1888,7 +2112,7 @@ function fitCandidateCaps(params) {
1888
2112
  }
1889
2113
  /** Simulates one candidate amount and tests its reserved target-cap headroom. @internal */
1890
2114
  function probeCandidateReallocation(params) {
1891
- 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;
1892
2116
  if (targetMarket.totalSupplyShares +
1893
2117
  targetMarket.toSupplyShares(assets, "Down") >
1894
2118
  MathLib.MAX_UINT_128) {
@@ -1898,7 +2122,7 @@ function probeCandidateReallocation(params) {
1898
2122
  context: simulationContext,
1899
2123
  reallocation: { ...reallocation, assets },
1900
2124
  targetMarketId: marketId,
1901
- timestamp: targetMarket.lastUpdate,
2125
+ timestamp,
1902
2126
  adapterIdsCache,
1903
2127
  probe: true,
1904
2128
  }), ReallocationAllocationUnderflowError, ReallocationAdapterSupplySharesUnderflowError);
@@ -3,6 +3,13 @@ import { type Address } from "viem";
3
3
  export declare const VAULT_DEPOSIT_MAX_DEADLINE_SECONDS = 604800n;
4
4
  /** Maximum time between now and a Midnight taker-flow deadline, in seconds. */
5
5
  export declare const MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS = 3600n;
6
+ /**
7
+ * Minimum time between a Midnight borrow's deadline and its market maturity, in seconds (2 hours).
8
+ * Debt still open at maturity becomes liquidatable, so entity and TransactionPlan borrows prepared at
9
+ * or before maturity that could execute closer to it are rejected. Credit covering the target at
10
+ * preparation does not exempt a borrow; sell credit only inside the window with `takeWithdraw`.
11
+ */
12
+ export declare const MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY: bigint;
6
13
  /**
7
14
  * Matches MAX_SLIPPAGE_TOLERANCE, the SDK's other ceiling on a WAD share of user funds; higher fees are rejected as likely unit mistakes.
8
15
  * @internal
@@ -14,8 +21,42 @@ export declare const MAX_SLIPPAGE_TOLERANCE: bigint;
14
21
  export declare const DEFAULT_MAX_REALLOCATION_PENALTY = 0n;
15
22
  /** Maximum Vault V2 reallocation penalty: 100%. */
16
23
  export declare const MAX_REALLOCATION_PENALTY = 1000000000000000000n;
24
+ /**
25
+ * Maximum penalty rate a ZeroExLeverageBundlesV1 Lever accepts per public-allocator reallocation:
26
+ * 1%, WAD-scaled. Fixed; no caller option.
27
+ */
28
+ export declare const LEVERAGE_MAX_REALLOCATION_PENALTY: bigint;
17
29
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
18
30
  export declare const DEFAULT_LLTV_BUFFER: bigint;
31
+ /**
32
+ * SDK slippage ceiling per leverage action, WAD-scaled: `MAX_SLIPPAGE_TOLERANCE` (10%) for every action, the
33
+ * ceiling `fetchZeroExQuote` enforces, so the fetch and the builders cannot drift apart. Not configurable.
34
+ */
35
+ export declare const LEVERAGE_MAX_EXECUTION_LOSS: Readonly<{
36
+ readonly lever: bigint;
37
+ readonly delever: bigint;
38
+ readonly close: bigint;
39
+ }>;
40
+ /**
41
+ * Largest amount a Lever's worst swap price (`maxSwapIn` per `minCollateralToBuy`) may be above the market's oracle
42
+ * price, WAD-scaled: 15%. Exactly 15% is accepted, and a price below the oracle, which favours the user, is never
43
+ * refused. Delever and Close are not checked. The worst price uses `maxSwapIn`, which already includes the caller's
44
+ * slippage, so the room left for a gap between 0x's price and the oracle is about 15% minus that slippage (5% at the
45
+ * 10% ceiling).
46
+ * Not configurable.
47
+ */
48
+ export declare const LEVERAGE_MAX_ORACLE_DEVIATION: bigint;
49
+ /** Leverage deadline window after the data block, in seconds (1 hour). */
50
+ export declare const LEVERAGE_DEADLINE_WINDOW = 3600n;
51
+ /**
52
+ * Margin applied to the interest a Close's debt may accrue before its deadline: the buffer is the debt accrued for
53
+ * the one-hour deadline window at 4× the data block's borrow rate. The factor matches the AdaptiveCurveIrm curve
54
+ * steepness (`AdaptiveCurveIrmLib.CURVE_STEEPNESS` in blue-sdk), the most utilization can raise the rate over its
55
+ * rate at target, while that rate at target itself drifts by well under 1% in an hour (`ADJUSTMENT_SPEED` is 50 per
56
+ * year). It does not cover a rate that rises more than 4×, such as one quoted below target that jumps to full
57
+ * utilization; the Close then reverts instead of overpaying. Fixed; no caller option.
58
+ */
59
+ export declare const LEVERAGE_CLOSE_INTEREST_BUFFER_FACTOR = 4n;
19
60
  /**
20
61
  * Forward interest-accrual window, in seconds (2 hours), reserved in target-market
21
62
  * cap checks (BluePublicAllocator max-in, Vault V2 absolute and relative caps) when
@@ -5,6 +5,13 @@ import { maxUint96 } from "viem";
5
5
  export const VAULT_DEPOSIT_MAX_DEADLINE_SECONDS = 604800n;
6
6
  /** Maximum time between now and a Midnight taker-flow deadline, in seconds. */
7
7
  export const MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS = 3600n;
8
+ /**
9
+ * Minimum time between a Midnight borrow's deadline and its market maturity, in seconds (2 hours).
10
+ * Debt still open at maturity becomes liquidatable, so entity and TransactionPlan borrows prepared at
11
+ * or before maturity that could execute closer to it are rejected. Credit covering the target at
12
+ * preparation does not exempt a borrow; sell credit only inside the window with `takeWithdraw`.
13
+ */
14
+ export const MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY = Time.s.from.h(2n);
8
15
  /**
9
16
  * Matches MAX_SLIPPAGE_TOLERANCE, the SDK's other ceiling on a WAD share of user funds; higher fees are rejected as likely unit mistakes.
10
17
  * @internal
@@ -16,8 +23,42 @@ export const MAX_SLIPPAGE_TOLERANCE = MathLib.WAD / 10n;
16
23
  export const DEFAULT_MAX_REALLOCATION_PENALTY = 0n;
17
24
  /** Maximum Vault V2 reallocation penalty: 100%. */
18
25
  export const MAX_REALLOCATION_PENALTY = MathLib.WAD;
26
+ /**
27
+ * Maximum penalty rate a ZeroExLeverageBundlesV1 Lever accepts per public-allocator reallocation:
28
+ * 1%, WAD-scaled. Fixed; no caller option.
29
+ */
30
+ export const LEVERAGE_MAX_REALLOCATION_PENALTY = MathLib.WAD / 100n;
19
31
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
20
32
  export const DEFAULT_LLTV_BUFFER = MathLib.WAD / 200n;
33
+ /**
34
+ * SDK slippage ceiling per leverage action, WAD-scaled: `MAX_SLIPPAGE_TOLERANCE` (10%) for every action, the
35
+ * ceiling `fetchZeroExQuote` enforces, so the fetch and the builders cannot drift apart. Not configurable.
36
+ */
37
+ export const LEVERAGE_MAX_EXECUTION_LOSS = Object.freeze({
38
+ lever: MAX_SLIPPAGE_TOLERANCE,
39
+ delever: MAX_SLIPPAGE_TOLERANCE,
40
+ close: MAX_SLIPPAGE_TOLERANCE,
41
+ });
42
+ /**
43
+ * Largest amount a Lever's worst swap price (`maxSwapIn` per `minCollateralToBuy`) may be above the market's oracle
44
+ * price, WAD-scaled: 15%. Exactly 15% is accepted, and a price below the oracle, which favours the user, is never
45
+ * refused. Delever and Close are not checked. The worst price uses `maxSwapIn`, which already includes the caller's
46
+ * slippage, so the room left for a gap between 0x's price and the oracle is about 15% minus that slippage (5% at the
47
+ * 10% ceiling).
48
+ * Not configurable.
49
+ */
50
+ export const LEVERAGE_MAX_ORACLE_DEVIATION = (MathLib.WAD * 15n) / 100n;
51
+ /** Leverage deadline window after the data block, in seconds (1 hour). */
52
+ export const LEVERAGE_DEADLINE_WINDOW = 3600n;
53
+ /**
54
+ * Margin applied to the interest a Close's debt may accrue before its deadline: the buffer is the debt accrued for
55
+ * the one-hour deadline window at 4× the data block's borrow rate. The factor matches the AdaptiveCurveIrm curve
56
+ * steepness (`AdaptiveCurveIrmLib.CURVE_STEEPNESS` in blue-sdk), the most utilization can raise the rate over its
57
+ * rate at target, while that rate at target itself drifts by well under 1% in an hour (`ADJUSTMENT_SPEED` is 50 per
58
+ * year). It does not cover a rate that rises more than 4×, such as one quoted below target that jumps to full
59
+ * utilization; the Close then reverts instead of overpaying. Fixed; no caller option.
60
+ */
61
+ export const LEVERAGE_CLOSE_INTEREST_BUFFER_FACTOR = 4n;
21
62
  /**
22
63
  * Forward interest-accrual window, in seconds (2 hours), reserved in target-market
23
64
  * cap checks (BluePublicAllocator max-in, Vault V2 absolute and relative caps) when
@@ -0,0 +1,13 @@
1
+ import { type Address } from "viem";
2
+ /**
3
+ * Returns the ZeroExLeverageBundlesV1 address registered for `chainId`, whether or not the bundle
4
+ * can run there.
5
+ *
6
+ * @param chainId - Target chain id.
7
+ * @returns The registered ZeroExLeverageBundlesV1 address.
8
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the address registry.
9
+ * @throws {LeverageUnsupportedChainError} with reason `noBundle` when no bundle, the zero address or a value that
10
+ * is not an address is registered.
11
+ * @internal
12
+ */
13
+ export declare const getRegisteredZeroExLeverageBundle: (chainId: number) => Address;
@@ -0,0 +1,23 @@
1
+ import { getChainAddresses } from "@morpho-org/blue-sdk";
2
+ import { isAddress, isAddressEqual, zeroAddress } from "viem";
3
+ import { LeverageUnsupportedChainError } from "../types/index.js";
4
+ /**
5
+ * Returns the ZeroExLeverageBundlesV1 address registered for `chainId`, whether or not the bundle
6
+ * can run there.
7
+ *
8
+ * @param chainId - Target chain id.
9
+ * @returns The registered ZeroExLeverageBundlesV1 address.
10
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the address registry.
11
+ * @throws {LeverageUnsupportedChainError} with reason `noBundle` when no bundle, the zero address or a value that
12
+ * is not an address is registered.
13
+ * @internal
14
+ */
15
+ export const getRegisteredZeroExLeverageBundle = (chainId) => {
16
+ const bundle = getChainAddresses(chainId).bundles?.zeroExLeverageBundlesV1;
17
+ if (typeof bundle !== "string" ||
18
+ !isAddress(bundle, { strict: false }) ||
19
+ isAddressEqual(bundle, zeroAddress)) {
20
+ throw new LeverageUnsupportedChainError({ chainId, reason: "noBundle" });
21
+ }
22
+ return bundle;
23
+ };
@@ -1,6 +1,8 @@
1
1
  export { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "./callback.js";
2
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS, MIN_DEAD_SHARES, MIN_VAULT_V2_DEAD_ASSETS, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
2
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, LEVERAGE_CLOSE_INTEREST_BUFFER_FACTOR, LEVERAGE_DEADLINE_WINDOW, LEVERAGE_MAX_EXECUTION_LOSS, LEVERAGE_MAX_ORACLE_DEVIATION, LEVERAGE_MAX_REALLOCATION_PENALTY, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY, MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS, MIN_DEAD_SHARES, MIN_VAULT_V2_DEAD_ASSETS, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
3
3
  export { validateBlueMarketDeadShares, validateVaultV1DeadShares, validateVaultV2DeadShares, } from "./deadShares.js";
4
+ export * from "./leverage/index.js";
5
+ export { computeLeveragePenaltyAssets, type LeverageAllocatorState, type LeverageReallocation, validateLeverageReallocations, } from "./leverage/reallocations.js";
4
6
  export { addTransactionMetadata } from "./metadata.js";
5
7
  export { type PreviewVaultV2ForceWithdrawParams, previewVaultV2ForceWithdraw, type VaultV2ForceWithdrawPreview, } from "./previewVaultV2ForceWithdraw.js";
6
8
  export { type PreviewVaultV2InKindRedeemParams, previewVaultV2InKindRedeem, type VaultV2InKindRedeemMarketPreview, } from "./previewVaultV2InKindRedeem.js";
@@ -11,3 +13,4 @@ export { getMidnightMaxSafeDebt, validateAccrualPosition, validateChainId, valid
11
13
  export { validateOfferSides } from "./validateOfferSides.js";
12
14
  export { type RequirementSpenderKey, validateRequirementSpender, } from "./validateRequirementSpender.js";
13
15
  export { computeVaultV2ForceWithdrawFeeSharesMinted, computeVaultV2ForceWithdrawMinSharesBurnt, computeVaultV2ForceWithdrawPlan, computeVaultV2ForceWithdrawSharesBurnt, resolveVaultV2ForceWithdrawEligibility, type VaultV2ForceWithdrawEligibility, type VaultV2ForceWithdrawPlan, } from "./vaultV2ForceWithdrawPlan.js";
16
+ export { getZeroExSwapRoute, validateZeroExQuote, type ZeroExSwapRoute, } from "./zeroExQuote.js";
@@ -1,6 +1,8 @@
1
1
  export { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "./callback.js";
2
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS, MIN_DEAD_SHARES, MIN_VAULT_V2_DEAD_ASSETS, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
2
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, LEVERAGE_CLOSE_INTEREST_BUFFER_FACTOR, LEVERAGE_DEADLINE_WINDOW, LEVERAGE_MAX_EXECUTION_LOSS, LEVERAGE_MAX_ORACLE_DEVIATION, LEVERAGE_MAX_REALLOCATION_PENALTY, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY, MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS, MIN_DEAD_SHARES, MIN_VAULT_V2_DEAD_ASSETS, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
3
3
  export { validateBlueMarketDeadShares, validateVaultV1DeadShares, validateVaultV2DeadShares, } from "./deadShares.js";
4
+ export * from "./leverage/index.js";
5
+ export { computeLeveragePenaltyAssets, validateLeverageReallocations, } from "./leverage/reallocations.js";
4
6
  export { addTransactionMetadata } from "./metadata.js";
5
7
  export { previewVaultV2ForceWithdraw, } from "./previewVaultV2ForceWithdraw.js";
6
8
  export { previewVaultV2InKindRedeem, } from "./previewVaultV2InKindRedeem.js";
@@ -11,3 +13,4 @@ export { getMidnightMaxSafeDebt, validateAccrualPosition, validateChainId, valid
11
13
  export { validateOfferSides } from "./validateOfferSides.js";
12
14
  export { validateRequirementSpender, } from "./validateRequirementSpender.js";
13
15
  export { computeVaultV2ForceWithdrawFeeSharesMinted, computeVaultV2ForceWithdrawMinSharesBurnt, computeVaultV2ForceWithdrawPlan, computeVaultV2ForceWithdrawSharesBurnt, resolveVaultV2ForceWithdrawEligibility, } from "./vaultV2ForceWithdrawPlan.js";
16
+ export { getZeroExSwapRoute, validateZeroExQuote, } from "./zeroExQuote.js";
@@ -0,0 +1 @@
1
+ export { type CloseLimits, type CloseLimitsParams, computeCloseInterestBuffer, computeCloseLimits, computeDeleverLimits, computeLeverageOracleDeviation, computeLeverLimits, type DeleverLimits, type DeleverLimitsParams, type LeverageActionOracleDeviation, type LeverageLimitsData, type LeverageLimitsInput, type LeverageOperation, type LeverageOracleDeviation, type LeverageOracleDeviationParams, type LeverageQuoteAmounts, type LeverLimits, type LeverLimitsParams, leverageDeadline, validateLeverageInputs, } from "./limits.js";
@@ -0,0 +1 @@
1
+ export { computeCloseInterestBuffer, computeCloseLimits, computeDeleverLimits, computeLeverageOracleDeviation, computeLeverLimits, leverageDeadline, validateLeverageInputs, } from "./limits.js";