@morpho-org/morpho-sdk 9.0.0 → 9.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/lib/cjs/actions/blue/borrow.d.ts +1 -0
- package/lib/cjs/actions/blue/borrow.js +1 -0
- package/lib/cjs/actions/blue/refinance.d.ts +1 -0
- package/lib/cjs/actions/blue/refinance.js +3 -0
- package/lib/cjs/actions/blue/repay.d.ts +1 -0
- package/lib/cjs/actions/blue/repay.js +1 -0
- package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +1 -0
- package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -0
- package/lib/cjs/actions/blue/supply.d.ts +1 -0
- package/lib/cjs/actions/blue/supply.js +2 -0
- package/lib/cjs/actions/blue/supplyCollateral.d.ts +1 -0
- package/lib/cjs/actions/blue/supplyCollateral.js +1 -0
- package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +1 -0
- package/lib/cjs/actions/blue/supplyCollateralBorrow.js +2 -0
- package/lib/cjs/actions/blue/withdraw.d.ts +1 -0
- package/lib/cjs/actions/blue/withdraw.js +2 -0
- package/lib/cjs/actions/blue/withdrawCollateral.d.ts +1 -0
- package/lib/cjs/actions/blue/withdrawCollateral.js +1 -0
- package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
- package/lib/cjs/actions/midnight/takeLend.js +1 -0
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
- package/lib/cjs/blue/errors.d.ts +1 -1
- package/lib/cjs/blue/errors.js +2 -1
- package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
- package/lib/cjs/client/morphoViemExtension.js +1 -7
- package/lib/cjs/entities/blue/blue.d.ts +43 -7
- package/lib/cjs/entities/blue/blue.js +27 -3
- package/lib/cjs/entities/midnight/midnight.d.ts +14 -6
- package/lib/cjs/entities/midnight/midnight.js +14 -6
- package/lib/cjs/entities/midnight/types.d.ts +9 -2
- package/lib/cjs/entities/vaultV2/vaultV2.d.ts +3 -1
- package/lib/cjs/entities/vaultV2/vaultV2.js +8 -5
- package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +40 -13
- package/lib/cjs/entities/vaultV2BlueReallocationData.js +207 -70
- package/lib/cjs/errors.d.ts +1 -1
- package/lib/cjs/errors.js +3 -2
- package/lib/cjs/helpers/validate.d.ts +11 -1
- package/lib/cjs/helpers/validate.js +17 -1
- package/lib/cjs/helpers/validateTakeableOffers.d.ts +4 -2
- package/lib/cjs/helpers/validateTakeableOffers.js +12 -1
- package/lib/cjs/types/error.d.ts +10 -1
- package/lib/cjs/types/error.js +13 -2
- package/lib/cjs/types/sharedLiquidity.d.ts +27 -11
- package/lib/esm/actions/blue/borrow.d.ts +1 -0
- package/lib/esm/actions/blue/borrow.js +1 -0
- package/lib/esm/actions/blue/refinance.d.ts +1 -0
- package/lib/esm/actions/blue/refinance.js +4 -1
- package/lib/esm/actions/blue/repay.d.ts +1 -0
- package/lib/esm/actions/blue/repay.js +1 -0
- package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +1 -0
- package/lib/esm/actions/blue/repayWithdrawCollateral.js +3 -1
- package/lib/esm/actions/blue/supply.d.ts +1 -0
- package/lib/esm/actions/blue/supply.js +3 -1
- package/lib/esm/actions/blue/supplyCollateral.d.ts +1 -0
- package/lib/esm/actions/blue/supplyCollateral.js +1 -0
- package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +1 -0
- package/lib/esm/actions/blue/supplyCollateralBorrow.js +3 -1
- package/lib/esm/actions/blue/withdraw.d.ts +1 -0
- package/lib/esm/actions/blue/withdraw.js +3 -1
- package/lib/esm/actions/blue/withdrawCollateral.d.ts +1 -0
- package/lib/esm/actions/blue/withdrawCollateral.js +1 -0
- package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
- package/lib/esm/actions/midnight/takeLend.js +1 -0
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
- package/lib/esm/blue/errors.d.ts +1 -1
- package/lib/esm/blue/errors.js +1 -1
- package/lib/esm/client/morphoViemExtension.d.ts +1 -1
- package/lib/esm/client/morphoViemExtension.js +1 -7
- package/lib/esm/entities/blue/blue.d.ts +43 -7
- package/lib/esm/entities/blue/blue.js +27 -3
- package/lib/esm/entities/midnight/midnight.d.ts +14 -6
- package/lib/esm/entities/midnight/midnight.js +14 -6
- package/lib/esm/entities/midnight/types.d.ts +9 -2
- package/lib/esm/entities/vaultV2/vaultV2.d.ts +3 -1
- package/lib/esm/entities/vaultV2/vaultV2.js +9 -6
- package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +40 -13
- package/lib/esm/entities/vaultV2BlueReallocationData.js +208 -71
- package/lib/esm/errors.d.ts +1 -1
- package/lib/esm/errors.js +1 -1
- package/lib/esm/helpers/validate.d.ts +11 -1
- package/lib/esm/helpers/validate.js +15 -0
- package/lib/esm/helpers/validateTakeableOffers.d.ts +4 -2
- package/lib/esm/helpers/validateTakeableOffers.js +13 -2
- package/lib/esm/types/error.d.ts +10 -1
- package/lib/esm/types/error.js +11 -1
- package/lib/esm/types/sharedLiquidity.d.ts +27 -11
- package/package.json +4 -4
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, Market, MarketUtils, MathLib, UnsupportedVaultV2AdapterError, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2BluePublicAllocatorConfigUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
|
|
2
2
|
import { _try, bigIntComparator } from "@morpho-org/morpho-ts";
|
|
3
3
|
import { isAddressEqual } from "viem";
|
|
4
|
+
import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1ReferralFeeAssets, } from "../actions/blue/common.js";
|
|
4
5
|
import { DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, MAX_REALLOCATION_PENALTY, } from "../helpers/constant.js";
|
|
5
6
|
import { resolveAllocatorCapHeadroom, resolveCapAccrualBuffer, resolveMaxWithdrawalUtilization, } from "../helpers/utilization.js";
|
|
6
|
-
import { InputExceedsMaxError, InsufficientSharedLiquidityError, NegativeInputError, NonPositiveInputError, ReallocationAdapterSupplySharesUnderflowError, ReallocationAllocationUnderflowError, ReallocationWithdrawExceedsMarketSupplyError, UnknownReallocationActiveAdaptersError, UnknownReallocationAdapterError, UnknownReallocationAllocationError, UnknownReallocationMarketError, UnknownReallocationMarketPublicAllocatorConfigError, UnknownReallocationPublicAllocatorConfigError, UnknownReallocationVaultError, } from "../types/index.js";
|
|
7
|
+
import { InputExceedsMaxError, InsufficientSharedLiquidityError, NegativeInputError, NonPositiveInputError, ReallocationAdapterSupplySharesUnderflowError, ReallocationAllocationUnderflowError, ReallocationWithdrawExceedsMarketSupplyError, ReferralFeePctExceededError, UnknownReallocationActiveAdaptersError, UnknownReallocationAdapterError, UnknownReallocationAllocationError, UnknownReallocationMarketError, UnknownReallocationMarketPublicAllocatorConfigError, UnknownReallocationPublicAllocatorConfigError, UnknownReallocationVaultError, } from "../types/index.js";
|
|
7
8
|
const MAX_SHARED_CAP_SEARCH_STEPS = 1024n;
|
|
8
9
|
const createCapReserveState = (markets) => ({
|
|
9
10
|
initialMarkets: { ...markets },
|
|
@@ -11,6 +12,17 @@ const createCapReserveState = (markets) => ({
|
|
|
11
12
|
touchedPairs: new Map(),
|
|
12
13
|
reserveByPairKey: new Map(),
|
|
13
14
|
});
|
|
15
|
+
const cloneCapReserveState = (state) => {
|
|
16
|
+
const touchedPairs = new Map();
|
|
17
|
+
for (const [vault, pairs] of state.touchedPairs)
|
|
18
|
+
touchedPairs.set(vault, new Map(pairs));
|
|
19
|
+
return {
|
|
20
|
+
initialMarkets: { ...state.initialMarkets },
|
|
21
|
+
marketAccruals: new Map(state.marketAccruals),
|
|
22
|
+
touchedPairs,
|
|
23
|
+
reserveByPairKey: new Map(state.reserveByPairKey),
|
|
24
|
+
};
|
|
25
|
+
};
|
|
14
26
|
/** Creates isolated transaction-scoped state for one simulation. @internal */
|
|
15
27
|
const createSimulationContext = () => ({
|
|
16
28
|
donatedPenaltyAssets: {},
|
|
@@ -161,6 +173,8 @@ export class VaultV2BlueReallocationData {
|
|
|
161
173
|
mutableAllocations;
|
|
162
174
|
/** Chain id associated with this snapshot. */
|
|
163
175
|
chainId;
|
|
176
|
+
/** Timestamp of the block the state was fetched at. */
|
|
177
|
+
timestamp;
|
|
164
178
|
/** Markets indexed by market id. */
|
|
165
179
|
markets;
|
|
166
180
|
/** Vault V2 entities indexed by address. */
|
|
@@ -182,6 +196,8 @@ export class VaultV2BlueReallocationData {
|
|
|
182
196
|
constructor(input) {
|
|
183
197
|
const isClone = input instanceof VaultV2BlueReallocationData;
|
|
184
198
|
this.chainId = input.chainId;
|
|
199
|
+
this.timestamp =
|
|
200
|
+
input.timestamp == null ? undefined : BigInt(input.timestamp);
|
|
185
201
|
this.mutableMarkets = {};
|
|
186
202
|
this.mutableVaults = {};
|
|
187
203
|
this.mutableAllocations = {};
|
|
@@ -554,16 +570,29 @@ export class VaultV2BlueReallocationData {
|
|
|
554
570
|
* Computes Vault V2 BluePublicAllocator calls available for a target market.
|
|
555
571
|
*
|
|
556
572
|
* Without `options.operation`, discovers every friendly call. With an
|
|
557
|
-
* operation,
|
|
558
|
-
*
|
|
559
|
-
*
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
* `
|
|
563
|
-
*
|
|
564
|
-
*
|
|
565
|
-
*
|
|
566
|
-
*
|
|
573
|
+
* operation, penalty tiers are considered ascending, starting with free
|
|
574
|
+
* vaults. The free tier aims to bring the target market back to 90%
|
|
575
|
+
* utilization; positive tiers cover only the remaining absolute shortfall
|
|
576
|
+
* (borrows minus supply). Within each tier, source markets go to the
|
|
577
|
+
* friendly source utilization (90% by default) before 100%. Free capacity
|
|
578
|
+
* inside `allocatorCapHeadroom` is kept unused, so a penalized leg can cover
|
|
579
|
+
* it instead. Discovery and liquidity getters still count every vault up to
|
|
580
|
+
* `options.maxPenalty`. A shared relative-cap lower bound may require one call
|
|
581
|
+
* to exceed the targeted amount. For `refinance`, compute the plan on the
|
|
582
|
+
* destination-market handle (for example,
|
|
583
|
+
* `client.morpho.blue(destination.marketParams, chainId)`), not the source
|
|
584
|
+
* handle. Pass the source position's `borrowAssets` accrued to
|
|
585
|
+
* `max(now, source.lastUpdate, destination.lastUpdate) + 2h` as
|
|
586
|
+
* `operation.amount`; the optional `operation.referralFeePct` is WAD-scaled.
|
|
587
|
+
* The planner includes the referral fee and its allocator-leg penalties in
|
|
588
|
+
* destination debt, so penalized legs also cover their own penalty.
|
|
589
|
+
* Refinance never uses vaults with a 100% penalty.
|
|
590
|
+
* Friendly source utilization defaults to 90% and is configurable through
|
|
591
|
+
* `options.maxWithdrawalUtilization`. Market/vault state and the returned
|
|
592
|
+
* post-state stay at `timestamp`. An enabled operation that needs no
|
|
593
|
+
* reallocation still returns a clone accrued to `timestamp`. Only
|
|
594
|
+
* target-market cap checks reserve interest the vault's existing allocation
|
|
595
|
+
* would accrue through `timestamp + capAccrualBuffer`
|
|
567
596
|
* (two hours by default; `0n` disables it). When an operation's plan would
|
|
568
597
|
* come within `allocatorCapHeadroom` (1% of the cap by default) of a target
|
|
569
598
|
* BluePublicAllocator cap, the plan is reduced to the larger of the
|
|
@@ -604,8 +633,9 @@ export class VaultV2BlueReallocationData {
|
|
|
604
633
|
* every leg of a plan.
|
|
605
634
|
* @returns Flat action-ready reallocations and their post-simulation state.
|
|
606
635
|
* @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
|
|
607
|
-
* @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `
|
|
636
|
+
* @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, `maxPenalty`, or `referralFeePct` is negative.
|
|
608
637
|
* @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
|
|
638
|
+
* @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
|
|
609
639
|
* @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
|
|
610
640
|
* @throws {UnknownReallocationMarketError} when a required market is absent.
|
|
611
641
|
* @throws {UnknownReallocationVaultError} when configured vault state is absent.
|
|
@@ -613,7 +643,7 @@ export class VaultV2BlueReallocationData {
|
|
|
613
643
|
* @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
|
|
614
644
|
* @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
|
|
615
645
|
* @throws {UnknownReallocationAllocationError} when required allocation state is absent.
|
|
616
|
-
* @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall.
|
|
646
|
+
* @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall and, for refinance, its planned allocator penalties.
|
|
617
647
|
* @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
|
|
618
648
|
* @example
|
|
619
649
|
* ```ts
|
|
@@ -667,6 +697,14 @@ export class VaultV2BlueReallocationData {
|
|
|
667
697
|
const { amount, type } = operation;
|
|
668
698
|
if (amount <= 0n)
|
|
669
699
|
throw new NonPositiveInputError("amount", amount);
|
|
700
|
+
const referralFeePct = type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
|
|
701
|
+
if (referralFeePct < 0n)
|
|
702
|
+
throw new NegativeInputError("referralFeePct", referralFeePct);
|
|
703
|
+
if (referralFeePct >= MathLib.WAD)
|
|
704
|
+
throw new ReferralFeePctExceededError(referralFeePct);
|
|
705
|
+
const feeAssets = type === "refinance"
|
|
706
|
+
? getBlueBundlesV1ReferralFeeAssets(amount, referralFeePct)
|
|
707
|
+
: 0n;
|
|
670
708
|
const timestamp = options.timestamp == null
|
|
671
709
|
? this.getLatestSnapshotTimestamp()
|
|
672
710
|
: BigInt(options.timestamp);
|
|
@@ -687,60 +725,150 @@ export class VaultV2BlueReallocationData {
|
|
|
687
725
|
}
|
|
688
726
|
const newTotalBorrowAssets = type === "borrow"
|
|
689
727
|
? market.totalBorrowAssets + amount
|
|
690
|
-
:
|
|
728
|
+
: type === "refinance"
|
|
729
|
+
? market.totalBorrowAssets + amount + feeAssets
|
|
730
|
+
: market.totalBorrowAssets;
|
|
691
731
|
const newTotalSupplyAssets = type === "withdraw"
|
|
692
732
|
? market.totalSupplyAssets - amount
|
|
693
733
|
: market.totalSupplyAssets;
|
|
734
|
+
const requiredAssets = MathLib.wDivUp(newTotalBorrowAssets, DEFAULT_SUPPLY_TARGET_UTILIZATION) -
|
|
735
|
+
newTotalSupplyAssets;
|
|
694
736
|
if (MarketUtils.getUtilization({
|
|
695
737
|
totalSupplyAssets: newTotalSupplyAssets,
|
|
696
738
|
totalBorrowAssets: newTotalBorrowAssets,
|
|
697
|
-
}) <= DEFAULT_SUPPLY_TARGET_UTILIZATION
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
739
|
+
}) <= DEFAULT_SUPPLY_TARGET_UTILIZATION ||
|
|
740
|
+
requiredAssets <= 0n) {
|
|
741
|
+
const data = this.clone();
|
|
742
|
+
data.setMarkets([market]);
|
|
743
|
+
return { reallocations: [], data };
|
|
744
|
+
}
|
|
703
745
|
const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
|
|
704
746
|
? newTotalBorrowAssets - newTotalSupplyAssets
|
|
705
747
|
: 0n;
|
|
748
|
+
const penaltyTiers = [
|
|
749
|
+
0n,
|
|
750
|
+
...new Set(Object.values(this.publicAllocatorConfigs).flatMap((config) => config != null && config.penalty > 0n && config.penalty <= maxPenalty
|
|
751
|
+
? [config.penalty]
|
|
752
|
+
: [])),
|
|
753
|
+
].sort(bigIntComparator((tier) => tier));
|
|
706
754
|
const plan = (maxAssets, headroom) => {
|
|
707
|
-
|
|
708
|
-
const
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
755
|
+
let reserves = createCapReserveState(this.mutableMarkets);
|
|
756
|
+
const reallocations = [];
|
|
757
|
+
let data = this.clone();
|
|
758
|
+
let context = createSimulationContext();
|
|
759
|
+
let remainingShortfall = absoluteShortfall;
|
|
760
|
+
let allocatorCapBoundTargets = new Set();
|
|
761
|
+
let idleBoundVaults = new Set();
|
|
762
|
+
for (const penalty of penaltyTiers) {
|
|
763
|
+
if (type === "refinance" && penalty === MathLib.WAD)
|
|
764
|
+
continue;
|
|
765
|
+
let isFriendlyPass = true;
|
|
766
|
+
for (const utilization of [maxWithdrawalUtilization, MathLib.WAD]) {
|
|
767
|
+
const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
|
|
768
|
+
isFriendlyPass = false;
|
|
769
|
+
if (remainingShortfall === 0n && !isFreeFriendlyPass)
|
|
770
|
+
continue;
|
|
771
|
+
let passMaxAssets = isFreeFriendlyPass
|
|
772
|
+
? maxAssets
|
|
773
|
+
: remainingShortfall;
|
|
774
|
+
const retryPaidPass = type === "refinance" && penalty > 0n;
|
|
775
|
+
if (retryPaidPass) {
|
|
776
|
+
passMaxAssets = MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
|
|
777
|
+
}
|
|
778
|
+
let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
|
|
779
|
+
// Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
|
|
780
|
+
const passStart = retryPaidPass
|
|
781
|
+
? {
|
|
782
|
+
data: data.clone(),
|
|
783
|
+
context,
|
|
784
|
+
reserves: cloneCapReserveState(reserves),
|
|
785
|
+
reallocationCount: reallocations.length,
|
|
786
|
+
}
|
|
787
|
+
: undefined;
|
|
788
|
+
let previousPassReallocatedAssets = 0n;
|
|
789
|
+
let hi;
|
|
790
|
+
let bestAttempt;
|
|
791
|
+
while (true) {
|
|
792
|
+
if (passStart != null) {
|
|
793
|
+
data = passStart.data.clone();
|
|
794
|
+
context = passStart.context;
|
|
795
|
+
reserves = cloneCapReserveState(passStart.reserves);
|
|
796
|
+
reallocations.length = passStart.reallocationCount;
|
|
797
|
+
}
|
|
798
|
+
const pass = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
|
|
799
|
+
context,
|
|
800
|
+
reserves,
|
|
801
|
+
marketId,
|
|
802
|
+
maxWithdrawalUtilization: utilization,
|
|
803
|
+
maxAssets: passMaxAssets,
|
|
804
|
+
capAccrualBuffer,
|
|
805
|
+
allocatorCapHeadroom: headroom,
|
|
806
|
+
penalty,
|
|
807
|
+
options: normalizedOptions,
|
|
808
|
+
});
|
|
809
|
+
reallocations.push(...pass.reallocations);
|
|
810
|
+
data = pass.data;
|
|
811
|
+
context = pass.context;
|
|
812
|
+
if (isFreeFriendlyPass) {
|
|
813
|
+
allocatorCapBoundTargets = pass.allocatorCapBoundTargets;
|
|
814
|
+
idleBoundVaults = pass.idleBoundVaults;
|
|
815
|
+
}
|
|
816
|
+
const currentMarket = data.getMarket(marketId);
|
|
817
|
+
const penaltyAssets = type === "refinance"
|
|
818
|
+
? getBlueBundlesV1PenaltyAssets(reallocations)
|
|
819
|
+
: 0n;
|
|
820
|
+
const borrow = type === "borrow"
|
|
821
|
+
? currentMarket.totalBorrowAssets + amount
|
|
822
|
+
: type === "refinance"
|
|
823
|
+
? currentMarket.totalBorrowAssets +
|
|
824
|
+
amount +
|
|
825
|
+
feeAssets +
|
|
826
|
+
penaltyAssets
|
|
827
|
+
: currentMarket.totalBorrowAssets;
|
|
828
|
+
const supply = type === "withdraw"
|
|
829
|
+
? currentMarket.totalSupplyAssets - amount
|
|
830
|
+
: currentMarket.totalSupplyAssets;
|
|
831
|
+
remainingShortfall = borrow > supply ? borrow - supply : 0n;
|
|
832
|
+
const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
|
|
833
|
+
if (passStart == null)
|
|
834
|
+
break;
|
|
835
|
+
if (bestAttempt == null ||
|
|
836
|
+
remainingShortfall < bestAttempt.remainingShortfall ||
|
|
837
|
+
(remainingShortfall === bestAttempt.remainingShortfall &&
|
|
838
|
+
passReallocatedAssets < bestAttempt.passReallocatedAssets))
|
|
839
|
+
bestAttempt = {
|
|
840
|
+
data,
|
|
841
|
+
context,
|
|
842
|
+
reserves: cloneCapReserveState(reserves),
|
|
843
|
+
reallocations: pass.reallocations,
|
|
844
|
+
remainingShortfall,
|
|
845
|
+
passReallocatedAssets,
|
|
846
|
+
};
|
|
847
|
+
if (remainingShortfall === 0n)
|
|
848
|
+
hi = hi == null ? passMaxAssets : MathLib.min(hi, passMaxAssets);
|
|
849
|
+
else
|
|
850
|
+
lo = MathLib.max(lo, passMaxAssets);
|
|
851
|
+
if (hi != null) {
|
|
852
|
+
if (hi - lo <= 1n)
|
|
853
|
+
break;
|
|
854
|
+
passMaxAssets = (lo + hi) / 2n;
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
if (passReallocatedAssets <= previousPassReallocatedAssets)
|
|
858
|
+
break;
|
|
859
|
+
previousPassReallocatedAssets = passReallocatedAssets;
|
|
860
|
+
passMaxAssets += MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
|
|
861
|
+
}
|
|
862
|
+
if (passStart != null && bestAttempt != null) {
|
|
863
|
+
data = bestAttempt.data;
|
|
864
|
+
context = bestAttempt.context;
|
|
865
|
+
reserves = cloneCapReserveState(bestAttempt.reserves);
|
|
866
|
+
reallocations.length = passStart.reallocationCount;
|
|
867
|
+
reallocations.push(...bestAttempt.reallocations);
|
|
868
|
+
remainingShortfall = bestAttempt.remainingShortfall;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
739
871
|
}
|
|
740
|
-
// The fallback pass only runs when the plan moves exactly the absolute
|
|
741
|
-
// shortfall, which a reduced plan would move anyway.
|
|
742
|
-
const allocatorCapBoundTargets = friendly.allocatorCapBoundTargets;
|
|
743
|
-
const idleBoundVaults = friendly.idleBoundVaults;
|
|
744
872
|
let reallocatedAssets = 0n;
|
|
745
873
|
let unboundAssets = 0n;
|
|
746
874
|
for (const { vault, from, to, assets } of reallocations) {
|
|
@@ -756,6 +884,10 @@ export class VaultV2BlueReallocationData {
|
|
|
756
884
|
liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
|
|
757
885
|
reallocatedAssets,
|
|
758
886
|
unboundAssets,
|
|
887
|
+
coversShortfall: type === "refinance"
|
|
888
|
+
? reallocatedAssets >=
|
|
889
|
+
absoluteShortfall + getBlueBundlesV1PenaltyAssets(reallocations)
|
|
890
|
+
: reallocatedAssets >= absoluteShortfall,
|
|
759
891
|
};
|
|
760
892
|
};
|
|
761
893
|
// A leg that fills an allocator cap, or idle legs that together take
|
|
@@ -769,30 +901,32 @@ export class VaultV2BlueReallocationData {
|
|
|
769
901
|
? absoluteShortfall
|
|
770
902
|
: target.unboundAssets, allocatorCapHeadroom);
|
|
771
903
|
// Shared-cap fitting is not monotonic in the budget.
|
|
772
|
-
if (selected.
|
|
773
|
-
target.reallocatedAssets >= absoluteShortfall)
|
|
904
|
+
if (!selected.coversShortfall && target.coversShortfall)
|
|
774
905
|
selected = target;
|
|
775
906
|
}
|
|
776
907
|
let available = MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
|
|
777
908
|
// Without headroom, `target` already is the full-cap plan toward the target.
|
|
778
909
|
const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
|
|
779
910
|
for (const maxAssets of fullCapBudgets) {
|
|
780
|
-
if (selected.
|
|
911
|
+
if (selected.coversShortfall)
|
|
781
912
|
break;
|
|
782
913
|
selected = plan(maxAssets, 0n);
|
|
783
914
|
if (selected.reallocatedAssets > available)
|
|
784
915
|
available = selected.reallocatedAssets;
|
|
785
916
|
}
|
|
786
|
-
if (selected.
|
|
917
|
+
if (!selected.coversShortfall) {
|
|
787
918
|
throw new InsufficientSharedLiquidityError({
|
|
788
919
|
marketId,
|
|
789
|
-
shortfall: absoluteShortfall
|
|
920
|
+
shortfall: absoluteShortfall +
|
|
921
|
+
(type === "refinance"
|
|
922
|
+
? getBlueBundlesV1PenaltyAssets(selected.reallocations)
|
|
923
|
+
: 0n),
|
|
790
924
|
available,
|
|
791
925
|
});
|
|
792
926
|
}
|
|
793
927
|
return { reallocations: selected.reallocations, data: selected.data };
|
|
794
928
|
}
|
|
795
|
-
computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, options = {}, }) {
|
|
929
|
+
computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
|
|
796
930
|
if (options.enabled === false)
|
|
797
931
|
return {
|
|
798
932
|
reallocations: [],
|
|
@@ -835,23 +969,23 @@ export class VaultV2BlueReallocationData {
|
|
|
835
969
|
return {
|
|
836
970
|
key,
|
|
837
971
|
ids: getAdapterIds(adapterIdsCache, adapter, market),
|
|
838
|
-
reserve: () => {
|
|
839
|
-
let reserve =
|
|
972
|
+
reserve: (reserveState) => {
|
|
973
|
+
let reserve = reserveState.reserveByPairKey.get(key);
|
|
840
974
|
if (reserve == null) {
|
|
841
|
-
let accruals =
|
|
975
|
+
let accruals = reserveState.marketAccruals.get(market.id);
|
|
842
976
|
if (accruals == null) {
|
|
843
|
-
const initialMarket =
|
|
977
|
+
const initialMarket = reserveState.initialMarkets[market.id];
|
|
844
978
|
if (initialMarket == null)
|
|
845
979
|
throw new UnknownReallocationMarketError(market.id);
|
|
846
980
|
accruals = [
|
|
847
981
|
initialMarket.accrueInterest(timestamp),
|
|
848
982
|
initialMarket.accrueInterest(timestamp + capAccrualBuffer),
|
|
849
983
|
];
|
|
850
|
-
|
|
984
|
+
reserveState.marketAccruals.set(market.id, accruals);
|
|
851
985
|
}
|
|
852
986
|
const [atTimestamp, projected] = accruals;
|
|
853
987
|
reserve = MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
|
|
854
|
-
|
|
988
|
+
reserveState.reserveByPairKey.set(key, reserve);
|
|
855
989
|
}
|
|
856
990
|
return reserve;
|
|
857
991
|
},
|
|
@@ -868,7 +1002,7 @@ export class VaultV2BlueReallocationData {
|
|
|
868
1002
|
if (seen.has(pair.key) || !pair.ids.includes(id))
|
|
869
1003
|
continue;
|
|
870
1004
|
seen.add(pair.key);
|
|
871
|
-
reserve += pair.reserve();
|
|
1005
|
+
reserve += pair.reserve(reserves);
|
|
872
1006
|
}
|
|
873
1007
|
return reserve;
|
|
874
1008
|
};
|
|
@@ -884,6 +1018,8 @@ export class VaultV2BlueReallocationData {
|
|
|
884
1018
|
publicAllocatorConfig.penalty >
|
|
885
1019
|
(options.maxPenalty ?? DEFAULT_MAX_REALLOCATION_PENALTY))
|
|
886
1020
|
return;
|
|
1021
|
+
if (penalty != null && publicAllocatorConfig.penalty !== penalty)
|
|
1022
|
+
return;
|
|
887
1023
|
const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
|
|
888
1024
|
// Exclude rounded penalty dust from idle candidates so one donation
|
|
889
1025
|
// cannot replenish liquidity for another same-plan reallocation.
|
|
@@ -934,7 +1070,7 @@ export class VaultV2BlueReallocationData {
|
|
|
934
1070
|
const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
|
|
935
1071
|
const allocatorHeadroom = MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
|
|
936
1072
|
untracked +
|
|
937
|
-
targetPair.reserve()), MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
|
|
1073
|
+
targetPair.reserve(reserves)), MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
|
|
938
1074
|
const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
|
|
939
1075
|
const minimumAllocationChange = MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
|
|
940
1076
|
const blockedTargetIds = targetAllocations
|
|
@@ -1303,7 +1439,7 @@ export class VaultV2BlueReallocationData {
|
|
|
1303
1439
|
}, utilization);
|
|
1304
1440
|
}
|
|
1305
1441
|
getLatestSnapshotTimestamp() {
|
|
1306
|
-
let timestamp = 0n;
|
|
1442
|
+
let timestamp = this.timestamp ?? 0n;
|
|
1307
1443
|
for (const market of Object.values(this.markets)) {
|
|
1308
1444
|
if (market != null)
|
|
1309
1445
|
timestamp = MathLib.max(timestamp, market.lastUpdate);
|
|
@@ -1348,6 +1484,7 @@ export class VaultV2BlueReallocationData {
|
|
|
1348
1484
|
}
|
|
1349
1485
|
data = new VaultV2BlueReallocationData({
|
|
1350
1486
|
chainId: this.chainId,
|
|
1487
|
+
timestamp: this.timestamp,
|
|
1351
1488
|
markets: probeMarkets,
|
|
1352
1489
|
});
|
|
1353
1490
|
if (sourceVaultKey != null) {
|
package/lib/esm/errors.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
|
|
2
2
|
/** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
|
|
3
3
|
UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
|
|
4
|
-
export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
|
|
4
|
+
export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
|
|
5
5
|
export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
|
|
6
6
|
export type { ErrorClass } from "@morpho-org/morpho-ts";
|
|
7
7
|
export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
|
package/lib/esm/errors.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
|
|
2
2
|
/** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
|
|
3
3
|
UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
|
|
4
|
-
export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
|
|
4
|
+
export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
|
|
5
5
|
export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
|
|
6
6
|
export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AccrualPosition, type MarketId } from "@morpho-org/blue-sdk";
|
|
1
|
+
import { type AccrualPosition, type MarketId, type MarketParams } from "@morpho-org/blue-sdk";
|
|
2
2
|
import { type Market as MidnightMarket, type MarketInput as MidnightMarketInput } from "@morpho-org/midnight-sdk";
|
|
3
3
|
import { type Address } from "viem";
|
|
4
4
|
import { type VaultV2BlueReallocation } from "../types/index.js";
|
|
@@ -15,6 +15,16 @@ import { type VaultV2BlueReallocation } from "../types/index.js";
|
|
|
15
15
|
* @internal
|
|
16
16
|
*/
|
|
17
17
|
export declare const validateUint256Field: (field: string, value: bigint) => void;
|
|
18
|
+
/**
|
|
19
|
+
* Rejects market params whose cached `id` does not hash from their five tuple fields, so a
|
|
20
|
+
* hand-built or mutated object cannot make the SDK describe one market while calldata targets another.
|
|
21
|
+
*
|
|
22
|
+
* @param marketParams - Market params whose `id` must equal the id derived from the tuple.
|
|
23
|
+
* @returns Nothing when `marketParams.id` matches the derived id.
|
|
24
|
+
* @throws {MarketIdMismatchError} when `marketParams.id` differs from the derived id.
|
|
25
|
+
* @internal
|
|
26
|
+
*/
|
|
27
|
+
export declare const validateMarketParamsId: (marketParams: MarketParams) => void;
|
|
18
28
|
/**
|
|
19
29
|
* Rejects a deadline that no periphery can honour: the contracts read `0` as "unset" and the ABI
|
|
20
30
|
* slot is a `uint256`. Callers that also need the deadline to be in the future layer their own
|
|
@@ -34,6 +34,21 @@ export const validateUint256Field = (field, value) => {
|
|
|
34
34
|
throw new InputExceedsMaxError({ field, value, max: maxUint256 });
|
|
35
35
|
}
|
|
36
36
|
};
|
|
37
|
+
/**
|
|
38
|
+
* Rejects market params whose cached `id` does not hash from their five tuple fields, so a
|
|
39
|
+
* hand-built or mutated object cannot make the SDK describe one market while calldata targets another.
|
|
40
|
+
*
|
|
41
|
+
* @param marketParams - Market params whose `id` must equal the id derived from the tuple.
|
|
42
|
+
* @returns Nothing when `marketParams.id` matches the derived id.
|
|
43
|
+
* @throws {MarketIdMismatchError} when `marketParams.id` differs from the derived id.
|
|
44
|
+
* @internal
|
|
45
|
+
*/
|
|
46
|
+
export const validateMarketParamsId = (marketParams) => {
|
|
47
|
+
const derivedId = MarketUtils.getMarketId(marketParams);
|
|
48
|
+
if (marketParams.id !== derivedId) {
|
|
49
|
+
throw new MarketIdMismatchError(marketParams.id, derivedId);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
37
52
|
/**
|
|
38
53
|
* Rejects a deadline that no periphery can honour: the contracts read `0` as "unset" and the ABI
|
|
39
54
|
* slot is a `uint256`. Callers that also need the deadline to be in the future layer their own
|
|
@@ -7,13 +7,15 @@ import type { MarketInput, OfferStruct } from "@morpho-org/midnight-sdk";
|
|
|
7
7
|
* @throws {EmptyMidnightTakeableOffersError} when no offers are provided.
|
|
8
8
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
9
9
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer belongs to another market.
|
|
10
|
-
* @throws {
|
|
10
|
+
* @throws {MidnightTakeableOfferZeroSellerReceiverError} when a sell offer routes seller proceeds to the zero address.
|
|
11
|
+
* @throws {MidnightCalldataEncodingError} when a market cannot be ABI-encoded or a sell offer's
|
|
12
|
+
* `receiverIfMakerIsSeller` is not an address.
|
|
11
13
|
* @internal
|
|
12
14
|
*/
|
|
13
15
|
export declare const validateTakeableOffers: (params: {
|
|
14
16
|
readonly market: MarketInput;
|
|
15
17
|
readonly takeableOffers: readonly {
|
|
16
|
-
readonly offer: Pick<OfferStruct, "buy" | "market">;
|
|
18
|
+
readonly offer: Pick<OfferStruct, "buy" | "market" | "receiverIfMakerIsSeller">;
|
|
17
19
|
}[];
|
|
18
20
|
readonly expectedBuy: boolean;
|
|
19
21
|
}) => `0x${string}`;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isAddressEqual, zeroAddress } from "viem";
|
|
2
|
+
import { EmptyMidnightTakeableOffersError, MidnightTakeableOfferMarketMismatchError, MidnightTakeableOfferZeroSellerReceiverError, } from "../types/index.js";
|
|
2
3
|
import { encodeMidnightMarketId } from "./encodeMidnightCalldata.js";
|
|
4
|
+
import { validateMidnightAddress } from "./validateMidnightAccount.js";
|
|
3
5
|
import { validateOfferSides } from "./validateOfferSides.js";
|
|
4
6
|
/**
|
|
5
7
|
* Validates the pure invariants shared by Midnight take entity and action layers.
|
|
@@ -9,7 +11,9 @@ import { validateOfferSides } from "./validateOfferSides.js";
|
|
|
9
11
|
* @throws {EmptyMidnightTakeableOffersError} when no offers are provided.
|
|
10
12
|
* @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
|
|
11
13
|
* @throws {MidnightTakeableOfferMarketMismatchError} when an offer belongs to another market.
|
|
12
|
-
* @throws {
|
|
14
|
+
* @throws {MidnightTakeableOfferZeroSellerReceiverError} when a sell offer routes seller proceeds to the zero address.
|
|
15
|
+
* @throws {MidnightCalldataEncodingError} when a market cannot be ABI-encoded or a sell offer's
|
|
16
|
+
* `receiverIfMakerIsSeller` is not an address.
|
|
13
17
|
* @internal
|
|
14
18
|
*/
|
|
15
19
|
export const validateTakeableOffers = (params) => {
|
|
@@ -27,6 +31,13 @@ export const validateTakeableOffers = (params) => {
|
|
|
27
31
|
actualMarket: actualMarketId,
|
|
28
32
|
});
|
|
29
33
|
}
|
|
34
|
+
if (take.offer.buy)
|
|
35
|
+
continue;
|
|
36
|
+
// Reject a malformed address before viem compares it.
|
|
37
|
+
validateMidnightAddress(`takeableOffers[${index}].offer.receiverIfMakerIsSeller`, take.offer.receiverIfMakerIsSeller);
|
|
38
|
+
if (isAddressEqual(take.offer.receiverIfMakerIsSeller, zeroAddress)) {
|
|
39
|
+
throw new MidnightTakeableOfferZeroSellerReceiverError({ index });
|
|
40
|
+
}
|
|
30
41
|
}
|
|
31
42
|
return marketId;
|
|
32
43
|
};
|
package/lib/esm/types/error.d.ts
CHANGED
|
@@ -1322,7 +1322,10 @@ export declare class EmptyBlueParkingMarketError extends Error {
|
|
|
1322
1322
|
readonly marketId: MarketId;
|
|
1323
1323
|
});
|
|
1324
1324
|
}
|
|
1325
|
-
/**
|
|
1325
|
+
/**
|
|
1326
|
+
* Thrown when parked assets would mint no Morpho Blue supply shares at preparation time; see
|
|
1327
|
+
* `MorphoMidnight.supplyBlueMakeLend` for why this is not an execution-time guarantee.
|
|
1328
|
+
*/
|
|
1326
1329
|
export declare class ZeroBlueParkingSharesError extends Error {
|
|
1327
1330
|
constructor(params: {
|
|
1328
1331
|
readonly marketId: MarketId;
|
|
@@ -1337,6 +1340,12 @@ export declare class MidnightTakeableOfferMarketMismatchError extends Error {
|
|
|
1337
1340
|
actualMarket: string;
|
|
1338
1341
|
});
|
|
1339
1342
|
}
|
|
1343
|
+
/** Thrown when a quoted Midnight sell offer routes its seller proceeds to the zero address. */
|
|
1344
|
+
export declare class MidnightTakeableOfferZeroSellerReceiverError extends Error {
|
|
1345
|
+
constructor(params: {
|
|
1346
|
+
index: number;
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1340
1349
|
/** Thrown when a Midnight offer's ratifier does not match its tree's ratifier route. */
|
|
1341
1350
|
export declare class MidnightOfferRatifierMismatchError extends Error {
|
|
1342
1351
|
constructor(params: {
|
package/lib/esm/types/error.js
CHANGED
|
@@ -1587,7 +1587,10 @@ export class EmptyBlueParkingMarketError extends Error {
|
|
|
1587
1587
|
this.name = "EmptyBlueParkingMarketError";
|
|
1588
1588
|
}
|
|
1589
1589
|
}
|
|
1590
|
-
/**
|
|
1590
|
+
/**
|
|
1591
|
+
* Thrown when parked assets would mint no Morpho Blue supply shares at preparation time; see
|
|
1592
|
+
* `MorphoMidnight.supplyBlueMakeLend` for why this is not an execution-time guarantee.
|
|
1593
|
+
*/
|
|
1591
1594
|
export class ZeroBlueParkingSharesError extends Error {
|
|
1592
1595
|
constructor(params) {
|
|
1593
1596
|
super(`Supplying "${params.assets}" assets to Morpho Blue market "${params.marketId}" mints zero supply shares at its current share price; park more assets or choose another market.`);
|
|
@@ -1601,6 +1604,13 @@ export class MidnightTakeableOfferMarketMismatchError extends Error {
|
|
|
1601
1604
|
this.name = "MidnightTakeableOfferMarketMismatchError";
|
|
1602
1605
|
}
|
|
1603
1606
|
}
|
|
1607
|
+
/** Thrown when a quoted Midnight sell offer routes its seller proceeds to the zero address. */
|
|
1608
|
+
export class MidnightTakeableOfferZeroSellerReceiverError extends Error {
|
|
1609
|
+
constructor(params) {
|
|
1610
|
+
super(`Midnight takeable offer "${params.index}" routes seller proceeds to the zero address. Drop the offer or refresh the quote.`);
|
|
1611
|
+
this.name = "MidnightTakeableOfferZeroSellerReceiverError";
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1604
1614
|
/** Thrown when a Midnight offer's ratifier does not match its tree's ratifier route. */
|
|
1605
1615
|
export class MidnightOfferRatifierMismatchError extends Error {
|
|
1606
1616
|
constructor(params) {
|