@morpho-org/morpho-sdk 6.2.0 → 6.3.1

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.
@@ -2,9 +2,15 @@ import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMark
2
2
  import { _try, bigIntComparator } from "@morpho-org/morpho-ts";
3
3
  import { isAddressEqual } from "viem";
4
4
  import { DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, MAX_REALLOCATION_PENALTY, } from "../helpers/constant.js";
5
- import { resolveMaxWithdrawalUtilization } from "../helpers/utilization.js";
5
+ import { resolveCapAccrualBuffer, resolveMaxWithdrawalUtilization, } from "../helpers/utilization.js";
6
6
  import { InputExceedsMaxError, InsufficientSharedLiquidityError, NegativeInputError, NonPositiveInputError, ReallocationAdapterSupplySharesUnderflowError, ReallocationAllocationUnderflowError, ReallocationWithdrawExceedsMarketSupplyError, UnknownReallocationActiveAdaptersError, UnknownReallocationAdapterError, UnknownReallocationAllocationError, UnknownReallocationMarketError, UnknownReallocationMarketPublicAllocatorConfigError, UnknownReallocationPublicAllocatorConfigError, UnknownReallocationVaultError, } from "../types/index.js";
7
7
  const MAX_SHARED_CAP_SEARCH_STEPS = 1024n;
8
+ const createCapReserveState = (markets) => ({
9
+ initialMarkets: { ...markets },
10
+ marketAccruals: new Map(),
11
+ touchedPairs: new Map(),
12
+ reserveByPairKey: new Map(),
13
+ });
8
14
  /** Creates isolated transaction-scoped state for one simulation. @internal */
9
15
  const createSimulationContext = () => ({
10
16
  donatedPenaltyAssets: {},
@@ -555,11 +561,18 @@ export class VaultV2BlueReallocationData {
555
561
  * utilization defaults to 90% and is configurable through
556
562
  * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
557
563
  * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
558
- * considered. Targets with no remaining supply or allocator capacity are skipped before
559
- * projecting source interest. The adapter's minimum share minting requirement, supply-share
560
- * limits, and target absolute or zero relative caps are checked against a one-asset deposit.
561
- * Shared cap IDs that a source withdrawal can reduce remain eligible, as do deposits whose
562
- * allocation does not increase after rounding.
564
+ * considered. Market/vault state and the returned post-state stay at
565
+ * `timestamp`; only target-market cap checks reserve interest the vault's
566
+ * existing allocation would accrue through `timestamp + capAccrualBuffer`
567
+ * (two hours by default; `0n` disables it). For market-source reallocations
568
+ * the source position's interest is also reserved on cap ids shared with the
569
+ * target, and reserves persist across every leg of a plan. Targets with no remaining supply
570
+ * or allocator capacity are skipped before projecting source interest. The
571
+ * adapter's minimum share minting requirement, supply-share limits, and target
572
+ * absolute or zero relative caps are checked against a one-asset deposit.
573
+ * Shared cap IDs that a source withdrawal can reduce remain eligible. Each
574
+ * accepted leg counts at least its requested `assets` against the target cap
575
+ * IDs, so a leg sized to a cap leaves no rounding headroom.
563
576
  *
564
577
  * Shared-cap discovery is conservative. Operation planning searches at most
565
578
  * 1,024 base units above its targeted amount for the nearest executable fit.
@@ -569,9 +582,15 @@ export class VaultV2BlueReallocationData {
569
582
  *
570
583
  * @param marketId - Target Blue market id.
571
584
  * @param options - Optional discovery controls and operation to support.
585
+ * Market/vault state and returned post-state stay at `timestamp`; only
586
+ * target-market cap checks reserve interest on the vault's existing allocation
587
+ * through `timestamp + capAccrualBuffer` (two hours by default; `0n` disables).
588
+ * For market-source reallocations the source position's interest is also
589
+ * reserved on cap ids shared with the target, and reserves persist across
590
+ * every leg of a plan.
572
591
  * @returns Flat action-ready reallocations and their post-simulation state.
573
592
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
574
- * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
593
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
575
594
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
576
595
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
577
596
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -616,13 +635,16 @@ export class VaultV2BlueReallocationData {
616
635
  return { reallocations: [], data: this };
617
636
  const maxWithdrawalUtilization = resolveMaxWithdrawalUtilization(options.maxWithdrawalUtilization);
618
637
  const maxPenalty = resolveMaxPenalty(options.maxPenalty);
638
+ const capAccrualBuffer = resolveCapAccrualBuffer(options.capAccrualBuffer);
619
639
  const resolvedOptions = { ...options, maxPenalty };
620
640
  const operation = options.operation;
621
641
  if (operation == null) {
622
642
  const { reallocations, data } = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
623
643
  context: createSimulationContext(),
644
+ reserves: createCapReserveState(this.mutableMarkets),
624
645
  marketId,
625
646
  maxWithdrawalUtilization,
647
+ capAccrualBuffer,
626
648
  options: resolvedOptions,
627
649
  });
628
650
  return { reallocations, data };
@@ -663,11 +685,14 @@ export class VaultV2BlueReallocationData {
663
685
  newTotalSupplyAssets;
664
686
  if (requiredAssets <= 0n)
665
687
  return { reallocations: [], data: this };
688
+ const reserves = createCapReserveState(this.mutableMarkets);
666
689
  const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
667
690
  context: createSimulationContext(),
691
+ reserves,
668
692
  marketId,
669
693
  maxWithdrawalUtilization,
670
694
  maxAssets: requiredAssets,
695
+ capAccrualBuffer,
671
696
  options: normalizedOptions,
672
697
  });
673
698
  const reallocations = [...friendly.reallocations];
@@ -682,9 +707,11 @@ export class VaultV2BlueReallocationData {
682
707
  if (friendlyBorrow > friendlySupply) {
683
708
  const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
684
709
  context: friendly.context,
710
+ reserves,
685
711
  marketId,
686
712
  maxWithdrawalUtilization: MathLib.WAD,
687
713
  maxAssets: friendlyBorrow - friendlySupply,
714
+ capAccrualBuffer,
688
715
  options: normalizedOptions,
689
716
  });
690
717
  reallocations.push(...fallback.reallocations);
@@ -702,7 +729,7 @@ export class VaultV2BlueReallocationData {
702
729
  }
703
730
  return { reallocations, data };
704
731
  }
705
- computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, marketId, maxWithdrawalUtilization, maxAssets, options = {}, }) {
732
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, options = {}, }) {
706
733
  if (options.enabled === false)
707
734
  return { reallocations: [], data: this, context };
708
735
  this.getMarket(marketId);
@@ -722,6 +749,56 @@ export class VaultV2BlueReallocationData {
722
749
  const adapterIdsCache = new Map();
723
750
  const activeAdaptersCache = new Map();
724
751
  let remainingAssets = maxAssets;
752
+ // Onchain, market interest is booked once at transaction start, on pre-plan
753
+ // positions at pre-plan rates, and stays on touched positions' cap ids.
754
+ // This reserve state is shared across every planner pass and leg of the plan.
755
+ // biome-ignore lint/complexity/useMaxParams: a pair is identified by its vault, adapter, and market.
756
+ const getPair = (vault, adapter, market) => {
757
+ const key = `${vault}:${adapter.address}:${market.id}`.toLowerCase();
758
+ const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
759
+ if (touched != null)
760
+ return touched;
761
+ const shares = adapter.supplyShares[market.id] ?? 0n;
762
+ return {
763
+ key,
764
+ ids: getAdapterIds(adapterIdsCache, adapter, market),
765
+ reserve: () => {
766
+ let reserve = reserves.reserveByPairKey.get(key);
767
+ if (reserve == null) {
768
+ let accruals = reserves.marketAccruals.get(market.id);
769
+ if (accruals == null) {
770
+ const initialMarket = reserves.initialMarkets[market.id];
771
+ if (initialMarket == null)
772
+ throw new UnknownReallocationMarketError(market.id);
773
+ accruals = [
774
+ initialMarket.accrueInterest(timestamp),
775
+ initialMarket.accrueInterest(timestamp + capAccrualBuffer),
776
+ ];
777
+ reserves.marketAccruals.set(market.id, accruals);
778
+ }
779
+ const [atTimestamp, projected] = accruals;
780
+ reserve = MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
781
+ reserves.reserveByPairKey.set(key, reserve);
782
+ }
783
+ return reserve;
784
+ },
785
+ };
786
+ };
787
+ // biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
788
+ const capReserve = (vault, id, candidatePairs) => {
789
+ let reserve = 0n;
790
+ const seen = new Set();
791
+ for (const pair of [
792
+ ...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
793
+ ...candidatePairs,
794
+ ]) {
795
+ if (seen.has(pair.key) || !pair.ids.includes(id))
796
+ continue;
797
+ seen.add(pair.key);
798
+ reserve += pair.reserve();
799
+ }
800
+ return reserve;
801
+ };
725
802
  while (remainingAssets == null || remainingAssets > 0n) {
726
803
  const candidates = vaults
727
804
  .map((vaultAddress) => {
@@ -759,6 +836,7 @@ export class VaultV2BlueReallocationData {
759
836
  if (!isAddressEqual(targetMarket.params.loanToken, vault.asset) ||
760
837
  !isAddressEqual(targetMarket.params.irm, adapter.adaptiveCurveIrm))
761
838
  continue;
839
+ const targetPair = getPair(vaultAddress, adapter, targetMarket);
762
840
  const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
763
841
  const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
764
842
  if (!isAddressEqual(marketPublicAllocatorConfig.vault, vaultAddress) ||
@@ -775,14 +853,19 @@ export class VaultV2BlueReallocationData {
775
853
  ];
776
854
  if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n))
777
855
  continue;
778
- const expectedSupplyAssets = targetMarket.toSupplyAssets(adapter.supplyShares[marketId] ?? 0n);
856
+ const adapterShares = adapter.supplyShares[marketId] ?? 0n;
857
+ const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
779
858
  const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
780
- const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation + untracked);
781
- const minimumAllocation = minimumSupply.market.toSupplyAssets((adapter.supplyShares[marketId] ?? 0n) + minimumSupply.shares);
782
- const minimumAllocationChange = minimumAllocation - adapterMarketCapAllocation.allocation;
859
+ const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
860
+ untracked +
861
+ targetPair.reserve());
862
+ const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
863
+ const minimumAllocationChange = MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
783
864
  const blockedTargetIds = targetAllocations
784
- .filter(({ allocation, absoluteCap, relativeCap }) => {
785
- const nextAllocation = allocation + minimumAllocationChange;
865
+ .filter(({ allocation, absoluteCap, relativeCap, id }) => {
866
+ const nextAllocation = allocation +
867
+ capReserve(vaultAddress, id, [targetPair]) +
868
+ minimumAllocationChange;
786
869
  return (nextAllocation > absoluteCap ||
787
870
  (relativeCap === 0n && nextAllocation > 0n));
788
871
  })
@@ -800,11 +883,14 @@ export class VaultV2BlueReallocationData {
800
883
  const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
801
884
  if (assets > 0n) {
802
885
  rawCandidates.push({
803
- vault: vaultAddress,
804
- from: { type: "idle" },
805
- to: { adapter: adapter.address },
806
- assets,
807
- penalty: publicAllocatorConfig.penalty,
886
+ reallocation: {
887
+ vault: vaultAddress,
888
+ from: { type: "idle" },
889
+ to: { adapter: adapter.address },
890
+ assets,
891
+ penalty: publicAllocatorConfig.penalty,
892
+ },
893
+ targetPair,
808
894
  });
809
895
  }
810
896
  }
@@ -838,6 +924,7 @@ export class VaultV2BlueReallocationData {
838
924
  // A withdrawal can create target headroom only for shared cap IDs.
839
925
  if (blockedTargetIds.some((id) => !sourceIds.includes(id)))
840
926
  continue;
927
+ const sourcePair = getPair(vaultAddress, sourceAdapter, sourceMarket);
841
928
  const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
842
929
  data.setMarkets([accruedSourceMarket]);
843
930
  const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
@@ -845,32 +932,32 @@ export class VaultV2BlueReallocationData {
845
932
  if (assets <= 0n)
846
933
  continue;
847
934
  rawCandidates.push({
848
- vault: vaultAddress,
849
- from: {
850
- type: "market",
851
- adapter: sourceAdapter.address,
852
- marketParams: sourceMarket.params,
935
+ reallocation: {
936
+ vault: vaultAddress,
937
+ from: {
938
+ type: "market",
939
+ adapter: sourceAdapter.address,
940
+ marketParams: sourceMarket.params,
941
+ },
942
+ to: { adapter: adapter.address },
943
+ assets,
944
+ penalty: publicAllocatorConfig.penalty,
853
945
  },
854
- to: { adapter: adapter.address },
855
- assets,
856
- penalty: publicAllocatorConfig.penalty,
946
+ targetPair,
947
+ sourcePair,
857
948
  });
858
949
  }
859
950
  }
860
951
  }
861
952
  const capCompatibleCandidates = [];
862
- for (const reallocation of rawCandidates) {
953
+ for (const { reallocation, targetPair, sourcePair, } of rawCandidates) {
863
954
  let lower = 0n;
864
955
  let upper = reallocation.assets;
865
- const reallocationAdapter = data.getAdapter(reallocation.vault, reallocation.to.adapter);
866
- const targetIds = getAdapterIds(adapterIdsCache, reallocationAdapter, targetMarket);
867
- const sourceIds = new Set();
868
- if (reallocation.from.type === "market") {
869
- const sourceAdapter = data.getAdapter(reallocation.vault, reallocation.from.adapter);
870
- const sourceMarket = data.getMarket(reallocation.from.marketParams.id);
871
- for (const id of getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket))
872
- sourceIds.add(id);
873
- }
956
+ const targetIds = targetPair.ids;
957
+ const sourceIds = new Set(sourcePair?.ids ?? []);
958
+ const reserveById = new Map();
959
+ for (const id of targetIds)
960
+ reserveById.set(id, capReserve(reallocation.vault, id, sourcePair == null ? [targetPair] : [targetPair, sourcePair]));
874
961
  const probeReallocation = (assets) => {
875
962
  if (targetMarket.totalSupplyShares +
876
963
  targetMarket.toSupplyShares(assets, "Down") >
@@ -894,8 +981,11 @@ export class VaultV2BlueReallocationData {
894
981
  for (const id of targetIds) {
895
982
  const allocation = postTransition.data.getAllocation(reallocation.vault, id);
896
983
  const capacity = VaultV2Utils.allocationHeadroom({ ...allocation, allocation: 0n }, firstTotalAssets).value;
984
+ // The reserve covers interest accrued before inclusion by every
985
+ // position the plan touched on this cap id, as booked onchain.
897
986
  const withinCap = allocation.absoluteCap > 0n &&
898
- allocation.allocation <= capacity;
987
+ allocation.allocation + (reserveById.get(id) ?? 0n) <=
988
+ capacity;
899
989
  if (!withinCap) {
900
990
  withinAllCaps = false;
901
991
  if (!sourceIds.has(id))
@@ -932,22 +1022,34 @@ export class VaultV2BlueReallocationData {
932
1022
  }
933
1023
  if (selectedAssets > 0n && probe?.withinAllCaps === true)
934
1024
  capCompatibleCandidates.push({
935
- ...reallocation,
936
- assets: selectedAssets,
1025
+ reallocation: { ...reallocation, assets: selectedAssets },
1026
+ targetPair,
1027
+ sourcePair,
937
1028
  });
938
1029
  }
939
- return capCompatibleCandidates.sort(bigIntComparator(({ assets }) => assets, "desc"))[0];
1030
+ return capCompatibleCandidates.sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"))[0];
940
1031
  })
941
1032
  .filter((candidate) => candidate != null)
942
- .sort(bigIntComparator(({ assets }) => assets, "desc"));
1033
+ .sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"));
943
1034
  const largest = candidates[0];
944
1035
  if (largest == null)
945
1036
  return { reallocations, data, context: simulationContext };
946
- const reallocation = largest;
947
- reallocations.push(reallocation);
1037
+ const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, } = largest;
1038
+ const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1039
+ let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1040
+ if (touchedVaultPairs == null) {
1041
+ touchedVaultPairs = new Map();
1042
+ reserves.touchedPairs.set(touchedVaultKey, touchedVaultPairs);
1043
+ }
1044
+ if (!touchedVaultPairs.has(acceptedTargetPair.key))
1045
+ touchedVaultPairs.set(acceptedTargetPair.key, acceptedTargetPair);
1046
+ if (acceptedSourcePair != null &&
1047
+ !touchedVaultPairs.has(acceptedSourcePair.key))
1048
+ touchedVaultPairs.set(acceptedSourcePair.key, acceptedSourcePair);
1049
+ reallocations.push(acceptedReallocation);
948
1050
  const transition = data.applyPublicReallocation({
949
1051
  context: simulationContext,
950
- reallocation,
1052
+ reallocation: acceptedReallocation,
951
1053
  targetMarketId: marketId,
952
1054
  timestamp,
953
1055
  adapterIdsCache,
@@ -955,18 +1057,25 @@ export class VaultV2BlueReallocationData {
955
1057
  data = transition.data;
956
1058
  simulationContext = transition.context;
957
1059
  if (remainingAssets != null)
958
- remainingAssets -= reallocation.assets;
1060
+ remainingAssets -= acceptedReallocation.assets;
959
1061
  }
960
1062
  return { reallocations, data, context: simulationContext };
961
1063
  }
962
1064
  /**
963
1065
  * Sums friendly Vault V2 shared liquidity available to a target market.
1066
+ * Market/vault state and returned post-state stay at `timestamp`; only
1067
+ * target-market cap checks reserve interest on the vault's existing allocation
1068
+ * through `timestamp + capAccrualBuffer` (two hours by default; `0n` disables).
1069
+ * For market-source reallocations the source position's interest is also
1070
+ * reserved on cap ids shared with the target, and reserves persist across
1071
+ * every leg of a plan.
964
1072
  *
965
1073
  * @param marketId - Target Blue market id.
966
- * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
1074
+ * @param options - Optional timestamp, cap-accrual buffer, enable flag, vault
1075
+ * allowlist, source utilization ceiling, and maximum penalty.
967
1076
  * @returns Reallocatable market and idle assets, or `0n` when none are available; rounding-only shared-cap fits may be conservatively omitted.
968
1077
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
969
- * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
1078
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
970
1079
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
971
1080
  * @throws {UnknownReallocationMarketError} when a required market is absent.
972
1081
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -1000,26 +1109,35 @@ export class VaultV2BlueReallocationData {
1000
1109
  getPublicReallocationLiquidity(marketId, options) {
1001
1110
  if (options?.enabled === false)
1002
1111
  return 0n;
1112
+ const capAccrualBuffer = resolveCapAccrualBuffer(options?.capAccrualBuffer);
1003
1113
  const maxPenalty = resolveMaxPenalty(options?.maxPenalty);
1004
1114
  return this.clone()
1005
1115
  .computeVaultV2BlueReallocationsAtUtilizationInPlace({
1006
1116
  context: createSimulationContext(),
1117
+ reserves: createCapReserveState(this.mutableMarkets),
1007
1118
  marketId,
1008
1119
  maxWithdrawalUtilization: resolveMaxWithdrawalUtilization(options?.maxWithdrawalUtilization),
1120
+ capAccrualBuffer,
1009
1121
  options: { ...options, maxPenalty },
1010
1122
  })
1011
1123
  .reallocations.reduce((total, { assets }) => total + assets, 0n);
1012
1124
  }
1013
1125
  /**
1014
1126
  * Computes borrow liquidity to a target utilization, including friendly
1015
- * Vault V2 public reallocations.
1127
+ * Vault V2 public reallocations. Market/vault state and returned post-state
1128
+ * stay at `timestamp`; only target-market cap checks reserve interest on the
1129
+ * vault's existing allocation through `timestamp + capAccrualBuffer` (two
1130
+ * hours by default; `0n` disables). For market-source reallocations the
1131
+ * source position's interest is also reserved on cap ids shared with the
1132
+ * target, and reserves persist across every leg of a plan.
1016
1133
  *
1017
1134
  * @param marketId - Target Blue market id.
1018
1135
  * @param utilization - Desired utilization, scaled by WAD. Defaults to 90%.
1019
- * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
1136
+ * @param options - Optional timestamp, cap-accrual buffer, enable flag, vault
1137
+ * allowlist, source utilization ceiling, and maximum penalty.
1020
1138
  * @returns Borrowable assets while remaining at or below `utilization`; rounding-only shared-cap fits may be conservatively omitted.
1021
1139
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
1022
- * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
1140
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
1023
1141
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
1024
1142
  * @throws {UnknownReallocationMarketError} when a required market is absent.
1025
1143
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -1053,6 +1171,7 @@ export class VaultV2BlueReallocationData {
1053
1171
  */
1054
1172
  // biome-ignore lint/complexity/useMaxParams: mirrors the existing V1 metric API
1055
1173
  getAvailableLiquidityToUtilization(marketId, utilization = DEFAULT_SUPPLY_TARGET_UTILIZATION, options) {
1174
+ const capAccrualBuffer = resolveCapAccrualBuffer(options?.capAccrualBuffer);
1056
1175
  const timestamp = options?.timestamp == null
1057
1176
  ? this.getLatestSnapshotTimestamp()
1058
1177
  : BigInt(options.timestamp);
@@ -1063,8 +1182,10 @@ export class VaultV2BlueReallocationData {
1063
1182
  const availableLiquidity = this.clone()
1064
1183
  .computeVaultV2BlueReallocationsAtUtilizationInPlace({
1065
1184
  context: createSimulationContext(),
1185
+ reserves: createCapReserveState(this.mutableMarkets),
1066
1186
  marketId,
1067
1187
  maxWithdrawalUtilization: resolveMaxWithdrawalUtilization(options?.maxWithdrawalUtilization),
1188
+ capAccrualBuffer,
1068
1189
  options: {
1069
1190
  ...options,
1070
1191
  timestamp,
@@ -1244,21 +1365,15 @@ export class VaultV2BlueReallocationData {
1244
1365
  if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id))
1245
1366
  targetAdapter.markets.push(supply.market);
1246
1367
  data.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
1247
- const targetChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1368
+ const simulatedChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1369
+ // The adapter's rounded expected-assets delta can differ by one wei at inclusion,
1370
+ // so cap tracking assumes each accepted leg adds at least its requested assets.
1371
+ const targetChange = MathLib.max(simulatedChange, reallocation.assets);
1248
1372
  for (const id of targetIds) {
1249
1373
  const allocation = data.getAllocation(reallocation.vault, id);
1250
- const nextAllocation = allocation.allocation + targetChange;
1251
- if (nextAllocation < 0n) {
1252
- throw new ReallocationAllocationUnderflowError({
1253
- vault: reallocation.vault,
1254
- id,
1255
- allocation: allocation.allocation,
1256
- change: targetChange,
1257
- });
1258
- }
1259
1374
  data.mutableAllocations[allocationsKey][id] = {
1260
1375
  ...allocation,
1261
- allocation: nextAllocation,
1376
+ allocation: allocation.allocation + targetChange,
1262
1377
  };
1263
1378
  }
1264
1379
  vault.assetBalance -= reallocation.assets;
@@ -7,6 +7,14 @@ export declare const DEFAULT_MAX_REALLOCATION_PENALTY = 0n;
7
7
  export declare const MAX_REALLOCATION_PENALTY = 1000000000000000000n;
8
8
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
9
9
  export declare const DEFAULT_LLTV_BUFFER: bigint;
10
+ /**
11
+ * Forward interest-accrual window, in seconds (2 hours), reserved in target-market
12
+ * cap checks (BluePublicAllocator max-in, Vault V2 absolute and relative caps) when
13
+ * planning reallocations, so a transaction included after the quote block does not
14
+ * revert on a cap check. Override with
15
+ * `VaultV2BluePublicAllocatorOptions.capAccrualBuffer`.
16
+ */
17
+ export declare const DEFAULT_CAP_ACCRUAL_BUFFER: bigint;
10
18
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
11
19
  export declare const MAX_ABSOLUTE_SHARE_PRICE: bigint;
12
20
  /**
@@ -1,4 +1,5 @@
1
1
  import { ChainId, MathLib } from "@morpho-org/blue-sdk";
2
+ import { Time } from "@morpho-org/morpho-ts";
2
3
  import { maxUint96 } from "viem";
3
4
  /** Maximum slippage tolerance: 10% */
4
5
  export const MAX_SLIPPAGE_TOLERANCE = MathLib.WAD / 10n;
@@ -8,6 +9,14 @@ export const DEFAULT_MAX_REALLOCATION_PENALTY = 0n;
8
9
  export const MAX_REALLOCATION_PENALTY = MathLib.WAD;
9
10
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
10
11
  export const DEFAULT_LLTV_BUFFER = MathLib.WAD / 200n;
12
+ /**
13
+ * Forward interest-accrual window, in seconds (2 hours), reserved in target-market
14
+ * cap checks (BluePublicAllocator max-in, Vault V2 absolute and relative caps) when
15
+ * planning reallocations, so a transaction included after the quote block does not
16
+ * revert on a cap check. Override with
17
+ * `VaultV2BluePublicAllocatorOptions.capAccrualBuffer`.
18
+ */
19
+ export const DEFAULT_CAP_ACCRUAL_BUFFER = Time.s.from.h(2n);
11
20
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
12
21
  export const MAX_ABSOLUTE_SHARE_PRICE = 100n * MathLib.RAY;
13
22
  /**
@@ -1,4 +1,4 @@
1
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
1
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
2
2
  export { addTransactionMetadata } from "./metadata.js";
3
3
  export { type PreviewVaultV2ForceWithdrawParams, previewVaultV2ForceWithdraw, type VaultV2ForceWithdrawPreview, } from "./previewVaultV2ForceWithdraw.js";
4
4
  export { type PreviewVaultV2InKindRedeemParams, previewVaultV2InKindRedeem, type VaultV2InKindRedeemMarketPreview, } from "./previewVaultV2InKindRedeem.js";
@@ -1,4 +1,4 @@
1
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
1
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
2
2
  export { addTransactionMetadata } from "./metadata.js";
3
3
  export { previewVaultV2ForceWithdraw, } from "./previewVaultV2ForceWithdraw.js";
4
4
  export { previewVaultV2InKindRedeem, } from "./previewVaultV2InKindRedeem.js";
@@ -1,3 +1,16 @@
1
+ import { type BigIntish } from "@morpho-org/blue-sdk";
2
+ /**
3
+ * Resolves and validates the target-market cap-accrual buffer.
4
+ * @internal
5
+ * @param value - Optional buffer duration in seconds.
6
+ * @returns The non-negative buffer duration, defaulting to two hours.
7
+ * @throws {NegativeInputError} when the buffer is negative.
8
+ * @example
9
+ * ```ts
10
+ * const buffer = resolveCapAccrualBuffer(undefined);
11
+ * ```
12
+ */
13
+ export declare const resolveCapAccrualBuffer: (value?: BigIntish) => bigint;
1
14
  /**
2
15
  * Resolves and validates a source withdrawal utilization ceiling.
3
16
  * @internal
@@ -1,6 +1,23 @@
1
1
  import { MathLib } from "@morpho-org/blue-sdk";
2
2
  import { InputExceedsMaxError, NegativeInputError } from "../types/index.js";
3
- import { DEFAULT_WITHDRAWAL_TARGET_UTILIZATION } from "./constant.js";
3
+ import { DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, } from "./constant.js";
4
+ /**
5
+ * Resolves and validates the target-market cap-accrual buffer.
6
+ * @internal
7
+ * @param value - Optional buffer duration in seconds.
8
+ * @returns The non-negative buffer duration, defaulting to two hours.
9
+ * @throws {NegativeInputError} when the buffer is negative.
10
+ * @example
11
+ * ```ts
12
+ * const buffer = resolveCapAccrualBuffer(undefined);
13
+ * ```
14
+ */
15
+ export const resolveCapAccrualBuffer = (value) => {
16
+ const buffer = value == null ? DEFAULT_CAP_ACCRUAL_BUFFER : BigInt(value);
17
+ if (buffer < 0n)
18
+ throw new NegativeInputError("capAccrualBuffer", buffer);
19
+ return buffer;
20
+ };
4
21
  /**
5
22
  * Resolves and validates a source withdrawal utilization ceiling.
6
23
  * @internal
@@ -4,8 +4,26 @@ import type { Address } from "viem";
4
4
  export interface VaultV2BluePublicAllocatorOptions {
5
5
  /** Whether Vault V2 public allocator discovery is enabled. */
6
6
  readonly enabled?: boolean;
7
- /** Timestamp at which market and Vault V2 interest is evaluated. */
7
+ /**
8
+ * Timestamp at which market and Vault V2 state is evaluated. Canonical state
9
+ * and the returned post-state stay at this timestamp; only target-market cap
10
+ * checks reserve interest on the vault's existing allocation through this
11
+ * timestamp plus `capAccrualBuffer`. For market-source reallocations the
12
+ * source position's interest is also reserved on cap ids shared with the
13
+ * target, and reserves persist across every leg of a plan.
14
+ */
8
15
  readonly timestamp?: BigIntish;
16
+ /**
17
+ * Seconds beyond `timestamp` through which target-market cap checks reserve
18
+ * interest on the vault's existing allocation. For market-source
19
+ * reallocations the source position's interest is also reserved on cap ids
20
+ * shared with the target, and reserves persist across every leg of a plan.
21
+ * Market and Vault V2 state, including the returned post-state, stay at
22
+ * `timestamp`. Set to `0n` to disable.
23
+ *
24
+ * @default DEFAULT_CAP_ACCRUAL_BUFFER (2h)
25
+ */
26
+ readonly capAccrualBuffer?: BigIntish;
9
27
  /**
10
28
  * Vault V2 addresses to consider. Arrays, readonly arrays, sets, and other
11
29
  * iterables are accepted. Defaults to every vault in the reallocation data.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@morpho-org/morpho-sdk",
3
3
  "description": "Abstraction layer for Morpho's complexity.",
4
- "version": "6.2.0",
4
+ "version": "6.3.1",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "repository": {
7
7
  "type": "git",