@morpho-org/morpho-sdk 9.1.0 → 9.2.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.
- package/README.md +4 -0
- package/lib/cjs/abis.d.ts +1 -1
- package/lib/cjs/abis.js +3 -1
- package/lib/cjs/blue/constants.d.ts +1 -1
- package/lib/cjs/blue/constants.js +2 -1
- package/lib/cjs/constants.d.ts +2 -2
- package/lib/cjs/constants.js +4 -1
- package/lib/cjs/entities/blue/blue.d.ts +71 -16
- package/lib/cjs/entities/blue/blue.js +32 -4
- package/lib/cjs/entities/midnight/midnight.d.ts +2 -1
- package/lib/cjs/entities/midnight/midnight.js +5 -4
- package/lib/cjs/entities/vaultV1/vaultV1.d.ts +8 -0
- package/lib/cjs/entities/vaultV1/vaultV1.js +5 -0
- package/lib/cjs/entities/vaultV2/vaultV2.d.ts +4 -0
- package/lib/cjs/entities/vaultV2/vaultV2.js +3 -0
- package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +37 -4
- package/lib/cjs/entities/vaultV2BlueReallocationData.js +197 -32
- package/lib/cjs/helpers/constant.d.ts +7 -0
- package/lib/cjs/helpers/constant.js +8 -1
- package/lib/cjs/helpers/deadShares.d.ts +82 -0
- package/lib/cjs/helpers/deadShares.js +200 -0
- package/lib/cjs/helpers/index.d.ts +2 -1
- package/lib/cjs/helpers/index.js +7 -1
- package/lib/cjs/midnight/abis.d.ts +1 -1
- package/lib/cjs/midnight/abis.js +3 -1
- package/lib/cjs/types/error.d.ts +54 -5
- package/lib/cjs/types/error.js +60 -6
- package/lib/cjs/types/sharedLiquidity.d.ts +10 -6
- package/lib/esm/abis.d.ts +1 -1
- package/lib/esm/abis.js +1 -1
- package/lib/esm/blue/constants.d.ts +1 -1
- package/lib/esm/blue/constants.js +1 -1
- package/lib/esm/constants.d.ts +2 -2
- package/lib/esm/constants.js +2 -2
- package/lib/esm/entities/blue/blue.d.ts +71 -16
- package/lib/esm/entities/blue/blue.js +34 -6
- package/lib/esm/entities/midnight/midnight.d.ts +2 -1
- package/lib/esm/entities/midnight/midnight.js +6 -5
- package/lib/esm/entities/vaultV1/vaultV1.d.ts +8 -0
- package/lib/esm/entities/vaultV1/vaultV1.js +5 -0
- package/lib/esm/entities/vaultV2/vaultV2.d.ts +4 -0
- package/lib/esm/entities/vaultV2/vaultV2.js +3 -0
- package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +37 -4
- package/lib/esm/entities/vaultV2BlueReallocationData.js +197 -32
- package/lib/esm/helpers/constant.d.ts +7 -0
- package/lib/esm/helpers/constant.js +7 -0
- package/lib/esm/helpers/deadShares.d.ts +82 -0
- package/lib/esm/helpers/deadShares.js +195 -0
- package/lib/esm/helpers/index.d.ts +2 -1
- package/lib/esm/helpers/index.js +2 -1
- package/lib/esm/midnight/abis.d.ts +1 -1
- package/lib/esm/midnight/abis.js +1 -1
- package/lib/esm/types/error.d.ts +54 -5
- package/lib/esm/types/error.js +57 -5
- package/lib/esm/types/sharedLiquidity.d.ts +10 -6
- package/package.json +8 -7
|
@@ -171,10 +171,22 @@ export class VaultV2BlueReallocationData {
|
|
|
171
171
|
mutableVaults;
|
|
172
172
|
/** Mutable allocation state used only by cloned simulation transitions. */
|
|
173
173
|
mutableAllocations;
|
|
174
|
+
/** Mutable Blue token balances used only by cloned simulation transitions. */
|
|
175
|
+
mutableBlueBalances;
|
|
174
176
|
/** Chain id associated with this snapshot. */
|
|
175
177
|
chainId;
|
|
176
178
|
/** Timestamp of the block the state was fetched at. */
|
|
177
179
|
timestamp;
|
|
180
|
+
/**
|
|
181
|
+
* Morpho Blue's ERC-20 balances at the snapshot block, indexed by token address.
|
|
182
|
+
* Explicit balances increase with idle-sourced reallocations in returned
|
|
183
|
+
* post-states. Sizing has zero margin over the snapshot balance, so activity
|
|
184
|
+
* on other Blue markets with the same loan token can make a plan revert;
|
|
185
|
+
* refetch close to submission. A missing token uses summed non-negative
|
|
186
|
+
* snapshot-market supply-minus-borrow only to size plans; balance-based
|
|
187
|
+
* rejection requires an explicit balance.
|
|
188
|
+
*/
|
|
189
|
+
blueBalances;
|
|
178
190
|
/** Markets indexed by market id. */
|
|
179
191
|
markets;
|
|
180
192
|
/** Vault V2 entities indexed by address. */
|
|
@@ -201,9 +213,11 @@ export class VaultV2BlueReallocationData {
|
|
|
201
213
|
this.mutableMarkets = {};
|
|
202
214
|
this.mutableVaults = {};
|
|
203
215
|
this.mutableAllocations = {};
|
|
216
|
+
this.mutableBlueBalances = {};
|
|
204
217
|
this.markets = this.mutableMarkets;
|
|
205
218
|
this.vaults = this.mutableVaults;
|
|
206
219
|
this.allocations = this.mutableAllocations;
|
|
220
|
+
this.blueBalances = this.mutableBlueBalances;
|
|
207
221
|
if (isClone) {
|
|
208
222
|
this.publicAllocatorConfigs = input.publicAllocatorConfigs;
|
|
209
223
|
this.activeAdapters = input.activeAdapters;
|
|
@@ -240,6 +254,10 @@ export class VaultV2BlueReallocationData {
|
|
|
240
254
|
this.mutableMarkets[marketId] =
|
|
241
255
|
market == null ? undefined : new Market({ ...market });
|
|
242
256
|
}
|
|
257
|
+
for (const [token, balance] of Object.entries(input.blueBalances ?? {})) {
|
|
258
|
+
this.mutableBlueBalances[token] =
|
|
259
|
+
balance == null ? undefined : BigInt(balance);
|
|
260
|
+
}
|
|
243
261
|
for (const [address, vault] of Object.entries(input.vaults ?? {})) {
|
|
244
262
|
const clonedVault = vault == null
|
|
245
263
|
? undefined
|
|
@@ -572,8 +590,9 @@ export class VaultV2BlueReallocationData {
|
|
|
572
590
|
* Without `options.operation`, discovers every friendly call. With an
|
|
573
591
|
* operation, penalty tiers are considered ascending, starting with free
|
|
574
592
|
* vaults. The free tier aims to bring the target market back to 90%
|
|
575
|
-
* utilization; positive tiers cover
|
|
576
|
-
*
|
|
593
|
+
* utilization; positive tiers cover the remaining absolute shortfall or,
|
|
594
|
+
* when larger, Blue's loan-token balance deficit while the penalty is
|
|
595
|
+
* flash-loaned. Within each tier, source markets go to the
|
|
577
596
|
* friendly source utilization (90% by default) before 100%. Free capacity
|
|
578
597
|
* inside `allocatorCapHeadroom` is kept unused, so a penalized leg can cover
|
|
579
598
|
* it instead. Discovery and liquidity getters still count every vault up to
|
|
@@ -587,6 +606,16 @@ export class VaultV2BlueReallocationData {
|
|
|
587
606
|
* The planner includes the referral fee and its allocator-leg penalties in
|
|
588
607
|
* destination debt, so penalized legs also cover their own penalty.
|
|
589
608
|
* Refinance never uses vaults with a 100% penalty.
|
|
609
|
+
* BlueBundlesV1 flash-loans the plan's penalty from Blue before executing
|
|
610
|
+
* reallocation legs. When an explicit `blueBalances` value is supplied, plans
|
|
611
|
+
* throw `InsufficientSharedLiquidityError` if Blue cannot fund that flash
|
|
612
|
+
* loan or a market-sourced leg's withdrawal before later idle legs arrive.
|
|
613
|
+
* Legs are not reordered. A missing balance falls back to summed snapshot-
|
|
614
|
+
* market liquidity only to size plans and may make them larger; it cannot
|
|
615
|
+
* cause rejection for Blue-balance constraints.
|
|
616
|
+
* Sizing has zero margin over the snapshot balance; activity on other Blue
|
|
617
|
+
* markets with the same loan token can make a plan revert. Refetch close to
|
|
618
|
+
* submission; there is no balance-buffer option.
|
|
590
619
|
* Friendly source utilization defaults to 90% and is configurable through
|
|
591
620
|
* `options.maxWithdrawalUtilization`. Market/vault state and the returned
|
|
592
621
|
* post-state stay at `timestamp`. An enabled operation that needs no
|
|
@@ -634,7 +663,7 @@ export class VaultV2BlueReallocationData {
|
|
|
634
663
|
* @returns Flat action-ready reallocations and their post-simulation state.
|
|
635
664
|
* @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
|
|
636
665
|
* @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, `maxPenalty`, or `referralFeePct` is negative.
|
|
637
|
-
* @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
|
|
666
|
+
* @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD, or an enabled borrow/withdraw plan otherwise covers its shortfall but its planned penalty exceeds the operation amount.
|
|
638
667
|
* @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
|
|
639
668
|
* @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
|
|
640
669
|
* @throws {UnknownReallocationMarketError} when a required market is absent.
|
|
@@ -643,7 +672,7 @@ export class VaultV2BlueReallocationData {
|
|
|
643
672
|
* @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
|
|
644
673
|
* @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
|
|
645
674
|
* @throws {UnknownReallocationAllocationError} when required allocation state is absent.
|
|
646
|
-
* @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the
|
|
675
|
+
* @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the operation shortfall or refinance penalties, or an explicit Blue balance cannot fund the penalty flash loan, an earlier market-sourced withdrawal, or the final operation transfer.
|
|
647
676
|
* @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
|
|
648
677
|
* @example
|
|
649
678
|
* ```ts
|
|
@@ -716,6 +745,31 @@ export class VaultV2BlueReallocationData {
|
|
|
716
745
|
: [...options.reallocatableVaults],
|
|
717
746
|
};
|
|
718
747
|
const market = this.getMarket(marketId).accrueInterest(timestamp);
|
|
748
|
+
const blueBalanceKey = findAddressKey(this.mutableBlueBalances, market.params.loanToken);
|
|
749
|
+
const explicitBlueBalance = blueBalanceKey == null
|
|
750
|
+
? undefined
|
|
751
|
+
: this.mutableBlueBalances[blueBalanceKey];
|
|
752
|
+
const hasExplicitBlueBalance = explicitBlueBalance !== undefined;
|
|
753
|
+
const blueBalance = explicitBlueBalance ??
|
|
754
|
+
Object.values(this.mutableMarkets).reduce((total, snapshotMarket) => snapshotMarket != null &&
|
|
755
|
+
isAddressEqual(snapshotMarket.params.loanToken, market.params.loanToken)
|
|
756
|
+
? total +
|
|
757
|
+
MathLib.zeroFloorSub(snapshotMarket.totalSupplyAssets, snapshotMarket.totalBorrowAssets)
|
|
758
|
+
: total, 0n);
|
|
759
|
+
const getTransferShortfall = (reallocations) => {
|
|
760
|
+
const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
|
|
761
|
+
if (penaltyAssets === 0n)
|
|
762
|
+
return 0n;
|
|
763
|
+
let shortfall = MathLib.zeroFloorSub(penaltyAssets, blueBalance);
|
|
764
|
+
let balance = MathLib.zeroFloorSub(blueBalance, penaltyAssets);
|
|
765
|
+
for (const { from, assets } of reallocations) {
|
|
766
|
+
if (from.type === "idle")
|
|
767
|
+
balance += assets;
|
|
768
|
+
else
|
|
769
|
+
shortfall = MathLib.max(shortfall, MathLib.zeroFloorSub(assets, balance));
|
|
770
|
+
}
|
|
771
|
+
return shortfall;
|
|
772
|
+
};
|
|
719
773
|
if (type === "withdraw" && amount > market.totalSupplyAssets) {
|
|
720
774
|
throw new ReallocationWithdrawExceedsMarketSupplyError({
|
|
721
775
|
marketId,
|
|
@@ -757,25 +811,30 @@ export class VaultV2BlueReallocationData {
|
|
|
757
811
|
let data = this.clone();
|
|
758
812
|
let context = createSimulationContext();
|
|
759
813
|
let remainingShortfall = absoluteShortfall;
|
|
814
|
+
let accountingShortfall = absoluteShortfall;
|
|
760
815
|
let allocatorCapBoundTargets = new Set();
|
|
761
816
|
let idleBoundVaults = new Set();
|
|
762
817
|
for (const penalty of penaltyTiers) {
|
|
763
818
|
if (type === "refinance" && penalty === MathLib.WAD)
|
|
764
819
|
continue;
|
|
765
820
|
let isFriendlyPass = true;
|
|
821
|
+
let triedFullCapacityAttempt = false;
|
|
766
822
|
for (const utilization of [maxWithdrawalUtilization, MathLib.WAD]) {
|
|
767
823
|
const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
|
|
768
824
|
isFriendlyPass = false;
|
|
769
825
|
if (remainingShortfall === 0n && !isFreeFriendlyPass)
|
|
770
826
|
continue;
|
|
771
|
-
let passMaxAssets =
|
|
772
|
-
?
|
|
773
|
-
:
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
}
|
|
827
|
+
let passMaxAssets = type === "refinance" && penalty > 0n
|
|
828
|
+
? MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty)
|
|
829
|
+
: isFreeFriendlyPass
|
|
830
|
+
? maxAssets
|
|
831
|
+
: remainingShortfall;
|
|
832
|
+
const retryPaidPass = penalty > 0n;
|
|
778
833
|
let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
|
|
834
|
+
let tryFullCapacityAttempt = false;
|
|
835
|
+
let isFullCapacityRetryPath = false;
|
|
836
|
+
const beforePassRemainingShortfall = remainingShortfall;
|
|
837
|
+
const beforePassAccountingShortfall = accountingShortfall;
|
|
779
838
|
// Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
|
|
780
839
|
const passStart = retryPaidPass
|
|
781
840
|
? {
|
|
@@ -786,9 +845,12 @@ export class VaultV2BlueReallocationData {
|
|
|
786
845
|
}
|
|
787
846
|
: undefined;
|
|
788
847
|
let previousPassReallocatedAssets = 0n;
|
|
848
|
+
let previousPhysicalShortfall;
|
|
789
849
|
let hi;
|
|
790
850
|
let bestAttempt;
|
|
791
851
|
while (true) {
|
|
852
|
+
const isFullCapacityAttempt = tryFullCapacityAttempt;
|
|
853
|
+
tryFullCapacityAttempt = false;
|
|
792
854
|
if (passStart != null) {
|
|
793
855
|
data = passStart.data.clone();
|
|
794
856
|
context = passStart.context;
|
|
@@ -800,7 +862,7 @@ export class VaultV2BlueReallocationData {
|
|
|
800
862
|
reserves,
|
|
801
863
|
marketId,
|
|
802
864
|
maxWithdrawalUtilization: utilization,
|
|
803
|
-
maxAssets: passMaxAssets,
|
|
865
|
+
maxAssets: isFullCapacityAttempt ? undefined : passMaxAssets,
|
|
804
866
|
capAccrualBuffer,
|
|
805
867
|
allocatorCapHeadroom: headroom,
|
|
806
868
|
penalty,
|
|
@@ -828,23 +890,56 @@ export class VaultV2BlueReallocationData {
|
|
|
828
890
|
const supply = type === "withdraw"
|
|
829
891
|
? currentMarket.totalSupplyAssets - amount
|
|
830
892
|
: currentMarket.totalSupplyAssets;
|
|
831
|
-
|
|
893
|
+
accountingShortfall = borrow > supply ? borrow - supply : 0n;
|
|
894
|
+
const penaltyForPhysicalShortfall = getBlueBundlesV1PenaltyAssets(reallocations);
|
|
895
|
+
const idleAssetsForPhysicalShortfall = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
|
|
896
|
+
const physicalShortfall = penaltyForPhysicalShortfall === 0n
|
|
897
|
+
? 0n
|
|
898
|
+
: MathLib.zeroFloorSub((type === "refinance"
|
|
899
|
+
? amount + feeAssets + penaltyForPhysicalShortfall
|
|
900
|
+
: amount) + penaltyForPhysicalShortfall, blueBalance + idleAssetsForPhysicalShortfall);
|
|
901
|
+
remainingShortfall = MathLib.max(accountingShortfall, physicalShortfall);
|
|
902
|
+
const attemptTransferShortfall = hasExplicitBlueBalance && isFullCapacityRetryPath
|
|
903
|
+
? getTransferShortfall(reallocations)
|
|
904
|
+
: 0n;
|
|
905
|
+
const attemptCoversShortfall = remainingShortfall === 0n;
|
|
832
906
|
const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
|
|
833
907
|
if (passStart == null)
|
|
834
908
|
break;
|
|
835
|
-
if (
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
909
|
+
if (isFullCapacityAttempt)
|
|
910
|
+
passMaxAssets = passReallocatedAssets;
|
|
911
|
+
const improvesAccounting = accountingShortfall < beforePassAccountingShortfall;
|
|
912
|
+
const attemptPriority = hasExplicitBlueBalance
|
|
913
|
+
? [0n, remainingShortfall, 0n, passReallocatedAssets]
|
|
914
|
+
: [
|
|
915
|
+
improvesAccounting ? 0n : 1n,
|
|
916
|
+
improvesAccounting ? accountingShortfall : 0n,
|
|
917
|
+
remainingShortfall,
|
|
918
|
+
passReallocatedAssets,
|
|
919
|
+
];
|
|
920
|
+
const previousBestAttempt = bestAttempt;
|
|
921
|
+
let isBetterAttempt = previousBestAttempt == null;
|
|
922
|
+
if (previousBestAttempt != null) {
|
|
923
|
+
const firstDifference = attemptPriority.findIndex((priority, index) => priority !== previousBestAttempt.priority[index]);
|
|
924
|
+
isBetterAttempt =
|
|
925
|
+
firstDifference !== -1 &&
|
|
926
|
+
attemptPriority[firstDifference] <
|
|
927
|
+
previousBestAttempt.priority[firstDifference];
|
|
928
|
+
}
|
|
929
|
+
if (isBetterAttempt &&
|
|
930
|
+
(!isFullCapacityRetryPath ||
|
|
931
|
+
(attemptCoversShortfall && attemptTransferShortfall === 0n)))
|
|
839
932
|
bestAttempt = {
|
|
840
933
|
data,
|
|
841
934
|
context,
|
|
842
935
|
reserves: cloneCapReserveState(reserves),
|
|
843
936
|
reallocations: pass.reallocations,
|
|
844
937
|
remainingShortfall,
|
|
938
|
+
accountingShortfall,
|
|
845
939
|
passReallocatedAssets,
|
|
940
|
+
priority: attemptPriority,
|
|
846
941
|
};
|
|
847
|
-
if (
|
|
942
|
+
if (attemptCoversShortfall)
|
|
848
943
|
hi = hi == null ? passMaxAssets : MathLib.min(hi, passMaxAssets);
|
|
849
944
|
else
|
|
850
945
|
lo = MathLib.max(lo, passMaxAssets);
|
|
@@ -854,18 +949,52 @@ export class VaultV2BlueReallocationData {
|
|
|
854
949
|
passMaxAssets = (lo + hi) / 2n;
|
|
855
950
|
continue;
|
|
856
951
|
}
|
|
857
|
-
if (
|
|
952
|
+
if (isFullCapacityAttempt && !attemptCoversShortfall)
|
|
953
|
+
break;
|
|
954
|
+
if (accountingShortfall === 0n &&
|
|
955
|
+
previousPhysicalShortfall != null &&
|
|
956
|
+
physicalShortfall >= previousPhysicalShortfall) {
|
|
957
|
+
if (!triedFullCapacityAttempt &&
|
|
958
|
+
passReallocatedAssets === passMaxAssets) {
|
|
959
|
+
triedFullCapacityAttempt = true;
|
|
960
|
+
tryFullCapacityAttempt = true;
|
|
961
|
+
isFullCapacityRetryPath = true;
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
break;
|
|
965
|
+
}
|
|
966
|
+
previousPhysicalShortfall = physicalShortfall;
|
|
967
|
+
if (passReallocatedAssets <= previousPassReallocatedAssets ||
|
|
968
|
+
penalty === MathLib.WAD)
|
|
858
969
|
break;
|
|
859
970
|
previousPassReallocatedAssets = passReallocatedAssets;
|
|
860
971
|
passMaxAssets += MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
|
|
861
972
|
}
|
|
862
|
-
if (passStart != null
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
973
|
+
if (passStart != null) {
|
|
974
|
+
const improved = bestAttempt != null &&
|
|
975
|
+
(hasExplicitBlueBalance
|
|
976
|
+
? bestAttempt.remainingShortfall < beforePassRemainingShortfall
|
|
977
|
+
: bestAttempt.accountingShortfall <
|
|
978
|
+
beforePassAccountingShortfall ||
|
|
979
|
+
bestAttempt.remainingShortfall <
|
|
980
|
+
beforePassRemainingShortfall);
|
|
981
|
+
if (improved && bestAttempt != null) {
|
|
982
|
+
data = bestAttempt.data;
|
|
983
|
+
context = bestAttempt.context;
|
|
984
|
+
reserves = cloneCapReserveState(bestAttempt.reserves);
|
|
985
|
+
reallocations.length = passStart.reallocationCount;
|
|
986
|
+
reallocations.push(...bestAttempt.reallocations);
|
|
987
|
+
remainingShortfall = bestAttempt.remainingShortfall;
|
|
988
|
+
accountingShortfall = bestAttempt.accountingShortfall;
|
|
989
|
+
}
|
|
990
|
+
else {
|
|
991
|
+
data = passStart.data;
|
|
992
|
+
context = passStart.context;
|
|
993
|
+
reserves = cloneCapReserveState(passStart.reserves);
|
|
994
|
+
reallocations.length = passStart.reallocationCount;
|
|
995
|
+
remainingShortfall = beforePassRemainingShortfall;
|
|
996
|
+
accountingShortfall = beforePassAccountingShortfall;
|
|
997
|
+
}
|
|
869
998
|
}
|
|
870
999
|
}
|
|
871
1000
|
}
|
|
@@ -878,16 +1007,28 @@ export class VaultV2BlueReallocationData {
|
|
|
878
1007
|
!(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
|
|
879
1008
|
unboundAssets += assets;
|
|
880
1009
|
}
|
|
1010
|
+
const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
|
|
1011
|
+
const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
|
|
1012
|
+
const physicalShortfall = penaltyAssets === 0n
|
|
1013
|
+
? 0n
|
|
1014
|
+
: MathLib.zeroFloorSub((type === "refinance"
|
|
1015
|
+
? amount + feeAssets + penaltyAssets
|
|
1016
|
+
: amount) + penaltyAssets, blueBalance + idleAssets);
|
|
1017
|
+
const transferShortfall = getTransferShortfall(reallocations);
|
|
1018
|
+
const coversAccountingShortfall = type === "refinance"
|
|
1019
|
+
? reallocatedAssets >= absoluteShortfall + penaltyAssets
|
|
1020
|
+
: reallocatedAssets >= absoluteShortfall;
|
|
881
1021
|
return {
|
|
882
1022
|
reallocations,
|
|
883
1023
|
data,
|
|
884
1024
|
liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
|
|
885
1025
|
reallocatedAssets,
|
|
886
1026
|
unboundAssets,
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
1027
|
+
physicalShortfall,
|
|
1028
|
+
coversShortfall: coversAccountingShortfall &&
|
|
1029
|
+
(type === "refinance" || penaltyAssets <= amount) &&
|
|
1030
|
+
(!hasExplicitBlueBalance ||
|
|
1031
|
+
(physicalShortfall === 0n && transferShortfall === 0n)),
|
|
891
1032
|
};
|
|
892
1033
|
};
|
|
893
1034
|
// A leg that fills an allocator cap, or idle legs that together take
|
|
@@ -915,12 +1056,30 @@ export class VaultV2BlueReallocationData {
|
|
|
915
1056
|
available = selected.reallocatedAssets;
|
|
916
1057
|
}
|
|
917
1058
|
if (!selected.coversShortfall) {
|
|
1059
|
+
const selectedTransferShortfall = hasExplicitBlueBalance
|
|
1060
|
+
? getTransferShortfall(selected.reallocations)
|
|
1061
|
+
: 0n;
|
|
1062
|
+
const selectedPenaltyAssets = getBlueBundlesV1PenaltyAssets(selected.reallocations);
|
|
1063
|
+
if (type !== "refinance" &&
|
|
1064
|
+
selectedPenaltyAssets > amount &&
|
|
1065
|
+
selected.reallocatedAssets >= absoluteShortfall &&
|
|
1066
|
+
(!hasExplicitBlueBalance ||
|
|
1067
|
+
(selected.physicalShortfall === 0n &&
|
|
1068
|
+
selectedTransferShortfall === 0n)))
|
|
1069
|
+
throw new InputExceedsMaxError({
|
|
1070
|
+
field: "reallocationPenaltyAssets",
|
|
1071
|
+
value: selectedPenaltyAssets,
|
|
1072
|
+
max: amount,
|
|
1073
|
+
});
|
|
918
1074
|
throw new InsufficientSharedLiquidityError({
|
|
919
1075
|
marketId,
|
|
920
|
-
shortfall: absoluteShortfall +
|
|
1076
|
+
shortfall: MathLib.max(absoluteShortfall +
|
|
921
1077
|
(type === "refinance"
|
|
922
1078
|
? getBlueBundlesV1PenaltyAssets(selected.reallocations)
|
|
923
|
-
: 0n),
|
|
1079
|
+
: 0n), selected.reallocatedAssets +
|
|
1080
|
+
(hasExplicitBlueBalance
|
|
1081
|
+
? MathLib.max(selected.physicalShortfall, selectedTransferShortfall)
|
|
1082
|
+
: 0n)),
|
|
924
1083
|
available,
|
|
925
1084
|
});
|
|
926
1085
|
}
|
|
@@ -1569,6 +1728,12 @@ export class VaultV2BlueReallocationData {
|
|
|
1569
1728
|
}
|
|
1570
1729
|
vault.assetBalance += reallocation.assets;
|
|
1571
1730
|
}
|
|
1731
|
+
if (reallocation.from.type === "idle") {
|
|
1732
|
+
const blueBalanceKey = findAddressKey(data.mutableBlueBalances, targetMarket.params.loanToken);
|
|
1733
|
+
if (blueBalanceKey != null &&
|
|
1734
|
+
data.mutableBlueBalances[blueBalanceKey] != null)
|
|
1735
|
+
data.mutableBlueBalances[blueBalanceKey] += reallocation.assets;
|
|
1736
|
+
}
|
|
1572
1737
|
if (firstTotalAssets == null) {
|
|
1573
1738
|
// Vault V2's transient firstTotalAssets tracks the first allocation in a
|
|
1574
1739
|
// transaction independently from elapsed time. Later allocations must not
|
|
@@ -30,6 +30,13 @@ export declare const DEFAULT_CAP_ACCRUAL_BUFFER: bigint;
|
|
|
30
30
|
* `VaultV2BluePublicAllocatorOptions.allocatorCapHeadroom`.
|
|
31
31
|
*/
|
|
32
32
|
export declare const DEFAULT_ALLOCATOR_CAP_HEADROOM: bigint;
|
|
33
|
+
/**
|
|
34
|
+
* Minimum shares a Morpho Blue market, Vault V1 or Vault V2 must hold at `DEAD_ADDRESS` to count as
|
|
35
|
+
* protected against share-price inflation (1e9, Protocol team rule).
|
|
36
|
+
*/
|
|
37
|
+
export declare const MIN_DEAD_SHARES = 1000000000n;
|
|
38
|
+
/** Minimum assets, in the vault asset's smallest unit, a Vault V2's dead shares must be worth (1e6). */
|
|
39
|
+
export declare const MIN_VAULT_V2_DEAD_ASSETS = 1000000n;
|
|
33
40
|
/** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
|
|
34
41
|
export declare const MAX_ABSOLUTE_SHARE_PRICE: bigint;
|
|
35
42
|
/**
|
|
@@ -32,6 +32,13 @@ export const DEFAULT_CAP_ACCRUAL_BUFFER = Time.s.from.h(2n);
|
|
|
32
32
|
* `VaultV2BluePublicAllocatorOptions.allocatorCapHeadroom`.
|
|
33
33
|
*/
|
|
34
34
|
export const DEFAULT_ALLOCATOR_CAP_HEADROOM = MathLib.WAD / 100n;
|
|
35
|
+
/**
|
|
36
|
+
* Minimum shares a Morpho Blue market, Vault V1 or Vault V2 must hold at `DEAD_ADDRESS` to count as
|
|
37
|
+
* protected against share-price inflation (1e9, Protocol team rule).
|
|
38
|
+
*/
|
|
39
|
+
export const MIN_DEAD_SHARES = 1000000000n;
|
|
40
|
+
/** Minimum assets, in the vault asset's smallest unit, a Vault V2's dead shares must be worth (1e6). */
|
|
41
|
+
export const MIN_VAULT_V2_DEAD_ASSETS = 1000000n;
|
|
35
42
|
/** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
|
|
36
43
|
export const MAX_ABSOLUTE_SHARE_PRICE = 100n * MathLib.RAY;
|
|
37
44
|
/**
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { type AccrualVault, type AccrualVaultV2, type IMarket } from "@morpho-org/blue-sdk";
|
|
2
|
+
import type { Address, Hash } from "viem";
|
|
3
|
+
type DeadSharesPath = readonly (Address | Hash)[];
|
|
4
|
+
/**
|
|
5
|
+
* Checks that a Morpho Blue market holds at least `MIN_DEAD_SHARES` supply shares at `DEAD_ADDRESS`.
|
|
6
|
+
*
|
|
7
|
+
* @param market - Fetched market snapshot.
|
|
8
|
+
* @param path - Vaults leading to this market, outermost first; empty for a direct market.
|
|
9
|
+
* @returns Nothing; returns normally when the market passes.
|
|
10
|
+
* @throws {MissingDeadSharesDataError} when `market.deadSupplyShares` was not fetched.
|
|
11
|
+
* @throws {InsufficientDeadSharesError} when the market holds fewer than `MIN_DEAD_SHARES` dead supply shares.
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { validateBlueMarketDeadShares } from "@morpho-org/morpho-sdk";
|
|
15
|
+
* import { fetchBlueMarket } from "@morpho-org/morpho-sdk/fetch";
|
|
16
|
+
* import { markets } from "@morpho-org/morpho-test";
|
|
17
|
+
* import { createPublicClient, http } from "viem";
|
|
18
|
+
* import { mainnet } from "viem/chains";
|
|
19
|
+
*
|
|
20
|
+
* const client = createPublicClient({ chain: mainnet, transport: http() });
|
|
21
|
+
* const market = await fetchBlueMarket(markets[mainnet.id].usdc_wbtc.id, client);
|
|
22
|
+
* validateBlueMarketDeadShares(market);
|
|
23
|
+
* // Returns void on success; throws if the snapshot fails the rule.
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export declare function validateBlueMarketDeadShares(market: Pick<IMarket, "params" | "deadSupplyShares"> & {
|
|
27
|
+
readonly id: Hash;
|
|
28
|
+
}, path?: DeadSharesPath): void;
|
|
29
|
+
/**
|
|
30
|
+
* Checks that a Vault V1 holds at least `MIN_DEAD_SHARES` shares at `DEAD_ADDRESS` and that every
|
|
31
|
+
* market in its withdraw queue passes `validateBlueMarketDeadShares`.
|
|
32
|
+
*
|
|
33
|
+
* @param vault - Fetched vault snapshot with its withdraw-queue allocations.
|
|
34
|
+
* @param path - Vaults leading to this vault, outermost first; empty for a direct deposit.
|
|
35
|
+
* @returns Nothing; returns normally when the vault and everything it can allocate to pass.
|
|
36
|
+
* @throws {MissingDeadSharesDataError} when `vault.deadShares`, a withdraw-queue allocation or a
|
|
37
|
+
* market's `deadSupplyShares` was not fetched.
|
|
38
|
+
* @throws {InsufficientDeadSharesError} when the vault or one of its withdraw-queue markets holds
|
|
39
|
+
* too few dead shares.
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* import { validateVaultV1DeadShares } from "@morpho-org/morpho-sdk";
|
|
43
|
+
* import { fetchAccrualVault } from "@morpho-org/morpho-sdk/fetch";
|
|
44
|
+
* import { vaults } from "@morpho-org/morpho-test";
|
|
45
|
+
* import { createPublicClient, http } from "viem";
|
|
46
|
+
* import { mainnet } from "viem/chains";
|
|
47
|
+
*
|
|
48
|
+
* const client = createPublicClient({ chain: mainnet, transport: http() });
|
|
49
|
+
* const vault = await fetchAccrualVault(vaults[mainnet.id].steakUsdc.address, client);
|
|
50
|
+
* validateVaultV1DeadShares(vault);
|
|
51
|
+
* // Returns void on success; throws if the snapshot fails the rule.
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export declare function validateVaultV1DeadShares(vault: AccrualVault, path?: DeadSharesPath): void;
|
|
55
|
+
/**
|
|
56
|
+
* Checks a Vault V2 against the dead-deposit rule: at least `MIN_DEAD_SHARES` shares at
|
|
57
|
+
* `DEAD_ADDRESS` worth at least `MIN_VAULT_V2_DEAD_ASSETS` assets, a share price above
|
|
58
|
+
* `1 / (10 * virtualShares)`, and every Blue market or Vault V1 it can allocate to (non-zero
|
|
59
|
+
* absolute cap) passing its own rule. Zero-cap entries are skipped.
|
|
60
|
+
*
|
|
61
|
+
* @param vault - Fetched vault snapshot with its adapters and `absoluteCaps`.
|
|
62
|
+
* @param path - Vaults leading to this vault, outermost first; empty for a direct deposit.
|
|
63
|
+
* @returns Nothing; returns normally when the vault and everything it can allocate to pass.
|
|
64
|
+
* @throws {MissingDeadSharesDataError} when a dead-share field, an adapter cap, or the data of an
|
|
65
|
+
* adapter the SDK cannot hydrate is missing.
|
|
66
|
+
* @throws {InsufficientDeadSharesError} when the vault or an allocatable market or Vault V1 fails the rule.
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* import { validateVaultV2DeadShares } from "@morpho-org/morpho-sdk";
|
|
70
|
+
* import { fetchAccrualVaultV2 } from "@morpho-org/morpho-sdk/fetch";
|
|
71
|
+
* import { createPublicClient, http } from "viem";
|
|
72
|
+
* import { mainnet } from "viem/chains";
|
|
73
|
+
*
|
|
74
|
+
* const client = createPublicClient({ chain: mainnet, transport: http() });
|
|
75
|
+
* const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
|
|
76
|
+
* const vault = await fetchAccrualVaultV2(keyrockUsdcVaultV2, client);
|
|
77
|
+
* validateVaultV2DeadShares(vault);
|
|
78
|
+
* // Returns void on success; throws if the snapshot fails the rule.
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export declare function validateVaultV2DeadShares(vault: AccrualVaultV2, path?: DeadSharesPath): void;
|
|
82
|
+
export {};
|