@morpho-org/morpho-sdk 10.0.0-next.0 → 10.0.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 +104 -12
- package/lib/cjs/abis.d.ts +1 -1
- package/lib/cjs/abis.js +1 -5
- package/lib/cjs/actions/blue/common.js +4 -2
- package/lib/cjs/actions/blue/withdrawBuyCallback.js +2 -1
- package/lib/cjs/actions/bundles/common.js +20 -14
- package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +2 -1
- package/lib/cjs/actions/midnight/cancelOffers.js +2 -1
- package/lib/cjs/actions/midnight/supplyCollateralBatch.js +4 -2
- package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +2 -1
- package/lib/cjs/actions/midnight/takeBorrow.js +2 -1
- package/lib/cjs/actions/midnight/takeLend.js +2 -1
- package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +2 -1
- package/lib/cjs/actions/midnight/takeWithdraw.js +2 -1
- package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +4 -2
- package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -11
- package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +2 -1
- package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +2 -1
- package/lib/cjs/actions/vaultV1/inKindRedeem.js +6 -3
- package/lib/cjs/actions/vaultV1/migrateToV2.js +1 -1
- package/lib/cjs/actions/vaultV2/forceWithdraw.js +4 -2
- package/lib/cjs/actions/vaultV2/inKindRedeem.js +4 -2
- package/lib/cjs/blue/abis.d.ts +1 -1
- package/lib/cjs/blue/abis.js +1 -5
- package/lib/cjs/blue/entities.d.ts +4 -4
- package/lib/cjs/blue/entities.js +1 -3
- package/lib/cjs/blue/errors.d.ts +2 -2
- package/lib/cjs/blue/errors.js +1 -5
- package/lib/cjs/blue/fetch.d.ts +2 -2
- package/lib/cjs/blue/fetch.js +1 -3
- package/lib/cjs/blue/utils.d.ts +1 -1
- package/lib/cjs/blue/utils.js +1 -2
- package/lib/cjs/entities/blue/blue.js +8 -4
- package/lib/cjs/entities/index.d.ts +4 -4
- package/lib/cjs/entities/index.js +1 -3
- package/lib/cjs/entities/midnight/deadline.js +2 -1
- package/lib/cjs/entities/midnight/midnight.js +14 -7
- package/lib/cjs/entities/midnight/publication.js +73 -44
- package/lib/cjs/entities/requirements/assertContractCode.js +4 -2
- package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +9 -13
- package/lib/cjs/entities/requirements/getErc2612Permit.js +10 -5
- package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -0
- package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +7 -1
- package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.d.ts +21 -0
- package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.js +111 -0
- package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.d.ts +20 -0
- package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.js +76 -0
- package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.d.ts +21 -0
- package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.js +93 -0
- package/lib/cjs/entities/vaultV1/inKindRedeemQuote.d.ts +25 -0
- package/lib/cjs/entities/vaultV1/inKindRedeemQuote.js +85 -0
- package/lib/cjs/entities/vaultV1/migrateToV2Quote.d.ts +20 -0
- package/lib/cjs/entities/vaultV1/migrateToV2Quote.js +37 -0
- package/lib/cjs/entities/vaultV1/vaultV1.js +51 -181
- package/lib/cjs/entities/vaultV2/forceWithdrawQuote.d.ts +25 -0
- package/lib/cjs/entities/vaultV2/forceWithdrawQuote.js +189 -0
- package/lib/cjs/entities/vaultV2/inKindRedeemQuote.d.ts +28 -0
- package/lib/cjs/entities/vaultV2/inKindRedeemQuote.js +110 -0
- package/lib/cjs/entities/vaultV2/vaultV2.d.ts +8 -34
- package/lib/cjs/entities/vaultV2/vaultV2.js +62 -429
- package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +2 -3
- package/lib/cjs/entities/vaultV2BlueReallocationData.js +346 -234
- package/lib/cjs/errors.d.ts +4 -4
- package/lib/cjs/errors.js +6 -7
- package/lib/cjs/fetch.d.ts +2 -2
- package/lib/cjs/fetch.js +1 -3
- package/lib/cjs/helpers/deadShares.js +34 -19
- package/lib/cjs/helpers/encodeMidnightCalldata.js +4 -2
- package/lib/cjs/helpers/metadata.js +12 -6
- package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +10 -5
- package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +6 -3
- package/lib/cjs/helpers/utilization.js +10 -5
- package/lib/cjs/helpers/validate.js +12 -6
- package/lib/cjs/helpers/validateMidnightBounds.js +2 -1
- package/lib/cjs/helpers/validateMidnightCollateralBatch.js +2 -1
- package/lib/cjs/helpers/validateMidnightPublication.js +4 -2
- package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +44 -22
- package/lib/cjs/helpers/validatePositiveInput.js +2 -1
- package/lib/cjs/helpers/validateTakeableOffers.js +2 -1
- package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +14 -7
- package/lib/cjs/index.d.ts +2 -2
- package/lib/cjs/index.js +10 -1
- package/lib/cjs/midnight/errors.d.ts +1 -2
- package/lib/cjs/midnight/errors.js +4 -5
- package/lib/cjs/transactionPlan/approval.js +12 -1
- package/lib/cjs/transactionPlan/deposit.d.ts +22 -0
- package/lib/cjs/transactionPlan/deposit.js +139 -0
- package/lib/cjs/transactionPlan/error.d.ts +10 -8
- package/lib/cjs/transactionPlan/error.js +10 -8
- package/lib/cjs/transactionPlan/getTokenPermit.js +2 -1
- package/lib/cjs/transactionPlan/index.d.ts +18 -0
- package/lib/cjs/transactionPlan/index.js +23 -5
- package/lib/cjs/transactionPlan/intent.d.ts +3 -3
- package/lib/cjs/transactionPlan/intent.js +14 -7
- package/lib/cjs/transactionPlan/permit.d.ts +1 -1
- package/lib/cjs/transactionPlan/permit.js +86 -20
- package/lib/cjs/transactionPlan/plan.d.ts +16 -6
- package/lib/cjs/transactionPlan/plan.js +72 -22
- package/lib/cjs/transactionPlan/redeem.d.ts +18 -0
- package/lib/cjs/transactionPlan/redeem.js +63 -0
- package/lib/cjs/transactionPlan/requirements.d.ts +4 -3
- package/lib/cjs/transactionPlan/requirements.js +12 -6
- package/lib/cjs/transactionPlan/serde.d.ts +2 -2
- package/lib/cjs/transactionPlan/serde.js +41 -15
- package/lib/cjs/transactionPlan/shareSpending.d.ts +18 -0
- package/lib/cjs/transactionPlan/shareSpending.js +50 -0
- package/lib/cjs/transactionPlan/types.d.ts +117 -11
- package/lib/cjs/transactionPlan/validateActions.js +11 -1
- package/lib/cjs/transactionPlan/validation.js +6 -3
- package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +93 -0
- package/lib/cjs/transactionPlan/vaultv1/deposit.js +94 -0
- package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +96 -0
- package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +203 -0
- package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +94 -0
- package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +217 -0
- package/lib/cjs/transactionPlan/vaultv1/redeem.d.ts +69 -0
- package/lib/cjs/transactionPlan/vaultv1/redeem.js +78 -0
- package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +77 -0
- package/lib/cjs/transactionPlan/vaultv1/withdraw.js +88 -0
- package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +14 -31
- package/lib/cjs/transactionPlan/vaultv2/deposit.js +15 -141
- package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +74 -0
- package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +155 -0
- package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +98 -0
- package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +206 -0
- package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +113 -0
- package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +206 -0
- package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +84 -0
- package/lib/cjs/transactionPlan/vaultv2/redeem.js +86 -0
- package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +14 -27
- package/lib/cjs/transactionPlan/vaultv2/withdraw.js +17 -124
- package/lib/cjs/transactionPlan/version.js +2 -1
- package/lib/cjs/transactionPlan/withdraw.d.ts +18 -0
- package/lib/cjs/transactionPlan/withdraw.js +94 -0
- package/lib/cjs/types/action.js +16 -8
- package/lib/cjs/types/error.d.ts +8 -1
- package/lib/cjs/types/error.js +10 -1
- package/lib/cjs/utils.d.ts +2 -2
- package/lib/cjs/utils.js +2 -4
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/esm/abis.d.ts +1 -1
- package/lib/esm/abis.js +1 -1
- package/lib/esm/actions/blue/common.js +4 -2
- package/lib/esm/actions/blue/withdrawBuyCallback.js +2 -1
- package/lib/esm/actions/bundles/common.js +20 -14
- package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -1
- package/lib/esm/actions/midnight/cancelOffers.js +2 -1
- package/lib/esm/actions/midnight/supplyCollateralBatch.js +4 -2
- package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +2 -1
- package/lib/esm/actions/midnight/takeBorrow.js +2 -1
- package/lib/esm/actions/midnight/takeLend.js +2 -1
- package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +2 -1
- package/lib/esm/actions/midnight/takeWithdraw.js +2 -1
- package/lib/esm/actions/midnight/withdrawCollateralBatch.js +4 -2
- package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +4 -13
- package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +2 -1
- package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +2 -1
- package/lib/esm/actions/vaultV1/inKindRedeem.js +6 -3
- package/lib/esm/actions/vaultV1/migrateToV2.js +1 -1
- package/lib/esm/actions/vaultV2/forceWithdraw.js +4 -2
- package/lib/esm/actions/vaultV2/inKindRedeem.js +4 -2
- package/lib/esm/blue/abis.d.ts +1 -1
- package/lib/esm/blue/abis.js +1 -1
- package/lib/esm/blue/entities.d.ts +4 -4
- package/lib/esm/blue/entities.js +2 -2
- package/lib/esm/blue/errors.d.ts +2 -2
- package/lib/esm/blue/errors.js +2 -2
- package/lib/esm/blue/fetch.d.ts +2 -2
- package/lib/esm/blue/fetch.js +2 -2
- package/lib/esm/blue/utils.d.ts +1 -1
- package/lib/esm/blue/utils.js +1 -1
- package/lib/esm/entities/blue/blue.js +8 -4
- package/lib/esm/entities/index.d.ts +4 -4
- package/lib/esm/entities/index.js +2 -2
- package/lib/esm/entities/midnight/deadline.js +2 -1
- package/lib/esm/entities/midnight/midnight.js +14 -7
- package/lib/esm/entities/midnight/publication.js +73 -44
- package/lib/esm/entities/requirements/assertContractCode.js +4 -2
- package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +10 -14
- package/lib/esm/entities/requirements/getErc2612Permit.js +10 -5
- package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -0
- package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +7 -1
- package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.d.ts +21 -0
- package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.js +108 -0
- package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.d.ts +20 -0
- package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.js +73 -0
- package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.d.ts +21 -0
- package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.js +90 -0
- package/lib/esm/entities/vaultV1/inKindRedeemQuote.d.ts +25 -0
- package/lib/esm/entities/vaultV1/inKindRedeemQuote.js +82 -0
- package/lib/esm/entities/vaultV1/migrateToV2Quote.d.ts +20 -0
- package/lib/esm/entities/vaultV1/migrateToV2Quote.js +34 -0
- package/lib/esm/entities/vaultV1/vaultV1.js +57 -187
- package/lib/esm/entities/vaultV2/forceWithdrawQuote.d.ts +25 -0
- package/lib/esm/entities/vaultV2/forceWithdrawQuote.js +186 -0
- package/lib/esm/entities/vaultV2/inKindRedeemQuote.d.ts +28 -0
- package/lib/esm/entities/vaultV2/inKindRedeemQuote.js +107 -0
- package/lib/esm/entities/vaultV2/vaultV2.d.ts +8 -34
- package/lib/esm/entities/vaultV2/vaultV2.js +70 -437
- package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +2 -3
- package/lib/esm/entities/vaultV2BlueReallocationData.js +346 -234
- package/lib/esm/errors.d.ts +4 -4
- package/lib/esm/errors.js +4 -4
- package/lib/esm/fetch.d.ts +2 -2
- package/lib/esm/fetch.js +2 -2
- package/lib/esm/helpers/deadShares.js +35 -20
- package/lib/esm/helpers/encodeMidnightCalldata.js +4 -2
- package/lib/esm/helpers/metadata.js +12 -6
- package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +10 -5
- package/lib/esm/helpers/previewVaultV2InKindRedeem.js +6 -3
- package/lib/esm/helpers/utilization.js +10 -5
- package/lib/esm/helpers/validate.js +12 -6
- package/lib/esm/helpers/validateMidnightBounds.js +2 -1
- package/lib/esm/helpers/validateMidnightCollateralBatch.js +2 -1
- package/lib/esm/helpers/validateMidnightPublication.js +4 -2
- package/lib/esm/helpers/validateMidnightTakeFeasibility.js +44 -22
- package/lib/esm/helpers/validatePositiveInput.js +2 -1
- package/lib/esm/helpers/validateTakeableOffers.js +2 -1
- package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +14 -7
- package/lib/esm/index.d.ts +2 -2
- package/lib/esm/index.js +1 -1
- package/lib/esm/midnight/errors.d.ts +1 -2
- package/lib/esm/midnight/errors.js +1 -2
- package/lib/esm/transactionPlan/approval.js +13 -2
- package/lib/esm/transactionPlan/deposit.d.ts +22 -0
- package/lib/esm/transactionPlan/deposit.js +135 -0
- package/lib/esm/transactionPlan/error.d.ts +10 -8
- package/lib/esm/transactionPlan/error.js +10 -8
- package/lib/esm/transactionPlan/getTokenPermit.js +2 -1
- package/lib/esm/transactionPlan/index.d.ts +18 -0
- package/lib/esm/transactionPlan/index.js +9 -0
- package/lib/esm/transactionPlan/intent.d.ts +3 -3
- package/lib/esm/transactionPlan/intent.js +14 -7
- package/lib/esm/transactionPlan/permit.d.ts +1 -1
- package/lib/esm/transactionPlan/permit.js +86 -20
- package/lib/esm/transactionPlan/plan.d.ts +16 -6
- package/lib/esm/transactionPlan/plan.js +68 -18
- package/lib/esm/transactionPlan/redeem.d.ts +18 -0
- package/lib/esm/transactionPlan/redeem.js +59 -0
- package/lib/esm/transactionPlan/requirements.d.ts +4 -3
- package/lib/esm/transactionPlan/requirements.js +12 -6
- package/lib/esm/transactionPlan/serde.d.ts +2 -2
- package/lib/esm/transactionPlan/serde.js +41 -15
- package/lib/esm/transactionPlan/shareSpending.d.ts +18 -0
- package/lib/esm/transactionPlan/shareSpending.js +47 -0
- package/lib/esm/transactionPlan/types.d.ts +117 -11
- package/lib/esm/transactionPlan/validateActions.js +11 -1
- package/lib/esm/transactionPlan/validation.js +6 -3
- package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +93 -0
- package/lib/esm/transactionPlan/vaultv1/deposit.js +90 -0
- package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +96 -0
- package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +198 -0
- package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +94 -0
- package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +212 -0
- package/lib/esm/transactionPlan/vaultv1/redeem.d.ts +69 -0
- package/lib/esm/transactionPlan/vaultv1/redeem.js +74 -0
- package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +77 -0
- package/lib/esm/transactionPlan/vaultv1/withdraw.js +84 -0
- package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +14 -31
- package/lib/esm/transactionPlan/vaultv2/deposit.js +17 -142
- package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +74 -0
- package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +150 -0
- package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +98 -0
- package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +201 -0
- package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +113 -0
- package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +201 -0
- package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +84 -0
- package/lib/esm/transactionPlan/vaultv2/redeem.js +82 -0
- package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +14 -27
- package/lib/esm/transactionPlan/vaultv2/withdraw.js +19 -125
- package/lib/esm/transactionPlan/version.js +2 -1
- package/lib/esm/transactionPlan/withdraw.d.ts +18 -0
- package/lib/esm/transactionPlan/withdraw.js +90 -0
- package/lib/esm/types/action.js +16 -8
- package/lib/esm/types/error.d.ts +8 -1
- package/lib/esm/types/error.js +10 -1
- package/lib/esm/utils.d.ts +2 -2
- package/lib/esm/utils.js +2 -2
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/package.json +15 -15
|
@@ -14,8 +14,9 @@ const createCapReserveState = (markets) => ({
|
|
|
14
14
|
});
|
|
15
15
|
const cloneCapReserveState = (state) => {
|
|
16
16
|
const touchedPairs = new Map();
|
|
17
|
-
for (const [vault, pairs] of state.touchedPairs)
|
|
17
|
+
for (const [vault, pairs] of state.touchedPairs) {
|
|
18
18
|
touchedPairs.set(vault, new Map(pairs));
|
|
19
|
+
}
|
|
19
20
|
return {
|
|
20
21
|
initialMarkets: { ...state.initialMarkets },
|
|
21
22
|
marketAccruals: new Map(state.marketAccruals),
|
|
@@ -37,8 +38,9 @@ const createSimulationContext = () => ({
|
|
|
37
38
|
* @internal
|
|
38
39
|
*/
|
|
39
40
|
const findAddressKey = (record, address) => {
|
|
40
|
-
if (Object.hasOwn(record, address))
|
|
41
|
+
if (Object.hasOwn(record, address)) {
|
|
41
42
|
return address;
|
|
43
|
+
}
|
|
42
44
|
return Object.keys(record).find((key) => isAddressEqual(key, address));
|
|
43
45
|
};
|
|
44
46
|
/**
|
|
@@ -54,22 +56,25 @@ const findAddressKey = (record, address) => {
|
|
|
54
56
|
const getAdapterIds = (cache, adapter, market) => {
|
|
55
57
|
const key = `${adapter.address}:${market.id}`;
|
|
56
58
|
const cached = cache.get(key);
|
|
57
|
-
if (cached != null)
|
|
59
|
+
if (cached != null) {
|
|
58
60
|
return cached;
|
|
61
|
+
}
|
|
59
62
|
const ids = adapter.ids(market.params);
|
|
60
63
|
cache.set(key, ids);
|
|
61
64
|
return ids;
|
|
62
65
|
};
|
|
63
66
|
const resolveMaxPenalty = (value) => {
|
|
64
67
|
const penalty = value ?? DEFAULT_MAX_REALLOCATION_PENALTY;
|
|
65
|
-
if (penalty < 0n)
|
|
68
|
+
if (penalty < 0n) {
|
|
66
69
|
throw new NegativeInputError("maxPenalty", penalty);
|
|
67
|
-
|
|
70
|
+
}
|
|
71
|
+
if (penalty > MAX_REALLOCATION_PENALTY) {
|
|
68
72
|
throw new InputExceedsMaxError({
|
|
69
73
|
field: "maxPenalty",
|
|
70
74
|
value: penalty,
|
|
71
75
|
max: MAX_REALLOCATION_PENALTY,
|
|
72
76
|
});
|
|
77
|
+
}
|
|
73
78
|
return penalty;
|
|
74
79
|
};
|
|
75
80
|
const getCanonicalMarket = (markets, market) => (markets[market.id] ??= new Market({ ...market }));
|
|
@@ -87,14 +92,12 @@ const cloneAccrualVault = (vault, markets) => new AccrualVault({
|
|
|
87
92
|
position: clonePosition(position, markets),
|
|
88
93
|
})));
|
|
89
94
|
const cloneAdapter = (adapter, markets) => {
|
|
90
|
-
if (adapter.type === "VaultV2MidnightAdapter")
|
|
91
|
-
return adapter;
|
|
92
95
|
const base = {
|
|
93
96
|
address: adapter.address,
|
|
94
97
|
parentVault: adapter.parentVault,
|
|
95
98
|
skimRecipient: adapter.skimRecipient,
|
|
96
99
|
};
|
|
97
|
-
if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)
|
|
100
|
+
if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2) {
|
|
98
101
|
return new AccrualVaultV2MorphoMarketV1AdapterV2({
|
|
99
102
|
...base,
|
|
100
103
|
marketIds: [...adapter.marketIds],
|
|
@@ -104,14 +107,17 @@ const cloneAdapter = (adapter, markets) => {
|
|
|
104
107
|
// V2 adapters can retain the canonical instance directly, so every
|
|
105
108
|
// adapter observes the same global Morpho market state.
|
|
106
109
|
adapter.markets.map((market) => getCanonicalMarket(markets, market)));
|
|
107
|
-
|
|
110
|
+
}
|
|
111
|
+
if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter) {
|
|
108
112
|
return new AccrualVaultV2MorphoMarketV1Adapter({ ...base, marketParamsList: [...adapter.marketParamsList] }, adapter.positions.map((position) => clonePosition(position, markets)));
|
|
109
|
-
|
|
113
|
+
}
|
|
114
|
+
if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter) {
|
|
110
115
|
return new AccrualVaultV2MorphoVaultV1Adapter({
|
|
111
116
|
...base,
|
|
112
117
|
morphoVaultV1: adapter.morphoVaultV1,
|
|
113
118
|
parentAllocation: adapter.parentAllocation,
|
|
114
119
|
}, cloneAccrualVault(adapter.accrualVaultV1, markets), adapter.shares);
|
|
120
|
+
}
|
|
115
121
|
throw new UnsupportedVaultV2AdapterError(adapter.address);
|
|
116
122
|
};
|
|
117
123
|
const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
|
|
@@ -137,8 +143,7 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
|
|
|
137
143
|
/**
|
|
138
144
|
* Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
|
|
139
145
|
*
|
|
140
|
-
* Constructor inputs are cloned
|
|
141
|
-
* shared by reference. Every simulated reallocation returns a new
|
|
146
|
+
* Constructor inputs are cloned. Every simulated reallocation returns a new
|
|
142
147
|
* instance. Planning keeps the transaction-scoped `firstTotalAssets`
|
|
143
148
|
* denominator outside the durable snapshot while applying reallocations in
|
|
144
149
|
* contract order. Penalty donations update simulated vault accounting but are
|
|
@@ -269,7 +274,7 @@ export class VaultV2BlueReallocationData {
|
|
|
269
274
|
/**
|
|
270
275
|
* Clones the complete simulation snapshot.
|
|
271
276
|
*
|
|
272
|
-
* @returns A deep clone of this simulation state
|
|
277
|
+
* @returns A deep clone of this simulation state.
|
|
273
278
|
* @example
|
|
274
279
|
* ```ts
|
|
275
280
|
* import { markets } from "@morpho-org/morpho-test";
|
|
@@ -325,8 +330,9 @@ export class VaultV2BlueReallocationData {
|
|
|
325
330
|
*/
|
|
326
331
|
getMarket(marketId) {
|
|
327
332
|
const market = this.mutableMarkets[marketId];
|
|
328
|
-
if (market == null)
|
|
333
|
+
if (market == null) {
|
|
329
334
|
throw new UnknownReallocationMarketError(marketId);
|
|
335
|
+
}
|
|
330
336
|
return market;
|
|
331
337
|
}
|
|
332
338
|
/**
|
|
@@ -363,8 +369,9 @@ export class VaultV2BlueReallocationData {
|
|
|
363
369
|
getMutableVault(vault) {
|
|
364
370
|
const key = findAddressKey(this.mutableVaults, vault);
|
|
365
371
|
const data = key == null ? undefined : this.mutableVaults[key];
|
|
366
|
-
if (data == null)
|
|
372
|
+
if (data == null) {
|
|
367
373
|
throw new UnknownReallocationVaultError(vault);
|
|
374
|
+
}
|
|
368
375
|
return data;
|
|
369
376
|
}
|
|
370
377
|
/**
|
|
@@ -403,8 +410,9 @@ export class VaultV2BlueReallocationData {
|
|
|
403
410
|
getAllocation(vault, id) {
|
|
404
411
|
const key = findAddressKey(this.allocations, vault);
|
|
405
412
|
const allocation = key == null ? undefined : this.allocations[key]?.[id];
|
|
406
|
-
if (allocation == null)
|
|
413
|
+
if (allocation == null) {
|
|
407
414
|
throw new UnknownReallocationAllocationError(vault, id);
|
|
415
|
+
}
|
|
408
416
|
return allocation;
|
|
409
417
|
}
|
|
410
418
|
/**
|
|
@@ -438,8 +446,9 @@ export class VaultV2BlueReallocationData {
|
|
|
438
446
|
*/
|
|
439
447
|
getPublicAllocatorConfig(vault) {
|
|
440
448
|
const config = this.getOptionalPublicAllocatorConfig(vault);
|
|
441
|
-
if (config == null)
|
|
449
|
+
if (config == null) {
|
|
442
450
|
throw new UnknownReallocationPublicAllocatorConfigError(vault);
|
|
451
|
+
}
|
|
443
452
|
return config;
|
|
444
453
|
}
|
|
445
454
|
/**
|
|
@@ -451,8 +460,9 @@ export class VaultV2BlueReallocationData {
|
|
|
451
460
|
*/
|
|
452
461
|
getOptionalPublicAllocatorConfig(vault) {
|
|
453
462
|
const key = findAddressKey(this.publicAllocatorConfigs, vault);
|
|
454
|
-
if (key == null)
|
|
463
|
+
if (key == null) {
|
|
455
464
|
throw new UnknownReallocationPublicAllocatorConfigError(vault);
|
|
465
|
+
}
|
|
456
466
|
return this.publicAllocatorConfigs[key];
|
|
457
467
|
}
|
|
458
468
|
/**
|
|
@@ -485,8 +495,9 @@ export class VaultV2BlueReallocationData {
|
|
|
485
495
|
getActiveAdapters(vault) {
|
|
486
496
|
const key = findAddressKey(this.activeAdapters, vault);
|
|
487
497
|
const adapters = key == null ? undefined : this.activeAdapters[key];
|
|
488
|
-
if (adapters == null)
|
|
498
|
+
if (adapters == null) {
|
|
489
499
|
throw new UnknownReallocationActiveAdaptersError(vault);
|
|
500
|
+
}
|
|
490
501
|
return adapters;
|
|
491
502
|
}
|
|
492
503
|
/**
|
|
@@ -530,8 +541,9 @@ export class VaultV2BlueReallocationData {
|
|
|
530
541
|
const config = key == null
|
|
531
542
|
? undefined
|
|
532
543
|
: this.marketPublicAllocatorConfigs[key]?.[adapterMarketCapId];
|
|
533
|
-
if (config == null)
|
|
544
|
+
if (config == null) {
|
|
534
545
|
throw new UnknownReallocationMarketPublicAllocatorConfigError(vault, adapterMarketCapId);
|
|
546
|
+
}
|
|
535
547
|
return config;
|
|
536
548
|
}
|
|
537
549
|
/**
|
|
@@ -570,8 +582,9 @@ export class VaultV2BlueReallocationData {
|
|
|
570
582
|
getMutableAdapter(vault, adapter) {
|
|
571
583
|
const data = this.getMutableVault(vault).accrualAdapters.find((candidate) => candidate instanceof AccrualVaultV2MorphoMarketV1AdapterV2 &&
|
|
572
584
|
isAddressEqual(candidate.address, adapter));
|
|
573
|
-
if (data == null)
|
|
585
|
+
if (data == null) {
|
|
574
586
|
throw new UnknownReallocationAdapterError(vault, adapter);
|
|
587
|
+
}
|
|
575
588
|
return data;
|
|
576
589
|
}
|
|
577
590
|
/**
|
|
@@ -697,8 +710,9 @@ export class VaultV2BlueReallocationData {
|
|
|
697
710
|
* ```
|
|
698
711
|
*/
|
|
699
712
|
computeVaultV2BlueReallocations(marketId, options = {}) {
|
|
700
|
-
if (options.enabled === false)
|
|
713
|
+
if (options.enabled === false) {
|
|
701
714
|
return { reallocations: [], data: this };
|
|
715
|
+
}
|
|
702
716
|
const maxWithdrawalUtilization = resolveMaxWithdrawalUtilization(options.maxWithdrawalUtilization);
|
|
703
717
|
const maxPenalty = resolveMaxPenalty(options.maxPenalty);
|
|
704
718
|
const capAccrualBuffer = resolveCapAccrualBuffer(options.capAccrualBuffer);
|
|
@@ -799,7 +813,7 @@ export class VaultV2BlueReallocationData {
|
|
|
799
813
|
return { normalizedOptions, market, hasExplicitBlueBalance, blueBalance };
|
|
800
814
|
}
|
|
801
815
|
computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
|
|
802
|
-
if (options.enabled === false)
|
|
816
|
+
if (options.enabled === false) {
|
|
803
817
|
return {
|
|
804
818
|
reallocations: [],
|
|
805
819
|
data: this,
|
|
@@ -807,6 +821,7 @@ export class VaultV2BlueReallocationData {
|
|
|
807
821
|
allocatorCapBoundTargets: new Set(),
|
|
808
822
|
idleBoundVaults: new Set(),
|
|
809
823
|
};
|
|
824
|
+
}
|
|
810
825
|
this.getMarket(marketId);
|
|
811
826
|
const timestamp = options.timestamp == null
|
|
812
827
|
? this.getLatestSnapshotTimestamp()
|
|
@@ -828,56 +843,12 @@ export class VaultV2BlueReallocationData {
|
|
|
828
843
|
const idleBoundVaults = new Set();
|
|
829
844
|
const initialIdleAssets = new Map();
|
|
830
845
|
const idleTakenAssets = new Map();
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
|
|
838
|
-
if (touched != null)
|
|
839
|
-
return touched;
|
|
840
|
-
const shares = adapter.supplyShares[market.id] ?? 0n;
|
|
841
|
-
return {
|
|
842
|
-
key,
|
|
843
|
-
ids: getAdapterIds(adapterIdsCache, adapter, market),
|
|
844
|
-
reserve: (reserveState) => {
|
|
845
|
-
let reserve = reserveState.reserveByPairKey.get(key);
|
|
846
|
-
if (reserve == null) {
|
|
847
|
-
let accruals = reserveState.marketAccruals.get(market.id);
|
|
848
|
-
if (accruals == null) {
|
|
849
|
-
const initialMarket = reserveState.initialMarkets[market.id];
|
|
850
|
-
if (initialMarket == null)
|
|
851
|
-
throw new UnknownReallocationMarketError(market.id);
|
|
852
|
-
accruals = [
|
|
853
|
-
initialMarket.accrueInterest(timestamp),
|
|
854
|
-
initialMarket.accrueInterest(timestamp + capAccrualBuffer),
|
|
855
|
-
];
|
|
856
|
-
reserveState.marketAccruals.set(market.id, accruals);
|
|
857
|
-
}
|
|
858
|
-
const [atTimestamp, projected] = accruals;
|
|
859
|
-
reserve = MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
|
|
860
|
-
reserveState.reserveByPairKey.set(key, reserve);
|
|
861
|
-
}
|
|
862
|
-
return reserve;
|
|
863
|
-
},
|
|
864
|
-
};
|
|
865
|
-
};
|
|
866
|
-
// biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
|
|
867
|
-
const capReserve = (vault, id, candidatePairs) => {
|
|
868
|
-
let reserve = 0n;
|
|
869
|
-
const seen = new Set();
|
|
870
|
-
for (const pair of [
|
|
871
|
-
...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
|
|
872
|
-
...candidatePairs,
|
|
873
|
-
]) {
|
|
874
|
-
if (seen.has(pair.key) || !pair.ids.includes(id))
|
|
875
|
-
continue;
|
|
876
|
-
seen.add(pair.key);
|
|
877
|
-
reserve += pair.reserve(reserves);
|
|
878
|
-
}
|
|
879
|
-
return reserve;
|
|
880
|
-
};
|
|
846
|
+
const { getPair, capReserve } = createCapReserveResolvers({
|
|
847
|
+
reserves,
|
|
848
|
+
adapterIdsCache,
|
|
849
|
+
timestamp,
|
|
850
|
+
capAccrualBuffer,
|
|
851
|
+
});
|
|
881
852
|
while (remainingAssets == null || remainingAssets > 0n) {
|
|
882
853
|
const candidates = vaults
|
|
883
854
|
.map((vaultAddress) => {
|
|
@@ -901,28 +872,16 @@ export class VaultV2BlueReallocationData {
|
|
|
901
872
|
setMarkets: data.setMarkets.bind(data),
|
|
902
873
|
applyPublicReallocation: data.applyPublicReallocation.bind(data),
|
|
903
874
|
};
|
|
904
|
-
|
|
905
|
-
if (idleState == null)
|
|
906
|
-
return;
|
|
907
|
-
const { availableIdleAssets } = idleState;
|
|
908
|
-
const vaultAddressKey = vaultAddress.toLowerCase();
|
|
909
|
-
if (!initialIdleAssets.has(vaultAddressKey))
|
|
910
|
-
initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
|
|
911
|
-
let activeAdapters = activeAdaptersCache.get(vaultAddress);
|
|
912
|
-
if (activeAdapters == null) {
|
|
913
|
-
activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
|
|
914
|
-
activeAdaptersCache.set(vaultAddress, activeAdapters);
|
|
915
|
-
}
|
|
916
|
-
return planVaultCandidate({
|
|
875
|
+
return planCachedVaultCandidate({
|
|
917
876
|
...params,
|
|
918
|
-
|
|
919
|
-
|
|
877
|
+
initialIdleAssets,
|
|
878
|
+
activeAdaptersCache,
|
|
920
879
|
});
|
|
921
880
|
})
|
|
922
881
|
.filter((candidate) => candidate != null)
|
|
923
882
|
.sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"));
|
|
924
883
|
const largest = candidates[0];
|
|
925
|
-
if (largest == null)
|
|
884
|
+
if (largest == null) {
|
|
926
885
|
return {
|
|
927
886
|
reallocations,
|
|
928
887
|
data,
|
|
@@ -930,6 +889,7 @@ export class VaultV2BlueReallocationData {
|
|
|
930
889
|
allocatorCapBoundTargets,
|
|
931
890
|
idleBoundVaults,
|
|
932
891
|
};
|
|
892
|
+
}
|
|
933
893
|
const updates = getAcceptedCandidateUpdates({
|
|
934
894
|
candidate: largest,
|
|
935
895
|
idleTakenAssets,
|
|
@@ -953,8 +913,9 @@ export class VaultV2BlueReallocationData {
|
|
|
953
913
|
});
|
|
954
914
|
data = transition.data;
|
|
955
915
|
simulationContext = transition.context;
|
|
956
|
-
if (remainingAssets != null)
|
|
916
|
+
if (remainingAssets != null) {
|
|
957
917
|
remainingAssets -= acceptedReallocation.assets;
|
|
918
|
+
}
|
|
958
919
|
}
|
|
959
920
|
return {
|
|
960
921
|
reallocations,
|
|
@@ -1010,8 +971,9 @@ export class VaultV2BlueReallocationData {
|
|
|
1010
971
|
* ```
|
|
1011
972
|
*/
|
|
1012
973
|
getPublicReallocationLiquidity(marketId, options) {
|
|
1013
|
-
if (options?.enabled === false)
|
|
974
|
+
if (options?.enabled === false) {
|
|
1014
975
|
return 0n;
|
|
976
|
+
}
|
|
1015
977
|
const capAccrualBuffer = resolveCapAccrualBuffer(options?.capAccrualBuffer);
|
|
1016
978
|
const maxPenalty = resolveMaxPenalty(options?.maxPenalty);
|
|
1017
979
|
return this.clone()
|
|
@@ -1080,8 +1042,9 @@ export class VaultV2BlueReallocationData {
|
|
|
1080
1042
|
: BigInt(options.timestamp);
|
|
1081
1043
|
const market = this.getMarket(marketId).accrueInterest(timestamp);
|
|
1082
1044
|
if (options?.enabled === false ||
|
|
1083
|
-
DEFAULT_SUPPLY_TARGET_UTILIZATION > utilization)
|
|
1045
|
+
DEFAULT_SUPPLY_TARGET_UTILIZATION > utilization) {
|
|
1084
1046
|
return market.getBorrowToUtilization(utilization);
|
|
1047
|
+
}
|
|
1085
1048
|
const availableLiquidity = this.clone()
|
|
1086
1049
|
.computeVaultV2BlueReallocationsAtUtilizationInPlace({
|
|
1087
1050
|
context: createSimulationContext(),
|
|
@@ -1104,12 +1067,14 @@ export class VaultV2BlueReallocationData {
|
|
|
1104
1067
|
getLatestSnapshotTimestamp() {
|
|
1105
1068
|
let timestamp = this.timestamp ?? 0n;
|
|
1106
1069
|
for (const market of Object.values(this.markets)) {
|
|
1107
|
-
if (market != null)
|
|
1070
|
+
if (market != null) {
|
|
1108
1071
|
timestamp = MathLib.max(timestamp, market.lastUpdate);
|
|
1072
|
+
}
|
|
1109
1073
|
}
|
|
1110
1074
|
for (const vault of Object.values(this.vaults)) {
|
|
1111
|
-
if (vault != null)
|
|
1075
|
+
if (vault != null) {
|
|
1112
1076
|
timestamp = MathLib.max(timestamp, vault.lastUpdate);
|
|
1077
|
+
}
|
|
1113
1078
|
}
|
|
1114
1079
|
return timestamp;
|
|
1115
1080
|
}
|
|
@@ -1165,8 +1130,9 @@ export class VaultV2BlueReallocationData {
|
|
|
1165
1130
|
});
|
|
1166
1131
|
}
|
|
1167
1132
|
// Idle allocations also credit the instance's explicit Blue liquidity balance.
|
|
1168
|
-
if (reallocation.from.type === "idle")
|
|
1133
|
+
if (reallocation.from.type === "idle") {
|
|
1169
1134
|
data.creditIdleReallocationBalance(reallocation, targetMarket);
|
|
1135
|
+
}
|
|
1170
1136
|
if (firstTotalAssets == null) {
|
|
1171
1137
|
const firstAllocation = data.accrueReallocationFirstAllocation({
|
|
1172
1138
|
vault,
|
|
@@ -1201,10 +1167,12 @@ export class VaultV2BlueReallocationData {
|
|
|
1201
1167
|
const supply = currentTargetMarket.supply(reallocation.assets, 0n, timestamp);
|
|
1202
1168
|
const targetSupplyShares = (targetAdapter.supplyShares[targetMarket.id] ?? 0n) + supply.shares;
|
|
1203
1169
|
targetAdapter.supplyShares[targetMarket.id] = targetSupplyShares;
|
|
1204
|
-
if (!targetAdapter.marketIds.includes(targetMarket.id))
|
|
1170
|
+
if (!targetAdapter.marketIds.includes(targetMarket.id)) {
|
|
1205
1171
|
targetAdapter.marketIds.push(targetMarket.id);
|
|
1206
|
-
|
|
1172
|
+
}
|
|
1173
|
+
if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id)) {
|
|
1207
1174
|
targetAdapter.markets.push(supply.market);
|
|
1175
|
+
}
|
|
1208
1176
|
this.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
|
|
1209
1177
|
const simulatedChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
|
|
1210
1178
|
// The adapter's rounded expected-assets delta can differ by one wei at inclusion,
|
|
@@ -1213,8 +1181,9 @@ export class VaultV2BlueReallocationData {
|
|
|
1213
1181
|
for (const id of targetIds) {
|
|
1214
1182
|
const allocation = this.getAllocation(reallocation.vault, id);
|
|
1215
1183
|
const allocations = this.mutableAllocations[allocationsKey];
|
|
1216
|
-
if (allocations == null)
|
|
1184
|
+
if (allocations == null) {
|
|
1217
1185
|
throw new UnknownReallocationAllocationError(reallocation.vault, id);
|
|
1186
|
+
}
|
|
1218
1187
|
allocations[id] = {
|
|
1219
1188
|
...allocation,
|
|
1220
1189
|
allocation: allocation.allocation + targetChange,
|
|
@@ -1224,12 +1193,14 @@ export class VaultV2BlueReallocationData {
|
|
|
1224
1193
|
/** Credits shared Blue liquidity when an idle allocation enters the target market. @internal */
|
|
1225
1194
|
creditIdleReallocationBalance(reallocation, targetMarket) {
|
|
1226
1195
|
const blueBalanceKey = findAddressKey(this.mutableBlueBalances, targetMarket.params.loanToken);
|
|
1227
|
-
if (blueBalanceKey == null)
|
|
1196
|
+
if (blueBalanceKey == null) {
|
|
1228
1197
|
return;
|
|
1198
|
+
}
|
|
1229
1199
|
const blueBalance = this.mutableBlueBalances[blueBalanceKey];
|
|
1230
|
-
if (blueBalance != null)
|
|
1200
|
+
if (blueBalance != null) {
|
|
1231
1201
|
this.mutableBlueBalances[blueBalanceKey] =
|
|
1232
1202
|
blueBalance + reallocation.assets;
|
|
1203
|
+
}
|
|
1233
1204
|
}
|
|
1234
1205
|
/** Builds the isolated markets, adapter views and caps used by a transition probe. @internal */
|
|
1235
1206
|
cloneReallocationProbe({ reallocation, targetMarketId, adapterIdsCache, sourceVaultKey, sourceVault, sourceAllocationsKey, }) {
|
|
@@ -1244,10 +1215,12 @@ export class VaultV2BlueReallocationData {
|
|
|
1244
1215
|
const sourceMarket = this.getMarket(reallocation.from.marketParams.id);
|
|
1245
1216
|
probeMarkets[sourceMarket.id] = sourceMarket;
|
|
1246
1217
|
adapterKeysToClone.add(reallocation.from.adapter.toLowerCase());
|
|
1247
|
-
for (const key of getDependentProbeAdapterKeys(sourceVault, sourceMarket.id))
|
|
1218
|
+
for (const key of getDependentProbeAdapterKeys(sourceVault, sourceMarket.id)) {
|
|
1248
1219
|
adapterKeysToClone.add(key);
|
|
1249
|
-
|
|
1220
|
+
}
|
|
1221
|
+
for (const id of getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.from.adapter), sourceMarket)) {
|
|
1250
1222
|
allocationIdsToClone.add(id);
|
|
1223
|
+
}
|
|
1251
1224
|
}
|
|
1252
1225
|
const data = new VaultV2BlueReallocationData({
|
|
1253
1226
|
chainId: this.chainId,
|
|
@@ -1266,8 +1239,9 @@ export class VaultV2BlueReallocationData {
|
|
|
1266
1239
|
if (sourceAllocationsKey != null) {
|
|
1267
1240
|
const sourceAllocations = this.mutableAllocations[sourceAllocationsKey];
|
|
1268
1241
|
const allocations = {};
|
|
1269
|
-
for (const id of allocationIdsToClone)
|
|
1242
|
+
for (const id of allocationIdsToClone) {
|
|
1270
1243
|
allocations[id] = sourceAllocations?.[id];
|
|
1244
|
+
}
|
|
1271
1245
|
data.mutableAllocations[sourceAllocationsKey] = allocations;
|
|
1272
1246
|
}
|
|
1273
1247
|
return data;
|
|
@@ -1348,16 +1322,18 @@ export class VaultV2BlueReallocationData {
|
|
|
1348
1322
|
this.mutableMarkets[market.id] = market;
|
|
1349
1323
|
changedMarketIds.add(market.id);
|
|
1350
1324
|
}
|
|
1351
|
-
if (changedMarketIds.size === 0)
|
|
1325
|
+
if (changedMarketIds.size === 0) {
|
|
1352
1326
|
return;
|
|
1327
|
+
}
|
|
1353
1328
|
const adapters = collectAdaptersToRefresh(this.mutableVaults, adaptersToRefresh);
|
|
1354
1329
|
for (const adapter of adapters) {
|
|
1355
1330
|
const update = refreshAdapterMarkets(adapter, {
|
|
1356
1331
|
markets: this.mutableMarkets,
|
|
1357
1332
|
changedMarketIds,
|
|
1358
1333
|
});
|
|
1359
|
-
if (update != null)
|
|
1334
|
+
if (update != null) {
|
|
1360
1335
|
Object.assign(adapter, update);
|
|
1336
|
+
}
|
|
1361
1337
|
}
|
|
1362
1338
|
}
|
|
1363
1339
|
}
|
|
@@ -1369,39 +1345,46 @@ function collectAdaptersToRefresh(vaults, adaptersToRefresh) {
|
|
|
1369
1345
|
// AccrualPosition constructors copy their Market, so rebuild those adapter
|
|
1370
1346
|
// views as well as repointing V2 adapters whenever the canonical state moves.
|
|
1371
1347
|
for (const vault of Object.values(vaults)) {
|
|
1372
|
-
if (vault == null)
|
|
1348
|
+
if (vault == null) {
|
|
1373
1349
|
continue;
|
|
1374
|
-
|
|
1350
|
+
}
|
|
1351
|
+
for (const adapter of vault.accrualAdapters) {
|
|
1375
1352
|
adapters.add(adapter);
|
|
1376
|
-
|
|
1353
|
+
}
|
|
1354
|
+
if (vault.accrualLiquidityAdapter != null) {
|
|
1377
1355
|
adapters.add(vault.accrualLiquidityAdapter);
|
|
1356
|
+
}
|
|
1378
1357
|
}
|
|
1379
1358
|
}
|
|
1380
1359
|
else {
|
|
1381
|
-
for (const adapter of adaptersToRefresh)
|
|
1360
|
+
for (const adapter of adaptersToRefresh) {
|
|
1382
1361
|
adapters.add(adapter);
|
|
1362
|
+
}
|
|
1383
1363
|
}
|
|
1384
1364
|
return adapters;
|
|
1385
1365
|
}
|
|
1386
1366
|
/** Computes one adapter's dependent market views after a canonical state change. @internal */
|
|
1387
1367
|
function refreshAdapterMarkets(adapter, { markets, changedMarketIds, }) {
|
|
1388
1368
|
if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2) {
|
|
1389
|
-
if (!adapter.markets.some(({ id }) => changedMarketIds.has(id)))
|
|
1369
|
+
if (!adapter.markets.some(({ id }) => changedMarketIds.has(id))) {
|
|
1390
1370
|
return;
|
|
1371
|
+
}
|
|
1391
1372
|
return {
|
|
1392
1373
|
markets: adapter.markets.map((adapterMarket) => getCanonicalMarket(markets, adapterMarket)),
|
|
1393
1374
|
};
|
|
1394
1375
|
}
|
|
1395
1376
|
if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter) {
|
|
1396
|
-
if (!adapter.positions.some(({ marketId }) => changedMarketIds.has(marketId)))
|
|
1377
|
+
if (!adapter.positions.some(({ marketId }) => changedMarketIds.has(marketId))) {
|
|
1397
1378
|
return;
|
|
1379
|
+
}
|
|
1398
1380
|
return {
|
|
1399
1381
|
positions: adapter.positions.map((position) => clonePosition(position, markets)),
|
|
1400
1382
|
};
|
|
1401
1383
|
}
|
|
1402
1384
|
if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter) {
|
|
1403
|
-
if (![...adapter.accrualVaultV1.allocations.keys()].some((marketId) => changedMarketIds.has(marketId)))
|
|
1385
|
+
if (![...adapter.accrualVaultV1.allocations.keys()].some((marketId) => changedMarketIds.has(marketId))) {
|
|
1404
1386
|
return;
|
|
1387
|
+
}
|
|
1405
1388
|
return {
|
|
1406
1389
|
accrualVaultV1: cloneAccrualVault(adapter.accrualVaultV1, markets),
|
|
1407
1390
|
};
|
|
@@ -1443,14 +1426,17 @@ function cloneMarketAllocatorConfigurations(configs) {
|
|
|
1443
1426
|
/** Finds adapter views that a source-market transition must isolate for probing. @internal */
|
|
1444
1427
|
function getDependentProbeAdapterKeys(sourceVault, sourceMarketId) {
|
|
1445
1428
|
const keys = new Set();
|
|
1446
|
-
if (sourceVault == null)
|
|
1429
|
+
if (sourceVault == null) {
|
|
1447
1430
|
return keys;
|
|
1431
|
+
}
|
|
1448
1432
|
const adapters = new Set(sourceVault.accrualAdapters);
|
|
1449
|
-
if (sourceVault.accrualLiquidityAdapter != null)
|
|
1433
|
+
if (sourceVault.accrualLiquidityAdapter != null) {
|
|
1450
1434
|
adapters.add(sourceVault.accrualLiquidityAdapter);
|
|
1435
|
+
}
|
|
1451
1436
|
for (const adapter of adapters) {
|
|
1452
|
-
if (adapterReferencesMarket(adapter, sourceMarketId))
|
|
1437
|
+
if (adapterReferencesMarket(adapter, sourceMarketId)) {
|
|
1453
1438
|
keys.add(adapter.address.toLowerCase());
|
|
1439
|
+
}
|
|
1454
1440
|
}
|
|
1455
1441
|
return keys;
|
|
1456
1442
|
}
|
|
@@ -1469,9 +1455,10 @@ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, init
|
|
|
1469
1455
|
const idleBoundVaults = [];
|
|
1470
1456
|
const idleTakenEntries = [];
|
|
1471
1457
|
const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
|
|
1472
|
-
if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
|
|
1458
|
+
if (acceptedReallocation.assets >= acceptedAllocatorHeadroom) {
|
|
1473
1459
|
// BluePublicAllocator caps are per vault and target adapter.
|
|
1474
1460
|
allocatorCapBoundTargets.push(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
|
|
1461
|
+
}
|
|
1475
1462
|
if (acceptedReallocation.from.type === "idle") {
|
|
1476
1463
|
const vaultKey = acceptedReallocation.vault.toLowerCase();
|
|
1477
1464
|
const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
|
|
@@ -1479,8 +1466,9 @@ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, init
|
|
|
1479
1466
|
// Candidates always record this; a missing entry counts the vault as bound.
|
|
1480
1467
|
const initial = initialIdleAssets.get(vaultKey) ?? 0n;
|
|
1481
1468
|
if (taken >=
|
|
1482
|
-
MathLib.zeroFloorSub(initial, MathLib.wMulUp(initial, allocatorCapHeadroom)))
|
|
1469
|
+
MathLib.zeroFloorSub(initial, MathLib.wMulUp(initial, allocatorCapHeadroom))) {
|
|
1483
1470
|
idleBoundVaults.push(vaultKey);
|
|
1471
|
+
}
|
|
1484
1472
|
}
|
|
1485
1473
|
const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
|
|
1486
1474
|
const existingPairs = reserves.touchedPairs.get(touchedVaultKey);
|
|
@@ -1489,12 +1477,14 @@ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, init
|
|
|
1489
1477
|
? [[touchedVaultKey, touchedVaultPairs]]
|
|
1490
1478
|
: [];
|
|
1491
1479
|
const touchedPairEntries = [];
|
|
1492
|
-
if (!touchedVaultPairs.has(acceptedTargetPair.key))
|
|
1480
|
+
if (!touchedVaultPairs.has(acceptedTargetPair.key)) {
|
|
1493
1481
|
touchedPairEntries.push([acceptedTargetPair.key, acceptedTargetPair]);
|
|
1482
|
+
}
|
|
1494
1483
|
if (acceptedSourcePair != null &&
|
|
1495
1484
|
!touchedVaultPairs.has(acceptedSourcePair.key) &&
|
|
1496
|
-
acceptedSourcePair.key !== acceptedTargetPair.key)
|
|
1485
|
+
acceptedSourcePair.key !== acceptedTargetPair.key) {
|
|
1497
1486
|
touchedPairEntries.push([acceptedSourcePair.key, acceptedSourcePair]);
|
|
1487
|
+
}
|
|
1498
1488
|
return {
|
|
1499
1489
|
allocatorCapBoundTargets,
|
|
1500
1490
|
idleTakenAssets: idleTakenEntries,
|
|
@@ -1504,26 +1494,117 @@ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, init
|
|
|
1504
1494
|
touchedPairEntries,
|
|
1505
1495
|
};
|
|
1506
1496
|
}
|
|
1497
|
+
/**
|
|
1498
|
+
* Creates cap-reserve readers over the shared in-place planning caches.
|
|
1499
|
+
* Returned readers populate reserve caches as in the utilization pass.
|
|
1500
|
+
* @internal
|
|
1501
|
+
*/
|
|
1502
|
+
function createCapReserveResolvers({ reserves, adapterIdsCache, timestamp, capAccrualBuffer, }) {
|
|
1503
|
+
// Onchain, market interest is booked once at transaction start, on pre-plan
|
|
1504
|
+
// positions at pre-plan rates, and stays on touched positions' cap ids.
|
|
1505
|
+
// This reserve state is shared across every planner pass and leg of the plan.
|
|
1506
|
+
// biome-ignore lint/complexity/useMaxParams: a pair is identified by its vault, adapter, and market.
|
|
1507
|
+
const getPair = (vault, adapter, market) => {
|
|
1508
|
+
const key = `${vault}:${adapter.address}:${market.id}`.toLowerCase();
|
|
1509
|
+
const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
|
|
1510
|
+
if (touched != null) {
|
|
1511
|
+
return touched;
|
|
1512
|
+
}
|
|
1513
|
+
const shares = adapter.supplyShares[market.id] ?? 0n;
|
|
1514
|
+
return {
|
|
1515
|
+
key,
|
|
1516
|
+
ids: getAdapterIds(adapterIdsCache, adapter, market),
|
|
1517
|
+
reserve: (reserveState) => {
|
|
1518
|
+
let reserve = reserveState.reserveByPairKey.get(key);
|
|
1519
|
+
if (reserve == null) {
|
|
1520
|
+
let accruals = reserveState.marketAccruals.get(market.id);
|
|
1521
|
+
if (accruals == null) {
|
|
1522
|
+
const initialMarket = reserveState.initialMarkets[market.id];
|
|
1523
|
+
if (initialMarket == null) {
|
|
1524
|
+
throw new UnknownReallocationMarketError(market.id);
|
|
1525
|
+
}
|
|
1526
|
+
accruals = [
|
|
1527
|
+
initialMarket.accrueInterest(timestamp),
|
|
1528
|
+
initialMarket.accrueInterest(timestamp + capAccrualBuffer),
|
|
1529
|
+
];
|
|
1530
|
+
reserveState.marketAccruals.set(market.id, accruals);
|
|
1531
|
+
}
|
|
1532
|
+
const [atTimestamp, projected] = accruals;
|
|
1533
|
+
reserve = MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
|
|
1534
|
+
reserveState.reserveByPairKey.set(key, reserve);
|
|
1535
|
+
}
|
|
1536
|
+
return reserve;
|
|
1537
|
+
},
|
|
1538
|
+
};
|
|
1539
|
+
};
|
|
1540
|
+
// biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
|
|
1541
|
+
const capReserve = (vault, id, candidatePairs) => {
|
|
1542
|
+
let reserve = 0n;
|
|
1543
|
+
const seen = new Set();
|
|
1544
|
+
for (const pair of [
|
|
1545
|
+
...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
|
|
1546
|
+
...candidatePairs,
|
|
1547
|
+
]) {
|
|
1548
|
+
if (seen.has(pair.key) || !pair.ids.includes(id)) {
|
|
1549
|
+
continue;
|
|
1550
|
+
}
|
|
1551
|
+
seen.add(pair.key);
|
|
1552
|
+
reserve += pair.reserve(reserves);
|
|
1553
|
+
}
|
|
1554
|
+
return reserve;
|
|
1555
|
+
};
|
|
1556
|
+
return { getPair, capReserve };
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* Plans one vault candidate, caching its initial idle assets and active adapters in place.
|
|
1560
|
+
* @internal
|
|
1561
|
+
*/
|
|
1562
|
+
function planCachedVaultCandidate(params) {
|
|
1563
|
+
const { vaultAddress, data, initialIdleAssets, activeAdaptersCache } = params;
|
|
1564
|
+
const idleState = resolveVaultCandidateIdleState(params);
|
|
1565
|
+
if (idleState == null) {
|
|
1566
|
+
return;
|
|
1567
|
+
}
|
|
1568
|
+
const { availableIdleAssets } = idleState;
|
|
1569
|
+
const vaultAddressKey = vaultAddress.toLowerCase();
|
|
1570
|
+
if (!initialIdleAssets.has(vaultAddressKey)) {
|
|
1571
|
+
initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
|
|
1572
|
+
}
|
|
1573
|
+
let activeAdapters = activeAdaptersCache.get(vaultAddress);
|
|
1574
|
+
if (activeAdapters == null) {
|
|
1575
|
+
activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
|
|
1576
|
+
activeAdaptersCache.set(vaultAddress, activeAdapters);
|
|
1577
|
+
}
|
|
1578
|
+
return planVaultCandidate({
|
|
1579
|
+
...params,
|
|
1580
|
+
...idleState,
|
|
1581
|
+
activeAdapters,
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1507
1584
|
/** Resolves an eligible vault's idle balance before initializing candidate caches. @internal */
|
|
1508
1585
|
function resolveVaultCandidateIdleState(params) {
|
|
1509
1586
|
const { vaultAddress, data, marketId, penalty, options, simulationContext, getOptionalPublicAllocatorConfig, } = params;
|
|
1510
1587
|
const targetMarket = data.getMarket(marketId);
|
|
1511
1588
|
const publicAllocatorConfig = getOptionalPublicAllocatorConfig(vaultAddress);
|
|
1512
|
-
if (publicAllocatorConfig == null)
|
|
1589
|
+
if (publicAllocatorConfig == null) {
|
|
1513
1590
|
return;
|
|
1591
|
+
}
|
|
1514
1592
|
const vault = data.getVault(vaultAddress);
|
|
1515
1593
|
if (!isAddressEqual(publicAllocatorConfig.vault, vaultAddress) ||
|
|
1516
1594
|
publicAllocatorConfig.penalty >
|
|
1517
|
-
(options.maxPenalty ?? DEFAULT_MAX_REALLOCATION_PENALTY))
|
|
1595
|
+
(options.maxPenalty ?? DEFAULT_MAX_REALLOCATION_PENALTY)) {
|
|
1518
1596
|
return;
|
|
1519
|
-
|
|
1597
|
+
}
|
|
1598
|
+
if (penalty != null && publicAllocatorConfig.penalty !== penalty) {
|
|
1520
1599
|
return;
|
|
1600
|
+
}
|
|
1521
1601
|
const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
|
|
1522
1602
|
const donatedPenaltyAssets = donatedPenaltyAssetsKey == null
|
|
1523
1603
|
? 0n
|
|
1524
1604
|
: simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey];
|
|
1525
|
-
if (donatedPenaltyAssets == null)
|
|
1605
|
+
if (donatedPenaltyAssets == null) {
|
|
1526
1606
|
throw new UnknownDataError(`Missing donated penalty assets for "${vaultAddress}".`);
|
|
1607
|
+
}
|
|
1527
1608
|
// Exclude rounded penalty dust from idle candidates so one donation
|
|
1528
1609
|
// cannot replenish liquidity for another same-plan reallocation.
|
|
1529
1610
|
const availableIdleAssets = MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssets);
|
|
@@ -1537,12 +1618,17 @@ function resolveVaultCandidateIdleState(params) {
|
|
|
1537
1618
|
function planVaultCandidate(params) {
|
|
1538
1619
|
const { vault, targetMarket, publicAllocatorConfig, availableIdleAssets, activeAdapters, } = params;
|
|
1539
1620
|
const targetSupplyHeadroom = MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
|
|
1621
|
+
if (targetSupplyHeadroom === 0n ||
|
|
1622
|
+
targetMarket.toSupplyShares(1n, "Down") >
|
|
1623
|
+
MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyShares)) {
|
|
1624
|
+
return;
|
|
1625
|
+
}
|
|
1540
1626
|
const minimumSupply = targetMarket.supply(1n, 0n);
|
|
1541
1627
|
const rawCandidates = [];
|
|
1542
1628
|
// Missing nested allocator state means the snapshot is incomplete, so
|
|
1543
1629
|
// typed getter errors below must propagate. Only explicit zero caps or
|
|
1544
1630
|
// disabled permissions make an adapter ineligible.
|
|
1545
|
-
for (const adapter of vault.accrualAdapters)
|
|
1631
|
+
for (const adapter of vault.accrualAdapters) {
|
|
1546
1632
|
rawCandidates.push(...planTargetAdapterCandidates({
|
|
1547
1633
|
...params,
|
|
1548
1634
|
vault,
|
|
@@ -1554,6 +1640,7 @@ function planVaultCandidate(params) {
|
|
|
1554
1640
|
minimumSupply,
|
|
1555
1641
|
adapter,
|
|
1556
1642
|
}));
|
|
1643
|
+
}
|
|
1557
1644
|
const capCompatibleCandidates = [];
|
|
1558
1645
|
for (const candidate of rawCandidates) {
|
|
1559
1646
|
const compatible = fitCandidateCaps({
|
|
@@ -1561,8 +1648,9 @@ function planVaultCandidate(params) {
|
|
|
1561
1648
|
...candidate,
|
|
1562
1649
|
targetMarket,
|
|
1563
1650
|
});
|
|
1564
|
-
if (compatible != null)
|
|
1651
|
+
if (compatible != null) {
|
|
1565
1652
|
capCompatibleCandidates.push(compatible);
|
|
1653
|
+
}
|
|
1566
1654
|
}
|
|
1567
1655
|
return capCompatibleCandidates.sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"))[0];
|
|
1568
1656
|
}
|
|
@@ -1572,22 +1660,26 @@ function planVaultCandidate(params) {
|
|
|
1572
1660
|
* @internal
|
|
1573
1661
|
*/
|
|
1574
1662
|
function planTargetAdapterCandidates(params) {
|
|
1575
|
-
const { vaultAddress, data, marketId, adapterIdsCache, getPair, capReserve, reserves, allocatorCapHeadroom, vault, targetMarket, activeAdapters,
|
|
1663
|
+
const { vaultAddress, data, marketId, adapterIdsCache, getPair, capReserve, reserves, allocatorCapHeadroom, vault, targetMarket, activeAdapters, minimumSupply, adapter, } = params;
|
|
1576
1664
|
const rawCandidates = [];
|
|
1577
|
-
if (!(adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2))
|
|
1665
|
+
if (!(adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)) {
|
|
1578
1666
|
return [];
|
|
1579
|
-
|
|
1667
|
+
}
|
|
1668
|
+
if (!isAddressEqual(adapter.parentVault, vaultAddress)) {
|
|
1580
1669
|
return [];
|
|
1670
|
+
}
|
|
1581
1671
|
if (!isAddressEqual(targetMarket.params.loanToken, vault.asset) ||
|
|
1582
|
-
!isAddressEqual(targetMarket.params.irm, adapter.adaptiveCurveIrm))
|
|
1672
|
+
!isAddressEqual(targetMarket.params.irm, adapter.adaptiveCurveIrm)) {
|
|
1583
1673
|
return [];
|
|
1674
|
+
}
|
|
1584
1675
|
const targetPair = getPair(vaultAddress, adapter, targetMarket);
|
|
1585
1676
|
const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
|
|
1586
1677
|
const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
|
|
1587
1678
|
if (!isAddressEqual(marketPublicAllocatorConfig.vault, vaultAddress) ||
|
|
1588
1679
|
!isAddressEqual(marketPublicAllocatorConfig.adapter, adapter.address) ||
|
|
1589
|
-
!activeAdapters.has(adapter.address.toLowerCase()))
|
|
1680
|
+
!activeAdapters.has(adapter.address.toLowerCase())) {
|
|
1590
1681
|
return [];
|
|
1682
|
+
}
|
|
1591
1683
|
const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
|
|
1592
1684
|
const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
|
|
1593
1685
|
const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
|
|
@@ -1596,8 +1688,9 @@ function planTargetAdapterCandidates(params) {
|
|
|
1596
1688
|
collateralCapAllocation,
|
|
1597
1689
|
adapterMarketCapAllocation,
|
|
1598
1690
|
];
|
|
1599
|
-
if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n))
|
|
1691
|
+
if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n)) {
|
|
1600
1692
|
return [];
|
|
1693
|
+
}
|
|
1601
1694
|
const adapterShares = adapter.supplyShares[marketId] ?? 0n;
|
|
1602
1695
|
const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
|
|
1603
1696
|
const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
|
|
@@ -1616,12 +1709,11 @@ function planTargetAdapterCandidates(params) {
|
|
|
1616
1709
|
})
|
|
1617
1710
|
.map(({ id }) => id);
|
|
1618
1711
|
// MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
|
|
1619
|
-
if (
|
|
1620
|
-
allocatorHeadroom === 0n ||
|
|
1712
|
+
if (allocatorHeadroom === 0n ||
|
|
1621
1713
|
minimumSupply.shares < minimumSupply.assets ||
|
|
1622
|
-
|
|
1623
|
-
blockedTargetIds.includes(adapterMarketCapId))
|
|
1714
|
+
blockedTargetIds.includes(adapterMarketCapId)) {
|
|
1624
1715
|
return [];
|
|
1716
|
+
}
|
|
1625
1717
|
const sourceParams = {
|
|
1626
1718
|
...params,
|
|
1627
1719
|
adapter,
|
|
@@ -1630,8 +1722,9 @@ function planTargetAdapterCandidates(params) {
|
|
|
1630
1722
|
blockedTargetIds,
|
|
1631
1723
|
};
|
|
1632
1724
|
const idleCandidate = planIdleCandidate(sourceParams);
|
|
1633
|
-
if (idleCandidate != null)
|
|
1725
|
+
if (idleCandidate != null) {
|
|
1634
1726
|
rawCandidates.push(idleCandidate);
|
|
1727
|
+
}
|
|
1635
1728
|
rawCandidates.push(...planSourceAdapterCandidates(sourceParams));
|
|
1636
1729
|
return rawCandidates;
|
|
1637
1730
|
}
|
|
@@ -1666,20 +1759,24 @@ function planSourceAdapterCandidates(params) {
|
|
|
1666
1759
|
const { vault, vaultAddress, activeAdapters } = params;
|
|
1667
1760
|
const candidates = [];
|
|
1668
1761
|
for (const sourceAdapter of vault.accrualAdapters) {
|
|
1669
|
-
if (!(sourceAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2))
|
|
1762
|
+
if (!(sourceAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)) {
|
|
1670
1763
|
continue;
|
|
1671
|
-
|
|
1764
|
+
}
|
|
1765
|
+
if (!isAddressEqual(sourceAdapter.parentVault, vaultAddress)) {
|
|
1672
1766
|
continue;
|
|
1673
|
-
|
|
1767
|
+
}
|
|
1768
|
+
if (!activeAdapters.has(sourceAdapter.address.toLowerCase())) {
|
|
1674
1769
|
continue;
|
|
1770
|
+
}
|
|
1675
1771
|
for (const sourceMarketReference of sourceAdapter.markets) {
|
|
1676
1772
|
const candidate = planSourceMarketCandidate({
|
|
1677
1773
|
...params,
|
|
1678
1774
|
sourceAdapter,
|
|
1679
1775
|
sourceMarketReference,
|
|
1680
1776
|
});
|
|
1681
|
-
if (candidate != null)
|
|
1777
|
+
if (candidate != null) {
|
|
1682
1778
|
candidates.push(candidate);
|
|
1779
|
+
}
|
|
1683
1780
|
}
|
|
1684
1781
|
}
|
|
1685
1782
|
return candidates;
|
|
@@ -1694,33 +1791,40 @@ function planSourceMarketCandidate(params) {
|
|
|
1694
1791
|
const { data, vault, vaultAddress, sourceAdapter, sourceMarketReference, normalizedMarketId, adapterIdsCache, blockedTargetIds, getPair, timestamp, setMarkets, targetSupplyHeadroom, allocatorHeadroom, maxWithdrawalUtilization, adapter, publicAllocatorConfig, targetPair, } = params;
|
|
1695
1792
|
const sourceMarket = data.getMarket(sourceMarketReference.id);
|
|
1696
1793
|
if (!isAddressEqual(sourceMarket.params.loanToken, vault.asset) ||
|
|
1697
|
-
!isAddressEqual(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm))
|
|
1794
|
+
!isAddressEqual(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm)) {
|
|
1698
1795
|
return;
|
|
1699
|
-
|
|
1796
|
+
}
|
|
1797
|
+
if (sourceMarket.id.toLowerCase() === normalizedMarketId) {
|
|
1700
1798
|
return;
|
|
1799
|
+
}
|
|
1701
1800
|
const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
|
|
1702
1801
|
const [, , sourceAdapterMarketCapId] = sourceIds;
|
|
1703
1802
|
const sourceConfig = data.getMarketPublicAllocatorConfig(vaultAddress, sourceAdapterMarketCapId);
|
|
1704
1803
|
if (!isAddressEqual(sourceConfig.vault, vaultAddress) ||
|
|
1705
1804
|
!isAddressEqual(sourceConfig.adapter, sourceAdapter.address) ||
|
|
1706
|
-
!sourceConfig.canPullFromMarket)
|
|
1805
|
+
!sourceConfig.canPullFromMarket) {
|
|
1707
1806
|
return;
|
|
1807
|
+
}
|
|
1708
1808
|
const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
|
|
1709
|
-
if (sourceAllocations.some(({ allocation }) => allocation === 0n))
|
|
1809
|
+
if (sourceAllocations.some(({ allocation }) => allocation === 0n)) {
|
|
1710
1810
|
return;
|
|
1811
|
+
}
|
|
1711
1812
|
const sourceSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
|
|
1712
|
-
if (sourceSupplyShares === 0n)
|
|
1813
|
+
if (sourceSupplyShares === 0n) {
|
|
1713
1814
|
return;
|
|
1815
|
+
}
|
|
1714
1816
|
// A withdrawal can create target headroom only for shared cap IDs.
|
|
1715
|
-
if (blockedTargetIds.some((id) => !sourceIds.includes(id)))
|
|
1817
|
+
if (blockedTargetIds.some((id) => !sourceIds.includes(id))) {
|
|
1716
1818
|
return;
|
|
1819
|
+
}
|
|
1717
1820
|
const sourcePair = getPair(vaultAddress, sourceAdapter, sourceMarket);
|
|
1718
1821
|
const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
|
|
1719
1822
|
setMarkets([accruedSourceMarket]);
|
|
1720
1823
|
const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
|
|
1721
1824
|
const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, accruedSourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
|
|
1722
|
-
if (assets <= 0n)
|
|
1825
|
+
if (assets <= 0n) {
|
|
1723
1826
|
return;
|
|
1827
|
+
}
|
|
1724
1828
|
return {
|
|
1725
1829
|
reallocation: {
|
|
1726
1830
|
vault: vaultAddress,
|
|
@@ -1748,8 +1852,9 @@ function fitCandidateCaps(params) {
|
|
|
1748
1852
|
const targetIds = targetPair.ids;
|
|
1749
1853
|
const sourceIds = new Set(sourcePair?.ids ?? []);
|
|
1750
1854
|
const reserveById = new Map();
|
|
1751
|
-
for (const id of targetIds)
|
|
1855
|
+
for (const id of targetIds) {
|
|
1752
1856
|
reserveById.set(id, capReserve(reallocation.vault, id, sourcePair == null ? [targetPair] : [targetPair, sourcePair]));
|
|
1857
|
+
}
|
|
1753
1858
|
const probeParams = { ...params, targetIds, sourceIds, reserveById };
|
|
1754
1859
|
// Non-shared target IDs impose monotonic upper bounds. Shared IDs
|
|
1755
1860
|
// can impose lower bounds and non-monotonic rounding constraints,
|
|
@@ -1772,21 +1877,23 @@ function fitCandidateCaps(params) {
|
|
|
1772
1877
|
});
|
|
1773
1878
|
}
|
|
1774
1879
|
}
|
|
1775
|
-
if (selectedAssets > 0n && probe?.withinAllCaps === true)
|
|
1880
|
+
if (selectedAssets > 0n && probe?.withinAllCaps === true) {
|
|
1776
1881
|
return {
|
|
1777
1882
|
reallocation: { ...reallocation, assets: selectedAssets },
|
|
1778
1883
|
targetPair,
|
|
1779
1884
|
sourcePair,
|
|
1780
1885
|
allocatorHeadroom,
|
|
1781
1886
|
};
|
|
1887
|
+
}
|
|
1782
1888
|
}
|
|
1783
1889
|
/** Simulates one candidate amount and tests its reserved target-cap headroom. @internal */
|
|
1784
1890
|
function probeCandidateReallocation(params) {
|
|
1785
1891
|
const { assets, targetMarket, applyPublicReallocation, simulationContext, reallocation, marketId, adapterIdsCache, targetIds, sourceIds, reserveById, } = params;
|
|
1786
1892
|
if (targetMarket.totalSupplyShares +
|
|
1787
1893
|
targetMarket.toSupplyShares(assets, "Down") >
|
|
1788
|
-
MathLib.MAX_UINT_128)
|
|
1894
|
+
MathLib.MAX_UINT_128) {
|
|
1789
1895
|
return;
|
|
1896
|
+
}
|
|
1790
1897
|
const postTransition = _try(() => applyPublicReallocation({
|
|
1791
1898
|
context: simulationContext,
|
|
1792
1899
|
reallocation: { ...reallocation, assets },
|
|
@@ -1795,8 +1902,9 @@ function probeCandidateReallocation(params) {
|
|
|
1795
1902
|
adapterIdsCache,
|
|
1796
1903
|
probe: true,
|
|
1797
1904
|
}), ReallocationAllocationUnderflowError, ReallocationAdapterSupplySharesUnderflowError);
|
|
1798
|
-
if (postTransition == null)
|
|
1905
|
+
if (postTransition == null) {
|
|
1799
1906
|
return;
|
|
1907
|
+
}
|
|
1800
1908
|
// Vault V2 checks relative caps against the transient firstTotalAssets,
|
|
1801
1909
|
// which stays fixed after the vault's first allocation in a transaction.
|
|
1802
1910
|
const { firstTotalAssets } = postTransition;
|
|
@@ -1811,8 +1919,9 @@ function probeCandidateReallocation(params) {
|
|
|
1811
1919
|
allocation.allocation + (reserveById.get(id) ?? 0n) <= capacity;
|
|
1812
1920
|
if (!withinCap) {
|
|
1813
1921
|
withinAllCaps = false;
|
|
1814
|
-
if (!sourceIds.has(id))
|
|
1922
|
+
if (!sourceIds.has(id)) {
|
|
1815
1923
|
withinUpperBounds = false;
|
|
1924
|
+
}
|
|
1816
1925
|
}
|
|
1817
1926
|
}
|
|
1818
1927
|
return { withinAllCaps, withinUpperBounds };
|
|
@@ -1826,25 +1935,30 @@ function findCandidateUpperBound(probeParams) {
|
|
|
1826
1935
|
const assets = probeUpper ? upper : (lower + upper + 1n) / 2n;
|
|
1827
1936
|
probeUpper = false;
|
|
1828
1937
|
if (probeCandidateReallocation({ ...probeParams, assets })
|
|
1829
|
-
?.withinUpperBounds === true)
|
|
1938
|
+
?.withinUpperBounds === true) {
|
|
1830
1939
|
lower = assets;
|
|
1831
|
-
|
|
1940
|
+
}
|
|
1941
|
+
else {
|
|
1832
1942
|
upper = assets - 1n;
|
|
1943
|
+
}
|
|
1833
1944
|
}
|
|
1834
1945
|
return lower;
|
|
1835
1946
|
}
|
|
1836
1947
|
/** Tracks shared-Blue transfer funding in the reallocation's execution order. @internal */
|
|
1837
1948
|
function getReallocationTransferShortfall(reallocations, blueBalance) {
|
|
1838
1949
|
const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
|
|
1839
|
-
if (penaltyAssets === 0n)
|
|
1950
|
+
if (penaltyAssets === 0n) {
|
|
1840
1951
|
return 0n;
|
|
1952
|
+
}
|
|
1841
1953
|
let shortfall = MathLib.zeroFloorSub(penaltyAssets, blueBalance);
|
|
1842
1954
|
let balance = MathLib.zeroFloorSub(blueBalance, penaltyAssets);
|
|
1843
1955
|
for (const { from, assets } of reallocations) {
|
|
1844
|
-
if (from.type === "idle")
|
|
1956
|
+
if (from.type === "idle") {
|
|
1845
1957
|
balance += assets;
|
|
1846
|
-
|
|
1958
|
+
}
|
|
1959
|
+
else {
|
|
1847
1960
|
shortfall = MathLib.max(shortfall, MathLib.zeroFloorSub(assets, balance));
|
|
1961
|
+
}
|
|
1848
1962
|
}
|
|
1849
1963
|
return shortfall;
|
|
1850
1964
|
}
|
|
@@ -1870,8 +1984,9 @@ function planVaultOperation(params) {
|
|
|
1870
1984
|
idleBoundVaults,
|
|
1871
1985
|
};
|
|
1872
1986
|
for (const penalty of penaltyTiers) {
|
|
1873
|
-
if (type === "refinance" && penalty === MathLib.WAD)
|
|
1987
|
+
if (type === "refinance" && penalty === MathLib.WAD) {
|
|
1874
1988
|
continue;
|
|
1989
|
+
}
|
|
1875
1990
|
state = planOperationPenaltyTier({ ...params, penalty, state });
|
|
1876
1991
|
}
|
|
1877
1992
|
return summarizeOperationPlan({ ...params, state });
|
|
@@ -1890,8 +2005,9 @@ function planOperationPenaltyTier(params) {
|
|
|
1890
2005
|
for (const utilization of [maxWithdrawalUtilization, MathLib.WAD]) {
|
|
1891
2006
|
const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
|
|
1892
2007
|
isFriendlyPass = false;
|
|
1893
|
-
if (state.remainingShortfall === 0n && !isFreeFriendlyPass)
|
|
2008
|
+
if (state.remainingShortfall === 0n && !isFreeFriendlyPass) {
|
|
1894
2009
|
continue;
|
|
2010
|
+
}
|
|
1895
2011
|
const result = planOperationUtilizationPass({
|
|
1896
2012
|
...params,
|
|
1897
2013
|
state,
|
|
@@ -1913,23 +2029,25 @@ function planOperationPenaltyTier(params) {
|
|
|
1913
2029
|
*/
|
|
1914
2030
|
function planOperationUtilizationPass(params) {
|
|
1915
2031
|
const { penalty } = params;
|
|
1916
|
-
let
|
|
1917
|
-
|
|
2032
|
+
let state = {
|
|
2033
|
+
...params.state,
|
|
2034
|
+
reallocations: [...params.state.reallocations],
|
|
2035
|
+
};
|
|
1918
2036
|
let triedFullCapacityAttempt = params.triedFullCapacityAttempt;
|
|
1919
2037
|
let passMaxAssets = getOperationPassBudget(params);
|
|
1920
2038
|
const retryPaidPass = penalty > 0n;
|
|
1921
2039
|
let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
|
|
1922
2040
|
let tryFullCapacityAttempt = false;
|
|
1923
2041
|
let isFullCapacityRetryPath = false;
|
|
1924
|
-
const beforePassRemainingShortfall = remainingShortfall;
|
|
1925
|
-
const beforePassAccountingShortfall = accountingShortfall;
|
|
2042
|
+
const beforePassRemainingShortfall = state.remainingShortfall;
|
|
2043
|
+
const beforePassAccountingShortfall = state.accountingShortfall;
|
|
1926
2044
|
// Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
|
|
1927
2045
|
const passStart = retryPaidPass
|
|
1928
2046
|
? {
|
|
1929
|
-
data: data.clone(),
|
|
1930
|
-
context,
|
|
1931
|
-
reserves: cloneCapReserveState(reserves),
|
|
1932
|
-
reallocationCount: reallocations.length,
|
|
2047
|
+
data: state.data.clone(),
|
|
2048
|
+
context: state.context,
|
|
2049
|
+
reserves: cloneCapReserveState(state.reserves),
|
|
2050
|
+
reallocationCount: state.reallocations.length,
|
|
1933
2051
|
}
|
|
1934
2052
|
: undefined;
|
|
1935
2053
|
let previousPassReallocatedAssets = 0n;
|
|
@@ -1940,54 +2058,26 @@ function planOperationUtilizationPass(params) {
|
|
|
1940
2058
|
const isFullCapacityAttempt = tryFullCapacityAttempt;
|
|
1941
2059
|
tryFullCapacityAttempt = false;
|
|
1942
2060
|
if (passStart != null) {
|
|
1943
|
-
|
|
1944
|
-
context = passStart.context;
|
|
1945
|
-
reserves = cloneCapReserveState(passStart.reserves);
|
|
1946
|
-
reallocations.length = passStart.reallocationCount;
|
|
2061
|
+
state = restoreOperationPassStart({ state, passStart });
|
|
1947
2062
|
}
|
|
1948
2063
|
const attempt = executeOperationAttempt({
|
|
1949
2064
|
...params,
|
|
1950
|
-
state
|
|
1951
|
-
reserves,
|
|
1952
|
-
reallocations,
|
|
1953
|
-
data,
|
|
1954
|
-
context,
|
|
1955
|
-
remainingShortfall,
|
|
1956
|
-
accountingShortfall,
|
|
1957
|
-
allocatorCapBoundTargets,
|
|
1958
|
-
idleBoundVaults,
|
|
1959
|
-
},
|
|
2065
|
+
state,
|
|
1960
2066
|
isFullCapacityAttempt,
|
|
1961
2067
|
passMaxAssets,
|
|
1962
2068
|
isFullCapacityRetryPath,
|
|
1963
2069
|
});
|
|
1964
|
-
|
|
1965
|
-
reserves,
|
|
1966
|
-
reallocations,
|
|
1967
|
-
data,
|
|
1968
|
-
context,
|
|
1969
|
-
remainingShortfall,
|
|
1970
|
-
accountingShortfall,
|
|
1971
|
-
allocatorCapBoundTargets,
|
|
1972
|
-
idleBoundVaults,
|
|
1973
|
-
} = attempt.state);
|
|
2070
|
+
state = attempt.state;
|
|
1974
2071
|
const { pass, physicalShortfall, attemptTransferShortfall, attemptCoversShortfall, passReallocatedAssets, } = attempt;
|
|
1975
|
-
if (passStart == null)
|
|
2072
|
+
if (passStart == null) {
|
|
1976
2073
|
break;
|
|
1977
|
-
|
|
2074
|
+
}
|
|
2075
|
+
if (isFullCapacityAttempt) {
|
|
1978
2076
|
passMaxAssets = passReallocatedAssets;
|
|
2077
|
+
}
|
|
1979
2078
|
bestAttempt = chooseOperationBestAttempt({
|
|
1980
2079
|
...params,
|
|
1981
|
-
state
|
|
1982
|
-
reserves,
|
|
1983
|
-
reallocations,
|
|
1984
|
-
data,
|
|
1985
|
-
context,
|
|
1986
|
-
remainingShortfall,
|
|
1987
|
-
accountingShortfall,
|
|
1988
|
-
allocatorCapBoundTargets,
|
|
1989
|
-
idleBoundVaults,
|
|
1990
|
-
},
|
|
2080
|
+
state,
|
|
1991
2081
|
bestAttempt,
|
|
1992
2082
|
beforePassAccountingShortfall,
|
|
1993
2083
|
isFullCapacityRetryPath,
|
|
@@ -2007,14 +2097,15 @@ function planOperationUtilizationPass(params) {
|
|
|
2007
2097
|
previousPassReallocatedAssets,
|
|
2008
2098
|
isFullCapacityAttempt,
|
|
2009
2099
|
attemptCoversShortfall,
|
|
2010
|
-
accountingShortfall,
|
|
2100
|
+
accountingShortfall: state.accountingShortfall,
|
|
2011
2101
|
physicalShortfall,
|
|
2012
2102
|
passReallocatedAssets,
|
|
2013
|
-
remainingShortfall,
|
|
2103
|
+
remainingShortfall: state.remainingShortfall,
|
|
2014
2104
|
penalty,
|
|
2015
2105
|
});
|
|
2016
|
-
if (next.type === "break")
|
|
2106
|
+
if (next.type === "break") {
|
|
2017
2107
|
break;
|
|
2108
|
+
}
|
|
2018
2109
|
({
|
|
2019
2110
|
lo,
|
|
2020
2111
|
hi,
|
|
@@ -2028,16 +2119,7 @@ function planOperationUtilizationPass(params) {
|
|
|
2028
2119
|
}
|
|
2029
2120
|
const finalState = finishOperationPass({
|
|
2030
2121
|
...params,
|
|
2031
|
-
state
|
|
2032
|
-
reserves,
|
|
2033
|
-
reallocations,
|
|
2034
|
-
data,
|
|
2035
|
-
context,
|
|
2036
|
-
remainingShortfall,
|
|
2037
|
-
accountingShortfall,
|
|
2038
|
-
allocatorCapBoundTargets,
|
|
2039
|
-
idleBoundVaults,
|
|
2040
|
-
},
|
|
2122
|
+
state,
|
|
2041
2123
|
passStart,
|
|
2042
2124
|
bestAttempt,
|
|
2043
2125
|
beforePassRemainingShortfall,
|
|
@@ -2048,6 +2130,18 @@ function planOperationUtilizationPass(params) {
|
|
|
2048
2130
|
triedFullCapacityAttempt,
|
|
2049
2131
|
};
|
|
2050
2132
|
}
|
|
2133
|
+
/**
|
|
2134
|
+
* Restores working data and reserves and truncates the shared reallocation array in place.
|
|
2135
|
+
* Other attempt results remain available to the retry search.
|
|
2136
|
+
* @internal
|
|
2137
|
+
*/
|
|
2138
|
+
function restoreOperationPassStart({ state, passStart, }) {
|
|
2139
|
+
const data = passStart.data.clone();
|
|
2140
|
+
const context = passStart.context;
|
|
2141
|
+
const reserves = cloneCapReserveState(passStart.reserves);
|
|
2142
|
+
state.reallocations.length = passStart.reallocationCount;
|
|
2143
|
+
return { ...state, data, context, reserves };
|
|
2144
|
+
}
|
|
2051
2145
|
/** Summarizes liquidity-bound legs and the accounting and physical funding result. @internal */
|
|
2052
2146
|
function summarizeOperationPlan(params) {
|
|
2053
2147
|
const { maxAssets, headroom, type, amount, feeAssets, blueBalance, absoluteShortfall, hasExplicitBlueBalance, } = params;
|
|
@@ -2058,8 +2152,9 @@ function summarizeOperationPlan(params) {
|
|
|
2058
2152
|
reallocatedAssets += assets;
|
|
2059
2153
|
const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
|
|
2060
2154
|
if (!allocatorCapBoundTargets.has(key) &&
|
|
2061
|
-
!(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
|
|
2155
|
+
!(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase()))) {
|
|
2062
2156
|
unboundAssets += assets;
|
|
2157
|
+
}
|
|
2063
2158
|
}
|
|
2064
2159
|
const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
|
|
2065
2160
|
const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
|
|
@@ -2214,7 +2309,7 @@ function chooseOperationBestAttempt(params) {
|
|
|
2214
2309
|
}
|
|
2215
2310
|
if (isBetterAttempt &&
|
|
2216
2311
|
(!isFullCapacityRetryPath ||
|
|
2217
|
-
(attemptCoversShortfall && attemptTransferShortfall === 0n)))
|
|
2312
|
+
(attemptCoversShortfall && attemptTransferShortfall === 0n))) {
|
|
2218
2313
|
return {
|
|
2219
2314
|
data,
|
|
2220
2315
|
context,
|
|
@@ -2225,6 +2320,7 @@ function chooseOperationBestAttempt(params) {
|
|
|
2225
2320
|
passReallocatedAssets,
|
|
2226
2321
|
priority: attemptPriority,
|
|
2227
2322
|
};
|
|
2323
|
+
}
|
|
2228
2324
|
return bestAttempt;
|
|
2229
2325
|
}
|
|
2230
2326
|
/** Advances bisection or grossed-up retries, stopping on stalled physical funding. @internal */
|
|
@@ -2238,8 +2334,9 @@ function advanceOperationPassSearch(params) {
|
|
|
2238
2334
|
attemptCoversShortfall,
|
|
2239
2335
|
}));
|
|
2240
2336
|
if (hi != null) {
|
|
2241
|
-
if (hi - lo <= 1n)
|
|
2337
|
+
if (hi - lo <= 1n) {
|
|
2242
2338
|
return { type: "break" };
|
|
2339
|
+
}
|
|
2243
2340
|
passMaxAssets = (lo + hi) / 2n;
|
|
2244
2341
|
return {
|
|
2245
2342
|
type: "continue",
|
|
@@ -2253,8 +2350,9 @@ function advanceOperationPassSearch(params) {
|
|
|
2253
2350
|
previousPassReallocatedAssets,
|
|
2254
2351
|
};
|
|
2255
2352
|
}
|
|
2256
|
-
if (isFullCapacityAttempt && !attemptCoversShortfall)
|
|
2353
|
+
if (isFullCapacityAttempt && !attemptCoversShortfall) {
|
|
2257
2354
|
return { type: "break" };
|
|
2355
|
+
}
|
|
2258
2356
|
if (accountingShortfall === 0n &&
|
|
2259
2357
|
previousPhysicalShortfall != null &&
|
|
2260
2358
|
physicalShortfall >= previousPhysicalShortfall) {
|
|
@@ -2278,8 +2376,9 @@ function advanceOperationPassSearch(params) {
|
|
|
2278
2376
|
}
|
|
2279
2377
|
previousPhysicalShortfall = physicalShortfall;
|
|
2280
2378
|
if (passReallocatedAssets <= previousPassReallocatedAssets ||
|
|
2281
|
-
penalty === MathLib.WAD)
|
|
2379
|
+
penalty === MathLib.WAD) {
|
|
2282
2380
|
return { type: "break" };
|
|
2381
|
+
}
|
|
2283
2382
|
previousPassReallocatedAssets = passReallocatedAssets;
|
|
2284
2383
|
passMaxAssets += MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
|
|
2285
2384
|
return {
|
|
@@ -2344,22 +2443,27 @@ function finishOperationPass(params) {
|
|
|
2344
2443
|
function updateOperationSearchBracket(params) {
|
|
2345
2444
|
let { lo, hi } = params;
|
|
2346
2445
|
const { passMaxAssets, attemptCoversShortfall } = params;
|
|
2347
|
-
if (attemptCoversShortfall)
|
|
2446
|
+
if (attemptCoversShortfall) {
|
|
2348
2447
|
hi = hi == null ? passMaxAssets : MathLib.min(hi, passMaxAssets);
|
|
2349
|
-
|
|
2448
|
+
}
|
|
2449
|
+
else {
|
|
2350
2450
|
lo = MathLib.max(lo, passMaxAssets);
|
|
2451
|
+
}
|
|
2351
2452
|
return { lo, hi };
|
|
2352
2453
|
}
|
|
2353
2454
|
/** Validates the operation amount and fee before reading its snapshot. @internal */
|
|
2354
2455
|
function resolveOperationFeeAssets(operation) {
|
|
2355
2456
|
const { amount } = operation;
|
|
2356
|
-
if (amount <= 0n)
|
|
2457
|
+
if (amount <= 0n) {
|
|
2357
2458
|
throw new NonPositiveInputError("amount", amount);
|
|
2459
|
+
}
|
|
2358
2460
|
const referralFeePct = operation.type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
|
|
2359
|
-
if (referralFeePct < 0n)
|
|
2461
|
+
if (referralFeePct < 0n) {
|
|
2360
2462
|
throw new NegativeInputError("referralFeePct", referralFeePct);
|
|
2361
|
-
|
|
2463
|
+
}
|
|
2464
|
+
if (referralFeePct >= MathLib.WAD) {
|
|
2362
2465
|
throw new ReferralFeePctExceededError(referralFeePct);
|
|
2466
|
+
}
|
|
2363
2467
|
const feeAssets = operation.type === "refinance"
|
|
2364
2468
|
? getBlueBundlesV1ReferralFeeAssets(amount, referralFeePct)
|
|
2365
2469
|
: 0n;
|
|
@@ -2375,10 +2479,12 @@ function getOperationMarketTotals({ market, marketId, type, amount, feeAssets, }
|
|
|
2375
2479
|
});
|
|
2376
2480
|
}
|
|
2377
2481
|
let newTotalBorrowAssets = market.totalBorrowAssets;
|
|
2378
|
-
if (type === "borrow")
|
|
2482
|
+
if (type === "borrow") {
|
|
2379
2483
|
newTotalBorrowAssets += amount;
|
|
2380
|
-
|
|
2484
|
+
}
|
|
2485
|
+
if (type === "refinance") {
|
|
2381
2486
|
newTotalBorrowAssets += amount + feeAssets;
|
|
2487
|
+
}
|
|
2382
2488
|
const newTotalSupplyAssets = type === "withdraw"
|
|
2383
2489
|
? market.totalSupplyAssets - amount
|
|
2384
2490
|
: market.totalSupplyAssets;
|
|
@@ -2398,18 +2504,21 @@ function selectOperationPlan(params) {
|
|
|
2398
2504
|
? absoluteShortfall
|
|
2399
2505
|
: target.unboundAssets, { headroom: allocatorCapHeadroom });
|
|
2400
2506
|
// Shared-cap fitting is not monotonic in the budget.
|
|
2401
|
-
if (!selected.coversShortfall && target.coversShortfall)
|
|
2507
|
+
if (!selected.coversShortfall && target.coversShortfall) {
|
|
2402
2508
|
selected = target;
|
|
2509
|
+
}
|
|
2403
2510
|
}
|
|
2404
2511
|
let available = MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
|
|
2405
2512
|
// Without headroom, `target` already is the full-cap plan toward the target.
|
|
2406
2513
|
const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
|
|
2407
2514
|
for (const maxAssets of fullCapBudgets) {
|
|
2408
|
-
if (selected.coversShortfall)
|
|
2515
|
+
if (selected.coversShortfall) {
|
|
2409
2516
|
break;
|
|
2517
|
+
}
|
|
2410
2518
|
selected = plan(maxAssets, { headroom: 0n });
|
|
2411
|
-
if (selected.reallocatedAssets > available)
|
|
2519
|
+
if (selected.reallocatedAssets > available) {
|
|
2412
2520
|
available = selected.reallocatedAssets;
|
|
2521
|
+
}
|
|
2413
2522
|
}
|
|
2414
2523
|
// Reject unfunded plans before comparing optional physical-balance alternatives.
|
|
2415
2524
|
assertSelectedOperationFunding({ ...params, selected, available });
|
|
@@ -2419,8 +2528,9 @@ function selectOperationPlan(params) {
|
|
|
2419
2528
|
/** Preserves penalty-specific error precedence when selected liquidity cannot fund the operation. @internal */
|
|
2420
2529
|
function assertSelectedOperationFunding(params) {
|
|
2421
2530
|
const { selected, available, hasExplicitBlueBalance, blueBalance, type, amount, absoluteShortfall, marketId, } = params;
|
|
2422
|
-
if (selected.coversShortfall)
|
|
2531
|
+
if (selected.coversShortfall) {
|
|
2423
2532
|
return;
|
|
2533
|
+
}
|
|
2424
2534
|
const selectedTransferShortfall = hasExplicitBlueBalance
|
|
2425
2535
|
? getReallocationTransferShortfall(selected.reallocations, blueBalance)
|
|
2426
2536
|
: 0n;
|
|
@@ -2429,12 +2539,13 @@ function assertSelectedOperationFunding(params) {
|
|
|
2429
2539
|
selectedPenaltyAssets > amount &&
|
|
2430
2540
|
selected.reallocatedAssets >= absoluteShortfall &&
|
|
2431
2541
|
(!hasExplicitBlueBalance ||
|
|
2432
|
-
(selected.physicalShortfall === 0n && selectedTransferShortfall === 0n)))
|
|
2542
|
+
(selected.physicalShortfall === 0n && selectedTransferShortfall === 0n))) {
|
|
2433
2543
|
throw new InputExceedsMaxError({
|
|
2434
2544
|
field: "reallocationPenaltyAssets",
|
|
2435
2545
|
value: selectedPenaltyAssets,
|
|
2436
2546
|
max: amount,
|
|
2437
2547
|
});
|
|
2548
|
+
}
|
|
2438
2549
|
throw new InsufficientSharedLiquidityError({
|
|
2439
2550
|
marketId,
|
|
2440
2551
|
shortfall: MathLib.max(absoluteShortfall +
|
|
@@ -2466,8 +2577,9 @@ function choosePhysicalBalancePlan(params) {
|
|
|
2466
2577
|
});
|
|
2467
2578
|
if (alternative.coversShortfall &&
|
|
2468
2579
|
getBlueBundlesV1PenaltyAssets(alternative.reallocations) <
|
|
2469
|
-
getBlueBundlesV1PenaltyAssets(selected.reallocations))
|
|
2580
|
+
getBlueBundlesV1PenaltyAssets(selected.reallocations)) {
|
|
2470
2581
|
selected = alternative;
|
|
2582
|
+
}
|
|
2471
2583
|
}
|
|
2472
2584
|
return selected;
|
|
2473
2585
|
}
|