@morpho-org/morpho-sdk 9.1.0-next.0 → 9.1.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 (126) hide show
  1. package/README.md +3 -1
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +1 -5
  4. package/lib/cjs/actions/blue/borrow.d.ts +1 -0
  5. package/lib/cjs/actions/blue/borrow.js +1 -0
  6. package/lib/cjs/actions/blue/refinance.d.ts +1 -0
  7. package/lib/cjs/actions/blue/refinance.js +3 -0
  8. package/lib/cjs/actions/blue/repay.d.ts +1 -0
  9. package/lib/cjs/actions/blue/repay.js +1 -0
  10. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +1 -0
  11. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -0
  12. package/lib/cjs/actions/blue/supply.d.ts +1 -0
  13. package/lib/cjs/actions/blue/supply.js +2 -0
  14. package/lib/cjs/actions/blue/supplyCollateral.d.ts +1 -0
  15. package/lib/cjs/actions/blue/supplyCollateral.js +1 -0
  16. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +1 -0
  17. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +2 -0
  18. package/lib/cjs/actions/blue/withdraw.d.ts +1 -0
  19. package/lib/cjs/actions/blue/withdraw.js +2 -0
  20. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +1 -0
  21. package/lib/cjs/actions/blue/withdrawCollateral.js +1 -0
  22. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
  23. package/lib/cjs/actions/midnight/takeLend.js +1 -0
  24. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  25. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
  26. package/lib/cjs/blue/abis.d.ts +1 -1
  27. package/lib/cjs/blue/abis.js +1 -5
  28. package/lib/cjs/blue/entities.d.ts +4 -4
  29. package/lib/cjs/blue/entities.js +1 -3
  30. package/lib/cjs/blue/errors.d.ts +2 -2
  31. package/lib/cjs/blue/errors.js +2 -5
  32. package/lib/cjs/blue/fetch.d.ts +2 -2
  33. package/lib/cjs/blue/fetch.js +1 -3
  34. package/lib/cjs/blue/utils.d.ts +1 -1
  35. package/lib/cjs/blue/utils.js +1 -2
  36. package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
  37. package/lib/cjs/client/morphoViemExtension.js +1 -7
  38. package/lib/cjs/entities/blue/blue.d.ts +43 -7
  39. package/lib/cjs/entities/blue/blue.js +27 -3
  40. package/lib/cjs/entities/index.d.ts +4 -4
  41. package/lib/cjs/entities/index.js +1 -3
  42. package/lib/cjs/entities/midnight/midnight.d.ts +7 -5
  43. package/lib/cjs/entities/midnight/midnight.js +7 -5
  44. package/lib/cjs/entities/midnight/types.d.ts +8 -1
  45. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +12 -34
  46. package/lib/cjs/entities/vaultV2/vaultV2.js +9 -38
  47. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +43 -18
  48. package/lib/cjs/entities/vaultV2BlueReallocationData.js +210 -79
  49. package/lib/cjs/errors.d.ts +4 -4
  50. package/lib/cjs/errors.js +6 -10
  51. package/lib/cjs/fetch.d.ts +2 -2
  52. package/lib/cjs/fetch.js +1 -3
  53. package/lib/cjs/helpers/validate.d.ts +11 -1
  54. package/lib/cjs/helpers/validate.js +17 -1
  55. package/lib/cjs/helpers/validateTakeableOffers.d.ts +4 -2
  56. package/lib/cjs/helpers/validateTakeableOffers.js +12 -1
  57. package/lib/cjs/midnight/errors.d.ts +1 -2
  58. package/lib/cjs/midnight/errors.js +4 -5
  59. package/lib/cjs/types/error.d.ts +6 -0
  60. package/lib/cjs/types/error.js +9 -1
  61. package/lib/cjs/types/sharedLiquidity.d.ts +27 -11
  62. package/lib/cjs/utils.d.ts +2 -2
  63. package/lib/cjs/utils.js +2 -4
  64. package/lib/esm/abis.d.ts +1 -1
  65. package/lib/esm/abis.js +1 -1
  66. package/lib/esm/actions/blue/borrow.d.ts +1 -0
  67. package/lib/esm/actions/blue/borrow.js +1 -0
  68. package/lib/esm/actions/blue/refinance.d.ts +1 -0
  69. package/lib/esm/actions/blue/refinance.js +4 -1
  70. package/lib/esm/actions/blue/repay.d.ts +1 -0
  71. package/lib/esm/actions/blue/repay.js +1 -0
  72. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +1 -0
  73. package/lib/esm/actions/blue/repayWithdrawCollateral.js +3 -1
  74. package/lib/esm/actions/blue/supply.d.ts +1 -0
  75. package/lib/esm/actions/blue/supply.js +3 -1
  76. package/lib/esm/actions/blue/supplyCollateral.d.ts +1 -0
  77. package/lib/esm/actions/blue/supplyCollateral.js +1 -0
  78. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +1 -0
  79. package/lib/esm/actions/blue/supplyCollateralBorrow.js +3 -1
  80. package/lib/esm/actions/blue/withdraw.d.ts +1 -0
  81. package/lib/esm/actions/blue/withdraw.js +3 -1
  82. package/lib/esm/actions/blue/withdrawCollateral.d.ts +1 -0
  83. package/lib/esm/actions/blue/withdrawCollateral.js +1 -0
  84. package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
  85. package/lib/esm/actions/midnight/takeLend.js +1 -0
  86. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  87. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
  88. package/lib/esm/blue/abis.d.ts +1 -1
  89. package/lib/esm/blue/abis.js +1 -1
  90. package/lib/esm/blue/entities.d.ts +4 -4
  91. package/lib/esm/blue/entities.js +2 -2
  92. package/lib/esm/blue/errors.d.ts +2 -2
  93. package/lib/esm/blue/errors.js +2 -2
  94. package/lib/esm/blue/fetch.d.ts +2 -2
  95. package/lib/esm/blue/fetch.js +2 -2
  96. package/lib/esm/blue/utils.d.ts +1 -1
  97. package/lib/esm/blue/utils.js +1 -1
  98. package/lib/esm/client/morphoViemExtension.d.ts +1 -1
  99. package/lib/esm/client/morphoViemExtension.js +1 -7
  100. package/lib/esm/entities/blue/blue.d.ts +43 -7
  101. package/lib/esm/entities/blue/blue.js +27 -3
  102. package/lib/esm/entities/index.d.ts +4 -4
  103. package/lib/esm/entities/index.js +2 -2
  104. package/lib/esm/entities/midnight/midnight.d.ts +7 -5
  105. package/lib/esm/entities/midnight/midnight.js +7 -5
  106. package/lib/esm/entities/midnight/types.d.ts +8 -1
  107. package/lib/esm/entities/vaultV2/vaultV2.d.ts +12 -34
  108. package/lib/esm/entities/vaultV2/vaultV2.js +10 -39
  109. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +43 -18
  110. package/lib/esm/entities/vaultV2BlueReallocationData.js +211 -80
  111. package/lib/esm/errors.d.ts +4 -4
  112. package/lib/esm/errors.js +4 -4
  113. package/lib/esm/fetch.d.ts +2 -2
  114. package/lib/esm/fetch.js +2 -2
  115. package/lib/esm/helpers/validate.d.ts +11 -1
  116. package/lib/esm/helpers/validate.js +15 -0
  117. package/lib/esm/helpers/validateTakeableOffers.d.ts +4 -2
  118. package/lib/esm/helpers/validateTakeableOffers.js +13 -2
  119. package/lib/esm/midnight/errors.d.ts +1 -2
  120. package/lib/esm/midnight/errors.js +1 -2
  121. package/lib/esm/types/error.d.ts +6 -0
  122. package/lib/esm/types/error.js +7 -0
  123. package/lib/esm/types/sharedLiquidity.d.ts +27 -11
  124. package/lib/esm/utils.d.ts +2 -2
  125. package/lib/esm/utils.js +2 -2
  126. package/package.json +6 -6
@@ -1,9 +1,10 @@
1
1
  import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, Market, MarketUtils, MathLib, UnsupportedVaultV2AdapterError, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2BluePublicAllocatorConfigUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
2
2
  import { _try, bigIntComparator } from "@morpho-org/morpho-ts";
3
3
  import { isAddressEqual } from "viem";
4
+ import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1ReferralFeeAssets, } from "../actions/blue/common.js";
4
5
  import { DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, MAX_REALLOCATION_PENALTY, } from "../helpers/constant.js";
5
6
  import { resolveAllocatorCapHeadroom, resolveCapAccrualBuffer, resolveMaxWithdrawalUtilization, } from "../helpers/utilization.js";
6
- import { InputExceedsMaxError, InsufficientSharedLiquidityError, NegativeInputError, NonPositiveInputError, ReallocationAdapterSupplySharesUnderflowError, ReallocationAllocationUnderflowError, ReallocationWithdrawExceedsMarketSupplyError, UnknownReallocationActiveAdaptersError, UnknownReallocationAdapterError, UnknownReallocationAllocationError, UnknownReallocationMarketError, UnknownReallocationMarketPublicAllocatorConfigError, UnknownReallocationPublicAllocatorConfigError, UnknownReallocationVaultError, } from "../types/index.js";
7
+ import { InputExceedsMaxError, InsufficientSharedLiquidityError, NegativeInputError, NonPositiveInputError, ReallocationAdapterSupplySharesUnderflowError, ReallocationAllocationUnderflowError, ReallocationWithdrawExceedsMarketSupplyError, ReferralFeePctExceededError, UnknownReallocationActiveAdaptersError, UnknownReallocationAdapterError, UnknownReallocationAllocationError, UnknownReallocationMarketError, UnknownReallocationMarketPublicAllocatorConfigError, UnknownReallocationPublicAllocatorConfigError, UnknownReallocationVaultError, } from "../types/index.js";
7
8
  const MAX_SHARED_CAP_SEARCH_STEPS = 1024n;
8
9
  const createCapReserveState = (markets) => ({
9
10
  initialMarkets: { ...markets },
@@ -11,6 +12,17 @@ const createCapReserveState = (markets) => ({
11
12
  touchedPairs: new Map(),
12
13
  reserveByPairKey: new Map(),
13
14
  });
15
+ const cloneCapReserveState = (state) => {
16
+ const touchedPairs = new Map();
17
+ for (const [vault, pairs] of state.touchedPairs)
18
+ touchedPairs.set(vault, new Map(pairs));
19
+ return {
20
+ initialMarkets: { ...state.initialMarkets },
21
+ marketAccruals: new Map(state.marketAccruals),
22
+ touchedPairs,
23
+ reserveByPairKey: new Map(state.reserveByPairKey),
24
+ };
25
+ };
14
26
  /** Creates isolated transaction-scoped state for one simulation. @internal */
15
27
  const createSimulationContext = () => ({
16
28
  donatedPenaltyAssets: {},
@@ -75,10 +87,6 @@ const cloneAccrualVault = (vault, markets) => new AccrualVault({
75
87
  position: clonePosition(position, markets),
76
88
  })));
77
89
  const cloneAdapter = (adapter, markets) => {
78
- // BluePublicAllocator never moves Midnight liquidity, and reallocation never mutates a Midnight
79
- // adapter, so its read-only snapshot is shared as-is.
80
- if (adapter.type === "VaultV2MidnightAdapter")
81
- return adapter;
82
90
  const base = {
83
91
  address: adapter.address,
84
92
  parentVault: adapter.parentVault,
@@ -126,9 +134,8 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
126
134
  /**
127
135
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
128
136
  *
129
- * Constructor inputs are cloned, except Midnight adapter snapshots: those are
130
- * shared by reference and must be treated as read-only. Every simulated
131
- * reallocation returns a new instance. Planning keeps the transaction-scoped `firstTotalAssets`
137
+ * Constructor inputs are cloned. Every simulated reallocation returns a new
138
+ * instance. Planning keeps the transaction-scoped `firstTotalAssets`
132
139
  * denominator outside the durable snapshot while applying reallocations in
133
140
  * contract order. Penalty donations update simulated vault accounting but are
134
141
  * excluded from same-plan idle liquidity so round-up dust cannot create
@@ -166,6 +173,8 @@ export class VaultV2BlueReallocationData {
166
173
  mutableAllocations;
167
174
  /** Chain id associated with this snapshot. */
168
175
  chainId;
176
+ /** Timestamp of the block the state was fetched at. */
177
+ timestamp;
169
178
  /** Markets indexed by market id. */
170
179
  markets;
171
180
  /** Vault V2 entities indexed by address. */
@@ -187,6 +196,8 @@ export class VaultV2BlueReallocationData {
187
196
  constructor(input) {
188
197
  const isClone = input instanceof VaultV2BlueReallocationData;
189
198
  this.chainId = input.chainId;
199
+ this.timestamp =
200
+ input.timestamp == null ? undefined : BigInt(input.timestamp);
190
201
  this.mutableMarkets = {};
191
202
  this.mutableVaults = {};
192
203
  this.mutableAllocations = {};
@@ -250,8 +261,7 @@ export class VaultV2BlueReallocationData {
250
261
  /**
251
262
  * Clones the complete simulation snapshot.
252
263
  *
253
- * @returns A deep clone of this simulation state. Midnight adapter snapshots are
254
- * shared by reference and must be treated as read-only.
264
+ * @returns A deep clone of this simulation state.
255
265
  * @example
256
266
  * ```ts
257
267
  * import { markets } from "@morpho-org/morpho-test";
@@ -560,16 +570,29 @@ export class VaultV2BlueReallocationData {
560
570
  * Computes Vault V2 BluePublicAllocator calls available for a target market.
561
571
  *
562
572
  * Without `options.operation`, discovers every friendly call. With an
563
- * operation, targets the amount required by that borrow or loan-asset
564
- * withdrawal and falls back to 100% source utilization only when friendly
565
- * liquidity cannot cover the absolute shortfall. A shared relative-cap lower
566
- * bound may require one call to exceed the targeted amount. Friendly source
567
- * utilization defaults to 90% and is configurable through
568
- * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
569
- * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
570
- * considered. Market/vault state and the returned post-state stay at
571
- * `timestamp`; only target-market cap checks reserve interest the vault's
572
- * existing allocation would accrue through `timestamp + capAccrualBuffer`
573
+ * operation, penalty tiers are considered ascending, starting with free
574
+ * vaults. The free tier aims to bring the target market back to 90%
575
+ * utilization; positive tiers cover only the remaining absolute shortfall
576
+ * (borrows minus supply). Within each tier, source markets go to the
577
+ * friendly source utilization (90% by default) before 100%. Free capacity
578
+ * inside `allocatorCapHeadroom` is kept unused, so a penalized leg can cover
579
+ * it instead. Discovery and liquidity getters still count every vault up to
580
+ * `options.maxPenalty`. A shared relative-cap lower bound may require one call
581
+ * to exceed the targeted amount. For `refinance`, compute the plan on the
582
+ * destination-market handle (for example,
583
+ * `client.morpho.blue(destination.marketParams, chainId)`), not the source
584
+ * handle. Pass the source position's `borrowAssets` accrued to
585
+ * `max(now, source.lastUpdate, destination.lastUpdate) + 2h` as
586
+ * `operation.amount`; the optional `operation.referralFeePct` is WAD-scaled.
587
+ * The planner includes the referral fee and its allocator-leg penalties in
588
+ * destination debt, so penalized legs also cover their own penalty.
589
+ * Refinance never uses vaults with a 100% penalty.
590
+ * Friendly source utilization defaults to 90% and is configurable through
591
+ * `options.maxWithdrawalUtilization`. Market/vault state and the returned
592
+ * post-state stay at `timestamp`. An enabled operation that needs no
593
+ * reallocation still returns a clone accrued to `timestamp`. Only
594
+ * target-market cap checks reserve interest the vault's existing allocation
595
+ * would accrue through `timestamp + capAccrualBuffer`
573
596
  * (two hours by default; `0n` disables it). When an operation's plan would
574
597
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
575
598
  * BluePublicAllocator cap, the plan is reduced to the larger of the
@@ -610,8 +633,9 @@ export class VaultV2BlueReallocationData {
610
633
  * every leg of a plan.
611
634
  * @returns Flat action-ready reallocations and their post-simulation state.
612
635
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
613
- * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
636
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, `maxPenalty`, or `referralFeePct` is negative.
614
637
  * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
638
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
615
639
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
616
640
  * @throws {UnknownReallocationMarketError} when a required market is absent.
617
641
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -619,7 +643,7 @@ export class VaultV2BlueReallocationData {
619
643
  * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
620
644
  * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
621
645
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
622
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall.
646
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall and, for refinance, its planned allocator penalties.
623
647
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
624
648
  * @example
625
649
  * ```ts
@@ -673,6 +697,14 @@ export class VaultV2BlueReallocationData {
673
697
  const { amount, type } = operation;
674
698
  if (amount <= 0n)
675
699
  throw new NonPositiveInputError("amount", amount);
700
+ const referralFeePct = type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
701
+ if (referralFeePct < 0n)
702
+ throw new NegativeInputError("referralFeePct", referralFeePct);
703
+ if (referralFeePct >= MathLib.WAD)
704
+ throw new ReferralFeePctExceededError(referralFeePct);
705
+ const feeAssets = type === "refinance"
706
+ ? getBlueBundlesV1ReferralFeeAssets(amount, referralFeePct)
707
+ : 0n;
676
708
  const timestamp = options.timestamp == null
677
709
  ? this.getLatestSnapshotTimestamp()
678
710
  : BigInt(options.timestamp);
@@ -693,60 +725,150 @@ export class VaultV2BlueReallocationData {
693
725
  }
694
726
  const newTotalBorrowAssets = type === "borrow"
695
727
  ? market.totalBorrowAssets + amount
696
- : market.totalBorrowAssets;
728
+ : type === "refinance"
729
+ ? market.totalBorrowAssets + amount + feeAssets
730
+ : market.totalBorrowAssets;
697
731
  const newTotalSupplyAssets = type === "withdraw"
698
732
  ? market.totalSupplyAssets - amount
699
733
  : market.totalSupplyAssets;
734
+ const requiredAssets = MathLib.wDivUp(newTotalBorrowAssets, DEFAULT_SUPPLY_TARGET_UTILIZATION) -
735
+ newTotalSupplyAssets;
700
736
  if (MarketUtils.getUtilization({
701
737
  totalSupplyAssets: newTotalSupplyAssets,
702
738
  totalBorrowAssets: newTotalBorrowAssets,
703
- }) <= DEFAULT_SUPPLY_TARGET_UTILIZATION)
704
- return { reallocations: [], data: this };
705
- const requiredAssets = MathLib.wDivUp(newTotalBorrowAssets, DEFAULT_SUPPLY_TARGET_UTILIZATION) -
706
- newTotalSupplyAssets;
707
- if (requiredAssets <= 0n)
708
- return { reallocations: [], data: this };
739
+ }) <= DEFAULT_SUPPLY_TARGET_UTILIZATION ||
740
+ requiredAssets <= 0n) {
741
+ const data = this.clone();
742
+ data.setMarkets([market]);
743
+ return { reallocations: [], data };
744
+ }
709
745
  const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
710
746
  ? newTotalBorrowAssets - newTotalSupplyAssets
711
747
  : 0n;
748
+ const penaltyTiers = [
749
+ 0n,
750
+ ...new Set(Object.values(this.publicAllocatorConfigs).flatMap((config) => config != null && config.penalty > 0n && config.penalty <= maxPenalty
751
+ ? [config.penalty]
752
+ : [])),
753
+ ].sort(bigIntComparator((tier) => tier));
712
754
  const plan = (maxAssets, headroom) => {
713
- const reserves = createCapReserveState(this.mutableMarkets);
714
- const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
715
- context: createSimulationContext(),
716
- reserves,
717
- marketId,
718
- maxWithdrawalUtilization,
719
- maxAssets,
720
- capAccrualBuffer,
721
- allocatorCapHeadroom: headroom,
722
- options: normalizedOptions,
723
- });
724
- const reallocations = [...friendly.reallocations];
725
- const data = friendly.data;
726
- const friendlyMarket = data.getMarket(marketId);
727
- const friendlyBorrow = type === "borrow"
728
- ? friendlyMarket.totalBorrowAssets + amount
729
- : friendlyMarket.totalBorrowAssets;
730
- const friendlySupply = type === "withdraw"
731
- ? friendlyMarket.totalSupplyAssets - amount
732
- : friendlyMarket.totalSupplyAssets;
733
- if (friendlyBorrow > friendlySupply) {
734
- const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
735
- context: friendly.context,
736
- reserves,
737
- marketId,
738
- maxWithdrawalUtilization: MathLib.WAD,
739
- maxAssets: friendlyBorrow - friendlySupply,
740
- capAccrualBuffer,
741
- allocatorCapHeadroom: headroom,
742
- options: normalizedOptions,
743
- });
744
- reallocations.push(...fallback.reallocations);
755
+ let reserves = createCapReserveState(this.mutableMarkets);
756
+ const reallocations = [];
757
+ let data = this.clone();
758
+ let context = createSimulationContext();
759
+ let remainingShortfall = absoluteShortfall;
760
+ let allocatorCapBoundTargets = new Set();
761
+ let idleBoundVaults = new Set();
762
+ for (const penalty of penaltyTiers) {
763
+ if (type === "refinance" && penalty === MathLib.WAD)
764
+ continue;
765
+ let isFriendlyPass = true;
766
+ for (const utilization of [maxWithdrawalUtilization, MathLib.WAD]) {
767
+ const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
768
+ isFriendlyPass = false;
769
+ if (remainingShortfall === 0n && !isFreeFriendlyPass)
770
+ continue;
771
+ let passMaxAssets = isFreeFriendlyPass
772
+ ? maxAssets
773
+ : remainingShortfall;
774
+ const retryPaidPass = type === "refinance" && penalty > 0n;
775
+ if (retryPaidPass) {
776
+ passMaxAssets = MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
777
+ }
778
+ let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
779
+ // Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
780
+ const passStart = retryPaidPass
781
+ ? {
782
+ data: data.clone(),
783
+ context,
784
+ reserves: cloneCapReserveState(reserves),
785
+ reallocationCount: reallocations.length,
786
+ }
787
+ : undefined;
788
+ let previousPassReallocatedAssets = 0n;
789
+ let hi;
790
+ let bestAttempt;
791
+ while (true) {
792
+ if (passStart != null) {
793
+ data = passStart.data.clone();
794
+ context = passStart.context;
795
+ reserves = cloneCapReserveState(passStart.reserves);
796
+ reallocations.length = passStart.reallocationCount;
797
+ }
798
+ const pass = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
799
+ context,
800
+ reserves,
801
+ marketId,
802
+ maxWithdrawalUtilization: utilization,
803
+ maxAssets: passMaxAssets,
804
+ capAccrualBuffer,
805
+ allocatorCapHeadroom: headroom,
806
+ penalty,
807
+ options: normalizedOptions,
808
+ });
809
+ reallocations.push(...pass.reallocations);
810
+ data = pass.data;
811
+ context = pass.context;
812
+ if (isFreeFriendlyPass) {
813
+ allocatorCapBoundTargets = pass.allocatorCapBoundTargets;
814
+ idleBoundVaults = pass.idleBoundVaults;
815
+ }
816
+ const currentMarket = data.getMarket(marketId);
817
+ const penaltyAssets = type === "refinance"
818
+ ? getBlueBundlesV1PenaltyAssets(reallocations)
819
+ : 0n;
820
+ const borrow = type === "borrow"
821
+ ? currentMarket.totalBorrowAssets + amount
822
+ : type === "refinance"
823
+ ? currentMarket.totalBorrowAssets +
824
+ amount +
825
+ feeAssets +
826
+ penaltyAssets
827
+ : currentMarket.totalBorrowAssets;
828
+ const supply = type === "withdraw"
829
+ ? currentMarket.totalSupplyAssets - amount
830
+ : currentMarket.totalSupplyAssets;
831
+ remainingShortfall = borrow > supply ? borrow - supply : 0n;
832
+ const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
833
+ if (passStart == null)
834
+ break;
835
+ if (bestAttempt == null ||
836
+ remainingShortfall < bestAttempt.remainingShortfall ||
837
+ (remainingShortfall === bestAttempt.remainingShortfall &&
838
+ passReallocatedAssets < bestAttempt.passReallocatedAssets))
839
+ bestAttempt = {
840
+ data,
841
+ context,
842
+ reserves: cloneCapReserveState(reserves),
843
+ reallocations: pass.reallocations,
844
+ remainingShortfall,
845
+ passReallocatedAssets,
846
+ };
847
+ if (remainingShortfall === 0n)
848
+ hi = hi == null ? passMaxAssets : MathLib.min(hi, passMaxAssets);
849
+ else
850
+ lo = MathLib.max(lo, passMaxAssets);
851
+ if (hi != null) {
852
+ if (hi - lo <= 1n)
853
+ break;
854
+ passMaxAssets = (lo + hi) / 2n;
855
+ continue;
856
+ }
857
+ if (passReallocatedAssets <= previousPassReallocatedAssets)
858
+ break;
859
+ previousPassReallocatedAssets = passReallocatedAssets;
860
+ passMaxAssets += MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
861
+ }
862
+ if (passStart != null && bestAttempt != null) {
863
+ data = bestAttempt.data;
864
+ context = bestAttempt.context;
865
+ reserves = cloneCapReserveState(bestAttempt.reserves);
866
+ reallocations.length = passStart.reallocationCount;
867
+ reallocations.push(...bestAttempt.reallocations);
868
+ remainingShortfall = bestAttempt.remainingShortfall;
869
+ }
870
+ }
745
871
  }
746
- // The fallback pass only runs when the plan moves exactly the absolute
747
- // shortfall, which a reduced plan would move anyway.
748
- const allocatorCapBoundTargets = friendly.allocatorCapBoundTargets;
749
- const idleBoundVaults = friendly.idleBoundVaults;
750
872
  let reallocatedAssets = 0n;
751
873
  let unboundAssets = 0n;
752
874
  for (const { vault, from, to, assets } of reallocations) {
@@ -762,6 +884,10 @@ export class VaultV2BlueReallocationData {
762
884
  liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
763
885
  reallocatedAssets,
764
886
  unboundAssets,
887
+ coversShortfall: type === "refinance"
888
+ ? reallocatedAssets >=
889
+ absoluteShortfall + getBlueBundlesV1PenaltyAssets(reallocations)
890
+ : reallocatedAssets >= absoluteShortfall,
765
891
  };
766
892
  };
767
893
  // A leg that fills an allocator cap, or idle legs that together take
@@ -775,30 +901,32 @@ export class VaultV2BlueReallocationData {
775
901
  ? absoluteShortfall
776
902
  : target.unboundAssets, allocatorCapHeadroom);
777
903
  // Shared-cap fitting is not monotonic in the budget.
778
- if (selected.reallocatedAssets < absoluteShortfall &&
779
- target.reallocatedAssets >= absoluteShortfall)
904
+ if (!selected.coversShortfall && target.coversShortfall)
780
905
  selected = target;
781
906
  }
782
907
  let available = MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
783
908
  // Without headroom, `target` already is the full-cap plan toward the target.
784
909
  const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
785
910
  for (const maxAssets of fullCapBudgets) {
786
- if (selected.reallocatedAssets >= absoluteShortfall)
911
+ if (selected.coversShortfall)
787
912
  break;
788
913
  selected = plan(maxAssets, 0n);
789
914
  if (selected.reallocatedAssets > available)
790
915
  available = selected.reallocatedAssets;
791
916
  }
792
- if (selected.reallocatedAssets < absoluteShortfall) {
917
+ if (!selected.coversShortfall) {
793
918
  throw new InsufficientSharedLiquidityError({
794
919
  marketId,
795
- shortfall: absoluteShortfall,
920
+ shortfall: absoluteShortfall +
921
+ (type === "refinance"
922
+ ? getBlueBundlesV1PenaltyAssets(selected.reallocations)
923
+ : 0n),
796
924
  available,
797
925
  });
798
926
  }
799
927
  return { reallocations: selected.reallocations, data: selected.data };
800
928
  }
801
- computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, options = {}, }) {
929
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
802
930
  if (options.enabled === false)
803
931
  return {
804
932
  reallocations: [],
@@ -841,23 +969,23 @@ export class VaultV2BlueReallocationData {
841
969
  return {
842
970
  key,
843
971
  ids: getAdapterIds(adapterIdsCache, adapter, market),
844
- reserve: () => {
845
- let reserve = reserves.reserveByPairKey.get(key);
972
+ reserve: (reserveState) => {
973
+ let reserve = reserveState.reserveByPairKey.get(key);
846
974
  if (reserve == null) {
847
- let accruals = reserves.marketAccruals.get(market.id);
975
+ let accruals = reserveState.marketAccruals.get(market.id);
848
976
  if (accruals == null) {
849
- const initialMarket = reserves.initialMarkets[market.id];
977
+ const initialMarket = reserveState.initialMarkets[market.id];
850
978
  if (initialMarket == null)
851
979
  throw new UnknownReallocationMarketError(market.id);
852
980
  accruals = [
853
981
  initialMarket.accrueInterest(timestamp),
854
982
  initialMarket.accrueInterest(timestamp + capAccrualBuffer),
855
983
  ];
856
- reserves.marketAccruals.set(market.id, accruals);
984
+ reserveState.marketAccruals.set(market.id, accruals);
857
985
  }
858
986
  const [atTimestamp, projected] = accruals;
859
987
  reserve = MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
860
- reserves.reserveByPairKey.set(key, reserve);
988
+ reserveState.reserveByPairKey.set(key, reserve);
861
989
  }
862
990
  return reserve;
863
991
  },
@@ -874,7 +1002,7 @@ export class VaultV2BlueReallocationData {
874
1002
  if (seen.has(pair.key) || !pair.ids.includes(id))
875
1003
  continue;
876
1004
  seen.add(pair.key);
877
- reserve += pair.reserve();
1005
+ reserve += pair.reserve(reserves);
878
1006
  }
879
1007
  return reserve;
880
1008
  };
@@ -890,6 +1018,8 @@ export class VaultV2BlueReallocationData {
890
1018
  publicAllocatorConfig.penalty >
891
1019
  (options.maxPenalty ?? DEFAULT_MAX_REALLOCATION_PENALTY))
892
1020
  return;
1021
+ if (penalty != null && publicAllocatorConfig.penalty !== penalty)
1022
+ return;
893
1023
  const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
894
1024
  // Exclude rounded penalty dust from idle candidates so one donation
895
1025
  // cannot replenish liquidity for another same-plan reallocation.
@@ -940,7 +1070,7 @@ export class VaultV2BlueReallocationData {
940
1070
  const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
941
1071
  const allocatorHeadroom = MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
942
1072
  untracked +
943
- targetPair.reserve()), MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
1073
+ targetPair.reserve(reserves)), MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
944
1074
  const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
945
1075
  const minimumAllocationChange = MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
946
1076
  const blockedTargetIds = targetAllocations
@@ -1309,7 +1439,7 @@ export class VaultV2BlueReallocationData {
1309
1439
  }, utilization);
1310
1440
  }
1311
1441
  getLatestSnapshotTimestamp() {
1312
- let timestamp = 0n;
1442
+ let timestamp = this.timestamp ?? 0n;
1313
1443
  for (const market of Object.values(this.markets)) {
1314
1444
  if (market != null)
1315
1445
  timestamp = MathLib.max(timestamp, market.lastUpdate);
@@ -1354,6 +1484,7 @@ export class VaultV2BlueReallocationData {
1354
1484
  }
1355
1485
  data = new VaultV2BlueReallocationData({
1356
1486
  chainId: this.chainId,
1487
+ timestamp: this.timestamp,
1357
1488
  markets: probeMarkets,
1358
1489
  });
1359
1490
  if (sourceVaultKey != null) {
@@ -1,7 +1,7 @@
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,
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,
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, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError as BlueUnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, 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";
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, 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
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
7
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
package/lib/esm/errors.js CHANGED
@@ -1,6 +1,6 @@
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,
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,
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, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError as BlueUnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, 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, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, NegativeValueError, RegistryValueAlreadyRegisteredError, } 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, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, 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, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
@@ -1,6 +1,6 @@
1
- export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MidnightAdapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
1
+ export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  fetchPreLiquidationParams as fetchBluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MidnightAdapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
5
+ fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
6
6
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";
package/lib/esm/fetch.js CHANGED
@@ -1,6 +1,6 @@
1
- export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MidnightAdapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
1
+ export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  fetchPreLiquidationParams as fetchBluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MidnightAdapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
5
+ fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
6
6
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";
@@ -1,4 +1,4 @@
1
- import { type AccrualPosition, type MarketId } from "@morpho-org/blue-sdk";
1
+ import { type AccrualPosition, type MarketId, type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Market as MidnightMarket, type MarketInput as MidnightMarketInput } from "@morpho-org/midnight-sdk";
3
3
  import { type Address } from "viem";
4
4
  import { type VaultV2BlueReallocation } from "../types/index.js";
@@ -15,6 +15,16 @@ import { type VaultV2BlueReallocation } from "../types/index.js";
15
15
  * @internal
16
16
  */
17
17
  export declare const validateUint256Field: (field: string, value: bigint) => void;
18
+ /**
19
+ * Rejects market params whose cached `id` does not hash from their five tuple fields, so a
20
+ * hand-built or mutated object cannot make the SDK describe one market while calldata targets another.
21
+ *
22
+ * @param marketParams - Market params whose `id` must equal the id derived from the tuple.
23
+ * @returns Nothing when `marketParams.id` matches the derived id.
24
+ * @throws {MarketIdMismatchError} when `marketParams.id` differs from the derived id.
25
+ * @internal
26
+ */
27
+ export declare const validateMarketParamsId: (marketParams: MarketParams) => void;
18
28
  /**
19
29
  * Rejects a deadline that no periphery can honour: the contracts read `0` as "unset" and the ABI
20
30
  * slot is a `uint256`. Callers that also need the deadline to be in the future layer their own
@@ -34,6 +34,21 @@ export const validateUint256Field = (field, value) => {
34
34
  throw new InputExceedsMaxError({ field, value, max: maxUint256 });
35
35
  }
36
36
  };
37
+ /**
38
+ * Rejects market params whose cached `id` does not hash from their five tuple fields, so a
39
+ * hand-built or mutated object cannot make the SDK describe one market while calldata targets another.
40
+ *
41
+ * @param marketParams - Market params whose `id` must equal the id derived from the tuple.
42
+ * @returns Nothing when `marketParams.id` matches the derived id.
43
+ * @throws {MarketIdMismatchError} when `marketParams.id` differs from the derived id.
44
+ * @internal
45
+ */
46
+ export const validateMarketParamsId = (marketParams) => {
47
+ const derivedId = MarketUtils.getMarketId(marketParams);
48
+ if (marketParams.id !== derivedId) {
49
+ throw new MarketIdMismatchError(marketParams.id, derivedId);
50
+ }
51
+ };
37
52
  /**
38
53
  * Rejects a deadline that no periphery can honour: the contracts read `0` as "unset" and the ABI
39
54
  * slot is a `uint256`. Callers that also need the deadline to be in the future layer their own
@@ -7,13 +7,15 @@ import type { MarketInput, OfferStruct } from "@morpho-org/midnight-sdk";
7
7
  * @throws {EmptyMidnightTakeableOffersError} when no offers are provided.
8
8
  * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
9
9
  * @throws {MidnightTakeableOfferMarketMismatchError} when an offer belongs to another market.
10
- * @throws {MidnightCalldataEncodingError} when a market cannot be ABI-encoded.
10
+ * @throws {MidnightTakeableOfferZeroSellerReceiverError} when a sell offer routes seller proceeds to the zero address.
11
+ * @throws {MidnightCalldataEncodingError} when a market cannot be ABI-encoded or a sell offer's
12
+ * `receiverIfMakerIsSeller` is not an address.
11
13
  * @internal
12
14
  */
13
15
  export declare const validateTakeableOffers: (params: {
14
16
  readonly market: MarketInput;
15
17
  readonly takeableOffers: readonly {
16
- readonly offer: Pick<OfferStruct, "buy" | "market">;
18
+ readonly offer: Pick<OfferStruct, "buy" | "market" | "receiverIfMakerIsSeller">;
17
19
  }[];
18
20
  readonly expectedBuy: boolean;
19
21
  }) => `0x${string}`;