@morpho-org/morpho-sdk 9.0.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 (90) hide show
  1. package/README.md +3 -1
  2. package/lib/cjs/actions/blue/borrow.d.ts +1 -0
  3. package/lib/cjs/actions/blue/borrow.js +1 -0
  4. package/lib/cjs/actions/blue/refinance.d.ts +1 -0
  5. package/lib/cjs/actions/blue/refinance.js +3 -0
  6. package/lib/cjs/actions/blue/repay.d.ts +1 -0
  7. package/lib/cjs/actions/blue/repay.js +1 -0
  8. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +1 -0
  9. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -0
  10. package/lib/cjs/actions/blue/supply.d.ts +1 -0
  11. package/lib/cjs/actions/blue/supply.js +2 -0
  12. package/lib/cjs/actions/blue/supplyCollateral.d.ts +1 -0
  13. package/lib/cjs/actions/blue/supplyCollateral.js +1 -0
  14. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +1 -0
  15. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +2 -0
  16. package/lib/cjs/actions/blue/withdraw.d.ts +1 -0
  17. package/lib/cjs/actions/blue/withdraw.js +2 -0
  18. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +1 -0
  19. package/lib/cjs/actions/blue/withdrawCollateral.js +1 -0
  20. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
  21. package/lib/cjs/actions/midnight/takeLend.js +1 -0
  22. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  23. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
  24. package/lib/cjs/blue/errors.d.ts +1 -1
  25. package/lib/cjs/blue/errors.js +2 -1
  26. package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
  27. package/lib/cjs/client/morphoViemExtension.js +1 -7
  28. package/lib/cjs/entities/blue/blue.d.ts +43 -7
  29. package/lib/cjs/entities/blue/blue.js +27 -3
  30. package/lib/cjs/entities/midnight/midnight.d.ts +14 -6
  31. package/lib/cjs/entities/midnight/midnight.js +14 -6
  32. package/lib/cjs/entities/midnight/types.d.ts +9 -2
  33. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +3 -1
  34. package/lib/cjs/entities/vaultV2/vaultV2.js +8 -5
  35. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +40 -13
  36. package/lib/cjs/entities/vaultV2BlueReallocationData.js +207 -70
  37. package/lib/cjs/errors.d.ts +1 -1
  38. package/lib/cjs/errors.js +3 -2
  39. package/lib/cjs/helpers/validate.d.ts +11 -1
  40. package/lib/cjs/helpers/validate.js +17 -1
  41. package/lib/cjs/helpers/validateTakeableOffers.d.ts +4 -2
  42. package/lib/cjs/helpers/validateTakeableOffers.js +12 -1
  43. package/lib/cjs/types/error.d.ts +10 -1
  44. package/lib/cjs/types/error.js +13 -2
  45. package/lib/cjs/types/sharedLiquidity.d.ts +27 -11
  46. package/lib/esm/actions/blue/borrow.d.ts +1 -0
  47. package/lib/esm/actions/blue/borrow.js +1 -0
  48. package/lib/esm/actions/blue/refinance.d.ts +1 -0
  49. package/lib/esm/actions/blue/refinance.js +4 -1
  50. package/lib/esm/actions/blue/repay.d.ts +1 -0
  51. package/lib/esm/actions/blue/repay.js +1 -0
  52. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +1 -0
  53. package/lib/esm/actions/blue/repayWithdrawCollateral.js +3 -1
  54. package/lib/esm/actions/blue/supply.d.ts +1 -0
  55. package/lib/esm/actions/blue/supply.js +3 -1
  56. package/lib/esm/actions/blue/supplyCollateral.d.ts +1 -0
  57. package/lib/esm/actions/blue/supplyCollateral.js +1 -0
  58. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +1 -0
  59. package/lib/esm/actions/blue/supplyCollateralBorrow.js +3 -1
  60. package/lib/esm/actions/blue/withdraw.d.ts +1 -0
  61. package/lib/esm/actions/blue/withdraw.js +3 -1
  62. package/lib/esm/actions/blue/withdrawCollateral.d.ts +1 -0
  63. package/lib/esm/actions/blue/withdrawCollateral.js +1 -0
  64. package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
  65. package/lib/esm/actions/midnight/takeLend.js +1 -0
  66. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  67. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
  68. package/lib/esm/blue/errors.d.ts +1 -1
  69. package/lib/esm/blue/errors.js +1 -1
  70. package/lib/esm/client/morphoViemExtension.d.ts +1 -1
  71. package/lib/esm/client/morphoViemExtension.js +1 -7
  72. package/lib/esm/entities/blue/blue.d.ts +43 -7
  73. package/lib/esm/entities/blue/blue.js +27 -3
  74. package/lib/esm/entities/midnight/midnight.d.ts +14 -6
  75. package/lib/esm/entities/midnight/midnight.js +14 -6
  76. package/lib/esm/entities/midnight/types.d.ts +9 -2
  77. package/lib/esm/entities/vaultV2/vaultV2.d.ts +3 -1
  78. package/lib/esm/entities/vaultV2/vaultV2.js +9 -6
  79. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +40 -13
  80. package/lib/esm/entities/vaultV2BlueReallocationData.js +208 -71
  81. package/lib/esm/errors.d.ts +1 -1
  82. package/lib/esm/errors.js +1 -1
  83. package/lib/esm/helpers/validate.d.ts +11 -1
  84. package/lib/esm/helpers/validate.js +15 -0
  85. package/lib/esm/helpers/validateTakeableOffers.d.ts +4 -2
  86. package/lib/esm/helpers/validateTakeableOffers.js +13 -2
  87. package/lib/esm/types/error.d.ts +10 -1
  88. package/lib/esm/types/error.js +11 -1
  89. package/lib/esm/types/sharedLiquidity.d.ts +27 -11
  90. package/package.json +4 -4
@@ -4,6 +4,7 @@ exports.VaultV2BlueReallocationData = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
+ const common_js_1 = require("../actions/blue/common.js");
7
8
  const constant_js_1 = require("../helpers/constant.js");
8
9
  const utilization_js_1 = require("../helpers/utilization.js");
9
10
  const index_js_1 = require("../types/index.js");
@@ -14,6 +15,17 @@ const createCapReserveState = (markets) => ({
14
15
  touchedPairs: new Map(),
15
16
  reserveByPairKey: new Map(),
16
17
  });
18
+ const cloneCapReserveState = (state) => {
19
+ const touchedPairs = new Map();
20
+ for (const [vault, pairs] of state.touchedPairs)
21
+ touchedPairs.set(vault, new Map(pairs));
22
+ return {
23
+ initialMarkets: { ...state.initialMarkets },
24
+ marketAccruals: new Map(state.marketAccruals),
25
+ touchedPairs,
26
+ reserveByPairKey: new Map(state.reserveByPairKey),
27
+ };
28
+ };
17
29
  /** Creates isolated transaction-scoped state for one simulation. @internal */
18
30
  const createSimulationContext = () => ({
19
31
  donatedPenaltyAssets: {},
@@ -164,6 +176,8 @@ class VaultV2BlueReallocationData {
164
176
  mutableAllocations;
165
177
  /** Chain id associated with this snapshot. */
166
178
  chainId;
179
+ /** Timestamp of the block the state was fetched at. */
180
+ timestamp;
167
181
  /** Markets indexed by market id. */
168
182
  markets;
169
183
  /** Vault V2 entities indexed by address. */
@@ -185,6 +199,8 @@ class VaultV2BlueReallocationData {
185
199
  constructor(input) {
186
200
  const isClone = input instanceof VaultV2BlueReallocationData;
187
201
  this.chainId = input.chainId;
202
+ this.timestamp =
203
+ input.timestamp == null ? undefined : BigInt(input.timestamp);
188
204
  this.mutableMarkets = {};
189
205
  this.mutableVaults = {};
190
206
  this.mutableAllocations = {};
@@ -557,16 +573,29 @@ class VaultV2BlueReallocationData {
557
573
  * Computes Vault V2 BluePublicAllocator calls available for a target market.
558
574
  *
559
575
  * Without `options.operation`, discovers every friendly call. With an
560
- * operation, targets the amount required by that borrow or loan-asset
561
- * withdrawal and falls back to 100% source utilization only when friendly
562
- * liquidity cannot cover the absolute shortfall. A shared relative-cap lower
563
- * bound may require one call to exceed the targeted amount. Friendly source
564
- * utilization defaults to 90% and is configurable through
565
- * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
566
- * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
567
- * considered. Market/vault state and the returned post-state stay at
568
- * `timestamp`; only target-market cap checks reserve interest the vault's
569
- * existing allocation would accrue through `timestamp + capAccrualBuffer`
576
+ * operation, penalty tiers are considered ascending, starting with free
577
+ * vaults. The free tier aims to bring the target market back to 90%
578
+ * utilization; positive tiers cover only the remaining absolute shortfall
579
+ * (borrows minus supply). Within each tier, source markets go to the
580
+ * friendly source utilization (90% by default) before 100%. Free capacity
581
+ * inside `allocatorCapHeadroom` is kept unused, so a penalized leg can cover
582
+ * it instead. Discovery and liquidity getters still count every vault up to
583
+ * `options.maxPenalty`. A shared relative-cap lower bound may require one call
584
+ * to exceed the targeted amount. For `refinance`, compute the plan on the
585
+ * destination-market handle (for example,
586
+ * `client.morpho.blue(destination.marketParams, chainId)`), not the source
587
+ * handle. Pass the source position's `borrowAssets` accrued to
588
+ * `max(now, source.lastUpdate, destination.lastUpdate) + 2h` as
589
+ * `operation.amount`; the optional `operation.referralFeePct` is WAD-scaled.
590
+ * The planner includes the referral fee and its allocator-leg penalties in
591
+ * destination debt, so penalized legs also cover their own penalty.
592
+ * Refinance never uses vaults with a 100% penalty.
593
+ * Friendly source utilization defaults to 90% and is configurable through
594
+ * `options.maxWithdrawalUtilization`. Market/vault state and the returned
595
+ * post-state stay at `timestamp`. An enabled operation that needs no
596
+ * reallocation still returns a clone accrued to `timestamp`. Only
597
+ * target-market cap checks reserve interest the vault's existing allocation
598
+ * would accrue through `timestamp + capAccrualBuffer`
570
599
  * (two hours by default; `0n` disables it). When an operation's plan would
571
600
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
572
601
  * BluePublicAllocator cap, the plan is reduced to the larger of the
@@ -607,8 +636,9 @@ class VaultV2BlueReallocationData {
607
636
  * every leg of a plan.
608
637
  * @returns Flat action-ready reallocations and their post-simulation state.
609
638
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
610
- * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
639
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, `maxPenalty`, or `referralFeePct` is negative.
611
640
  * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
641
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
612
642
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
613
643
  * @throws {UnknownReallocationMarketError} when a required market is absent.
614
644
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -616,7 +646,7 @@ class VaultV2BlueReallocationData {
616
646
  * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
617
647
  * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
618
648
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
619
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall.
649
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall and, for refinance, its planned allocator penalties.
620
650
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
621
651
  * @example
622
652
  * ```ts
@@ -670,6 +700,14 @@ class VaultV2BlueReallocationData {
670
700
  const { amount, type } = operation;
671
701
  if (amount <= 0n)
672
702
  throw new index_js_1.NonPositiveInputError("amount", amount);
703
+ const referralFeePct = type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
704
+ if (referralFeePct < 0n)
705
+ throw new index_js_1.NegativeInputError("referralFeePct", referralFeePct);
706
+ if (referralFeePct >= blue_sdk_1.MathLib.WAD)
707
+ throw new index_js_1.ReferralFeePctExceededError(referralFeePct);
708
+ const feeAssets = type === "refinance"
709
+ ? (0, common_js_1.getBlueBundlesV1ReferralFeeAssets)(amount, referralFeePct)
710
+ : 0n;
673
711
  const timestamp = options.timestamp == null
674
712
  ? this.getLatestSnapshotTimestamp()
675
713
  : BigInt(options.timestamp);
@@ -690,60 +728,150 @@ class VaultV2BlueReallocationData {
690
728
  }
691
729
  const newTotalBorrowAssets = type === "borrow"
692
730
  ? market.totalBorrowAssets + amount
693
- : market.totalBorrowAssets;
731
+ : type === "refinance"
732
+ ? market.totalBorrowAssets + amount + feeAssets
733
+ : market.totalBorrowAssets;
694
734
  const newTotalSupplyAssets = type === "withdraw"
695
735
  ? market.totalSupplyAssets - amount
696
736
  : market.totalSupplyAssets;
737
+ const requiredAssets = blue_sdk_1.MathLib.wDivUp(newTotalBorrowAssets, constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION) -
738
+ newTotalSupplyAssets;
697
739
  if (blue_sdk_1.MarketUtils.getUtilization({
698
740
  totalSupplyAssets: newTotalSupplyAssets,
699
741
  totalBorrowAssets: newTotalBorrowAssets,
700
- }) <= constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION)
701
- return { reallocations: [], data: this };
702
- const requiredAssets = blue_sdk_1.MathLib.wDivUp(newTotalBorrowAssets, constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION) -
703
- newTotalSupplyAssets;
704
- if (requiredAssets <= 0n)
705
- return { reallocations: [], data: this };
742
+ }) <= constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION ||
743
+ requiredAssets <= 0n) {
744
+ const data = this.clone();
745
+ data.setMarkets([market]);
746
+ return { reallocations: [], data };
747
+ }
706
748
  const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
707
749
  ? newTotalBorrowAssets - newTotalSupplyAssets
708
750
  : 0n;
751
+ const penaltyTiers = [
752
+ 0n,
753
+ ...new Set(Object.values(this.publicAllocatorConfigs).flatMap((config) => config != null && config.penalty > 0n && config.penalty <= maxPenalty
754
+ ? [config.penalty]
755
+ : [])),
756
+ ].sort((0, morpho_ts_1.bigIntComparator)((tier) => tier));
709
757
  const plan = (maxAssets, headroom) => {
710
- const reserves = createCapReserveState(this.mutableMarkets);
711
- const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
712
- context: createSimulationContext(),
713
- reserves,
714
- marketId,
715
- maxWithdrawalUtilization,
716
- maxAssets,
717
- capAccrualBuffer,
718
- allocatorCapHeadroom: headroom,
719
- options: normalizedOptions,
720
- });
721
- const reallocations = [...friendly.reallocations];
722
- const data = friendly.data;
723
- const friendlyMarket = data.getMarket(marketId);
724
- const friendlyBorrow = type === "borrow"
725
- ? friendlyMarket.totalBorrowAssets + amount
726
- : friendlyMarket.totalBorrowAssets;
727
- const friendlySupply = type === "withdraw"
728
- ? friendlyMarket.totalSupplyAssets - amount
729
- : friendlyMarket.totalSupplyAssets;
730
- if (friendlyBorrow > friendlySupply) {
731
- const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
732
- context: friendly.context,
733
- reserves,
734
- marketId,
735
- maxWithdrawalUtilization: blue_sdk_1.MathLib.WAD,
736
- maxAssets: friendlyBorrow - friendlySupply,
737
- capAccrualBuffer,
738
- allocatorCapHeadroom: headroom,
739
- options: normalizedOptions,
740
- });
741
- reallocations.push(...fallback.reallocations);
758
+ let reserves = createCapReserveState(this.mutableMarkets);
759
+ const reallocations = [];
760
+ let data = this.clone();
761
+ let context = createSimulationContext();
762
+ let remainingShortfall = absoluteShortfall;
763
+ let allocatorCapBoundTargets = new Set();
764
+ let idleBoundVaults = new Set();
765
+ for (const penalty of penaltyTiers) {
766
+ if (type === "refinance" && penalty === blue_sdk_1.MathLib.WAD)
767
+ continue;
768
+ let isFriendlyPass = true;
769
+ for (const utilization of [maxWithdrawalUtilization, blue_sdk_1.MathLib.WAD]) {
770
+ const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
771
+ isFriendlyPass = false;
772
+ if (remainingShortfall === 0n && !isFreeFriendlyPass)
773
+ continue;
774
+ let passMaxAssets = isFreeFriendlyPass
775
+ ? maxAssets
776
+ : remainingShortfall;
777
+ const retryPaidPass = type === "refinance" && penalty > 0n;
778
+ if (retryPaidPass) {
779
+ passMaxAssets = blue_sdk_1.MathLib.mulDivUp(remainingShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - penalty);
780
+ }
781
+ let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
782
+ // Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
783
+ const passStart = retryPaidPass
784
+ ? {
785
+ data: data.clone(),
786
+ context,
787
+ reserves: cloneCapReserveState(reserves),
788
+ reallocationCount: reallocations.length,
789
+ }
790
+ : undefined;
791
+ let previousPassReallocatedAssets = 0n;
792
+ let hi;
793
+ let bestAttempt;
794
+ while (true) {
795
+ if (passStart != null) {
796
+ data = passStart.data.clone();
797
+ context = passStart.context;
798
+ reserves = cloneCapReserveState(passStart.reserves);
799
+ reallocations.length = passStart.reallocationCount;
800
+ }
801
+ const pass = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
802
+ context,
803
+ reserves,
804
+ marketId,
805
+ maxWithdrawalUtilization: utilization,
806
+ maxAssets: passMaxAssets,
807
+ capAccrualBuffer,
808
+ allocatorCapHeadroom: headroom,
809
+ penalty,
810
+ options: normalizedOptions,
811
+ });
812
+ reallocations.push(...pass.reallocations);
813
+ data = pass.data;
814
+ context = pass.context;
815
+ if (isFreeFriendlyPass) {
816
+ allocatorCapBoundTargets = pass.allocatorCapBoundTargets;
817
+ idleBoundVaults = pass.idleBoundVaults;
818
+ }
819
+ const currentMarket = data.getMarket(marketId);
820
+ const penaltyAssets = type === "refinance"
821
+ ? (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations)
822
+ : 0n;
823
+ const borrow = type === "borrow"
824
+ ? currentMarket.totalBorrowAssets + amount
825
+ : type === "refinance"
826
+ ? currentMarket.totalBorrowAssets +
827
+ amount +
828
+ feeAssets +
829
+ penaltyAssets
830
+ : currentMarket.totalBorrowAssets;
831
+ const supply = type === "withdraw"
832
+ ? currentMarket.totalSupplyAssets - amount
833
+ : currentMarket.totalSupplyAssets;
834
+ remainingShortfall = borrow > supply ? borrow - supply : 0n;
835
+ const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
836
+ if (passStart == null)
837
+ break;
838
+ if (bestAttempt == null ||
839
+ remainingShortfall < bestAttempt.remainingShortfall ||
840
+ (remainingShortfall === bestAttempt.remainingShortfall &&
841
+ passReallocatedAssets < bestAttempt.passReallocatedAssets))
842
+ bestAttempt = {
843
+ data,
844
+ context,
845
+ reserves: cloneCapReserveState(reserves),
846
+ reallocations: pass.reallocations,
847
+ remainingShortfall,
848
+ passReallocatedAssets,
849
+ };
850
+ if (remainingShortfall === 0n)
851
+ hi = hi == null ? passMaxAssets : blue_sdk_1.MathLib.min(hi, passMaxAssets);
852
+ else
853
+ lo = blue_sdk_1.MathLib.max(lo, passMaxAssets);
854
+ if (hi != null) {
855
+ if (hi - lo <= 1n)
856
+ break;
857
+ passMaxAssets = (lo + hi) / 2n;
858
+ continue;
859
+ }
860
+ if (passReallocatedAssets <= previousPassReallocatedAssets)
861
+ break;
862
+ previousPassReallocatedAssets = passReallocatedAssets;
863
+ passMaxAssets += blue_sdk_1.MathLib.mulDivUp(remainingShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - penalty);
864
+ }
865
+ if (passStart != null && bestAttempt != null) {
866
+ data = bestAttempt.data;
867
+ context = bestAttempt.context;
868
+ reserves = cloneCapReserveState(bestAttempt.reserves);
869
+ reallocations.length = passStart.reallocationCount;
870
+ reallocations.push(...bestAttempt.reallocations);
871
+ remainingShortfall = bestAttempt.remainingShortfall;
872
+ }
873
+ }
742
874
  }
743
- // The fallback pass only runs when the plan moves exactly the absolute
744
- // shortfall, which a reduced plan would move anyway.
745
- const allocatorCapBoundTargets = friendly.allocatorCapBoundTargets;
746
- const idleBoundVaults = friendly.idleBoundVaults;
747
875
  let reallocatedAssets = 0n;
748
876
  let unboundAssets = 0n;
749
877
  for (const { vault, from, to, assets } of reallocations) {
@@ -759,6 +887,10 @@ class VaultV2BlueReallocationData {
759
887
  liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
760
888
  reallocatedAssets,
761
889
  unboundAssets,
890
+ coversShortfall: type === "refinance"
891
+ ? reallocatedAssets >=
892
+ absoluteShortfall + (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations)
893
+ : reallocatedAssets >= absoluteShortfall,
762
894
  };
763
895
  };
764
896
  // A leg that fills an allocator cap, or idle legs that together take
@@ -772,30 +904,32 @@ class VaultV2BlueReallocationData {
772
904
  ? absoluteShortfall
773
905
  : target.unboundAssets, allocatorCapHeadroom);
774
906
  // Shared-cap fitting is not monotonic in the budget.
775
- if (selected.reallocatedAssets < absoluteShortfall &&
776
- target.reallocatedAssets >= absoluteShortfall)
907
+ if (!selected.coversShortfall && target.coversShortfall)
777
908
  selected = target;
778
909
  }
779
910
  let available = blue_sdk_1.MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
780
911
  // Without headroom, `target` already is the full-cap plan toward the target.
781
912
  const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
782
913
  for (const maxAssets of fullCapBudgets) {
783
- if (selected.reallocatedAssets >= absoluteShortfall)
914
+ if (selected.coversShortfall)
784
915
  break;
785
916
  selected = plan(maxAssets, 0n);
786
917
  if (selected.reallocatedAssets > available)
787
918
  available = selected.reallocatedAssets;
788
919
  }
789
- if (selected.reallocatedAssets < absoluteShortfall) {
920
+ if (!selected.coversShortfall) {
790
921
  throw new index_js_1.InsufficientSharedLiquidityError({
791
922
  marketId,
792
- shortfall: absoluteShortfall,
923
+ shortfall: absoluteShortfall +
924
+ (type === "refinance"
925
+ ? (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations)
926
+ : 0n),
793
927
  available,
794
928
  });
795
929
  }
796
930
  return { reallocations: selected.reallocations, data: selected.data };
797
931
  }
798
- computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, options = {}, }) {
932
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
799
933
  if (options.enabled === false)
800
934
  return {
801
935
  reallocations: [],
@@ -838,23 +972,23 @@ class VaultV2BlueReallocationData {
838
972
  return {
839
973
  key,
840
974
  ids: getAdapterIds(adapterIdsCache, adapter, market),
841
- reserve: () => {
842
- let reserve = reserves.reserveByPairKey.get(key);
975
+ reserve: (reserveState) => {
976
+ let reserve = reserveState.reserveByPairKey.get(key);
843
977
  if (reserve == null) {
844
- let accruals = reserves.marketAccruals.get(market.id);
978
+ let accruals = reserveState.marketAccruals.get(market.id);
845
979
  if (accruals == null) {
846
- const initialMarket = reserves.initialMarkets[market.id];
980
+ const initialMarket = reserveState.initialMarkets[market.id];
847
981
  if (initialMarket == null)
848
982
  throw new index_js_1.UnknownReallocationMarketError(market.id);
849
983
  accruals = [
850
984
  initialMarket.accrueInterest(timestamp),
851
985
  initialMarket.accrueInterest(timestamp + capAccrualBuffer),
852
986
  ];
853
- reserves.marketAccruals.set(market.id, accruals);
987
+ reserveState.marketAccruals.set(market.id, accruals);
854
988
  }
855
989
  const [atTimestamp, projected] = accruals;
856
990
  reserve = blue_sdk_1.MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
857
- reserves.reserveByPairKey.set(key, reserve);
991
+ reserveState.reserveByPairKey.set(key, reserve);
858
992
  }
859
993
  return reserve;
860
994
  },
@@ -871,7 +1005,7 @@ class VaultV2BlueReallocationData {
871
1005
  if (seen.has(pair.key) || !pair.ids.includes(id))
872
1006
  continue;
873
1007
  seen.add(pair.key);
874
- reserve += pair.reserve();
1008
+ reserve += pair.reserve(reserves);
875
1009
  }
876
1010
  return reserve;
877
1011
  };
@@ -887,6 +1021,8 @@ class VaultV2BlueReallocationData {
887
1021
  publicAllocatorConfig.penalty >
888
1022
  (options.maxPenalty ?? constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY))
889
1023
  return;
1024
+ if (penalty != null && publicAllocatorConfig.penalty !== penalty)
1025
+ return;
890
1026
  const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
891
1027
  // Exclude rounded penalty dust from idle candidates so one donation
892
1028
  // cannot replenish liquidity for another same-plan reallocation.
@@ -937,7 +1073,7 @@ class VaultV2BlueReallocationData {
937
1073
  const untracked = blue_sdk_1.MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
938
1074
  const allocatorHeadroom = blue_sdk_1.MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
939
1075
  untracked +
940
- targetPair.reserve()), blue_sdk_1.MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
1076
+ targetPair.reserve(reserves)), blue_sdk_1.MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
941
1077
  const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
942
1078
  const minimumAllocationChange = blue_sdk_1.MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
943
1079
  const blockedTargetIds = targetAllocations
@@ -1306,7 +1442,7 @@ class VaultV2BlueReallocationData {
1306
1442
  }, utilization);
1307
1443
  }
1308
1444
  getLatestSnapshotTimestamp() {
1309
- let timestamp = 0n;
1445
+ let timestamp = this.timestamp ?? 0n;
1310
1446
  for (const market of Object.values(this.markets)) {
1311
1447
  if (market != null)
1312
1448
  timestamp = blue_sdk_1.MathLib.max(timestamp, market.lastUpdate);
@@ -1351,6 +1487,7 @@ class VaultV2BlueReallocationData {
1351
1487
  }
1352
1488
  data = new VaultV2BlueReallocationData({
1353
1489
  chainId: this.chainId,
1490
+ timestamp: this.timestamp,
1354
1491
  markets: probeMarkets,
1355
1492
  });
1356
1493
  if (sourceVaultKey != null) {
@@ -1,7 +1,7 @@
1
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, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
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
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
7
  export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
package/lib/cjs/errors.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidnightPayloadDecodeError = exports.MidnightMempoolValidationError = exports.MidnightApiError = exports.InvalidMidnightTypedDataSignatureError = exports.InvalidMidnightTreeHeightError = exports.InvalidMidnightTreeError = exports.InvalidMidnightTickSpacingError = exports.InvalidMidnightRatifierV1AddressError = exports.InvalidMidnightRateRatifierV1TimeError = exports.InvalidMidnightRateRatifierV1TickError = exports.InvalidMidnightRateRatifierV1RateError = exports.InvalidMidnightPositionLossFactorError = exports.InvalidMidnightPositionAccrualTimestampError = exports.InvalidMidnightPositionAccrualStateError = exports.InvalidMidnightOfferParameterError = exports.InvalidMidnightOfferGroupError = exports.InvalidMidnightApiResponseError = exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMidnightMarketParameterError = exports.InvalidMidnightEcrecoverSignatureVError = exports.MidnightChainIdMismatchError = exports.UnsupportedPermitDomainExtensionsError = exports.UnnamedAbiOutputsError = exports.UnknownAbiFunctionError = exports.NonTupleReturnValueError = exports.MissingPermitDomainNameError = exports.BlueMarketParamsIdMismatchError = exports.MalformedTokenMetadataError = exports.isBlueUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getBlueUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedBlueVaultV2AdapterError = exports.UnsupportedBluePreLiquidationParamsError = exports.UnsupportedBlueMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownBlueVaultConfigError = exports.UnknownBlueTokenPriceError = exports.UnknownBlueTokenError = exports.UnknownBlueOfFactory = exports.UnknownBlueMarketParamsError = exports.UnknownBlueMarketAllocationError = exports.UnknownBlueFactory = exports.UnknownBlueDataError = exports.UnknownAddressError = exports.InvalidBlueMarketParamsError = exports.IncompleteChainRegistryError = exports.BlueErrors = void 0;
4
- exports.RegistryValueAlreadyRegisteredError = exports.NegativeValueError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.DivisionByZeroError = exports._try = exports.UnknownMidnightCollateralIndexError = exports.MidnightTickOutOfRangeError = exports.MidnightSettlementFeeExceedsPriceError = exports.MidnightRatifierV1TakerNotAllowedError = exports.MidnightRateRatifierV1BoundOverflowError = exports.MidnightPriceGreaterThanOneError = void 0;
3
+ exports.MidnightMempoolValidationError = exports.MidnightApiError = exports.InvalidMidnightTypedDataSignatureError = exports.InvalidMidnightTreeHeightError = exports.InvalidMidnightTreeError = exports.InvalidMidnightTickSpacingError = exports.InvalidMidnightRatifierV1AddressError = exports.InvalidMidnightRateRatifierV1TimeError = exports.InvalidMidnightRateRatifierV1TickError = exports.InvalidMidnightRateRatifierV1RateError = exports.InvalidMidnightPositionLossFactorError = exports.InvalidMidnightPositionAccrualTimestampError = exports.InvalidMidnightPositionAccrualStateError = exports.InvalidMidnightOfferParameterError = exports.InvalidMidnightOfferGroupError = exports.InvalidMidnightApiResponseError = exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMidnightMarketParameterError = exports.InvalidMidnightEcrecoverSignatureVError = exports.MidnightChainIdMismatchError = exports.UnsupportedPermitDomainExtensionsError = exports.UnnamedAbiOutputsError = exports.UnknownAbiFunctionError = exports.Permit2ExpirationOutOfRangeError = exports.NonTupleReturnValueError = exports.MissingPermitDomainNameError = exports.BlueMarketParamsIdMismatchError = exports.MalformedTokenMetadataError = exports.isBlueUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getBlueUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedBlueVaultV2AdapterError = exports.UnsupportedBluePreLiquidationParamsError = exports.UnsupportedBlueMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownBlueVaultConfigError = exports.UnknownBlueTokenPriceError = exports.UnknownBlueTokenError = exports.UnknownBlueOfFactory = exports.UnknownBlueMarketParamsError = exports.UnknownBlueMarketAllocationError = exports.UnknownBlueFactory = exports.UnknownBlueDataError = exports.UnknownAddressError = exports.InvalidBlueMarketParamsError = exports.IncompleteChainRegistryError = exports.BlueErrors = void 0;
4
+ exports.RegistryValueAlreadyRegisteredError = exports.NegativeValueError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.DivisionByZeroError = exports._try = exports.UnknownMidnightCollateralIndexError = exports.MidnightTickOutOfRangeError = exports.MidnightSettlementFeeExceedsPriceError = exports.MidnightRatifierV1TakerNotAllowedError = exports.MidnightRateRatifierV1BoundOverflowError = exports.MidnightPriceGreaterThanOneError = exports.MidnightPayloadDecodeError = void 0;
5
5
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  Object.defineProperty(exports, "BlueErrors", { enumerable: true, get: function () { return blue_sdk_1.BlueErrors; } });
7
7
  Object.defineProperty(exports, "IncompleteChainRegistryError", { enumerable: true, get: function () { return blue_sdk_1.IncompleteChainRegistryError; } });
@@ -31,6 +31,7 @@ Object.defineProperty(exports, "MalformedTokenMetadataError", { enumerable: true
31
31
  Object.defineProperty(exports, "BlueMarketParamsIdMismatchError", { enumerable: true, get: function () { return blue_sdk_viem_1.MarketParamsIdMismatchError; } });
32
32
  Object.defineProperty(exports, "MissingPermitDomainNameError", { enumerable: true, get: function () { return blue_sdk_viem_1.MissingPermitDomainNameError; } });
33
33
  Object.defineProperty(exports, "NonTupleReturnValueError", { enumerable: true, get: function () { return blue_sdk_viem_1.NonTupleReturnValueError; } });
34
+ Object.defineProperty(exports, "Permit2ExpirationOutOfRangeError", { enumerable: true, get: function () { return blue_sdk_viem_1.Permit2ExpirationOutOfRangeError; } });
34
35
  Object.defineProperty(exports, "UnknownAbiFunctionError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnknownAbiFunctionError; } });
35
36
  Object.defineProperty(exports, "UnnamedAbiOutputsError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnnamedAbiOutputsError; } });
36
37
  Object.defineProperty(exports, "UnsupportedPermitDomainExtensionsError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnsupportedPermitDomainExtensionsError; } });
@@ -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
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateSlippageTolerance = exports.validateVaultV2BlueReallocations = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeVaultAsset = exports.validateMidnightNativeAmount = exports.validateNativeAsset = exports.validateChainId = exports.validatePositionHealth = exports.getMidnightMaxSafeDebt = exports.validateAccrualPosition = exports.validateMidnightMarketChainId = exports.validateReferralFee = exports.validateDeadline = exports.validateUint256Field = void 0;
3
+ exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateSlippageTolerance = exports.validateVaultV2BlueReallocations = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeVaultAsset = exports.validateMidnightNativeAmount = exports.validateNativeAsset = exports.validateChainId = exports.validatePositionHealth = exports.getMidnightMaxSafeDebt = exports.validateAccrualPosition = exports.validateMidnightMarketChainId = exports.validateReferralFee = exports.validateDeadline = exports.validateMarketParamsId = exports.validateUint256Field = void 0;
4
4
  exports.validateUserAddress = validateUserAddress;
5
5
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
@@ -39,6 +39,22 @@ const validateUint256Field = (field, value) => {
39
39
  }
40
40
  };
41
41
  exports.validateUint256Field = validateUint256Field;
42
+ /**
43
+ * Rejects market params whose cached `id` does not hash from their five tuple fields, so a
44
+ * hand-built or mutated object cannot make the SDK describe one market while calldata targets another.
45
+ *
46
+ * @param marketParams - Market params whose `id` must equal the id derived from the tuple.
47
+ * @returns Nothing when `marketParams.id` matches the derived id.
48
+ * @throws {MarketIdMismatchError} when `marketParams.id` differs from the derived id.
49
+ * @internal
50
+ */
51
+ const validateMarketParamsId = (marketParams) => {
52
+ const derivedId = blue_sdk_1.MarketUtils.getMarketId(marketParams);
53
+ if (marketParams.id !== derivedId) {
54
+ throw new index_js_1.MarketIdMismatchError(marketParams.id, derivedId);
55
+ }
56
+ };
57
+ exports.validateMarketParamsId = validateMarketParamsId;
42
58
  /**
43
59
  * Rejects a deadline that no periphery can honour: the contracts read `0` as "unset" and the ABI
44
60
  * 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}`;
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateTakeableOffers = void 0;
4
+ const viem_1 = require("viem");
4
5
  const index_js_1 = require("../types/index.js");
5
6
  const encodeMidnightCalldata_js_1 = require("./encodeMidnightCalldata.js");
7
+ const validateMidnightAccount_js_1 = require("./validateMidnightAccount.js");
6
8
  const validateOfferSides_js_1 = require("./validateOfferSides.js");
7
9
  /**
8
10
  * Validates the pure invariants shared by Midnight take entity and action layers.
@@ -12,7 +14,9 @@ const validateOfferSides_js_1 = require("./validateOfferSides.js");
12
14
  * @throws {EmptyMidnightTakeableOffersError} when no offers are provided.
13
15
  * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
14
16
  * @throws {MidnightTakeableOfferMarketMismatchError} when an offer belongs to another market.
15
- * @throws {MidnightCalldataEncodingError} when a market cannot be ABI-encoded.
17
+ * @throws {MidnightTakeableOfferZeroSellerReceiverError} when a sell offer routes seller proceeds to the zero address.
18
+ * @throws {MidnightCalldataEncodingError} when a market cannot be ABI-encoded or a sell offer's
19
+ * `receiverIfMakerIsSeller` is not an address.
16
20
  * @internal
17
21
  */
18
22
  const validateTakeableOffers = (params) => {
@@ -30,6 +34,13 @@ const validateTakeableOffers = (params) => {
30
34
  actualMarket: actualMarketId,
31
35
  });
32
36
  }
37
+ if (take.offer.buy)
38
+ continue;
39
+ // Reject a malformed address before viem compares it.
40
+ (0, validateMidnightAccount_js_1.validateMidnightAddress)(`takeableOffers[${index}].offer.receiverIfMakerIsSeller`, take.offer.receiverIfMakerIsSeller);
41
+ if ((0, viem_1.isAddressEqual)(take.offer.receiverIfMakerIsSeller, viem_1.zeroAddress)) {
42
+ throw new index_js_1.MidnightTakeableOfferZeroSellerReceiverError({ index });
43
+ }
33
44
  }
34
45
  return marketId;
35
46
  };
@@ -1322,7 +1322,10 @@ export declare class EmptyBlueParkingMarketError extends Error {
1322
1322
  readonly marketId: MarketId;
1323
1323
  });
1324
1324
  }
1325
- /** Thrown when parked assets would mint no Morpho Blue supply shares. */
1325
+ /**
1326
+ * Thrown when parked assets would mint no Morpho Blue supply shares at preparation time; see
1327
+ * `MorphoMidnight.supplyBlueMakeLend` for why this is not an execution-time guarantee.
1328
+ */
1326
1329
  export declare class ZeroBlueParkingSharesError extends Error {
1327
1330
  constructor(params: {
1328
1331
  readonly marketId: MarketId;
@@ -1337,6 +1340,12 @@ export declare class MidnightTakeableOfferMarketMismatchError extends Error {
1337
1340
  actualMarket: string;
1338
1341
  });
1339
1342
  }
1343
+ /** Thrown when a quoted Midnight sell offer routes its seller proceeds to the zero address. */
1344
+ export declare class MidnightTakeableOfferZeroSellerReceiverError extends Error {
1345
+ constructor(params: {
1346
+ index: number;
1347
+ });
1348
+ }
1340
1349
  /** Thrown when a Midnight offer's ratifier does not match its tree's ratifier route. */
1341
1350
  export declare class MidnightOfferRatifierMismatchError extends Error {
1342
1351
  constructor(params: {