@morpho-org/morpho-sdk 6.1.0 → 6.3.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 (57) hide show
  1. package/lib/cjs/blue/errors.d.ts +1 -1
  2. package/lib/cjs/blue/errors.js +2 -1
  3. package/lib/cjs/constants.d.ts +1 -1
  4. package/lib/cjs/constants.js +2 -1
  5. package/lib/cjs/entities/blue/blue.d.ts +14 -2
  6. package/lib/cjs/entities/blue/blue.js +7 -1
  7. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +1 -0
  8. package/lib/cjs/entities/vaultV1/vaultV1.js +1 -0
  9. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +34 -9
  10. package/lib/cjs/entities/vaultV2BlueReallocationData.js +167 -47
  11. package/lib/cjs/errors.d.ts +1 -1
  12. package/lib/cjs/errors.js +3 -2
  13. package/lib/cjs/helpers/constant.d.ts +8 -0
  14. package/lib/cjs/helpers/constant.js +10 -1
  15. package/lib/cjs/helpers/encodeDeallocation.d.ts +1 -0
  16. package/lib/cjs/helpers/encodeDeallocation.js +1 -0
  17. package/lib/cjs/helpers/index.d.ts +1 -1
  18. package/lib/cjs/helpers/index.js +2 -1
  19. package/lib/cjs/helpers/metadata.d.ts +13 -0
  20. package/lib/cjs/helpers/metadata.js +13 -0
  21. package/lib/cjs/helpers/utilization.d.ts +13 -0
  22. package/lib/cjs/helpers/utilization.js +19 -1
  23. package/lib/cjs/helpers/validate.d.ts +0 -2
  24. package/lib/cjs/helpers/validate.js +2 -3
  25. package/lib/cjs/types/data.d.ts +3 -0
  26. package/lib/cjs/types/entity.d.ts +3 -0
  27. package/lib/cjs/types/metadata.d.ts +6 -0
  28. package/lib/cjs/types/sharedLiquidity.d.ts +19 -1
  29. package/lib/esm/blue/errors.d.ts +1 -1
  30. package/lib/esm/blue/errors.js +1 -1
  31. package/lib/esm/constants.d.ts +1 -1
  32. package/lib/esm/constants.js +1 -1
  33. package/lib/esm/entities/blue/blue.d.ts +14 -2
  34. package/lib/esm/entities/blue/blue.js +7 -1
  35. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +1 -0
  36. package/lib/esm/entities/vaultV1/vaultV1.js +1 -0
  37. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +34 -9
  38. package/lib/esm/entities/vaultV2BlueReallocationData.js +168 -48
  39. package/lib/esm/errors.d.ts +1 -1
  40. package/lib/esm/errors.js +1 -1
  41. package/lib/esm/helpers/constant.d.ts +8 -0
  42. package/lib/esm/helpers/constant.js +9 -0
  43. package/lib/esm/helpers/encodeDeallocation.d.ts +1 -0
  44. package/lib/esm/helpers/encodeDeallocation.js +1 -0
  45. package/lib/esm/helpers/index.d.ts +1 -1
  46. package/lib/esm/helpers/index.js +1 -1
  47. package/lib/esm/helpers/metadata.d.ts +13 -0
  48. package/lib/esm/helpers/metadata.js +13 -0
  49. package/lib/esm/helpers/utilization.d.ts +13 -0
  50. package/lib/esm/helpers/utilization.js +18 -1
  51. package/lib/esm/helpers/validate.d.ts +0 -2
  52. package/lib/esm/helpers/validate.js +1 -1
  53. package/lib/esm/types/data.d.ts +3 -0
  54. package/lib/esm/types/entity.d.ts +3 -0
  55. package/lib/esm/types/metadata.d.ts +6 -0
  56. package/lib/esm/types/sharedLiquidity.d.ts +19 -1
  57. package/package.json +4 -4
@@ -8,6 +8,12 @@ const constant_js_1 = require("../helpers/constant.js");
8
8
  const utilization_js_1 = require("../helpers/utilization.js");
9
9
  const index_js_1 = require("../types/index.js");
10
10
  const MAX_SHARED_CAP_SEARCH_STEPS = 1024n;
11
+ const createCapReserveState = (markets) => ({
12
+ initialMarkets: { ...markets },
13
+ marketAccruals: new Map(),
14
+ touchedPairs: new Map(),
15
+ reserveByPairKey: new Map(),
16
+ });
11
17
  /** Creates isolated transaction-scoped state for one simulation. @internal */
12
18
  const createSimulationContext = () => ({
13
19
  donatedPenaltyAssets: {},
@@ -558,9 +564,15 @@ class VaultV2BlueReallocationData {
558
564
  * utilization defaults to 90% and is configurable through
559
565
  * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
560
566
  * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
561
- * considered. Targets with no remaining supply or allocator capacity are skipped before
562
- * projecting source interest. The adapter's minimum share minting requirement, supply-share
563
- * limits, and target absolute or zero relative caps are checked against a one-asset deposit.
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`
570
+ * (two hours by default; `0n` disables it). For market-source reallocations
571
+ * the source position's interest is also reserved on cap ids shared with the
572
+ * target, and reserves persist across every leg of a plan. Targets with no remaining supply
573
+ * or allocator capacity are skipped before projecting source interest. The
574
+ * adapter's minimum share minting requirement, supply-share limits, and target
575
+ * absolute or zero relative caps are checked against a one-asset deposit.
564
576
  * Shared cap IDs that a source withdrawal can reduce remain eligible, as do deposits whose
565
577
  * allocation does not increase after rounding.
566
578
  *
@@ -572,9 +584,15 @@ class VaultV2BlueReallocationData {
572
584
  *
573
585
  * @param marketId - Target Blue market id.
574
586
  * @param options - Optional discovery controls and operation to support.
587
+ * Market/vault state and returned post-state stay at `timestamp`; only
588
+ * target-market cap checks reserve interest on the vault's existing allocation
589
+ * through `timestamp + capAccrualBuffer` (two hours by default; `0n` disables).
590
+ * For market-source reallocations the source position's interest is also
591
+ * reserved on cap ids shared with the target, and reserves persist across
592
+ * every leg of a plan.
575
593
  * @returns Flat action-ready reallocations and their post-simulation state.
576
594
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
577
- * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
595
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
578
596
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
579
597
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
580
598
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -619,13 +637,16 @@ class VaultV2BlueReallocationData {
619
637
  return { reallocations: [], data: this };
620
638
  const maxWithdrawalUtilization = (0, utilization_js_1.resolveMaxWithdrawalUtilization)(options.maxWithdrawalUtilization);
621
639
  const maxPenalty = resolveMaxPenalty(options.maxPenalty);
640
+ const capAccrualBuffer = (0, utilization_js_1.resolveCapAccrualBuffer)(options.capAccrualBuffer);
622
641
  const resolvedOptions = { ...options, maxPenalty };
623
642
  const operation = options.operation;
624
643
  if (operation == null) {
625
644
  const { reallocations, data } = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
626
645
  context: createSimulationContext(),
646
+ reserves: createCapReserveState(this.mutableMarkets),
627
647
  marketId,
628
648
  maxWithdrawalUtilization,
649
+ capAccrualBuffer,
629
650
  options: resolvedOptions,
630
651
  });
631
652
  return { reallocations, data };
@@ -666,11 +687,14 @@ class VaultV2BlueReallocationData {
666
687
  newTotalSupplyAssets;
667
688
  if (requiredAssets <= 0n)
668
689
  return { reallocations: [], data: this };
690
+ const reserves = createCapReserveState(this.mutableMarkets);
669
691
  const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
670
692
  context: createSimulationContext(),
693
+ reserves,
671
694
  marketId,
672
695
  maxWithdrawalUtilization,
673
696
  maxAssets: requiredAssets,
697
+ capAccrualBuffer,
674
698
  options: normalizedOptions,
675
699
  });
676
700
  const reallocations = [...friendly.reallocations];
@@ -685,9 +709,11 @@ class VaultV2BlueReallocationData {
685
709
  if (friendlyBorrow > friendlySupply) {
686
710
  const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
687
711
  context: friendly.context,
712
+ reserves,
688
713
  marketId,
689
714
  maxWithdrawalUtilization: blue_sdk_1.MathLib.WAD,
690
715
  maxAssets: friendlyBorrow - friendlySupply,
716
+ capAccrualBuffer,
691
717
  options: normalizedOptions,
692
718
  });
693
719
  reallocations.push(...fallback.reallocations);
@@ -705,7 +731,7 @@ class VaultV2BlueReallocationData {
705
731
  }
706
732
  return { reallocations, data };
707
733
  }
708
- computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, marketId, maxWithdrawalUtilization, maxAssets, options = {}, }) {
734
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, options = {}, }) {
709
735
  if (options.enabled === false)
710
736
  return { reallocations: [], data: this, context };
711
737
  this.getMarket(marketId);
@@ -725,6 +751,56 @@ class VaultV2BlueReallocationData {
725
751
  const adapterIdsCache = new Map();
726
752
  const activeAdaptersCache = new Map();
727
753
  let remainingAssets = maxAssets;
754
+ // Onchain, market interest is booked once at transaction start, on pre-plan
755
+ // positions at pre-plan rates, and stays on touched positions' cap ids.
756
+ // This reserve state is shared across every planner pass and leg of the plan.
757
+ // biome-ignore lint/complexity/useMaxParams: a pair is identified by its vault, adapter, and market.
758
+ const getPair = (vault, adapter, market) => {
759
+ const key = `${vault}:${adapter.address}:${market.id}`.toLowerCase();
760
+ const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
761
+ if (touched != null)
762
+ return touched;
763
+ const shares = adapter.supplyShares[market.id] ?? 0n;
764
+ return {
765
+ key,
766
+ ids: getAdapterIds(adapterIdsCache, adapter, market),
767
+ reserve: () => {
768
+ let reserve = reserves.reserveByPairKey.get(key);
769
+ if (reserve == null) {
770
+ let accruals = reserves.marketAccruals.get(market.id);
771
+ if (accruals == null) {
772
+ const initialMarket = reserves.initialMarkets[market.id];
773
+ if (initialMarket == null)
774
+ throw new index_js_1.UnknownReallocationMarketError(market.id);
775
+ accruals = [
776
+ initialMarket.accrueInterest(timestamp),
777
+ initialMarket.accrueInterest(timestamp + capAccrualBuffer),
778
+ ];
779
+ reserves.marketAccruals.set(market.id, accruals);
780
+ }
781
+ const [atTimestamp, projected] = accruals;
782
+ reserve = blue_sdk_1.MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
783
+ reserves.reserveByPairKey.set(key, reserve);
784
+ }
785
+ return reserve;
786
+ },
787
+ };
788
+ };
789
+ // biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
790
+ const capReserve = (vault, id, candidatePairs) => {
791
+ let reserve = 0n;
792
+ const seen = new Set();
793
+ for (const pair of [
794
+ ...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
795
+ ...candidatePairs,
796
+ ]) {
797
+ if (seen.has(pair.key) || !pair.ids.includes(id))
798
+ continue;
799
+ seen.add(pair.key);
800
+ reserve += pair.reserve();
801
+ }
802
+ return reserve;
803
+ };
728
804
  while (remainingAssets == null || remainingAssets > 0n) {
729
805
  const candidates = vaults
730
806
  .map((vaultAddress) => {
@@ -762,6 +838,7 @@ class VaultV2BlueReallocationData {
762
838
  if (!(0, viem_1.isAddressEqual)(targetMarket.params.loanToken, vault.asset) ||
763
839
  !(0, viem_1.isAddressEqual)(targetMarket.params.irm, adapter.adaptiveCurveIrm))
764
840
  continue;
841
+ const targetPair = getPair(vaultAddress, adapter, targetMarket);
765
842
  const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
766
843
  const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
767
844
  if (!(0, viem_1.isAddressEqual)(marketPublicAllocatorConfig.vault, vaultAddress) ||
@@ -778,14 +855,19 @@ class VaultV2BlueReallocationData {
778
855
  ];
779
856
  if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n))
780
857
  continue;
781
- const expectedSupplyAssets = targetMarket.toSupplyAssets(adapter.supplyShares[marketId] ?? 0n);
858
+ const adapterShares = adapter.supplyShares[marketId] ?? 0n;
859
+ const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
782
860
  const untracked = blue_sdk_1.MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
783
- const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation + untracked);
784
- const minimumAllocation = minimumSupply.market.toSupplyAssets((adapter.supplyShares[marketId] ?? 0n) + minimumSupply.shares);
861
+ const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
862
+ untracked +
863
+ targetPair.reserve());
864
+ const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
785
865
  const minimumAllocationChange = minimumAllocation - adapterMarketCapAllocation.allocation;
786
866
  const blockedTargetIds = targetAllocations
787
- .filter(({ allocation, absoluteCap, relativeCap }) => {
788
- const nextAllocation = allocation + minimumAllocationChange;
867
+ .filter(({ allocation, absoluteCap, relativeCap, id }) => {
868
+ const nextAllocation = allocation +
869
+ capReserve(vaultAddress, id, [targetPair]) +
870
+ minimumAllocationChange;
789
871
  return (nextAllocation > absoluteCap ||
790
872
  (relativeCap === 0n && nextAllocation > 0n));
791
873
  })
@@ -803,11 +885,14 @@ class VaultV2BlueReallocationData {
803
885
  const assets = blue_sdk_1.MathLib.min(blue_sdk_1.MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
804
886
  if (assets > 0n) {
805
887
  rawCandidates.push({
806
- vault: vaultAddress,
807
- from: { type: "idle" },
808
- to: { adapter: adapter.address },
809
- assets,
810
- penalty: publicAllocatorConfig.penalty,
888
+ reallocation: {
889
+ vault: vaultAddress,
890
+ from: { type: "idle" },
891
+ to: { adapter: adapter.address },
892
+ assets,
893
+ penalty: publicAllocatorConfig.penalty,
894
+ },
895
+ targetPair,
811
896
  });
812
897
  }
813
898
  }
@@ -841,6 +926,7 @@ class VaultV2BlueReallocationData {
841
926
  // A withdrawal can create target headroom only for shared cap IDs.
842
927
  if (blockedTargetIds.some((id) => !sourceIds.includes(id)))
843
928
  continue;
929
+ const sourcePair = getPair(vaultAddress, sourceAdapter, sourceMarket);
844
930
  const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
845
931
  data.setMarkets([accruedSourceMarket]);
846
932
  const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
@@ -848,32 +934,32 @@ class VaultV2BlueReallocationData {
848
934
  if (assets <= 0n)
849
935
  continue;
850
936
  rawCandidates.push({
851
- vault: vaultAddress,
852
- from: {
853
- type: "market",
854
- adapter: sourceAdapter.address,
855
- marketParams: sourceMarket.params,
937
+ reallocation: {
938
+ vault: vaultAddress,
939
+ from: {
940
+ type: "market",
941
+ adapter: sourceAdapter.address,
942
+ marketParams: sourceMarket.params,
943
+ },
944
+ to: { adapter: adapter.address },
945
+ assets,
946
+ penalty: publicAllocatorConfig.penalty,
856
947
  },
857
- to: { adapter: adapter.address },
858
- assets,
859
- penalty: publicAllocatorConfig.penalty,
948
+ targetPair,
949
+ sourcePair,
860
950
  });
861
951
  }
862
952
  }
863
953
  }
864
954
  const capCompatibleCandidates = [];
865
- for (const reallocation of rawCandidates) {
955
+ for (const { reallocation, targetPair, sourcePair, } of rawCandidates) {
866
956
  let lower = 0n;
867
957
  let upper = reallocation.assets;
868
- const reallocationAdapter = data.getAdapter(reallocation.vault, reallocation.to.adapter);
869
- const targetIds = getAdapterIds(adapterIdsCache, reallocationAdapter, targetMarket);
870
- const sourceIds = new Set();
871
- if (reallocation.from.type === "market") {
872
- const sourceAdapter = data.getAdapter(reallocation.vault, reallocation.from.adapter);
873
- const sourceMarket = data.getMarket(reallocation.from.marketParams.id);
874
- for (const id of getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket))
875
- sourceIds.add(id);
876
- }
958
+ const targetIds = targetPair.ids;
959
+ const sourceIds = new Set(sourcePair?.ids ?? []);
960
+ const reserveById = new Map();
961
+ for (const id of targetIds)
962
+ reserveById.set(id, capReserve(reallocation.vault, id, sourcePair == null ? [targetPair] : [targetPair, sourcePair]));
877
963
  const probeReallocation = (assets) => {
878
964
  if (targetMarket.totalSupplyShares +
879
965
  targetMarket.toSupplyShares(assets, "Down") >
@@ -897,8 +983,11 @@ class VaultV2BlueReallocationData {
897
983
  for (const id of targetIds) {
898
984
  const allocation = postTransition.data.getAllocation(reallocation.vault, id);
899
985
  const capacity = blue_sdk_1.VaultV2Utils.allocationHeadroom({ ...allocation, allocation: 0n }, firstTotalAssets).value;
986
+ // The reserve covers interest accrued before inclusion by every
987
+ // position the plan touched on this cap id, as booked onchain.
900
988
  const withinCap = allocation.absoluteCap > 0n &&
901
- allocation.allocation <= capacity;
989
+ allocation.allocation + (reserveById.get(id) ?? 0n) <=
990
+ capacity;
902
991
  if (!withinCap) {
903
992
  withinAllCaps = false;
904
993
  if (!sourceIds.has(id))
@@ -935,22 +1024,34 @@ class VaultV2BlueReallocationData {
935
1024
  }
936
1025
  if (selectedAssets > 0n && probe?.withinAllCaps === true)
937
1026
  capCompatibleCandidates.push({
938
- ...reallocation,
939
- assets: selectedAssets,
1027
+ reallocation: { ...reallocation, assets: selectedAssets },
1028
+ targetPair,
1029
+ sourcePair,
940
1030
  });
941
1031
  }
942
- return capCompatibleCandidates.sort((0, morpho_ts_1.bigIntComparator)(({ assets }) => assets, "desc"))[0];
1032
+ return capCompatibleCandidates.sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"))[0];
943
1033
  })
944
1034
  .filter((candidate) => candidate != null)
945
- .sort((0, morpho_ts_1.bigIntComparator)(({ assets }) => assets, "desc"));
1035
+ .sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"));
946
1036
  const largest = candidates[0];
947
1037
  if (largest == null)
948
1038
  return { reallocations, data, context: simulationContext };
949
- const reallocation = largest;
950
- reallocations.push(reallocation);
1039
+ const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, } = largest;
1040
+ const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1041
+ let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1042
+ if (touchedVaultPairs == null) {
1043
+ touchedVaultPairs = new Map();
1044
+ reserves.touchedPairs.set(touchedVaultKey, touchedVaultPairs);
1045
+ }
1046
+ if (!touchedVaultPairs.has(acceptedTargetPair.key))
1047
+ touchedVaultPairs.set(acceptedTargetPair.key, acceptedTargetPair);
1048
+ if (acceptedSourcePair != null &&
1049
+ !touchedVaultPairs.has(acceptedSourcePair.key))
1050
+ touchedVaultPairs.set(acceptedSourcePair.key, acceptedSourcePair);
1051
+ reallocations.push(acceptedReallocation);
951
1052
  const transition = data.applyPublicReallocation({
952
1053
  context: simulationContext,
953
- reallocation,
1054
+ reallocation: acceptedReallocation,
954
1055
  targetMarketId: marketId,
955
1056
  timestamp,
956
1057
  adapterIdsCache,
@@ -958,18 +1059,25 @@ class VaultV2BlueReallocationData {
958
1059
  data = transition.data;
959
1060
  simulationContext = transition.context;
960
1061
  if (remainingAssets != null)
961
- remainingAssets -= reallocation.assets;
1062
+ remainingAssets -= acceptedReallocation.assets;
962
1063
  }
963
1064
  return { reallocations, data, context: simulationContext };
964
1065
  }
965
1066
  /**
966
1067
  * Sums friendly Vault V2 shared liquidity available to a target market.
1068
+ * Market/vault state and returned post-state stay at `timestamp`; only
1069
+ * target-market cap checks reserve interest on the vault's existing allocation
1070
+ * through `timestamp + capAccrualBuffer` (two hours by default; `0n` disables).
1071
+ * For market-source reallocations the source position's interest is also
1072
+ * reserved on cap ids shared with the target, and reserves persist across
1073
+ * every leg of a plan.
967
1074
  *
968
1075
  * @param marketId - Target Blue market id.
969
- * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
1076
+ * @param options - Optional timestamp, cap-accrual buffer, enable flag, vault
1077
+ * allowlist, source utilization ceiling, and maximum penalty.
970
1078
  * @returns Reallocatable market and idle assets, or `0n` when none are available; rounding-only shared-cap fits may be conservatively omitted.
971
1079
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
972
- * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
1080
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
973
1081
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
974
1082
  * @throws {UnknownReallocationMarketError} when a required market is absent.
975
1083
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -1003,26 +1111,35 @@ class VaultV2BlueReallocationData {
1003
1111
  getPublicReallocationLiquidity(marketId, options) {
1004
1112
  if (options?.enabled === false)
1005
1113
  return 0n;
1114
+ const capAccrualBuffer = (0, utilization_js_1.resolveCapAccrualBuffer)(options?.capAccrualBuffer);
1006
1115
  const maxPenalty = resolveMaxPenalty(options?.maxPenalty);
1007
1116
  return this.clone()
1008
1117
  .computeVaultV2BlueReallocationsAtUtilizationInPlace({
1009
1118
  context: createSimulationContext(),
1119
+ reserves: createCapReserveState(this.mutableMarkets),
1010
1120
  marketId,
1011
1121
  maxWithdrawalUtilization: (0, utilization_js_1.resolveMaxWithdrawalUtilization)(options?.maxWithdrawalUtilization),
1122
+ capAccrualBuffer,
1012
1123
  options: { ...options, maxPenalty },
1013
1124
  })
1014
1125
  .reallocations.reduce((total, { assets }) => total + assets, 0n);
1015
1126
  }
1016
1127
  /**
1017
1128
  * Computes borrow liquidity to a target utilization, including friendly
1018
- * Vault V2 public reallocations.
1129
+ * Vault V2 public reallocations. Market/vault state and returned post-state
1130
+ * stay at `timestamp`; only target-market cap checks reserve interest on the
1131
+ * vault's existing allocation through `timestamp + capAccrualBuffer` (two
1132
+ * hours by default; `0n` disables). For market-source reallocations the
1133
+ * source position's interest is also reserved on cap ids shared with the
1134
+ * target, and reserves persist across every leg of a plan.
1019
1135
  *
1020
1136
  * @param marketId - Target Blue market id.
1021
1137
  * @param utilization - Desired utilization, scaled by WAD. Defaults to 90%.
1022
- * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
1138
+ * @param options - Optional timestamp, cap-accrual buffer, enable flag, vault
1139
+ * allowlist, source utilization ceiling, and maximum penalty.
1023
1140
  * @returns Borrowable assets while remaining at or below `utilization`; rounding-only shared-cap fits may be conservatively omitted.
1024
1141
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
1025
- * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
1142
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
1026
1143
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
1027
1144
  * @throws {UnknownReallocationMarketError} when a required market is absent.
1028
1145
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -1056,6 +1173,7 @@ class VaultV2BlueReallocationData {
1056
1173
  */
1057
1174
  // biome-ignore lint/complexity/useMaxParams: mirrors the existing V1 metric API
1058
1175
  getAvailableLiquidityToUtilization(marketId, utilization = constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION, options) {
1176
+ const capAccrualBuffer = (0, utilization_js_1.resolveCapAccrualBuffer)(options?.capAccrualBuffer);
1059
1177
  const timestamp = options?.timestamp == null
1060
1178
  ? this.getLatestSnapshotTimestamp()
1061
1179
  : BigInt(options.timestamp);
@@ -1066,8 +1184,10 @@ class VaultV2BlueReallocationData {
1066
1184
  const availableLiquidity = this.clone()
1067
1185
  .computeVaultV2BlueReallocationsAtUtilizationInPlace({
1068
1186
  context: createSimulationContext(),
1187
+ reserves: createCapReserveState(this.mutableMarkets),
1069
1188
  marketId,
1070
1189
  maxWithdrawalUtilization: (0, utilization_js_1.resolveMaxWithdrawalUtilization)(options?.maxWithdrawalUtilization),
1190
+ capAccrualBuffer,
1071
1191
  options: {
1072
1192
  ...options,
1073
1193
  timestamp,
@@ -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, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, 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, 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.UnknownMidnightCollateralIndexError = exports.MidnightTickOutOfRangeError = exports.MidnightSettlementFeeExceedsPriceError = exports.MidnightRatifierV1TakerNotAllowedError = exports.MidnightRateRatifierV1BoundOverflowError = exports.MidnightPriceGreaterThanOneError = 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.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.DivisionByZeroError = exports._try = void 0;
3
+ exports.MidnightTickOutOfRangeError = exports.MidnightSettlementFeeExceedsPriceError = exports.MidnightRatifierV1TakerNotAllowedError = exports.MidnightRateRatifierV1BoundOverflowError = exports.MidnightPriceGreaterThanOneError = 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.BlueMarketParamsIdMismatchError = 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.DivisionByZeroError = exports._try = exports.UnknownMidnightCollateralIndexError = 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; } });
@@ -27,6 +27,7 @@ Object.defineProperty(exports, "InvalidNumberError", { enumerable: true, get: fu
27
27
  Object.defineProperty(exports, "InvalidPermitDomainChainIdError", { enumerable: true, get: function () { return blue_sdk_viem_1.InvalidPermitDomainChainIdError; } });
28
28
  Object.defineProperty(exports, "InvalidPermitDomainVerifyingContractError", { enumerable: true, get: function () { return blue_sdk_viem_1.InvalidPermitDomainVerifyingContractError; } });
29
29
  Object.defineProperty(exports, "isBlueUnknownOfFactoryError", { enumerable: true, get: function () { return blue_sdk_viem_1.isUnknownOfFactoryError; } });
30
+ Object.defineProperty(exports, "BlueMarketParamsIdMismatchError", { enumerable: true, get: function () { return blue_sdk_viem_1.MarketParamsIdMismatchError; } });
30
31
  Object.defineProperty(exports, "UnsupportedPermitDomainExtensionsError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnsupportedPermitDomainExtensionsError; } });
31
32
  var midnight_sdk_1 = require("@morpho-org/midnight-sdk");
32
33
  Object.defineProperty(exports, "MidnightChainIdMismatchError", { enumerable: true, get: function () { return midnight_sdk_1.ChainIdMismatchError; } });
@@ -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,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_TOKEN_APPROVALS = exports.APPROVE_ONLY_ONCE_TOKENS = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_LLTV_BUFFER = exports.MAX_REALLOCATION_PENALTY = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.MAX_SLIPPAGE_TOLERANCE = void 0;
3
+ exports.MAX_TOKEN_APPROVALS = exports.APPROVE_ONLY_ONCE_TOKENS = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_CAP_ACCRUAL_BUFFER = exports.DEFAULT_LLTV_BUFFER = exports.MAX_REALLOCATION_PENALTY = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.MAX_SLIPPAGE_TOLERANCE = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
6
  const viem_1 = require("viem");
6
7
  /** Maximum slippage tolerance: 10% */
7
8
  exports.MAX_SLIPPAGE_TOLERANCE = blue_sdk_1.MathLib.WAD / 10n;
@@ -11,6 +12,14 @@ exports.DEFAULT_MAX_REALLOCATION_PENALTY = 0n;
11
12
  exports.MAX_REALLOCATION_PENALTY = blue_sdk_1.MathLib.WAD;
12
13
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
13
14
  exports.DEFAULT_LLTV_BUFFER = blue_sdk_1.MathLib.WAD / 200n;
15
+ /**
16
+ * Forward interest-accrual window, in seconds (2 hours), reserved in target-market
17
+ * cap checks (BluePublicAllocator max-in, Vault V2 absolute and relative caps) when
18
+ * planning reallocations, so a transaction included after the quote block does not
19
+ * revert on a cap check. Override with
20
+ * `VaultV2BluePublicAllocatorOptions.capAccrualBuffer`.
21
+ */
22
+ exports.DEFAULT_CAP_ACCRUAL_BUFFER = morpho_ts_1.Time.s.from.h(2n);
14
23
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
15
24
  exports.MAX_ABSOLUTE_SHARE_PRICE = 100n * blue_sdk_1.MathLib.RAY;
16
25
  /**
@@ -7,5 +7,6 @@ import { type Deallocation } from "../types/index.js";
7
7
  * @param onBehalf - The address from which the penalty is taken (share owner).
8
8
  * @returns The ABI-encoded calldata for `VaultV2.forceDeallocate`.
9
9
  * @throws {NonPositiveInputError} when `deallocation.amount <= 0n`.
10
+ * @internal
10
11
  */
11
12
  export declare function encodeForceDeallocateCall(deallocation: Deallocation, onBehalf: Address): Hex;
@@ -24,6 +24,7 @@ function encodeDeallocateData(deallocation) {
24
24
  * @param onBehalf - The address from which the penalty is taken (share owner).
25
25
  * @returns The ABI-encoded calldata for `VaultV2.forceDeallocate`.
26
26
  * @throws {NonPositiveInputError} when `deallocation.amount <= 0n`.
27
+ * @internal
27
28
  */
28
29
  function encodeForceDeallocateCall(deallocation, onBehalf) {
29
30
  if (deallocation.amount <= 0n) {
@@ -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,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveVaultV2ForceWithdrawEligibility = exports.computeVaultV2ForceWithdrawSharesBurnt = exports.computeVaultV2ForceWithdrawPlan = exports.computeVaultV2ForceWithdrawMinSharesBurnt = exports.computeVaultV2ForceWithdrawFeeSharesMinted = exports.validateRequirementSpender = exports.validateOfferSides = exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateMidnightMarketChainId = exports.validateChainId = exports.validateAccrualPosition = exports.computeVaultMaxSharePrice = exports.computeVaultMaxShareAllowance = exports.computeMinForceWithdrawSharePrice = exports.signAndVerifyTypedData = exports.grossFromNetAssets = exports.previewVaultV2InKindRedeem = exports.previewVaultV2ForceWithdraw = exports.addTransactionMetadata = exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_REALLOCATION_PENALTY = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.DEFAULT_LLTV_BUFFER = exports.APPROVE_ONLY_ONCE_TOKENS = void 0;
3
+ exports.resolveVaultV2ForceWithdrawEligibility = exports.computeVaultV2ForceWithdrawSharesBurnt = exports.computeVaultV2ForceWithdrawPlan = exports.computeVaultV2ForceWithdrawMinSharesBurnt = exports.computeVaultV2ForceWithdrawFeeSharesMinted = exports.validateRequirementSpender = exports.validateOfferSides = exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateMidnightMarketChainId = exports.validateChainId = exports.validateAccrualPosition = exports.computeVaultMaxSharePrice = exports.computeVaultMaxShareAllowance = exports.computeMinForceWithdrawSharePrice = exports.signAndVerifyTypedData = exports.grossFromNetAssets = exports.previewVaultV2InKindRedeem = exports.previewVaultV2ForceWithdraw = exports.addTransactionMetadata = exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_REALLOCATION_PENALTY = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.DEFAULT_LLTV_BUFFER = exports.DEFAULT_CAP_ACCRUAL_BUFFER = exports.APPROVE_ONLY_ONCE_TOKENS = void 0;
4
4
  var constant_js_1 = require("./constant.js");
5
5
  Object.defineProperty(exports, "APPROVE_ONLY_ONCE_TOKENS", { enumerable: true, get: function () { return constant_js_1.APPROVE_ONLY_ONCE_TOKENS; } });
6
+ Object.defineProperty(exports, "DEFAULT_CAP_ACCRUAL_BUFFER", { enumerable: true, get: function () { return constant_js_1.DEFAULT_CAP_ACCRUAL_BUFFER; } });
6
7
  Object.defineProperty(exports, "DEFAULT_LLTV_BUFFER", { enumerable: true, get: function () { return constant_js_1.DEFAULT_LLTV_BUFFER; } });
7
8
  Object.defineProperty(exports, "DEFAULT_MAX_REALLOCATION_PENALTY", { enumerable: true, get: function () { return constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY; } });
8
9
  Object.defineProperty(exports, "DEFAULT_SUPPLY_TARGET_UTILIZATION", { enumerable: true, get: function () { return constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION; } });
@@ -29,6 +29,19 @@ import type { Metadata } from "../types/index.js";
29
29
  * @returns The same `tx` object when `data` is missing, an empty string, or
30
30
  * canonical empty calldata (`"0x"`); otherwise, a new transaction object
31
31
  * with `data` containing any appended metadata. The input is never mutated.
32
+ * @example
33
+ * ```ts
34
+ * import { addTransactionMetadata } from "@morpho-org/morpho-sdk";
35
+ * import { getChainAddresses } from "@morpho-org/morpho-sdk/addresses";
36
+ * import type { Address, Hex } from "viem";
37
+ * import { mainnet } from "viem/chains";
38
+ *
39
+ * const { blue } = getChainAddresses(mainnet.id);
40
+ * const tx = { to: blue, value: 0n, data: "0x1234" as Hex };
41
+ * const result: { to: Address; value: bigint; data: Hex } =
42
+ * addTransactionMetadata(tx, { origin: "deadbeef", timestamp: true });
43
+ * // => { to: blue, value: 0n, data: "0x1234" + <4-byte timestamp> + "deadbeef" }
44
+ * ```
32
45
  */
33
46
  export declare function addTransactionMetadata(tx: {
34
47
  data: Hex;
@@ -32,6 +32,19 @@ const viem_1 = require("viem");
32
32
  * @returns The same `tx` object when `data` is missing, an empty string, or
33
33
  * canonical empty calldata (`"0x"`); otherwise, a new transaction object
34
34
  * with `data` containing any appended metadata. The input is never mutated.
35
+ * @example
36
+ * ```ts
37
+ * import { addTransactionMetadata } from "@morpho-org/morpho-sdk";
38
+ * import { getChainAddresses } from "@morpho-org/morpho-sdk/addresses";
39
+ * import type { Address, Hex } from "viem";
40
+ * import { mainnet } from "viem/chains";
41
+ *
42
+ * const { blue } = getChainAddresses(mainnet.id);
43
+ * const tx = { to: blue, value: 0n, data: "0x1234" as Hex };
44
+ * const result: { to: Address; value: bigint; data: Hex } =
45
+ * addTransactionMetadata(tx, { origin: "deadbeef", timestamp: true });
46
+ * // => { to: blue, value: 0n, data: "0x1234" + <4-byte timestamp> + "deadbeef" }
47
+ * ```
35
48
  */
36
49
  function addTransactionMetadata(tx, metadata) {
37
50
  const { data, ..._tx } = tx;
@@ -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,9 +1,27 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveMaxWithdrawalUtilization = void 0;
3
+ exports.resolveMaxWithdrawalUtilization = exports.resolveCapAccrualBuffer = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const index_js_1 = require("../types/index.js");
6
6
  const constant_js_1 = require("./constant.js");
7
+ /**
8
+ * Resolves and validates the target-market cap-accrual buffer.
9
+ * @internal
10
+ * @param value - Optional buffer duration in seconds.
11
+ * @returns The non-negative buffer duration, defaulting to two hours.
12
+ * @throws {NegativeInputError} when the buffer is negative.
13
+ * @example
14
+ * ```ts
15
+ * const buffer = resolveCapAccrualBuffer(undefined);
16
+ * ```
17
+ */
18
+ const resolveCapAccrualBuffer = (value) => {
19
+ const buffer = value == null ? constant_js_1.DEFAULT_CAP_ACCRUAL_BUFFER : BigInt(value);
20
+ if (buffer < 0n)
21
+ throw new index_js_1.NegativeInputError("capAccrualBuffer", buffer);
22
+ return buffer;
23
+ };
24
+ exports.resolveCapAccrualBuffer = resolveCapAccrualBuffer;
7
25
  /**
8
26
  * Resolves and validates a source withdrawal utilization ceiling.
9
27
  * @internal